docs: Add supported versions and fix-backport policy master
authorKienan Stewart <kstewart@efficios.com>
Thu, 14 Mar 2024 15:33:47 +0000 (11:33 -0400)
committerJérémie Galarneau <jeremie.galarneau@efficios.com>
Wed, 10 Apr 2024 20:31:51 +0000 (16:31 -0400)
Change-Id: Idb22c6487e2397b807c5d1b78acbc2adb03be363
Signed-off-by: Kienan Stewart <kstewart@efficios.com>
Signed-off-by: Jérémie Galarneau <jeremie.galarneau@efficios.com>
949 files changed:
.clang-format
.clang-tidy [new file with mode: 0644]
.commit_template [new file with mode: 0644]
.git-blame-ignore-revs [new file with mode: 0644]
.gitignore
CONTRIBUTING.md
CodingStyle [deleted file]
CodingStyle.md [new file with mode: 0644]
Makefile.am
README.adoc
configure.ac
doc/Makefile.am
doc/api/.gitignore [new file with mode: 0644]
doc/api/Makefile.am [new file with mode: 0644]
doc/api/README.adoc [new file with mode: 0644]
doc/api/liblttng-ctl/Doxyfile.in [new file with mode: 0644]
doc/api/liblttng-ctl/DoxygenLayout.xml [new file with mode: 0644]
doc/api/liblttng-ctl/Makefile.am [new file with mode: 0644]
doc/api/liblttng-ctl/dox/groups.dox [new file with mode: 0644]
doc/api/liblttng-ctl/images/concepts.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/event-rule.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/live.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/many-sessions.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/per-process-buffering-root.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/per-process-buffering.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/per-user-buffering-root.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/per-user-buffering.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/plumbing.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/rotation.png [new file with mode: 0644]
doc/api/liblttng-ctl/images/snapshot.png [new file with mode: 0644]
doc/api/liblttng-ctl/style.css [new file with mode: 0644]
doc/examples/rotation/rotate-client-example.c
doc/examples/trigger-condition-event-matches/instrumented-app.c
doc/examples/trigger-condition-event-matches/notification-client.cpp
doc/examples/trigger-condition-event-matches/tracepoint-trigger-example.h
doc/man/Makefile.am
doc/man/README.md
doc/man/lttng-add-context.1.txt
doc/man/lttng-add-trigger.1.txt
doc/man/lttng-destroy.1.txt
doc/man/lttng-list.1.txt
doc/man/lttng-start.1.txt
doc/man/lttng-stop.1.txt
extras/bindings/swig/python/.clang-tidy [new file with mode: 0644]
extras/bindings/swig/python/Makefile.am
extras/bindings/swig/python/lttng.i.in
extras/bindings/swig/python/tests/example.py
extras/bindings/swig/python/tests/tests.py
extras/core-handler/crash.c
extras/zsh-completion/_lttng [new file with mode: 0644]
extras/zsh-completion/_lttng-crash [new file with mode: 0644]
extras/zsh-completion/_lttng-relayd [new file with mode: 0644]
extras/zsh-completion/_lttng-sessiond [new file with mode: 0644]
format-cpp [new file with mode: 0755]
include/Makefile.am
include/lttng/action/action-internal.hpp
include/lttng/action/action.h
include/lttng/action/list-internal.hpp
include/lttng/action/list.h
include/lttng/action/notify-internal.hpp
include/lttng/action/notify.h
include/lttng/action/path-internal.hpp
include/lttng/action/path.h
include/lttng/action/rate-policy-internal.hpp
include/lttng/action/rate-policy.h
include/lttng/action/rotate-session-internal.hpp
include/lttng/action/rotate-session.h
include/lttng/action/snapshot-session-internal.hpp
include/lttng/action/snapshot-session.h
include/lttng/action/start-session-internal.hpp
include/lttng/action/start-session.h
include/lttng/action/stop-session-internal.hpp
include/lttng/action/stop-session.h
include/lttng/channel-internal.hpp
include/lttng/channel.h
include/lttng/clear-handle.h
include/lttng/clear.h
include/lttng/condition/buffer-usage-internal.hpp
include/lttng/condition/buffer-usage.h
include/lttng/condition/condition-internal.hpp
include/lttng/condition/condition.h
include/lttng/condition/evaluation-internal.hpp
include/lttng/condition/evaluation.h
include/lttng/condition/event-rule-matches-internal.hpp
include/lttng/condition/event-rule-matches.h
include/lttng/condition/session-consumed-size-internal.hpp
include/lttng/condition/session-consumed-size.h
include/lttng/condition/session-rotation-internal.hpp
include/lttng/condition/session-rotation.h
include/lttng/constant.h
include/lttng/destruction-handle.h
include/lttng/domain-internal.hpp
include/lttng/domain.h
include/lttng/endpoint-internal.hpp
include/lttng/error-query-internal.hpp
include/lttng/error-query.h
include/lttng/event-expr-internal.hpp
include/lttng/event-expr.h
include/lttng/event-field-value-internal.hpp
include/lttng/event-field-value.h
include/lttng/event-internal.hpp
include/lttng/event-rule/event-rule-internal.hpp
include/lttng/event-rule/event-rule.h
include/lttng/event-rule/jul-logging-internal.hpp
include/lttng/event-rule/jul-logging.h
include/lttng/event-rule/kernel-kprobe-internal.hpp
include/lttng/event-rule/kernel-kprobe.h
include/lttng/event-rule/kernel-syscall-internal.hpp
include/lttng/event-rule/kernel-syscall.h
include/lttng/event-rule/kernel-tracepoint-internal.hpp
include/lttng/event-rule/kernel-tracepoint.h
include/lttng/event-rule/kernel-uprobe-internal.hpp
include/lttng/event-rule/kernel-uprobe.h
include/lttng/event-rule/log4j-logging-internal.hpp
include/lttng/event-rule/log4j-logging.h
include/lttng/event-rule/python-logging-internal.hpp
include/lttng/event-rule/python-logging.h
include/lttng/event-rule/user-tracepoint-internal.hpp
include/lttng/event-rule/user-tracepoint.h
include/lttng/event.h
include/lttng/handle.h
include/lttng/health-internal.hpp
include/lttng/health.h
include/lttng/kernel-probe-internal.hpp
include/lttng/kernel-probe.h
include/lttng/kernel.h [new file with mode: 0644]
include/lttng/load-internal.hpp
include/lttng/load.h
include/lttng/location-internal.hpp
include/lttng/location.h
include/lttng/log-level-rule-internal.hpp
include/lttng/log-level-rule.h
include/lttng/lttng-error.h
include/lttng/lttng-export.h
include/lttng/lttng.h
include/lttng/notification/channel-internal.hpp
include/lttng/notification/channel.h
include/lttng/notification/notification-internal.hpp
include/lttng/notification/notification.h
include/lttng/ref-internal.hpp
include/lttng/rotate-internal.hpp
include/lttng/rotation.h
include/lttng/save-internal.hpp
include/lttng/save.h
include/lttng/session-descriptor-internal.hpp
include/lttng/session-descriptor.h
include/lttng/session-internal.hpp
include/lttng/session.h
include/lttng/snapshot-internal.hpp
include/lttng/snapshot.h
include/lttng/tracker.h
include/lttng/trigger/trigger-internal.hpp
include/lttng/trigger/trigger.h
include/lttng/userspace-probe-internal.hpp
include/lttng/userspace-probe.h
m4/ax_prog_doxygen.m4 [new file with mode: 0644]
pre-inst-env.in [new file with mode: 0644]
pyproject.toml [new file with mode: 0644]
src/bin/lttng-consumerd/health-consumerd.cpp
src/bin/lttng-consumerd/health-consumerd.hpp
src/bin/lttng-consumerd/lttng-consumerd.cpp
src/bin/lttng-consumerd/lttng-consumerd.hpp
src/bin/lttng-crash/lttng-crash.cpp
src/bin/lttng-relayd/Makefile.am
src/bin/lttng-relayd/backward-compatibility-group-by.cpp
src/bin/lttng-relayd/backward-compatibility-group-by.hpp
src/bin/lttng-relayd/cmd-2-1.cpp
src/bin/lttng-relayd/cmd-2-1.hpp
src/bin/lttng-relayd/cmd-2-11.cpp
src/bin/lttng-relayd/cmd-2-11.hpp
src/bin/lttng-relayd/cmd-2-2.cpp
src/bin/lttng-relayd/cmd-2-2.hpp
src/bin/lttng-relayd/cmd-2-4.cpp
src/bin/lttng-relayd/cmd-2-4.hpp
src/bin/lttng-relayd/cmd.hpp
src/bin/lttng-relayd/connection.cpp
src/bin/lttng-relayd/connection.hpp
src/bin/lttng-relayd/ctf-trace.cpp
src/bin/lttng-relayd/ctf-trace.hpp
src/bin/lttng-relayd/health-relayd.cpp
src/bin/lttng-relayd/health-relayd.hpp
src/bin/lttng-relayd/index.cpp
src/bin/lttng-relayd/index.hpp
src/bin/lttng-relayd/live.cpp
src/bin/lttng-relayd/live.hpp
src/bin/lttng-relayd/lttng-relayd.hpp
src/bin/lttng-relayd/lttng-viewer-abi.hpp
src/bin/lttng-relayd/main.cpp
src/bin/lttng-relayd/session.cpp
src/bin/lttng-relayd/session.hpp
src/bin/lttng-relayd/sessiond-trace-chunks.cpp
src/bin/lttng-relayd/sessiond-trace-chunks.hpp
src/bin/lttng-relayd/stream.cpp
src/bin/lttng-relayd/stream.hpp
src/bin/lttng-relayd/tcp_keep_alive.cpp
src/bin/lttng-relayd/thread-utils.cpp [new file with mode: 0644]
src/bin/lttng-relayd/tracefile-array.cpp
src/bin/lttng-relayd/tracefile-array.hpp
src/bin/lttng-relayd/utils.cpp
src/bin/lttng-relayd/viewer-session.cpp
src/bin/lttng-relayd/viewer-session.hpp
src/bin/lttng-relayd/viewer-stream.cpp
src/bin/lttng-relayd/viewer-stream.hpp
src/bin/lttng-sessiond/Makefile.am
src/bin/lttng-sessiond/action-executor.cpp
src/bin/lttng-sessiond/action-executor.hpp
src/bin/lttng-sessiond/agent-thread.cpp
src/bin/lttng-sessiond/agent-thread.hpp
src/bin/lttng-sessiond/agent.cpp
src/bin/lttng-sessiond/agent.hpp
src/bin/lttng-sessiond/buffer-registry.cpp
src/bin/lttng-sessiond/buffer-registry.hpp
src/bin/lttng-sessiond/channel.cpp
src/bin/lttng-sessiond/channel.hpp
src/bin/lttng-sessiond/clear.cpp
src/bin/lttng-sessiond/client.cpp
src/bin/lttng-sessiond/client.hpp
src/bin/lttng-sessiond/clock-class.cpp
src/bin/lttng-sessiond/clock-class.hpp
src/bin/lttng-sessiond/cmd.cpp
src/bin/lttng-sessiond/cmd.hpp
src/bin/lttng-sessiond/condition-internal.cpp
src/bin/lttng-sessiond/condition-internal.hpp
src/bin/lttng-sessiond/consumer.cpp
src/bin/lttng-sessiond/consumer.hpp
src/bin/lttng-sessiond/context.cpp
src/bin/lttng-sessiond/context.hpp
src/bin/lttng-sessiond/ctf2-trace-class-visitor.cpp [new file with mode: 0644]
src/bin/lttng-sessiond/ctf2-trace-class-visitor.hpp [new file with mode: 0644]
src/bin/lttng-sessiond/dispatch.cpp
src/bin/lttng-sessiond/dispatch.hpp
src/bin/lttng-sessiond/event-class.cpp
src/bin/lttng-sessiond/event-class.hpp
src/bin/lttng-sessiond/event-notifier-error-accounting.cpp
src/bin/lttng-sessiond/event-notifier-error-accounting.hpp
src/bin/lttng-sessiond/event.cpp
src/bin/lttng-sessiond/event.hpp
src/bin/lttng-sessiond/fd-limit.cpp
src/bin/lttng-sessiond/fd-limit.hpp
src/bin/lttng-sessiond/field.cpp
src/bin/lttng-sessiond/field.hpp
src/bin/lttng-sessiond/globals.cpp
src/bin/lttng-sessiond/health-sessiond.hpp
src/bin/lttng-sessiond/health.cpp
src/bin/lttng-sessiond/kern-modules.hpp
src/bin/lttng-sessiond/kernel-consumer.cpp
src/bin/lttng-sessiond/kernel-consumer.hpp
src/bin/lttng-sessiond/kernel.cpp
src/bin/lttng-sessiond/kernel.hpp
src/bin/lttng-sessiond/lttng-sessiond.hpp
src/bin/lttng-sessiond/lttng-syscall.cpp
src/bin/lttng-sessiond/lttng-syscall.hpp
src/bin/lttng-sessiond/main.cpp
src/bin/lttng-sessiond/manage-apps.cpp
src/bin/lttng-sessiond/manage-apps.hpp
src/bin/lttng-sessiond/manage-consumer.cpp
src/bin/lttng-sessiond/manage-consumer.hpp
src/bin/lttng-sessiond/manage-kernel.cpp
src/bin/lttng-sessiond/manage-kernel.hpp
src/bin/lttng-sessiond/modprobe.cpp
src/bin/lttng-sessiond/modprobe.hpp
src/bin/lttng-sessiond/notification-thread-commands.cpp
src/bin/lttng-sessiond/notification-thread-commands.hpp
src/bin/lttng-sessiond/notification-thread-events.cpp
src/bin/lttng-sessiond/notification-thread-events.hpp
src/bin/lttng-sessiond/notification-thread-internal.hpp
src/bin/lttng-sessiond/notification-thread.cpp
src/bin/lttng-sessiond/notification-thread.hpp
src/bin/lttng-sessiond/notify-apps.cpp
src/bin/lttng-sessiond/notify-apps.hpp
src/bin/lttng-sessiond/process-utils.cpp
src/bin/lttng-sessiond/register.cpp
src/bin/lttng-sessiond/register.hpp
src/bin/lttng-sessiond/rotate.cpp [deleted file]
src/bin/lttng-sessiond/rotate.hpp [deleted file]
src/bin/lttng-sessiond/rotation-thread.cpp
src/bin/lttng-sessiond/rotation-thread.hpp
src/bin/lttng-sessiond/save.cpp
src/bin/lttng-sessiond/save.hpp
src/bin/lttng-sessiond/session.cpp
src/bin/lttng-sessiond/session.hpp
src/bin/lttng-sessiond/sessiond-config.cpp
src/bin/lttng-sessiond/sessiond-config.hpp
src/bin/lttng-sessiond/snapshot.cpp
src/bin/lttng-sessiond/snapshot.hpp
src/bin/lttng-sessiond/stream-class.cpp
src/bin/lttng-sessiond/stream-class.hpp
src/bin/lttng-sessiond/thread-utils.cpp
src/bin/lttng-sessiond/thread.cpp
src/bin/lttng-sessiond/thread.hpp
src/bin/lttng-sessiond/timer.cpp
src/bin/lttng-sessiond/timer.hpp
src/bin/lttng-sessiond/trace-class.cpp
src/bin/lttng-sessiond/trace-class.hpp
src/bin/lttng-sessiond/trace-kernel.cpp
src/bin/lttng-sessiond/trace-kernel.hpp
src/bin/lttng-sessiond/trace-ust.cpp
src/bin/lttng-sessiond/trace-ust.hpp
src/bin/lttng-sessiond/tracker.cpp
src/bin/lttng-sessiond/tracker.hpp
src/bin/lttng-sessiond/trigger-error-query.cpp
src/bin/lttng-sessiond/tsdl-trace-class-visitor.cpp
src/bin/lttng-sessiond/tsdl-trace-class-visitor.hpp
src/bin/lttng-sessiond/ust-abi-internal.hpp
src/bin/lttng-sessiond/ust-app.cpp
src/bin/lttng-sessiond/ust-app.hpp
src/bin/lttng-sessiond/ust-clock-class.cpp
src/bin/lttng-sessiond/ust-consumer.cpp
src/bin/lttng-sessiond/ust-consumer.hpp
src/bin/lttng-sessiond/ust-ctl-internal.hpp
src/bin/lttng-sessiond/ust-error-internal.hpp
src/bin/lttng-sessiond/ust-field-convert.cpp
src/bin/lttng-sessiond/ust-field-convert.hpp
src/bin/lttng-sessiond/ust-metadata.cpp [deleted file]
src/bin/lttng-sessiond/ust-registry-channel.cpp
src/bin/lttng-sessiond/ust-registry-channel.hpp
src/bin/lttng-sessiond/ust-registry-event.cpp
src/bin/lttng-sessiond/ust-registry-event.hpp
src/bin/lttng-sessiond/ust-registry-session-pid.cpp
src/bin/lttng-sessiond/ust-registry-session-pid.hpp
src/bin/lttng-sessiond/ust-registry-session-uid.cpp
src/bin/lttng-sessiond/ust-registry-session-uid.hpp
src/bin/lttng-sessiond/ust-registry-session.cpp
src/bin/lttng-sessiond/ust-registry-session.hpp
src/bin/lttng-sessiond/ust-registry.cpp
src/bin/lttng-sessiond/ust-registry.hpp
src/bin/lttng-sessiond/ust-sigbus.cpp
src/bin/lttng-sessiond/ust-sigbus.hpp
src/bin/lttng-sessiond/utils.cpp
src/bin/lttng-sessiond/utils.hpp
src/bin/lttng/Makefile.am
src/bin/lttng/command.hpp
src/bin/lttng/commands/add_context.cpp
src/bin/lttng/commands/add_trigger.cpp
src/bin/lttng/commands/clear.cpp
src/bin/lttng/commands/create.cpp
src/bin/lttng/commands/destroy.cpp
src/bin/lttng/commands/disable_channels.cpp
src/bin/lttng/commands/disable_events.cpp
src/bin/lttng/commands/disable_rotation.cpp
src/bin/lttng/commands/enable_channels.cpp
src/bin/lttng/commands/enable_events.cpp
src/bin/lttng/commands/enable_rotation.cpp
src/bin/lttng/commands/help.cpp
src/bin/lttng/commands/list.cpp
src/bin/lttng/commands/list_triggers.cpp
src/bin/lttng/commands/load.cpp
src/bin/lttng/commands/metadata.cpp
src/bin/lttng/commands/regenerate.cpp
src/bin/lttng/commands/remove_trigger.cpp
src/bin/lttng/commands/rotate.cpp
src/bin/lttng/commands/save.cpp
src/bin/lttng/commands/set_session.cpp
src/bin/lttng/commands/snapshot.cpp
src/bin/lttng/commands/start.cpp
src/bin/lttng/commands/status.cpp
src/bin/lttng/commands/stop.cpp
src/bin/lttng/commands/track-untrack.cpp
src/bin/lttng/commands/version.cpp
src/bin/lttng/commands/view.cpp
src/bin/lttng/conf.cpp
src/bin/lttng/conf.hpp
src/bin/lttng/exception.cpp [new file with mode: 0644]
src/bin/lttng/exception.hpp [new file with mode: 0644]
src/bin/lttng/loglevel.cpp
src/bin/lttng/loglevel.hpp
src/bin/lttng/lttng.cpp
src/bin/lttng/uprobe.cpp
src/bin/lttng/uprobe.hpp
src/bin/lttng/utils.cpp
src/bin/lttng/utils.hpp
src/common/Makefile.am
src/common/actions/action.cpp
src/common/actions/list.cpp
src/common/actions/notify.cpp
src/common/actions/path.cpp
src/common/actions/rate-policy.cpp
src/common/actions/rotate-session.cpp
src/common/actions/snapshot-session.cpp
src/common/actions/start-session.cpp
src/common/actions/stop-session.cpp
src/common/align.hpp
src/common/argpar-utils/argpar-utils.cpp
src/common/argpar-utils/argpar-utils.hpp
src/common/argpar/argpar.c
src/common/argpar/argpar.h
src/common/buffer-view.cpp
src/common/buffer-view.hpp
src/common/bug.hpp
src/common/bytecode/bytecode.cpp
src/common/bytecode/bytecode.hpp
src/common/channel.cpp
src/common/common.hpp
src/common/compat/compat-fcntl.cpp [deleted file]
src/common/compat/directory-handle.cpp
src/common/compat/directory-handle.hpp
src/common/compat/dirent.hpp
src/common/compat/endian.hpp
src/common/compat/fcntl.hpp [deleted file]
src/common/compat/getenv.hpp
src/common/compat/netdb.hpp
src/common/compat/paths.hpp
src/common/compat/poll.cpp
src/common/compat/poll.hpp
src/common/compat/pthread.hpp
src/common/compat/socket.hpp
src/common/compat/string.hpp
src/common/compat/tid.hpp
src/common/compat/time.hpp
src/common/compiler.hpp [new file with mode: 0644]
src/common/conditions/buffer-usage.cpp
src/common/conditions/condition.cpp
src/common/conditions/event-rule-matches.cpp
src/common/conditions/session-consumed-size.cpp
src/common/conditions/session-rotation.cpp
src/common/config/config-session-abi.hpp
src/common/config/session-config.cpp
src/common/config/session-config.hpp
src/common/consumer/consumer-metadata-cache.cpp
src/common/consumer/consumer-metadata-cache.hpp
src/common/consumer/consumer-stream.cpp
src/common/consumer/consumer-stream.hpp
src/common/consumer/consumer-timer.cpp
src/common/consumer/consumer-timer.hpp
src/common/consumer/consumer.cpp
src/common/consumer/consumer.hpp
src/common/consumer/metadata-bucket.cpp
src/common/consumer/metadata-bucket.hpp
src/common/container-wrapper.hpp [new file with mode: 0644]
src/common/context.cpp
src/common/context.hpp
src/common/credentials.cpp
src/common/credentials.hpp
src/common/daemonize.cpp
src/common/daemonize.hpp
src/common/defaults.cpp
src/common/defaults.hpp
src/common/domain.cpp
src/common/dynamic-array.cpp
src/common/dynamic-array.hpp
src/common/dynamic-buffer.cpp
src/common/dynamic-buffer.hpp
src/common/endpoint.cpp
src/common/error-query.cpp
src/common/error.cpp
src/common/error.hpp
src/common/evaluation.cpp
src/common/event-expr/event-expr.cpp
src/common/event-field-value.cpp
src/common/event-rule/event-rule.cpp
src/common/event-rule/jul-logging.cpp
src/common/event-rule/kernel-kprobe.cpp
src/common/event-rule/kernel-syscall.cpp
src/common/event-rule/kernel-tracepoint.cpp
src/common/event-rule/kernel-uprobe.cpp
src/common/event-rule/log4j-logging.cpp
src/common/event-rule/python-logging.cpp
src/common/event-rule/user-tracepoint.cpp
src/common/event.cpp
src/common/eventfd.cpp [new file with mode: 0644]
src/common/eventfd.hpp [new file with mode: 0644]
src/common/exception.cpp
src/common/exception.hpp
src/common/fd-handle.cpp
src/common/fd-tracker/fd-tracker.cpp
src/common/fd-tracker/fd-tracker.hpp
src/common/fd-tracker/inode.cpp
src/common/fd-tracker/inode.hpp
src/common/fd-tracker/utils-poll.cpp
src/common/fd-tracker/utils.cpp
src/common/fd-tracker/utils.hpp
src/common/file-descriptor.cpp [new file with mode: 0644]
src/common/file-descriptor.hpp [new file with mode: 0644]
src/common/filter-grammar-test.cpp
src/common/filter.cpp
src/common/filter.hpp
src/common/filter/.clang-tidy [new file with mode: 0644]
src/common/filter/.clang-tidy.ignore [new file with mode: 0644]
src/common/filter/filter-ast.hpp
src/common/filter/filter-ir.hpp
src/common/filter/filter-parser.ypp
src/common/filter/filter-symbols.hpp
src/common/filter/filter-visitor-generate-bytecode.cpp
src/common/filter/filter-visitor-generate-ir.cpp
src/common/filter/filter-visitor-ir-check-binary-comparator.cpp
src/common/filter/filter-visitor-ir-check-binary-op-nesting.cpp
src/common/filter/filter-visitor-ir-normalize-glob-patterns.cpp
src/common/filter/filter-visitor-ir-validate-globbing.cpp
src/common/filter/filter-visitor-ir-validate-string.cpp
src/common/filter/filter-visitor-xml.cpp
src/common/filter/memstream.hpp
src/common/format.hpp
src/common/fs-handle-internal.hpp
src/common/fs-handle.hpp
src/common/futex.cpp
src/common/futex.hpp
src/common/hashtable/hashtable-symbols.hpp
src/common/hashtable/hashtable.cpp
src/common/hashtable/hashtable.hpp
src/common/hashtable/utils.cpp
src/common/health/health.cpp
src/common/index-allocator.cpp
src/common/index-allocator.hpp
src/common/index/ctf-index.hpp
src/common/index/index.cpp
src/common/index/index.hpp
src/common/ini-config/ini-config.cpp
src/common/ini-config/ini-config.hpp
src/common/ini-config/ini.cpp
src/common/ini-config/ini.hpp
src/common/io-hint.cpp [new file with mode: 0644]
src/common/io-hint.hpp [new file with mode: 0644]
src/common/kernel-consumer/kernel-consumer.cpp
src/common/kernel-consumer/kernel-consumer.hpp
src/common/kernel-ctl/kernel-ctl.cpp
src/common/kernel-ctl/kernel-ctl.hpp
src/common/kernel-ctl/kernel-ioctl.hpp
src/common/kernel-probe.cpp
src/common/location.cpp
src/common/locked-reference.hpp
src/common/lockfile.cpp [new file with mode: 0644]
src/common/lockfile.hpp [new file with mode: 0644]
src/common/log-level-rule.cpp
src/common/logging-utils.cpp [new file with mode: 0644]
src/common/logging-utils.hpp [new file with mode: 0644]
src/common/lttng-elf.cpp
src/common/lttng-elf.hpp
src/common/lttng-kernel-old.hpp
src/common/lttng-kernel.hpp
src/common/macros.hpp
src/common/make-unique-wrapper.hpp
src/common/mi-lttng.cpp
src/common/mi-lttng.hpp
src/common/notification.cpp
src/common/optional.hpp
src/common/path.cpp
src/common/payload-view.cpp
src/common/payload-view.hpp
src/common/payload.cpp
src/common/payload.hpp
src/common/pipe.cpp
src/common/pipe.hpp
src/common/pthread-lock.hpp
src/common/random.cpp [new file with mode: 0644]
src/common/random.hpp [new file with mode: 0644]
src/common/readwrite.cpp
src/common/readwrite.hpp
src/common/relayd/relayd.cpp
src/common/relayd/relayd.hpp
src/common/runas.cpp
src/common/runas.hpp
src/common/scope-exit.hpp [new file with mode: 0644]
src/common/session-descriptor.cpp
src/common/sessiond-comm/agent.hpp
src/common/sessiond-comm/inet.cpp
src/common/sessiond-comm/inet.hpp
src/common/sessiond-comm/inet6.cpp
src/common/sessiond-comm/inet6.hpp
src/common/sessiond-comm/relayd.hpp
src/common/sessiond-comm/sessiond-comm.cpp
src/common/sessiond-comm/sessiond-comm.hpp
src/common/shm.cpp
src/common/snapshot.cpp
src/common/snapshot.hpp
src/common/spawn-viewer.cpp
src/common/spawn-viewer.hpp
src/common/string-utils/format.hpp
src/common/string-utils/string-utils.cpp
src/common/string-utils/string-utils.hpp
src/common/testpoint/testpoint.cpp
src/common/testpoint/testpoint.hpp
src/common/thread.cpp
src/common/time.cpp
src/common/time.hpp
src/common/trace-chunk-registry.hpp
src/common/trace-chunk.cpp
src/common/trace-chunk.hpp
src/common/tracker.cpp
src/common/tracker.hpp
src/common/trigger.cpp
src/common/unix.cpp
src/common/unix.hpp
src/common/urcu.hpp
src/common/uri.cpp
src/common/uri.hpp
src/common/userspace-probe.cpp
src/common/ust-consumer/ust-consumer.cpp
src/common/ust-consumer/ust-consumer.hpp
src/common/utils.cpp
src/common/utils.hpp
src/common/uuid.cpp
src/common/uuid.hpp
src/common/waiter.cpp
src/common/waiter.hpp
src/lib/lttng-ctl/channel.cpp
src/lib/lttng-ctl/clear.cpp
src/lib/lttng-ctl/deprecated-symbols.cpp
src/lib/lttng-ctl/destruction-handle.cpp
src/lib/lttng-ctl/event.cpp
src/lib/lttng-ctl/liblttng-ctl.sym
src/lib/lttng-ctl/load.cpp
src/lib/lttng-ctl/lttng-ctl-health.cpp
src/lib/lttng-ctl/lttng-ctl-helper.hpp
src/lib/lttng-ctl/lttng-ctl.cpp
src/lib/lttng-ctl/rotate.cpp
src/lib/lttng-ctl/save.cpp
src/lib/lttng-ctl/snapshot.cpp
src/lib/lttng-ctl/tracker.cpp
src/vendor/.clang-tidy [new file with mode: 0644]
src/vendor/Makefile.am
src/vendor/fmt/args.h
src/vendor/fmt/chrono.h
src/vendor/fmt/color.h
src/vendor/fmt/compile.h
src/vendor/fmt/core.h
src/vendor/fmt/format-inl.h
src/vendor/fmt/format.h
src/vendor/fmt/locale.h [deleted file]
src/vendor/fmt/os.h
src/vendor/fmt/ostream.h
src/vendor/fmt/printf.h
src/vendor/fmt/ranges.h
src/vendor/fmt/std.h [new file with mode: 0644]
src/vendor/fmt/xchar.h
src/vendor/nlohmann/json.hpp [new file with mode: 0644]
tests/Makefile.am
tests/destructive/Makefile.am
tests/destructive/metadata-regeneration
tests/fast_regression [deleted file]
tests/long_regression
tests/meta/Makefile.am [new file with mode: 0644]
tests/meta/test_shellcheck [new file with mode: 0755]
tests/perf/find_event.c
tests/perf/test_perf_raw.in
tests/perf_regression [deleted file]
tests/regression/Makefile.am
tests/regression/kernel/Makefile.am
tests/regression/kernel/select_poll_epoll.cpp
tests/regression/kernel/test_all_events
tests/regression/kernel/test_callstack
tests/regression/kernel/test_channel
tests/regression/kernel/test_clock_override
tests/regression/kernel/test_event_basic
tests/regression/kernel/test_kernel_function
tests/regression/kernel/test_lttng_logger
tests/regression/kernel/test_ns_contexts
tests/regression/kernel/test_ns_contexts_change
tests/regression/kernel/test_rotation_destroy_flush
tests/regression/kernel/test_select_poll_epoll
tests/regression/kernel/test_syscall
tests/regression/kernel/test_userspace_probe
tests/regression/kernel/validate_select_poll_epoll.py
tests/regression/tools/Makefile.am
tests/regression/tools/base-path/test_ust
tests/regression/tools/channel/test_channel
tests/regression/tools/clear/Makefile.am
tests/regression/tools/clear/test_kernel
tests/regression/tools/clear/test_live_hang.py [new file with mode: 0755]
tests/regression/tools/clear/test_ust
tests/regression/tools/client/Makefile.am [new file with mode: 0644]
tests/regression/tools/client/test_bug1373_events_differ_only_by_loglevel [new file with mode: 0755]
tests/regression/tools/client/test_bug1480_assert_data_pending [new file with mode: 0755]
tests/regression/tools/client/test_event_rule_listing.py [new file with mode: 0755]
tests/regression/tools/client/test_session_commands.py [new file with mode: 0755]
tests/regression/tools/context/Makefile.am [new file with mode: 0644]
tests/regression/tools/context/test_ust.py [new file with mode: 0755]
tests/regression/tools/crash/test_crash
tests/regression/tools/exclusion/test_exclusion
tests/regression/tools/filtering/gen-ust-events.c
tests/regression/tools/filtering/test_invalid_filter
tests/regression/tools/filtering/test_unsupported_op
tests/regression/tools/filtering/test_valid_filter
tests/regression/tools/filtering/tp.h
tests/regression/tools/health/health_check.c
tests/regression/tools/health/health_fail.c
tests/regression/tools/health/health_stall.c
tests/regression/tools/health/test_health.sh
tests/regression/tools/health/test_thread_ok
tests/regression/tools/live/live_test.cpp
tests/regression/tools/live/test_kernel
tests/regression/tools/live/test_lttng_kernel
tests/regression/tools/live/test_lttng_ust
tests/regression/tools/live/test_ust
tests/regression/tools/live/test_ust_tracefile_count
tests/regression/tools/metadata/test_kernel
tests/regression/tools/metadata/test_ust
tests/regression/tools/metadata/utils.sh
tests/regression/tools/mi/test_mi
tests/regression/tools/notification/base_client.c
tests/regression/tools/notification/consumer_testpoints.cpp
tests/regression/tools/notification/default_pipe_size_getter.cpp
tests/regression/tools/notification/notification.cpp
tests/regression/tools/notification/rotation.c
tests/regression/tools/notification/sessiond_testpoints.cpp
tests/regression/tools/notification/test_notification_kernel_buffer_usage
tests/regression/tools/notification/test_notification_kernel_capture
tests/regression/tools/notification/test_notification_kernel_error
tests/regression/tools/notification/test_notification_kernel_instrumentation
tests/regression/tools/notification/test_notification_kernel_syscall
tests/regression/tools/notification/test_notification_kernel_userspace_probe
tests/regression/tools/notification/test_notification_multi_app
tests/regression/tools/notification/test_notification_notifier_discarded_count
tests/regression/tools/notification/test_notification_ust_buffer_usage
tests/regression/tools/notification/test_notification_ust_capture
tests/regression/tools/notification/test_notification_ust_error
tests/regression/tools/notification/test_notification_ust_event_rule_condition_exclusion
tests/regression/tools/notification/test_rotation
tests/regression/tools/notification/util_event_generator.sh
tests/regression/tools/regen-metadata/test_kernel
tests/regression/tools/regen-metadata/test_ust
tests/regression/tools/regen-statedump/test_kernel
tests/regression/tools/regen-statedump/test_ust
tests/regression/tools/relayd-grouping/test_ust
tests/regression/tools/rotation/schedule_api.c
tests/regression/tools/rotation/test_kernel
tests/regression/tools/rotation/test_save_load_mi
tests/regression/tools/rotation/test_schedule_api
tests/regression/tools/rotation/test_ust
tests/regression/tools/rotation/test_ust_kernel
tests/regression/tools/save-load/test_autoload
tests/regression/tools/save-load/test_load
tests/regression/tools/save-load/test_save
tests/regression/tools/snapshots/test_kernel
tests/regression/tools/snapshots/test_kernel_streaming
tests/regression/tools/snapshots/test_ust_fast
tests/regression/tools/snapshots/test_ust_long
tests/regression/tools/snapshots/test_ust_streaming
tests/regression/tools/snapshots/ust_test
tests/regression/tools/streaming/test_high_throughput_limits
tests/regression/tools/streaming/test_kernel
tests/regression/tools/streaming/test_ust
tests/regression/tools/tracefile-limits/test_tracefile_count
tests/regression/tools/tracefile-limits/test_tracefile_size
tests/regression/tools/tracker/test_event_tracker
tests/regression/tools/trigger/hidden/hidden_trigger.cpp
tests/regression/tools/trigger/hidden/test_hidden_trigger
tests/regression/tools/trigger/name/trigger_name.cpp
tests/regression/tools/trigger/rate-policy/test_ust_rate_policy
tests/regression/tools/trigger/start-stop/test_start_stop
tests/regression/tools/trigger/test_add_trigger_cli
tests/regression/tools/trigger/test_list_triggers_cli
tests/regression/tools/trigger/test_remove_trigger_cli
tests/regression/tools/trigger/utils/Makefile.am
tests/regression/tools/trigger/utils/notification-client.c [deleted file]
tests/regression/tools/trigger/utils/notification-client.cpp [new file with mode: 0644]
tests/regression/tools/trigger/utils/register-some-triggers.cpp
tests/regression/tools/wildcard/test_event_wildcard
tests/regression/tools/working-directory/test_relayd_working_directory
tests/regression/ust/Makefile.am
tests/regression/ust/baddr-statedump/Makefile.am
tests/regression/ust/baddr-statedump/test_baddr-statedump.py
tests/regression/ust/baddr-statedump/tp.h
tests/regression/ust/before-after/test_before_after
tests/regression/ust/blocking/test_blocking
tests/regression/ust/buffers-pid/test_buffers_pid
tests/regression/ust/clock-override/lttng-ust-clock-override-test.c
tests/regression/ust/clock-override/test_clock_override
tests/regression/ust/daemon/daemon.c
tests/regression/ust/daemon/test_daemon.py
tests/regression/ust/daemon/ust_tests_daemon.h
tests/regression/ust/exit-fast/test_exit-fast.py
tests/regression/ust/exit-fast/ust_tests_exitfast.h
tests/regression/ust/fork/fork.c
tests/regression/ust/fork/test_fork.py
tests/regression/ust/fork/ust_tests_fork.h
tests/regression/ust/getcpu-override/lttng-ust-getcpu-override-test.c
tests/regression/ust/getcpu-override/test_getcpu_override
tests/regression/ust/high-throughput/main.c
tests/regression/ust/high-throughput/test_high_throughput
tests/regression/ust/high-throughput/tp.h
tests/regression/ust/java-jul/test_java_jul
tests/regression/ust/java-log4j/test_java_log4j
tests/regression/ust/java-log4j2/test_agent_log4j2_domain_log4j
tests/regression/ust/libc-wrapper/prog.c
tests/regression/ust/libc-wrapper/test_libc-wrapper.py
tests/regression/ust/linking/demo.c
tests/regression/ust/linking/test_linking.py
tests/regression/ust/linking/ust_tests_demo.h
tests/regression/ust/linking/ust_tests_demo2.h
tests/regression/ust/linking/ust_tests_demo3.h
tests/regression/ust/low-throughput/test_low_throughput
tests/regression/ust/low-throughput/tp.h
tests/regression/ust/multi-lib/callsites.c
tests/regression/ust/multi-lib/multi-lib-test.c
tests/regression/ust/multi-lib/probes.h
tests/regression/ust/multi-lib/test_multi_lib
tests/regression/ust/multi-session/test_multi_session
tests/regression/ust/multi-session/ust_gen_nevents.h
tests/regression/ust/namespaces/test_ns_contexts
tests/regression/ust/namespaces/test_ns_contexts_change
tests/regression/ust/nprocesses/test_nprocesses
tests/regression/ust/overlap/demo/demo.c
tests/regression/ust/overlap/demo/ust_tests_demo.h
tests/regression/ust/overlap/demo/ust_tests_demo2.h
tests/regression/ust/overlap/demo/ust_tests_demo3.h
tests/regression/ust/overlap/test_overlap
tests/regression/ust/periodical-metadata-flush/test_periodical_metadata_flush
tests/regression/ust/python-logging/test_python_logging.in
tests/regression/ust/rotation-destroy-flush/test_rotation_destroy_flush
tests/regression/ust/test_event_basic
tests/regression/ust/test_event_perf
tests/regression/ust/test_event_tracef
tests/regression/ust/type-declarations/test_type_declarations.py
tests/regression/ust/type-declarations/type-declarations.c
tests/regression/ust/type-declarations/ust_tests_td.h
tests/regression/ust/ust-constructor/Makefile.am [new file with mode: 0644]
tests/regression/ust/ust-constructor/__init__.py [new file with mode: 0644]
tests/regression/ust/ust-constructor/test_ust_constructor_c_dynamic.py [new file with mode: 0755]
tests/regression/ust/ust-constructor/test_ust_constructor_c_static.py [new file with mode: 0755]
tests/regression/ust/ust-constructor/test_ust_constructor_cpp_dynamic.py [new file with mode: 0755]
tests/regression/ust/ust-constructor/test_ust_constructor_cpp_static.py [new file with mode: 0755]
tests/regression/ust/ust-constructor/ust_constructor_common.py [new file with mode: 0644]
tests/regression/ust/ust-dl/Makefile.am
tests/regression/ust/ust-dl/libbar-tp.h
tests/regression/ust/ust-dl/libbar.h
tests/regression/ust/ust-dl/libfoo-tp.h
tests/regression/ust/ust-dl/libfoo.c
tests/regression/ust/ust-dl/libfoo.h
tests/regression/ust/ust-dl/libzzz-tp.h
tests/regression/ust/ust-dl/libzzz.h
tests/regression/ust/ust-dl/prog.c
tests/regression/ust/ust-dl/test_ust-dl.py
tests/root_destructive_tests [deleted file]
tests/stress/test_multi_sessions_per_uid_10app
tests/stress/test_multi_sessions_per_uid_5app_streaming
tests/stress/test_multi_sessions_per_uid_5app_streaming_kill_relayd
tests/unit/ini_config/ini_config.cpp
tests/unit/test_action.cpp
tests/unit/test_buffer_view.cpp
tests/unit/test_condition.cpp
tests/unit/test_directory_handle.cpp
tests/unit/test_event_expr_to_bytecode.cpp
tests/unit/test_event_rule.cpp
tests/unit/test_fd_tracker.cpp
tests/unit/test_kernel_data.cpp
tests/unit/test_kernel_probe.cpp
tests/unit/test_log_level_rule.cpp
tests/unit/test_notification.cpp
tests/unit/test_payload.cpp
tests/unit/test_rate_policy.cpp
tests/unit/test_relayd_backward_compat_group_by_session.cpp
tests/unit/test_session.cpp
tests/unit/test_string_utils.cpp
tests/unit/test_unix_socket.cpp
tests/unit/test_uri.cpp
tests/unit/test_ust_data.cpp
tests/unit/test_utils_compat_poll.cpp
tests/unit/test_utils_compat_pthread.cpp
tests/unit/test_utils_expand_path.cpp
tests/unit/test_utils_parse_size_suffix.cpp
tests/unit/test_utils_parse_time_suffix.cpp
tests/unit/test_uuid.cpp
tests/utils/Makefile.am
tests/utils/babelstats.pl [deleted file]
tests/utils/bt2_plugins/Makefile.am [new file with mode: 0644]
tests/utils/bt2_plugins/README.md [new file with mode: 0644]
tests/utils/bt2_plugins/event_name/Makefile.am [new file with mode: 0644]
tests/utils/bt2_plugins/event_name/event_name.cpp [new file with mode: 0644]
tests/utils/bt2_plugins/event_name/event_name.hpp [new file with mode: 0644]
tests/utils/bt2_plugins/field_stats/Makefile.am [new file with mode: 0644]
tests/utils/bt2_plugins/field_stats/field_stats.cpp [new file with mode: 0644]
tests/utils/bt2_plugins/field_stats/field_stats.hpp [new file with mode: 0644]
tests/utils/bt2_plugins/fmt.hpp [new file with mode: 0644]
tests/utils/bt2_plugins/lttngtest-plugin.cpp [new file with mode: 0644]
tests/utils/bt2_plugins/utils.hpp [new file with mode: 0644]
tests/utils/lttngtest/Makefile.am [new file with mode: 0644]
tests/utils/lttngtest/__init__.py [new file with mode: 0644]
tests/utils/lttngtest/environment.py [new file with mode: 0644]
tests/utils/lttngtest/logger.py [new file with mode: 0644]
tests/utils/lttngtest/lttng.py [new file with mode: 0644]
tests/utils/lttngtest/lttngctl.py [new file with mode: 0644]
tests/utils/lttngtest/tap_generator.py [new file with mode: 0644]
tests/utils/parse-callstack.py
tests/utils/tap-driver.sh
tests/utils/tap/Makefile.am
tests/utils/tap/clock.cpp [new file with mode: 0644]
tests/utils/tap/tap.c
tests/utils/tap/tap.h
tests/utils/tap/tap.sh
tests/utils/test_utils.py
tests/utils/testapp/Makefile.am
tests/utils/testapp/gen-data-pending/Makefile.am [new file with mode: 0644]
tests/utils/testapp/gen-data-pending/main.cpp [new file with mode: 0644]
tests/utils/testapp/gen-kernel-test-events/gen-kernel-test-events.c
tests/utils/testapp/gen-ns-events/Makefile.am
tests/utils/testapp/gen-ns-events/gen-ns-events.cpp
tests/utils/testapp/gen-py-events/gen-py-events.py
tests/utils/testapp/gen-syscall-events-callstack/gen-syscall-events-callstack.c
tests/utils/testapp/gen-syscall-events/gen-syscall-events.cpp
tests/utils/testapp/gen-ust-events-constructor/01-c-tp-before-define.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/01-tp-before-define.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/02-c-define-tp.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/02-define-tp.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/03-c-tp-after-define.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/03-tp-after-define.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/04-c-tp-provider.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/04-tp-provider.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/05-c-tp-after-provider.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/05-tp-after-provider.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/Makefile.am [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/main-a.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/main.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/main_c-a.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/main_c-so.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/obj-a.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/obj-a.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/obj.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/obj.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a-define.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a-provider.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a_c-define.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a_c-provider.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-a_c.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so-define.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so-provider.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so_c-define.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so_c-provider.c [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp-so_c.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/tp.h [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-constructor/uses_heap.cpp [new file with mode: 0644]
tests/utils/testapp/gen-ust-events-ns/Makefile.am
tests/utils/testapp/gen-ust-events-ns/gen-ust-events-ns.cpp
tests/utils/testapp/gen-ust-events-ns/tp.h
tests/utils/testapp/gen-ust-events/gen-ust-events.cpp
tests/utils/testapp/gen-ust-events/tp.h
tests/utils/testapp/gen-ust-nevents-str/gen-ust-nevents-str.cpp
tests/utils/testapp/gen-ust-nevents-str/tp.h
tests/utils/testapp/gen-ust-nevents/gen-ust-nevents.cpp
tests/utils/testapp/gen-ust-nevents/tp.h
tests/utils/testapp/gen-ust-tracef/gen-ust-tracef.cpp
tests/utils/testapp/signal-helper.hpp
tests/utils/testapp/userspace-probe-elf-binary/Makefile.am
tests/utils/testapp/userspace-probe-elf-binary/userspace-probe-elf-binary.c
tests/utils/testapp/userspace-probe-elf-cxx-binary/test_class.cpp
tests/utils/testapp/userspace-probe-elf-cxx-binary/test_class.hpp
tests/utils/testapp/userspace-probe-elf-cxx-binary/userspace-probe-elf-cxx-binary.cpp
tests/utils/testapp/userspace-probe-sdt-binary/Makefile.am
tests/utils/testapp/userspace-probe-sdt-binary/libbar.c
tests/utils/testapp/userspace-probe-sdt-binary/libfoo.c
tests/utils/testapp/userspace-probe-sdt-binary/libzzz.c
tests/utils/testapp/userspace-probe-sdt-binary/sema.c
tests/utils/testapp/userspace-probe-sdt-binary/userspace-probe-sdt-binary.c
tests/utils/utils.cpp
tests/utils/utils.h
tests/utils/utils.sh
tests/utils/xml-utils/extract_xml.cpp
tests/utils/xml-utils/validate_xml.cpp

index 66b5ef4088dc7e9088f12c8ff4c7f4c298e6558b..28ea69873145dcb40b167d659a3b828b8968e9b8 100644 (file)
@@ -1,7 +1,8 @@
 AccessModifierOffset: -8
-AlignAfterOpenBracket: DontAlign
+AlignAfterOpenBracket: Align
 AlignConsecutiveAssignments: false
 AlignConsecutiveDeclarations: false
+AlignConsecutiveMacros: Consecutive
 AlignEscapedNewlines: Left
 AlignOperands: false
 AlignTrailingComments: false
@@ -14,8 +15,9 @@ AllowShortLoopsOnASingleLine: false
 AlwaysBreakAfterReturnType: None
 AlwaysBreakBeforeMultilineStrings: false
 AlwaysBreakTemplateDeclarations: Yes
-BinPackArguments: true
+BinPackArguments: false
 BinPackParameters: false
+BitFieldColonSpacing: None
 BreakBeforeBraces: Custom
 BreakConstructorInitializers: AfterColon
 BraceWrapping:
@@ -38,21 +40,35 @@ BreakStringLiterals: false
 ColumnLimit: 100
 ConstructorInitializerAllOnOneLineOrOnePerLine: true
 ConstructorInitializerIndentWidth: 8
-ContinuationIndentWidth: 16
+ContinuationIndentWidth: 8
+Cpp11BracedListStyle: false
 DerivePointerAlignment: false
 DisableFormat: false
 EmptyLineBeforeAccessModifier: LogicalBlock
+FixNamespaceComments: true
 ForEachMacros:
   - 'cds_lfht_for_each_entry'
   - 'cds_lfht_for_each_entry_safe'
   - 'cds_lfht_for_each_duplicate'
   - 'cds_list_for_each_entry'
   - 'cds_list_for_each_entry_safe'
+  - 'for_each_action_mutable'
+  - 'for_each_action_const'
+  - 'cds_wfs_for_each_blocking_safe'
 
-IncludeBlocks: Preserve
+IncludeBlocks: Regroup
 IncludeCategories:
-  - Regex: '.*'
+  - Regex: '".*"'
+    Priority: 0
+  - Regex: '<common/.*>'
     Priority: 1
+  - Regex: '<lttng/.*>'
+    Priority: 2
+  - Regex: '<vendor/.*>'
+    Priority: 3
+  - Regex: '<.*>'
+    Priority: 9
+
 IncludeIsMainRegex: '(Test)?$'
 IndentCaseLabels: false
 IndentPPDirectives: None
diff --git a/.clang-tidy b/.clang-tidy
new file mode 100644 (file)
index 0000000..5b6f370
--- /dev/null
@@ -0,0 +1,103 @@
+HeaderFilterRegex: '.*((include/.*-internal)|(src/common.*)|(src/bin.*)|(src/lib.*)|(tests.*))\.(h|hpp)$'
+Checks:          '-*,
+                  bugprone-argument-comment,
+                  bugprone-assert-side-effect,
+                  bugprone-assignment-in-if-condition,
+                  bugprone-bad-signal-to-kill-thread,
+                  bugprone-bool-pointer-implicit-conversion,
+                  bugprone-copy-constructor-init,
+                  bugprone-dangling-handle,
+                  bugprone-exception-escape,
+                  bugprone-fold-init-type,
+                  bugprone-forward-declaration-namespace,
+                  bugprone-forwarding-reference-overload,
+                  bugprone-inaccurate-erase,
+                  bugprone-incorrect-roundings,
+                  bugprone-infinite-loop,
+                  bugprone-integer-division,
+                  bugprone-macro-parentheses,
+                  bugprone-macro-repeated-side-effects,
+                  bugprone-misplaced-operator-in-strlen-in-alloc,
+                  bugprone-misplaced-pointer-arithmetic-in-alloc,
+                  bugprone-move-forwarding-reference,
+                  bugprone-multiple-statement-macro,
+                  bugprone-not-null-terminated-result,
+                  bugprone-parent-virtual-call,
+                  bugprone-posix-return,
+                  bugprone-shared-ptr-array-mismatch,
+                  bugprone-signal-handler,
+                  bugprone-signed-char-misuse,
+                  bugprone-sizeof-container,
+                  bugprone-sizeof-expression,
+                  bugprone-standalone-empty,
+                  bugprone-string-constructor,
+                  bugprone-string-integer-assignment,
+                  bugprone-string-literal-with-embedded-nul,
+                  bugprone-suspicious-enum-usage,
+                  bugprone-suspicious-include,
+                  bugprone-suspicious-memory-comparison
+                  bugprone-suspicious-memset-usage,
+                  bugprone-suspicious-missing-comma,
+                  bugprone-suspicious-realloc-usage,
+                  bugprone-suspicious-semicolon,
+                  bugprone-suspicious-string-compare,
+                  bugprone-swapped-arguments,
+                  bugprone-terminating-continue,
+                  bugprone-throw-keyword-missing,
+                  bugprone-too-small-loop-variable,
+                  bugprone-unchecked-optional-access
+                  bugprone-undefined-memory-manipulation,
+                  bugprone-undelegated-constructor,
+                  bugprone-unhandled-exception-at-new,
+                  bugprone-unhandled-self-assignment,
+                  bugprone-unused-raii,
+                  bugprone-unused-return-value,
+                  bugprone-use-after-move,
+                  bugprone-virtual-near-miss,
+                  bugprone-unused-raii,
+                  bugprone-use-after-move,
+                  cppcoreguidelines-pro-type-const-cast,
+                  cppcoreguidelines-slicing,
+                  cppcoreguidelines-special-member-functions,
+                  cppcoreguidelines-virtual-class-destructor,
+                  google-build-explicit-make-pair,
+                  google-explicit-constructor,
+                  misc-const-correctness,
+                  misc-misleading-identifier,
+                  misc-non-copyable-objects,
+                  misc-throw-by-value-catch-by-reference,
+                  misc-unused-parameters,
+                  misc-unused-using-decls,
+                  misc-use-anonymous-namespace,
+                  modernize-avoid-bind,
+                  modernize-concat-nested-namespaces,
+                  modernize-loop-convert,
+                  modernize-make-shared,
+                  modernize-make-unique,
+                  modernize-pass-by-value,
+                  modernize-redundant-void-arg,
+                  modernize-replace-auto-ptr,
+                  modernize-replace-random-shuffle,
+                  modernize-replace-auto-ptr,
+                  modernize-shrink-to-fit,
+                  modernize-use-bool-literals,
+                  modernize-use-default-member-init,
+                  modernize-use-emplace,
+                  modernize-use-equals-default,
+                  modernize-use-equals-delete,
+                  modernize-use-noexcept,
+                  modernize-use-nullptr,
+                  modernize-use-override,
+                  modernize-use-transparent-functors,
+                  modernize-use-using,
+                  performance-*,
+                  -performance-no-int-to-ptr,
+                  readability-redundant-member-init,
+                  readability-simplify-boolean-expr,
+                  readability-static-definition-in-anonymous-namespace'
+FormatStyle: 'file'
+CheckOptions:
+  - key:          bugprone-assert-side-effect.AssertMacros
+    value:        assert,LTTNG_ASSERT
+  - key:          bugprone-signed-char-misuse.CharTypdefsToIgnore
+    value:        'int8_t'
diff --git a/.commit_template b/.commit_template
new file mode 100644 (file)
index 0000000..b0da315
--- /dev/null
@@ -0,0 +1,24 @@
+Fix: Short description
+
+Observed issue
+==============
+
+Steps to reproduce (list of commands or narrative description).
+
+Cause
+=====
+
+Solution
+========
+
+Known drawbacks
+===============
+
+References
+==========
+[1]:
+
+Fixes: #xxx
+Refs: #yyy
+
+Signed-off-by:
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
new file mode 100644 (file)
index 0000000..82b6854
--- /dev/null
@@ -0,0 +1,4 @@
+# Run clang-format on the whole tree
+28ab034a2c3582d07d3423d2d746731f87d3969f
+# Clean-up: run format-cpp on the tree
+28f23191dcbf047429d51950a337a57d7a3f866a
index 827e00e0158552fcdd6394bc30b479cf4a33575f..4c5a4e5e9999f9b0dbf86be3eb07f51df7a0983d 100644 (file)
@@ -31,6 +31,7 @@ stamp-h1
 libtool
 tags
 /config/
+pre-inst-env
 
 .autotools
 .cproject
@@ -99,6 +100,11 @@ compile_commands.json
 /tests/regression/ust/high-throughput/gen-events
 /tests/regression/tools/filtering/gen-ust-events
 /tests/utils/testapp/gen-ust-events/gen-ust-events
+/tests/utils/testapp/gen-ust-events-constructor/gen-ust-events-constructor-a
+/tests/utils/testapp/gen-ust-events-constructor/gen-ust-events-constructor-so
+/tests/utils/testapp/gen-ust-events-constructor/gen-ust-events-c-constructor-a
+/tests/utils/testapp/gen-ust-events-constructor/gen-ust-events-c-constructor-so
+/tests/utils/testapp/gen-ust-events-constructor/uses_heap
 /tests/utils/testapp/gen-ust-events-ns/gen-ust-events-ns
 /tests/regression/tools/health/health_check
 /tests/regression/kernel/select_poll_epoll
@@ -132,6 +138,8 @@ compile_commands.json
 /tests/regression/ust/ust-dl/test_ust-dl
 /tests/regression/ust/multi-lib/exec-with-callsites
 /tests/regression/ust/multi-lib/exec-without-callsites
+/tests/utils/testapp/gen-data-pending/gen-data-pending
+/tests/utils/tap/clock
 /tests/utils/testapp/gen-syscall-events-callstack/gen-syscall-events-callstack
 /tests/utils/testapp/gen-ust-events/gen-ust-events
 /tests/utils/testapp/gen-ust-events-ns/gen-ust-events-ns
@@ -170,6 +178,10 @@ compile_commands.json
 /doc/man/*.h
 /doc/man/asciidoc-attrs.conf
 !/doc/man/lttng-health-check.3
+/doc/man/man1
+/doc/man/man3
+/doc/man/man7
+/doc/man/man8
 
 # examples
 /doc/examples/rotation/rotate-client
index 6873d78109b05927ed17de73cce8d335389b601a..fbb48cd5ee145f11ceff31910ead598524d6f26c 100644 (file)
@@ -15,48 +15,44 @@ control. The upstream Git repository URL is:
 
 ## Coding standard
 
-LTTng-tools uses the
-[Linux kernel coding style](http://www.kernel.org/doc/Documentation/CodingStyle)
-with one addition: single-line `if`/`for`/`while` statements must be
-wrapped in braces.
-
-Example:
-
-~~~ c
-/* not good */
-if (this == that)
-    goto fail;
-
-/* good */
-if (this == that) {
-    goto fail;
-}
-~~~
+See CodingStyle for guidelines style and design guidelines.
 
-Although the LTTng-tools code base is primarily written in C, it does
-contain shell, Perl, and Python code as well. There is no official coding
+Although the LTTng-tools code base is primarily written in C++, it does
+contain C, shell, and Python code as well. There is no official coding
 standard for these languages. However, using a style consistent with the
 rest of the code written in that language is strongly encouraged.
 
 
 ## Creating and sending a patch
 
-LTTng-tools's development flow is primarily email-based, although we
-also accept pull requests on our
-[GitHub mirror](https://github.com/lttng/lttng-tools) and
-[Gerrit Code Review](https://review.lttng.org). If you're going
-to create GitHub pull requests, make sure you still follow the
+LTTng-tools's development flow is primarily based on
+[Gerrit Code Review](https://review.lttng.org), although we also accept
+e-mail based patch series on the
+[`lttng-dev` mailing list](https://lists.lttng.org/cgi-bin/mailman/listinfo/lttng-dev)
+and pull requests on our [GitHub mirror](https://github.com/lttng/lttng-tools).
+If you're going to create GitHub pull requests, make sure you still follow the
 guidelines below.
 
-Like a lot of open source projects, patches are submitted and reviewed
-on its development mailing list,
-[`lttng-dev`](http://lists.lttng.org/cgi-bin/mailman/listinfo/lttng-dev)
-(`lttng-dev@lists.lttng.org`). The mailing list is also used to share
-and comment on <abbr title="Request for Comments">RFC</abbr>s and answer
+The mailing list is also used to share and comment on
+<abbr title="Request for Comments">RFC</abbr>s and answer
 user questions.
 
-Once your changes have been committed to your local branch, you may use
-Git's [`format-patch`](https://git-scm.com/docs/git-format-patch) command
+A template commit messsage is available below, and as a file that you may
+configure your local check out to use:
+
+    git config commit.template .commit_template
+
+Once your changes have been comitted to your local branch, you may use the
+[git-review](https://opendev.org/opendev/git-review) plugin to submit them
+directly to [Gerrit](https://review.lttng.org) using the following command:
+
+    git review
+
+Please note that you will need to create an account on [Gerrit](https://review.lttng.org)
+and add an SSH public key.
+
+For e-mail based patches you may use Git's
+[`format-patch`](https://git-scm.com/docs/git-format-patch) command
 to generate a patch file. The following command line generates a
 patch from the latest commit:
 
diff --git a/CodingStyle b/CodingStyle
deleted file mode 100644 (file)
index 6ff931b..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-LTTng-Tools Coding Style
-
-Author: David Goulet
-Last Update: 13/11/2012
-
-Tabs VS Spaces:
--------------
-
-Right, so our two cents in this endless war! This project uses TABS for one
-simple reason, the coder can choose whatever size or type his/her indentation
-is and can set the prefered coding style by replacing the tabs which each
-normally respected IDE/editor can do.
-
-For vim, here is what I used:
-
-  set shiftwidth=4
-  set noexpandtab
-
-There is one exception for which  we use space in this project is for enum,
-defines and macros values indentation. For instance:
-
-Use space to indent the the value so they fit when reading them all. Same goes
-for the #define below.
-
-enum my_enum {
-       value1     = 1,
-       value289   = 289,
-       ...
-};
-
-#define DEFAULT_VALUE_OF_SOME_SORT   6
-#define THE_ANSWER                   42
-
-Use either a single space or tabs to indent the '\' at the end of lines.
-Use tabs at the beginning of lines.
-
-Either:
-
-#define a_macro(x) \
-       do { \
-               fsync(); \
-       } while (0)
-
-or
-
-#define a_macro(x)             \
-       do {                    \
-               fsync();        \
-       } while (0)
-
-Here is a pretty cool vim macro that will highlight your whitespaces and spaces
-before tab. This helps a *LOT* when coding.
-
-" Show trailing whitepace and spaces before a tab:
-function MyTrail()
-    let no_hl_trail = ["man", "help"]
-    if index(no_hl_trail, &ft) >= 0
-        return
-    endif
-    syn match ErrorMsg /\s\+$\| \+\ze\t\|\t\+\ze / containedin=@NoTrail
-endfunction
-syn cluster NoTrail contains=ALL remove=cComment
-autocmd Syntax * call MyTrail()
-
-C Style:
--------------
-
-The coding style used for this project follows the the Linux kernel guide
-lines, except that brackets "{", "}" should typically be used even for
-single-line if/else statements. Please refer to:
-
-- doc/kernel-CodingStyle.txt (copied from Linux 3.4.4 git tree).
-
-- Linux kernel scripts/checkpatch.pl for a script which verify the patch
-  coding style.
-
-For header files, please declare the following in this order:
-
-1) #defines
-       - Default values should go in: src/common/defaults.h
-       - Macros used across the project: src/common/macros.h
-
-2) Variables
-       - No _static_ in a header file! This is madness.
-       - Use _extern_ if the global variable is set else where.
-
-3) Function prototype
-
-Furthermore, respect the name spacing of files for each non-static symbol
-visiable outside the scope of the C file. For instance, for the utils.c file in
-libcommon, every call should be prefixed by "utils_*".
-
-Error handling:
--------------
-
-We ask to use one single return point in a function. For that, we uses the
-"goto" statement for the error handling creating one single point for error
-handling and return code. See the following example:
-
-int some_function(...)
-{
-       int ret;
-       [...]
-
-       if (ret != 0) {
-               goto error;
-       }
-
-       [...]
-error:
-       return ret;
-}
-
-Commenting:
--------------
-
-Every function MUST have a comment above it even if the function is trivial.
-
-Please add non-trivial comments/documentation as much as you can in the code.
-Poor comments WILL be rejected upon merging so please pay attention to this
-details because we do!
-
-If the comments requires more than one line, please format like so:
-
-/*
- * Some comments which requires multiple
- * lines [...]
- */
-
-and on a single line:
-
-/* My comment on a single line. */
diff --git a/CodingStyle.md b/CodingStyle.md
new file mode 100644 (file)
index 0000000..0aac924
--- /dev/null
@@ -0,0 +1,318 @@
+# Coding style guide
+
+It is said that there is no accounting for taste. However, when it comes to code, we are of the opinion that a _consistent_ style makes it easier to collaborate in a shared code base.
+
+Style guidelines are bound to be controversial. Some conventions laid out in this guide have objective merit. However, most boil down to personal preferences of the original authors.
+
+As such, this guide attempts to lay out the conventions used in the project so that new contributors can easily conform to them and minimize time lost during code review.
+
+Contributions are expected to adhere to these guidelines.
+
+## C++
+
+### Migration from C
+
+As the LTTng-tools project aims at supporting a broad range of compilers -- currently starting from GCC 4.8 and Clang 3.3 -- its build system is configured to use the C++11 standard.
+
+LTTng-tools has historically been developped in C99 with liberal uses of GNU extensions. Since the release of LTTng 2.13, it has started a migration to C++.
+
+In order to ease the transition, it underwent an initial migration phase which had a limited scope: build all existing C code as C++11.
+
+As such, most of the project's code does not qualify as idiomatic C++ code. This migration is ongoing and expected to span across multiple release cycles.
+
+However, new contributions are expected to conform the C++ style described in this guide. Some exceptions are allowed for small fixes which have to be back-ported to stable branches.
+
+### Automated formatting
+
+All the project's C++ files follow the [clang-format](https://clang.llvm.org/docs/ClangFormat.html) [style](https://clang.llvm.org/docs/ClangFormatStyleOptions.html) of the `.clang-format` file for whitespaces, indentation, and line breaks.
+
+You _must_ format your changes with clang-format before you contribute a patch.
+
+Note that clang-format 14 is required to use the project's `.clang-format` file.
+
+Most text editors allow you to format a sub-section of a source file using clang-format to ensure it adheres to the project's style.
+
+If you are submitting a change to existing source files, _do not run clang-format on the whole file_ as this may introduce more changes than you intended and _will_ cause your changes to be rejected.
+
+### Tabs VS Spaces
+
+While our founding mothers and fathers eschewed any consideration for non-English languages when designing the ASCII character encoding they, in a rare moment of technical decadence, decided to dedicate a character to the sole purpose of expressing tabulations.
+
+This project makes use of this character to express indentations in its source files.
+
+Note that while tab characters are used for semantic indentation purposes, spaces are perfectly fine to use for _visual_ alignment (e.g. ascii diagrams).
+
+### Single line control flow statements
+
+Single line control flow statements (if/for/while) are required to use braces.
+
+```cpp
+/* bad */
+if  (my_thingy)
+       do_the_thing();
+
+/* good */
+if  (my_thingy)  {
+       do_the_thing();
+}
+```
+
+### Naming
+
+- Use snake case (e.g. `a_snake_case_name`) except for template parameters, which use camel case and end with `Type` (e.g. `ACamelCaseNameType`).
+
+- Prefer using explicit and verbose names. For instance:
+  - When naming a variable that indicates a count of bananas, prefer `banana_count` to `bananas`, `count`, or `n`.
+  - When naming a function or method that validates and initializes a user profile, prefer `validate_and_initialize_user_profile()` to `set_up()`, `viup()`, `do_user_profile()`, `init()`.
+
+- Avoid the use of overly generic terms like `data`, `ptr`, and `buffer`.
+
+- Use an underscore prefix for private or protected methods and members, and member type names: `_try_connect()`, `class _user_count`, `int _version`.
+
+- Name trivial setters and getters like the property name, without a verb (e.g. `set` and `get` prefixes).
+
+  ```cpp
+  /* good, gets the session's name. */
+  session.name();
+  /* good, sets the session's name. */
+  session.name("my new name");
+
+  /* good, non-trivial accessor */
+  session.add_channel(my_channel);
+  ```
+
+- Use the `is` or `has` prefixes to name boolean properties or functions which return a `bool` type.
+
+- Do not make-up abbreviations to shorten names. Term of art abbreviations are, however, acceptable. For example: `mpeg`, `ctf`, `cfg`, `init` are accepted. A notable exception to this rule applies to namespaces, see the "Use of namespaces/Aliases" section.
+
+### Comments
+
+In general, comments should focus on _why_ something is done and document the assumptions the code was built upon. They should not repeat what it does in plain english except if the code is particularily complex. Keep in mind that what may be obvious to you right now may not be obvious to reviewers... or your future self.
+
+Also, write comments in grammatically-sound English and avoid writing using telegraph style:
+
+```cpp
+/* Bad: init cfg */
+
+/* Bad: init cfg before reply */
+
+/* Good: The configuration must be initialized before replying since it initializes the user's credentials. */
+```
+
+### Include guards
+
+Header files must use include guards to prevent multiple inclusion issues. To avoid collisions, the name of include guards must be as specific as possible and include the name of the file.
+
+```cpp
+/* In file thingy-handler.hpp */
+
+#ifndef LTTNG_CONSUMERD_THINGY_HANDLER
+#define LTTNG_CONSUMERD_THINGY_HANDLER
+
+/* Some briliant code. */
+
+#endif  /* LTTNG_CONSUMERD_THINGY_HANDLER */
+```
+
+
+### Use of namespaces
+
+Make liberal use of namespaces. Very little should be available in the `lttng`,
+let alone global, namespace.
+
+Moreover, prefer to use anonymous namespaces to the `static`  keyword to restrict the visibility of a symbol to its translation unit.
+
+#### Do not pollute the global namespace
+
+Never use the `using` directive to import the contents of a namespace. If a namespace is used often in a file, define an alias.
+
+#### Aliases
+
+Within a translation unit, it is acceptable to abbreviate commonly-used namespace names to define an alias. For instance, the file containing the implementation of the `food::fruits::citrus::grapefruit` can use the `ffc` namespace alias for brievety.
+
+```cpp
+/* In file grapefruit.cpp */
+
+namespace ffc = food::fruits::citrus;
+
+ffc::grapefruit::grapefruit()
+{
+    // ...
+}
+```
+
+### File layout example
+
+```cpp
+/*
+ * Copyright (C) 20xx Robert Binette <bob@codebleu.qc.ca>
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ *
+ */
+
+#ifndef LTTNG_THING_DOER_H
+#define LTTNG_THING_DOER_H
+
+/* Mind the order of inclusions, in alphabetical order per category. */
+
+/* Project-local headers. */
+#include "my-local-stuff.hpp"
+#include "utils.hpp"
+
+/* Project-wide headers. */
+#include <vendor/optional.hpp>
+
+/* System headers. */
+#include <functional>
+#include <string>
+#include 
+
+namespace lttng {
+namespace sessiond {
+
+class things;
+
+using on_new_name_function = std::function<void(const std::string& name)>;
+
+class thing_doer : public lttng::sessiond::doer {
+public:
+       explicit thing_doer(const std::string& name);
+
+       void do() override final;
+       const std::string& name() const;
+
+private:
+       unsigned int _count_things(std::vector) const noexcept;
+
+       const std::string _name;
+};
+
+} /* namespace sessiond */
+} /* namespace lttng */
+
+#endif /* LTTNG_THING_DOER_H */
+```
+
+### Miscelaneous guidelines
+
+In general, the project’s contributors make an effort to follow, for C++11 code:
+
+[The C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md)
+
+[Scott Meyers’s “Effective Modern C++”](https://www.oreilly.com/library/view/effective-modern-c/9781491908419/)
+
+Here are a couple of reminders:
+* When defining a class, put constructors as the first methods, whatever their access (public/protected/private), then the destructor, and then the rest.
+
+* Declare variables as close to where they are used as possible.
+
+* Use auto when possible.
+
+* Use const as much as possible, even for pointer (const char* const) and numeric values (const unsigned int) which never need to change.
+
+* Make methods const noexcept or const as much as possible.
+
+* Make constructors explicit unless you really need an implicit constructor (which is rare).
+
+* Use `std::unique_ptr` to manage memory when possible.
+  * However, use references (`*my_unique_ptr`) and raw pointers (`my_unique_ptr.get()`) when not transferring ownership.
+  * Only use `std::shared_ptr` when ownership is conceptually shared.
+
+* Use `nullptr`, not `NULL` nor `0`.
+
+* Return by value (rvalue) instead of by output parameter (non-const lvalue reference), even complex objects, unless you can prove that the performance is improved when returning by parameter.
+
+* For a function parameter or a return value of which the type needs to be a reference or pointer, use:
+  * **If the value is mandatory**, a reference.
+  * **If the value is optional**, a raw pointer.
+
+* Don't use `std::move()` when you already have an rvalue, which means:
+  * Don't write `return std::move(...);` as this can interfere with RVO (Return Value Optimization).
+  * Don't use `std::move()` with a function call (`std::move(func())`).
+
+* For each possible move/copy constructor or assignment operator, do one of:
+  * Write a custom one.
+  * Mark it as defaulted (`default`)
+  * Mark it as deleted (`delete`).
+
+* Use scoped enumerations (`enum class`).
+
+* Mark classes known to be final with the `final` keyword.
+
+* Use type aliases (`using`), not type definitions (`typedef`).
+
+* Use anonymous namespaces for local functions instead of `static`.
+
+* Return a structure with named members instead of a generic container such as `std::pair` or `std::tuple`.
+
+* When a class inherits a base class with virtual methods, use the `override` keyword to mark overridden virtual methods, and do not use the `virtual` keyword again (as the method is already known to be virtual).
+
+* Define overloaded operators only if their meaning is obvious, unsurprising, and consistent with the corresponding built-in operators.
+
+  For example, use `|` as a bitwise or logical-or, not as a shell-style pipe.
+
+* Use RAII wrappers when managing system resources or interacting with C libraries.
+
+  In other words, don't rely on ``goto``s and error labels to clean up as you would do in C.
+
+* Throw an exception when there's an unexpected, exceptional condition,
+  [including from a constructor](https://isocpp.org/wiki/faq/exceptions#ctors-can-throw), instead of returning a status code.
+
+  However, be mindful of the exception-safety of your users. For instance, `liblttng-ctl` exposes a C interface meaning that is must catch and handle all exceptions, most likely by returning a suitable error code.
+
+* Accept a by-value parameter and move it (when it's moveable) when you intend to copy it anyway. You can do this with most STL containers.
+
+## Python
+
+Python code should be formatted using [black](https://github.com/psf/black).
+
+## Shell (BASH)
+
+New scripts and modifications to existing scripts should pass linting
+with [Shellcheck](https://www.shellcheck.net/).
+
+## C Style (historical)
+
+The coding style used for this project follows the the Linux kernel guide lines, except that brackets `{`, `}` should typically be used even for single-line if/else statements. Please refer to:
+
+- doc/kernel-CodingStyle.txt (copied from the Linux 3.4.4 tree).
+
+- Linux kernel scripts/checkpatch.pl for a script which verify the patch
+  coding style.
+
+For header files, please declare the following in this order:
+
+1) `#define`
+
+ - Default values should go in: src/common/defaults.h
+ - Macros used across the project: src/common/macros.h
+
+2) Variables
+
+ - No _static_ in a header file! This is madness.
+ - Use _extern_ if the global variable is set else where.
+
+3) Function prototype
+
+Furthermore, respect the name spacing of files for each non-static symbol visiable outside the scope of the C file. For instance, for the utils.c file in libcommon, every call should be prefixed by "utils_*".
+
+### Error handling
+
+In legacy C-style code, we ask to use one single return point in a function. For that, we uses the "goto" statement for the error handling creating one single point for error handling and return code. See the following example:
+
+```c
+int some_function(...)
+{
+       int ret;
+       [...]
+
+       if (ret != 0) {
+               goto error;
+       }
+
+       [...]
+error:
+       return ret;
+}
+```
index 636296e46e7e017fde3cce19377a875687bdeb8c..040d9df6c9c834c7196bbc00a8ae916cebc2c420 100644 (file)
@@ -14,9 +14,10 @@ dist_doc_DATA = LICENSE \
                 ChangeLog \
                README.adoc
 
-dist_noinst_DATA = CodingStyle
+dist_noinst_DATA = CodingStyle.md
 
 EXTRA_DIST = extras/lttng-bash_completion \
+            extras/zsh-completion \
             LICENSES/BSD-2-Clause \
             LICENSES/BSD-3-Clause \
             LICENSES/GPL-2.0 \
index 830dd933e850ac1505c80347a1ffdd66d42dad51..676467aa4cfbe09499994f8232865c24c33666d0 100644 (file)
@@ -16,7 +16,7 @@ endif::env-github[]
 5 May 2020
 
 [.normal]
-https://ci.lttng.org/job/lttng-tools_master_build/[image:https://img.shields.io/jenkins/s/https/ci.lttng.org/lttng-tools_master_build.svg[Jenkins, title="Jenkins"]]
+https://ci.lttng.org/job/lttng-tools_master_linuxbuild/[image:https://img.shields.io/jenkins/build.svg?jobUrl=https://ci.lttng.org/job/lttng-tools_master_linuxbuild/[Jenkins, title="Jenkins"]]
 https://scan.coverity.com/projects/lttng-tools[image:https://img.shields.io/coverity/scan/lttng-tools.svg[Coverity, title="Coverity"]]
 
 [.lead]
@@ -54,7 +54,7 @@ components:
 
 * **Linux kernel{nbsp}≥{nbsp}2.6.30**
 
-* **http://www.liburcu.org/[Userspace{nbsp}RCU]{nbsp}≥{nbsp}0.11.0**.
+* **http://www.liburcu.org/[Userspace{nbsp}RCU]{nbsp}≥{nbsp}0.14.0**.
 +
 Debian/Ubuntu package: `liburcu{nbh}dev`.
 
@@ -72,16 +72,14 @@ The following dependencies are optional:
   of the https://lttng.org/man/1/lttng-view/[`lttng view`] command,
   `make{nbsp}check` and tests.
 +
-Debian/Ubuntu package: `babeltrace2`
+Debian/Ubuntu package: `babeltrace2 libbabeltrace2-dev`
 
 * **https://lttng.org/[LTTng{nbh}UST]** (same minor version as {lt}):
   LTTng user space tracing (applications and libraries).
 +
 Debian/Ubuntu package: `liblttng{nbh}ust{nbh}dev`
 
-* **Perl**: `make{nbsp}check` and tests.
-
-* **https://www.python.org/[Python]{nbsp}≥{nbsp}3.0**:
+* **https://www.python.org/[Python]{nbsp}≥{nbsp}3.4**:
   `make{nbsp}check` and tests.
 +
 Debian/Ubuntu package: `python3`
@@ -133,7 +131,7 @@ information on versioning.
 You need the following tools to build {lt}:
 
 * **https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html[GNU{nbsp}Autotools]**
-  (**Automake{nbsp}≥{nbsp}1.10**,
+  (**Automake{nbsp}≥{nbsp}1.12**,
   **Autoconf{nbsp}≥{nbsp}2.64**, and **Autoheader{nbsp}≥{nbsp}2.50**)
 
 * **http://www.gnu.org/software/autoconf/[GNU{nbsp}Libtool]{nbsp}≥{nbsp}2.2**
@@ -144,7 +142,7 @@ You need the following tools to build {lt}:
 
 To build the {lt} manual pages:
 
-* **https://www.methods.co.nz/asciidoc/[AsciiDoc]{nbsp}≥{nbsp}8.4.5**
+* **https://asciidoc.org/[AsciiDoc]{nbsp}≥{nbsp}8.4.5**
 +
 NOTE: Previous versions could work, but were not tested.
 
@@ -223,6 +221,21 @@ As there's no official {lib} Python bindings yet, see
 link:doc/python-howto.txt[`doc/python-howto.txt`] to understand how to
 use them.
 
+== Supported versions
+
+The LTTng project supports the last two released stable versions
+(e.g. stable-2.13 and stable-2.12).
+
+Fixes are backported from the master branch to the last stable version unless
+those fixes would break the ABI or API. Those fixes may be backported to the
+second-last stable version, depending on complexity and ABI/API compatibility.
+
+Security fixes are backported from the master branch to both of the last stable
+version and the second-last stable version.
+
+New features are integrated into the master branch and not backported to the
+last stable branch.
+
 == Community
 
 Mailing list::
@@ -245,3 +258,6 @@ Continuous integration::
 Code review::
     https://review.lttng.org/q/project:lttng-tools[_lttng{nbh}tools_ project]
     on LTTng Review
+
+Contributor's guide::
+    https://github.com/lttng/lttng-tools/blob/master/CONTRIBUTING.md
\ No newline at end of file
index a34e25f21fa5a38ef622724718b52ebb6eb3741a..0a4d726d7d1b32113004ce84bc41f265e5832e9e 100644 (file)
@@ -90,8 +90,9 @@ m4_define([WARN_FLAGS_C_LIST], [ dnl
   -Wdiscarded-qualifiers dnl
   -Wmissing-prototypes dnl
   -Wmissing-parameter-type dnl
-  -Wjump-misses-init dnl
-  -Wnested-externs dnl
+  -Wsuggest-final-types dnl
+  -Wsuggest-final-methods dnl
+  -Wsuggest-override dnl
 ])
 
 # Pass -Werror as an extra flag during the test: this is needed to make the
@@ -156,19 +157,23 @@ AS_IF([test "x$enable_Werror" = "xyes"], [
 AC_PROG_GREP
 AC_PROG_MAKE_SET
 AC_PROG_SED
+AC_PROG_MKDIR_P
 AC_PATH_PROG([report_fold], [fold])
 LT_INIT
 
 # Check for objcopy, required by the base address statedump and dynamic linker tests
-AC_CHECK_TOOL([OBJCOPY], [objcopy], [no])
-AS_IF([test "x$OBJCOPY" = "xno"],
+AC_CHECK_TOOL([OBJCOPY], [objcopy])
+AS_IF([test "x$OBJCOPY" = "x"],
        [AC_MSG_WARN([Cannot find objcopy. The base address statedump and dynamic linker tests will be disabled. Install the binutils package to remediate this.])]
 )
-AM_CONDITIONAL([HAVE_OBJCOPY], [test "x$OBJCOPY" != xno])
+AM_CONDITIONAL([HAVE_OBJCOPY], [test "x$OBJCOPY" != "x"])
 
 # check for pgrep
-AC_PATH_PROG([PGREP], [pgrep], [no])
-AM_CONDITIONAL([HAVE_PGREP], [test "x$PGREP" != "xno"])
+AC_PATH_PROG([PGREP], [pgrep])
+AM_CONDITIONAL([HAVE_PGREP], [test "x$PGREP" != "x"])
+
+AC_PATH_PROG([SHELLCHECK], [shellcheck])
+AM_CONDITIONAL([HAVE_SHELLCHECK], [test "x$SHELLCHECK" != "x"])
 
 # set $IN_GIT_REPO if we're in the Git repository; the `bootstrap` file
 # is not distributed in tarballs
@@ -299,7 +304,7 @@ AC_CHECK_HEADERS([ \
        signal.h stdlib.h sys/un.h sys/socket.h stdlib.h stdio.h \
        getopt.h sys/ipc.h sys/shm.h popt.h grp.h arpa/inet.h \
        netdb.h netinet/in.h paths.h stddef.h sys/file.h sys/ioctl.h \
-       sys/mount.h sys/param.h sys/time.h elf.h
+       sys/mount.h sys/param.h sys/time.h elf.h sys/random.h sys/syscall.h
 ])
 
 AM_CONDITIONAL([HAVE_ELF_H], [test x$ac_cv_header_elf_h = xyes])
@@ -311,7 +316,8 @@ AC_CHECK_FUNCS([ \
        mkdir munmap putenv realpath rmdir socket strchr strcspn strdup \
        strncasecmp strndup strnlen strpbrk strrchr strstr strtol strtoul \
        strtoull dirfd gethostbyname2 getipnodebyname epoll_create1 \
-       sched_getcpu sysconf sync_file_range
+       sched_getcpu sysconf sync_file_range getrandom posix_fadvise \
+       arc4random flock
 ])
 
 # Check for pthread_setname_np and pthread_getname_np
@@ -652,7 +658,7 @@ AM_CONDITIONAL([PYTHON_BINDING], [test "x$enable_python_binding" = xyes])
 if test "x$enable_python_binding" = xyes; then
   AX_PKG_SWIG($swig_version, [], [ AC_MSG_ERROR([SWIG $swig_version or newer is needed]) ])
   AS_IF([test x$enable_shared = xno], [ AC_MSG_ERROR([Python bindings require shared libraries.]) ])
-  AM_PATH_PYTHON([3.0])
+  AM_PATH_PYTHON([3.4])
 
   AC_ARG_VAR([PYTHON_INCLUDE], [Include flags for python, bypassing python-config])
   AC_ARG_VAR([PYTHON_CONFIG], [Path to python-config])
@@ -660,9 +666,9 @@ if test "x$enable_python_binding" = xyes; then
     AS_IF([test -z "$PYTHON_CONFIG"], [
       AC_PATH_PROGS([PYTHON_CONFIG],
                     [python$PYTHON_VERSION-config python-config],
-                    [no],
+                    [],
                     [`dirname $PYTHON`])
-      AS_IF([test "$PYTHON_CONFIG" = no], [AC_MSG_ERROR([cannot find python-config for $PYTHON. Do you have python-dev installed?])])
+      AS_IF([test "x$PYTHON_CONFIG" = "x"], [AC_MSG_ERROR([cannot find python-config for $PYTHON. Do you have python-dev installed?])])
     ])
     AC_MSG_CHECKING([python include flags])
     PYTHON_INCLUDE=`$PYTHON_CONFIG --includes`
@@ -750,6 +756,31 @@ if test "x$test_java_agent_jul" = "xyes" || test "x$test_java_agent_log4j" = "xy
        fi
 fi
 
+# API documentation using Doxygen
+AC_ARG_ENABLE([api-doc], [
+       AS_HELP_STRING([--enable-api-doc], [build HTML API documentation])
+], [api_doc=$enableval], [api_doc=no])
+
+AS_IF([test "x$api_doc" = xyes], [
+       DX_DOXYGEN_FEATURE(ON)
+       DX_DOT_FEATURE(OFF)
+       DX_HTML_FEATURE(ON)
+       DX_CHM_FEATURE(OFF)
+       DX_CHI_FEATURE(OFF)
+       DX_MAN_FEATURE(OFF)
+       DX_RTF_FEATURE(OFF)
+       DX_XML_FEATURE(OFF)
+       DX_PDF_FEATURE(OFF)
+       DX_PS_FEATURE(OFF)
+       DX_INIT_DOXYGEN(["LTTng control library"], [$(builddir)/Doxyfile], [output])
+
+       AS_IF([test -z "$DX_DOXYGEN"], [
+               AC_MSG_ERROR([You need Doxygen to build the liblttng-ctl API documentation])
+       ])
+])
+
+AM_CONDITIONAL([API_DOC], [test "x$api_doc" = xyes])
+
 # enable building man pages (user's intention)
 AC_ARG_ENABLE(
        man-pages,
@@ -766,10 +797,10 @@ have_asciidoc_xmlto=no
 warn_prebuilt_man_pages=no
 
 AS_IF([test "x$man_pages_opt" = "xyes"], [
-       AC_PATH_PROG([ASCIIDOC], [asciidoc], [no])
-       AC_PATH_PROG([XMLTO], [xmlto], [no])
+       AC_PATH_PROG([ASCIIDOC], [asciidoc])
+       AC_PATH_PROG([XMLTO], [xmlto])
 
-       AS_IF([test "x$ASCIIDOC" = "xno" || test "x$XMLTO" = "xno"], [
+       AS_IF([test "x$ASCIIDOC" = "x" || test "x$XMLTO" = "x"], [
                AS_IF([test "x$in_git_repo" = "xyes"], [
                        # this is an error because we're in the Git repo, which
                        # means the man pages are not already generated for us,
@@ -812,8 +843,8 @@ AS_IF([test "x$embedded_help" = "xyes"], [
        AS_IF([test "x$man_pages_opt" = "xno"], [
                AC_MSG_ERROR([You need the --enable-man-pages option with the --enable-embedded-help option.])
        ])
-       AC_PATH_PROG([man_prog_path], [man], [no])
-       AS_IF([test "x$man_prog_path" = "xno"], [
+       AC_PATH_PROG([man_prog_path], [man])
+       AS_IF([test "x$man_prog_path" = "x"], [
                AC_MSG_ERROR([You need man with the --enable-embedded-help option.])
        ])
        AC_DEFINE_UNQUOTED([LTTNG_EMBED_HELP], 1, [Embed --help messages.])
@@ -948,6 +979,9 @@ AS_IF([test "$test_sdt_uprobe" = "autodetect"], [
 
 AM_CONDITIONAL([TEST_SDT_UPROBE], [test "$test_sdt_uprobe" = "yes"])
 
+AC_ARG_ENABLE([lib-lttng-ctl], AS_HELP_STRING([--disable-lib-lttng-ctl],
+       [Disable the build of liblttng-ctl (only possible if no binaries that depend on it are built)]))
+
 # Arguments for binaries build exclusion
 AC_ARG_ENABLE([bin-lttng], AS_HELP_STRING([--disable-bin-lttng],[Disable the build of lttng binaries]))
 AC_ARG_ENABLE([bin-lttng-consumerd], AS_HELP_STRING([--disable-bin-lttng-consumerd],
@@ -1018,11 +1052,23 @@ AS_IF([test x$enable_bin_lttng_sessiond != xno],
 )
 
 # Libraries dependencies enabling
+# If we want to build liblttng-ctl
+AS_IF([test x$enable_lib_lttng_ctl != xno],
+      [
+       build_lib_lttng_ctl=yes
+      ]
+)
+# If we need to build liblttng-ctl because a binary depends on it
 AS_IF([test x$build_lib_lttng_ctl = xyes],
       [
        build_lib_sessiond_comm=yes
       ]
 )
+# Fail if we didn't want to build liblttng-ctl but need to build it anyway
+AS_IF([test "x$build_lib_lttng_ctl" = "xyes" -a "x$enable_lib_lttng_ctl" = "xno"],[
+       AC_MSG_FAILURE(
+               [liblttng-ctl must be built, because at least one binary that depends on it is enabled])
+])
 
 AS_IF([test x$build_lib_consumer = xyes],
       [
@@ -1119,6 +1165,13 @@ test "x$enable_bin_lttng_sessiond" != "xno"],
 )
 
 AM_CONDITIONAL([BUILD_TESTS], [test x$build_tests = xyes])
+
+AS_IF([test "x$build_tests" = "xyes"],
+  [
+    PKG_CHECK_MODULES([babeltrace2], [babeltrace2])
+  ]
+)
+
 AM_CONDITIONAL([BUILD_EXTRAS], [test x$enable_extras != xno])
 
 # Export libraries build conditions.
@@ -1176,6 +1229,9 @@ AC_SUBST(lttnglibexecdir)
 AC_CONFIG_FILES([
        Makefile
        doc/Makefile
+       doc/api/Makefile
+       doc/api/liblttng-ctl/Doxyfile
+       doc/api/liblttng-ctl/Makefile
        doc/examples/Makefile
        doc/examples/rotation/Makefile
        doc/examples/trigger-condition-event-matches/Makefile
@@ -1202,6 +1258,7 @@ AC_CONFIG_FILES([
        src/vendor/msgpack/Makefile
        tests/Makefile
        tests/destructive/Makefile
+       tests/meta/Makefile
        tests/regression/Makefile
        tests/regression/kernel/Makefile
        tests/regression/tools/Makefile
@@ -1234,6 +1291,8 @@ AC_CONFIG_FILES([
        tests/regression/tools/trigger/utils/Makefile
        tests/regression/tools/trigger/name/Makefile
        tests/regression/tools/trigger/hidden/Makefile
+       tests/regression/tools/context/Makefile
+       tests/regression/tools/client/Makefile
        tests/regression/ust/Makefile
        tests/regression/ust/nprocesses/Makefile
        tests/regression/ust/high-throughput/Makefile
@@ -1261,17 +1320,24 @@ AC_CONFIG_FILES([
        tests/regression/ust/rotation-destroy-flush/Makefile
        tests/regression/ust/blocking/Makefile
        tests/regression/ust/namespaces/Makefile
+       tests/regression/ust/ust-constructor/Makefile
        tests/stress/Makefile
        tests/unit/Makefile
        tests/unit/ini_config/Makefile
        tests/perf/Makefile
        tests/utils/Makefile
+       tests/utils/bt2_plugins/Makefile
+       tests/utils/bt2_plugins/event_name/Makefile
+       tests/utils/bt2_plugins/field_stats/Makefile
+       tests/utils/lttngtest/Makefile
        tests/utils/tap/Makefile
        tests/utils/testapp/Makefile
+       tests/utils/testapp/gen-data-pending/Makefile
        tests/utils/testapp/gen-ns-events/Makefile
        tests/utils/testapp/gen-kernel-test-events/Makefile
        tests/utils/testapp/gen-py-events/Makefile
        tests/utils/testapp/gen-ust-events/Makefile
+       tests/utils/testapp/gen-ust-events-constructor/Makefile
        tests/utils/testapp/gen-ust-events-ns/Makefile
        tests/utils/testapp/gen-syscall-events-callstack/Makefile
        tests/utils/testapp/gen-ust-nevents/Makefile
@@ -1289,6 +1355,7 @@ AC_CONFIG_FILES([tests/regression/ust/python-logging/test_python_logging],[chmod
 # Inject LTTNG_TOOLS_BUILD_WITH_LIBPFM variable in test script.
 AC_CONFIG_FILES([tests/perf/test_perf_raw],[chmod +x tests/perf/test_perf_raw])
 AC_CONFIG_FILES([tests/regression/ust/ust-dl/test_ust-dl],[chmod +x tests/regression/ust/ust-dl/test_ust-dl])
+AC_CONFIG_FILES([pre-inst-env],[chmod +x pre-inst-env])
 
 AC_OUTPUT
 
@@ -1334,6 +1401,13 @@ PPRINT_PROP_BOOL([libkmod support], $value)
 test "x$with_lttng_ust" = "xyes" && value=1 || value=0
 PPRINT_PROP_BOOL([LTTng-UST support], $value)
 
+AS_ECHO
+PPRINT_SUBTITLE([Libraries])
+
+# liblttng-ctl enabled/disabled
+test x$build_lib_lttng_ctl != xno && value=1 || value=0
+PPRINT_PROP_BOOL([liblttng-ctl], $value)
+
 AS_ECHO
 PPRINT_SUBTITLE([Binaries])
 
@@ -1420,6 +1494,9 @@ m4_popdef([build_man_pages_msg])
 test "x$embedded_help" = xyes && value=1 || value=0
 PPRINT_PROP_BOOL([Embed --help messages], $value, $PPRINT_COLOR_SUBTITLE)
 
+test "x$api_doc" = xyes && value=1 || value=0
+PPRINT_PROP_BOOL([liblttng-ctl HTML API documentation], $value, $PPRINT_COLOR_SUBTITLE)
+
 PPRINT_SET_INDENT(1)
 
 report_bindir="`eval eval echo $bindir`"
index 121db3b89c32dad14cb55b00f73abc5a7ff5387a..61d9be6bec623f5ec9e2248f0868a96fdbfecebd 100644 (file)
@@ -15,3 +15,7 @@ EXTRA_DIST = quickstart.txt streaming-howto.txt python-howto.txt \
 dist_doc_DATA = quickstart.txt streaming-howto.txt python-howto.txt \
        snapshot-howto.txt live-reading-howto.txt \
        live-reading-protocol.txt valgrind-howto.txt
+
+if API_DOC
+SUBDIRS += api
+endif
diff --git a/doc/api/.gitignore b/doc/api/.gitignore
new file mode 100644 (file)
index 0000000..fa4a410
--- /dev/null
@@ -0,0 +1,3 @@
+output/
+Doxyfile
+README.html
diff --git a/doc/api/Makefile.am b/doc/api/Makefile.am
new file mode 100644 (file)
index 0000000..b5e85ac
--- /dev/null
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+SUBDIRS = liblttng-ctl
+EXTRA_DIST = README.adoc
diff --git a/doc/api/README.adoc b/doc/api/README.adoc
new file mode 100644 (file)
index 0000000..d62782b
--- /dev/null
@@ -0,0 +1,390 @@
+// Render with Asciidoctor
+
+= LTTng-tools C API documentation guidelines
+Philippe Proulx <pproulx@efficios.com>
+25 August 2021
+:toc: left
+
+This document explains how to write documentation for the LTTng-tools
+C{nbsp}API.
+
+== General rules
+
+* Use four spaces to indent Doxygen text and two spaces to indent HTML.
+
+* Try to stay behind the 72^th^ column mark when possible.
+
+* Use https://en.wikipedia.org/wiki/Non-breaking_space[`+&nbsp;+`]
+  wherever needed.
+
+* Refer to a function with the `func()` form and to an
+  enumerator/structure/variable or type with the `#name` syntax.
++
+You don't need any `struct`/`enum` prefix with Doxygen.
+
+* When you refer to any keyword or definition, use the `+\c+` command if
+  it's a single word, otherwise surround the words with `<code>` and
+  `</code>`:
++
+--
+----
+@returns
+    Event rule on success, or \c NULL on error.
+----
+--
+
+* Use the `$$\$$__command__` style in text (paragraphs, list items,
+  definition terms, and the rest) and the `@__command__` style for
+  other locations (for example, `@brief`, `@param`, `@sa`, `@file`).
+
+* Use a `@code{.unparsed}` block for a plain text block (shell input,
+  for example):
++
+----
+@code{.unparsed}
+$ lttng enable-event --all --kernel --syscall
+@endcode
+----
+
+* In the text, use custom aliases when applicable.
++
+See `Doxyfile.in` for the list of available aliases.
+
+== Function documentation
+
+Full example:
+
+----
+/*!
+@brief
+    Does something (third person singular, simple present) with some
+    parameter \lt_p{param} unless some other parameter
+    \lt_p{other_param} has some value.
+
+Full documentation goes here and adds any relevant information that's
+not in the brief description.
+
+@code
+/* If needed, put any C code in a code block. */
+@endcode
+
+Crucifix scenester vegan organic neutra palo santo glossier occupy
+truffaut. Meh fixie taiyaki single-origin coffee wayfarers. Thundercats
+farm-to-table shoreditch vinyl.
+
+@remarks
+    This is where you would put some remarks. Occupy flexitarian neutra,
+    edison bulb bespoke sriracha post-ironic. Mlkshk plaid pop-up
+    polaroid chillwave, ennui neutra.
+
+See this image:
+
+@image html mein-illustration.png "Caption goes here."
+
+@note
+    @parblock
+    This is a multiparagraph note.
+
+    Tote bag sartorial distillery, try-hard succulents wayfarers DIY
+    YOLO four loko jianbing farm-to-table unicorn vice.
+
+    Mumblecore semiotics raw denim palo santo chartreuse helvetica
+    shabby chic, distillery pabst poke swag copper mug blue bottle.
+    @endpar
+
+@attention
+    Use an attention command if this message is really important.
+
+@attention
+    @parblock
+    An attention block with more than one paragraph:
+
+    @code
+    some_code(23)
+    @endcode
+
+    Elit dolore pariatur ex anim officia cupidatat adipisicing mollit
+    incididunt irure anim nostrud.
+    @endparblock
+
+@param[in] param
+    Description of this parameter.
+@param[in] other_param
+    @parblock
+    Description of this other parameter. Nulla consequat tempus libero,
+    sed finibus velit.
+
+    Offal actually vinyl taiyaki kickstarter etsy.
+    @endparblock
+@param[out] out_param
+    <strong>On success</strong>, \lt_p{*out_param} contains to something
+    useful.
+
+@retval #LTTNG_SOME_STATUS_OK
+    Success.
+@retval #LTTNG_SOME_STATUS_MEMORY_ERROR
+    Out of memory.
+@retval #LTTNG_SOME_STATUS_ERROR
+    @parblock
+    Longer description for this specific status.
+
+    Organic locavore sartorial 3 wolf moon brooklyn, VHS pug distillery
+    schlitz tofu banjo chambray you probably haven't heard of them hot
+    chicken copper mug.
+
+    Neutra kale chips kombucha, salvia green juice live-edge swag
+    biodiesel scenester austin yuccie dreamcatcher cronut small batch.
+    @endparblock
+
+@lt_pre_not_null{param}
+@lt_pre_not_null{other_param}
+@pre
+    \lt_p{param} is like this or like that.
+
+@post
+    \lt_p{other_param} is still in some state, and woke jean waistcoat.
+
+@sa lttng_some_other_function() --
+    Does something else with some parameter.
+@sa lttng_another_function() --
+    Cardigan celiac palo santo, tacos chicharrones pitchfork chambray
+    photo booth subway tile 90's street.
+*/
+----
+
+Parts:
+
+. **Opening Doxygen comment**.
++
+Use `+/*!+`.
+
+. **Brief description**.
++
+Use third person singular in the simple present tense: you're
+documenting what the function does. Assume that the sentence implicitly
+starts with "`This function`".
++
+Try to mention, briefly, all the parameters (with `\lt_p`) and what the
+function returns.
++
+End the sentence with a period.
+
+. **Detailed description**.
++
+Write complete sentences.
++
+Refer to parameters (with `\lt_p`) as much as possible.
++
+In general, keep paragraphs short: often, a single sentence is enough.
++
+Refer to the documented function with "`this function`".
++
+Write notes (`@note` command), remarks (`@remark` command), or
+attentions (`@attention` command) when needed. Most notes and remarks,
+however, can be simple paragraphs. Use `@parblock` end `@endparblock` to
+have more than one note/remark/warning paragraph.
+
+. **Parameter descriptions** (if any).
++
+Use the `@param[in]`, `@param[out]`, and `@param[in,out]` commands
+depending on the parameter direction.
++
+Document parameters in the declaration order.
++
+Refer to other parameters (with `\lt_p`) when useful for the reader.
++
+End each description with a period.
++
+Use `@parblock` end `@endparblock` to have more than one paragraph for a
+given parameter description.
++
+Make sure there's no blank line, except within a `@parblock` block,
+within the parameter description block so that Doxygen puts all the
+descriptions in the same section. For example, _don't_ write this:
++
+----
+@param[in] hexagon
+    Ugh literally +1 aesthetic, fashion axe try-hard mixtape pork belly
+    four loko.
+
+@param[in] selfies
+    Brooklyn ethical migas, viral edison bulb meggings butcher
+    flexitarian letterpress humblebrag kombucha pour-over etsy sriracha
+    blog.
+----
+
+. **Return value** (if any).
++
+If the function returns a status code::
+    Use the `@retval` command multiple times to document each relevant
+    status:
++
+----
+@retval #LTTNG_SOME_STATUS_OK
+    Success.
+@retval #LTTNG_SOME_STATUS_SOME_ERROR
+    Some error.
+----
++
+End each description with a period.
++
+Use `@parblock` and `@endparblock` to have more than one paragraph for a
+given return value description.
++
+Make sure there's no blank line, except within a `@parblock` block,
+within the return value description block so that Doxygen puts all the
+descriptions in the same section. For example, _don't_ write this:
++
+----
+@retval #LTTNG_SOME_STATUS_OK
+    Success.
+
+@retval #LTTNG_SOME_STATUS_SOME_ERROR
+    Some error.
+----
+
+If the function returns a simple value::
+    Use the `@returns` command to document it.
++
+Refer to parameters (with `\lt_p`) when useful for the reader.
++
+End the description with a period.
+
+. **Preconditions** (if any).
++
+List all the function's preconditions with the `@pre` command or any
+alias which starts with `@lt_pre` (see `Doxyfile.in`).
++
+Use the simple present tense.
++
+Do not write the word "`must`" as a precondition is already a
+requirement.
++
+End the description with a period.
++
+Make sure there's no blank line within the precondition description
+block so that Doxygen puts all the descriptions in the same section. For
+example, _don't_ write this:
++
+----
+@lt_pre_not_null{param}
+
+@pre
+    \lt_p{param} is like this or like that.
+----
+
+. **Postconditions** (if any).
++
+List all the function's _relevant_ postconditions with the `@post`
+command or any alias which starts with `@lt_post` (see `Doxyfile.in`).
++
+Anything that the body of the function documentation describes and which
+forms the nature of the function doesn't need to be written as an
+explicit postcondition. For example, if a function adds some
+object{nbsp}A to some object{nbsp}B, don't write the postcondition
+"`B{nbsp}contains{nbsp}A`".
++
+Use the simple present tense.
++
+End the description with a period.
++
+Make sure there's no blank line within the postcondition description
+block so that Doxygen puts all the descriptions in the same section. For
+example, _don't_ write this:
++
+----
+@post
+    The returned pointer is blue.
+
+@post
+    \lt_p{other_param} is still in some state, and woke jean waistcoat.
+----
+
+. **Items to see also** (if any).
++
+Use the `@sa` command, multiple times if needed, to refer to related
+functions or types.
++
+This is a way for you to inform the reader about other existing, related
+items. Keep in mind that the reader doesn't always know where to look
+for things.
++
+In the brief description of the referred item, _don't_ mention its
+parameters, if any.
++
+End each brief description with a period.
++
+Make sure there's no blank line within the item description block so
+that Doxygen puts all the descriptions in the same section. For example,
+_don't_ write this:
++
+----
+@sa lttng_some_other_function() --
+    Does something else with a parameter.
+
+@sa lttng_another_function() --
+    Cardigan celiac palo santo, tacos chicharrones pitchfork chambray
+    photo booth subway tile 90's street.
+----
+
+
+== Writing style
+
+The ultimate goal of the LTTng-tools C{nbsp}API documentation is to make
+the layman write code using this API as fast and correct as possible
+without having to ask for help. For this purpose, the documentation must
+be as clear as possible, just like the function and type names try to
+be.
+
+Don't hesitate to repeat technical terms, even in the same sentence, if
+needed. For example, if you document an "`event rule`", then always use
+the term "`event rule`" in the documentation, not "`event`", nor
+"`rule`", since they are ambiguous.
+
+You can use light emphasis to show the importance of a part of the text
+with the `\em` command (one word) or by surrounding the text to
+emphasize with `<em>` and `</em>`. Likewise, you can use strong emphasis
+when needed with the `\b` command (one word) or with `<strong>` and
+`</strong>`. In general, prefer light emphasis to strong emphasis, and
+use it economically.
+
+Links to other parts of the documentation are very important. Consider
+that the reader never knows that other functions exist other than the
+one she's reading. Use as many internal links as possible. Use the
+following forms of links:
+
+`__func__()`::
+    Automatic link to the function or macro named `__func__`.
+
+`#__name__`::
+    Automatic link to the type or enumerator named `__name__`.
+
+`\ref __ref__`::
+    Link to `__ref__` (page name, group name, function or macro name,
+    type name, variable name, etc.) using its default text.
+
+`\ref __ref__ "__some text__"`::
+    Link to `__ref__` (page name, group name, function or macro name,
+    type name, variable name, etc.) using the text `__some text__`.
+
+See Doxygen's "`http://www.doxygen.nl/manual/autolink.html[Automatic
+link generation]`" page for other ways to create automatic links.
+
+Follow, as much as possible, the
+https://docs.microsoft.com/en-ca/style-guide/welcome/[Microsoft Style
+Guide] when you document the API. This includes:
+
+* Use an active voice.
+* Use a gender-neutral language.
+* Use the present tense (you almost never need the future tense).
+* Address your reader directly (use "`you`").
+* Use contractions ("`it's`", "`you're`", "`don't`", and the rest).
+* Avoid anthropomorphism.
+* Ensure parallelism in lists, procedures, and sentences.
+* Terminate list items with a period, except when the list only contains
+  very short items.
+* Do not use Latin abbreviations.
+* Use "`and`" or "`or`" instead of a slash.
+* Avoid using negatives.
+* Avoid using "`should`": most of the time, you mean "`must`", and
+  that's very clear for the reader.
diff --git a/doc/api/liblttng-ctl/Doxyfile.in b/doc/api/liblttng-ctl/Doxyfile.in
new file mode 100644 (file)
index 0000000..4e78ae7
--- /dev/null
@@ -0,0 +1,218 @@
+DOXYFILE_ENCODING       = UTF-8
+PROJECT_NAME            = "LTTng control library C API"
+PROJECT_NUMBER          = @PACKAGE_VERSION@
+CREATE_SUBDIRS          = NO
+ALLOW_UNICODE_NAMES     = NO
+OUTPUT_LANGUAGE         = English
+BRIEF_MEMBER_DESC       = YES
+REPEAT_BRIEF            = YES
+ALWAYS_DETAILED_SEC     = NO
+INLINE_INHERITED_MEMB   = NO
+FULL_PATH_NAMES         = YES
+STRIP_FROM_PATH         = "@top_srcdir@/include"
+STRIP_FROM_INC_PATH     =
+SHORT_NAMES             = NO
+JAVADOC_AUTOBRIEF       = NO
+QT_AUTOBRIEF            = NO
+MULTILINE_CPP_IS_BRIEF  = YES
+INHERIT_DOCS            = YES
+SEPARATE_MEMBER_PAGES   = NO
+TAB_SIZE                = 4
+ALIASES                 =
+
+# Aliases: general
+ALIASES                += lt_version="@PACKAGE_VERSION@"
+ALIASES                += lt_version_maj_min="@MAJOR_VERSION@.@MINOR_VERSION@"
+ALIASES                += lt_api="LTTng control library&nbsp;C&nbsp;API"
+ALIASES                += lt_p{1}="<code class=\"lt-param\">\1</code>"
+ALIASES                += lt_var{1}="<strong class=\"lt-var\">\1</strong>"
+ALIASES                += lt_dt_opt="<strong><em>Optional</em></strong>:"
+ALIASES                += lt_man_nl{2}="<code><strong>\1</strong>(\2)</code>"
+ALIASES                += lt_man{2}="<a href=\"https://lttng.org/man/\2/\1/v\lt_version_maj_min/\">\lt_man_nl{\1,\2}</a>"
+ALIASES                += lt_man_gen{2}="<a href=\"https://man7.org/linux/man-pages/man\2/\1.\2.html\">\lt_man_nl{\1,\2}</a>"
+ALIASES                += lt_voidp="<code>void&nbsp;*</code>"
+
+# Aliases: preconditions
+ALIASES                += lt_pre_not_null{1}="@pre \lt_p{\1} is \em not \c NULL."
+ALIASES                += lt_pre_valid_c_str{1}="@pre \lt_p{\1} is a valid (null-terminated) C&nbsp;string."
+ALIASES                += lt_pre_sess_exists{1}="@pre \lt_p{\1} names an accessible \ref api_session \"recording session\" within the \ref api-gen-sessiond-conn \"connected session daemon\"."
+ALIASES                += lt_pre_sess_never_active{1}="@pre \lt_p{\1} names a \ref api_session \"recording session\" which never became \link lttng_session::enabled active\endlink (started) since its creation."
+ALIASES                += lt_pre_sess_active{1}="@pre \lt_p{\1} names an \link lttng_session::enabled active\endlink (started) \ref api_session \"recording session\"."
+ALIASES                += lt_pre_sess_inactive{1}="@pre \lt_p{\1} names an \link lttng_session::enabled inactive\endlink (stopped) \ref api_session \"recording session\"."
+ALIASES                += lt_pre_sess_name_not_auto{1}="@pre \lt_p{\1} is not \c auto."
+ALIASES                += lt_pre_conn="@pre liblttng-ctl can \ref api-gen-sessiond-conn \"connect to a session daemon\"."
+ALIASES                += lt_pre_has_type{2}="@pre \lt_p{\1} has the type #\2."
+
+# Aliases: default values
+ALIASES                += lt_def_net_ctrl_port="@DEFAULT_NETWORK_CONTROL_PORT@"
+ALIASES                += lt_def_net_data_port="@DEFAULT_NETWORK_DATA_PORT@"
+ALIASES                += lt_def_net_ctrl_url="<code>net://127.0.0.1:@DEFAULT_NETWORK_CONTROL_PORT@</code>"
+ALIASES                += lt_def_net_data_url="<code>net://127.0.0.1:@DEFAULT_NETWORK_DATA_PORT@</code>"
+ALIASES                += lt_def_net_url="<code>net://127.0.0.1:@DEFAULT_NETWORK_CONTROL_PORT@:@DEFAULT_NETWORK_DATA_PORT@</code>"
+
+# Aliases: object names
+ALIASES                += lt_obj_session="\ref api_session \"recording session\""
+ALIASES                += lt_obj_c_session="\ref api_session \"Recording session\""
+ALIASES                += lt_obj_session_descr="\ref api_session_descr \"recording session descriptor\""
+ALIASES                += lt_obj_c_session_descr="\ref api_session_descr \"Recording session descriptor\""
+ALIASES                += lt_obj_domain="\ref api-channel-domain \"tracing domain\""
+ALIASES                += lt_obj_domains="\ref api-channel-domain \"tracing domains\""
+ALIASES                += lt_obj_c_domain="\ref api-channel-domain \"Tracing domain\""
+ALIASES                += lt_obj_channel="\ref api-channel-channel \"channel\""
+ALIASES                += lt_obj_channels="\ref api-channel-channel \"channels\""
+ALIASES                += lt_obj_c_channel="\ref api-channel-channel \"Channel\""
+ALIASES                += lt_obj_rer="\ref api_rer \"recording event rule\""
+ALIASES                += lt_obj_rers="\ref api_rer \"recording event rules\""
+ALIASES                += lt_obj_c_rer="\ref api_rer \"Recording event rule\""
+ALIASES                += lt_obj_trigger="\ref api_trigger \"trigger\""
+ALIASES                += lt_obj_triggers="\ref api_trigger \"triggers\""
+ALIASES                += lt_obj_c_trigger="\ref api_trigger \"Trigger\""
+
+
+OPTIMIZE_OUTPUT_FOR_C   = YES
+MARKDOWN_SUPPORT        = NO
+TOC_INCLUDE_HEADINGS    = 0
+AUTOLINK_SUPPORT        = YES
+SUBGROUPING             = YES
+INLINE_GROUPED_CLASSES  = NO
+INLINE_SIMPLE_STRUCTS   = NO
+TYPEDEF_HIDES_STRUCT    = NO
+LOOKUP_CACHE_SIZE       = 0
+
+EXTRACT_ALL             = NO
+EXTRACT_PRIVATE         = NO
+EXTRACT_PACKAGE         = NO
+EXTRACT_STATIC          = YES
+EXTRACT_LOCAL_CLASSES   = YES
+EXTRACT_LOCAL_METHODS   = NO
+EXTRACT_ANON_NSPACES    = NO
+HIDE_UNDOC_MEMBERS      = YES
+HIDE_UNDOC_CLASSES      = YES
+HIDE_FRIEND_COMPOUNDS   = NO
+HIDE_IN_BODY_DOCS       = YES
+INTERNAL_DOCS           = NO
+CASE_SENSE_NAMES        = NO
+HIDE_SCOPE_NAMES        = NO
+HIDE_COMPOUND_REFERENCE = NO
+SHOW_INCLUDE_FILES      = NO
+SHOW_GROUPED_MEMB_INC   = NO
+FORCE_LOCAL_INCLUDES    = NO
+INLINE_INFO             = YES
+SORT_MEMBER_DOCS        = YES
+SORT_BRIEF_DOCS         = YES
+SORT_MEMBERS_CTORS_1ST  = NO
+SORT_GROUP_NAMES        = NO
+SORT_BY_SCOPE_NAME      = NO
+STRICT_PROTO_MATCHING   = NO
+GENERATE_TODOLIST       = YES
+GENERATE_TESTLIST       = YES
+GENERATE_BUGLIST        = YES
+GENERATE_DEPRECATEDLIST = YES
+ENABLED_SECTIONS        =
+MAX_INITIALIZER_LINES   = 0
+SHOW_USED_FILES         = NO
+SHOW_FILES              = NO
+SHOW_NAMESPACES         = NO
+FILE_VERSION_FILTER     =
+LAYOUT_FILE             = "@srcdir@/DoxygenLayout.xml"
+CITE_BIB_FILES          =
+
+QUIET                   = NO
+WARNINGS                = YES
+WARN_IF_UNDOCUMENTED    = YES
+WARN_IF_DOC_ERROR       = YES
+WARN_NO_PARAMDOC        = YES
+WARN_AS_ERROR           = NO
+WARN_FORMAT             = "$file:$line: $text"
+WARN_LOGFILE            =
+
+INPUT                   = "@srcdir@/dox/groups.dox" \
+                          "@top_srcdir@/include/lttng/constant.h" \
+                          "@top_srcdir@/include/lttng/handle.h" \
+                          "@top_srcdir@/include/lttng/lttng.h" \
+                          "@top_srcdir@/include/lttng/lttng-error.h" \
+                          "@top_srcdir@/include/lttng/clear.h" \
+                          "@top_srcdir@/include/lttng/clear-handle.h" \
+                          "@top_srcdir@/include/lttng/session.h" \
+                          "@top_srcdir@/include/lttng/session-descriptor.h" \
+                          "@top_srcdir@/include/lttng/destruction-handle.h" \
+                          "@top_srcdir@/include/lttng/domain.h" \
+                          "@top_srcdir@/include/lttng/channel.h" \
+                          "@top_srcdir@/include/lttng/event.h"
+INPUT_ENCODING          = UTF-8
+FILE_PATTERNS           = *.h *.dox
+RECURSIVE               = NO
+EXCLUDE                 =
+EXCLUDE_SYMLINKS        = NO
+EXCLUDE_PATTERNS        =
+EXCLUDE_SYMBOLS         =
+EXAMPLE_PATTERNS        = *
+EXAMPLE_RECURSIVE       = NO
+IMAGE_PATH              = "@srcdir@/images"
+INPUT_FILTER            =
+FILTER_PATTERNS         =
+FILTER_SOURCE_FILES     = NO
+FILTER_SOURCE_PATTERNS  =
+USE_MDFILE_AS_MAINPAGE  =
+
+SOURCE_BROWSER          = NO
+INLINE_SOURCES          = NO
+STRIP_CODE_COMMENTS     = YES
+REFERENCED_BY_RELATION  = NO
+REFERENCES_RELATION     = NO
+REFERENCES_LINK_SOURCE  = NO
+SOURCE_TOOLTIPS         = YES
+USE_HTAGS               = NO
+VERBATIM_HEADERS        = YES
+
+ALPHABETICAL_INDEX      = YES
+IGNORE_PREFIX           =
+
+OUTPUT_DIRECTORY        = @builddir@/output
+
+GENERATE_HTML           = YES
+HTML_FILE_EXTENSION     = .html
+HTML_HEADER             =
+HTML_FOOTER             =
+HTML_STYLESHEET         =
+HTML_EXTRA_STYLESHEET   = @srcdir@/style.css
+HTML_EXTRA_FILES        =
+HTML_COLORSTYLE_HUE     = 220
+HTML_COLORSTYLE_SAT     = 100
+HTML_COLORSTYLE_GAMMA   = 120
+HTML_TIMESTAMP          = NO
+HTML_DYNAMIC_SECTIONS   = NO
+HTML_DYNAMIC_MENUS      = NO
+HTML_INDEX_NUM_ENTRIES  = 100
+
+GENERATE_DOCSET         = NO
+GENERATE_HTMLHELP       = NO
+GENERATE_CHI            = NO
+GENERATE_QHP            = NO
+GENERATE_ECLIPSEHELP    = NO
+
+DISABLE_INDEX           = NO
+GENERATE_TREEVIEW       = YES
+ENUM_VALUES_PER_LINE    = 4
+TREEVIEW_WIDTH          = 300
+EXT_LINKS_IN_WINDOW     = NO
+FORMULA_FONTSIZE        = 10
+FORMULA_TRANSPARENT     = YES
+USE_MATHJAX             = NO
+MATHJAX_FORMAT          = HTML-CSS
+MATHJAX_RELPATH         = http://cdn.mathjax.org/mathjax/latest
+MATHJAX_EXTENSIONS      =
+MATHJAX_CODEFILE        =
+SEARCHENGINE            = YES
+SERVER_BASED_SEARCH     = NO
+EXTERNAL_SEARCH         = NO
+SEARCHENGINE_URL        =
+SEARCHDATA_FILE         = searchdata.xml
+EXTERNAL_SEARCH_ID      =
+EXTRA_SEARCH_MAPPINGS   =
+
+GENERATE_LATEX          = NO
+GENERATE_RTF            = NO
+GENERATE_MAN            = NO
+GENERATE_XML            = NO
+GENERATE_PERLMOD        = NO
diff --git a/doc/api/liblttng-ctl/DoxygenLayout.xml b/doc/api/liblttng-ctl/DoxygenLayout.xml
new file mode 100644 (file)
index 0000000..6f37926
--- /dev/null
@@ -0,0 +1,46 @@
+<doxygenlayout version="1.0">
+  <navindex>
+    <tab type="mainpage" visible="yes" title="Bonjour!"/>
+    <tab type="pages" visible="yes" title="All pages" intro=""/>
+    <tab type="modules" visible="yes" title="API reference"
+      intro="List of all API reference modules:"/>
+    <tab type="classlist" visible="yes" title="Structures"/>
+  </navindex>
+
+  <group>
+    <detaileddescription/>
+    <briefdescription visible="no"/>
+    <memberdecl>
+      <nestedgroups visible="yes" title=""/>
+      <classes visible="yes" title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <enumvalues title=""/>
+      <defines title=""/>
+      <variables title=""/>
+      <functions title=""/>
+      <membergroups visible="yes"/>
+    </memberdecl>
+    <memberdef>
+      <pagedocs/>
+      <classes visible="yes" title=""/>
+      <typedefs title=""/>
+      <enums title=""/>
+      <enumvalues title=""/>
+      <defines title=""/>
+      <variables title=""/>
+      <functions title=""/>
+    </memberdef>
+    <authorsection visible="yes"/>
+  </group>
+
+  <directory>
+    <detaileddescription title=""/>
+    <briefdescription visible="no"/>
+    <directorygraph visible="yes"/>
+    <memberdecl>
+      <dirs visible="yes"/>
+      <files visible="yes"/>
+    </memberdecl>
+  </directory>
+</doxygenlayout>
diff --git a/doc/api/liblttng-ctl/Makefile.am b/doc/api/liblttng-ctl/Makefile.am
new file mode 100644 (file)
index 0000000..4450a45
--- /dev/null
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+API_DOC_INSTALL_DIR = "$(DESTDIR)$(docdir)/api/liblttng-ctl"
+
+all-local: doxygen-doc
+
+install-data-local: doxygen-doc
+       $(mkdir_p) "$(API_DOC_INSTALL_DIR)"
+       cp -rv output/html "$(API_DOC_INSTALL_DIR)"
+
+@DX_RULES@
+
+MOSTLYCLEANFILES = $(DX_CLEANFILES)
+EXTRA_DIST = \
+       Doxyfile.in \
+       DoxygenLayout.xml \
+       style.css \
+       dox \
+       images
diff --git a/doc/api/liblttng-ctl/dox/groups.dox b/doc/api/liblttng-ctl/dox/groups.dox
new file mode 100644 (file)
index 0000000..f10de45
--- /dev/null
@@ -0,0 +1,2353 @@
+/*!
+@mainpage Bonjour!
+
+Welcome to the <strong>\lt_api</strong> (liblttng-ctl) documentation!
+
+The
+<a href="https://lttng.org/"><em>Linux Trace Toolkit: next generation</em></a>
+is an open-source software package used for correlated tracing of the
+Linux kernel, user applications, and user libraries.
+
+liblttng-ctl, which is part of the LTTng-tools project, makes it
+possible to control <a href="https://lttng.org/">LTTng</a> tracing, but
+also to
+\ref api_trigger "receive notifications when specific events occur".
+
+<h2>Plumbing</h2>
+
+The following diagram shows the components of LTTng:
+
+@image html plumbing.png "Components of LTTng."
+
+As you can see, liblttng-ctl is a bridge between a user application
+and a session daemon (see \lt_man{lttng-sessiond,8} and
+\ref api-gen-sessiond-conn "Session daemon connection").
+
+The \lt_man{lttng,1} command-line tool which ships with LTTng-tools, for
+example, uses liblttng-ctl to perform its commands.
+
+See the
+<a href="https://lttng.org/docs/v\lt_version_maj_min/#doc-plumbing"><em>Components of LTTng</em></a>
+section of the LTTng Documentation to learn more.
+
+<h2>Contents</h2>
+
+This API documentation has three main modules:
+
+- The \ref api_session makes it possible to create, manipulate
+  (\ref api_session_snapshot "take a snapshot",
+  \ref api_session_rotation "rotate",
+  \ref api_session_clear "clear", and the rest), and destroy
+  <em>recording sessions</em>.
+
+  A recording session is a per-Unix user dialogue for everything related
+  to event recording.
+
+  A recording session owns \lt_obj_channels which
+  own \lt_obj_rers. Those objects constitute
+  the main configuration of a recording session.
+
+- The \ref api_inst_pt makes it possible to get details about the
+  available LTTng tracepoints, Java/Python loggers, and Linux kernel
+  system calls without needing any \lt_obj_session.
+
+- The \ref api_trigger makes it possible to create and register
+  <em>triggers</em>.
+
+  A trigger associates a condition to one or more actions: when the
+  condition of a trigger is satisfied, LTTng attempts to execute its
+  actions.
+
+  This API is fully decoupled from the \ref api_session.
+
+  Amongst the interesting available trigger conditions and actions
+  are the
+  \link #LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES <em>event rule matches</em>\endlink
+  condition and the
+  \link #LTTNG_ACTION_TYPE_NOTIFY <em>notify</em>\endlink
+  action. With those, your application can receive an asynchronous
+  message (a notification) when a specified event rule matches
+  an LTTng event.
+
+The three modules above often refer to the \ref api_gen which offers
+common enumerations, macros, and functions.
+
+See <a href="modules.html">API reference</a> for the complete table
+of contents.
+
+<h2>Build with liblttng-ctl</h2>
+
+To build an application with liblttng-ctl:
+
+<dl>
+  <dt>Header file
+  <dd>
+    Include <code>%lttng/lttng.h</code>:
+
+    @code
+    #include <lttng/lttng.h>
+    @endcode
+
+    With
+    <a href="https://www.freedesktop.org/wiki/Software/pkg-config/">pkg-config</a>,
+    get the required C&nbsp;flags with:
+
+    @code{.unparsed}
+    $ pkg-config --cflags lttng-ctl
+    @endcode
+
+  <dt>Linking
+  <dd>
+    Link your application with <code>liblttng-ctl</code>:
+
+    @code{.unparsed}
+    $ cc my-app.o ... -llttng-ctl
+    @endcode
+
+    With pkg-config, get the required linker options with:
+
+    @code{.unparsed}
+    $ pkg-config --libs lttng-ctl
+    @endcode
+</dl>
+
+@defgroup api_gen General API
+
+The general \lt_api offers:
+
+- \ref lttng_error_code "Error code enumerators" and lttng_strerror().
+
+- \ref api-gen-sessiond-conn "Session daemon connection" functions:
+
+  - lttng_session_daemon_alive()
+  - lttng_set_tracing_group()
+
+<h1>\anchor api-gen-sessiond-conn Session daemon connection</h1>
+
+Many functions of the \lt_api require a connection to a listening LTTng
+session daemon (see \lt_man{lttng-sessiond,8}) to control LTTng tracing.
+
+liblttng-ctl connects to a session daemon through a Unix domain socket
+when you call some of its public functions, \em not when it loads.
+
+Each Unix user may have its own independent running session daemon.
+However, liblttng-ctl must connect to the session daemon of the
+\c root user (the root session daemon) to control Linux kernel tracing.
+
+How liblttng-ctl chooses which session daemon to connect to is as
+follows, considering \lt_var{U} is the Unix user of the process running
+liblttng-ctl:
+
+<dl>
+  <dt>\lt_var{U} is \c root
+  <dd>Connect to the root session daemon.
+
+  <dt>\lt_var{U} is not \c root
+  <dd>
+    <dl>
+      <dt>If \lt_var{U} is part of the current liblttng-ctl Unix <em>tracing group</em>
+      <dd>
+        Try to connect to the root session daemon.
+
+        If the root session daemon isn't running, connect to the
+        session daemon of \lt_var{U}.
+
+      <dt>If \lt_var{U} is not part of the tracing group
+      <dd>
+        Connect to the session daemon of \lt_var{U}.
+    </dl>
+</dl>
+
+The Unix tracing group of the root session daemon is one of:
+
+<dl>
+  <dt>
+    With the <code>\--group=<em>GROUP</em></code> option of the root
+    session daemon
+  <dd>
+    Exactly <code><em>GROUP</em></code>.
+
+    In that case, you must call lttng_set_tracing_group(), passing
+    exactly <code><em>GROUP</em></code>, \em before you call a
+    liblttng-ctl function which needs to connect to a session daemon.
+
+  <dt>
+    Without the <code>\--group</code> option of the root
+    session daemon
+  <dd>
+    Exactly \c tracing (also the default Unix tracing group of
+    liblttng-ctl, therefore you don't need to call
+    lttng_set_tracing_group()).
+</dl>
+
+Check that your application can successfully connect to a session daemon
+with lttng_session_daemon_alive().
+
+LTTng-instrumented user applications automatically register to both the
+root and user session daemons. This makes it possible for both session
+daemons to list the available instrumented applications and their
+\ref api_inst_pt "instrumentation points".
+
+@defgroup api_session Recording session API
+
+A <strong><em>recording session</em></strong> is a stateful dialogue
+between an application and a session daemon for everything related to
+event recording.
+
+Everything that you do when you control LTTng tracers to record events
+happens within a recording session. In particular, a recording session:
+
+- Has its own name, unique for a given session daemon.
+
+- Has its own set of trace files, if any.
+
+- Has its own state of
+  \link lttng_session::enabled activity\endlink (started or stopped).
+
+  An active recording session is an implicit
+  \lt_obj_rer condition.
+
+- Has its own \ref api-session-modes "mode"
+  (local, network streaming, snapshot, or live).
+
+- Has its own \lt_obj_channels to which are attached
+  their own recording event rules.
+
+- Has its own \ref api_pais "process attribute inclusion sets".
+
+Those attributes and objects are completely isolated between different
+recording sessions.
+
+A recording session is like an
+<a href="https://en.wikipedia.org/wiki/Automated_teller_machine">ATM</a>
+session: the operations you do on the
+banking system through the ATM don't alter the data of other users of
+the same system. In the case of the ATM, a session lasts as long as your
+bank card is inside. In the case of LTTng, a recording session lasts
+from a call to lttng_create_session_ext() to the completion of its
+destruction operation (which you can initiate with
+lttng_destroy_session_ext()).
+
+A recording session belongs to a session daemon (see
+\lt_man{lttng-sessiond,8} and
+\ref api-gen-sessiond-conn "Session daemon connection"). For a given
+session daemon, each Unix user has its own, private recording sessions.
+Note, however, that the \c root Unix user may operate on or destroy
+another user's recording session.
+
+@image html many-sessions.png "Each Unix user has its own, private recording sessions."
+
+@sa The <em>RECORDING SESSION</em> section of \lt_man{lttng-concepts,7}.
+
+<h1>Operations</h1>
+
+The recording session operations are:
+
+<table>
+  <tr>
+    <th>Operation
+    <th>Means
+  <tr>
+    <td>Creation
+    <td>
+      -# Create a \lt_obj_session_descr
+         with one of the dedicated creation functions depending on the
+         \ref api-session-modes "recording session mode".
+
+      -# Call lttng_create_session_ext(), passing the recording session
+         descriptor of step&nbsp;1.
+
+      -# When you're done with the recording session descriptor, destroy
+         it with lttng_session_descriptor_destroy().
+
+      @sa \lt_man{lttng-create,1}
+  <tr>
+    <td>Destruction
+    <td>
+      -# Call lttng_destroy_session_ext(), passing the name of the
+         recording session to destroy.
+
+         This function initiates a destruction operation, returning
+         immediately.
+
+         This function can set a pointer to a
+         \ref api_session_destr_handle "destruction handle"
+         (#lttng_destruction_handle) so that you can wait for the
+         completion of the operation. Without such a handle, you can't
+         know when the destruction operation completes and whether or
+         not it does successfully.
+
+      -# <strong>If you have a destruction handle from
+         step&nbsp;1</strong>:
+
+         -# Call lttng_destruction_handle_wait_for_completion() to wait
+            for the completion of the destruction operation.
+
+         -# Call lttng_destruction_handle_get_result() to get whether or
+            not the destruction operation successfully completed.
+
+            You can also call
+            lttng_destruction_handle_get_rotation_state() and
+            lttng_destruction_handle_get_archive_location() at this
+            point.
+
+         -# Destroy the destruction handle with
+            lttng_destruction_handle_destroy().
+
+      @sa \lt_man{lttng-destroy,1}
+  <tr>
+    <td>Basic property access
+    <td>
+      See:
+
+      - The members of #lttng_session
+      - lttng_session_descriptor_get_session_name()
+      - lttng_session_get_creation_time()
+      - lttng_set_session_shm_path()
+      - lttng_data_pending()
+  <tr>
+    <td>\lt_obj_c_domain access
+    <td>
+      -# Call lttng_list_domains(), passing the name of the recording
+         session of which to get the tracing domains.
+
+         This function sets a pointer to an array of
+         \link #lttng_domain tracing domain summaries\endlink
+         and returns the number of entries.
+
+      -# Access the properties of each tracing domain summary through
+         structure members.
+
+      -# When you're done with the array of tracing domain summaries,
+         free it with <code>free()</code>.
+  <tr>
+    <td>\lt_obj_c_channel access
+    <td>
+      -# Create a \link #lttng_handle recording session handle\endlink
+         with lttng_create_handle() to specify the name of the
+         recording session and the summary of the
+         \lt_obj_domain of the channels to access.
+
+      -# Call lttng_list_channels(), passing the recording session
+         handle of step&nbsp;1.
+
+         This function sets a pointer to an array of
+         \link #lttng_channel channel summaries\endlink
+         and returns the number of entries.
+
+      -# Destroy the recording session handle of step&nbsp;1 with
+         lttng_destroy_handle().
+
+      -# Access the \ref api-channel-channel-props "properties" of each
+         channel summary through structure members or using dedicated
+         getters.
+
+      -# When you're done with the array of channel summaries,
+         free it with <code>free()</code>.
+  <tr>
+    <td>Activity control
+    <td>
+      See:
+
+      - lttng_start_tracing()
+      - lttng_stop_tracing()
+      - lttng_stop_tracing_no_wait()
+
+      The #LTTNG_ACTION_TYPE_START_SESSION and
+      #LTTNG_ACTION_TYPE_STOP_SESSION trigger actions can also
+      activate and deactivate a recording session.
+  <tr>
+    <td>Listing
+    <td>
+      -# Call lttng_list_sessions().
+
+         This function sets a pointer to an array of
+         \link #lttng_session recording session summaries\endlink
+         and returns the number of entries.
+
+      -# Access the properties of each recording session summary through
+         structure members or using dedicated getters.
+
+      -# When you're done with the array of recording session summaries,
+         free it with <code>free()</code>.
+
+      @sa \lt_man{lttng-list,1}
+  <tr>
+    <td>Process attribute inclusion set access
+    <td>See \ref api_pais
+  <tr>
+    <td>Clearing
+    <td>See \ref api_session_clear
+  <tr>
+    <td>Snapshot recording
+    <td>
+      See \ref api_session_snapshot
+
+      The #LTTNG_ACTION_TYPE_SNAPSHOT_SESSION trigger action can also
+      take a recording session snapshot.
+  <tr>
+    <td>Rotation
+    <td>
+      See \ref api_session_rotation
+
+      The #LTTNG_ACTION_TYPE_ROTATE_SESSION trigger action can also
+      rotate a recording session.
+  <tr>
+    <td>Saving and loading
+    <td>See \ref api_session_save_load
+  <tr>
+    <td>Trace data regeneration
+    <td>
+      See:
+
+      - lttng_regenerate_metadata()
+      - lttng_regenerate_statedump()
+
+      @sa \lt_man{lttng-regenerate,1}
+</table>
+
+<h1>\anchor api-session-modes Recording session modes</h1>
+
+LTTng offers four <strong><em>recording session modes</em></strong>:
+
+<table>
+  <tr>
+    <th>Mode
+    <th>Description
+    <th>Descriptor creation function(s)
+  <tr>
+    <td>\anchor api-session-local-mode Local
+    <td>
+      Write the trace data to the local file system, or do not write any
+      trace data.
+    <td>
+      - lttng_session_descriptor_create()
+      - lttng_session_descriptor_local_create()
+  <tr>
+    <td>\anchor api-session-net-mode Network streaming
+    <td>
+      Send the trace data over the network to a listening relay daemon
+      (see \lt_man{lttng-relayd,8}).
+    <td>lttng_session_descriptor_network_create()
+  <tr>
+    <td>\anchor api-session-snapshot-mode Snapshot
+    <td>
+      Only write the trace data to the local file system or send it to a
+      listening relay daemon when LTTng
+      takes a \ref api_session_snapshot "snapshot".
+
+      LTTng takes a snapshot of such a recording session when:
+
+      - You call lttng_snapshot_record().
+
+      - LTTng executes an #LTTNG_ACTION_TYPE_SNAPSHOT_SESSION trigger
+        action.
+
+      LTTng forces the
+      \ref api-channel-er-loss-mode "event record loss mode" of all
+      the channels of such a recording session to be
+      \"\ref api-channel-overwrite-mode "overwrite"\".
+    <td>
+      - lttng_session_descriptor_snapshot_create()
+      - lttng_session_descriptor_snapshot_local_create()
+      - lttng_session_descriptor_snapshot_network_create()
+  <tr>
+    <td>\anchor api-session-live-mode Live
+    <td>
+      Send the trace data over the network to a listening relay daemon
+      for live reading.
+
+      An LTTng live reader (for example,
+      <a href="https://babeltrace.org/">Babeltrace&nbsp;2</a>) can
+      connect to the same relay daemon to receive trace data while the
+      recording session is active.
+    <td>
+      lttng_session_descriptor_live_network_create()
+</table>
+
+@sa The <em>Recording session modes</em> section of
+\lt_man{lttng-concepts,7}.
+
+<h1>\anchor api-session-url Output URL format</h1>
+
+Some functions of the \lt_api require an <strong><em>output
+URL</em></strong>.
+
+An output URL is a C&nbsp;string which specifies where to send trace
+data and, when LTTng connects to a relay daemon (see
+\lt_man{lttng-relayd,8}), control commands.
+
+There are three available output URL formats:
+
+<table>
+  <tr>
+    <th>Type
+    <th>Description
+    <th>Format
+  <tr>
+    <td>\anchor api-session-local-url Local
+    <td>
+      Send trace data to the local file system, without connecting to a
+      relay daemon.
+
+      Accepted by:
+
+      - lttng_create_session() (deprecated)
+      - lttng_create_session_snapshot() (deprecated)
+      - lttng_snapshot_output_set_local_path()
+      - lttng_save_session_attr_set_output_url()
+      - lttng_load_session_attr_set_input_url()
+      - lttng_load_session_attr_set_override_url()
+    <td>
+      <code>file://<em>TRACEDIR</em></code>
+
+      <dl>
+        <dt><code><em>TRACEDIR</em></code>
+        <dd>
+          Absolute path to the directory containing the trace data on
+          the local file system.
+      </dl>
+  <tr>
+    <td>\anchor api-session-one-port-url Remote: single port
+    <td>
+      Send trace data and/or control commands to a specific relay daemon
+      with a specific TCP port.
+
+      Accepted by:
+
+      - lttng_session_descriptor_network_create()
+      - lttng_session_descriptor_snapshot_network_create()
+      - lttng_session_descriptor_live_network_create()
+      - lttng_snapshot_output_set_network_urls()
+      - lttng_snapshot_output_set_ctrl_url()
+      - lttng_snapshot_output_set_data_url()
+      - lttng_load_session_attr_set_override_ctrl_url()
+      - lttng_load_session_attr_set_override_data_url()
+    <td>
+      <code><em>PROTO</em>://<em>HOST</em></code>[<code>:<em>PORT</em></code>][<code>/<em>TRACEDIR</em></code>]
+
+      <dl>
+        <dt><code><em>PROTO</em></code>
+        <dd>
+          Network protocol, amongst:
+
+          <dl>
+            <dt>\c net
+            <dd>
+              TCP over IPv4.
+
+            <dt>\c net6
+            <dd>
+              TCP over IPv6.
+
+            <dt>\c tcp
+            <dd>
+              Same as <code>net</code>.
+
+            <dt>\c tcp6
+            <dd>
+              Same as <code>net6</code>.
+          </dl>
+
+        <dt><code><em>HOST</em></code>
+        <dd>
+          Hostname or IP address.
+
+          An IPv6 address must be enclosed in square brackets (<code>[</code>
+          and&nbsp;<code>]</code>); see
+          <a href="https://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>.
+
+        <dt><code><em>PORT</em></code>
+        <dd>
+          TCP port.
+
+          If it's missing, the default control and data ports are
+          respectively \lt_def_net_ctrl_port and
+          \lt_def_net_data_port.
+
+        <dt><code><em>TRACEDIR</em></code>
+        <dd>
+          Path of the directory containing the trace data on the remote
+          file system.
+
+          This path is relative to the base output directory of the
+          LTTng relay daemon (see the <em>Output directory</em>
+          section of \lt_man{lttng-relayd,8}).
+      </dl>
+  <tr>
+    <td>\anchor api-session-two-port-url Remote: control and data ports
+    <td>
+      Send trace data and control commands to a specific relay daemon
+      with specific TCP ports.
+
+      This form is usually a shorthand for two
+      \ref api-session-one-port-url "single-port output URLs" with
+      specified ports.
+
+      Accepted by:
+
+      - lttng_create_session_snapshot() (deprecated)
+      - lttng_create_session_live() (deprecated)
+      - lttng_session_descriptor_network_create()
+      - lttng_session_descriptor_snapshot_network_create()
+      - lttng_session_descriptor_live_network_create()
+      - lttng_snapshot_output_set_network_url()
+      - lttng_snapshot_output_set_network_urls()
+      - lttng_snapshot_output_set_ctrl_url()
+      - lttng_load_session_attr_set_override_url()
+      - lttng_load_session_attr_set_override_ctrl_url()
+    <td>
+      <code><em>PROTO</em>://<em>HOST</em>:<em>CTRLPORT</em>:<em>DATAPORT</em></code>[<code>/<em>TRACEDIR</em></code>]
+
+      <dl>
+        <dt><code><em>PROTO</em></code>
+        <dd>
+          Network protocol, amongst:
+
+          <dl>
+            <dt>\c net
+            <dd>
+              TCP over IPv4.
+
+            <dt>\c net6
+            <dd>
+              TCP over IPv6.
+
+            <dt>\c tcp
+            <dd>
+              Same as <code>net</code>.
+
+            <dt>\c tcp6
+            <dd>
+              Same as <code>net6</code>.
+          </dl>
+
+        <dt><code><em>HOST</em></code>
+        <dd>
+          Hostname or IP address.
+
+          An IPv6 address must be enclosed in square brackets (<code>[</code>
+          and&nbsp;<code>]</code>); see
+          <a href="https://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>.
+
+        <dt><code><em>CTRLPORT</em></code>
+        <dd>
+          Control TCP port.
+
+        <dt><code><em>DATAPORT</em></code>
+        <dd>
+          Trace data TCP port.
+
+        <dt><code><em>TRACEDIR</em></code>
+        <dd>
+          Path of the directory containing the trace data on the remote
+          file system.
+
+          This path is relative to the base output directory of the
+          LTTng relay daemon (see the <code>\--output</code> option of
+          \lt_man{lttng-relayd,8}).
+      </dl>
+</table>
+
+@defgroup api_session_descr Recording session descriptor API
+@ingroup api_session
+
+A <strong><em>recording session descriptor</em></strong> describes the
+properties of a \lt_obj_session to be (not created
+yet).
+
+To create a recording session from a recording session descriptor:
+
+-# Create a recording session descriptor
+   with one of the dedicated creation functions, depending on the
+   \ref api-session-modes "recording session mode":
+
+   <dl>
+     <dt>\ref api-session-local-mode "Local mode"
+     <dd>
+       One of:
+
+       - lttng_session_descriptor_create()
+       - lttng_session_descriptor_local_create()
+
+     <dt>\ref api-session-net-mode "Network streaming mode"
+     <dd>
+       lttng_session_descriptor_network_create()
+
+     <dt>\ref api-session-snapshot-mode "Snapshot mode"
+     <dd>
+       One of:
+
+       - lttng_session_descriptor_snapshot_create()
+       - lttng_session_descriptor_snapshot_local_create()
+       - lttng_session_descriptor_snapshot_network_create()
+
+     <dt>\ref api-session-live-mode "Live mode"
+     <dd>
+       lttng_session_descriptor_live_network_create()
+   </dl>
+
+-# Call lttng_create_session_ext(), passing the recording session
+   descriptor of step&nbsp;1.
+
+   After a successful call to this function, you can call
+   lttng_session_descriptor_get_session_name() to get the name of the
+   created recording session (set when creating the descriptor or
+   automatically generated).
+
+-# When you're done with the recording session descriptor, destroy
+   it with lttng_session_descriptor_destroy().
+
+@defgroup api_session_destr_handle Recording session destruction handle API
+@ingroup api_session
+
+A <strong><em>recording session destruction handle</em></strong>
+represents a \lt_obj_session destruction operation.
+
+The main purposes of a recording session destruction handle is to:
+
+- Wait for the completion of the recording session
+  destruction operation with
+  lttng_destruction_handle_wait_for_completion() and get whether or not
+  it was successful with lttng_destruction_handle_get_result().
+
+- Get the state of any
+  \ref api_session_rotation "recording session rotation"
+  which the recording session destruction operation caused
+  with lttng_destruction_handle_get_rotation_state(), and the location
+  of its trace chunk archive with
+  lttng_destruction_handle_get_archive_location().
+
+To destroy a recording session:
+
+-# Call lttng_destroy_session_ext(), passing the name of the recording
+   session to destroy.
+
+   This function initiates a destruction operation, returning
+   immediately.
+
+   This function can set a pointer to a
+   \link #lttng_destruction_handle destruction handle\endlink so that
+   you can wait for the completion of the operation. Without such a
+   handle, you can't know when the destruction operation completes and
+   whether or not it does successfully.
+
+-# Call lttng_destruction_handle_wait_for_completion() to wait
+   for the completion of the destruction operation.
+
+-# Call lttng_destruction_handle_get_result() to get whether or
+   not the destruction operation successfully completed.
+
+-# <strong>If LTTng performed at least one
+   \ref api_session_rotation "rotation" of the destroyed recording
+   session</strong>, call lttng_destruction_handle_get_rotation_state()
+   to know whether or not the last rotation was successful and
+   lttng_destruction_handle_get_archive_location() to get the location
+   of its trace chunk archive.
+
+-# Destroy the destruction handle with
+   lttng_destruction_handle_destroy().
+
+@defgroup api_channel Domain and channel API
+@ingroup api_session
+
+<h1>\anchor api-channel-domain Tracing domain</h1>
+
+A <strong><em>tracing domain</em></strong> identifies a type of LTTng
+tracer.
+
+A tracing domain has its own properties and features.
+
+There are currently five available tracing domains:
+
+<table>
+  <tr>
+    <th>Domain name
+    <th>Type enumerator
+  <tr>
+    <td>Linux kernel
+    <td>#LTTNG_DOMAIN_KERNEL
+  <tr>
+    <td>User space
+    <td>#LTTNG_DOMAIN_UST
+  <tr>
+    <td><a href="https://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html"><code>java.util.logging</code></a> (JUL)
+    <td>#LTTNG_DOMAIN_JUL
+  <tr>
+    <td><a href="https://logging.apache.org/log4j/1.2/">Apache log4j</a>
+    <td>#LTTNG_DOMAIN_LOG4J
+  <tr>
+    <td><a href="https://docs.python.org/3/library/logging.html">Python logging</a>
+    <td>#LTTNG_DOMAIN_PYTHON
+</table>
+
+A \lt_obj_channel is always part of a tracing domain.
+
+Many liblttng-ctl functions require a tracing domain type (sometimes
+within a
+\link #lttng_handle recording session handle\endlink)
+to target specific tracers or to avoid ambiguity. For example, because
+the Linux kernel and user space tracing domains support named
+tracepoints as \ref api_inst_pt "instrumentation points", you need to
+specify a tracing domain when you create a
+\lt_obj_rer with lttng_enable_event_with_exclusions() because both
+tracing domains could have LTTng tracepoints sharing the same name.
+
+@sa The <em>TRACING DOMAIN</em> section of \lt_man{lttng-concepts,7}.
+
+<h1>\anchor api-channel-channel Channel</h1>
+
+A <strong><em>channel</em></strong> is an object which is responsible
+for a set of ring buffers.
+
+Each ring buffer is divided into multiple <em>sub-buffers</em>. When a
+\lt_obj_rer matches an event, LTTng can record it to one or more
+sub-buffers of one or more channels.
+
+A channel is always associated to a \lt_obj_domain.
+The \link #LTTNG_DOMAIN_JUL <code>java.util.logging</code>\endlink,
+\link #LTTNG_DOMAIN_LOG4J Apache log4j\endlink, and
+\link #LTTNG_DOMAIN_PYTHON Python\endlink tracing
+domains each have a default channel which you can't configure.
+
+Note that the some functions, like lttng_enable_event_with_exclusions(),
+can automatically create a default channel with sane defaults when no
+channel exists for the provided \lt_obj_domain.
+
+A channel owns \lt_obj_rers.
+
+@image html concepts.png "A recording session contains channels that are members of tracing domains and contain recording event rules."
+
+You can't destroy a channel.
+
+<h2>Operations</h2>
+
+The channel operations are:
+
+<table>
+  <tr>
+    <th>Operation
+    <th>Means
+  <tr>
+    <td>Creation
+    <td>
+      -# Call lttng_channel_create() with a \lt_obj_domain summary to
+         create an initial channel summary.
+
+         This function calls lttng_channel_set_default_attr() to set
+         the properties of the created channel summary to default values
+         depending on the tracing domain summary.
+
+      -# Set the properties of the channel summary of step&nbsp;1
+         through direct members or with dedicated setters.
+
+         See the property table below.
+
+      -# Create a \link #lttng_handle recording session handle\endlink
+         structure to specify the name of the recording session and the
+         tracing domain of the channel to create.
+
+      -# Call lttng_enable_channel() with the recording session handle
+         of step&nbsp;3 and the channel summary of step&nbsp;1
+         o create the channel.
+
+      -# Destroy the recording session handle with
+         lttng_destroy_handle() and the channel summary with
+         lttng_channel_destroy().
+
+      @sa \lt_man{lttng-enable-channel,1}
+  <tr>
+    <td>Basic property access
+    <td>
+      See the \ref api-channel-channel-props "property table" below.
+  <tr>
+    <td>\lt_obj_c_rer access
+    <td>
+      -# Create a \link #lttng_handle recording session handle\endlink
+         with lttng_create_handle() to specify the name of the
+         recording session and the summary of the
+         \lt_obj_domain of the channel of which to get the recording
+         event rule descriptors.
+
+      -# Call lttng_list_events(), passing the recording session
+         handle of step&nbsp;1 and a channel name.
+
+         This function sets a pointer to an array of
+         \link #lttng_event recording event rule descriptors\endlink
+         and returns the number of entries.
+
+      -# Destroy the recording session handle of step&nbsp;1 with
+         lttng_destroy_handle().
+
+      -# Access the properties of each
+         recording event rule descriptor through structure members or
+         using dedicated getters.
+
+      -# When you're done with the array of recording event rule
+         descriptors, free it with <code>free()</code>.
+  <tr>
+    <td>Event record context field adding
+    <td>
+      -# Initialize a #lttng_event_context structure, setting
+         its properties to describe the context field to be added.
+
+      -# Create a \link #lttng_handle recording session handle\endlink
+         structure to specify the name of the recording session and the
+         tracing domain of the channel to create.
+
+      -# Call lttng_add_context() with the recording session handle
+         of step&nbsp;2 and the context field descriptor of step&nbsp;1,
+         optionally passing the name of the channel to target.
+
+      -# Destroy the recording session handle with
+         lttng_destroy_handle().
+
+      @sa \lt_man{lttng-add-context,1}
+  <tr>
+    <td>Enabling
+    <td>
+      Use lttng_enable_channel().
+
+      @sa \lt_man{lttng-enable-channel,1}
+  <tr>
+    <td>Disabling
+    <td>
+      Use lttng_disable_channel().
+
+      @sa \lt_man{lttng-disable-channel,1}
+  <tr>
+    <td>Statistics
+    <td>
+      See:
+
+      - lttng_channel_get_discarded_event_count()
+      - lttng_channel_get_lost_packet_count()
+</table>
+
+<h2>\anchor api-channel-channel-props Properties</h2>
+
+The properties of a channel are:
+
+<table>
+  <tr>
+    <th>Property name
+    <th>Description
+    <th>Access
+  <tr>
+    <td>Buffering scheme
+    <td>
+      See \ref api-channel-buf-scheme "Buffering scheme".
+    <td>
+      The lttng_domain::buf_type member for the containing tracing
+      domain.
+
+      All the channels of a given tracing domain share the same
+      buffering scheme.
+  <tr>
+    <td>Event record loss mode
+    <td>
+      See \ref api-channel-er-loss-mode "Event record loss mode".
+    <td>
+      The lttng_channel_attr::overwrite member.
+  <tr>
+    <td>Sub-buffer size
+    <td>
+      See \ref api-channel-sub-buf-size-count "Sub-buffer size and count".
+    <td>
+      The lttng_channel_attr::subbuf_size member.
+  <tr>
+    <td>Sub-buffer count
+    <td>
+      See \ref api-channel-sub-buf-size-count "Sub-buffer size and count".
+    <td>
+      The lttng_channel_attr::num_subbuf member.
+  <tr>
+    <td>Maximum trace file size
+    <td>
+      See \ref api-channel-max-trace-file-size-count "Maximum trace file size and count".
+    <td>
+      The lttng_channel_attr::tracefile_size member.
+  <tr>
+    <td>Maximum trace file count
+    <td>
+      See \ref api-channel-max-trace-file-size-count "Maximum trace file size and count".
+    <td>
+      The lttng_channel_attr::tracefile_count member.
+  <tr>
+    <td>Read timer period
+    <td>
+      See \ref api-channel-read-timer "Read timer".
+    <td>
+      The lttng_channel_attr::read_timer_interval member.
+  <tr>
+    <td>Switch timer period
+    <td>
+      See \ref api-channel-switch-timer "Switch timer".
+    <td>
+      The lttng_channel_attr::switch_timer_interval member.
+  <tr>
+    <td>Live timer period
+    <td>
+      See \ref api-channel-live-timer "Live timer".
+    <td>
+      The \lt_p{live_timer_period} parameter of
+      lttng_session_descriptor_live_network_create() when you create
+      the descriptor of a \ref api-session-live-mode "live" recording
+      session to contain the channel.
+  <tr>
+    <td>Monitor timer period
+    <td>
+      See \ref api-channel-monitor-timer "Monitor timer".
+    <td>
+      - lttng_channel_get_monitor_timer_interval()
+      - lttng_channel_set_monitor_timer_interval()
+  <tr>
+    <td>Output type (Linux kernel channel)
+    <td>
+      Whether to use <code>mmap()</code> or <code>splice()</code>.
+    <td>
+      The lttng_channel_attr::output member.
+  <tr>
+    <td>\anchor api-channel-blocking-timeout Blocking timeout (user space channel)
+    <td>
+      How long to block (if ever) at the instrumentation point site when
+      a sub-buffer is not available for applications executed with the
+      \c LTTNG_UST_ALLOW_BLOCKING environment variable set.
+    <td>
+      - lttng_channel_get_blocking_timeout()
+      - lttng_channel_set_blocking_timeout()
+</table>
+
+All the properties above are immutable once a channel exists.
+
+@sa The <em>CHANNEL AND RING BUFFER</em> section of
+\lt_man{lttng-concepts,7}.
+
+<h3>\anchor api-channel-buf-scheme Buffering scheme</h3>
+
+A channel has at least one ring buffer per CPU. LTTng always records an
+event to the ring buffer dedicated to the CPU which emits it.
+
+The <strong><em>buffering scheme</em></strong> of a
+\link #LTTNG_DOMAIN_UST user space\endlink
+channel determines what has its own set of per-CPU
+ring buffers, considering \lt_var{U} is the Unix user of the process
+running liblttng-ctl:
+
+<dl>
+  <dt>
+    \anchor api-channel-per-user-buf
+    \link #LTTNG_BUFFER_PER_UID Per-user buffering\endlink
+  <dd>
+    Allocate one set of ring buffers (one per CPU) shared by all the
+    instrumented processes of:
+
+    <dl>
+      <dt>If \lt_var{U} is <code>root</code>
+      <dd>
+        Each Unix user.
+
+        @image html per-user-buffering-root.png
+
+      <dt>Otherwise
+      <dd>
+        \lt_var{U}
+
+        @image html per-user-buffering.png
+    </dl>
+
+  <dt>
+    \anchor api-channel-per-proc-buf
+    \link #LTTNG_BUFFER_PER_PID Per-process buffering\endlink
+  <dd>
+    Allocate one set of ring buffers (one per CPU) for each
+    instrumented process of:
+
+    <dl>
+      <dt>If \lt_var{U} is <code>root</code>
+      <dd>
+        All Unix users.
+
+        @image html per-process-buffering-root.png
+
+      <dt>Otherwise
+      <dd>
+        \lt_var{U}
+
+        @image html per-process-buffering.png
+    </dl>
+</dl>
+
+The per-process buffering scheme tends to consume more memory than the
+per-user option because systems generally have more instrumented
+processes than Unix users running instrumented processes. However, the
+per-process buffering scheme ensures that one process having a high
+event throughput won't fill all the shared sub-buffers of the same Unix
+user, only its own.
+
+The buffering scheme of a Linux kernel (#LTTNG_DOMAIN_KERNEL) channel is
+always to allocate a single set of ring buffers for the whole system
+(#LTTNG_BUFFER_GLOBAL). This scheme is similar to the
+\ref api-channel-per-user-buf "per-user" one, but with a single, global
+user "running" the kernel.
+
+To set the buffering scheme of a channel when you create it:
+
+- Set the lttng_domain::buf_type member of the structure which you pass
+  within the #lttng_handle structure to lttng_enable_channel().
+
+  Note that, for a given \lt_obj_session, \em all
+  the channels of a given \lt_obj_domain must share the same buffering
+  scheme.
+
+@sa The <em>Buffering scheme</em> section of \lt_man{lttng-concepts,7}.
+
+<h3>\anchor api-channel-er-loss-mode Event record loss mode</h3>
+
+When LTTng emits an event, LTTng can record it to a specific, available
+sub-buffer within the ring buffers of specific channels. When there's no
+space left in a sub-buffer, the tracer marks it as consumable and
+another, available sub-buffer starts receiving the following event
+records. An LTTng consumer daemon eventually consumes the marked
+sub-buffer, which returns to the available state.
+
+In an ideal world, sub-buffers are consumed faster than they are filled.
+In the real world, however, all sub-buffers can be full at some point,
+leaving no space to record the following events.
+
+By default, LTTng-modules and LTTng-UST are <em>non-blocking</em>
+tracers: when there's no available sub-buffer to record an event, it's
+acceptable to lose event records when the alternative would be to cause
+substantial delays in the execution of the instrumented application.
+LTTng privileges performance over integrity; it aims at perturbing the
+instrumented application as little as possible in order to make the
+detection of subtle race conditions and rare interrupt cascades
+possible.
+
+Since LTTng&nbsp;2.10, the LTTng user space tracer, LTTng-UST, supports
+a <em>blocking mode</em>: see lttng_channel_get_blocking_timeout() and
+lttng_channel_set_blocking_timeout().
+
+When it comes to losing event records because there's no available
+sub-buffer, or because the blocking timeout of the channel is reached,
+the <strong><em>event record loss mode</em></strong> of the channel
+determines what to do. The available event record loss modes are:
+
+<dl>
+  <dt>\anchor api-channel-discard-mode Discard mode
+  <dd>
+    Drop the newest event records until a sub-buffer becomes available.
+
+    This is the only available mode when you specify a blocking timeout
+    with lttng_channel_set_blocking_timeout().
+
+    With this mode, LTTng increments a count of discarded event records
+    when it discards an event record and saves this count to the trace.
+    A trace reader can use the saved discarded event record count of the
+    trace to decide whether or not to perform some analysis even if
+    trace data is known to be missing.
+
+    Get the number of discarded event records of a channel with
+    lttng_channel_get_discarded_event_count().
+
+  <dt>\anchor api-channel-overwrite-mode Overwrite mode
+  <dd>
+    Clear the sub-buffer containing the oldest event records and start
+    writing the newest event records there.
+
+    This mode is sometimes called <em>flight recorder mode</em> because
+    it's similar to a
+    <a href="https://en.wikipedia.org/wiki/Flight_recorder">flight recorder</a>:
+    always keep a fixed amount of the latest data. It's also
+    similar to the roll mode of an oscilloscope.
+
+    Since LTTng&nbsp;2.8, with this mode, LTTng writes to a given
+    sub-buffer its sequence number within its data stream. With a
+    \ref api-session-local-mode "local",
+    \ref api-session-net-mode "network streaming", or
+    \ref api-session-live-mode "live" recording session, a trace
+    reader can use such sequence numbers to report discarded packets. A
+    trace reader can use the saved discarded sub-buffer (packet) count
+    of the trace to decide whether or not to perform some analysis even
+    if trace data is known to be missing.
+
+    Get the number of discarded packets (sub-buffers) of a channel with
+    lttng_channel_get_lost_packet_count().
+
+    With this mode, LTTng doesn't write to the trace the exact number of
+    lost event records in the lost sub-buffers.
+</dl>
+
+Which mechanism you should choose depends on your context: prioritize
+the newest or the oldest event records in the ring buffer?
+
+Beware that, in overwrite mode, the tracer abandons a <em>whole
+sub-buffer</em> as soon as a there's no space left for a new event
+record, whereas in discard mode, the tracer only discards the event
+record that doesn't fit.
+
+To set the event record loss mode of a channel when you create it:
+
+- Set the lttng_channel_attr::overwrite member of the lttng_channel::attr
+  member of the structure you pass to lttng_enable_channel().
+
+There are a few ways to decrease your probability of losing event
+records. The
+\ref api-channel-sub-buf-size-count "Sub-buffer size and count" section
+shows how to fine-tune the sub-buffer size and count of a channel to
+virtually stop losing event records, though at the cost of greater
+memory usage.
+
+@sa The <em>Event record loss mode</em> section of
+\lt_man{lttng-concepts,7}.
+
+<h3>\anchor api-channel-sub-buf-size-count Sub-buffer size and count</h3>
+
+A channel has one or more ring buffer for each CPU of the target system.
+
+See \ref api-channel-buf-scheme "Buffering scheme" to learn how many
+ring buffers of a given channel are dedicated to each CPU depending on
+its buffering scheme.
+
+To set the size of each sub-buffer the ring buffers of a channel have
+when you create it:
+
+- Set the lttng_channel_attr::subbuf_size member of the
+  lttng_channel::attr member of the structure you pass to
+  lttng_enable_channel().
+
+To set the number of sub-buffers each ring buffer of a channel has
+when you create it:
+
+- Set the lttng_channel_attr::num_subbuf member of the
+  lttng_channel::attr member of the structure you pass to
+  lttng_enable_channel().
+
+Note that LTTng switching the current sub-buffer of a ring buffer
+(marking a full one as consumable and switching to an available one for
+LTTng to record the next events) introduces noticeable CPU overhead.
+Knowing this, the following list presents a few practical situations
+along with how to configure the sub-buffer size and count for them:
+
+<dl>
+  <dt>High event throughput
+  <dd>
+    In general, prefer large sub-buffers to lower the risk of losing
+    event records.
+
+    Having larger sub-buffers also ensures a lower sub-buffer
+    \ref api-channel-switch-timer "switching frequency".
+
+    The sub-buffer count is only meaningful if you create the channel in
+    \ref api-channel-overwrite-mode "overwrite mode": in this case, if
+    LTTng overwrites a sub-buffer, then the other sub-buffers are left
+    unaltered.
+
+  <dt>Low event throughput
+  <dd>
+    In general, prefer smaller sub-buffers since the risk of losing
+    event records is low.
+
+    Because LTTng emits events less frequently, the sub-buffer switching
+    frequency should remain low and therefore the overhead of the tracer
+    shouldn't be a problem.
+
+  <dt>Low memory system
+  <dd>
+    If your target system has a low memory limit, prefer fewer first,
+    then smaller sub-buffers.
+
+    Even if the system is limited in memory, you want to keep the
+    sub-buffers as large as possible to avoid a high sub-buffer
+    switching frequency.
+</dl>
+
+Note that LTTng uses <a href="https://diamon.org/ctf/">CTF</a> as its
+trace format, which means event record data is very compact. For
+example, the average LTTng kernel event record weights about
+32&nbsp;bytes. Therefore, a sub-buffer size of 1&nbsp;MiB is considered
+large.
+
+The previous scenarios highlight the major trade-off between a few large
+sub-buffers and more, smaller sub-buffers: sub-buffer switching
+frequency vs. how many event records are lost in
+\ref api-channel-overwrite-mode "overwrite mode".
+Assuming a constant event throughput and using the overwrite mode, the
+two following configurations have the same ring buffer total size:
+
+<dl>
+  <dt>Two sub-buffers of 4&nbsp;MiB each
+  <dd>
+    Expect a very low sub-buffer switching frequency, but if LTTng ever
+    needs to overwrite a sub-buffer, half of the event records so far
+    (4&nbsp;MiB) are definitely lost.
+
+  <dt>Eight sub-buffers of 1&nbsp;MiB each
+  <dd>
+    Expect four times the tracer overhead of the configuration above,
+    but if LTTng needs to overwrite a sub-buffer, only the eighth of
+    event records so far (1&nbsp;MiB) are definitely lost.
+</dl>
+
+In \ref api-channel-discard-mode "discard mode", the sub-buffer count
+parameter is pointless: use two sub-buffers and set their size according
+to your requirements.
+
+@sa The <em>Sub-buffer size and count</em> section of
+\lt_man{lttng-concepts,7}.
+
+<h3>\anchor api-channel-max-trace-file-size-count Maximum trace file size and count</h3>
+
+By default, trace files can grow as large as needed.
+
+To set the maximum size of each trace file that LTTng writes from the
+ring buffers of a channel when you create it:
+
+- Set the lttng_channel_attr::tracefile_size member of the
+  lttng_channel::attr member of the structure you pass to
+  lttng_enable_channel().
+
+When the size of a trace file reaches the fixed maximum size of the
+channel, LTTng creates another file to contain the next event records.
+LTTng appends a file count to each trace file name in this case.
+
+If you set the trace file size attribute when you create a channel, the
+maximum number of trace files that LTTng creates is <em>unlimited</em>
+by default.
+
+To limit the size of each trace file that LTTng writes from the
+ring buffers of a channel when you create it:
+
+- Set the lttng_channel_attr::tracefile_count member of the
+  lttng_channel::attr member of the structure you pass to
+  lttng_enable_channel().
+
+When the number of trace files reaches the fixed maximum count of the
+channel, LTTng overwrites the oldest trace file. This mechanism is
+called <em>trace file rotation</em>.
+
+@attention
+    @parblock
+    Even if you don't limit the trace file count, always assume that
+    LTTng manages all the trace files of the recording session.
+
+    In other words, there's no safe way to know if LTTng still holds a
+    given trace file open with the trace file rotation feature.
+
+    The only way to obtain an unmanaged, self-contained LTTng trace
+    before you \link lttng_destroy_session_ext() destroy the
+    recording session\endlink is with the
+    \ref api_session_rotation "recording session rotation" feature,
+    which is available since LTTng&nbsp;2.11.
+    @endparblock
+
+@sa The <em>Maximum trace file size and count</em> section of
+\lt_man{lttng-concepts,7}.
+
+<h3>\anchor api-channel-timers Timers</h3>
+
+Each channel can have up to four optional
+<strong><em>timers</em></strong>:
+
+<dl>
+  <dt>\anchor api-channel-switch-timer Switch timer
+  <dd>
+    When this timer expires, a sub-buffer switch happens: for each ring
+    buffer of the channel, LTTng marks the current sub-buffer as
+    consumable and switches to an available one to record the next
+    events.
+
+    A switch timer is useful to ensure that LTTng consumes and commits
+    trace data to trace files or to a distant relay daemon
+    (see \lt_man{lttng-relayd,8}) periodically in case of a low event
+    throughput.
+
+    Such a timer is also convenient when you use
+    \ref api-channel-sub-buf-size-count "large sub-buffers"
+    to cope with a sporadic high event throughput, even if the
+    throughput is otherwise low.
+
+    To set the period of the switch timer of a channel when you create
+    it:
+
+    - Set the lttng_channel_attr::switch_timer_interval member of the
+      lttng_channel::attr member of the structure you pass to
+      lttng_enable_channel().
+
+    A channel only has a switch timer when its
+    recording session is \em not in
+    \ref api-session-live-mode "live mode". lttng_enable_channel()
+    ignores the lttng_channel_attr::switch_timer_interval member with a
+    live recording session. For a live recording session, the
+    \ref api-channel-live-timer "live timer" plays the role of the
+    switch timer.
+
+  <dt>\anchor api-channel-live-timer Live timer
+  <dd>
+    Like the \ref api-channel-switch-timer "switch timer", but for a
+    channel which belongs to a
+    \ref api-session-live-mode "live" recording session.
+
+    If this timer expires but there's no sub-buffer to consume, LTTng
+    sends a message with a timestamp to the connected relay daemon (see
+    \lt_man{lttng-relayd,8}) so that its live readers can progress.
+
+    To set the period of the live timer of a channel when you create
+    its recording session:
+
+    - Set the \lt_p{live_timer_period} parameter when you call
+      lttng_session_descriptor_live_network_create() to create a
+      live recording session descriptor to pass to
+      lttng_create_session_ext().
+
+    @note
+        All the channels of a live recording session share the same
+        live timer period.
+
+  <dt>\anchor api-channel-read-timer Read timer
+  <dd>
+    When this timer expires, LTTng checks for full, consumable
+    sub-buffers.
+
+    By default, the LTTng tracers use an asynchronous message mechanism
+    to signal a full sub-buffer so that a consumer daemon can consume
+    it.
+
+    When such messages must be avoided, for example in real-time
+    applications, use this timer instead.
+
+    To set the period of the read timer of a channel when you create
+    it:
+
+    - Set the lttng_channel_attr::read_timer_interval member of the
+      lttng_channel::attr member of the structure you pass to
+      lttng_enable_channel().
+
+  <dt>\anchor api-channel-monitor-timer Monitor timer
+  <dd>
+    When this timer expires, the consumer daemon samples some channel
+    statistics to evaluate the following trigger conditions:
+
+    -# The consumed buffer size of a given recording session becomes
+       greater than some value.
+
+    -# The buffer usage of a given channel becomes greater than some
+       value.
+
+    -# The buffer usage of a given channel becomes less than some value.
+
+    If you disable the monitor timer of a channel&nbsp;\lt_var{C}:
+
+    - The consumed buffer size value of the recording session
+      of&nbsp;\lt_var{C} could be wrong for trigger condition
+      type&nbsp;1: the consumed buffer size of&nbsp;\lt_var{C} won't be
+      part of the grand total.
+
+    - The buffer usage trigger conditions (types&nbsp;2 and&nbsp;3)
+      for&nbsp;\lt_var{C} will never be satisfied.
+
+      See \ref api_trigger to learn more about triggers.
+
+    To set the period of the monitor timer of a channel when you create
+    it:
+
+    - Call lttng_channel_set_monitor_timer_interval() with the
+      #lttng_channel structure you pass to lttng_enable_channel().
+</dl>
+
+@sa The <em>Timers</em> section of \lt_man{lttng-concepts,7}.
+
+@defgroup api_rer Recording event rule API
+@ingroup api_channel
+
+<h1>Concepts</h1>
+
+An <em>instrumentation point</em> is a point, within a piece of
+software, which, when executed, creates an LTTng <em>event</em>.
+See \ref api_inst_pt to learn how to list the available instrumentation
+points.
+
+An <em>event rule</em> is a set of \ref api-rer-conds "conditions" to
+match a set of events.
+
+A <strong><em>recording event rule</em></strong> is a specific type of
+event rule of which the action is to serialize and write the matched
+event as an <em>event record</em> to a sub-buffer of its attached
+\lt_obj_channel.
+
+An event record has a \ref api-rer-er-name "name" and fields.
+
+When LTTng creates an event&nbsp;\lt_var{E}, a recording event
+rule&nbsp;\lt_var{ER} is said to <em>match</em>&nbsp;\lt_var{E}
+when&nbsp;\lt_var{E} satisfies \em all the conditions
+of&nbsp;\lt_var{ER}. This concept is similar to a regular expression
+which matches a set of strings.
+
+When a recording event rule matches an event, LTTng \em emits the event,
+therefore attempting to record it.
+
+@attention
+    @parblock
+    The event creation and emission processes are \em documentation
+    concepts to help understand the journey from an instrumentation
+    point to an event record.
+
+    The actual creation of an event can be costly because LTTng needs to
+    evaluate the arguments of the instrumentation point.
+
+    In practice, LTTng implements various optimizations for the
+    \link #LTTNG_DOMAIN_KERNEL Linux kernel\endlink and
+    \link #LTTNG_DOMAIN_UST user space\endlink \lt_obj_domains
+    to avoid actually creating an event when the tracer knows, thanks to
+    properties which are independent from the event payload and current
+    \link #lttng_event_context_type context\endlink, that it would never
+    emit such an event. Those properties are:
+
+    - The \ref api-rer-conds-inst-pt-type "instrumentation point type".
+
+    - The \ref api-rer-conds-event-name "instrumentation point name" (or
+      event name).
+
+    - The \ref api-rer-conds-ll "instrumentation point log level".
+
+    - The \link lttng_event::enabled status\endlink (enabled or
+      disabled) of the rule itself.
+
+    - The \link lttng_channel::enabled status\endlink (enabled or
+      disabled) of the \lt_obj_channel containing the rule.
+
+    - The \link lttng_session::enabled activity\endlink (started or
+      stopped) of the \lt_obj_session containing the rule.
+
+    - Whether or not the process for which LTTng would create the event
+      is \ref api_pais "allowed to record events".
+
+    In other words: if, for a given instrumentation point&nbsp;\lt_var{IP},
+    the LTTng tracer knows that it would never emit an event,
+    executing&nbsp;\lt_var{IP} represents a simple boolean variable check
+    and, for a \link #LTTNG_DOMAIN_KERNEL Linux kernel\endlink
+    \lt_obj_rer, a few current process attribute checks.
+    @endparblock
+
+You always attach a recording event rule to a
+\lt_obj_channel, which belongs to
+a \lt_obj_session, when you
+\link lttng_enable_event_with_exclusions() create it\endlink.
+A channel owns recording event rules.
+
+When multiple matching recording event rules are attached to the same
+channel, LTTng attempts to serialize and record the matched event
+<em>once</em>.
+
+@image html event-rule.png "Logical path from an instrumentation point to an event record."
+
+As of LTTng-tools&nbsp;\lt_version_maj_min, you cannot remove a
+recording event rule: it exists as long as its \lt_obj_session exists.
+
+<h1>Operations</h1>
+
+The recording event rule operations are:
+
+<table>
+  <tr>
+    <th>Operation
+    <th>Means
+  <tr>
+    <td>Creation
+    <td>
+      -# Call lttng_event_create() to create an initial
+         \link #lttng_event recording event rule descriptor\endlink.
+
+      -# Set the properties of the recording event rule descriptor of
+         step&nbsp;1 through direct members or with dedicated setters.
+
+         See the property table below.
+
+      -# Create a \link #lttng_handle recording session handle\endlink
+         structure to specify the name of the recording session and the
+         tracing domain of the recording event rule to create.
+
+      -# Call lttng_enable_event_with_exclusions() with the recording
+         session handle of step&nbsp;3, the recording event rule
+         descriptor of step&nbsp;1, the name of a
+         \lt_obj_channel to which to attach the
+         created recording event rule, and, depending on the selected
+         function, other properties to create the rule.
+
+      -# Destroy the recording session handle with
+         lttng_destroy_handle() and the recording event rule descriptor
+         with lttng_event_destroy().
+
+      @sa \lt_man{lttng-enable-event,1}
+  <tr>
+    <td>Property access
+    <td>
+      See:
+
+      - The members of #lttng_event
+      - lttng_event_get_userspace_probe_location()
+      - lttng_event_set_userspace_probe_location()
+      - lttng_event_get_filter_expression()
+      - lttng_event_get_exclusion_name_count()
+      - lttng_event_get_exclusion_name()
+
+      @sa \ref api-rer-conds "Recording event rule conditions".
+  <tr>
+    <td>Enabling
+    <td>
+      With an #lttng_event instance which comes from
+      lttng_list_events(), use lttng_enable_event().
+
+      Otherwise, use lttng_enable_event_with_exclusions().
+
+      @sa \lt_man{lttng-enable-event,1}
+  <tr>
+    <td>Disabling
+    <td>
+      Use lttng_disable_event() or lttng_disable_event_ext().
+
+      @sa \lt_man{lttng-disable-event,1}
+</table>
+
+<h1>\anchor api-rer-conds Recording event rule conditions</h1>
+
+For LTTng to emit and record an event&nbsp;\lt_var{E},&nbsp;\lt_var{E}
+must satisfy \em all the conditions of a recording event
+rule&nbsp;\lt_var{ER}, that is:
+
+<dl>
+  <dt>Explicit conditions
+  <dd>
+    You set the following conditions when you
+    \link lttng_enable_event_with_exclusions() create\endlink
+    \lt_var{ER} from some
+    \link #lttng_event recording event rule descriptor\endlink
+    \c event_rule (#lttng_event).
+
+    <table>
+      <tr>
+        <th>Name
+        <th>Description
+      <tr>
+        <td>
+          \anchor api-rer-conds-inst-pt-type
+          \ref api-rer-conds-inst-pt-type "Instrumentation point type"
+        <td>
+          \lt_var{E} satisfies the instrumentation point type condition
+          of \lt_var{ER} if the instrumentation point from which LTTng
+          creates&nbsp;\lt_var{E} is, depending on the
+          \lt_obj_domain which contains \lt_var{ER}:
+
+          <dl>
+            <dt>#LTTNG_DOMAIN_KERNEL
+            <dd>
+              Depending on
+              \link lttng_event::type <code>event_rule.type</code>\endlink:
+
+              <dl>
+                <dt>#LTTNG_EVENT_TRACEPOINT
+                <dd>
+                  An LTTng kernel tracepoint, that is, a statically
+                  defined point in the source code of the kernel image
+                  or of a kernel module with LTTng kernel tracer macros.
+
+                  @sa lttng_list_tracepoints()
+
+                <dt>#LTTNG_EVENT_SYSCALL
+                <dd>
+                  The entry and exit of a Linux kernel system call.
+
+                  @sa lttng_list_syscalls()
+
+                <dt>#LTTNG_EVENT_PROBE
+                <dd>
+                  A Linux
+                  <a href="https://www.kernel.org/doc/html/latest/trace/kprobes.html">kprobe</a>,
+                  that is, a single probe dynamically placed in the
+                  compiled kernel code.
+
+                  \link lttng_event::lttng_event_attr_u::probe
+                  <code>event_rule.attr.probe</code>\endlink
+                  indicates the kprobe location,
+                  while \link lttng_event::name
+                  <code>event_rule.name</code>\endlink
+                  is the name of the created kprobe instrumentation
+                  point (future event name).
+
+                  The payload of a Linux kprobe event is empty.
+
+                <dt>#LTTNG_EVENT_FUNCTION
+                <dd>
+                  A Linux
+                  <a href="https://www.kernel.org/doc/html/latest/trace/kprobes.html">kretprobe</a>,
+                  that is, two probes dynamically placed at the entry
+                  and exit of a function in the compiled kernel code.
+
+                  \link lttng_event::lttng_event_attr_u::probe
+                  <code>event_rule.attr.probe</code>\endlink
+                  indicates the kretprobe location,
+                  while \link lttng_event::name
+                  <code>event_rule.name</code>\endlink
+                  is the name of the created kretprobe instrumentation
+                  point (future event name).
+
+                  The payload of a Linux kretprobe event is empty.
+
+                <dt>#LTTNG_EVENT_USERSPACE_PROBE
+                <dd>
+                  A Linux
+                  <a href="https://lwn.net/Articles/499190/">uprobe</a>,
+                  that is, a single probe dynamically placed at the
+                  entry of a compiled user space application/library
+                  function through the kernel.
+
+                  Set and get the location of the uprobe with
+                  lttng_event_set_userspace_probe_location() and
+                  lttng_event_get_userspace_probe_location().
+
+                  \link lttng_event::name <code>event_rule.name</code>\endlink
+                  is the name of the created uprobe instrumentation
+                  point (future event name).
+
+                  The payload of a Linux uprobe event is empty.
+              </dl>
+
+            <dt>#LTTNG_DOMAIN_UST
+            <dd>
+              An LTTng user space tracepoint, that is, a statically
+              defined point in the source code of a C/C++
+              application/library with LTTng user space tracer macros.
+
+              \link lttng_event::type <code>event_rule.type</code>\endlink
+              must be #LTTNG_EVENT_TRACEPOINT.
+
+              @sa lttng_list_tracepoints()
+
+            <dt>#LTTNG_DOMAIN_JUL
+            <dt>#LTTNG_DOMAIN_LOG4J
+            <dt>#LTTNG_DOMAIN_PYTHON
+            <dd>
+              A Java/Python logging statement.
+
+              \link lttng_event::type <code>event_rule.type</code>\endlink
+              must be #LTTNG_EVENT_TRACEPOINT.
+
+              @sa lttng_list_tracepoints()
+          </dl>
+      <tr>
+        <td>
+          \anchor api-rer-conds-event-name
+          \ref api-rer-conds-event-name "Event name"
+        <td>
+          An event&nbsp;\lt_var{E} satisfies the event name condition
+          of&nbsp;\lt_var{ER} if the two following statements are
+          \b true:
+
+          - \link lttng_event::name <code>event_rule.name</code>\endlink
+            matches, depending on
+            \link lttng_event::type <code>event_rule.type</code>\endlink
+            (see \ref api-rer-conds-inst-pt-type "Instrumentation point type"
+            above):
+
+            <dl>
+              <dt>#LTTNG_EVENT_TRACEPOINT
+              <dd>
+                The full name of the LTTng tracepoint or Java/Python
+                logger from which LTTng creates&nbsp;\lt_var{E}.
+
+                Note that the full name of a
+                \link #LTTNG_DOMAIN_UST user space\endlink tracepoint is
+                <code><em>PROVIDER</em>:<em>NAME</em></code>, where
+                <code><em>PROVIDER</em></code> is the tracepoint
+                provider name and <code><em>NAME</em></code> is the
+                tracepoint name.
+
+              <dt>#LTTNG_EVENT_SYSCALL
+              <dd>
+                The name of the system call, without any
+                <code>sys_</code> prefix, from which LTTng
+                creates&nbsp;\lt_var{E}.
+            </dl>
+
+            @sa \ref api-rer-er-name "Event record name".
+
+          - If the \lt_obj_domain
+            containing&nbsp;\lt_var{ER} is #LTTNG_DOMAIN_UST:
+            none of the event name exclusion patterns of
+            \c event_rule matches the full name of the user
+            space tracepoint from which LTTng creates&nbsp;\lt_var{E}.
+
+            Set the event name exclusion patterns of
+            \c event_rule when you call
+            lttng_enable_event_with_exclusions().
+
+            Get the event name exclusion patterns of
+            a recording event rule descriptor with
+            lttng_event_get_exclusion_name_count() and
+            lttng_event_get_exclusion_name().
+
+          This condition is only meaningful when
+          \link lttng_event::type <code>event_rule.type</code>\endlink
+          is #LTTNG_EVENT_TRACEPOINT or
+          #LTTNG_EVENT_SYSCALL: it's always satisfied for the other
+          \ref api-rer-conds-inst-pt-type "instrumentation point types".
+
+          In all cases,
+          \link lttng_event::name <code>event_rule.name</code>\endlink
+          and the event name exclusion patterns of
+          \c event_rule are <em>globbing patterns</em>: the
+          <code>*</code> character means "match anything". To match a
+          literal <code>*</code> character, use <code>\\*</code>.
+      <tr>
+        <td>
+          \anchor api-rer-conds-ll
+          \ref api-rer-conds-ll "Instrumentation point log level"
+        <td>
+          An event&nbsp;\lt_var{E} satisfies the instrumentation point
+          log level condition of&nbsp;\lt_var{ER} if, depending on
+          \link lttng_event::loglevel_type <code>event_rule.loglevel_type</code>\endlink,
+          the log level of the LTTng user space tracepoint or
+          logging statement from which LTTng creates&nbsp;\lt_var{E}
+          is:
+
+          <dl>
+            <dt>#LTTNG_EVENT_LOGLEVEL_ALL
+            <dd>
+              Anything (the condition is always satisfied).
+
+            <dt>#LTTNG_EVENT_LOGLEVEL_RANGE
+            <dd>
+              At least as severe as
+              \link lttng_event::loglevel <code>event_rule.loglevel</code>\endlink.
+
+            <dt>#LTTNG_EVENT_LOGLEVEL_SINGLE
+            <dd>
+              Exactly
+              \link lttng_event::loglevel <code>event_rule.loglevel</code>\endlink.
+          </dl>
+
+          This condition is only meaningful when the \lt_obj_domain
+          containing&nbsp;\lt_var{ER} is \em not #LTTNG_DOMAIN_KERNEL:
+          it's always satisfied for #LTTNG_DOMAIN_KERNEL.
+      <tr>
+        <td>
+          \anchor api-rer-conds-filter
+          \ref api-rer-conds-filter "Event payload and context filter"
+        <td>
+          An event&nbsp;\lt_var{E} satisfies the event payload and
+          context filter condition of&nbsp;\lt_var{ER} if
+          \c event_rule has no filter expression or if its filter
+          expression \lt_var{EXPR} evaluates to \b true
+          when LTTng creates&nbsp;\lt_var{E}.
+
+          This condition is only meaningful when:
+
+          - The \lt_obj_domain containing&nbsp;\lt_var{ER} is
+            #LTTNG_DOMAIN_KERNEL or #LTTNG_DOMAIN_UST: it's always
+            satisfied for the other tracing domains.
+
+          - \link lttng_event::type <code>event_rule.type</code>\endlink
+            is #LTTNG_EVENT_TRACEPOINT or #LTTNG_EVENT_SYSCALL:
+            it's always satisfied for the other
+            \ref api-rer-conds-inst-pt-type "instrumentation point types".
+
+          Set the event payload and context filter expression of
+          \c event_rule when you call
+          lttng_enable_event_with_exclusions().
+
+          Get the event payload and context filter expression of
+          a recording event rule descriptor with
+          lttng_event_get_filter_expression().
+
+          \lt_var{EXPR} can contain references to the payload fields
+          of&nbsp;\lt_var{E} and to the current
+          \link #lttng_event_context_type context\endlink fields.
+
+          The expected syntax of \lt_var{EXPR} is similar to the syntax
+          of a C&nbsp;language conditional expression (an expression
+          which an \c if statement can evaluate), but there are a few
+          differences:
+
+          - A <code><em>NAME</em></code> expression identifies an event
+            payload field named <code><em>NAME</em></code> (a
+            C&nbsp;identifier).
+
+            Use the C&nbsp;language dot and square bracket notations to
+            access nested structure and array/sequence fields. You can
+            only use a constant, positive integer number within square
+            brackets. If the index is out of bounds, \lt_var{EXPR} is
+            \b false.
+
+            The value of an enumeration field is an integer.
+
+            When a field expression doesn't exist, \lt_var{EXPR} is
+            \b false.
+
+            Examples: <code>my_field</code>, <code>target_cpu</code>,
+            <code>seq[7]</code>, <code>msg.user[1].data[2][17]</code>.
+
+          - A <code>$ctx.<em>TYPE</em></code> expression identifies the
+            statically-known context field having the type
+            <code><em>TYPE</em></code> (a C&nbsp;identifier).
+
+            When a field expression doesn't exist, \lt_var{EXPR} is \b
+            false.
+
+            Examples: <code>$ctx.prio</code>,
+            <code>$ctx.preemptible</code>,
+            <code>$ctx.perf:cpu:stalled-cycles-frontend</code>.
+
+          - A <code>$app.<em>PROVIDER</em>:<em>TYPE</em></code>
+            expression identifies the application-specific context field
+            having the type <code><em>TYPE</em></code> (a
+            C&nbsp;identifier) from the provider
+            <code><em>PROVIDER</em></code> (a C&nbsp;identifier).
+
+            When a field expression doesn't exist, \lt_var{EXPR} is \b
+            false.
+
+            Example: <code>$app.server:cur_user</code>.
+
+          - Compare strings, either string fields or string literals
+            (double-quoted), with the <code>==</code> and
+            <code>!=</code> operators.
+
+            When comparing to a string literal, the <code>*</code>
+            character means "match anything". To match a literal
+            <code>*</code> character, use <code>\\*</code>.
+
+            Examples: <code>my_field&nbsp;==&nbsp;"user34"</code>,
+            <code>my_field&nbsp;==&nbsp;my_other_field</code>,
+            <code>my_field&nbsp;==&nbsp;"192.168.*"</code>.
+
+          - The
+            <a href="https://en.wikipedia.org/wiki/Order_of_operations">precedence table</a>
+            of the operators which are supported in
+            \lt_var{EXPR} is as follows. In this table, the highest
+            precedence is&nbsp;1:
+
+            <table>
+              <tr>
+                <th>Precedence
+                <th>Operator
+                <th>Description
+                <th>Associativity
+              <tr>
+                <td>1
+                <td><code>-</code>
+                <td>Unary minus
+                <td>Right-to-left
+              <tr>
+                <td>1
+                <td><code>+</code>
+                <td>Unary plus
+                <td>Right-to-left
+              <tr>
+                <td>1
+                <td><code>!</code>
+                <td>Logical NOT
+                <td>Right-to-left
+              <tr>
+                <td>1
+                <td><code>~</code>
+                <td>Bitwise NOT
+                <td>Right-to-left
+              <tr>
+                <td>2
+                <td><code>&lt;&lt;</code>
+                <td>Bitwise left shift
+                <td>Left-to-right
+              <tr>
+                <td>2
+                <td><code>&gt;&gt;</code>
+                <td>Bitwise right shift
+                <td>Left-to-right
+              <tr>
+                <td>3
+                <td><code>&amp;</code>
+                <td>Bitwise AND
+                <td>Left-to-right
+              <tr>
+                <td>4
+                <td><code>^</code>
+                <td>Bitwise XOR
+                <td>Left-to-right
+              <tr>
+                <td>5
+                <td><code>|</code>
+                <td>Bitwise OR
+                <td>Left-to-right
+              <tr>
+                <td>6
+                <td><code>&lt;</code>
+                <td>Less than
+                <td>Left-to-right
+              <tr>
+                <td>6
+                <td><code>&lt;=</code>
+                <td>Less than or equal to
+                <td>Left-to-right
+              <tr>
+                <td>6
+                <td><code>&gt;</code>
+                <td>Greater than
+                <td>Left-to-right
+              <tr>
+                <td>6
+                <td><code>&gt;=</code>
+                <td>Greater than or equal to
+                <td>Left-to-right
+              <tr>
+                <td>7
+                <td><code>==</code>
+                <td>Equal to
+                <td>Left-to-right
+              <tr>
+                <td>7
+                <td><code>!=</code>
+                <td>Not equal to
+                <td>Left-to-right
+              <tr>
+                <td>8
+                <td><code>&amp;&amp;</code>
+                <td>Logical AND
+                <td>Left-to-right
+              <tr>
+                <td>9
+                <td><code>||</code>
+                <td>Logical OR
+                <td>Left-to-right
+            </table>
+
+            Parentheses are supported to bypass the default order.
+
+            @attention
+                Unlike the C&nbsp;language, the bitwise AND and OR
+                operators (<code>&amp;</code> and <code>|</code>) in
+                \lt_var{EXPR} take precedence over relational
+                operators (<code>&lt;&lt;</code>, <code>&lt;=</code>,
+                <code>&gt;</code>, <code>&gt;=</code>, <code>==</code>,
+                and <code>!=</code>). This means the expression
+                <code>2&nbsp;&&nbsp;2&nbsp;==&nbsp;2</code>
+                is \b true while the equivalent C&nbsp;expression
+                is \b false.
+
+            The arithmetic operators are :not: supported.
+
+            LTTng first casts all integer constants and fields to signed
+            64-bit integers. The representation of negative integers is
+            two's complement. This means that, for example, the signed
+            8-bit integer field 0xff (-1) becomes 0xffffffffffffffff
+            (still&nbsp;-1) once casted.
+
+            Before a bitwise operator is applied, LTTng casts all its
+            operands to unsigned 64-bit integers, and then casts the
+            result back to a signed 64-bit integer. For the bitwise NOT
+            operator, it's the equivalent of this C&nbsp;expression:
+
+            @code
+            (int64_t) ~((uint64_t) val)
+            @endcode
+
+            For the binary bitwise operators, it's the equivalent of those
+            C&nbsp;expressions:
+
+            @code
+            (int64_t) ((uint64_t) lhs >> (uint64_t) rhs)
+            (int64_t) ((uint64_t) lhs << (uint64_t) rhs)
+            (int64_t) ((uint64_t) lhs & (uint64_t) rhs)
+            (int64_t) ((uint64_t) lhs ^ (uint64_t) rhs)
+            (int64_t) ((uint64_t) lhs | (uint64_t) rhs)
+            @endcode
+
+            If the right-hand side of a bitwise shift operator
+            (<code>&lt;&lt;</code> and <code>&gt;&gt;</code>) is not in
+            the [0,&nbsp;63] range, then \lt_var{EXPR} is \b false.
+
+          @note
+              See the \ref api_pais to allow or disallow processes to
+              record LTTng events based on their attributes
+              instead of using equivalent statically-known context
+              fields in \lt_var{EXPR} like <code>$ctx.pid</code>.
+              The former method is much more efficient.
+
+          \lt_var{EXPR} examples:
+
+          @code{.unparsed}
+          msg_id == 23 && size >= 2048
+          @endcode
+
+          @code{.unparsed}
+          $ctx.procname == "lttng*" && (!flag || poel < 34)
+          @endcode
+
+          @code{.unparsed}
+          $app.my_provider:my_context == 17.34e9 || some_enum >= 14
+          @endcode
+
+          @code{.unparsed}
+          $ctx.cpu_id == 2 && filename != "*.log"
+          @endcode
+
+          @code{.unparsed}
+          eax_reg & 0xff7 == 0x240 && x[4] >> 12 <= 0x1234
+          @endcode
+    </table>
+
+  <dt>Implicit conditions
+  <dd>
+    - \lt_var{ER} itself is \link lttng_event::enabled enabled\endlink.
+
+      A recording event rule is enabled on
+      \link lttng_enable_event_with_exclusions() creation\endlink.
+
+      @sa lttng_enable_event() --
+          Creates or enables a recording event rule.
+      @sa lttng_disable_event_ext() --
+          Disables a recording event rule.
+
+    - The \lt_obj_channel which contains&nbsp;\lt_var{ER} is
+      \link lttng_channel::enabled enabled\endlink.
+
+      A channel is enabled on
+      \link lttng_enable_channel() creation\endlink.
+
+      @sa lttng_enable_channel() --
+          Creates or enables a channel.
+      @sa lttng_disable_channel() --
+          Disables a channel.
+
+    - The \lt_obj_session which contains&nbsp;\lt_var{ER} is
+      \link lttng_session::enabled active\endlink (started).
+
+      A recording session is inactive (stopped) on
+      \link lttng_create_session_ext() creation\endlink.
+
+      @sa lttng_start_tracing() --
+          Starts a recording session.
+      @sa lttng_stop_tracing() --
+          Stops a recording session.
+
+    - The process for which LTTng creates&nbsp;\lt_var{E} is
+      \ref api_pais "allowed to record events".
+
+      All processes are allowed to record events on recording session
+      \link lttng_create_session_ext() creation\endlink.
+</dl>
+
+<h1>\anchor api-rer-er-name Event record name</h1>
+
+When LTTng records an event&nbsp;\lt_var{E}, the resulting event record
+has a name which depends on the
+\ref api-rer-conds-inst-pt-type "instrumentation point type condition"
+of the recording event rule&nbsp;\lt_var{ER} which matched&nbsp;\lt_var{E}
+as well as on the \lt_obj_domain which contains&nbsp;\lt_var{ER}:
+
+<table>
+  <tr>
+    <th>Tracing domain
+    <th>Instrumentation point type
+    <th>Event record name
+  <tr>
+    <td>#LTTNG_DOMAIN_KERNEL or #LTTNG_DOMAIN_UST
+    <td>#LTTNG_EVENT_TRACEPOINT
+    <td>
+      Full name of the tracepoint from which LTTng creates&nbsp;\lt_var{E}.
+
+      Note that the full name of a
+      \link #LTTNG_DOMAIN_UST user space\endlink tracepoint is
+      <code><em>PROVIDER</em>:<em>NAME</em></code>, where
+      <code><em>PROVIDER</em></code> is the tracepoint provider name and
+      <code><em>NAME</em></code> is the tracepoint name.
+  <tr>
+    <td>#LTTNG_DOMAIN_JUL
+    <td>#LTTNG_EVENT_TRACEPOINT
+    <td>
+      <code>lttng_jul:event</code>
+
+      Such an event record has a string field <code>logger_name</code>
+      which contains the name of the <code>java.util.logging</code>
+      logger from which LTTng creates&nbsp;\lt_var{E}.
+  <tr>
+    <td>#LTTNG_DOMAIN_LOG4J
+    <td>#LTTNG_EVENT_TRACEPOINT
+    <td>
+      <code>lttng_log4j:event</code>
+
+      Such an event record has a string field <code>logger_name</code>
+      which contains the name of the Apache log4j logger from which
+      LTTng creates&nbsp;\lt_var{E}.
+  <tr>
+    <td>#LTTNG_DOMAIN_PYTHON
+    <td>#LTTNG_EVENT_TRACEPOINT
+    <td>
+      <code>lttng_python:event</code>
+
+      Such an event record has a string field <code>logger_name</code>
+      which contains the name of the Python logger from which LTTng
+      creates&nbsp;\lt_var{E}.
+  <tr>
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>#LTTNG_EVENT_SYSCALL
+    <td>
+      Location:
+
+      <dl>
+        <dt>Entry
+        <dd>
+          <code>syscall_entry_<em>NAME</em></code>, where
+          <code><em>NAME</em></code> is the name of the system call from
+          which LTTng creates&nbsp;\lt_var{E}, without any
+          <code>sys_</code> prefix.
+
+        <dt>Exit
+        <dd>
+          <code>syscall_exit_<em>NAME</em></code>, where
+          <code><em>NAME</em></code> is the name of the system call from
+          which LTTng creates&nbsp;\lt_var{E}, without any
+          <code>sys_</code> prefix.
+      </dl>
+  <tr>
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>#LTTNG_EVENT_PROBE or  #LTTNG_EVENT_USERSPACE_PROBE
+    <td>
+      The lttng_event::name member of the
+      descriptor you used to create \lt_var{ER} with
+      lttng_enable_event_with_exclusions().
+  <tr>
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>#LTTNG_EVENT_FUNCTION
+    <td>
+      Location:
+
+      <dl>
+        <dt>Entry
+        <dd><code><em>NAME</em>_entry</code>
+
+        <dt>Exit
+        <dd><code><em>NAME</em>_exit</code>
+      </dl>
+
+      where <code><em>NAME</em></code> is the lttng_event::name member
+      of the descriptor you used to create
+      \lt_var{ER} with lttng_enable_event_with_exclusions().
+</table>
+
+@defgroup api_pais Process attribute inclusion set API
+@ingroup api_session
+
+To be done.
+
+@defgroup api_session_clear Recording session clearing API
+@ingroup api_session
+
+This API makes it possible to clear a \lt_obj_session, that is, to
+delete the contents of its tracing buffers and/or of all its
+\ref api-session-local-mode "local" and
+\ref api-session-net-mode "streamed" trace data.
+
+To clear a recording session:
+
+-# Call lttng_clear_session(), passing the name of the recording session
+   to clear.
+
+   This function initiates a clearing operation, returning immediately.
+
+   This function can set a pointer to a
+   \link #lttng_clear_handle clearing handle\endlink
+   so that you can wait for the completion of the
+   operation. Without such a handle, you can't know when the clearing
+   operation completes and whether or not it does successfully.
+
+-# <strong>If you have a clearing handle from step&nbsp;1</strong>:
+
+   -# Call lttng_clear_handle_wait_for_completion() to wait for the
+      completion of the clearing operation.
+
+   -# Call lttng_clear_handle_get_result() to get whether or not the
+      clearing operation successfully completed.
+
+   -# Destroy the clearing handle with lttng_clear_handle_destroy().
+
+@sa \lt_man{lttng-clear,1}
+
+@defgroup api_session_snapshot Recording session snapshot API
+@ingroup api_session
+
+To be done.
+
+@defgroup api_session_rotation Recording session rotation API
+@ingroup api_session
+
+To be done.
+
+@defgroup api_session_save_load Recording session saving and loading API
+@ingroup api_session
+
+To be done.
+
+@defgroup api_inst_pt Instrumentation point listing API
+
+The lttng_list_tracepoints() and lttng_list_syscalls() functions set a
+pointer to an array of
+<strong><em>\ref api-rer-inst-pt-descr "instrumentation point descriptors"</em></strong>.
+
+With those two functions, you can get details about the available
+LTTng tracepoints, Java/Python loggers, and Linux kernel system calls,
+as long as you can
+\ref api-gen-sessiond-conn "connect to a session daemon".
+You can then use the discovered information to create corresponding
+\lt_obj_rers so that you can record the events
+which LTTng creates from instrumentation points.
+
+See \ref api_rer to learn more about instrumentation points, events,
+event records, and recording event rules.
+
+@defgroup api_trigger Trigger API
+
+To be done.
+
+@defgroup api_trigger_cond Trigger condition API
+@ingroup api_trigger
+
+To be done.
+
+@defgroup api_trigger_cond_er_matches "Event rule matches" trigger condition API
+@ingroup api_trigger_cond
+
+To be done.
+
+@defgroup api_er Event rule API
+@ingroup api_trigger_cond_er_matches
+
+To be done.
+
+@defgroup api_ll_rule Log level rule API
+@ingroup api_er
+
+To be done.
+
+@defgroup api_ev_expr Event expression API
+@ingroup api_trigger_cond_er_matches
+
+To be done.
+
+@defgroup api_ev_field_val Event field value API
+@ingroup api_trigger_cond_er_matches
+
+To be done.
+
+@defgroup api_trigger_action Trigger action API
+@ingroup api_trigger
+
+To be done.
+
+@defgroup api_notif Notification API
+@ingroup api_trigger_action
+
+To be done.
+
+@defgroup api_error Error query API
+
+To be done.
+*/
diff --git a/doc/api/liblttng-ctl/images/concepts.png b/doc/api/liblttng-ctl/images/concepts.png
new file mode 100644 (file)
index 0000000..b0977be
Binary files /dev/null and b/doc/api/liblttng-ctl/images/concepts.png differ
diff --git a/doc/api/liblttng-ctl/images/event-rule.png b/doc/api/liblttng-ctl/images/event-rule.png
new file mode 100644 (file)
index 0000000..9c05ecf
Binary files /dev/null and b/doc/api/liblttng-ctl/images/event-rule.png differ
diff --git a/doc/api/liblttng-ctl/images/live.png b/doc/api/liblttng-ctl/images/live.png
new file mode 100644 (file)
index 0000000..1ab2420
Binary files /dev/null and b/doc/api/liblttng-ctl/images/live.png differ
diff --git a/doc/api/liblttng-ctl/images/many-sessions.png b/doc/api/liblttng-ctl/images/many-sessions.png
new file mode 100644 (file)
index 0000000..447248a
Binary files /dev/null and b/doc/api/liblttng-ctl/images/many-sessions.png differ
diff --git a/doc/api/liblttng-ctl/images/per-process-buffering-root.png b/doc/api/liblttng-ctl/images/per-process-buffering-root.png
new file mode 100644 (file)
index 0000000..c028cc7
Binary files /dev/null and b/doc/api/liblttng-ctl/images/per-process-buffering-root.png differ
diff --git a/doc/api/liblttng-ctl/images/per-process-buffering.png b/doc/api/liblttng-ctl/images/per-process-buffering.png
new file mode 100644 (file)
index 0000000..a2c9850
Binary files /dev/null and b/doc/api/liblttng-ctl/images/per-process-buffering.png differ
diff --git a/doc/api/liblttng-ctl/images/per-user-buffering-root.png b/doc/api/liblttng-ctl/images/per-user-buffering-root.png
new file mode 100644 (file)
index 0000000..aa7ff2a
Binary files /dev/null and b/doc/api/liblttng-ctl/images/per-user-buffering-root.png differ
diff --git a/doc/api/liblttng-ctl/images/per-user-buffering.png b/doc/api/liblttng-ctl/images/per-user-buffering.png
new file mode 100644 (file)
index 0000000..cb83d21
Binary files /dev/null and b/doc/api/liblttng-ctl/images/per-user-buffering.png differ
diff --git a/doc/api/liblttng-ctl/images/plumbing.png b/doc/api/liblttng-ctl/images/plumbing.png
new file mode 100644 (file)
index 0000000..00797e5
Binary files /dev/null and b/doc/api/liblttng-ctl/images/plumbing.png differ
diff --git a/doc/api/liblttng-ctl/images/rotation.png b/doc/api/liblttng-ctl/images/rotation.png
new file mode 100644 (file)
index 0000000..66f5c42
Binary files /dev/null and b/doc/api/liblttng-ctl/images/rotation.png differ
diff --git a/doc/api/liblttng-ctl/images/snapshot.png b/doc/api/liblttng-ctl/images/snapshot.png
new file mode 100644 (file)
index 0000000..c004d1f
Binary files /dev/null and b/doc/api/liblttng-ctl/images/snapshot.png differ
diff --git a/doc/api/liblttng-ctl/style.css b/doc/api/liblttng-ctl/style.css
new file mode 100644 (file)
index 0000000..25b69ce
--- /dev/null
@@ -0,0 +1,109 @@
+.contents h1,
+.contents h2:not(.groupheader),
+.contents h3 {
+    color: #6A2F43;
+}
+
+.contents h1,
+.contents h2:not(.groupheader) {
+    border-bottom: 1px solid #ccc;
+    display: inline-block;
+}
+
+.contents h1 {
+    font-size: 1.5em;
+    margin-top: 2em;
+}
+
+.contents h2:not(.groupheader) {
+    font-size: 1.2em;
+    margin-top: 1.5em;
+}
+
+.contents dl {
+    margin-left: 2em;
+}
+
+.contents dl.params,
+.contents dl.section,
+.contents dl.retval,
+.contents dl.exception,
+.contents dl.tparams {
+    margin-left: 0;
+}
+
+.contents .image {
+    background-color: rgba(0, 0, 0, .05);
+    padding-top: 1em;
+    padding-bottom: 1em;
+}
+
+.contents .image img {
+    border: 1px solid #ccc;
+    background-color: white;
+    padding: 1em;
+}
+
+.contents .image .caption {
+    font-size: 75%;
+}
+
+.contents .fragment {
+    padding: 1em;
+}
+
+#projectname {
+    font-size: 200%;
+}
+
+#projectbrief {
+    display: none;
+}
+
+code.lt-param,
+table.params .paramname {
+    color: #602020;
+    font-weight: bold;
+    font-family: monospace;
+    font-size: 90%;
+}
+
+th > code.lt-param {
+    color: white;
+}
+
+.contents dl.attention {
+    background-color: #fbdfda;
+    padding-top: 1em;
+    padding-bottom: 1em;
+}
+
+.contents table.doxtable th {
+    background-color: #5173b3;
+}
+
+.contents table.doxtable td {
+    vertical-align: top;
+}
+
+.contents p.intertd {
+    font-weight: normal;
+}
+
+.contents td > code:not(.lt-param),
+.contents p > code:not(.lt-param),
+.contents dt > code:not(.lt-param),
+.contents dd > code:not(.lt-param),
+.contents li > code:not(.lt-param) {
+    background-color: rgba(0, 0, 0, .05);
+    padding-left: .2em;
+    padding-right: .2em;
+    border-radius: .25em;
+    border: .1em solid rgba(0, 0, 0, .1)
+}
+
+.contents .lt-var {
+    font-style: italic;
+    font-family: serif;
+    font-size: 1.1em;
+}
index a5ee70da326c2181d8133af103e7d83eb57ecc6d..1f9070a04138f24672ba6534242b561dfdc6f943 100644 (file)
@@ -32,6 +32,8 @@
  */
 
 #include <lttng/lttng.h>
+
+#include <assert.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -44,7 +46,10 @@ static volatile int quit = 0;
 
 static void sighandler(int signal __attribute__((unused)))
 {
-       printf("Signal caught, exiting\n");
+       const char msg[] = "Signal caught, exiting\n";
+       const int ret = write(STDOUT_FILENO, msg, sizeof(msg));
+
+       assert(ret == 0); /* NOLINT assert is not async signal safe */
        quit = 1;
 }
 
@@ -76,8 +81,7 @@ static int setup_session(const char *session_name, const char *path)
        strcpy(ev.name, "*");
        ev.loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
 
-       ret = lttng_enable_event_with_exclusions(
-                       chan_handle, &ev, "mychan", NULL, 0, NULL);
+       ret = lttng_enable_event_with_exclusions(chan_handle, &ev, "mychan", NULL, 0, NULL);
        if (ret < 0) {
                fprintf(stderr, "Failed to enable events (ret = %i)\n", ret);
                goto end;
@@ -153,16 +157,14 @@ static int rotate_session(const char *session_name, const char *ext_program)
 
        ret = lttng_rotate_session(session_name, NULL, &handle);
        if (ret < 0) {
-               fprintf(stderr, "Failed to rotate session, %s\n",
-                               lttng_strerror(ret));
+               fprintf(stderr, "Failed to rotate session, %s\n", lttng_strerror(ret));
                goto end;
        }
 
        fflush(stdout);
 
        do {
-               rotation_status = lttng_rotation_handle_get_state(
-                               handle, &rotation_state);
+               rotation_status = lttng_rotation_handle_get_state(handle, &rotation_state);
                if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
                        ret = -1;
                        fprintf(stderr, "Failed to get the current rotation's state\n");
@@ -189,27 +191,24 @@ static int rotate_session(const char *session_name, const char *ext_program)
                const char *absolute_path;
                enum lttng_trace_archive_location_status location_status;
 
-               rotation_status = lttng_rotation_handle_get_archive_location(
-                               handle, &location);
+               rotation_status = lttng_rotation_handle_get_archive_location(handle, &location);
                if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
-                       fprintf(stderr, "Failed to retrieve the rotation's completed chunk archive location\n");
+                       fprintf(stderr,
+                               "Failed to retrieve the rotation's completed chunk archive location\n");
                        ret = -1;
                        goto end;
                }
 
-               location_status =
-                               lttng_trace_archive_location_local_get_absolute_path(
-                                               location, &absolute_path);
+               location_status = lttng_trace_archive_location_local_get_absolute_path(
+                       location, &absolute_path);
                if (location_status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        fprintf(stderr, "Failed to get absolute path of completed chunk archive");
                        ret = -1;
                        goto end;
                }
 
-               printf("Output files of session %s rotated to %s\n",
-                               session_name, absolute_path);
-               ret = snprintf(cmd, PATH_MAX, "%s %s", ext_program,
-                               absolute_path);
+               printf("Output files of session %s rotated to %s\n", session_name, absolute_path);
+               ret = snprintf(cmd, PATH_MAX, "%s %s", ext_program, absolute_path);
                if (ret < 0) {
                        fprintf(stderr, "Failed to prepare command string\n");
                        goto end;
@@ -219,20 +218,22 @@ static int rotate_session(const char *session_name, const char *ext_program)
        }
        case LTTNG_ROTATION_STATE_EXPIRED:
                printf("Output files of session %s rotated, but the handle expired\n",
-                               session_name);
+                      session_name);
                ret = 0;
                goto end;
        case LTTNG_ROTATION_STATE_ERROR:
-               fprintf(stderr, "An error occurred with the rotation of session %s\n",
-                               session_name);
+               fprintf(stderr,
+                       "An error occurred with the rotation of session %s\n",
+                       session_name);
                ret = -1;
                goto end;
        case LTTNG_ROTATION_STATE_ONGOING:
                abort();
                goto end;
        case LTTNG_ROTATION_STATE_NO_ROTATION:
-               fprintf(stderr, "No rotation was performed on rotation request for session %s\n",
-                               session_name);
+               fprintf(stderr,
+                       "No rotation was performed on rotation request for session %s\n",
+                       session_name);
                ret = -1;
                goto end;
        }
@@ -260,16 +261,15 @@ end:
 
 static void usage(const char *prog_name)
 {
-       fprintf(stderr, "Usage: %s <session-name> <delay-sec> <nr-rotate> <program>\n",
-                       prog_name);
+       fprintf(stderr, "Usage: %s <session-name> <delay-sec> <nr-rotate> <program>\n", prog_name);
        fprintf(stderr, "  <session-name>: the name of the session you want to create\n");
        fprintf(stderr, "  <delay-sec>: the delay in seconds between each rotation\n");
        fprintf(stderr,
-                       "  <nr-rotate>: the number of rotation you want to perform, "
-                       "-1 for infinite until ctrl-c\n");
+               "  <nr-rotate>: the number of rotation you want to perform, "
+               "-1 for infinite until ctrl-c\n");
        fprintf(stderr,
-                       "  <program>: program to run on each chunk, it must be "
-                       "executable, and expect a trace folder as only argument\n");
+               "  <program>: program to run on each chunk, it must be "
+               "executable, and expect a trace folder as only argument\n");
        fprintf(stderr, "\nThe trace folder is deleted when this program completes.\n");
 }
 
index 465b4a123c6646f497614fa16dfe4c17a06315d2..6148d1c090d3abd298e514accf94292ff35dd4d4 100644 (file)
@@ -8,6 +8,7 @@
 #include "tracepoint-trigger-example.h"
 
 #include <lttng/tracepoint.h>
+
 #include <stdio.h>
 #include <sys/time.h>
 #include <time.h>
@@ -25,10 +26,10 @@ int main(void)
                gettimeofday(&tv, NULL);
                the_time = tv.tv_sec;
 
-               strftime(time_str, sizeof(time_str), "[%m-%d-%Y] %T",
-                               localtime(&the_time));
+               strftime(time_str, sizeof(time_str), "[%m-%d-%Y] %T", localtime(&the_time));
                printf("%s.%ld - Tracing event \"trigger_example:my_event\"\n",
-                               time_str, tv.tv_usec);
+                      time_str,
+                      tv.tv_usec);
 
                tracepoint(trigger_example, my_event, i);
                sleep(2);
index bce5d815d991590bde3a54ce60f0fde228894f29..05c7387c2417e850f9be61a1517bea50a01a4cb2 100644 (file)
@@ -5,6 +5,8 @@
  *
  */
 
+#include <common/macros.hpp>
+
 #include <lttng/lttng.h>
 
 #include <inttypes.h>
 #include <sys/time.h>
 #include <time.h>
 
-#include <common/macros.hpp>
-
 static int print_capture(const struct lttng_condition *condition,
-               const struct lttng_event_field_value *capture,
-               unsigned int indent_level);
+                        const struct lttng_event_field_value *capture,
+                        unsigned int indent_level);
 static int print_array(const struct lttng_condition *condition,
-               const struct lttng_event_field_value *array,
-               unsigned int indent_level);
+                      const struct lttng_event_field_value *array,
+                      unsigned int indent_level);
 
 static void indent(unsigned int indentation_level)
 {
@@ -44,8 +44,7 @@ static void print_one_event_expr(const struct lttng_event_expr *event_expr)
        {
                const char *name;
 
-               name = lttng_event_expr_event_payload_field_get_name(
-                               event_expr);
+               name = lttng_event_expr_event_payload_field_get_name(event_expr);
                printf("%s", name);
 
                break;
@@ -55,8 +54,7 @@ static void print_one_event_expr(const struct lttng_event_expr *event_expr)
        {
                const char *name;
 
-               name = lttng_event_expr_channel_context_field_get_name(
-                               event_expr);
+               name = lttng_event_expr_channel_context_field_get_name(event_expr);
                printf("$ctx.%s", name);
 
                break;
@@ -67,10 +65,9 @@ static void print_one_event_expr(const struct lttng_event_expr *event_expr)
                const char *provider_name;
                const char *type_name;
 
-               provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(
-                               event_expr);
-               type_name = lttng_event_expr_app_specific_context_field_get_type_name(
-                               event_expr);
+               provider_name =
+                       lttng_event_expr_app_specific_context_field_get_provider_name(event_expr);
+               type_name = lttng_event_expr_app_specific_context_field_get_type_name(event_expr);
 
                printf("$app.%s:%s", provider_name, type_name);
 
@@ -83,14 +80,12 @@ static void print_one_event_expr(const struct lttng_event_expr *event_expr)
                const struct lttng_event_expr *parent_expr;
                enum lttng_event_expr_status status;
 
-               parent_expr = lttng_event_expr_array_field_element_get_parent_expr(
-                               event_expr);
-               LTTNG_ASSERT(parent_expr != NULL);
+               parent_expr = lttng_event_expr_array_field_element_get_parent_expr(event_expr);
+               LTTNG_ASSERT(parent_expr != nullptr);
 
                print_one_event_expr(parent_expr);
 
-               status = lttng_event_expr_array_field_element_get_index(
-                               event_expr, &index);
+               status = lttng_event_expr_array_field_element_get_index(event_expr, &index);
                LTTNG_ASSERT(status == LTTNG_EVENT_EXPR_STATUS_OK);
 
                printf("[%u]", index);
@@ -103,12 +98,10 @@ static void print_one_event_expr(const struct lttng_event_expr *event_expr)
        }
 }
 
-static bool action_group_contains_notify(
-               const struct lttng_action *action_group)
+static bool action_group_contains_notify(const struct lttng_action *action_group)
 {
        unsigned int i, count;
-       enum lttng_action_status status =
-                       lttng_action_list_get_count(action_group, &count);
+       enum lttng_action_status status = lttng_action_list_get_count(action_group, &count);
 
        if (status != LTTNG_ACTION_STATUS_OK) {
                printf("Failed to get action count from action group\n");
@@ -116,10 +109,8 @@ static bool action_group_contains_notify(
        }
 
        for (i = 0; i < count; i++) {
-               const struct lttng_action *action =
-                               lttng_action_list_get_at_index(action_group, i);
-               const enum lttng_action_type action_type =
-                               lttng_action_get_type(action);
+               const struct lttng_action *action = lttng_action_list_get_at_index(action_group, i);
+               const enum lttng_action_type action_type = lttng_action_get_type(action);
 
                if (action_type == LTTNG_ACTION_TYPE_NOTIFY) {
                        return true;
@@ -129,22 +120,21 @@ static bool action_group_contains_notify(
 }
 
 static int print_capture(const struct lttng_condition *condition,
-               const struct lttng_event_field_value *capture,
-               unsigned int indent_level)
+                        const struct lttng_event_field_value *capture,
+                        unsigned int indent_level)
 {
        int ret = 0;
        enum lttng_event_field_value_status event_field_status;
        uint64_t u_val;
        int64_t s_val;
        double d_val;
-       const char *string_val = NULL;
+       const char *string_val = nullptr;
 
        switch (lttng_event_field_value_get_type(capture)) {
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT:
        {
                event_field_status =
-                               lttng_event_field_value_unsigned_int_get_value(
-                                               capture, &u_val);
+                       lttng_event_field_value_unsigned_int_get_value(capture, &u_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -155,9 +145,7 @@ static int print_capture(const struct lttng_condition *condition,
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT:
        {
-               event_field_status =
-                               lttng_event_field_value_signed_int_get_value(
-                                               capture, &s_val);
+               event_field_status = lttng_event_field_value_signed_int_get_value(capture, &s_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -169,8 +157,7 @@ static int print_capture(const struct lttng_condition *condition,
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM:
        {
                event_field_status =
-                               lttng_event_field_value_unsigned_int_get_value(
-                                               capture, &u_val);
+                       lttng_event_field_value_unsigned_int_get_value(capture, &u_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -181,9 +168,7 @@ static int print_capture(const struct lttng_condition *condition,
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM:
        {
-               event_field_status =
-                               lttng_event_field_value_signed_int_get_value(
-                                               capture, &s_val);
+               event_field_status = lttng_event_field_value_signed_int_get_value(capture, &s_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -194,8 +179,7 @@ static int print_capture(const struct lttng_condition *condition,
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_REAL:
        {
-               event_field_status = lttng_event_field_value_real_get_value(
-                               capture, &d_val);
+               event_field_status = lttng_event_field_value_real_get_value(capture, &d_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -206,8 +190,7 @@ static int print_capture(const struct lttng_condition *condition,
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_STRING:
        {
-               event_field_status = lttng_event_field_value_string_get_value(
-                               capture, &string_val);
+               event_field_status = lttng_event_field_value_string_get_value(capture, &string_val);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        ret = 1;
                        goto end;
@@ -233,31 +216,30 @@ end:
        return ret;
 }
 
-static void print_unavailabe(void)
+static void print_unavailabe()
 {
        printf("Capture unavailable");
 }
 
 static int print_array(const struct lttng_condition *condition,
-               const struct lttng_event_field_value *array,
-               unsigned int indent_level)
+                      const struct lttng_event_field_value *array,
+                      unsigned int indent_level)
 {
        int ret = 0;
        enum lttng_event_field_value_status event_field_status;
        unsigned int captured_field_count;
 
-       event_field_status = lttng_event_field_value_array_get_length(
-                       array, &captured_field_count);
+       event_field_status = lttng_event_field_value_array_get_length(array, &captured_field_count);
        if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                ret = 1;
                goto end;
        }
 
        for (unsigned int i = 0; i < captured_field_count; i++) {
-               const struct lttng_event_field_value *captured_field = NULL;
+               const struct lttng_event_field_value *captured_field = nullptr;
                const struct lttng_event_expr *expr =
-                               lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-                                               condition, i);
+                       lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
+                               condition, i);
                LTTNG_ASSERT(expr);
 
                indent(indent_level + 1);
@@ -266,20 +248,17 @@ static int print_array(const struct lttng_condition *condition,
                print_one_event_expr(expr);
                printf(" Value: ");
 
-               event_field_status =
-                               lttng_event_field_value_array_get_element_at_index(
-                                               array, i, &captured_field);
+               event_field_status = lttng_event_field_value_array_get_element_at_index(
+                       array, i, &captured_field);
                if (event_field_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
-                       if (event_field_status ==
-                                       LTTNG_EVENT_FIELD_VALUE_STATUS_UNAVAILABLE) {
+                       if (event_field_status == LTTNG_EVENT_FIELD_VALUE_STATUS_UNAVAILABLE) {
                                print_unavailabe();
                        } else {
                                ret = 1;
                                goto end;
                        }
                } else {
-                       print_capture(condition, captured_field,
-                                       indent_level + 1);
+                       print_capture(condition, captured_field, indent_level + 1);
                }
 
                if (i + 1 < captured_field_count) {
@@ -297,25 +276,21 @@ end:
 static int print_captures(struct lttng_notification *notification)
 {
        int ret = 0;
-       const struct lttng_evaluation *evaluation =
-                       lttng_notification_get_evaluation(notification);
-       const struct lttng_condition *condition =
-                       lttng_notification_get_condition(notification);
+       const struct lttng_evaluation *evaluation = lttng_notification_get_evaluation(notification);
+       const struct lttng_condition *condition = lttng_notification_get_condition(notification);
 
        /* Status */
        enum lttng_condition_status condition_status;
        enum lttng_evaluation_event_rule_matches_status evaluation_status;
 
-       const struct lttng_event_field_value *captured_field_array = NULL;
+       const struct lttng_event_field_value *captured_field_array = nullptr;
        unsigned int expected_capture_field_count;
 
        LTTNG_ASSERT(lttng_evaluation_get_type(evaluation) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       condition_status =
-                       lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                                       condition,
-                                       &expected_capture_field_count);
+       condition_status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
+               condition, &expected_capture_field_count);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                ret = 1;
                goto end;
@@ -326,9 +301,8 @@ static int print_captures(struct lttng_notification *notification)
                goto end;
        }
 
-       evaluation_status =
-                       lttng_evaluation_event_rule_matches_get_captured_values(
-                                       evaluation, &captured_field_array);
+       evaluation_status = lttng_evaluation_event_rule_matches_get_captured_values(
+               evaluation, &captured_field_array);
        if (evaluation_status != LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_OK) {
                ret = 1;
                goto end;
@@ -343,10 +317,8 @@ end:
 static int print_notification(struct lttng_notification *notification)
 {
        int ret = 0;
-       const struct lttng_evaluation *evaluation =
-                       lttng_notification_get_evaluation(notification);
-       const enum lttng_condition_type type =
-                       lttng_evaluation_get_type(evaluation);
+       const struct lttng_evaluation *evaluation = lttng_notification_get_evaluation(notification);
+       const enum lttng_condition_type type = lttng_evaluation_get_type(evaluation);
 
        switch (type) {
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
@@ -369,13 +341,12 @@ static int print_notification(struct lttng_notification *notification)
                char time_str[64];
                struct timeval tv;
                time_t the_time;
-               const struct lttng_trigger *trigger = NULL;
+               const struct lttng_trigger *trigger = nullptr;
 
-               gettimeofday(&tv, NULL);
+               gettimeofday(&tv, nullptr);
                the_time = tv.tv_sec;
 
-               strftime(time_str, sizeof(time_str), "[%m-%d-%Y] %T",
-                               localtime(&the_time));
+               strftime(time_str, sizeof(time_str), "[%m-%d-%Y] %T", localtime(&the_time));
                printf("%s.%ld - ", time_str, tv.tv_usec);
 
                trigger = lttng_notification_get_trigger(notification);
@@ -391,7 +362,7 @@ static int print_notification(struct lttng_notification *notification)
                }
 
                printf("Received notification of event rule matches trigger \"%s\"\n",
-                               trigger_name);
+                      trigger_name);
                ret = print_captures(notification);
                break;
        }
@@ -406,10 +377,10 @@ end:
 int main(int argc, char **argv)
 {
        int ret;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int count, i, j, subcription_count = 0, trigger_count;
        enum lttng_trigger_status trigger_status;
-       struct lttng_notification_channel *notification_channel = NULL;
+       struct lttng_notification_channel *notification_channel = nullptr;
 
        if (argc < 2) {
                fprintf(stderr, "Missing trigger name(s)\n");
@@ -420,8 +391,8 @@ int main(int argc, char **argv)
 
        trigger_count = argc - 1;
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        if (!notification_channel) {
                fprintf(stderr, "Failed to create notification channel\n");
                ret = -1;
@@ -442,16 +413,13 @@ int main(int argc, char **argv)
        }
 
        for (i = 0; i < count; i++) {
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
                const struct lttng_condition *condition =
-                               lttng_trigger_get_const_condition(trigger);
-               const struct lttng_action *action =
-                               lttng_trigger_get_const_action(trigger);
-               const enum lttng_action_type action_type =
-                               lttng_action_get_type(action);
+                       lttng_trigger_get_const_condition(trigger);
+               const struct lttng_action *action = lttng_trigger_get_const_action(trigger);
+               const enum lttng_action_type action_type = lttng_action_get_type(action);
                enum lttng_notification_channel_status channel_status;
-               const char *trigger_name = NULL;
+               const char *trigger_name = nullptr;
                bool subscribe = false;
 
                lttng_trigger_get_name(trigger, &trigger_name);
@@ -467,28 +435,27 @@ int main(int argc, char **argv)
                }
 
                if (!((action_type == LTTNG_ACTION_TYPE_LIST &&
-                                     action_group_contains_notify(action)) ||
-                                   action_type == LTTNG_ACTION_TYPE_NOTIFY)) {
+                      action_group_contains_notify(action)) ||
+                     action_type == LTTNG_ACTION_TYPE_NOTIFY)) {
                        printf("The action of trigger \"%s\" is not \"notify\", skipping.\n",
-                                       trigger_name);
+                              trigger_name);
                        continue;
                }
 
-               channel_status = lttng_notification_channel_subscribe(
-                               notification_channel, condition);
-               if (channel_status ==
-                               LTTNG_NOTIFICATION_CHANNEL_STATUS_ALREADY_SUBSCRIBED) {
+               channel_status =
+                       lttng_notification_channel_subscribe(notification_channel, condition);
+               if (channel_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_ALREADY_SUBSCRIBED) {
                        continue;
                }
                if (channel_status) {
-                       fprintf(stderr, "Failed to subscribe to notifications of trigger \"%s\"\n",
-                                       trigger_name);
+                       fprintf(stderr,
+                               "Failed to subscribe to notifications of trigger \"%s\"\n",
+                               trigger_name);
                        ret = -1;
                        goto end;
                }
 
-               printf("Subscribed to notifications of trigger \"%s\"\n",
-                               trigger_name);
+               printf("Subscribed to notifications of trigger \"%s\"\n", trigger_name);
                subcription_count++;
        }
 
@@ -502,10 +469,8 @@ int main(int argc, char **argv)
                struct lttng_notification *notification;
                enum lttng_notification_channel_status channel_status;
 
-               channel_status =
-                               lttng_notification_channel_get_next_notification(
-                                               notification_channel,
-                                               &notification);
+               channel_status = lttng_notification_channel_get_next_notification(
+                       notification_channel, &notification);
                switch (channel_status) {
                case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
                        printf("Dropped notification\n");
@@ -524,7 +489,8 @@ int main(int argc, char **argv)
                        printf("Notification channel was closed by peer.\n");
                        break;
                default:
-                       fprintf(stderr, "A communication error occurred on the notification channel.\n");
+                       fprintf(stderr,
+                               "A communication error occurred on the notification channel.\n");
                        ret = -1;
                        goto end;
                }
index e82e3c704998e2bc88f022a93bb5de4e7ef99b12..9aad47e7c66d7612c7999c20d6dbb2f6ec4daae6 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(trigger_example, my_event,
-       TP_ARGS(int, iteration),
-       TP_FIELDS(
-               ctf_integer(uint64_t, iteration, iteration)
-       )
-)
+TRACEPOINT_EVENT(trigger_example,
+                my_event,
+                TP_ARGS(int, iteration),
+                TP_FIELDS(ctf_integer(uint64_t, iteration, iteration)))
 
 #endif /* _TRACEPOINT_TRIGGER_EXAMPLE_H */
 
index 037d84d9f572c225cafe109fe145bde7c83e383a..8f20ede92e39f3bea3508e9ea8611e11aa450736 100644 (file)
@@ -7,6 +7,9 @@
 # function which adds the source directory prefix and adds a given suffix
 manaddsuffix = $(addsuffix $(1),$(addprefix $(srcdir)/,$(2)))
 
+# Local targets.
+LOCAL =
+
 # List only the names without the .*.txt extension here:
 MAN1_NAMES = \
        lttng \
@@ -113,7 +116,7 @@ MAN_H_RECIPE = \
 %.8.h: %.8
        $(MAN_H_RECIPE)
 
-all-local: $(MAN_H)
+LOCAL += $(MAN_H)
 
 CLEANFILES += $(MAN_H)
 endif # EMBED_HELP
@@ -205,6 +208,27 @@ dist_man7_MANS += $(MAN7)
 dist_man8_MANS += $(MAN8)
 endif # MAN_PAGES_OPT
 
+MAN_HIERARCHY = man1 man3 man7 man8
+
+LOCAL += $(MAN_HIERARCHY)
+
+CLEANFILES += $(MAN_HIERARCHY)
+
+# Mimic mandb(8) path hierarchy -- as if installed -- by symlinking
+# sub-directories to the top man directory. This allows developers to read
+# the locally generated man pages. For example `$ ./pre-inst-env man lttng'.
+man1:
+       @ln -s $(abs_builddir) $@
+
+man3:
+       @ln -s $(abs_builddir) $@
+
+man7:
+       @ln -s $(abs_builddir) $@
+
+man8:
+       @ln -s $(abs_builddir) $@
+
 if !MAN_PAGES_OPT
 dist-hook:
        @echo "Error: Please enable the man pages before creating a distribution tarball."
@@ -215,5 +239,8 @@ endif # !MAN_PAGES_OPT
 EXTRA_DIST = $(MAN_TXT) $(COMMON_TXT) $(XSL_FILE) \
        $(ASCIIDOC_CONF) $(ASCIIDOC_ATTRS_CONF).in
 
+# Build local targets.
+all-local: $(LOCAL)
+
 # keep generated man pages that can be considered intermediate files
 .PRECIOUS: %.1 %.3 %.7 %.8
index 1b0233b8e9975c2b1658b0f54723bc2e522d1c6e..ef1cd655580e93741f38f935840d8f26ee599e5b 100644 (file)
@@ -4,7 +4,7 @@ LTTng-tools man pages
 This directory contains the sources of the LTTng-tools man pages.
 
 LTTng-tools man pages are written in
-[AsciiDoc](http://www.methods.co.nz/asciidoc/), and then converted to
+[AsciiDoc](https://asciidoc.org/), and then converted to
 DocBook (XML) using the `asciidoc` command, and finally to troff using
 the appropriate DocBook XSL stylesheet (using the `xmlto` command).
 
index 49f0a7b039e09edce86da308f362b5658091c959..d8cf42f9602aecb622946634947b16dd737a67cd 100644 (file)
@@ -55,7 +55,7 @@ channels.
 Repeat the option:--type='TYPE' option to add more than one context
 field to be recorded. 'TYPE' is one of:
 
-* A statically-known, or built-in context field named.
+* A statically-known, or built-in context field name.
 
 * A perf counter name:
 +
index 656f87b4e5e67686fb7266e63923dc88f83004e7..51f91c2abe136fb404afb621be7fe45524b8c65d 100644 (file)
@@ -168,7 +168,7 @@ option:--action=**notify** [nloption:--rate-policy='POLICY']
 {nbsp}
 +
 Sends a notification through the notification
-mechanism of the session daemon (see man:lttng-session(8)).
+mechanism of the session daemon (see man:lttng-sessiond(8)).
 +
 The session daemon sends details about the condition evaluation along
 with the notification.
index 457808dab6a185d2705924eb4b2a1a17d4f99ddb..4c610bb492b43bfcaef46c4a1fad731473515fae 100644 (file)
@@ -11,7 +11,7 @@ lttng-destroy - Destroy LTTng recording sessions
 SYNOPSIS
 --------
 [verse]
-*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *destroy* [option:--no-wait] [option:--all | 'SESSION']
+*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *destroy* [option:--no-wait] [option:--all | option:--glob 'SESSION' | 'SESSION']
 
 
 DESCRIPTION
@@ -76,6 +76,9 @@ option:-a, option:--all::
     man:lttng-list(1), instead of the current recording session or the
     recording session named 'SESSION'.
 
+option:-g, option:--glob::
+    Interpret SESSION as a globbing pattern.
+
 option:-n, option:--no-wait::
     Do :not: ensure that the trace data of the recording session(s) to
     destroy is valid before exiting.
@@ -126,6 +129,16 @@ $ lttng destroy --all
 ----
 ====
 
+.Destroy all recording sessions with the suffix foo.
+====
+See the option:--glob option.
+
+[role="term"]
+----
+$ lttng destroy --global '*foo'
+----
+====
+
 
 include::common-footer.txt[]
 
index e9c12ae43847692e46db956b91a516e61a2de198..7e6a95b3aab35595e4e4d7da5eb961879ee15370 100644 (file)
@@ -85,13 +85,13 @@ With the option:--jul, option:--log4j, and/or option:--python options::
 Also list the available instrumentation point fields with the
 option:--fields option.
 
-See man:lttng-concept(7) to learn more about recording sessions, tracing
+See man:lttng-concepts(7) to learn more about recording sessions, tracing
 domains, channels, recording event rules, and instrumentation points.
 
 See the ``<<examples,EXAMPLES>>'' section below for usage examples.
 
 List the channels and recording event rules of the current recording
-session (see man:lttng-concept(7) to learn more) with the
+session (see man:lttng-concepts(7) to learn more) with the
 man:lttng-status(1) command.
 
 
index b595b2f5ce2f804f605f99ebd350fe910d6ab1a4..f3ee0e785053792c5e11575802b75fb626fc0e22 100644 (file)
@@ -11,7 +11,7 @@ lttng-start - Start an LTTng recording session
 SYNOPSIS
 --------
 [verse]
-*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *start* ['SESSION']
+*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *start* [option::--all | option::--glob 'SESSION' | 'SESSION' ]
 
 
 DESCRIPTION
@@ -44,6 +44,11 @@ include::common-lttng-cmd-options-head.txt[]
 
 include::common-lttng-cmd-help-options.txt[]
 
+option:-a, option:--all::
+    Start all sessions.
+
+option:-g, option:--glob::
+    Interpret SESSION as a globbing pattern.
 
 include::common-lttng-cmd-after-options.txt[]
 
@@ -67,6 +72,26 @@ $ lttng start my-session
 ----
 ====
 
+.Start all sessions.
+====
+See the option::--all option.
+
+[role="term"]
+----
+$ lttng start --all
+----
+====
+
+.Start all sessions with the suffix foo.
+====
+See the option::--glob option.
+
+[role="term"]
+----
+$ lttng start --glob '*foo'
+----
+====
+
 
 include::common-footer.txt[]
 
index 0ad1f0e3c32b29c1809fb8fd5061c2400a6f58c5..ca1129df3ac5769297296cd411cd652be90ffe4b 100644 (file)
@@ -11,7 +11,7 @@ lttng-stop - Stop an LTTng recording session
 SYNOPSIS
 --------
 [verse]
-*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *stop* [option:--no-wait] ['SESSION']
+*lttng* ['linkgenoptions:(GENERAL OPTIONS)'] *stop* [option:--no-wait] [option:--all | option:--glob 'SESSION' | 'SESSION']
 
 
 DESCRIPTION
@@ -62,6 +62,11 @@ option:-n, option:--no-wait::
     Do :not: ensure that the trace data of the selected recording
     session is valid before exiting.
 
+option:-a, option:--all::
+    Stop all sessions.
+
+option:-g, option:--glob::
+    Interpret SESSION as a globbing pattern.
 
 include::common-lttng-cmd-help-options.txt[]
 
@@ -98,6 +103,26 @@ $ lttng stop --no-wait
 ----
 ====
 
+.Stop all sessions.
+====
+See the option:--all option.
+
+[role="term"]
+----
+$ lttng stop --all
+----
+====
+
+.Stop all sessions with the suffix foo.
+====
+See the option:--glob option.
+
+[role="term"]
+----
+$ lttng stop --glob '*foo'
+----
+====
+
 
 include::common-footer.txt[]
 
diff --git a/extras/bindings/swig/python/.clang-tidy b/extras/bindings/swig/python/.clang-tidy
new file mode 100644 (file)
index 0000000..8866f3d
--- /dev/null
@@ -0,0 +1,7 @@
+# clang-tidy uses the closest .clang-tidy in a parent directory
+# to override settings.
+#
+# Add a dummy check since we can't disable them all without
+# clang-tidy complaining. This ensures that generated code
+# is not flagged.
+Checks: '-*,llvm-twine-local'
index a8fd56d806ed300fc71aff206b51827c3b92d8f7..d9cdd680d52756541314116896996ee02a5c500f 100644 (file)
@@ -7,12 +7,18 @@ lttng.i: lttng.i.in
 # `swig_this` shadows a global of the same name.  Later versions (like 4.0.1)
 # have renamed this global to `Swig_This_global`.
 #
-# Disable -Wshadow for that file.
-AM_CFLAGS += -Wno-shadow
-
-AM_CFLAGS += -Wno-missing-field-initializers
-
-AM_CFLAGS += -Wno-cast-function-type
+# Disable some warning flags for that file.
+AM_CFLAGS += \
+       -Wno-cast-function-type \
+       -Wno-missing-field-initializers \
+       -Wno-null-dereference \
+       -Wno-redundant-decls \
+       -Wno-shadow \
+       -Wno-unused-parameter
+
+# Swig regularily changes and generates code that results warnings which break
+# Werror builds. Disable that option for this sub-project.
+AM_CFLAGS += -Wno-error
 
 AM_CPPFLAGS += $(PYTHON_INCLUDE)
 
@@ -28,6 +34,11 @@ _lttng_la_LIBADD =   $(top_builddir)/src/lib/lttng-ctl/liblttng-ctl.la               \
                        $(top_builddir)/src/common/libsessiond-comm.la          \
                        $(top_builddir)/src/common/libcommon-gpl.la
 
+# Use this fake source file to force the link mode of the library
+# from gcc to g++. The library contains only C code, but depends on
+# libstdc++.
+nodist_EXTRA__lttng_la_SOURCES = dummy.cpp
+
 lttng_wrap.c: lttng.i
        $(SWIG) -python -I. -I$(top_srcdir)/src/common/sessiond-comm lttng.i
 
index b555f4aae02c85ab0762d8115def223b18ec7504..94198769c3e54b6bfc3be46ef168ab3eb75df0fe 100644 (file)
@@ -154,6 +154,28 @@ enum lttng_event_output {
 %rename("EVENT_CONTEXT_PREEMPTIBLE") LTTNG_EVENT_CONTEXT_PREEMPTIBLE;
 %rename("EVENT_CONTEXT_NEED_RESCHEDULE") LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE;
 %rename("EVENT_CONTEXT_MIGRATABLE") LTTNG_EVENT_CONTEXT_MIGRATABLE;
+%rename("EVENT_CONTEXT_CALLSTACK_KERNEL") LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL;
+%rename("EVENT_CONTEXT_CALLSTACK_USER") LTTNG_EVENT_CONTEXT_CALLSTACK_USER;
+%rename("EVENT_CONTEXT_CGROUP_NS") LTTNG_EVENT_CONTEXT_CGROUP_NS;
+%rename("EVENT_CONTEXT_IPC_NS") LTTNG_EVENT_CONTEXT_IPC_NS;
+%rename("EVENT_CONTEXT_MNT_NS") LTTNG_EVENT_CONTEXT_MNT_NS;
+%rename("EVENT_CONTEXT_NET_NS") LTTNG_EVENT_CONTEXT_NET_NS;
+%rename("EVENT_CONTEXT_PID_NS") LTTNG_EVENT_CONTEXT_PID_NS;
+%rename("EVENT_CONTEXT_USER_NS") LTTNG_EVENT_CONTEXT_USER_NS;
+%rename("EVENT_CONTEXT_UTS_NS") LTTNG_EVENT_CONTEXT_UTS_NS;
+%rename("EVENT_CONTEXT_UID") LTTNG_EVENT_CONTEXT_UID;
+%rename("EVENT_CONTEXT_EUID") LTTNG_EVENT_CONTEXT_EUID;
+%rename("EVENT_CONTEXT_SUID") LTTNG_EVENT_CONTEXT_SUID;
+%rename("EVENT_CONTEXT_GID") LTTNG_EVENT_CONTEXT_GID;
+%rename("EVENT_CONTEXT_EGID") LTTNG_EVENT_CONTEXT_EGID;
+%rename("EVENT_CONTEXT_SGID") LTTNG_EVENT_CONTEXT_SGID;
+%rename("EVENT_CONTEXT_VUID") LTTNG_EVENT_CONTEXT_VUID;
+%rename("EVENT_CONTEXT_VEUID") LTTNG_EVENT_CONTEXT_VEUID;
+%rename("EVENT_CONTEXT_VSUID") LTTNG_EVENT_CONTEXT_VSUID;
+%rename("EVENT_CONTEXT_VGID") LTTNG_EVENT_CONTEXT_VGID;
+%rename("EVENT_CONTEXT_VEGID") LTTNG_EVENT_CONTEXT_VEGID;
+%rename("EVENT_CONTEXT_VSGID") LTTNG_EVENT_CONTEXT_VSGID;
+%rename("EVENT_CONTEXT_TIME_NS") LTTNG_EVENT_CONTEXT_TIME_NS;
 enum lttng_event_context_type {
        LTTNG_EVENT_CONTEXT_PID               = 0,
        LTTNG_EVENT_CONTEXT_PERF_COUNTER      = 1,
@@ -175,6 +197,28 @@ enum lttng_event_context_type {
        LTTNG_EVENT_CONTEXT_PREEMPTIBLE       = 17,
        LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE   = 18,
        LTTNG_EVENT_CONTEXT_MIGRATABLE        = 19,
+       LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL  = 20,
+       LTTNG_EVENT_CONTEXT_CALLSTACK_USER    = 21,
+       LTTNG_EVENT_CONTEXT_CGROUP_NS         = 22,
+       LTTNG_EVENT_CONTEXT_IPC_NS            = 23,
+       LTTNG_EVENT_CONTEXT_MNT_NS            = 24,
+       LTTNG_EVENT_CONTEXT_NET_NS            = 25,
+       LTTNG_EVENT_CONTEXT_PID_NS            = 26,
+       LTTNG_EVENT_CONTEXT_USER_NS           = 27,
+       LTTNG_EVENT_CONTEXT_UTS_NS            = 28,
+       LTTNG_EVENT_CONTEXT_UID               = 29,
+       LTTNG_EVENT_CONTEXT_EUID              = 30,
+       LTTNG_EVENT_CONTEXT_SUID              = 31,
+       LTTNG_EVENT_CONTEXT_GID               = 32,
+       LTTNG_EVENT_CONTEXT_EGID              = 33,
+       LTTNG_EVENT_CONTEXT_SGID              = 34,
+       LTTNG_EVENT_CONTEXT_VUID              = 35,
+       LTTNG_EVENT_CONTEXT_VEUID             = 36,
+       LTTNG_EVENT_CONTEXT_VSUID             = 37,
+       LTTNG_EVENT_CONTEXT_VGID              = 38,
+       LTTNG_EVENT_CONTEXT_VEGID             = 39,
+       LTTNG_EVENT_CONTEXT_VSGID             = 40,
+       LTTNG_EVENT_CONTEXT_TIME_NS           = 41,
 };
 
 
@@ -928,6 +972,72 @@ struct lttng_event_context {
                        case 19:
                                sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_MIGRATABLE)");
                                break;
+                       case 20:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_CALLSTACK_KERNEL)");
+                               break;
+                       case 21:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_CALLSTACK_USER)");
+                               break;
+                       case 22:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_CGROUP_NS)");
+                               break;
+                       case 23:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_IPC_NS)");
+                               break;
+                       case 24:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_MNT_NS)");
+                               break;
+                       case 25:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_NET_NS)");
+                               break;
+                       case 26:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_PID_NS)");
+                               break;
+                       case 27:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_USER_NS)");
+                               break;
+                       case 28:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_UTS_NS)");
+                               break;
+                       case 29:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_UID)");
+                               break;
+                       case 30:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_EUID)");
+                               break;
+                       case 31:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_SUID)");
+                               break;
+                       case 32:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_GID)");
+                               break;
+                       case 33:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_EGID)");
+                               break;
+                       case 34:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_SGID)");
+                               break;
+                       case 35:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VUID)");
+                               break;
+                       case 36:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VEUID)");
+                               break;
+                       case 37:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VSUID)");
+                               break;
+                       case 38:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VGID)");
+                               break;
+                       case 39:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VEGID)");
+                               break;
+                       case 40:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_VSGID)");
+                               break;
+                       case 41:
+                               sprintf(temp, "lttng.EventContext; ctx(EVENT_CONTEXT_TIME_NS)");
+                               break;
                        default:
                                sprintf(temp, "lttng.EventContext; type(%i)", $self->ctx);
                                break;
index 45587b56bcc6d580dc351b3c7a71c5d42e27ad07..56835625b2fc24348817e766bfbb35659cabf7f0 100644 (file)
@@ -7,18 +7,21 @@
 
 from lttng import *
 
+
 # This error will be raised is something goes wrong
 class LTTngError(Exception):
-       def __init__(self, value):
-               self.value = value
-       def __str__(self):
-               return repr(self.value)
+    def __init__(self, value):
+        self.value = value
+
+    def __str__(self):
+        return repr(self.value)
+
 
-#Setting up the domain to use
+# Setting up the domain to use
 dom = Domain()
 dom.type = DOMAIN_KERNEL
 
-#Setting up a channel to use
+# Setting up a channel to use
 channel = Channel()
 channel.name = "mychan"
 channel.attr.overwrite = 0
@@ -28,7 +31,7 @@ channel.attr.switch_timer_interval = 0
 channel.attr.read_timer_interval = 200
 channel.attr.output = EVENT_SPLICE
 
-#Setting up some events that will be used
+# Setting up some events that will be used
 event = Event()
 event.type = EVENT_TRACEPOINT
 event.loglevel_type = EVENT_LOGLEVEL_ALL
@@ -49,66 +52,66 @@ sched_process_free.type = EVENT_TRACEPOINT
 sched_process_free.loglevel_type = EVENT_LOGLEVEL_ALL
 
 
-#Creating a new session
-res = create("test","/lttng-traces/test")
-if res<0:
-       raise LTTngError(strerror(res))
+# Creating a new session
+res = create("test", "/lttng-traces/test")
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Creating handle
+# Creating handle
 han = None
 han = Handle("test", dom)
 if han is None:
-       raise LTTngError("Handle not created")
+    raise LTTngError("Handle not created")
 
-#Enabling the kernel channel
+# Enabling the kernel channel
 res = enable_channel(han, channel)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Enabling some events in given channel
-#To enable all events in default channel, use
-#enable_event(han, event, None)
+# Enabling some events in given channel
+# To enable all events in default channel, use
+# enable_event(han, event, None)
 res = enable_event(han, sched_switch, channel.name)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
 res = enable_event(han, sched_process_exit, channel.name)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
 res = enable_event(han, sched_process_free, channel.name)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Disabling an event
+# Disabling an event
 res = disable_event(han, sched_switch.name, channel.name)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Getting a list of the channels
+# Getting a list of the channels
 l = list_channels(han)
 if type(l) is int:
-               raise LTTngError(strerror(l))
+    raise LTTngError(strerror(l))
 
-#Starting the trace
+# Starting the trace
 res = start("test")
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Stopping the trace
+# Stopping the trace
 res = stop("test")
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Disabling a channel
+# Disabling a channel
 res = disable_channel(han, channel.name)
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
 
-#Destroying the handle
+# Destroying the handle
 del han
 
-#Destroying the session
+# Destroying the session
 res = destroy("test")
-if res<0:
-       raise LTTngError(strerror(res))
+if res < 0:
+    raise LTTngError(strerror(res))
index fbbfdc48062e00a24a51cf5d5ee640ae4c9d519d..7dd1d062472ce3e72e8b31914f231ff244b06470 100644 (file)
@@ -10,7 +10,8 @@ import time
 import tempfile
 from lttng import *
 
-class TestLttngPythonModule (unittest.TestCase):
+
+class TestLttngPythonModule(unittest.TestCase):
 
     def setUp(self):
         self.tmpdir = tempfile.TemporaryDirectory()
@@ -45,7 +46,6 @@ class TestLttngPythonModule (unittest.TestCase):
         r = destroy("test_kernel_all_ev")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-
     def test_kernel_event(self):
 
         dom = Domain()
@@ -53,7 +53,7 @@ class TestLttngPythonModule (unittest.TestCase):
         dom.buf_type = BUFFER_GLOBAL
 
         channel = Channel()
-        channel.name="mychan"
+        channel.name = "mychan"
         channel.attr.overwrite = 0
         channel.attr.subbuf_size = 4096
         channel.attr.num_subbuf = 8
@@ -78,15 +78,15 @@ class TestLttngPythonModule (unittest.TestCase):
 
         han = Handle("test_kernel_event", dom)
 
-        #Create session test
+        # Create session test
         r = create("test_kernel_event", self.tmpdir.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Enabling channel tests
+        # Enabling channel tests
         r = enable_channel(han, channel)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Enabling events tests
+        # Enabling events tests
         r = enable_event(han, sched_switch, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
@@ -96,21 +96,21 @@ class TestLttngPythonModule (unittest.TestCase):
         r = enable_event(han, sched_process_free, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Disabling events tests
+        # Disabling events tests
         r = disable_event(han, sched_switch.name, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
         r = disable_event(han, sched_process_free.name, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Renabling events tests
+        # Renabling events tests
         r = enable_event(han, sched_switch, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
         r = enable_event(han, sched_process_free, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Start, stop, destroy
+        # Start, stop, destroy
         r = start("test_kernel_event")
         self.assertGreaterEqual(r, 0, strerror(r))
         time.sleep(2)
@@ -118,14 +118,12 @@ class TestLttngPythonModule (unittest.TestCase):
         r = stop("test_kernel_event")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        r=disable_channel(han, channel.name)
+        r = disable_channel(han, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        r=destroy("test_kernel_event")
+        r = destroy("test_kernel_event")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-
-
     def test_ust_all_events(self):
         dom = Domain()
         dom.type = DOMAIN_UST
@@ -153,7 +151,6 @@ class TestLttngPythonModule (unittest.TestCase):
         r = destroy("test_ust_all_ev")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-
     def test_ust_event(self):
 
         dom = Domain()
@@ -161,7 +158,7 @@ class TestLttngPythonModule (unittest.TestCase):
         dom.buf_type = BUFFER_PER_UID
 
         channel = Channel()
-        channel.name="mychan"
+        channel.name = "mychan"
         channel.attr.overwrite = 0
         channel.attr.subbuf_size = 4096
         channel.attr.num_subbuf = 8
@@ -186,15 +183,15 @@ class TestLttngPythonModule (unittest.TestCase):
 
         han = Handle("test_ust_event", dom)
 
-        #Create session test
+        # Create session test
         r = create("test_ust_event", self.tmpdir.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Enabling channel tests
+        # Enabling channel tests
         r = enable_channel(han, channel)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Enabling events tests
+        # Enabling events tests
         r = enable_event(han, ev1, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
@@ -204,21 +201,21 @@ class TestLttngPythonModule (unittest.TestCase):
         r = enable_event(han, ev3, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Disabling events tests
+        # Disabling events tests
         r = disable_event(han, ev1.name, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
         r = disable_event(han, ev3.name, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Renabling events tests
+        # Renabling events tests
         r = enable_event(han, ev1, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
         r = enable_event(han, ev3, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Start, stop
+        # Start, stop
         r = start("test_ust_event")
         self.assertGreaterEqual(r, 0, strerror(r))
         time.sleep(2)
@@ -226,7 +223,7 @@ class TestLttngPythonModule (unittest.TestCase):
         r = stop("test_ust_event")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Restart/restop
+        # Restart/restop
         r = start("test_ust_event")
         self.assertGreaterEqual(r, 0, strerror(r))
         time.sleep(2)
@@ -234,25 +231,24 @@ class TestLttngPythonModule (unittest.TestCase):
         r = stop("test_ust_event")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Disabling channel and destroy
-        r=disable_channel(han, channel.name)
+        # Disabling channel and destroy
+        r = disable_channel(han, channel.name)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        r=destroy("test_ust_event")
+        r = destroy("test_ust_event")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-
     def test_other_functions(self):
         dom = Domain()
-        dom.type=DOMAIN_KERNEL
+        dom.type = DOMAIN_KERNEL
         dom.buf_type = BUFFER_GLOBAL
 
-        event=Event()
-        event.type=EVENT_TRACEPOINT
-        event.loglevel_type=EVENT_LOGLEVEL_ALL
+        event = Event()
+        event.type = EVENT_TRACEPOINT
+        event.loglevel_type = EVENT_LOGLEVEL_ALL
 
         ctx = EventContext()
-        ctx.type=EVENT_CONTEXT_PID
+        ctx.type = EVENT_CONTEXT_PID
 
         chattr = ChannelAttr()
         chattr.overwrite = 0
@@ -262,7 +258,7 @@ class TestLttngPythonModule (unittest.TestCase):
         chattr.read_timer_interval = 200
         chattr.output = EVENT_SPLICE
 
-        han = Handle("test_otherf" , dom)
+        han = Handle("test_otherf", dom)
 
         r = create("test_otherf", self.tmpdir.name)
         self.assertGreaterEqual(r, 0, strerror(r))
@@ -270,29 +266,28 @@ class TestLttngPythonModule (unittest.TestCase):
         r = enable_event(han, event, None)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Context test
+        # Context test
         r = add_context(han, ctx, "sched_switch", "channel0")
         self.assertGreaterEqual(r, 0, strerror(r))
-        #Any channel
+        # Any channel
         r = add_context(han, ctx, "sched_wakeup", None)
         self.assertGreaterEqual(r, 0, strerror(r))
-        #All events
+        # All events
         r = add_context(han, ctx, None, None)
         self.assertGreaterEqual(r, 0, strerror(r))
 
-        #Def. channel attr
+        # Def. channel attr
         channel_set_default_attr(dom, chattr)
         channel_set_default_attr(None, None)
 
-        #Ses Daemon alive
+        # Ses Daemon alive
         r = session_daemon_alive()
         self.assertTrue(r == 1 or r == 0, strerror(r))
 
-        #Setting trace group
+        # Setting trace group
         r = set_tracing_group("testing")
         self.assertGreaterEqual(r, 0, strerror(r))
 
-
         r = start("test_otherf")
         self.assertGreaterEqual(r, 0, strerror(r))
         time.sleep(2)
@@ -316,6 +311,7 @@ def ust_suite():
     suite.addTest(TestLttngPythonModule("test_ust_all_events"))
     return suite
 
+
 def kernel_suite():
     suite = unittest.TestSuite()
     suite.addTest(TestLttngPythonModule("test_kernel_event"))
@@ -323,7 +319,8 @@ def kernel_suite():
     suite.addTest(TestLttngPythonModule("test_other_functions"))
     return suite
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     destroy("test_kernel_event")
     destroy("test_kernel_all_events")
     destroy("test_ust_all_events")
index bc7296814f4011e37365a5125da1fe73f5bed3a1..c1e2a91bcc51b257bc3959dddf0bcc4fe9950f09 100644 (file)
@@ -5,7 +5,6 @@
  *
  */
 
-
 #include <signal.h>
 
 int main(void)
diff --git a/extras/zsh-completion/_lttng b/extras/zsh-completion/_lttng
new file mode 100644 (file)
index 0000000..b929e5d
--- /dev/null
@@ -0,0 +1,2040 @@
+#compdef lttng
+#
+# Copyright (c) 2015-2023 Philippe Proulx <eeppeliteloop@gmail.com>
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+#
+# This is a Zsh completion function for the lttng(1) command (see
+# <https://lttng.org/>), for versions 2.5 to 2.14.
+#
+# If you want, at your own risk, the function to work with versions
+# above 2.14, set `LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1`.
+#
+# Each subcommand changes the command part of the current context so
+# that you can target a specific subcommand with `zstyle`, for
+# example:
+#
+#     $ zstyle ':completion:*:*:lttng-start:*:sessions' verbose yes
+#     $ zstyle ':completion:*:*:lttng-add-context:type-option:*' \
+#              group-order perf-context-types static-context-types
+#
+# The relevant style arguments and tags are:
+#
+# `actions` tag (with the `lttng-snapshot` command):
+#     Snapshot action names.
+#
+# `channel` argument and `channels` tag:
+#     Channel names.
+#
+#     The `verbose` style controls whether or not this function adds
+#     completions as a list (with channel information for each item) or
+#     simple channel names.
+#
+#     If the verbose style is enabled, then the information part of each
+#     item starts with either `  [enabled` or `  [disabled` (note the
+#     two leading spaces), depending on the status of the channel.
+#
+# `commands` tag:
+#     lttng(1) subcommand names.
+#
+# `log-levels` tag:
+#     Log level names.
+#
+# `session` argument and `sessions` tag:
+#     Recording session names.
+#
+#     The `verbose` style controls whether or not this function adds
+#     completions as a list (with recording session information for each
+#     item) or simple recording session names.
+#
+#     If the verbose style is enabled, then the information part of each
+#     item starts with either `  [active` or `  [inactive` (note the two
+#     leading spaces), depending on the status of the recording session.
+#
+# `type-option` argument:
+#     `static-context-types` tag:
+#         Statically-known context field types.
+#
+#     `perf-context-types` tag:
+#         perf counter context field types.
+#
+# `triggers` tag:
+#     Trigger names.
+
+# Sets the `minor_version` variable to the minor version of LTTng-tools,
+# or to `0` if not found.
+__lttng_set_minor_version() {
+  minor_version=0
+
+  local -a match
+
+  if [[ $($prog_name --version) =~ '[[:blank:]]+2\.([[:digit:]]+)' ]]; then
+    minor_version=$match[1]
+  fi
+}
+
+# Runs the `lttng` command with `"$@"` using `$tracing_group`.
+__lttng_run() {
+  $prog_name --no-sessiond --group=$tracing_group "$@" 2>/dev/null
+}
+
+# Runs the `lttng --mi=xml` command using the selected tracing group
+# (`$tracing_group`) with:
+#
+# `$1`:
+#     A message of what's expected to show on error.
+#
+# Other arguments:
+#     Passed to the command as is.
+#
+# This function returns 1 with LTTng-tools < 2.6 and if `xmllint` isn't
+# available.
+__lttng_mi_run() {
+  local -r msg=$1
+
+  shift
+
+  if ((minor_version < 6)); then
+    # MI output requires LTTng-tools ≥ 2.6
+    _message -e descriptions $msg
+    return 1
+  fi
+
+  if ((! $+commands[xmllint])); then
+    # XML output parsing requires xmllint
+    _message -e descriptions $msg
+    return 1
+  fi
+
+  __lttng_run --mi=xml "$@"
+
+  if (($? != 0)); then
+    # Command failed
+    _message -e descriptions $msg
+    return 1
+  fi
+}
+
+# Call this instead of _arguments() within this function when you don't
+# need the `-C` option.
+__lttng_arguments() {
+  _arguments -s -W : "$@"
+}
+
+# Returns whether or not the verbose style is enabled for the given
+# argument (`$1`) and tag (`$2`), using `$curcontext` for the other
+# parts of the full completion context.
+__lttng_style_is_verbose() {
+  local -r arg=$1 tag=$2
+  local -r ccparts=("${(@s.:.)curcontext}")
+
+  zstyle -t :completion:${ccparts[1]}:${ccparts[2]}:${ccparts[3]}:$arg:$tag verbose
+}
+
+# Returns 0 if a Linux kernel tracing domain option is set in
+# `$opt_args`, or `1` otherwise.
+__lttng_kernel_domain_opt_is_set() {
+  (($+opt_args[-k] || $+opt_args[--kernel] ||
+    $+opt_args[domain--k] || $+opt_args[domain---kernel]))
+}
+
+# Returns 0 if a user space tracing domain option is set in
+# `$opt_args`, or `1` otherwise.
+__lttng_user_domain_opt_is_set() {
+  (($+opt_args[-u] || $+opt_args[--userspace] ||
+    $+opt_args[domain--u] || $+opt_args[domain---userspace]))
+}
+
+# Returns 0 if a `java.util.logging` tracing domain option is set in
+# `$opt_args`, or `1` otherwise.
+__lttng_jul_domain_opt_is_set() {
+  (($+opt_args[-j] || $+opt_args[--jul] ||
+    $+opt_args[domain--j] || $+opt_args[domain---jul]))
+}
+
+# Returns 0 if an Apache log4j tracing domain option is set in
+# `$opt_args`, or `1` otherwise.
+__lttng_log4j_domain_opt_is_set() {
+  (($+opt_args[-l] || $+opt_args[--log4j] ||
+    $+opt_args[domain--l] || $+opt_args[domain---log4j]))
+}
+
+# Returns 0 if a Python tracing domain option is set in `$opt_args`,
+# or `1` otherwise.
+__lttng_python_domain_opt_is_set() {
+  (($+opt_args[-p] || $+opt_args[--python] ||
+    $+opt_args[domain--p] || $+opt_args[domain---python]))
+}
+
+# Adds completions for the name of an `lttng` command.
+__lttng_complete_cmd_name() {
+  # LTTng-tools 2.5+
+  local cmd_names=(
+    'add-context:add context fields to be recorded'
+    'create:create a recording session'
+    'destroy:destroy a recording session'
+    'disable-channel:disable channels'
+    'disable-event:disable recording event rules'
+    'enable-channel:create or enable a channel'
+    'enable-event:create or enable recording event rules'
+    'help:show the help of a command'
+    'list:list recording sessions and instrumentation points'
+    'set-session:set the current recording session'
+    'snapshot:take a recording session snapshot'
+    'start:start a recording session'
+    'stop:stop a recording session'
+    'version:show LTTng-tools version information'
+    'view:launch a trace reader'
+  )
+
+  # LTTng-tools 2.6+
+  if ((minor_version >= 6)); then
+    cmd_names+=(
+      'load:load recording session configurations'
+      'save:save recording session configurations'
+    )
+  fi
+
+  # LTTng-tools 2.7+
+  if ((minor_version >= 7)); then
+    cmd_names+=(
+      'track:allow specific processes to record events'
+      'untrack:disallow specific processes to record events'
+    )
+  fi
+
+  # LTTng-tools 2.8+
+  if ((minor_version >= 8)); then
+    cmd_names+=(
+      'status:show the status of the current recording session'
+    )
+  fi
+
+  # LTTng-tools 2.9+
+  if ((minor_version >= 9)); then
+    cmd_names+=(
+      'regenerate:regenerate specific recording session data'
+    )
+  fi
+
+  # LTTng-tools 2.11+
+  if ((minor_version >= 11)); then
+    cmd_names+=(
+      'rotate:archive the current trace chunk of a recording session'
+      'enable-rotation:set a recording session rotation schedule'
+      'disable-rotation:unset a recording session rotation schedule'
+    )
+  fi
+
+  # LTTng-tools 2.12+
+  if ((minor_version >= 12)); then
+    cmd_names+=(
+      'clear:clear a recording session'
+    )
+  fi
+
+  # LTTng-tools 2.13+
+  if ((minor_version >= 13)); then
+    cmd_names+=(
+      'add-trigger:add a trigger'
+      'list-triggers:list triggers'
+      'remove-trigger:remove a trigger'
+    )
+  fi
+
+  # Add completions
+  local expl
+
+  _describe -t commands command cmd_names
+}
+
+# Adds completions for the name of an `lttng snapshot` action.
+__lttng_complete_snapshot_action_name() {
+  local -r action_names=(
+    'add-output:add a snapshot output'
+    'del-output:remove a snapshot output'
+    'list-output:show the snapshot output'
+    'record:take a snapshot'
+  )
+
+  # Add completions
+  local expl
+
+  _describe -t actions 'snapshot action' action_names
+}
+
+# Adds user ID completions.
+#
+# The added completions are displayed as user names, but the actual
+# completions are corresponding user IDs.
+__lttng_complete_uid() {
+  if [[ ! -f /etc/passwd ]]; then
+    # Weird flex but ok
+    _message -e descriptions 'user ID'
+    return
+  fi
+
+  # Read user names and IDs from `/etc/passwd`
+  local line
+  local -a uids names fields
+
+  while read -r line; do
+    if [[ -z ${line// } ]]; then
+      # Skip empty line
+      continue
+    fi
+
+    # Extract user ID and name
+    fields=("${(@s/:/)line}")
+    uids+=($fields[3])
+    names+=("$fields[1]")
+  done < /etc/passwd
+
+  # Add completions
+  local expl
+
+  _wanted users expl 'user ID' compadd -d names -a uids
+}
+
+# Adds completions for a context field type (for the `--type` option of
+# the `add-context` command).
+#
+# This function replaces the argument field of the current context with
+# `type-option`.
+#
+# This function relies on the tracing domain options of `$opt_args` to
+# restrict the offered completions. Without a tracing domain option,
+# this function adds all the possible context field type completions.
+#
+# This function runs `lttng add-context --list` to get the list of
+# available context field types.
+#
+# This function adds completions with both the `static-context-types`
+# and `perf-context-types` tags so that the Zsh user can hide a group or
+# select them with the `group-order` and `tag-order` style.
+__lttng_complete_context_type() {
+  # Statically-known context field types
+  local kernel_types=(
+    pid procname prio nice vpid tid vtid ppid vppid hostname
+    interruptible preemptible need_reschedule migratable
+    callstack-kernel callstack-user cgroup_ns ipc_ns mnt_ns net_ns
+    pid_ns time_ns user_ns uts_ns uid euid suid gid egid sgid vuid veuid
+    vsuid vgid vegid vsgid
+  )
+  local user_types=(
+    vpid pthread_id procname ip cgroup_ns ipc_ns mnt_ns net_ns pid_ns
+    time_ns user_ns uts_ns vuid veuid vsuid vgid vegid vsgid
+  )
+
+  # Set `types` and `domain` depending on the selected tracing domain
+  local -a types
+  local domain descr_suffix
+
+  if __lttng_kernel_domain_opt_is_set; then
+    # Kernel context field types
+    types=($kernel_types)
+    domain=k
+  elif __lttng_user_domain_opt_is_set; then
+    # User space context field types
+    types=($user_types)
+    domain=u
+  else
+    # No supported tracing domain: offer all context field types
+    types=($user_types $kernel_types)
+    descr_suffix=' (all tracing domains)'
+  fi
+
+  # Get XML list of available context field types
+  local -r msg='context type'
+  local list_xml
+
+  list_xml=$(__lttng_mi_run $msg add-context --list)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Convert to one context field type per line
+  local lines
+
+  lines=$(__lttng_xmllint_xpath $list_xml '//*[local-name()="symbol"]/text()')
+
+  if (($? != 0)); then
+    _guard '^-*' $msg
+    return
+  fi
+
+  # Filter context field types depending on the selected tracing domain
+  local -a static_items perf_items
+  local line
+
+  while read -r line; do
+    if (($types[(Ie)$line])); then
+      # Statically-known context field type
+      static_items+=$line
+    elif [[ $line = perf:cpu:* && $domain != u ]]; then
+      # Per-CPU perf counter
+      perf_items+=$line
+    elif [[ $line = perf:thread:* && $domain != k ]]; then
+      # Per-thread perf counter
+      perf_items+=$line
+    elif [[ $line = perf:* && $domain != u ]]; then
+      # Other perf counter (Linux kernel tracing domain or none)
+      perf_items+=$line
+    fi
+  done <<< $lines
+
+  # Add completions
+  _alternative -C type-option \
+    "static-context-types:statically-known context type${descr_suffix}:compadd -a static_items" \
+    "perf-context-types:perf counter context type${descr_suffix}:compadd -a perf_items"
+}
+
+# Adds completions for a trigger name.
+#
+# Relies on `$opt_args[--owner-uid]` to restrict the offered
+# completions.
+__lttng_complete_trigger_name() {
+  # Get XML list of available triggers
+  local msg='trigger name'
+  local list_xml
+
+  list_xml=$(__lttng_mi_run $msg list-triggers)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Create the owner UID predicate XPath part
+  local owner_uid_xpath
+
+  if (($+opt_args[--owner-uid])); then
+    owner_uid_xpath="[./*[local-name()='owner_uid'] = ${opt_args[--owner-uid]}]"
+  fi
+
+  # Convert to one trigger name per line
+  local lines
+
+  lines=$(__lttng_xmllint_xpath $list_xml "//*[local-name()='trigger']$owner_uid_xpath/*[local-name()='name']/text()")
+
+  if (($? != 0)); then
+    _guard '^-*' $msg
+    return
+  fi
+
+  local -a trigger_names
+
+  while read -r line; do
+    trigger_names+=$line
+  done <<< $lines
+
+  # Add completions
+  local expl
+
+  _wanted triggers expl $msg compadd -a trigger_names
+}
+
+# Runs `xmllint` with:
+#
+# `$1`:
+#     An XML document to parse.
+#
+# `$2`:
+#     An XPath to extract data.
+__lttng_xmllint_xpath() {
+  local -r xml=$1 xpath=$2
+
+  xmllint --xpath $xpath - <<< $xml 2>/dev/null
+}
+
+# Prints the equivalent recording session status adjective (`active` or
+# `inactive`) for an `enabled` XML property, or `unknown` on error.
+__lttng_session_status_from_enabled_prop() {
+  local -r prop=$1
+
+  case $prop in
+    true) echo -n active;;
+    false) echo -n inactive;;
+    *) echo -n unknown;;
+  esac
+}
+
+# Prints the value of the immediate XML property named `$3` of the child
+# node named `$2` within the parent node `$1`.
+__lttng_immediate_prop_from_xml() {
+  local -r node_xml=$1 node_name=$2 prop_name=$3
+
+  __lttng_xmllint_xpath $node_xml "/*[local-name()='$node_name']/*[local-name()='$prop_name']/text()"
+}
+
+# Prints the value of the immediate XML `name` property of the child
+# node named `$2` within the parent node `$1`.
+__lttng_name_prop_from_xml() {
+  local -r node_xml=$1 node_name=$2
+
+  __lttng_immediate_prop_from_xml $node_xml $node_name name
+}
+
+# Prints the value of the immediate XML `enabled` property of the child
+# node named `$2` within the parent node `$1`.
+__lttng_enabled_prop_from_xml() {
+  local -r node_xml=$1 node_name=$2
+
+  __lttng_immediate_prop_from_xml $node_xml $node_name enabled
+}
+
+# Adds completions for a recording session name.
+#
+# Arguments:
+#
+# `$1`:
+#     One of:
+#
+#     `all`:
+#         Add completions for active and inactive recording sessions.
+#
+#     `active`:
+#         Only add completions for active recording sessions.
+#
+#     `inactive`:
+#         Only add completions for inactive recording sessions.
+#
+# `$2`:
+#     One of:
+#
+#     `all`:
+#         Add completions for recording sessions regardless of their
+#         mode.
+#
+#     `snapshot`:
+#         Only add completions for snapshot recording sessions.
+#
+#     `live`:
+#         Only add completions for LTTng live recording sessions.
+__lttng_complete_session_name() {
+  local -r req_status=$1 req_mode=$2
+
+  # Get XML document (summary of recording sessions)
+  local session_summaries_xml
+
+  session_summaries_xml=$(__lttng_mi_run 'recording session name' list)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Count recording sessions
+  local -i session_count
+
+  session_count=$(__lttng_xmllint_xpath $session_summaries_xml 'count(//*[local-name()="session"])')
+
+  if (($? != 0 || session_count == 0)); then
+    _guard '^-*' 'recording session name'
+    return
+  fi
+
+  # Append the name and info of one recording session at a time
+  local -a session_names session_infos
+  local -i index iprop
+  local session_name session_summary_xml snapshot_mode session_status session_info
+
+  # For each recording session summary
+  for index in {1..$session_count}; do
+    # Get recording session summary XML node
+    session_summary_xml=$(__lttng_xmllint_xpath $session_summaries_xml "//*[local-name()='session'][$index]")
+
+    if (($? != 0)); then
+      continue
+    fi
+
+    # Get recording session name
+    session_name=$(__lttng_name_prop_from_xml $session_summary_xml session)
+
+    if (($? != 0)); then
+      continue
+    fi
+
+    # Get recording session status
+    session_status=$(__lttng_enabled_prop_from_xml $session_summary_xml session)
+
+    if (($? != 0)); then
+      continue
+    fi
+
+    session_status=$(__lttng_session_status_from_enabled_prop $session_status)
+
+    if [[ $req_status != all && $req_status != $session_status ]]; then
+      # Skip recording session with unexpected status
+      continue
+    fi
+
+    # Get recording session mode
+    session_mode=
+    iprop=$(__lttng_immediate_prop_from_xml $session_summary_xml session snapshot_mode)
+
+    if (($? == 0 && iprop)); then
+      session_mode=snapshot
+    else
+      iprop=$(__lttng_immediate_prop_from_xml $session_summary_xml session live_timer_interval)
+
+      if (($? == 0 && iprop)); then
+        session_mode=live
+      fi
+    fi
+
+    if [[ $req_mode != all && $req_mode != $session_mode ]]; then
+      # Skip recording session with unexpected mode
+      continue
+    fi
+
+    session_info=$session_status
+
+    if [[ -n $session_mode ]]; then
+      session_info+=", $session_mode mode"
+    fi
+
+    session_names+=("$session_name")
+    session_infos+=($session_info)
+  done
+
+  # No recording sessions: show message
+  if (($#session_names == 0)); then
+    _guard '^-*' 'recording session name'
+    return
+  fi
+
+  # Compute maximum session info length
+  local -i max_info_len=0 len
+
+  for session_info in $session_infos; do
+    len=$#session_info
+
+    if ((len > max_info_len)); then
+      max_info_len=$len
+    fi
+  done
+
+  # Compute maximum session name length
+  local -i max_name_len=0
+
+  for session_name in $session_names; do
+    len=$#session_name
+
+    if ((len > max_name_len)); then
+      max_name_len=$len
+    fi
+  done
+
+  # Some room for the longest info string, two spaces, and two brackets
+  local -ir max_possible_name_len=$((COLUMNS - max_info_len - 5))
+
+  if ((max_name_len > max_possible_name_len)); then
+    # Clamp
+    max_name_len=$max_possible_name_len
+  fi
+
+  # Create the dislay strings (name, status, mode)
+  local -a disps
+
+  for index in {1..${#session_names}}; do
+    disps+=("${(r:$max_name_len:: :)session_names[$index]}  [$session_infos[$index]]")
+  done
+
+  # Add completions
+  local expl
+
+  if __lttng_style_is_verbose session sessions; then
+    # Verbose mode (list with infos)
+    _wanted -C session sessions expl 'recording session name' \
+      compadd -d disps -l -a session_names
+  else
+    # Just the recording session names
+    _wanted -C session sessions expl 'recording session name' \
+      compadd -a session_names
+  fi
+}
+
+# Prints the name of the Unix user's current recording session, if any.
+__lttng_cur_session_name() {
+  local -r lttngrc_path=${LTTNG_HOME:-$HOME}/.lttngrc
+
+  if [[ ! -f $lttngrc_path ]]; then
+    return 1
+  fi
+
+  local cur_session_name
+  local -a match
+
+  while read -r line; do
+    if [[ $line =~ 'session=([^[:blank:]]+)' ]]; then
+      cur_session_name=$match[1]
+      break
+    fi
+  done < $lttngrc_path
+
+  if [[ -z $cur_session_name ]]; then
+    return 1
+  fi
+
+  echo -n $cur_session_name
+}
+
+# Prints the equivalent status adjective (`enabled` or `disabled`) for
+# an `enabled` XML property, or `unknown` on error.
+__lttng_status_from_enabled_prop() {
+  local -r prop=$1
+
+  case $prop in
+    true) echo -n enabled;;
+    false) echo -n disabled;;
+    *) echo -n unknown;;
+  esac
+}
+
+# Prints the XML document of `lttng list $2` (specifics of a single
+# recording session).
+#
+# `$1` is a message of what's expected to show on error.
+__lttng_session_xml() {
+  local -r msg=$1 session_name=$2
+
+  __lttng_mi_run $msg list $session_name
+}
+
+# Adds completions for a channel name.
+#
+# This function relies on the tracing domain options of `$opt_args`,
+# `$opt_args[-s]`, `$opt_args[--session]`, and the first non-option
+# argument to restrict the offered completions.
+#
+# Arguments:
+#
+# `$1`:
+#     One of:
+#
+#     `all`:
+#         Add completions for enabled and disabled channels.
+#
+#     `enabled`:
+#         Only add completions for enabled channels.
+#
+#     `disabled`:
+#         Only add completions for disabled channels.
+#
+# `$2`:
+#     `opt`:
+#         Use `$opt_args[-s]` and `$opt_args[--session]` to find the
+#         name of the selected recording session.
+#
+#     `arg`:
+#         Use `$line[1]` to find the name of the selected recording
+#         session.
+__lttng_complete_channel_name() {
+  local -r req_status=$1 session_name_src=$2
+
+  shift 2
+
+  # Find the recording session name to use
+  local session_name
+
+  if [[ $session_name_src = opt ]]; then
+    if (($+opt_args[-s])); then
+      session_name=$opt_args[-s]
+    elif (($+opt_args[--session])); then
+      session_name=$opt_args[--session]
+    fi
+  elif [[ $session_name_src = arg ]]; then
+    session_name=$line[1]
+  fi
+
+  if [[ -z $session_name ]]; then
+    # Fall back to current recording session
+    session_name=$(__lttng_cur_session_name)
+
+    if (($? != 0)); then
+      _guard '^-*' 'channel name'
+      return
+    fi
+  fi
+
+  # Get XML document (detailed recording session)
+  local session_xml
+
+  session_xml=$(__lttng_session_xml 'channel name' $session_name)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Count tracing domains
+  local -i domain_count
+
+  domain_count=$(__lttng_xmllint_xpath $session_xml 'count(//*[local-name()="domain"])')
+
+  if (($? != 0 || domain_count == 0)); then
+    _guard '^-*' 'channel name'
+    return
+  fi
+
+  # Append the name and info of one channel at a time
+  local domain_xml domain prop
+  local channel_xml channel_name channel_status channel_erl_mode
+  local -a channel_names channel_infos
+  local -i channel_count domain_index channel_index
+
+  # For each tracing domain
+  for domain_index in {1..$domain_count}; do
+    # Get tracing domain XML node
+    domain_xml=$(__lttng_xmllint_xpath $session_xml "//*[local-name()='domain'][$domain_index]")
+
+    if (($? != 0)); then
+      continue
+    fi
+
+    # Get tracing domain type
+    domain=$(__lttng_xmllint_xpath $domain_xml '/*/*[local-name()="type"]/text()')
+
+    if (($? != 0)); then
+      continue
+    fi
+
+    # Skip unexpected tracing domains
+    if [[ $domain = KERNEL ]]; then
+      if __lttng_user_domain_opt_is_set; then
+        # Skip unexpected Linux kernel tracing domain
+        continue
+      fi
+
+      domain='Linux kernel'
+    fi
+
+    if [[ $domain = UST ]]; then
+      if __lttng_kernel_domain_opt_is_set; then
+        # Skip unexpected user space tracing domain
+        continue
+      fi
+
+      domain='user space'
+    fi
+
+    # Count channels within tracing domain
+    channel_count=$(__lttng_xmllint_xpath $domain_xml 'count(//*[local-name()="channel"])')
+
+    if (($? != 0 || channel_count == 0)); then
+      continue
+    fi
+
+    # For each channel
+    for channel_index in {1..$channel_count}; do
+      # Get channel XML node
+      channel_xml=$(__lttng_xmllint_xpath $domain_xml "//*[local-name()='channel'][$channel_index]")
+
+      if (($? != 0)); then
+        continue
+      fi
+
+      # Get channel name
+      channel_name=$(__lttng_name_prop_from_xml $channel_xml channel)
+
+      if (($? != 0)); then
+        continue
+      fi
+
+      # Get channel status
+      channel_status=$(__lttng_enabled_prop_from_xml $channel_xml channel)
+
+      if (($? != 0)); then
+        continue
+      fi
+
+      channel_status=$(__lttng_status_from_enabled_prop $channel_status)
+
+      if [[ $req_status != all && $req_status != $channel_status ]]; then
+        # Skip channel with unexpected status
+        continue
+      fi
+
+      # Get channel event record loss mode
+      channel_erl_mode=$(__lttng_xmllint_xpath $channel_xml '//*[local-name()="attributes"]/*[local-name()="overwrite_mode"]/text()')
+
+      if (($? != 0)); then
+        continue
+      fi
+
+      if [[ $channel_erl_mode = DISCARD ]]; then
+        channel_erl_mode=discard
+      elif [[ $channel_erl_mode = OVERWRITE ]]; then
+        channel_erl_mode=overwrite
+      fi
+
+      channel_names+=("$channel_name")
+      channel_infos+=("$channel_status, $domain, $channel_erl_mode mode")
+    done
+  done
+
+  # No channels: show message
+  if (($#channel_names == 0)); then
+    _guard '^-*' 'channel name'
+    return
+  fi
+
+  # Compute maximum channel info length
+  local channel_info
+  local -i max_info_len=0 len
+
+  for channel_info in $channel_infos; do
+    len=$#channel_info
+
+    if ((len > max_info_len)); then
+      max_info_len=$len
+    fi
+  done
+
+  # Compute maximum channel name length
+  local -i max_name_len=0
+
+  for channel_name in $channel_names; do
+    len=$#channel_name
+
+    if ((len > max_name_len)); then
+      max_name_len=$len
+    fi
+  done
+
+  # Some room for the longest info string, two spaces, and two brackets
+  local -ir max_possible_name_len=$((COLUMNS - max_info_len - 5))
+
+  if ((max_name_len > max_possible_name_len)); then
+    # Clamp
+    max_name_len=$max_possible_name_len
+  fi
+
+  # Create the dislay strings (name, status, tracing domain, mode)
+  local -a disps
+
+  for channel_index in {1..${#channel_names}}; do
+    disps+=("${(r:$max_name_len:: :)channel_names[$channel_index]}  [$channel_infos[$channel_index]]")
+  done
+
+  # Add completions
+  local expl
+
+  if __lttng_style_is_verbose channel channels; then
+    # Verbose mode (list with infos).
+    #
+    # Using `-2` as Linux kernel and user space channels may have the
+    # same name, but we want to show the different infos.
+    _wanted -C channel channels expl 'channel name' \
+      compadd "$@" -2 -d disps -l -a channel_names
+  else
+    # Just the channel names, no duplicates
+    _wanted -C channel channels expl 'channel name' \
+      compadd "$@" -a channel_names
+  fi
+}
+
+# Add completions for instrumentation point names.
+#
+# This function relies on the tracing domain options of `$opt_args` and
+# `$opt_args[ip---syscall]` to restrict the offered completions.
+__lttng_complete_ip_name() {
+  local msg
+  local -a list_opts
+
+  if __lttng_kernel_domain_opt_is_set; then
+    list_opts=(-k)
+
+    if (($+opt_args[ip---syscall])); then
+      msg='system call name (no `sys_` prefix)'
+      list_opts+=(--syscall)
+    else
+      msg='Linux kernel tracepoint name'
+    fi
+  elif __lttng_user_domain_opt_is_set; then
+    msg='user space tracepoint name'
+    list_opts=(-u)
+  elif __lttng_jul_domain_opt_is_set; then
+    msg='`java.util.logging` logger name'
+    list_opts=(-j)
+  elif __lttng_log4j_domain_opt_is_set; then
+    msg='Apache log4j logger name'
+    list_opts=(-l)
+  elif __lttng_python_domain_opt_is_set; then
+    msg='Python logger name'
+    list_opts=(-p)
+  else
+    # No tracing domain option
+    _guard '^-*' 'instrumentation point or recording event rule name'
+    return
+  fi
+
+  # Get XML list of available instrumentation point names
+  local list_xml
+
+  list_xml=$(__lttng_mi_run $msg list $list_opts)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Convert to one instrumentation point name per line
+  local ip_names
+
+  ip_names=$(__lttng_xmllint_xpath $list_xml '//*[local-name()="event"]//*[local-name()="name"]/text()')
+
+  if (($? != 0)) || [[ -z $ip_names ]]; then
+    # `xmllint` error or no instrumentation points
+    _guard '^-*' $msg
+    return
+  fi
+
+  local ip_name
+  local -a items
+
+  while read -r ip_name; do
+    if [[ -z $ip_name ]]; then
+      continue
+    fi
+
+    items+=($ip_name)
+  done <<< $ip_names
+
+  # Add completions
+  local expl
+
+  _wanted instrumentation-points expl $msg compadd "$@" -a items
+}
+
+# Adds completions for the arguments of the `add-context` command.
+__lttng_complete_add_context_cmd() {
+  local specs=(
+    $help_opt_specs
+    '(- : *)--list[list the available context field types]'
+    '(--list -s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name inactive all'
+    '(--list -c --channel)'{-c+,--channel=}'[select a specific channel]: : __lttng_complete_channel_name enabled opt'
+    '(--list)*'{-t+,--type=}'[add a context field to be recorded]: : __lttng_complete_context_type'
+    + '(domain)'
+    '(--list)'{-k,--kernel}'[select the Linux kernel tracing domain]'
+    '(--list)'{-u,--userspace}'[select the user space tracing domain]'
+  )
+
+  # The Java tracing domain options require LTTng-tools ≥ 2.8 (for
+  # application-specific context field types).
+  if ((minor_version >= 8)); then
+    specs+=(
+      '(--list)'{-j,--jul}'[select the `java.util.logging` tracing domain]'
+      '(--list)'{-l,--log4j}'[select the Apache log4j tracing domain]'
+    )
+  fi
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for log level names.
+#
+# This function relies on the tracing domain options of `$opt_args` to
+# restrict the offered completions.
+__lttng_complete_log_level() {
+  local -a log_levels
+
+  # Fill the `log_levels` array depending on the tracing domain option
+  if __lttng_user_domain_opt_is_set; then
+    log_levels=(
+      EMERG
+      ALERT
+      CRIT
+      ERR
+      WARNING
+      NOTICE
+      INFO
+      DEBUG_SYSTEM
+      DEBUG_PROGRAM
+      DEBUG_PROCESS
+      DEBUG_MODULE
+      DEBUG_UNIT
+      DEBUG_FUNCTION
+      DEBUG_LINE
+      DEBUG
+    )
+  elif __lttng_jul_domain_opt_is_set; then
+    log_levels=(
+      OFF
+      SEVERE
+      WARNING
+      INFO
+      CONFIG
+      FINE
+      FINER
+      FINEST
+      ALL
+    )
+  elif __lttng_log4j_domain_opt_is_set; then
+    log_levels=(
+      OFF
+      FATAL
+      ERROR
+      WARN
+      INFO
+      DEBUG
+      TRACE
+      ALL
+    )
+  elif __lttng_python_domain_opt_is_set; then
+    log_levels=(
+      CRITICAL
+      ERROR
+      WARNING
+      INFO
+      DEBUG
+      NOTSET
+    )
+  else
+    # No tracing domain option
+    _guard '^-*' 'log level name'
+  fi
+
+  # Add completions
+  local expl
+
+  _wanted log-levels expl 'log level name' compadd -a log_levels
+}
+
+# Adds completions for a trigger condition type.
+__lttng_complete_trigger_condition_type() {
+  local -r types=(
+    'event-rule-matches:an event rule matches an event'
+  )
+
+  # Add completions
+  local expl
+
+  _describe 'trigger condition type' types
+}
+
+# Adds completions for a trigger action type.
+__lttng_complete_trigger_action_type() {
+  local -r types=(
+    'notify:send a notification through the notification mechanism'
+    'start-session:start a recording session'
+    'stop-session:stop a recording session'
+    'rotate-session:archive the current trace chunk of a recording session'
+    'snapshot-session:take a recording session snapshot'
+  )
+
+  # Add completions
+  local expl
+
+  _describe 'trigger action type' types
+}
+
+# Adds completions for the arguments of the `add-trigger` command.
+#
+# Note that those completions are incomplete, in that:
+#
+# • A valid event rule specification, as per lttng-event-rule(7),
+#   must follow `--condition=event-rule-matches`.
+#
+# • `--capture` options are possible within an `event-rule-matches`
+#   condition specifier.
+#
+# • The `--rate-policy` option and other arguments, sometimes mandatory,
+#   are possible within an action specifier.
+#
+# Having full completion for condition and action specifiers require
+# more Zsh magic as _arguments(), like most command-line argument
+# parsers, doesn't take option positions into account.
+__lttng_complete_add_trigger_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-n --name)'{-n+,--name=}'[set the trigger name]:new trigger name:'
+    '--owner-uid=[add the trigger as another Unix user]: : __lttng_complete_uid'
+    '--condition=[set the condition type and arguments]: : __lttng_complete_trigger_condition_type'
+    '*--action=[set the action type and arguments]: : __lttng_complete_trigger_action_type'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `clear` command.
+__lttng_complete_clear_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-a --all):: : __lttng_complete_session_name all all'
+    '(1 -a --all)'{-a,--all}'[clear all recording sessions]'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `create` command.
+__lttng_complete_create_cmd() {
+  local specs=(
+    $help_opt_specs
+    ':: :_guard "^-*" "new recording session name"'
+    '(-C --ctrl-url output)'{-C+,--ctrl-url=}'[set the control URL]:control URL:'
+    '(-D --data-url output)'{-D+,--data-url=}'[set the trace data output URL]:trace data output URL:'
+  )
+
+  # The `--shm-path` option requires LTTng-tools ≥ 2.7
+  if ((minor_version >= 7)); then
+    specs+=(
+      '--shm-path=[write shared memory files to a specific directory]:shared memory file directory:_files -/'
+    )
+  fi
+
+  # Add the remaining option groups
+  specs+=(
+    + '(output)'
+    '(-D --data-url -C --ctrl-url --live)--no-output[disable trace data output]'
+    '(-D --data-url -C --ctrl-url --live)'{-o+,--output=}'[set the local trace data output directory]:trace data output directory:_files -/'
+    '(-D --data-url -C --ctrl-url)'{-U+,--set-url=}'[set the trace data output and control URL]:trace data output and control URL:'
+    + '(mode)'
+    '(-o --output --no-output)--live=[create an LTTng live recording session]:live timer period (µs):'
+    '--snapshot[create a snapshot recording session]'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `destroy` command.
+__lttng_complete_destroy_cmd() {
+  local specs=(
+    $help_opt_specs
+    '(-a --all):: : __lttng_complete_session_name all all'
+    '(1 -a --all)'{-a,--all}'[destroy all recording sessions]'
+  )
+
+  # The `--no-wait` option requires LTTng-tools ≥ 2.8
+  if ((minor_version >= 8)); then
+    specs+=(
+      '(-n --no-wait)'{-n,--no-wait}'[exit immediately]'
+    )
+  fi
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `disable-channel` command.
+__lttng_complete_disable_channel_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    ': : _sequence __lttng_complete_channel_name enabled opt'
+    + '(domain)'
+    {-k,--kernel}'[select the Linux kernel tracing domain]'
+    {-u,--userspace}'[select the user space tracing domain]'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Prints the XML tracing domain name value depending on the tracing
+# domain option (in `$opt_args`), or prints nothing and returns 1 when
+# not available.
+__lttng_xml_domain_name_from_opt() {
+  if __lttng_kernel_domain_opt_is_set; then
+    echo -n KERNEL
+  elif __lttng_user_domain_opt_is_set; then
+    echo -n UST
+  elif __lttng_jul_domain_opt_is_set; then
+    echo -n JUL
+  elif __lttng_log4j_domain_opt_is_set; then
+    echo -n LOG4J
+  elif __lttng_python_domain_opt_is_set; then
+    echo -n PYTHON
+  else
+    return 1
+  fi
+}
+
+# Prints the XML instrumentation point type value depending on the
+# instrumentation point option (in `$opt_args`).
+__lttng_xml_ip_type_from_opt() {
+  if (($+opt_args[--syscall] || $+opt_args[ip---syscall])); then
+    echo -n SYSCALL
+  elif (($+opt_args[--probe] || $+opt_args[ip---probe])); then
+    echo -n PROBE
+  elif (($+opt_args[--function] || $+opt_args[ip---function])); then
+    echo -n FUNCTION
+  else
+    echo -n TRACEPOINT
+  fi
+}
+
+# Adds completions for an old, enabled recording event rule name
+# condition (for the `disable-event` command).
+__lttng_complete_old_enabled_er_name_cond() {
+  local -r msg='recording event rule name condition'
+
+  # Find the recording session name to use
+  local session_name
+
+  if (($+opt_args[-s])); then
+    session_name=$opt_args[-s]
+  elif (($+opt_args[--session])); then
+    session_name=$opt_args[--session]
+  else
+    # Fall back to current recording session
+    session_name=$(__lttng_cur_session_name)
+
+    if (($? != 0)); then
+      _guard '^-*' $msg
+    fi
+  fi
+
+  # Find the channel name to use (`channel0` is the default name)
+  local channel_name=channel0
+
+  if (($+opt_args[-c])); then
+    channel_name=$opt_args[-c]
+  elif (($+opt_args[--channel])); then
+    channel_name=$opt_args[--channel]
+  fi
+
+  # Create tracing domain XPath part
+  local domain_xpath
+  local xml_domain_val
+
+  xml_domain_val=$(__lttng_xml_domain_name_from_opt)
+
+  if (($? == 0)); then
+    domain_xpath="*[local-name() = 'domain'][*[local-name() = 'type'] = '$xml_domain_val']//"
+  fi
+
+  # Create channel XPath part
+  local -r channel_xpath="*[local-name() = 'channel'][*[local-name() = 'name'] = '$channel_name']//"
+
+  # Create instrumentation point type XPath part
+  local -r xml_ip_type_val=$(__lttng_xml_ip_type_from_opt)
+  local -r ip_type_xpath="[*[local-name() = 'type'] = '$xml_ip_type_val']"
+
+  # Get XML document (detailed recording session)
+  local session_xml
+
+  session_xml=$(__lttng_session_xml $msg $session_name)
+
+  if (($? != 0)); then
+    return 1
+  fi
+
+  # Convert to one recording event rule name per line
+  local lines
+
+  lines=$(__lttng_xmllint_xpath $session_xml "//$domain_xpath${channel_xpath}*[local-name() = 'event']${ip_type_xpath}[*[local-name() = 'enabled'] = 'true']/*[local-name() = 'name']/text()")
+
+  if (($? != 0)); then
+    _guard '^-*' $msg
+    return
+  fi
+
+  local -a er_names
+
+  while read -r line; do
+    if [[ -z ${line// } ]]; then
+      # Skip empty line
+      continue
+    fi
+
+    er_names+=$line
+  done <<< $lines
+
+  # Add completions
+  local expl
+
+  _wanted -C event events expl $msg compadd "$@" -a er_names
+}
+
+# Adds completions for the arguments of the `disable-event` command.
+__lttng_complete_disable_event_cmd() {
+  local -r kernel_ip_opt_excl=(--syscall --probe --function)
+  local specs=(
+    $help_opt_specs
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    '(-c --channel)'{-c+,--channel=}'[select a specific channel]: : __lttng_complete_channel_name all opt'
+    + '(names)'
+    {-a,--all-events}'[disable all recording event rules]'
+    ': :_sequence __lttng_complete_old_enabled_er_name_cond'
+    + '(domain)'
+    {-k,--kernel}'[select the Linux kernel tracing domain]'
+    "($kernel_ip_opt_excl)"{-u,--userspace}'[select the user space tracing domain]'
+    "($kernel_ip_opt_excl)"{-j,--jul}'[select the `java.util.logging` tracing domain]'
+  )
+
+  # Add tracing domain option specifications based on the minor version
+  # of LTTng-tools.
+  if ((minor_version >= 6)); then
+    specs+=(
+      "($kernel_ip_opt_excl)"{-l,--log4j}'[select the Apache log4j tracing domain]'
+    )
+  fi
+
+  if ((minor_version >= 7)); then
+    specs+=(
+      "($kernel_ip_opt_excl)"{-p,--python}'[select the Python tracing domain]'
+    )
+  fi
+
+  # Add instrumentation point type option specifications based on the
+  # minor version of LTTng-tools.
+  if ((minor_version >= 6)); then
+    specs+=(
+      + '(ip)'
+      "($non_kernel_domain_opt_excl)--syscall[disable recording ER matching Linux system call events]"
+    )
+  fi
+
+  if ((minor_version >= 7)); then
+    specs+=(
+      '--tracepoint[disable recording ER matching tracepoint events]'
+      "($non_kernel_domain_opt_excl)--probe[disable recording ER matching kprobe events]"
+      "($non_kernel_domain_opt_excl)--function[disable recording ER matching kretprobe events]"
+    )
+  fi
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `disable-rotation` command.
+__lttng_complete_disable_rotation_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    '--timer[disable the periodic rotation schedule]'
+    '--size[disable the size-based rotation schedule]'
+  )
+
+  __lttng_arguments $specs
+}
+
+# Adds completions for a channel output type (`mmap` and, possibly,
+# `splice`) (for the `--output` option of the `enable-channel` command).
+#
+# This function replaces the argument field of the current context with
+# `output-opt`.
+#
+# This function relies on the user space tracing domain options of
+# `$opt_args` to restrict the offered completions. Without the user
+# space tracing domain option, this function adds the `splice`
+# completion too.
+__lttng_complete_channel_output_type() {
+  local output_types=(mmap)
+
+  if ! __lttng_user_domain_opt_is_set; then
+    # Linux kernel tracing domain or none
+    output_types+=(splice)
+  fi
+
+  local expl
+
+  _wanted -C 'output-opt' values expl 'output type' compadd -a output_types
+}
+
+# Adds completions for the non-option argument of the `enable-channel`
+# command.
+#
+# This function either, depending on the keys of `$opt_args`:
+#
+# At least one creation option:
+#     Shows a message to enter the new channel name.
+#
+# Otherwise:
+#     Adds completions for a comma-separated list of known channel names
+#     using __lttng_complete_channel_name().
+__lttng_complete_enable_channel_cmd_names() {
+  local key
+  local -r enable_opts=(
+    -s --session
+    domain---kernel domain--k
+    domain---userspace domain--u
+  )
+
+  # For each key of `$opt_args`
+  for key in "${(@k)opt_args}"; do
+    if (($enable_opts[(Ie)$key])); then
+      # Enabling option exists: skip
+      continue
+    fi
+
+    # Creation option exists: single name
+    _guard '^-*' 'new channel name'
+    return
+  done
+
+  # Comma-separated list of existing channel names
+  _sequence __lttng_complete_channel_name disabled opt
+}
+
+# Adds completions for the arguments of the `enable-channel` command.
+__lttng_complete_enable_channel_cmd() {
+  local specs=(
+    $help_opt_specs
+    '--switch-timer=[set the switch timer period]:switch timer period (µs):'
+    '--read-timer=[set the read timer period]:read timer period (µs):'
+    '--subbuf-size=[set the size of each sub-buffer]:sub-buffer size (bytes; `k`/`M`/`G` suffixes supported):'
+    '--num-subbuf=[set the number of sub-buffers per ring buffer]:sub-buffer count:'
+    '--tracefile-size=[set the maximum size of each trace file]:trace file size (bytes; `k`/`M`/`G` suffixes supported):'
+    '--tracefile-count=[set the maximum number of trace files]:maximum trace file count:'
+    '--output=[set the output type]: : __lttng_complete_channel_output_type'
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    ': : __lttng_complete_enable_channel_cmd_names'
+  )
+
+  # The `--blocking-timeout` and `--monitor-timer` options require
+  # LTTng-tools ≥ 2.10.
+  if ((minor_version >= 10)); then
+    specs+=(
+      '(--kernel --overwrite --buffers-global)--blocking-timeout=[set the blocking timeout]:blocking timeout (µs):'
+      '--monitor-timer=[set the monitor timer period]:monitor timer period (µs):'
+    )
+  fi
+
+  # Add the remaining option groups
+  specs+=(
+    + '(domain)'
+    '(--blocking-timeout --buffers-uid --buffers-pid)'{-k,--kernel}'[select the Linux kernel tracing domain]'
+    '(--buffers-global)'{-u,--userspace}'[select the user space tracing domain]'
+    + '(loss-mode)'
+    '--discard[discard event records with no available sub-buffer]'
+    '(--blocking-timeout)--overwrite[overwrite oldest sub-buffer with no available sub-buffer]'
+    + '(buffering)'
+    '(-k --kernel)--buffers-uid[use per-user ring buffers]'
+    '(-k --kernel)--buffers-pid[use per-process ring buffers]'
+    '(-u --userspace --blocking-timeout)--buffers-global[use global ring buffers]'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `enable-event` command.
+__lttng_complete_enable_event_cmd() {
+  local -r kernel_opts_excl=(
+    -k --kernel
+    --syscall
+    --probe
+    --userspace-probe
+    --function
+  )
+  local -r non_kernel_opts_excl=(
+    $non_kernel_domain_opt_excl
+    -x --exclude
+    log-level
+  )
+  local -r exclude_opt_excl=(
+    $kernel_opts_excl
+    -j --jul
+    -l --log4j
+    -p --python
+    -x --exclude
+  )
+  local ip_specs=(
+    '--tracepoint[only match LTTng tracepoint events]'
+    "($non_kernel_opts_excl)--syscall[only match Linux system call events]"
+    "($non_kernel_opts_excl)--probe=[only match kprobe events]:kprobe location:"
+    "($non_kernel_opts_excl)--function=[only match kretprobe events]:kretprobe location:"
+  )
+  local domain_specs=(
+    "($non_kernel_opts_excl)"{-k,--kernel}'[select the Linux kernel tracing domain]'
+    "($kernel_opts_excl)"{-u,--userspace}'[select the user space tracing domain]'
+    "($kernel_opts_excl -x --exclude)"{-j,--jul}'[select the `java.util.logging` tracing domain]'
+  )
+
+  # The Apache log4j tracing domain options require LTTng-tools ≥ 2.6
+  if ((minor_version >= 6)); then
+    domain_specs+=(
+      "($kernel_opts_excl -x --exclude)"{-l,--log4j}'[select the Apache log4j tracing domain]'
+    )
+  fi
+
+  # The Python tracing domain options require LTTng-tools 2.7
+  if ((minor_version >= 7)); then
+    domain_specs+=(
+      "($kernel_opts_excl -x --exclude)"{-p,--python}'[select the Python tracing domain]'
+    )
+  fi
+
+  # The Linux user space probe instrumentation options require LTTng-tools 2.11
+  if ((minor_version >= 11)); then
+    ip_specs+=(
+      "($non_kernel_opts_excl)--userspace-probe=[only match Linux user space probe events]:user space probe location:"
+    )
+  fi
+
+  # Add completions.
+  #
+  # There's no way, based on the command-line arguments, to distinguish
+  # between creating a new recording event rule and enabling an
+  # existing, disabled recording event rule here.
+  #
+  # For example, given this:
+  #
+  #     $ lttng enable-event --kernel --syscall <TAB>
+  #
+  # At this point, the user might want the list of existing, disabled
+  # kernel system call recording event rule names (current recording
+  # session, default channel name), or the full list of available system
+  # call instrumentation point names.
+  #
+  # This function makes the arbitrary choice to provide the available
+  # instrumentation point names (__lttng_complete_ip_name()) because,
+  # interactively, it seems to be more common/useful than disabling
+  # existing recording event rules.
+  local -r specs=(
+    $help_opt_specs
+    '(--probe --userspace-probe --function -f --filter)'{-f+,--filter=}'[only match events which satisfy an expression]:filter expression:'
+    "($exclude_opt_excl)"{-x+,--exclude=}'[exclude event name patterns]:comma-separated list of patterns:'
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    '(-c --channel)'{-c+,--channel=}'[select a specific channel]: : __lttng_complete_channel_name all opt'
+    + '(log-level)'
+    "($kernel_opts_excl)--loglevel=[only match events with specific log levels]: : __lttng_complete_log_level"
+    "($kernel_opts_excl)--loglevel-only=[only match events with an exact log level]: : __lttng_complete_log_level"
+    + '(names)'
+    {-a,--all}'[match events regardless of their name]'
+    ': :_sequence __lttng_complete_ip_name'
+    + '(ip)' $ip_specs
+    + '(domain)' $domain_specs
+  )
+
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `enable-rotation` command.
+__lttng_complete_enable_rotation_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    '--timer=[rotate periodically]:period (µs; `ms`/`s`/`m`/`h` suffixes supported):'
+    '--size=[rotate based on flushed size of current trace chunk]:size (bytes; `k`/`M`/`G` suffixes supported):'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `help` command.
+__lttng_complete_help_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    ': : __lttng_complete_cmd_name'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `list` command.
+__lttng_complete_list_cmd() {
+  local -r domain_opt_excl=(
+    -d --domain
+    -f --fields
+    -c --channel
+    -k --kernel
+    -u --userspace
+    -j --jul
+    -l --log4j
+    -p --python
+    --syscall
+  )
+  local specs=(
+    $help_opt_specs
+    '(-d --domain -f --fields --syscall -c --channel 1)'{-f,--fields}'[show instrumentation point fields]'
+    "($domain_opt_excl)"{-d,--domain}'[show tracing domains with at least one channel]'
+    '(-d --domain -f --fields --syscall -c --channel)'{-c+,--channel=}'[list the objects of a specific channel]: : __lttng_complete_channel_name all arg'
+    '(-d --domain -f --fields --syscall):recording session name: __lttng_complete_session_name all all'
+    '(-d --domain -k --kernel)'{-k,--kernel}'[list Linux kernel tracing domain objects]'
+    '(-d --domain -u --userspace)'{-u,--userspace}'[list user space tracing domain objects]'
+    '(-d --domain -j --jul)'{-j,--jul}'[list `java.util.logging` tracing domain objects]'
+  )
+
+  # The Apache log4j tracing domain and `--syscall` options require
+  # LTTng-tools ≥ 2.6.
+  if ((minor_version >= 6)); then
+    specs+=(
+      '(-d --domain -l --log4j)'{-l,--log4j}'[list Apache log4j tracing domain objects]'
+      '(-d --domain)--syscall[list Linux kernel system calls]'
+    )
+  fi
+
+  # The Python tracing domain options require LTTng-tools 2.7
+  if ((minor_version >= 7)); then
+    specs+=(
+      '(-d --domain -p --python)'{-p,--python}'[list Python tracing domain objects]'
+    )
+  fi
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `list-triggers` command.
+__lttng_complete_list_triggers_cmd() {
+  __lttng_arguments $help_opt_specs
+}
+
+# Adds completions for the arguments of the `load` command.
+__lttng_complete_load_cmd() {
+  local specs=(
+    $help_opt_specs
+    '(-f --force)'{-f,--force}'[overwrite existing recording sessions]'
+    '(-i --input-path)'{-i+,--input-path=}'[load recording session configurations from a specific path]:recording session configuration path:_files'
+    '(-a --all --override-name 1)'{-a,--all}'[load all recording session configurations]'
+    '(-a --all):recording session configuration name:_guard "^-*" "recording session name"'
+  )
+
+  if ((minor_version >= 9)); then
+    specs+=(
+      '--override-url=[override the loaded recording session output URL]:output URL:'
+      '(-a --all)--override-name=[override the loaded recording session name]:recording session name:'
+    )
+  fi
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `metadata` command
+# (deprecated).
+__lttng_complete_metadata_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    ':action:(regenerate)'
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `regenerate` command.
+__lttng_complete_regenerate_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    ':trace data type:(metadata statedump)'
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `remove-trigger` command.
+__lttng_complete_remove_trigger_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '--owner-uid=[remove the trigger as another Unix user]: : __lttng_complete_uid'
+    ': : __lttng_complete_trigger_name'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `rotate` command.
+__lttng_complete_rotate_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-n --no-wait)'{-n,--no-wait}'[exit immediately]'
+    ': : __lttng_complete_session_name all all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `save` command.
+__lttng_complete_save_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-f --force)'{-f,--force}'[overwrite existing recording session configuration files]'
+    '(-o --output-path)'{-o+,--output-path=}'[save recording session configuration files to a specific directory]:recording session configuration directory:_files -/'
+    '(-a --all 1)'{-a,--all}'[save all recording session configurations]'
+    '(-a --all): : __lttng_complete_session_name all all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `set-session` command.
+__lttng_complete_set_session_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    ': : __lttng_complete_session_name all all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `snapshot` command.
+__lttng_complete_snapshot_cmd() {
+  local specs=(
+    $help_opt_specs
+    '(-): : __lttng_complete_snapshot_action_name' \
+    '(-)*:: :->action-args' \
+  )
+
+  # Add action name completions
+  local curcontext=$curcontext state state_descr line
+  local -A opt_args
+
+  _arguments -C -s -W : $specs
+
+  if (($? == 0)); then
+    # Completions added: we're done
+    return
+  fi
+
+  # Add action-specific completions
+  local -r common_session_specs=(
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all snapshot'
+  )
+  local -r common_output_specs=(
+    '(-m --max-size)'{-m+,--max-size=}'[set the maximum total size of all snapshot files]:maximum size (bytes; `k`/`M`/`G` suffixes supported):'
+    '(-n --name)'{-n+,--name=}'[set the snapshot output name]:snapshot output name:'
+    '(1 -C --ctrl-url output)'{-C+,--ctrl-url=}'[set the control URL]:control URL:'
+    '(1 -D --data-url output)'{-D+,--data-url=}'[set the trace data output URL]:trace data output URL:'
+    '(-C --ctrl-url -D --data-url): :_guard "^-*" "snapshot output URL"'
+  )
+
+  if [[ $state[1] = action-args ]]; then
+    # Add completions for the arguments of the specific snapshot action
+    curcontext=${curcontext%:*:*}:lttng-snapshot-$line[1]:
+
+    case $line[1] in
+      add-output | record)
+        specs=($common_session_specs $common_output_specs);;
+      del-output)
+        specs=($common_session_specs ':snapshot output index:(1)');;
+      list-output)
+        specs=($common_session_specs);;
+      *)
+        _message "unknown snapshot action \`$line[1]\`"
+        return 1
+        ;;
+    esac
+
+    # Add completions
+    __lttng_arguments $specs
+    return
+  fi
+
+  return 1
+}
+
+# Adds completions for the arguments of the `start` command.
+__lttng_complete_start_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    ': : __lttng_complete_session_name inactive all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `stop` command.
+__lttng_complete_stop_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-n --no-wait)'{-n,--no-wait}'[exit immediately]'
+    ': : __lttng_complete_session_name active all'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `status` command.
+__lttng_complete_status_cmd() {
+  __lttng_arguments $help_opt_specs
+}
+
+# Adds completions for the arguments of the `track` command.
+__lttng_complete_track_cmd() {
+  local specs=(
+    $help_opt_specs
+    '(-s --session)'{-s+,--session=}'[select a specific recording session]: : __lttng_complete_session_name all all'
+    '(-a --all)'{-a,--all}'[add all possible values to the selected inclusion sets]'
+    '(-p --pid)'{-p+,--pid=}'[add values to the process ID inclusion set]:process ID(s):_sequence _pids'
+  )
+
+  # Virtual PID and user/group inclusion sets require LTTng-tools ≥ 2.12
+  if ((minor_version >= 12)); then
+    specs+=(
+      '--vpid=[add values to the virtual process ID inclusion set]:virtual process ID(s):_sequence _pids'
+      '(-u --userspace)--uid=[add values to the user ID inclusion set]:user(s):_sequence _users'
+      '--vuid=[add values to the virtual user ID inclusion set]:virtual user(s):_sequence _users'
+      '(-u --userspace)--gid=[add values to the group ID inclusion set]:group(s):_sequence _groups'
+      '--vgid=[add values to the virtual group ID inclusion set]:virtual group(s):_sequence _groups'
+    )
+  fi
+
+  # Append tracing domain specifications
+  specs+=(
+    + '(domain)'
+    {-k,--kernel}'[select the Linux kernel tracing domain]'
+    "(--uid --gid)"{-u,--userspace}'[select the user space tracing domain]'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Adds completions for the arguments of the `untrack` command.
+__lttng_complete_untrack_cmd() {
+  # As of LTTng-tools 2.13, the `track` and `untrack` commands expect
+  # the same arguments.
+  __lttng_complete_track_cmd
+}
+
+# Adds completions for the arguments of the `version` command.
+__lttng_complete_version_cmd() {
+  __lttng_arguments $help_opt_specs
+}
+
+# Adds completions for the arguments of the `view` command.
+__lttng_complete_view_cmd() {
+  local -r specs=(
+    $help_opt_specs
+    '(-e --viewer)'{-e+,--viewer=}'[set the trace reader path]:trace reader path:_files'
+    '(-t --trace-path): : __lttng_complete_session_name all all'
+    '(1 -t --trace-path)'{-t+,--trace-path=}'[set the trace directory to pass to the reader]:trace directory:_files -/'
+  )
+
+  # Add completions
+  __lttng_arguments $specs
+}
+
+# Add completions for the specific `lttng` command named `$line[1]`.
+__lttng_complete_cmd() {
+  # An lttng(1) command: replace `lttng` with `lttng-$line[1]` (for
+  # example, `lttng-add-trigger`).
+  curcontext=${curcontext%:*:*}:lttng-$line[1]:
+
+  # Keep the tracing group: we need to execute `lttng` for some
+  # completions and use the required tracing group to connect to the
+  # same session daemon.
+  #
+  # The default tracing group is `tracing`.
+  local tracing_group=tracing
+
+  if (($+opt_args[-g])); then
+    tracing_group=$opt_args[-g]
+  elif (($+opt_args[--group])); then
+    tracing_group=$opt_args[--group]
+  fi
+
+  # Add command completions: dispatch to a dedicated function
+  local -r func_name=__lttng_complete_${line[1]//-/_}_cmd
+
+  if ! typeset -f $func_name >/dev/null; then
+    _message "unknown command \`$line[1]\`"
+    return 1
+  fi
+
+  local -A opt_args
+
+  $func_name
+}
+
+# Save program name
+local -r prog_name=$words[1]
+
+# First, set the `minor_version` variable to the minor version of
+# LTTng-tools. Some features depend on a specific version and this
+# completion function supports many versions from LTTng-tools 2.5.
+local -i minor_version
+
+__lttng_set_minor_version
+
+# Exit now with LTTng-tools < 2.5 or LTTng-tools > 2.14
+local -r ignore_version_limit=${LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT:-0}
+
+if ((minor_version < 5 || (minor_version > 14 && !ignore_version_limit))); then
+  _message "completion not available for LTTng-tools 2.$minor_version; please update the completion files or set \`LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1\`"
+  return 1
+fi
+
+# Common help option specifications
+local -r help_opt_specs=(
+  '(- : *)'{-h,--help}'[show help]'
+)
+
+# Common non Linux kernel tracing domain option exclusions
+local -r non_kernel_domain_opt_excl=(-u --userspace -j --jul -l --log4j -p --python)
+
+# General option specifications
+local gen_opt_specs=(
+  $help_opt_specs
+  '(- : *)--list-commands[list the available commands and quit]'
+  '--relayd-path=[set the relay daemon path]:relay daemon path:_files -g \*lttng-relayd'
+  '--group=[set the tracing group]:tracing group:_groups'
+  '(-q --quiet)*'{-v,--verbose}'[increase verbosity]'
+  '(-q --quiet -v --verbose)'{-q,--quiet}'[suppress all messages, including warnings and errors]'
+  '(- : *)'{-V,--version}'[show version and quit]'
+)
+
+# MI output requires LTTng-tools ≥ 2.6
+if ((minor_version >= 6)); then
+  gen_opt_specs+=(
+    '(-m --mi)'{-m+,--mi=}'[use the machine interface output]:machine interface type:(xml)'
+  )
+fi
+
+# Append session daemon option specifications
+gen_opt_specs+=(
+  + '(sessiond)'
+  {-n,--no-sessiond}'[do not spawn a session daemon]'
+  '--sessiond-path=[set the session daemon path]:session daemon path:_files -g \*lttng-sessiond'
+)
+
+# Add general option and command name completions
+local curcontext=$curcontext state state_descr line
+local -A opt_args
+
+_arguments -C -s -W : \
+  '(-): : __lttng_complete_cmd_name' \
+  '(-)*:: :->cmd-args' \
+  $gen_opt_specs
+
+local -ir main_ret=$?
+
+if ((main_ret == 0)); then
+  # Completions added: we're done
+  return
+fi
+
+if [[ $state[1] = cmd-args ]]; then
+  # Add completions for the arguments of the specific command
+  __lttng_complete_cmd
+  return
+fi
+
+return $main_ret
diff --git a/extras/zsh-completion/_lttng-crash b/extras/zsh-completion/_lttng-crash
new file mode 100644 (file)
index 0000000..f595217
--- /dev/null
@@ -0,0 +1,75 @@
+#compdef lttng-crash
+#
+# Copyright (c) 2015-2023 Philippe Proulx <eeppeliteloop@gmail.com>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+#
+# This is a Zsh completion function for the lttng-crash(1) command (see
+# <https://lttng.org/>), for versions 2.7 to 2.14.
+#
+# If you want, at your own risk, the function to work with versions
+# above 2.14, set `LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1`.
+
+# Sets the `minor_version` variable to the minor version of LTTng-tools,
+# or to `0` if not found.
+__lttng_set_minor_version() {
+  minor_version=0
+
+  local -a match
+
+  if [[ $($words[1] --version) =~ '[[:blank:]]+2\.([[:digit:]]+)' ]]; then
+    minor_version=$match[1]
+  fi
+}
+
+# Adds completions for the arguments of the `lttng-crash` command.
+__lttng_complete_lttng_crash() {
+  local curcontext=$curcontext state state_descr line
+  local -A opt_args
+  local specs=(
+    '*'{-v,--verbose}'[increase verbosity]'
+    '(- : *)'{-V,--version}'[show version and quit]'
+    '(- : *)'{-h,--help}'[show help]'
+    '(-x --extract)'{-x+,--extract=}'[set the path of the directory where to extract the trace]:trace extraction directory path:_directories'
+    '(-e --viewer)'{-e+,--viewer=}'[set the trace reader command]:trace reader command:_files'
+    '1:shared memory directory:_directories'
+  )
+
+  _arguments -C -s -w : $specs
+}
+
+# First, set the `minor_version` variable to the minor version of
+# LTTng-tools. Some features depend on a specific version and this
+# completion function supports many versions from LTTng-tools 2.7.
+local -i minor_version
+
+__lttng_set_minor_version
+
+# Exit now with LTTng-tools < 2.7 or LTTng-tools > 2.14
+local -r ignore_version_limit=${LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT:-0}
+
+if ((minor_version < 7 || (minor_version > 14 && !ignore_version_limit))); then
+  _message "completion not available for LTTng-tools 2.$minor_version; please update the completion files or set \`LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1\`"
+  return 1
+fi
+
+# Add completions for lttng-crash(1)
+__lttng_complete_lttng_crash "$@"
diff --git a/extras/zsh-completion/_lttng-relayd b/extras/zsh-completion/_lttng-relayd
new file mode 100644 (file)
index 0000000..8d1140f
--- /dev/null
@@ -0,0 +1,93 @@
+#compdef lttng-relayd
+#
+# Copyright (c) 2015-2023 Philippe Proulx <eeppeliteloop@gmail.com>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+#
+# This is a Zsh completion function for the lttng-relayd(1) command
+# (see <https://lttng.org/>), for versions 2.5 to 2.14.
+#
+# If you want, at your own risk, the function to work with versions
+# above 2.14, set `LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1`.
+
+# Sets the `minor_version` variable to the minor version of LTTng-tools,
+# or to `0` if not found.
+__lttng_set_minor_version() {
+  minor_version=0
+
+  local -a match
+
+  if [[ $($words[1] --version) =~ '2\.([[:digit:]]+)' ]]; then
+    minor_version=$match[1]
+  fi
+}
+
+# Adds completions for the arguments of the `lttng-relayd` command.
+__lttng_complete_lttng_relayd() {
+  local curcontext=$curcontext state state_descr line
+  local -A opt_args
+
+  # LTTng-tools 2.5+
+  local specs=(
+    '*'{-v,--verbose}'[increase verbosity]'
+    '(- : *)'{-V,--version}'[show version and quit]'
+    '(- : *)'{-h,--help}'[show help]'
+    '(-d --daemonize -b --background)'{-d,--daemonize}'[start as daemon and close file descriptors (console)]'
+    '(-b --background -d --daemonize)'{-b,--background}'[start as daemon, but keep file descriptors (console) open]'
+    '(-C --control-port)'{-C+,--control-port=}'[set the control port URL]:control port URL: '
+    '(-D --data-port)'{-D+,--data-port=}'[set the data port URL]:data port URL: '
+    '(-L --live-port)'{-L+,--live-port=}'[set the live port URL]:live port URL: '
+    '(-o --output)'{-o+,--output=}'[set the trace output directory path]:trace output directory path:_directories'
+    '(-g --group)'{-g+,--group=}'[set the Unix tracing group name]:Unix tracing group name:_groups'
+    '(-f --config)'{-f+,--config=}'[set the path to the INI daemon configuration file]:configuration file path:_files'
+  )
+
+  # LTTng-tools 2.12+
+  if ((minor_version >= 12)); then
+    specs+=(
+      '(--fd-pool-size)--fd-pool-size=[set the size of the file descriptor pool]:file descriptor pool size: '
+      '(-w --working-directory)'{-w+,--working-directory=}'[set the working directory of the processes `lttng-relayd` creates]:working directory:_directories'
+      '(-p --group-output-by-host -s --group-output-by-session)'{-p,--group-output-by-host}'[group the written trace directories by hostname]'
+      '(-p --group-output-by-host -s --group-output-by-session)'{-s,--group-output-by-session}'[group the written trace directories by recording session name]'
+      '(-x --disallow-clear)'{-x,--disallow-clear}'[disallow clearing operations]'
+    )
+  fi
+
+  _arguments -C -s -w : $specs
+}
+
+# First, set the `minor_version` variable to the minor version of
+# LTTng-tools. Some features depend on a specific version and this
+# completion function supports many versions from LTTng-tools 2.5.
+local -i minor_version
+
+__lttng_set_minor_version
+
+# Exit now with LTTng-tools < 2.5 or LTTng-tools > 2.14
+local -r ignore_version_limit=${LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT:-0}
+
+if ((minor_version < 5 || (minor_version > 14 && !ignore_version_limit))); then
+  _message "completion not available for LTTng-tools 2.$minor_version; please update the completion files or set \`LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1\`"
+  return 1
+fi
+
+# Add completions for lttng-relayd(1)
+__lttng_complete_lttng_relayd "$@"
diff --git a/extras/zsh-completion/_lttng-sessiond b/extras/zsh-completion/_lttng-sessiond
new file mode 100644 (file)
index 0000000..7388c0c
--- /dev/null
@@ -0,0 +1,153 @@
+#compdef lttng-sessiond
+#
+# Copyright (c) 2015-2023 Philippe Proulx <eeppeliteloop@gmail.com>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+#
+# This is a Zsh completion function for the lttng-sessiond(1) command
+# (see <https://lttng.org/>), for versions 2.5 to 2.14.
+#
+# If you want, at your own risk, the function to work with versions
+# above 2.14, set `LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1`.
+
+# Sets the `minor_version` variable to the minor version of LTTng-tools,
+# or to `0` if not found.
+__lttng_set_minor_version() {
+  minor_version=0
+
+  local -a match
+
+  if [[ $($words[1] --version) =~ '2\.([[:digit:]]+)' ]]; then
+    minor_version=$match[1]
+  fi
+}
+
+# Adds completions for an LTTng kernel probe name.
+__lttng_complete_probe_modules() {
+  # Find relevant kernel module files
+  local dir="/usr/lib/modules/$(uname -r)/extra"
+
+  if [[ ! -d $dir ]]; then
+    dir="/usr/lib/modules/$(uname -r)/updates"
+
+    if [[ ! -d $dir ]]; then
+      _message "cannot find directory \"$dir\""
+      return 1
+    fi
+  fi
+
+  local -a probe_files=("$dir"/**/lttng-probe-*.(ko|ko.gz|ko.zst)(:t))
+
+  if (($#probe_files == 0)); then
+    _message "no probe modules found in \"$dir\""
+    return 1
+  fi
+
+  # Strip prefix and extension
+  probe_files=(${probe_files#lttng-probe-})
+  probe_files=(${probe_files%.gz})
+  probe_files=(${probe_files%.zst})
+  probe_files=(${probe_files%.ko})
+
+  # Add completions
+  local expl
+
+  compadd "$@" -a - probe_files
+}
+
+# Adds completions for the arguments of the `lttng-sessiond` command.
+__lttng_complete_lttng_sessiond() {
+  local curcontext=$curcontext state state_descr line
+  local -A opt_args
+
+  # LTTng-tools 2.5+
+  local specs=(
+    '(-q --quiet)*'{-v,--verbose}'[increase verbosity]'
+    '(-q --quiet -v --verbose)'{-q,--quiet}'[suppress all messages, including warnings and errors]'
+    '(- : *)'{-V,--version}'[show version and quit]'
+    '(- : *)'{-h,--help}'[show help]'
+    '(-c --client-sock)'{-c+,--client-sock=}'[set the path to the client Unix socket]:client Unix socket path:_files'
+    '(-a --apps-sock)'{-a+,--apps-sock=}'[set the path to the app Unix socket]:app Unix socket path:_files'
+    '--kconsumerd-err-sock=[set the path to the kernel consumer daemon error socket]:kernel consumer daemon error Unix socket path:_files'
+    '--kconsumerd-cmd-sock=[set the path to the kernel consumer daemon command socket]:kernel consumer daemon command Unix socket path:_files'
+    '--ustconsumerd32-err-sock=[set the path to the 32-bit UST consumer daemon error Unix socket]:32-bit UST consumer daemon error Unix socket path:_files'
+    '--ustconsumerd32-cmd-sock=[set the path to the 32-bit UST consumer daemon command Unix socket]:32-bit UST consumer daemon command Unix socket path:_files'
+    '--ustconsumerd64-err-sock=[set the path to the 64-bit UST consumer daemon error Unix socket]:64-bit UST consumer daemon error Unix socket path:_files'
+    '--ustconsumerd64-cmd-sock=[set the path to the 64-bit UST consumer daemon command Unix socket]:64-bit UST consumer daemon command Unix socket path:_files'
+    '--consumerd32-path=[set the path to the 32-bit UST consumer daemon]:32-bit UST consumer daemon path:_files'
+    '--consumerd32-libdir=[set the path to the directory containing 32-bit UST consumer daemon libraries]:32-bit UST consumer daemon libraries directory path:_directories'
+    '--consumerd64-path=[set the path to the 64-bit UST consumer daemon]:64-bit UST consumer daemon path:_files'
+    '--consumerd64-libdir=[set the path to the directory containing 64-bit UST consumer daemon libraries]:64-bit UST consumer daemon libraries directory path:_directories'
+    '(-d --daemonize -b --background)'{-d,--daemonize}'[start as daemon and close file descriptors (console)]'
+    '(-b --background -d --daemonize)'{-b,--background}'[start as daemon, but keep file descriptors (console) open]'
+    '(-g --group)'{-g+,--group=}'[set the Unix tracing group name]:Unix tracing group name:_groups'
+    '(-S --sig-parent)'{-S,--sig-parent}'[send the USR1 signal to the parent process to notify readiness]'
+    '(-p --pidfile)'{-p+,--pidfile=}'[set the path to the PID file]:PID file path:_files'
+    "--verbose-consumer[increase verbosity of consumer daemon]"
+    '(--kmod-probes --extra-kmod-probes)--no-kernel[disable the kernel tracer]'
+    '(-f --config)'{-f+,--config=}'[set the path to the INI daemon configuration file]:configuration file path:_files'
+    '(-l --load)'{-l+,--load=}'[set the path from which to load recording session configurations]:recording session configurations path:_files'
+    '(--no-kernel --kmod-probes)--extra-kmod-probes=[extra kernel probe modules to load]:kernel probe module:_sequence __lttng_complete_probe_modules'
+  )
+
+  # LTTng-tools 2.5 only
+  if ((minor_version == 5)); then
+    specs+=(
+      '--jul-tcp-port=[set the TCP port on which to listen for `java.util.logging` application registration]:JUL application registration TCP port: '
+    )
+  fi
+
+  # LTTng-tools 2.6+
+  if ((minor_version >= 6)); then
+    specs+=(
+      '--agent-tcp-port=[set the TCP port on which to listen for agent application registration]:agent application registration TCP port: '
+      '(--no-kernel --extra-kmod-probes)--kmod-probes=[kernel probe modules to load]:kernel probe module:_sequence __lttng_complete_probe_modules'
+    )
+  fi
+
+  # LTTng-tools 2.13+
+  if ((minor_version >= 13)); then
+    specs+=(
+      '--event-notifier-error-buffer-size-kernel=[set the size of the kernel event notifier error counter buffers]:kernel event notifier error counter buffer size (slots): '
+      '--event-notifier-error-buffer-size-userspace=[set the size of the user space event notifier error counter buffers]:user space event notifier error counter buffer size (slots): '
+    )
+  fi
+
+  _arguments -C -s -w : $specs
+}
+
+# First, set the `minor_version` variable to the minor version of
+# LTTng-tools. Some features depend on a specific version and this
+# completion function supports many versions from LTTng-tools 2.5.
+local -i minor_version
+
+__lttng_set_minor_version
+
+# Exit now with LTTng-tools < 2.5 or LTTng-tools > 2.14
+local -r ignore_version_limit=${LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT:-0}
+
+if ((minor_version < 5 || (minor_version > 14 && !ignore_version_limit))); then
+  _message "completion not available for LTTng-tools 2.$minor_version; please update the completion files or set \`LTTNG_ZSH_COMP_IGNORE_VERSION_LIMIT=1\`"
+  return 1
+fi
+
+# Add completions for lttng-sessiond(1)
+__lttng_complete_lttng_sessiond "$@"
diff --git a/format-cpp b/format-cpp
new file mode 100755 (executable)
index 0000000..17275de
--- /dev/null
@@ -0,0 +1,56 @@
+#!/bin/bash
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Copyright (C) 2020-2022 Philippe Proulx <pproulx@efficios.com>
+
+expected_formatter_major_version=14
+
+# Runs the formatter, making sure it's the expected version.
+format_cpp() {
+       local formatter=$1
+       local version
+
+       version=$($formatter --version)
+
+        # shellcheck disable=SC2181
+       if (($? != 0)); then
+               echo "Cannot execute \`$formatter --version\`." >&2
+               return 1
+       fi
+
+       if [[ "$version" != *"clang-format version $expected_formatter_major_version"* ]]; then
+               echo "Expecting clang-format $expected_formatter_major_version." >&2
+               echo -n Got: >&2
+               echo " \`$version\`" >&2
+               echo >&2
+               echo "Use the FORMATTER environment variable to specify the location of clang-format $expected_formatter_major_version"
+               return 1
+       fi
+
+       local root_dir
+
+       root_dir="$(dirname "${BASH_SOURCE[0]}")"
+
+       # Using xargs to fail as soon as the formatter fails (`-exec`
+       # won't stop if its subprocess fails).
+       #
+       # shellcheck disable=SC2086
+       find "$root_dir" -path './src/vendor' -prune \
+               -o -type f \( -name '*\.h' -o -name '*\.hpp' -o -name '*\.c' -o -name '*\.cpp' \) \
+               -not -path '*/\.*' -print0 | xargs -P$(nproc) -n1 -0 $formatter -i --style=file --fallback-style=none
+}
+
+if [[ -n "$FORMATTER" ]]; then
+       # Try using environment-provided formatter
+       formatter=$FORMATTER
+elif command -v clang-format-$expected_formatter_major_version &> /dev/null; then
+       # Try using the expected version of clang-format
+       formatter="clang-format-$expected_formatter_major_version"
+else
+       # Try using `clang-format` as is
+       formatter='clang-format'
+fi
+
+# Try to format files
+format_cpp "$formatter"
index d840d58dcd8458487348a993feddde279d531485..a2d6a5cf015eea6c9b3b907b4ca917d00b541814 100644 (file)
@@ -110,6 +110,7 @@ lttnginclude_HEADERS = \
        lttng/event.h \
        lttng/handle.h \
        lttng/health.h \
+       lttng/kernel.h \
        lttng/kernel-probe.h \
        lttng/load.h \
        lttng/location.h \
index 996e166ec2b6e8548f1dd5750b19552c41c2ee1d..bf55fa8037eb8a5fe23fb6bb9179425b0a3c3208 100644 (file)
@@ -13,7 +13,9 @@
 #include <common/macros.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/lttng.h>
+
 #include <pthread.h>
 #include <stdbool.h>
 #include <sys/types.h>
@@ -24,22 +26,17 @@ struct mi_writer;
 struct mi_lttng_error_query_callbacks;
 struct lttng_trigger;
 
-typedef bool (*action_validate_cb)(struct lttng_action *action);
-typedef void (*action_destroy_cb)(struct lttng_action *action);
-typedef int (*action_serialize_cb)(struct lttng_action *action,
-               struct lttng_payload *payload);
-typedef bool (*action_equal_cb)(const struct lttng_action *a,
-               const struct lttng_action *b);
-typedef ssize_t (*action_create_from_payload_cb)(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
-typedef const struct lttng_rate_policy *(*action_get_rate_policy_cb)(
-               const struct lttng_action *action);
-typedef enum lttng_action_status (*action_add_error_query_results_cb)(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results);
-typedef enum lttng_error_code (*action_mi_serialize_cb)(
-               const struct lttng_action *condition, struct mi_writer *writer);
+using action_validate_cb = bool (*)(struct lttng_action *);
+using action_destroy_cb = void (*)(struct lttng_action *);
+using action_serialize_cb = int (*)(struct lttng_action *, struct lttng_payload *);
+using action_equal_cb = bool (*)(const struct lttng_action *, const struct lttng_action *);
+using action_create_from_payload_cb = ssize_t (*)(struct lttng_payload_view *,
+                                                 struct lttng_action **);
+using action_get_rate_policy_cb = const struct lttng_rate_policy *(*) (const struct lttng_action *);
+using action_add_error_query_results_cb = enum lttng_action_status (*)(
+       const struct lttng_action *, struct lttng_error_query_results *);
+using action_mi_serialize_cb = enum lttng_error_code (*)(const struct lttng_action *,
+                                                        struct mi_writer *);
 
 struct lttng_action {
        struct urcu_ref ref;
@@ -75,31 +72,29 @@ struct lttng_action_comm {
 } LTTNG_PACKED;
 
 void lttng_action_init(struct lttng_action *action,
-               enum lttng_action_type type,
-               action_validate_cb validate,
-               action_serialize_cb serialize,
-               action_equal_cb equal,
-               action_destroy_cb destroy,
-               action_get_rate_policy_cb get_rate_policy,
-               action_add_error_query_results_cb add_error_query_results,
-               action_mi_serialize_cb mi);
+                      enum lttng_action_type type,
+                      action_validate_cb validate,
+                      action_serialize_cb serialize,
+                      action_equal_cb equal,
+                      action_destroy_cb destroy,
+                      action_get_rate_policy_cb get_rate_policy,
+                      action_add_error_query_results_cb add_error_query_results,
+                      action_mi_serialize_cb mi);
 
 bool lttng_action_validate(struct lttng_action *action);
 
-int lttng_action_serialize(struct lttng_action *action,
-               struct lttng_payload *buf);
+int lttng_action_serialize(struct lttng_action *action, struct lttng_payload *buf);
 
 ssize_t lttng_action_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_action **action);
+                                        struct lttng_action **action);
 
-bool lttng_action_is_equal(const struct lttng_action *a,
-               const struct lttng_action *b);
+bool lttng_action_is_equal(const struct lttng_action *a, const struct lttng_action *b);
 
 void lttng_action_get(struct lttng_action *action);
 
 void lttng_action_put(struct lttng_action *action);
 
-const charlttng_action_type_string(enum lttng_action_type action_type);
+const char *lttng_action_type_string(enum lttng_action_type action_type);
 
 void lttng_action_increase_execution_request_count(struct lttng_action *action);
 
@@ -109,23 +104,23 @@ void lttng_action_increase_execution_failure_count(struct lttng_action *action);
 
 bool lttng_action_should_execute(const struct lttng_action *action);
 
-enum lttng_action_status lttng_action_add_error_query_results(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results);
+enum lttng_action_status
+lttng_action_add_error_query_results(const struct lttng_action *action,
+                                    struct lttng_error_query_results *results);
 
 /*
  * For use by the various lttng_action implementation. Implements the default
  * behavior to the generic error "execution failure counter" that all actions
  * (except list, which passes-through) provide.
  */
-enum lttng_action_status lttng_action_generic_add_error_query_results(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results);
-enum lttng_error_code lttng_action_mi_serialize(const struct lttng_trigger *trigger,
-               const struct lttng_action *action,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks,
-               struct lttng_dynamic_array *action_path_indexes);
+enum lttng_action_status
+lttng_action_generic_add_error_query_results(const struct lttng_action *action,
+                                            struct lttng_error_query_results *results);
+enum lttng_error_code
+lttng_action_mi_serialize(const struct lttng_trigger *trigger,
+                         const struct lttng_action *action,
+                         struct mi_writer *writer,
+                         const struct mi_lttng_error_query_callbacks *error_query_callbacks,
+                         struct lttng_dynamic_array *action_path_indexes);
 
 #endif /* LTTNG_ACTION_INTERNAL_H */
index 70237e43cd772fea79b0b8ecea332820d3e2d5b5..6e303f4414527441e515754d2ff824cdf07dccea 100644 (file)
@@ -39,8 +39,7 @@ enum lttng_action_status {
  *
  * Returns the type of an action on success, LTTNG_ACTION_TYPE_UNKNOWN on error.
  */
-LTTNG_EXPORT extern enum lttng_action_type lttng_action_get_type(
-               const struct lttng_action *action);
+LTTNG_EXPORT extern enum lttng_action_type lttng_action_get_type(const struct lttng_action *action);
 
 /*
  * Destroy (frees) an action object.
index 294a53ca24841c2769f12811f7a3a1c73a1a885f..607d5981887df3d8fceb1f958c9b9faab910c837 100644 (file)
@@ -8,10 +8,16 @@
 #ifndef LTTNG_ACTION_LIST_INTERNAL_H
 #define LTTNG_ACTION_LIST_INTERNAL_H
 
-#include <sys/types.h>
-
+#include <common/container-wrapper.hpp>
+#include <common/exception.hpp>
+#include <common/format.hpp>
 #include <common/macros.hpp>
 
+#include <lttng/lttng.h>
+
+#include <assert.h>
+#include <sys/types.h>
+
 struct lttng_action;
 struct lttng_payload_view;
 struct mi_writer;
@@ -25,18 +31,67 @@ struct lttng_trigger;
  * On success, return the number of bytes consumed from `view`, and the created
  * list in `*list`. On failure, return -1.
  */
-extern ssize_t lttng_action_list_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **list);
-
-extern struct lttng_action *lttng_action_list_borrow_mutable_at_index(
-               const struct lttng_action *list, unsigned int index);
-
-enum lttng_error_code lttng_action_list_mi_serialize(const struct lttng_trigger *trigger,
-               const struct lttng_action *action,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks,
-               struct lttng_dynamic_array *action_path_indexes);
+extern ssize_t lttng_action_list_create_from_payload(struct lttng_payload_view *view,
+                                                    struct lttng_action **list);
+
+extern struct lttng_action *
+lttng_action_list_borrow_mutable_at_index(const struct lttng_action *list, unsigned int index);
+
+enum lttng_error_code
+lttng_action_list_mi_serialize(const struct lttng_trigger *trigger,
+                              const struct lttng_action *action,
+                              struct mi_writer *writer,
+                              const struct mi_lttng_error_query_callbacks *error_query_callbacks,
+                              struct lttng_dynamic_array *action_path_indexes);
+
+namespace lttng {
+namespace ctl {
+namespace details {
+class action_list_operations {
+public:
+       static lttng_action *get(const lttng_action *list, std::size_t index) noexcept
+       {
+               return lttng_action_list_borrow_mutable_at_index(list, index);
+       }
+
+       static std::size_t size(const lttng_action *list)
+       {
+               unsigned int count;
+               const auto status = lttng_action_list_get_count(list, &count);
+
+               if (status != LTTNG_ACTION_STATUS_OK) {
+                       LTTNG_THROW_INVALID_ARGUMENT_ERROR(
+                               "Failed to get action list element count");
+               }
+
+               return count;
+       }
+};
+
+class const_action_list_operations {
+public:
+       static const lttng_action *get(const lttng_action *list, std::size_t index) noexcept
+       {
+               return lttng_action_list_get_at_index(list, index);
+       }
+
+       static std::size_t size(const lttng_action *list)
+       {
+               return action_list_operations::size(list);
+       }
+};
+} /* namespace details */
+
+using action_list_view = utils::random_access_container_wrapper<const lttng_action *,
+                                                               lttng_action *,
+                                                               details::action_list_operations>;
+
+using const_action_list_view =
+       utils::random_access_container_wrapper<const lttng_action *,
+                                              const lttng_action *,
+                                              details::const_action_list_operations>;
+
+} /* namespace ctl */
+} /* namespace lttng */
 
 #endif /* LTTNG_ACTION_LIST_INTERNAL_H */
index 0dfffa296ad073e1e597c942bc9dcb252aec5430..5fe3a503b111eb30669a993047af084a8d3de1dc 100644 (file)
@@ -33,14 +33,14 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_list_create(void);
  *
  * Adding an action list to an action list is not supported.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_list_add_action(
-               struct lttng_action *list, struct lttng_action *action);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_list_add_action(struct lttng_action *list, struct lttng_action *action);
 
 /*
  * Get the number of actions in an action list.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_list_get_count(
-               const struct lttng_action *list, unsigned int *count);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_list_get_count(const struct lttng_action *list, unsigned int *count);
 
 /*
  * Get an action from the action list at a given index.
@@ -51,9 +51,8 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_list_get_count(
  *
  * Returns an action, or NULL on error.
  */
-LTTNG_EXPORT extern const struct lttng_action *lttng_action_list_get_at_index(
-               const struct lttng_action *list,
-               unsigned int index);
+LTTNG_EXPORT extern const struct lttng_action *
+lttng_action_list_get_at_index(const struct lttng_action *list, unsigned int index);
 
 #ifdef __cplusplus
 }
index c923019c31235e8426d24784c895620c9ee69aa4..2d4d1bd4ad9e2f9fc53492a7cc920eba21aa14a5 100644 (file)
@@ -8,16 +8,15 @@
 #ifndef LTTNG_ACTION_NOTIFY_INTERNAL_H
 #define LTTNG_ACTION_NOTIFY_INTERNAL_H
 
-#include <lttng/action/notify.h>
 #include <lttng/action/action-internal.hpp>
+#include <lttng/action/notify.h>
 
 struct lttng_action_notify {
        struct lttng_action parent;
        struct lttng_rate_policy *policy;
 };
 
-ssize_t lttng_action_notify_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
+ssize_t lttng_action_notify_create_from_payload(struct lttng_payload_view *view,
+                                               struct lttng_action **action);
 
 #endif /* LTTNG_ACTION_NOTIFY_INTERNAL_H */
index 3aa55e09c8e5084cdce97a1a2f3980e9787dad76..300e28507473a1cb5d7ccdfa96b702b8124b2537 100644 (file)
@@ -39,9 +39,9 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_notify_create(void);
  * LTTNG_ACTION_STATUS_ERROR on internal error,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_notify_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_notify_set_rate_policy(struct lttng_action *action,
+                                   const struct lttng_rate_policy *policy);
 
 /*
  * Get the rate policy of a notify action.
@@ -49,9 +49,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_notify_set_rate_policy
  * Returns LTTNG_ACTION_STATUS_OK on success,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_notify_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_notify_get_rate_policy(const struct lttng_action *action,
+                                   const struct lttng_rate_policy **policy);
 
 #ifdef __cplusplus
 }
index f07776b9bb251790c5a741ed56a1fa01ce3ea562..4ad63844915f6bd51b7e807ba48876ebbb095d03 100644 (file)
@@ -8,25 +8,25 @@
 #ifndef LTTNG_ACTION_PATH_INTERNAL_H
 #define LTTNG_ACTION_PATH_INTERNAL_H
 
-#include <lttng/action/path.h>
-#include <common/macros.hpp>
 #include <common/dynamic-array.hpp>
+#include <common/macros.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
+#include <lttng/action/path.h>
+
 #include <sys/types.h>
 
 struct lttng_action_path {
        struct lttng_dynamic_array indexes;
 };
 
-int lttng_action_path_copy(const struct lttng_action_path *src,
-               struct lttng_action_path **dst);
+int lttng_action_path_copy(const struct lttng_action_path *src, struct lttng_action_path **dst);
 
-ssize_t lttng_action_path_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action_path **action_path);
+ssize_t lttng_action_path_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_action_path **action_path);
 
 int lttng_action_path_serialize(const struct lttng_action_path *action_path,
-               struct lttng_payload *payload);
+                               struct lttng_payload *payload);
 
 #endif /* LTTNG_ACTION_PATH_INTERNAL_H */
index 6ec91676b9e090f57a5688537a20dda537ec6409..88d8b640d3586e4b9c58afa7d42bbc396cbae421 100644 (file)
@@ -9,8 +9,9 @@
 #define LTTNG_ACTION_PATH_H
 
 #include <lttng/lttng-export.h>
-#include <stdint.h>
+
 #include <stddef.h>
+#include <stdint.h>
 
 struct lttng_action_path;
 
@@ -45,22 +46,20 @@ enum lttng_action_path_status {
  *
  * The `indexes` are copied internally and can be disposed-of by the caller.
  */
-LTTNG_EXPORT extern struct lttng_action_path *lttng_action_path_create(
-               const uint64_t *indexes, size_t index_count);
+LTTNG_EXPORT extern struct lttng_action_path *lttng_action_path_create(const uint64_t *indexes,
+                                                                      size_t index_count);
 
 /*
  * Get the count of indexes in an action path.
  */
-LTTNG_EXPORT extern enum lttng_action_path_status lttng_action_path_get_index_count(
-               const struct lttng_action_path *path, size_t *index_count);
+LTTNG_EXPORT extern enum lttng_action_path_status
+lttng_action_path_get_index_count(const struct lttng_action_path *path, size_t *index_count);
 
 /*
  * Get an index from an action path.
  */
 LTTNG_EXPORT extern enum lttng_action_path_status lttng_action_path_get_index_at_index(
-               const struct lttng_action_path *path,
-               size_t path_index,
-               uint64_t *out_index);
+       const struct lttng_action_path *path, size_t path_index, uint64_t *out_index);
 
 /*
  * Destroy an action path object.
index 5f6eb1f456b3eaed003d4e1b199e46d6131c925e..643a01cdac22689efa7a59ba98ede77a14a5abef 100644 (file)
 
 #include <common/macros.hpp>
 #include <common/payload-view.hpp>
+
 #include <lttng/action/rate-policy.h>
 #include <lttng/lttng-error.h>
-#include <stdbool.h>
 
+#include <stdbool.h>
 
 struct mi_writer;
 
-int lttng_rate_policy_serialize(struct lttng_rate_policy *rate_policy,
-               struct lttng_payload *buf);
+int lttng_rate_policy_serialize(struct lttng_rate_policy *rate_policy, struct lttng_payload *buf);
 
 ssize_t lttng_rate_policy_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_rate_policy **rate_policy);
+                                             struct lttng_rate_policy **rate_policy);
 
 bool lttng_rate_policy_is_equal(const struct lttng_rate_policy *a,
-               const struct lttng_rate_policy *b);
+                               const struct lttng_rate_policy *b);
 
-const char *lttng_rate_policy_type_string(
-               enum lttng_rate_policy_type rate_policy_type);
+const char *lttng_rate_policy_type_string(enum lttng_rate_policy_type rate_policy_type);
 
-struct lttng_rate_policy *lttng_rate_policy_copy(
-               const struct lttng_rate_policy *source);
+struct lttng_rate_policy *lttng_rate_policy_copy(const struct lttng_rate_policy *source);
 
-bool lttng_rate_policy_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter);
+bool lttng_rate_policy_should_execute(const struct lttng_rate_policy *policy, uint64_t counter);
 
-enum lttng_error_code lttng_rate_policy_mi_serialize(
-               const struct lttng_rate_policy *policy,
-               struct mi_writer *writer);
+enum lttng_error_code lttng_rate_policy_mi_serialize(const struct lttng_rate_policy *policy,
+                                                    struct mi_writer *writer);
 
 #endif /* LTTNG_RATE_POLICY */
index 1cd0126e3dd52b6eeeaac3fccb94cf82d6a20dcd..229e14c0da4ecf4876b144b395deb0a24f471340 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef LTTNG_RATE_POLICY_H
 #define LTTNG_RATE_POLICY_H
 
-#include <inttypes.h>
 #include <lttng/lttng-export.h>
+
+#include <inttypes.h>
 #include <sys/types.h>
 
 struct lttng_rate_policy;
@@ -37,8 +38,8 @@ enum lttng_rate_policy_type {
 /*
  * Get the type of a rate policy.
  */
-LTTNG_EXPORT extern enum lttng_rate_policy_type lttng_rate_policy_get_type(
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_rate_policy_type
+lttng_rate_policy_get_type(const struct lttng_rate_policy *policy);
 
 /*
  * Create a rate_policy of type `every n`.
@@ -50,8 +51,7 @@ LTTNG_EXPORT extern enum lttng_rate_policy_type lttng_rate_policy_get_type(
  * rate_policy objects must be destroyed using the lttng_rate_policy_destroy()
  * function.
  */
-LTTNG_EXPORT extern struct lttng_rate_policy *lttng_rate_policy_every_n_create(
-               uint64_t interval);
+LTTNG_EXPORT extern struct lttng_rate_policy *lttng_rate_policy_every_n_create(uint64_t interval);
 
 /*
  * Get the interval of a every N rate policy.
@@ -60,8 +60,8 @@ LTTNG_EXPORT extern struct lttng_rate_policy *lttng_rate_policy_every_n_create(
  * on success, LTTNG_RATE_FIRING_POLICY_STATUS_INVALID if an invalid
  * parameter is passed.
  */
-LTTNG_EXPORT extern enum lttng_rate_policy_status lttng_rate_policy_every_n_get_interval(
-               const struct lttng_rate_policy *policy, uint64_t *interval);
+LTTNG_EXPORT extern enum lttng_rate_policy_status
+lttng_rate_policy_every_n_get_interval(const struct lttng_rate_policy *policy, uint64_t *interval);
 
 /*
  * Create a rate_policy of type `once after N`.
@@ -74,8 +74,8 @@ LTTNG_EXPORT extern enum lttng_rate_policy_status lttng_rate_policy_every_n_get_
  * rate_policy objects must be destroyed using the lttng_rate_policy_destroy()
  * function.
  */
-LTTNG_EXPORT extern struct lttng_rate_policy *lttng_rate_policy_once_after_n_create(
-               uint64_t threshold);
+LTTNG_EXPORT extern struct lttng_rate_policy *
+lttng_rate_policy_once_after_n_create(uint64_t threshold);
 
 /*
  * Get the threshold of a once after N rate policy.
@@ -85,8 +85,8 @@ LTTNG_EXPORT extern struct lttng_rate_policy *lttng_rate_policy_once_after_n_cre
  * parameter is passed.
  */
 LTTNG_EXPORT extern enum lttng_rate_policy_status
-lttng_rate_policy_once_after_n_get_threshold(
-               const struct lttng_rate_policy *policy, uint64_t *threshold);
+lttng_rate_policy_once_after_n_get_threshold(const struct lttng_rate_policy *policy,
+                                            uint64_t *threshold);
 
 /*
  * Destroy (frees) a rate policy object.
index 5030aeac335fa0003c728f8d8014fb98c549ebd9..cbab68e39d882d27af2c91422aadb0feaec9010a 100644 (file)
@@ -19,8 +19,7 @@ struct lttng_payload_view;
  * On success, return the number of bytes consumed from `view`, and the created
  * action in `*action`. On failure, return -1.
  */
-extern ssize_t lttng_action_rotate_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
+extern ssize_t lttng_action_rotate_session_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_action **action);
 
 #endif /* LTTNG_ACTION_ROTATE_SESSION_INTERNAL_H */
index 199b6f169a52eae8d852b92f47d53ee221e842c6..e628c5f52a7cce66d0f77ea893c6c093b1501ae5 100644 (file)
@@ -33,15 +33,16 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_rotate_session_create(void
  * Set the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_ROTATE_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_set_session_name(
-               struct lttng_action *action, const char *session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_rotate_session_set_session_name(struct lttng_action *action, const char *session_name);
 
 /*
  * Get the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_ROTATE_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_get_session_name(
-               const struct lttng_action *action, const char **session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_rotate_session_get_session_name(const struct lttng_action *action,
+                                            const char **session_name);
 
 /*
  * Set the rate policy of a rotate session action.
@@ -50,9 +51,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_get_ses
  * LTTNG_ACTION_STATUS_ERROR on internal error,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_rotate_session_set_rate_policy(struct lttng_action *action,
+                                           const struct lttng_rate_policy *policy);
 
 /*
  * Get the rate policy of a rotate session action.
@@ -60,9 +61,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_set_rat
  * Returns LTTNG_ACTION_STATUS_OK on success,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_rotate_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_rotate_session_get_rate_policy(const struct lttng_action *action,
+                                           const struct lttng_rate_policy **policy);
 
 #ifdef __cplusplus
 }
index 27a8795ade1f475a6d820ead0d7f0cd6d5b39645..3943fe8f31ba4de82e4f765995f7a08cdd57caa0 100644 (file)
@@ -8,10 +8,10 @@
 #ifndef LTTNG_ACTION_SNAPSHOT_SESSION_INTERNAL_H
 #define LTTNG_ACTION_SNAPSHOT_SESSION_INTERNAL_H
 
-#include <sys/types.h>
-
 #include <common/macros.hpp>
 
+#include <sys/types.h>
+
 struct lttng_action;
 struct lttng_payload_view;
 
@@ -21,8 +21,7 @@ struct lttng_payload_view;
  * On success, return the number of bytes consumed from `view`, and the created
  * action in `*action`. On failure, return -1.
  */
-extern ssize_t lttng_action_snapshot_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
+extern ssize_t lttng_action_snapshot_session_create_from_payload(struct lttng_payload_view *view,
+                                                                struct lttng_action **action);
 
 #endif /* LTTNG_ACTION_SNAPSHOT_SESSION_INTERNAL_H */
index 8590862007f9dc4fe7d3861dfac444f079340c91..aadb784b2c3de8e2f70c00314b4c730ea5650585 100644 (file)
@@ -34,15 +34,17 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_snapshot_session_create(vo
  * Set the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_SNAPSHOT_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_set_session_name(
-               struct lttng_action *action, const char *session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_set_session_name(struct lttng_action *action,
+                                              const char *session_name);
 
 /*
  * Get the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_SNAPSHOT_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_get_session_name(
-               const struct lttng_action *action, const char **session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_get_session_name(const struct lttng_action *action,
+                                              const char **session_name);
 
 /*
  * Set an explicit snapshot output for this snapshot session action.
@@ -52,16 +54,16 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_get_s
  *
  * This function takes ownership of the given snapshot output.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_set_output(
-               struct lttng_action *action,
-               struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_set_output(struct lttng_action *action,
+                                        struct lttng_snapshot_output *output);
 
 /*
  * Get the explicit snapshot output for this snapshot session action.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_get_output(
-               const struct lttng_action *action,
-               const struct lttng_snapshot_output **output);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_get_output(const struct lttng_action *action,
+                                        const struct lttng_snapshot_output **output);
 
 /*
  * Set the rate policy of a snapshot session action.
@@ -70,9 +72,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_get_o
  * LTTNG_ACTION_STATUS_ERROR on internal error,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_set_rate_policy(struct lttng_action *action,
+                                             const struct lttng_rate_policy *policy);
 
 /*
  * Get the rate policy of a snapshot session action.
@@ -80,9 +82,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_set_r
  * Returns LTTNG_ACTION_STATUS_OK on success,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_snapshot_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_snapshot_session_get_rate_policy(const struct lttng_action *action,
+                                             const struct lttng_rate_policy **policy);
 
 #ifdef __cplusplus
 }
index 44dab1bf1c9f439513d75c638c0eaee89a77836f..d33e073af43e38568ae7c3b24b4ef824292dcab0 100644 (file)
@@ -19,8 +19,7 @@ struct lttng_payload_view;
  * On success, return the number of bytes consumed from `view`, and the created
  * action in `*action`. On failure, return -1.
  */
-extern ssize_t lttng_action_start_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
+extern ssize_t lttng_action_start_session_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_action **action);
 
 #endif /* LTTNG_ACTION_START_SESSION_INTERNAL_H */
index db52000321c208481ba32cf2d45adbb11d82559a..da8c1c1b9f68c50792a43298ed2cd327715f6218 100644 (file)
@@ -33,15 +33,16 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_start_session_create(void)
  * Set the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_START_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_set_session_name(
-               struct lttng_action *action, const char *session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_start_session_set_session_name(struct lttng_action *action, const char *session_name);
 
 /*
  * Get the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_START_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_get_session_name(
-               const struct lttng_action *action, const char **session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_start_session_get_session_name(const struct lttng_action *action,
+                                           const char **session_name);
 
 /*
  * Set the rate policy of a start session action.
@@ -50,9 +51,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_get_sess
  * LTTNG_ACTION_STATUS_ERROR on internal error,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_start_session_set_rate_policy(struct lttng_action *action,
+                                          const struct lttng_rate_policy *policy);
 
 /*
  * Get the rate policy of a start session action.
@@ -60,9 +61,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_set_rate
  * Returns LTTNG_ACTION_STATUS_OK on success,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_start_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_start_session_get_rate_policy(const struct lttng_action *action,
+                                          const struct lttng_rate_policy **policy);
 
 #ifdef __cplusplus
 }
index 22055352fd9099b65600f4d1fff86e5555f9c690..46f1d6ebad6d64e6cfe9098d37adcf47ca9cdd00 100644 (file)
@@ -19,8 +19,7 @@ struct lttng_payload_view;
  * On success, return the number of bytes consumed from `view`, and the created
  * action in `*action`. On failure, return -1.
  */
-extern ssize_t lttng_action_stop_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action);
+extern ssize_t lttng_action_stop_session_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_action **action);
 
 #endif /* LTTNG_ACTION_STOP_SESSION_INTERNAL_H */
index 5b223ef23fbfa846a893b5a266801388a8f87941..b4a82a229353106521086cf9f168d84198ecf3f6 100644 (file)
@@ -33,15 +33,16 @@ LTTNG_EXPORT extern struct lttng_action *lttng_action_stop_session_create(void);
  * Set the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_STOP_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_set_session_name(
-               struct lttng_action *action, const char *session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_stop_session_set_session_name(struct lttng_action *action, const char *session_name);
 
 /*
  * Get the session name of an lttng_action object of type
  * LTTNG_ACTION_TYPE_STOP_SESSION.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_get_session_name(
-               const struct lttng_action *action, const char **session_name);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_stop_session_get_session_name(const struct lttng_action *action,
+                                          const char **session_name);
 
 /*
  * Set the rate policy of a stop session action.
@@ -50,9 +51,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_get_sessi
  * LTTNG_ACTION_STATUS_ERROR on internal error,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_stop_session_set_rate_policy(struct lttng_action *action,
+                                         const struct lttng_rate_policy *policy);
 
 /*
  * Get the rate policy of a stop session action.
@@ -60,9 +61,9 @@ LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_set_rate_
  * Returns LTTNG_ACTION_STATUS_OK on success,
  * LTTNG_ACTION_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_action_status lttng_action_stop_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy);
+LTTNG_EXPORT extern enum lttng_action_status
+lttng_action_stop_session_get_rate_policy(const struct lttng_action *action,
+                                         const struct lttng_rate_policy **policy);
 
 #ifdef __cplusplus
 }
index d4960828ec2da0844ada398f150ef916d96a3ae0..bcf3225ed6ed3f5b7fca5a64caaee715b644c213 100644 (file)
@@ -8,6 +8,7 @@
 #ifndef LTTNG_CHANNEL_INTERNAL_H
 #define LTTNG_CHANNEL_INTERNAL_H
 
+#include <common/error.hpp>
 #include <common/macros.hpp>
 
 struct lttng_channel_extended {
@@ -40,22 +41,19 @@ struct lttng_channel_comm {
        int64_t blocking_timeout;
 } LTTNG_PACKED;
 
-struct lttng_channel *lttng_channel_create_internal(void);
+struct lttng_channel *lttng_channel_create_internal();
 
 struct lttng_channel *lttng_channel_copy(const struct lttng_channel *src);
 
 ssize_t lttng_channel_create_from_buffer(const struct lttng_buffer_view *view,
-               struct lttng_channel **event);
+                                        struct lttng_channel **event);
 
-int lttng_channel_serialize(struct lttng_channel *channel,
-               struct lttng_dynamic_buffer *buf);
+int lttng_channel_serialize(struct lttng_channel *channel, struct lttng_dynamic_buffer *buf);
 
 void lttng_channel_set_default_extended_attr(struct lttng_domain *domain,
-               struct lttng_channel_extended *extended_attr);
+                                            struct lttng_channel_extended *extended_attr);
 
 enum lttng_error_code lttng_channels_create_and_flatten_from_buffer(
-               const struct lttng_buffer_view *view,
-               unsigned int count,
-               struct lttng_channel **channels);
+       const struct lttng_buffer_view *view, unsigned int count, struct lttng_channel **channels);
 
 #endif /* LTTNG_CHANNEL_INTERNAL_H */
index 62e202d2659fb00ad49cc6b14113f36b2035b0a4..a6a6f04fcb185cec5b412ea31401897aef84634b 100644 (file)
@@ -11,6 +11,7 @@
 #include <lttng/domain.h>
 #include <lttng/event.h>
 #include <lttng/lttng-export.h>
+
 #include <stdint.h>
 
 #ifdef __cplusplus
@@ -22,19 +23,140 @@ extern "C" {
  *
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_CHANNEL_ATTR_PADDING1        LTTNG_SYMBOL_NAME_LEN + 12
+#define LTTNG_CHANNEL_ATTR_PADDING1 LTTNG_SYMBOL_NAME_LEN + 12
+
+/*!
+@brief
+    Attributes of a \link #lttng_channel channel summary\endlink.
+
+@ingroup api_channel
+
+The lttng_channel::attr member is an instance of such a structure.
+
+lttng_channel_set_default_attr() sets the members of such a structure
+to their default values given a specific \lt_obj_domain summary.
+
+\anchor api-channel-valid-attr-struct A \em valid #lttng_channel_attr
+structure satisfies the following constraints:
+
+<table>
+  <tr>
+    <th>Member
+    <th>Constraints
+  <tr>
+    <td>lttng_channel_attr::overwrite
+    <td>0, 1, or -1
+  <tr>
+    <td>lttng_channel_attr::subbuf_size
+    <td>
+      - Greater than 0
+      - Power of two
+  <tr>
+    <td>lttng_channel_attr::num_subbuf
+    <td>
+      - Greater than 0
+      - Power of two
+</table>
+*/
 struct lttng_channel_attr {
-       int overwrite;                      /* -1: session default, 1: overwrite, 0: discard */
-       uint64_t subbuf_size;               /* bytes, power of 2 */
-       uint64_t num_subbuf;                /* power of 2 */
+       /*!
+       @brief
+           \ref api-channel-er-loss-mode "Event record loss mode".
+
+       One of:
+
+       <dl>
+         <dt>0
+         <dd>
+           The \ref api-channel-er-loss-mode "event record loss mode"
+           of the channel is
+           <em>\ref api-channel-discard-mode "discard"</em>.
+
+         <dt>1
+         <dd>
+           The event record loss mode of the channel is
+           <em>\ref api-channel-overwrite-mode "overwrite"</em>.
+
+         <dt>-1
+         <dd>
+           The event record loss mode of the channel is the default
+           value of its \lt_obj_session:
+
+           <dl>
+             <dt>\ref api-session-snapshot-mode "Snapshot mode"
+             <dd>Overwrite mode
+
+             <dt>Other modes
+             <dd>Discard mode
+           </dl>
+       </dl>
+       */
+       int overwrite; /* -1: session default, 1: overwrite, 0: discard */
+
+       /*!
+       @brief
+           \ref api-channel-sub-buf-size-count "Sub-buffer size"
+           (bytes).
+       */
+       uint64_t subbuf_size; /* bytes, power of 2 */
+
+       /*!
+       @brief
+           \ref api-channel-sub-buf-size-count "Sub-buffer count".
+       */
+       uint64_t num_subbuf; /* power of 2 */
+
+       /*!
+       @brief
+           \ref api-channel-switch-timer "Switch timer period" (µs),
+           if applicable.
+
+       Only available if the \lt_obj_session which
+       owns this channel is \em not in
+       \ref api-session-live-mode "live mode".
+       */
        unsigned int switch_timer_interval; /* usec */
-       unsigned int read_timer_interval;   /* usec */
-       enum lttng_event_output output;     /* splice, mmap */
+
+       /// \ref api-channel-read-timer "Read timer period" (µs).
+       unsigned int read_timer_interval; /* usec */
+
+       /// Output type (Linux kernel channel).
+       enum lttng_event_output output; /* splice, mmap */
+
        /* LTTng 2.1 padding limit */
-       uint64_t tracefile_size;            /* bytes */
-       uint64_t tracefile_count;           /* number of tracefiles */
+
+       /*!
+       @brief
+           \ref api-channel-max-trace-file-size-count "Maximum trace file size"
+           (bytes), or 0 for unlimited.
+       */
+       uint64_t tracefile_size; /* bytes */
+
+       /*!
+       @brief
+           \ref api-channel-max-trace-file-size-count "Maximum trace file count",
+           or 0 for unlimited.
+       */
+       uint64_t tracefile_count; /* number of tracefiles */
+
        /* LTTng 2.3 padding limit */
-       unsigned int live_timer_interval;   /* usec */
+
+       /*!
+       @brief
+           \ref api-channel-live-timer "Live timer period" (µs), if
+           applicable.
+
+       You may \em not set this member: use the
+       \lt_p{live_timer_period} parameter of
+       lttng_session_descriptor_live_network_create() when you create
+       the descriptor of a \ref api-session-live-mode "live" recording
+       session to contain the channel to create.
+
+       Only available if the \lt_obj_session which
+       owns this channel is in \ref api-session-live-mode "live mode".
+       */
+       unsigned int live_timer_interval; /* usec */
+
        /* LTTng 2.7 padding limit */
        uint32_t align_to_64;
        union {
@@ -50,90 +172,509 @@ struct lttng_channel_attr {
  *
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_CHANNEL_PADDING1             16
+#define LTTNG_CHANNEL_PADDING1 16
+
+/*!
+@brief
+    \lt_obj_c_channel summary.
+
+@ingroup api_channel
+
+The purpose of such a structure is to provide information about a
+channel itself, but not about its \lt_obj_rers
+(use lttng_list_events() for this).
+
+lttng_list_channels() sets a pointer to an array of all the
+channel summaries of a given \lt_obj_session and \lt_obj_domain.
+
+Most properties are part of the lttng_channel::attr member, but the
+following ones have their own dedicated accessors:
+
+<dl>
+  <dt>\ref api-channel-monitor-timer "Monitor timer" period
+  <dd>
+    - lttng_channel_get_monitor_timer_interval()
+    - lttng_channel_set_monitor_timer_interval()
+
+  <dt>\ref api-channel-blocking-timeout "Blocking timeout"
+  <dd>
+    - lttng_channel_get_blocking_timeout()
+    - lttng_channel_set_blocking_timeout()
+</dl>
+
+Create a channel summary with lttng_channel_create().
+
+Destroy a channel summary with lttng_channel_destroy().
+*/
 struct lttng_channel {
+       /// Name.
        char name[LTTNG_SYMBOL_NAME_LEN];
+
+       /*!
+       @brief
+           1 if this \lt_obj_channel is enabled, or 0 otherwise.
+
+       @sa lttng_enable_channel() --
+           Creates or enables a channel.
+       @sa lttng_disable_channel() --
+           Disables a channel.
+       */
        uint32_t enabled;
+
+       /// Other properties.
        struct lttng_channel_attr attr;
 
        char padding[LTTNG_CHANNEL_PADDING1];
 };
 
-/*
- */
+/*!
+@brief
+    Creates and returns a \lt_obj_channel summary,
+    setting the members of its lttng_channel::attr member to default
+    values according to the \lt_obj_domain summary \lt_p{domain}.
+
+@ingroup api_channel
+
+This function internally calls
+
+@code
+lttng_channel_set_default_attr(domain, &channel->attr);
+@endcode
+
+where \c channel is the returned channel summary.
+
+After you create a channel summary with this function, you can modify
+its \ref api-channel-channel-props "properties" and call
+lttng_enable_channel() to create and enable a channel.
+
+@param[in] domain
+    Tracing domain summary to consider to set the members of the
+    lttng_channel::attr member of the returned structure to default
+    values.
+
+@returns
+    @parblock
+    New channel summary.
+
+    Destroy the returned channel summary with lttng_channel_destroy().
+    @endparblock
+
+@lt_pre_not_null{domain}
+
+@sa lttng_channel_destroy() --
+    Destroys a channel summary.
+*/
 LTTNG_EXPORT extern struct lttng_channel *lttng_channel_create(struct lttng_domain *domain);
 
-/*
- */
+/*!
+@brief
+    Destroys the \lt_obj_channel summary \lt_p{channel}.
+
+@ingroup api_channel
+
+@note
+    This function doesn't destroy the \lt_obj_channel
+    which \lt_p{channel} summarizes: the only way to destroy a channel
+    is to \link lttng_destroy_session_ext() destroy its recording
+    session\endlink.
+
+@param[in] channel
+    @parblock
+    Channel summary to destroy.
+
+    May be \c NULL.
+    @endparblock
+*/
 LTTNG_EXPORT extern void lttng_channel_destroy(struct lttng_channel *channel);
 
-/*
- * List the channel(s) of a session.
- *
- * The handle CAN NOT be NULL.
- *
- * Return the size (number of entries) of the "lttng_channel" array. Caller
- * must free channels. On error, a negative LTTng error code is returned.
- */
+/*!
+@brief
+    Sets \lt_p{*channels} to the summaries of the
+    \lt_obj_channels of the recording session handle \lt_p{handle}.
+
+@ingroup api_session
+
+@param[in] handle
+    Recording session handle which contains the name of the recording
+    session and the summary of the \lt_obj_domain which own the channels
+    of which to get the summaries.
+@param[out] channels
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*channels} to
+    the summaries of the channels.
+
+    Free \lt_p{*channels} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*channels} on success, or a \em
+    negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{channels}
+*/
 LTTNG_EXPORT extern int lttng_list_channels(struct lttng_handle *handle,
-               struct lttng_channel **channels);
+                                           struct lttng_channel **channels);
 
-/*
- * Create or enable a channel.
- *
- * The chan and handle params can not be NULL.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Creates or enables a \lt_obj_channel summarized by \lt_p{channel}
+    within the recording session handle \lt_p{handle}.
+
+@ingroup api_channel
+
+This function, depending on \lt_p{channel->name}:
+
+<dl>
+  <dt>
+    \lt_p{channel-&gt;name} names an existing
+    channel within the \lt_obj_session and
+    \lt_obj_domain of \lt_p{handle}
+  <dd>
+    Enables the existing channel.
+
+    In this case, this function only uses \lt_p{channel->name}, ignoring
+    all the other properties of \lt_p{channel}.
+
+  <dt>Otherwise
+  <dd>
+    Creates and enables a new channel, considering all the properties of
+    \lt_p{channel}.
+</dl>
+
+@param[in] handle
+    Recording session handle which contains the name of the
+    recording session and the summary of the \lt_obj_domain which own
+    the channel to create or enable.
+@param[in] channel
+    Summary of the channel to create or enable.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{channel}
+@pre
+    <strong>If this function must create a new channel</strong>, then
+    \lt_p{channel->attr} is \ref api-channel-valid-attr-struct "valid".
+@pre
+    <strong>If this function must create a new channel</strong>, then
+    \lt_p{handle->session_name} names a
+    \lt_obj_session which never became
+    \link lttng_session::enabled active\endlink (started) since its
+    creation.
+@pre
+    <strong>If this function must create a new channel</strong>, then
+    all the existing channels of \lt_p{handle} have the same
+    \ref api-channel-buf-scheme "buffering scheme".
+
+@sa lttng_disable_channel() --
+    Disables a channel.
+*/
 LTTNG_EXPORT extern int lttng_enable_channel(struct lttng_handle *handle,
-               struct lttng_channel *chan);
+                                            struct lttng_channel *channel);
 
-/*
- * Disable channel.
- *
- * Name and handle CAN NOT be NULL.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Disables the \lt_obj_channel named \lt_p{channel_name} within the
+    recording session handle \lt_p{handle}.
+
+@ingroup api_channel
+
+@param[in] handle
+    Recording session handle which contains the name of the
+    recording session and the summary of the \lt_obj_domain which own
+    the channel to disable.
+@param[in] channel_name
+    Name of the channel to disable within \lt_p{handle}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{channel_name}
+@pre
+    \lt_p{channel_name} names an existing channel within the recording
+    session and tracing domain of \lt_p{handle}.
+
+@sa lttng_enable_channel() --
+    Creates or enables a channel.
+*/
 LTTNG_EXPORT extern int lttng_disable_channel(struct lttng_handle *handle,
-               const char *name);
+                                             const char *channel_name);
 
-/*
- * Set the default channel attributes for a specific domain and an allocated
- * lttng_channel_attr pointer.
- *
- * If one or both arguments are NULL, nothing happens.
- */
+/*!
+@brief
+    Sets the members of \lt_p{attr} to their default values considering
+    the \lt_obj_domain summary \lt_p{domain}.
+
+@ingroup api_channel
+
+Use this function on an lttng_channel::attr member.
+
+@param[in] domain
+    Tracing domain summary to consider to set the members of \lt_p{attr}
+    to their default values.
+@param[in] attr
+    Structure of which to set the members to their default values.
+
+@lt_pre_not_null{domain}
+@lt_pre_not_null{attr}
+*/
 LTTNG_EXPORT extern void lttng_channel_set_default_attr(struct lttng_domain *domain,
-               struct lttng_channel_attr *attr);
+                                                       struct lttng_channel_attr *attr);
 
-/*
- * Get the discarded event count of a specific LTTng channel.
- *
- * Returns 0 on success, or a negative LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_channel_get_discarded_event_count(struct lttng_channel *chan,
-               uint64_t *discarded_events);
+/*!
+@brief
+    Sets \lt_p{*count} to the number of discarded event
+    records of the \lt_obj_channel summarized by \lt_p{channel}.
 
-/*
- * Get the lost packet count of a specific LTTng channel.
- *
- * Returns 0 on success, or a negative LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_channel_get_lost_packet_count(struct lttng_channel *chan,
-               uint64_t *lost_packets);
+@ingroup api_channel
+
+In \ref api-channel-discard-mode "discard mode", LTTng discards an event
+record when there's no sub-buffer left to write it.
+
+lttng_list_channels() sets a pointer to an array of all the
+channel summaries of a given \lt_obj_session and \lt_obj_domain.
+
+@param[in] channel
+    Summary of the channel of which to get the number of discarded
+    event records.
+@param[out] count
+    <strong>On success</strong>, this function sets \lt_p{*count} to
+    the number of discarded event records of the channel summarized
+    by \lt_p{channel}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{channel}
+@pre
+    You obtained \lt_p{channel} with lttng_list_channels().
+@pre
+    The lttng_channel_attr::overwrite member of \lt_p{channel->attr}
+    is 0.
+@lt_pre_not_null{count}
+
+@sa lttng_channel_get_lost_packet_count() --
+    Returns the number of discarded packets (sub-buffers) of a channel.
+*/
+LTTNG_EXPORT extern int lttng_channel_get_discarded_event_count(struct lttng_channel *channel,
+                                                               uint64_t *count);
+
+/*!
+@brief
+    Sets \lt_p{*count} to the number of discarded packets (sub-buffers)
+    of the \lt_obj_channel summarized by \lt_p{channel}.
+
+@ingroup api_channel
+
+In \ref api-channel-overwrite-mode "overwrite mode", LTTng discards a
+whole sub-buffer when there's no sub-buffer left to record an event.
+
+lttng_list_channels() sets a pointer to an array of all the
+channel summaries of a given \lt_obj_session and \lt_obj_domain.
+
+@param[in] channel
+    Summary of the channel of which to get the number of discarded
+    packets.
+@param[out] count
+    <strong>On success</strong>, this function sets \lt_p{*count} to
+    the number of discarded packets of the channel summarized
+    by \lt_p{channel}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{channel}
+@pre
+    You obtained \lt_p{channel} with lttng_list_channels().
+@pre
+    The lttng_channel_attr::overwrite member of \lt_p{channel->attr}
+    is 1.
+@lt_pre_not_null{count}
+
+@sa lttng_channel_get_discarded_event_count() --
+    Returns the number of discarded event records of a channel.
+*/
+LTTNG_EXPORT extern int lttng_channel_get_lost_packet_count(struct lttng_channel *channel,
+                                                           uint64_t *count);
+
+/*!
+@brief
+    Sets \lt_p{period} to the
+    \ref api-channel-monitor-timer "monitor timer" period (µs)
+    property of the \lt_obj_channel summary \lt_p{channel}.
+
+@ingroup api_channel
+
+@param[in] channel
+    Summary of the channel of which to get the monitor timer period.
+@param[out] period
+    <strong>On success</strong>, this function sets \lt_p{*period} to
+    the monitor timer period (µs) property of \lt_p{channel}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{channel}
+@lt_pre_not_null{period}
+
+@sa lttng_channel_set_monitor_timer_interval() --
+    Sets the monitor timer period property of a channel summary.
+*/
+LTTNG_EXPORT extern int lttng_channel_get_monitor_timer_interval(struct lttng_channel *channel,
+                                                                uint64_t *period);
+
+/*!
+@brief
+    Sets the \ref api-channel-monitor-timer "monitor timer" period
+    property of the channel summary \lt_p{channel} to
+    \lt_p{period}&nbsp;µs.
+
+@ingroup api_channel
+
+@param[in] channel
+    Channel summary of which to set the monitor timer period
+    to \lt_p{period}&nbsp;µs.
+@param[in] period
+    Monitor timer period property to set.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{channel}
+@pre
+    \lt_p{period}&nbsp;≥&nbsp;1
+
+@sa lttng_channel_get_monitor_timer_interval() --
+    Returns the monitor timer period property of a channel summary.
+*/
+LTTNG_EXPORT extern int lttng_channel_set_monitor_timer_interval(struct lttng_channel *channel,
+                                                                uint64_t period);
+
+/*!
+@brief
+    Sets \lt_p{timeout} to the
+    \ref api-channel-blocking-timeout "blocking timeout"
+    property of the \lt_obj_channel summary \lt_p{channel}.
+
+@ingroup api_channel
+
+This property only applies to \link #LTTNG_DOMAIN_UST user space\endlink
+channels.
+
+@param[in] channel
+    Summary of the channel of which to get the blocking timeout.
+@param[out] timeout
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*timeout} to
+    one of:
+
+    <dl>
+      <dt>-1
+      <dd>
+       The blocking timeout of \lt_p{channel} is infinite.
+
+      <dt>0
+      <dd>
+       Blocking is disabled for \lt_p{channel}.
+
+      <dt>Otherwise
+      <dd>
+       The blocking timeout of \lt_p{channel} is
+       \lt_p{*timeout}&nbsp;µs.
+    </dl>
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{channel}
+@pre
+    The \lt_obj_domain type of \lt_p{channel} is #LTTNG_DOMAIN_UST.
+@lt_pre_not_null{timeout}
+
+@sa lttng_channel_set_blocking_timeout() --
+    Sets the blocking timeout property of a channel summary.
+*/
+LTTNG_EXPORT extern int lttng_channel_get_blocking_timeout(struct lttng_channel *channel,
+                                                          int64_t *timeout);
+
+/*!
+@brief
+    Sets the \ref api-channel-blocking-timeout "blocking timeout"
+    property of the channel summary \lt_p{channel} to
+    \lt_p{timeout}.
+
+@ingroup api_channel
+
+This property only applies to \link #LTTNG_DOMAIN_UST user space\endlink
+channels.
+
+@param[in] channel
+    Channel summary of which to set the blocking timeout
+    to \lt_p{timeout}.
+@param[in] timeout
+    @parblock
+    One of:
+
+    <dl>
+      <dt>-1
+      <dd>
+       The blocking timeout of \lt_p{channel} is infinite.
+
+      <dt>0
+      <dd>
+       Blocking is disabled for \lt_p{channel}.
 
-LTTNG_EXPORT extern int lttng_channel_get_monitor_timer_interval(struct lttng_channel *chan,
-               uint64_t *monitor_timer_interval);
+      <dt>Otherwise
+      <dd>
+       The blocking timeout of \lt_p{channel} is
+       \lt_p{timeout}&nbsp;µs.
+    </dl>
+    @endparblock
 
-LTTNG_EXPORT extern int lttng_channel_set_monitor_timer_interval(struct lttng_channel *chan,
-               uint64_t monitor_timer_interval);
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
 
-LTTNG_EXPORT extern int lttng_channel_get_blocking_timeout(struct lttng_channel *chan,
-               int64_t *blocking_timeout);
+@lt_pre_not_null{channel}
+@pre
+    The \lt_obj_domain type of \lt_p{channel} is #LTTNG_DOMAIN_UST.
+@pre
+    \lt_p{timeout}&nbsp;≥&nbsp;-1
 
-LTTNG_EXPORT extern int lttng_channel_set_blocking_timeout(struct lttng_channel *chan,
-               int64_t blocking_timeout);
+@sa lttng_channel_get_blocking_timeout() --
+    Returns the blocking timeout property of a channel summary.
+*/
+LTTNG_EXPORT extern int lttng_channel_set_blocking_timeout(struct lttng_channel *channel,
+                                                          int64_t timeout);
 
 #ifdef __cplusplus
 }
index e07e6c47f502a4991599d5a75887de4713d3d676..9a8048456421e5b7a62f2097e887094bcde82a13 100644 (file)
 extern "C" {
 #endif
 
-/*
- * Handle used to represent a specific instance of session clear
- * operation.
- */
+/*!
+@addtogroup api_session_clear
+@{
+*/
+
+/*!
+@struct lttng_clear_handle
+
+@brief
+    \lt_obj_c_session clearing handle (opaque type).
+*/
 struct lttng_clear_handle;
 
-/*
- * Negative values indicate errors. Values >= 0 indicate success.
- */
+/*!
+@brief
+    Return type of \lt_obj_session clearing handle functions.
+
+Error status enumerators have a negative value.
+*/
 enum lttng_clear_handle_status {
-       LTTNG_CLEAR_HANDLE_STATUS_ERROR = -2,
-       LTTNG_CLEAR_HANDLE_STATUS_INVALID = -1,
+       /// Success.
        LTTNG_CLEAR_HANDLE_STATUS_OK = 0,
+
+       /// Recording session clearing operation completed.
        LTTNG_CLEAR_HANDLE_STATUS_COMPLETED = 1,
+
+       /// Timeout reached.
        LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT = 2,
+
+       /// Unsatisfied precondition.
+       LTTNG_CLEAR_HANDLE_STATUS_INVALID = -1,
+
+       /// Other error.
+       LTTNG_CLEAR_HANDLE_STATUS_ERROR = -2,
 };
 
-/*
- * Destroy an lttng_clear_handle.
- * The handle should be discarded after this call.
- */
+/*!
+@brief
+    Destroys the \lt_obj_session clearing handle \lt_p{handle}.
+
+@param[in] handle
+    @parblock
+    Recording session clearing handle to destroy.
+
+    May be \c NULL.
+    @endparblock
+*/
 LTTNG_EXPORT extern void lttng_clear_handle_destroy(struct lttng_clear_handle *handle);
 
-/*
- * Wait for a session clear operation to complete.
- *
- * A negative timeout_ms value can be used to wait indefinitely.
- *
- * Returns LTTNG_CLEAR_HANDLE_STATUS_COMPLETED if the session clear
- * operation was completed. LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT is returned
- * to indicate that the wait timed out.
- * On error, one of the negative lttng_clear_handle_status is returned.
- *
- * Note: This function returning a success status does not mean that
- * the clear operation itself succeeded; it indicates that the _wait_
- * operation completed successfully.
- */
+/*!
+@brief
+    Waits for the \lt_obj_session clearing operation identified by
+    \lt_p{handle} to complete.
+
+If this function returns #LTTNG_CLEAR_HANDLE_STATUS_COMPLETED, then the
+recording session clearing operation identified by \lt_p{handle}
+completed. This doesn't mean, however, that the clearing operation
+itself succeeded; use lttng_clear_handle_get_result() to know this.
+
+@param[in] handle
+    Recording session clearing handle which identifies the clearing
+    operation of which to wait for completion.
+@param[in] timeout_ms
+    Maximum time (milliseconds) to wait for the completion of the
+    recording session clearing operation identified by \lt_p{handle}
+    before returning #LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT, or
+    <code>-1</code> to wait indefinitely.
+
+@retval #LTTNG_CLEAR_HANDLE_STATUS_COMPLETED
+    The recording session clearing operation identified by \lt_p{handle}
+    completed (with or without success).
+@retval #LTTNG_CLEAR_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT
+    The function waited for the completion of the recording session
+    clearing operation for more than \lt_p{timeout_ms}&nbsp;ms.
+@retval #LTTNG_CLEAR_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+
+@sa lttng_clear_handle_get_result() --
+    Returns whether or not a recording session clearing operation
+    succeeded.
+*/
 LTTNG_EXPORT extern enum lttng_clear_handle_status
-       lttng_clear_handle_wait_for_completion(
-               struct lttng_clear_handle *handle, int timeout_ms);
+lttng_clear_handle_wait_for_completion(struct lttng_clear_handle *handle, int timeout_ms);
 
-/*
- * Get the result of a session clear operation.
- *
- * This function must be used on a clear handle which was successfully waited
- * on.
- *
- * Returns LTTNG_CLEAR_HANDLE_STATUS_OK if the result of the session
- * clear operation could be obtained. Check the value of 'result' to
- * determine if the session clear operation completed successfully or not.
- *
- * On error, one of the negative lttng_clear_handle_status is returned.
- * Returns LTTNG_CLEAR_HANDLE_STATUS_INVALID if the clear operation
- * was not waited-on using the handle or if the arguments of the function are
- * invalid (e.g. NULL).
- */
+/*!
+@brief
+    Sets \lt_p{*result} to the result of the \lt_obj_session clearing
+    operation identified by \lt_p{handle}.
+
+You must successfully wait for the completion of the recording session
+clearing operation identified by \lt_p{handle} with
+lttng_clear_handle_wait_for_completion() before you call this function.
+
+On success, \lt_p{*result} is #LTTNG_OK if the clearing operation was
+successful.
+
+@param[in] handle
+    Handle of the recording session clearing operation of which to get
+    the result.
+@param[out] result
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*result} to
+    the result of the recording session clearing operation identified by
+    \lt_p{handle}.
+
+    \lt_p{*result} is #LTTNG_OK if the clearing operation was
+    successful.
+    @endparblock
+
+@retval #LTTNG_CLEAR_HANDLE_STATUS_OK
+    Success: \lt_p{*result} is the result of the recording session
+    clearing operation identified by \lt_p{handle}.
+@retval #LTTNG_CLEAR_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_CLEAR_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+@pre
+    You successfully waited for the completion of the recording session
+    clearing operation identified by \lt_p{handle} with
+    lttng_clear_handle_wait_for_completion().
+@lt_pre_not_null{result}
+
+@sa lttng_clear_handle_wait_for_completion() --
+    Waits for a recording session clearing operation to complete.
+*/
 LTTNG_EXPORT extern enum lttng_clear_handle_status
-       lttng_clear_handle_get_result(
-               const struct lttng_clear_handle *handle,
-               enum lttng_error_code *result);
+lttng_clear_handle_get_result(const struct lttng_clear_handle *handle,
+                             enum lttng_error_code *result);
+
+/// @}
+
 #ifdef __cplusplus
 }
 #endif
index 5dfd5db583caccef22f07d3e8869ae465c9a6f19..34d8e49815bd87eda62acc8891599f18503623f2 100644 (file)
 extern "C" {
 #endif
 
+/*!
+@addtogroup api_session_clear
+@{
+*/
+
 struct lttng_clear_handle;
 
-/*
- * Clear a tracing session.
- *
- * Clear the data buffers and trace data.
- *
- * For sessions saving trace data to disk and streaming over the network to a
- * relay daemon, the buffers content and existing stream files are cleared when
- * the clear command is issued.
- *
- * For snapshot sessions (flight recorder), only the buffer content is cleared.
- * Prior snapshots are individually recorded to disk, and are therefore
- * untouched by this "clear" command.
- *
- * For live sessions streaming over network to a relay daemon, the buffers
- * will be cleared and the files on the relay daemon side will be cleared as
- * well. However, any active live trace viewer currently reading an existing
- * trace packet will be able to proceed to read that packet entirely before
- * skipping over cleared stream data.
- *
- * The clear command guarantees that no trace data produced before this function
- * is called will be present in the resulting trace.
- *
- * Trace data produced between the moment this function is called and when it
- * returns might be present in the resulting trace.
- *
- * Provides an lttng_clear_handle which can be used to wait for the completion
- * of the session's clear.
- *
- * Return LTTNG_OK on success else a negative LTTng error code. The returned
- * handle is owned by the caller and must be free'd using
- * lttng_clear_handle_destroy().
- *
- * Important error codes:
- *    LTTNG_ERR_CLEAR_RELAY_DISALLOWED
- *    LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY
- *    LTTNG_ERR_CLEAR_FAIL_CONSUMER
+/*!
+@brief
+    Initiates a clearing operation of the \lt_obj_session
+    named \lt_p{session_name}.
+
+Depending on the mode of the recording session \lt_var{RS}
+named \lt_p{session_name}, the clearing operation attempts to:
+
+<dl>
+  <dt>\ref api-session-local-mode "Local"
+  <dt>\ref api-session-net-mode "Network streaming"
+  <dd>
+    Delete the contents of the recording buffers of \lt_var{RS}.
+
+    Delete the local/remote data stream files of \lt_var{RS}.
+
+  <dt>\ref api-session-snapshot-mode "Snapshot"
+  <dd>
+    Delete the contents of the recording buffers of \lt_var{RS}.
+
+    LTTng doesn't touch prior snapshots of \lt_var{RS}.
+
+  <dt>\ref api-session-live-mode "Live"
+  <dd>
+    Delete the contents of the recording buffers of \lt_var{RS}.
+
+    Delete the remote data stream files of \lt_var{RS}.
+
+    Any active live reader currently reading a data stream packet
+    may continue to read said packet completely.
+</dl>
+
+The clearing operation which this function initiates, if successful,
+guarantees that any trace data which LTTng produced \em before you call
+this function won't be part of any trace, except:
+
+- Preexisting recording session
+  \ref api_session_snapshot "snapshots".
+- Preexisting
+  \ref api_session_rotation "trace chunk archives".
+
+It's possible that trace data which LTTng produces while you're calling
+this function makes it to a trace.
+
+Use \lt_p{*handle} to wait for the completion of the recording session
+clearing operation.
+
+@param[in] session_name
+    Name of the recording session to clear.
+@param[out] handle
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*handle} to
+    a handle which identifies this recording session clearing operation.
+
+    May be \c NULL.
+
+    Wait for the completion of this clearing operation with
+    lttng_clear_handle_wait_for_completion().
+
+    Destroy \lt_p{*handle} with lttng_clear_handle_destroy().
+    @endparblock
+
+@returns
+    @parblock
+    #LTTNG_OK on success, or a \em negative enumerator otherwise.
+
+    Notable return values:
+
+    <table>
+      <tr>
+       <td>-#LTTNG_ERR_CLEAR_RELAY_DISALLOWED
+       <td>
+         The relay daemon doesn't allow recording session clearing
+         operations.
+      <tr>
+       <td>-#LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY
+       <td>
+         The relay daemon doesn't support the recording session
+         clearing operation.
+      <tr>
+       <td>-#LTTNG_ERR_CLEAR_FAIL_CONSUMER
+       <td>
+         A consumer daemon failed to clear the recording session named
+         \lt_p{session_name}.
+    </table>
+    @endparblock
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@pre
+    No clearing operation is in progress for the recording session named
+    \lt_p{session_name}.
 */
 LTTNG_EXPORT extern enum lttng_error_code lttng_clear_session(const char *session_name,
-               struct lttng_clear_handle **handle);
+                                                             struct lttng_clear_handle **handle);
+
+/// @}
+
 #ifdef __cplusplus
 }
 #endif
index b2e6f85c19b88d06157de95f634e9c48d62cded2..25c91d1761c2f3e7cf5f50c9f0222f6c4dc5110b 100644 (file)
@@ -8,12 +8,14 @@
 #ifndef LTTNG_CONDITION_BUFFER_USAGE_INTERNAL_H
 #define LTTNG_CONDITION_BUFFER_USAGE_INTERNAL_H
 
+#include "common/buffer-view.hpp"
+
+#include <common/macros.hpp>
+
 #include <lttng/condition/buffer-usage.h>
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/evaluation-internal.hpp>
 #include <lttng/domain.h>
-#include "common/buffer-view.hpp"
-#include <common/macros.hpp>
 
 struct lttng_condition_buffer_usage {
        struct lttng_condition parent;
@@ -57,24 +59,21 @@ struct lttng_evaluation_buffer_usage_comm {
        uint64_t buffer_capacity;
 } LTTNG_PACKED;
 
-struct lttng_evaluation *lttng_evaluation_buffer_usage_create(
-               enum lttng_condition_type type, uint64_t use,
-               uint64_t capacity);
+struct lttng_evaluation *lttng_evaluation_buffer_usage_create(enum lttng_condition_type type,
+                                                             uint64_t use,
+                                                             uint64_t capacity);
 
-ssize_t lttng_condition_buffer_usage_low_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t lttng_condition_buffer_usage_low_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_condition **condition);
 
-ssize_t lttng_condition_buffer_usage_high_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t lttng_condition_buffer_usage_high_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_condition **condition);
 
-ssize_t lttng_evaluation_buffer_usage_low_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+ssize_t lttng_evaluation_buffer_usage_low_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_evaluation **evaluation);
 
-ssize_t lttng_evaluation_buffer_usage_high_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+ssize_t
+lttng_evaluation_buffer_usage_high_create_from_payload(struct lttng_payload_view *view,
+                                                      struct lttng_evaluation **evaluation);
 
 #endif /* LTTNG_CONDITION_BUFFER_USAGE_INTERNAL_H */
index dcdb7ca1f091c18ae47d68f1f8c29caed14076bb..198f3e65768198fec1148fe232fa269d42b601e5 100644 (file)
@@ -8,12 +8,13 @@
 #ifndef LTTNG_CONDITION_BUFFER_USAGE_H
 #define LTTNG_CONDITION_BUFFER_USAGE_H
 
-#include <lttng/condition/evaluation.h>
 #include <lttng/condition/condition.h>
-#include <stdint.h>
+#include <lttng/condition/evaluation.h>
 #include <lttng/domain.h>
 #include <lttng/lttng-export.h>
 
+#include <stdint.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -57,8 +58,7 @@ extern "C" {
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *
-lttng_condition_buffer_usage_low_create(void);
+LTTNG_EXPORT extern struct lttng_condition *lttng_condition_buffer_usage_low_create(void);
 
 /*
  * Create a newly allocated upper-bound buffer usage condition.
@@ -73,8 +73,7 @@ lttng_condition_buffer_usage_low_create(void);
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *
-lttng_condition_buffer_usage_high_create(void);
+LTTNG_EXPORT extern struct lttng_condition *lttng_condition_buffer_usage_high_create(void);
 
 /*
  * Get the buffer usage threshold ratio of a buffer usage condition.
@@ -89,9 +88,8 @@ lttng_condition_buffer_usage_high_create(void);
  * call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_get_threshold_ratio(
-               const struct lttng_condition *condition,
-               double *threshold_ratio);
+lttng_condition_buffer_usage_get_threshold_ratio(const struct lttng_condition *condition,
+                                                double *threshold_ratio);
 
 /*
  * Set the buffer usage threshold ratio of a buffer usage condition.
@@ -105,9 +103,8 @@ lttng_condition_buffer_usage_get_threshold_ratio(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_set_threshold_ratio(
-               struct lttng_condition *condition,
-               double threshold_ratio);
+lttng_condition_buffer_usage_set_threshold_ratio(struct lttng_condition *condition,
+                                                double threshold_ratio);
 
 /*
  * Get the buffer usage threshold of a buffer usage condition.
@@ -121,9 +118,8 @@ lttng_condition_buffer_usage_set_threshold_ratio(
  * bytes, was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_get_threshold(
-               const struct lttng_condition *condition,
-               uint64_t *threshold_bytes);
+lttng_condition_buffer_usage_get_threshold(const struct lttng_condition *condition,
+                                          uint64_t *threshold_bytes);
 
 /*
  * Set the buffer usage threshold in bytes of a buffer usage condition.
@@ -135,9 +131,8 @@ lttng_condition_buffer_usage_get_threshold(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_set_threshold(
-               struct lttng_condition *condition,
-               uint64_t threshold_bytes);
+lttng_condition_buffer_usage_set_threshold(struct lttng_condition *condition,
+                                          uint64_t threshold_bytes);
 
 /*
  * Get the session name property of a buffer usage condition.
@@ -152,9 +147,8 @@ lttng_condition_buffer_usage_set_threshold(
  * was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name);
+lttng_condition_buffer_usage_get_session_name(const struct lttng_condition *condition,
+                                             const char **session_name);
 
 /*
  * Set the session name property of a buffer usage condition.
@@ -165,9 +159,8 @@ lttng_condition_buffer_usage_get_session_name(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_set_session_name(
-               struct lttng_condition *condition,
-               const char *session_name);
+lttng_condition_buffer_usage_set_session_name(struct lttng_condition *condition,
+                                             const char *session_name);
 
 /*
  * Get the channel name property of a buffer usage condition.
@@ -182,9 +175,8 @@ lttng_condition_buffer_usage_set_session_name(
  * was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_get_channel_name(
-               const struct lttng_condition *condition,
-               const char **channel_name);
+lttng_condition_buffer_usage_get_channel_name(const struct lttng_condition *condition,
+                                             const char **channel_name);
 
 /*
  * Set the channel name property of a buffer usage condition.
@@ -195,9 +187,8 @@ lttng_condition_buffer_usage_get_channel_name(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_set_channel_name(
-               struct lttng_condition *condition,
-               const char *channel_name);
+lttng_condition_buffer_usage_set_channel_name(struct lttng_condition *condition,
+                                             const char *channel_name);
 
 /*
  * Get the domain type property of a buffer usage condition.
@@ -208,9 +199,8 @@ lttng_condition_buffer_usage_set_channel_name(
  * call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_get_domain_type(
-               const struct lttng_condition *condition,
-               enum lttng_domain_type *type);
+lttng_condition_buffer_usage_get_domain_type(const struct lttng_condition *condition,
+                                            enum lttng_domain_type *type);
 
 /*
  * Set the domain type property of a buffer usage condition.
@@ -219,10 +209,8 @@ lttng_condition_buffer_usage_get_domain_type(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_buffer_usage_set_domain_type(
-               struct lttng_condition *condition,
-               enum lttng_domain_type type);
-
+lttng_condition_buffer_usage_set_domain_type(struct lttng_condition *condition,
+                                            enum lttng_domain_type type);
 
 /**
  * lttng_evaluation_buffer_usage are specialised lttng_evaluations which
@@ -242,9 +230,8 @@ lttng_condition_buffer_usage_set_domain_type(
  * an invalid parameter is passed.
  */
 LTTNG_EXPORT extern enum lttng_evaluation_status
-lttng_evaluation_buffer_usage_get_usage_ratio(
-               const struct lttng_evaluation *evaluation,
-               double *usage_ratio);
+lttng_evaluation_buffer_usage_get_usage_ratio(const struct lttng_evaluation *evaluation,
+                                             double *usage_ratio);
 
 /*
  * Get the buffer usage property of a buffer usage evaluation.
@@ -253,9 +240,8 @@ lttng_evaluation_buffer_usage_get_usage_ratio(
  * bytes, or LTTNG_EVALUATION_STATUS_INVALID if an invalid parameter is passed.
  */
 LTTNG_EXPORT extern enum lttng_evaluation_status
-lttng_evaluation_buffer_usage_get_usage(
-               const struct lttng_evaluation *evaluation,
-               uint64_t *usage_bytes);
+lttng_evaluation_buffer_usage_get_usage(const struct lttng_evaluation *evaluation,
+                                       uint64_t *usage_bytes);
 
 #ifdef __cplusplus
 }
index 27407d07a6f2573a878c101cdd76c5fdd4515f18..c69ae2a21c4aa65e7432741423b7c1469113358b 100644 (file)
 #include <common/macros.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/condition/condition.h>
 #include <lttng/lttng-error.h>
+
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -23,19 +25,14 @@ struct mi_writer;
 struct mi_lttng_error_query_callbacks;
 struct lttng_trigger;
 
-typedef void (*condition_destroy_cb)(struct lttng_condition *condition);
-typedef bool (*condition_validate_cb)(const struct lttng_condition *condition);
-typedef int (*condition_serialize_cb)(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload);
-typedef bool (*condition_equal_cb)(const struct lttng_condition *a,
-               const struct lttng_condition *b);
-typedef ssize_t (*condition_create_from_payload_cb)(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
-typedef enum lttng_error_code (*condition_mi_serialize_cb)(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer);
+using condition_destroy_cb = void (*)(struct lttng_condition *);
+using condition_validate_cb = bool (*)(const struct lttng_condition *);
+using condition_serialize_cb = int (*)(const struct lttng_condition *, struct lttng_payload *);
+using condition_equal_cb = bool (*)(const struct lttng_condition *, const struct lttng_condition *);
+using condition_create_from_payload_cb = ssize_t (*)(struct lttng_payload_view *,
+                                                    struct lttng_condition **);
+using condition_mi_serialize_cb = enum lttng_error_code (*)(const struct lttng_condition *,
+                                                           struct mi_writer *);
 
 struct lttng_condition {
        /* Reference counting is only exposed to internal users. */
@@ -58,27 +55,23 @@ void lttng_condition_get(struct lttng_condition *condition);
 
 void lttng_condition_put(struct lttng_condition *condition);
 
-void lttng_condition_init(struct lttng_condition *condition,
-               enum lttng_condition_type type);
+void lttng_condition_init(struct lttng_condition *condition, enum lttng_condition_type type);
 
 bool lttng_condition_validate(const struct lttng_condition *condition);
 
-ssize_t lttng_condition_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t lttng_condition_create_from_payload(struct lttng_payload_view *view,
+                                           struct lttng_condition **condition);
 
 int lttng_condition_serialize(const struct lttng_condition *condition,
-               struct lttng_payload *payload);
+                             struct lttng_payload *payload);
 
-bool lttng_condition_is_equal(const struct lttng_condition *a,
-               const struct lttng_condition *b);
+bool lttng_condition_is_equal(const struct lttng_condition *a, const struct lttng_condition *b);
 
-enum lttng_error_code lttng_condition_mi_serialize(
-               const struct lttng_trigger *trigger,
-               const struct lttng_condition *condition,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks);
+enum lttng_error_code
+lttng_condition_mi_serialize(const struct lttng_trigger *trigger,
+                            const struct lttng_condition *condition,
+                            struct mi_writer *writer,
+                            const struct mi_lttng_error_query_callbacks *error_query_callbacks);
 
 const char *lttng_condition_type_str(enum lttng_condition_type type);
 
index f0f5ffdd86cfc149035c6877612859c2a23a50dd..13a09c19a912e79d0cf3d817b689f2b3021f3610 100644 (file)
@@ -41,8 +41,8 @@ enum lttng_condition_status {
  * Returns the type of a condition on success, LTTNG_CONDITION_TYPE_UNKNOWN on
  * error.
  */
-LTTNG_EXPORT extern enum lttng_condition_type lttng_condition_get_type(
-               const struct lttng_condition *condition);
+LTTNG_EXPORT extern enum lttng_condition_type
+lttng_condition_get_type(const struct lttng_condition *condition);
 
 /*
  * Destroy (release) a condition object.
index f74927c24b0c71d35c8b597dd3d39788c2a4edde..36dc3a544c5e789239a81c409ecf557847433c7b 100644 (file)
@@ -8,19 +8,19 @@
 #ifndef LTTNG_EVALUATION_INTERNAL_H
 #define LTTNG_EVALUATION_INTERNAL_H
 
-#include <lttng/condition/evaluation.h>
-#include <lttng/condition/condition.h>
 #include <common/macros.hpp>
+
+#include <lttng/condition/condition.h>
+#include <lttng/condition/evaluation.h>
+
 #include <stdbool.h>
 #include <sys/types.h>
 
 struct lttng_payload;
 struct lttng_payload_view;
 
-typedef void (*evaluation_destroy_cb)(struct lttng_evaluation *evaluation);
-typedef int (*evaluation_serialize_cb)(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload);
+using evaluation_destroy_cb = void (*)(struct lttng_evaluation *);
+using evaluation_serialize_cb = int (*)(const struct lttng_evaluation *, struct lttng_payload *);
 
 struct lttng_evaluation_comm {
        /* enum lttng_condition_type type */
@@ -34,15 +34,13 @@ struct lttng_evaluation {
        evaluation_destroy_cb destroy;
 };
 
-void lttng_evaluation_init(struct lttng_evaluation *evaluation,
-               enum lttng_condition_type type);
+void lttng_evaluation_init(struct lttng_evaluation *evaluation, enum lttng_condition_type type);
 
-ssize_t lttng_evaluation_create_from_payload(
-               const struct lttng_condition *condition,
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+ssize_t lttng_evaluation_create_from_payload(const struct lttng_condition *condition,
+                                            struct lttng_payload_view *view,
+                                            struct lttng_evaluation **evaluation);
 
 int lttng_evaluation_serialize(const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload);
+                              struct lttng_payload *payload);
 
 #endif /* LTTNG_EVALUATION_INTERNAL_H */
index 494cb9739be77bdb1515d2188ddf17e439f7081e..599bc35b320e525ebcaab20751ecfd87d8f16084 100644 (file)
@@ -31,8 +31,8 @@ enum lttng_evaluation_status {
  * Returns the type of a condition on success, LTTNG_CONDITION_TYPE_UNKNOWN on
  * error.
  */
-LTTNG_EXPORT extern enum lttng_condition_type lttng_evaluation_get_type(
-               const struct lttng_evaluation *evaluation);
+LTTNG_EXPORT extern enum lttng_condition_type
+lttng_evaluation_get_type(const struct lttng_evaluation *evaluation);
 
 /*
  * Destroy (frees) an evaluation object.
index bb7e03e21b51259c19faf11a91712948e09ceafc..22bfb9557cb331acd2bd8e14d5a3ea0ac9729f46 100644 (file)
@@ -8,12 +8,13 @@
 #ifndef LTTNG_CONDITION_EVENT_RULE_MATCHES_INTERNAL_H
 #define LTTNG_CONDITION_EVENT_RULE_MATCHES_INTERNAL_H
 
-#include <lttng/condition/condition-internal.hpp>
 #include <common/buffer-view.hpp>
+#include <common/dynamic-array.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+
+#include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/evaluation-internal.hpp>
-#include <common/dynamic-array.hpp>
 #include <lttng/event-field-value.h>
 
 struct lttng_capture_descriptor {
@@ -51,39 +52,34 @@ struct lttng_evaluation_event_rule_matches {
        struct lttng_event_field_value *captured_values;
 };
 
-ssize_t lttng_condition_event_rule_matches_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t lttng_condition_event_rule_matches_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_condition **condition);
 
 enum lttng_condition_status
-lttng_condition_event_rule_matches_borrow_rule_mutable(
-               const struct lttng_condition *condition,
-               struct lttng_event_rule **rule);
+lttng_condition_event_rule_matches_borrow_rule_mutable(const struct lttng_condition *condition,
+                                                      struct lttng_event_rule **rule);
 
-void lttng_condition_event_rule_matches_set_error_counter_index(
-               struct lttng_condition *condition,
-               uint64_t error_counter_index);
+void lttng_condition_event_rule_matches_set_error_counter_index(struct lttng_condition *condition,
+                                                               uint64_t error_counter_index);
 
-uint64_t lttng_condition_event_rule_matches_get_error_counter_index(
-               const struct lttng_condition *condition);
+uint64_t
+lttng_condition_event_rule_matches_get_error_counter_index(const struct lttng_condition *condition);
 
 struct lttng_evaluation *lttng_evaluation_event_rule_matches_create(
-               const struct lttng_condition_event_rule_matches *condition,
-               const char *capture_payload,
-               size_t capture_payload_size,
-               bool decode_capture_payload);
+       const struct lttng_condition_event_rule_matches *condition,
+       const char *capture_payload,
+       size_t capture_payload_size,
+       bool decode_capture_payload);
 
 ssize_t lttng_evaluation_event_rule_matches_create_from_payload(
-               const struct lttng_condition_event_rule_matches *condition,
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation);
+       const struct lttng_condition_event_rule_matches *condition,
+       struct lttng_payload_view *view,
+       struct lttng_evaluation **_evaluation);
 
-enum lttng_error_code
-lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
-               struct lttng_condition *condition);
+enum lttng_error_code lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
+       struct lttng_condition *condition);
 
-const struct lttng_bytecode *
-lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
-               const struct lttng_condition *condition, unsigned int index);
+const struct lttng_bytecode *lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
+       const struct lttng_condition *condition, unsigned int index);
 
 #endif /* LTTNG_CONDITION_EVENT_RULE_MATCHES_INTERNAL_H */
index b1bbe08f3321015728783d190e1be34f027f744e..c579a1864cd6f43d7304b1e5cff87f06d6e49c52 100644 (file)
@@ -8,9 +8,9 @@
 #ifndef LTTNG_CONDITION_EVENT_RULE_MATCHES_H
 #define LTTNG_CONDITION_EVENT_RULE_MATCHES_H
 
-#include <lttng/event-rule/event-rule.h>
 #include <lttng/condition/condition.h>
 #include <lttng/condition/evaluation.h>
+#include <lttng/event-rule/event-rule.h>
 #include <lttng/lttng-export.h>
 
 #ifdef __cplusplus
@@ -43,8 +43,8 @@ enum lttng_evaluation_event_rule_matches_status {
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *lttng_condition_event_rule_matches_create(
-               struct lttng_event_rule *rule);
+LTTNG_EXPORT extern struct lttng_condition *
+lttng_condition_event_rule_matches_create(struct lttng_event_rule *rule);
 
 /*
  * Get the rule property of an Event Rule Matches condition.
@@ -56,9 +56,9 @@ LTTNG_EXPORT extern struct lttng_condition *lttng_condition_event_rule_matches_c
  * Returns LTTNG_CONDITION_STATUS_OK and a pointer to the condition's rule
  * on success, LTTNG_CONDITION_STATUS_INVALID if an invalid
  * parameter is passed. */
-LTTNG_EXPORT extern enum lttng_condition_status lttng_condition_event_rule_matches_get_rule(
-               const struct lttng_condition *condition,
-               const struct lttng_event_rule **rule);
+LTTNG_EXPORT extern enum lttng_condition_status
+lttng_condition_event_rule_matches_get_rule(const struct lttng_condition *condition,
+                                           const struct lttng_event_rule **rule);
 
 /**
  * lttng_evaluation_event_rule_matches_hit are specialised lttng_evaluations
@@ -92,8 +92,8 @@ LTTNG_EXPORT extern enum lttng_condition_status lttng_condition_event_rule_match
  */
 LTTNG_EXPORT extern enum lttng_evaluation_event_rule_matches_status
 lttng_evaluation_event_rule_matches_get_captured_values(
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_event_field_value **field_val);
+       const struct lttng_evaluation *evaluation,
+       const struct lttng_event_field_value **field_val);
 
 /*
  * Appends (transfering the ownership) the capture descriptor `expr` to
@@ -124,9 +124,8 @@ lttng_evaluation_event_rule_matches_get_captured_values(
  *     * The associated event-rule does not support runtime capture.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_event_rule_matches_append_capture_descriptor(
-               struct lttng_condition *condition,
-               struct lttng_event_expr *expr);
+lttng_condition_event_rule_matches_append_capture_descriptor(struct lttng_condition *condition,
+                                                            struct lttng_event_expr *expr);
 
 /*
  * Sets `*count` to the number of capture descriptors in the Event Rule Matches
@@ -145,7 +144,7 @@ lttng_condition_event_rule_matches_append_capture_descriptor(
  */
 LTTNG_EXPORT extern enum lttng_condition_status
 lttng_condition_event_rule_matches_get_capture_descriptor_count(
-               const struct lttng_condition *condition, unsigned int *count);
+       const struct lttng_condition *condition, unsigned int *count);
 
 /*
  * Returns the capture descriptor (borrowed) of the Event Rule Matches condition
@@ -160,7 +159,7 @@ lttng_condition_event_rule_matches_get_capture_descriptor_count(
  */
 LTTNG_EXPORT extern const struct lttng_event_expr *
 lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-               const struct lttng_condition *condition, unsigned int index);
+       const struct lttng_condition *condition, unsigned int index);
 
 #ifdef __cplusplus
 }
index cdfa100346c134f24800f6d2e3aa0bc04c0f61f0..e49a608143b1f9aaf640c4746a04fc984337417e 100644 (file)
@@ -8,12 +8,13 @@
 #ifndef LTTNG_CONDITION_SESSION_CONSUMED_SIZE_INTERNAL_H
 #define LTTNG_CONDITION_SESSION_CONSUMED_SIZE_INTERNAL_H
 
-#include <lttng/condition/session-consumed-size.h>
-#include <lttng/condition/condition-internal.hpp>
-#include <lttng/condition/evaluation-internal.hpp>
 #include <common/buffer-view.hpp>
 #include <common/macros.hpp>
 
+#include <lttng/condition/condition-internal.hpp>
+#include <lttng/condition/evaluation-internal.hpp>
+#include <lttng/condition/session-consumed-size.h>
+
 struct lttng_payload;
 struct lttng_payload_view;
 
@@ -42,15 +43,14 @@ struct lttng_evaluation_session_consumed_size_comm {
        uint64_t session_consumed;
 } LTTNG_PACKED;
 
-struct lttng_evaluation *lttng_evaluation_session_consumed_size_create(
-               uint64_t consumed);
+struct lttng_evaluation *lttng_evaluation_session_consumed_size_create(uint64_t consumed);
 
-ssize_t lttng_condition_session_consumed_size_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t
+lttng_condition_session_consumed_size_create_from_payload(struct lttng_payload_view *view,
+                                                         struct lttng_condition **condition);
 
-ssize_t lttng_evaluation_session_consumed_size_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+ssize_t
+lttng_evaluation_session_consumed_size_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_evaluation **evaluation);
 
 #endif /* LTTNG_CONDITION_SESSION_CONSUMED_SIZE_INTERNAL_H */
index 4d52cb68936bae93513d4ed98879e9aa36834481..98284c748c841bba487fec8d7c558ba24243d796 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_CONDITION_SESSION_CONSUMED_SIZE_H
 #define LTTNG_CONDITION_SESSION_CONSUMED_SIZE_H
 
-#include <lttng/condition/evaluation.h>
 #include <lttng/condition/condition.h>
+#include <lttng/condition/evaluation.h>
 #include <lttng/lttng-export.h>
+
 #include <stdint.h>
 
 #ifdef __cplusplus
@@ -43,8 +44,7 @@ extern "C" {
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *
-lttng_condition_session_consumed_size_create(void);
+LTTNG_EXPORT extern struct lttng_condition *lttng_condition_session_consumed_size_create(void);
 
 /*
  * Get the threshold of a session consumed size condition.
@@ -58,9 +58,8 @@ lttng_condition_session_consumed_size_create(void);
  * bytes, was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_consumed_size_get_threshold(
-               const struct lttng_condition *condition,
-               uint64_t *consumed_threshold_bytes);
+lttng_condition_session_consumed_size_get_threshold(const struct lttng_condition *condition,
+                                                   uint64_t *consumed_threshold_bytes);
 
 /*
  * Set the threshold of a session consumed size usage condition.
@@ -71,9 +70,8 @@ lttng_condition_session_consumed_size_get_threshold(
  * if invalid parameters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_consumed_size_set_threshold(
-               struct lttng_condition *condition,
-               uint64_t consumed_threshold_bytes);
+lttng_condition_session_consumed_size_set_threshold(struct lttng_condition *condition,
+                                                   uint64_t consumed_threshold_bytes);
 
 /*
  * Get the session name property of a session consumed size condition.
@@ -88,9 +86,8 @@ lttng_condition_session_consumed_size_set_threshold(
  * was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_consumed_size_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name);
+lttng_condition_session_consumed_size_get_session_name(const struct lttng_condition *condition,
+                                                      const char **session_name);
 
 /*
  * Set the session name property of a session consumed size condition.
@@ -101,9 +98,8 @@ lttng_condition_session_consumed_size_get_session_name(
  * if invalid parameters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_consumed_size_set_session_name(
-               struct lttng_condition *condition,
-               const char *session_name);
+lttng_condition_session_consumed_size_set_session_name(struct lttng_condition *condition,
+                                                      const char *session_name);
 
 /**
  * lttng_evaluation_session_consumed_size is specialised lttng_evaluations
@@ -118,9 +114,8 @@ lttng_condition_session_consumed_size_set_session_name(
  * bytes, or LTTNG_EVALUATION_STATUS_INVALID if an invalid parameter is passed.
  */
 LTTNG_EXPORT extern enum lttng_evaluation_status
-lttng_evaluation_session_consumed_size_get_consumed_size(
-               const struct lttng_evaluation *evaluation,
-               uint64_t *session_consumed);
+lttng_evaluation_session_consumed_size_get_consumed_size(const struct lttng_evaluation *evaluation,
+                                                        uint64_t *session_consumed);
 
 #ifdef __cplusplus
 }
index e9a2984450f4104bd18966f95bd1ba78b1c372c1..a3d14b493113921fdc248ae58af24c920613a87a 100644 (file)
@@ -8,12 +8,14 @@
 #ifndef LTTNG_CONDITION_SESSION_ROTATION_INTERNAL_H
 #define LTTNG_CONDITION_SESSION_ROTATION_INTERNAL_H
 
-#include <lttng/condition/session-rotation.h>
+#include "common/buffer-view.hpp"
+
+#include <common/macros.hpp>
+
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/evaluation-internal.hpp>
-#include "common/buffer-view.hpp"
+#include <lttng/condition/session-rotation.h>
 #include <lttng/location.h>
-#include <common/macros.hpp>
 
 struct lttng_condition_session_rotation {
        struct lttng_condition parent;
@@ -37,28 +39,26 @@ struct lttng_evaluation_session_rotation_comm {
        uint8_t has_location;
 } LTTNG_PACKED;
 
-ssize_t lttng_condition_session_rotation_ongoing_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t
+lttng_condition_session_rotation_ongoing_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_condition **condition);
 
-ssize_t lttng_condition_session_rotation_completed_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition);
+ssize_t
+lttng_condition_session_rotation_completed_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_condition **condition);
 
-struct lttng_evaluation *lttng_evaluation_session_rotation_ongoing_create(
-                uint64_t id);
+struct lttng_evaluation *lttng_evaluation_session_rotation_ongoing_create(uint64_t id);
 
 /* Ownership of location is transferred to the evaluation. */
-struct lttng_evaluation *lttng_evaluation_session_rotation_completed_create(
-               uint64_t id,
-               struct lttng_trace_archive_location *location);
+struct lttng_evaluation *
+lttng_evaluation_session_rotation_completed_create(uint64_t id,
+                                                  struct lttng_trace_archive_location *location);
 
-ssize_t lttng_evaluation_session_rotation_ongoing_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+ssize_t
+lttng_evaluation_session_rotation_ongoing_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_evaluation **evaluation);
 
 ssize_t lttng_evaluation_session_rotation_completed_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation);
+       struct lttng_payload_view *view, struct lttng_evaluation **evaluation);
 
 #endif /* LTTNG_CONDITION_SESSION_ROTATION_INTERNAL_H */
index 086fff915fd5ad0d225fd388afef403b81d7fcb9..6e6207fb28e0d689790bc19f1301278b1c91de73 100644 (file)
@@ -8,13 +8,14 @@
 #ifndef LTTNG_CONDITION_SESSION_ROTATION_H
 #define LTTNG_CONDITION_SESSION_ROTATION_H
 
-#include <lttng/condition/evaluation.h>
 #include <lttng/condition/condition.h>
-#include <stdint.h>
+#include <lttng/condition/evaluation.h>
 #include <lttng/domain.h>
 #include <lttng/location.h>
 #include <lttng/lttng-export.h>
 
+#include <stdint.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -39,8 +40,7 @@ extern "C" {
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *
-lttng_condition_session_rotation_ongoing_create(void);
+LTTNG_EXPORT extern struct lttng_condition *lttng_condition_session_rotation_ongoing_create(void);
 
 /*
  * Create a newly allocated session rotation completion condition.
@@ -54,8 +54,7 @@ lttng_condition_session_rotation_ongoing_create(void);
  * Returns a new condition on success, NULL on failure. This condition must be
  * destroyed using lttng_condition_destroy().
  */
-LTTNG_EXPORT extern struct lttng_condition *
-lttng_condition_session_rotation_completed_create(void);
+LTTNG_EXPORT extern struct lttng_condition *lttng_condition_session_rotation_completed_create(void);
 
 /*
  * Get the session name property of a session rotation condition.
@@ -70,9 +69,8 @@ lttng_condition_session_rotation_completed_create(void);
  * was not set prior to this call.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_rotation_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name);
+lttng_condition_session_rotation_get_session_name(const struct lttng_condition *condition,
+                                                 const char **session_name);
 
 /*
  * Set the session name property of a session rotation condition.
@@ -83,9 +81,8 @@ lttng_condition_session_rotation_get_session_name(
  * if invalid paramenters are passed.
  */
 LTTNG_EXPORT extern enum lttng_condition_status
-lttng_condition_session_rotation_set_session_name(
-               struct lttng_condition *condition,
-               const char *session_name);
+lttng_condition_session_rotation_set_session_name(struct lttng_condition *condition,
+                                                 const char *session_name);
 
 /**
  * lttng_evaluation_session_rotation are specialised lttng_evaluations
@@ -101,8 +98,7 @@ lttng_condition_session_rotation_set_session_name(
  * passed.
  */
 LTTNG_EXPORT extern enum lttng_evaluation_status
-lttng_evaluation_session_rotation_get_id(
-               const struct lttng_evaluation *evaluation, uint64_t *id);
+lttng_evaluation_session_rotation_get_id(const struct lttng_evaluation *evaluation, uint64_t *id);
 
 /*
  * Get the session rotation location property of a session rotation completed
@@ -121,8 +117,8 @@ lttng_evaluation_session_rotation_get_id(
  */
 LTTNG_EXPORT extern enum lttng_evaluation_status
 lttng_evaluation_session_rotation_completed_get_location(
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_trace_archive_location **location);
+       const struct lttng_evaluation *evaluation,
+       const struct lttng_trace_archive_location **location);
 
 #ifdef __cplusplus
 }
index 1b6f44d8bc95e5622019c7dfcec7b65dd7a52aef..f20e96458f795335aacdba6ccdc0a62b4f6e9b12 100644 (file)
@@ -9,9 +9,7 @@
 #define LTTNG_CONSTANT_H
 
 #ifndef LTTNG_DEPRECATED
-#if defined (__GNUC__) \
-       && ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)  \
-                       || __GNUC__ >= 5)
+#if defined(__GNUC__) && ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5) || __GNUC__ >= 5)
 #define LTTNG_DEPRECATED(msg) __attribute__((deprecated(msg)))
 #else
 #define LTTNG_DEPRECATED(msg) __attribute__((deprecated))
 /*
  * Event symbol length. Copied from LTTng kernel ABI.
  */
-#define LTTNG_SYMBOL_NAME_LEN                  256
+
+/*!
+@brief
+    Maximum symbol length.
+
+@ingroup api_gen
+*/
+#define LTTNG_SYMBOL_NAME_LEN 256
 
 /*
  * PROC(5) mentions that PID_MAX_LIMIT may not exceed 2^22 on 64-bit HW.
  * We prefer to use 32-bits for simplicity's sake.
  */
-#define LTTNG_MAX_PID                          INT32_MAX
-#define LTTNG_MAX_PID_STR                      "2147483647"
+#define LTTNG_MAX_PID    INT32_MAX
+#define LTTNG_MAX_PID_STR "2147483647"
+
+/*!
+@brief
+    Maximum name length.
 
-#define LTTNG_NAME_MAX                         255
+@ingroup api_gen
+*/
+#define LTTNG_NAME_MAX 255
 
 /*
  * POSIX guarantees that a host name will not exceed 255 characters.
@@ -53,8 +64,8 @@
  *
  * 256 is used to include a trailing NULL character.
  */
-#define LTTNG_HOST_NAME_MAX                    256
+#define LTTNG_HOST_NAME_MAX 256
 
-#define LTTNG_PATH_MAX                         4096
+#define LTTNG_PATH_MAX 4096
 
 #endif /* LTTNG_CONSTANT_H */
index 6fa4339ac921cb776864e1dd9fdf9a763012f494..108ba4aa6bd35f8681e07536e9aafb81ba08d19a 100644 (file)
 #ifndef LTTNG_DESTRUCTION_HANDLE_H
 #define LTTNG_DESTRUCTION_HANDLE_H
 
-#include <lttng/rotation.h>
 #include <lttng/lttng-error.h>
 #include <lttng/lttng-export.h>
+#include <lttng/rotation.h>
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-/*
- * Handle used to represent a specific instance of session destruction
- * operation.
- *
- * See lttng_destroy_session_ext() in lttng/session.h.
- */
+/*!
+@addtogroup api_session_destr_handle
+@{
+*/
+
+/*!
+@struct lttng_destruction_handle
+
+@brief
+    Recording session destruction handle (opaque type).
+*/
 struct lttng_destruction_handle;
 
-/*
- * Negative values indicate errors. Values >= 0 indicate success.
- */
+/*!
+@brief
+    Return type of recording session destruction handle fuctions.
+
+Error status enumerators have a negative value.
+*/
 enum lttng_destruction_handle_status {
-       /* Generic error. */
-       LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR = -2,
-       /* Invalid parameters provided */
-       LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID = -1,
-       /* Success. */
+       /// Success.
        LTTNG_DESTRUCTION_HANDLE_STATUS_OK = 0,
-       /* Destruction operation completed successfully. */
+
+       /// Recording session destruction operation completed.
        LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED = 1,
-       /* Operation timed out. */
+
+       /// Timeout reached.
        LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT = 2,
+
+       /// Unsatisfied precondition.
+       LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID = -1,
+
+       /// Other error.
+       LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR = -2,
 };
 
-/*
- * Destroy an lttng_destruction_session handle.
- * The handle should be discarded after this call.
- */
-LTTNG_EXPORT extern void lttng_destruction_handle_destroy(
-               struct lttng_destruction_handle *handle);
+/*!
+@brief
+    Destroys the recording session destruction handle \lt_p{handle}.
 
-/*
- * Wait for the destruction of a session to complete.
- *
- * A negative timeout_ms value can be used to wait indefinitely.
- *
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED if the session destruction
- * operation was completed. LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT is returned
- * to indicate that the wait timed out.
- * On error, one of the negative lttng_destruction_handle_status is returned.
- *
- * Note: This function returning a success status does not mean that
- * the destruction operation itself succeeded; it indicates that the _wait_
- * operation completed successfully.
- */
+@param[in] handle
+    @parblock
+    Recording session destruction handle to destroy.
+
+    May be \c NULL.
+    @endparblock
+*/
+LTTNG_EXPORT extern void lttng_destruction_handle_destroy(struct lttng_destruction_handle *handle);
+
+/*!
+@brief
+    Waits for the recording session destruction operation identified by
+    \lt_p{handle} to complete.
+
+If this function returns #LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED,
+then the recording session destruction operation identified by
+\lt_p{handle} completed. This doesn't mean, however, that the
+destruction operation itself succeeded; use
+lttng_destruction_handle_get_result() to know this.
+
+@param[in] handle
+    Recording session destruction handle which identifies the
+    destruction operation of which to wait for completion.
+@param[in] timeout_ms
+    Maximum time (milliseconds) to wait for the completion of the
+    recording session destruction operation identified by \lt_p{handle}
+    before returning #LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT, or
+    <code>-1</code> to wait indefinitely.
+
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED
+    The recording session destruction operation identified by
+    \lt_p{handle} completed (with or without success).
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT
+    The function waited for the completion of the recording session
+    destruction operation for more than \lt_p{timeout_ms}&nbsp;ms.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+
+@sa lttng_destruction_handle_get_result() --
+    Returns whether or not a recording session destruction operation
+    succeeded.
+*/
 LTTNG_EXPORT extern enum lttng_destruction_handle_status
-lttng_destruction_handle_wait_for_completion(
-               struct lttng_destruction_handle *handle, int timeout_ms);
+lttng_destruction_handle_wait_for_completion(struct lttng_destruction_handle *handle,
+                                            int timeout_ms);
 
-/*
- * Get the result of a session destruction operation.
- *
- * This function must be used on a session destruction handle which was
- * successfully waited on.
- *
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_OK if the result of the session
- * destruction operation could be obtained. Check the value of 'result' to
- * determine if the destruction of the session completed successfully or not.
- *
- * On error, one of the negative lttng_destruction_handle_status is returned.
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID if the session destruction
- * was not waited-on using the handle or if the arguments of the function are
- * invalid (e.g. NULL).
- */
+/*!
+@brief
+    Sets \lt_p{*result} to the result of the recording session
+    destruction operation identified by \lt_p{handle}.
+
+You must successfully wait for the completion of the recording session
+destruction operation identified by \lt_p{handle} with
+lttng_destruction_handle_wait_for_completion() before you call this function.
+
+On success, \lt_p{*result} is #LTTNG_OK if the destruction operation was
+successful.
+
+@param[in] handle
+    Handle of the recording session destruction operation of which to
+    get the result.
+@param[out] result
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*result} to
+    the result of the recording session destruction operation identified
+    by \lt_p{handle}.
+
+    \lt_p{*result} is #LTTNG_OK if the destruction operation was
+    successful.
+    @endparblock
+
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_OK
+    Success: \lt_p{*result} is the result of the recording session
+    destruction operation identified by \lt_p{handle}.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+@pre
+    You successfully waited for the completion of the recording session
+    destruction operation identified by \lt_p{handle} with
+    lttng_destruction_handle_wait_for_completion().
+@lt_pre_not_null{result}
+
+@sa lttng_destruction_handle_wait_for_completion() --
+    Waits for a recording session destruction operation to complete.
+*/
 LTTNG_EXPORT extern enum lttng_destruction_handle_status
-lttng_destruction_handle_get_result(
-               const struct lttng_destruction_handle *handle,
-               enum lttng_error_code *result);
+lttng_destruction_handle_get_result(const struct lttng_destruction_handle *handle,
+                                   enum lttng_error_code *result);
 
-/*
- * Get the status of the session rotation performed as part of the session's
- * destruction.
- *
- * A session will perform a final rotation if it was ever rotated over its
- * lifetime. If this happens, this function returns the state of the rotation
- * that was performed.
- *
- * This function must be used on a session destruction handle which was
- * successfully waited on.
- *
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_OK if the state of the session
- * rotation could be obtained. Check the value of 'rotation_state' to
- * determine if the rotation of the session completed successfully or not.
- *
- * On error, one of the negative lttng_destruction_handle_status is returned.
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID if the session destruction
- * was not waited-on using the handle or if the arguments of the function are
- * invalid (e.g. NULL).
- *
- * Note that if no rotation was performed, rotation_state will be set to
- * LTTNG_ROTATION_STATE_NO_ROTATION.
- */
+/*!
+@brief
+    Sets \lt_p{*rotation_state} to the state of a final
+    \ref api_session_rotation "rotation" operation which the
+    destruction of the recording session identified by \lt_p{handle}
+    caused.
+
+You must successfully wait for the completion of the recording session
+destruction operation identified by \lt_p{handle} with
+lttng_destruction_handle_wait_for_completion() before you call this
+function.
+
+This function is only useful if LTTng performed at least one recording
+session rotation during the lifetime of the destroyed recording session.
+
+@param[in] handle
+    Handle of the destruction operation of the recording session of
+    which to get the state of the final rotation operation.
+@param[out] rotation_state
+    @parblock
+    <strong>On success</strong>, this function sets
+    \lt_p{*rotation_state} to the state of the final rotation operation
+    which the recording session destruction operation identified by
+    \lt_p{handle} caused.
+
+    \lt_p{*rotation_state} is #LTTNG_ROTATION_STATE_NO_ROTATION if LTTng
+    didn't perform any final recording session rotation.
+    @endparblock
+
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_OK
+    Success: \lt_p{*rotation_state} is the state of the final rotation
+    of the destroyed recording session.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+@pre
+    You successfully waited for the completion of the recording session
+    destruction operation identified by \lt_p{handle} with
+    lttng_destruction_handle_wait_for_completion().
+@lt_pre_not_null{rotation_state}
+
+@sa lttng_destruction_handle_get_archive_location() --
+    Get the location of the trace chunk archive which a recording
+    session destruction operation created.
+*/
 LTTNG_EXPORT extern enum lttng_destruction_handle_status
-lttng_destruction_handle_get_rotation_state(
-               const struct lttng_destruction_handle *handle,
-               enum lttng_rotation_state *rotation_state);
+lttng_destruction_handle_get_rotation_state(const struct lttng_destruction_handle *handle,
+                                           enum lttng_rotation_state *rotation_state);
 
-/*
- * Get the location of the archive resulting from the rotation performed during
- * the session's destruction.
- *
- * This function must be used on a session destruction handle which was
- * successfully waited on and a session rotation must have been be completed
- * successfully in order for this call to succeed.
- *
- * The location returned remains owned by the session destruction handle.
- *
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_OK if the location of the archive
- * resulting from the session rotation could be obtained.
- *
- * On error, one of the negative lttng_destruction_handle_status is returned.
- * Returns LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID if the session destruction
- * was not waited-on using the handle, if no session rotation occurred as part
- * of the session's destruction, or if the arguments of the function are
- * invalid (e.g. NULL).
- */
+/*!
+@brief
+    Sets \lt_p{*location} to the location of the final
+    \ref api_session_rotation "trace chunk archive" which
+    the destruction of the recording session identified by \lt_p{handle}
+    created.
+
+You must make sure that the destruction of the recording session caused
+a final, successful rotation with
+lttng_destruction_handle_get_rotation_state().
+
+This function is only useful if LTTng performed at least one recording
+session rotation during the lifetime of the destroyed recording session.
+
+@param[in] handle
+    Handle of the destruction operation of the recording session of
+    which to get the location of the final trace chunk archive.
+@param[out] location
+    @parblock
+    <strong>On success</strong>, this function sets
+    \lt_p{*location} to the location of the final trace chunk archive
+    which the recording session destruction operation identified by
+    \lt_p{handle} created.
+
+    \lt_p{*location} is owned by \lt_p{handle}.
+    @endparblock
+
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_OK
+    Success: \lt_p{*location} is the location of the final trace
+    chunk archive of the destroyed recording session.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR
+    Other error.
+
+@lt_pre_not_null{handle}
+@pre
+    lttng_destruction_handle_get_rotation_state() set the
+    #LTTNG_ROTATION_STATE_COMPLETED state for \lt_p{handle}.
+@lt_pre_not_null{location}
+
+@sa lttng_destruction_handle_get_rotation_state() --
+    Get the state of the final rotation operation which a recording
+    session destruction operation caused.
+*/
 LTTNG_EXPORT extern enum lttng_destruction_handle_status
-lttng_destruction_handle_get_archive_location(
-               const struct lttng_destruction_handle *handle,
-               const struct lttng_trace_archive_location **location);
+lttng_destruction_handle_get_archive_location(const struct lttng_destruction_handle *handle,
+                                             const struct lttng_trace_archive_location **location);
+
+/// @}
 
 #ifdef __cplusplus
 }
index 4439c7825e1945668676f589bc28f660cdce7605..f41d61e84d32ad257ee6b3cc16e4165c1e2f1183 100644 (file)
@@ -8,8 +8,8 @@
 #ifndef LTTNG_DOMAIN_INTERNAL_H
 #define LTTNG_DOMAIN_INTERNAL_H
 
-#include "lttng/domain.h"
 #include "common/macros.hpp"
+#include "lttng/domain.h"
 
 const char *lttng_domain_type_str(enum lttng_domain_type domain_type);
 
index 192c04bf239458c0621ae3ca9ae1dd9bfe8267f7..26e9da93206ec2128a64f81688210c21425c14c4 100644 (file)
 extern "C" {
 #endif
 
+/*!
+@addtogroup api_channel
+@{
+*/
+
 #include <lttng/constant.h>
 #include <lttng/lttng-export.h>
 
-/*
- * Domain types: the different possible tracers.
- */
+/*!
+@brief
+    Tracing domain type (tracer type).
+*/
 enum lttng_domain_type {
-       LTTNG_DOMAIN_NONE                     = 0,      /* No associated domain. */
-       LTTNG_DOMAIN_KERNEL                   = 1,      /* Linux Kernel tracer. */
-       LTTNG_DOMAIN_UST                      = 2,      /* Global Userspace tracer. */
-       LTTNG_DOMAIN_JUL                      = 3,      /* Java Util Logging. */
-       LTTNG_DOMAIN_LOG4J                    = 4,      /* Java Log4j Framework. */
-       LTTNG_DOMAIN_PYTHON                   = 5,      /* Python logging Framework. */
+       /// None.
+       LTTNG_DOMAIN_NONE = 0,
+
+       /// Linux kernel.
+       LTTNG_DOMAIN_KERNEL = 1,
+
+       /// User space.
+       LTTNG_DOMAIN_UST = 2,
+
+       /// <code>java.util.logging</code> (JUL).
+       LTTNG_DOMAIN_JUL = 3,
+
+       /// Apache log4j.
+       LTTNG_DOMAIN_LOG4J = 4,
+
+       /// Python logging.
+       LTTNG_DOMAIN_PYTHON = 5,
 };
 
-/* Buffer type for a specific domain. */
+/*!
+@brief
+    Buffering scheme of a channel.
+
+See \ref api-channel-buf-scheme "Buffering scheme" to learn more.
+*/
 enum lttng_buffer_type {
-       LTTNG_BUFFER_PER_PID,   /* Only supported by UST being the default. */
-       LTTNG_BUFFER_PER_UID,   /* Only supported by UST. */
-       LTTNG_BUFFER_GLOBAL,    /* Only supported by the Kernel. */
+       /// Per-process buffering.
+       LTTNG_BUFFER_PER_PID,
+
+       /// Per-user buffering.
+       LTTNG_BUFFER_PER_UID,
+
+       /// Global (Linux kernel) buffering.
+       LTTNG_BUFFER_GLOBAL,
 };
 
 /*
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_DOMAIN_PADDING1              12
-#define LTTNG_DOMAIN_PADDING2              LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_DOMAIN_PADDING1 12
+#define LTTNG_DOMAIN_PADDING2 LTTNG_SYMBOL_NAME_LEN + 32
+
+/*!
+@brief
+    Tracing domain summary.
+
+Such a structure is involved:
+
+- As a member of a \link #lttng_handle recording session handle\endlink.
+
+  Some functions which require both a \lt_obj_session
+  and a tracing domain accept an #lttng_handle structure.
+
+- When you list the tracing domains of a recording session with
+  lttng_list_domains().
+
+- When you create a \link #lttng_channel channel summary
+  structure\endlink with lttng_channel_create().
+
+You must initialize such a structure to zeros before setting its
+members and using it, for example:
+
+@code
+struct lttng_domain domain;
+
+memset(&domain, 0, sizeof(domain));
+@endcode
+*/
 struct lttng_domain {
+       /// Tracing domain type.
        enum lttng_domain_type type;
+
+       /*!
+       @brief
+           Buffering scheme of all the channels associated to this tracing
+           domain.
+       */
        enum lttng_buffer_type buf_type;
+
        char padding[LTTNG_DOMAIN_PADDING1];
 
        union {
@@ -51,16 +113,37 @@ struct lttng_domain {
        } attr;
 };
 
-/*
- * List the registered domain(s) of a session.
- *
- * Session name CAN NOT be NULL.
- *
- * Return the size (number of entries) of the "lttng_domain" array. Caller
- * must free domains. On error, a negative LTTng error code is returned.
- */
-LTTNG_EXPORT extern int lttng_list_domains(const char *session_name,
-               struct lttng_domain **domains);
+/// @}
+
+/*!
+@brief
+    Sets \lt_p{*domains} to the summaries of the tracing domains which
+    contain at least one channel within the recording session
+    named \lt_p{session_name}.
+
+@ingroup api_session
+
+@param[in] session_name
+    Name of the recording session for which to get the tracing domain
+    summaries.
+@param[out] domains
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*domains} to
+    the summaries of the tracing domains.
+
+    Free \lt_p{*domains} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*domains} on success, or a \em negative
+    #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_not_null{domains}
+*/
+LTTNG_EXPORT extern int lttng_list_domains(const char *session_name, struct lttng_domain **domains);
 
 #ifdef __cplusplus
 }
index 5317f7ff5a5d2a0defede813dd8952bf86e45d5c..306a96a4723d27da2d0d172bb13086b32ab7a3e5 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_ENDPOINT_INTERNAL_H
 #define LTTNG_ENDPOINT_INTERNAL_H
 
-#include <lttng/endpoint.h>
 #include <common/macros.hpp>
 
+#include <lttng/endpoint.h>
+
 enum lttng_endpoint_type {
        LTTNG_ENDPOINT_TYPE_DEFAULT_SESSIOND_NOTIFICATION = 0,
        LTTNG_ENDPOINT_TYPE_DEFAULT_SESSIOND_COMMAND = 1,
index 7bf4da7481da438b53d2c1add3ca023287a28754..39ec36535762b9e12ccd496d603467d155831b12 100644 (file)
@@ -3,17 +3,18 @@
  *
  * Copyright (C) 2021 Jérémie Galarneau <jeremie.galarneau@efficios.com>
  *
- * SPDX-License-Identifier: GPL-2.1-only
+ * SPDX-License-Identifier: LGPL-2.1-only
  *
  */
 
 #ifndef LTTNG_ERROR_QUERY_INTERNAL_H
 #define LTTNG_ERROR_QUERY_INTERNAL_H
 
-#include <lttng/lttng.h>
 #include <common/macros.hpp>
-#include <common/payload.hpp>
 #include <common/payload-view.hpp>
+#include <common/payload.hpp>
+
+#include <lttng/lttng.h>
 
 struct mi_writer;
 
@@ -23,59 +24,53 @@ enum lttng_error_query_target_type {
        LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION,
 };
 
-enum lttng_error_query_target_type lttng_error_query_get_target_type(
-               const struct lttng_error_query *query);
+enum lttng_error_query_target_type
+lttng_error_query_get_target_type(const struct lttng_error_query *query);
 
-const struct lttng_trigger *lttng_error_query_trigger_borrow_target(
-               const struct lttng_error_query *query);
+const struct lttng_trigger *
+lttng_error_query_trigger_borrow_target(const struct lttng_error_query *query);
 
-const struct lttng_trigger *lttng_error_query_condition_borrow_target(
-               const struct lttng_error_query *query);
+const struct lttng_trigger *
+lttng_error_query_condition_borrow_target(const struct lttng_error_query *query);
 
-const struct lttng_trigger *lttng_error_query_action_borrow_trigger_target(
-               const struct lttng_error_query *query);
+const struct lttng_trigger *
+lttng_error_query_action_borrow_trigger_target(const struct lttng_error_query *query);
 
-struct lttng_action *lttng_error_query_action_borrow_action_target(
-               const struct lttng_error_query *query,
-               struct lttng_trigger *trigger);
+struct lttng_action *
+lttng_error_query_action_borrow_action_target(const struct lttng_error_query *query,
+                                             struct lttng_trigger *trigger);
 
 int lttng_error_query_serialize(const struct lttng_error_query *query,
-               struct lttng_payload *payload);
+                               struct lttng_payload *payload);
 
 ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_error_query **query);
+                                             struct lttng_error_query **query);
 
-int lttng_error_query_result_serialize(
-               const struct lttng_error_query_result *result,
-               struct lttng_payload *payload);
+int lttng_error_query_result_serialize(const struct lttng_error_query_result *result,
+                                      struct lttng_payload *payload);
 
-ssize_t lttng_error_query_result_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_error_query_result **result);
+ssize_t lttng_error_query_result_create_from_payload(struct lttng_payload_view *view,
+                                                    struct lttng_error_query_result **result);
 
-int lttng_error_query_results_serialize(
-               const struct lttng_error_query_results *results,
-               struct lttng_payload *payload);
+int lttng_error_query_results_serialize(const struct lttng_error_query_results *results,
+                                       struct lttng_payload *payload);
 
-ssize_t lttng_error_query_results_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_error_query_results **results);
+ssize_t lttng_error_query_results_create_from_payload(struct lttng_payload_view *view,
+                                                     struct lttng_error_query_results **results);
 
 struct lttng_error_query_result *
-lttng_error_query_result_counter_create(
-               const char *name, const char *description, uint64_t value);
+lttng_error_query_result_counter_create(const char *name, const char *description, uint64_t value);
 
 void lttng_error_query_result_destroy(struct lttng_error_query_result *result);
 
-struct lttng_error_query_results *lttng_error_query_results_create(void);
+struct lttng_error_query_results *lttng_error_query_results_create();
 
 /* Ownership of `result` is transferred on success. */
-int lttng_error_query_results_add_result(
-               struct lttng_error_query_results *results,
-               struct lttng_error_query_result *result);
+int lttng_error_query_results_add_result(struct lttng_error_query_results *results,
+                                        struct lttng_error_query_result *result);
 
-enum lttng_error_code lttng_error_query_results_mi_serialize(
-               const struct lttng_error_query_results *results,
-               struct mi_writer *writer);
+enum lttng_error_code
+lttng_error_query_results_mi_serialize(const struct lttng_error_query_results *results,
+                                      struct mi_writer *writer);
 
 #endif /* LTTNG_ERROR_QUERY_INTERNAL_H */
index a7cbae4210cb253e071e6fc0881bd0bce85357e8..cebf8266ca5abfd7040a197135e34c3dd407a463 100644 (file)
@@ -3,16 +3,17 @@
  *
  * Copyright (C) 2021 Jérémie Galarneau <jeremie.galarneau@efficios.com>
  *
- * SPDX-License-Identifier: GPL-2.1-only
+ * SPDX-License-Identifier: LGPL-2.1-only
  *
  */
 
 #ifndef LTTNG_ERROR_QUERY_H
 #define LTTNG_ERROR_QUERY_H
 
-#include <lttng/lttng.h>
 #include <lttng/lttng-export.h>
+#include <lttng/lttng.h>
 #include <lttng/trigger/trigger.h>
+
 #include <stdint.h>
 
 #ifdef __cplusplus
@@ -59,12 +60,12 @@ enum lttng_error_query_results_status {
 };
 
 /* Create an error query targetting a trigger object. */
-LTTNG_EXPORT extern struct lttng_error_query *lttng_error_query_trigger_create(
-               const struct lttng_trigger *trigger);
+LTTNG_EXPORT extern struct lttng_error_query *
+lttng_error_query_trigger_create(const struct lttng_trigger *trigger);
 
 /* Create an error query targetting a trigger's condition object. */
-LTTNG_EXPORT extern struct lttng_error_query *lttng_error_query_condition_create(
-               const struct lttng_trigger *trigger);
+LTTNG_EXPORT extern struct lttng_error_query *
+lttng_error_query_condition_create(const struct lttng_trigger *trigger);
 
 /*
  * Create an error query targetting an action object.
@@ -72,9 +73,9 @@ LTTNG_EXPORT extern struct lttng_error_query *lttng_error_query_condition_create
  * `action_path` is copied internally. The root of the `action_path` is the
  * action of `trigger`.
  */
-LTTNG_EXPORT extern struct lttng_error_query *lttng_error_query_action_create(
-               const struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path);
+LTTNG_EXPORT extern struct lttng_error_query *
+lttng_error_query_action_create(const struct lttng_trigger *trigger,
+                               const struct lttng_action_path *action_path);
 
 /* Destroy an error query. */
 LTTNG_EXPORT extern void lttng_error_query_destroy(struct lttng_error_query *query);
@@ -85,47 +86,43 @@ LTTNG_EXPORT extern void lttng_error_query_destroy(struct lttng_error_query *que
  * Currently, only the `lttng_session_daemon_command_endpoint` is supported,
  * see `lttng/endpoint.h`.
  */
-LTTNG_EXPORT extern enum lttng_error_code lttng_error_query_execute(
-               const struct lttng_error_query *query,
-               const struct lttng_endpoint *endpoint,
-               struct lttng_error_query_results **results);
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_error_query_execute(const struct lttng_error_query *query,
+                         const struct lttng_endpoint *endpoint,
+                         struct lttng_error_query_results **results);
 
 /* Get the number of results in a result set. */
 LTTNG_EXPORT LTTNG_EXPORT extern enum lttng_error_query_results_status
-lttng_error_query_results_get_count(
-               const struct lttng_error_query_results *results,
-               unsigned int *count);
+lttng_error_query_results_get_count(const struct lttng_error_query_results *results,
+                                   unsigned int *count);
 
 /* Get a result from a result set by index. */
 LTTNG_EXPORT extern enum lttng_error_query_results_status
-lttng_error_query_results_get_result(
-               const struct lttng_error_query_results *results,
-               const struct lttng_error_query_result **result,
-               unsigned int index);
+lttng_error_query_results_get_result(const struct lttng_error_query_results *results,
+                                    const struct lttng_error_query_result **result,
+                                    unsigned int index);
 
 /* Destroy an error query result set. */
-LTTNG_EXPORT extern void lttng_error_query_results_destroy(
-               struct lttng_error_query_results *results);
+LTTNG_EXPORT extern void
+lttng_error_query_results_destroy(struct lttng_error_query_results *results);
 
 /* Get the type of an error query result. */
-LTTNG_EXPORT extern enum lttng_error_query_result_type lttng_error_query_result_get_type(
-               const struct lttng_error_query_result *result);
+LTTNG_EXPORT extern enum lttng_error_query_result_type
+lttng_error_query_result_get_type(const struct lttng_error_query_result *result);
 
 /* Get the name of result. */
-LTTNG_EXPORT extern enum lttng_error_query_result_status lttng_error_query_result_get_name(
-               const struct lttng_error_query_result *result,
-               const char **name);
+LTTNG_EXPORT extern enum lttng_error_query_result_status
+lttng_error_query_result_get_name(const struct lttng_error_query_result *result, const char **name);
 
 /* Get the description of a result. */
 LTTNG_EXPORT extern enum lttng_error_query_result_status
-lttng_error_query_result_get_description(
-               const struct lttng_error_query_result *result,
-               const char **description);
+lttng_error_query_result_get_description(const struct lttng_error_query_result *result,
+                                        const char **description);
 
 /* Get the value of an error counter. */
 LTTNG_EXPORT extern enum lttng_error_query_result_status
-lttng_error_query_result_counter_get_value(
-               const struct lttng_error_query_result *result, uint64_t *value);
+lttng_error_query_result_counter_get_value(const struct lttng_error_query_result *result,
+                                          uint64_t *value);
 
 #ifdef __cplusplus
 }
index 07547e587275db2b31769ee33b13e7d4f4589bd8..c44e63e4a6ef92f78791980fe55c57a1190f55c1 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_EVENT_EXPR_INTERNAL_H
 
 #include <common/macros.hpp>
+
 #include <lttng/event-expr.h>
 
 struct lttng_bytecode;
@@ -47,21 +48,19 @@ struct lttng_event_expr_array_field_element {
 /*
  * Returns whether or not `expr` is an l-value (locator value).
  */
-static inline
-bool lttng_event_expr_is_lvalue(const struct lttng_event_expr *expr)
+static inline bool lttng_event_expr_is_lvalue(const struct lttng_event_expr *expr)
 {
        LTTNG_ASSERT(expr);
        return expr->type == LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD ||
-                       expr->type == LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD ||
-                       expr->type == LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD ||
-                       expr->type == LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT;
+               expr->type == LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD ||
+               expr->type == LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD ||
+               expr->type == LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT;
 }
 
 int lttng_event_expr_to_bytecode(const struct lttng_event_expr *expr,
-               struct lttng_bytecode **bytecode_out);
+                                struct lttng_bytecode **bytecode_out);
 
-enum lttng_error_code lttng_event_expr_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer);
+enum lttng_error_code lttng_event_expr_mi_serialize(const struct lttng_event_expr *expression,
+                                                   struct mi_writer *writer);
 
 #endif /* LTTNG_EVENT_EXPR_INTERNAL_H */
index cab22c97e96d40b7cd67700503f1ff7fab3ca77b..7b42785cad4763363dd97a9414a281d904cfd867 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_EVENT_EXPR_H
 
 #include <lttng/lttng-export.h>
+
 #include <stdbool.h>
 
 struct lttng_event_expr;
@@ -84,8 +85,8 @@ enum lttng_event_expr_status {
  * Returns the type of the event expression `expr`, or
  * `LTTNG_EVENT_EXPR_TYPE_INVALID` if `expr` is `NULL`.
  */
-LTTNG_EXPORT extern enum lttng_event_expr_type lttng_event_expr_get_type(
-               const struct lttng_event_expr *expr);
+LTTNG_EXPORT extern enum lttng_event_expr_type
+lttng_event_expr_get_type(const struct lttng_event_expr *expr);
 
 /*
  * Creates an event payload field expression for the payload field named
@@ -96,8 +97,8 @@ LTTNG_EXPORT extern enum lttng_event_expr_type lttng_event_expr_get_type(
  * * There's a memory error.
  * * `field_name` is `NULL`.
  */
-LTTNG_EXPORT extern struct lttng_event_expr *lttng_event_expr_event_payload_field_create(
-               const char *field_name);
+LTTNG_EXPORT extern struct lttng_event_expr *
+lttng_event_expr_event_payload_field_create(const char *field_name);
 
 /*
  * Returns the field name of the event payload field expression `expr`,
@@ -107,8 +108,8 @@ LTTNG_EXPORT extern struct lttng_event_expr *lttng_event_expr_event_payload_fiel
  * * The type of `expr` is not
  *   `LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD`.
  */
-LTTNG_EXPORT extern const char *lttng_event_expr_event_payload_field_get_name(
-               const struct lttng_event_expr *expr);
+LTTNG_EXPORT extern const char *
+lttng_event_expr_event_payload_field_get_name(const struct lttng_event_expr *expr);
 
 /*
  * Creates a per-channel context field expression for the per-channel
@@ -130,8 +131,8 @@ lttng_event_expr_channel_context_field_create(const char *field_name);
  * * The type of `expr` is not
  *   `LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD`.
  */
-LTTNG_EXPORT extern const char *lttng_event_expr_channel_context_field_get_name(
-               const struct lttng_event_expr *expr);
+LTTNG_EXPORT extern const char *
+lttng_event_expr_channel_context_field_get_name(const struct lttng_event_expr *expr);
 
 /*
  * Creates an application-specific context field expression for the
@@ -145,8 +146,8 @@ LTTNG_EXPORT extern const char *lttng_event_expr_channel_context_field_get_name(
  * * `type_name` is `NULL`.
  */
 LTTNG_EXPORT extern struct lttng_event_expr *
-lttng_event_expr_app_specific_context_field_create(
-               const char *provider_name, const char *type_name);
+lttng_event_expr_app_specific_context_field_create(const char *provider_name,
+                                                  const char *type_name);
 
 /*
  * Returns the provider name of the application-specific context field
@@ -157,8 +158,7 @@ lttng_event_expr_app_specific_context_field_create(
  *   `LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD`.
  */
 LTTNG_EXPORT extern const char *
-lttng_event_expr_app_specific_context_field_get_provider_name(
-               const struct lttng_event_expr *expr);
+lttng_event_expr_app_specific_context_field_get_provider_name(const struct lttng_event_expr *expr);
 
 /*
  * Returns the type name of the application-specific context field
@@ -169,8 +169,7 @@ lttng_event_expr_app_specific_context_field_get_provider_name(
  *   `LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD`.
  */
 LTTNG_EXPORT extern const char *
-lttng_event_expr_app_specific_context_field_get_type_name(
-               const struct lttng_event_expr *expr);
+lttng_event_expr_app_specific_context_field_get_type_name(const struct lttng_event_expr *expr);
 
 /*
  * Creates an array field element expression for the parent array field
@@ -188,9 +187,9 @@ lttng_event_expr_app_specific_context_field_get_type_name(
  *    * `LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD`
  *    * `LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT`
  */
-LTTNG_EXPORT extern struct lttng_event_expr *lttng_event_expr_array_field_element_create(
-               struct lttng_event_expr *array_field_expr,
-               unsigned int index);
+LTTNG_EXPORT extern struct lttng_event_expr *
+lttng_event_expr_array_field_element_create(struct lttng_event_expr *array_field_expr,
+                                           unsigned int index);
 
 /*
  * Returns the parent array field expression of the array field element
@@ -201,8 +200,7 @@ LTTNG_EXPORT extern struct lttng_event_expr *lttng_event_expr_array_field_elemen
  *   `LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT`.
  */
 LTTNG_EXPORT extern const struct lttng_event_expr *
-lttng_event_expr_array_field_element_get_parent_expr(
-               const struct lttng_event_expr *expr);
+lttng_event_expr_array_field_element_get_parent_expr(const struct lttng_event_expr *expr);
 
 /*
  * Sets `*index` to the index of the array field element expression
@@ -220,8 +218,8 @@ lttng_event_expr_array_field_element_get_parent_expr(
  *     * `index` is `NULL`.
  */
 LTTNG_EXPORT extern enum lttng_event_expr_status
-lttng_event_expr_array_field_element_get_index(
-               const struct lttng_event_expr *expr, unsigned int *index);
+lttng_event_expr_array_field_element_get_index(const struct lttng_event_expr *expr,
+                                              unsigned int *index);
 
 /*
  * Returns whether or not the event expressions `expr_a` and `expr_b`
@@ -230,7 +228,7 @@ lttng_event_expr_array_field_element_get_index(
  * `expr_a` and `expr_b` can be `NULL`.
  */
 LTTNG_EXPORT extern bool lttng_event_expr_is_equal(const struct lttng_event_expr *expr_a,
-               const struct lttng_event_expr *expr_b);
+                                                  const struct lttng_event_expr *expr_b);
 
 /*
  * Destroys the event expression `expr` if not `NULL`.
index 03ef8960b2d509b9ccd5c85c598195a192ab7ff3..57a6a3e1c537fa00ee7e1c63d2d672aa0fcdc84b 100644 (file)
@@ -8,10 +8,12 @@
 #ifndef LTTNG_EVENT_FIELD_VALUE_INTERNAL_H
 #define LTTNG_EVENT_FIELD_VALUE_INTERNAL_H
 
-#include <stdint.h>
-#include <lttng/event-field-value.h>
 #include <common/dynamic-array.hpp>
 
+#include <lttng/event-field-value.h>
+
+#include <stdint.h>
+
 struct lttng_event_field_value {
        enum lttng_event_field_value_type type;
 };
@@ -114,9 +116,8 @@ struct lttng_event_field_value_array {
  *     * `count` is `NULL`.
  */
 enum lttng_event_field_value_status
-lttng_event_field_value_enum_get_label_count(
-               const struct lttng_event_field_value *field_val,
-               unsigned int *count);
+lttng_event_field_value_enum_get_label_count(const struct lttng_event_field_value *field_val,
+                                            unsigned int *count);
 
 /*
  * Returns the label at index `index` of the enumeration event field
@@ -129,45 +130,39 @@ lttng_event_field_value_enum_get_label_count(
  * * `index` is greater than or equal to the label count of `field_val`,
  *   as returned by lttng_event_field_value_enum_get_label_count().
  */
-const char *lttng_event_field_value_enum_get_label_at_index(
-               const struct lttng_event_field_value *field_val,
-               unsigned int index);
+const char *
+lttng_event_field_value_enum_get_label_at_index(const struct lttng_event_field_value *field_val,
+                                               unsigned int index);
 
-struct lttng_event_field_value *lttng_event_field_value_uint_create(
-               uint64_t val);
+struct lttng_event_field_value *lttng_event_field_value_uint_create(uint64_t val);
 
-struct lttng_event_field_value *lttng_event_field_value_int_create(
-               int64_t val);
+struct lttng_event_field_value *lttng_event_field_value_int_create(int64_t val);
 
-struct lttng_event_field_value *lttng_event_field_value_enum_uint_create(
-               uint64_t val);
+struct lttng_event_field_value *lttng_event_field_value_enum_uint_create(uint64_t val);
 
-struct lttng_event_field_value *lttng_event_field_value_enum_int_create(
-               int64_t val);
+struct lttng_event_field_value *lttng_event_field_value_enum_int_create(int64_t val);
 
 struct lttng_event_field_value *lttng_event_field_value_real_create(double val);
 
-struct lttng_event_field_value *lttng_event_field_value_string_create(
-               const char *val);
+struct lttng_event_field_value *lttng_event_field_value_string_create(const char *val);
 
-struct lttng_event_field_value *lttng_event_field_value_string_create_with_size(
-               const char *val, size_t size);
+struct lttng_event_field_value *lttng_event_field_value_string_create_with_size(const char *val,
+                                                                               size_t size);
 
-struct lttng_event_field_value *lttng_event_field_value_array_create(void);
+struct lttng_event_field_value *lttng_event_field_value_array_create();
 
-int lttng_event_field_value_enum_append_label(
-               struct lttng_event_field_value *field_val, const char *label);
+int lttng_event_field_value_enum_append_label(struct lttng_event_field_value *field_val,
+                                             const char *label);
 
-int lttng_event_field_value_enum_append_label_with_size(
-               struct lttng_event_field_value *field_val, const char *label,
-               size_t size);
+int lttng_event_field_value_enum_append_label_with_size(struct lttng_event_field_value *field_val,
+                                                       const char *label,
+                                                       size_t size);
 
-int lttng_event_field_value_array_append(
-               struct lttng_event_field_value *array_field_val,
-               struct lttng_event_field_value *field_val);
+int lttng_event_field_value_array_append(struct lttng_event_field_value *array_field_val,
+                                        struct lttng_event_field_value *field_val);
 
 int lttng_event_field_value_array_append_unavailable(
-               struct lttng_event_field_value *array_field_val);
+       struct lttng_event_field_value *array_field_val);
 
 void lttng_event_field_value_destroy(struct lttng_event_field_value *field_val);
 
index 02d93c66109d5cb834d27a0f2f9f0e14de3cab47..7f10deec31c544e6bb47366f05bcaaa5dd23f9a7 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_EVENT_FIELD_VALUE_H
 
 #include <lttng/lttng-export.h>
+
 #include <stdint.h>
 
 struct lttng_event_field_value;
@@ -104,8 +105,8 @@ enum lttng_event_field_value_status {
  * `LTTNG_EVENT_FIELD_VALUE_TYPE_INVALID`:
  *     `field_val` is `NULL`.
  */
-LTTNG_EXPORT extern enum lttng_event_field_value_type lttng_event_field_value_get_type(
-               const struct lttng_event_field_value *field_val);
+LTTNG_EXPORT extern enum lttng_event_field_value_type
+lttng_event_field_value_get_type(const struct lttng_event_field_value *field_val);
 
 /*
  * Sets `*val` to the raw value of the unsigned integer/enumeration
@@ -124,8 +125,8 @@ LTTNG_EXPORT extern enum lttng_event_field_value_type lttng_event_field_value_ge
  *     * `val` is `NULL`.
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
-lttng_event_field_value_unsigned_int_get_value(
-               const struct lttng_event_field_value *field_val, uint64_t *val);
+lttng_event_field_value_unsigned_int_get_value(const struct lttng_event_field_value *field_val,
+                                              uint64_t *val);
 
 /*
  * Sets `*val` to the raw value of the signed integer/enumeration event
@@ -144,8 +145,8 @@ lttng_event_field_value_unsigned_int_get_value(
  *     * `val` is `NULL`.
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
-lttng_event_field_value_signed_int_get_value(
-               const struct lttng_event_field_value *field_val, int64_t *val);
+lttng_event_field_value_signed_int_get_value(const struct lttng_event_field_value *field_val,
+                                            int64_t *val);
 
 /*
  * Sets `*val` to the raw value of the real event field value
@@ -163,8 +164,8 @@ lttng_event_field_value_signed_int_get_value(
  *     * `val` is `NULL`.
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
-lttng_event_field_value_real_get_value(
-               const struct lttng_event_field_value *field_val, double *val);
+lttng_event_field_value_real_get_value(const struct lttng_event_field_value *field_val,
+                                      double *val);
 
 /*
  * Returns the raw value (an UTF-8 C string) of the string event field
@@ -179,9 +180,8 @@ lttng_event_field_value_real_get_value(
  *       `LTTNG_EVENT_FIELD_VALUE_TYPE_STRING`.
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
-lttng_event_field_value_string_get_value(
-               const struct lttng_event_field_value *field_val,
-               const char **value);
+lttng_event_field_value_string_get_value(const struct lttng_event_field_value *field_val,
+                                        const char **value);
 
 /*
  * Sets `*length` to the length (the number of contained elements) of
@@ -199,9 +199,8 @@ lttng_event_field_value_string_get_value(
  *     * `length` is `NULL`.
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
-lttng_event_field_value_array_get_length(
-               const struct lttng_event_field_value *field_val,
-               unsigned int *length);
+lttng_event_field_value_array_get_length(const struct lttng_event_field_value *field_val,
+                                        unsigned int *length);
 
 /*
  * Sets `*elem_field_val` to the event field value at index `index` in
@@ -225,9 +224,9 @@ lttng_event_field_value_array_get_length(
  */
 LTTNG_EXPORT extern enum lttng_event_field_value_status
 lttng_event_field_value_array_get_element_at_index(
-               const struct lttng_event_field_value *field_val,
-               unsigned int index,
-               const struct lttng_event_field_value **elem_field_val);
+       const struct lttng_event_field_value *field_val,
+       unsigned int index,
+       const struct lttng_event_field_value **elem_field_val);
 
 #ifdef __cplusplus
 }
index daa8fa68e74a5167fe7e8caf4911c98c56d5d596..3d8893b698defe82902d1208cefc3d6600be2004 100644 (file)
@@ -13,6 +13,7 @@
 #define LTTNG_EVENT_INTERNAL_H
 
 #include <common/macros.hpp>
+
 #include <lttng/event.h>
 #include <lttng/lttng-error.h>
 
@@ -58,7 +59,7 @@ struct lttng_event_comm {
 struct lttng_event_exclusion_comm {
        /* Includes terminator `\0`. */
        uint32_t len;
-       char payload [];
+       char payload[];
 } LTTNG_PACKED;
 
 struct lttng_event_probe_attr_comm {
@@ -154,43 +155,38 @@ struct lttng_event_extended {
 struct lttng_event *lttng_event_copy(const struct lttng_event *event);
 
 ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_event **out_event,
-               struct lttng_event_exclusion **out_exclusion,
-               char **out_filter_expression,
-               struct lttng_bytecode **out_bytecode);
+                                       struct lttng_event **out_event,
+                                       struct lttng_event_exclusion **out_exclusion,
+                                       char **out_filter_expression,
+                                       struct lttng_bytecode **out_bytecode);
 
 int lttng_event_serialize(const struct lttng_event *event,
-               unsigned int exclusion_count,
-               char **exclusion_list,
-               char *filter_expression,
-               size_t bytecode_len,
-               struct lttng_bytecode *bytecode,
-               struct lttng_payload *payload);
+                         unsigned int exclusion_count,
+                         const char *const *exclusion_list,
+                         const char *filter_expression,
+                         size_t bytecode_len,
+                         struct lttng_bytecode *bytecode,
+                         struct lttng_payload *payload);
 
-ssize_t lttng_event_context_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_context **event_ctx);
+ssize_t lttng_event_context_create_from_payload(struct lttng_payload_view *view,
+                                               struct lttng_event_context **event_ctx);
 
 int lttng_event_context_serialize(struct lttng_event_context *context,
-               struct lttng_payload *payload);
+                                 struct lttng_payload *payload);
 
 void lttng_event_context_destroy(struct lttng_event_context *context);
 
-enum lttng_error_code lttng_events_create_and_flatten_from_payload(
-               struct lttng_payload_view *view,
-               unsigned int count,
-               struct lttng_event **events);
+enum lttng_error_code lttng_events_create_and_flatten_from_payload(struct lttng_payload_view *view,
+                                                                  unsigned int count,
+                                                                  struct lttng_event **events);
 
-ssize_t lttng_event_field_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_field **field);
+ssize_t lttng_event_field_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_event_field **field);
 
 int lttng_event_field_serialize(const struct lttng_event_field *field,
-               struct lttng_payload *payload);
+                               struct lttng_payload *payload);
 
 enum lttng_error_code lttng_event_fields_create_and_flatten_from_payload(
-               struct lttng_payload_view *view,
-               unsigned int count,
-               struct lttng_event_field **fields);
+       struct lttng_payload_view *view, unsigned int count, struct lttng_event_field **fields);
 
 #endif /* LTTNG_EVENT_INTERNAL_H */
index 46fb98144820946007263297517795411085da89..1b73b06094c775a4234023b1debfa13683786ccd 100644 (file)
@@ -8,13 +8,15 @@
 #ifndef LTTNG_EVENT_RULE_INTERNAL_H
 #define LTTNG_EVENT_RULE_INTERNAL_H
 
-#include <common/macros.hpp>
 #include <common/credentials.hpp>
+#include <common/macros.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <lttng/domain.h>
-#include <lttng/event.h>
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/event.h>
 #include <lttng/lttng-error.h>
+
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -31,36 +33,24 @@ enum lttng_event_rule_generate_exclusions_status {
        LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_OUT_OF_MEMORY,
 };
 
-typedef void (*event_rule_destroy_cb)(struct lttng_event_rule *event_rule);
-typedef bool (*event_rule_validate_cb)(
-               const struct lttng_event_rule *event_rule);
-typedef int (*event_rule_serialize_cb)(
-               const struct lttng_event_rule *event_rule,
-               struct lttng_payload *payload);
-typedef bool (*event_rule_equal_cb)(const struct lttng_event_rule *a,
-               const struct lttng_event_rule *b);
-typedef ssize_t (*event_rule_create_from_payload_cb)(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **event_rule);
-typedef enum lttng_error_code (*event_rule_generate_filter_bytecode_cb)(
-               struct lttng_event_rule *event_rule,
-               const struct lttng_credentials *creds);
-typedef const char *(*event_rule_get_filter_cb)(
-               const struct lttng_event_rule *event_rule);
-typedef const struct lttng_bytecode *(
-               *event_rule_get_filter_bytecode_cb)(
-               const struct lttng_event_rule *event_rule);
-typedef enum lttng_event_rule_generate_exclusions_status (
-               *event_rule_generate_exclusions_cb)(
-               const struct lttng_event_rule *event_rule,
-               struct lttng_event_exclusion **exclusions);
-typedef unsigned long (*event_rule_hash_cb)(
-               const struct lttng_event_rule *event_rule);
-typedef struct lttng_event *(*event_rule_generate_lttng_event_cb)(
-               const struct lttng_event_rule *event_rule);
-typedef enum lttng_error_code (*event_rule_mi_serialize_cb)(
-               const struct lttng_event_rule *event_rule,
-               struct mi_writer *writer);
+using event_rule_destroy_cb = void (*)(struct lttng_event_rule *);
+using event_rule_validate_cb = bool (*)(const struct lttng_event_rule *);
+using event_rule_serialize_cb = int (*)(const struct lttng_event_rule *, struct lttng_payload *);
+using event_rule_equal_cb = bool (*)(const struct lttng_event_rule *,
+                                    const struct lttng_event_rule *);
+using event_rule_create_from_payload_cb = ssize_t (*)(struct lttng_payload_view *,
+                                                     struct lttng_event_rule **);
+using event_rule_generate_filter_bytecode_cb =
+       enum lttng_error_code (*)(struct lttng_event_rule *, const struct lttng_credentials *);
+using event_rule_get_filter_cb = const char *(*) (const struct lttng_event_rule *);
+using event_rule_get_filter_bytecode_cb =
+       const struct lttng_bytecode *(*) (const struct lttng_event_rule *);
+using event_rule_generate_exclusions_cb = enum lttng_event_rule_generate_exclusions_status (*)(
+       const struct lttng_event_rule *, struct lttng_event_exclusion **);
+using event_rule_hash_cb = unsigned long (*)(const struct lttng_event_rule *);
+using event_rule_generate_lttng_event_cb = struct lttng_event *(*) (const struct lttng_event_rule *);
+using event_rule_mi_serialize_cb = enum lttng_error_code (*)(const struct lttng_event_rule *,
+                                                            struct mi_writer *);
 
 struct lttng_event_rule {
        struct urcu_ref ref;
@@ -84,31 +74,27 @@ struct lttng_event_rule_comm {
        char payload[];
 };
 
-void lttng_event_rule_init(struct lttng_event_rule *event_rule,
-               enum lttng_event_rule_type type);
+void lttng_event_rule_init(struct lttng_event_rule *event_rule, enum lttng_event_rule_type type);
 
 bool lttng_event_rule_validate(const struct lttng_event_rule *event_rule);
 
-ssize_t lttng_event_rule_create_from_payload(
-               struct lttng_payload_view *payload,
-               struct lttng_event_rule **event_rule);
+ssize_t lttng_event_rule_create_from_payload(struct lttng_payload_view *payload,
+                                            struct lttng_event_rule **event_rule);
 
 int lttng_event_rule_serialize(const struct lttng_event_rule *event_rule,
-               struct lttng_payload *payload);
+                              struct lttng_payload *payload);
 
-bool lttng_event_rule_is_equal(const struct lttng_event_rule *a,
-               const struct lttng_event_rule *b);
+bool lttng_event_rule_is_equal(const struct lttng_event_rule *a, const struct lttng_event_rule *b);
 
 bool lttng_event_rule_get(struct lttng_event_rule *rule);
 
 void lttng_event_rule_put(struct lttng_event_rule *rule);
 
-enum lttng_domain_type lttng_event_rule_get_domain_type(
-               const struct lttng_event_rule *rule);
+enum lttng_domain_type lttng_event_rule_get_domain_type(const struct lttng_event_rule *rule);
 
-enum lttng_error_code lttng_event_rule_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds);
+enum lttng_error_code
+lttng_event_rule_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                         const struct lttng_credentials *creds);
 
 /*
  * If not present/implemented returns NULL.
@@ -120,8 +106,8 @@ const char *lttng_event_rule_get_filter(const struct lttng_event_rule *rule);
  * If not present/implemented returns NULL.
  * Caller DOES NOT own the returned object.
  */
-const struct lttng_bytecode *lttng_event_rule_get_filter_bytecode(
-               const struct lttng_event_rule *rule);
+const struct lttng_bytecode *
+lttng_event_rule_get_filter_bytecode(const struct lttng_event_rule *rule);
 
 /*
  * If not present/implemented return NULL.
@@ -129,7 +115,7 @@ const struct lttng_bytecode *lttng_event_rule_get_filter_bytecode(
  */
 enum lttng_event_rule_generate_exclusions_status
 lttng_event_rule_generate_exclusions(const struct lttng_event_rule *rule,
-               struct lttng_event_exclusion **exclusions);
+                                    struct lttng_event_exclusion **exclusions);
 
 const char *lttng_event_rule_type_str(enum lttng_event_rule_type type);
 
@@ -144,13 +130,12 @@ unsigned long lttng_event_rule_hash(const struct lttng_event_rule *rule);
  *
  * The caller owns the returned object.
  */
-struct lttng_event *lttng_event_rule_generate_lttng_event(
-               const struct lttng_event_rule *rule);
+struct lttng_event *lttng_event_rule_generate_lttng_event(const struct lttng_event_rule *rule);
 
 /* Test if an event rule targets an agent domain. */
 bool lttng_event_rule_targets_agent_domain(const struct lttng_event_rule *rule);
 
-enum lttng_error_code lttng_event_rule_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer);
+enum lttng_error_code lttng_event_rule_mi_serialize(const struct lttng_event_rule *rule,
+                                                   struct mi_writer *writer);
 
 #endif /* LTTNG_EVENT_RULE_INTERNAL_H */
index 0c2453ccfd772c13aab52d0c041ef4c8729ebcf7..a75db771e9e2155e20ef7de2f2fd7609256e998b 100644 (file)
@@ -48,8 +48,8 @@ enum lttng_event_rule_status {
  * Returns the type of an event rule on success, LTTNG_EVENT_RULE_UNKNOWN on
  * error.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_type lttng_event_rule_get_type(
-               const struct lttng_event_rule *event_rule);
+LTTNG_EXPORT extern enum lttng_event_rule_type
+lttng_event_rule_get_type(const struct lttng_event_rule *event_rule);
 
 /*
  * Destroy an event rule object.
index b769f0f8094215e3d309fd6b26765c28eab96ecc..c84ab7a7f86e39281577e526d4f4a5c319014e32 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_EVENT_RULE_JUL_LOGGING_INTERNAL_H
 #define LTTNG_EVENT_RULE_JUL_LOGGING_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/jul-logging.h>
 #include <lttng/event.h>
@@ -51,8 +52,7 @@ struct lttng_event_rule_jul_logging_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_jul_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_jul_logging_create_from_payload(struct lttng_payload_view *view,
+                                                        struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_JUL_LOGGING_INTERNAL_H */
index 833e6adff7b84f101a545d74b2c2c03ada9c61dd..7960c1c7e517086f6dd3ad0f726e633c2cebe7bf 100644 (file)
@@ -9,9 +9,9 @@
 #define LTTNG_EVENT_RULE_JUL_LOGGING_H
 
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/event.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-export.h>
-#include <lttng/event.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -35,8 +35,8 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_jul_logging_create
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_jul_logging_set_name_pattern(struct lttng_event_rule *rule, const char *pattern);
 
 /*
  * Get the name pattern of a jul logging event rule.
@@ -50,8 +50,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_se
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_jul_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                             const char **pattern);
 
 /*
  * Set the filter expression of a jul logging event rule.
@@ -61,8 +62,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_ge
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_jul_logging_set_filter(struct lttng_event_rule *rule, const char *expression);
 
 /*
  * Get the filter expression of a jul logging event rule.
@@ -76,8 +77,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_se
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_jul_logging_get_filter(const struct lttng_event_rule *rule,
+                                       const char **expression);
 
 /*
  * Set the log level rule of a jul logging event rule.
@@ -89,7 +91,7 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_jul_logging_ge
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
 lttng_event_rule_jul_logging_set_log_level_rule(struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule);
+                                               const struct lttng_log_level_rule *log_level_rule);
 
 /*
  * Get the log level rule of a jul logging event rule.
@@ -104,9 +106,8 @@ lttng_event_rule_jul_logging_set_log_level_rule(struct lttng_event_rule *rule,
  * to this call.
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_jul_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+lttng_event_rule_jul_logging_get_log_level_rule(const struct lttng_event_rule *rule,
+                                               const struct lttng_log_level_rule **log_level_rule);
 
 #ifdef __cplusplus
 }
index 5b4997987c9c27a80e38b8b744052b7b9170a0c5..f92fc10c4b2d8d7d8556582eb9298fcfbff64f25 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef LTTNG_EVENT_RULE_KERNEL_KPROBE_INTERNAL_H
 #define LTTNG_EVENT_RULE_KERNEL_KPROBE_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-kprobe.h>
 
@@ -31,8 +32,7 @@ struct lttng_event_rule_kernel_kprobe_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
-               struct lttng_payload_view *payload,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(struct lttng_payload_view *payload,
+                                                          struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_KERNEL_KPROBE_INTERNAL_H */
index c970116afebd19fa059e02066fe10c70711dee4e..6e292f0d1a1112e0920645c9bd053be5d95b69cf 100644 (file)
@@ -25,8 +25,8 @@ struct lttng_kernel_probe_location;
  * Returns a new event rule on success, NULL on failure. The returned event rule
  * must be destroyed using lttng_event_rule_destroy().
  */
-LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_kprobe_create(
-               const struct lttng_kernel_probe_location *location);
+LTTNG_EXPORT extern struct lttng_event_rule *
+lttng_event_rule_kernel_kprobe_create(const struct lttng_kernel_probe_location *location);
 
 /*
  * Get the kernel probe location of a kernel kprobe event rule.
@@ -40,9 +40,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_kprobe_crea
  * passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a location was not set prior to
  * this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_get_location(
-               const struct lttng_event_rule *rule,
-               const struct lttng_kernel_probe_location **location);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_get_location(const struct lttng_event_rule *rule,
+                                           const struct lttng_kernel_probe_location **location);
 
 /*
  * Set the name of a kernel kprobe event rule.
@@ -52,8 +52,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_
  * Returns LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_set_event_name(
-               struct lttng_event_rule *rule, const char *name);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_set_event_name(struct lttng_event_rule *rule, const char *name);
 
 /*
  * Get the name of a kernel kprobe event rule.
@@ -66,8 +66,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_
  * success, LTTNG_EVENT_RULE_STATUS_INVALID if an invalid parameter is passed,
  * or LTTNG_EVENT_RULE_STATUS_UNSET if a name was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_get_event_name(
-               const struct lttng_event_rule *rule, const char **name);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_get_event_name(const struct lttng_event_rule *rule,
+                                             const char **name);
 
 #ifdef __cplusplus
 }
index 2ca1823eca4aa1a4c1e209b692a131922c052110..9cef606bbe9807e2a232f7efab45b81ef81fa5f7 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef LTTNG_EVENT_RULE_KERNEL_SYSCALL_INTERNAL_H
 #define LTTNG_EVENT_RULE_KERNEL_SYSCALL_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-syscall.h>
 
@@ -40,11 +41,10 @@ struct lttng_event_rule_kernel_syscall_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_kernel_syscall_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_kernel_syscall_create_from_payload(struct lttng_payload_view *view,
+                                                           struct lttng_event_rule **rule);
 
 const char *lttng_event_rule_kernel_syscall_emission_site_str(
-               enum lttng_event_rule_kernel_syscall_emission_site emission_site);
+       enum lttng_event_rule_kernel_syscall_emission_site emission_site);
 
 #endif /* LTTNG_EVENT_RULE_KERNEL_SYSCALL_INTERNAL_H */
index ce8be6a5dd420b22fb73952e3cab3c36a4eae208..4ae104ff622ffd34a558441fa6e13c82ce4fb662 100644 (file)
@@ -31,8 +31,8 @@ enum lttng_event_rule_kernel_syscall_emission_site {
  * Returns a new event rule on success, NULL on failure. This event rule must be
  * destroyed using lttng_event_rule_destroy().
  */
-LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_syscall_create(enum
-               lttng_event_rule_kernel_syscall_emission_site emission_site);
+LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_syscall_create(
+       enum lttng_event_rule_kernel_syscall_emission_site emission_site);
 
 /*
  * Set the name pattern of a kernel syscall event rule.
@@ -44,8 +44,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_syscall_cre
  * Returns LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_set_name_pattern(struct lttng_event_rule *rule,
+                                                const char *pattern);
 
 /*
  * Get the name pattern of a kernel syscall event rule.
@@ -59,8 +60,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_get_name_pattern(const struct lttng_event_rule *rule,
+                                                const char **pattern);
 
 /*
  * Set the filter expression of a kernel syscall event rule.
@@ -70,8 +72,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall
  * Returns LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_set_filter(struct lttng_event_rule *rule, const char *expression);
 
 /*
  * Get the filter expression of a kernel syscall event rule.
@@ -85,8 +87,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_get_filter(const struct lttng_event_rule *rule,
+                                          const char **expression);
 
 /*
  * Get the emission site of a kernel syscall event rule.
@@ -94,8 +97,7 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_syscall
  * Returns a enum lttng_event_rule_kernel_syscall_emission_site.
  */
 LTTNG_EXPORT extern enum lttng_event_rule_kernel_syscall_emission_site
-lttng_event_rule_kernel_syscall_get_emission_site(
-               const struct lttng_event_rule *rule);
+lttng_event_rule_kernel_syscall_get_emission_site(const struct lttng_event_rule *rule);
 
 #ifdef __cplusplus
 }
index d800eef9177830ff69d530fd6465173eec016916..1a0e50abd8c90f40f7f9177cdde5cc5646167899 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_EVENT_RULE_KERNEL_TRACEPOINT_INTERNAL_H
 #define LTTNG_EVENT_RULE_KERNEL_TRACEPOINT_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-tracepoint.h>
 #include <lttng/event.h>
@@ -44,8 +45,7 @@ struct lttng_event_rule_kernel_tracepoint_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_KERNEL_TRACEPOINT_INTERNAL_H */
index 550a04ac492701dd9385f547900adad394ddda42..6c566e1596a0f502b16efbe09eeef9059f1d5ae3 100644 (file)
@@ -34,8 +34,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_tracepoint_
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_set_name_pattern(struct lttng_event_rule *rule,
+                                                   const char *pattern);
 
 /*
  * Get the name pattern of a kernel tracepoint event rule.
@@ -49,8 +50,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepo
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_get_name_pattern(const struct lttng_event_rule *rule,
+                                                   const char **pattern);
 
 /*
  * Set the filter expression of a kernel tracepoint event rule.
@@ -60,8 +62,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepo
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_set_filter(struct lttng_event_rule *rule,
+                                             const char *expression);
 
 /*
  * Get the filter expression of a kernel tracepoint event rule.
@@ -75,8 +78,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepo
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_get_filter(const struct lttng_event_rule *rule,
+                                             const char **expression);
 
 #ifdef __cplusplus
 }
index f9a1931004f293c5136120e73b12d4a32c628509..61dfd4f3f4f74b5293b4f4e38a10efadcd534901 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef LTTNG_EVENT_RULE_KERNEL_UPROBE_INTERNAL_H
 #define LTTNG_EVENT_RULE_KERNEL_UPROBE_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-uprobe.h>
 
@@ -32,12 +33,10 @@ struct lttng_event_rule_kernel_uprobe_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_event_rule **rule);
 
 struct lttng_userspace_probe_location *
-lttng_event_rule_kernel_uprobe_get_location_mutable(
-               const struct lttng_event_rule *rule);
+lttng_event_rule_kernel_uprobe_get_location_mutable(const struct lttng_event_rule *rule);
 
 #endif /* LTTNG_EVENT_RULE_KERNEL_UPROBE_INTERNAL_H */
index 6b29b695d4291f2b22677de33b4088959fa0b58b..cfb0ccaa78aee60075f2f471b34ce44210cccfa3 100644 (file)
@@ -24,8 +24,8 @@ extern "C" {
  * Returns a new event rule on success, NULL on failure. This event rule must be
  * destroyed using lttng_event_rule_destroy().
  */
-LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_uprobe_create(
-               const struct lttng_userspace_probe_location *location);
+LTTNG_EXPORT extern struct lttng_event_rule *
+lttng_event_rule_kernel_uprobe_create(const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the location of a kernel uprobe event rule.
@@ -39,9 +39,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_kernel_uprobe_crea
  * passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a location was not set prior to
  * this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_get_location(
-               const struct lttng_event_rule *rule,
-               const struct lttng_userspace_probe_location **location);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_get_location(const struct lttng_event_rule *rule,
+                                           const struct lttng_userspace_probe_location **location);
 
 /*
  * Set the name of a kernel uprobe event rule.
@@ -51,8 +51,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_set_event_name(
-               struct lttng_event_rule *rule, const char *name);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_set_event_name(struct lttng_event_rule *rule, const char *name);
 
 /*
  * Get the name of a kernel uprobe event rule.
@@ -65,8 +65,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_
  * success, LTTNG_EVENT_RULE_STATUS_INVALID if an invalid parameter is passed,
  * or LTTNG_EVENT_RULE_STATUS_UNSET if a name was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_get_event_name(
-               const struct lttng_event_rule *rule, const char **name);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_get_event_name(const struct lttng_event_rule *rule,
+                                             const char **name);
 
 #ifdef __cplusplus
 }
index a65e74b6d1c50d29459ffea72d8406a7e59db1c5..239bf98ee41e0769d0c481e572e11f33760c0974 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_EVENT_RULE_LOG4J_LOGGING_INTERNAL_H
 #define LTTNG_EVENT_RULE_LOG4J_LOGGING_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/log4j-logging.h>
 #include <lttng/event.h>
@@ -51,8 +52,7 @@ struct lttng_event_rule_log4j_logging_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_log4j_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_log4j_logging_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_LOG4J_LOGGING_INTERNAL_H */
index 277e7d95019059b9723f009d875757e8ab17ed02..9128b4d690804bc03089da154499f4d5acae59f1 100644 (file)
@@ -9,9 +9,9 @@
 #define LTTNG_EVENT_RULE_LOG4J_LOGGING_H
 
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/event.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-export.h>
-#include <lttng/event.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -35,8 +35,8 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_log4j_logging_crea
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_set_name_pattern(struct lttng_event_rule *rule, const char *pattern);
 
 /*
  * Get the name pattern of a log4j logging event rule.
@@ -50,8 +50,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                               const char **pattern);
 
 /*
  * Set the filter expression of a log4j logging event rule.
@@ -61,8 +62,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_set_filter(struct lttng_event_rule *rule, const char *expression);
 
 /*
  * Get the filter expression of a log4j logging event rule.
@@ -76,8 +77,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_get_filter(const struct lttng_event_rule *rule,
+                                         const char **expression);
 
 /*
  * Set the log level rule of a log4j logging event rule.
@@ -87,9 +89,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_log4j_logging_set_log_level_rule(struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule);
+LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_log_level_rule(
+       struct lttng_event_rule *rule, const struct lttng_log_level_rule *log_level_rule);
 
 /*
  * Get the log level rule of a log4j logging event rule.
@@ -103,10 +104,8 @@ lttng_event_rule_log4j_logging_set_log_level_rule(struct lttng_event_rule *rule,
  * is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a log level rule was not set prior
  * to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_log4j_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_log_level_rule(
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule);
 
 #ifdef __cplusplus
 }
index d23f4e2a541048c217d42203c73228e2ca9948f6..f7513f420c15e07f16b1709d4816bf938f52fb95 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_EVENT_RULE_PYTHON_LOGGING_INTERNAL_H
 #define LTTNG_EVENT_RULE_PYTHON_LOGGING_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/python-logging.h>
 #include <lttng/event.h>
@@ -51,8 +52,7 @@ struct lttng_event_rule_python_logging_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_python_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_python_logging_create_from_payload(struct lttng_payload_view *view,
+                                                           struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_PYTHON_LOGGING_INTERNAL_H */
index d4a6ada472b28d1a6ed012ac89bdaba9ca506632..d77be2e50d0e015b465be2bf39b8b28053f06f57 100644 (file)
@@ -9,9 +9,9 @@
 #define LTTNG_EVENT_RULE_PYTHON_LOGGING_H
 
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/event.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-export.h>
-#include <lttng/event.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -35,8 +35,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_python_logging_cre
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_python_logging_set_name_pattern(struct lttng_event_rule *rule,
+                                                const char *pattern);
 
 /*
  * Get the name pattern of a python logging event rule.
@@ -50,8 +51,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_python_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                                const char **pattern);
 
 /*
  * Set the filter expression of a python logging event rule.
@@ -61,8 +63,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_python_logging_set_filter(struct lttng_event_rule *rule, const char *expression);
 
 /*
  * Get the filter expression of a python logging event rule.
@@ -76,8 +78,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_python_logging_get_filter(const struct lttng_event_rule *rule,
+                                          const char **expression);
 
 /*
  * Set the log level rule of a python logging event rule.
@@ -87,9 +90,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_python_logging_set_log_level_rule(struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule);
+LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_set_log_level_rule(
+       struct lttng_event_rule *rule, const struct lttng_log_level_rule *log_level_rule);
 
 /*
  * Get the log level rule of a python logging event rule.
@@ -103,10 +105,8 @@ lttng_event_rule_python_logging_set_log_level_rule(struct lttng_event_rule *rule
  * is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a log level rule was not set prior
  * to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_python_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_python_logging_get_log_level_rule(
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule);
 
 #ifdef __cplusplus
 }
index 1960a8a4d38ca2e0b4d79ed267c3139ea8f6f5df..65199bbbc2167faa207f63c26cc11d15fd9f15e0 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_EVENT_RULE_USER_TRACEPOINT_INTERNAL_H
 #define LTTNG_EVENT_RULE_USER_TRACEPOINT_INTERNAL_H
 
-#include <common/payload-view.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/payload-view.hpp>
+
 #include <lttng/domain.h>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/user-tracepoint.h>
@@ -58,8 +59,7 @@ struct lttng_event_rule_user_tracepoint_comm {
        char payload[];
 } LTTNG_PACKED;
 
-ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **rule);
+ssize_t lttng_event_rule_user_tracepoint_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_event_rule **rule);
 
 #endif /* LTTNG_EVENT_RULE_USER_TRACEPOINT_INTERNAL_H */
index 7ee91ce79c15c5bdcfb2305a2689e108d676e24c..8f227b77815e336cbd03afa645cd39b943720e8b 100644 (file)
@@ -10,9 +10,9 @@
 
 #include <lttng/domain.h>
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/event.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-export.h>
-#include <lttng/event.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -36,8 +36,9 @@ LTTNG_EXPORT extern struct lttng_event_rule *lttng_event_rule_user_tracepoint_cr
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_set_name_pattern(struct lttng_event_rule *rule,
+                                                 const char *pattern);
 
 /*
  * Get the name pattern of a user tracepoint event rule.
@@ -51,8 +52,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoin
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a pattern
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_get_name_pattern(const struct lttng_event_rule *rule,
+                                                 const char **pattern);
 
 /*
  * Set the filter expression of a user tracepoint event rule.
@@ -62,8 +64,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoin
  * Return LTTNG_EVENT_RULE_STATUS_OK on success, LTTNG_EVENT_RULE_STATUS_INVALID
  * if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_filter(
-               struct lttng_event_rule *rule, const char *expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_set_filter(struct lttng_event_rule *rule, const char *expression);
 
 /*
  * Get the filter expression of a user tracepoint event rule.
@@ -77,8 +79,9 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoin
  * parameter is passed, or LTTNG_EVENT_RULE_STATUS_UNSET if a filter expression
  * was not set prior to this call.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_filter(
-               const struct lttng_event_rule *rule, const char **expression);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_get_filter(const struct lttng_event_rule *rule,
+                                           const char **expression);
 
 /*
  * Set the log level rule of a user tracepoint event rule.
@@ -89,8 +92,8 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoin
  * if invalid parameters are passed.
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
-lttng_event_rule_user_tracepoint_set_log_level_rule(struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule);
+lttng_event_rule_user_tracepoint_set_log_level_rule(
+       struct lttng_event_rule *rule, const struct lttng_log_level_rule *log_level_rule);
 
 /*
  * Get the log level rule of a user tracepoint event rule.
@@ -106,8 +109,7 @@ lttng_event_rule_user_tracepoint_set_log_level_rule(struct lttng_event_rule *rul
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
 lttng_event_rule_user_tracepoint_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule);
 
 /*
  * Add a name pattern exclusion to the set of name pattern exclusion of an event rule.
@@ -117,9 +119,9 @@ lttng_event_rule_user_tracepoint_get_log_level_rule(
  * Returns LTTNG_EVENT_RULE_STATUS_OK on success,
  * LTTNG_EVENT_RULE_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
-               struct lttng_event_rule *rule,
-               const char *exclusion);
+LTTNG_EXPORT extern enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(struct lttng_event_rule *rule,
+                                                           const char *exclusion);
 
 /*
  * Get the name pattern exclusions property count of an event rule.
@@ -130,7 +132,7 @@ LTTNG_EXPORT extern enum lttng_event_rule_status lttng_event_rule_user_tracepoin
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
 lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-               const struct lttng_event_rule *rule, unsigned int *count);
+       const struct lttng_event_rule *rule, unsigned int *count);
 
 /*
  * Get the pattern name exclusion at the given index.
@@ -141,9 +143,7 @@ lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
  */
 LTTNG_EXPORT extern enum lttng_event_rule_status
 lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-               const struct lttng_event_rule *rule,
-               unsigned int index,
-               const char **exclusion);
+       const struct lttng_event_rule *rule, unsigned int index, const char **exclusion);
 
 #ifdef __cplusplus
 }
index 5915db6d6738632d126ad2b0369f78d84256e215..e4ee28988712300d513f9f9a23ddc925b09cb216 100644 (file)
 #ifndef LTTNG_EVENT_H
 #define LTTNG_EVENT_H
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #include <lttng/handle.h>
 #include <lttng/lttng-export.h>
 #include <lttng/userspace-probe.h>
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+/*!
+@brief
+    \ref api-rer-conds-inst-pt-type "Instrumentation type condition"
+    of a recording event
 
-/*
- * Instrumentation type of tracing event.
- */
+@ingroup api_rer
+*/
 enum lttng_event_type {
-       LTTNG_EVENT_ALL                       = -1,
-       LTTNG_EVENT_TRACEPOINT                = 0,
-       LTTNG_EVENT_PROBE                     = 1,
-       LTTNG_EVENT_FUNCTION                  = 2,
-       LTTNG_EVENT_FUNCTION_ENTRY            = 3,
-       LTTNG_EVENT_NOOP                      = 4,
-       LTTNG_EVENT_SYSCALL                   = 5,
-       LTTNG_EVENT_USERSPACE_PROBE           = 6,
+       /// Match LTTng kernel tracepoint and Linux system call events.
+       LTTNG_EVENT_ALL = -1,
+
+       /// Match LTTng tracepoint or Java/Python logging events.
+       LTTNG_EVENT_TRACEPOINT = 0,
+
+       /*!
+       Match Linux
+       <a href="https://www.kernel.org/doc/html/latest/trace/kprobes.html">kprobe</a>
+       events.
+       */
+       LTTNG_EVENT_PROBE = 1,
+
+       /*!
+       Match Linux
+       <a href="https://www.kernel.org/doc/html/latest/trace/kprobes.html">kretprobe</a>
+       events.
+       */
+       LTTNG_EVENT_FUNCTION = 2,
+
+       /// @cond UNUSED
+       LTTNG_EVENT_FUNCTION_ENTRY = 3,
+       LTTNG_EVENT_NOOP = 4,
+       /// @endcond
+
+       /// Match Linux system call events.
+       LTTNG_EVENT_SYSCALL = 5,
+
+       /*!
+       Match Linux
+       <a href="https://lwn.net/Articles/499190/">uprobe</a>
+       events.
+       */
+       LTTNG_EVENT_USERSPACE_PROBE = 6,
 };
 
-/*
- * Loglevel information.
- */
+/*!
+@brief
+    Operand of the
+    \ref api-rer-conds-ll "instrumentation point log level condition"
+    of a recording event rule.
+
+@ingroup api_rer
+
+In the enumerator descriptions below, consider that \lt_var{LL} is the
+log level value of the condition, that is, the value of the
+lttng_event::loglevel member when the lttng_event::loglevel_type member
+is the described enumerator.
+
+Depending on the \lt_obj_domain of the recording event rule, \lt_var{LL}
+is one of the enumerators of #lttng_loglevel, #lttng_loglevel_jul,
+#lttng_loglevel_log4j, or #lttng_loglevel_python.
+*/
 enum lttng_loglevel_type {
-       LTTNG_EVENT_LOGLEVEL_ALL              = 0,
-       LTTNG_EVENT_LOGLEVEL_RANGE            = 1,
-       LTTNG_EVENT_LOGLEVEL_SINGLE           = 2,
+       /// Match events regardless of their log level.
+       LTTNG_EVENT_LOGLEVEL_ALL = 0,
+
+       /*!
+       Match events with a log level that's at least as severe as
+       \lt_var{LL}.
+       */
+       LTTNG_EVENT_LOGLEVEL_RANGE = 1,
+
+       /// Match events with a log level that's exacty \lt_var{LL}.
+       LTTNG_EVENT_LOGLEVEL_SINGLE = 2,
 };
 
-/*
- * Available loglevels.
- */
+/*!
+@brief
+    Value of the
+    \ref api-rer-conds-ll "instrumentation point log level condition"=
+    of an LTTng
+    \link #LTTNG_DOMAIN_UST user space\endlink tracepoint
+    recording event rule.
+
+@ingroup api_rer
+
+@sa #lttng_loglevel_type --
+    Operand of the log level condition of a recording event rule.
+*/
 enum lttng_loglevel {
-       LTTNG_LOGLEVEL_EMERG                  = 0,
-       LTTNG_LOGLEVEL_ALERT                  = 1,
-       LTTNG_LOGLEVEL_CRIT                   = 2,
-       LTTNG_LOGLEVEL_ERR                    = 3,
-       LTTNG_LOGLEVEL_WARNING                = 4,
-       LTTNG_LOGLEVEL_NOTICE                 = 5,
-       LTTNG_LOGLEVEL_INFO                   = 6,
-       LTTNG_LOGLEVEL_DEBUG_SYSTEM           = 7,
-       LTTNG_LOGLEVEL_DEBUG_PROGRAM          = 8,
-       LTTNG_LOGLEVEL_DEBUG_PROCESS          = 9,
-       LTTNG_LOGLEVEL_DEBUG_MODULE           = 10,
-       LTTNG_LOGLEVEL_DEBUG_UNIT             = 11,
-       LTTNG_LOGLEVEL_DEBUG_FUNCTION         = 12,
-       LTTNG_LOGLEVEL_DEBUG_LINE             = 13,
-       LTTNG_LOGLEVEL_DEBUG                  = 14,
+       /// System is unusable.
+       LTTNG_LOGLEVEL_EMERG = 0,
+
+       /// Action must be taken immediately.
+       LTTNG_LOGLEVEL_ALERT = 1,
+
+       /// Critical conditions.
+       LTTNG_LOGLEVEL_CRIT = 2,
+
+       /// Error conditions.
+       LTTNG_LOGLEVEL_ERR = 3,
+
+       /// Warning conditions.
+       LTTNG_LOGLEVEL_WARNING = 4,
+
+       /// Normal, but significant, condition.
+       LTTNG_LOGLEVEL_NOTICE = 5,
+
+       /// Informational message.
+       LTTNG_LOGLEVEL_INFO = 6,
+
+       /// Debug information with system-level scope (set of programs).
+       LTTNG_LOGLEVEL_DEBUG_SYSTEM = 7,
+
+       /// Debug information with program-level scope (set of processes).
+       LTTNG_LOGLEVEL_DEBUG_PROGRAM = 8,
+
+       /// Debug information with process-level scope (set of modules).
+       LTTNG_LOGLEVEL_DEBUG_PROCESS = 9,
+
+       /*!
+       Debug information with module (executable/library) scope
+       (set of units).
+       */
+       LTTNG_LOGLEVEL_DEBUG_MODULE = 10,
+
+       /// Debug information with compilation unit scope (set of functions).
+       LTTNG_LOGLEVEL_DEBUG_UNIT = 11,
+
+       /// Debug information with function-level scope.
+       LTTNG_LOGLEVEL_DEBUG_FUNCTION = 12,
+
+       /// Debug information with line-level scope.
+       LTTNG_LOGLEVEL_DEBUG_LINE = 13,
+
+       /// Debug-level message.
+       LTTNG_LOGLEVEL_DEBUG = 14,
 };
 
-/*
- * Available loglevels for the JUL domain. Those are an exact map from the
- * class java.util.logging.Level.
- */
+/*!
+@brief
+    Value of the
+    \ref api-rer-conds-ll "instrumentation point log level condition"
+    of a
+    \link #LTTNG_DOMAIN_JUL <code>java.util.logging</code>\endlink
+    recording event rule.
+
+@ingroup api_rer
+
+@sa #lttng_loglevel_type --
+    Operand of the log level condition of a recording event rule.
+*/
 enum lttng_loglevel_jul {
-       LTTNG_LOGLEVEL_JUL_OFF                = INT32_MAX,
-       LTTNG_LOGLEVEL_JUL_SEVERE             = 1000,
-       LTTNG_LOGLEVEL_JUL_WARNING            = 900,
-       LTTNG_LOGLEVEL_JUL_INFO               = 800,
-       LTTNG_LOGLEVEL_JUL_CONFIG             = 700,
-       LTTNG_LOGLEVEL_JUL_FINE               = 500,
-       LTTNG_LOGLEVEL_JUL_FINER              = 400,
-       LTTNG_LOGLEVEL_JUL_FINEST             = 300,
-       LTTNG_LOGLEVEL_JUL_ALL                = INT32_MIN,
+       /// Logging turned off.
+       LTTNG_LOGLEVEL_JUL_OFF = INT32_MAX,
+
+       /// Serious failure.
+       LTTNG_LOGLEVEL_JUL_SEVERE = 1000,
+
+       /// Potential problem.
+       LTTNG_LOGLEVEL_JUL_WARNING = 900,
+
+       /// Informational messages.
+       LTTNG_LOGLEVEL_JUL_INFO = 800,
+
+       /// Static configuration messages.
+       LTTNG_LOGLEVEL_JUL_CONFIG = 700,
+
+       /// Tracing information.
+       LTTNG_LOGLEVEL_JUL_FINE = 500,
+
+       /// Fairly detailed tracing message.
+       LTTNG_LOGLEVEL_JUL_FINER = 400,
+
+       /// Highly detailed tracing message.
+       LTTNG_LOGLEVEL_JUL_FINEST = 300,
+
+       /// All messages.
+       LTTNG_LOGLEVEL_JUL_ALL = INT32_MIN,
 };
 
-/*
- * Available loglevels for the LOG4j domain. Those are an exact map from the
- * class org.apache.log4j.Level.
- */
+/*!
+@brief
+    Value of the
+    \ref api-rer-conds-ll "instrumentation point log level condition"
+    of an
+    \link #LTTNG_DOMAIN_LOG4J Apache log4j\endlink
+    recording event rule.
+
+@ingroup api_rer
+
+@sa #lttng_loglevel_type --
+    Operand of the log level condition of a recording event rule.
+*/
 enum lttng_loglevel_log4j {
-       LTTNG_LOGLEVEL_LOG4J_OFF              = INT32_MAX,
-       LTTNG_LOGLEVEL_LOG4J_FATAL            = 50000,
-       LTTNG_LOGLEVEL_LOG4J_ERROR            = 40000,
-       LTTNG_LOGLEVEL_LOG4J_WARN             = 30000,
-       LTTNG_LOGLEVEL_LOG4J_INFO             = 20000,
-       LTTNG_LOGLEVEL_LOG4J_DEBUG            = 10000,
-       LTTNG_LOGLEVEL_LOG4J_TRACE            = 5000,
-       LTTNG_LOGLEVEL_LOG4J_ALL              = INT32_MIN,
+       /// Logging turned off.
+       LTTNG_LOGLEVEL_LOG4J_OFF = INT32_MAX,
+
+       /*!
+       Very severe error events that will presumably lead the
+       application to abort.
+       */
+       LTTNG_LOGLEVEL_LOG4J_FATAL = 50000,
+
+       /*!
+       Error events that might still allow the application to continue
+       running.
+       */
+       LTTNG_LOGLEVEL_LOG4J_ERROR = 40000,
+
+       /// Potentially harmful situations.
+       LTTNG_LOGLEVEL_LOG4J_WARN = 30000,
+
+       /*!
+       Informational messages that highlight the progress of the
+       application at coarse-grained level.
+       */
+       LTTNG_LOGLEVEL_LOG4J_INFO = 20000,
+
+       /*!
+       Fine-grained informational events that are most useful to debug
+       an application.
+       */
+       LTTNG_LOGLEVEL_LOG4J_DEBUG = 10000,
+
+       /*!
+       Finer-grained informational events than the
+       #LTTNG_LOGLEVEL_LOG4J_DEBUG level.
+       */
+       LTTNG_LOGLEVEL_LOG4J_TRACE = 5000,
+
+       /// All levels, including custom levels.
+       LTTNG_LOGLEVEL_LOG4J_ALL = INT32_MIN,
 };
 
-/*
- * Available loglevels for the Python domain. Those are an exact map from the
- * Level class.
- */
+/*!
+@brief
+    Value of the
+    \ref api-rer-conds-ll "instrumentation point log level condition"
+    of a
+    \link #LTTNG_DOMAIN_PYTHON Python\endlink
+    recording event rule.
+
+@ingroup api_rer
+
+@sa #lttng_loglevel_type --
+    Operand of the log level condition of a recording event rule.
+*/
 enum lttng_loglevel_python {
-       LTTNG_LOGLEVEL_PYTHON_CRITICAL        = 50,
-       LTTNG_LOGLEVEL_PYTHON_ERROR           = 40,
-       LTTNG_LOGLEVEL_PYTHON_WARNING         = 30,
-       LTTNG_LOGLEVEL_PYTHON_INFO            = 20,
-       LTTNG_LOGLEVEL_PYTHON_DEBUG           = 10,
-       LTTNG_LOGLEVEL_PYTHON_NOTSET          = 0,
+       /// Critical.
+       LTTNG_LOGLEVEL_PYTHON_CRITICAL = 50,
+
+       /// Error.
+       LTTNG_LOGLEVEL_PYTHON_ERROR = 40,
+
+       /// Warning.
+       LTTNG_LOGLEVEL_PYTHON_WARNING = 30,
+
+       /// Information.
+       LTTNG_LOGLEVEL_PYTHON_INFO = 20,
+
+       /// Debugging.
+       LTTNG_LOGLEVEL_PYTHON_DEBUG = 10,
+
+       /// Logging turned off.
+       LTTNG_LOGLEVEL_PYTHON_NOTSET = 0,
 };
 
-/*
- * LTTng consumer mode
- */
+/*!
+@brief
+    Channel output type.
+
+@ingroup api_channel
+*/
 enum lttng_event_output {
-       LTTNG_EVENT_SPLICE                    = 0,
-       LTTNG_EVENT_MMAP                      = 1,
+       /// Use the \lt_man_gen{splice,2} system call.
+       LTTNG_EVENT_SPLICE = 0,
+
+       /// Use the \lt_man_gen{mmap,2} system call.
+       LTTNG_EVENT_MMAP = 1,
 };
 
-/* Event context possible type */
+/*!
+@brief
+    Context field type.
+
+@ingroup api_channel
+
+The following table indicates, for each enumerator, its description, for
+which \lt_obj_domain it's available, and the
+data type and the name of the resulting context field in traces.
+
+<table>
+  <tr>
+    <th>Enumerator
+    <th>Description
+    <th>Tracing domain
+    <th>Field type
+    <th>Field name
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PID
+    <td>Process ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>pid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PROCNAME
+    <td>Process name
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>String
+    <td><code>procname</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PRIO
+    <td>Process priority
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>prio</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_NICE
+    <td>Nice value of the process
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>nice</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VPID
+    <td>Virtual process ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vpid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_TID
+    <td>Thread ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>tid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VTID
+    <td>Virtual thread ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>vtid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PPID
+    <td>ID of the parent process
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>ppid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VPPID
+    <td>Virtual ID of the parent process
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>vppid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PTHREAD_ID
+    <td>POSIX thread ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>pthread_id</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_HOSTNAME
+    <td>Hostname
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>String
+    <td><code>hostname</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_IP
+    <td>Instruction pointer
+    <td>#LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>ip</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER
+    <td>
+      Per-CPU perf counter.
+
+      If the lttng_event_context::ctx member of an #lttng_event_context
+      structure is #LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER, then the
+      lttng_event_context::lttng_event_context_u::perf_counter member
+      of lttng_event_context::u selects a specific per-CPU perf counter.
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td>Depends on the selected perf counter
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER
+    <td>
+      Per-thread perf counter.
+
+      If the lttng_event_context::ctx member of an #lttng_event_context
+      structure is #LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER, then the
+      lttng_event_context::lttng_event_context_u::perf_counter member
+      of lttng_event_context::u selects a specific per-thread
+      perf counter.
+    <td>#LTTNG_DOMAIN_UST
+    <td>Integer
+    <td>Depends on the selected perf counter
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_APP_CONTEXT
+    <td>
+      Application-specific context.
+
+      If the lttng_event_context::ctx member of an #lttng_event_context
+      structure is #LTTNG_EVENT_CONTEXT_APP_CONTEXT, then the
+      lttng_event_context::lttng_event_context_u::app_ctx member of
+      of lttng_event_context::u selects
+      a specific application-specific context.
+    <td>#LTTNG_DOMAIN_JUL or #LTTNG_DOMAIN_LOG4J
+    <td>Integer or string
+    <td>Depends on the selected application-specific context
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_INTERRUPTIBLE
+    <td>Whether or not the process is interruptible
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer (0 or 1)
+    <td><code>interruptible</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PREEMPTIBLE
+    <td>Whether or not the process is preemptible
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer (0 or 1)
+    <td><code>preemptible</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE
+    <td>Whether or not the process needs a reschedule
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer (0 or 1)
+    <td><code>need_reschedule</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_MIGRATABLE
+    <td>Whether or not the process is migratable
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer (0 or 1)
+    <td><code>migratable</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL
+    <td>Linux kernel call stack
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Dynamic-length array of integers (instruction pointers)
+    <td><code>callstack_kernel</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_CALLSTACK_USER
+    <td>
+      User space call stack.
+
+      Only supported on IA-32 and x86-64 architectures.
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Dynamic-length array of integers (instruction pointers)
+    <td><code>callstack_user</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_CGROUP_NS
+    <td>
+      Control group root directory namespace ID.
+
+      @sa \lt_man_gen{cgroup_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>cgroup_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_IPC_NS
+    <td>
+      System&nbsp;V IPC and POSIX message queue namespace ID.
+
+      @sa \lt_man_gen{ipc_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>ipc_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_MNT_NS
+    <td>
+      Mount point namespace ID.
+
+      @sa \lt_man_gen{mount_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>mnt_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_NET_NS
+    <td>
+      Networking namespace ID.
+
+      @sa \lt_man_gen{network_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>net_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_PID_NS
+    <td>
+      Process ID namespace ID.
+
+      @sa \lt_man_gen{pid_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>pid_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_USER_NS
+    <td>
+      User and group ID namespace ID.
+
+      @sa \lt_man_gen{user_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>user_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_UTS_NS
+    <td>
+      Hostname and NIS domain name namespace ID.
+
+      @sa \lt_man_gen{uts_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>uts_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_TIME_NS
+    <td>
+      Boot and monotonic clock namespace ID.
+
+      @sa \lt_man_gen{time_namespaces,7}
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>time_ns</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_UID
+    <td>User ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>uid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_EUID
+    <td>Effective user ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>euid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_SUID
+    <td>Set owner user ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>suid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_GID
+    <td>Group ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>gid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_EGID
+    <td>Effective group ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>egid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_SGID
+    <td>Set owner group ID
+    <td>#LTTNG_DOMAIN_KERNEL
+    <td>Integer
+    <td><code>sgid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VUID
+    <td>Virtual user ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vuid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VEUID
+    <td>Virtual effective user ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>veuid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VSUID
+    <td>Virtual set owner user ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vsuid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VGID
+    <td>Virtual group ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vgid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VEGID
+    <td>Virtual effective group ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vegid</code>
+  <tr>
+    <td>#LTTNG_EVENT_CONTEXT_VSGID
+    <td>Virtual set owner group ID
+    <td>#LTTNG_DOMAIN_KERNEL and #LTTNG_DOMAIN_UST
+    <td>Integer
+    <td><code>vsgid</code>
+</table>
+
+@ingroup api_channel
+*/
 enum lttng_event_context_type {
-       LTTNG_EVENT_CONTEXT_PID                 = 0,
-       LTTNG_EVENT_CONTEXT_PERF_COUNTER        = 1,    /* Backward compat. */
-       LTTNG_EVENT_CONTEXT_PROCNAME            = 2,
-       LTTNG_EVENT_CONTEXT_PRIO                = 3,
-       LTTNG_EVENT_CONTEXT_NICE                = 4,
-       LTTNG_EVENT_CONTEXT_VPID                = 5,
-       LTTNG_EVENT_CONTEXT_TID                 = 6,
-       LTTNG_EVENT_CONTEXT_VTID                = 7,
-       LTTNG_EVENT_CONTEXT_PPID                = 8,
-       LTTNG_EVENT_CONTEXT_VPPID               = 9,
-       LTTNG_EVENT_CONTEXT_PTHREAD_ID          = 10,
-       LTTNG_EVENT_CONTEXT_HOSTNAME            = 11,
-       LTTNG_EVENT_CONTEXT_IP                  = 12,
-       LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER    = 13,
+       /// Process ID.
+       LTTNG_EVENT_CONTEXT_PID = 0,
+
+       /// @cond BACKWARD_COMPAT_EVENT_CTX_TYPES
+       LTTNG_EVENT_CONTEXT_PERF_COUNTER = 1, /* Backward compat. */
+       /// @endcond
+
+       /// Process name.
+       LTTNG_EVENT_CONTEXT_PROCNAME = 2,
+
+       /// Process priority.
+       LTTNG_EVENT_CONTEXT_PRIO = 3,
+
+       /// Nice value of the process.
+       LTTNG_EVENT_CONTEXT_NICE = 4,
+
+       /// Virtual process ID.
+       LTTNG_EVENT_CONTEXT_VPID = 5,
+
+       /// Thread ID.
+       LTTNG_EVENT_CONTEXT_TID = 6,
+
+       /// Virtual thread ID.
+       LTTNG_EVENT_CONTEXT_VTID = 7,
+
+       /// ID of the parent process.
+       LTTNG_EVENT_CONTEXT_PPID = 8,
+
+       /// Virtual ID of the parent process.
+       LTTNG_EVENT_CONTEXT_VPPID = 9,
+
+       /// POSIX thread ID.
+       LTTNG_EVENT_CONTEXT_PTHREAD_ID = 10,
+
+       /// Hostname.
+       LTTNG_EVENT_CONTEXT_HOSTNAME = 11,
+
+       /// Instruction pointer.
+       LTTNG_EVENT_CONTEXT_IP = 12,
+
+       /// Per-CPU perf counter.
+       LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER = 13,
+
+       /// Per-thread perf counter.
        LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER = 14,
-       LTTNG_EVENT_CONTEXT_APP_CONTEXT         = 15,
-       LTTNG_EVENT_CONTEXT_INTERRUPTIBLE       = 16,
-       LTTNG_EVENT_CONTEXT_PREEMPTIBLE         = 17,
-       LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE     = 18,
-       LTTNG_EVENT_CONTEXT_MIGRATABLE          = 19,
-       LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL    = 20,
-       LTTNG_EVENT_CONTEXT_CALLSTACK_USER      = 21, /* Supported on x86_32 and x86_64 only. */
-       LTTNG_EVENT_CONTEXT_CGROUP_NS           = 22,
-       LTTNG_EVENT_CONTEXT_IPC_NS              = 23,
-       LTTNG_EVENT_CONTEXT_MNT_NS              = 24,
-       LTTNG_EVENT_CONTEXT_NET_NS              = 25,
-       LTTNG_EVENT_CONTEXT_PID_NS              = 26,
-       LTTNG_EVENT_CONTEXT_USER_NS             = 27,
-       LTTNG_EVENT_CONTEXT_UTS_NS              = 28,
-       LTTNG_EVENT_CONTEXT_UID                 = 29,
-       LTTNG_EVENT_CONTEXT_EUID                = 30,
-       LTTNG_EVENT_CONTEXT_SUID                = 31,
-       LTTNG_EVENT_CONTEXT_GID                 = 32,
-       LTTNG_EVENT_CONTEXT_EGID                = 33,
-       LTTNG_EVENT_CONTEXT_SGID                = 34,
-       LTTNG_EVENT_CONTEXT_VUID                = 35,
-       LTTNG_EVENT_CONTEXT_VEUID               = 36,
-       LTTNG_EVENT_CONTEXT_VSUID               = 37,
-       LTTNG_EVENT_CONTEXT_VGID                = 38,
-       LTTNG_EVENT_CONTEXT_VEGID               = 39,
-       LTTNG_EVENT_CONTEXT_VSGID               = 40,
-       LTTNG_EVENT_CONTEXT_TIME_NS             = 41,
+
+       /// Application-specific context.
+       LTTNG_EVENT_CONTEXT_APP_CONTEXT = 15,
+
+       /// Whether or not the process is interruptible.
+       LTTNG_EVENT_CONTEXT_INTERRUPTIBLE = 16,
+
+       /// Whether or not the process is preemptible.
+       LTTNG_EVENT_CONTEXT_PREEMPTIBLE = 17,
+
+       /// Whether or not the process needs a reschedule.
+       LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE = 18,
+
+       /// Whether or not the process is migratable.
+       LTTNG_EVENT_CONTEXT_MIGRATABLE = 19,
+
+       /// Linux kernel call stack.
+       LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL = 20,
+
+       /// User space call stack.
+       LTTNG_EVENT_CONTEXT_CALLSTACK_USER = 21,
+
+       /// Control group root directory namespace ID.
+       LTTNG_EVENT_CONTEXT_CGROUP_NS = 22,
+
+       /// System&nbsp;V IPC and POSIX message queue namespace ID.
+       LTTNG_EVENT_CONTEXT_IPC_NS = 23,
+
+       /// Mount point namespace ID.
+       LTTNG_EVENT_CONTEXT_MNT_NS = 24,
+
+       /// Networking namespace ID.
+       LTTNG_EVENT_CONTEXT_NET_NS = 25,
+
+       /// Process ID namespace ID.
+       LTTNG_EVENT_CONTEXT_PID_NS = 26,
+
+       /// User and group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_USER_NS = 27,
+
+       /// Hostname and NIS domain name namespace ID.
+       LTTNG_EVENT_CONTEXT_UTS_NS = 28,
+
+       /// User ID namespace ID.
+       LTTNG_EVENT_CONTEXT_UID = 29,
+
+       /// Effective user ID namespace ID.
+       LTTNG_EVENT_CONTEXT_EUID = 30,
+
+       /// Set owner user ID namespace ID.
+       LTTNG_EVENT_CONTEXT_SUID = 31,
+
+       /// Group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_GID = 32,
+
+       /// Effective group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_EGID = 33,
+
+       /// Set owner group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_SGID = 34,
+
+       /// Virtual user ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VUID = 35,
+
+       /// Virtual effective user ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VEUID = 36,
+
+       /// Virtual set owner user ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VSUID = 37,
+
+       /// Virtual group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VGID = 38,
+
+       /// Virtual effective group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VEGID = 39,
+
+       /// Virtual set owner group ID namespace ID.
+       LTTNG_EVENT_CONTEXT_VSGID = 40,
+
+       /// Boot and monotonic clock namespace ID.
+       LTTNG_EVENT_CONTEXT_TIME_NS = 41,
 };
 
+/*!
+@brief
+    LTTng tracepoint field data type
+    (type of the lttng_event_field::type member).
+
+@ingroup api_inst_pt
+*/
 enum lttng_event_field_type {
-       LTTNG_EVENT_FIELD_OTHER               = 0,
-       LTTNG_EVENT_FIELD_INTEGER             = 1,
-       LTTNG_EVENT_FIELD_ENUM                = 2,
-       LTTNG_EVENT_FIELD_FLOAT               = 3,
-       LTTNG_EVENT_FIELD_STRING              = 4,
+       /// Other/unknown.
+       LTTNG_EVENT_FIELD_OTHER = 0,
+
+       /// Integer.
+       LTTNG_EVENT_FIELD_INTEGER = 1,
+
+       /// Enumeration.
+       LTTNG_EVENT_FIELD_ENUM = 2,
+
+       /// Floating point number.
+       LTTNG_EVENT_FIELD_FLOAT = 3,
+
+       /// String.
+       LTTNG_EVENT_FIELD_STRING = 4,
 };
 
+/*!
+@brief
+    \ref api-rer-inst-pt-descr "Instrumentation point descriptor"
+    flag (type of the lttng_event::flags member).
+
+@ingroup api_inst_pt
+*/
 enum lttng_event_flag {
-       LTTNG_EVENT_FLAG_SYSCALL_32           = (1U << 0),
-       LTTNG_EVENT_FLAG_SYSCALL_64           = (1U << 1),
+       /*!
+       @brief
+           32-bit Linux system call.
+
+       Only valid when the lttng_event::type member is
+       #LTTNG_EVENT_SYSCALL.
+       */
+       LTTNG_EVENT_FLAG_SYSCALL_32 = (1U << 0),
+
+       /*!
+       @brief
+           64-bit Linux system call.
+
+       Only valid when the lttng_event::type member is
+       #LTTNG_EVENT_SYSCALL.
+       */
+       LTTNG_EVENT_FLAG_SYSCALL_64 = (1U << 1),
 };
 
-/*
- * Perf counter attributes
- *
- * The structures should be initialized to zero before use.
- */
-#define LTTNG_PERF_EVENT_PADDING1          16
+#define LTTNG_PERF_EVENT_PADDING1 16
+
+/*!
+@brief
+    perf counter context field descriptor.
+
+@ingroup api_channel
+
+If the lttng_event_context::ctx member of an #lttng_event_context
+structure is #LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER or
+#LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER, then the
+lttng_event_context::lttng_event_context_u::perf_counter member
+of lttng_event_context::u selects a specific perf counter.
+
+You must initialize such a structure to zeros before setting its members
+and using it, for example:
+
+@code
+struct lttng_event_perf_counter_ctx perf_counter_ctx;
+
+memset(&perf_counter_ctx, 0, sizeof(perf_counter_ctx));
+@endcode
+*/
 struct lttng_event_perf_counter_ctx {
+       /*!
+       @brief
+           perf counter type ID.
+
+       One of:
+
+       <table>
+         <tr>
+           <th>Type
+           <th>ID
+         <tr>
+           <td>Hardware counter
+           <td>0
+         <tr>
+           <td>Software counter
+           <td>1
+         <tr>
+           <td>Hardware cache counter
+           <td>3
+         <tr>
+           <td>Performance Monitoring Unit (PMU) counter
+           <td>4
+       </table>
+       */
        uint32_t type;
+
+       /*!
+       @brief
+           perf counter configuration.
+
+       Depending on the lttng_event_perf_counter_ctx::type member:
+
+       <dl>
+         <dt>0 (hardware counter)
+         <dd>
+           One of:
+
+           <table>
+             <tr>
+               <th>Counter
+               <th>ID
+             <tr>
+               <td>CPU cycles
+               <td>0
+             <tr>
+               <td>Instructions
+               <td>1
+             <tr>
+               <td>Cache references
+               <td>2
+             <tr>
+               <td>Cache misses
+               <td>3
+             <tr>
+               <td>Branch instructions
+               <td>4
+             <tr>
+               <td>Branch misses
+               <td>5
+             <tr>
+               <td>Bus cycles
+               <td>6
+             <tr>
+               <td>Stalled cycles (front end)
+               <td>7
+             <tr>
+               <td>Stalled cycles (back end)
+               <td>8
+           </table>
+
+         <dt>1 (software counter)
+         <dd>
+           One of:
+
+           <table>
+             <tr>
+               <th>Counter
+               <th>ID
+             <tr>
+               <td>CPU clock
+               <td>0
+             <tr>
+               <td>Task clock
+               <td>1
+             <tr>
+               <td>Page faults
+               <td>2
+             <tr>
+               <td>Context switches
+               <td>3
+             <tr>
+               <td>CPU migrations
+               <td>4
+             <tr>
+               <td>Minor page faults
+               <td>5
+             <tr>
+               <td>Major page faults
+               <td>6
+             <tr>
+               <td>Alignment faults
+               <td>7
+             <tr>
+               <td>Emulation faults
+               <td>8
+           </table>
+
+         <dt>3 (hardware cache counter)
+         <dd>
+           The result of a bitwise OR operation between a cache ID,
+           an operation ID, and a result ID, as follows:
+
+           <table>
+             <tr>
+               <th>Cache ID
+               <th>Description
+             <tr>
+               <td>0
+               <td>Data L1
+             <tr>
+               <td>1
+               <td>Instructions L1
+             <tr>
+               <td>2
+               <td>LL
+             <tr>
+               <td>3
+               <td>Data <a
+       href="https://en.wikipedia.org/wiki/Translation_lookaside_buffer">TLB</a> <tr> <td>4
+               <td>Instruction TLB
+             <tr>
+               <td>5
+               <td>Branch prediction unit (BPU)
+           </table>
+
+           <table>
+             <tr>
+               <th>Operator ID
+               <th>Description
+             <tr>
+               <td>0
+               <td>Read
+             <tr>
+               <td>0x100
+               <td>Write
+             <tr>
+               <td>0x200
+               <td>Prefetch
+           </table>
+
+           <table>
+             <tr>
+               <th>Result ID
+               <th>Description
+             <tr>
+               <td>0
+               <td>Access
+             <tr>
+               <td>0x10000
+               <td>Miss
+           </table>
+
+         <dt>4 (PMU counter)
+         <dd>
+           PMU counter raw ID.
+
+           @sa \lt_man_gen{perf-record,1}
+       </dl>
+       */
        uint64_t config;
+
+       /// Context field name.
        char name[LTTNG_SYMBOL_NAME_LEN];
 
        char padding[LTTNG_PERF_EVENT_PADDING1];
 };
 
-/*
- * Event/channel context
- *
- * The structures should be initialized to zero before use.
- */
-#define LTTNG_EVENT_CONTEXT_PADDING1       16
-#define LTTNG_EVENT_CONTEXT_PADDING2       LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_EVENT_CONTEXT_PADDING1 16
+#define LTTNG_EVENT_CONTEXT_PADDING2 LTTNG_SYMBOL_NAME_LEN + 32
+
+/*!
+@brief
+    Context field descriptor.
+
+@ingroup api_channel
+
+Such a structure describes a context field to be recorded within all the
+\ref api_rer "event records" of a given \lt_obj_channel (see
+lttng_add_context()).
+
+You must initialize such a structure to zeros before setting its members
+and using it, for example:
+
+@code
+struct lttng_event_context ctx;
+
+memset(&ctx, 0, sizeof(ctx));
+@endcode
+*/
 struct lttng_event_context {
+       /*!
+       @brief
+           Context field type.
+
+       Some types have a \lt_obj_domain
+       constraint.
+
+       If this member has the value
+       #LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER or
+       #LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER, then you must also set
+       the lttng_event_context::lttng_event_context_u::perf_counter
+       member of lttng_event_context::u.
+
+       If this member has the value #LTTNG_EVENT_CONTEXT_APP_CONTEXT,
+       then you must also set the
+       lttng_event_context::lttng_event_context_u::app_ctx member
+       of lttng_event_context::u.
+       */
        enum lttng_event_context_type ctx;
+
        char padding[LTTNG_EVENT_CONTEXT_PADDING1];
 
-       union {
+       /*!
+       @brief
+           perf counter or application-specific context field
+           descriptor.
+
+       @ingroup api_channel
+       */
+       union lttng_event_context_u {
+               /*!
+               @brief
+                   perf counter context field descriptor.
+
+               Only used when the lttng_event_context::ctx member
+               is #LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER or
+               #LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER.
+               */
                struct lttng_event_perf_counter_ctx perf_counter;
+
                struct {
+                       /// Provider name.
                        char *provider_name;
+
+                       /// Field type.
                        char *ctx_name;
-               } app_ctx;
+               }
+
+               /*!
+               @brief
+                   Application-specific context field descriptor.
+
+               Only used when the lttng_event_context::ctx member
+               is #LTTNG_EVENT_CONTEXT_APP_CONTEXT.
+               */
+               app_ctx;
+
                char padding[LTTNG_EVENT_CONTEXT_PADDING2];
-       } u;
+       }
+
+       /// perf counter or application-specific context field descriptor.
+       u;
 };
 
-/*
- * Event probe.
- *
- * Either addr is used or symbol_name and offset.
- *
- * The structures should be initialized to zero before use.
- */
-#define LTTNG_EVENT_PROBE_PADDING1         16
+#define LTTNG_EVENT_PROBE_PADDING1 16
+
+/*!
+@brief
+    Legacy Linux kprobe/kretprobe location.
+
+@ingroup api_rer
+
+Such a structure indicates the location of a Linux kprobe/kretprobe for
+a \lt_obj_rer having such an instrumentation point type.
+
+You must initialize such a structure to zeros before setting its members
+and using it, for example:
+
+@code
+struct lttng_event_probe_attr loc;
+
+memset(&loc, 0, sizeof(loc));
+@endcode
+
+Set either lttng_event_probe_attr::addr or
+lttng_event_probe_attr::symbol_name and lttng_event_probe_attr::offset.
+
+@sa \ref api-rer-conds-inst-pt-type "Instrumentation point type condition".
+*/
 struct lttng_event_probe_attr {
+       /*!
+       @brief
+           kprobe/kretprobe address.
+
+       If this member is not 0, then
+       lttng_event_probe_attr::symbol_name must be an empty string.
+       */
        uint64_t addr;
 
+       /*!
+       @brief
+           kprobe/kretprobe address offset from the symbol named
+           lttng_event_probe_attr::symbol_name.
+       */
        uint64_t offset;
+
+       /*!
+       @brief
+           kprobe/kretprobe symbol name.
+
+       The actual kprobe/kretprobe address is the address of the named
+       symbol plus the value of lttng_event_probe_attr::offset.
+
+       If this member is not an empty string, then
+       lttng_event_probe_attr::addr must be 0.
+       */
        char symbol_name[LTTNG_SYMBOL_NAME_LEN];
 
        char padding[LTTNG_EVENT_PROBE_PADDING1];
@@ -229,7 +1142,7 @@ struct lttng_event_probe_attr {
  *
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_EVENT_FUNCTION_PADDING1      16
+#define LTTNG_EVENT_FUNCTION_PADDING1 16
 struct lttng_event_function_attr {
        char symbol_name[LTTNG_SYMBOL_NAME_LEN];
 
@@ -241,38 +1154,202 @@ struct lttng_event_function_attr {
  *
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_EVENT_PADDING1               12
-#define LTTNG_EVENT_PADDING2               LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_EVENT_PADDING1 12
+#define LTTNG_EVENT_PADDING2 LTTNG_SYMBOL_NAME_LEN + 32
+
+/*!
+@brief
+    \lt_obj_c_rer descriptor.
+
+@ingroup api_rer
+
+Such a structure describes a recording event rule. More specifically,
+it describes the \ref api-rer-conds "conditions" of a recording
+event rule.
+
+lttng_list_events() sets a pointer to an array of all the recording
+event rule descriptors of a given \lt_obj_channel.
+
+@note
+    \anchor api-rer-inst-pt-descr lttng_list_tracepoints()
+    and lttng_list_syscalls() also set
+    a pointer to an array of instances of this structure. In this
+    context, the #lttng_event structure is named
+    \"<em>instrumentation point descriptor</em>\".
+
+lttng_enable_event(), lttng_enable_event_with_filter(), and
+lttng_enable_event_with_exclusions() expect such a structure to create
+or enable a recording event rule.
+
+Most properties are members of the structure itself, but the
+following ones have their own dedicated accessors:
+
+<dl>
+  <dt>
+    Linux uprobe location (when the lttng_event::type member is
+    #LTTNG_EVENT_USERSPACE_PROBE)
+  <dd>
+    - lttng_event_get_userspace_probe_location()
+    - lttng_event_set_userspace_probe_location()
+
+  <dt>\ref api-rer-conds-event-name "Event name" exclusion patterns
+  <dd>
+    lttng_event_get_exclusion_name()
+
+  <dt>\ref api-rer-conds-filter "Event payload and context filter" expression
+  <dd>
+    lttng_event_get_filter_expression()
+</dl>
+
+Create an empty recording event rule descriptor with
+lttng_event_create().
+
+\anchor api-rer-valid-event-struct A \em valid #lttng_event structure
+satisfies the following constraints:
+
+- If the lttng_event::type member is #LTTNG_EVENT_PROBE or
+  #LTTNG_EVENT_FUNCTION, then the lttng_event::lttng_event_attr_u::probe
+  member of lttng_event::attr is valid according to the
+  documentation of #lttng_event_probe_attr.
+
+- If the lttng_event::type member is #LTTNG_EVENT_USERSPACE_PROBE, then
+  the recording event rule descriptor has a Linux uprobe location
+  (you called lttng_event_set_userspace_probe_location() on it to
+  set it).
+
+Destroy a recording event rule descriptor with lttng_event_destroy().
+*/
 struct lttng_event {
        /* Offset 0 */
+       /// \ref api-rer-conds-inst-pt-type "Instrumentation point type condition".
        enum lttng_event_type type;
 
        /* Offset 4 */
+       /*!
+           @brief \ref api-rer-conds-event-name "Event name" pattern
+           condition.
+
+       If empty, lttng_enable_event(),
+       lttng_enable_event_with_filter(), and
+       lttng_enable_event_with_exclusions() use <code>*</code> (match
+       events with any name).
+
+       If the lttng_event::type member is #LTTNG_EVENT_PROBE,
+       #LTTNG_EVENT_FUNCTION, or #LTTNG_EVENT_USERSPACE_PROBE, then
+       this member is actually the name of the created Linux
+       kprobe/kretprobe/uprobe instrumentation point (future event
+       name).
+
+       If this structure is an
+       \ref api-rer-inst-pt-descr "instrumentation point descriptor",
+       then this member is the name of the LTTng tracepoint, Linux
+       system call, or Java/Python logger.
+       */
        char name[LTTNG_SYMBOL_NAME_LEN];
 
        /* Offset 260 */
+       /*!
+       @brief
+           Operand of the
+           \ref api-rer-conds-ll "instrumentation point log level condition".
+       */
        enum lttng_loglevel_type loglevel_type;
 
        /* Offset 264 */
+       /*!
+           @brief Value of the
+           \ref api-rer-conds-ll "instrumentation point log level condition".
+
+       This member must be one of the enumerators of
+       #lttng_loglevel, #lttng_loglevel_jul, #lttng_loglevel_log4j, or
+       #lttng_loglevel_python, depending on the
+       \lt_obj_domain when you call lttng_enable_event(),
+       lttng_enable_event_with_filter(), or
+       lttng_enable_event_with_exclusions().
+
+       If this structure is an
+       \ref api-rer-inst-pt-descr "instrumentation point descriptor",
+       then this member is the log level of the LTTng tracepoint or
+       Java/Python logger.
+       */
        int loglevel;
 
        /* Offset 268 */
-       int32_t enabled;        /* Does not apply: -1 */
+       /*!
+       @brief
+           1 if this recording event rule is enabled, or 0 otherwise.
+
+       This is a read-only member.
+
+       @sa lttng_enable_event() --
+           Creates or enables a recording event rule.
+       @sa lttng_disable_event_ext() --
+           Disables a recording event rule.
+       */
+       int32_t enabled; /* Does not apply: -1 */
 
        /* Offset 272 */
+       /*!
+       @brief
+           ID of the process which offers the instrumentation point
+           described by this structure.
+
+       This is a read-only member.
+
+       This member is \em not part of a recording event rule.
+       */
        pid_t pid;
 
        /* Offset 276 */
-       unsigned char filter;   /* filter enabled ? */
+       /*!
+       @brief
+           1 if the recording event rule described by this has an
+           \ref api-rer-conds-filter "event payload and context filter"
+           expression, or 0 otherwise.
+
+       This is a read-only member: use the \lt_p{filter_expr} parameter
+       of lttng_enable_event_with_filter() or
+       lttng_enable_event_with_exclusions() when you create a
+       recording event rule to set an event payload and context
+       filter expression.
+
+       If this member is 1, then get the actual filter expression
+       string with lttng_event_get_filter_expression().
+       */
+       unsigned char filter;
 
        /* Offset 277 */
-       unsigned char exclusion; /* exclusions added ? */
+       /*!
+       @brief
+           1 if the recording event rule described by this has
+           \ref api-rer-conds-event-name "event name" exclusion
+           patterns (part of the event name condition), or 0 otherwise.
+
+       This is a read-only member: use the
+       \lt_p{event_name_exclusion_count} and
+       \lt_p{event_name_exclusions} parameters of
+       lttng_enable_event_with_exclusions() when you create a recording
+       event rule to set event name exclusion patterns.
+
+       If this member is 1, then get the actual event name exclusion
+       patterns with lttng_event_get_exclusion_name_count() and
+       lttng_event_get_exclusion_name().
+       */
+       unsigned char exclusion;
 
        /* Offset 278 */
        char padding2[2];
 
        /* Offset 280 */
-       /* Event flag, from 2.6 and above. */
+       /*!
+       @brief
+           \ref api-rer-inst-pt-descr "Instrumentation point descriptor"
+           flags (bitwise OR).
+
+       This is a read-only member.
+
+       This member is \em not part of a recording event rule.
+       */
        enum lttng_event_flag flags;
 
        /* Offset 284 */
@@ -285,241 +1362,989 @@ struct lttng_event {
        } extended;
 
        /* Offset 296 */
-       /* Per event type configuration */
-       union {
+       /*!
+       @brief
+           Linux kprobe/kretprobe recording event rule configuration.
+
+       @ingroup api_rer
+       */
+       union lttng_event_attr_u {
+               /*!
+               @brief
+                   Linux kprobe/kretprobe location.
+
+               Only valid when the lttng_event::type member is
+               #LTTNG_EVENT_PROBE or #LTTNG_EVENT_FUNCTION.
+               */
                struct lttng_event_probe_attr probe;
+
                struct lttng_event_function_attr ftrace;
 
                char padding[LTTNG_EVENT_PADDING2];
-       } attr;
+       }
+
+       /*!
+       @brief
+           Linux kprobe/kretprobe recording event rule configuration.
+
+       Only valid when the lttng_event::type member is
+       #LTTNG_EVENT_PROBE or #LTTNG_EVENT_FUNCTION.
+       */
+       attr;
 };
 
-#define LTTNG_EVENT_FIELD_PADDING      LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_EVENT_FIELD_PADDING LTTNG_SYMBOL_NAME_LEN + 32
+
+/*!
+@brief
+    LTTng tracepoint field description.
+
+@ingroup api_inst_pt
+
+lttng_list_tracepoint_fields() sets a pointer to an array of all the
+tracepoint field descriptions of a given \lt_obj_domain.
+*/
 struct lttng_event_field {
+       /// Field name.
        char field_name[LTTNG_SYMBOL_NAME_LEN];
+
+       /// Field data type.
        enum lttng_event_field_type type;
+
        char padding[LTTNG_EVENT_FIELD_PADDING];
+
+       /*!
+       @brief
+           \ref api-rer-inst-pt-descr "Descriptor" of the tracepoint
+           which contains this field.
+       */
        struct lttng_event event;
+
+       /*!
+       @brief
+           0 if LTTng writes this field to an event record, or 1
+           otherwise.
+       */
        int nowrite;
 };
 
-/*
- * List the event(s) of a session channel.
- *
- * Both handle and channel_name CAN NOT be NULL.
- *
- * Return the size (number of entries) of the "lttng_event" array. Caller must
- * free events. On error a negative LTTng error code is returned.
- */
+/*!
+@brief
+    Sets \lt_p{*event_rules} to the descriptors of the
+    \lt_obj_rers of the \lt_obj_channel named \lt_p{channel_name}
+    within the recording session handle \lt_p{handle}.
+
+@ingroup api_channel
+
+@param[in] handle
+    Recording session handle which contains the name of the
+    recording session and the summary
+    of the \lt_obj_domain which own the channel (named
+    \lt_p{channel_name}) of which to get the recording event rule
+    descriptors.
+@param[in] channel_name
+    Name of the channel, within \lt_p{handle}, of which to get all the
+    recording event rule descriptors.
+@param[out] event_rules
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*event_rules}
+    to the recording event rule descriptors.
+
+    Free \lt_p{*event_rules} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*event_rules} on success, or a
+    \em negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{channel_name}
+@pre
+    \lt_p{channel_name} names an existing channel within the recording
+    session and tracing domain of \lt_p{handle}.
+@lt_pre_not_null{event_rules}
+*/
 LTTNG_EXPORT extern int lttng_list_events(struct lttng_handle *handle,
-               const char *channel_name, struct lttng_event **events);
+                                         const char *channel_name,
+                                         struct lttng_event **event_rules);
 
-/*
- * Create an lttng_event.
- *
- * This creation function, introduced in LTTng 2.11, works around
- * the fact that the layout of the 'lttng_event' is publicly exposed.
- *
- * It allocates a larger object which exposes the same public fields
- * as a 'struct lttng_event', but also allows the use of the following extended
- * attribute setters:
- *   - lttng_event_set_userspace_probe_location();
- *
- * Events created through this function must be destroyed using
- * lttng_event_destroy().
- *
- * Returns a zeroed lttng_event on success, NULL on error.
- */
+/*!
+@brief
+    Creates and returns an empty recording event rule descriptor.
+
+@ingroup api_rer
+
+After you create a recording event rule descriptor with this function,
+you can modify its properties and call
+lttng_enable_event_with_exclusions() to create and enable a recording
+event rule.
+
+@returns
+    @parblock
+    New recording event rule descriptor.
+
+    Destroy the returned recording event rule descriptor with
+    lttng_event_destroy().
+    @endparblock
+
+@sa lttng_event_destroy() --
+    Destroys a recording event rule descriptor.
+*/
 LTTNG_EXPORT extern struct lttng_event *lttng_event_create(void);
 
-/*
- * Destroy an lttng_event.
- *
- * This destruction function, introduced in LTTng 2.11, should only
- * be used with events created by lttng_event_create().
-  */
-LTTNG_EXPORT extern void lttng_event_destroy(struct lttng_event *event);
+/*!
+@brief
+    Destroys the recording event rule descriptor \lt_p{event_rule}.
 
-/*
- * Get the filter expression of a specific LTTng event.
- *
- * If the call is successful, then the filter expression's address is put
- * in *filter_expression. If the event has no filter expression,
- * *filter_expression is set to NULL. The caller does NOT own
- * *filter_expression.
- *
- * Returns 0 on success, or a negative LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_event_get_filter_expression(struct lttng_event *event,
-               const char **filter_string);
+@ingroup api_rer
 
-/*
- * Get the number of exclusion names of a specific LTTng event.
- *
- * Returns the number of exclusion names on success, or a negative
- * LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_event_get_exclusion_name_count(struct lttng_event *event);
+@note
+    This function doesn't destroy the recording event rule
+    which \lt_p{event_rule} describes: you can't destroy a
+    recording event rule.
 
-/*
- * Get an LTTng event's exclusion name at a given index.
- *
- * If the call is successful, then the exclusion name string's address
- * is put in *exclusion_name. The caller does NOT own *exclusion_name.
- *
- * Returns 0 on success, or a negative LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_event_get_exclusion_name(struct lttng_event *event,
-               size_t index, const char **exclusion_name);
+@param[in] event_rule
+    @parblock
+    Recording event rule descriptor to destroy.
 
-/*
- * Get the userspace probe location of a specific LTTng event.
- * If the call is successful, then a pointer to the probe location is returned.
- * If the event has no probe location a NULL pointer is returned. The caller
- * does not own the returned probe location.
- */
+    May be \c NULL.
+    @endparblock
+
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{event_rule} was created with
+    lttng_event_create().
+
+@sa lttng_event_create() --
+    Creates an empty recording event rule descriptor.
+*/
+LTTNG_EXPORT extern void lttng_event_destroy(struct lttng_event *event_rule);
+
+/*!
+@brief
+    Sets \lt_p{*filter_expr} to the
+    \ref api-rer-conds-filter "event payload and context filter"
+    expression of the recording event rule described by
+    \lt_p{event_rule}.
+
+@ingroup api_rer
+
+@param[in] event_rule
+    Descriptor of the recording event rule of which to get the event
+    payload and context filter expression.
+@param[out] filter_expr
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*filter_expr}
+    to:
+
+    <dl>
+      <dt>
+       If \lt_p{event_rule} has an event payload and context filter
+       expression
+      <dd>
+       The event payload and context filter
+       expression of \lt_p{event_rule}.
+
+       \lt_p{*filter_expr} remains valid as long as \lt_p{event_rule}
+       exists and you don't modify it.
+
+      <dt>Otherwise
+      <dd>\c NULL
+    </dl>
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{event_rule}
+@lt_pre_not_null{filter_expr}
+
+@sa lttng_event::filter --
+    Indicates whether or not a recording event rule has an event payload
+    and context filter.
+*/
+LTTNG_EXPORT extern int lttng_event_get_filter_expression(struct lttng_event *event_rule,
+                                                         const char **filter_expr);
+
+/*!
+@brief
+    Returns the number of \ref api-rer-conds-event-name "event name"
+    exclusion patterns of the recording
+    event rule described by \lt_p{event_rule}.
+
+@ingroup api_rer
+
+@param[in] event_rule
+    Descriptor of the recording event rule of which to get the number
+    of event name exclusion patterns.
+
+@returns
+    Number of event name exclusion patterns of \lt_p{event_rule}, or a
+    \em negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_not_null{event_rule}
+
+@sa lttng_event_get_exclusion_name() --
+    Returns an event name exclusion pattern by index of a recording
+    event rule.
+@sa lttng_event::exclusion --
+    Indicates whether or not a recording event rule has event name
+    exclusion patterns.
+*/
+LTTNG_EXPORT extern int lttng_event_get_exclusion_name_count(struct lttng_event *event_rule);
+
+/*!
+@brief
+    Sets \lt_p{*event_name_exclusion} to the
+    \ref api-rer-conds-event-name "event name" exclusion
+    pattern at index \lt_p{index} of the recording event rule described
+    by \lt_p{event_rule}.
+
+@ingroup api_rer
+
+@param[in] event_rule
+    Descriptor of the recording event rule of which to get the event
+    name exclusion pattern at index \lt_p{index}.
+@param[in] index
+    Index of the event name exclusion pattern to get from
+    \lt_p{event_rule}.
+@param[out] event_name_exclusion
+    @parblock
+    <strong>On success</strong>, this function sets
+    \lt_p{*event_name_exclusion} to the event name exclusion pattern at
+    index \lt_p{index} of
+    \lt_p{event_rule}.
+
+    \lt_p{*event_name_exclusion} remains valis as long as
+    \lt_p{event_rule} exists and you don't modify it.
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{event_rule}
+@pre
+    \lt_p{index} is less than the number of event name exclusion
+    patterns (as returned by lttng_event_get_exclusion_name_count())
+    of \lt_p{event_rule}.
+@lt_pre_not_null{event_name_exclusion}
+
+@sa lttng_event_get_exclusion_name_count() --
+    Returns the number of event name exclusion patterns of a recording
+    event rule.
+*/
+LTTNG_EXPORT extern int lttng_event_get_exclusion_name(struct lttng_event *event_rule,
+                                                      size_t index,
+                                                      const char **event_name_exclusion);
+
+/*!
+@brief
+    Returns the Linux uprobe location of the recording event rule
+    described by \lt_p{event_rule}.
+
+@ingroup api_rer
+
+@param[in] event_rule
+    Descriptor of the recording event rule of which to get the
+    Linux uprobe location.
+
+@returns
+    @parblock
+    Linux uprobe location of the recording event rule described by
+    \lt_p{event_rule}, or \c NULL if none.
+
+    The returned location remains valid as long as \lt_p{event_rule}
+    exists and you don't modify it.
+    @endparblock
+
+@lt_pre_not_null{event_rule}
+@pre
+    \lt_p{event_rule->type} (see lttng_event::type) is
+    #LTTNG_EVENT_USERSPACE_PROBE.
+
+@sa lttng_event_set_userspace_probe_location() --
+    Sets the Linux uprobe location of a recording event rule.
+@sa \ref api-rer-conds-inst-pt-type "Instrumentation point type condition".
+*/
 LTTNG_EXPORT extern const struct lttng_userspace_probe_location *
-lttng_event_get_userspace_probe_location(const struct lttng_event *event);
+lttng_event_get_userspace_probe_location(const struct lttng_event *event_rule);
 
-/*
- * Set an LTTng event's userspace probe location.
- *
- * If the call is successful, then the probe location is set to the event. The
- * ownership of the probe_location is given to the event.
- *
- * Note that the event must have been created using 'lttng_event_create()' in
- * order for this call to succeed.
- *
- * Returns 0 on success, or a negative LTTng error code on error.
- */
-LTTNG_EXPORT extern int lttng_event_set_userspace_probe_location(struct lttng_event *event,
-               struct lttng_userspace_probe_location *probe_location);
+/*!
+@brief
+    Sets the Linux uprobe location of the recording event rule described
+    by \lt_p{event_rule} to \lt_p{location}.
 
-/*
- * List the available tracepoints of a specific lttng domain.
- *
- * The handle CAN NOT be NULL.
- *
- * Return the size (number of entries) of the "lttng_event" array.  Caller must
- * free events. On error a negative LTTng error code is returned.
- */
+@ingroup api_rer
+
+@param[in] event_rule
+    Descriptor of the recording event rule of which to set the
+    Linux uprobe location to \lt_p{location}.
+@param[in] location
+    New Linux uprobe location of \lt_p{event_rule}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{event_rule}
+@pre
+    \lt_p{event_rule} was created with lttng_event_create().
+@pre
+    \lt_p{event_rule->type} (see lttng_event::type) is
+    #LTTNG_EVENT_USERSPACE_PROBE.
+@lt_pre_not_null{location}
+
+@post
+    <strong>On success</strong>, \lt_p{*location} is invalid
+    (its ownership is transfered to \lt_p{event_rule}).
+
+@sa lttng_event_get_userspace_probe_location() --
+    Returns the Linux uprobe location of a recording event rule.
+@sa \ref api-rer-conds-inst-pt-type "Instrumentation point type condition".
+*/
+LTTNG_EXPORT extern int
+lttng_event_set_userspace_probe_location(struct lttng_event *event_rule,
+                                        struct lttng_userspace_probe_location *location);
+
+/*!
+@brief
+    Sets \lt_p{*descrs} to the
+    \ref api-rer-inst-pt-descr "descriptors" of the
+    available LTTng tracepoints or Java/Python loggers for the
+    \lt_obj_domain of \lt_p{handle}.
+
+@ingroup api_inst_pt
+
+@param[in] handle
+    @parblock
+    Recording session handle which contains the summary of the
+    \lt_obj_domain which offers the LTTng tracepoints or Java/Python
+    loggers of which to get the descriptors.
+
+    This function ignores \lt_p{handle->session_name}.
+    @endparblock
+@param[out] descrs
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*descrs}
+    to the descriptors of the available tracepoints or Java/Python
+    loggers of \lt_p{handle}.
+
+    Free \lt_p{*descrs} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*descrs} on success, or a \em
+    negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{descrs}
+
+@sa lttng_list_tracepoint_fields() --
+    Returns all the field descriptions of all the available LTTng
+    tracepoints.
+@sa lttng_list_syscalls() --
+    Returns the descriptors of all the available Linux system calls.
+*/
 LTTNG_EXPORT extern int lttng_list_tracepoints(struct lttng_handle *handle,
-               struct lttng_event **events);
+                                              struct lttng_event **descrs);
 
-/*
- * List the available tracepoints fields of a specific lttng domain.
- *
- * The handle CAN NOT be NULL.
- *
- * Return the size (number of entries) of the "lttng_event_field" array.
- * Caller must free fields. On error a negative LTTng error code is
- * returned.
- */
+/*!
+@brief
+    Sets \lt_p{*fields} to the field descriptions of all the available
+    LTTng tracepoints for the \lt_obj_domain of \lt_p{handle}.
+
+@ingroup api_inst_pt
+
+@param[in] handle
+    @parblock
+    Recording session handle which contains the summary of the
+    \lt_obj_domain which offers the LTTng tracepoints of which to get
+    the field descriptions.
+
+    This function ignores \lt_p{handle->session_name}.
+    @endparblock
+@param[out] fields
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*fields}
+    to the descriptions of the available LTTng tracepoint fields of
+    \lt_p{handle}.
+
+    Each #lttng_event_field instance in \lt_p{*fields} contains a
+    pointer to the \ref api-rer-inst-pt-descr "descriptor" of
+    a tracepoint which contains the described field
+    (lttng_event_field::event member).
+
+    Free \lt_p{*fields} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*fields} on success, or a \em
+    negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{fields}
+
+@sa lttng_list_tracepoints() --
+    Returns the descriptors of all the available LTTng tracepoints
+    or Java/Python loggers.
+@sa lttng_list_syscalls() --
+    Returns the descriptors of all the available Linux system calls.
+*/
 LTTNG_EXPORT extern int lttng_list_tracepoint_fields(struct lttng_handle *handle,
-               struct lttng_event_field **fields);
+                                                    struct lttng_event_field **fields);
 
-/*
- * List the available kernel syscall.
- *
- * Return the size (number of entries) of the allocated "lttng_event" array.
- * All events in will be of type syscall. Caller must free events. On error a
- * negative LTTng error code is returned.
- */
-LTTNG_EXPORT extern int lttng_list_syscalls(struct lttng_event **events);
+/*!
+@brief
+    Sets \lt_p{*descrs} to the
+    \ref api-rer-inst-pt-descr "descriptors" of the
+    available Linux system calls for the
+    #LTTNG_DOMAIN_KERNEL tracing domain.
 
-/*
- * Add context to event(s) for a specific channel (or for all).
- *
- * If the channel_name is NULL and they are no channel for the domain, the
- * default channel is created (channel0). The context is then added on ALL
- * channels since no name was specified.
- *
- * The event_name is ignored since adding a context to an event is not possible
- * for now.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+@ingroup api_inst_pt
+
+@param[out] descrs
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*descrs}
+    to the available system calls.
+
+    The #lttng_event instances of \lt_p{*descrs} have an
+    lttng_event::flags member which indicates whether the described
+    system call is 32-bit, 64-bit, or both.
+
+    Free \lt_p{*descrs} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*descrs} on success, or a \em
+    negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{descrs}
+
+@sa lttng_list_tracepoint_fields() --
+    Returns all the field descriptions of all the available LTTng
+    tracepoints.
+@sa lttng_list_syscalls() --
+    Returns the descriptors of all the available Linux system calls.
+*/
+LTTNG_EXPORT extern int lttng_list_syscalls(struct lttng_event **descrs);
+
+/*!
+@brief
+    Makes the future \ref api_rer "event records" of the
+    \lt_obj_channel named \lt_p{channel_name} (or of a default channel
+    or all the channels if \c NULL) within the
+    \lt_obj_session and \lt_obj_domain of \lt_p{handle}
+    have a context field described by \lt_p{context_field_descriptor}.
+
+@ingroup api_channel
+
+Context values (for example, the ID of the current process, the
+instruction pointer, or the hostname) are always available during
+tracing. This function makes LTTng record a specific context value as a
+field for each future event record of the selected channel(s).
+
+@param[in] handle
+    Recording session handle which contains the name of the recording
+    session and the summary of the \lt_obj_domain which own the
+    channel(s) to select.
+@param[in] context_field_descriptor
+    Descriptor of the context field to add to each event record of
+    the selected channel(s).
+@param[in] event_name
+    Unused: must be \c NULL.
+@param[in] channel_name
+    @parblock
+    Name of the channel to select.
+
+    If \c NULL, then:
+
+    <dl>
+      <dt>
+       If the recording session and tracing domain of
+       \lt_p{handle} have no channels
+      <dd>
+       LTTng creates a new, default channel named \c channel0 within
+       \lt_p{handle} which becomes the selected channel.
+
+      <dt>Otherwise
+      <dd>
+       LTTng selects all the channels of \lt_p{handle}.
+    </dl>
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@lt_pre_sess_never_active{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid (you passed a
+    \lt_obj_domain summary to
+    lttng_create_handle() when you created \lt_p{handle}).
+@pre
+    \lt_p{context_field_descriptor} is valid according to the
+    documentation of #lttng_event_context.
+@pre
+    \lt_p{event_name} is \c NULL.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{channel_name} names an
+    existing channel within the recording session and tracing domain of
+    \lt_p{handle}.
+*/
 LTTNG_EXPORT extern int lttng_add_context(struct lttng_handle *handle,
-               struct lttng_event_context *ctx, const char *event_name,
-               const char *channel_name);
+                                         struct lttng_event_context *context_field_descriptor,
+                                         const char *event_name,
+                                         const char *channel_name);
 
-/*
- * Create or enable an event (or events) for a channel.
- *
- * If the event you are trying to enable does not exist, it will be created,
- * else it is enabled. If channel_name is NULL, the default channel is used
- * (channel0).
- *
- * The handle and ev params can not be NULL.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Alias of lttng_enable_event_with_exclusions() which passes the
+    \ref api-rer-conds-filter "event payload and context filter"
+    expression of \lt_p{event_rule}
+    as the \lt_p{filter_expr} parameter and the
+    \ref api-rer-conds-event-name "event name" exclusion patterns
+    of \lt_p{event_rule} as the
+    \lt_p{event_name_exclusion_count} and
+    \lt_p{event_name_exclusions} parameters.
+
+@ingroup api_rer
+
+This function is equivalent to:
+
+@code
+int ret;
+int i;
+char **event_name_exclusions = NULL;
+const char *filter_expr = NULL;
+const int event_name_exclusion_count = lttng_event_get_exclusion_name_count(event_rule);
+
+assert(event_name_exclusion_count >= 0);
+
+if (event_name_exclusion_count > 0) {
+    event_name_exclusions = calloc(event_name_exclusion_count,
+                                  sizeof(*event_name_exclusions));
+    assert(event_name_exclusions);
+
+    for (i = 0; i < event_name_exclusion_count; i++) {
+       const char *event_name_exclusion;
+
+       ret = lttng_event_get_exclusion_name(event_rule, (size_t) i,
+                                            &event_name_exclusion);
+       assert(ret == 0);
+       event_name_exclusions[i] = (char *) event_name_exclusion;
+    }
+}
+
+ret = lttng_event_get_filter_expression(event_rule, &filter_expr);
+assert(ret == 0);
+ret = lttng_enable_event_with_exclusions(handle, event_rule, channel_name,
+                                        filter_expr,
+                                        event_name_exclusion_count,
+                                        event_name_exclusions);
+free(event_name_exclusions);
+return ret;
+@endcode
+*/
 LTTNG_EXPORT extern int lttng_enable_event(struct lttng_handle *handle,
-               struct lttng_event *ev, const char *channel_name);
+                                          struct lttng_event *event_rule,
+                                          const char *channel_name);
 
-/*
- * Create or enable an event with a specific filter.
- *
- * If the event you are trying to enable does not exist, it will be created,
- * else it is enabled.
- * If ev is NULL, all events are enabled with that filter.
- * If channel_name is NULL, the default channel is used (channel0) and created
- * if not found.
- * If filter_expression is NULL, an event without associated filter is
- * created.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Alias of lttng_enable_event_with_exclusions() which passes the
+    the \ref api-rer-conds-event-name "event name" exclusion patterns
+    of \lt_p{event_rule} as the
+    \lt_p{event_name_exclusion_count} and
+    \lt_p{event_name_exclusions} parameters.
+
+@ingroup api_rer
+
+This function is equivalent to:
+
+@code
+int ret;
+int i;
+char **event_name_exclusions = NULL;
+const char *filter_expr = NULL;
+const int event_name_exclusion_count = lttng_event_get_exclusion_name_count(event_rule);
+
+assert(event_name_exclusion_count >= 0);
+
+if (event_name_exclusion_count > 0) {
+    event_name_exclusions = calloc(event_name_exclusion_count,
+                                  sizeof(*event_name_exclusions));
+    assert(event_name_exclusions);
+
+    for (i = 0; i < event_name_exclusion_count; i++) {
+       const char *event_name_exclusion;
+
+       ret = lttng_event_get_exclusion_name(event_rule, (size_t) i,
+                                            &event_name_exclusion);
+       assert(ret == 0);
+       event_name_exclusions[i] = (char *) event_name_exclusion;
+    }
+}
+
+ret = lttng_enable_event_with_exclusions(handle, event_rule, channel_name,
+                                        filter_expr,
+                                        event_name_exclusion_count,
+                                        event_name_exclusions);
+free(event_name_exclusions);
+return ret;
+@endcode
+*/
 LTTNG_EXPORT extern int lttng_enable_event_with_filter(struct lttng_handle *handle,
-               struct lttng_event *event, const char *channel_name,
-               const char *filter_expression);
+                                                      struct lttng_event *event_rule,
+                                                      const char *channel_name,
+                                                      const char *filter_expr);
 
-/*
- * Create or enable an event with a filter and/or exclusions.
- *
- * If the event you are trying to enable does not exist, it will be created,
- * else it is enabled.
- * If ev is NULL, all events are enabled with the filter and exclusion options.
- * If channel_name is NULL, the default channel is used (channel0) and created
- * if not found.
- * If filter_expression is NULL, an event without associated filter is
- * created.
- * If exclusion count is zero, the event will be created without exclusions.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Creates or enables a recording event rule
+    described by \lt_p{event_rule}, having the
+    \ref api-rer-conds-filter "event payload and context filter"
+    expression \lt_p{filter_expr} and the
+    \ref api-rer-conds-event-name "event name" exclusion patterns
+    \lt_p{event_name_exclusions}, within
+    the \lt_obj_channel named \lt_p{channel_name}
+    (or within a default channel if \c NULL) within the recording
+    session handle \lt_p{handle}.
+
+@ingroup api_rer
+
+This function, depending on the
+\ref api-rer-conds-inst-pt-type "instrumentation point type",
+\ref api-rer-conds-event-name "event name",
+and \ref api-rer-conds-ll "log level" conditions of \lt_p{event_rule},
+as well as on \lt_p{filter_expr} and \lt_p{event_name_exclusions}:
+
+<dl>
+  <dt>
+    The conditions and parameters describe an existing recording event
+    rule within the selected channel
+  <dd>
+    Enables the existing recording event rule.
+
+  <dt>Otherwise
+  <dd>
+    Creates and enables a new recording event rule within the
+    selected channel.
+</dl>
+
+If \lt_p{event_rule->type} is #LTTNG_EVENT_ALL and
+\lt_p{handle->domain.type} is #LTTNG_DOMAIN_KERNEL, then this
+function actually creates or enables two recording event rules: one with
+the #LTTNG_EVENT_TRACEPOINT type, and one with the #LTTNG_EVENT_SYSCALL
+type.
+
+@param[in] handle
+    Recording session handle which contains the name of the recording
+    session and the summary of the \lt_obj_domain which own the selected
+    channel.
+@param[in] event_rule
+    @parblock
+    Descriptor of the recording event rule to create or enable.
+
+    This function:
+
+    - Ignores any event payload and context filter
+      expression within \lt_p{event_rule}: it always uses
+      \lt_p{filter_expr}.
+
+    - Ignores any event name exclusion patterns within
+      \lt_p{event_rule}: it always uses \lt_p{event_name_exclusions}.
+    @endparblock
+@param[in] channel_name
+    @parblock
+    Name of the channel, within \lt_p{handle}, to select (that is,
+    containing the recording event rule to create or enable).
+
+    If \c NULL, then this function uses \c channel0. If no channel named
+    \c channel0 within \lt_p{handle} exists, then LTTng creates a new,
+    default channel named as such and selects it before it creates the
+    recording event rule described by \lt_p{event_rule}.
+    @endparblock
+@param[in] filter_expr
+    @parblock
+    Event payload and context filter expression of the recording
+    event rule to create or enable.
+
+    <strong>If \c NULL</strong>, the created or enabled recording event
+    rule has no event payload and context filter expression.
+
+    This parameter, even when \c NULL, overrides any existing
+    event payload and context filter expression within
+    \lt_p{event_rule}.
+    @endparblock
+@param[in] event_name_exclusion_count
+    Number of items in \lt_p{event_name_exclusions}.
+@param[in] event_name_exclusions
+    @parblock
+    Event name exclusion patterns of the recording event rule to create
+    or enable.
+
+    This function copies the strings of this array.
+
+    \lt_p{event_name_exclusion_count} indicates the size of this
+    array, which may be \c NULL if \lt_p{event_name_exclusion_count}
+    is&nbsp;0.
+
+    This parameter, even when \c NULL or empty, overrides any existing
+    event name exclusion patterns within \lt_p{event_rule}.
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{event_rule}
+@pre
+    \lt_p{event_rule} is \ref api-rer-valid-event-struct "valid".
+@pre
+    <strong>If \lt_p{handle->domain.type} is \em not
+    #LTTNG_DOMAIN_KERNEL</strong>, then \lt_p{event_rule->type} is
+    #LTTNG_EVENT_TRACEPOINT.
+@pre
+    <strong>If \lt_p{handle->domain.type} is \em not
+    #LTTNG_DOMAIN_UST</strong>, then \lt_p{event_name_exclusion_count}
+    is&nbsp;0.
+@pre
+    <strong>If this function must enable an existing recording event
+    rule</strong>, then the recording event rule to enable is disabled.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{channel_name} names an
+    existing channel within the recording session and tracing domain of
+    \lt_p{handle}.
+@pre
+    <strong>If \lt_p{channel_name} is \c NULL</strong>, then
+    \lt_p{handle} contains either no channels or a default channel named
+    \c channel0.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{filter_expr} is a valid
+    event payload and context filter expression.
+@pre
+    \lt_p{event_name_exclusion_count}&nbsp;≥&nbsp;0.
+
+@sa lttng_enable_event() --
+    Alias which calls this function with the event payload and context
+    filter expression and event name exclusion patterns of the
+    recording event rule descriptor.
+@sa lttng_enable_event_with_filter() --
+    Alias which calls this function with the event name exclusion
+    patterns of the recording event rule descriptor.
+@sa lttng_disable_event_ext() --
+    Disables a recording event rule.
+*/
 LTTNG_EXPORT extern int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
-               struct lttng_event *event, const char *channel_name,
-               const char *filter_expression,
-               int exclusion_count, char **exclusion_names);
+                                                          struct lttng_event *event_rule,
+                                                          const char *channel_name,
+                                                          const char *filter_expr,
+                                                          int event_name_exclusion_count,
+                                                          char **event_name_exclusions);
 
-/*
- * Disable event(s) of a channel and domain.
- *
- * If name is NULL, all events are disabled.
- * If channel_name is NULL, the default channel is used (channel0).
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_disable_event(struct lttng_handle *handle,
-               const char *name, const char *channel_name);
+/*!
+@brief
+    Alias of lttng_disable_event_ext() which creates a temporary
+    recording event rule descriptor, settings its
+    lttng_event::name member to \lt_p{event_name} if not \c NULL and
+    its lttng_event::type member to #LTTNG_EVENT_ALL.
 
-/*
- * Disable event(s) of a channel and domain.
- *
- * Takes a struct lttng_event as parameter.
- * If channel_name is NULL, the default channel is used (channel0).
- *
- * Currently, @filter_expression must be NULL. (disabling specific
- * filter expressions not implemented)
- * Currently, only LTTNG_EVENT_ALL and LTTNG_EVENT_SYSCALL event types
- * are implemented for field @ev.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+@ingroup api_rer
+
+This function is equivalent to:
+
+@code
+struct lttng_event event_rule = { 0 };
+
+event_rule.type = LTTNG_EVENT_ALL;
+
+if (event_name) {
+    strcpy(event_rule.name, event_name);
+}
+
+event_rule.loglevel = -1;
+return lttng_disable_event_ext(handle, &event_rule, channel_name, NULL);
+@endcode
+*/
+LTTNG_EXPORT extern int
+lttng_disable_event(struct lttng_handle *handle, const char *event_name, const char *channel_name);
+
+/*!
+@brief
+    Disables recording event rules by
+    \ref api-rer-conds-inst-pt-type "instrumentation point type" and
+    \ref api-rer-conds-event-name "event name" condition within the
+    \lt_obj_channel named \lt_p{channel_name}
+    (or within a default channel if \c NULL) within the recording
+    session handle \lt_p{handle}.
+
+@ingroup api_rer
+
+Depending on \lt_p{event_rule->name}, this function:
+
+<dl>
+  <dt>Not empty
+  <dd>
+    Depending on \lt_p{event_rule->type}:
+
+    <dl>
+      <dt>#LTTNG_EVENT_ALL
+      <dd>
+       Disables \em all the recording event rules of which the event
+       name pattern is exactly \lt_p{event_rule->name} within the
+       selected channel.
+
+      <dt>Otherwise
+      <dd>
+       Disables all the recording event rules of which the
+       instrumentation point type is
+       \lt_p{event_rule->type} and the event
+       name pattern is exactly \lt_p{event_rule->name} within the
+       selected channel.
+
+       Only supported when \lt_p{handle->domain.type} is
+       #LTTNG_DOMAIN_KERNEL.
+    </dl>
+
+  <dt>Empty
+  <dd>
+    Depending on \lt_p{event_rule->type}:
+
+    <dl>
+      <dt>#LTTNG_EVENT_ALL
+      <dd>
+       Disables \em all the recording event rules within the selected
+       channel.
+
+      <dt>Otherwise
+      <dd>
+       Disables all the recording event rules of which the
+       instrumentation point type is
+       \lt_p{event_rule->type} within the
+       selected channel.
+
+       Only supported when \lt_p{handle->domain.type} is
+       #LTTNG_DOMAIN_KERNEL.
+    </dl>
+</dl>
+
+This function ignores all the other \ref api-rer-conds "condition"
+properties of \lt_p{event_rule}.
+
+To use this function, create a temporary, zeroed
+\link #lttng_event recording event rule descriptor\endlink,
+setting only:
+
+- <strong>Optional, and only if \lt_p{handle->domain.type}
+  is #LTTNG_DOMAIN_KERNEL</strong>: its lttng_event::type member.
+
+- <strong>Optional</strong>: its lttng_event::name member
+
+- Its lttng_event::loglevel member to&nbsp;-1.
+
+For example:
+
+@code
+struct lttng_event event_rule = { 0 };
+
+event_rule.type = LTTNG_EVENT_SYSCALL;
+strcpy(event_rule.name, "open*");
+event_rule.loglevel = -1;
+@endcode
+
+@param[in] handle
+    Recording session handle which contains the name of the recording
+    session and the summary of the \lt_obj_domain which own the selected
+    channel.
+@param[in] event_rule
+    @parblock
+    Recording event rule descriptor which contains the
+    instrumentation point type and event name conditions to consider
+    to disable recording event rules within the selected channel.
+    @endparblock
+@param[in] channel_name
+    @parblock
+    Name of the channel, within \lt_p{handle}, to select (that is,
+    containing the recording event rules to disable).
+
+    If \c NULL, then this function uses \c channel0.
+    @endparblock
+@param[in] filter_expr
+    Unused: must be \c NULL.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{handle}
+@lt_pre_valid_c_str{handle->session_name}
+@lt_pre_sess_exists{handle->session_name}
+@pre
+    \lt_p{handle->domain} is valid as per the documentation of
+    #lttng_domain.
+@lt_pre_not_null{event_rule}
+@pre
+    <strong>If \lt_p{handle->domain.type} is \em not
+    #LTTNG_DOMAIN_KERNEL</strong>, then \lt_p{event_rule->type}
+    is #LTTNG_EVENT_ALL.
+@pre
+    <strong>If not #LTTNG_EVENT_ALL</strong>, then
+    \lt_p{event_rule->type} is the instrumentation point type of at
+    least one Linux kernel recording event rule within the selected
+    channel.
+@pre
+    <strong>If not empty</strong>, then \lt_p{event_rule->name} is the
+    exact event name pattern of at least one recording event rule within
+    the selected channel.
+@pre
+    The recording event rules to disable are enabled.
+@pre
+    <strong>If not \c NULL</strong>, then \lt_p{channel_name} names an
+    existing channel within the recording session and tracing domain of
+    \lt_p{handle}.
+@pre
+    <strong>If \lt_p{channel_name} is \c NULL</strong>, then the
+    channel named \c channel0 exists within the recording session and
+    tracing domain of \lt_p{handle}.
+
+@sa lttng_disable_event() --
+    Alias which calls this function with \lt_p{event_rule->type}
+    set to #LTTNG_EVENT_ALL.
+@sa lttng_enable_event_with_exclusions() --
+    Creates or enables a recording event rule.
+*/
 LTTNG_EXPORT extern int lttng_disable_event_ext(struct lttng_handle *handle,
-               struct lttng_event *ev, const char *channel_name,
-               const char *filter_expression);
+                                               struct lttng_event *event_rule,
+                                               const char *channel_name,
+                                               const char *filter_expr);
 
 #ifdef __cplusplus
 }
index efc889f1d62ba89b2b6785113d562b6e1d9e6415..08f9eaad965be23569ac500acfb6dd4206237551 100644 (file)
 extern "C" {
 #endif
 
+/*!
+@addtogroup api_session
+@{
+*/
+
 /*
  * Handle used as a context for commands.
  *
  * The structures should be initialized to zero before use.
  */
-#define LTTNG_HANDLE_PADDING1              16
+#define LTTNG_HANDLE_PADDING1 16
+
+/*!
+@brief
+    Recording session handle.
+
+Such a structure is a pair of a \ref api_session "recording session"
+name and a \ref api-channel-domain "tracing domain" summary.
+
+Some functions which accept a recording session handle parameter ignore
+the recording session name or the tracing domain summary.
+
+Create a recording session handle with lttng_create_handle().
+
+Destroy a recording session handle with lttng_destroy_handle().
+*/
 struct lttng_handle {
+       /// \ref api_session "Recording session" name.
        char session_name[LTTNG_NAME_MAX];
+
+       /// \ref api-channel-domain "Tracing domain" summary.
        struct lttng_domain domain;
 
        char padding[LTTNG_HANDLE_PADDING1];
 };
 
-/*
- * Create an handle used as a context for every request made to the library.
- *
- * This handle contains the session name and domain on which the command will
- * be executed. A domain is basically a tracer like the kernel or user space.
- *
- * A NULL domain indicates that the handle is not bound to a specific domain.
- * This is mostly used for actions that apply on a session and not on a domain
- * (e.g lttng_set_consumer_url).
- *
- * Return a newly allocated handle that should be freed using
- * lttng_destroy_handle. On error, NULL is returned.
- */
+/*!
+@brief
+    Creates and returns a recording session handle from the
+    \ref api_session "recording session" name
+    \lt_p{session_name} and the optional
+    \ref api-channel-domain "tracing domain" summary \lt_p{domain}.
+
+@param[in] session_name
+    @parblock
+    Recording session name part of the recording session handle to
+    create.
+
+    May be \c NULL.
+    @endparblock
+@param[in] domain
+    @parblock
+    Tracing domain summary part of the recording session handle to
+    create.
+
+    May be \c NULL.
+    @endparblock
+
+@returns
+    @parblock
+    New recording session handle.
+
+    Destroy the returned handle with lttng_destroy_handle().
+    @endparblock
+
+@sa lttng_destroy_handle() --
+    Destroys a recording session handle.
+*/
 LTTNG_EXPORT extern struct lttng_handle *lttng_create_handle(const char *session_name,
-               struct lttng_domain *domain);
+                                                            struct lttng_domain *domain);
 
-/*
- * Destroy an handle that has been previously created with lttng_create_handle.
- *
- * It free the given pointer making it unusable.
- */
+/*!
+@brief
+    Destroys the recording session handle \lt_p{handle}.
+
+@note
+    @parblock
+    This function doesn't destroy the recording session named
+    \lt_p{handle->session_name}, but only the handle itself.
+
+    Use lttng_destroy_session_ext() to destroy a recording session.
+    @endparblock
+
+@param[in] handle
+    @parblock
+    Recording session handle to destroy.
+
+    May be \c NULL.
+    @endparblock
+*/
 LTTNG_EXPORT extern void lttng_destroy_handle(struct lttng_handle *handle);
 
+/// @}
 
 #ifdef __cplusplus
 }
index 67bdc6a5eeec383b9ce7706b62c6a61d36769c9e..eee164cb141d4b86ed009d52d31c8ccfa9f5508e 100644 (file)
  */
 
 #include <common/compat/time.hpp>
+#include <common/macros.hpp>
+
+#include <lttng/health.h>
+
 #include <pthread.h>
+#include <urcu/list.h>
 #include <urcu/tls-compat.h>
 #include <urcu/uatomic.h>
-#include <urcu/list.h>
-#include <lttng/health.h>
-#include <common/macros.hpp>
 
 /*
  * These are the value added to the current state depending of the position in
  * the thread where is either waiting on a poll() or running in the code.
  */
-#define HEALTH_POLL_VALUE      (1UL << 0)
-#define HEALTH_CODE_VALUE      (1UL << 1)
+#define HEALTH_POLL_VALUE (1UL << 0)
+#define HEALTH_CODE_VALUE (1UL << 1)
 
-#define HEALTH_IS_IN_POLL(x)   ((x) & HEALTH_POLL_VALUE)
+#define HEALTH_IS_IN_POLL(x) ((x) &HEALTH_POLL_VALUE)
 
 struct health_app;
 
 enum health_flags {
-       HEALTH_ERROR                     = (1U << 0),
+       HEALTH_ERROR = (1U << 0),
 };
 
 struct health_state {
@@ -43,40 +45,39 @@ struct health_state {
        /*
         * current and flags are updated by multiple threads concurrently.
         */
-       unsigned long current;          /* progress counter, updated atomically */
-       enum health_flags flags;        /* other flags, updated atomically */
-       int type;                       /* Indicates the nature of the thread. */
+       unsigned long current; /* progress counter, updated atomically */
+       enum health_flags flags; /* other flags, updated atomically */
+       int type; /* Indicates the nature of the thread. */
        /* Node of the global TLS state list. */
        struct cds_list_head node;
 };
 
 enum health_cmd {
-       HEALTH_CMD_CHECK                = 0,
+       HEALTH_CMD_CHECK = 0,
 };
 
 struct health_comm_msg {
-       uint32_t cmd;           /* enum health_cmd */
+       uint32_t cmd; /* enum health_cmd */
 } LTTNG_PACKED;
 
 struct health_comm_reply {
-       uint64_t ret_code;      /* bitmask of threads in bad health */
+       uint64_t ret_code; /* bitmask of threads in bad health */
 } LTTNG_PACKED;
 
 /* Declare TLS health state. */
-extern DECLARE_URCU_TLS(struct health_state, health_state);
+extern thread_local struct health_state health_state;
 
 /*
  * Update current counter by 1 to indicate that the thread entered or left a
  * blocking state caused by a poll(). If the counter's value is not an even
  * number (meaning a code execution flow), an LTTNG_ASSERT() is raised.
  */
-static inline void health_poll_entry(void)
+static inline void health_poll_entry()
 {
        /* Code MUST be in code execution state which is an even number. */
-       LTTNG_ASSERT(!(uatomic_read(&URCU_TLS(health_state).current)
-                               & HEALTH_POLL_VALUE));
+       LTTNG_ASSERT(!(uatomic_read(&health_state.current) & HEALTH_POLL_VALUE));
 
-       uatomic_add(&URCU_TLS(health_state).current, HEALTH_POLL_VALUE);
+       uatomic_add(&health_state.current, HEALTH_POLL_VALUE);
 }
 
 /*
@@ -84,30 +85,29 @@ static inline void health_poll_entry(void)
  * If the counter's value is not an odd number (a poll execution), an LTTNG_ASSERT()
  * is raised.
  */
-static inline void health_poll_exit(void)
+static inline void health_poll_exit()
 {
        /* Code MUST be in poll execution state which is an odd number. */
-       LTTNG_ASSERT(uatomic_read(&URCU_TLS(health_state).current)
-                               & HEALTH_POLL_VALUE);
+       LTTNG_ASSERT(uatomic_read(&health_state.current) & HEALTH_POLL_VALUE);
 
-       uatomic_add(&URCU_TLS(health_state).current, HEALTH_POLL_VALUE);
+       uatomic_add(&health_state.current, HEALTH_POLL_VALUE);
 }
 
 /*
  * Update current counter by 2 indicates progress in execution of a
  * thread.
  */
-static inline void health_code_update(void)
+static inline void health_code_update()
 {
-       uatomic_add(&URCU_TLS(health_state).current, HEALTH_CODE_VALUE);
+       uatomic_add(&health_state.current, HEALTH_CODE_VALUE);
 }
 
 /*
  * Set health "error" flag.
  */
-static inline void health_error(void)
+static inline void health_error()
 {
-       uatomic_or(&URCU_TLS(health_state).flags, HEALTH_ERROR);
+       uatomic_or(&health_state.flags, HEALTH_ERROR);
 }
 
 struct health_app *health_app_create(int nr_types);
index 26e88570542777ea16deae79f46bdd0041fbd316..4e82c7be13ad8c4d9a1c8569a461761d867f0ceb 100644 (file)
@@ -40,7 +40,7 @@ LTTNG_EXPORT extern struct lttng_health *lttng_health_create_sessiond(void);
  * Return a newly allocated health object, or NULL on error.
  */
 LTTNG_EXPORT extern struct lttng_health *
-       lttng_health_create_consumerd(enum lttng_health_consumerd consumerd);
+lttng_health_create_consumerd(enum lttng_health_consumerd consumerd);
 
 /**
  * lttng_health_create_relayd - Create relayd health object
@@ -101,8 +101,7 @@ LTTNG_EXPORT extern int lttng_health_get_nr_threads(const struct lttng_health *h
  * lttng_health_destroy() is called on @health.
  */
 LTTNG_EXPORT extern const struct lttng_health_thread *
-       lttng_health_get_thread(const struct lttng_health *health,
-               unsigned int nth_thread);
+lttng_health_get_thread(const struct lttng_health *health, unsigned int nth_thread);
 
 /**
  * lttng_health_thread_state - Get thread health state
index 07c546f9d3d0d66d1ec4f83ee42a75bbc8f0bd5e..bdafb4d0a56a865cdd024534c1af562ebd4e6d0f 100644 (file)
 
 #include <common/fd-handle.hpp>
 #include <common/macros.hpp>
-#include <lttng/lttng-error.h>
+
 #include <lttng/kernel-probe.h>
 #include <lttng/lttng-error.h>
+
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -22,23 +23,17 @@ struct lttng_payload_view;
 struct lttng_dynamic_buffer;
 struct mi_writer;
 
-typedef bool (*kernel_probe_location_equal_cb)(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b);
-typedef int (*kernel_probe_location_serialize_cb)(
-               const struct lttng_kernel_probe_location *kernel_probe_location,
-               struct lttng_payload *payload);
-typedef bool (*kernel_probe_location_equal_cb)(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b);
-typedef ssize_t (*kernel_probe_location_create_from_payload_cb)(
-               struct lttng_payload_view *view,
-               struct lttng_kernel_probe_location **kernel_probe_location);
-typedef unsigned long (*kernel_probe_location_hash_cb)(
-               const struct lttng_kernel_probe_location *location);
-typedef enum lttng_error_code (*kernel_probe_location_mi_serialize_cb)(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer);
+using kernel_probe_location_equal_cb = bool (*)(const struct lttng_kernel_probe_location *,
+                                               const struct lttng_kernel_probe_location *);
+using kernel_probe_location_serialize_cb = int (*)(const struct lttng_kernel_probe_location *,
+                                                  struct lttng_payload *);
+using kernel_probe_location_equal_cb = bool (*)(const struct lttng_kernel_probe_location *,
+                                               const struct lttng_kernel_probe_location *);
+using kernel_probe_location_create_from_payload_cb =
+       ssize_t (*)(struct lttng_payload_view *, struct lttng_kernel_probe_location **);
+using kernel_probe_location_hash_cb = unsigned long (*)(const struct lttng_kernel_probe_location *);
+using kernel_probe_location_mi_serialize_cb =
+       enum lttng_error_code (*)(const struct lttng_kernel_probe_location *, struct mi_writer *);
 
 struct lttng_kernel_probe_location_comm {
        /* enum lttng_kernel_probe_location_type */
@@ -86,26 +81,22 @@ struct lttng_kernel_probe_location_address {
        uint64_t address;
 };
 
-int lttng_kernel_probe_location_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload);
+int lttng_kernel_probe_location_serialize(const struct lttng_kernel_probe_location *location,
+                                         struct lttng_payload *payload);
 
 ssize_t lttng_kernel_probe_location_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_kernel_probe_location **probe_location);
+       struct lttng_payload_view *view, struct lttng_kernel_probe_location **probe_location);
 
-bool lttng_kernel_probe_location_is_equal(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b);
+bool lttng_kernel_probe_location_is_equal(const struct lttng_kernel_probe_location *a,
+                                         const struct lttng_kernel_probe_location *b);
 
-struct lttng_kernel_probe_location *lttng_kernel_probe_location_copy(
-               const struct lttng_kernel_probe_location *location);
+struct lttng_kernel_probe_location *
+lttng_kernel_probe_location_copy(const struct lttng_kernel_probe_location *location);
 
-unsigned long lttng_kernel_probe_location_hash(
-               const struct lttng_kernel_probe_location *location);
+unsigned long lttng_kernel_probe_location_hash(const struct lttng_kernel_probe_location *location);
 
-enum lttng_error_code lttng_kernel_probe_location_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer);
+enum lttng_error_code
+lttng_kernel_probe_location_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                        struct mi_writer *writer);
 
 #endif /* LTTNG_KERNEL_PROBE_INTERNAL_H */
index cdd617dea12625296435615fa72f778f3ff84938..8e894fae8714564cfa0d71108f65b35cae30dedc 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_KERNEL_PROBE_H
 
 #include <lttng/lttng-export.h>
+
 #include <stdint.h>
 
 #ifdef __cplusplus
@@ -18,53 +19,50 @@ extern "C" {
 struct lttng_kernel_probe_location;
 
 enum lttng_kernel_probe_location_status {
-       LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK           = 0,
+       LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK = 0,
        /* Invalid parameters provided. */
-       LTTNG_KERNEL_PROBE_LOCATION_STATUS_INVALID      = -1,
+       LTTNG_KERNEL_PROBE_LOCATION_STATUS_INVALID = -1,
 };
 
 enum lttng_kernel_probe_location_type {
-       LTTNG_KERNEL_PROBE_LOCATION_TYPE_UNKNOWN        = -1,
+       LTTNG_KERNEL_PROBE_LOCATION_TYPE_UNKNOWN = -1,
        /* Location derived from a symbol and an offset. */
-       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET  = 0,
+       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET = 0,
        /* Location derived from an address. */
-       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS        = 1,
+       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS = 1,
 };
 
 /*
  * Get the type of the kernel probe location.
  */
 LTTNG_EXPORT extern enum lttng_kernel_probe_location_type
-lttng_kernel_probe_location_get_type(
-               const struct lttng_kernel_probe_location *location);
+lttng_kernel_probe_location_get_type(const struct lttng_kernel_probe_location *location);
 
 /*
  * Destroy the kernel probe location.
  */
-LTTNG_EXPORT extern void lttng_kernel_probe_location_destroy(
-               struct lttng_kernel_probe_location *location);
+LTTNG_EXPORT extern void
+lttng_kernel_probe_location_destroy(struct lttng_kernel_probe_location *location);
 
 /*
  * Create a symbol derived probe location.
  * On failure, NULL is returned.
  */
 LTTNG_EXPORT extern struct lttng_kernel_probe_location *
-lttng_kernel_probe_location_symbol_create(const char *symbol_name,
-               uint64_t offset);
+lttng_kernel_probe_location_symbol_create(const char *symbol_name, uint64_t offset);
 
 /*
  * Get the symbol name of a symbol derived probe location.
  */
-LTTNG_EXPORT extern const char *lttng_kernel_probe_location_symbol_get_name(
-               const struct lttng_kernel_probe_location *location);
+LTTNG_EXPORT extern const char *
+lttng_kernel_probe_location_symbol_get_name(const struct lttng_kernel_probe_location *location);
 
 /*
  * Get the offset of a symbol derived location.
  */
 LTTNG_EXPORT extern enum lttng_kernel_probe_location_status
-lttng_kernel_probe_location_symbol_get_offset(
-               const struct lttng_kernel_probe_location *location,
-               uint64_t *offset);
+lttng_kernel_probe_location_symbol_get_offset(const struct lttng_kernel_probe_location *location,
+                                             uint64_t *offset);
 
 /*
  * Create an address derived probe location.
@@ -77,9 +75,8 @@ lttng_kernel_probe_location_address_create(uint64_t address);
  * Get the address of an address derived probe location.
  */
 LTTNG_EXPORT extern enum lttng_kernel_probe_location_status
-lttng_kernel_probe_location_address_get_address(
-               const struct lttng_kernel_probe_location *location,
-               uint64_t *offset);
+lttng_kernel_probe_location_address_get_address(const struct lttng_kernel_probe_location *location,
+                                               uint64_t *offset);
 
 #ifdef __cplusplus
 }
diff --git a/include/lttng/kernel.h b/include/lttng/kernel.h
new file mode 100644 (file)
index 0000000..d3a9f05
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * kernel.h
+ *
+ * Linux Trace Toolkit Control Library Header File
+ *
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier; LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_KERNEL_H
+#define LTTNG_KERNEL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum lttng_kernel_tracer_status {
+       /* Loaded without error. */
+       LTTNG_KERNEL_TRACER_STATUS_INITIALIZED = 0,
+       /* Unknown error. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_UNKNOWN = -1,
+       /* lttng-sessiond isn't running as root. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_NEED_ROOT = -2,
+       /* Notifier setup failed. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER = -3,
+       /* Failed to open /proc/lttng. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_OPEN_PROC_LTTNG = -4,
+       /* Version mismatch between kernel tracer and kernel tracer ABI. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_VERSION_MISMATCH = -5,
+       /* Kernel module loading failed. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_UNKNOWN = -6,
+       /* Kernel modules missing. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_MISSING = -7,
+       /* Kernel module signature error. */
+       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_SIGNATURE = -8,
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LTTNG_KERNEL_H */
index ef09ffd9cebb40dfa76f5002a5fda317e95f8870..78f38e47e9d5811f180c93ae8eab5a665cec1a4e 100644 (file)
@@ -9,12 +9,13 @@
 #ifndef LTTNG_LOAD_INTERNAL_ABI_H
 #define LTTNG_LOAD_INTERNAL_ABI_H
 
-#include <limits.h>
-#include <stdint.h>
+#include <common/config/session-config.hpp>
+#include <common/macros.hpp>
 
 #include <lttng/constant.h>
-#include <common/macros.hpp>
-#include <common/config/session-config.hpp>
+
+#include <limits.h>
+#include <stdint.h>
 
 /*
  * Object used by the load_session API. This is opaque to the public library.
index 0395bb4145acfea3923abeca700eaf3c062aa527..5f7b4ec4473da82f2bc7e3a003f123f2b8b665c8 100644 (file)
@@ -31,21 +31,20 @@ LTTNG_EXPORT extern struct lttng_load_session_attr *lttng_load_session_attr_crea
  */
 LTTNG_EXPORT extern void lttng_load_session_attr_destroy(struct lttng_load_session_attr *attr);
 
-
 /*
  * Load session attribute getter family of functions.
  */
 
 /* Return session name. NULL indicates all sessions must be loaded. */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_session_name(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_session_name(struct lttng_load_session_attr *attr);
 /*
  * Return input URL. A NULL value indicates the default session
  * configuration location. The URL format used is documented in lttng-create(1).
  * NULL indicates that the default session configuration path is used.
  */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_input_url(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_input_url(struct lttng_load_session_attr *attr);
 
 /*
  * Return the configuration overwrite attribute. This attribute indicates
@@ -53,8 +52,7 @@ LTTNG_EXPORT extern const char *lttng_load_session_attr_get_input_url(
  * same name already exists. If such a session exists, it is destroyed before
  * the replacement is loaded.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_get_overwrite(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern int lttng_load_session_attr_get_overwrite(struct lttng_load_session_attr *attr);
 
 /*
  * Return the destination URL configuration override attribute. This attribute
@@ -63,8 +61,8 @@ LTTNG_EXPORT extern int lttng_load_session_attr_get_overwrite(
  *
  * NULL indicates no override will be applied on configuration load.
  */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_url(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_override_url(struct lttng_load_session_attr *attr);
 
 /*
  * Return the configuration override control URL attribute. This attribute
@@ -73,8 +71,8 @@ LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_url(
  *
  * NULL indicates no control URL override will be applied on configuration load.
  */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_ctrl_url(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_override_ctrl_url(struct lttng_load_session_attr *attr);
 
 /*
  * Return the configuration override data URL attribute. This attribute
@@ -83,8 +81,8 @@ LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_ctrl_url(
  *
  * NULL indicates no data URL override will be applied on configuration load.
  */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_data_url(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_override_data_url(struct lttng_load_session_attr *attr);
 
 /*
  * Return the configuration override session name attribute.
@@ -94,8 +92,8 @@ LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_data_url(
  * NULL indicates no session name override will be applied on configuration
  * load.
  */
-LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_session_name(
-       struct lttng_load_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_load_session_attr_get_override_session_name(struct lttng_load_session_attr *attr);
 
 /*
  * Load session attribute setter family of functions.
@@ -108,8 +106,9 @@ LTTNG_EXPORT extern const char *lttng_load_session_attr_get_override_session_nam
  * Set the name of the session to load. A NULL name means all sessions
  * found at the input URL will be loaded.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_session_name(
-       struct lttng_load_session_attr *attr, const char *session_name);
+LTTNG_EXPORT extern int
+lttng_load_session_attr_set_session_name(struct lttng_load_session_attr *attr,
+                                        const char *session_name);
 
 /*
  * Set the URL of the session configuration to load. A NULL value indicates the
@@ -117,16 +116,16 @@ LTTNG_EXPORT extern int lttng_load_session_attr_set_session_name(
  *
  * Note that file:// is the only supported URL format.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_input_url(
-       struct lttng_load_session_attr *attr, const char *url);
+LTTNG_EXPORT extern int lttng_load_session_attr_set_input_url(struct lttng_load_session_attr *attr,
+                                                             const char *url);
 
 /*
  * Set the overwrite attribute. If set to true, current sessions matching the
  * loaded sessions will be destroyed and be replaced by the session(s) being
  * loaded.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_overwrite(
-       struct lttng_load_session_attr *attr, int overwrite);
+LTTNG_EXPORT extern int lttng_load_session_attr_set_overwrite(struct lttng_load_session_attr *attr,
+                                                             int overwrite);
 
 /*
  * The following setter are for overriding sessions attributes during the
@@ -145,8 +144,8 @@ LTTNG_EXPORT extern int lttng_load_session_attr_set_overwrite(
  *
  * See lttng-create(1) for more detail.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_override_url(
-       struct lttng_load_session_attr *attr, const char *url);
+LTTNG_EXPORT extern int
+lttng_load_session_attr_set_override_url(struct lttng_load_session_attr *attr, const char *url);
 
 /*
  * Set the control url override attribute.
@@ -158,8 +157,9 @@ LTTNG_EXPORT extern int lttng_load_session_attr_set_override_url(
  *
  * See lttng-create(1) for more detail.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_override_ctrl_url(
-       struct lttng_load_session_attr *attr, const char *url);
+LTTNG_EXPORT extern int
+lttng_load_session_attr_set_override_ctrl_url(struct lttng_load_session_attr *attr,
+                                             const char *url);
 
 /*
  * Set the data url override attribute.
@@ -171,8 +171,9 @@ LTTNG_EXPORT extern int lttng_load_session_attr_set_override_ctrl_url(
  *
  * See lttng-create(1) for more detail.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_override_data_url(
-       struct lttng_load_session_attr *attr, const char *url);
+LTTNG_EXPORT extern int
+lttng_load_session_attr_set_override_data_url(struct lttng_load_session_attr *attr,
+                                             const char *url);
 
 /*
  * Set the session name override attribute.
@@ -180,8 +181,9 @@ LTTNG_EXPORT extern int lttng_load_session_attr_set_override_data_url(
  * Loading a configuration file defining multiple sessions will fail if a
  * session name is provided.
  */
-LTTNG_EXPORT extern int lttng_load_session_attr_set_override_session_name(
-       struct lttng_load_session_attr *attr, const char *session_name);
+LTTNG_EXPORT extern int
+lttng_load_session_attr_set_override_session_name(struct lttng_load_session_attr *attr,
+                                                 const char *session_name);
 
 /*
  * Load session configuration(s).
index 4daeed061b06d8e2916f6ce141ef6c3bee0e3d65..669347e2ebbca28f18b6c82a463d2f2aa992a493 100644 (file)
@@ -8,10 +8,12 @@
 #ifndef LTTNG_LOCATION_INTERNAL_H
 #define LTTNG_LOCATION_INTERNAL_H
 
-#include <lttng/location.h>
-#include <common/dynamic-buffer.hpp>
 #include <common/buffer-view.hpp>
+#include <common/dynamic-buffer.hpp>
 #include <common/macros.hpp>
+
+#include <lttng/location.h>
+
 #include <sys/types.h>
 #include <urcu/ref.h>
 
@@ -73,28 +75,24 @@ struct lttng_trace_archive_location_comm {
        char payload[];
 } LTTNG_PACKED;
 
-
-struct lttng_trace_archive_location *lttng_trace_archive_location_local_create(
-               const char *path);
+struct lttng_trace_archive_location *lttng_trace_archive_location_local_create(const char *path);
 
 struct lttng_trace_archive_location *lttng_trace_archive_location_relay_create(
-               const char *host,
-               enum lttng_trace_archive_location_relay_protocol_type protocol,
-               uint16_t control_port, uint16_t data_port,
-               const char *relative_path);
+       const char *host,
+       enum lttng_trace_archive_location_relay_protocol_type protocol,
+       uint16_t control_port,
+       uint16_t data_port,
+       const char *relative_path);
 
-ssize_t lttng_trace_archive_location_create_from_buffer(
-               const struct lttng_buffer_view *buffer,
-               struct lttng_trace_archive_location **location);
+ssize_t
+lttng_trace_archive_location_create_from_buffer(const struct lttng_buffer_view *buffer,
+                                               struct lttng_trace_archive_location **location);
 
-ssize_t lttng_trace_archive_location_serialize(
-               const struct lttng_trace_archive_location *location,
-               struct lttng_dynamic_buffer *buffer);
+ssize_t lttng_trace_archive_location_serialize(const struct lttng_trace_archive_location *location,
+                                              struct lttng_dynamic_buffer *buffer);
 
-void lttng_trace_archive_location_get(
-               struct lttng_trace_archive_location *location);
+void lttng_trace_archive_location_get(struct lttng_trace_archive_location *location);
 
-void lttng_trace_archive_location_put(
-               struct lttng_trace_archive_location *location);
+void lttng_trace_archive_location_put(struct lttng_trace_archive_location *location);
 
 #endif /* LTTNG_LOCATION_INTERNAL_H */
index ce686315effe4ffa1149d7344cb85c4dcfca60fd..a1ea16f23a60cd75cf2f09b61e8eee8e28395c7d 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_LOCATION_H
 
 #include <lttng/lttng-export.h>
+
 #include <stdint.h>
 
 #ifdef __cplusplus
@@ -40,8 +41,7 @@ struct lttng_trace_archive_location;
  * Get a trace archive location's type.
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_type
-lttng_trace_archive_location_get_type(
-               const struct lttng_trace_archive_location *location);
+lttng_trace_archive_location_get_type(const struct lttng_trace_archive_location *location);
 
 /*
  * Get the absolute path of a local trace archive location.
@@ -50,8 +50,7 @@ lttng_trace_archive_location_get_type(
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
 lttng_trace_archive_location_local_get_absolute_path(
-               const struct lttng_trace_archive_location *location,
-               const char **absolute_path);
+       const struct lttng_trace_archive_location *location, const char **absolute_path);
 
 /*
  * Get the host address of the relay daemon associated to this trace archive
@@ -60,9 +59,8 @@ lttng_trace_archive_location_local_get_absolute_path(
  * The trace archive location maintains ownership of relay_host.
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_host(
-               const struct lttng_trace_archive_location *location,
-               const char **relay_host);
+lttng_trace_archive_location_relay_get_host(const struct lttng_trace_archive_location *location,
+                                           const char **relay_host);
 
 /*
  * Get the control port of the relay daemon associated to this trace archive
@@ -70,8 +68,7 @@ lttng_trace_archive_location_relay_get_host(
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
 lttng_trace_archive_location_relay_get_control_port(
-               const struct lttng_trace_archive_location *location,
-               uint16_t *control_port);
+       const struct lttng_trace_archive_location *location, uint16_t *control_port);
 
 /*
  * Get the data port of the relay daemon associated to this trace archive
@@ -79,8 +76,7 @@ lttng_trace_archive_location_relay_get_control_port(
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
 lttng_trace_archive_location_relay_get_data_port(
-               const struct lttng_trace_archive_location *location,
-               uint16_t *data_port);
+       const struct lttng_trace_archive_location *location, uint16_t *data_port);
 
 /*
  * Get the protocol used to communicate with the relay daemon associated to this
@@ -88,8 +84,8 @@ lttng_trace_archive_location_relay_get_data_port(
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
 lttng_trace_archive_location_relay_get_protocol_type(
-               const struct lttng_trace_archive_location *location,
-               enum lttng_trace_archive_location_relay_protocol_type *protocol);
+       const struct lttng_trace_archive_location *location,
+       enum lttng_trace_archive_location_relay_protocol_type *protocol);
 
 /*
  * Get path relative to the relay daemon's current output path.
@@ -98,8 +94,7 @@ lttng_trace_archive_location_relay_get_protocol_type(
  */
 LTTNG_EXPORT extern enum lttng_trace_archive_location_status
 lttng_trace_archive_location_relay_get_relative_path(
-               const struct lttng_trace_archive_location *location,
-               const char **relative_path);
+       const struct lttng_trace_archive_location *location, const char **relative_path);
 
 #ifdef __cplusplus
 }
index 71447cfe35ff6f5b49fadbd974d4e34251e02cdb..6b08e8a5ff517cbe47ec7d032dff43a47d465c4b 100644 (file)
@@ -8,17 +8,18 @@
 #ifndef LTTNG_LOG_LEVEL_RULE_INTERNAL_H
 #define LTTNG_LOG_LEVEL_RULE_INTERNAL_H
 
-#include <stdint.h>
-
 #include <common/buffer-view.hpp>
 #include <common/dynamic-array.hpp>
 #include <common/macros.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/event.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-error.h>
 
+#include <stdint.h>
+
 struct mi_writer;
 
 /*
@@ -36,29 +37,24 @@ struct lttng_log_level_rule_comm {
        int32_t level;
 };
 
-ssize_t lttng_log_level_rule_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_log_level_rule **rule);
+ssize_t lttng_log_level_rule_create_from_payload(struct lttng_payload_view *view,
+                                                struct lttng_log_level_rule **rule);
 
 int lttng_log_level_rule_serialize(const struct lttng_log_level_rule *rule,
-               struct lttng_payload *payload);
+                                  struct lttng_payload *payload);
 
 bool lttng_log_level_rule_is_equal(const struct lttng_log_level_rule *a,
-               const struct lttng_log_level_rule *b);
+                                  const struct lttng_log_level_rule *b);
 
-struct lttng_log_level_rule *lttng_log_level_rule_copy(
-               const struct lttng_log_level_rule *source);
+struct lttng_log_level_rule *lttng_log_level_rule_copy(const struct lttng_log_level_rule *source);
 
-void lttng_log_level_rule_to_loglevel(
-               const struct lttng_log_level_rule *log_level_rule,
-               enum lttng_loglevel_type *loglevel_type,
-               int *loglevel_value);
+void lttng_log_level_rule_to_loglevel(const struct lttng_log_level_rule *log_level_rule,
+                                     enum lttng_loglevel_type *loglevel_type,
+                                     int *loglevel_value);
 
-unsigned long lttng_log_level_rule_hash(
-               const struct lttng_log_level_rule *log_level_rule);
+unsigned long lttng_log_level_rule_hash(const struct lttng_log_level_rule *log_level_rule);
 
-enum lttng_error_code lttng_log_level_rule_mi_serialize(
-               const struct lttng_log_level_rule *rule,
-               struct mi_writer *writer);
+enum lttng_error_code lttng_log_level_rule_mi_serialize(const struct lttng_log_level_rule *rule,
+                                                       struct mi_writer *writer);
 
 #endif /* LTTNG_LOG_LEVEL_RULE_INTERNAL_H */
index ddb3501a1a66f4e2bfe49577ef32c9f298f7f4da..a73b26ae3e514d8904ddc2b035640e4a1b733ae8 100644 (file)
@@ -34,8 +34,8 @@ enum lttng_log_level_rule_status {
  * `LTTNG_LOG_LEVEL_RULE_TYPE_UNKNOWN`:
  *     `rule` is `NULL`.
  */
-LTTNG_EXPORT extern enum lttng_log_level_rule_type lttng_log_level_rule_get_type(
-               const struct lttng_log_level_rule *rule);
+LTTNG_EXPORT extern enum lttng_log_level_rule_type
+lttng_log_level_rule_get_type(const struct lttng_log_level_rule *rule);
 
 /*
  * Creates a log level rule for which a log level must match exactly `level` to
@@ -48,8 +48,7 @@ LTTNG_EXPORT extern enum lttng_log_level_rule_type lttng_log_level_rule_get_type
  * The returned log level rule must be destroyed using
  * lttng_log_level_rule_destroy().
  */
-LTTNG_EXPORT extern struct lttng_log_level_rule *lttng_log_level_rule_exactly_create(
-               int level);
+LTTNG_EXPORT extern struct lttng_log_level_rule *lttng_log_level_rule_exactly_create(int level);
 
 /*
  * Sets `level` to the level of the "exactly" log level rule `rule`.
@@ -64,8 +63,8 @@ LTTNG_EXPORT extern struct lttng_log_level_rule *lttng_log_level_rule_exactly_cr
  *     * `level` is NULL.
  *     * The type of `rule` is not `LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY`.
  */
-LTTNG_EXPORT extern enum lttng_log_level_rule_status lttng_log_level_rule_exactly_get_level(
-               const struct lttng_log_level_rule *rule, int *level);
+LTTNG_EXPORT extern enum lttng_log_level_rule_status
+lttng_log_level_rule_exactly_get_level(const struct lttng_log_level_rule *rule, int *level);
 
 /*
  * Creates a log level rule for which a log level must be at least as severe as
@@ -97,14 +96,13 @@ lttng_log_level_rule_at_least_as_severe_as_create(int level);
  *       `LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS`.
  */
 LTTNG_EXPORT extern enum lttng_log_level_rule_status
-lttng_log_level_rule_at_least_as_severe_as_get_level(
-               const struct lttng_log_level_rule *rule, int *level);
+lttng_log_level_rule_at_least_as_severe_as_get_level(const struct lttng_log_level_rule *rule,
+                                                    int *level);
 
 /*
  * Destroy the log level rule `log_level_rule` if not `NULL`.
  */
-LTTNG_EXPORT extern void lttng_log_level_rule_destroy(
-               struct lttng_log_level_rule *log_level_rule);
+LTTNG_EXPORT extern void lttng_log_level_rule_destroy(struct lttng_log_level_rule *log_level_rule);
 
 #ifdef __cplusplus
 }
index 790a78a0b60e88188486fc230b84c01ba031f347..fa05af777e0431b32fb695007856b28268e9a2b0 100644 (file)
 #ifndef LTTNG_ERROR_H
 #define LTTNG_ERROR_H
 
-#include <lttng/lttng-export.h>
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+#include <lttng/lttng-export.h>
+
+/*!
+@addtogroup api_gen
+@{
+*/
+
+/*!
+@brief
+    General error codes.
+
+Many functions, most of them dating from older liblttng-ctl versions,
+return this type (or an \c int value which is equal to the negation of
+one of those enumerators).
+
+Not all error codes are relevant to a given function: this API
+documentation makes an effort to document the most relevant status codes
+for each function. This is not always possible, however, as LTTng is
+made of multiple interacting components (tracers, consumer daemons,
+session daemons, and the rest); those error codes can move from one to
+another and the possible error codes of a given liblttng-ctl function
+can change from version to version.
+
+@sa lttng_strerror() --
+    Returns a human-readable message for a general error code, positive
+    or negative.
+*/
 enum lttng_error_code {
-       LTTNG_OK                         = 10,  /* Ok */
-       LTTNG_ERR_UNK                    = 11,  /* Unknown Error */
-       LTTNG_ERR_UND                    = 12,  /* Undefined command */
-       LTTNG_ERR_SESSION_STARTED        = 13,  /* Session is running */
-       LTTNG_ERR_UNKNOWN_DOMAIN         = 14,  /* Tracing domain not known */
-       LTTNG_ERR_NOT_SUPPORTED          = 15,  /* Operation not supported */
-       LTTNG_ERR_NO_SESSION             = 16,  /* No session found */
-       LTTNG_ERR_CREATE_DIR_FAIL        = 17,  /* Create directory fail */
-       LTTNG_ERR_SESSION_FAIL           = 18,  /* Create session fail */
-       LTTNG_ERR_NO_SESSIOND            = 19,  /* No session daemon available */
-       LTTNG_ERR_SET_URL                = 20,  /* Error setting URL */
-       LTTNG_ERR_URL_EXIST              = 21,  /* URL already exists. */
-       LTTNG_ERR_BUFFER_NOT_SUPPORTED   = 22,  /* Buffer type not supported. */
-       LTTNG_ERR_SESS_NOT_FOUND         = 23,  /* Session by name not found */
-       LTTNG_ERR_BUFFER_TYPE_MISMATCH   = 24,  /* Buffer type mismatched. */
-       LTTNG_ERR_FATAL                  = 25,  /* Fatal error */
-       LTTNG_ERR_NOMEM                  = 26,  /* Not enough memory. */
-       LTTNG_ERR_SELECT_SESS            = 27,  /* Must select a session */
-       LTTNG_ERR_EXIST_SESS             = 28,  /* Session name already exist */
-       LTTNG_ERR_NO_EVENT               = 29,  /* No event found */
-       LTTNG_ERR_CONNECT_FAIL           = 30,  /* Unable to connect to unix socket */
-       LTTNG_ERR_SNAPSHOT_OUTPUT_EXIST  = 31,  /* Snapshot output already exists */
-       LTTNG_ERR_EPERM                  = 32,  /* Permission denied */
-       LTTNG_ERR_KERN_NA                = 33,  /* Kernel tracer unavailable */
-       LTTNG_ERR_KERN_VERSION           = 34,  /* Kernel tracer not compatible */
-       LTTNG_ERR_KERN_EVENT_EXIST       = 35,  /* Kernel event already exists */
-       LTTNG_ERR_KERN_SESS_FAIL         = 36,  /* Kernel create session failed */
-       LTTNG_ERR_KERN_CHAN_EXIST        = 37,  /* Kernel channel already exists */
-       LTTNG_ERR_KERN_CHAN_FAIL         = 38,  /* Kernel create channel failed */
-       LTTNG_ERR_KERN_CHAN_NOT_FOUND    = 39,  /* Kernel channel not found */
-       LTTNG_ERR_KERN_CHAN_DISABLE_FAIL = 40,  /* Kernel disable channel failed */
-       LTTNG_ERR_KERN_CHAN_ENABLE_FAIL  = 41,  /* Kernel enable channel failed */
-       LTTNG_ERR_KERN_CONTEXT_FAIL      = 42,  /* Kernel add context failed */
-       LTTNG_ERR_KERN_ENABLE_FAIL       = 43,  /* Kernel enable event failed */
-       LTTNG_ERR_KERN_DISABLE_FAIL      = 44,  /* Kernel disable event failed */
-       LTTNG_ERR_KERN_META_FAIL         = 45,  /* Kernel open metadata failed */
-       LTTNG_ERR_KERN_START_FAIL        = 46,  /* Kernel start trace failed */
-       LTTNG_ERR_KERN_STOP_FAIL         = 47,  /* Kernel stop trace failed */
-       LTTNG_ERR_KERN_CONSUMER_FAIL     = 48,  /* Kernel consumer start failed */
-       LTTNG_ERR_KERN_STREAM_FAIL       = 49,  /* Kernel create stream failed */
-       LTTNG_ERR_START_SESSION_ONCE     = 50,  /* Session needs to be started once. */
-       LTTNG_ERR_SNAPSHOT_FAIL          = 51,  /* Snapshot record failed. */
-       LTTNG_ERR_NO_STREAM              = 52,  /* Index without stream on relay. */
-       LTTNG_ERR_KERN_LIST_FAIL         = 53,  /* Kernel listing events failed */
-       LTTNG_ERR_UST_CALIBRATE_FAIL     = 54,  /* UST calibration failed */
-       LTTNG_ERR_UST_EVENT_ENABLED      = 55,  /* UST event already enabled. */
-       LTTNG_ERR_UST_SESS_FAIL          = 56,  /* UST create session failed */
-       LTTNG_ERR_UST_CHAN_EXIST         = 57,  /* UST channel already exist */
-       LTTNG_ERR_UST_CHAN_FAIL          = 58,  /* UST create channel failed */
-       LTTNG_ERR_UST_CHAN_NOT_FOUND     = 59,  /* UST channel not found */
-       LTTNG_ERR_UST_CHAN_DISABLE_FAIL  = 60,  /* UST disable channel failed */
-       LTTNG_ERR_UST_CHAN_ENABLE_FAIL   = 61,  /* UST enable channel failed */
-       LTTNG_ERR_CHAN_EXIST             = 62,  /* Channel already exists. */
-       LTTNG_ERR_UST_ENABLE_FAIL        = 63,  /* UST enable event failed */
-       LTTNG_ERR_UST_DISABLE_FAIL       = 64,  /* UST disable event failed */
-       LTTNG_ERR_UST_META_FAIL          = 65,  /* UST open metadata failed */
-       LTTNG_ERR_UST_START_FAIL         = 66,  /* UST start trace failed */
-       LTTNG_ERR_UST_STOP_FAIL          = 67,  /* UST stop trace failed */
-       LTTNG_ERR_UST_CONSUMER64_FAIL    = 68,  /* 64-bit UST consumer start failed */
-       LTTNG_ERR_UST_CONSUMER32_FAIL    = 69,  /* 32-bit UST consumer start failed */
-       LTTNG_ERR_UST_STREAM_FAIL        = 70,  /* UST create stream failed */
-       LTTNG_ERR_SNAPSHOT_NODATA        = 71,  /* No data in snapshot. */
-       LTTNG_ERR_NO_CHANNEL             = 72,  /* No channel found in the session. */
-       LTTNG_ERR_SESSION_INVALID_CHAR   = 73,  /* Invalid characters found in session name. */
-       LTTNG_ERR_UST_LIST_FAIL          = 74,  /* UST listing events failed */
-       LTTNG_ERR_UST_EVENT_EXIST        = 75,  /* UST event exist */
-       LTTNG_ERR_UST_EVENT_NOT_FOUND    = 76,  /* UST event not found */
-       LTTNG_ERR_UST_CONTEXT_EXIST      = 77,  /* UST context exist */
-       LTTNG_ERR_UST_CONTEXT_INVAL      = 78,  /* UST context invalid */
-       LTTNG_ERR_NEED_ROOT_SESSIOND     = 79,  /* root sessiond is needed */
-       LTTNG_ERR_TRACE_ALREADY_STARTED  = 80,  /* Tracing already started */
-       LTTNG_ERR_TRACE_ALREADY_STOPPED  = 81,  /* Tracing already stopped */
-       LTTNG_ERR_KERN_EVENT_ENOSYS      = 82,  /* Kernel event type not supported */
-       LTTNG_ERR_NEED_CHANNEL_NAME      = 83,  /* Non-default channel exists within session: channel name needs to be specified with '-c name' */
-       LTTNG_ERR_NO_UST                 = 84,  /* LTTng-UST tracer is not supported. Please rebuild lttng-tools with lttng-ust support enabled. */
-       LTTNG_ERR_SAVE_FILE_EXIST        = 85,  /* Session file already exists. */
-       LTTNG_ERR_SAVE_IO_FAIL           = 86,  /* IO error while writing session configuration */
-       LTTNG_ERR_LOAD_INVALID_CONFIG    = 87,  /* Invalid session configuration */
-       LTTNG_ERR_LOAD_IO_FAIL           = 88,  /* IO error while reading a session configuration */
-       LTTNG_ERR_LOAD_SESSION_NOENT     = 89,  /* Session file not found */
-       LTTNG_ERR_MAX_SIZE_INVALID       = 90,  /* Snapshot max size is invalid. */
-       LTTNG_ERR_MI_OUTPUT_TYPE         = 91,  /* Invalid MI output format */
-       LTTNG_ERR_MI_IO_FAIL             = 92,  /* IO error while writing machine interface output */
-       LTTNG_ERR_MI_NOT_IMPLEMENTED     = 93,  /* Mi feature not implemented */
+       /* Internal codes */
+       /// @cond INTERNAL_ERR_CODES
+       LTTNG_ERR_SELECT_SESS = 27, /* Must select a session */
+       LTTNG_ERR_NO_STREAM = 52, /* Index without stream on relay. */
+       LTTNG_ERR_UST_CALIBRATE_FAIL = 54, /* UST calibration failed */
+       LTTNG_ERR_UST_CHAN_ENABLE_FAIL = 61, /* UST enable channel failed */
+       LTTNG_ERR_CHAN_EXIST = 62, /* Channel already exists. */
+       LTTNG_ERR_UST_META_FAIL = 65, /* UST open metadata failed */
+       LTTNG_ERR_UST_STREAM_FAIL = 70, /* UST create stream failed */
+       LTTNG_ERR_SNAPSHOT_NODATA = 71, /* No data in snapshot. */
+       LTTNG_ERR_MI_OUTPUT_TYPE = 91, /* Invalid MI output format */
+       LTTNG_ERR_MI_IO_FAIL = 92, /* IO error while writing machine interface output */
+       LTTNG_ERR_MI_NOT_IMPLEMENTED = 93, /* Mi feature not implemented */
+       LTTNG_ERR_EVENT_EXIST_LOGLEVEL = 100, /* Event enabled with different loglevel */
+       LTTNG_ERR_FILTER_EXIST = 108, /* Filter already exist */
+       LTTNG_ERR_COMMAND_CANCELLED = 128, /* Command cancelled. */
+       LTTNG_ERR_ROTATE_RENAME_FAIL_CONSUMER = 142, /* Rotation rename failure on consumer */
+       LTTNG_ERR_ROTATION_PENDING_LOCAL_FAIL_CONSUMER = 143, /* Rotation pending check (local)
+                                                                failure on consumer */
+       LTTNG_ERR_ROTATION_PENDING_RELAY_FAIL_CONSUMER = 144, /* Rotation pending check (relay)
+                                                                failure on consumer */
+       LTTNG_ERR_MKDIR_FAIL_CONSUMER = 145, /* mkdir failure on consumer */
+       LTTNG_ERR_TRACE_CHUNK_EXISTS_FAIL_CONSUMER = 151, /* failed to query consumer for trace
+                                                            chunk existence */
+       /// @endcond
+
+       /// Success.
+       LTTNG_OK = 10,
+
+       /// Unknown error.
+       LTTNG_ERR_UNK = 11,
+
+       /// Undefined command.
+       LTTNG_ERR_UND = 12,
+
+       /*!
+       \lt_obj_c_session already
+       \link lttng_session::enabled started\endlink (active).
+       */
+       LTTNG_ERR_SESSION_STARTED = 13,
+
+       /// Unknown \lt_obj_domain.
+       LTTNG_ERR_UNKNOWN_DOMAIN = 14,
+
+       /// Unsupported operation.
+       LTTNG_ERR_NOT_SUPPORTED = 15,
+
+       /// No \lt_obj_session found.
+       LTTNG_ERR_NO_SESSION = 16,
+
+       /// Failed to create a directory.
+       LTTNG_ERR_CREATE_DIR_FAIL = 17,
+
+       /// Failed to create a \lt_obj_session.
+       LTTNG_ERR_SESSION_FAIL = 18,
+
+       /*!
+       No available
+       \ref api-gen-sessiond-conn "session daemon to connect to".
+       */
+       LTTNG_ERR_NO_SESSIOND = 19,
+
+       /// Failed to set an URL.
+       LTTNG_ERR_SET_URL = 20,
+
+       /// URL already exists.
+       LTTNG_ERR_URL_EXIST = 21,
+
+       /// Unsupported \ref api-channel-buf-scheme "buffering scheme".
+       LTTNG_ERR_BUFFER_NOT_SUPPORTED = 22,
+
+       /// Nonexistent \lt_obj_session name.
+       LTTNG_ERR_SESS_NOT_FOUND = 23,
+
+       /*!
+       A \lt_obj_channel within the given \lt_obj_domain already exists
+       and is configured with another
+       \ref api-channel-buf-scheme "buffering scheme".
+       */
+       LTTNG_ERR_BUFFER_TYPE_MISMATCH = 24,
+
+       /// Fatal error.
+       LTTNG_ERR_FATAL = 25,
+
+       /// Failed to allocate memory.
+       LTTNG_ERR_NOMEM = 26,
+
+       /// \lt_obj_c_session name already exists.
+       LTTNG_ERR_EXIST_SESS = 28,
+
+       /// \lt_obj_c_rer not found.
+       LTTNG_ERR_NO_EVENT = 29,
+
+       /// Failed to connect to Unix socket.
+       LTTNG_ERR_CONNECT_FAIL = 30,
+
+       /// \ref api_session_snapshot "Snapshot" output already exists.
+       LTTNG_ERR_SNAPSHOT_OUTPUT_EXIST = 31,
+
+       /// Permission denied.
+       LTTNG_ERR_EPERM = 32,
+
+       /// Linux kernel tracer isn't available.
+       LTTNG_ERR_KERN_NA = 33,
+
+       /// Incompatible Linux kernel tracer.
+       LTTNG_ERR_KERN_VERSION = 34,
+
+       /// Linux kernel \lt_obj_rer already exists.
+       LTTNG_ERR_KERN_EVENT_EXIST = 35,
+
+       /// Linux kernel tracer: failed to create a \lt_obj_session.
+       LTTNG_ERR_KERN_SESS_FAIL = 36,
+
+       /// Linux kernel \lt_obj_channel already exists.
+       LTTNG_ERR_KERN_CHAN_EXIST = 37,
+
+       /// Failed to create a Linux kernel \lt_obj_channel.
+       LTTNG_ERR_KERN_CHAN_FAIL = 38,
+
+       /// Linux kernel \lt_obj_channel not found.
+       LTTNG_ERR_KERN_CHAN_NOT_FOUND = 39,
+
+       /// Failed to disable a Linux kernel \lt_obj_channel.
+       LTTNG_ERR_KERN_CHAN_DISABLE_FAIL = 40,
+
+       /// Failed to create/enable a Linux kernel \lt_obj_channel.
+       LTTNG_ERR_KERN_CHAN_ENABLE_FAIL = 41,
+
+       /*!
+       Failed to add a context field to be recorded to the event
+       records of a Linux kernel \lt_obj_channel.
+       */
+       LTTNG_ERR_KERN_CONTEXT_FAIL = 42,
+
+       /// Failed to create/enable a Linux kernel \lt_obj_rer.
+       LTTNG_ERR_KERN_ENABLE_FAIL = 43,
+
+       /// Failed to disable a Linux kernel \lt_obj_rer.
+       LTTNG_ERR_KERN_DISABLE_FAIL = 44,
+
+       /// Failed to open a Linux kernel trace metadata stream.
+       LTTNG_ERR_KERN_META_FAIL = 45,
+
+       /*!
+       Linux kernel tracer: failed to
+       \link lttng_start_tracing() start tracing\endlink.
+       */
+       LTTNG_ERR_KERN_START_FAIL = 46,
+
+       /*!
+       Linux kernel tracer: failed to
+       \link lttng_stop_tracing stop tracing\endlink.
+       */
+       LTTNG_ERR_KERN_STOP_FAIL = 47,
+
+       /// Failed to start a Linux kernel consumer daemon.
+       LTTNG_ERR_KERN_CONSUMER_FAIL = 48,
+
+       /// Failed to create a Linux kernel trace data stream.
+       LTTNG_ERR_KERN_STREAM_FAIL = 49,
+
+       /*!
+       The \lt_obj_session never became
+       \link lttng_session::enabled active\endlink.
+       */
+       LTTNG_ERR_START_SESSION_ONCE = 50,
+
+       /*!
+       Failed to take a recording session
+       \ref api_session_snapshot "snapshot".
+       */
+       LTTNG_ERR_SNAPSHOT_FAIL = 51,
+
+       /// Failed to list Linux kernel \lt_obj_rers.
+       LTTNG_ERR_KERN_LIST_FAIL = 53,
+
+       /// User space \lt_obj_rer already enabled.
+       LTTNG_ERR_UST_EVENT_ENABLED = 55,
+
+       /*!
+       User space tracer: failed to
+       \link lttng_create_session_ext() create\endlink a
+       \lt_obj_session.
+       */
+       LTTNG_ERR_UST_SESS_FAIL = 56,
+
+       /// User space \lt_obj_channel already exists.
+       LTTNG_ERR_UST_CHAN_EXIST = 57,
+
+       /*!
+       Failed to
+       \link lttng_enable_channel() create\endlink a user space
+       \lt_obj_channel.
+       */
+       LTTNG_ERR_UST_CHAN_FAIL = 58,
+
+       /// User space \lt_obj_channel not found.
+       LTTNG_ERR_UST_CHAN_NOT_FOUND = 59,
+
+       /*!
+       Failed to \link lttng_disable_channel() disable\endlink
+       a user space \lt_obj_channel.
+       */
+       LTTNG_ERR_UST_CHAN_DISABLE_FAIL = 60,
+
+       /// Failed to create/enable a user space \lt_obj_rer.
+       LTTNG_ERR_UST_ENABLE_FAIL = 63,
+
+       /// Failed to disable a user space \lt_obj_rer.
+       LTTNG_ERR_UST_DISABLE_FAIL = 64,
+
+       /*!
+       User space tracer: failed to
+       \link lttng_start_tracing() start tracing\endlink.
+       */
+       LTTNG_ERR_UST_START_FAIL = 66,
+
+       /*!
+       User space tracer: failed to
+       \link lttng_stop_tracing() stop tracing\endlink.
+       */
+       LTTNG_ERR_UST_STOP_FAIL = 67,
+
+       /// Failed to start a 64-bit user space consumer daemon.
+       LTTNG_ERR_UST_CONSUMER64_FAIL = 68,
+
+       /// Failed to start a 32-bit user space consumer daemon.
+       LTTNG_ERR_UST_CONSUMER32_FAIL = 69,
+
+       /// \lt_obj_c_session has no \lt_obj_channels.
+       LTTNG_ERR_NO_CHANNEL = 72,
+
+       /// \lt_obj_c_session name contains an invalid character.
+       LTTNG_ERR_SESSION_INVALID_CHAR = 73,
+
+       /// Failed to list user space \lt_obj_rers.
+       LTTNG_ERR_UST_LIST_FAIL = 74,
+
+       /// User space \lt_obj_rer already exists.
+       LTTNG_ERR_UST_EVENT_EXIST = 75,
+
+       /// User space \lt_obj_rer not found.
+       LTTNG_ERR_UST_EVENT_NOT_FOUND = 76,
+
+       /*!
+       \link lttng_add_context() Context field\endlink to be recorded
+       to the event records of a user space
+       \lt_obj_channel already exists.
+       */
+       LTTNG_ERR_UST_CONTEXT_EXIST = 77,
+
+       /*!
+       Invalid/unknown
+       \link #lttng_event_context_type context field type\endlink.
+       */
+       LTTNG_ERR_UST_CONTEXT_INVAL = 78,
+
+       /*!
+       A root session daemon is required, but isn't available.
+
+       See \ref api-gen-sessiond-conn "Session daemon connection".
+       */
+       LTTNG_ERR_NEED_ROOT_SESSIOND = 79,
+
+       /*!
+       \lt_obj_c_session is already
+       \link lttng_session::enabled active\endlink (started).
+       */
+       LTTNG_ERR_TRACE_ALREADY_STARTED = 80,
+
+       /*!
+       \lt_obj_c_session is already
+       \link lttng_session::enabled inactive\endlink (stopped).
+       */
+       LTTNG_ERR_TRACE_ALREADY_STOPPED = 81,
+
+       /// Linux kernel instrumentation point type not supported.
+       LTTNG_ERR_KERN_EVENT_ENOSYS = 82,
+
+       /*!
+       A \lt_obj_channel name is required because
+       a non-default channel exists within the selected
+       \lt_obj_session and \lt_obj_domain.
+       */
+       LTTNG_ERR_NEED_CHANNEL_NAME = 83,
+
+       /*!
+       \lt_obj_c_channel name is required because a
+       non-default channel exists within the \lt_obj_session.
+       */
+       LTTNG_ERR_NO_UST = 84,
+
+       /*!
+       \ref api_session_save_load "Recording session configuration file"
+       already exists.
+       */
+       LTTNG_ERR_SAVE_FILE_EXIST = 85,
+
+       /*!
+       I/O error while writing a
+       \ref api_session_save_load "recording session configuration file".
+       */
+       LTTNG_ERR_SAVE_IO_FAIL = 86,
+
+       /*!
+       Invalid
+       \ref api_session_save_load "recording session configuration file".
+       */
+       LTTNG_ERR_LOAD_INVALID_CONFIG = 87,
+
+       /*!
+       I/O error while reading a
+       \ref api_session_save_load "recording session configuration file".
+       */
+       LTTNG_ERR_LOAD_IO_FAIL = 88,
+
+       /*!
+       \ref api_session_save_load "Recording session configuration file"
+       not found.
+       */
+       LTTNG_ERR_LOAD_SESSION_NOENT = 89,
+
+       /*!
+       Maximum total size of all the
+       \ref api_session_snapshot "snapshot" trace files is invalid.
+       */
+       LTTNG_ERR_MAX_SIZE_INVALID = 90,
+
        /* 94 */
        /* 95 */
        /* 96 */
-       LTTNG_ERR_INVALID                = 97,  /* Invalid parameter */
-       LTTNG_ERR_NO_USTCONSUMERD        = 98,  /* No UST consumer detected */
-       LTTNG_ERR_NO_KERNCONSUMERD       = 99,  /* No Kernel consumer detected */
-       LTTNG_ERR_EVENT_EXIST_LOGLEVEL   = 100, /* Event enabled with different loglevel */
-       LTTNG_ERR_URL_DATA_MISS          = 101, /* Missing network data URL */
-       LTTNG_ERR_URL_CTRL_MISS          = 102, /* Missing network control URL */
-       LTTNG_ERR_ENABLE_CONSUMER_FAIL   = 103, /* Enabling consumer failed */
-       LTTNG_ERR_RELAYD_CONNECT_FAIL    = 104, /* lttng-relayd create session failed */
-       LTTNG_ERR_RELAYD_VERSION_FAIL    = 105, /* lttng-relayd not compatible */
-       LTTNG_ERR_FILTER_INVAL           = 106, /* Invalid filter bytecode */
-       LTTNG_ERR_FILTER_NOMEM           = 107, /* Lack of memory for filter bytecode */
-       LTTNG_ERR_FILTER_EXIST           = 108, /* Filter already exist */
-       LTTNG_ERR_NO_CONSUMER            = 109, /* No consumer exist for the session */
-       LTTNG_ERR_EXCLUSION_INVAL        = 110, /* Invalid event exclusion data */
-       LTTNG_ERR_EXCLUSION_NOMEM        = 111, /* Lack of memory while processing event exclusions */
-       LTTNG_ERR_INVALID_EVENT_NAME     = 112, /* Invalid event name */
-       LTTNG_ERR_INVALID_CHANNEL_NAME   = 113, /* Invalid channel name */
-       LTTNG_ERR_PROCESS_ATTR_EXISTS  = 114, /* Process attribute is already tracked */
-       LTTNG_ERR_PROCESS_ATTR_MISSING = 115, /* Process attribute was not tracked */
-       LTTNG_ERR_INVALID_CHANNEL_DOMAIN = 116, /* Invalid channel domain */
-       LTTNG_ERR_OVERFLOW               = 117, /* Overflow occurred. */
-       LTTNG_ERR_SESSION_NOT_STARTED    = 118, /* Session not started */
-       LTTNG_ERR_LIVE_SESSION           = 119, /* Live session unsupported */
-       LTTNG_ERR_PER_PID_SESSION        = 120, /* Per-PID sessions unsupported */
-       LTTNG_ERR_KERN_CONTEXT_UNAVAILABLE = 121, /* Context unavailable on this kernel */
-       LTTNG_ERR_REGEN_STATEDUMP_FAIL   = 122, /* Failed to regenerate the state dump */
-       LTTNG_ERR_REGEN_STATEDUMP_NOMEM  = 123, /* Failed to regenerate the state dump, not enough memory */
-       LTTNG_ERR_NOT_SNAPSHOT_SESSION   = 124, /* Session is not in snapshot mode. */
-       LTTNG_ERR_INVALID_TRIGGER        = 125, /* Invalid trigger provided. */
-       LTTNG_ERR_TRIGGER_EXISTS         = 126, /* Trigger already registered. */
-       LTTNG_ERR_TRIGGER_NOT_FOUND      = 127, /* Trigger not found. */
-       LTTNG_ERR_COMMAND_CANCELLED      = 128, /* Command cancelled. */
-       LTTNG_ERR_ROTATION_PENDING       = 129, /* Rotation already pending for this session. */
-       LTTNG_ERR_ROTATION_NOT_AVAILABLE = 130, /* Rotate feature not available for this type of session (e.g: live) */
-       LTTNG_ERR_ROTATION_SCHEDULE_SET  = 131, /* Schedule type already set for this session. */
-       LTTNG_ERR_ROTATION_SCHEDULE_NOT_SET = 132, /* No schedule of this type set for this session. */
-       LTTNG_ERR_ROTATION_MULTIPLE_AFTER_STOP = 133, /* Already rotated once after a stop. */
-       LTTNG_ERR_ROTATION_WRONG_VERSION   = 134, /* Session rotation not supported by this kernel tracer version */
-       LTTNG_ERR_NO_SESSION_OUTPUT        = 135, /* Session has no output configured. */
-       LTTNG_ERR_ROTATION_NOT_AVAILABLE_RELAY = 136, /* Rotate feature not available on the relay. */
-       LTTNG_ERR_AGENT_TRACING_DISABLED = 137, /* Agent tracing disabled. */
-       LTTNG_ERR_PROBE_LOCATION_INVAL   = 138, /* Invalid userspace probe location. */
-       LTTNG_ERR_ELF_PARSING            = 139, /* ELF parsing error. */
-       LTTNG_ERR_SDT_PROBE_SEMAPHORE    = 140, /* SDT probe guarded by a semaphore. */
-       LTTNG_ERR_ROTATION_FAIL_CONSUMER = 141, /* Rotation failure on consumer */
-       LTTNG_ERR_ROTATE_RENAME_FAIL_CONSUMER = 142, /* Rotation rename failure on consumer */
-       LTTNG_ERR_ROTATION_PENDING_LOCAL_FAIL_CONSUMER = 143, /* Rotation pending check (local) failure on consumer */
-       LTTNG_ERR_ROTATION_PENDING_RELAY_FAIL_CONSUMER = 144, /* Rotation pending check (relay) failure on consumer */
-       LTTNG_ERR_MKDIR_FAIL_CONSUMER    = 145, /* mkdir failure on consumer */
-       LTTNG_ERR_CHAN_NOT_FOUND         = 146, /* Channel not found */
-       LTTNG_ERR_SNAPSHOT_UNSUPPORTED   = 147, /* Session configuration does not allow the use of snapshots */
-       LTTNG_ERR_SESSION_NOT_EXIST      = 148, /* The session does not exist on the session daemon */
-       LTTNG_ERR_CREATE_TRACE_CHUNK_FAIL_CONSUMER     = 149, /* trace chunk creation failure on consumer */
-       LTTNG_ERR_CLOSE_TRACE_CHUNK_FAIL_CONSUMER      = 150, /* trace chunk close failure on consumer */
-       LTTNG_ERR_TRACE_CHUNK_EXISTS_FAIL_CONSUMER     = 151, /* failed to query consumer for trace chunk existence */
-       LTTNG_ERR_INVALID_PROTOCOL                     = 152, /* a protocol error occurred */
-       LTTNG_ERR_FILE_CREATION_ERROR                  = 153, /* failed to create a file */
-       LTTNG_ERR_TIMER_STOP_ERROR                     = 154, /* failed to stop timer. */
-       LTTNG_ERR_ROTATION_NOT_AVAILABLE_KERNEL = 155, /* Rotation feature not supported by the kernel tracer. */
-       LTTNG_ERR_CLEAR_RELAY_DISALLOWED   = 156, /* LTTng-relayd peer does not allow lttng clear command. */
-       LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY = 157, /* Clearing a session is not supported by the relay daemon. */
-       LTTNG_ERR_CLEAR_FAIL_CONSUMER    = 158, /* Clear failure on consumer */
-       LTTNG_ERR_ROTATION_AFTER_STOP_CLEAR = 159, /* Session was already cleared since it became inactive. */
-       LTTNG_ERR_USER_NOT_FOUND         = 160, /* User not found. */
-       LTTNG_ERR_GROUP_NOT_FOUND        = 161, /* Group not found. */
-       LTTNG_ERR_UNSUPPORTED_DOMAIN     = 162,  /* Unsupported domain used. */
-       LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY = 163, /* Operation does not apply to the process attribute tracker's tracking policy */
-       LTTNG_ERR_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD = 164, /* Error initializing event notifier group notification file descriptor */
-       LTTNG_ERR_INVALID_CAPTURE_EXPRESSION = 165, /* Invalid capture expression. */
-       LTTNG_ERR_EVENT_NOTIFIER_REGISTRATION = 166, /* Error registering event notifier to the tracer. */
-       LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING = 167, /* Error initializing event notifier error accounting. */
-       LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING_FULL = 168, /* Error event notifier error accounting full. */
-       LTTNG_ERR_INVALID_ERROR_QUERY_TARGET = 169, /* Invalid error query target. */
-       LTTNG_ERR_BUFFER_FLUSH_FAILED        = 170, /* Buffer flush failed */
+
+       /// Invalid parameter (unsatisfied precondition).
+       LTTNG_ERR_INVALID = 97,
+
+       /// No user space consumer daemon available.
+       LTTNG_ERR_NO_USTCONSUMERD = 98,
+
+       /// No Linux kernel consumer daemon available.
+       LTTNG_ERR_NO_KERNCONSUMERD = 99,
+
+       /// Missing network data \ref api-session-url "URL".
+       LTTNG_ERR_URL_DATA_MISS = 101,
+
+       /// Missing network control \ref api-session-url "URL".
+       LTTNG_ERR_URL_CTRL_MISS = 102,
+
+       /// Failed to communicate with a consumer daemon.
+       LTTNG_ERR_ENABLE_CONSUMER_FAIL = 103,
+
+       /*!
+       Failed to connect to or communicate with a relay daemon
+       (see \lt_man{lttng-relayd,8}).
+       */
+       LTTNG_ERR_RELAYD_CONNECT_FAIL = 104,
+
+       /// Incompatible relay daemon (see \lt_man{lttng-relayd,8}) version.
+       LTTNG_ERR_RELAYD_VERSION_FAIL = 105,
+
+       /*!
+       Invalid \link lttng_enable_event_with_filter() context and event
+       payload filter expression\endlink.
+       */
+       LTTNG_ERR_FILTER_INVAL = 106,
+
+       /*!
+       Failed to allocate memory for a context and event payload filter
+       object.
+       */
+       LTTNG_ERR_FILTER_NOMEM = 107,
+
+       /// No available consumer daemon.
+       LTTNG_ERR_NO_CONSUMER = 109,
+
+       /*!
+       Invalid event name
+       \link lttng_enable_event_with_exclusions() exclusion\endlink
+       data.
+       */
+       LTTNG_ERR_EXCLUSION_INVAL = 110,
+
+       /// Failed to allocate memory for an event name exclusion object.
+       LTTNG_ERR_EXCLUSION_NOMEM = 111,
+
+       /// Invalid event name condition part of a \lt_obj_rer.
+       LTTNG_ERR_INVALID_EVENT_NAME = 112,
+
+       /// Invalid \lt_obj_channel name.
+       LTTNG_ERR_INVALID_CHANNEL_NAME = 113,
+
+       /*!
+       Process attribute is already part of an
+       \ref api_pais "inclusion set".
+       */
+       LTTNG_ERR_PROCESS_ATTR_EXISTS = 114,
+
+       /*!
+       Process attribute isn't part of an
+       \ref api_pais "inclusion set".
+       */
+       LTTNG_ERR_PROCESS_ATTR_MISSING = 115,
+
+       /// Invalid \lt_obj_domain for \lt_obj_channel.
+       LTTNG_ERR_INVALID_CHANNEL_DOMAIN = 116,
+
+       /// Overflow.
+       LTTNG_ERR_OVERFLOW = 117,
+
+       /*!
+       \lt_obj_c_session isn't
+       \link lttng_session::enabled active\endlink (started).
+       */
+       LTTNG_ERR_SESSION_NOT_STARTED = 118,
+
+       /*!
+       Unsupported LTTng \ref api-session-live-mode "live" recording
+       session mode.
+       */
+       LTTNG_ERR_LIVE_SESSION = 119,
+
+       /*!
+       Unsupported
+       \ref api-channel-per-proc-buf "per-process buffering scheme".
+       */
+       LTTNG_ERR_PER_PID_SESSION = 120,
+
+       /*!
+       \link #lttng_event_context_type Context field type\endlink
+       isn't available on the current Linux kernel.
+       */
+       LTTNG_ERR_KERN_CONTEXT_UNAVAILABLE = 121,
+
+       /*!
+       Failed to \link lttng_regenerate_statedump() regenerate the
+       LTTng state dump event records\endlink.
+       */
+       LTTNG_ERR_REGEN_STATEDUMP_FAIL = 122,
+
+       /*!
+       Failed to allocate memory to \link lttng_regenerate_statedump()
+       regenerate the LTTng state dump event records\endlink.
+       */
+       LTTNG_ERR_REGEN_STATEDUMP_NOMEM = 123,
+
+       /*!
+       \lt_obj_c_session isn't in
+       \ref api-session-snapshot-mode "snapshot mode".
+       */
+       LTTNG_ERR_NOT_SNAPSHOT_SESSION = 124,
+
+       /// Invalid \lt_obj_trigger.
+       LTTNG_ERR_INVALID_TRIGGER = 125,
+
+       /// \lt_obj_c_trigger already exists (registered).
+       LTTNG_ERR_TRIGGER_EXISTS = 126,
+
+       /// \lt_obj_c_trigger not found.
+       LTTNG_ERR_TRIGGER_NOT_FOUND = 127,
+
+       /*!
+       \ref api_session_rotation "Recording session rotation" operation
+       already in progress.
+       */
+       LTTNG_ERR_ROTATION_PENDING = 129,
+
+       /*!
+       \ref api_session_rotation "Recording session rotation" feature
+       isn't available for the \ref api-session-modes "mode" of the
+       given recording session.
+       */
+       LTTNG_ERR_ROTATION_NOT_AVAILABLE = 130,
+
+       /*!
+       \ref api_session_rotation "Recording session rotation" schedule
+       already set.
+       */
+       LTTNG_ERR_ROTATION_SCHEDULE_SET = 131,
+
+       /*!
+       \ref api_session_rotation "Recording session rotation" schedule
+       isn't set.
+       */
+       LTTNG_ERR_ROTATION_SCHEDULE_NOT_SET = 132,
+
+       /*!
+       LTTng already
+       \ref api_session_rotation "archived the current trace chunk" of
+       the recording session since it became
+       \link lttng_session::enabled inactive\endlink (stopped).
+       */
+       LTTNG_ERR_ROTATION_MULTIPLE_AFTER_STOP = 133,
+
+       /*!
+       Linux kernel tracer: unavailable
+       \ref api_session_rotation "recording session rotation" feature.
+       */
+       LTTNG_ERR_ROTATION_WRONG_VERSION = 134,
+
+       /// \lt_obj_c_session has no configured output.
+       LTTNG_ERR_NO_SESSION_OUTPUT = 135,
+
+       /*!
+       Relay daemon: unavailable
+       \ref api_session_rotation "recording session rotation" feature.
+       */
+       LTTNG_ERR_ROTATION_NOT_AVAILABLE_RELAY = 136,
+
+       /// Unavailable logging instrumentation point feature.
+       LTTNG_ERR_AGENT_TRACING_DISABLED = 137,
+
+       /// Invalid user space probe location.
+       LTTNG_ERR_PROBE_LOCATION_INVAL = 138,
+
+       /// Failed to parse ELF file.
+       LTTNG_ERR_ELF_PARSING = 139,
+
+       /*!
+       SystemTap User-level Statically Defined Tracing (USDT) probe
+       guarded by a semaphore.
+       */
+       LTTNG_ERR_SDT_PROBE_SEMAPHORE = 140,
+
+       /*!
+       Consumer daemon failed to perform a
+       \ref api_session_rotation "recording session rotation"
+       operation.
+       */
+       LTTNG_ERR_ROTATION_FAIL_CONSUMER = 141,
+
+       /// \lt_obj_c_channel not found.
+       LTTNG_ERR_CHAN_NOT_FOUND = 146,
+
+       /*!
+       Cannot take a
+       \ref api_session_snapshot "snapshot" with the current
+       recording session configuration.
+       */
+       LTTNG_ERR_SNAPSHOT_UNSUPPORTED = 147,
+
+       /// Nonexistent \lt_obj_session.
+       LTTNG_ERR_SESSION_NOT_EXIST = 148,
+
+       /*!
+       Consumer daemon failed to create a
+       \ref api_session_rotation "trace chunk archive".
+       */
+       LTTNG_ERR_CREATE_TRACE_CHUNK_FAIL_CONSUMER = 149,
+
+       /*!
+       Consumer daemon failed to close a
+       \ref api_session_rotation "trace chunk archive".
+       */
+       LTTNG_ERR_CLOSE_TRACE_CHUNK_FAIL_CONSUMER = 150,
+
+       /// Invalid protocol.
+       LTTNG_ERR_INVALID_PROTOCOL = 152,
+
+       /// Failed to create a file.
+       LTTNG_ERR_FILE_CREATION_ERROR = 153,
+
+       /// Failed to stop a timer.
+       LTTNG_ERR_TIMER_STOP_ERROR = 154,
+
+       /*!
+       Linux kernel tracer:
+       \ref api_session_rotation "recording session rotation" feature
+       isn't available.
+       */
+       LTTNG_ERR_ROTATION_NOT_AVAILABLE_KERNEL = 155,
+
+       /*!
+       The relay daemon (see \lt_man{lttng-relayd,8}) doesn't allow
+       \ref api_session_clear "recording session clearing" operations.
+       */
+       LTTNG_ERR_CLEAR_RELAY_DISALLOWED = 156,
+
+       /*!
+       The relay daemon (see \lt_man{lttng-relayd,8}) doesn't support
+       the
+       \ref api_session_clear "recording session clearing" operation.
+       */
+       LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY = 157,
+
+       /*!
+       Consumer daemon failed to
+       \ref api_session_clear "clear the recording session".
+       */
+       LTTNG_ERR_CLEAR_FAIL_CONSUMER = 158,
+
+       /*!
+       LTTng already
+       \ref api_session_clear "cleared the recording session" since it
+       became \link lttng_session::enabled inactive\endlink (stopped).
+       */
+       LTTNG_ERR_ROTATION_AFTER_STOP_CLEAR = 159,
+
+       /* Unix user not found. */
+       LTTNG_ERR_USER_NOT_FOUND = 160,
+
+       /* Unix group not found. */
+       LTTNG_ERR_GROUP_NOT_FOUND = 161,
+
+       /* Unsupported \lt_obj_domain. */
+       LTTNG_ERR_UNSUPPORTED_DOMAIN = 162,
+
+       /*!
+       Invalid operation considering the policy of the
+       \ref api_pais "process attribute inclusion set".
+       */
+       LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY = 163,
+
+       /*!
+       Failed to initialize the file descriptor of the event notifier
+       group notification.
+       */
+       LTTNG_ERR_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD = 164,
+
+       /// Invalid event field capture expression.
+       LTTNG_ERR_INVALID_CAPTURE_EXPRESSION = 165,
+
+       /// Failed to register the event notifier to the tracer.
+       LTTNG_ERR_EVENT_NOTIFIER_REGISTRATION = 166,
+
+       /// Failed to initialize the event notifier error accounting.
+       LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING = 167,
+
+       /// Event notifier error accouting is full.
+       LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING_FULL = 168,
+
+       /// Invalid error query target.
+       LTTNG_ERR_INVALID_ERROR_QUERY_TARGET = 169,
+
+       /// Failed to flush a buffer.
+       LTTNG_ERR_BUFFER_FLUSH_FAILED = 170,
 
        /* MUST be last element of the manually-assigned section of the enum */
+       /// @cond INTERNAL_ERR_CODES
        LTTNG_ERR_NR,
+       /// @endcond
 
        /* Backward-compatibility assignments */
-       LTTNG_ERR_PID_TRACKED            = LTTNG_ERR_PROCESS_ATTR_EXISTS, /* Backward compat alias */
-       LTTNG_ERR_PID_NOT_TRACKED        = LTTNG_ERR_PROCESS_ATTR_MISSING, /* Backward compat alias */
+       /*!
+       Process attribute is already part of an
+       \ref api_pais "inclusion set".
+
+       @deprecated
+           Use #LTTNG_ERR_PROCESS_ATTR_EXISTS.
+       */
+       LTTNG_ERR_PID_TRACKED = LTTNG_ERR_PROCESS_ATTR_EXISTS,
+
+       /*!
+       Process attribute isn't part of an
+       \ref api_pais "inclusion set".
+
+       @deprecated
+           Use #LTTNG_ERR_PROCESS_ATTR_MISSING.
+        */
+       LTTNG_ERR_PID_NOT_TRACKED = LTTNG_ERR_PROCESS_ATTR_MISSING,
 };
 
-/*
- * Return a human-readable error message for a LTTng error code.
- *
- * Parameter MUST be a negative value or else you'll get a generic message.
- */
-LTTNG_EXPORT extern const char *lttng_strerror(int code);
+/*!
+@brief
+    Returns a human-readable message for the general error code
+    \lt_p{error_code}.
+
+@param[in] error_code
+    Error code (one of the #lttng_error_code enumerators), positive or
+    negative, for which to get a corresponding human-readable message.
+
+@returns
+    Human-readable message which corresponds to \lt_p{error_code}.
+
+@pre
+    \lt_p{error_code} is a valid #lttng_error_code enumerator.
+*/
+LTTNG_EXPORT extern const char *lttng_strerror(int error_code);
+
+/// @}
 
 #ifdef __cplusplus
 }
index ae3990a29dbad5786fdeaecbc971f9d1b07b067f..51eca4ee7d13e7030dfbbb52f0c417d9076a492a 100644 (file)
@@ -7,8 +7,8 @@
 #ifndef LTTNG_EXPORT_H
 #define LTTNG_EXPORT_H
 #if defined(_WIN32) || defined(__CYGWIN__)
-# define LTTNG_EXPORT
+#define LTTNG_EXPORT
 #else
-# define LTTNG_EXPORT __attribute__((visibility("default")))
+#define LTTNG_EXPORT __attribute__((visibility("default")))
 #endif
 #endif
index dbfe9a7dbde5f94494d646c957765a7b63c33e76..6ae331bdaac7fd084b09d0053e3d6eb410549644 100644 (file)
@@ -12,6 +12,8 @@
 #ifndef LTTNG_H
 #define LTTNG_H
 
+#include <lttng/lttng-export.h>
+
 /* Error codes that can be returned by API calls */
 #include <lttng/lttng-error.h>
 
 #include <lttng/event-expr.h>
 #include <lttng/event-field-value.h>
 #include <lttng/event-rule/event-rule.h>
-#include <lttng/event-rule/log4j-logging.h>
 #include <lttng/event-rule/jul-logging.h>
 #include <lttng/event-rule/kernel-kprobe.h>
 #include <lttng/event-rule/kernel-syscall.h>
-#include <lttng/event-rule/python-logging.h>
 #include <lttng/event-rule/kernel-tracepoint.h>
 #include <lttng/event-rule/kernel-uprobe.h>
+#include <lttng/event-rule/log4j-logging.h>
+#include <lttng/event-rule/python-logging.h>
 #include <lttng/event-rule/user-tracepoint.h>
 #include <lttng/event.h>
 #include <lttng/handle.h>
 #include <lttng/health.h>
 #include <lttng/kernel-probe.h>
+#include <lttng/kernel.h>
 #include <lttng/load.h>
 #include <lttng/location.h>
 #include <lttng/log-level-rule.h>
 #include <lttng/lttng-error.h>
-#include <lttng/lttng-export.h>
 #include <lttng/notification/channel.h>
 #include <lttng/notification/notification.h>
 #include <lttng/rotation.h>
@@ -75,35 +77,79 @@ extern "C" {
 #endif
 
 enum lttng_calibrate_type {
-       LTTNG_CALIBRATE_FUNCTION              = 0,
+       LTTNG_CALIBRATE_FUNCTION = 0,
 };
 
 /* Machine interface output type */
 enum lttng_mi_output_type {
-       LTTNG_MI_XML                          = 1 /* XML output */
+       LTTNG_MI_XML = 1 /* XML output */
 };
 
-#define LTTNG_CALIBRATE_PADDING1           16
+#define LTTNG_CALIBRATE_PADDING1 16
 struct lttng_calibrate {
        enum lttng_calibrate_type type;
 
        char padding[LTTNG_CALIBRATE_PADDING1];
 };
 
-/*
- * Check if a session daemon is alive.
- *
- * Return 1 if alive or 0 if not. On error, returns a negative negative LTTng
- * error code.
- */
+/*!
+@brief
+    Returns whether or not liblttng-ctl is able to connect to a
+    listening session daemon.
+
+@ingroup api_gen
+
+How this function tries to
+\ref api-gen-sessiond-conn "connect to a session daemon" depends on the
+current Unix tracing group (initially \c tracing) of the library. Set
+the tracing group with lttng_set_tracing_group().
+
+@returns
+    @parblock
+    One of:
+
+    <dl>
+      <dt>1</dt>
+      <dd>
+       liblttng-ctl is able to connect to a session daemon.
+
+      <dt>0
+      <dd>
+       liblttng-ctl isn't able to connect to a session daemon.
+
+      <dt>Negative value
+      <dd>
+       Error: a negative #lttng_error_code enumerator.
+    </dl>
+    @endparblock
+
+@sa lttng_set_tracing_group() --
+    Sets the current Unix tracing group of liblttng-ctl.
+*/
 LTTNG_EXPORT extern int lttng_session_daemon_alive(void);
 
-/*
- * Set the tracing group for the *current* flow of execution.
- *
- * On success, returns 0 else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_set_tracing_group(const char *name);
+/*!
+@brief
+    Sets the current Unix tracing group of liblttng-ctl to \lt_p{group}.
+
+@ingroup api_gen
+
+How the liblttng-ctl functions
+\ref api-gen-sessiond-conn "connect to a session daemon" depends on
+the current Unix tracing group (initially \c tracing) of the library.
+
+@param[in] group
+    New Unix tracing group of liblttng-ctl.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_not_null{group}
+@pre
+    \lt_p{group} names an existing Unix group.
+*/
+LTTNG_EXPORT extern int lttng_set_tracing_group(const char *group);
 
 /*
  * This call registers an "outside consumer" for a session and an lttng domain.
@@ -116,33 +162,126 @@ LTTNG_EXPORT extern int lttng_set_tracing_group(const char *name);
  * Return 0 on success else a negative LTTng error code.
  */
 LTTNG_EXPORT extern int lttng_register_consumer(struct lttng_handle *handle,
-               const char *socket_path);
+                                               const char *socket_path);
 
-/*
- * Start tracing for *all* domain(s) in the session.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Makes the recording session named \lt_p{session_name} active,
+    starting all the tracers for its
+    \ref api-channel-channel "channels".
+
+@ingroup api_session
+
+@note
+    An #LTTNG_ACTION_TYPE_START_SESSION trigger action can also activate
+    (start) a recording session.
+
+@param[in] session_name
+    Name of the recording session to activate/start.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_sess_inactive{session_name}
+
+@sa lttng_stop_tracing() --
+    Stops a recording session.
+@sa \lt_man{lttng-start,1}
+*/
 LTTNG_EXPORT extern int lttng_start_tracing(const char *session_name);
 
-/*
- * Stop tracing for *all* domain(s) in the session.
- *
- * This call will wait for data availability for each domain of the session so
- * this can take an abritrary amount of time. However, when returning you have
- * the guarantee that the data is ready to be read and analyze. Use the
- * _no_wait call below to avoid this behavior.
- *
- * The session_name can't be NULL.
- *
- * Return 0 on success else a negative LTTng error code.
- */
+/*!
+@brief
+    Makes the recording session named \lt_p{session_name} inactive,
+    stopping all the tracers for its
+    \ref api-channel-channel "channels", blocking until the operation
+    completes.
+
+@ingroup api_session
+
+This function blocks until the trace data of the
+recording session named \lt_p{session_name} is valid. Use
+lttng_stop_tracing_no_wait() to avoid a blocking call.
+
+If LTTng \ref api_session_rotation "archived the current trace chunk"
+of the recording session named \lt_p{session_name} at least
+once during its lifetime, then this function renames the current trace
+chunk subdirectory. Although it's safe to
+read the content of this renamed subdirectory while the recording
+session remains inactive, it's \em not a trace chunk archive: you need to
+\link lttng_destroy_session_ext() destroy\endlink the recording session
+or a rotation needs to occur to archive it.
+
+@note
+    An #LTTNG_ACTION_TYPE_STOP_SESSION trigger action can also
+    deactivate (stop) a recording session.
+
+@param[in] session_name
+    Name of the recording session to deactivate/stop.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_sess_active{session_name}
+
+@sa lttng_stop_tracing_no_wait() --
+    Deactivates a recording session without waiting for the operation
+    to complete.
+@sa lttng_start_tracing() --
+    Starts a recording session.
+@sa \lt_man{lttng-stop,1}
+*/
 LTTNG_EXPORT extern int lttng_stop_tracing(const char *session_name);
 
-/*
- * Behave exactly like lttng_stop_tracing but does not wait for data
- * availability.
- */
+/*!
+@brief
+    Makes the recording session named \lt_p{session_name} inactive,
+    stopping all the tracers for its
+    \ref api-channel-channel "channels" without waiting for the
+    operation to complete.
+
+@ingroup api_session
+
+Unlike lttng_stop_tracing(), this function does \em not block until
+the operation is complete: it returns immediately. This
+means the traces(s) of the recording session might not be valid when
+this function returns, and there's no way to know when it/they become
+valid.
+
+@note
+    An #LTTNG_ACTION_TYPE_STOP_SESSION trigger action can also
+    deactivate (stop) a recording session.
+
+@param[in] session_name
+    Name of the recording session to deactivate/stop.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_sess_active{session_name}
+@pre
+    No deactivation operation is in progress for the recording session
+    named \lt_p{session_name}.
+
+@sa lttng_stop_tracing() --
+    Deactivates a recording session, blocking until the operation
+    completes.
+@sa lttng_start_tracing() --
+    Starts a recording session.
+@sa \lt_man{lttng-stop,1}
+*/
 LTTNG_EXPORT extern int lttng_stop_tracing_no_wait(const char *session_name);
 
 /*
@@ -152,7 +291,7 @@ LTTNG_EXPORT extern int lttng_stop_tracing_no_wait(const char *session_name);
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wshadow"
 LTTNG_EXPORT extern int lttng_calibrate(struct lttng_handle *handle,
-               struct lttng_calibrate *calibrate);
+                                       struct lttng_calibrate *calibrate);
 #pragma GCC diagnostic pop
 
 /*
@@ -179,42 +318,180 @@ LTTNG_EXPORT extern int lttng_calibrate(struct lttng_handle *handle,
  *
  * Return 0 on success else a negative LTTng error code.
  */
-LTTNG_EXPORT extern int lttng_set_consumer_url(struct lttng_handle *handle,
-               const char *control_url, const char *data_url);
+LTTNG_EXPORT extern int
+lttng_set_consumer_url(struct lttng_handle *handle, const char *control_url, const char *data_url);
 
-/*
- * For a given session name, this call checks if the data is ready to be read
- * or is still being extracted by the consumer(s) (pending) hence not ready to
- * be used by any readers.
- *
- * Return 0 if there is _no_ data pending in the buffers thus having a
- * guarantee that the data can be read safely. Else, return 1 if there is still
- * traced data is pending. On error, a negative value is returned and readable
- * by lttng_strerror().
- */
+/*!
+@brief
+    Returns whether or not you may read the traces of the recording
+    session named \lt_p{session_name}.
+
+@ingroup api_session
+
+It's not safe to read the traces of a recording session while
+LTTng is still consuming data from the tracers for its
+\ref api-channel-channel "channels".
+
+This function makes it possible to know when LTTng is done consuming
+trace data from tracers for the channels of the recording session
+named \lt_p{session_name}.
+
+@param[in] session_name
+    Name of the recording session of which get whether or not
+    you may read its traces.
+
+@returns
+    @parblock
+    One of:
+
+    <dl>
+      <dt>0
+      <dd>
+       You may read the traces of the recording session named
+       \lt_p{session_name}.
+
+       This remains true as long as the recording session remains
+       \link lttng_session::enabled inactive\endlink (stopped).
+
+      <dt>1</dt>
+      <dd>
+       You may \em not read the traces of the recording session named
+       \lt_p{session_name}.
+
+      <dt>Negative value
+      <dd>
+       Error: a negative #lttng_error_code enumerator.
+    </dl>
+    @endparblock
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_sess_inactive{session_name}
+*/
 LTTNG_EXPORT extern int lttng_data_pending(const char *session_name);
 
 /*
- * Deprecated, replaced by lttng_regenerate_metadata.
+ * Gets the status of the kernel tracer.
+ *
+ * Sets the value of the argument, which must not be null.
  */
-LTTNG_DEPRECATED("Use lttng_regenerate_metadata")
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_get_kernel_tracer_status(enum lttng_kernel_tracer_status *status);
+
+/*!
+@brief
+    Regenerates the metadata streams of the recording session named
+    \lt_p{session_name}.
+
+@ingroup api_session
+
+@deprecated
+    Use lttng_regenerate_metadata().
+
+@param[in] session_name
+    Name of the recording session of which to regenerate the metadata
+    streams.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+*/
+/// @cond DEPRECATED
+LTTNG_DEPRECATED()
+/// @endcond
 LTTNG_EXPORT extern int lttng_metadata_regenerate(const char *session_name);
 
-/*
- * Trigger the regeneration of the metadata for a session.
- * The new metadata overwrite the previous one locally or remotely (through
- * the lttng-relayd). Only kernel, per-uid and non-live sessions are supported.
- * Return 0 on success, a negative LTTng error code on error.
- */
+/*!
+@brief
+    Regenerates the metadata streams of the recording session named
+    \lt_p{session_name}.
+
+@ingroup api_session
+
+Use this function to resample the offset between the monotonic clock and
+the wall time of the system, and then regenerate (overwrite) all the
+metadata stream files (local or remote) of the recording session
+named \lt_p{session_name}.
+
+More specifically, you may want to resample the wall time following a
+major <a href="https://en.wikipedia.org/wiki/Network_Time_Protocol">NTP</a>
+correction. As such, LTTng can trace a system booting with an incorrect
+wall time before its wall time is NTP-corrected. Regenerating the
+metadata of a recording session ensures that trace readers
+can accurately determine the event record timestamps relative to the
+Unix epoch.
+
+Note that if you plan to \ref api_session_rotation "rotate" the
+recording session named \lt_p{session_name}, this function only
+regenerates the metadata stream files of the \em current and \em next
+trace chunks.
+
+See the preconditions of this function which show important limitations.
+
+@param[in] session_name
+    Name of the recording session of which to regenerate the metadata
+    streams.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@pre
+    The recording session named \lt_p{session_name} was \em not created
+    in \ref api-session-live-mode "live mode".
+@pre
+    All the \ref api-channel-channel "channels" of the recording session
+    named \lt_p{session_name} use a
+    \ref api-channel-per-user-buf "per-user buffering scheme".
+
+@sa lttng_regenerate_statedump() --
+    Regenerates the state dump event records of a recording session.
+@sa \lt_man{lttng-regenerate,1}
+*/
 LTTNG_EXPORT extern int lttng_regenerate_metadata(const char *session_name);
 
-/*
- * Trigger the regeneration of the statedump for a session. The new statedump
- * information is appended to the currently active trace, the session needs to
- * be active.
- *
- * Return 0 on success, a negative LTTng error code on error.
- */
+/*!
+@brief
+    Regenerates the state dump event records of the recording session
+    named \lt_p{session_name}.
+
+@ingroup api_session
+
+Use this function to collect up-to-date state dump information and
+append corresponding event records to the
+\ref api-channel-channel "sub-buffers" of the recording session named
+\lt_p{session_name}.
+
+This is particularly useful if you created the recording session in
+\ref api-session-snapshot-mode "snapshot mode"
+or if LTTng \ref api_session_rotation "rotates" trace files for one of
+its \ref api-channel-channel "channels": in both cases, the state dump
+information may be lost.
+
+@param[in] session_name
+    Name of the recording session of which to regenerate the
+    state dump event records.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+
+@sa lttng_regenerate_metadata() --
+    Regenerates the metadata streams of a recording session.
+@sa \lt_man{lttng-regenerate,1}
+*/
 LTTNG_EXPORT extern int lttng_regenerate_statedump(const char *session_name);
 
 #ifdef __cplusplus
index 3364704eed12ccad98f410876970df69d92c3edd..173b3dcdc3333c873c645b66d098c71565cfa000 100644 (file)
@@ -8,12 +8,15 @@
 #ifndef LTTNG_NOTIFICATION_CHANNEL_INTERNAL_H
 #define LTTNG_NOTIFICATION_CHANNEL_INTERNAL_H
 
-#include <lttng/notification/channel.h>
 #include <common/macros.hpp>
+#include <common/make-unique-wrapper.hpp>
 #include <common/payload.hpp>
-#include <stdint.h>
-#include <stdbool.h>
+
+#include <lttng/notification/channel.h>
+
 #include <pthread.h>
+#include <stdbool.h>
+#include <stdint.h>
 #include <urcu/list.h>
 
 /*
@@ -82,6 +85,11 @@ struct pending_notification {
  * in the pending_notifications list.
  */
 struct lttng_notification_channel {
+       using uptr = std::unique_ptr<
+               lttng_notification_channel,
+               lttng::memory::create_deleter_class<lttng_notification_channel,
+                                                   lttng_notification_channel_destroy>::deleter>;
+
        pthread_mutex_t lock;
        int socket;
        struct {
index 030c88cbd3e1829ee1db2bd34fb2dc6bf43e3d4a..dad62b0b3abf730ced0b63151d9f9fa6e01c2591 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_NOTIFICATION_CHANNEL_H
 
 #include <lttng/lttng-export.h>
+
 #include <stdbool.h>
 
 #ifdef __cplusplus
@@ -58,8 +59,8 @@ enum lttng_notification_channel_status {
  * The returned lttng_notification_channel must be destroyed using
  * the lttng_notification_channel_destroy() function.
  */
-LTTNG_EXPORT extern struct lttng_notification_channel *lttng_notification_channel_create(
-               struct lttng_endpoint *endpoint);
+LTTNG_EXPORT extern struct lttng_notification_channel *
+lttng_notification_channel_create(struct lttng_endpoint *endpoint);
 
 /*
  * Get the next notification received on a notification channel.
@@ -83,9 +84,8 @@ LTTNG_EXPORT extern struct lttng_notification_channel *lttng_notification_channe
  *     that caused the reception to fail.
  */
 LTTNG_EXPORT extern enum lttng_notification_channel_status
-lttng_notification_channel_get_next_notification(
-               struct lttng_notification_channel *channel,
-               struct lttng_notification **notification);
+lttng_notification_channel_get_next_notification(struct lttng_notification_channel *channel,
+                                                struct lttng_notification **notification);
 
 /*
  * Check whether a notification is pending on a notification channel.
@@ -104,9 +104,8 @@ lttng_notification_channel_get_next_notification(
  *     provided.
  */
 LTTNG_EXPORT extern enum lttng_notification_channel_status
-lttng_notification_channel_has_pending_notification(
-               struct lttng_notification_channel *channel,
-               bool *notification_pending);
+lttng_notification_channel_has_pending_notification(struct lttng_notification_channel *channel,
+                                                   bool *notification_pending);
 
 /*
  * Subscribe to notifications of a condition through a notification channel.
@@ -124,9 +123,8 @@ lttng_notification_channel_has_pending_notification(
  *     client was already subscribed to the condition through this channel.
  */
 LTTNG_EXPORT extern enum lttng_notification_channel_status
-lttng_notification_channel_subscribe(
-               struct lttng_notification_channel *channel,
-               const struct lttng_condition *condition);
+lttng_notification_channel_subscribe(struct lttng_notification_channel *channel,
+                                    const struct lttng_condition *condition);
 
 /*
  * Unsubscribe to notifications of a condition through a notification channel.
@@ -144,15 +142,14 @@ lttng_notification_channel_subscribe(
  *     client was not already subscribed to the condition through this channel.
  */
 LTTNG_EXPORT extern enum lttng_notification_channel_status
-lttng_notification_channel_unsubscribe(
-               struct lttng_notification_channel *channel,
-               const struct lttng_condition *condition);
+lttng_notification_channel_unsubscribe(struct lttng_notification_channel *channel,
+                                      const struct lttng_condition *condition);
 
 /*
  * Closes and destroys (frees) a notification channel.
  */
-LTTNG_EXPORT extern void lttng_notification_channel_destroy(
-               struct lttng_notification_channel *channel);
+LTTNG_EXPORT extern void
+lttng_notification_channel_destroy(struct lttng_notification_channel *channel);
 
 #ifdef __cplusplus
 }
index 9557c38b88cb738e17ead59d3cc0217ee80474ed..36b3d7f3839ba6cd06ea0974324a84d2a51cefbc 100644 (file)
@@ -8,16 +8,25 @@
 #ifndef LTTNG_NOTIFICATION_INTERNAL_H
 #define LTTNG_NOTIFICATION_INTERNAL_H
 
-#include <lttng/notification/notification.h>
 #include <common/macros.hpp>
-#include <stdint.h>
+#include <common/make-unique-wrapper.hpp>
+
+#include <lttng/notification/notification.h>
+
+#include <memory>
 #include <stdbool.h>
+#include <stdint.h>
 #include <sys/types.h>
 
 struct lttng_payload;
 struct lttng_payload_view;
 
 struct lttng_notification {
+       using uptr = std::unique_ptr<
+               lttng_notification,
+               lttng::memory::create_deleter_class<lttng_notification,
+                                                   lttng_notification_destroy>::deleter>;
+
        struct lttng_trigger *trigger;
        struct lttng_evaluation *evaluation;
 };
@@ -29,23 +38,21 @@ struct lttng_notification_comm {
        char payload[];
 } LTTNG_PACKED;
 
-struct lttng_notification *lttng_notification_create(
-               struct lttng_trigger *trigger,
-               struct lttng_evaluation *evaluation);
+struct lttng_notification *lttng_notification_create(struct lttng_trigger *trigger,
+                                                    struct lttng_evaluation *evaluation);
 
 int lttng_notification_serialize(const struct lttng_notification *notification,
-               struct lttng_payload *payload);
+                                struct lttng_payload *payload);
 
-ssize_t lttng_notification_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_notification **notification);
+ssize_t lttng_notification_create_from_payload(struct lttng_payload_view *view,
+                                              struct lttng_notification **notification);
 
-const struct lttng_condition *lttng_notification_get_const_condition(
-               const struct lttng_notification *notification);
-const struct lttng_evaluation *lttng_notification_get_const_evaluation(
-               const struct lttng_notification *notification);
+const struct lttng_condition *
+lttng_notification_get_const_condition(const struct lttng_notification *notification);
+const struct lttng_evaluation *
+lttng_notification_get_const_evaluation(const struct lttng_notification *notification);
 
-const struct lttng_trigger *lttng_notification_get_const_trigger(
-               const struct lttng_notification *notification);
+const struct lttng_trigger *
+lttng_notification_get_const_trigger(const struct lttng_notification *notification);
 
 #endif /* LTTNG_NOTIFICATION_INTERNAL_H */
index d1c088fecc8973fc5f9bcabfca8df065e4b6793c..c434f11321fc27e017887d90696684c53448cdb5 100644 (file)
@@ -30,8 +30,8 @@ struct lttng_notification;
  *
  * Returns an lttng_condition object on success, NULL on error.
  */
-LTTNG_EXPORT extern const struct lttng_condition *lttng_notification_get_condition(
-               struct lttng_notification *notification);
+LTTNG_EXPORT extern const struct lttng_condition *
+lttng_notification_get_condition(struct lttng_notification *notification);
 
 /*
  * Get a notification's condition's evaluation.
@@ -45,8 +45,8 @@ LTTNG_EXPORT extern const struct lttng_condition *lttng_notification_get_conditi
  *
  * Returns an lttng_evaluation object on success, NULL on error.
  */
-LTTNG_EXPORT extern const struct lttng_evaluation *lttng_notification_get_evaluation(
-               struct lttng_notification *notification);
+LTTNG_EXPORT extern const struct lttng_evaluation *
+lttng_notification_get_evaluation(struct lttng_notification *notification);
 
 /*
  * Get a notification's origin trigger.
@@ -57,8 +57,8 @@ LTTNG_EXPORT extern const struct lttng_evaluation *lttng_notification_get_evalua
  *
  * Returns an lttng_trigger object on success, NULL on error.
  */
-LTTNG_EXPORT extern const struct lttng_trigger *lttng_notification_get_trigger(
-               struct lttng_notification *notification);
+LTTNG_EXPORT extern const struct lttng_trigger *
+lttng_notification_get_trigger(struct lttng_notification *notification);
 
 /*
  * Destroys (frees) a notification. The notification's condition and evaluation
index a02ae4cdc1229a627226e74991cebb49887b4820..8416d6bcff29f4526836a7b3682c688cf12e26c4 100644 (file)
@@ -1,6 +1,3 @@
-#ifndef LTTNG_REF_INTERNAL_H
-#define LTTNG_REF_INTERNAL_H
-
 /*
  * LTTng - Non thread-safe reference counting
  *
  *
  */
 
+#ifndef LTTNG_REF_INTERNAL_H
+#define LTTNG_REF_INTERNAL_H
+
+#include <common/macros.hpp>
+
+#include <urcu/urcu.h>
 
-typedef void (*lttng_release_func)(void *);
+using lttng_release_func = void (*)(void *);
 
 struct lttng_ref {
        unsigned long count;
        lttng_release_func release;
 };
 
-static inline
-void lttng_ref_init(struct lttng_ref *ref, lttng_release_func release)
+static inline void lttng_ref_init(struct lttng_ref *ref, lttng_release_func release)
 {
        LTTNG_ASSERT(ref);
        ref->count = 1;
        ref->release = release;
 }
 
-static inline
-void lttng_ref_get(struct lttng_ref *ref)
+static inline void lttng_ref_get(struct lttng_ref *ref)
 {
        LTTNG_ASSERT(ref);
        ref->count++;
@@ -35,8 +36,7 @@ void lttng_ref_get(struct lttng_ref *ref)
        LTTNG_ASSERT(ref->count);
 }
 
-static inline
-void lttng_ref_put(struct lttng_ref *ref)
+static inline void lttng_ref_put(struct lttng_ref *ref)
 {
        LTTNG_ASSERT(ref);
        /* Underflow check. */
index 076f50a9a71d85c0a8619bc903c180cfb93f7256..dbc66f3456a1e0caf6f2c6eab1f36a4a0e5f5e22 100644 (file)
@@ -8,13 +8,14 @@
 #ifndef LTTNG_ROTATE_INTERNAL_ABI_H
 #define LTTNG_ROTATE_INTERNAL_ABI_H
 
-#include <limits.h>
-#include <stdint.h>
-#include <stdbool.h>
+#include <common/macros.hpp>
 
 #include <lttng/constant.h>
 #include <lttng/rotation.h>
-#include <common/macros.hpp>
+
+#include <limits.h>
+#include <stdbool.h>
+#include <stdint.h>
 
 /*
  * Object returned by the rotate session API.
@@ -70,12 +71,12 @@ struct lttng_rotation_schedules {
  * are then copied to the user's lttng_rotation_handle object.
  */
 
-/* For the LTTNG_ROTATE_SESSION command. */
+/* For the LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION command. */
 struct lttng_rotate_session_return {
        uint64_t rotation_id;
 } LTTNG_PACKED;
 
-/* For the LTTNG_ROTATION_GET_INFO command. */
+/* For the LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO command. */
 struct lttng_rotation_get_info_return {
        /* Represents values defined in enum lttng_rotation_state. */
        int32_t status;
index 08f2a985be806ae26284b124486c9bc5c8e91775..e5b14e8b7101c4bbcd8d2f8eaf0c5d35c4ad2ae9 100644 (file)
@@ -9,10 +9,11 @@
 #ifndef LTTNG_ROTATION_H
 #define LTTNG_ROTATION_H
 
-#include <stdint.h>
 #include <lttng/location.h>
 #include <lttng/lttng-export.h>
 
+#include <stdint.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -102,9 +103,9 @@ struct lttng_rotation_handle;
  * This will issue a request to the session daemon on every call. Hence,
  * the result of this call may change over time.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_handle_get_state(
-               struct lttng_rotation_handle *rotation_handle,
-               enum lttng_rotation_state *rotation_state);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_rotation_handle_get_state(struct lttng_rotation_handle *rotation_handle,
+                               enum lttng_rotation_state *rotation_state);
 
 /*
  * Get the location of the rotation's resulting archive.
@@ -115,15 +116,15 @@ LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_handle_get_state(
  * Note that location will not be set in case of error, or if the session
  * rotation handle has expired.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_handle_get_archive_location(
-               struct lttng_rotation_handle *rotation_handle,
-               const struct lttng_trace_archive_location **location);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_rotation_handle_get_archive_location(struct lttng_rotation_handle *rotation_handle,
+                                          const struct lttng_trace_archive_location **location);
 
 /*
  * Destroy an lttng_rotate_session handle.
  */
-LTTNG_EXPORT extern void lttng_rotation_handle_destroy(
-               struct lttng_rotation_handle *rotation_handle);
+LTTNG_EXPORT extern void
+lttng_rotation_handle_destroy(struct lttng_rotation_handle *rotation_handle);
 
 /*
  * Rotate the output folder of the session.
@@ -139,14 +140,14 @@ LTTNG_EXPORT extern void lttng_rotation_handle_destroy(
  * LTTng error code on error.
  */
 LTTNG_EXPORT extern int lttng_rotate_session(const char *session_name,
-               struct lttng_rotation_immediate_descriptor *descriptor,
-               struct lttng_rotation_handle **rotation_handle);
+                                            struct lttng_rotation_immediate_descriptor *descriptor,
+                                            struct lttng_rotation_handle **rotation_handle);
 
 /*
  * Get the type of a rotation schedule object.
  */
-LTTNG_EXPORT extern enum lttng_rotation_schedule_type lttng_rotation_schedule_get_type(
-               const struct lttng_rotation_schedule *schedule);
+LTTNG_EXPORT extern enum lttng_rotation_schedule_type
+lttng_rotation_schedule_get_type(const struct lttng_rotation_schedule *schedule);
 
 /*
  * Return a newly allocated size-based session rotation schedule or NULL on
@@ -162,24 +163,21 @@ lttng_rotation_schedule_size_threshold_create(void);
  * LTTNG_ROTATION_STATUS_UNAVAILABLE is returned if the value is unset.
  */
 LTTNG_EXPORT extern enum lttng_rotation_status
-lttng_rotation_schedule_size_threshold_get_threshold(
-               const struct lttng_rotation_schedule *schedule,
-               uint64_t *size_threshold_bytes);
+lttng_rotation_schedule_size_threshold_get_threshold(const struct lttng_rotation_schedule *schedule,
+                                                    uint64_t *size_threshold_bytes);
 
 /*
  * Set a session rotation schedule's size threshold.
  */
 LTTNG_EXPORT extern enum lttng_rotation_status
-lttng_rotation_schedule_size_threshold_set_threshold(
-               struct lttng_rotation_schedule *schedule,
-               uint64_t size_threshold_bytes);
+lttng_rotation_schedule_size_threshold_set_threshold(struct lttng_rotation_schedule *schedule,
+                                                    uint64_t size_threshold_bytes);
 
 /*
  * Return a newly allocated periodic session rotation schedule or NULL on
  * error.
  */
-LTTNG_EXPORT extern struct lttng_rotation_schedule *
-lttng_rotation_schedule_periodic_create(void);
+LTTNG_EXPORT extern struct lttng_rotation_schedule *lttng_rotation_schedule_periodic_create(void);
 
 /*
  * Get a time-based session rotation schedule's period.
@@ -187,36 +185,35 @@ lttng_rotation_schedule_periodic_create(void);
  * Returns LTTNG_ROTATION_STATUS_OK on success.
  * LTTNG_ROTATION_STATUS_UNAVAILABLE is returned if the value is unset.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_schedule_periodic_get_period(
-               const struct lttng_rotation_schedule *schedule,
-               uint64_t *period_us);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_rotation_schedule_periodic_get_period(const struct lttng_rotation_schedule *schedule,
+                                           uint64_t *period_us);
 
 /*
  * Set a time-based session rotation schedule's period.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_schedule_periodic_set_period(
-               struct lttng_rotation_schedule *schedule,
-               uint64_t period_us);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_rotation_schedule_periodic_set_period(struct lttng_rotation_schedule *schedule,
+                                           uint64_t period_us);
 
 /*
  * Destroy a rotation schedule.
  */
-LTTNG_EXPORT extern void lttng_rotation_schedule_destroy(
-               struct lttng_rotation_schedule *schedule);
+LTTNG_EXPORT extern void lttng_rotation_schedule_destroy(struct lttng_rotation_schedule *schedule);
 
 /*
  * Destroy a set of rotation schedules. Pointers to any schedule contained
  * in this set become invalid after this call.
  */
-LTTNG_EXPORT extern void lttng_rotation_schedules_destroy(
-               struct lttng_rotation_schedules *schedules);
+LTTNG_EXPORT extern void
+lttng_rotation_schedules_destroy(struct lttng_rotation_schedules *schedules);
 
 /*
  * Get the number of schedules in a schedule set.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_schedules_get_count(
-               const struct lttng_rotation_schedules *schedules,
-               unsigned int *count);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_rotation_schedules_get_count(const struct lttng_rotation_schedules *schedules,
+                                  unsigned int *count);
 
 /*
  * Get a schedule from the set at a given index.
@@ -228,9 +225,8 @@ LTTNG_EXPORT extern enum lttng_rotation_status lttng_rotation_schedules_get_coun
  * Returns a rotation schedule, or NULL on error.
  */
 LTTNG_EXPORT extern const struct lttng_rotation_schedule *
-lttng_rotation_schedules_get_at_index(
-               const struct lttng_rotation_schedules *schedules,
-               unsigned int index);
+lttng_rotation_schedules_get_at_index(const struct lttng_rotation_schedules *schedules,
+                                     unsigned int index);
 
 /*
  * Add a session rotation schedule to a session.
@@ -242,9 +238,9 @@ lttng_rotation_schedules_get_at_index(
  * LTTNG_ROTATION_STATUS_SCHEDULE_ALREADY_SET if a rotation of the same type
  * is already set.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_session_add_rotation_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedule *schedule);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_session_add_rotation_schedule(const char *session_name,
+                                   const struct lttng_rotation_schedule *schedule);
 
 /*
  * Remove a session rotation schedule from a session.
@@ -253,18 +249,18 @@ LTTNG_EXPORT extern enum lttng_rotation_status lttng_session_add_rotation_schedu
  * LTTNG_ROTATION_STATUS_SCHEDULE_INVALID if the provided schedule is
  * not set.
  */
-LTTNG_EXPORT extern enum lttng_rotation_status lttng_session_remove_rotation_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedule *schedule);
+LTTNG_EXPORT extern enum lttng_rotation_status
+lttng_session_remove_rotation_schedule(const char *session_name,
+                                      const struct lttng_rotation_schedule *schedule);
 
 /*
  * Get the rotation schedules associated with a given session.
  *
  * Returns LTTNG_OK on success, or a negative lttng error code on error.
  */
-LTTNG_EXPORT extern int lttng_session_list_rotation_schedules(
-               const char *session_name,
-               struct lttng_rotation_schedules **schedules);
+LTTNG_EXPORT extern int
+lttng_session_list_rotation_schedules(const char *session_name,
+                                     struct lttng_rotation_schedules **schedules);
 
 #ifdef __cplusplus
 }
index 6b2bb9433f6008a12f98f260eea53dab9a121b77..4b8343bdb9043f2bec23b2d21aefd2ee5c5122cb 100644 (file)
@@ -8,11 +8,12 @@
 #ifndef LTTNG_SAVE_INTERNAL_ABI_H
 #define LTTNG_SAVE_INTERNAL_ABI_H
 
-#include <limits.h>
-#include <stdint.h>
+#include <common/macros.hpp>
 
 #include <lttng/constant.h>
-#include <common/macros.hpp>
+
+#include <limits.h>
+#include <stdint.h>
 
 /*
  * Object used by the save_session API. This is opaque to the public library.
index d28fdffcdc062c4b77596f7f5ed0e2e931a72de0..6120467a78ffa7ac5f6d1ef8f2920a069eff617c 100644 (file)
@@ -30,39 +30,36 @@ LTTNG_EXPORT extern struct lttng_save_session_attr *lttng_save_session_attr_crea
  */
 LTTNG_EXPORT extern void lttng_save_session_attr_destroy(struct lttng_save_session_attr *output);
 
-
 /*
  * Save session attribute getter family functions.
  */
 
 /* Return session name. NULL indicated all sessions must be saved. */
-LTTNG_EXPORT extern const char *lttng_save_session_attr_get_session_name(
-       struct lttng_save_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_save_session_attr_get_session_name(struct lttng_save_session_attr *attr);
 /*
  * Return destination URL. A NULL value indicates the default session
  * configuration location. The URL format used is documented in lttng(1).
  * NULL indicates that the default session configuration path is used.
  */
-LTTNG_EXPORT extern const char *lttng_save_session_attr_get_output_url(
-       struct lttng_save_session_attr *attr);
+LTTNG_EXPORT extern const char *
+lttng_save_session_attr_get_output_url(struct lttng_save_session_attr *attr);
 /*
  * Return the configuration overwrite attribute. This attribute indicates
  * whether or not existing configuration files must be overwritten.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_get_overwrite(
-       struct lttng_save_session_attr *attr);
+LTTNG_EXPORT extern int lttng_save_session_attr_get_overwrite(struct lttng_save_session_attr *attr);
 /*
  * Return the omit name configuration attribute. This attribute indicates
  * whether or not the saved sessions' names should be omitted.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_get_omit_name(
-       struct lttng_save_session_attr *attr);
+LTTNG_EXPORT extern int lttng_save_session_attr_get_omit_name(struct lttng_save_session_attr *attr);
 /*
  * Return the omit output configuration attribute. This attribute indicates
  * whether or not the saved sessions' output configuration should be omitted.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_get_omit_output(
-       struct lttng_save_session_attr *attr);
+LTTNG_EXPORT extern int
+lttng_save_session_attr_get_omit_output(struct lttng_save_session_attr *attr);
 
 /*
  * Save session attribute setter family functions.
@@ -75,33 +72,34 @@ LTTNG_EXPORT extern int lttng_save_session_attr_get_omit_output(
  * Set the name of the session to save. A NULL name means all sessions
  * known to the session daemon will be saved.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_set_session_name(
-       struct lttng_save_session_attr *attr, const char *session_name);
+LTTNG_EXPORT extern int
+lttng_save_session_attr_set_session_name(struct lttng_save_session_attr *attr,
+                                        const char *session_name);
 /*
  * Set the URL of the session configuration to save. A NULL value indicates the
  * use of the default location being the session one. The URL's format is is
  * documented in lttng(1).
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_set_output_url(
-       struct lttng_save_session_attr *attr, const char *url);
+LTTNG_EXPORT extern int lttng_save_session_attr_set_output_url(struct lttng_save_session_attr *attr,
+                                                              const char *url);
 /*
  * Set the overwrite attribute. If set to true, files of the same name as the
  * current session configuration URL will be overwritten.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_set_overwrite(
-       struct lttng_save_session_attr *attr, int overwrite);
+LTTNG_EXPORT extern int lttng_save_session_attr_set_overwrite(struct lttng_save_session_attr *attr,
+                                                             int overwrite);
 /*
  * Set the omit name attribute. If set to true, the sessions' names are omitted
  * from the resulting session configuration file.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_set_omit_name(
-       struct lttng_save_session_attr *attr, int omit_name);
+LTTNG_EXPORT extern int lttng_save_session_attr_set_omit_name(struct lttng_save_session_attr *attr,
+                                                             int omit_name);
 /*
  * Set the omit output attribute. If set to true, the sessions' output
  * configurations are omitted from the resulting session configuration file.
  */
-LTTNG_EXPORT extern int lttng_save_session_attr_set_omit_output(
-       struct lttng_save_session_attr *attr, int omit_output);
+LTTNG_EXPORT extern int
+lttng_save_session_attr_set_omit_output(struct lttng_save_session_attr *attr, int omit_output);
 
 /*
  * Save session configuration(s).
index c132f5600f66fbe4cd6d77c276b1867b04444c12..a2dd70d5798dcc35f8d3ddc0e997ab79620b6c57 100644 (file)
@@ -8,11 +8,13 @@
 #ifndef LTTNG_SESSION_DESCRIPTOR_INTERNAL_H
 #define LTTNG_SESSION_DESCRIPTOR_INTERNAL_H
 
-#include <lttng/session-descriptor.h>
-#include <lttng/lttng-error.h>
-#include <common/uri.hpp>
-#include <common/dynamic-buffer.hpp>
 #include <common/buffer-view.hpp>
+#include <common/dynamic-buffer.hpp>
+#include <common/uri.hpp>
+
+#include <lttng/lttng-error.h>
+#include <lttng/session-descriptor.h>
+
 #include <stdbool.h>
 
 /* Note that these enums are used as part of the lttnctl protocol. */
@@ -33,52 +35,44 @@ enum lttng_session_descriptor_output_type {
        LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK = 2,
 };
 
-ssize_t lttng_session_descriptor_create_from_buffer(
-               const struct lttng_buffer_view *view,
-               struct lttng_session_descriptor **descriptor);
+ssize_t lttng_session_descriptor_create_from_buffer(const struct lttng_buffer_view *view,
+                                                   struct lttng_session_descriptor **descriptor);
 
-int lttng_session_descriptor_serialize(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_dynamic_buffer *buffer);
+int lttng_session_descriptor_serialize(const struct lttng_session_descriptor *descriptor,
+                                      struct lttng_dynamic_buffer *buffer);
 
 enum lttng_session_descriptor_type
-lttng_session_descriptor_get_type(
-               const struct lttng_session_descriptor *descriptor);
+lttng_session_descriptor_get_type(const struct lttng_session_descriptor *descriptor);
 
 enum lttng_session_descriptor_output_type
-lttng_session_descriptor_get_output_type(
-               const struct lttng_session_descriptor *descriptor);
+lttng_session_descriptor_get_output_type(const struct lttng_session_descriptor *descriptor);
 
 void lttng_session_descriptor_get_local_output_uri(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_uri *local_uri);
+       const struct lttng_session_descriptor *descriptor, struct lttng_uri *local_uri);
 
 void lttng_session_descriptor_get_network_output_uris(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_uri *control,
-               struct lttng_uri *data);
+       const struct lttng_session_descriptor *descriptor,
+       struct lttng_uri *control,
+       struct lttng_uri *data);
 
 unsigned long long
-lttng_session_descriptor_live_get_timer_interval(
-               const struct lttng_session_descriptor *descriptor);
+lttng_session_descriptor_live_get_timer_interval(const struct lttng_session_descriptor *descriptor);
 
-int lttng_session_descriptor_set_session_name(
-               struct lttng_session_descriptor *descriptor,
-               const char *name);
+int lttng_session_descriptor_set_session_name(struct lttng_session_descriptor *descriptor,
+                                             const char *name);
 
 bool lttng_session_descriptor_is_output_destination_initialized(
-               const struct lttng_session_descriptor *descriptor);
+       const struct lttng_session_descriptor *descriptor);
 
 bool lttng_session_descriptor_has_output_directory(
-               const struct lttng_session_descriptor *descriptor);
+       const struct lttng_session_descriptor *descriptor);
 
-enum lttng_error_code lttng_session_descriptor_set_default_output(
-               struct lttng_session_descriptor *descriptor,
-               time_t *session_creation_time,
-               const char *absolute_home_path);
+enum lttng_error_code
+lttng_session_descriptor_set_default_output(struct lttng_session_descriptor *descriptor,
+                                           time_t *session_creation_time,
+                                           const char *absolute_home_path);
 
-int lttng_session_descriptor_assign(
-               struct lttng_session_descriptor *dst_descriptor,
-               const struct lttng_session_descriptor *src_descriptor);
+int lttng_session_descriptor_assign(struct lttng_session_descriptor *dst_descriptor,
+                                   const struct lttng_session_descriptor *src_descriptor);
 
 #endif /* LTTNG_SESSION_DESCRIPTOR_INTERNAL_H */
index 5db04be7e9a959aa7935692e4481f9f3e1d19d03..f4151b3a806d73da2753fb50475f6f48c94386e5 100644 (file)
@@ -8,12 +8,23 @@
 #ifndef LTTNG_SESSION_DESCRIPTOR_H
 #define LTTNG_SESSION_DESCRIPTOR_H
 
-#include <lttng/lttng-export.h>
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+#include <lttng/lttng-export.h>
+
+/*!
+@addtogroup api_session_descr
+@{
+*/
+
+/*!
+@struct lttng_session_descriptor
+
+@brief
+    Recording session descriptor (opaque type).
+*/
 struct lttng_session_descriptor;
 
 /*
@@ -90,91 +101,468 @@ struct lttng_session_descriptor;
  *     default data port, and the 'control_url' host will be used.
  */
 
+/*!
+@brief
+    Return type of recording session descriptor fuctions.
+
+Error status enumerators have a negative value.
+*/
 enum lttng_session_descriptor_status {
-       /* Invalid session descriptor parameter. */
-       LTTNG_SESSION_DESCRIPTOR_STATUS_INVALID = -1,
+       /// Success.
        LTTNG_SESSION_DESCRIPTOR_STATUS_OK = 0,
-       /* Session descriptor parameter is unset. */
+
+       /// Unsatisfied precondition.
+       LTTNG_SESSION_DESCRIPTOR_STATUS_INVALID = -1,
+
+       /// Recording session descriptor property is not set.
        LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET = 1,
 };
 
-/*
- * Create a session descriptor in no-output mode.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
-LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_create(const char *name);
+/*!
+@brief
+    Creates a recording session descriptor to create a no-output,
+    \ref api-session-local-mode "local" recording session
+    named \lt_p{session_name}.
 
-/*
- * Create a session descriptor with a local output destination.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * The 'path' must either be an absolute path or it can be left NULL to
- * use the default local output destination.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+LTTng won't write any trace data for a recording session created from
+the returned descriptor.
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@sa lttng_session_descriptor_local_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-local-mode "local" recording session with an
+    output.
+
+@lt_pre_sess_name_not_auto{session_name}
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_local_create(const char *name, const char *path);
+lttng_session_descriptor_create(const char *session_name);
 
-/*
- * Create a session descriptor with a remote output destination.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * The 'control_url' and 'data_url' must conform to the URL format
- * described above or can be left NULL to use the default network output.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-local-mode "local" recording session
+    named \lt_p{session_name}.
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+@param[in] trace_dir
+    @parblock
+    Absolute path of the directory containing the traces of the
+    recording session you create from the returned descriptor.
+
+    If \c NULL, the output directory is, after calling
+    lttng_create_session_ext(),
+    <code><em>$LTTNG_HOME</em>/lttng-traces/<em>NAME</em>-<em>TS</em></code>,
+    with:
+
+    <dl>
+      <dt><code><em>$LTTNG_HOME</em></code>
+      <dd>
+       The value of the \c LTTNG_HOME environment variable, or
+       of the \c HOME environment variable if \c LTTNG_HOME isn't
+       set.
+
+      <dt><code><em>NAME</em></code>
+      <dd>
+       Recording session name (\lt_p{session_name} if not \c NULL, or
+       an automatically generated name otherwise).
+
+      <dt><code><em>TS</em></code>
+      <dd>
+       \link lttng_session_get_creation_time() Timestamp of the
+       creation\endlink of the recording session using the
+       <code>YYYYmmdd-HHMMSS</code> form.
+    </dl>
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{trace_dir} is a valid path.
+
+@sa lttng_session_descriptor_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-local-mode "local" recording session without an
+    output.
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_network_create(const char *name,
-               const char *control_url, const char *data_url);
+lttng_session_descriptor_local_create(const char *session_name, const char *trace_dir);
 
-/*
- * Create a snapshot session descriptor without a default output.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-net-mode "network streaming" recording session
+    named \lt_p{session_name}.
+
+The valid combinations of \lt_p{control_url} and \lt_p{data_url} are:
+
+<table>
+  <tr>
+    <th>\lt_p{control_url}
+    <th>\lt_p{data_url}
+    <th>Behaviour
+  <tr>
+    <td>\c NULL
+    <td>\c NULL
+    <td>
+      Use \lt_def_net_ctrl_url as \lt_p{control_url}.
+
+      Use \lt_def_net_data_url as \lt_p{data_url}.
+  <tr>
+    <td>\ref api-session-one-port-url "Single-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, and trace directory (if any) of
+      \lt_p{control_url} and the port \lt_def_net_data_port
+      as \lt_p{data_url}.
+  <tr>
+    <td>Single-port output URL
+    <td>
+      Single-port output URL with the exact same protocol, host,
+      and trace directory (if any) as \lt_p{control_url}.
+    <td>
+      Use the specified output URLs.
+  <tr>
+    <td>\ref api-session-two-port-url "Two-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, data port, and trace directory (if any)
+      of \lt_p{control_url} as \lt_p{data_url}.
+</table>
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+@param[in] control_url
+    @parblock
+    One of:
+
+    <dl>
+      <dt>\ref api-session-one-port-url "Single-port output URL"
+      <dd>
+       Indicates where (to which relay daemon; see
+       \lt_man{lttng-relayd,8}) to send the control data.
+
+      <dt>\ref api-session-two-port-url "Two-port output URL"
+      <dd>
+       Indicates where to send the control \em and trace data.
+    </dl>
+
+    If \c NULL, this function uses \lt_def_net_url.
+    @endparblock
+@param[in] data_url
+    @parblock
+    \ref api-session-one-port-url "Single-port output URL" which
+    indicates where to send the trace data.
+
+    May be <code>NULL</code>: see the table above for the default value
+    depending on \lt_p{control_url}.
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    \lt_p{control_url} and \lt_p{data_url} satisfy one of the valid
+    combinations shown in the table above.
+*/
+LTTNG_EXPORT extern struct lttng_session_descriptor *lttng_session_descriptor_network_create(
+       const char *session_name, const char *control_url, const char *data_url);
+
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    named \lt_p{session_name} without an initial output.
+
+A recording session which lttng_create_session_ext() creates from the
+returned descriptor has no initial snapshot output: you need to either
+add one with lttng_snapshot_add_output() or provide one when you take a
+snapshot with lttng_snapshot_record().
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+
+@sa lttng_session_descriptor_snapshot_local_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    with an initial local output.
+@sa lttng_session_descriptor_snapshot_network_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    with an initial remote output.
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_create(const char *name);
+lttng_session_descriptor_snapshot_create(const char *session_name);
 
-/*
- * Create a snapshot session descriptor with a local output destination.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * The 'path' must either be an absolute path or it can be left NULL to
- * use the default local output destination as the default snapshot output.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    named \lt_p{session_name} and having an initial local output.
+
+Using the returned descriptor when you call lttng_create_session_ext()
+to create a snapshot recording session is similar to using a descriptor
+which lttng_session_descriptor_snapshot_create() returns and calling
+lttng_snapshot_add_output() after creating the recording session.
+
+The name of this initial snapshot output is <code>snapshot-0</code>.
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+@param[in] trace_dir
+    @parblock
+    Absolute path of an initial snapshot output.
+
+    If \c NULL, the snapshot output directory is, after calling
+    lttng_create_session_ext(),
+    <code><em>$LTTNG_HOME</em>/lttng-traces/<em>NAME</em>-<em>TS</em></code>,
+    with:
+
+    <dl>
+      <dt><code><em>$LTTNG_HOME</em></code>
+      <dd>
+       The value of the \c LTTNG_HOME environment variable, or
+       of the \c HOME environment variable if \c LTTNG_HOME isn't
+       set.
+
+      <dt><code><em>NAME</em></code>
+      <dd>
+       Recording session name (\lt_p{session_name} if not \c NULL, or
+       an automatically generated name otherwise).
+
+      <dt><code><em>TS</em></code>
+      <dd>
+       \link lttng_session_get_creation_time() Timestamp of the
+       creation\endlink of the recording session using the
+       <code>YYYYmmdd-HHMMSS</code> form.
+    </dl>
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{trace_dir} is a valid path.
+
+@sa lttng_session_descriptor_snapshot_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    without an initial output.
+@sa lttng_session_descriptor_snapshot_network_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    with an initial remote output.
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_local_create(const char *name,
-               const char *path);
+lttng_session_descriptor_snapshot_local_create(const char *session_name, const char *trace_dir);
 
-/*
- * Create a snapshot session descriptor with a remote output destination.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * The 'control_url' and 'data_url' must conform to the URL format
- * described above or can be left NULL to use the default network output as
- * the default snapshot output.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    named \lt_p{session_name} and having an initial remote output.
+
+Using the returned descriptor when you call lttng_create_session_ext()
+to create a snapshot recording session is similar to using a descriptor
+which lttng_session_descriptor_snapshot_create() returns and calling
+lttng_snapshot_add_output() after creating the recording session.
+
+The name of this initial snapshot output is <code>snapshot-0</code>.
+
+The valid combinations of \lt_p{control_url} and \lt_p{data_url} are:
+
+<table>
+  <tr>
+    <th>\lt_p{control_url}
+    <th>\lt_p{data_url}
+    <th>Behaviour
+  <tr>
+    <td>\c NULL
+    <td>\c NULL
+    <td>
+      Use \lt_def_net_ctrl_url as \lt_p{control_url}.
+
+      Use \lt_def_net_data_url as \lt_p{data_url}.
+  <tr>
+    <td>\ref api-session-one-port-url "Single-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, and trace directory (if any) of
+      \lt_p{control_url} and the port \lt_def_net_data_port
+      as \lt_p{data_url}.
+  <tr>
+    <td>Single-port output URL
+    <td>
+      Single-port output URL with the exact same protocol, host,
+      and trace directory (if any) as \lt_p{control_url}.
+    <td>
+      Use the specified output URLs.
+  <tr>
+    <td>\ref api-session-two-port-url "Two-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, data port, and trace directory (if any)
+      of \lt_p{control_url} as \lt_p{data_url}.
+</table>
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+@param[in] control_url
+    @parblock
+    Control data URL of an initial snapshot output.
+
+    One of:
+
+    <dl>
+      <dt>\ref api-session-one-port-url "Single-port output URL"
+      <dd>
+       Indicates where (to which relay daemon; see
+       \lt_man{lttng-relayd,8}) to send the control data.
+
+      <dt>\ref api-session-two-port-url "Two-port output URL"
+      <dd>
+       Indicates where to send the control \em and trace data.
+    </dl>
+
+    If \c NULL, this function uses \lt_def_net_url.
+    @endparblock
+@param[in] data_url
+    @parblock
+    Trace data URL of an initial snapshot output.
+
+    \ref api-session-one-port-url "Single-port output URL" which
+    indicates where to send the trace data.
+
+    May be <code>NULL</code>: see the table above for the default value
+    depending on \lt_p{control_url}.
+    @endparblock
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    \lt_p{control_url} and \lt_p{data_url} satisfy one of the valid
+    combinations shown in the table above.
+
+@sa lttng_session_descriptor_snapshot_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    without an initial output.
+@sa lttng_session_descriptor_snapshot_local_create() --
+    Creates a recording session descriptor to create a
+    \ref api-session-snapshot-mode "snapshot" recording session
+    with an initial local output.
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_network_create(const char *name,
-               const char *control_url, const char *data_url);
+lttng_session_descriptor_snapshot_network_create(const char *session_name,
+                                                const char *control_url,
+                                                const char *data_url);
 
 /*
+ * NOTE: Not documented with Doxygen as what lttng_create_session_ext()
+ * creates from such a descriptor is useless (a live recording session
+ * without any output). Original documentation follows.
+ *
  * Create a live session descriptor without an output.
  *
  * The 'name' parameter can be left NULL to auto-generate a session name.
@@ -188,30 +576,111 @@ lttng_session_descriptor_snapshot_network_create(const char *name,
  * Returns an lttng_session_descriptor instance on success, NULL on error.
  */
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_live_create(
-               const char *name, unsigned long long live_timer_interval_us);
+lttng_session_descriptor_live_create(const char *name, unsigned long long live_timer_interval_us);
 
-/*
- * Create a live session descriptor with a remote output destination.
- *
- * The 'name' parameter can be left NULL to auto-generate a session name.
- *
- * The 'control_url' and 'data_url' must conform to the URL format
- * described above or can be left NULL to use the default network output.
- *
- * The 'live_timer_interval_us' parameter is the live timer's period, specified
- * in microseconds.
- *
- * This parameter can't be 0. There is no default value defined for a live
- * timer's period.
- *
- * Returns an lttng_session_descriptor instance on success, NULL on error.
- */
+/*!
+@brief
+    Creates a recording session descriptor to create a
+    \ref api-session-live-mode "live" recording session
+    named \lt_p{session_name}.
+
+The valid combinations of \lt_p{control_url} and \lt_p{data_url} are:
+
+<table>
+  <tr>
+    <th>\lt_p{control_url}
+    <th>\lt_p{data_url}
+    <th>Behaviour
+  <tr>
+    <td>\c NULL
+    <td>\c NULL
+    <td>
+      Use \lt_def_net_ctrl_url as \lt_p{control_url}.
+
+      Use \lt_def_net_data_url as \lt_p{data_url}.
+  <tr>
+    <td>\ref api-session-one-port-url "Single-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, and trace directory (if any) of
+      \lt_p{control_url} and the port \lt_def_net_data_port
+      as \lt_p{data_url}.
+  <tr>
+    <td>Single-port output URL
+    <td>
+      Single-port output URL with the exact same protocol, host,
+      and trace directory (if any) as \lt_p{control_url}.
+    <td>
+      Use the specified output URLs.
+  <tr>
+    <td>\ref api-session-two-port-url "Two-port output URL"
+    <td>\c NULL
+    <td>
+      Use the protocol, host, data port, and trace directory (if any)
+      of \lt_p{control_url} as \lt_p{data_url}.
+</table>
+
+@param[in] session_name
+    @parblock
+    Recording session name.
+
+    If \c NULL, LTTng automatically generates a recording session name
+    when you call lttng_create_session_ext().
+
+    Call lttng_session_descriptor_get_session_name() with the returned
+    recording session descriptor after successfully calling
+    lttng_create_session_ext() to get the generated name.
+    @endparblock
+@param[in] control_url
+    @parblock
+    One of:
+
+    <dl>
+      <dt>\ref api-session-one-port-url "Single-port output URL"
+      <dd>
+       Indicates where (to which relay daemon; see
+       \lt_man{lttng-relayd,8}) to send the control data.
+
+      <dt>\ref api-session-two-port-url "Two-port output URL"
+      <dd>
+       Indicates where to send the control \em and trace data.
+    </dl>
+
+    If \c NULL, this function uses \lt_def_net_url.
+    @endparblock
+@param[in] data_url
+    @parblock
+    \ref api-session-one-port-url "Single-port output URL" which
+    indicates where to send the trace data.
+
+    May be <code>NULL</code>: see the table above for the default value
+    depending on \lt_p{control_url}.
+    @endparblock
+@param[in] live_timer_period
+    Period (µs) of the \ref api-channel-live-timer "live timers" of all
+    the channels of a recording session which lttng_create_session_ext()
+    creates from the returned descriptor.
+
+@returns
+    @parblock
+    Recording session descriptor on success, or \c NULL on error.
+
+    Destroy the returned descriptor with
+    lttng_session_descriptor_destroy().
+    @endparblock
+
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    \lt_p{control_url} and \lt_p{data_url} satisfy one of the valid
+    combinations shown in the table above.
+@pre
+    \lt_p{live_timer_period}&nbsp;≥&nbsp;1
+*/
 LTTNG_EXPORT extern struct lttng_session_descriptor *
-lttng_session_descriptor_live_network_create(
-               const char *name,
-               const char *control_url, const char *data_url,
-               unsigned long long live_timer_interval_us);
+lttng_session_descriptor_live_network_create(const char *session_name,
+                                            const char *control_url,
+                                            const char *data_url,
+                                            unsigned long long live_timer_period);
 
 /*
  * Get a session descriptor's session name.
@@ -228,19 +697,75 @@ lttng_session_descriptor_live_network_create(
  * NULL, and LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET if the descriptor's
  * name parameter is unset.
  */
+
+/*!
+@brief
+    Sets \lt_p{*session_name} to the name of the recording session
+    which lttng_create_session_ext() created from the recording
+    session descriptor \lt_p{session_descriptor}.
+
+Call this function after successfully calling lttng_create_session_ext()
+when \lt_p{session_descriptor} wasn't created with a specific recording
+session name to get the automatically generated name of the created
+recording session.
+
+@param[in] session_descriptor
+    Recording session descriptor from which lttng_create_session_ext()
+    previously created the recording session of which to get the name.
+@param[out] session_name
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*session_name}
+    to the name of the recording session which
+    lttng_create_session_ext() previously created from
+    \lt_p{session_descriptor}.
+
+    \lt_p{session_descriptor} owns \lt_p{*session_name}.
+
+    \lt_p{*session_name} remains valid until the next recording
+    session descriptor function call with \lt_p{session_descriptor}.
+    @endparblock
+
+@retval #LTTNG_SESSION_DESCRIPTOR_STATUS_OK
+    Success.
+@retval #LTTNG_SESSION_DESCRIPTOR_STATUS_INVALID
+    Unsatisfied precondition.
+@retval #LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET
+    The name property of \lt_p{session_descriptor} is not set.
+
+@lt_pre_not_null{session_descriptor}
+@pre
+    You successfully called lttng_create_session_ext() with
+    \lt_p{session_descriptor}.
+@lt_pre_not_null{session_name}
+*/
 LTTNG_EXPORT extern enum lttng_session_descriptor_status
-lttng_session_descriptor_get_session_name(
-               const struct lttng_session_descriptor *descriptor,
-               const char **name);
+lttng_session_descriptor_get_session_name(const struct lttng_session_descriptor *session_descriptor,
+                                         const char **session_name);
 
-/*
- * Destroy a local lttng_session object.
- *
- * This does not destroy the session on the session daemon; it releases
- * the resources allocated by the descriptor object.
- */
-LTTNG_EXPORT extern void lttng_session_descriptor_destroy(
-               struct lttng_session_descriptor *descriptor);
+/*!
+@brief
+    Destroys the recording session descriptor \lt_p{session_descriptor}.
+
+@note
+    @parblock
+    This function doesn't destroy the recording session which
+    lttng_create_session_ext() created from \lt_p{session_descriptor},
+    but only the descriptor itself.
+
+    Use lttng_destroy_session_ext() to destroy a recording session.
+    @endparblock
+
+@param[in] session_descriptor
+    @parblock
+    Recording session descriptor to destroy.
+
+    May be \c NULL.
+    @endparblock
+*/
+LTTNG_EXPORT extern void
+lttng_session_descriptor_destroy(struct lttng_session_descriptor *session_descriptor);
+
+/// @}
 
 #ifdef __cplusplus
 }
index 7f73b9610dd3adf3c54539e90172f65a19e0bae5..61e65981c6e280e74b2789a1f80e2e453cf1de16 100644 (file)
@@ -8,8 +8,12 @@
 #ifndef LTTNG_SESSION_INTERNAL_H
 #define LTTNG_SESSION_INTERNAL_H
 
-#include <lttng/constant.h>
 #include <common/macros.hpp>
+#include <common/make-unique-wrapper.hpp>
+
+#include <lttng/constant.h>
+
+struct lttng_session;
 
 struct lttng_session_extended {
        struct {
@@ -18,4 +22,8 @@ struct lttng_session_extended {
        } LTTNG_PACKED creation_time;
 } LTTNG_PACKED;
 
+using lttng_session_uptr = std::unique_ptr<
+       lttng_session[],
+       lttng::memory::create_deleter_class<lttng_session, lttng::memory::free>::deleter>;
+
 #endif /* LTTNG_SESSION_INTERNAL_H */
index 153a37b03680da361e97f0f64bdee979ae16c6fe..a6735edadeee1a03310b3a6fba9f60623f84b82b 100644 (file)
 extern "C" {
 #endif
 
-#include <lttng/constant.h>
 #include <lttng/lttng-export.h>
 
+/*!
+@addtogroup api_session
+@{
+*/
+
+#include <lttng/constant.h>
+
 struct lttng_handle;
 struct lttng_session_descriptor;
 struct lttng_destruction_handle;
 
-/*
- * Basic session information.
- *
- * The "enabled" field is only used when listing the sessions which indicate if
- * it's started or not.
- *
- * The structures should be initialized to zero before use.
- */
-#define LTTNG_SESSION_PADDING1             8
+#define LTTNG_SESSION_PADDING1 8
+
+/*!
+@brief
+    Recording session summary.
+
+The purpose of such a structure is to provide information about a
+\lt_obj_session itself, but not about its \lt_obj_domains
+and \lt_obj_channels (use lttng_list_domains() and lttng_list_channels()
+for this).
+
+lttng_list_sessions() sets a pointer to an array of all the available
+recording session summaries.
+*/
 struct lttng_session {
+       /// Name.
        char name[LTTNG_NAME_MAX];
-       /*
-        * Human-readable representation of the trace's destination.
-        * In the case of a local tracing session, a path is provided:
-        *     /path/to/the/output
-        *
-        * In the case of a remote (network) tracing session, the string has
-        * the following format:
-        *     net://hostname/path:ctrl_port [data: data_port]
-        */
+
+       /*!
+       @brief
+           <em>Human-readable</em> representation of the output (local
+           or remote).
+       */
        char path[PATH_MAX];
-       uint32_t enabled;       /* enabled/started: 1, disabled/stopped: 0 */
+
+       /*!
+       @brief
+           1 if this recording session is active (started), or 0
+           otherwise.
+
+       @sa lttng_start_tracing() --
+           Starts a recording session.
+       @sa lttng_stop_tracing() --
+           Stops a recording session.
+       */
+       uint32_t enabled; /* enabled/started: 1, disabled/stopped: 0 */
+
+       /*!
+       @brief
+           1 if this recording session was created in
+           \ref api-session-snapshot-mode "snapshot mode",
+           or 0 otherwise.
+
+       @note
+           If this member is 1, then the
+           lttng_session::live_timer_interval member is 0.
+       */
        uint32_t snapshot_mode;
-       unsigned int live_timer_interval;       /* usec */
+
+       /*!
+       @brief
+           Period (µs) of the \ref api-channel-live-timer "live timers"
+           of the channels of this recording session, or 0 if this
+           recording session wasn't created in
+           \ref api-session-live-mode "live mode".
+
+       @note
+           If this member is \em not 0, then the
+           lttng_session::snapshot_mode member is 0.
+       */
+       unsigned int live_timer_interval; /* usec */
 
        /*
         * End of public attributes.
@@ -73,140 +116,397 @@ struct lttng_session {
        } extended;
 };
 
-/*
- * Create a session on the session daemon from a session descriptor.
- *
- * See the session descriptor API description in session-descriptor.h
- *
- * Note that unspecified session descriptor parameters, such as a session's
- * name, are updated in the session descriptor if the creation of the session
- * succeeds. This allows users to query the session's auto-generated name
- * after its creation. Note that other attributes can be queried using the
- * session listing API.
- *
- * Returns LTTNG_OK on success. See lttng-error.h for the meaning of the other
- * return codes.
- */
-LTTNG_EXPORT extern enum lttng_error_code lttng_create_session_ext(
-               struct lttng_session_descriptor *session_descriptor);
+/*!
+@brief
+    Creates a recording session from the recording session descriptor
+    \lt_p{session_descriptor}.
 
-/*
- * Create a tracing session using a name and an optional URL.
- *
- * If _url_ is NULL, no consumer is created for the session. The name can't be
- * NULL here.
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_create_session(const char *name, const char *url);
+See \ref api_session_descr to learn how to create a recording session
+descriptor.
 
-/*
- * Create a tracing session that will exclusively be used for snapshot meaning
- * the session will be in no output mode and every channel enabled for that
- * session will be set in overwrite mode and in mmap output since splice is not
- * supported.
- *
- * Name can't be NULL. If an url is given, it will be used to create a default
- * snapshot output using it as a destination. If NULL, no output will be
- * defined and an add-output call will be needed.
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_create_session_snapshot(const char *name,
-               const char *snapshot_url);
+On success, if the name property of \lt_p{session_descriptor} isn't set,
+this function sets it to the automatically generated name of the
+recording session. Get the recording session name with
+lttng_session_descriptor_get_session_name().
 
-/*
- * Create a session exclusively used for live reading.
- *
- * In this mode, the switch-timer parameter is forced for each UST channel, a
- * live-switch-timer is enabled for kernel channels, manually setting
- * switch-timer is forbidden. Synchronization beacons are sent to the relayd,
- * indexes are sent and metadata is checked for each packet.
- *
- * Name can't be NULL. If no URL is given, the default is to send the data to
- * net://127.0.0.1. The timer_interval is in usec.
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_create_session_live(const char *name, const char *url,
-               unsigned int timer_interval);
+@param[in] session_descriptor
+    Descriptor from which to create a recording session.
 
-/*
- * Destroy a tracing session.
- *
- * The session will not be usable, tracing will be stopped thus buffers will be
- * flushed.
- *
- * This call will wait for data availability for each domain of the session,
- * which can take an arbitrary amount of time. However, when returning the
- * tracing data is guaranteed to be ready to be read and analyzed.
- *
- * lttng_destroy_session_no_wait() may be used if such a guarantee is not
- * needed.
- *
- * The name can't be NULL here.
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_destroy_session(const char *name);
+@returns
+    #LTTNG_OK on success, or a \em negative enumerator otherwise.
 
-/*
- * Destroy a tracing session.
- *
- * Performs the same function as lttng_destroy_session(), but provides
- * an lttng_destruction_handle which can be used to wait for the completion
- * of the session's destruction. The lttng_destroy_handle can also be used
- * obtain the status and archive location of any implicit session
- * rotation that may have occurred during the session's destruction.
- *
- * Returns LTTNG_OK on success. The returned handle is owned by the caller
- * and must be free'd using lttng_destruction_handle_destroy().
- */
-LTTNG_EXPORT extern enum lttng_error_code lttng_destroy_session_ext(const char *session_name,
-               struct lttng_destruction_handle **handle);
+@lt_pre_conn
+@lt_pre_not_null{session_descriptor}
+@pre
+    If the name property of \lt_p{session_descriptor} is set, then no
+    available recording session has this name.
 
-/*
- * Behaves exactly like lttng_destroy_session but does not wait for data
- * availability.
- */
-LTTNG_EXPORT extern int lttng_destroy_session_no_wait(const char *name);
+@sa \ref api_session_descr.
+@sa \lt_man{lttng-create,1}
+*/
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_create_session_ext(struct lttng_session_descriptor *session_descriptor);
 
-/*
- * List all the tracing sessions.
- *
- * Return the number of entries of the "lttng_session" array. The caller
- * must free the returned sessions array directly using free().
- *
- * On error, a negative LTTng error code is returned.
- */
+/*!
+@brief
+    Creates a recording session named \lt_p{session_name} in
+    \ref api-session-local-mode "local"
+    or \ref api-session-net-mode "network streaming" mode, optionally
+    setting its output URL to \lt_p{output_url}.
+
+@deprecated
+    Use lttng_create_session_ext() with a dedicated
+    local or network streaming
+    \ref api_session_descr "recording session descriptor".
+
+@param[in] session_name
+    Name of the new recording session.
+@param[in] output_url
+    @parblock
+    \ref api-session-url "Output URL" of the recording session to
+    create.
+
+    If it's a \ref api-session-one-port-url "single-port output URL",
+    then the trace data port is \lt_def_net_data_port.
+
+    If \c NULL, LTTng doesn't write any trace data for this recording
+    session.
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    No available recording session is named \lt_p{session_name}.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{output_url} is a valid
+    \ref api-session-url "output URL".
+
+@sa lttng_create_session_snapshot() --
+    Creates a recording session in snapshot mode.
+@sa lttng_create_session_live() --
+    Creates a recording session in live mode.
+@sa \lt_man{lttng-create,1}
+*/
+LTTNG_EXPORT extern int lttng_create_session(const char *session_name, const char *output_url);
+
+/*!
+@brief
+    Creates a recording session named \lt_p{session_name} in
+    \ref api-session-snapshot-mode "snapshot" mode, optionally setting
+    the URL of its initial snapshot output to \lt_p{output_url}.
+
+@deprecated
+    Use lttng_create_session_ext() with a dedicated snapshot
+    \ref api_session_descr "recording session descriptor".
+
+@param[in] session_name
+    Name of the new recording session.
+@param[in] output_url
+    @parblock
+    \ref api-session-url "URL" of an initial snapshot output
+    which LTTng adds to this recording session.
+
+    If it's a \ref api-session-one-port-url "single-port output URL",
+    then the trace data port is \lt_def_net_data_port.
+
+    This initial snapshot output is named <code>snapshot-0</code>.
+
+    If \c NULL, then the created recording session has no initial
+    snapshot output: you need to either add one with
+    lttng_snapshot_add_output() or provide one when you take a snapshot
+    with lttng_snapshot_record().
+    @endparblock
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    No available recording session is named \lt_p{session_name}.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{output_url} is a valid
+    \ref api-session-url "output URL".
+
+@sa lttng_create_session() --
+    Creates a recording session in local or network streaming mode.
+@sa lttng_create_session_live() --
+    Creates a recording session in live mode.
+@sa \lt_man{lttng-create,1}
+*/
+LTTNG_EXPORT extern int lttng_create_session_snapshot(const char *session_name,
+                                                     const char *output_url);
+
+/*!
+@brief
+    Creates a recording session named \lt_p{session_name} in
+    \ref api-session-live-mode "live" mode, optionally setting its
+    URL to \lt_p{output_url}.
+
+@deprecated
+    Use lttng_create_session_ext() with a dedicated live
+    \ref api_session_descr "recording session descriptor".
+
+@param[in] session_name
+    Name of the new recording session.
+@param[in] output_url
+    @parblock
+    \ref api-session-url "Output URL" of the recording session to
+    create: \ref api-session-one-port-url "single-port" or
+    \ref api-session-two-port-url "two-port".
+
+    If it's a \ref api-session-one-port-url "single-port output URL",
+    then the trace data port is \lt_def_net_data_port.
+
+    If \c NULL, this function uses \lt_def_net_url.
+    @endparblock
+@param[in] live_timer_period
+    Period (µs) of the \ref api-channel-live-timer "live timers" of all
+    the channels of the created recording session.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_name_not_auto{session_name}
+@pre
+    No available recording session is named \lt_p{session_name}.
+@pre
+    <strong>If not \c NULL</strong>, \lt_p{output_url} is a valid
+    \ref api-session-one-port-url "single-port output URL" or
+    \ref api-session-two-port-url "two-port output URL".
+@pre
+    \lt_p{live_timer_period}&nbsp;≥&nbsp;1
+
+@sa lttng_create_session() --
+    Creates a recording session in local or network streaming mode.
+@sa lttng_create_session_snapshot() --
+    Creates a recording session in snapshot mode.
+@sa \lt_man{lttng-create,1}
+*/
+LTTNG_EXPORT extern int lttng_create_session_live(const char *session_name,
+                                                 const char *output_url,
+                                                 unsigned int live_timer_period);
+
+/*!
+@brief
+    Destroys the recording session named \lt_p{session_name}, blocking
+    until the operation completes.
+
+@deprecated
+    Use lttng_destroy_session_ext().
+
+"Destroying" a recording session means freeing the resources which the
+LTTng daemons and tracers acquired for it, also making sure to flush all
+the recorded trace data to either the local file system or the connected
+LTTng relay daemon (see \lt_man{lttng-relayd,8}), depending on the
+\ref api-session-modes "recording session mode".
+
+This function stops any recording activity within the recording session
+named \lt_p{session_name}.
+
+This function implicitly calls lttng_stop_tracing(), blocking until the
+trace data of the recording session becomes valid. Use
+lttng_destroy_session_no_wait() to avoid a blocking call.
+
+@param[in] session_name
+    Name of the recording session to destroy.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+
+@sa lttng_destroy_session_no_wait() --
+    Initiates the destruction operation of a recording session,
+    returning immediately.
+@sa \lt_man{lttng-destroy,1}
+*/
+LTTNG_EXPORT extern int lttng_destroy_session(const char *session_name);
+
+/*!
+@brief
+    Initiates the destruction operation of the recording session named
+    \lt_p{session_name}.
+
+@deprecated
+    Use lttng_destroy_session_ext().
+
+"Destroying" a recording session means freeing the resources which the
+LTTng daemons and tracers acquired for it, also making sure to flush all
+the recorded trace data to either the local file system or the connected
+LTTng relay daemon (see \lt_man{lttng-relayd,8}), depending on the
+\ref api-session-modes "recording session mode".
+
+Unlike lttng_destroy_session(), this function does \em not block until
+the destruction operation is complete: it returns immediately. This
+means the trace(s) of the recording session might not be valid when
+this function returns, and there's no way to know when it/they become
+valid.
+
+@param[in] session_name
+    Name of the recording session to destroy.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@pre
+    No destruction operation is in progress for the recording session
+    named \lt_p{session_name}.
+
+@sa lttng_destroy_session() --
+    Destroys a recording session, blocking until the operation
+    completes.
+@sa \lt_man{lttng-destroy,1}
+*/
+LTTNG_EXPORT extern int lttng_destroy_session_no_wait(const char *session_name);
+
+/*!
+@brief
+    Initiates a destruction operation of the recording session
+    named \lt_p{session_name}.
+
+"Destroying" a recording session means freeing the resources which the
+LTTng daemons and tracers acquired for it, also making sure to flush all
+the recorded trace data to either the local file system or the connected
+LTTng relay daemon (see \lt_man{lttng-relayd,8}), depending on the
+\ref api-session-modes "recording session mode".
+
+This function doesn't block until the destruction operation completes:
+it only initiates the operation.
+Use \lt_p{*handle} to wait for the operation to complete.
+
+@param[in] session_name
+    Name of the recording session to destroy.
+@param[out] handle
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*handle} to
+    a handle which identifies this recording session destruction
+    operation.
+
+    May be \c NULL.
+
+    Wait for the completion of this destruction operation with
+    lttng_destruction_handle_wait_for_completion().
+
+    Destroy \lt_p{*handle} with lttng_destruction_handle_destroy().
+    @endparblock
+
+@returns
+    #LTTNG_OK on success, or a \em negative enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@pre
+    No destruction operation is in progress for the recording session
+    named \lt_p{session_name}.
+
+@sa \lt_man{lttng-destroy,1}
+*/
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_destroy_session_ext(const char *session_name, struct lttng_destruction_handle **handle);
+
+/*!
+@brief
+    Sets \lt_p{*sessions} to the summaries of all the available
+    recording sessions.
+
+@param[out] sessions
+    @parblock
+    <strong>On success</strong>, this function sets \lt_p{*sessions} to
+    the summaries of the available recording sessions.
+
+    Free \lt_p{*sessions} with <code>free()</code>.
+    @endparblock
+
+@returns
+    The number of items in \lt_p{*sessions} on success, or a \em
+    negative #lttng_error_code enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{sessions}
+
+@sa \lt_man{lttng-list,1}
+*/
 LTTNG_EXPORT extern int lttng_list_sessions(struct lttng_session **sessions);
 
-/*
- * Get the creation time of an lttng_session object on the session daemon.
- *
- * This function must only be used with lttng_session objects returned
- * by lttng_list_sessions() or lttng_session_create().
- *
- * The creation time returned is a UNIX timestamp; the number of seconds since
- * Epoch (1970-01-01 00:00:00 +0000 (UTC)).
- *
- * Returns LTTNG_OK on success. See lttng-error.h for the meaning of the other
- * return codes.
- */
-LTTNG_EXPORT extern enum lttng_error_code lttng_session_get_creation_time(
-               const struct lttng_session *session, uint64_t *creation_time);
+/*!
+@brief
+    Sets \lt_p{*creation_timestamp} to the timestamp of the creation of
+    the recording session summarized by \lt_p{session}.
 
-/*
- * Set the shared memory path for a session.
- *
- * Sets the (optional) file system path where shared memory buffers will
- * be created for the session. This is useful for buffer extraction on
- * crash, when used with filesystems like pramfs.
- *
- * Return 0 on success else a negative LTTng error code.
- */
-LTTNG_EXPORT extern int lttng_set_session_shm_path(const char *session_name,
-               const char *shm_path);
+@param[in] session
+    Summary of the recording session of which to get the creation
+    timestamp, as obtained with lttng_list_sessions().
+@param[out] creation_timestamp
+    <strong>On success</strong>, this function sets
+    \lt_p{*creation_timestamp} to the Unix timestamp of the creation of
+    \lt_p{session}.
+
+@returns
+    #LTTNG_OK on success, or a \em negative enumerator otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session}
+@pre
+    The recording session summarized by \lt_p{session} is accessible
+    within the connected session daemon.
+@lt_pre_not_null{creation_timestamp}
+*/
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_session_get_creation_time(const struct lttng_session *session, uint64_t *creation_timestamp);
+
+/*!
+@brief
+    Sets the path of the directory containing the shared memory files
+    holding the channel ring buffers of the recording session named
+    \lt_p{session_name} on the local file sytem to \lt_p{shm_dir}.
+
+Specifying a location on an
+<a href="https://en.wikipedia.org/wiki/Non-volatile_random-access_memory">NVRAM</a>
+file system makes it possible to recover the latest recorded trace data
+when the system reboots after a crash with the \lt_man{lttng-crash,1}
+utility.
+
+@param[in] session_name
+    Name of the recording session of which to set the shared memory
+    file directory path.
+@param[in] shm_dir
+    Path of the directory containing the shared memory files of the
+    recording session named \lt_p{session_name}.
+
+@returns
+    0 on success, or a \em negative #lttng_error_code enumerator
+    otherwise.
+
+@lt_pre_conn
+@lt_pre_not_null{session_name}
+@lt_pre_sess_exists{session_name}
+@lt_pre_sess_never_active{session_name}
+@lt_pre_not_null{shm_dir}
+@pre
+    \lt_p{shm_dir} is a writable directory.
+*/
+LTTNG_EXPORT extern int lttng_set_session_shm_path(const char *session_name, const char *shm_dir);
+
+/// @}
 
 #ifdef __cplusplus
 }
index c60a1963b67e80ed14b153f93c8432a93d49d6fc..706bf6ebfa767d6737678004e05f9ad085d31c27 100644 (file)
@@ -8,10 +8,12 @@
 #ifndef LTTNG_SNAPSHOT_INTERNAL_ABI_H
 #define LTTNG_SNAPSHOT_INTERNAL_ABI_H
 
+#include <common/macros.hpp>
+
+#include <lttng/constant.h>
+
 #include <limits.h>
 #include <stdint.h>
-#include <lttng/constant.h>
-#include <common/macros.hpp>
 
 /*
  * Object used for the snapshot API. This is opaque to the public library.
index b777e006b2f131e95f7508fec428d8c52f0476a3..4c1049b4d4243fd72de68a008df012207b787713 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef LTTNG_SNAPSHOT_H
 #define LTTNG_SNAPSHOT_H
 
-#include <limits.h>
 #include <lttng/lttng-export.h>
+
+#include <limits.h>
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -40,15 +41,20 @@ LTTNG_EXPORT extern void lttng_snapshot_output_destroy(struct lttng_snapshot_out
  */
 
 /* Return snapshot ID. */
-LTTNG_EXPORT extern uint32_t lttng_snapshot_output_get_id(const struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern uint32_t
+lttng_snapshot_output_get_id(const struct lttng_snapshot_output *output);
 /* Return maximum size of a snapshot. */
-LTTNG_EXPORT extern uint64_t lttng_snapshot_output_get_maxsize(const struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern uint64_t
+lttng_snapshot_output_get_maxsize(const struct lttng_snapshot_output *output);
 /* Return snapshot name. */
-LTTNG_EXPORT extern const char *lttng_snapshot_output_get_name(const struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern const char *
+lttng_snapshot_output_get_name(const struct lttng_snapshot_output *output);
 /* Return snapshot control URL in a text format. */
-LTTNG_EXPORT extern const char *lttng_snapshot_output_get_ctrl_url(const struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern const char *
+lttng_snapshot_output_get_ctrl_url(const struct lttng_snapshot_output *output);
 /* Return snapshot data URL in a text format. */
-LTTNG_EXPORT extern const char *lttng_snapshot_output_get_data_url(const struct lttng_snapshot_output *output);
+LTTNG_EXPORT extern const char *
+lttng_snapshot_output_get_data_url(const struct lttng_snapshot_output *output);
 
 /*
  * Snapshot output setter family functions.
@@ -59,13 +65,13 @@ LTTNG_EXPORT extern const char *lttng_snapshot_output_get_data_url(const struct
 
 /* Set a custom ID. */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_id(uint32_t id,
-               struct lttng_snapshot_output *output);
+                                                    struct lttng_snapshot_output *output);
 /* Set the maximum size. */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_size(uint64_t size,
-               struct lttng_snapshot_output *output);
+                                                      struct lttng_snapshot_output *output);
 /* Set the snapshot name. */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_name(const char *name,
-               struct lttng_snapshot_output *output);
+                                                      struct lttng_snapshot_output *output);
 
 /*
  * Set the output destination to be a path on the local filesystem.
@@ -75,7 +81,7 @@ LTTNG_EXPORT extern int lttng_snapshot_output_set_name(const char *name,
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_local_path(const char *path,
-               struct lttng_snapshot_output *output);
+                                                            struct lttng_snapshot_output *output);
 
 /*
  * Set the output destination to be the network from a combined control/data
@@ -86,7 +92,7 @@ LTTNG_EXPORT extern int lttng_snapshot_output_set_local_path(const char *path,
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_network_url(const char *url,
-               struct lttng_snapshot_output *output);
+                                                             struct lttng_snapshot_output *output);
 
 /*
  * Set the output destination to be the network using separate URLs for control
@@ -99,15 +105,14 @@ LTTNG_EXPORT extern int lttng_snapshot_output_set_network_url(const char *url,
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_network_urls(
-               const char *ctrl_url, const char *data_url,
-               struct lttng_snapshot_output *output);
+       const char *ctrl_url, const char *data_url, struct lttng_snapshot_output *output);
 
 /* Set the control URL. Local and remote URL are supported. */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_ctrl_url(const char *url,
-               struct lttng_snapshot_output *output);
+                                                          struct lttng_snapshot_output *output);
 /* Set the data URL. Local and remote URL are supported. */
 LTTNG_EXPORT extern int lttng_snapshot_output_set_data_url(const char *url,
-               struct lttng_snapshot_output *output);
+                                                          struct lttng_snapshot_output *output);
 
 /*
  * Add an output object to a session identified by name.
@@ -115,7 +120,7 @@ LTTNG_EXPORT extern int lttng_snapshot_output_set_data_url(const char *url,
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
 LTTNG_EXPORT extern int lttng_snapshot_add_output(const char *session_name,
-               struct lttng_snapshot_output *output);
+                                                 struct lttng_snapshot_output *output);
 
 /*
  * Delete an output object to a session identified by name.
@@ -123,7 +128,7 @@ LTTNG_EXPORT extern int lttng_snapshot_add_output(const char *session_name,
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
 LTTNG_EXPORT extern int lttng_snapshot_del_output(const char *session_name,
-               struct lttng_snapshot_output *output);
+                                                 struct lttng_snapshot_output *output);
 
 /*
  * List all snapshot output(s) of a session identified by name. The output list
@@ -133,7 +138,7 @@ LTTNG_EXPORT extern int lttng_snapshot_del_output(const char *session_name,
  * is untouched.
  */
 LTTNG_EXPORT extern int lttng_snapshot_list_output(const char *session_name,
-               struct lttng_snapshot_output_list **list);
+                                                  struct lttng_snapshot_output_list **list);
 
 /*
  * Return the next available snapshot output object in the given list. A list
@@ -142,13 +147,14 @@ LTTNG_EXPORT extern int lttng_snapshot_list_output(const char *session_name,
  * Return the next object on success or else NULL indicating the end of the
  * list.
  */
-LTTNG_EXPORT extern struct lttng_snapshot_output *lttng_snapshot_output_list_get_next(
-               struct lttng_snapshot_output_list *list);
+LTTNG_EXPORT extern struct lttng_snapshot_output *
+lttng_snapshot_output_list_get_next(struct lttng_snapshot_output_list *list);
 
 /*
  * Free an output list object.
  */
-LTTNG_EXPORT extern void lttng_snapshot_output_list_destroy(struct lttng_snapshot_output_list *list);
+LTTNG_EXPORT extern void
+lttng_snapshot_output_list_destroy(struct lttng_snapshot_output_list *list);
 
 /*
  * Snapshot a trace for the given session.
@@ -162,8 +168,8 @@ LTTNG_EXPORT extern void lttng_snapshot_output_list_destroy(struct lttng_snapsho
  *
  * Return 0 on success or else a negative LTTNG_ERR value.
  */
-LTTNG_EXPORT extern int lttng_snapshot_record(const char *session_name,
-               struct lttng_snapshot_output *output, int wait);
+LTTNG_EXPORT extern int
+lttng_snapshot_record(const char *session_name, struct lttng_snapshot_output *output, int wait);
 
 #ifdef __cplusplus
 }
index 869f8a8f85b0bf7b1e1e39ee71298f23d732287c..f8f493e6650c1cd504fc44841a37907c6458d664 100644 (file)
@@ -116,17 +116,17 @@ struct lttng_process_attr_values;
  * The tracker's ownership is transfered to the caller. Use
  * lttng_process_attr_tracker_handle_destroy() to dispose of it.
  */
-LTTNG_EXPORT extern enum lttng_error_code lttng_session_get_tracker_handle(
-               const char *session_name,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               struct lttng_process_attr_tracker_handle **out_tracker_handle);
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_session_get_tracker_handle(const char *session_name,
+                                enum lttng_domain_type domain,
+                                enum lttng_process_attr process_attr,
+                                struct lttng_process_attr_tracker_handle **out_tracker_handle);
 
 /*
  * Destroy a process attribute tracker handle.
  */
-LTTNG_EXPORT extern void lttng_process_attr_tracker_handle_destroy(
-               struct lttng_process_attr_tracker_handle *tracker_handle);
+LTTNG_EXPORT extern void
+lttng_process_attr_tracker_handle_destroy(struct lttng_process_attr_tracker_handle *tracker_handle);
 
 /*
  * Get the tracking policy of a process attribute tracker.
@@ -137,8 +137,8 @@ LTTNG_EXPORT extern void lttng_process_attr_tracker_handle_destroy(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_tracker_handle_get_tracking_policy(
-               const struct lttng_process_attr_tracker_handle *tracker_handle,
-               enum lttng_tracking_policy *policy);
+       const struct lttng_process_attr_tracker_handle *tracker_handle,
+       enum lttng_tracking_policy *policy);
 
 /*
  * Set the tracking policy of a process attribute tracker.
@@ -150,8 +150,8 @@ lttng_process_attr_tracker_handle_get_tracking_policy(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_tracker_handle_set_tracking_policy(
-               const struct lttng_process_attr_tracker_handle *tracker_handle,
-               enum lttng_tracking_policy policy);
+       const struct lttng_process_attr_tracker_handle *tracker_handle,
+       enum lttng_tracking_policy policy);
 
 /*
  * Add a numerical PID to the process ID process attribute tracker inclusion
@@ -165,9 +165,7 @@ lttng_process_attr_tracker_handle_set_tracking_policy(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_process_id_tracker_handle_add_pid(
-               const struct lttng_process_attr_tracker_handle
-                               *process_id_tracker,
-               pid_t pid);
+       const struct lttng_process_attr_tracker_handle *process_id_tracker, pid_t pid);
 
 /*
  * Remove a numerical PID from the process ID process attribute tracker include
@@ -180,9 +178,7 @@ lttng_process_attr_process_id_tracker_handle_add_pid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_process_id_tracker_handle_remove_pid(
-               const struct lttng_process_attr_tracker_handle
-                               *process_id_tracker,
-               pid_t pid);
+       const struct lttng_process_attr_tracker_handle *process_id_tracker, pid_t pid);
 
 /*
  * Add a numerical PID to the virtual process ID process attribute tracker
@@ -196,9 +192,7 @@ lttng_process_attr_process_id_tracker_handle_remove_pid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
-               const struct lttng_process_attr_tracker_handle
-                               *process_id_tracker,
-               pid_t vpid);
+       const struct lttng_process_attr_tracker_handle *process_id_tracker, pid_t vpid);
 
 /*
  * Remove a numerical PID from the virtual process ID process attribute tracker
@@ -211,9 +205,7 @@ lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(
-               const struct lttng_process_attr_tracker_handle
-                               *process_id_tracker,
-               pid_t vpid);
+       const struct lttng_process_attr_tracker_handle *process_id_tracker, pid_t vpid);
 
 /*
  * Add a numerical UID to the user ID process attribute tracker inclusion set.
@@ -226,8 +218,7 @@ lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_user_id_tracker_handle_add_uid(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               uid_t uid);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, uid_t uid);
 
 /*
  * Remove a numerical UID from the user ID process attribute tracker include
@@ -240,8 +231,7 @@ lttng_process_attr_user_id_tracker_handle_add_uid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_user_id_tracker_handle_remove_uid(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               uid_t uid);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, uid_t uid);
 
 /*
  * Add a user name to the user ID process attribute tracker inclusion set.
@@ -257,8 +247,7 @@ lttng_process_attr_user_id_tracker_handle_remove_uid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_user_id_tracker_handle_add_user_name(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               const char *user_name);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, const char *user_name);
 
 /*
  * Remove a user name from the user ID process attribute tracker include
@@ -274,8 +263,7 @@ lttng_process_attr_user_id_tracker_handle_add_user_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_user_id_tracker_handle_remove_user_name(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               const char *user_name);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, const char *user_name);
 
 /*
  * Add a numerical UID to the virtual user ID process attribute tracker
@@ -289,8 +277,7 @@ lttng_process_attr_user_id_tracker_handle_remove_user_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               uid_t vuid);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, uid_t vuid);
 
 /*
  * Remove a numerical UID from the virtual user ID process attribute tracker
@@ -303,8 +290,7 @@ lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_user_id_tracker_handle_remove_uid(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               uid_t vuid);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker, uid_t vuid);
 
 /*
  * Add a user name to the virtual user ID process attribute tracker include
@@ -321,8 +307,8 @@ lttng_process_attr_virtual_user_id_tracker_handle_remove_uid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               const char *virtual_user_name);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker,
+       const char *virtual_user_name);
 
 /*
  * Remove a user name from the virtual user ID process attribute tracker
@@ -338,8 +324,8 @@ lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_user_id_tracker_handle_remove_user_name(
-               const struct lttng_process_attr_tracker_handle *user_id_tracker,
-               const char *virtual_user_name);
+       const struct lttng_process_attr_tracker_handle *user_id_tracker,
+       const char *virtual_user_name);
 
 /*
  * Add a numerical GID to the group ID process attribute tracker inclusion set.
@@ -352,8 +338,7 @@ lttng_process_attr_virtual_user_id_tracker_handle_remove_user_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_group_id_tracker_handle_add_gid(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               gid_t gid);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, gid_t gid);
 
 /*
  * Remove a numerical GID from the group ID process attribute tracker include
@@ -366,8 +351,7 @@ lttng_process_attr_group_id_tracker_handle_add_gid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_group_id_tracker_handle_remove_gid(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               gid_t gid);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, gid_t gid);
 
 /*
  * Add a group name to the group ID process attribute tracker inclusion set.
@@ -383,8 +367,7 @@ lttng_process_attr_group_id_tracker_handle_remove_gid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_group_id_tracker_handle_add_group_name(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               const char *group_name);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, const char *group_name);
 
 /*
  * Remove a group name from the group ID process attribute tracker include
@@ -400,8 +383,7 @@ lttng_process_attr_group_id_tracker_handle_add_group_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_group_id_tracker_handle_remove_group_name(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               const char *group_name);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, const char *group_name);
 
 /*
  * Add a numerical GID to the virtual group ID process attribute tracker
@@ -415,8 +397,7 @@ lttng_process_attr_group_id_tracker_handle_remove_group_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               gid_t vgid);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, gid_t vgid);
 
 /*
  * Remove a numerical GID from the virtual group ID process attribute tracker
@@ -429,8 +410,7 @@ lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_group_id_tracker_handle_remove_gid(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               gid_t vgid);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker, gid_t vgid);
 
 /*
  * Add a group name to the virtual group ID process attribute tracker include
@@ -447,8 +427,8 @@ lttng_process_attr_virtual_group_id_tracker_handle_remove_gid(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               const char *virtual_group_name);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker,
+       const char *virtual_group_name);
 
 /*
  * Remove a group name from the virtual group ID process attribute tracker
@@ -464,8 +444,8 @@ lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_virtual_group_id_tracker_handle_remove_group_name(
-               const struct lttng_process_attr_tracker_handle *group_id_tracker,
-               const char *virtual_group_name);
+       const struct lttng_process_attr_tracker_handle *group_id_tracker,
+       const char *virtual_group_name);
 
 /*
  * Get the process attribute values that are part of a tracker's inclusion set.
@@ -482,8 +462,8 @@ lttng_process_attr_virtual_group_id_tracker_handle_remove_group_name(
  */
 LTTNG_EXPORT extern enum lttng_process_attr_tracker_handle_status
 lttng_process_attr_tracker_handle_get_inclusion_set(
-               struct lttng_process_attr_tracker_handle *tracker_handle,
-               const struct lttng_process_attr_values **values);
+       struct lttng_process_attr_tracker_handle *tracker_handle,
+       const struct lttng_process_attr_values **values);
 
 /*
  * Get the count of values within a set of process attribute values.
@@ -492,9 +472,8 @@ lttng_process_attr_tracker_handle_get_inclusion_set(
  * LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID if an invalid argument is provided.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_count(
-               const struct lttng_process_attr_values *values,
-               unsigned int *count);
+lttng_process_attr_values_get_count(const struct lttng_process_attr_values *values,
+                                   unsigned int *count);
 
 /*
  * Get the type of a process attribute value at a given index.
@@ -503,9 +482,8 @@ lttng_process_attr_values_get_count(
  * LTTNG_PROCESS_ATTR_VALUE_TYPE_INVALID if an invalid argument is provided.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_value_type
-lttng_process_attr_values_get_type_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index);
+lttng_process_attr_values_get_type_at_index(const struct lttng_process_attr_values *values,
+                                           unsigned int index);
 
 /*
  * Get a process ID process attribute value.
@@ -515,10 +493,9 @@ lttng_process_attr_values_get_type_at_index(
  * is not a process ID.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_pid_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index,
-               pid_t *pid);
+lttng_process_attr_values_get_pid_at_index(const struct lttng_process_attr_values *values,
+                                          unsigned int index,
+                                          pid_t *pid);
 
 /*
  * Get a user ID process attribute value.
@@ -528,10 +505,9 @@ lttng_process_attr_values_get_pid_at_index(
  * is not a user ID.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_uid_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index,
-               uid_t *uid);
+lttng_process_attr_values_get_uid_at_index(const struct lttng_process_attr_values *values,
+                                          unsigned int index,
+                                          uid_t *uid);
 
 /*
  * Get a user name process attribute value.
@@ -541,10 +517,9 @@ lttng_process_attr_values_get_uid_at_index(
  * is not a user name.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_user_name_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index,
-               const char **user_name);
+lttng_process_attr_values_get_user_name_at_index(const struct lttng_process_attr_values *values,
+                                                unsigned int index,
+                                                const char **user_name);
 
 /*
  * Get a group ID process attribute value.
@@ -554,10 +529,9 @@ lttng_process_attr_values_get_user_name_at_index(
  * is not a group ID.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_gid_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index,
-               gid_t *gid);
+lttng_process_attr_values_get_gid_at_index(const struct lttng_process_attr_values *values,
+                                          unsigned int index,
+                                          gid_t *gid);
 
 /*
  * Get a group name process attribute value.
@@ -567,10 +541,9 @@ lttng_process_attr_values_get_gid_at_index(
  * is not a group name.
  */
 LTTNG_EXPORT extern enum lttng_process_attr_values_status
-lttng_process_attr_values_get_group_name_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index,
-               const char **group_name);
+lttng_process_attr_values_get_group_name_at_index(const struct lttng_process_attr_values *values,
+                                                 unsigned int index,
+                                                 const char **group_name);
 
 /* The following entry points are deprecated. */
 
@@ -589,10 +562,8 @@ lttng_process_attr_values_get_group_name_at_index(
  *
  * Returns 0 on success, else a negative LTTng error code.
  */
-LTTNG_EXPORT extern int lttng_list_tracker_pids(struct lttng_handle *handle,
-               int *enabled,
-               int32_t **pids,
-               size_t *nr_pids);
+LTTNG_EXPORT extern int
+lttng_list_tracker_pids(struct lttng_handle *handle, int *enabled, int32_t **pids, size_t *nr_pids);
 
 /*
  * Deprecated: see `lttng_process_attr_process_id_tracker_handle_add_pid`.
index a05a36ed3a2b4a5b1b5901a35b5b316be03613bb..c0aa3506a501121137541c21fd027d41339817e7 100644 (file)
@@ -12,7 +12,9 @@
 #include <common/dynamic-array.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+
 #include <lttng/lttng.h>
+
 #include <pthread.h>
 #include <stdbool.h>
 #include <stdint.h>
@@ -107,26 +109,21 @@ struct lttng_triggers_comm {
 };
 
 ssize_t lttng_trigger_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_trigger **trigger);
+                                         struct lttng_trigger **trigger);
 
-int lttng_trigger_serialize(const struct lttng_trigger *trigger,
-               struct lttng_payload *payload);
+int lttng_trigger_serialize(const struct lttng_trigger *trigger, struct lttng_payload *payload);
 
 bool lttng_trigger_validate(const struct lttng_trigger *trigger);
 
-int lttng_trigger_assign_name(
-               struct lttng_trigger *dst, const struct lttng_trigger *src);
+int lttng_trigger_assign_name(struct lttng_trigger *dst, const struct lttng_trigger *src);
 
-void lttng_trigger_set_tracer_token(
-               struct lttng_trigger *trigger, uint64_t token);
+void lttng_trigger_set_tracer_token(struct lttng_trigger *trigger, uint64_t token);
 
 uint64_t lttng_trigger_get_tracer_token(const struct lttng_trigger *trigger);
 
-int lttng_trigger_generate_name(struct lttng_trigger *trigger,
-               uint64_t unique_id);
+int lttng_trigger_generate_name(struct lttng_trigger *trigger, uint64_t unique_id);
 
-bool lttng_trigger_is_equal(
-               const struct lttng_trigger *a, const struct lttng_trigger *b);
+bool lttng_trigger_is_equal(const struct lttng_trigger *a, const struct lttng_trigger *b);
 
 bool lttng_trigger_is_hidden(const struct lttng_trigger *trigger);
 
@@ -140,16 +137,16 @@ void lttng_trigger_put(struct lttng_trigger *trigger);
  * Serialize a trigger to a mi_writer.
  * Return LTTNG_OK in success, other enum lttng_error_code on error.
  */
-enum lttng_error_code lttng_trigger_mi_serialize(const struct lttng_trigger *trigger,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks);
+enum lttng_error_code
+lttng_trigger_mi_serialize(const struct lttng_trigger *trigger,
+                          struct mi_writer *writer,
+                          const struct mi_lttng_error_query_callbacks *error_query_callbacks);
 
 /*
  * Allocate a new set of triggers.
  * The returned object must be freed via lttng_triggers_destroy.
  */
-struct lttng_triggers *lttng_triggers_create(void);
+struct lttng_triggers *lttng_triggers_create();
 
 /*
  * Return the a pointer to a mutable element at index "index" of an
@@ -161,8 +158,8 @@ struct lttng_triggers *lttng_triggers_create(void);
  * The ownership of the trigger set element is NOT transfered.
  * The returned object can NOT be freed via lttng_trigger_destroy.
  */
-struct lttng_trigger *lttng_triggers_borrow_mutable_at_index(
-               const struct lttng_triggers *triggers, unsigned int index);
+struct lttng_trigger *lttng_triggers_borrow_mutable_at_index(const struct lttng_triggers *triggers,
+                                                            unsigned int index);
 
 /*
  * Add a trigger to the triggers set.
@@ -170,8 +167,7 @@ struct lttng_trigger *lttng_triggers_borrow_mutable_at_index(
  * A reference to the added trigger is acquired on behalf of the trigger set
  * on success.
  */
-int lttng_triggers_add(
-               struct lttng_triggers *triggers, struct lttng_trigger *trigger);
+int lttng_triggers_add(struct lttng_triggers *triggers, struct lttng_trigger *trigger);
 
 /*
  * Remove all triggers marked as hidden from the provided trigger set.
@@ -182,41 +178,38 @@ int lttng_triggers_remove_hidden_triggers(struct lttng_triggers *triggers);
  * Serialize a trigger set to an lttng_payload object.
  * Return LTTNG_OK on success, negative lttng error code on error.
  */
-int lttng_triggers_serialize(const struct lttng_triggers *triggers,
-               struct lttng_payload *payload);
+int lttng_triggers_serialize(const struct lttng_triggers *triggers, struct lttng_payload *payload);
 
 ssize_t lttng_triggers_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_triggers **triggers);
+                                          struct lttng_triggers **triggers);
 
 /*
  * Serialize a trigger set to a mi_writer.
  * Return LTTNG_OK in success, other enum lttng_error_code on error.
  */
-enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *triggers,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks);
+enum lttng_error_code
+lttng_triggers_mi_serialize(const struct lttng_triggers *triggers,
+                           struct mi_writer *writer,
+                           const struct mi_lttng_error_query_callbacks *error_query_callbacks);
 
-const struct lttng_credentials *lttng_trigger_get_credentials(
-               const struct lttng_trigger *trigger);
+const struct lttng_credentials *lttng_trigger_get_credentials(const struct lttng_trigger *trigger);
 
 void lttng_trigger_set_credentials(struct lttng_trigger *trigger,
-               const struct lttng_credentials *creds);
+                                  const struct lttng_credentials *creds);
 
 /*
  * Return the type of any underlying domain restriction. If no particular
  * requirement is present, returns LTTNG_DOMAIN_NONE.
  */
-enum lttng_domain_type lttng_trigger_get_underlying_domain_type_restriction(
-               const struct lttng_trigger *trigger);
+enum lttng_domain_type
+lttng_trigger_get_underlying_domain_type_restriction(const struct lttng_trigger *trigger);
 
 /*
  * Generate any bytecode related to the trigger.
  * On success LTTNG_OK. On error, returns lttng_error code.
  */
-enum lttng_error_code lttng_trigger_generate_bytecode(
-               struct lttng_trigger *trigger,
-               const struct lttng_credentials *creds);
+enum lttng_error_code lttng_trigger_generate_bytecode(struct lttng_trigger *trigger,
+                                                     const struct lttng_credentials *creds);
 
 /*
  * Note that the trigger object is not locked by "copy" as it is const and
@@ -253,17 +246,17 @@ void lttng_trigger_lock(struct lttng_trigger *trigger);
 
 void lttng_trigger_unlock(struct lttng_trigger *trigger);
 
-enum lttng_trigger_status lttng_trigger_add_error_results(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results *results);
+enum lttng_trigger_status
+lttng_trigger_add_error_results(const struct lttng_trigger *trigger,
+                               struct lttng_error_query_results *results);
 
-enum lttng_trigger_status lttng_trigger_condition_add_error_results(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results *results);
+enum lttng_trigger_status
+lttng_trigger_condition_add_error_results(const struct lttng_trigger *trigger,
+                                         struct lttng_error_query_results *results);
 
-enum lttng_trigger_status lttng_trigger_add_action_error_query_results(
-               struct lttng_trigger *trigger,
-               struct lttng_error_query_results *results);
+enum lttng_trigger_status
+lttng_trigger_add_action_error_query_results(struct lttng_trigger *trigger,
+                                            struct lttng_error_query_results *results);
 
 /*
  * Set the trigger name.
@@ -276,7 +269,6 @@ enum lttng_trigger_status lttng_trigger_add_action_error_query_results(
  * Return LTTNG_TRIGGER_STATUS_OK on success, LTTNG_TRIGGER_STATUS_INVALID
  * if invalid parameters are passed.
  */
-enum lttng_trigger_status lttng_trigger_set_name(
-               struct lttng_trigger *trigger, const char *name);
+enum lttng_trigger_status lttng_trigger_set_name(struct lttng_trigger *trigger, const char *name);
 
 #endif /* LTTNG_TRIGGER_INTERNAL_H */
index 0a944a15af197d4fe2870e99f496531296b1e177..18ab06e505627d1539633dbf8ed1d707d4b9612d 100644 (file)
@@ -8,12 +8,13 @@
 #ifndef LTTNG_TRIGGER_H
 #define LTTNG_TRIGGER_H
 
-#include <sys/types.h>
 #include <lttng/constant.h>
-#include <inttypes.h>
 #include <lttng/lttng-error.h>
 #include <lttng/lttng-export.h>
 
+#include <inttypes.h>
+#include <sys/types.h>
+
 struct lttng_action;
 struct lttng_condition;
 struct lttng_trigger;
@@ -63,8 +64,8 @@ enum lttng_trigger_status {
  * Trigger objects must be destroyed using the lttng_trigger_destroy()
  * function.
  */
-LTTNG_EXPORT extern struct lttng_trigger *lttng_trigger_create(
-               struct lttng_condition *condition, struct lttng_action *action);
+LTTNG_EXPORT extern struct lttng_trigger *lttng_trigger_create(struct lttng_condition *condition,
+                                                              struct lttng_action *action);
 
 /*
  * Set the user identity (uid) of a trigger.
@@ -75,8 +76,8 @@ LTTNG_EXPORT extern struct lttng_trigger *lttng_trigger_create(
  * LTTNG_TRIGGER_STATUS_EPERM if not authorized,
  * LTTNG_TRIGGER_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_trigger_status lttng_trigger_set_owner_uid(
-               struct lttng_trigger *trigger, uid_t uid);
+LTTNG_EXPORT extern enum lttng_trigger_status
+lttng_trigger_set_owner_uid(struct lttng_trigger *trigger, uid_t uid);
 
 /*
  * Get the user identity (uid) of a trigger.
@@ -85,8 +86,8 @@ LTTNG_EXPORT extern enum lttng_trigger_status lttng_trigger_set_owner_uid(
  * LTTNG_TRIGGER_STATUS_UNSET if unset,
  * LTTNG_TRIGGER_STATUS_INVALID if invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_trigger_status lttng_trigger_get_owner_uid(
-               const struct lttng_trigger *trigger, uid_t *uid);
+LTTNG_EXPORT extern enum lttng_trigger_status
+lttng_trigger_get_owner_uid(const struct lttng_trigger *trigger, uid_t *uid);
 
 /*
  * Get the condition of a trigger.
@@ -95,11 +96,11 @@ LTTNG_EXPORT extern enum lttng_trigger_status lttng_trigger_get_owner_uid(
  *
  * Returns a condition on success, NULL on error.
  */
-LTTNG_EXPORT extern struct lttng_condition *lttng_trigger_get_condition(
-               struct lttng_trigger *trigger);
+LTTNG_EXPORT extern struct lttng_condition *
+lttng_trigger_get_condition(struct lttng_trigger *trigger);
 
-LTTNG_EXPORT extern const struct lttng_condition *lttng_trigger_get_const_condition(
-               const struct lttng_trigger *trigger);
+LTTNG_EXPORT extern const struct lttng_condition *
+lttng_trigger_get_const_condition(const struct lttng_trigger *trigger);
 
 /*
  * Get the action of a trigger.
@@ -108,11 +109,10 @@ LTTNG_EXPORT extern const struct lttng_condition *lttng_trigger_get_const_condit
  *
  * Returns an action on success, NULL on error.
  */
-LTTNG_EXPORT extern struct lttng_action *lttng_trigger_get_action(
-               struct lttng_trigger *trigger);
+LTTNG_EXPORT extern struct lttng_action *lttng_trigger_get_action(struct lttng_trigger *trigger);
 
-LTTNG_EXPORT extern const struct lttng_action *lttng_trigger_get_const_action(
-               const struct lttng_trigger *trigger);
+LTTNG_EXPORT extern const struct lttng_action *
+lttng_trigger_get_const_action(const struct lttng_trigger *trigger);
 
 /*
  * Get the name of a trigger.
@@ -125,8 +125,8 @@ LTTNG_EXPORT extern const struct lttng_action *lttng_trigger_get_const_action(
  * success, LTTNG_TRIGGER_STATUS_INVALID if an invalid parameter is passed,
  * or LTTNG_TRIGGER_STATUS_UNSET if the trigger is unnamed.
  */
-LTTNG_EXPORT extern enum lttng_trigger_status lttng_trigger_get_name(
-               const struct lttng_trigger *trigger, const char **name);
+LTTNG_EXPORT extern enum lttng_trigger_status
+lttng_trigger_get_name(const struct lttng_trigger *trigger, const char **name);
 
 /*
  * Destroy (frees) a trigger object.
@@ -141,9 +141,8 @@ LTTNG_EXPORT extern void lttng_trigger_destroy(struct lttng_trigger *trigger);
  *
  * Returns an LTTng status code.
  */
-LTTNG_EXPORT extern enum lttng_error_code lttng_register_trigger_with_name(
-               struct lttng_trigger *trigger,
-               const char *name);
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_register_trigger_with_name(struct lttng_trigger *trigger, const char *name);
 
 /*
  * Register a trigger to the session daemon, generating a unique name for its
@@ -155,8 +154,8 @@ LTTNG_EXPORT extern enum lttng_error_code lttng_register_trigger_with_name(
  *
  * Returns an LTTng status code.
  */
-LTTNG_EXPORT extern enum lttng_error_code lttng_register_trigger_with_automatic_name(
-               struct lttng_trigger *trigger);
+LTTNG_EXPORT extern enum lttng_error_code
+lttng_register_trigger_with_automatic_name(struct lttng_trigger *trigger);
 
 /*
  * Unregister a trigger from the session daemon.
@@ -177,8 +176,7 @@ LTTNG_EXPORT extern int lttng_unregister_trigger(const struct lttng_trigger *tri
  *
  * Returns LTTNG_OK on success, else a suitable LTTng error code.
  */
-LTTNG_EXPORT extern enum lttng_error_code lttng_list_triggers(
-               struct lttng_triggers **triggers);
+LTTNG_EXPORT extern enum lttng_error_code lttng_list_triggers(struct lttng_triggers **triggers);
 
 /*
  * Get a trigger from the set at a given index.
@@ -189,8 +187,8 @@ LTTNG_EXPORT extern enum lttng_error_code lttng_list_triggers(
  *
  * Returns a trigger, or NULL on error.
  */
-LTTNG_EXPORT extern const struct lttng_trigger *lttng_triggers_get_at_index(
-               const struct lttng_triggers *triggers, unsigned int index);
+LTTNG_EXPORT extern const struct lttng_trigger *
+lttng_triggers_get_at_index(const struct lttng_triggers *triggers, unsigned int index);
 
 /*
  * Get the number of triggers in a trigger set.
@@ -198,8 +196,8 @@ LTTNG_EXPORT extern const struct lttng_trigger *lttng_triggers_get_at_index(
  * Return LTTNG_TRIGGER_STATUS_OK on success,
  * LTTNG_TRIGGER_STATUS_INVALID when invalid parameters are passed.
  */
-LTTNG_EXPORT extern enum lttng_trigger_status lttng_triggers_get_count(
-               const struct lttng_triggers *triggers, unsigned int *count);
+LTTNG_EXPORT extern enum lttng_trigger_status
+lttng_triggers_get_count(const struct lttng_triggers *triggers, unsigned int *count);
 
 /*
  * Destroy a trigger set.
index 392242daecfed435ce9f7842c8584c1ce9747116..016aeb1c62762d23bb5225543be40d89a6528b0a 100644 (file)
@@ -9,9 +9,12 @@
 #ifndef LTTNG_USERSPACE_PROBE_INTERNAL_H
 #define LTTNG_USERSPACE_PROBE_INTERNAL_H
 
-#include <lttng/userspace-probe.h>
-#include <common/macros.hpp>
 #include <common/fd-handle.hpp>
+#include <common/macros.hpp>
+
+#include <lttng/lttng-error.h>
+#include <lttng/userspace-probe.h>
+
 #include <stdbool.h>
 
 struct lttng_payload;
@@ -19,14 +22,12 @@ struct lttng_payload_view;
 struct lttng_dynamic_buffer;
 struct mi_writer;
 
-typedef bool (*userspace_probe_location_equal_cb)(
-               const struct lttng_userspace_probe_location *a,
-               const struct lttng_userspace_probe_location *b);
-typedef unsigned long (*userspace_probe_location_hash_cb)(
-               const struct lttng_userspace_probe_location *location);
-typedef enum lttng_error_code (*userspace_probe_location_mi)(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer);
+using userspace_probe_location_equal_cb = bool (*)(const struct lttng_userspace_probe_location *,
+                                                  const struct lttng_userspace_probe_location *);
+using userspace_probe_location_hash_cb =
+       unsigned long (*)(const struct lttng_userspace_probe_location *);
+using userspace_probe_location_mi =
+       enum lttng_error_code (*)(const struct lttng_userspace_probe_location *, struct mi_writer);
 
 /*
  * No elf-specific comm structure is defined since no elf-specific payload is
@@ -124,39 +125,35 @@ struct lttng_userspace_probe_location_tracepoint {
        struct fd_handle *binary_fd_handle;
 };
 
-int lttng_userspace_probe_location_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_payload *payload);
+int lttng_userspace_probe_location_serialize(const struct lttng_userspace_probe_location *location,
+                                            struct lttng_payload *payload);
 
 int lttng_userspace_probe_location_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_userspace_probe_location **probe_location);
+       struct lttng_payload_view *view, struct lttng_userspace_probe_location **probe_location);
 
 /*
  * Returns a version of the location that is serialized to a contiguous region
  * of memory. Pass NULL to buffer to only get the storage requirement of the
  * flattened userspace probe location.
  */
-int lttng_userspace_probe_location_flatten(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_dynamic_buffer *buffer);
+int lttng_userspace_probe_location_flatten(const struct lttng_userspace_probe_location *location,
+                                          struct lttng_dynamic_buffer *buffer);
 
-struct lttng_userspace_probe_location *lttng_userspace_probe_location_copy(
-               const struct lttng_userspace_probe_location *location);
+struct lttng_userspace_probe_location *
+lttng_userspace_probe_location_copy(const struct lttng_userspace_probe_location *location);
 
 bool lttng_userspace_probe_location_lookup_method_is_equal(
-               const struct lttng_userspace_probe_location_lookup_method *a,
-               const struct lttng_userspace_probe_location_lookup_method *b);
+       const struct lttng_userspace_probe_location_lookup_method *a,
+       const struct lttng_userspace_probe_location_lookup_method *b);
 
-bool lttng_userspace_probe_location_is_equal(
-               const struct lttng_userspace_probe_location *a,
-               const struct lttng_userspace_probe_location *b);
+bool lttng_userspace_probe_location_is_equal(const struct lttng_userspace_probe_location *a,
+                                            const struct lttng_userspace_probe_location *b);
 
-unsigned long lttng_userspace_probe_location_hash(
-               const struct lttng_userspace_probe_location *location);
+unsigned long
+lttng_userspace_probe_location_hash(const struct lttng_userspace_probe_location *location);
 
-enum lttng_error_code lttng_userspace_probe_location_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer);
+enum lttng_error_code
+lttng_userspace_probe_location_mi_serialize(const struct lttng_userspace_probe_location *location,
+                                           struct mi_writer *writer);
 
 #endif /* LTTNG_USERSPACE_PROBE_INTERNAL_H */
index b6fc13508a3c02f48db57c7596cfa915d0bf150e..7de667efcb5d0555d35f04d1491fe15b4dd56523 100644 (file)
@@ -21,10 +21,10 @@ extern "C" {
 struct lttng_userspace_probe_location_lookup_method;
 
 enum lttng_userspace_probe_location_lookup_method_type {
-       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_UNKNOWN           = -1,
-       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT  = 0,
-       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF      = 1,
-       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT    = 2,
+       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_UNKNOWN = -1,
+       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT = 0,
+       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF = 1,
+       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT = 2,
 };
 
 /*
@@ -32,13 +32,13 @@ enum lttng_userspace_probe_location_lookup_method_type {
  */
 LTTNG_EXPORT extern enum lttng_userspace_probe_location_lookup_method_type
 lttng_userspace_probe_location_lookup_method_get_type(
-               const struct lttng_userspace_probe_location_lookup_method *lookup_method);
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method);
 
 /*
  * Destroy a lookup method.
  */
 LTTNG_EXPORT extern void lttng_userspace_probe_location_lookup_method_destroy(
-               struct lttng_userspace_probe_location_lookup_method *lookup_method);
+       struct lttng_userspace_probe_location_lookup_method *lookup_method);
 
 /*
  * Create a tracepoint ELF function lookup method struct.
@@ -54,7 +54,6 @@ lttng_userspace_probe_location_lookup_method_function_elf_create(void);
 LTTNG_EXPORT extern struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_lookup_method_tracepoint_sdt_create(void);
 
-
 /*
  * Contains all the information needed to compute the instrumentation point in
  * the binary. It is used in conjonction with a lookup method.
@@ -62,32 +61,30 @@ lttng_userspace_probe_location_lookup_method_tracepoint_sdt_create(void);
 struct lttng_userspace_probe_location;
 
 enum lttng_userspace_probe_location_status {
-       LTTNG_USERSPACE_PROBE_LOCATION_STATUS_OK        = 0,
+       LTTNG_USERSPACE_PROBE_LOCATION_STATUS_OK = 0,
        /* Invalid parameters provided. */
-       LTTNG_USERSPACE_PROBE_LOCATION_STATUS_INVALID   = -1,
+       LTTNG_USERSPACE_PROBE_LOCATION_STATUS_INVALID = -1,
 };
 
 enum lttng_userspace_probe_location_type {
-       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_UNKNOWN     = -1,
+       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_UNKNOWN = -1,
        /* Function. */
-       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION    = 0,
+       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION = 0,
        /* SDT probe's callsites. */
-       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT  = 1,
+       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT = 1,
 };
 
 /*
  * Get the type of the userspace probe location.
  */
 LTTNG_EXPORT extern enum lttng_userspace_probe_location_type
-lttng_userspace_probe_location_get_type(
-               const struct lttng_userspace_probe_location *location);
+lttng_userspace_probe_location_get_type(const struct lttng_userspace_probe_location *location);
 
 /*
  * Destroy the userspace probe location.
  */
-LTTNG_EXPORT extern void lttng_userspace_probe_location_destroy(
-               struct lttng_userspace_probe_location *location);
-
+LTTNG_EXPORT extern void
+lttng_userspace_probe_location_destroy(struct lttng_userspace_probe_location *location);
 
 enum lttng_userspace_probe_location_function_instrumentation_type {
        LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_UNKNOWN = -1,
@@ -104,35 +101,36 @@ enum lttng_userspace_probe_location_function_instrumentation_type {
  * location.
  */
 LTTNG_EXPORT extern struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_function_create(const char *binary_path,
-               const char *function_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method);
+lttng_userspace_probe_location_function_create(
+       const char *binary_path,
+       const char *function_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method);
 
 /*
  * Get the target binary path of the probe location of the function type.
  */
 LTTNG_EXPORT extern const char *lttng_userspace_probe_location_function_get_binary_path(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the target function type of the probe location of the function type.
  */
 LTTNG_EXPORT extern const char *lttng_userspace_probe_location_function_get_function_name(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the FD to the target binary file to the probe location of the function
  * type. The FD is only valid for the duration of the lifetime of `location`.
  */
 LTTNG_EXPORT extern int lttng_userspace_probe_location_function_get_binary_fd(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the instrumentation type of the function probe location.
  */
 LTTNG_EXPORT extern enum lttng_userspace_probe_location_function_instrumentation_type
 lttng_userspace_probe_location_function_get_instrumentation_type(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the instrumentation type of the function probe location.
@@ -145,8 +143,8 @@ lttng_userspace_probe_location_function_get_instrumentation_type(
  */
 LTTNG_EXPORT extern enum lttng_userspace_probe_location_status
 lttng_userspace_probe_location_function_set_instrumentation_type(
-               const struct lttng_userspace_probe_location *location,
-               enum lttng_userspace_probe_location_function_instrumentation_type instrumentation_type);
+       const struct lttng_userspace_probe_location *location,
+       enum lttng_userspace_probe_location_function_instrumentation_type instrumentation_type);
 
 /*
  * Get the lookup method of the given userspace probe location.
@@ -156,7 +154,7 @@ lttng_userspace_probe_location_function_set_instrumentation_type(
  */
 LTTNG_EXPORT extern const struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_get_lookup_method(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Create a probe location of the tracepoint type.
@@ -168,35 +166,37 @@ lttng_userspace_probe_location_get_lookup_method(
  * location.
  */
 LTTNG_EXPORT extern struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_tracepoint_create(const char *binary_path,
-               const char *probe_name, const char *provider_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method);
+lttng_userspace_probe_location_tracepoint_create(
+       const char *binary_path,
+       const char *probe_name,
+       const char *provider_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method);
 
 /*
  * Get the target binary path of the probe location of the tracepoint type.
  */
 LTTNG_EXPORT extern const char *lttng_userspace_probe_location_tracepoint_get_binary_path(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the target probe name of the probe location of the tracepoint type.
  */
 LTTNG_EXPORT extern const char *lttng_userspace_probe_location_tracepoint_get_probe_name(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the target probe provider name of the probe location of the tracepoint
  * type.
  */
 LTTNG_EXPORT extern const char *lttng_userspace_probe_location_tracepoint_get_provider_name(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 /*
  * Get the FD to the target binary file to the probe location of the tracepoint
  * type. The FD is only valid for the duration of the lifetime of `location`.
  */
 LTTNG_EXPORT extern int lttng_userspace_probe_location_tracepoint_get_binary_fd(
-               const struct lttng_userspace_probe_location *location);
+       const struct lttng_userspace_probe_location *location);
 
 #ifdef __cplusplus
 }
diff --git a/m4/ax_prog_doxygen.m4 b/m4/ax_prog_doxygen.m4
new file mode 100644 (file)
index 0000000..ed1dc83
--- /dev/null
@@ -0,0 +1,586 @@
+# ===========================================================================
+#     https://www.gnu.org/software/autoconf-archive/ax_prog_doxygen.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   DX_INIT_DOXYGEN(PROJECT-NAME, [DOXYFILE-PATH], [OUTPUT-DIR], ...)
+#   DX_DOXYGEN_FEATURE(ON|OFF)
+#   DX_DOT_FEATURE(ON|OFF)
+#   DX_HTML_FEATURE(ON|OFF)
+#   DX_CHM_FEATURE(ON|OFF)
+#   DX_CHI_FEATURE(ON|OFF)
+#   DX_MAN_FEATURE(ON|OFF)
+#   DX_RTF_FEATURE(ON|OFF)
+#   DX_XML_FEATURE(ON|OFF)
+#   DX_PDF_FEATURE(ON|OFF)
+#   DX_PS_FEATURE(ON|OFF)
+#
+# DESCRIPTION
+#
+#   The DX_*_FEATURE macros control the default setting for the given
+#   Doxygen feature. Supported features are 'DOXYGEN' itself, 'DOT' for
+#   generating graphics, 'HTML' for plain HTML, 'CHM' for compressed HTML
+#   help (for MS users), 'CHI' for generating a separate .chi file by the
+#   .chm file, and 'MAN', 'RTF', 'XML', 'PDF' and 'PS' for the appropriate
+#   output formats. The environment variable DOXYGEN_PAPER_SIZE may be
+#   specified to override the default 'a4wide' paper size.
+#
+#   By default, HTML, PDF and PS documentation is generated as this seems to
+#   be the most popular and portable combination. MAN pages created by
+#   Doxygen are usually problematic, though by picking an appropriate subset
+#   and doing some massaging they might be better than nothing. CHM and RTF
+#   are specific for MS (note that you can't generate both HTML and CHM at
+#   the same time). The XML is rather useless unless you apply specialized
+#   post-processing to it.
+#
+#   The macros mainly control the default state of the feature. The use can
+#   override the default by specifying --enable or --disable. The macros
+#   ensure that contradictory flags are not given (e.g.,
+#   --enable-doxygen-html and --enable-doxygen-chm,
+#   --enable-doxygen-anything with --disable-doxygen, etc.) Finally, each
+#   feature will be automatically disabled (with a warning) if the required
+#   programs are missing.
+#
+#   Once all the feature defaults have been specified, call DX_INIT_DOXYGEN
+#   with the following parameters: a one-word name for the project for use
+#   as a filename base etc., an optional configuration file name (the
+#   default is '$(srcdir)/Doxyfile', the same as Doxygen's default), and an
+#   optional output directory name (the default is 'doxygen-doc'). To run
+#   doxygen multiple times for different configuration files and output
+#   directories provide more parameters: the second, forth, sixth, etc
+#   parameter are configuration file names and the third, fifth, seventh,
+#   etc parameter are output directories. No checking is done to catch
+#   duplicates.
+#
+#   Automake Support
+#
+#   The DX_RULES substitution can be used to add all needed rules to the
+#   Makefile. Note that this is a substitution without being a variable:
+#   only the @DX_RULES@ syntax will work.
+#
+#   The provided targets are:
+#
+#     doxygen-doc: Generate all doxygen documentation.
+#
+#     doxygen-run: Run doxygen, which will generate some of the
+#                  documentation (HTML, CHM, CHI, MAN, RTF, XML)
+#                  but will not do the post processing required
+#                  for the rest of it (PS, PDF).
+#
+#     doxygen-ps:  Generate doxygen PostScript documentation.
+#
+#     doxygen-pdf: Generate doxygen PDF documentation.
+#
+#   Note that by default these are not integrated into the automake targets.
+#   If doxygen is used to generate man pages, you can achieve this
+#   integration by setting man3_MANS to the list of man pages generated and
+#   then adding the dependency:
+#
+#     $(man3_MANS): doxygen-doc
+#
+#   This will cause make to run doxygen and generate all the documentation.
+#
+#   The following variable is intended for use in Makefile.am:
+#
+#     DX_CLEANFILES = everything to clean.
+#
+#   Then add this variable to MOSTLYCLEANFILES.
+#
+# LICENSE
+#
+#   Copyright (c) 2009 Oren Ben-Kiki <oren@ben-kiki.org>
+#   Copyright (c) 2015 Olaf Mandel <olaf@mandel.name>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 24
+
+## ----------##
+## Defaults. ##
+## ----------##
+
+DX_ENV=""
+AC_DEFUN([DX_FEATURE_doc],  ON)
+AC_DEFUN([DX_FEATURE_dot],  OFF)
+AC_DEFUN([DX_FEATURE_man],  OFF)
+AC_DEFUN([DX_FEATURE_html], ON)
+AC_DEFUN([DX_FEATURE_chm],  OFF)
+AC_DEFUN([DX_FEATURE_chi],  OFF)
+AC_DEFUN([DX_FEATURE_rtf],  OFF)
+AC_DEFUN([DX_FEATURE_xml],  OFF)
+AC_DEFUN([DX_FEATURE_pdf],  ON)
+AC_DEFUN([DX_FEATURE_ps],   ON)
+
+## --------------- ##
+## Private macros. ##
+## --------------- ##
+
+# DX_ENV_APPEND(VARIABLE, VALUE)
+# ------------------------------
+# Append VARIABLE="VALUE" to DX_ENV for invoking doxygen and add it
+# as a substitution (but not a Makefile variable). The substitution
+# is skipped if the variable name is VERSION.
+AC_DEFUN([DX_ENV_APPEND],
+[AC_SUBST([DX_ENV], ["$DX_ENV $1='$2'"])dnl
+m4_if([$1], [VERSION], [], [AC_SUBST([$1], [$2])dnl
+AM_SUBST_NOTMAKE([$1])])dnl
+])
+
+# DX_DIRNAME_EXPR
+# ---------------
+# Expand into a shell expression prints the directory part of a path.
+AC_DEFUN([DX_DIRNAME_EXPR],
+         [[expr ".$1" : '\(\.\)[^/]*$' \| "x$1" : 'x\(.*\)/[^/]*$']])
+
+# DX_IF_FEATURE(FEATURE, IF-ON, IF-OFF)
+# -------------------------------------
+# Expands according to the M4 (static) status of the feature.
+AC_DEFUN([DX_IF_FEATURE], [ifelse(DX_FEATURE_$1, ON, [$2], [$3])])
+
+# DX_REQUIRE_PROG(VARIABLE, PROGRAM)
+# ----------------------------------
+# Require the specified program to be found for the DX_CURRENT_FEATURE to work.
+AC_DEFUN([DX_REQUIRE_PROG], [
+AC_PATH_TOOL([$1], [$2])
+if test "$DX_FLAG_[]DX_CURRENT_FEATURE$$1" = 1; then
+    AC_MSG_WARN([$2 not found - will not DX_CURRENT_DESCRIPTION])
+    AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0)
+fi
+])
+
+# DX_TEST_FEATURE(FEATURE)
+# ------------------------
+# Expand to a shell expression testing whether the feature is active.
+AC_DEFUN([DX_TEST_FEATURE], [test "$DX_FLAG_$1" = 1])
+
+# DX_CHECK_DEPEND(REQUIRED_FEATURE, REQUIRED_STATE)
+# -------------------------------------------------
+# Verify that a required features has the right state before trying to turn on
+# the DX_CURRENT_FEATURE.
+AC_DEFUN([DX_CHECK_DEPEND], [
+test "$DX_FLAG_$1" = "$2" \
+|| AC_MSG_ERROR([doxygen-DX_CURRENT_FEATURE ifelse([$2], 1,
+                            requires, contradicts) doxygen-$1])
+])
+
+# DX_CLEAR_DEPEND(FEATURE, REQUIRED_FEATURE, REQUIRED_STATE)
+# ----------------------------------------------------------
+# Turn off the DX_CURRENT_FEATURE if the required feature is off.
+AC_DEFUN([DX_CLEAR_DEPEND], [
+test "$DX_FLAG_$1" = "$2" || AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0)
+])
+
+# DX_FEATURE_ARG(FEATURE, DESCRIPTION,
+#                CHECK_DEPEND, CLEAR_DEPEND,
+#                REQUIRE, DO-IF-ON, DO-IF-OFF)
+# --------------------------------------------
+# Parse the command-line option controlling a feature. CHECK_DEPEND is called
+# if the user explicitly turns the feature on (and invokes DX_CHECK_DEPEND),
+# otherwise CLEAR_DEPEND is called to turn off the default state if a required
+# feature is disabled (using DX_CLEAR_DEPEND). REQUIRE performs additional
+# requirement tests (DX_REQUIRE_PROG). Finally, an automake flag is set and
+# DO-IF-ON or DO-IF-OFF are called according to the final state of the feature.
+AC_DEFUN([DX_ARG_ABLE], [
+    AC_DEFUN([DX_CURRENT_FEATURE], [$1])
+    AC_DEFUN([DX_CURRENT_DESCRIPTION], [$2])
+    AC_ARG_ENABLE(doxygen-$1,
+                  [AS_HELP_STRING(DX_IF_FEATURE([$1], [--disable-doxygen-$1],
+                                                      [--enable-doxygen-$1]),
+                                  DX_IF_FEATURE([$1], [don't $2], [$2]))],
+                  [
+case "$enableval" in
+#(
+y|Y|yes|Yes|YES)
+    AC_SUBST([DX_FLAG_$1], 1)
+    $3
+;; #(
+n|N|no|No|NO)
+    AC_SUBST([DX_FLAG_$1], 0)
+;; #(
+*)
+    AC_MSG_ERROR([invalid value '$enableval' given to doxygen-$1])
+;;
+esac
+], [
+AC_SUBST([DX_FLAG_$1], [DX_IF_FEATURE([$1], 1, 0)])
+$4
+])
+if DX_TEST_FEATURE([$1]); then
+    $5
+    :
+fi
+if DX_TEST_FEATURE([$1]); then
+    $6
+    :
+else
+    $7
+    :
+fi
+])
+
+## -------------- ##
+## Public macros. ##
+## -------------- ##
+
+# DX_XXX_FEATURE(DEFAULT_STATE)
+# -----------------------------
+AC_DEFUN([DX_DOXYGEN_FEATURE], [AC_DEFUN([DX_FEATURE_doc],  [$1])])
+AC_DEFUN([DX_DOT_FEATURE],     [AC_DEFUN([DX_FEATURE_dot], [$1])])
+AC_DEFUN([DX_MAN_FEATURE],     [AC_DEFUN([DX_FEATURE_man],  [$1])])
+AC_DEFUN([DX_HTML_FEATURE],    [AC_DEFUN([DX_FEATURE_html], [$1])])
+AC_DEFUN([DX_CHM_FEATURE],     [AC_DEFUN([DX_FEATURE_chm],  [$1])])
+AC_DEFUN([DX_CHI_FEATURE],     [AC_DEFUN([DX_FEATURE_chi],  [$1])])
+AC_DEFUN([DX_RTF_FEATURE],     [AC_DEFUN([DX_FEATURE_rtf],  [$1])])
+AC_DEFUN([DX_XML_FEATURE],     [AC_DEFUN([DX_FEATURE_xml],  [$1])])
+AC_DEFUN([DX_XML_FEATURE],     [AC_DEFUN([DX_FEATURE_xml],  [$1])])
+AC_DEFUN([DX_PDF_FEATURE],     [AC_DEFUN([DX_FEATURE_pdf],  [$1])])
+AC_DEFUN([DX_PS_FEATURE],      [AC_DEFUN([DX_FEATURE_ps],   [$1])])
+
+# DX_INIT_DOXYGEN(PROJECT, [CONFIG-FILE], [OUTPUT-DOC-DIR], ...)
+# --------------------------------------------------------------
+# PROJECT also serves as the base name for the documentation files.
+# The default CONFIG-FILE is "$(srcdir)/Doxyfile" and OUTPUT-DOC-DIR is
+# "doxygen-doc".
+# More arguments are interpreted as interleaved CONFIG-FILE and
+# OUTPUT-DOC-DIR values.
+AC_DEFUN([DX_INIT_DOXYGEN], [
+
+# Files:
+AC_SUBST([DX_PROJECT], [$1])
+AC_SUBST([DX_CONFIG], ['ifelse([$2], [], [$(srcdir)/Doxyfile], [$2])'])
+AC_SUBST([DX_DOCDIR], ['ifelse([$3], [], [doxygen-doc], [$3])'])
+m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2,
+      [AC_SUBST([DX_CONFIG]m4_eval(DX_i[/2]),
+                'm4_default_nblank_quoted(m4_argn(DX_i, $@),
+                                          [$(srcdir)/Doxyfile])')])])dnl
+m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 5, m4_count($@,), 2,
+      [AC_SUBST([DX_DOCDIR]m4_eval([(]DX_i[-1)/2]),
+                'm4_default_nblank_quoted(m4_argn(DX_i, $@),
+                                          [doxygen-doc])')])])dnl
+m4_define([DX_loop], m4_dquote(m4_if(m4_eval(3 < m4_count($@)), 1,
+          [m4_for([DX_i], 4, m4_count($@), 2, [, m4_eval(DX_i[/2])])],
+          [])))dnl
+
+# Environment variables used inside doxygen.cfg:
+DX_ENV_APPEND(SRCDIR, $srcdir)
+DX_ENV_APPEND(PROJECT, $DX_PROJECT)
+DX_ENV_APPEND(VERSION, $PACKAGE_VERSION)
+
+# Doxygen itself:
+DX_ARG_ABLE(doc, [generate any doxygen documentation],
+            [],
+            [],
+            [DX_REQUIRE_PROG([DX_DOXYGEN], doxygen)
+             DX_REQUIRE_PROG([DX_PERL], perl)],
+            [DX_ENV_APPEND(PERL_PATH, $DX_PERL)])
+
+# Dot for graphics:
+DX_ARG_ABLE(dot, [generate graphics for doxygen documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [DX_REQUIRE_PROG([DX_DOT], dot)],
+            [DX_ENV_APPEND(HAVE_DOT, YES)
+             DX_ENV_APPEND(DOT_PATH, [`DX_DIRNAME_EXPR($DX_DOT)`])],
+            [DX_ENV_APPEND(HAVE_DOT, NO)])
+
+# Man pages generation:
+DX_ARG_ABLE(man, [generate doxygen manual pages],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [],
+            [DX_ENV_APPEND(GENERATE_MAN, YES)],
+            [DX_ENV_APPEND(GENERATE_MAN, NO)])
+
+# RTF file generation:
+DX_ARG_ABLE(rtf, [generate doxygen RTF documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [],
+            [DX_ENV_APPEND(GENERATE_RTF, YES)],
+            [DX_ENV_APPEND(GENERATE_RTF, NO)])
+
+# XML file generation:
+DX_ARG_ABLE(xml, [generate doxygen XML documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [],
+            [DX_ENV_APPEND(GENERATE_XML, YES)],
+            [DX_ENV_APPEND(GENERATE_XML, NO)])
+
+# (Compressed) HTML help generation:
+DX_ARG_ABLE(chm, [generate doxygen compressed HTML help documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [DX_REQUIRE_PROG([DX_HHC], hhc)],
+            [DX_ENV_APPEND(HHC_PATH, $DX_HHC)
+             DX_ENV_APPEND(GENERATE_HTML, YES)
+             DX_ENV_APPEND(GENERATE_HTMLHELP, YES)],
+            [DX_ENV_APPEND(GENERATE_HTMLHELP, NO)])
+
+# Separate CHI file generation.
+DX_ARG_ABLE(chi, [generate doxygen separate compressed HTML help index file],
+            [DX_CHECK_DEPEND(chm, 1)],
+            [DX_CLEAR_DEPEND(chm, 1)],
+            [],
+            [DX_ENV_APPEND(GENERATE_CHI, YES)],
+            [DX_ENV_APPEND(GENERATE_CHI, NO)])
+
+# Plain HTML pages generation:
+DX_ARG_ABLE(html, [generate doxygen plain HTML documentation],
+            [DX_CHECK_DEPEND(doc, 1) DX_CHECK_DEPEND(chm, 0)],
+            [DX_CLEAR_DEPEND(doc, 1) DX_CLEAR_DEPEND(chm, 0)],
+            [],
+            [DX_ENV_APPEND(GENERATE_HTML, YES)],
+            [DX_TEST_FEATURE(chm) || DX_ENV_APPEND(GENERATE_HTML, NO)])
+
+# PostScript file generation:
+DX_ARG_ABLE(ps, [generate doxygen PostScript documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [DX_REQUIRE_PROG([DX_LATEX], latex)
+             DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex)
+             DX_REQUIRE_PROG([DX_DVIPS], dvips)
+             DX_REQUIRE_PROG([DX_EGREP], egrep)])
+
+# PDF file generation:
+DX_ARG_ABLE(pdf, [generate doxygen PDF documentation],
+            [DX_CHECK_DEPEND(doc, 1)],
+            [DX_CLEAR_DEPEND(doc, 1)],
+            [DX_REQUIRE_PROG([DX_PDFLATEX], pdflatex)
+             DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex)
+             DX_REQUIRE_PROG([DX_EGREP], egrep)])
+
+# LaTeX generation for PS and/or PDF:
+if DX_TEST_FEATURE(ps) || DX_TEST_FEATURE(pdf); then
+    DX_ENV_APPEND(GENERATE_LATEX, YES)
+else
+    DX_ENV_APPEND(GENERATE_LATEX, NO)
+fi
+
+# Paper size for PS and/or PDF:
+AC_ARG_VAR(DOXYGEN_PAPER_SIZE,
+           [a4wide (default), a4, letter, legal or executive])
+case "$DOXYGEN_PAPER_SIZE" in
+#(
+"")
+    AC_SUBST(DOXYGEN_PAPER_SIZE, "")
+;; #(
+a4wide|a4|letter|legal|executive)
+    DX_ENV_APPEND(PAPER_SIZE, $DOXYGEN_PAPER_SIZE)
+;; #(
+*)
+    AC_MSG_ERROR([unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE'])
+;;
+esac
+
+# Rules:
+AS_IF([[test $DX_FLAG_html -eq 1]],
+[[DX_SNIPPET_html="## ------------------------------- ##
+## Rules specific for HTML output. ##
+## ------------------------------- ##
+
+DX_CLEAN_HTML = \$(DX_DOCDIR)/html]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+                \$(DX_DOCDIR]DX_i[)/html]])[
+
+"]],
+[[DX_SNIPPET_html=""]])
+AS_IF([[test $DX_FLAG_chi -eq 1]],
+[[DX_SNIPPET_chi="
+DX_CLEAN_CHI = \$(DX_DOCDIR)/\$(PACKAGE).chi]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).chi]])["]],
+[[DX_SNIPPET_chi=""]])
+AS_IF([[test $DX_FLAG_chm -eq 1]],
+[[DX_SNIPPET_chm="## ------------------------------ ##
+## Rules specific for CHM output. ##
+## ------------------------------ ##
+
+DX_CLEAN_CHM = \$(DX_DOCDIR)/chm]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/chm]])[\
+${DX_SNIPPET_chi}
+
+"]],
+[[DX_SNIPPET_chm=""]])
+AS_IF([[test $DX_FLAG_man -eq 1]],
+[[DX_SNIPPET_man="## ------------------------------ ##
+## Rules specific for MAN output. ##
+## ------------------------------ ##
+
+DX_CLEAN_MAN = \$(DX_DOCDIR)/man]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/man]])[
+
+"]],
+[[DX_SNIPPET_man=""]])
+AS_IF([[test $DX_FLAG_rtf -eq 1]],
+[[DX_SNIPPET_rtf="## ------------------------------ ##
+## Rules specific for RTF output. ##
+## ------------------------------ ##
+
+DX_CLEAN_RTF = \$(DX_DOCDIR)/rtf]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/rtf]])[
+
+"]],
+[[DX_SNIPPET_rtf=""]])
+AS_IF([[test $DX_FLAG_xml -eq 1]],
+[[DX_SNIPPET_xml="## ------------------------------ ##
+## Rules specific for XML output. ##
+## ------------------------------ ##
+
+DX_CLEAN_XML = \$(DX_DOCDIR)/xml]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/xml]])[
+
+"]],
+[[DX_SNIPPET_xml=""]])
+AS_IF([[test $DX_FLAG_ps -eq 1]],
+[[DX_SNIPPET_ps="## ----------------------------- ##
+## Rules specific for PS output. ##
+## ----------------------------- ##
+
+DX_CLEAN_PS = \$(DX_DOCDIR)/\$(PACKAGE).ps]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+              \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps]])[
+
+DX_PS_GOAL = doxygen-ps
+
+doxygen-ps: \$(DX_CLEAN_PS)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag
+       \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\
+       rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\
+       \$(DX_LATEX) refman.tex; \\
+       \$(DX_MAKEINDEX) refman.idx; \\
+       \$(DX_LATEX) refman.tex; \\
+       countdown=5; \\
+       while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\
+                         refman.log > /dev/null 2>&1 \\
+          && test \$\$countdown -gt 0; do \\
+           \$(DX_LATEX) refman.tex; \\
+            countdown=\`expr \$\$countdown - 1\`; \\
+       done; \\
+       \$(DX_DVIPS) -o ../\$(PACKAGE).ps refman.dvi
+
+]])["]],
+[[DX_SNIPPET_ps=""]])
+AS_IF([[test $DX_FLAG_pdf -eq 1]],
+[[DX_SNIPPET_pdf="## ------------------------------ ##
+## Rules specific for PDF output. ##
+## ------------------------------ ##
+
+DX_CLEAN_PDF = \$(DX_DOCDIR)/\$(PACKAGE).pdf]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+               \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf]])[
+
+DX_PDF_GOAL = doxygen-pdf
+
+doxygen-pdf: \$(DX_CLEAN_PDF)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag
+       \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\
+       rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\
+       \$(DX_PDFLATEX) refman.tex; \\
+       \$(DX_MAKEINDEX) refman.idx; \\
+       \$(DX_PDFLATEX) refman.tex; \\
+       countdown=5; \\
+       while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\
+                         refman.log > /dev/null 2>&1 \\
+          && test \$\$countdown -gt 0; do \\
+           \$(DX_PDFLATEX) refman.tex; \\
+           countdown=\`expr \$\$countdown - 1\`; \\
+       done; \\
+       mv refman.pdf ../\$(PACKAGE).pdf
+
+]])["]],
+[[DX_SNIPPET_pdf=""]])
+AS_IF([[test $DX_FLAG_ps -eq 1 -o $DX_FLAG_pdf -eq 1]],
+[[DX_SNIPPET_latex="## ------------------------------------------------- ##
+## Rules specific for LaTeX (shared for PS and PDF). ##
+## ------------------------------------------------- ##
+
+DX_V_LATEX = \$(_DX_v_LATEX_\$(V))
+_DX_v_LATEX_ = \$(_DX_v_LATEX_\$(AM_DEFAULT_VERBOSITY))
+_DX_v_LATEX_0 = @echo \"  LATEX \" \$][@;
+
+DX_CLEAN_LATEX = \$(DX_DOCDIR)/latex]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+                 \$(DX_DOCDIR]DX_i[)/latex]])[
+
+"]],
+[[DX_SNIPPET_latex=""]])
+
+AS_IF([[test $DX_FLAG_doc -eq 1]],
+[[DX_SNIPPET_doc="## --------------------------------- ##
+## Format-independent Doxygen rules. ##
+## --------------------------------- ##
+
+${DX_SNIPPET_html}\
+${DX_SNIPPET_chm}\
+${DX_SNIPPET_man}\
+${DX_SNIPPET_rtf}\
+${DX_SNIPPET_xml}\
+${DX_SNIPPET_ps}\
+${DX_SNIPPET_pdf}\
+${DX_SNIPPET_latex}\
+DX_V_DXGEN = \$(_DX_v_DXGEN_\$(V))
+_DX_v_DXGEN_ = \$(_DX_v_DXGEN_\$(AM_DEFAULT_VERBOSITY))
+_DX_v_DXGEN_0 = @echo \"  DXGEN \" \$<;
+
+.PHONY: doxygen-run doxygen-doc \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+.INTERMEDIATE: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+doxygen-run:]m4_foreach([DX_i], [DX_loop],
+                         [[ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag]])[
+
+doxygen-doc: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag: \$(DX_CONFIG]DX_i[) \$(pkginclude_HEADERS)
+       \$(A""M_V_at)rm -rf \$(DX_DOCDIR]DX_i[)
+       \$(DX_V_DXGEN)\$(DX_ENV) DOCDIR=\$(DX_DOCDIR]DX_i[) \$(DX_DOXYGEN) \$(DX_CONFIG]DX_i[)
+       \$(A""M_V_at)echo Timestamp >\$][@
+
+]])dnl
+[DX_CLEANFILES = \\]
+m4_foreach([DX_i], [DX_loop],
+[[     \$(DX_DOCDIR]DX_i[)/doxygen_sqlite3.db \\
+       \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \\
+]])dnl
+[      -r \\
+       \$(DX_CLEAN_HTML) \\
+       \$(DX_CLEAN_CHM) \\
+       \$(DX_CLEAN_CHI) \\
+       \$(DX_CLEAN_MAN) \\
+       \$(DX_CLEAN_RTF) \\
+       \$(DX_CLEAN_XML) \\
+       \$(DX_CLEAN_PS) \\
+       \$(DX_CLEAN_PDF) \\
+       \$(DX_CLEAN_LATEX)"]],
+[[DX_SNIPPET_doc=""]])
+AC_SUBST([DX_RULES],
+["${DX_SNIPPET_doc}"])dnl
+AM_SUBST_NOTMAKE([DX_RULES])
+
+#For debugging:
+#echo DX_FLAG_doc=$DX_FLAG_doc
+#echo DX_FLAG_dot=$DX_FLAG_dot
+#echo DX_FLAG_man=$DX_FLAG_man
+#echo DX_FLAG_html=$DX_FLAG_html
+#echo DX_FLAG_chm=$DX_FLAG_chm
+#echo DX_FLAG_chi=$DX_FLAG_chi
+#echo DX_FLAG_rtf=$DX_FLAG_rtf
+#echo DX_FLAG_xml=$DX_FLAG_xml
+#echo DX_FLAG_pdf=$DX_FLAG_pdf
+#echo DX_FLAG_ps=$DX_FLAG_ps
+#echo DX_ENV=$DX_ENV
+])
diff --git a/pre-inst-env.in b/pre-inst-env.in
new file mode 100644 (file)
index 0000000..f779aa4
--- /dev/null
@@ -0,0 +1,39 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Copyright (c) 2023 Olivier Dion <odion@efficios.com>
+
+srcdir=$(realpath "@abs_top_srcdir@")
+builddir=$(realpath "@abs_top_builddir@")
+bin="$builddir/src/bin"
+
+# lttng-sessiond setup.
+LTTNG_SESSION_CONFIG_XSD_PATH="$srcdir/src/common"
+export LTTNG_SESSION_CONFIG_XSD_PATH
+
+LTTNG_CONSUMERD32_BIN="$bin/lttng-consumerd/lttng-consumerd"
+LTTNG_CONSUMERD64_BIN="$bin/lttng-consumerd/lttng-consumerd"
+export LTTNG_CONSUMERD32_BIN
+export LTTNG_CONSUMERD64_BIN
+
+# lttng-create setup.
+LTTNG_SESSIOND_PATH="$bin/lttng-sessiond/lttng-sessiond"
+export LTTNG_SESSIOND_PATH
+
+# Easy access to binaries.
+PATH="$bin/lttng:$bin/lttng-consumerd:$bin/lttng-crash:$bin/lttng-relayd:$bin/lttng-sessiond:$PATH"
+export PATH
+
+# Use local path to search manual pages.
+MANPATH="$builddir/doc/man"
+export MANPATH
+
+# Use local path to search manual pages for lttng --help.
+LTTNG_MANPATH="$builddir/doc/man"
+export LTTNG_MANPATH
+
+# Use system man instead of /usr/bin/man.
+LTTNG_MAN_BIN_PATH=$(type -p man)
+export LTTNG_MAN_BIN_PATH
+
+exec "$@"
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644 (file)
index 0000000..28c78a0
--- /dev/null
@@ -0,0 +1,4 @@
+[project]
+requires-python = ">= 3.4"
+
+[tool.black]
index 8417fc6dccfca4122561edeadb4b2d623dc9f029..d0a6ce14fd451e35cc3036533dc8fcb59bc71352 100644 (file)
@@ -6,59 +6,44 @@
  */
 
 #define _LGPL_SOURCE
+#include "health-consumerd.hpp"
+#include "lttng-consumerd.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/poll.hpp>
+#include <common/consumer/consumer-timer.hpp>
+#include <common/consumer/consumer.hpp>
+#include <common/defaults.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
 #include <fcntl.h>
 #include <getopt.h>
 #include <grp.h>
+#include <inttypes.h>
 #include <limits.h>
+#include <poll.h>
 #include <pthread.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/ipc.h>
+#include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/shm.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <urcu/list.h>
-#include <poll.h>
+#include <ulimit.h>
 #include <unistd.h>
-#include <sys/mman.h>
 #include <urcu/compiler.h>
-#include <ulimit.h>
-#include <inttypes.h>
-
-#include <common/defaults.hpp>
-#include <common/common.hpp>
-#include <common/consumer/consumer.hpp>
-#include <common/consumer/consumer-timer.hpp>
-#include <common/compat/poll.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
-
-#include "lttng-consumerd.hpp"
-#include "health-consumerd.hpp"
+#include <urcu/list.h>
 
 /* Global health check unix path */
 static char health_unix_sock_path[PATH_MAX];
 
-int health_quit_pipe[2];
-
-/*
- * Check if the thread quit pipe was triggered.
- *
- * Return 1 if it was triggered else 0;
- */
-static
-int check_health_quit_pipe(int fd, uint32_t events)
-{
-       if (fd == health_quit_pipe[0] && (events & LPOLLIN)) {
-               return 1;
-       }
-
-       return 0;
-}
+int health_quit_pipe[2] = { -1, -1 };
 
 /*
  * Send data on a unix socket using the liblttsessiondcomm API.
@@ -75,8 +60,7 @@ static int send_unix_sock(int sock, void *buf, size_t len)
        return lttcomm_send_unix_sock(sock, buf, len);
 }
 
-static
-int setup_health_path(void)
+static int setup_health_path()
 {
        int is_root, ret = 0;
        enum lttng_consumer_type type;
@@ -91,16 +75,19 @@ int setup_health_path(void)
                }
                switch (type) {
                case LTTNG_CONSUMER_KERNEL:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_GLOBAL_KCONSUMER_HEALTH_UNIX_SOCK);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_GLOBAL_KCONSUMER_HEALTH_UNIX_SOCK);
                        break;
                case LTTNG_CONSUMER64_UST:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_GLOBAL_USTCONSUMER64_HEALTH_UNIX_SOCK);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_GLOBAL_USTCONSUMER64_HEALTH_UNIX_SOCK);
                        break;
                case LTTNG_CONSUMER32_UST:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_GLOBAL_USTCONSUMER32_HEALTH_UNIX_SOCK);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_GLOBAL_USTCONSUMER32_HEALTH_UNIX_SOCK);
                        break;
                default:
                        ret = -EINVAL;
@@ -108,7 +95,7 @@ int setup_health_path(void)
                }
        } else {
                home_path = utils_get_home_dir();
-               if (home_path == NULL) {
+               if (home_path == nullptr) {
                        /* TODO: Add --socket PATH option */
                        ERR("Can't get HOME directory for sockets creation.");
                        ret = -EPERM;
@@ -121,16 +108,22 @@ int setup_health_path(void)
                }
                switch (type) {
                case LTTNG_CONSUMER_KERNEL:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_HOME_KCONSUMER_HEALTH_UNIX_SOCK, home_path);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_HOME_KCONSUMER_HEALTH_UNIX_SOCK,
+                                home_path);
                        break;
                case LTTNG_CONSUMER64_UST:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_HOME_USTCONSUMER64_HEALTH_UNIX_SOCK, home_path);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_HOME_USTCONSUMER64_HEALTH_UNIX_SOCK,
+                                home_path);
                        break;
                case LTTNG_CONSUMER32_UST:
-                       snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                               DEFAULT_HOME_USTCONSUMER32_HEALTH_UNIX_SOCK, home_path);
+                       snprintf(health_unix_sock_path,
+                                sizeof(health_unix_sock_path),
+                                DEFAULT_HOME_USTCONSUMER32_HEALTH_UNIX_SOCK,
+                                home_path);
                        break;
                default:
                        ret = -EINVAL;
@@ -146,8 +139,8 @@ end:
  */
 void *thread_manage_health_consumerd(void *data __attribute__((unused)))
 {
-       int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int sock = -1, new_sock = -1, ret, i, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct health_comm_msg msg;
        struct health_comm_reply reply;
@@ -189,8 +182,7 @@ void *thread_manage_health_consumerd(void *data __attribute__((unused)))
                        goto error;
                }
 
-               ret = chmod(health_unix_sock_path,
-                               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+               ret = chmod(health_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
                if (ret < 0) {
                        ERR("Unable to set permissions on %s", health_unix_sock_path);
                        PERROR("chmod");
@@ -232,11 +224,11 @@ void *thread_manage_health_consumerd(void *data __attribute__((unused)))
        cmm_smp_mb__before_uatomic_dec();
        uatomic_dec(&lttng_consumer_ready);
 
-       while (1) {
+       while (true) {
                DBG("Health check ready");
 
                /* Inifinite blocking call, waiting for transmission */
-restart:
+       restart:
                ret = lttng_poll_wait(&events, -1);
                if (ret < 0) {
                        /*
@@ -252,20 +244,20 @@ restart:
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_health_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       /* Activity on health quit pipe, exiting. */
+                       if (pollfd == health_quit_pipe[0]) {
+                               DBG("Activity on health quit pipe");
                                err = 0;
                                goto exit;
                        }
 
                        /* Event on the registration socket */
                        if (pollfd == sock) {
-                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
-                                               && !(revents & LPOLLIN)) {
+                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP) &&
+                                   !(revents & LPOLLIN)) {
                                        ERR("Health socket poll error");
                                        goto error;
                                }
@@ -284,7 +276,7 @@ restart:
                (void) utils_set_fd_cloexec(new_sock);
 
                DBG("Receiving data from client for health...");
-               ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
+               ret = lttcomm_recv_unix_sock(new_sock, (void *) &msg, sizeof(msg));
                if (ret <= 0) {
                        DBG("Nothing recv() from client... continuing");
                        ret = close(new_sock);
@@ -342,5 +334,5 @@ error:
        lttng_poll_clean(&events);
 
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
index 4e3bf8686ec99884103e06de0f07eb41eeb11fc8..109ccb4c449f6f80ca94a573bb7005622a08ae79 100644 (file)
 #include <lttng/health-internal.hpp>
 
 enum health_type_consumerd {
-       HEALTH_CONSUMERD_TYPE_CHANNEL           = 0,
-       HEALTH_CONSUMERD_TYPE_METADATA          = 1,
-       HEALTH_CONSUMERD_TYPE_DATA              = 2,
-       HEALTH_CONSUMERD_TYPE_SESSIOND          = 3,
-       HEALTH_CONSUMERD_TYPE_METADATA_TIMER    = 4,
+       HEALTH_CONSUMERD_TYPE_CHANNEL = 0,
+       HEALTH_CONSUMERD_TYPE_METADATA = 1,
+       HEALTH_CONSUMERD_TYPE_DATA = 2,
+       HEALTH_CONSUMERD_TYPE_SESSIOND = 3,
+       HEALTH_CONSUMERD_TYPE_METADATA_TIMER = 4,
 
        NR_HEALTH_CONSUMERD_TYPES,
 };
index a8bda52ba7bdccf74ccea7e5339a0b7855bfc7c8..e46b6b6716ccddecea67ff43e0295ca364287d9f 100644 (file)
@@ -7,53 +7,53 @@
  */
 
 #define _LGPL_SOURCE
+#include "health-consumerd.hpp"
+#include "lttng-consumerd.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/getenv.hpp>
+#include <common/compat/poll.hpp>
+#include <common/consumer/consumer-timer.hpp>
+#include <common/consumer/consumer.hpp>
+#include <common/defaults.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
 #include <fcntl.h>
 #include <getopt.h>
 #include <grp.h>
 #include <limits.h>
+#include <poll.h>
 #include <pthread.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/ipc.h>
+#include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/shm.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <urcu/list.h>
-#include <poll.h>
+#include <ulimit.h>
 #include <unistd.h>
-#include <sys/mman.h>
 #include <urcu/compiler.h>
-#include <ulimit.h>
-
-#include <common/defaults.hpp>
-#include <common/common.hpp>
-#include <common/consumer/consumer.hpp>
-#include <common/consumer/consumer-timer.hpp>
-#include <common/compat/poll.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
-
-#include "lttng-consumerd.hpp"
-#include "health-consumerd.hpp"
+#include <urcu/list.h>
 
 /* threads (channel handling, poll, metadata, sessiond) */
 
-static pthread_t channel_thread, data_thread, metadata_thread,
-               sessiond_thread, metadata_timer_thread, health_thread;
+static pthread_t channel_thread, data_thread, metadata_thread, sessiond_thread,
+       metadata_timer_thread, health_thread;
 static bool metadata_timer_thread_online;
 
 /* to count the number of times the user pressed ctrl+c */
 static int sigintcount = 0;
 
 /* Argument variables */
-int lttng_opt_quiet;    /* not static in error.h */
-int lttng_opt_verbose;  /* not static in error.h */
-int lttng_opt_mi;       /* not static in error.h */
+int lttng_opt_quiet; /* not static in error.h */
+int lttng_opt_verbose; /* not static in error.h */
+int lttng_opt_mi; /* not static in error.h */
 
 static int opt_daemon;
 static const char *progname;
@@ -82,8 +82,7 @@ enum lttng_consumer_type lttng_consumer_get_type(void)
 /*
  * Signal handler for the daemon
  */
-static void sighandler(int sig, siginfo_t *siginfo,
-               void *arg __attribute__((unused)))
+static void sighandler(int sig, siginfo_t *siginfo, void *arg __attribute__((unused)))
 {
        if (sig == SIGINT && sigintcount++ == 0) {
                DBG("ignoring first SIGINT");
@@ -116,7 +115,7 @@ static void sighandler(int sig, siginfo_t *siginfo,
  * Setup signal handler for :
  *      SIGINT, SIGTERM, SIGPIPE, SIGBUS
  */
-static int set_signal_handler(void)
+static int set_signal_handler()
 {
        int ret = 0;
        struct sigaction sa;
@@ -131,24 +130,24 @@ static int set_signal_handler(void)
        sa.sa_flags = SA_SIGINFO;
 
        sa.sa_sigaction = sighandler;
-       if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGTERM, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGINT, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGBUS, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGBUS, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
        sa.sa_flags = 0;
        sa.sa_handler = SIG_IGN;
-       if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGPIPE, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
@@ -162,32 +161,42 @@ static int set_signal_handler(void)
 static void usage(FILE *fp)
 {
        fprintf(fp, "Usage: %s OPTIONS\n\nOptions:\n", progname);
-       fprintf(fp, "  -h, --help                         "
-                       "Display this usage.\n");
-       fprintf(fp, "  -c, --consumerd-cmd-sock PATH      "
-                       "Specify path for the command socket\n");
-       fprintf(fp, "  -e, --consumerd-err-sock PATH      "
-                       "Specify path for the error socket\n");
-       fprintf(fp, "  -d, --daemonize                    "
-                       "Start as a daemon.\n");
-       fprintf(fp, "  -q, --quiet                        "
-                       "No output at all.\n");
-       fprintf(fp, "  -v, --verbose                      "
-                       "Verbose mode. Activate DBG() macro.\n");
-       fprintf(fp, "  -V, --version                      "
-                       "Show version number.\n");
-       fprintf(fp, "  -g, --group NAME                   "
-                       "Specify the tracing group name. (default: tracing)\n");
-       fprintf(fp, "  -k, --kernel                       "
-                       "Consumer kernel buffers (default).\n");
-       fprintf(fp, "  -u, --ust                          "
-                       "Consumer UST buffers.%s\n",
+       fprintf(fp,
+               "  -h, --help                         "
+               "Display this usage.\n");
+       fprintf(fp,
+               "  -c, --consumerd-cmd-sock PATH      "
+               "Specify path for the command socket\n");
+       fprintf(fp,
+               "  -e, --consumerd-err-sock PATH      "
+               "Specify path for the error socket\n");
+       fprintf(fp,
+               "  -d, --daemonize                    "
+               "Start as a daemon.\n");
+       fprintf(fp,
+               "  -q, --quiet                        "
+               "No output at all.\n");
+       fprintf(fp,
+               "  -v, --verbose                      "
+               "Verbose mode. Activate DBG() macro.\n");
+       fprintf(fp,
+               "  -V, --version                      "
+               "Show version number.\n");
+       fprintf(fp,
+               "  -g, --group NAME                   "
+               "Specify the tracing group name. (default: tracing)\n");
+       fprintf(fp,
+               "  -k, --kernel                       "
+               "Consumer kernel buffers (default).\n");
+       fprintf(fp,
+               "  -u, --ust                          "
+               "Consumer UST buffers.%s\n",
 #ifdef HAVE_LIBLTTNG_UST_CTL
-                       ""
+               ""
 #else
-                       " (support not compiled in)"
+               " (support not compiled in)"
 #endif
-                       );
+       );
 }
 
 /*
@@ -197,34 +206,35 @@ static int parse_args(int argc, char **argv)
 {
        int c, ret = 0;
 
-       static struct option long_options[] = {
-               { "consumerd-cmd-sock", 1, 0, 'c' },
-               { "consumerd-err-sock", 1, 0, 'e' },
-               { "daemonize", 0, 0, 'd' },
-               { "group", 1, 0, 'g' },
-               { "help", 0, 0, 'h' },
-               { "quiet", 0, 0, 'q' },
-               { "verbose", 0, 0, 'v' },
-               { "version", 0, 0, 'V' },
-               { "kernel", 0, 0, 'k' },
+       static struct option long_options[] = { { "consumerd-cmd-sock", 1, nullptr, 'c' },
+                                               { "consumerd-err-sock", 1, nullptr, 'e' },
+                                               { "daemonize", 0, nullptr, 'd' },
+                                               { "group", 1, nullptr, 'g' },
+                                               { "help", 0, nullptr, 'h' },
+                                               { "quiet", 0, nullptr, 'q' },
+                                               { "verbose", 0, nullptr, 'v' },
+                                               { "version", 0, nullptr, 'V' },
+                                               { "kernel", 0, nullptr, 'k' },
 #ifdef HAVE_LIBLTTNG_UST_CTL
-               { "ust", 0, 0, 'u' },
+                                               { "ust", 0, nullptr, 'u' },
 #endif
-               { NULL, 0, 0, 0 }
-       };
+                                               { nullptr, 0, nullptr, 0 } };
 
-       while (1) {
+       while (true) {
                int option_index = 0;
-               c = getopt_long(argc, argv, "dhqvVku" "c:e:g:",
-                               long_options, &option_index);
+               c = getopt_long(argc,
+                               argv,
+                               "dhqvVku"
+                               "c:e:g:",
+                               long_options,
+                               &option_index);
                if (c == -1) {
                        break;
                }
 
                switch (c) {
                case 0:
-                       fprintf(stderr, "option %s",
-                               long_options[option_index].name);
+                       fprintf(stderr, "option %s", long_options[option_index].name);
                        if (optarg) {
                                fprintf(stderr, " with arg %s\n", optarg);
                                ret = -1;
@@ -234,7 +244,7 @@ static int parse_args(int argc, char **argv)
                case 'c':
                        if (lttng_is_setuid_setgid()) {
                                WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                                       "-c, --consumerd-cmd-sock");
+                                    "-c, --consumerd-cmd-sock");
                        } else {
                                snprintf(command_sock_path, PATH_MAX, "%s", optarg);
                        }
@@ -242,7 +252,7 @@ static int parse_args(int argc, char **argv)
                case 'e':
                        if (lttng_is_setuid_setgid()) {
                                WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                                       "-e, --consumerd-err-sock");
+                                    "-e, --consumerd-err-sock");
                        } else {
                                snprintf(error_sock_path, PATH_MAX, "%s", optarg);
                        }
@@ -253,7 +263,7 @@ static int parse_args(int argc, char **argv)
                case 'g':
                        if (lttng_is_setuid_setgid()) {
                                WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                                       "-g, --group");
+                                    "-g, --group");
                        } else {
                                tracing_group_name = optarg;
                        }
@@ -275,13 +285,13 @@ static int parse_args(int argc, char **argv)
                        break;
 #ifdef HAVE_LIBLTTNG_UST_CTL
                case 'u':
-# if (CAA_BITS_PER_LONG == 64)
+#if (CAA_BITS_PER_LONG == 64)
                        opt_type = LTTNG_CONSUMER64_UST;
-# elif (CAA_BITS_PER_LONG == 32)
+#elif (CAA_BITS_PER_LONG == 32)
                        opt_type = LTTNG_CONSUMER32_UST;
-# else
-#  error "Unknown bitness"
-# endif
+#else
+#error "Unknown bitness"
+#endif
                        break;
 #endif
                default:
@@ -298,7 +308,7 @@ end:
  * Set open files limit to unlimited. This daemon can open a large number of
  * file descriptors in order to consumer multiple kernel traces.
  */
-static void set_ulimit(void)
+static void set_ulimit()
 {
        int ret;
        struct rlimit lim;
@@ -324,7 +334,7 @@ int main(int argc, char **argv)
 
        rcu_register_thread();
 
-       if (run_as_create_worker(argv[0], NULL, NULL) < 0) {
+       if (run_as_create_worker(argv[0], nullptr, nullptr) < 0) {
                goto exit_set_signal_handler;
        }
 
@@ -379,27 +389,30 @@ int main(int argc, char **argv)
        if (*command_sock_path == '\0') {
                switch (opt_type) {
                case LTTNG_CONSUMER_KERNEL:
-                       ret = snprintf(command_sock_path, PATH_MAX,
-                                       DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(command_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
                        }
                        break;
                case LTTNG_CONSUMER64_UST:
-                       ret = snprintf(command_sock_path, PATH_MAX,
-                                       DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(command_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
                        }
                        break;
                case LTTNG_CONSUMER32_UST:
-                       ret = snprintf(command_sock_path, PATH_MAX,
-                                       DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(command_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
@@ -429,8 +442,11 @@ int main(int argc, char **argv)
        }
 
        /* create the consumer instance with and assign the callbacks */
-       the_consumer_context = lttng_consumer_create(opt_type, lttng_consumer_read_subbuffer,
-               NULL, lttng_consumer_on_recv_stream, NULL);
+       the_consumer_context = lttng_consumer_create(opt_type,
+                                                    lttng_consumer_read_subbuffer,
+                                                    nullptr,
+                                                    lttng_consumer_on_recv_stream,
+                                                    nullptr);
        if (!the_consumer_context) {
                retval = -1;
                goto exit_init_data;
@@ -440,27 +456,30 @@ int main(int argc, char **argv)
        if (*error_sock_path == '\0') {
                switch (opt_type) {
                case LTTNG_CONSUMER_KERNEL:
-                       ret = snprintf(error_sock_path, PATH_MAX,
-                                       DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(error_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
                        }
                        break;
                case LTTNG_CONSUMER64_UST:
-                       ret = snprintf(error_sock_path, PATH_MAX,
-                                       DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(error_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
                        }
                        break;
                case LTTNG_CONSUMER32_UST:
-                       ret = snprintf(error_sock_path, PATH_MAX,
-                                       DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
-                                       DEFAULT_LTTNG_RUNDIR);
+                       ret = snprintf(error_sock_path,
+                                      PATH_MAX,
+                                      DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
+                                      DEFAULT_LTTNG_RUNDIR);
                        if (ret < 0) {
                                retval = -1;
                                goto exit_init_data;
@@ -502,8 +521,10 @@ int main(int argc, char **argv)
        }
 
        /* Create thread to manage the client socket */
-       ret = pthread_create(&health_thread, default_pthread_attr(),
-                       thread_manage_health_consumerd, (void *) NULL);
+       ret = pthread_create(&health_thread,
+                            default_pthread_attr(),
+                            thread_manage_health_consumerd,
+                            (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create health");
@@ -518,14 +539,16 @@ int main(int argc, char **argv)
        while (uatomic_read(&lttng_consumer_ready)) {
                usleep(100000);
        }
-       cmm_smp_mb();   /* Read ready before following operations */
+       cmm_smp_mb(); /* Read ready before following operations */
 
        /*
         * Create the thread to manage the UST metadata periodic timer and
         * live timer.
         */
-       ret = pthread_create(&metadata_timer_thread, NULL,
-                       consumer_timer_thread, (void *) the_consumer_context);
+       ret = pthread_create(&metadata_timer_thread,
+                            nullptr,
+                            consumer_timer_thread,
+                            (void *) the_consumer_context);
        if (ret) {
                errno = ret;
                PERROR("pthread_create");
@@ -535,9 +558,10 @@ int main(int argc, char **argv)
        metadata_timer_thread_online = true;
 
        /* Create thread to manage channels */
-       ret = pthread_create(&channel_thread, default_pthread_attr(),
-                       consumer_thread_channel_poll,
-                       (void *) the_consumer_context);
+       ret = pthread_create(&channel_thread,
+                            default_pthread_attr(),
+                            consumer_thread_channel_poll,
+                            (void *) the_consumer_context);
        if (ret) {
                errno = ret;
                PERROR("pthread_create");
@@ -546,9 +570,10 @@ int main(int argc, char **argv)
        }
 
        /* Create thread to manage the polling/writing of trace metadata */
-       ret = pthread_create(&metadata_thread, default_pthread_attr(),
-                       consumer_thread_metadata_poll,
-                       (void *) the_consumer_context);
+       ret = pthread_create(&metadata_thread,
+                            default_pthread_attr(),
+                            consumer_thread_metadata_poll,
+                            (void *) the_consumer_context);
        if (ret) {
                errno = ret;
                PERROR("pthread_create");
@@ -557,8 +582,10 @@ int main(int argc, char **argv)
        }
 
        /* Create thread to manage the polling/writing of trace data */
-       ret = pthread_create(&data_thread, default_pthread_attr(),
-                       consumer_thread_data_poll, (void *) the_consumer_context);
+       ret = pthread_create(&data_thread,
+                            default_pthread_attr(),
+                            consumer_thread_data_poll,
+                            (void *) the_consumer_context);
        if (ret) {
                errno = ret;
                PERROR("pthread_create");
@@ -567,9 +594,10 @@ int main(int argc, char **argv)
        }
 
        /* Create the thread to manage the reception of fds */
-       ret = pthread_create(&sessiond_thread, default_pthread_attr(),
-                       consumer_thread_sessiond_poll,
-                       (void *) the_consumer_context);
+       ret = pthread_create(&sessiond_thread,
+                            default_pthread_attr(),
+                            consumer_thread_sessiond_poll,
+                            (void *) the_consumer_context);
        if (ret) {
                errno = ret;
                PERROR("pthread_create");
@@ -577,7 +605,6 @@ int main(int argc, char **argv)
                goto exit_sessiond_thread;
        }
 
-
        /*
         * This is where we start awaiting program completion (e.g. through
         * signal that asks threads to teardown.
@@ -665,8 +692,8 @@ exit_init_data:
                metadata_timer_thread_online = false;
        }
        tmp_ctx = the_consumer_context;
-       the_consumer_context = NULL;
-       cmm_barrier();  /* Clear ctx for signal handler. */
+       the_consumer_context = nullptr;
+       cmm_barrier(); /* Clear ctx for signal handler. */
        lttng_consumer_destroy(tmp_ctx);
 
        if (health_consumerd) {
index 833116ade67062ab22d9830f2156f1e9132d59f2..f21d5abba90c8205cafee47eac4c73faa92f6a48 100644 (file)
@@ -9,8 +9,9 @@
 #ifndef _LTTNG_CONSUMERD_H
 #define _LTTNG_CONSUMERD_H
 
+#include <common/consumer/consumer.hpp>
 
-#define NR_LTTNG_CONSUMER_READY                1
+#define NR_LTTNG_CONSUMER_READY 1
 extern int lttng_consumer_ready;
 
 extern const char *tracing_group_name;
@@ -20,7 +21,6 @@ extern const char *tracing_group_name;
  * have a C linkage name makes it easier, as it avoids having to look up a
  * mangled name.
  */
-extern "C" LTTNG_EXPORT
-enum lttng_consumer_type lttng_consumer_get_type();
+extern "C" LTTNG_EXPORT enum lttng_consumer_type lttng_consumer_get_type();
 
 #endif /* _LTTNG_CONSUMERD_H */
index 3987a60ddac334d2e75fabf213102c7d4d1ea0f6..d4e41e0336fe95ace3fb532885f954e2397b99fb 100644 (file)
@@ -6,34 +6,34 @@
  *
  */
 
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/spawn-viewer.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
+#include <ctype.h>
+#include <dirent.h>
+#include <fcntl.h>
 #include <getopt.h>
+#include <inttypes.h>
 #include <signal.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-#include <fcntl.h>
 #include <sys/wait.h>
 #include <unistd.h>
-#include <ctype.h>
-#include <dirent.h>
-#include <common/compat/endian.hpp>
-#include <inttypes.h>
-#include <stdbool.h>
-
 #include <version.hpp>
-#include <lttng/lttng.h>
-#include <common/common.hpp>
-#include <common/spawn-viewer.hpp>
-#include <common/utils.hpp>
 
-#define COPY_BUFLEN            4096
-#define RB_CRASH_DUMP_ABI_LEN  32
+#define COPY_BUFLEN          4096
+#define RB_CRASH_DUMP_ABI_LEN 32
 
-#define RB_CRASH_DUMP_ABI_MAGIC_LEN    16
+#define RB_CRASH_DUMP_ABI_MAGIC_LEN 16
 
 /*
  * The 128-bit magic number is xor'd in the process data so it does not
  *   0x17, 0x7B, 0xF1, 0x77, 0xBF, 0x17, 0x7B, 0xF1,
  *   0x77, 0xBF, 0x17, 0x7B, 0xF1, 0x77, 0xBF, 0x17,
  */
-#define RB_CRASH_DUMP_ABI_MAGIC_XOR                                    \
-       {                                                               \
-               0x17 ^ 0xFF, 0x7B ^ 0xFF, 0xF1 ^ 0xFF, 0x77 ^ 0xFF,     \
-               0xBF ^ 0xFF, 0x17 ^ 0xFF, 0x7B ^ 0xFF, 0xF1 ^ 0xFF,     \
-               0x77 ^ 0xFF, 0xBF ^ 0xFF, 0x17 ^ 0xFF, 0x7B ^ 0xFF,     \
-               0xF1 ^ 0xFF, 0x77 ^ 0xFF, 0xBF ^ 0xFF, 0x17 ^ 0xFF,     \
+#define RB_CRASH_DUMP_ABI_MAGIC_XOR                                                           \
+       {                                                                                     \
+               0x17 ^ 0xFF, 0x7B ^ 0xFF, 0xF1 ^ 0xFF, 0x77 ^ 0xFF, 0xBF ^ 0xFF, 0x17 ^ 0xFF, \
+                       0x7B ^ 0xFF, 0xF1 ^ 0xFF, 0x77 ^ 0xFF, 0xBF ^ 0xFF, 0x17 ^ 0xFF,      \
+                       0x7B ^ 0xFF, 0xF1 ^ 0xFF, 0x77 ^ 0xFF, 0xBF ^ 0xFF, 0x17 ^ 0xFF,      \
        }
 
 static const char *help_msg =
 #ifdef LTTNG_EMBED_HELP
 #include <lttng-crash.1.h>
 #else
-NULL
+       nullptr
 #endif
-;
+       ;
 
 /*
  * Non-static to ensure the compiler does not optimize away the xor.
  */
 uint8_t lttng_crash_expected_magic_xor[] = RB_CRASH_DUMP_ABI_MAGIC_XOR;
 
-#define RB_CRASH_ENDIAN                        0x1234
-#define RB_CRASH_ENDIAN_REVERSE                0x3412
+#define RB_CRASH_ENDIAN                0x1234
+#define RB_CRASH_ENDIAN_REVERSE 0x3412
 
 enum lttng_crash_type {
        LTTNG_CRASH_TYPE_UST = 0,
@@ -73,43 +72,43 @@ enum lttng_crash_type {
 
 /* LTTng ring buffer defines (copied) */
 
-#define HALF_ULONG_BITS(wl)    (((wl) * CHAR_BIT) >> 1)
+#define HALF_ULONG_BITS(wl) (((wl) *CHAR_BIT) >> 1)
 
-#define SB_ID_OFFSET_SHIFT(wl) (HALF_ULONG_BITS(wl) + 1)
-#define SB_ID_OFFSET_COUNT(wl) (1UL << SB_ID_OFFSET_SHIFT(wl))
-#define SB_ID_OFFSET_MASK(wl)  (~(SB_ID_OFFSET_COUNT(wl) - 1))
+#define SB_ID_OFFSET_SHIFT(wl) (HALF_ULONG_BITS(wl) + 1)
+#define SB_ID_OFFSET_COUNT(wl) (1UL << SB_ID_OFFSET_SHIFT(wl))
+#define SB_ID_OFFSET_MASK(wl)  (~(SB_ID_OFFSET_COUNT(wl) - 1))
 /*
  * Lowest bit of top word half belongs to noref. Used only for overwrite mode.
  */
-#define SB_ID_NOREF_SHIFT(wl)  (SB_ID_OFFSET_SHIFT(wl) - 1)
-#define SB_ID_NOREF_COUNT(wl)  (1UL << SB_ID_NOREF_SHIFT(wl))
-#define SB_ID_NOREF_MASK(wl)   SB_ID_NOREF_COUNT(wl)
+#define SB_ID_NOREF_SHIFT(wl) (SB_ID_OFFSET_SHIFT(wl) - 1)
+#define SB_ID_NOREF_COUNT(wl) (1UL << SB_ID_NOREF_SHIFT(wl))
+#define SB_ID_NOREF_MASK(wl)  SB_ID_NOREF_COUNT(wl)
 /*
  * In overwrite mode: lowest half of word is used for index.
  * Limit of 2^16 subbuffers per buffer on 32-bit, 2^32 on 64-bit.
  * In producer-consumer mode: whole word used for index.
  */
-#define SB_ID_INDEX_SHIFT(wl)  0
-#define SB_ID_INDEX_COUNT(wl)  (1UL << SB_ID_INDEX_SHIFT(wl))
-#define SB_ID_INDEX_MASK(wl)   (SB_ID_NOREF_COUNT(wl) - 1)
+#define SB_ID_INDEX_SHIFT(wl) 0
+#define SB_ID_INDEX_COUNT(wl) (1UL << SB_ID_INDEX_SHIFT(wl))
+#define SB_ID_INDEX_MASK(wl)  (SB_ID_NOREF_COUNT(wl) - 1)
 
 enum rb_modes {
-       RING_BUFFER_OVERWRITE = 0,      /* Overwrite when buffer full */
-       RING_BUFFER_DISCARD = 1,        /* Discard when buffer full */
+       RING_BUFFER_OVERWRITE = 0, /* Overwrite when buffer full */
+       RING_BUFFER_DISCARD = 1, /* Discard when buffer full */
 };
 
 namespace {
 struct crash_abi_unknown {
        uint8_t magic[RB_CRASH_DUMP_ABI_MAGIC_LEN];
-       uint64_t mmap_length;   /* Overall length of crash record */
-       uint16_t endian;        /*
-                                * { 0x12, 0x34 }: big endian
-                                * { 0x34, 0x12 }: little endian
-                                */
-       uint16_t major;         /* Major number. */
-       uint16_t minor;         /* Minor number. */
-       uint8_t word_size;      /* Word size (bytes). */
-       uint8_t layout_type;    /* enum lttng_crash_layout */
+       uint64_t mmap_length; /* Overall length of crash record */
+       uint16_t endian; /*
+                         * { 0x12, 0x34 }: big endian
+                         * { 0x34, 0x12 }: little endian
+                         */
+       uint16_t major; /* Major number. */
+       uint16_t minor; /* Minor number. */
+       uint8_t word_size; /* Word size (bytes). */
+       uint8_t layout_type; /* enum lttng_crash_layout */
 } __attribute__((packed));
 
 struct crash_abi_0_0 {
@@ -144,26 +143,21 @@ struct crash_abi_0_0 {
                uint32_t sb_array;
        } __attribute__((packed)) stride;
 
-       uint64_t buf_size;      /* Size of the buffer */
-       uint64_t subbuf_size;   /* Sub-buffer size */
-       uint64_t num_subbuf;    /* Number of sub-buffers for writer */
-       uint32_t mode;          /* Buffer mode: 0: overwrite, 1: discard */
+       uint64_t buf_size; /* Size of the buffer */
+       uint64_t subbuf_size; /* Sub-buffer size */
+       uint64_t num_subbuf; /* Number of sub-buffers for writer */
+       uint32_t mode; /* Buffer mode: 0: overwrite, 1: discard */
 } __attribute__((packed));
 
 struct lttng_crash_layout {
        struct {
-               int prod_offset, consumed_offset,
-                       commit_hot_array, commit_hot_seq,
-                       buf_wsb_array, buf_wsb_id,
-                       sb_array, sb_array_shmp_offset,
-                       sb_backend_p_offset, content_size,
-                       packet_size;
+               int prod_offset, consumed_offset, commit_hot_array, commit_hot_seq, buf_wsb_array,
+                       buf_wsb_id, sb_array, sb_array_shmp_offset, sb_backend_p_offset,
+                       content_size, packet_size;
        } offset;
        struct {
-               int prod_offset, consumed_offset,
-                       commit_hot_seq, buf_wsb_id,
-                       sb_array_shmp_offset, sb_backend_p_offset,
-                       content_size, packet_size;
+               int prod_offset, consumed_offset, commit_hot_seq, buf_wsb_id, sb_array_shmp_offset,
+                       sb_backend_p_offset, content_size, packet_size;
        } length;
        struct {
                int commit_hot_array, buf_wsb_array, sb_array;
@@ -172,18 +166,18 @@ struct lttng_crash_layout {
        int reverse_byte_order;
        int word_size;
 
-       uint64_t mmap_length;   /* Length of crash record */
-       uint64_t buf_size;      /* Size of the buffer */
-       uint64_t subbuf_size;   /* Sub-buffer size */
-       uint64_t num_subbuf;    /* Number of sub-buffers for writer */
-       uint32_t mode;          /* Buffer mode: 0: overwrite, 1: discard */
+       uint64_t mmap_length; /* Length of crash record */
+       uint64_t buf_size; /* Size of the buffer */
+       uint64_t subbuf_size; /* Sub-buffer size */
+       uint64_t num_subbuf; /* Number of sub-buffers for writer */
+       uint32_t mode; /* Buffer mode: 0: overwrite, 1: discard */
 };
 } /* namespace */
 
 /* Variables */
 static const char *progname;
-static char *opt_viewer_path = NULL;
-static char *opt_output_path = NULL;
+static char *opt_viewer_path = nullptr;
+static char *opt_output_path = nullptr;
 
 static char *the_input_path;
 
@@ -195,16 +189,13 @@ enum {
 
 /* Getopt options. No first level command. */
 static struct option long_options[] = {
-       { "version",            0, NULL, 'V' },
-       { "help",               0, NULL, 'h' },
-       { "verbose",            0, NULL, 'v' },
-       { "viewer",             1, NULL, 'e' },
-       { "extract",            1, NULL, 'x' },
-       { "list-options",       0, NULL, OPT_DUMP_OPTIONS },
-       { NULL, 0, NULL, 0 },
+       { "version", 0, nullptr, 'V' }, { "help", 0, nullptr, 'h' },
+       { "verbose", 0, nullptr, 'v' }, { "viewer", 1, nullptr, 'e' },
+       { "extract", 1, nullptr, 'x' }, { "list-options", 0, nullptr, OPT_DUMP_OPTIONS },
+       { nullptr, 0, nullptr, 0 },
 };
 
-static void usage(void)
+static void usage()
 {
        int ret = utils_show_help(1, "lttng-crash", help_msg);
 
@@ -217,11 +208,11 @@ static void usage(void)
 
 static void version(FILE *ofp)
 {
-       fprintf(ofp, "%s (LTTng Crash Trace Viewer) " VERSION " - " VERSION_NAME
-                       "%s%s\n",
-                       progname,
-                       GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
-                       EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
+       fprintf(ofp,
+               "%s (LTTng Crash Trace Viewer) " VERSION " - " VERSION_NAME "%s%s\n",
+               progname,
+               GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
+               EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
 }
 
 /*
@@ -233,10 +224,10 @@ static void version(FILE *ofp)
 static void list_options(FILE *ofp)
 {
        int i = 0;
-       struct option *option = NULL;
+       struct option *option = nullptr;
 
        option = &long_options[i];
-       while (option->name != NULL) {
+       while (option->name != nullptr) {
                fprintf(ofp, "--%s\n", option->name);
 
                if (isprint(option->val)) {
@@ -262,7 +253,7 @@ static int parse_args(int argc, char **argv)
                exit(EXIT_FAILURE);
        }
 
-       while ((opt = getopt_long(argc, argv, "+Vhve:x:", long_options, NULL)) != -1) {
+       while ((opt = getopt_long(argc, argv, "+Vhve:x:", long_options, nullptr)) != -1) {
                switch (opt) {
                case 'V':
                        version(stdout);
@@ -310,8 +301,7 @@ error:
        return -1;
 }
 
-static
-int copy_file(const char *file_dest, const char *file_src)
+static int copy_file(const char *file_dest, const char *file_src)
 {
        int fd_src = -1, fd_dest = -1;
        ssize_t readlen, writelen;
@@ -326,8 +316,7 @@ int copy_file(const char *file_dest, const char *file_src)
                ret = -errno;
                goto error;
        }
-       fd_dest = open(file_dest, O_RDWR | O_CREAT | O_EXCL,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       fd_dest = open(file_dest, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
        if (fd_dest < 0) {
                PERROR("Error opening %s for writing", file_dest);
                ret = -errno;
@@ -368,25 +357,26 @@ error:
        return ret;
 }
 
-static
-uint64_t _crash_get_field(const struct lttng_crash_layout *layout,
-               const char *ptr, size_t size)
+static uint64_t
+_crash_get_field(const struct lttng_crash_layout *layout, const char *ptr, size_t size)
 {
        switch (size) {
-       case 1: return *(uint8_t *) ptr;
-       case 2: if (layout->reverse_byte_order) {
+       case 1:
+               return *(uint8_t *) ptr;
+       case 2:
+               if (layout->reverse_byte_order) {
                        return bswap_16(*(uint16_t *) ptr);
                } else {
                        return *(uint16_t *) ptr;
-
                }
-       case 4: if (layout->reverse_byte_order) {
+       case 4:
+               if (layout->reverse_byte_order) {
                        return bswap_32(*(uint32_t *) ptr);
                } else {
                        return *(uint32_t *) ptr;
-
                }
-       case 8: if (layout->reverse_byte_order) {
+       case 8:
+               if (layout->reverse_byte_order) {
                        return bswap_64(*(uint64_t *) ptr);
                } else {
                        return *(uint64_t *) ptr;
@@ -395,37 +385,30 @@ uint64_t _crash_get_field(const struct lttng_crash_layout *layout,
                abort();
                return -1;
        }
-
 }
 
-#define crash_get_field(layout, map, name)                             \
-       _crash_get_field(layout, (map) + (layout)->offset.name,         \
-               layout->length.name)
-
-#define crash_get_array_field(layout, map, array_name, idx, field_name)        \
-       _crash_get_field(layout,                                        \
-               (map) + (layout)->offset.array_name                     \
-                       + (idx * (layout)->stride.array_name)           \
-                       + (layout)->offset.field_name,                  \
-               (layout)->length.field_name)
-
-#define crash_get_hdr_raw_field(layout, hdr, name)     ((hdr)->name)
-
-#define crash_get_hdr_field(layout, hdr, name)                         \
-       _crash_get_field(layout, (const char *) &(hdr)->name,           \
-               sizeof((hdr)->name))
-
-#define crash_get_layout(layout, hdr, name)                            \
-       do {                                                            \
-               (layout)->name = crash_get_hdr_field(layout, hdr,       \
-                                       name);                          \
-               DBG("layout.%s = %" PRIu64, #name,                      \
-                       (uint64_t) (layout)->name);                     \
+#define crash_get_field(layout, map, name) \
+       _crash_get_field(layout, (map) + (layout)->offset.name, (layout)->length.name)
+
+#define crash_get_array_field(layout, map, array_name, idx, field_name)  \
+       _crash_get_field(layout,                                         \
+                        (map) + (layout)->offset.array_name +           \
+                                ((idx) * (layout)->stride.array_name) + \
+                                (layout)->offset.field_name,            \
+                        (layout)->length.field_name)
+
+#define crash_get_hdr_raw_field(layout, hdr, name) ((hdr)->name)
+
+#define crash_get_hdr_field(layout, hdr, name) \
+       _crash_get_field(layout, (const char *) &(hdr)->name, sizeof((hdr)->name))
+
+#define crash_get_layout(layout, hdr, name)                                    \
+       do {                                                                   \
+               (layout)->name = crash_get_hdr_field(layout, hdr, name);       \
+               DBG("layout.%s = %" PRIu64, #name, (uint64_t) (layout)->name); \
        } while (0)
 
-static
-int get_crash_layout_0_0(struct lttng_crash_layout *layout,
-               char *map)
+static int get_crash_layout_0_0(struct lttng_crash_layout *layout, char *map)
 {
        const struct crash_abi_0_0 *abi = (const struct crash_abi_0_0 *) map;
 
@@ -462,18 +445,28 @@ int get_crash_layout_0_0(struct lttng_crash_layout *layout,
        return 0;
 }
 
-static
-void print_dbg_magic(const uint8_t *magic)
+static void print_dbg_magic(const uint8_t *magic)
 {
        DBG("magic: 0x%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X",
-               magic[0], magic[1], magic[2], magic[3],
-               magic[4], magic[5], magic[6], magic[7],
-               magic[8], magic[9], magic[10], magic[11],
-               magic[12], magic[13], magic[14], magic[15]);
+           magic[0],
+           magic[1],
+           magic[2],
+           magic[3],
+           magic[4],
+           magic[5],
+           magic[6],
+           magic[7],
+           magic[8],
+           magic[9],
+           magic[10],
+           magic[11],
+           magic[12],
+           magic[13],
+           magic[14],
+           magic[15]);
 }
 
-static
-int check_magic(const uint8_t *magic)
+static int check_magic(const uint8_t *magic)
 {
        int i;
 
@@ -485,9 +478,7 @@ int check_magic(const uint8_t *magic)
        return 0;
 }
 
-static
-int get_crash_layout(struct lttng_crash_layout *layout, int fd,
-               const char *input_file)
+static int get_crash_layout(struct lttng_crash_layout *layout, int fd, const char *input_file)
 {
        char *map;
        int ret = 0, unmapret;
@@ -507,14 +498,14 @@ int get_crash_layout(struct lttng_crash_layout *layout, int fd,
        }
        if (stat.st_size < RB_CRASH_DUMP_ABI_LEN) {
                ERR("File '%s' truncated: file length of %" PRIi64
-                               " bytes does not meet the minimal expected "
-                               "length of %d bytes",
-                               input_file, (int64_t) stat.st_size,
-                               RB_CRASH_DUMP_ABI_LEN);
+                   " bytes does not meet the minimal expected "
+                   "length of %d bytes",
+                   input_file,
+                   (int64_t) stat.st_size,
+                   RB_CRASH_DUMP_ABI_LEN);
                return -1;
        }
-       map = (char *) mmap(NULL, RB_CRASH_DUMP_ABI_LEN, PROT_READ, MAP_PRIVATE,
-               fd, 0);
+       map = (char *) mmap(nullptr, RB_CRASH_DUMP_ABI_LEN, PROT_READ, MAP_PRIVATE, fd, 0);
        if (map == MAP_FAILED) {
                PERROR("Mapping file");
                return -1;
@@ -524,7 +515,7 @@ int get_crash_layout(struct lttng_crash_layout *layout, int fd,
        print_dbg_magic(magic);
        if (check_magic(magic)) {
                DBG("Unknown magic number");
-               ret = 1;        /* positive return value, skip */
+               ret = 1; /* positive return value, skip */
                goto end;
        }
        endian = crash_get_hdr_field(layout, abi, endian);
@@ -536,7 +527,7 @@ int get_crash_layout(struct lttng_crash_layout *layout, int fd,
                break;
        default:
                DBG("Unknown endianness value: 0x%X", (unsigned int) endian);
-               ret = 1;        /* positive return value, skip */
+               ret = 1; /* positive return value, skip */
                goto end;
        }
        layout_type = (enum lttng_crash_type) crash_get_hdr_field(layout, abi, layout_type);
@@ -545,11 +536,11 @@ int get_crash_layout(struct lttng_crash_layout *layout, int fd,
                break;
        case LTTNG_CRASH_TYPE_KERNEL:
                ERR("lttng-modules buffer layout support not implemented");
-               ret = 1;        /* positive return value, skip */
+               ret = 1; /* positive return value, skip */
                goto end;
        default:
                ERR("Unknown layout type %u", (unsigned int) layout_type);
-               ret = 1;        /* positive return value, skip */
+               ret = 1; /* positive return value, skip */
                goto end;
        }
        mmap_length = crash_get_hdr_field(layout, abi, mmap_length);
@@ -590,43 +581,36 @@ end:
 }
 
 /* buf_trunc mask selects only the buffer number. */
-static inline
-uint64_t buf_trunc(uint64_t offset, uint64_t buf_size)
+static inline uint64_t buf_trunc(uint64_t offset, uint64_t buf_size)
 {
        return offset & ~(buf_size - 1);
 }
 
 /* subbuf_trunc mask selects the subbuffer number. */
-static inline
-uint64_t subbuf_trunc(uint64_t offset, uint64_t subbuf_size)
+static inline uint64_t subbuf_trunc(uint64_t offset, uint64_t subbuf_size)
 {
        return offset & ~(subbuf_size - 1);
 }
 
 /* buf_offset mask selects only the offset within the current buffer. */
-static inline
-uint64_t buf_offset(uint64_t offset, uint64_t buf_size)
+static inline uint64_t buf_offset(uint64_t offset, uint64_t buf_size)
 {
        return offset & (buf_size - 1);
 }
 
 /* subbuf_offset mask selects the offset within the current subbuffer. */
-static inline
-uint64_t subbuf_offset(uint64_t offset, uint64_t subbuf_size)
+static inline uint64_t subbuf_offset(uint64_t offset, uint64_t subbuf_size)
 {
        return offset & (subbuf_size - 1);
 }
 
 /* subbuf_index returns the index of the current subbuffer within the buffer. */
-static inline
-uint64_t subbuf_index(uint64_t offset, uint64_t buf_size, uint64_t subbuf_size)
+static inline uint64_t subbuf_index(uint64_t offset, uint64_t buf_size, uint64_t subbuf_size)
 {
        return buf_offset(offset, buf_size) / subbuf_size;
 }
 
-static inline
-uint64_t subbuffer_id_get_index(uint32_t mode, uint64_t id,
-               unsigned int wl)
+static inline uint64_t subbuffer_id_get_index(uint32_t mode, uint64_t id, unsigned int wl)
 {
        if (mode == RING_BUFFER_OVERWRITE)
                return id & SB_ID_INDEX_MASK(wl);
@@ -634,14 +618,11 @@ uint64_t subbuffer_id_get_index(uint32_t mode, uint64_t id,
                return id;
 }
 
-static
-int copy_crash_subbuf(const struct lttng_crash_layout *layout,
-               int fd_dest, char *buf, uint64_t offset)
+static int
+copy_crash_subbuf(const struct lttng_crash_layout *layout, int fd_dest, char *buf, uint64_t offset)
 {
-       uint64_t buf_size, subbuf_size, num_subbuf, sbidx, id,
-               sb_bindex, rpages_offset, p_offset, seq_cc,
-               committed, commit_count_mask, consumed_cur,
-               packet_size;
+       uint64_t buf_size, subbuf_size, num_subbuf, sbidx, id, sb_bindex, rpages_offset, p_offset,
+               seq_cc, committed, commit_count_mask, consumed_cur, packet_size;
        char *subbuf_ptr;
        ssize_t writelen;
 
@@ -656,13 +637,14 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
        num_subbuf = layout->num_subbuf;
 
        switch (layout->word_size) {
-       case 4: commit_count_mask = 0xFFFFFFFFULL / num_subbuf;
+       case 4:
+               commit_count_mask = 0xFFFFFFFFULL / num_subbuf;
                break;
-       case 8: commit_count_mask = 0xFFFFFFFFFFFFFFFFULL / num_subbuf;
+       case 8:
+               commit_count_mask = 0xFFFFFFFFFFFFFFFFULL / num_subbuf;
                break;
        default:
-               ERR("Unsupported word size: %u",
-                       (unsigned int) layout->word_size);
+               ERR("Unsupported word size: %u", (unsigned int) layout->word_size);
                return -EINVAL;
        }
 
@@ -673,16 +655,16 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
         * Find where the seq cc is located. Compute length of data to
         * copy.
         */
-       seq_cc = crash_get_array_field(layout, buf, commit_hot_array,
-               sbidx, commit_hot_seq);
+       seq_cc = crash_get_array_field(layout, buf, commit_hot_array, sbidx, commit_hot_seq);
        consumed_cur = crash_get_field(layout, buf, consumed_offset);
 
        /*
         * Check that the buffer we are getting is after or at
         * consumed_cur position.
         */
-       if ((long) subbuf_trunc(offset, subbuf_size)
-                       - (long) subbuf_trunc(consumed_cur, subbuf_size) < 0) {
+       if ((long) subbuf_trunc(offset, subbuf_size) -
+                   (long) subbuf_trunc(consumed_cur, subbuf_size) <
+           0) {
                DBG("No data: position is before consumed_cur");
                goto nodata;
        }
@@ -690,9 +672,9 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
        /*
         * Check if subbuffer has been fully committed.
         */
-       if (((seq_cc - subbuf_size) & commit_count_mask)
-                       - (buf_trunc(offset, buf_size) / num_subbuf)
-                       == 0) {
+       if (((seq_cc - subbuf_size) & commit_count_mask) -
+                   (buf_trunc(offset, buf_size) / num_subbuf) ==
+           0) {
                committed = subbuf_size;
        } else {
                committed = subbuf_offset(seq_cc, subbuf_size);
@@ -703,14 +685,11 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
        }
 
        /* Find actual physical offset in subbuffer table */
-       id = crash_get_array_field(layout, buf, buf_wsb_array,
-               sbidx, buf_wsb_id);
-       sb_bindex = subbuffer_id_get_index(layout->mode, id,
-               layout->word_size);
-       rpages_offset = crash_get_array_field(layout, buf, sb_array,
-               sb_bindex, sb_array_shmp_offset);
-       p_offset = crash_get_field(layout, buf + rpages_offset,
-               sb_backend_p_offset);
+       id = crash_get_array_field(layout, buf, buf_wsb_array, sbidx, buf_wsb_id);
+       sb_bindex = subbuffer_id_get_index(layout->mode, id, layout->word_size);
+       rpages_offset =
+               crash_get_array_field(layout, buf, sb_array, sb_bindex, sb_array_shmp_offset);
+       p_offset = crash_get_field(layout, buf + rpages_offset, sb_backend_p_offset);
        subbuf_ptr = buf + p_offset;
 
        if (committed == subbuf_size) {
@@ -719,8 +698,8 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
                 */
                if (layout->length.packet_size) {
                        memcpy(&packet_size,
-                               subbuf_ptr + layout->offset.packet_size,
-                               layout->length.packet_size);
+                              subbuf_ptr + layout->offset.packet_size,
+                              layout->length.packet_size);
                        if (layout->reverse_byte_order) {
                                packet_size = bswap_64(packet_size);
                        }
@@ -742,11 +721,13 @@ int copy_crash_subbuf(const struct lttng_crash_layout *layout,
                }
                if (layout->length.content_size) {
                        memcpy(subbuf_ptr + layout->offset.content_size,
-                               &patch_size, layout->length.content_size);
+                              &patch_size,
+                              layout->length.content_size);
                }
                if (layout->length.packet_size) {
                        memcpy(subbuf_ptr + layout->offset.packet_size,
-                               &patch_size, layout->length.packet_size);
+                              &patch_size,
+                              layout->length.packet_size);
                }
                packet_size = committed;
        }
@@ -766,9 +747,7 @@ nodata:
        return -ENODATA;
 }
 
-static
-int copy_crash_data(const struct lttng_crash_layout *layout, int fd_dest,
-               int fd_src)
+static int copy_crash_data(const struct lttng_crash_layout *layout, int fd_dest, int fd_src)
 {
        char *buf;
        int ret = 0, has_data = 0;
@@ -800,8 +779,7 @@ int copy_crash_data(const struct lttng_crash_layout *layout, int fd_dest,
        DBG("consumed_offset: 0x%" PRIx64, consumed_offset);
        subbuf_size = layout->subbuf_size;
 
-       for (offset = consumed_offset; offset < prod_offset;
-                       offset += subbuf_size) {
+       for (offset = consumed_offset; offset < prod_offset; offset += subbuf_size) {
                ret = copy_crash_subbuf(layout, fd_dest, buf, offset);
                if (!ret) {
                        has_data = 1;
@@ -822,20 +800,18 @@ end:
        }
 }
 
-static
-int extract_file(int output_dir_fd, const char *output_file,
-               int input_dir_fd, const char *input_file)
+static int
+extract_file(int output_dir_fd, const char *output_file, int input_dir_fd, const char *input_file)
 {
        int fd_dest, fd_src, ret = 0, closeret;
        struct lttng_crash_layout layout;
 
-       layout.reverse_byte_order = 0;  /* For reading magic number */
+       layout.reverse_byte_order = 0; /* For reading magic number */
 
        DBG("Extract file '%s'", input_file);
        fd_src = openat(input_dir_fd, input_file, O_RDONLY);
        if (fd_src < 0) {
-               PERROR("Error opening '%s' for reading",
-                       input_file);
+               PERROR("Error opening '%s' for reading", input_file);
                ret = -1;
                goto end;
        }
@@ -846,12 +822,12 @@ int extract_file(int output_dir_fd, const char *output_file,
                goto close_src;
        }
 
-       fd_dest = openat(output_dir_fd, output_file,
-                       O_RDWR | O_CREAT | O_EXCL,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       fd_dest = openat(output_dir_fd,
+                        output_file,
+                        O_RDWR | O_CREAT | O_EXCL,
+                        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
        if (fd_dest < 0) {
-               PERROR("Error opening '%s' for writing",
-                       output_file);
+               PERROR("Error opening '%s' for writing", output_file);
                ret = -1;
                goto close_src;
        }
@@ -881,13 +857,11 @@ end:
        return ret;
 }
 
-static
-int extract_all_files(const char *output_path,
-               const char *input_path)
+static int extract_all_files(const char *output_path, const char *input_path)
 {
        DIR *input_dir, *output_dir;
        int input_dir_fd, output_dir_fd, ret = 0, closeret;
-       struct dirent *entry;   /* input */
+       struct dirent *entry; /* input */
 
        /* Open input directory */
        input_dir = opendir(input_path);
@@ -914,11 +888,9 @@ int extract_all_files(const char *output_path,
        }
 
        while ((entry = readdir(input_dir))) {
-               if (!strcmp(entry->d_name, ".")
-                               || !strcmp(entry->d_name, ".."))
+               if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
                        continue;
-               ret = extract_file(output_dir_fd, entry->d_name,
-                       input_dir_fd, entry->d_name);
+               ret = extract_file(output_dir_fd, entry->d_name, input_dir_fd, entry->d_name);
                if (ret == -ENODATA) {
                        DBG("No data in file '%s', skipping", entry->d_name);
                        ret = 0;
@@ -942,9 +914,7 @@ int extract_all_files(const char *output_path,
        return ret;
 }
 
-static
-int extract_one_trace(const char *output_path,
-               const char *input_path)
+static int extract_one_trace(const char *output_path, const char *input_path)
 {
        char dest[PATH_MAX], src[PATH_MAX];
        int ret;
@@ -969,9 +939,7 @@ int extract_one_trace(const char *output_path,
        return extract_all_files(output_path, input_path);
 }
 
-static
-int extract_trace_recursive(const char *output_path,
-               const char *input_path)
+static int extract_trace_recursive(const char *output_path, const char *input_path)
 {
        DIR *dir;
        int dir_fd, ret = 0, closeret;
@@ -999,20 +967,19 @@ int extract_trace_recursive(const char *output_path,
                size_t name_len;
                char filename[PATH_MAX];
 
-               if (!strcmp(entry->d_name, ".")
-                               || !strcmp(entry->d_name, "..")) {
+               if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
                        continue;
                }
 
                name_len = strlen(entry->d_name);
                if (path_len + name_len + 2 > sizeof(filename)) {
                        ERR("Failed to remove file: path name too long (%s/%s)",
-                               input_path, entry->d_name);
+                           input_path,
+                           entry->d_name);
                        continue;
                }
 
-               if (snprintf(filename, sizeof(filename), "%s/%s",
-                               input_path, entry->d_name) < 0) {
+               if (snprintf(filename, sizeof(filename), "%s/%s", input_path, entry->d_name) < 0) {
                        ERR("Failed to format path.");
                        continue;
                }
@@ -1026,12 +993,13 @@ int extract_trace_recursive(const char *output_path,
                        char output_subpath[PATH_MAX];
                        char input_subpath[PATH_MAX];
 
-                       strncpy(output_subpath, output_path,
-                               sizeof(output_subpath));
+                       strncpy(output_subpath, output_path, sizeof(output_subpath));
                        output_subpath[sizeof(output_subpath) - 1] = '\0';
-                       strncat(output_subpath, "/",
+                       strncat(output_subpath,
+                               "/",
                                sizeof(output_subpath) - strlen(output_subpath) - 1);
-                       strncat(output_subpath, entry->d_name,
+                       strncat(output_subpath,
+                               entry->d_name,
                                sizeof(output_subpath) - strlen(output_subpath) - 1);
 
                        ret = mkdir(output_subpath, S_IRWXU | S_IRWXG);
@@ -1041,26 +1009,25 @@ int extract_trace_recursive(const char *output_path,
                                goto end;
                        }
 
-                       strncpy(input_subpath, input_path,
-                               sizeof(input_subpath));
+                       strncpy(input_subpath, input_path, sizeof(input_subpath));
                        input_subpath[sizeof(input_subpath) - 1] = '\0';
-                       strncat(input_subpath, "/",
+                       strncat(input_subpath,
+                               "/",
                                sizeof(input_subpath) - strlen(input_subpath) - 1);
-                       strncat(input_subpath, entry->d_name,
+                       strncat(input_subpath,
+                               entry->d_name,
                                sizeof(input_subpath) - strlen(input_subpath) - 1);
 
-                       ret = extract_trace_recursive(output_subpath,
-                               input_subpath);
+                       ret = extract_trace_recursive(output_subpath, input_subpath);
                        if (ret) {
                                has_warning = 1;
                        }
                } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
                        if (!strcmp(entry->d_name, "metadata")) {
-                               ret = extract_one_trace(output_path,
-                                       input_path);
+                               ret = extract_one_trace(output_path, input_path);
                                if (ret) {
                                        WARN("Error extracting trace '%s', continuing anyway.",
-                                               input_path);
+                                            input_path);
                                        has_warning = 1;
                                }
                        }
@@ -1077,8 +1044,7 @@ end:
        return has_warning;
 }
 
-static
-int delete_dir_recursive(const char *path)
+static int delete_dir_recursive(const char *path)
 {
        DIR *dir;
        int dir_fd, ret = 0, closeret;
@@ -1090,7 +1056,7 @@ int delete_dir_recursive(const char *path)
        if (!dir) {
                PERROR("Cannot open '%s' path", path);
                ret = -errno;
-               goto end_no_closedir;
+               goto end_no_closedir;
        }
 
        path_len = strlen(path);
@@ -1107,20 +1073,19 @@ int delete_dir_recursive(const char *path)
                size_t name_len;
                char filename[PATH_MAX];
 
-               if (!strcmp(entry->d_name, ".")
-                               || !strcmp(entry->d_name, "..")) {
+               if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
                        continue;
                }
 
                name_len = strlen(entry->d_name);
                if (path_len + name_len + 2 > sizeof(filename)) {
                        ERR("Failed to remove file: path name too long (%s/%s)",
-                               path, entry->d_name);
+                           path,
+                           entry->d_name);
                        continue;
                }
 
-               if (snprintf(filename, sizeof(filename), "%s/%s",
-                               path, entry->d_name) < 0) {
+               if (snprintf(filename, sizeof(filename), "%s/%s", path, entry->d_name) < 0) {
                        ERR("Failed to format path.");
                        continue;
                }
@@ -1140,10 +1105,8 @@ int delete_dir_recursive(const char *path)
                        }
                        strncpy(subpath, path, PATH_MAX);
                        subpath[PATH_MAX - 1] = '\0';
-                       strncat(subpath, "/",
-                                       PATH_MAX - strlen(subpath) - 1);
-                       strncat(subpath, entry->d_name,
-                                       PATH_MAX - strlen(subpath) - 1);
+                       strncat(subpath, "/", PATH_MAX - strlen(subpath) - 1);
+                       strncat(subpath, entry->d_name, PATH_MAX - strlen(subpath) - 1);
 
                        ret = delete_dir_recursive(subpath);
                        free(subpath);
@@ -1177,8 +1140,7 @@ end_no_closedir:
        return ret;
 }
 
-static
-int view_trace(const char *trace_path, char *viewer_path)
+static int view_trace(const char *trace_path, char *viewer_path)
 {
        pid_t pid;
 
@@ -1216,7 +1178,7 @@ int main(int argc, char *argv[])
 {
        int ret;
        bool has_warning = false;
-       const char *output_path = NULL;
+       const char *output_path = nullptr;
        char tmppath[] = "/tmp/lttng-crash-XXXXXX";
 
        progname = argv[0] ? argv[0] : "lttng-crash";
index b473d5c62b29463eb449bc7ee096ae9a96ab672b..fce8c2346b8e9b77ea962be41540b4c83e87f7be 100644 (file)
@@ -25,7 +25,8 @@ lttng_relayd_SOURCES = main.cpp lttng-relayd.hpp utils.hpp utils.cpp cmd.hpp \
                        tracefile-array.cpp tracefile-array.hpp \
                        tcp_keep_alive.cpp tcp_keep_alive.hpp \
                        sessiond-trace-chunks.cpp sessiond-trace-chunks.hpp \
-                       backward-compatibility-group-by.cpp backward-compatibility-group-by.hpp
+                       backward-compatibility-group-by.cpp backward-compatibility-group-by.hpp \
+                       thread-utils.cpp
 
 # link on liblttngctl for check if relayd is already alive.
 lttng_relayd_LDADD = $(URCU_LIBS) \
index 78f8a1971a190814919007e98f59ab33b6bb8ba9..a14a33accd86691a4f33f9924034677b97e38d88 100644 (file)
@@ -5,20 +5,19 @@
  *
  */
 
+#include "backward-compatibility-group-by.hpp"
 #include "common/time.hpp"
-#include <regex.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
 
 #include <common/common.hpp>
 #include <common/defaults.hpp>
 #include <common/utils.hpp>
 
-#include "backward-compatibility-group-by.hpp"
+#include <regex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
-#define DATETIME_REGEX \
-       ".*-[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]-[0-2][0-9][0-5][0-9][0-5][0-9]$"
+#define DATETIME_REGEX ".*-[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]-[0-2][0-9][0-5][0-9][0-5][0-9]$"
 
 /*
  * Provide support for --group-output-by-session for producer >= 2.4 and < 2.11.
  * Return the allocated string containing the new stream path or else NULL.
  */
 char *backward_compat_group_by_session(const char *path,
-               const char *local_session_name,
-               time_t relay_session_creation_time)
+                                      const char *local_session_name,
+                                      time_t relay_session_creation_time)
 {
        int ret;
        size_t len;
        char *leftover_ptr;
-       char *local_copy = NULL;
-       char *datetime = NULL;
-       char *partial_base_path = NULL;
-       char *filepath_per_session = NULL;
+       char *local_copy = nullptr;
+       char *datetime = nullptr;
+       char *partial_base_path = nullptr;
+       char *filepath_per_session = nullptr;
        const char *second_token_ptr;
        const char *leftover_second_token_ptr;
        const char *hostname_ptr;
@@ -48,7 +47,8 @@ char *backward_compat_group_by_session(const char *path,
        LTTNG_ASSERT(local_session_name[0] != '\0');
 
        DBG("Parsing path \"%s\" of session \"%s\" to create a new path that is grouped by session",
-                       path, local_session_name);
+           path,
+           local_session_name);
 
        /* Get a local copy for strtok */
        local_copy = strdup(path);
@@ -74,15 +74,13 @@ char *backward_compat_group_by_session(const char *path,
         */
        hostname_ptr = strtok_r(local_copy, "/", &leftover_ptr);
        if (!hostname_ptr) {
-               ERR("Failed to parse session path \"%s\": couldn't identify hostname",
-                               path);
+               ERR("Failed to parse session path \"%s\": couldn't identify hostname", path);
                goto error;
        }
 
-       second_token_ptr = strtok_r(NULL, "/", &leftover_ptr);
+       second_token_ptr = strtok_r(nullptr, "/", &leftover_ptr);
        if (!second_token_ptr) {
-               ERR("Failed to parse session path \"%s\": couldn't identify session name",
-                               path);
+               ERR("Failed to parse session path \"%s\": couldn't identify session name", path);
                goto error;
        }
 
@@ -100,8 +98,7 @@ char *backward_compat_group_by_session(const char *path,
         *            <session_name>-<date>-<time>
         *            <auto>-<date>-<time>
         */
-       if (strncmp(second_token_ptr, local_session_name,
-                           strlen(local_session_name)) != 0) {
+       if (strncmp(second_token_ptr, local_session_name, strlen(local_session_name)) != 0) {
                /*
                 * Token does not start with session name.
                 * This mean this is an extra path scenario.
@@ -150,8 +147,7 @@ char *backward_compat_group_by_session(const char *path,
                goto error;
        }
 
-       leftover_second_token_ptr =
-                       second_token_ptr + strlen(local_session_name);
+       leftover_second_token_ptr = second_token_ptr + strlen(local_session_name);
        len = strlen(leftover_second_token_ptr);
        if (len == 0) {
                /*
@@ -159,14 +155,13 @@ char *backward_compat_group_by_session(const char *path,
                 * session_name. If this is a auto session name, we need to
                 * fetch the creation datetime.
                 */
-               ret = regexec(&regex, local_session_name, 0, NULL, 0);
+               ret = regexec(&regex, local_session_name, 0, nullptr, 0);
                if (ret == 0) {
                        const ssize_t local_session_name_offset =
-                                       strlen(local_session_name) - DATETIME_STR_LEN + 1;
+                               strlen(local_session_name) - DATETIME_STR_LEN + 1;
 
                        LTTNG_ASSERT(local_session_name_offset >= 0);
-                       datetime = strdup(local_session_name +
-                                       local_session_name_offset);
+                       datetime = strdup(local_session_name + local_session_name_offset);
                        if (!datetime) {
                                PERROR("Failed to parse session path: couldn't copy datetime on regex match");
                                goto error_regex;
@@ -178,16 +173,15 @@ char *backward_compat_group_by_session(const char *path,
                                goto error;
                        }
 
-                       ret = time_to_datetime_str(relay_session_creation_time,
-                                       datetime, DATETIME_STR_LEN);
+                       ret = time_to_datetime_str(
+                               relay_session_creation_time, datetime, DATETIME_STR_LEN);
                        if (ret) {
                                /* time_to_datetime_str already logs errors. */
                                goto error;
                        }
                }
        } else if (len == DATETIME_STR_LEN &&
-                       !regexec(&regex, leftover_second_token_ptr, 0, NULL,
-                                       0)) {
+                  !regexec(&regex, leftover_second_token_ptr, 0, nullptr, 0)) {
                /*
                 * The leftover from the second token is of format
                 * "-<datetime>", use it as the creation time.
@@ -206,8 +200,8 @@ char *backward_compat_group_by_session(const char *path,
                 * "name-<datetime>" format. Using the datetime from such a
                 * session would be invalid.
                 * */
-               LTTNG_ASSERT(partial_base_path == NULL);
-               LTTNG_ASSERT(datetime == NULL);
+               LTTNG_ASSERT(partial_base_path == nullptr);
+               LTTNG_ASSERT(datetime == nullptr);
 
                partial_base_path = strdup(second_token_ptr);
                if (!partial_base_path) {
@@ -216,13 +210,17 @@ char *backward_compat_group_by_session(const char *path,
                }
        }
 
-       ret = asprintf(&filepath_per_session, "%s/%s%s%s/%s%s%s",
-                       local_session_name, hostname_ptr, datetime ? "-" : "",
-                       datetime ? datetime : "",
-                       partial_base_path ? partial_base_path : "",
-                       partial_base_path ? "/" : "", leftover_ptr);
+       ret = asprintf(&filepath_per_session,
+                      "%s/%s%s%s/%s%s%s",
+                      local_session_name,
+                      hostname_ptr,
+                      datetime ? "-" : "",
+                      datetime ? datetime : "",
+                      partial_base_path ? partial_base_path : "",
+                      partial_base_path ? "/" : "",
+                      leftover_ptr);
        if (ret < 0) {
-               filepath_per_session = NULL;
+               filepath_per_session = nullptr;
                goto error;
        }
 error_regex:
index 4cf7462de55fb22cc72eb42211c3d389f04cea9a..fef6bd0ab1362c0bec35871246c13b49d42a2f4d 100644 (file)
@@ -11,7 +11,7 @@
 #include <time.h>
 
 char *backward_compat_group_by_session(const char *path,
-               const char *local_session_name,
-               time_t session_creation_time);
+                                      const char *local_session_name,
+                                      time_t session_creation_time);
 
 #endif /* BACKWARD_COMPATIBILITY_GROUP_BY_H */
index 9befdd606ac6b8f0db8b7d0a36b2dc9148285f50..27a800c7d50ad50671b833b5337abef2bfc55a50 100644 (file)
@@ -9,29 +9,32 @@
 
 #define _LGPL_SOURCE
 
+#include "cmd-2-1.hpp"
+#include "utils.hpp"
+
 #include <common/common.hpp>
-#include <common/sessiond-comm/relayd.hpp>
 #include <common/compat/string.hpp>
-#include <lttng/constant.h>
+#include <common/sessiond-comm/relayd.hpp>
 
-#include "cmd-2-1.hpp"
-#include "utils.hpp"
+#include <lttng/constant.h>
 
 /*
  * cmd_recv_stream_2_1 allocates path_name and channel_name.
  */
 int cmd_recv_stream_2_1(const struct lttng_buffer_view *payload,
-               char **ret_path_name, char **ret_channel_name)
+                       char **ret_path_name,
+                       char **ret_channel_name)
 {
        int ret;
        struct lttcomm_relayd_add_stream stream_info;
-       char *path_name = NULL;
-       char *channel_name = NULL;
+       char *path_name = nullptr;
+       char *channel_name = nullptr;
        size_t len;
 
        if (payload->size < sizeof(stream_info)) {
                ERR("Unexpected payload size in \"cmd_recv_stream_2_1\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(stream_info), payload->size);
+                   sizeof(stream_info),
+                   payload->size);
                ret = -1;
                goto error;
        }
index 147069b6bc3303ee3fbdddb627f59d4eec9be650..5dc0bd37080c64de9c8fbc691c1e321a74cb323f 100644 (file)
  */
 
 #include "lttng-relayd.hpp"
+
 #include <common/buffer-view.hpp>
 
 int cmd_recv_stream_2_1(const struct lttng_buffer_view *payload,
-               char **path_name, char **channel_name);
+                       char **path_name,
+                       char **channel_name);
 
 #endif /* RELAYD_CMD_2_1_H */
index 73c3a3c513fadd563dc9052e6abfd670f08282f6..cc004555fe2b0c92c25b8149430730ea4b9219e8 100644 (file)
@@ -6,26 +6,30 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
+#include "cmd-2-11.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
-#include <common/sessiond-comm/relayd.hpp>
-
 #include <common/compat/endian.hpp>
 #include <common/compat/string.hpp>
+#include <common/sessiond-comm/relayd.hpp>
+
 #include <lttng/constant.h>
 
-#include "cmd-2-11.hpp"
-#include "utils.hpp"
+#include <inttypes.h>
 
 int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
-               char *session_name, char *hostname, char *base_path,
-               uint32_t *live_timer, bool *snapshot,
-               uint64_t *id_sessiond,
-               lttng_uuid& sessiond_uuid,
-               bool *has_current_chunk, uint64_t *current_chunk_id,
-               time_t *creation_time,
-               bool *session_name_contains_creation_time)
+                           char *session_name,
+                           char *hostname,
+                           char *base_path,
+                           uint32_t *live_timer,
+                           bool *snapshot,
+                           uint64_t *id_sessiond,
+                           lttng_uuid& sessiond_uuid,
+                           bool *has_current_chunk,
+                           uint64_t *current_chunk_id,
+                           time_t *creation_time,
+                           bool *session_name_contains_creation_time)
 {
        int ret;
        struct lttcomm_relayd_create_session_2_11 header;
@@ -38,7 +42,8 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
 
        if (payload->size < header_len) {
                ERR("Unexpected payload size in \"cmd_create_session_2_11\": expected >= %zu bytes, got %zu bytes",
-                               header_len, payload->size);
+                   header_len,
+                   payload->size);
                ret = -1;
                goto error;
        }
@@ -53,13 +58,15 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        header.creation_time = be64toh(header.creation_time);
        header.session_id = be64toh(header.session_id);
 
-       std::copy(std::begin(header.sessiond_uuid), std::end(header.sessiond_uuid), sessiond_uuid.begin());
+       std::copy(std::begin(header.sessiond_uuid),
+                 std::end(header.sessiond_uuid),
+                 sessiond_uuid.begin());
 
-       received_names_size = header.session_name_len + header.hostname_len +
-                               header.base_path_len;
+       received_names_size = header.session_name_len + header.hostname_len + header.base_path_len;
        if (payload->size < header_len + received_names_size) {
                ERR("Unexpected payload size in \"cmd_create_session_2_11\": expected >= %zu bytes, got %zu bytes",
-                               header_len + received_names_size, payload->size);
+                   header_len + received_names_size,
+                   payload->size);
                ret = -1;
                goto error;
        }
@@ -67,7 +74,10 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        /* Validate length against defined constant. */
        if (header.session_name_len > LTTNG_NAME_MAX) {
                ret = -ENAMETOOLONG;
-               ERR("Length of session name (%" PRIu32 " bytes) received in create_session command exceeds maximum length (%d bytes)", header.session_name_len, LTTNG_NAME_MAX);
+               ERR("Length of session name (%" PRIu32
+                   " bytes) received in create_session command exceeds maximum length (%d bytes)",
+                   header.session_name_len,
+                   LTTNG_NAME_MAX);
                goto error;
        } else if (header.session_name_len == 0) {
                ret = -EINVAL;
@@ -76,18 +86,23 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        }
        if (header.hostname_len > LTTNG_HOST_NAME_MAX) {
                ret = -ENAMETOOLONG;
-               ERR("Length of hostname (%" PRIu32 " bytes) received in create_session command exceeds maximum length (%d bytes)", header.hostname_len, LTTNG_HOST_NAME_MAX);
+               ERR("Length of hostname (%" PRIu32
+                   " bytes) received in create_session command exceeds maximum length (%d bytes)",
+                   header.hostname_len,
+                   LTTNG_HOST_NAME_MAX);
                goto error;
        }
        if (header.base_path_len > LTTNG_PATH_MAX) {
                ret = -ENAMETOOLONG;
-               ERR("Length of base_path (%" PRIu32 " bytes) received in create_session command exceeds maximum length (%d bytes)", header.base_path_len, PATH_MAX);
+               ERR("Length of base_path (%" PRIu32
+                   " bytes) received in create_session command exceeds maximum length (%d bytes)",
+                   header.base_path_len,
+                   PATH_MAX);
                goto error;
        }
 
        offset = header_len;
-       session_name_view = lttng_buffer_view_from_view(payload, offset,
-                       header.session_name_len);
+       session_name_view = lttng_buffer_view_from_view(payload, offset, header.session_name_len);
        if (!lttng_buffer_view_is_valid(&session_name_view)) {
                ERR("Invalid payload in \"cmd_create_session_2_11\": buffer too short to contain session name");
                ret = -1;
@@ -95,8 +110,7 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        }
 
        offset += header.session_name_len;
-       hostname_view = lttng_buffer_view_from_view(payload,
-                       offset, header.hostname_len);
+       hostname_view = lttng_buffer_view_from_view(payload, offset, header.hostname_len);
        if (!lttng_buffer_view_is_valid(&hostname_view)) {
                ERR("Invalid payload in \"cmd_create_session_2_11\": buffer too short to contain hostname");
                ret = -1;
@@ -104,8 +118,7 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        }
 
        offset += header.hostname_len;
-       base_path_view = lttng_buffer_view_from_view(payload,
-                       offset, header.base_path_len);
+       base_path_view = lttng_buffer_view_from_view(payload, offset, header.base_path_len);
        if (header.base_path_len > 0 && !lttng_buffer_view_is_valid(&base_path_view)) {
                ERR("Invalid payload in \"cmd_create_session_2_11\": buffer too short to contain base path");
                ret = -1;
@@ -125,8 +138,7 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
                goto error;
        }
 
-       if (base_path_view.size != 0 &&
-                       base_path_view.data[base_path_view.size - 1] != '\0') {
+       if (base_path_view.size != 0 && base_path_view.data[base_path_view.size - 1] != '\0') {
                ERR("cmd_create_session_2_11 base_path is invalid (not NULL terminated)");
                ret = -1;
                goto error;
@@ -145,8 +157,7 @@ int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
        *current_chunk_id = header.current_chunk_id.value;
        *has_current_chunk = header.current_chunk_id.is_set;
        *creation_time = (time_t) header.creation_time;
-       *session_name_contains_creation_time =
-               header.session_name_contains_creation_time;
+       *session_name_contains_creation_time = header.session_name_contains_creation_time;
        *id_sessiond = header.session_id;
 
        ret = 0;
@@ -159,23 +170,26 @@ error:
  * cmd_recv_stream_2_11 allocates path_name and channel_name.
  */
 int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
-               char **ret_path_name, char **ret_channel_name,
-               uint64_t *tracefile_size, uint64_t *tracefile_count,
-               uint64_t *trace_archive_id)
+                        char **ret_path_name,
+                        char **ret_channel_name,
+                        uint64_t *tracefile_size,
+                        uint64_t *tracefile_count,
+                        uint64_t *trace_archive_id)
 {
        int ret;
        struct lttcomm_relayd_add_stream_2_11 header;
        size_t header_len, received_names_size;
        struct lttng_buffer_view channel_name_view;
        struct lttng_buffer_view pathname_view;
-       char *path_name = NULL;
-       char *channel_name = NULL;
+       char *path_name = nullptr;
+       char *channel_name = nullptr;
 
        header_len = sizeof(header);
 
        if (payload->size < header_len) {
                ERR("Unexpected payload size in \"cmd_recv_stream_2_11\": expected >= %zu bytes, got %zu bytes",
-                               header_len, payload->size);
+                   header_len,
+                   payload->size);
                ret = -1;
                goto error;
        }
@@ -190,7 +204,8 @@ int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
        received_names_size = header.channel_name_len + header.pathname_len;
        if (payload->size < header_len + received_names_size) {
                ERR("Unexpected payload size in \"cmd_recv_stream_2_11\": expected >= %zu bytes, got %zu bytes",
-                               header_len + received_names_size, payload->size);
+                   header_len + received_names_size,
+                   payload->size);
                ret = -1;
                goto error;
        }
@@ -208,8 +223,8 @@ int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
        }
 
        /* Validate that names are (NULL terminated. */
-       channel_name_view = lttng_buffer_view_from_view(payload, header_len,
-                       header.channel_name_len);
+       channel_name_view =
+               lttng_buffer_view_from_view(payload, header_len, header.channel_name_len);
        if (!lttng_buffer_view_is_valid(&channel_name_view)) {
                ERR("Invalid payload received in \"cmd_recv_stream_2_11\": buffer too short for channel name");
                ret = -1;
@@ -222,8 +237,8 @@ int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
                goto error;
        }
 
-       pathname_view = lttng_buffer_view_from_view(payload,
-                       header_len + header.channel_name_len, header.pathname_len);
+       pathname_view = lttng_buffer_view_from_view(
+               payload, header_len + header.channel_name_len, header.pathname_len);
        if (!lttng_buffer_view_is_valid(&pathname_view)) {
                ERR("Invalid payload received in \"cmd_recv_stream_2_11\": buffer too short for path name");
                ret = -1;
@@ -256,8 +271,8 @@ int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
        *ret_path_name = path_name;
        *ret_channel_name = channel_name;
        /* Move ownership to caller */
-       path_name = NULL;
-       channel_name = NULL;
+       path_name = nullptr;
+       channel_name = nullptr;
        ret = 0;
 error:
        free(channel_name);
index 79f241aaa249fce2a50378f1a8abd72684ae62f2..97565df5b8481e3fc8ff07999b0c5d9e8b905216 100644 (file)
@@ -9,20 +9,28 @@
 #define RELAYD_CMD_2_11_H
 
 #include "lttng-relayd.hpp"
+
 #include <common/buffer-view.hpp>
 #include <common/uuid.hpp>
 
 int cmd_create_session_2_11(const struct lttng_buffer_view *payload,
-               char *session_name, char *hostname, char *base_path,
-               uint32_t *live_timer, bool *snapshot,
-               uint64_t *id_sessiond, lttng_uuid& sessiond_uuid,
-               bool *has_current_chunk, uint64_t *current_chunk_id,
-               time_t *creation_time,
-               bool *session_name_contains_creation_time);
+                           char *session_name,
+                           char *hostname,
+                           char *base_path,
+                           uint32_t *live_timer,
+                           bool *snapshot,
+                           uint64_t *id_sessiond,
+                           lttng_uuid& sessiond_uuid,
+                           bool *has_current_chunk,
+                           uint64_t *current_chunk_id,
+                           time_t *creation_time,
+                           bool *session_name_contains_creation_time);
 
 int cmd_recv_stream_2_11(const struct lttng_buffer_view *payload,
-               char **ret_path_name, char **ret_channel_name,
-               uint64_t *tracefile_size, uint64_t *tracefile_count,
-               uint64_t *trace_archive_id);
+                        char **ret_path_name,
+                        char **ret_channel_name,
+                        uint64_t *tracefile_size,
+                        uint64_t *tracefile_count,
+                        uint64_t *trace_archive_id);
 
 #endif /* RELAYD_CMD_2_11_H */
index 3d9af63a313f5f2a9ff6bf9a6f451d62dcf25578..dcdd1bac14cb9f14057fb0fb8a8119cad6fa439b 100644 (file)
@@ -9,33 +9,36 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/sessiond-comm/relayd.hpp>
+#include "cmd-2-1.hpp"
+#include "cmd-2-2.hpp"
+#include "utils.hpp"
 
+#include <common/common.hpp>
 #include <common/compat/endian.hpp>
 #include <common/compat/string.hpp>
-#include <lttng/constant.h>
+#include <common/sessiond-comm/relayd.hpp>
 
-#include "cmd-2-2.hpp"
-#include "cmd-2-1.hpp"
-#include "utils.hpp"
+#include <lttng/constant.h>
 
 /*
  * cmd_recv_stream_2_2 allocates path_name and channel_name.
  */
 int cmd_recv_stream_2_2(const struct lttng_buffer_view *payload,
-               char **ret_path_name, char **ret_channel_name,
-               uint64_t *tracefile_size, uint64_t *tracefile_count)
+                       char **ret_path_name,
+                       char **ret_channel_name,
+                       uint64_t *tracefile_size,
+                       uint64_t *tracefile_count)
 {
        int ret;
        struct lttcomm_relayd_add_stream_2_2 stream_info;
-       char *path_name = NULL;
-       char *channel_name = NULL;
+       char *path_name = nullptr;
+       char *channel_name = nullptr;
        size_t len;
 
        if (payload->size < sizeof(stream_info)) {
                ERR("Unexpected payload size in \"cmd_recv_stream_2_2\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(stream_info), payload->size);
+                   sizeof(stream_info),
+                   payload->size);
                ret = -1;
                goto error;
        }
index 010bbb127940554f7699ad765efe2f3f5d089375..4686949be2710e494d52b6690516e0d5170e0445 100644 (file)
  */
 
 #include "lttng-relayd.hpp"
+
 #include <common/buffer-view.hpp>
 
 int cmd_recv_stream_2_2(const struct lttng_buffer_view *payload,
-               char **path_name, char **channel_name,
-               uint64_t *tracefile_size, uint64_t *tracefile_count);
+                       char **path_name,
+                       char **channel_name,
+                       uint64_t *tracefile_size,
+                       uint64_t *tracefile_count);
 
 #endif /* RELAYD_CMD_2_2_H */
index 7b546c7f661d5babd2161c0e51abb98d0f250036..f67c05b892d9b939889833765e22965c8619741a 100644 (file)
@@ -9,19 +9,21 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/sessiond-comm/relayd.hpp>
+#include "cmd-2-4.hpp"
+#include "lttng-relayd.hpp"
 
+#include <common/common.hpp>
 #include <common/compat/endian.hpp>
 #include <common/compat/string.hpp>
-#include <lttng/constant.h>
+#include <common/sessiond-comm/relayd.hpp>
 
-#include "cmd-2-4.hpp"
-#include "lttng-relayd.hpp"
+#include <lttng/constant.h>
 
 int cmd_create_session_2_4(const struct lttng_buffer_view *payload,
-               char *session_name, char *hostname,
-               uint32_t *live_timer, bool *snapshot)
+                          char *session_name,
+                          char *hostname,
+                          uint32_t *live_timer,
+                          bool *snapshot)
 {
        int ret;
        struct lttcomm_relayd_create_session_2_4 session_info;
@@ -29,7 +31,8 @@ int cmd_create_session_2_4(const struct lttng_buffer_view *payload,
 
        if (payload->size < sizeof(session_info)) {
                ERR("Unexpected payload size in \"cmd_create_session_2_4\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(session_info), payload->size);
+                   sizeof(session_info),
+                   payload->size);
                ret = -1;
                goto error;
        }
index b3d105c84744194b764370acdc6f48d3fd125974..98a6dabcc124cac04be66c3b1775e883526a17b7 100644 (file)
  */
 
 #include "lttng-relayd.hpp"
+
 #include <common/buffer-view.hpp>
 
 int cmd_create_session_2_4(const struct lttng_buffer_view *payload,
-               char *session_name, char *hostname,
-               uint32_t *live_timer, bool *snapshot);
+                          char *session_name,
+                          char *hostname,
+                          uint32_t *live_timer,
+                          bool *snapshot);
 
 #endif /* RELAYD_CMD_2_4_H */
index 24e361a4b2634bc8e4635e83033de3159911c9bc..351527c09370cf7151571ee48a5246317e0387ba 100644 (file)
@@ -11,8 +11,8 @@
  */
 
 #include "cmd-2-1.hpp"
+#include "cmd-2-11.hpp"
 #include "cmd-2-2.hpp"
 #include "cmd-2-4.hpp"
-#include "cmd-2-11.hpp"
 
 #endif /* RELAYD_CMD_H */
index 711de3a5cff81a76a2ae3bd9fb8e1ca4cc6311bf..668a61e7a1a6b3674191a54964569bc6eba52982 100644 (file)
@@ -8,30 +8,30 @@
  */
 
 #define _LGPL_SOURCE
-#include <common/common.hpp>
-#include <urcu/rculist.h>
-
 #include "connection.hpp"
 #include "stream.hpp"
 #include "viewer-session.hpp"
 
+#include <common/common.hpp>
+#include <common/urcu.hpp>
+
+#include <urcu/rculist.h>
+
 bool connection_get(struct relay_connection *conn)
 {
        return urcu_ref_get_unless_zero(&conn->ref);
 }
 
-struct relay_connection *connection_get_by_sock(struct lttng_ht *relay_connections_ht,
-               int sock)
+struct relay_connection *connection_get_by_sock(struct lttng_ht *relay_connections_ht, int sock)
 {
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
-       struct relay_connection *conn = NULL;
+       struct relay_connection *conn = nullptr;
 
        LTTNG_ASSERT(sock >= 0);
 
-       rcu_read_lock();
-       lttng_ht_lookup(relay_connections_ht, (void *)((unsigned long) sock),
-                       &iter);
+       lttng::urcu::read_lock_guard read_lock;
+       lttng_ht_lookup(relay_connections_ht, (void *) ((unsigned long) sock), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
        if (!node) {
                DBG2("Relay connection by sock %d not found", sock);
@@ -39,10 +39,9 @@ struct relay_connection *connection_get_by_sock(struct lttng_ht *relay_connectio
        }
        conn = lttng::utils::container_of(node, &relay_connection::sock_n);
        if (!connection_get(conn)) {
-               conn = NULL;
+               conn = nullptr;
        }
 end:
-       rcu_read_unlock();
        return conn;
 }
 
@@ -52,41 +51,37 @@ int connection_reset_protocol_state(struct relay_connection *connection)
 
        switch (connection->type) {
        case RELAY_DATA:
-               connection->protocol.data.state_id =
-                               DATA_CONNECTION_STATE_RECEIVE_HEADER;
+               connection->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_HEADER;
                memset(&connection->protocol.data.state.receive_header,
-                               0,
-                               sizeof(connection->protocol.data.state.receive_header));
+                      0,
+                      sizeof(connection->protocol.data.state.receive_header));
                connection->protocol.data.state.receive_header.left_to_receive =
-                               sizeof(struct lttcomm_relayd_data_hdr);
+                       sizeof(struct lttcomm_relayd_data_hdr);
                break;
        case RELAY_CONTROL:
-               connection->protocol.ctrl.state_id =
-                               CTRL_CONNECTION_STATE_RECEIVE_HEADER;
+               connection->protocol.ctrl.state_id = CTRL_CONNECTION_STATE_RECEIVE_HEADER;
                memset(&connection->protocol.ctrl.state.receive_header,
-                               0,
-                               sizeof(connection->protocol.ctrl.state.receive_header));
+                      0,
+                      sizeof(connection->protocol.ctrl.state.receive_header));
                connection->protocol.data.state.receive_header.left_to_receive =
-                               sizeof(struct lttcomm_relayd_hdr);
-               ret = lttng_dynamic_buffer_set_size(
-                               &connection->protocol.ctrl.reception_buffer,
-                               sizeof(struct lttcomm_relayd_hdr));
+                       sizeof(struct lttcomm_relayd_hdr);
+               ret = lttng_dynamic_buffer_set_size(&connection->protocol.ctrl.reception_buffer,
+                                                   sizeof(struct lttcomm_relayd_hdr));
                if (ret) {
-                       ERR("Failed to reinitialize control connection reception buffer size to %zu bytes.", sizeof(struct lttcomm_relayd_hdr));
+                       ERR("Failed to reinitialize control connection reception buffer size to %zu bytes.",
+                           sizeof(struct lttcomm_relayd_hdr));
                        goto end;
                }
                break;
        default:
                goto end;
        }
-       DBG("Reset communication state of relay connection (fd = %i)",
-                       connection->sock->fd);
+       DBG("Reset communication state of relay connection (fd = %i)", connection->sock->fd);
 end:
        return ret;
 }
 
-struct relay_connection *connection_create(struct lttcomm_sock *sock,
-               enum connection_type type)
+struct relay_connection *connection_create(struct lttcomm_sock *sock, enum connection_type type)
 {
        struct relay_connection *conn;
 
@@ -115,11 +110,10 @@ static void rcu_free_connection(struct rcu_head *head)
        lttcomm_destroy_sock(conn->sock);
        if (conn->viewer_session) {
                viewer_session_destroy(conn->viewer_session);
-               conn->viewer_session = NULL;
+               conn->viewer_session = nullptr;
        }
        if (conn->type == RELAY_CONTROL) {
-               lttng_dynamic_buffer_reset(
-                               &conn->protocol.ctrl.reception_buffer);
+               lttng_dynamic_buffer_reset(&conn->protocol.ctrl.reception_buffer);
        }
        free(conn);
 }
@@ -131,8 +125,7 @@ static void destroy_connection(struct relay_connection *conn)
 
 static void connection_release(struct urcu_ref *ref)
 {
-       struct relay_connection *conn =
-               lttng::utils::container_of(ref, &relay_connection::ref);
+       struct relay_connection *conn = lttng::utils::container_of(ref, &relay_connection::ref);
 
        if (conn->in_socket_ht) {
                struct lttng_ht_iter iter;
@@ -147,7 +140,7 @@ static void connection_release(struct urcu_ref *ref)
                if (session_close(conn->session)) {
                        ERR("session_close");
                }
-               conn->session = NULL;
+               conn->session = nullptr;
        }
        if (conn->viewer_session) {
                viewer_session_close(conn->viewer_session);
@@ -157,22 +150,19 @@ static void connection_release(struct urcu_ref *ref)
 
 void connection_put(struct relay_connection *conn)
 {
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        urcu_ref_put(&conn->ref, connection_release);
-       rcu_read_unlock();
 }
 
-void connection_ht_add(struct lttng_ht *relay_connections_ht,
-               struct relay_connection *conn)
+void connection_ht_add(struct lttng_ht *relay_connections_ht, struct relay_connection *conn)
 {
        LTTNG_ASSERT(!conn->in_socket_ht);
        lttng_ht_add_unique_ulong(relay_connections_ht, &conn->sock_n);
-       conn->in_socket_ht = 1;
+       conn->in_socket_ht = true;
        conn->socket_ht = relay_connections_ht;
 }
 
-int connection_set_session(struct relay_connection *conn,
-               struct relay_session *session)
+int connection_set_session(struct relay_connection *conn, struct relay_session *session)
 {
        int ret = 0;
 
index de25255a7aab10057d6f0b7eb8631618283ef771..917c2ef6010a8e1d8a3de57ed97505c52e90c72c 100644 (file)
  *
  */
 
-#include <limits.h>
-#include <inttypes.h>
-#include <pthread.h>
-#include <urcu.h>
-#include <urcu/wfcqueue.h>
-#include <urcu/list.h>
+#include "session.hpp"
 
+#include <common/dynamic-buffer.hpp>
 #include <common/hashtable/hashtable.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/sessiond-comm/relayd.hpp>
-#include <common/dynamic-buffer.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
 
-#include "session.hpp"
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <urcu.h>
+#include <urcu/list.h>
+#include <urcu/wfcqueue.h>
 
 enum connection_type {
-       RELAY_CONNECTION_UNKNOWN    = 0,
-       RELAY_DATA                  = 1,
-       RELAY_CONTROL               = 2,
-       RELAY_VIEWER_COMMAND        = 3,
-       RELAY_VIEWER_NOTIFICATION   = 4,
+       RELAY_CONNECTION_UNKNOWN = 0,
+       RELAY_DATA = 1,
+       RELAY_CONTROL = 2,
+       RELAY_VIEWER_COMMAND = 3,
+       RELAY_VIEWER_NOTIFICATION = 4,
 };
 
 enum data_connection_state {
@@ -107,8 +107,8 @@ struct relay_connection {
         */
        struct lttng_ht_node_ulong sock_n;
        bool in_socket_ht;
-       struct lttng_ht *socket_ht;     /* HACK: Contained within this hash table. */
-       struct rcu_head rcu_node;       /* For call_rcu teardown. */
+       struct lttng_ht *socket_ht; /* HACK: Contained within this hash table. */
+       struct rcu_head rcu_node; /* For call_rcu teardown. */
 
        union {
                struct {
@@ -129,16 +129,12 @@ struct relay_connection {
        } protocol;
 };
 
-struct relay_connection *connection_create(struct lttcomm_sock *sock,
-               enum connection_type type);
-struct relay_connection *connection_get_by_sock(struct lttng_ht *relay_connections_ht,
-               int sock);
+struct relay_connection *connection_create(struct lttcomm_sock *sock, enum connection_type type);
+struct relay_connection *connection_get_by_sock(struct lttng_ht *relay_connections_ht, int sock);
 int connection_reset_protocol_state(struct relay_connection *connection);
 bool connection_get(struct relay_connection *connection);
 void connection_put(struct relay_connection *connection);
-void connection_ht_add(struct lttng_ht *relay_connections_ht,
-               struct relay_connection *conn);
-int connection_set_session(struct relay_connection *conn,
-               struct relay_session *session);
+void connection_ht_add(struct lttng_ht *relay_connections_ht, struct relay_connection *conn);
+int connection_set_session(struct relay_connection *conn, struct relay_session *session);
 
 #endif /* _CONNECTION_H */
index ba4a29092ca537f28e68153027823840f3882fdc..cde9f3927e381297b3f3b8bd53a00532ea2f2e98 100644 (file)
@@ -9,21 +9,22 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/utils.hpp>
-#include <urcu/rculist.h>
-
 #include "ctf-trace.hpp"
 #include "lttng-relayd.hpp"
 #include "stream.hpp"
 
+#include <common/common.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
+#include <urcu/rculist.h>
+
 static uint64_t last_relay_ctf_trace_id;
 static pthread_mutex_t last_relay_ctf_trace_id_lock = PTHREAD_MUTEX_INITIALIZER;
 
 static void rcu_destroy_ctf_trace(struct rcu_head *rcu_head)
 {
-       struct ctf_trace *trace =
-               lttng::utils::container_of(rcu_head, &ctf_trace::rcu_node);
+       struct ctf_trace *trace = lttng::utils::container_of(rcu_head, &ctf_trace::rcu_node);
 
        free(trace);
 }
@@ -44,16 +45,15 @@ static void ctf_trace_destroy(struct ctf_trace *trace)
        ASSERT_RCU_READ_LOCKED();
 
        session_put(trace->session);
-       trace->session = NULL;
+       trace->session = nullptr;
        free(trace->path);
-       trace->path = NULL;
+       trace->path = nullptr;
        call_rcu(&trace->rcu_node, rcu_destroy_ctf_trace);
 }
 
 static void ctf_trace_release(struct urcu_ref *ref)
 {
-       struct ctf_trace *trace =
-               lttng::utils::container_of(ref, &ctf_trace::ref);
+       struct ctf_trace *trace = lttng::utils::container_of(ref, &ctf_trace::ref);
        int ret;
        struct lttng_ht_iter iter;
 
@@ -92,8 +92,7 @@ bool ctf_trace_get(struct ctf_trace *trace)
  * create and refcounting. Whenever all the streams belonging to a trace
  * put their reference, its refcount drops to 0.
  */
-static struct ctf_trace *ctf_trace_create(struct relay_session *session,
-               const char *subpath)
+static struct ctf_trace *ctf_trace_create(struct relay_session *session, const char *subpath)
 {
        struct ctf_trace *trace;
 
@@ -122,19 +121,21 @@ static struct ctf_trace *ctf_trace_create(struct relay_session *session,
 
        lttng_ht_node_init_str(&trace->node, trace->path);
        trace->session = session;
-       pthread_mutex_init(&trace->lock, NULL);
-       pthread_mutex_init(&trace->stream_list_lock, NULL);
+       pthread_mutex_init(&trace->lock, nullptr);
+       pthread_mutex_init(&trace->stream_list_lock, nullptr);
        lttng_ht_add_str(session->ctf_traces_ht, &trace->node);
 
-       DBG("Created ctf_trace %" PRIu64 "of session \"%s\" from host \"%s\" with path: %s",
-                       trace->id, session->session_name, session->hostname,
-                       subpath);
+       DBG("Created ctf_trace %" PRIu64 " of session \"%s\" from host \"%s\" with path: %s",
+           trace->id,
+           session->session_name,
+           session->hostname,
+           subpath);
 
 end:
        return trace;
 error:
        ctf_trace_put(trace);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -143,13 +144,13 @@ error:
  * ctf_trace_put().
  */
 struct ctf_trace *ctf_trace_get_by_path_or_create(struct relay_session *session,
-               const char *subpath)
+                                                 const char *subpath)
 {
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
-       struct ctf_trace *trace = NULL;
+       struct ctf_trace *trace = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_lookup(session->ctf_traces_ht, subpath, &iter);
        node = lttng_ht_iter_get_node_str(&iter);
        if (!node) {
@@ -158,10 +159,9 @@ struct ctf_trace *ctf_trace_get_by_path_or_create(struct relay_session *session,
        }
        trace = lttng::utils::container_of(node, &ctf_trace::node);
        if (!ctf_trace_get(trace)) {
-               trace = NULL;
+               trace = nullptr;
        }
 end:
-       rcu_read_unlock();
        if (!trace) {
                /* Try to create */
                trace = ctf_trace_create(session, subpath);
@@ -171,25 +171,23 @@ end:
 
 void ctf_trace_put(struct ctf_trace *trace)
 {
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        urcu_ref_put(&trace->ref, ctf_trace_release);
-       rcu_read_unlock();
 }
 
 int ctf_trace_close(struct ctf_trace *trace)
 {
        struct relay_stream *stream;
 
-       rcu_read_lock();
-       cds_list_for_each_entry_rcu(stream, &trace->stream_list,
-                       stream_node) {
+       lttng::urcu::read_lock_guard read_lock;
+       cds_list_for_each_entry_rcu(stream, &trace->stream_list, stream_node)
+       {
                /*
                 * Close stream since the connection owning the trace is being
                 * torn down.
                 */
                try_stream_close(stream);
        }
-       rcu_read_unlock();
        /*
         * Since all references to the trace are held by its streams, we
         * don't need to do any self-ref put.
@@ -201,15 +199,14 @@ struct relay_viewer_stream *ctf_trace_get_viewer_metadata_stream(struct ctf_trac
 {
        struct relay_viewer_stream *vstream;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        vstream = rcu_dereference(trace->viewer_metadata_stream);
        if (!vstream) {
                goto end;
        }
        if (!viewer_stream_get(vstream)) {
-               vstream = NULL;
+               vstream = nullptr;
        }
 end:
-       rcu_read_unlock();
        return vstream;
 }
index dbf7d3fa21166d533507550f02261e41b26e887e..3d9026da818c4857fedce83fb65fcb883f6af102 100644 (file)
  *
  */
 
-#include <inttypes.h>
-#include <urcu/ref.h>
-
-#include <common/hashtable/hashtable.hpp>
-
 #include "session.hpp"
 #include "stream.hpp"
 #include "viewer-stream.hpp"
 
+#include <common/hashtable/hashtable.hpp>
+
+#include <inttypes.h>
+#include <urcu/ref.h>
+
 struct ctf_trace {
-       struct urcu_ref ref;            /* Every stream has a ref on the trace. */
-       struct relay_session *session;  /* Back ref to trace session */
+       struct urcu_ref ref; /* Every stream has a ref on the trace. */
+       struct relay_session *session; /* Back ref to trace session */
 
        /* Trace sub-folder relative to the session output path. */
        char *path;
@@ -31,7 +31,7 @@ struct ctf_trace {
         */
        pthread_mutex_t lock;
        uint64_t id;
-       struct relay_viewer_stream *viewer_metadata_stream;     /* RCU protected */
+       struct relay_viewer_stream *viewer_metadata_stream; /* RCU protected */
 
        /*
         * Relay streams associated with this ctf trace.
@@ -46,7 +46,7 @@ struct ctf_trace {
         * stream path name.
         */
        struct lttng_ht_node_str node;
-       struct rcu_head rcu_node;       /* For call_rcu teardown. */
+       struct rcu_head rcu_node; /* For call_rcu teardown. */
 
        /*
         * True if the metadata stream of this trace was sent the viewer in the
@@ -56,7 +56,7 @@ struct ctf_trace {
 };
 
 struct ctf_trace *ctf_trace_get_by_path_or_create(struct relay_session *session,
-               const char *subpath);
+                                                 const char *subpath);
 bool ctf_trace_get(struct ctf_trace *trace);
 void ctf_trace_put(struct ctf_trace *trace);
 
index 8e22dfe66335f1332ff8740e6e64ee0869480411..d1b619d3972d9f0a21d30adb2cd164a990fe4c6c 100644 (file)
@@ -6,62 +6,46 @@
  */
 
 #define _LGPL_SOURCE
+#include "health-relayd.hpp"
+#include "lttng-relayd.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/getenv.hpp>
+#include <common/compat/poll.hpp>
+#include <common/consumer/consumer-timer.hpp>
+#include <common/consumer/consumer.hpp>
+#include <common/defaults.hpp>
+#include <common/fd-tracker/utils.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
 #include <fcntl.h>
 #include <getopt.h>
 #include <grp.h>
+#include <inttypes.h>
 #include <limits.h>
+#include <poll.h>
 #include <pthread.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/ipc.h>
+#include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/shm.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <urcu/list.h>
-#include <poll.h>
 #include <unistd.h>
-#include <sys/mman.h>
 #include <urcu/compiler.h>
-#include <inttypes.h>
-
-#include <common/defaults.hpp>
-#include <common/common.hpp>
-#include <common/consumer/consumer.hpp>
-#include <common/consumer/consumer-timer.hpp>
-#include <common/compat/poll.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/fd-tracker/utils.hpp>
-
-#include "lttng-relayd.hpp"
-#include "health-relayd.hpp"
+#include <urcu/list.h>
 
 /* Global health check unix path */
-static
-char health_unix_sock_path[PATH_MAX];
+static char health_unix_sock_path[PATH_MAX];
 
 int health_quit_pipe[2] = { -1, -1 };
 
-/*
- * Check if the thread quit pipe was triggered.
- *
- * Return 1 if it was triggered else 0;
- */
-static
-int check_health_quit_pipe(int fd, uint32_t events)
-{
-       if (fd == health_quit_pipe[0] && (events & LPOLLIN)) {
-               return 1;
-       }
-
-       return 0;
-}
-
 /*
  * Send data on a unix socket using the liblttsessiondcomm API.
  *
@@ -112,7 +96,8 @@ static int create_lttng_rundir_with_perm(const char *rundir)
                        }
 
                        ret = chmod(rundir,
-                                       S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
+                                   S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH |
+                                           S_IXOTH);
                        if (ret < 0) {
                                ERR("Unable to set permissions on %s", rundir);
                                PERROR("chmod");
@@ -126,27 +111,24 @@ error:
        return ret;
 }
 
-static
-int parse_health_env(void)
+static int parse_health_env()
 {
        const char *health_path;
 
        health_path = lttng_secure_getenv(LTTNG_RELAYD_HEALTH_ENV);
        if (health_path) {
-               strncpy(health_unix_sock_path, health_path,
-                       PATH_MAX);
+               strncpy(health_unix_sock_path, health_path, PATH_MAX);
                health_unix_sock_path[PATH_MAX - 1] = '\0';
        }
 
        return 0;
 }
 
-static
-int setup_health_path(void)
+static int setup_health_path()
 {
        int is_root, ret = 0;
-       const char *home_path = NULL;
-       char *rundir = NULL, *relayd_path = NULL;
+       const char *home_path = nullptr;
+       char *rundir = nullptr, *relayd_path = nullptr;
 
        ret = parse_health_env();
        if (ret) {
@@ -168,7 +150,7 @@ int setup_health_path(void)
                 */
                home_path = utils_get_home_dir();
 
-               if (home_path == NULL) {
+               if (home_path == nullptr) {
                        /* TODO: Add --socket PATH option */
                        ERR("Can't get HOME directory for sockets creation.");
                        ret = -EPERM;
@@ -202,18 +184,21 @@ int setup_health_path(void)
                if (strlen(health_unix_sock_path) != 0) {
                        goto end;
                }
-               snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                       DEFAULT_GLOBAL_RELAY_HEALTH_UNIX_SOCK,
-                       (int) getpid());
+               snprintf(health_unix_sock_path,
+                        sizeof(health_unix_sock_path),
+                        DEFAULT_GLOBAL_RELAY_HEALTH_UNIX_SOCK,
+                        (int) getpid());
        } else {
                /* Set health check Unix path */
                if (strlen(health_unix_sock_path) != 0) {
                        goto end;
                }
 
-               snprintf(health_unix_sock_path, sizeof(health_unix_sock_path),
-                       DEFAULT_HOME_RELAY_HEALTH_UNIX_SOCK,
-                       home_path, (int) getpid());
+               snprintf(health_unix_sock_path,
+                        sizeof(health_unix_sock_path),
+                        DEFAULT_HOME_RELAY_HEALTH_UNIX_SOCK,
+                        home_path,
+                        (int) getpid());
        }
 
 end:
@@ -222,8 +207,7 @@ end:
        return ret;
 }
 
-static
-int accept_unix_socket(void *data, int *out_fd)
+static int accept_unix_socket(void *data, int *out_fd)
 {
        int ret;
        int accepting_sock = *((int *) data);
@@ -239,8 +223,7 @@ end:
        return ret;
 }
 
-static
-int open_unix_socket(void *data, int *out_fd)
+static int open_unix_socket(void *data, int *out_fd)
 {
        int ret;
        const char *path = (const char *) data;
@@ -261,8 +244,8 @@ end:
  */
 void *thread_manage_health_relayd(void *data __attribute__((unused)))
 {
-       int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int sock = -1, new_sock = -1, ret, i, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct health_comm_msg msg;
        struct health_comm_reply reply;
@@ -285,9 +268,12 @@ void *thread_manage_health_relayd(void *data __attribute__((unused)))
                err = -1;
                goto error;
        }
-       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock,
-                       (const char **) &sock_name, 1, open_unix_socket,
-                       health_unix_sock_path);
+       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker,
+                                              &sock,
+                                              (const char **) &sock_name,
+                                              1,
+                                              open_unix_socket,
+                                              health_unix_sock_path);
        free(sock_name);
        if (ret < 0) {
                ERR("Unable to create health check Unix socket");
@@ -314,8 +300,7 @@ void *thread_manage_health_relayd(void *data __attribute__((unused)))
                        goto error;
                }
 
-               ret = chmod(health_unix_sock_path,
-                               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+               ret = chmod(health_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
                if (ret < 0) {
                        ERR("Unable to set permissions on %s", health_unix_sock_path);
                        PERROR("chmod");
@@ -336,9 +321,8 @@ void *thread_manage_health_relayd(void *data __attribute__((unused)))
        }
 
        /* Size is set to 2 for the unix socket and quit pipe. */
-       ret = fd_tracker_util_poll_create(the_fd_tracker,
-                       "Health management thread epoll", &events, 2,
-                       LTTNG_CLOEXEC);
+       ret = fd_tracker_util_poll_create(
+               the_fd_tracker, "Health management thread epoll", &events, 2, LTTNG_CLOEXEC);
        if (ret < 0) {
                ERR("Poll set creation failed");
                goto error;
@@ -357,13 +341,13 @@ void *thread_manage_health_relayd(void *data __attribute__((unused)))
 
        lttng_relay_notify_ready();
 
-       while (1) {
+       while (true) {
                char *accepted_socket_name;
 
                DBG("Health check ready");
 
                /* Inifinite blocking call, waiting for transmission */
-restart:
+       restart:
                ret = lttng_poll_wait(&events, -1);
                if (ret < 0) {
                        /*
@@ -379,12 +363,12 @@ restart:
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_health_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == health_quit_pipe[0]) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -397,22 +381,28 @@ restart:
                                        ERR("Health socket poll error");
                                        goto error;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                        }
                }
 
-               ret = asprintf(&accepted_socket_name, "Socket accepted from unix socket @ %s",
-                               health_unix_sock_path);
+               ret = asprintf(&accepted_socket_name,
+                              "Socket accepted from unix socket @ %s",
+                              health_unix_sock_path);
                if (ret == -1) {
                        PERROR("Failed to allocate name of accepted socket from unix socket @ %s",
-                                       health_unix_sock_path);
+                              health_unix_sock_path);
                        goto error;
                }
-               ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &new_sock,
-                               (const char **) &accepted_socket_name, 1,
-                               accept_unix_socket, &sock);
+               ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker,
+                                                      &new_sock,
+                                                      (const char **) &accepted_socket_name,
+                                                      1,
+                                                      accept_unix_socket,
+                                                      &sock);
                free(accepted_socket_name);
                if (ret < 0) {
                        goto error;
@@ -425,12 +415,11 @@ restart:
                (void) utils_set_fd_cloexec(new_sock);
 
                DBG("Receiving data from client for health...");
-               ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
+               ret = lttcomm_recv_unix_sock(new_sock, (void *) &msg, sizeof(msg));
                if (ret <= 0) {
                        DBG("Nothing recv() from client... continuing");
-                       ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                                       &new_sock, 1, fd_tracker_util_close_fd,
-                                       NULL);
+                       ret = fd_tracker_close_unsuspendable_fd(
+                               the_fd_tracker, &new_sock, 1, fd_tracker_util_close_fd, nullptr);
                        if (ret) {
                                PERROR("close");
                        }
@@ -461,9 +450,8 @@ restart:
                }
 
                /* End of transmission */
-               ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                               &new_sock, 1, fd_tracker_util_close_fd,
-                               NULL);
+               ret = fd_tracker_close_unsuspendable_fd(
+                       the_fd_tracker, &new_sock, 1, fd_tracker_util_close_fd, nullptr);
                if (ret) {
                        PERROR("close");
                }
@@ -479,8 +467,8 @@ exit:
        DBG("Health check thread dying");
        unlink(health_unix_sock_path);
        if (sock >= 0) {
-               ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &sock,
-                               1, fd_tracker_util_close_fd, NULL);
+               ret = fd_tracker_close_unsuspendable_fd(
+                       the_fd_tracker, &sock, 1, fd_tracker_util_close_fd, nullptr);
                if (ret) {
                        PERROR("close");
                }
@@ -494,5 +482,5 @@ exit:
        (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
 
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
index 7d885c672127aa2917c18061093cc8be82f00ef8..2e417084887be3b42579f1b6cfbf8a8409fcbdac 100644 (file)
@@ -9,18 +9,19 @@
  *
  */
 
-#include <limits.h>
 #include <lttng/health-internal.hpp>
 
-#define LTTNG_RELAYD_HEALTH_ENV                "LTTNG_RELAYD_HEALTH"
+#include <limits.h>
+
+#define LTTNG_RELAYD_HEALTH_ENV "LTTNG_RELAYD_HEALTH"
 
 enum health_type_relayd {
-       HEALTH_RELAYD_TYPE_DISPATCHER           = 0,
-       HEALTH_RELAYD_TYPE_WORKER               = 1,
-       HEALTH_RELAYD_TYPE_LISTENER             = 2,
-       HEALTH_RELAYD_TYPE_LIVE_DISPATCHER      = 3,
-       HEALTH_RELAYD_TYPE_LIVE_WORKER          = 4,
-       HEALTH_RELAYD_TYPE_LIVE_LISTENER        = 5,
+       HEALTH_RELAYD_TYPE_DISPATCHER = 0,
+       HEALTH_RELAYD_TYPE_WORKER = 1,
+       HEALTH_RELAYD_TYPE_LISTENER = 2,
+       HEALTH_RELAYD_TYPE_LIVE_DISPATCHER = 3,
+       HEALTH_RELAYD_TYPE_LIVE_WORKER = 4,
+       HEALTH_RELAYD_TYPE_LIVE_LISTENER = 5,
 
        NR_HEALTH_RELAYD_TYPES,
 };
index a20ae2658a505cfab8431546e458e960ac83f203..e3b8bde8230717a4f5e225d124f307aba135a4f1 100644 (file)
@@ -9,14 +9,15 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/utils.hpp>
-#include <common/compat/endian.hpp>
-
+#include "connection.hpp"
+#include "index.hpp"
 #include "lttng-relayd.hpp"
 #include "stream.hpp"
-#include "index.hpp"
-#include "connection.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
 
 /*
  * Allocate a new relay index object. Pass the stream in which it is
  * Called with stream mutex held.
  * Return allocated object or else NULL on error.
  */
-static struct relay_index *relay_index_create(struct relay_stream *stream,
-               uint64_t net_seq_num)
+static struct relay_index *relay_index_create(struct relay_stream *stream, uint64_t net_seq_num)
 {
        struct relay_index *index;
 
        DBG2("Creating relay index for stream id %" PRIu64 " and seqnum %" PRIu64,
-                       stream->stream_handle, net_seq_num);
+            stream->stream_handle,
+            net_seq_num);
 
        index = zmalloc<relay_index>();
        if (!index) {
@@ -42,13 +43,13 @@ static struct relay_index *relay_index_create(struct relay_stream *stream,
        if (!stream_get(stream)) {
                ERR("Cannot get stream");
                free(index);
-               index = NULL;
+               index = nullptr;
                goto end;
        }
        index->stream = stream;
 
        lttng_ht_node_init_u64(&index->index_n, net_seq_num);
-       pthread_mutex_init(&index->lock, NULL);
+       pthread_mutex_init(&index->lock, nullptr);
        urcu_ref_init(&index->ref);
 
 end:
@@ -62,7 +63,7 @@ end:
  * RCU read side lock MUST be acquired.
  */
 static struct relay_index *relay_index_add_unique(struct relay_stream *stream,
-               struct relay_index *index)
+                                                 struct relay_index *index)
 {
        struct cds_lfht_node *node_ptr;
        struct relay_index *_index;
@@ -70,17 +71,18 @@ static struct relay_index *relay_index_add_unique(struct relay_stream *stream,
        ASSERT_RCU_READ_LOCKED();
 
        DBG2("Adding relay index with stream id %" PRIu64 " and seqnum %" PRIu64,
-                       stream->stream_handle, index->index_n.key);
+            stream->stream_handle,
+            index->index_n.key);
 
        node_ptr = cds_lfht_add_unique(stream->indexes_ht->ht,
-                       stream->indexes_ht->hash_fct(&index->index_n, lttng_ht_seed),
-                       stream->indexes_ht->match_fct, &index->index_n,
-                       &index->index_n.node);
+                                      stream->indexes_ht->hash_fct(&index->index_n, lttng_ht_seed),
+                                      stream->indexes_ht->match_fct,
+                                      &index->index_n,
+                                      &index->index_n.node);
        if (node_ptr != &index->index_n.node) {
-               _index = caa_container_of(node_ptr, struct relay_index,
-                               index_n.node);
+               _index = caa_container_of(node_ptr, struct relay_index, index_n.node);
        } else {
-               _index = NULL;
+               _index = nullptr;
        }
        return _index;
 }
@@ -93,8 +95,9 @@ static bool relay_index_get(struct relay_index *index)
        ASSERT_RCU_READ_LOCKED();
 
        DBG2("index get for stream id %" PRIu64 " and seqnum %" PRIu64 " refcount %d",
-                       index->stream->stream_handle, index->index_n.key,
-                       (int) index->ref.refcount);
+            index->stream->stream_handle,
+            index->index_n.key,
+            (int) index->ref.refcount);
 
        return urcu_ref_get_unless_zero(&index->ref);
 }
@@ -107,16 +110,17 @@ static bool relay_index_get(struct relay_index *index)
  * Return index object or else NULL on error.
  */
 struct relay_index *relay_index_get_by_id_or_create(struct relay_stream *stream,
-                uint64_t net_seq_num)
+                                                   uint64_t net_seq_num)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct relay_index *index = NULL;
+       struct relay_index *index = nullptr;
 
        DBG3("Finding index for stream id %" PRIu64 " and seq_num %" PRIu64,
-                       stream->stream_handle, net_seq_num);
+            stream->stream_handle,
+            net_seq_num);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_lookup(stream->indexes_ht, &net_seq_num, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (node) {
@@ -127,7 +131,8 @@ struct relay_index *relay_index_get_by_id_or_create(struct relay_stream *stream,
                index = relay_index_create(stream, net_seq_num);
                if (!index) {
                        ERR("Cannot create index for stream id %" PRIu64 " and seq_num %" PRIu64,
-                               stream->stream_handle, net_seq_num);
+                           stream->stream_handle,
+                           net_seq_num);
                        goto end;
                }
                oldindex = relay_index_add_unique(stream, index);
@@ -136,7 +141,7 @@ struct relay_index *relay_index_get_by_id_or_create(struct relay_stream *stream,
                        relay_index_put(index);
                        index = oldindex;
                        if (!relay_index_get(index)) {
-                               index = NULL;
+                               index = nullptr;
                        }
                } else {
                        stream->indexes_in_flight++;
@@ -144,15 +149,16 @@ struct relay_index *relay_index_get_by_id_or_create(struct relay_stream *stream,
                }
        }
 end:
-       rcu_read_unlock();
        DBG2("Index %sfound or created in HT for stream ID %" PRIu64 " and seqnum %" PRIu64,
-                       (index == NULL) ? "NOT " : "", stream->stream_handle, net_seq_num);
+            (index == NULL) ? "NOT " : "",
+            stream->stream_handle,
+            net_seq_num);
        return index;
 }
 
 int relay_index_set_file(struct relay_index *index,
-               struct lttng_index_file *index_file,
-               uint64_t data_offset)
+                        struct lttng_index_file *index_file,
+                        uint64_t data_offset)
 {
        int ret = 0;
 
@@ -169,8 +175,7 @@ end:
        return ret;
 }
 
-int relay_index_set_data(struct relay_index *index,
-               const struct ctf_packet_index *data)
+int relay_index_set_data(struct relay_index *index, const struct ctf_packet_index *data)
 {
        int ret = 0;
 
@@ -199,8 +204,7 @@ static void index_destroy(struct relay_index *index)
 
 static void index_destroy_rcu(struct rcu_head *rcu_head)
 {
-       struct relay_index *index =
-               lttng::utils::container_of(rcu_head, &relay_index::rcu_node);
+       struct relay_index *index = lttng::utils::container_of(rcu_head, &relay_index::rcu_node);
 
        index_destroy(index);
 }
@@ -215,7 +219,7 @@ static void index_release(struct urcu_ref *ref)
 
        if (index->index_file) {
                lttng_index_file_put(index->index_file);
-               index->index_file = NULL;
+               index->index_file = nullptr;
        }
        if (index->in_hash_table) {
                /* Delete index from hash table. */
@@ -226,7 +230,7 @@ static void index_release(struct urcu_ref *ref)
        }
 
        stream_put(index->stream);
-       index->stream = NULL;
+       index->stream = nullptr;
 
        call_rcu(&index->rcu_node, index_destroy_rcu);
 }
@@ -239,19 +243,19 @@ static void index_release(struct urcu_ref *ref)
 void relay_index_put(struct relay_index *index)
 {
        DBG2("index put for stream id %" PRIu64 " and seqnum %" PRIu64 " refcount %d",
-                       index->stream->stream_handle, index->index_n.key,
-                       (int) index->ref.refcount);
+            index->stream->stream_handle,
+            index->index_n.key,
+            (int) index->ref.refcount);
        /*
         * Ensure existence of index->lock for index unlock.
         */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        /*
         * Index lock ensures that concurrent test and update of stream
         * ref is atomic.
         */
        LTTNG_ASSERT(index->ref.refcount != 0);
        urcu_ref_put(&index->ref, index_release);
-       rcu_read_unlock();
 }
 
 /*
@@ -277,7 +281,8 @@ int relay_index_try_flush(struct relay_index *index)
        }
 
        DBG2("Writing index for stream ID %" PRIu64 " and seq num %" PRIu64,
-                       index->stream->stream_handle, index->index_n.key);
+            index->stream->stream_handle,
+            index->index_n.key);
        flushed = true;
        index->flushed = true;
        ret = lttng_index_file_write(index->index_file, &index->index_data);
@@ -300,13 +305,12 @@ void relay_index_close_all(struct relay_stream *stream)
        struct lttng_ht_iter iter;
        struct relay_index *index;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(stream->indexes_ht->ht, &iter.iter,
-                       index, index_n.node) {
+       lttng::urcu::read_lock_guard read_lock;
+
+       cds_lfht_for_each_entry (stream->indexes_ht->ht, &iter.iter, index, index_n.node) {
                /* Put self-ref from index. */
                relay_index_put(index);
        }
-       rcu_read_unlock();
 }
 
 void relay_index_close_partial_fd(struct relay_stream *stream)
@@ -314,9 +318,9 @@ void relay_index_close_partial_fd(struct relay_stream *stream)
        struct lttng_ht_iter iter;
        struct relay_index *index;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(stream->indexes_ht->ht, &iter.iter,
-                       index, index_n.node) {
+       lttng::urcu::read_lock_guard read_lock;
+
+       cds_lfht_for_each_entry (stream->indexes_ht->ht, &iter.iter, index, index_n.node) {
                if (!index->index_file) {
                        continue;
                }
@@ -327,7 +331,6 @@ void relay_index_close_partial_fd(struct relay_stream *stream)
                 */
                relay_index_put(index);
        }
-       rcu_read_unlock();
 }
 
 uint64_t relay_index_find_last(struct relay_stream *stream)
@@ -336,15 +339,14 @@ uint64_t relay_index_find_last(struct relay_stream *stream)
        struct relay_index *index;
        uint64_t net_seq_num = -1ULL;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(stream->indexes_ht->ht, &iter.iter,
-                       index, index_n.node) {
-               if (net_seq_num == -1ULL ||
-                               index->index_n.key > net_seq_num) {
+       lttng::urcu::read_lock_guard read_lock;
+
+       cds_lfht_for_each_entry (stream->indexes_ht->ht, &iter.iter, index, index_n.node) {
+               if (net_seq_num == -1ULL || index->index_n.key > net_seq_num) {
                        net_seq_num = index->index_n.key;
                }
        }
-       rcu_read_unlock();
+
        return net_seq_num;
 }
 
@@ -352,10 +354,9 @@ uint64_t relay_index_find_last(struct relay_stream *stream)
  * Update the index file of an already existing relay_index.
  * Offsets by 'removed_data_count' the offset field of an index.
  */
-static
-int relay_index_switch_file(struct relay_index *index,
-               struct lttng_index_file *new_index_file,
-               uint64_t removed_data_count)
+static int relay_index_switch_file(struct relay_index *index,
+                                  struct lttng_index_file *new_index_file,
+                                  uint64_t removed_data_count)
 {
        int ret = 0;
        uint64_t offset;
@@ -389,17 +390,16 @@ int relay_index_switch_all_files(struct relay_stream *stream)
        struct relay_index *index;
        int ret = 0;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(stream->indexes_ht->ht, &iter.iter,
-                       index, index_n.node) {
-               ret = relay_index_switch_file(index, stream->index_file,
-                               stream->pos_after_last_complete_data_index);
+       lttng::urcu::read_lock_guard read_lock;
+
+       cds_lfht_for_each_entry (stream->indexes_ht->ht, &iter.iter, index, index_n.node) {
+               ret = relay_index_switch_file(
+                       index, stream->index_file, stream->pos_after_last_complete_data_index);
                if (ret) {
-                       goto end;
+                       return ret;
                }
        }
-end:
-       rcu_read_unlock();
+
        return ret;
 }
 
@@ -407,11 +407,11 @@ end:
  * Set index data from the control port to a given index object.
  */
 int relay_index_set_control_data(struct relay_index *index,
-               const struct lttcomm_relayd_index *data,
-               unsigned int minor_version)
+                                const struct lttcomm_relayd_index *data,
+                                unsigned int minor_version)
 {
        /* The index on disk is encoded in big endian. */
-       ctf_packet_index index_data {};
+       ctf_packet_index index_data{};
 
        index_data.packet_size = htobe64(data->packet_size);
        index_data.content_size = htobe64(data->content_size);
index cb29485eb72559b8d049cc03af4c477634a3580b..8ba88c99220642da66e74d03372591bb45f9a649 100644 (file)
  *
  */
 
-#include <inttypes.h>
-#include <pthread.h>
-
 #include <common/hashtable/hashtable.hpp>
 #include <common/index/index.hpp>
 
+#include <inttypes.h>
+#include <pthread.h>
+
 struct relay_stream;
 struct relay_connection;
 struct lttcomm_relayd_index;
@@ -24,8 +24,8 @@ struct relay_index {
        /*
         * index lock nests inside stream lock.
         */
-       struct urcu_ref ref;            /* Reference from getters. */
-       struct relay_stream *stream;    /* Back ref to stream */
+       struct urcu_ref ref; /* Reference from getters. */
+       struct relay_stream *stream; /* Back ref to stream */
 
        pthread_mutex_t lock;
        /*
@@ -49,17 +49,16 @@ struct relay_index {
         * index across the stream.
         */
        struct lttng_ht_node_u64 index_n;
-       struct rcu_head rcu_node;       /* For call_rcu teardown. */
+       struct rcu_head rcu_node; /* For call_rcu teardown. */
 };
 
 struct relay_index *relay_index_get_by_id_or_create(struct relay_stream *stream,
-               uint64_t net_seq_num);
+                                                   uint64_t net_seq_num);
 void relay_index_put(struct relay_index *index);
 int relay_index_set_file(struct relay_index *index,
-               struct lttng_index_file *index_file,
-               uint64_t data_offset);
-int relay_index_set_data(struct relay_index *index,
-               const struct ctf_packet_index *data);
+                        struct lttng_index_file *index_file,
+                        uint64_t data_offset);
+int relay_index_set_data(struct relay_index *index, const struct ctf_packet_index *data);
 int relay_index_try_flush(struct relay_index *index);
 
 void relay_index_close_all(struct relay_stream *stream);
@@ -67,7 +66,7 @@ void relay_index_close_partial_fd(struct relay_stream *stream);
 uint64_t relay_index_find_last(struct relay_stream *stream);
 int relay_index_switch_all_files(struct relay_stream *stream);
 int relay_index_set_control_data(struct relay_index *index,
-               const struct lttcomm_relayd_index *data,
-               unsigned int minor_version);
+                                const struct lttcomm_relayd_index *data,
+                                unsigned int minor_version);
 
 #endif /* _RELAY_INDEX_H */
index abbec8c20e89e02253a0dce83a38a138909b9dff..699778d0e4ef2c144e4bcaba390387750b2f7606 100644 (file)
@@ -8,6 +8,37 @@
  */
 
 #define _LGPL_SOURCE
+#include "cmd.hpp"
+#include "connection.hpp"
+#include "ctf-trace.hpp"
+#include "health-relayd.hpp"
+#include "live.hpp"
+#include "lttng-relayd.hpp"
+#include "session.hpp"
+#include "stream.hpp"
+#include "testpoint.hpp"
+#include "utils.hpp"
+#include "viewer-session.hpp"
+#include "viewer-stream.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/compat/poll.hpp>
+#include <common/compat/socket.hpp>
+#include <common/defaults.hpp>
+#include <common/fd-tracker/utils.hpp>
+#include <common/fs-handle.hpp>
+#include <common/futex.hpp>
+#include <common/index/index.hpp>
+#include <common/sessiond-comm/inet.hpp>
+#include <common/sessiond-comm/relayd.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
+#include <common/uri.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
 #include <fcntl.h>
 #include <getopt.h>
 #include <grp.h>
@@ -18,6 +49,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <string>
 #include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/resource.h>
 #include <urcu/futex.h>
 #include <urcu/rculist.h>
 #include <urcu/uatomic.h>
-#include <string>
-
-#include <common/common.hpp>
-#include <common/compat/endian.hpp>
-#include <common/compat/poll.hpp>
-#include <common/compat/socket.hpp>
-#include <common/defaults.hpp>
-#include <common/fd-tracker/utils.hpp>
-#include <common/fs-handle.hpp>
-#include <common/futex.hpp>
-#include <common/index/index.hpp>
-#include <common/sessiond-comm/inet.hpp>
-#include <common/sessiond-comm/relayd.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/uri.hpp>
-#include <common/utils.hpp>
-#include <lttng/lttng.h>
 
-#include "cmd.hpp"
-#include "connection.hpp"
-#include "ctf-trace.hpp"
-#include "health-relayd.hpp"
-#include "live.hpp"
-#include "lttng-relayd.hpp"
-#include "session.hpp"
-#include "stream.hpp"
-#include "testpoint.hpp"
-#include "utils.hpp"
-#include "viewer-session.hpp"
-#include "viewer-stream.hpp"
-
-#define SESSION_BUF_DEFAULT_COUNT      16
+#define SESSION_BUF_DEFAULT_COUNT 16
 
 static struct lttng_uri *live_uri;
 
@@ -86,11 +88,9 @@ static pthread_t live_worker_thread;
 static struct relay_conn_queue viewer_conn_queue;
 
 static uint64_t last_relay_viewer_session_id;
-static pthread_mutex_t last_relay_viewer_session_id_lock =
-               PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t last_relay_viewer_session_id_lock = PTHREAD_MUTEX_INITIALIZER;
 
-static
-const char *lttng_viewer_command_str(lttng_viewer_command cmd)
+static const char *lttng_viewer_command_str(lttng_viewer_command cmd)
 {
        switch (cmd) {
        case LTTNG_VIEWER_CONNECT:
@@ -116,9 +116,8 @@ const char *lttng_viewer_command_str(lttng_viewer_command cmd)
        }
 }
 
-static
-const char *lttng_viewer_next_index_return_code_str(
-               enum lttng_viewer_next_index_return_code code)
+static const char *
+lttng_viewer_next_index_return_code_str(enum lttng_viewer_next_index_return_code code)
 {
        switch (code) {
        case LTTNG_VIEWER_INDEX_OK:
@@ -138,9 +137,7 @@ const char *lttng_viewer_next_index_return_code_str(
        }
 }
 
-static
-const char *lttng_viewer_attach_return_code_str(
-               enum lttng_viewer_attach_return_code code)
+static const char *lttng_viewer_attach_return_code_str(enum lttng_viewer_attach_return_code code)
 {
        switch (code) {
        case LTTNG_VIEWER_ATTACH_OK:
@@ -160,9 +157,8 @@ const char *lttng_viewer_attach_return_code_str(
        }
 };
 
-static
-const char *lttng_viewer_get_packet_return_code_str(
-               enum lttng_viewer_get_packet_return_code code)
+static const char *
+lttng_viewer_get_packet_return_code_str(enum lttng_viewer_get_packet_return_code code)
 {
        switch (code) {
        case LTTNG_VIEWER_GET_PACKET_OK:
@@ -181,8 +177,7 @@ const char *lttng_viewer_get_packet_return_code_str(
 /*
  * Cleanup the daemon
  */
-static
-void cleanup_relayd_live(void)
+static void cleanup_relayd_live()
 {
        DBG("Cleaning up");
 
@@ -196,8 +191,7 @@ void cleanup_relayd_live(void)
  * Return the size of the received message or else a negative value on error
  * with errno being set by recvmsg() syscall.
  */
-static
-ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
+static ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
 {
        ssize_t ret;
 
@@ -222,8 +216,7 @@ ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
  * Return the size of the sent message or else a negative value on error with
  * errno being set by sendmsg() syscall.
  */
-static
-ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
+static ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
 {
        ssize_t ret;
 
@@ -242,32 +235,36 @@ ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
  * Returns 1 if new streams got added, 0 if nothing changed, a negative value
  * on error.
  */
-static
-int check_new_streams(struct relay_connection *conn)
+static int check_new_streams(struct relay_connection *conn)
 {
        struct relay_session *session;
-       unsigned long current_val;
        int ret = 0;
 
        if (!conn->viewer_session) {
                goto end;
        }
-       rcu_read_lock();
-       cds_list_for_each_entry_rcu(session,
-                       &conn->viewer_session->session_list,
-                       viewer_session_node) {
-               if (!session_get(session)) {
-                       continue;
-               }
-               current_val = uatomic_cmpxchg(&session->new_streams, 1, 0);
-               ret = current_val;
-               session_put(session);
-               if (ret == 1) {
-                       goto end;
+
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_list_for_each_entry_rcu(
+                       session, &conn->viewer_session->session_list, viewer_session_node)
+               {
+                       if (!session_get(session)) {
+                               continue;
+                       }
+
+                       ret = uatomic_read(&session->new_streams);
+                       session_put(session);
+                       if (ret == 1) {
+                               goto end;
+                       }
                }
        }
+
 end:
-       rcu_read_unlock();
+       DBG("Viewer connection has%s new streams: socket_fd = %d",
+           ret == 0 ? " no" : "",
+           conn->sock->fd);
        return ret;
 }
 
@@ -277,73 +274,72 @@ end:
  *
  * Return 0 on success or else a negative value.
  */
-static
-ssize_t send_viewer_streams(struct lttcomm_sock *sock,
-               uint64_t session_id, unsigned int ignore_sent_flag)
+static ssize_t
+send_viewer_streams(struct lttcomm_sock *sock, uint64_t session_id, unsigned int ignore_sent_flag)
 {
        ssize_t ret;
        struct lttng_ht_iter iter;
        struct relay_viewer_stream *vstream;
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
-                       stream_n.node) {
-               struct ctf_trace *ctf_trace;
-               struct lttng_viewer_stream send_stream = {};
+               cds_lfht_for_each_entry (
+                       viewer_streams_ht->ht, &iter.iter, vstream, stream_n.node) {
+                       struct ctf_trace *ctf_trace;
+                       struct lttng_viewer_stream send_stream = {};
 
-               health_code_update();
+                       health_code_update();
 
-               if (!viewer_stream_get(vstream)) {
-                       continue;
-               }
+                       if (!viewer_stream_get(vstream)) {
+                               continue;
+                       }
 
-               pthread_mutex_lock(&vstream->stream->lock);
-               /* Ignore if not the same session. */
-               if (vstream->stream->trace->session->id != session_id ||
-                               (!ignore_sent_flag && vstream->sent_flag)) {
-                       pthread_mutex_unlock(&vstream->stream->lock);
-                       viewer_stream_put(vstream);
-                       continue;
-               }
+                       pthread_mutex_lock(&vstream->stream->lock);
+                       /* Ignore if not the same session. */
+                       if (vstream->stream->trace->session->id != session_id ||
+                           (!ignore_sent_flag && vstream->sent_flag)) {
+                               pthread_mutex_unlock(&vstream->stream->lock);
+                               viewer_stream_put(vstream);
+                               continue;
+                       }
 
-               ctf_trace = vstream->stream->trace;
-               send_stream.id = htobe64(vstream->stream->stream_handle);
-               send_stream.ctf_trace_id = htobe64(ctf_trace->id);
-               send_stream.metadata_flag = htobe32(
-                               vstream->stream->is_metadata);
-               if (lttng_strncpy(send_stream.path_name, vstream->path_name,
-                               sizeof(send_stream.path_name))) {
-                       pthread_mutex_unlock(&vstream->stream->lock);
-                       viewer_stream_put(vstream);
-                       ret = -1;       /* Error. */
-                       goto end_unlock;
-               }
-               if (lttng_strncpy(send_stream.channel_name,
-                               vstream->channel_name,
-                               sizeof(send_stream.channel_name))) {
-                       pthread_mutex_unlock(&vstream->stream->lock);
-                       viewer_stream_put(vstream);
-                       ret = -1;       /* Error. */
-                       goto end_unlock;
-               }
+                       ctf_trace = vstream->stream->trace;
+                       send_stream.id = htobe64(vstream->stream->stream_handle);
+                       send_stream.ctf_trace_id = htobe64(ctf_trace->id);
+                       send_stream.metadata_flag = htobe32(vstream->stream->is_metadata);
+                       if (lttng_strncpy(send_stream.path_name,
+                                         vstream->path_name,
+                                         sizeof(send_stream.path_name))) {
+                               pthread_mutex_unlock(&vstream->stream->lock);
+                               viewer_stream_put(vstream);
+                               ret = -1; /* Error. */
+                               goto end;
+                       }
+                       if (lttng_strncpy(send_stream.channel_name,
+                                         vstream->channel_name,
+                                         sizeof(send_stream.channel_name))) {
+                               pthread_mutex_unlock(&vstream->stream->lock);
+                               viewer_stream_put(vstream);
+                               ret = -1; /* Error. */
+                               goto end;
+                       }
 
-               DBG("Sending stream %" PRIu64 " to viewer",
-                               vstream->stream->stream_handle);
-               vstream->sent_flag = 1;
-               pthread_mutex_unlock(&vstream->stream->lock);
+                       DBG("Sending stream %" PRIu64 " to viewer", vstream->stream->stream_handle);
+                       vstream->sent_flag = true;
+                       pthread_mutex_unlock(&vstream->stream->lock);
 
-               ret = send_response(sock, &send_stream, sizeof(send_stream));
-               viewer_stream_put(vstream);
-               if (ret < 0) {
-                       goto end_unlock;
+                       ret = send_response(sock, &send_stream, sizeof(send_stream));
+                       viewer_stream_put(vstream);
+                       if (ret < 0) {
+                               goto end;
+                       }
                }
        }
 
        ret = 0;
 
-end_unlock:
-       rcu_read_unlock();
+end:
        return ret;
 }
 
@@ -359,17 +355,17 @@ end_unlock:
  * Return 0 on success or else a negative value.
  */
 static int make_viewer_streams(struct relay_session *relay_session,
-               struct relay_viewer_session *viewer_session,
-               enum lttng_viewer_seek seek_t,
-               uint32_t *nb_total,
-               uint32_t *nb_unsent,
-               uint32_t *nb_created,
-               bool *closed)
+                              struct relay_viewer_session *viewer_session,
+                              enum lttng_viewer_seek seek_t,
+                              uint32_t *nb_total,
+                              uint32_t *nb_unsent,
+                              uint32_t *nb_created,
+                              bool *closed)
 {
        int ret;
        struct lttng_ht_iter iter;
        struct ctf_trace *ctf_trace;
-       struct relay_stream *relay_stream = NULL;
+       struct relay_stream *relay_stream = nullptr;
 
        LTTNG_ASSERT(relay_session);
        ASSERT_LOCKED(relay_session->lock);
@@ -382,197 +378,201 @@ static int make_viewer_streams(struct relay_session *relay_session,
         * Create viewer streams for relay streams that are ready to be
         * used for a the given session id only.
         */
-       rcu_read_lock();
-       cds_lfht_for_each_entry (relay_session->ctf_traces_ht->ht, &iter.iter,
-                       ctf_trace, node.node) {
-               bool trace_has_metadata_stream = false;
-
-               health_code_update();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (!ctf_trace_get(ctf_trace)) {
-                       continue;
-               }
-
-               /*
-                * Iterate over all the streams of the trace to see if we have a
-                * metadata stream.
-                */
-               cds_list_for_each_entry_rcu(relay_stream,
-                               &ctf_trace->stream_list, stream_node)
-               {
-                       bool is_metadata_stream;
+               cds_lfht_for_each_entry (
+                       relay_session->ctf_traces_ht->ht, &iter.iter, ctf_trace, node.node) {
+                       bool trace_has_metadata_stream = false;
 
-                       pthread_mutex_lock(&relay_stream->lock);
-                       is_metadata_stream = relay_stream->is_metadata;
-                       pthread_mutex_unlock(&relay_stream->lock);
+                       health_code_update();
 
-                       if (is_metadata_stream) {
-                               trace_has_metadata_stream = true;
-                               break;
+                       if (!ctf_trace_get(ctf_trace)) {
+                               continue;
                        }
-               }
-
-               relay_stream = NULL;
-
-               /*
-                * If there is no metadata stream in this trace at the moment
-                * and we never sent one to the viewer, skip the trace. We
-                * accept that the viewer will not see this trace at all.
-                */
-               if (!trace_has_metadata_stream &&
-                               !ctf_trace->metadata_stream_sent_to_viewer) {
-                       ctf_trace_put(ctf_trace);
-                       continue;
-               }
 
-               cds_list_for_each_entry_rcu(relay_stream,
-                               &ctf_trace->stream_list, stream_node)
-               {
-                       struct relay_viewer_stream *viewer_stream;
-
-                       if (!stream_get(relay_stream)) {
-                               continue;
+                       /*
+                        * Iterate over all the streams of the trace to see if we have a
+                        * metadata stream.
+                        */
+                       cds_list_for_each_entry_rcu(
+                               relay_stream, &ctf_trace->stream_list, stream_node)
+                       {
+                               bool is_metadata_stream;
+
+                               pthread_mutex_lock(&relay_stream->lock);
+                               is_metadata_stream = relay_stream->is_metadata;
+                               pthread_mutex_unlock(&relay_stream->lock);
+
+                               if (is_metadata_stream) {
+                                       trace_has_metadata_stream = true;
+                                       break;
+                               }
                        }
 
-                       pthread_mutex_lock(&relay_stream->lock);
+                       relay_stream = nullptr;
+
                        /*
-                        * stream published is protected by the session lock.
+                        * If there is no metadata stream in this trace at the moment
+                        * and we never sent one to the viewer, skip the trace. We
+                        * accept that the viewer will not see this trace at all.
                         */
-                       if (!relay_stream->published) {
-                               goto next;
+                       if (!trace_has_metadata_stream &&
+                           !ctf_trace->metadata_stream_sent_to_viewer) {
+                               ctf_trace_put(ctf_trace);
+                               continue;
                        }
-                       viewer_stream = viewer_stream_get_by_id(
-                                       relay_stream->stream_handle);
-                       if (!viewer_stream) {
-                               struct lttng_trace_chunk *viewer_stream_trace_chunk = NULL;
 
-                               /*
-                                * Save that we sent the metadata stream to the
-                                * viewer. So that we know what trace the viewer
-                                * is aware of.
-                                */
-                               if (relay_stream->is_metadata) {
-                                       ctf_trace->metadata_stream_sent_to_viewer = true;
+                       cds_list_for_each_entry_rcu(
+                               relay_stream, &ctf_trace->stream_list, stream_node)
+                       {
+                               struct relay_viewer_stream *viewer_stream;
+
+                               if (!stream_get(relay_stream)) {
+                                       continue;
                                }
 
+                               pthread_mutex_lock(&relay_stream->lock);
                                /*
-                                * If a rotation is ongoing, use a copy of the
-                                * relay stream's chunk to ensure the stream
-                                * files exist.
-                                *
-                                * Otherwise, the viewer session's current trace
-                                * chunk can be used safely.
+                                * stream published is protected by the session lock.
                                 */
-                               if ((relay_stream->ongoing_rotation.is_set ||
-                                               session_has_ongoing_rotation(relay_session)) &&
-                                               relay_stream->trace_chunk) {
-                                       viewer_stream_trace_chunk = lttng_trace_chunk_copy(
-                                                       relay_stream->trace_chunk);
-                                       if (!viewer_stream_trace_chunk) {
-                                               ret = -1;
-                                               ctf_trace_put(ctf_trace);
-                                               goto error_unlock;
-                                       }
-                               } else {
+                               if (!relay_stream->published) {
+                                       goto next;
+                               }
+                               viewer_stream =
+                                       viewer_stream_get_by_id(relay_stream->stream_handle);
+                               if (!viewer_stream) {
+                                       struct lttng_trace_chunk *viewer_stream_trace_chunk =
+                                               nullptr;
+
                                        /*
-                                        * Transition the viewer session into the newest trace chunk available.
+                                        * Save that we sent the metadata stream to the
+                                        * viewer. So that we know what trace the viewer
+                                        * is aware of.
                                         */
-                                       if (!lttng_trace_chunk_ids_equal(viewer_session->current_trace_chunk,
-                                                       relay_stream->trace_chunk)) {
+                                       if (relay_stream->is_metadata) {
+                                               ctf_trace->metadata_stream_sent_to_viewer = true;
+                                       }
 
-                                               ret = viewer_session_set_trace_chunk_copy(
-                                                               viewer_session,
-                                                               relay_stream->trace_chunk);
-                                               if (ret) {
+                                       /*
+                                        * If a rotation is ongoing, use a copy of the
+                                        * relay stream's chunk to ensure the stream
+                                        * files exist.
+                                        *
+                                        * Otherwise, the viewer session's current trace
+                                        * chunk can be used safely.
+                                        */
+                                       if ((relay_stream->ongoing_rotation.is_set ||
+                                            session_has_ongoing_rotation(relay_session)) &&
+                                           relay_stream->trace_chunk) {
+                                               viewer_stream_trace_chunk = lttng_trace_chunk_copy(
+                                                       relay_stream->trace_chunk);
+                                               if (!viewer_stream_trace_chunk) {
                                                        ret = -1;
                                                        ctf_trace_put(ctf_trace);
                                                        goto error_unlock;
                                                }
-                                       }
-
-                                       if (relay_stream->trace_chunk) {
+                                       } else {
                                                /*
-                                                * If the corresponding relay
-                                                * stream's trace chunk is set,
-                                                * the viewer stream will be
-                                                * created under it.
-                                                *
-                                                * Note that a relay stream can
-                                                * have a NULL output trace
-                                                * chunk (for instance, after a
-                                                * clear against a stopped
-                                                * session).
+                                                * Transition the viewer session into the newest
+                                                * trace chunk available.
                                                 */
-                                               const bool reference_acquired = lttng_trace_chunk_get(
-                                                               viewer_session->current_trace_chunk);
+                                               if (!lttng_trace_chunk_ids_equal(
+                                                           viewer_session->current_trace_chunk,
+                                                           relay_stream->trace_chunk)) {
+                                                       ret = viewer_session_set_trace_chunk_copy(
+                                                               viewer_session,
+                                                               relay_stream->trace_chunk);
+                                                       if (ret) {
+                                                               ret = -1;
+                                                               ctf_trace_put(ctf_trace);
+                                                               goto error_unlock;
+                                                       }
+                                               }
 
-                                               LTTNG_ASSERT(reference_acquired);
-                                               viewer_stream_trace_chunk =
+                                               if (relay_stream->trace_chunk) {
+                                                       /*
+                                                        * If the corresponding relay
+                                                        * stream's trace chunk is set,
+                                                        * the viewer stream will be
+                                                        * created under it.
+                                                        *
+                                                        * Note that a relay stream can
+                                                        * have a NULL output trace
+                                                        * chunk (for instance, after a
+                                                        * clear against a stopped
+                                                        * session).
+                                                        */
+                                                       const bool reference_acquired =
+                                                               lttng_trace_chunk_get(
+                                                                       viewer_session
+                                                                               ->current_trace_chunk);
+
+                                                       LTTNG_ASSERT(reference_acquired);
+                                                       viewer_stream_trace_chunk =
                                                                viewer_session->current_trace_chunk;
+                                               }
                                        }
-                               }
 
-                               viewer_stream = viewer_stream_create(
-                                               relay_stream,
-                                               viewer_stream_trace_chunk,
-                                               seek_t);
-                               lttng_trace_chunk_put(viewer_stream_trace_chunk);
-                               viewer_stream_trace_chunk = NULL;
-                               if (!viewer_stream) {
-                                       ret = -1;
-                                       ctf_trace_put(ctf_trace);
-                                       goto error_unlock;
-                               }
+                                       viewer_stream = viewer_stream_create(
+                                               relay_stream, viewer_stream_trace_chunk, seek_t);
+                                       lttng_trace_chunk_put(viewer_stream_trace_chunk);
+                                       viewer_stream_trace_chunk = nullptr;
+                                       if (!viewer_stream) {
+                                               ret = -1;
+                                               ctf_trace_put(ctf_trace);
+                                               goto error_unlock;
+                                       }
 
-                               if (nb_created) {
-                                       /* Update number of created stream counter. */
-                                       (*nb_created)++;
-                               }
-                               /*
-                                * Ensure a self-reference is preserved even
-                                * after we have put our local reference.
-                                */
-                               if (!viewer_stream_get(viewer_stream)) {
-                                       ERR("Unable to get self-reference on viewer stream, logic error.");
-                                       abort();
-                               }
-                       } else {
-                               if (!viewer_stream->sent_flag && nb_unsent) {
-                                       /* Update number of unsent stream counter. */
-                                       (*nb_unsent)++;
-                               }
-                       }
-                       /* Update number of total stream counter. */
-                       if (nb_total) {
-                               if (relay_stream->is_metadata) {
-                                       if (!relay_stream->closed ||
-                                                       relay_stream->metadata_received >
-                                                                       viewer_stream->metadata_sent) {
-                                               (*nb_total)++;
+                                       if (nb_created) {
+                                               /* Update number of created stream counter. */
+                                               (*nb_created)++;
+                                       }
+                                       /*
+                                        * Ensure a self-reference is preserved even
+                                        * after we have put our local reference.
+                                        */
+                                       if (!viewer_stream_get(viewer_stream)) {
+                                               ERR("Unable to get self-reference on viewer stream, logic error.");
+                                               abort();
                                        }
                                } else {
-                                       if (!relay_stream->closed ||
-                                                       !(((int64_t)(relay_stream->prev_data_seq -
-                                                                         relay_stream->last_net_seq_num)) >=
-                                                                       0)) {
-                                               (*nb_total)++;
+                                       if (!viewer_stream->sent_flag && nb_unsent) {
+                                               /* Update number of unsent stream counter. */
+                                               (*nb_unsent)++;
+                                       }
+                               }
+                               /* Update number of total stream counter. */
+                               if (nb_total) {
+                                       if (relay_stream->is_metadata) {
+                                               if (!relay_stream->closed ||
+                                                   relay_stream->metadata_received >
+                                                           viewer_stream->metadata_sent) {
+                                                       (*nb_total)++;
+                                               }
+                                       } else {
+                                               if (!relay_stream->closed ||
+                                                   !(((int64_t) (relay_stream->prev_data_seq -
+                                                                 relay_stream->last_net_seq_num)) >=
+                                                     0)) {
+                                                       (*nb_total)++;
+                                               }
                                        }
                                }
+                               /* Put local reference. */
+                               viewer_stream_put(viewer_stream);
+                       next:
+                               pthread_mutex_unlock(&relay_stream->lock);
+                               stream_put(relay_stream);
                        }
-                       /* Put local reference. */
-                       viewer_stream_put(viewer_stream);
-               next:
-                       pthread_mutex_unlock(&relay_stream->lock);
-                       stream_put(relay_stream);
+                       relay_stream = nullptr;
+                       ctf_trace_put(ctf_trace);
                }
-               relay_stream = NULL;
-               ctf_trace_put(ctf_trace);
        }
 
        ret = 0;
 
 error_unlock:
-       rcu_read_unlock();
 
        if (relay_stream) {
                pthread_mutex_unlock(&relay_stream->lock);
@@ -582,7 +582,7 @@ error_unlock:
        return ret;
 }
 
-int relayd_live_stop(void)
+int relayd_live_stop()
 {
        /* Stop dispatch thread */
        CMM_STORE_SHARED(live_dispatch_thread_exit, 1);
@@ -590,56 +590,7 @@ int relayd_live_stop(void)
        return 0;
 }
 
-/*
- * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
- */
-static
-int create_named_thread_poll_set(struct lttng_poll_event *events,
-               int size, const char *name)
-{
-       int ret;
-
-       if (events == NULL || size == 0) {
-               ret = -1;
-               goto error;
-       }
-
-       ret = fd_tracker_util_poll_create(the_fd_tracker,
-                       name, events, 1, LTTNG_CLOEXEC);
-       if (ret) {
-               PERROR("Failed to create \"%s\" poll file descriptor", name);
-               goto error;
-       }
-
-       /* Add quit pipe */
-       ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
-       if (ret < 0) {
-               goto error;
-       }
-
-       return 0;
-
-error:
-       return ret;
-}
-
-/*
- * Check if the thread quit pipe was triggered.
- *
- * Return 1 if it was triggered else 0;
- */
-static
-int check_thread_quit_pipe(int fd, uint32_t events)
-{
-       if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
-               return 1;
-       }
-
-       return 0;
-}
-
-static
-int create_sock(void *data, int *out_fd)
+static int create_sock(void *data, int *out_fd)
 {
        int ret;
        struct lttcomm_sock *sock = (lttcomm_sock *) data;
@@ -654,8 +605,7 @@ end:
        return ret;
 }
 
-static
-int close_sock(void *data, int *in_fd __attribute__((unused)))
+static int close_sock(void *data, int *in_fd __attribute__((unused)))
 {
        struct lttcomm_sock *sock = (lttcomm_sock *) data;
 
@@ -679,16 +629,14 @@ end:
        return ret;
 }
 
-static
-struct lttcomm_sock *accept_live_sock(struct lttcomm_sock *listening_sock,
-               const char *name)
+static struct lttcomm_sock *accept_live_sock(struct lttcomm_sock *listening_sock, const char *name)
 {
        int out_fd, ret;
-       struct lttcomm_sock *socks[2] = { listening_sock, NULL };
-       struct lttcomm_sock *new_sock = NULL;
+       struct lttcomm_sock *socks[2] = { listening_sock, nullptr };
+       struct lttcomm_sock *new_sock = nullptr;
 
-       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &out_fd,
-                       (const char **) &name, 1, accept_sock, &socks);
+       ret = fd_tracker_open_unsuspendable_fd(
+               the_fd_tracker, &out_fd, (const char **) &name, 1, accept_sock, &socks);
        if (ret) {
                goto end;
        }
@@ -701,16 +649,15 @@ end:
 /*
  * Create and init socket from uri.
  */
-static
-struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
+static struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
 {
        int ret, sock_fd;
-       struct lttcomm_sock *sock = NULL;
+       struct lttcomm_sock *sock = nullptr;
        char uri_str[LTTNG_PATH_MAX];
-       char *formated_name = NULL;
+       char *formated_name = nullptr;
 
        sock = lttcomm_alloc_sock_from_uri(uri);
-       if (sock == NULL) {
+       if (sock == nullptr) {
                ERR("Allocating socket");
                goto error;
        }
@@ -722,19 +669,21 @@ struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
        ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
        uri_str[sizeof(uri_str) - 1] = '\0';
        if (ret >= 0) {
-               ret = asprintf(&formated_name, "%s socket @ %s", name,
-                               uri_str);
+               ret = asprintf(&formated_name, "%s socket @ %s", name, uri_str);
                if (ret < 0) {
-                       formated_name = NULL;
+                       formated_name = nullptr;
                }
        }
 
-       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
-                       (const char **) (formated_name ? &formated_name : NULL),
-                       1, create_sock, sock);
+       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker,
+                                              &sock_fd,
+                                              (const char **) (formated_name ? &formated_name :
+                                                                               nullptr),
+                                              1,
+                                              create_sock,
+                                              sock);
        if (ret) {
-               PERROR("Failed to create \"%s\" socket",
-                               formated_name ?: "Unknown");
+               PERROR("Failed to create \"%s\" socket", formated_name ?: "Unknown");
                goto error;
        }
        DBG("Listening on %s socket %d", name, sock->fd);
@@ -748,7 +697,6 @@ struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
        ret = sock->ops->listen(sock, -1);
        if (ret < 0) {
                goto error;
-
        }
 
        free(formated_name);
@@ -759,17 +707,16 @@ error:
                lttcomm_destroy_sock(sock);
        }
        free(formated_name);
-       return NULL;
+       return nullptr;
 }
 
 /*
  * This thread manages the listening for new connections on the network
  */
-static
-void *thread_listener(void *data __attribute__((unused)))
+static void *thread_listener(void *data __attribute__((unused)))
 {
-       int i, ret, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int i, ret, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct lttcomm_sock *live_control_sock;
 
@@ -786,8 +733,7 @@ void *thread_listener(void *data __attribute__((unused)))
        }
 
        /* Pass 2 as size here for the thread quit pipe and control sockets. */
-       ret = create_named_thread_poll_set(&events, 2,
-                       "Live listener thread epoll");
+       ret = create_named_thread_poll_set(&events, 2, "Live listener thread epoll");
        if (ret < 0) {
                goto error_create_poll;
        }
@@ -804,12 +750,12 @@ void *thread_listener(void *data __attribute__((unused)))
                goto error_testpoint;
        }
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                DBG("Listener accepting live viewers connections");
 
-restart:
+       restart:
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
                health_poll_exit();
@@ -826,15 +772,15 @@ restart:
 
                DBG("Relay new viewer connection received");
                for (i = 0; i < nb_fd; i++) {
-                       health_code_update();
-
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
+
+                       health_code_update();
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_thread_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (relayd_is_thread_quit_pipe(pollfd)) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -851,15 +797,15 @@ restart:
                                struct lttcomm_sock *newsock;
 
                                newsock = accept_live_sock(live_control_sock,
-                                               "Live socket to client");
+                                                          "Live socket to client");
                                if (!newsock) {
                                        PERROR("accepting control sock");
                                        goto error;
                                }
                                DBG("Relay viewer connection accepted socket %d", newsock->fd);
 
-                               ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
-                                               sizeof(val));
+                               ret = setsockopt(
+                                       newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
                                if (ret < 0) {
                                        PERROR("setsockopt inet");
                                        lttcomm_destroy_sock(newsock);
@@ -871,13 +817,12 @@ restart:
                                        goto error;
                                }
                                /* Ownership assumed by the connection. */
-                               newsock = NULL;
+                               newsock = nullptr;
 
                                /* Enqueue request for the dispatcher thread. */
                                cds_wfcq_head_ptr_t head;
                                head.h = &viewer_conn_queue.head;
-                               cds_wfcq_enqueue(head, &viewer_conn_queue.tail,
-                                                &new_conn->qnode);
+                               cds_wfcq_enqueue(head, &viewer_conn_queue.tail, &new_conn->qnode);
 
                                /*
                                 * Wake the dispatch queue futex.
@@ -904,9 +849,8 @@ error_create_poll:
        if (live_control_sock->fd >= 0) {
                int sock_fd = live_control_sock->fd;
 
-               ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                               &sock_fd, 1, close_sock,
-                               live_control_sock);
+               ret = fd_tracker_close_unsuspendable_fd(
+                       the_fd_tracker, &sock_fd, 1, close_sock, live_control_sock);
                if (ret) {
                        PERROR("close");
                }
@@ -924,19 +868,18 @@ error_sock_control:
        if (lttng_relay_stop_threads()) {
                ERR("Error stopping threads");
        }
-       return NULL;
+       return nullptr;
 }
 
 /*
  * This thread manages the dispatching of the requests to worker threads
  */
-static
-void *thread_dispatcher(void *data __attribute__((unused)))
+static void *thread_dispatcher(void *data __attribute__((unused)))
 {
        int err = -1;
        ssize_t ret;
        struct cds_wfcq_node *node;
-       struct relay_connection *conn = NULL;
+       struct relay_connection *conn = nullptr;
 
        DBG("[thread] Live viewer relay dispatcher started");
 
@@ -964,15 +907,14 @@ void *thread_dispatcher(void *data __attribute__((unused)))
                        /* Dequeue commands */
                        node = cds_wfcq_dequeue_blocking(&viewer_conn_queue.head,
                                                         &viewer_conn_queue.tail);
-                       if (node == NULL) {
+                       if (node == nullptr) {
                                DBG("Woken up but nothing in the live-viewer "
-                                               "relay command queue");
+                                   "relay command queue");
                                /* Continue thread execution */
                                break;
                        }
                        conn = lttng::utils::container_of(node, &relay_connection::qnode);
-                       DBG("Dispatching viewer request waiting on sock %d",
-                                       conn->sock->fd);
+                       DBG("Dispatching viewer request waiting on sock %d", conn->sock->fd);
 
                        /*
                         * Inform worker thread of the new request. This
@@ -980,13 +922,15 @@ void *thread_dispatcher(void *data __attribute__((unused)))
                         * the data will be read at some point in time
                         * or wait to the end of the world :)
                         */
-                       ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn));
+                       ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn)); /* NOLINT sizeof
+                                                                                     used on a
+                                                                                     pointer. */
                        if (ret < 0) {
                                PERROR("write conn pipe");
                                connection_put(conn);
                                goto error;
                        }
-               } while (node != NULL);
+               } while (node != nullptr);
 
                /* Futex wait on queue. Blocking call on futex() */
                health_poll_entry();
@@ -1008,7 +952,7 @@ error_testpoint:
        if (lttng_relay_stop_threads()) {
                ERR("Error stopping threads");
        }
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1016,13 +960,12 @@ error_testpoint:
  *
  * Return 0 on success or else negative value.
  */
-static
-int viewer_connect(struct relay_connection *conn)
+static int viewer_connect(struct relay_connection *conn)
 {
        int ret;
        struct lttng_viewer_connect reply, msg;
 
-       conn->version_check_done = 1;
+       conn->version_check_done = true;
 
        health_code_update();
 
@@ -1040,7 +983,8 @@ int viewer_connect(struct relay_connection *conn)
        /* Major versions must be the same */
        if (reply.major != be32toh(msg.major)) {
                DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
-                               reply.major, be32toh(msg.major));
+                   reply.major,
+                   be32toh(msg.major));
                ret = -1;
                goto end;
        }
@@ -1101,14 +1045,13 @@ end:
  *
  * Return 0 on success or else a negative value.
  */
-static
-int viewer_list_sessions(struct relay_connection *conn)
+static int viewer_list_sessions(struct relay_connection *conn)
 {
        int ret = 0;
        struct lttng_viewer_list_sessions session_list;
        struct lttng_ht_iter iter;
        struct relay_session *session;
-       struct lttng_viewer_session *send_session_buf = NULL;
+       struct lttng_viewer_session *send_session_buf = nullptr;
        uint32_t buf_count = SESSION_BUF_DEFAULT_COUNT;
        uint32_t count = 0;
 
@@ -1117,61 +1060,65 @@ int viewer_list_sessions(struct relay_connection *conn)
                return -1;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
-                       session_n.node) {
-               struct lttng_viewer_session *send_session;
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               health_code_update();
+               cds_lfht_for_each_entry (sessions_ht->ht, &iter.iter, session, session_n.node) {
+                       struct lttng_viewer_session *send_session;
 
-               pthread_mutex_lock(&session->lock);
-               if (session->connection_closed) {
-                       /* Skip closed session */
-                       goto next_session;
-               }
+                       health_code_update();
 
-               if (count >= buf_count) {
-                       struct lttng_viewer_session *newbuf;
-                       uint32_t new_buf_count = buf_count << 1;
+                       pthread_mutex_lock(&session->lock);
+                       if (session->connection_closed) {
+                               /* Skip closed session */
+                               goto next_session;
+                       }
 
-                       newbuf = (lttng_viewer_session *) realloc(send_session_buf,
-                               new_buf_count * sizeof(*send_session_buf));
-                       if (!newbuf) {
+                       if (count >= buf_count) {
+                               struct lttng_viewer_session *newbuf;
+                               uint32_t new_buf_count = buf_count << 1;
+
+                               newbuf = (lttng_viewer_session *) realloc(
+                                       send_session_buf,
+                                       new_buf_count * sizeof(*send_session_buf));
+                               if (!newbuf) {
+                                       ret = -1;
+                                       goto break_loop;
+                               }
+                               send_session_buf = newbuf;
+                               buf_count = new_buf_count;
+                       }
+                       send_session = &send_session_buf[count];
+                       if (lttng_strncpy(send_session->session_name,
+                                         session->session_name,
+                                         sizeof(send_session->session_name))) {
                                ret = -1;
                                goto break_loop;
                        }
-                       send_session_buf = newbuf;
-                       buf_count = new_buf_count;
-               }
-               send_session = &send_session_buf[count];
-               if (lttng_strncpy(send_session->session_name,
-                               session->session_name,
-                               sizeof(send_session->session_name))) {
-                       ret = -1;
-                       goto break_loop;
-               }
-               if (lttng_strncpy(send_session->hostname, session->hostname,
-                               sizeof(send_session->hostname))) {
-                       ret = -1;
-                       goto break_loop;
-               }
-               send_session->id = htobe64(session->id);
-               send_session->live_timer = htobe32(session->live_timer);
-               if (session->viewer_attached) {
-                       send_session->clients = htobe32(1);
-               } else {
-                       send_session->clients = htobe32(0);
+                       if (lttng_strncpy(send_session->hostname,
+                                         session->hostname,
+                                         sizeof(send_session->hostname))) {
+                               ret = -1;
+                               goto break_loop;
+                       }
+                       send_session->id = htobe64(session->id);
+                       send_session->live_timer = htobe32(session->live_timer);
+                       if (session->viewer_attached) {
+                               send_session->clients = htobe32(1);
+                       } else {
+                               send_session->clients = htobe32(0);
+                       }
+                       send_session->streams = htobe32(session->stream_count);
+                       count++;
+               next_session:
+                       pthread_mutex_unlock(&session->lock);
+                       continue;
+               break_loop:
+                       pthread_mutex_unlock(&session->lock);
+                       break;
                }
-               send_session->streams = htobe32(session->stream_count);
-               count++;
-       next_session:
-               pthread_mutex_unlock(&session->lock);
-               continue;
-       break_loop:
-               pthread_mutex_unlock(&session->lock);
-               break;
        }
-       rcu_read_unlock();
+
        if (ret < 0) {
                goto end_free;
        }
@@ -1187,8 +1134,7 @@ int viewer_list_sessions(struct relay_connection *conn)
 
        health_code_update();
 
-       ret = send_response(conn->sock, send_session_buf,
-                       count * sizeof(*send_session_buf));
+       ret = send_response(conn->sock, send_session_buf, count * sizeof(*send_session_buf));
        if (ret < 0) {
                goto end_free;
        }
@@ -1203,14 +1149,13 @@ end_free:
 /*
  * Send the viewer the list of current streams.
  */
-static
-int viewer_get_new_streams(struct relay_connection *conn)
+static int viewer_get_new_streams(struct relay_connection *conn)
 {
        int ret, send_streams = 0;
        uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0, nb_total = 0;
        struct lttng_viewer_new_streams_request request;
        struct lttng_viewer_new_streams_response response;
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
        uint64_t session_id;
        bool closed = false;
 
@@ -1262,9 +1207,12 @@ int viewer_get_new_streams(struct relay_connection *conn)
                goto send_reply_unlock;
        }
        ret = make_viewer_streams(session,
-                       conn->viewer_session,
-                       LTTNG_VIEWER_SEEK_BEGINNING, &nb_total, &nb_unsent,
-                       &nb_created, &closed);
+                                 conn->viewer_session,
+                                 LTTNG_VIEWER_SEEK_BEGINNING,
+                                 &nb_total,
+                                 &nb_unsent,
+                                 &nb_created,
+                                 &closed);
        if (ret < 0) {
                /*
                 * This is caused by an internal error; propagate the negative
@@ -1273,6 +1221,8 @@ int viewer_get_new_streams(struct relay_connection *conn)
                response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
                goto send_reply_unlock;
        }
+
+       uatomic_set(&session->new_streams, 0);
        send_streams = 1;
        response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
 
@@ -1331,8 +1281,7 @@ error:
 /*
  * Send the viewer the list of current sessions.
  */
-static
-int viewer_attach_session(struct relay_connection *conn)
+static int viewer_attach_session(struct relay_connection *conn)
 {
        int send_streams = 0;
        ssize_t ret;
@@ -1340,7 +1289,7 @@ int viewer_attach_session(struct relay_connection *conn)
        enum lttng_viewer_seek seek_type;
        struct lttng_viewer_attach_session_request request;
        struct lttng_viewer_attach_session_response response;
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
        enum lttng_viewer_attach_return_code viewer_attach_status;
        bool closed = false;
        uint64_t session_id;
@@ -1364,7 +1313,7 @@ int viewer_attach_session(struct relay_connection *conn)
        if (!conn->viewer_session) {
                viewer_attach_status = LTTNG_VIEWER_ATTACH_NO_SESSION;
                DBG("Client trying to attach before creating a live viewer session, returning status=%s",
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                goto send_reply;
        }
 
@@ -1372,8 +1321,8 @@ int viewer_attach_session(struct relay_connection *conn)
        if (!session) {
                viewer_attach_status = LTTNG_VIEWER_ATTACH_UNK;
                DBG("Relay session %" PRIu64 " not found, returning status=%s",
-                               session_id,
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+                   session_id,
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                goto send_reply;
        }
        DBG("Attach relay session ID %" PRIu64 " received", session_id);
@@ -1382,18 +1331,17 @@ int viewer_attach_session(struct relay_connection *conn)
        if (session->live_timer == 0) {
                viewer_attach_status = LTTNG_VIEWER_ATTACH_NOT_LIVE;
                DBG("Relay session ID %" PRIu64 " is not a live session, returning status=%s",
-                               session_id,
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+                   session_id,
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                goto send_reply;
        }
 
        send_streams = 1;
-       viewer_attach_status = viewer_session_attach(conn->viewer_session,
-                       session);
+       viewer_attach_status = viewer_session_attach(conn->viewer_session, session);
        if (viewer_attach_status != LTTNG_VIEWER_ATTACH_OK) {
                DBG("Error attaching to relay session %" PRIu64 ", returning status=%s",
-                               session_id,
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+                   session_id,
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                goto send_reply;
        }
 
@@ -1404,9 +1352,9 @@ int viewer_attach_session(struct relay_connection *conn)
                seek_type = (lttng_viewer_seek) be32toh(request.seek);
                break;
        default:
-               ERR("Wrong seek parameter for relay session %" PRIu64
-                               ", returning status=%s", session_id,
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+               ERR("Wrong seek parameter for relay session %" PRIu64 ", returning status=%s",
+                   session_id,
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                viewer_attach_status = LTTNG_VIEWER_ATTACH_SEEK_ERR;
                send_streams = 0;
                goto send_reply;
@@ -1423,15 +1371,14 @@ int viewer_attach_session(struct relay_connection *conn)
                goto send_reply;
        }
 
-       ret = make_viewer_streams(session,
-                       conn->viewer_session, seek_type,
-                       &nb_streams, NULL, NULL, &closed);
+       ret = make_viewer_streams(
+               session, conn->viewer_session, seek_type, &nb_streams, nullptr, nullptr, &closed);
        if (ret < 0) {
                goto end_put_session;
        }
        pthread_mutex_unlock(&session->lock);
        session_put(session);
-       session = NULL;
+       session = nullptr;
 
        response.streams_count = htobe32(nb_streams);
        /*
@@ -1445,8 +1392,8 @@ int viewer_attach_session(struct relay_connection *conn)
                response.streams_count = 0;
                viewer_attach_status = LTTNG_VIEWER_ATTACH_UNK;
                ERR("Session %" PRIu64 " is closed, returning status=%s",
-                               session_id,
-                               lttng_viewer_attach_return_code_str(viewer_attach_status));
+                   session_id,
+                   lttng_viewer_attach_return_code_str(viewer_attach_status));
                goto send_reply;
        }
 
@@ -1495,8 +1442,7 @@ error:
  *
  * Called with rstream lock held.
  */
-static int try_open_index(struct relay_viewer_stream *vstream,
-               struct relay_stream *rstream)
+static int try_open_index(struct relay_viewer_stream *vstream, struct relay_stream *rstream)
 {
        int ret = 0;
        const uint32_t connection_major = rstream->trace->session->major;
@@ -1510,19 +1456,21 @@ static int try_open_index(struct relay_viewer_stream *vstream,
        /*
         * First time, we open the index file and at least one index is ready.
         */
-       if (rstream->index_received_seqcount == 0 ||
-                       !vstream->stream_file.trace_chunk) {
+       if (rstream->index_received_seqcount == 0 || !vstream->stream_file.trace_chunk) {
                ret = -ENOENT;
                goto end;
        }
 
        chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
-                       vstream->stream_file.trace_chunk, rstream->path_name,
-                       rstream->channel_name, rstream->tracefile_size,
-                       vstream->current_tracefile_id,
-                       lttng_to_index_major(connection_major, connection_minor),
-                       lttng_to_index_minor(connection_major, connection_minor),
-                       true, &vstream->index_file);
+               vstream->stream_file.trace_chunk,
+               rstream->path_name,
+               rstream->channel_name,
+               rstream->tracefile_size,
+               vstream->current_tracefile_id,
+               lttng_to_index_major(connection_major, connection_minor),
+               lttng_to_index_minor(connection_major, connection_minor),
+               true,
+               &vstream->index_file);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
                        ret = -ENOENT;
@@ -1547,37 +1495,37 @@ end:
  * Called with rstream lock held.
  */
 static int check_index_status(struct relay_viewer_stream *vstream,
-               struct relay_stream *rstream, struct ctf_trace *trace,
-               struct lttng_viewer_index *index)
+                             struct relay_stream *rstream,
+                             struct ctf_trace *trace,
+                             struct lttng_viewer_index *index)
 {
        int ret;
 
        DBG("Check index status: index_received_seqcount %" PRIu64 " "
-                               "index_sent_seqcount %" PRIu64 " "
-                               "for stream %" PRIu64,
-                               rstream->index_received_seqcount,
-                               vstream->index_sent_seqcount,
-                               vstream->stream->stream_handle);
-       if ((trace->session->connection_closed || rstream->closed)
-                       && rstream->index_received_seqcount
-                               == vstream->index_sent_seqcount) {
+           "index_sent_seqcount %" PRIu64 " "
+           "for stream %" PRIu64,
+           rstream->index_received_seqcount,
+           vstream->index_sent_seqcount,
+           vstream->stream->stream_handle);
+       if ((trace->session->connection_closed || rstream->closed) &&
+           rstream->index_received_seqcount == vstream->index_sent_seqcount) {
                /*
                 * Last index sent and session connection or relay
                 * stream are closed.
                 */
                index->status = LTTNG_VIEWER_INDEX_HUP;
                DBG("Check index status: Connection or stream are closed, stream %" PRIu64
-                       ",connection-closed=%d, relay-stream-closed=%d, returning status=%s",
-                       vstream->stream->stream_handle,
-                       trace->session->connection_closed, rstream->closed,
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) index->status));
+                   ",connection-closed=%d, relay-stream-closed=%d, returning status=%s",
+                   vstream->stream->stream_handle,
+                   trace->session->connection_closed,
+                   rstream->closed,
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) index->status));
                goto hup;
        } else if (rstream->beacon_ts_end != -1ULL &&
-                       (rstream->index_received_seqcount == 0 ||
-                       (vstream->index_sent_seqcount != 0 &&
-                       rstream->index_received_seqcount
-                               <= vstream->index_sent_seqcount))) {
+                  (rstream->index_received_seqcount == 0 ||
+                   (vstream->index_sent_seqcount != 0 &&
+                    rstream->index_received_seqcount <= vstream->index_sent_seqcount))) {
                /*
                 * We've received a synchronization beacon and the last index
                 * available has been sent, the index for now is inactive.
@@ -1597,15 +1545,14 @@ static int check_index_status(struct relay_viewer_stream *vstream,
                index->timestamp_end = htobe64(rstream->beacon_ts_end);
                index->stream_id = htobe64(rstream->ctf_stream_id);
                DBG("Check index status: inactive with beacon, for stream %" PRIu64
-                       ", returning status=%s",
-                       vstream->stream->stream_handle,
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) index->status));
+                   ", returning status=%s",
+                   vstream->stream->stream_handle,
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) index->status));
                goto index_ready;
        } else if (rstream->index_received_seqcount == 0 ||
-                       (vstream->index_sent_seqcount != 0 &&
-                       rstream->index_received_seqcount
-                               <= vstream->index_sent_seqcount)) {
+                  (vstream->index_sent_seqcount != 0 &&
+                   rstream->index_received_seqcount <= vstream->index_sent_seqcount)) {
                /*
                 * This checks whether received <= sent seqcount. In
                 * this case, we have not received a beacon. Therefore,
@@ -1619,32 +1566,29 @@ static int check_index_status(struct relay_viewer_stream *vstream,
                 */
                index->status = LTTNG_VIEWER_INDEX_RETRY;
                DBG("Check index status:"
-                       "did not received beacon for stream %" PRIu64
-                       ", returning status=%s",
-                       vstream->stream->stream_handle,
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) index->status));
+                   "did not received beacon for stream %" PRIu64 ", returning status=%s",
+                   vstream->stream->stream_handle,
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) index->status));
                goto index_ready;
        } else if (!tracefile_array_seq_in_file(rstream->tfa,
-                       vstream->current_tracefile_id,
-                       vstream->index_sent_seqcount)) {
+                                               vstream->current_tracefile_id,
+                                               vstream->index_sent_seqcount)) {
                /*
                 * The next index we want to send cannot be read either
                 * because we need to perform a rotation, or due to
                 * the producer having overwritten its trace file.
                 */
-               DBG("Viewer stream %" PRIu64 " rotation",
-                               vstream->stream->stream_handle);
+               DBG("Viewer stream %" PRIu64 " rotation", vstream->stream->stream_handle);
                ret = viewer_stream_rotate(vstream);
                if (ret == 1) {
                        /* EOF across entire stream. */
                        index->status = LTTNG_VIEWER_INDEX_HUP;
                        DBG("Check index status:"
-                               "reached end of file for stream %" PRIu64
-                               ", returning status=%s",
-                               vstream->stream->stream_handle,
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) index->status));
+                           "reached end of file for stream %" PRIu64 ", returning status=%s",
+                           vstream->stream->stream_handle,
+                           lttng_viewer_next_index_return_code_str(
+                                   (enum lttng_viewer_next_index_return_code) index->status));
                        goto hup;
                }
                /*
@@ -1662,24 +1606,21 @@ static int check_index_status(struct relay_viewer_stream *vstream,
                 * still unavailable.
                 */
                if (rstream->tracefile_count == 1 &&
-                               !tracefile_array_seq_in_file(
-                                       rstream->tfa,
-                                       vstream->current_tracefile_id,
-                                       vstream->index_sent_seqcount)) {
+                   !tracefile_array_seq_in_file(rstream->tfa,
+                                                vstream->current_tracefile_id,
+                                                vstream->index_sent_seqcount)) {
                        index->status = LTTNG_VIEWER_INDEX_RETRY;
                        DBG("Check index status:"
-                               "tracefile array sequence number %" PRIu64
-                               " not in file for stream %" PRIu64
-                               ", returning status=%s",
-                               vstream->index_sent_seqcount,
-                               vstream->stream->stream_handle,
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) index->status));
+                           "tracefile array sequence number %" PRIu64
+                           " not in file for stream %" PRIu64 ", returning status=%s",
+                           vstream->index_sent_seqcount,
+                           vstream->stream->stream_handle,
+                           lttng_viewer_next_index_return_code_str(
+                                   (enum lttng_viewer_next_index_return_code) index->status));
                        goto index_ready;
                }
-               LTTNG_ASSERT(tracefile_array_seq_in_file(rstream->tfa,
-                               vstream->current_tracefile_id,
-                               vstream->index_sent_seqcount));
+               LTTNG_ASSERT(tracefile_array_seq_in_file(
+                       rstream->tfa, vstream->current_tracefile_id, vstream->index_sent_seqcount));
        }
        /* ret == 0 means successful so we continue. */
        ret = 0;
@@ -1691,15 +1632,13 @@ index_ready:
        return 1;
 }
 
-static
-void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
-                struct lttng_trace_chunk *new_trace_chunk)
+static void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
+                                               struct lttng_trace_chunk *new_trace_chunk)
 {
        lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
 
        if (new_trace_chunk) {
-               const bool acquired_reference = lttng_trace_chunk_get(
-                               new_trace_chunk);
+               const bool acquired_reference = lttng_trace_chunk_get(new_trace_chunk);
 
                LTTNG_ASSERT(acquired_reference);
        }
@@ -1714,20 +1653,20 @@ void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
  *
  * Return 0 on success or else a negative value.
  */
-static
-int viewer_get_next_index(struct relay_connection *conn)
+static int viewer_get_next_index(struct relay_connection *conn)
 {
        int ret;
        struct lttng_viewer_get_next_index request_index;
        struct lttng_viewer_index viewer_index;
        struct ctf_packet_index packet_index;
-       struct relay_viewer_stream *vstream = NULL;
-       struct relay_stream *rstream = NULL;
-       struct ctf_trace *ctf_trace = NULL;
-       struct relay_viewer_stream *metadata_viewer_stream = NULL;
+       struct relay_viewer_stream *vstream = nullptr;
+       struct relay_stream *rstream = nullptr;
+       struct ctf_trace *ctf_trace = nullptr;
+       struct relay_viewer_stream *metadata_viewer_stream = nullptr;
        bool viewer_stream_and_session_in_same_chunk, viewer_stream_one_rotation_behind;
        uint64_t stream_file_chunk_id = -1ULL, viewer_session_chunk_id = -1ULL;
        enum lttng_trace_chunk_status status;
+       bool attached_sessions_have_new_streams = false;
 
        LTTNG_ASSERT(conn);
 
@@ -1743,10 +1682,10 @@ int viewer_get_next_index(struct relay_connection *conn)
        vstream = viewer_stream_get_by_id(be64toh(request_index.stream_id));
        if (!vstream) {
                viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
-               DBG("Client requested index of unknown stream id %" PRIu64", returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               DBG("Client requested index of unknown stream id %" PRIu64 ", returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
        }
 
@@ -1755,8 +1694,7 @@ int viewer_get_next_index(struct relay_connection *conn)
        ctf_trace = rstream->trace;
 
        /* metadata_viewer_stream may be NULL. */
-       metadata_viewer_stream =
-                       ctf_trace_get_viewer_metadata_stream(ctf_trace);
+       metadata_viewer_stream = ctf_trace_get_viewer_metadata_stream(ctf_trace);
 
        /*
         * Hold the session lock to protect against concurrent changes
@@ -1772,51 +1710,63 @@ int viewer_get_next_index(struct relay_connection *conn)
         */
        if (rstream->is_metadata) {
                viewer_index.status = LTTNG_VIEWER_INDEX_HUP;
-               DBG("Client requested index of a metadata stream id %" PRIu64", returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               DBG("Client requested index of a metadata stream id %" PRIu64
+                   ", returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               goto send_reply;
+       }
+
+       ret = check_new_streams(conn);
+       if (ret < 0) {
+               viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
+               ERR("Error checking for new streams in the attached sessions, returning status=%s",
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
+       } else if (ret == 1) {
+               attached_sessions_have_new_streams = true;
        }
 
        if (rstream->ongoing_rotation.is_set) {
                /* Rotation is ongoing, try again later. */
                viewer_index.status = LTTNG_VIEWER_INDEX_RETRY;
-               DBG("Client requested index for stream id %" PRIu64" while a stream rotation is ongoing, returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               DBG("Client requested index for stream id %" PRIu64
+                   " while a stream rotation is ongoing, returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
        }
 
        if (session_has_ongoing_rotation(rstream->trace->session)) {
                /* Rotation is ongoing, try again later. */
                viewer_index.status = LTTNG_VIEWER_INDEX_RETRY;
-               DBG("Client requested index for stream id %" PRIu64" while a session rotation is ongoing, returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               DBG("Client requested index for stream id %" PRIu64
+                   " while a session rotation is ongoing, returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
        }
 
        /*
         * Transition the viewer session into the newest trace chunk available.
         */
-       if (!lttng_trace_chunk_ids_equal(
-                       conn->viewer_session->current_trace_chunk,
-                       rstream->trace_chunk)) {
+       if (!lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
+                                        rstream->trace_chunk)) {
                DBG("Relay stream and viewer chunk ids differ");
 
-               ret = viewer_session_set_trace_chunk_copy(
-                               conn->viewer_session,
-                               rstream->trace_chunk);
+               ret = viewer_session_set_trace_chunk_copy(conn->viewer_session,
+                                                         rstream->trace_chunk);
                if (ret) {
                        viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
                        ERR("Error copying trace chunk for stream id %" PRIu64
-                               ", returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+                           ", returning status=%s",
+                           (uint64_t) be64toh(request_index.stream_id),
+                           lttng_viewer_next_index_return_code_str(
+                                   (enum lttng_viewer_next_index_return_code) viewer_index.status));
                        goto send_reply;
                }
        }
@@ -1833,53 +1783,49 @@ int viewer_get_next_index(struct relay_connection *conn)
         * after a session's destruction.
         */
        if (vstream->stream_file.trace_chunk) {
-               status = lttng_trace_chunk_get_id(
-                               vstream->stream_file.trace_chunk,
-                               &stream_file_chunk_id);
+               status = lttng_trace_chunk_get_id(vstream->stream_file.trace_chunk,
+                                                 &stream_file_chunk_id);
                LTTNG_ASSERT(status == LTTNG_TRACE_CHUNK_STATUS_OK);
        }
        if (conn->viewer_session->current_trace_chunk) {
-               status = lttng_trace_chunk_get_id(
-                               conn->viewer_session->current_trace_chunk,
-                               &viewer_session_chunk_id);
+               status = lttng_trace_chunk_get_id(conn->viewer_session->current_trace_chunk,
+                                                 &viewer_session_chunk_id);
                LTTNG_ASSERT(status == LTTNG_TRACE_CHUNK_STATUS_OK);
        }
 
        viewer_stream_and_session_in_same_chunk = lttng_trace_chunk_ids_equal(
-                       conn->viewer_session->current_trace_chunk,
-                       vstream->stream_file.trace_chunk);
+               conn->viewer_session->current_trace_chunk, vstream->stream_file.trace_chunk);
        viewer_stream_one_rotation_behind = rstream->completed_rotation_count ==
-                       vstream->last_seen_rotation_count + 1;
+               vstream->last_seen_rotation_count + 1;
 
        if (viewer_stream_and_session_in_same_chunk) {
                DBG("Transition to latest chunk check (%s -> %s): Same chunk, no need to rotate",
-                               vstream->stream_file.trace_chunk ?
-                                               std::to_string(stream_file_chunk_id).c_str() :
-                                               "None",
-                               conn->viewer_session->current_trace_chunk ?
-                                               std::to_string(viewer_session_chunk_id).c_str() :
-                                               "None");
+                   vstream->stream_file.trace_chunk ?
+                           std::to_string(stream_file_chunk_id).c_str() :
+                           "None",
+                   conn->viewer_session->current_trace_chunk ?
+                           std::to_string(viewer_session_chunk_id).c_str() :
+                           "None");
        } else if (viewer_stream_one_rotation_behind && !rstream->trace_chunk) {
                DBG("Transition to latest chunk check (%s -> %s): One chunk behind relay stream which is being destroyed, no need to rotate",
-                               vstream->stream_file.trace_chunk ?
-                                               std::to_string(stream_file_chunk_id).c_str() :
-                                               "None",
-                               conn->viewer_session->current_trace_chunk ?
-                                               std::to_string(viewer_session_chunk_id).c_str() :
-                                               "None");
+                   vstream->stream_file.trace_chunk ?
+                           std::to_string(stream_file_chunk_id).c_str() :
+                           "None",
+                   conn->viewer_session->current_trace_chunk ?
+                           std::to_string(viewer_session_chunk_id).c_str() :
+                           "None");
        } else {
                DBG("Transition to latest chunk check (%s -> %s): Viewer stream chunk ID and viewer session chunk ID differ, rotating viewer stream",
-                               vstream->stream_file.trace_chunk ?
-                                               std::to_string(stream_file_chunk_id).c_str() :
-                                               "None",
-                               conn->viewer_session->current_trace_chunk ?
-                                               std::to_string(viewer_session_chunk_id).c_str() :
-                                               "None");
+                   vstream->stream_file.trace_chunk ?
+                           std::to_string(stream_file_chunk_id).c_str() :
+                           "None",
+                   conn->viewer_session->current_trace_chunk ?
+                           std::to_string(viewer_session_chunk_id).c_str() :
+                           "None");
 
                viewer_stream_rotate_to_trace_chunk(vstream,
-                               conn->viewer_session->current_trace_chunk);
-               vstream->last_seen_rotation_count =
-                               rstream->completed_rotation_count;
+                                                   conn->viewer_session->current_trace_chunk);
+               vstream->last_seen_rotation_count = rstream->completed_rotation_count;
        }
 
        ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
@@ -1892,37 +1838,36 @@ int viewer_get_next_index(struct relay_connection *conn)
                 */
                goto send_reply;
        }
+
        /* At this point, ret is 0 thus we will be able to read the index. */
        LTTNG_ASSERT(!ret);
 
        /* Try to open an index if one is needed for that stream. */
        ret = try_open_index(vstream, rstream);
        if (ret == -ENOENT) {
-              if (rstream->closed) {
+               if (rstream->closed) {
                        viewer_index.status = LTTNG_VIEWER_INDEX_HUP;
                        DBG("Cannot open index for stream id %" PRIu64
-                               "stream is closed, returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+                           "stream is closed, returning status=%s",
+                           (uint64_t) be64toh(request_index.stream_id),
+                           lttng_viewer_next_index_return_code_str(
+                                   (enum lttng_viewer_next_index_return_code) viewer_index.status));
                        goto send_reply;
-              } else {
+               } else {
                        viewer_index.status = LTTNG_VIEWER_INDEX_RETRY;
-                       DBG("Cannot open index for stream id %" PRIu64
-                               ", returning status=%s",
-                               (uint64_t) be64toh(request_index.stream_id),
-                               lttng_viewer_next_index_return_code_str(
-                                       (enum lttng_viewer_next_index_return_code) viewer_index.status));
+                       DBG("Cannot open index for stream id %" PRIu64 ", returning status=%s",
+                           (uint64_t) be64toh(request_index.stream_id),
+                           lttng_viewer_next_index_return_code_str(
+                                   (enum lttng_viewer_next_index_return_code) viewer_index.status));
                        goto send_reply;
-              }
+               }
        }
        if (ret < 0) {
                viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
-               ERR("Error opening index for stream id %" PRIu64
-                       ", returning status=%s",
-                       (uint64_t) be64toh(request_index.stream_id),
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               ERR("Error opening index for stream id %" PRIu64 ", returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
        }
 
@@ -1938,9 +1883,12 @@ int viewer_get_next_index(struct relay_connection *conn)
                struct fs_handle *fs_handle;
 
                ret = utils_stream_file_path(rstream->path_name,
-                               rstream->channel_name, rstream->tracefile_size,
-                               vstream->current_tracefile_id, NULL, file_path,
-                               sizeof(file_path));
+                                            rstream->channel_name,
+                                            rstream->tracefile_size,
+                                            vstream->current_tracefile_id,
+                                            nullptr,
+                                            file_path,
+                                            sizeof(file_path));
                if (ret < 0) {
                        goto error_put;
                }
@@ -1951,17 +1899,16 @@ int viewer_get_next_index(struct relay_connection *conn)
                 * per-pid buffers) and a clear command has been performed.
                 */
                status = lttng_trace_chunk_open_fs_handle(
-                               vstream->stream_file.trace_chunk,
-                               file_path, O_RDONLY, 0, &fs_handle, true);
+                       vstream->stream_file.trace_chunk, file_path, O_RDONLY, 0, &fs_handle, true);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
-                       if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE &&
-                                       rstream->closed) {
+                       if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE && rstream->closed) {
                                viewer_index.status = LTTNG_VIEWER_INDEX_HUP;
                                DBG("Cannot find trace chunk file and stream is closed for stream id %" PRIu64
-                                       ", returning status=%s",
-                                       (uint64_t) be64toh(request_index.stream_id),
-                                       lttng_viewer_next_index_return_code_str(
-                                               (enum lttng_viewer_next_index_return_code) viewer_index.status));
+                                   ", returning status=%s",
+                                   (uint64_t) be64toh(request_index.stream_id),
+                                   lttng_viewer_next_index_return_code_str(
+                                           (enum lttng_viewer_next_index_return_code)
+                                                   viewer_index.status));
                                goto send_reply;
                        }
                        PERROR("Failed to open trace file for viewer stream");
@@ -1970,35 +1917,20 @@ int viewer_get_next_index(struct relay_connection *conn)
                vstream->stream_file.handle = fs_handle;
        }
 
-       ret = check_new_streams(conn);
-       if (ret < 0) {
-               viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
-               ERR("Error checking for new streams before sending new index to stream id %" PRIu64
-                       ", returning status=%s",
-                       (uint64_t) be64toh(request_index.stream_id),
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) viewer_index.status));
-               goto send_reply;
-       } else if (ret == 1) {
-               viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
-       }
-
        ret = lttng_index_file_read(vstream->index_file, &packet_index);
        if (ret) {
                viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
-               ERR("Relay error reading index file for stream id %" PRIu64
-                       ", returning status=%s",
-                       (uint64_t) be64toh(request_index.stream_id),
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               ERR("Relay error reading index file for stream id %" PRIu64 ", returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                goto send_reply;
        } else {
                viewer_index.status = LTTNG_VIEWER_INDEX_OK;
-               DBG("Read index file for stream id %" PRIu64
-                       ", returning status=%s",
-                       (uint64_t) be64toh(request_index.stream_id),
-                       lttng_viewer_next_index_return_code_str(
-                               (enum lttng_viewer_next_index_return_code) viewer_index.status));
+               DBG("Read index file for stream id %" PRIu64 ", returning status=%s",
+                   (uint64_t) be64toh(request_index.stream_id),
+                   lttng_viewer_next_index_return_code_str(
+                           (enum lttng_viewer_next_index_return_code) viewer_index.status));
                vstream->index_sent_seqcount++;
        }
 
@@ -2006,8 +1938,8 @@ int viewer_get_next_index(struct relay_connection *conn)
         * Indexes are stored in big endian, no need to switch before sending.
         */
        DBG("Sending viewer index for stream %" PRIu64 " offset %" PRIu64,
-               rstream->stream_handle,
-               (uint64_t) be64toh(packet_index.offset));
+           rstream->stream_handle,
+           (uint64_t) be64toh(packet_index.offset));
        viewer_index.offset = packet_index.offset;
        viewer_index.packet_size = packet_index.packet_size;
        viewer_index.content_size = packet_index.content_size;
@@ -2024,18 +1956,21 @@ send_reply:
 
        if (metadata_viewer_stream) {
                pthread_mutex_lock(&metadata_viewer_stream->stream->lock);
-               DBG("get next index metadata check: recv %" PRIu64
-                               " sent %" PRIu64,
-                       metadata_viewer_stream->stream->metadata_received,
-                       metadata_viewer_stream->metadata_sent);
+               DBG("get next index metadata check: recv %" PRIu64 " sent %" PRIu64,
+                   metadata_viewer_stream->stream->metadata_received,
+                   metadata_viewer_stream->metadata_sent);
                if (!metadata_viewer_stream->stream->metadata_received ||
-                               metadata_viewer_stream->stream->metadata_received >
-                                       metadata_viewer_stream->metadata_sent) {
+                   metadata_viewer_stream->stream->metadata_received >
+                           metadata_viewer_stream->metadata_sent) {
                        viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
                }
                pthread_mutex_unlock(&metadata_viewer_stream->stream->lock);
        }
 
+       if (attached_sessions_have_new_streams) {
+               viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
+       }
+
        viewer_index.flags = htobe32(viewer_index.flags);
        viewer_index.status = htobe32(viewer_index.status);
        health_code_update();
@@ -2048,8 +1983,8 @@ send_reply:
 
        if (vstream) {
                DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
-                               vstream->index_sent_seqcount,
-                               vstream->stream->stream_handle);
+                   vstream->index_sent_seqcount,
+                   vstream->stream->stream_handle);
        }
 end:
        if (metadata_viewer_stream) {
@@ -2075,15 +2010,14 @@ error_put:
  *
  * Return 0 on success or else a negative value.
  */
-static
-int viewer_get_packet(struct relay_connection *conn)
+static int viewer_get_packet(struct relay_connection *conn)
 {
        int ret;
        off_t lseek_ret;
-       char *reply = NULL;
+       char *reply = nullptr;
        struct lttng_viewer_get_packet get_packet_info;
        struct lttng_viewer_trace_packet reply_header;
-       struct relay_viewer_stream *vstream = NULL;
+       struct relay_viewer_stream *vstream = nullptr;
        uint32_t reply_size = sizeof(reply_header);
        uint32_t packet_data_len = 0;
        ssize_t read_len;
@@ -2092,8 +2026,7 @@ int viewer_get_packet(struct relay_connection *conn)
 
        health_code_update();
 
-       ret = recv_request(conn->sock, &get_packet_info,
-                       sizeof(get_packet_info));
+       ret = recv_request(conn->sock, &get_packet_info, sizeof(get_packet_info));
        if (ret < 0) {
                goto end;
        }
@@ -2106,9 +2039,9 @@ int viewer_get_packet(struct relay_connection *conn)
        vstream = viewer_stream_get_by_id(stream_id);
        if (!vstream) {
                get_packet_status = LTTNG_VIEWER_GET_PACKET_ERR;
-               DBG("Client requested packet of unknown stream id %" PRIu64
-                       ", returning status=%s", stream_id,
-                       lttng_viewer_get_packet_return_code_str(get_packet_status));
+               DBG("Client requested packet of unknown stream id %" PRIu64 ", returning status=%s",
+                   stream_id,
+                   lttng_viewer_get_packet_return_code_str(get_packet_status));
                goto send_reply_nolock;
        } else {
                packet_data_len = be32toh(get_packet_info.len);
@@ -2119,29 +2052,31 @@ int viewer_get_packet(struct relay_connection *conn)
        if (!reply) {
                get_packet_status = LTTNG_VIEWER_GET_PACKET_ERR;
                PERROR("Falled to allocate reply, returning status=%s",
-                       lttng_viewer_get_packet_return_code_str(get_packet_status));
+                      lttng_viewer_get_packet_return_code_str(get_packet_status));
                goto error;
        }
 
        pthread_mutex_lock(&vstream->stream->lock);
-       lseek_ret = fs_handle_seek(vstream->stream_file.handle,
-                       be64toh(get_packet_info.offset), SEEK_SET);
+       lseek_ret = fs_handle_seek(
+               vstream->stream_file.handle, be64toh(get_packet_info.offset), SEEK_SET);
        if (lseek_ret < 0) {
                get_packet_status = LTTNG_VIEWER_GET_PACKET_ERR;
                PERROR("Failed to seek file system handle of viewer stream %" PRIu64
-                      " to offset %" PRIu64", returning status=%s", stream_id,
-                       (uint64_t) be64toh(get_packet_info.offset),
-                       lttng_viewer_get_packet_return_code_str(get_packet_status));
+                      " to offset %" PRIu64 ", returning status=%s",
+                      stream_id,
+                      (uint64_t) be64toh(get_packet_info.offset),
+                      lttng_viewer_get_packet_return_code_str(get_packet_status));
                goto error;
        }
-       read_len = fs_handle_read(vstream->stream_file.handle,
-                       reply + sizeof(reply_header), packet_data_len);
+       read_len = fs_handle_read(
+               vstream->stream_file.handle, reply + sizeof(reply_header), packet_data_len);
        if (read_len < packet_data_len) {
                get_packet_status = LTTNG_VIEWER_GET_PACKET_ERR;
                PERROR("Failed to read from file system handle of viewer stream id %" PRIu64
-                      ", offset: %" PRIu64 ", returning status=%s", stream_id,
+                      ", offset: %" PRIu64 ", returning status=%s",
+                      stream_id,
                       (uint64_t) be64toh(get_packet_info.offset),
-                       lttng_viewer_get_packet_return_code_str(get_packet_status));
+                      lttng_viewer_get_packet_return_code_str(get_packet_status));
                goto error;
        }
 
@@ -2167,8 +2102,7 @@ send_reply_nolock:
                ret = send_response(conn->sock, reply, reply_size);
        } else {
                /* No reply to send. */
-               ret = send_response(conn->sock, &reply_header,
-                               reply_size);
+               ret = send_response(conn->sock, &reply_header, reply_size);
        }
 
        health_code_update();
@@ -2193,17 +2127,17 @@ end:
  *
  * Return 0 on success else a negative value.
  */
-static
-int viewer_get_metadata(struct relay_connection *conn)
+static int viewer_get_metadata(struct relay_connection *conn)
 {
        int ret = 0;
        int fd = -1;
        ssize_t read_len;
        uint64_t len = 0;
-       char *data = NULL;
+       char *data = nullptr;
        struct lttng_viewer_get_metadata request;
        struct lttng_viewer_metadata_packet reply;
-       struct relay_viewer_stream *vstream = NULL;
+       struct relay_viewer_stream *vstream = nullptr;
+       bool dispose_of_stream = false;
 
        LTTNG_ASSERT(conn);
 
@@ -2228,10 +2162,13 @@ int viewer_get_metadata(struct relay_connection *conn)
                 * find it.
                 */
                DBG("Client requested metadata of unknown stream id %" PRIu64,
-                               (uint64_t) be64toh(request.stream_id));
+                   (uint64_t) be64toh(request.stream_id));
                reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
                goto send_reply;
        }
+
+       pthread_mutex_lock(&vstream->stream->trace->session->lock);
+       pthread_mutex_lock(&vstream->stream->trace->lock);
        pthread_mutex_lock(&vstream->stream->lock);
        if (!vstream->stream->is_metadata) {
                ERR("Invalid metadata stream");
@@ -2240,11 +2177,7 @@ int viewer_get_metadata(struct relay_connection *conn)
 
        if (vstream->metadata_sent >= vstream->stream->metadata_received) {
                /*
-                * The live viewers expect to receive a NO_NEW_METADATA
-                * status before a stream disappears, otherwise they abort the
-                * entire live connection when receiving an error status.
-                *
-                * Clear feature resets the metadata_sent to 0 until the
+                * Clear feature resets the metadata_received to 0 until the
                 * same metadata is received again.
                 */
                reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
@@ -2252,33 +2185,18 @@ int viewer_get_metadata(struct relay_connection *conn)
                 * The live viewer considers a closed 0 byte metadata stream as
                 * an error.
                 */
-               if (vstream->metadata_sent > 0) {
-                       if (vstream->stream->closed && vstream->stream->no_new_metadata_notified) {
-                               /*
-                                * Release ownership for the viewer metadata
-                                * stream. Note that this reference is the
-                                * viewer's reference. The vstream still exists
-                                * until the end of the function as
-                                * viewer_stream_get_by_id() took a reference.
-                                */
-                               viewer_stream_put(vstream);
-                       }
-
-                       vstream->stream->no_new_metadata_notified = true;
-               }
+               dispose_of_stream = vstream->metadata_sent > 0 && vstream->stream->closed;
                goto send_reply;
        }
 
        if (vstream->stream->trace_chunk &&
-                       !lttng_trace_chunk_ids_equal(
-                               conn->viewer_session->current_trace_chunk,
-                               vstream->stream->trace_chunk)) {
+           !lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
+                                        vstream->stream->trace_chunk)) {
                /* A rotation has occurred on the relay stream. */
                DBG("Metadata relay stream and viewer chunk ids differ");
 
-               ret = viewer_session_set_trace_chunk_copy(
-                               conn->viewer_session,
-                               vstream->stream->trace_chunk);
+               ret = viewer_session_set_trace_chunk_copy(conn->viewer_session,
+                                                         vstream->stream->trace_chunk);
                if (ret) {
                        reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
                        goto send_reply;
@@ -2286,30 +2204,42 @@ int viewer_get_metadata(struct relay_connection *conn)
        }
 
        if (conn->viewer_session->current_trace_chunk &&
-                       !lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
-                                       vstream->stream_file.trace_chunk)) {
+           !lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
+                                        vstream->stream_file.trace_chunk)) {
                bool acquired_reference;
 
                DBG("Viewer session and viewer stream chunk differ: "
-                               "vsession chunk %p vstream chunk %p",
-                               conn->viewer_session->current_trace_chunk,
-                               vstream->stream_file.trace_chunk);
+                   "vsession chunk %p vstream chunk %p",
+                   conn->viewer_session->current_trace_chunk,
+                   vstream->stream_file.trace_chunk);
                lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
-               acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
+               acquired_reference =
+                       lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
                LTTNG_ASSERT(acquired_reference);
-               vstream->stream_file.trace_chunk =
-                       conn->viewer_session->current_trace_chunk;
+               vstream->stream_file.trace_chunk = conn->viewer_session->current_trace_chunk;
                viewer_stream_close_files(vstream);
        }
 
        len = vstream->stream->metadata_received - vstream->metadata_sent;
 
        if (!vstream->stream_file.trace_chunk) {
+               if (vstream->stream->trace->session->connection_closed) {
+                       /*
+                        * If the connection is closed, there is no way for the metadata stream
+                        * to ever transition back to an active chunk. As such, signal to the viewer
+                        * that there is no new metadata available.
+                        *
+                        * The stream can be disposed-of. On the next execution of this command,
+                        * the relay daemon will reply with an error status since the stream can't
+                        * be found.
+                        */
+                       dispose_of_stream = true;
+               }
+
                reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
                len = 0;
                goto send_reply;
-       } else if (vstream->stream_file.trace_chunk &&
-                       !vstream->stream_file.handle && len > 0) {
+       } else if (vstream->stream_file.trace_chunk && !vstream->stream_file.handle && len > 0) {
                /*
                 * Either this is the first time the metadata file is read, or a
                 * rotation of the corresponding relay stream has occurred.
@@ -2320,9 +2250,12 @@ int viewer_get_metadata(struct relay_connection *conn)
                struct relay_stream *rstream = vstream->stream;
 
                ret = utils_stream_file_path(rstream->path_name,
-                               rstream->channel_name, rstream->tracefile_size,
-                               vstream->current_tracefile_id, NULL, file_path,
-                               sizeof(file_path));
+                                            rstream->channel_name,
+                                            rstream->tracefile_size,
+                                            vstream->current_tracefile_id,
+                                            nullptr,
+                                            file_path,
+                                            sizeof(file_path));
                if (ret < 0) {
                        goto error;
                }
@@ -2333,8 +2266,7 @@ int viewer_get_metadata(struct relay_connection *conn)
                 * per-pid buffers) and a clear command has been performed.
                 */
                status = lttng_trace_chunk_open_fs_handle(
-                               vstream->stream_file.trace_chunk,
-                               file_path, O_RDONLY, 0, &fs_handle, true);
+                       vstream->stream_file.trace_chunk, file_path, O_RDONLY, 0, &fs_handle, true);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
                                reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
@@ -2365,12 +2297,12 @@ int viewer_get_metadata(struct relay_connection *conn)
                         * safe to assume that
                         * `metadata_received` > `metadata_sent`.
                         */
-                       const off_t seek_ret = fs_handle_seek(fs_handle,
-                                       vstream->metadata_sent, SEEK_SET);
+                       const off_t seek_ret =
+                               fs_handle_seek(fs_handle, vstream->metadata_sent, SEEK_SET);
 
                        if (seek_ret < 0) {
                                PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64,
-                                               vstream->metadata_sent);
+                                      vstream->metadata_sent);
                                reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
                                goto send_reply;
                        }
@@ -2407,12 +2339,12 @@ int viewer_get_metadata(struct relay_connection *conn)
                         * attempt to parse an incomplete (incoherent) metadata
                         * stream, which would result in an error.
                         */
-                       const off_t seek_ret = fs_handle_seek(
-                                       vstream->stream_file.handle, -read_len,
-                                       SEEK_CUR);
+                       const off_t seek_ret =
+                               fs_handle_seek(vstream->stream_file.handle, -read_len, SEEK_CUR);
 
                        DBG("Failed to read metadata: requested = %" PRIu64 ", got = %zd",
-                                       len, read_len);
+                           len,
+                           read_len);
                        read_len = 0;
                        len = 0;
                        if (seek_ret < 0) {
@@ -2434,6 +2366,8 @@ send_reply:
        health_code_update();
        if (vstream) {
                pthread_mutex_unlock(&vstream->stream->lock);
+               pthread_mutex_unlock(&vstream->stream->trace->lock);
+               pthread_mutex_unlock(&vstream->stream->trace->session->lock);
        }
        ret = send_response(conn->sock, &reply, sizeof(reply));
        if (ret < 0) {
@@ -2448,8 +2382,9 @@ send_reply:
                }
        }
 
-       DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
-                       (uint64_t) be64toh(request.stream_id));
+       DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64,
+           len,
+           (uint64_t) be64toh(request.stream_id));
 
        DBG("Metadata sent");
 
@@ -2458,7 +2393,22 @@ end_free:
 end:
        if (vstream) {
                viewer_stream_put(vstream);
+               if (dispose_of_stream) {
+                       /*
+                        * Trigger the destruction of the viewer stream
+                        * by releasing its global reference.
+                        *
+                        * The live viewers expect to receive a NO_NEW_METADATA
+                        * status before a stream disappears, otherwise they abort the
+                        * entire live connection when receiving an error status.
+                        *
+                        * On the next query for this stream, an error will be reported to the
+                        * client.
+                        */
+                       viewer_stream_put(vstream);
+               }
        }
+
        return ret;
 }
 
@@ -2467,8 +2417,7 @@ end:
  *
  * Return 0 on success or else a negative value.
  */
-static
-int viewer_create_session(struct relay_connection *conn)
+static int viewer_create_session(struct relay_connection *conn)
 {
        int ret;
        struct lttng_viewer_create_session_response resp;
@@ -2500,13 +2449,12 @@ end:
  *
  * Return 0 on success or else a negative value.
  */
-static
-int viewer_detach_session(struct relay_connection *conn)
+static int viewer_detach_session(struct relay_connection *conn)
 {
        int ret;
        struct lttng_viewer_detach_session_response response;
        struct lttng_viewer_detach_session_request request;
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
        uint64_t viewer_session_to_close;
 
        LTTNG_ASSERT(conn);
@@ -2533,8 +2481,7 @@ int viewer_detach_session(struct relay_connection *conn)
 
        session = session_get_by_id(be64toh(request.session_id));
        if (!session) {
-               DBG("Relay session %" PRIu64 " not found",
-                               (uint64_t) be64toh(request.session_id));
+               DBG("Relay session %" PRIu64 " not found", (uint64_t) be64toh(request.session_id));
                response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
                goto send_reply;
        }
@@ -2569,8 +2516,7 @@ end:
 /*
  * live_relay_unknown_command: send -1 if received unknown command
  */
-static
-void live_relay_unknown_command(struct relay_connection *conn)
+static void live_relay_unknown_command(struct relay_connection *conn)
 {
        struct lttcomm_relayd_generic_reply reply;
 
@@ -2582,13 +2528,10 @@ void live_relay_unknown_command(struct relay_connection *conn)
 /*
  * Process the commands received on the control socket
  */
-static
-int process_control(struct lttng_viewer_cmd *recv_hdr,
-               struct relay_connection *conn)
+static int process_control(struct lttng_viewer_cmd *recv_hdr, struct relay_connection *conn)
 {
        int ret = 0;
-       lttng_viewer_command cmd =
-                       (lttng_viewer_command) be32toh(recv_hdr->cmd);
+       lttng_viewer_command cmd = (lttng_viewer_command) be32toh(recv_hdr->cmd);
 
        /*
         * Make sure we've done the version check before any command other then
@@ -2596,13 +2539,15 @@ int process_control(struct lttng_viewer_cmd *recv_hdr,
         */
        if (cmd != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
                ERR("Viewer on connection %d requested %s command before version check",
-                       conn->sock->fd, lttng_viewer_command_str(cmd));
+                   conn->sock->fd,
+                   lttng_viewer_command_str(cmd));
                ret = -1;
                goto end;
        }
 
        DBG("Processing %s viewer command from connection %d",
-                       lttng_viewer_command_str(cmd), conn->sock->fd);
+           lttng_viewer_command_str(cmd),
+           conn->sock->fd);
 
        switch (cmd) {
        case LTTNG_VIEWER_CONNECT:
@@ -2633,8 +2578,7 @@ int process_control(struct lttng_viewer_cmd *recv_hdr,
                ret = viewer_detach_session(conn);
                break;
        default:
-               ERR("Received unknown viewer command (%u)",
-                               be32toh(recv_hdr->cmd));
+               ERR("Received unknown viewer command (%u)", be32toh(recv_hdr->cmd));
                live_relay_unknown_command(conn);
                ret = -1;
                goto end;
@@ -2644,15 +2588,14 @@ end:
        return ret;
 }
 
-static
-void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
+static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
 {
        int ret;
 
        (void) lttng_poll_del(events, pollfd);
 
-       ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
-                       fd_tracker_util_close_fd, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(
+               the_fd_tracker, &pollfd, 1, fd_tracker_util_close_fd, nullptr);
        if (ret < 0) {
                ERR("Closing pollfd %d", pollfd);
        }
@@ -2661,8 +2604,7 @@ void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
 /*
  * This thread does the actual work
  */
-static
-void *thread_worker(void *data __attribute__((unused)))
+static void *thread_worker(void *data __attribute__((unused)))
 {
        int ret, err = -1;
        uint32_t nb_fd;
@@ -2688,8 +2630,7 @@ void *thread_worker(void *data __attribute__((unused)))
                goto viewer_connections_ht_error;
        }
 
-       ret = create_named_thread_poll_set(&events, 2,
-                       "Live viewer worker thread epoll");
+       ret = create_named_thread_poll_set(&events, 2, "Live viewer worker thread epoll");
        if (ret < 0) {
                goto error_poll_create;
        }
@@ -2700,7 +2641,7 @@ void *thread_worker(void *data __attribute__((unused)))
        }
 
 restart:
-       while (1) {
+       while (true) {
                int i;
 
                health_code_update();
@@ -2729,14 +2670,14 @@ restart:
                 */
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       uint32_t revents = LTTNG_POLL_GETEV(&events, i);
-                       int pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_thread_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (relayd_is_thread_quit_pipe(pollfd)) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -2747,13 +2688,14 @@ restart:
                                        struct relay_connection *conn;
 
                                        ret = lttng_read(live_conn_pipe[0],
-                                                       &conn, sizeof(conn));
+                                                        &conn,
+                                                        sizeof(conn)); /* NOLINT sizeof used on a
+                                                                          pointer. */
                                        if (ret < 0) {
                                                goto error;
                                        }
-                                       ret = lttng_poll_add(&events,
-                                                       conn->sock->fd,
-                                                       LPOLLIN | LPOLLRDHUP);
+                                       ret = lttng_poll_add(
+                                               &events, conn->sock->fd, LPOLLIN | LPOLLRDHUP);
                                        if (ret) {
                                                ERR("Failed to add new live connection file descriptor to poll set");
                                                goto error;
@@ -2764,7 +2706,9 @@ restart:
                                        ERR("Relay live pipe error");
                                        goto error;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                        } else {
@@ -2777,8 +2721,8 @@ restart:
                                }
 
                                if (revents & LPOLLIN) {
-                                       ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
-                                                       sizeof(recv_hdr), 0);
+                                       ret = conn->sock->ops->recvmsg(
+                                               conn->sock, &recv_hdr, sizeof(recv_hdr), 0);
                                        if (ret <= 0) {
                                                /* Connection closed. */
                                                cleanup_connection_pollfd(&events, pollfd);
@@ -2792,7 +2736,8 @@ restart:
                                                        cleanup_connection_pollfd(&events, pollfd);
                                                        /* Put "create" ownership reference. */
                                                        connection_put(conn);
-                                                       DBG("Viewer connection closed with %d", pollfd);
+                                                       DBG("Viewer connection closed with %d",
+                                                           pollfd);
                                                }
                                        }
                                } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
@@ -2800,7 +2745,9 @@ restart:
                                        /* Put "create" ownership reference. */
                                        connection_put(conn);
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        connection_put(conn);
                                        goto error;
                                }
@@ -2815,14 +2762,15 @@ error:
        (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
 
        /* Cleanup remaining connection object. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
-                       destroy_conn,
-                       sock_n.node) {
-               health_code_update();
-               connection_put(destroy_conn);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       viewer_connections_ht->ht, &iter.iter, destroy_conn, sock_n.node) {
+                       health_code_update();
+                       connection_put(destroy_conn);
+               }
        }
-       rcu_read_unlock();
 error_poll_create:
        lttng_ht_destroy(viewer_connections_ht);
 viewer_connections_ht_error:
@@ -2842,20 +2790,20 @@ error_testpoint:
                ERR("Error stopping threads");
        }
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Create the relay command pipe to wake thread_manage_apps.
  * Closed in cleanup().
  */
-static int create_conn_pipe(void)
+static int create_conn_pipe()
 {
-       return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
-                       "Live connection pipe", live_conn_pipe);
+       return fd_tracker_util_pipe_open_cloexec(
+               the_fd_tracker, "Live connection pipe", live_conn_pipe);
 }
 
-int relayd_live_join(void)
+int relayd_live_join()
 {
        int ret, retval = 0;
        void *status;
@@ -2928,8 +2876,10 @@ int relayd_live_create(struct lttng_uri *uri)
        }
 
        /* Setup the dispatcher thread */
-       ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
-                       thread_dispatcher, (void *) NULL);
+       ret = pthread_create(&live_dispatcher_thread,
+                            default_pthread_attr(),
+                            thread_dispatcher,
+                            (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create viewer dispatcher");
@@ -2938,8 +2888,7 @@ int relayd_live_create(struct lttng_uri *uri)
        }
 
        /* Setup the worker thread */
-       ret = pthread_create(&live_worker_thread, default_pthread_attr(),
-                       thread_worker, NULL);
+       ret = pthread_create(&live_worker_thread, default_pthread_attr(), thread_worker, nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create viewer worker");
@@ -2948,8 +2897,8 @@ int relayd_live_create(struct lttng_uri *uri)
        }
 
        /* Setup the listener thread */
-       ret = pthread_create(&live_listener_thread, default_pthread_attr(),
-                       thread_listener, (void *) NULL);
+       ret = pthread_create(
+               &live_listener_thread, default_pthread_attr(), thread_listener, (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create viewer listener");
index d1866d3f5690a2d07456a4294b75f20bc910090f..53f67d30ef019061b2a4e00cf537c3a2434489c6 100644 (file)
  *
  */
 
-#include <common/uri.hpp>
-
 #include "lttng-relayd.hpp"
 
+#include <common/uri.hpp>
+
 int relayd_live_create(struct lttng_uri *live_uri);
-int relayd_live_stop(void);
-int relayd_live_join(void);
+int relayd_live_stop();
+int relayd_live_join();
 
 #endif /* LTTNG_RELAYD_LIVE_H */
index a92ace77d34c19289e0fadb676f0900b4a96862a..bf86575f5589a8071e05f84d35437962382303d9 100644 (file)
  *
  */
 
+#include <common/compat/poll.hpp>
+#include <common/fd-tracker/fd-tracker.hpp>
+#include <common/hashtable/hashtable.hpp>
+
 #include <limits.h>
 #include <urcu.h>
 #include <urcu/wfcqueue.h>
 
-#include <common/hashtable/hashtable.hpp>
-#include <common/fd-tracker/fd-tracker.hpp>
-
 struct sessiond_trace_chunk_registry;
 
 /*
@@ -46,14 +47,19 @@ extern struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
 
 extern char *opt_output_path;
 extern const char *tracing_group_name;
-extern const char * const config_section_name;
+extern const char *const config_section_name;
 extern enum relay_group_output_by opt_group_output_by;
 
-extern int thread_quit_pipe[2];
-
 extern struct fd_tracker *the_fd_tracker;
 
-void lttng_relay_notify_ready(void);
-int lttng_relay_stop_threads(void);
+void lttng_relay_notify_ready();
+int lttng_relay_stop_threads();
+
+int relayd_init_thread_quit_pipe();
+int relayd_notify_thread_quit_pipe();
+void relayd_close_thread_quit_pipe();
+bool relayd_is_thread_quit_pipe(const int fd);
+
+int create_named_thread_poll_set(struct lttng_poll_event *events, int size, const char *name);
 
 #endif /* LTTNG_RELAYD_H */
index 6fdb7fa609f5336429e6a21748b3b97d5edb7a43..393fb6f282103bb8702865375fc8491b2e371fab 100644 (file)
  *
  */
 
-#include <limits.h>
 #include <common/macros.hpp>
 
-#define LTTNG_VIEWER_PATH_MAX          4096
-#define LTTNG_VIEWER_NAME_MAX          255
-#define LTTNG_VIEWER_HOST_NAME_MAX     64
+#include <limits.h>
+
+#define LTTNG_VIEWER_PATH_MAX     4096
+#define LTTNG_VIEWER_NAME_MAX     255
+#define LTTNG_VIEWER_HOST_NAME_MAX 64
 
 /* Flags in reply to get_next_index and get_packet. */
 enum {
        /* New metadata is required to read this packet. */
-       LTTNG_VIEWER_FLAG_NEW_METADATA  = (1 << 0),
+       LTTNG_VIEWER_FLAG_NEW_METADATA = (1 << 0),
        /* New stream got added to the trace. */
-       LTTNG_VIEWER_FLAG_NEW_STREAM    = (1 << 1),
+       LTTNG_VIEWER_FLAG_NEW_STREAM = (1 << 1),
 };
 
 enum lttng_viewer_command {
-       LTTNG_VIEWER_CONNECT            = 1,
-       LTTNG_VIEWER_LIST_SESSIONS      = 2,
-       LTTNG_VIEWER_ATTACH_SESSION     = 3,
-       LTTNG_VIEWER_GET_NEXT_INDEX     = 4,
-       LTTNG_VIEWER_GET_PACKET         = 5,
-       LTTNG_VIEWER_GET_METADATA       = 6,
-       LTTNG_VIEWER_GET_NEW_STREAMS    = 7,
-       LTTNG_VIEWER_CREATE_SESSION     = 8,
-       LTTNG_VIEWER_DETACH_SESSION     = 9,
+       LTTNG_VIEWER_CONNECT = 1,
+       LTTNG_VIEWER_LIST_SESSIONS = 2,
+       LTTNG_VIEWER_ATTACH_SESSION = 3,
+       LTTNG_VIEWER_GET_NEXT_INDEX = 4,
+       LTTNG_VIEWER_GET_PACKET = 5,
+       LTTNG_VIEWER_GET_METADATA = 6,
+       LTTNG_VIEWER_GET_NEW_STREAMS = 7,
+       LTTNG_VIEWER_CREATE_SESSION = 8,
+       LTTNG_VIEWER_DETACH_SESSION = 9,
 };
 
 enum lttng_viewer_attach_return_code {
-       LTTNG_VIEWER_ATTACH_OK          = 1, /* The attach command succeeded. */
-       LTTNG_VIEWER_ATTACH_ALREADY     = 2, /* A viewer is already attached. */
-       LTTNG_VIEWER_ATTACH_UNK         = 3, /* The session ID is unknown. */
-       LTTNG_VIEWER_ATTACH_NOT_LIVE    = 4, /* The session is not live. */
-       LTTNG_VIEWER_ATTACH_SEEK_ERR    = 5, /* Seek error. */
-       LTTNG_VIEWER_ATTACH_NO_SESSION  = 6, /* No viewer session created. */
+       LTTNG_VIEWER_ATTACH_OK = 1, /* The attach command succeeded. */
+       LTTNG_VIEWER_ATTACH_ALREADY = 2, /* A viewer is already attached. */
+       LTTNG_VIEWER_ATTACH_UNK = 3, /* The session ID is unknown. */
+       LTTNG_VIEWER_ATTACH_NOT_LIVE = 4, /* The session is not live. */
+       LTTNG_VIEWER_ATTACH_SEEK_ERR = 5, /* Seek error. */
+       LTTNG_VIEWER_ATTACH_NO_SESSION = 6, /* No viewer session created. */
 };
 
 enum lttng_viewer_next_index_return_code {
-       LTTNG_VIEWER_INDEX_OK           = 1, /* Index is available. */
-       LTTNG_VIEWER_INDEX_RETRY        = 2, /* Index not yet available. */
-       LTTNG_VIEWER_INDEX_HUP          = 3, /* Index closed (trace destroyed). */
-       LTTNG_VIEWER_INDEX_ERR          = 4, /* Unknow error. */
-       LTTNG_VIEWER_INDEX_INACTIVE     = 5, /* Inactive stream beacon. */
-       LTTNG_VIEWER_INDEX_EOF          = 6, /* End of index file. */
+       LTTNG_VIEWER_INDEX_OK = 1, /* Index is available. */
+       LTTNG_VIEWER_INDEX_RETRY = 2, /* Index not yet available. */
+       LTTNG_VIEWER_INDEX_HUP = 3, /* Index closed (trace destroyed). */
+       LTTNG_VIEWER_INDEX_ERR = 4, /* Unknow error. */
+       LTTNG_VIEWER_INDEX_INACTIVE = 5, /* Inactive stream beacon. */
+       LTTNG_VIEWER_INDEX_EOF = 6, /* End of index file. */
 };
 
 enum lttng_viewer_get_packet_return_code {
-       LTTNG_VIEWER_GET_PACKET_OK      = 1,
-       LTTNG_VIEWER_GET_PACKET_RETRY   = 2,
-       LTTNG_VIEWER_GET_PACKET_ERR     = 3,
-       LTTNG_VIEWER_GET_PACKET_EOF     = 4,
+       LTTNG_VIEWER_GET_PACKET_OK = 1,
+       LTTNG_VIEWER_GET_PACKET_RETRY = 2,
+       LTTNG_VIEWER_GET_PACKET_ERR = 3,
+       LTTNG_VIEWER_GET_PACKET_EOF = 4,
 };
 
 enum lttng_viewer_get_metadata_return_code {
-       LTTNG_VIEWER_METADATA_OK        = 1,
-       LTTNG_VIEWER_NO_NEW_METADATA    = 2,
-       LTTNG_VIEWER_METADATA_ERR       = 3,
+       LTTNG_VIEWER_METADATA_OK = 1,
+       LTTNG_VIEWER_NO_NEW_METADATA = 2,
+       LTTNG_VIEWER_METADATA_ERR = 3,
 };
 
 enum lttng_viewer_connection_type {
-       LTTNG_VIEWER_CLIENT_COMMAND             = 1,
-       LTTNG_VIEWER_CLIENT_NOTIFICATION        = 2,
+       LTTNG_VIEWER_CLIENT_COMMAND = 1,
+       LTTNG_VIEWER_CLIENT_NOTIFICATION = 2,
 };
 
 enum lttng_viewer_seek {
        /* Receive the trace packets from the beginning. */
-       LTTNG_VIEWER_SEEK_BEGINNING     = 1,
+       LTTNG_VIEWER_SEEK_BEGINNING = 1,
        /* Receive the trace packets from now. */
-       LTTNG_VIEWER_SEEK_LAST          = 2,
+       LTTNG_VIEWER_SEEK_LAST = 2,
 };
 
 enum lttng_viewer_new_streams_return_code {
-       LTTNG_VIEWER_NEW_STREAMS_OK           = 1, /* If new streams are being sent. */
-       LTTNG_VIEWER_NEW_STREAMS_NO_NEW       = 2, /* If no new streams are available. */
-       LTTNG_VIEWER_NEW_STREAMS_ERR          = 3, /* Error. */
-       LTTNG_VIEWER_NEW_STREAMS_HUP          = 4, /* Session closed. */
+       LTTNG_VIEWER_NEW_STREAMS_OK = 1, /* If new streams are being sent. */
+       LTTNG_VIEWER_NEW_STREAMS_NO_NEW = 2, /* If no new streams are available. */
+       LTTNG_VIEWER_NEW_STREAMS_ERR = 3, /* Error. */
+       LTTNG_VIEWER_NEW_STREAMS_HUP = 4, /* Session closed. */
 };
 
 enum lttng_viewer_create_session_return_code {
-       LTTNG_VIEWER_CREATE_SESSION_OK          = 1,
-       LTTNG_VIEWER_CREATE_SESSION_ERR         = 2,
+       LTTNG_VIEWER_CREATE_SESSION_OK = 1,
+       LTTNG_VIEWER_CREATE_SESSION_ERR = 2,
 };
 
 enum lttng_viewer_detach_session_return_code {
-       LTTNG_VIEWER_DETACH_SESSION_OK          = 1,
-       LTTNG_VIEWER_DETACH_SESSION_UNK         = 2,
-       LTTNG_VIEWER_DETACH_SESSION_ERR         = 3,
+       LTTNG_VIEWER_DETACH_SESSION_OK = 1,
+       LTTNG_VIEWER_DETACH_SESSION_UNK = 2,
+       LTTNG_VIEWER_DETACH_SESSION_ERR = 3,
 };
 
 struct lttng_viewer_session {
@@ -116,9 +117,9 @@ struct lttng_viewer_stream {
 } LTTNG_PACKED;
 
 struct lttng_viewer_cmd {
-       uint64_t data_size;     /* data size following this header */
-       uint32_t cmd;           /* enum lttcomm_relayd_command */
-       uint32_t cmd_version;   /* command version */
+       uint64_t data_size; /* data size following this header */
+       uint32_t cmd; /* enum lttcomm_relayd_command */
+       uint32_t cmd_version; /* command version */
 } LTTNG_PACKED;
 
 /*
@@ -129,7 +130,7 @@ struct lttng_viewer_connect {
        uint64_t viewer_session_id;
        uint32_t major;
        uint32_t minor;
-       uint32_t type;          /* enum lttng_viewer_connection_type */
+       uint32_t type; /* enum lttng_viewer_connection_type */
 } LTTNG_PACKED;
 
 /*
@@ -137,7 +138,7 @@ struct lttng_viewer_connect {
  */
 struct lttng_viewer_list_sessions {
        uint32_t sessions_count;
-       char session_list[];    /* struct lttng_viewer_session */
+       char session_list[]; /* struct lttng_viewer_session */
 } LTTNG_PACKED;
 
 /*
@@ -145,8 +146,8 @@ struct lttng_viewer_list_sessions {
  */
 struct lttng_viewer_attach_session_request {
        uint64_t session_id;
-       uint64_t offset;        /* unused for now */
-       uint32_t seek;          /* enum lttng_viewer_seek */
+       uint64_t offset; /* unused for now */
+       uint32_t seek; /* enum lttng_viewer_seek */
 } LTTNG_PACKED;
 
 struct lttng_viewer_attach_session_response {
@@ -162,7 +163,7 @@ struct lttng_viewer_attach_session_response {
  */
 struct lttng_viewer_get_next_index {
        uint64_t stream_id;
-} __attribute__ ((__packed__));
+} __attribute__((__packed__));
 
 struct lttng_viewer_index {
        uint64_t offset;
@@ -172,9 +173,9 @@ struct lttng_viewer_index {
        uint64_t timestamp_end;
        uint64_t events_discarded;
        uint64_t stream_id;
-       uint32_t status;        /* enum lttng_viewer_next_index_return_code */
-       uint32_t flags;         /* LTTNG_VIEWER_FLAG_* */
-} __attribute__ ((__packed__));
+       uint32_t status; /* enum lttng_viewer_next_index_return_code */
+       uint32_t flags; /* LTTNG_VIEWER_FLAG_* */
+} __attribute__((__packed__));
 
 /*
  * LTTNG_VIEWER_GET_PACKET payload.
@@ -186,9 +187,9 @@ struct lttng_viewer_get_packet {
 } LTTNG_PACKED;
 
 struct lttng_viewer_trace_packet {
-       uint32_t status;        /* enum lttng_viewer_get_packet_return_code */
+       uint32_t status; /* enum lttng_viewer_get_packet_return_code */
        uint32_t len;
-       uint32_t flags;         /* LTTNG_VIEWER_FLAG_* */
+       uint32_t flags; /* LTTNG_VIEWER_FLAG_* */
        char data[];
 } LTTNG_PACKED;
 
@@ -201,7 +202,7 @@ struct lttng_viewer_get_metadata {
 
 struct lttng_viewer_metadata_packet {
        uint64_t len;
-       uint32_t status;        /* enum lttng_viewer_get_metadata_return_code */
+       uint32_t status; /* enum lttng_viewer_get_metadata_return_code */
        char data[];
 } LTTNG_PACKED;
 
index 318af66f787526f049faef36f9c4cf1a78425c71..ea0ed2119b5237684b35695038658fa2ed4ea5b6 100644 (file)
@@ -9,55 +9,6 @@
  */
 
 #define _LGPL_SOURCE
-#include <getopt.h>
-#include <grp.h>
-#include <limits.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/resource.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/resource.h>
-#include <inttypes.h>
-#include <urcu/futex.h>
-#include <urcu/uatomic.h>
-#include <urcu/rculist.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <strings.h>
-#include <ctype.h>
-#include <algorithm>
-
-#include <lttng/lttng.h>
-#include <common/common.hpp>
-#include <common/compat/poll.hpp>
-#include <common/compat/socket.hpp>
-#include <common/compat/endian.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/defaults.hpp>
-#include <common/daemonize.hpp>
-#include <common/futex.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/sessiond-comm/inet.hpp>
-#include <common/sessiond-comm/relayd.hpp>
-#include <common/uri.hpp>
-#include <common/utils.hpp>
-#include <common/path.hpp>
-#include <common/align.hpp>
-#include <common/ini-config/ini-config.hpp>
-#include <common/dynamic-buffer.hpp>
-#include <common/buffer-view.hpp>
-#include <common/string-utils/format.hpp>
-#include <common/fd-tracker/fd-tracker.hpp>
-#include <common/fd-tracker/utils.hpp>
-
 #include "backward-compatibility-group-by.hpp"
 #include "cmd.hpp"
 #include "connection.hpp"
 #include "version.hpp"
 #include "viewer-stream.hpp"
 
+#include <common/align.hpp>
+#include <common/buffer-view.hpp>
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/compat/getenv.hpp>
+#include <common/compat/poll.hpp>
+#include <common/compat/socket.hpp>
+#include <common/daemonize.hpp>
+#include <common/defaults.hpp>
+#include <common/dynamic-buffer.hpp>
+#include <common/fd-tracker/fd-tracker.hpp>
+#include <common/fd-tracker/utils.hpp>
+#include <common/futex.hpp>
+#include <common/ini-config/ini-config.hpp>
+#include <common/path.hpp>
+#include <common/sessiond-comm/inet.hpp>
+#include <common/sessiond-comm/relayd.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/string-utils/format.hpp>
+#include <common/urcu.hpp>
+#include <common/uri.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
+#include <algorithm>
+#include <ctype.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <grp.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/mman.h>
+#include <sys/mount.h>
+#include <sys/resource.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <urcu/futex.h>
+#include <urcu/rculist.h>
+#include <urcu/uatomic.h>
+
 static const char *help_msg =
 #ifdef LTTNG_EMBED_HELP
 #include <lttng-relayd.8.h>
 #else
-NULL
+       nullptr
 #endif
-;
+       ;
 
 enum relay_connection_status {
        RELAY_CONNECTION_STATUS_OK,
@@ -98,22 +99,22 @@ static int opt_daemon, opt_background, opt_print_version, opt_allow_clear = 1;
 enum relay_group_output_by opt_group_output_by = RELAYD_GROUP_OUTPUT_BY_UNKNOWN;
 
 /* Argument variables */
-int lttng_opt_quiet;    /* not static in error.h */
-int lttng_opt_verbose;  /* not static in error.h */
-int lttng_opt_mi;       /* not static in error.h */
+int lttng_opt_quiet; /* not static in error.h */
+int lttng_opt_verbose; /* not static in error.h */
+int lttng_opt_mi; /* not static in error.h */
 
 /*
  * We need to wait for listener and live listener threads, as well as
  * health check thread, before being ready to signal readiness.
  */
-#define NR_LTTNG_RELAY_READY   3
+#define NR_LTTNG_RELAY_READY 3
 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
 
 /* Size of receive buffer. */
-#define RECV_DATA_BUFFER_SIZE          65536
+#define RECV_DATA_BUFFER_SIZE 65536
 
-static int recv_child_signal;  /* Set to 1 when a SIGUSR1 signal is received. */
-static pid_t child_ppid;       /* Internal parent PID use with daemonize. */
+static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
+static pid_t child_ppid; /* Internal parent PID use with daemonize. */
 
 static struct lttng_uri *control_uri;
 static struct lttng_uri *data_uri;
@@ -124,13 +125,7 @@ const char *progname;
 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
 static int tracing_group_name_override;
 
-const char * const config_section_name = "relayd";
-
-/*
- * Quit pipe for all threads. This permits a single cancellation point
- * for all threads when receiving an event on the pipe.
- */
-int thread_quit_pipe[2] = { -1, -1 };
+const char *const config_section_name = "relayd";
 
 /*
  * This pipe is used to inform the worker thread that a command is queued and
@@ -182,36 +177,107 @@ struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
 struct fd_tracker *the_fd_tracker;
 
 static struct option long_options[] = {
-       { "control-port", 1, 0, 'C', },
-       { "data-port", 1, 0, 'D', },
-       { "live-port", 1, 0, 'L', },
-       { "daemonize", 0, 0, 'd', },
-       { "background", 0, 0, 'b', },
-       { "group", 1, 0, 'g', },
-       { "fd-pool-size", 1, 0, '\0', },
-       { "help", 0, 0, 'h', },
-       { "output", 1, 0, 'o', },
-       { "verbose", 0, 0, 'v', },
-       { "config", 1, 0, 'f' },
-       { "version", 0, 0, 'V' },
-       { "working-directory", 1, 0, 'w', },
-       { "group-output-by-session", 0, 0, 's', },
-       { "group-output-by-host", 0, 0, 'p', },
-       { "disallow-clear", 0, 0, 'x' },
-       { NULL, 0, 0, 0, },
+       {
+               "control-port",
+               1,
+               nullptr,
+               'C',
+       },
+       {
+               "data-port",
+               1,
+               nullptr,
+               'D',
+       },
+       {
+               "live-port",
+               1,
+               nullptr,
+               'L',
+       },
+       {
+               "daemonize",
+               0,
+               nullptr,
+               'd',
+       },
+       {
+               "background",
+               0,
+               nullptr,
+               'b',
+       },
+       {
+               "group",
+               1,
+               nullptr,
+               'g',
+       },
+       {
+               "fd-pool-size",
+               1,
+               nullptr,
+               '\0',
+       },
+       {
+               "help",
+               0,
+               nullptr,
+               'h',
+       },
+       {
+               "output",
+               1,
+               nullptr,
+               'o',
+       },
+       {
+               "verbose",
+               0,
+               nullptr,
+               'v',
+       },
+       { "config", 1, nullptr, 'f' },
+       { "version", 0, nullptr, 'V' },
+       {
+               "working-directory",
+               1,
+               nullptr,
+               'w',
+       },
+       {
+               "group-output-by-session",
+               0,
+               nullptr,
+               's',
+       },
+       {
+               "group-output-by-host",
+               0,
+               nullptr,
+               'p',
+       },
+       { "disallow-clear", 0, nullptr, 'x' },
+       {
+               nullptr,
+               0,
+               nullptr,
+               0,
+       },
 };
 
 static const char *config_ignore_options[] = { "help", "config", "version" };
 
-static void print_version(void) {
+static void print_version()
+{
        fprintf(stdout, "%s\n", VERSION);
 }
 
-static void relayd_config_log(void)
+static void relayd_config_log()
 {
        DBG("LTTng-relayd " VERSION " - " VERSION_NAME "%s%s",
-                       GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
-                       EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
+           GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
+           EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
        if (EXTRA_VERSION_DESCRIPTION[0] != '\0') {
                DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION "\n");
        }
@@ -236,14 +302,15 @@ static int set_option(int opt, const char *arg, const char *optname)
                        unsigned long v;
 
                        errno = 0;
-                       v = strtoul(arg, NULL, 0);
+                       v = strtoul(arg, nullptr, 0);
                        if (errno != 0 || !isdigit((unsigned char) arg[0])) {
                                ERR("Wrong value in --fd-pool-size parameter: %s", arg);
                                ret = -1;
                                goto end;
                        }
                        if (v >= UINT_MAX) {
-                               ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg);
+                               ERR("File descriptor cap overflow in --fd-pool-size parameter: %s",
+                                   arg);
                                ret = -1;
                                goto end;
                        }
@@ -258,7 +325,7 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'C':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-C, --control-port");
+                            "-C, --control-port");
                } else {
                        ret = uri_parse(arg, &control_uri);
                        if (ret < 0) {
@@ -273,7 +340,7 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'D':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-D, -data-port");
+                            "-D, -data-port");
                } else {
                        ret = uri_parse(arg, &data_uri);
                        if (ret < 0) {
@@ -288,7 +355,7 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'L':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-L, -live-port");
+                            "-L, -live-port");
                } else {
                        ret = uri_parse(arg, &live_uri);
                        if (ret < 0) {
@@ -309,10 +376,10 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'g':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-g, --group");
+                            "-g, --group");
                } else {
                        tracing_group_name = strdup(arg);
-                       if (tracing_group_name == NULL) {
+                       if (tracing_group_name == nullptr) {
                                ret = -errno;
                                PERROR("strdup");
                                goto end;
@@ -333,7 +400,7 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'o':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-o, --output");
+                            "-o, --output");
                } else {
                        ret = asprintf(&opt_output_path, "%s", arg);
                        if (ret < 0) {
@@ -346,7 +413,7 @@ static int set_option(int opt, const char *arg, const char *optname)
        case 'w':
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-w, --working-directory");
+                            "-w, --working-directory");
                } else {
                        ret = asprintf(&opt_working_directory, "%s", arg);
                        if (ret < 0) {
@@ -406,7 +473,7 @@ end:
  * return value conventions.
  */
 static int config_entry_handler(const struct config_entry *entry,
-               void *unused __attribute__((unused)))
+                               void *unused __attribute__((unused)))
 {
        int ret = 0, i;
 
@@ -424,7 +491,7 @@ static int config_entry_handler(const struct config_entry *entry,
 
        for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
                /* Ignore if entry name is not fully matched. */
-               if (strcmp(entry->name, long_options[i].name)) {
+               if (strcmp(entry->name, long_options[i].name) != 0) {
                        continue;
                }
 
@@ -438,7 +505,8 @@ static int config_entry_handler(const struct config_entry *entry,
                        if (ret <= 0) {
                                if (ret) {
                                        WARN("Invalid configuration value \"%s\" for option %s",
-                                                       entry->value, entry->name);
+                                            entry->value,
+                                            entry->name);
                                }
                                /* False, skip boolean config option. */
                                goto end;
@@ -449,31 +517,29 @@ static int config_entry_handler(const struct config_entry *entry,
                goto end;
        }
 
-       WARN("Unrecognized option \"%s\" in daemon configuration file.",
-                       entry->name);
+       WARN("Unrecognized option \"%s\" in daemon configuration file.", entry->name);
 
 end:
        return ret;
 }
 
-static int parse_env_options(void)
+static int parse_env_options()
 {
        int ret = 0;
-       char *value = NULL;
+       char *value = nullptr;
 
        value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV);
        if (value) {
                opt_working_directory = strdup(value);
                if (!opt_working_directory) {
-                       ERR("Failed to allocate working directory string (\"%s\")",
-                                       value);
+                       ERR("Failed to allocate working directory string (\"%s\")", value);
                        ret = -1;
                }
        }
        return ret;
 }
 
-static int set_fd_pool_size(void)
+static int set_fd_pool_size()
 {
        int ret = 0;
        struct rlimit rlimit;
@@ -486,38 +552,41 @@ static int set_fd_pool_size(void)
        }
 
        DBG("File descriptor count limits are %" PRIu64 " (soft) and %" PRIu64 " (hard)",
-                       (uint64_t) rlimit.rlim_cur,
-                       (uint64_t) rlimit.rlim_max);
+           (uint64_t) rlimit.rlim_cur,
+           (uint64_t) rlimit.rlim_max);
        if (lttng_opt_fd_pool_size == -1) {
                /* Use default value (soft limit - reserve). */
                if (rlimit.rlim_cur < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
-                       ERR("The process' file number limit is too low (%" PRIu64 "). The process' file number limit must be set to at least %i.",
-                                       (uint64_t) rlimit.rlim_cur, DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
+                       ERR("The process' file number limit is too low (%" PRIu64
+                           "). The process' file number limit must be set to at least %i.",
+                           (uint64_t) rlimit.rlim_cur,
+                           DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
                        ret = -1;
                        goto end;
                }
-               lttng_opt_fd_pool_size = rlimit.rlim_cur -
-                               DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
+               lttng_opt_fd_pool_size = rlimit.rlim_cur - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
                goto end;
        }
 
        if (lttng_opt_fd_pool_size < DEFAULT_RELAYD_MIN_FD_POOL_SIZE) {
                ERR("File descriptor pool size must be set to at least %d",
-                               DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
+                   DEFAULT_RELAYD_MIN_FD_POOL_SIZE);
                ret = -1;
                goto end;
        }
 
        if (lttng_opt_fd_pool_size > rlimit.rlim_cur) {
-               ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64 ").",
-                               lttng_opt_fd_pool_size, (uint64_t) rlimit.rlim_cur);
+               ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
+                   ").",
+                   lttng_opt_fd_pool_size,
+                   (uint64_t) rlimit.rlim_cur);
                ret = -1;
                goto end;
        }
 
        DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
-                       lttng_opt_fd_pool_size,
-                       lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
+           lttng_opt_fd_pool_size,
+           lttng_opt_fd_pool_size - DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE);
        lttng_opt_fd_pool_size -= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE;
 end:
        return ret;
@@ -528,10 +597,10 @@ static int set_options(int argc, char **argv)
        int c, ret = 0, option_index = 0, retval = 0;
        int orig_optopt = optopt, orig_optind = optind;
        char *default_address, *optstring;
-       char *config_path = NULL;
+       char *config_path = nullptr;
 
        optstring = utils_generate_optstring(long_options,
-                       sizeof(long_options) / sizeof(struct option));
+                                            sizeof(long_options) / sizeof(struct option));
        if (!optstring) {
                retval = -ENOMEM;
                goto exit;
@@ -539,8 +608,7 @@ static int set_options(int argc, char **argv)
 
        /* Check for the --config option */
 
-       while ((c = getopt_long(argc, argv, optstring, long_options,
-                                       &option_index)) != -1) {
+       while ((c = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) {
                if (c == '?') {
                        retval = -EINVAL;
                        goto exit;
@@ -550,7 +618,7 @@ static int set_options(int argc, char **argv)
 
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-f, --config");
+                            "-f, --config");
                } else {
                        free(config_path);
                        config_path = utils_expand_path(optarg);
@@ -560,8 +628,8 @@ static int set_options(int argc, char **argv)
                }
        }
 
-       ret = config_get_section_entries(config_path, config_section_name,
-                       config_entry_handler, NULL);
+       ret = config_get_section_entries(
+               config_path, config_section_name, config_entry_handler, nullptr);
        if (ret) {
                if (ret > 0) {
                        ERR("Invalid configuration option at line %i", ret);
@@ -573,7 +641,7 @@ static int set_options(int argc, char **argv)
        /* Reset getopt's global state */
        optopt = orig_optopt;
        optind = orig_optind;
-       while (1) {
+       while (true) {
                c = getopt_long(argc, argv, optstring, long_options, &option_index);
                if (c == -1) {
                        break;
@@ -587,10 +655,10 @@ static int set_options(int argc, char **argv)
        }
 
        /* assign default values */
-       if (control_uri == NULL) {
+       if (control_uri == nullptr) {
                ret = asprintf(&default_address,
-                       "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
-                       DEFAULT_NETWORK_CONTROL_PORT);
+                              "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
+                              DEFAULT_NETWORK_CONTROL_PORT);
                if (ret < 0) {
                        PERROR("asprintf default data address");
                        retval = -1;
@@ -605,10 +673,10 @@ static int set_options(int argc, char **argv)
                        goto exit;
                }
        }
-       if (data_uri == NULL) {
+       if (data_uri == nullptr) {
                ret = asprintf(&default_address,
-                       "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
-                       DEFAULT_NETWORK_DATA_PORT);
+                              "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
+                              DEFAULT_NETWORK_DATA_PORT);
                if (ret < 0) {
                        PERROR("asprintf default data address");
                        retval = -1;
@@ -623,10 +691,10 @@ static int set_options(int argc, char **argv)
                        goto exit;
                }
        }
-       if (live_uri == NULL) {
+       if (live_uri == nullptr) {
                ret = asprintf(&default_address,
-                       "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
-                       DEFAULT_NETWORK_VIEWER_PORT);
+                              "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
+                              DEFAULT_NETWORK_VIEWER_PORT);
                if (ret < 0) {
                        PERROR("asprintf default viewer control address");
                        retval = -1;
@@ -656,7 +724,8 @@ static int set_options(int argc, char **argv)
                if (value) {
                        ret = config_parse_value(value);
                        if (ret < 0) {
-                               ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
+                               ERR("Invalid value for %s specified",
+                                   DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV);
                                retval = -1;
                                goto exit;
                        }
@@ -670,20 +739,19 @@ exit:
        return retval;
 }
 
-static void print_global_objects(void)
+static void print_global_objects()
 {
        print_viewer_streams();
        print_relay_streams();
        print_sessions();
 }
 
-static int noop_close(void *data __attribute__((unused)),
-               int *fds __attribute__((unused)))
+static int noop_close(void *data __attribute__((unused)), int *fds __attribute__((unused)))
 {
        return 0;
 }
 
-static void untrack_stdio(void)
+static void untrack_stdio()
 {
        int fds[] = { fileno(stdout), fileno(stderr) };
 
@@ -691,14 +759,13 @@ static void untrack_stdio(void)
         * noop_close is used since we don't really want to close
         * the stdio output fds; we merely want to stop tracking them.
         */
-       (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                       fds, 2, noop_close, NULL);
+       (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker, fds, 2, noop_close, nullptr);
 }
 
 /*
  * Cleanup the daemon
  */
-static void relayd_cleanup(void)
+static void relayd_cleanup()
 {
        print_global_objects();
 
@@ -719,16 +786,11 @@ static void relayd_cleanup(void)
        }
        /* Close thread quit pipes */
        if (health_quit_pipe[0] != -1) {
-               (void) fd_tracker_util_pipe_close(
-                               the_fd_tracker, health_quit_pipe);
-       }
-       if (thread_quit_pipe[0] != -1) {
-               (void) fd_tracker_util_pipe_close(
-                               the_fd_tracker, thread_quit_pipe);
+               (void) fd_tracker_util_pipe_close(the_fd_tracker, health_quit_pipe);
        }
+       relayd_close_thread_quit_pipe();
        if (sessiond_trace_chunk_registry) {
-               sessiond_trace_chunk_registry_destroy(
-                               sessiond_trace_chunk_registry);
+               sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry);
        }
        if (the_fd_tracker) {
                untrack_stdio();
@@ -748,23 +810,6 @@ static void relayd_cleanup(void)
        }
 }
 
-/*
- * Write to writable pipe used to notify a thread.
- */
-static int notify_thread_pipe(int wpipe)
-{
-       ssize_t ret;
-
-       ret = lttng_write(wpipe, "!", 1);
-       if (ret < 1) {
-               PERROR("write poll pipe");
-               goto end;
-       }
-       ret = 0;
-end:
-       return ret;
-}
-
 static int notify_health_quit_pipe(int *pipe)
 {
        ssize_t ret;
@@ -782,13 +827,13 @@ end:
 /*
  * Stop all relayd and relayd-live threads.
  */
-int lttng_relay_stop_threads(void)
+int lttng_relay_stop_threads()
 {
        int retval = 0;
 
        /* Stopping all threads */
        DBG("Terminating all threads");
-       if (notify_thread_pipe(thread_quit_pipe[1])) {
+       if (relayd_notify_thread_quit_pipe()) {
                ERR("write error on thread quit pipe");
                retval = -1;
        }
@@ -841,7 +886,7 @@ static void sighandler(int sig)
  * Setup signal handler for :
  *             SIGINT, SIGTERM, SIGPIPE
  */
-static int set_signal_handler(void)
+static int set_signal_handler()
 {
        int ret = 0;
        struct sigaction sa;
@@ -856,23 +901,23 @@ static int set_signal_handler(void)
        sa.sa_flags = 0;
 
        sa.sa_handler = sighandler;
-       if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGTERM, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGINT, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGUSR1, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
        sa.sa_handler = SIG_IGN;
-       if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGPIPE, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
@@ -882,7 +927,7 @@ static int set_signal_handler(void)
        return ret;
 }
 
-void lttng_relay_notify_ready(void)
+void lttng_relay_notify_ready()
 {
        /* Notify the parent of the fork() process that we are ready. */
        if (opt_daemon || opt_background) {
@@ -892,72 +937,15 @@ void lttng_relay_notify_ready(void)
        }
 }
 
-/*
- * Init thread quit pipe.
- *
- * Return -1 on error or 0 if all pipes are created.
- */
-static int init_thread_quit_pipe(void)
-{
-       return fd_tracker_util_pipe_open_cloexec(
-                       the_fd_tracker, "Quit pipe", thread_quit_pipe);
-}
-
 /*
  * Init health quit pipe.
  *
  * Return -1 on error or 0 if all pipes are created.
  */
-static int init_health_quit_pipe(void)
-{
-       return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
-                       "Health quit pipe", health_quit_pipe);
-}
-
-/*
- * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
- */
-static int create_named_thread_poll_set(struct lttng_poll_event *events,
-               int size, const char *name)
-{
-       int ret;
-
-       if (events == NULL || size == 0) {
-               ret = -1;
-               goto error;
-       }
-
-       ret = fd_tracker_util_poll_create(the_fd_tracker,
-                       name, events, 1, LTTNG_CLOEXEC);
-       if (ret) {
-               PERROR("Failed to create \"%s\" poll file descriptor", name);
-               goto error;
-       }
-
-       /* Add quit pipe */
-       ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
-       if (ret < 0) {
-               goto error;
-       }
-
-       return 0;
-
-error:
-       return ret;
-}
-
-/*
- * Check if the thread quit pipe was triggered.
- *
- * Return 1 if it was triggered else 0;
- */
-static int check_thread_quit_pipe(int fd, uint32_t events)
+static int init_health_quit_pipe()
 {
-       if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
-               return 1;
-       }
-
-       return 0;
+       return fd_tracker_util_pipe_open_cloexec(
+               the_fd_tracker, "Health quit pipe", health_quit_pipe);
 }
 
 static int create_sock(void *data, int *out_fd)
@@ -1002,16 +990,15 @@ end:
 /*
  * Create and init socket from uri.
  */
-static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
-               const char *name)
+static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri, const char *name)
 {
        int ret, sock_fd;
-       struct lttcomm_sock *sock = NULL;
+       struct lttcomm_sock *sock = nullptr;
        char uri_str[PATH_MAX];
-       char *formated_name = NULL;
+       char *formated_name = nullptr;
 
        sock = lttcomm_alloc_sock_from_uri(uri);
-       if (sock == NULL) {
+       if (sock == nullptr) {
                ERR("Allocating socket");
                goto error;
        }
@@ -1023,19 +1010,21 @@ static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
        ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
        uri_str[sizeof(uri_str) - 1] = '\0';
        if (ret >= 0) {
-               ret = asprintf(&formated_name, "%s socket @ %s", name,
-                               uri_str);
+               ret = asprintf(&formated_name, "%s socket @ %s", name, uri_str);
                if (ret < 0) {
-                       formated_name = NULL;
+                       formated_name = nullptr;
                }
        }
 
-       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
-                       (const char **) (formated_name ? &formated_name : NULL),
-                       1, create_sock, sock);
+       ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker,
+                                              &sock_fd,
+                                              (const char **) (formated_name ? &formated_name :
+                                                                               nullptr),
+                                              1,
+                                              create_sock,
+                                              sock);
        if (ret) {
-               PERROR("Failed to open \"%s\" relay socket",
-                               formated_name ?: "Unknown");
+               PERROR("Failed to open \"%s\" relay socket", formated_name ?: "Unknown");
                goto error;
        }
        DBG("Listening on %s socket %d", name, sock->fd);
@@ -1049,7 +1038,6 @@ static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri,
        ret = sock->ops->listen(sock, -1);
        if (ret < 0) {
                goto error;
-
        }
 
        free(formated_name);
@@ -1060,21 +1048,18 @@ error:
                lttcomm_destroy_sock(sock);
        }
        free(formated_name);
-       return NULL;
+       return nullptr;
 }
 
-static
-struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
-               const char *name)
+static struct lttcomm_sock *accept_relayd_sock(struct lttcomm_sock *listening_sock,
+                                              const char *name)
 {
        int out_fd, ret;
-       struct lttcomm_sock *socks[2] = { listening_sock, NULL };
-       struct lttcomm_sock *new_sock = NULL;
+       struct lttcomm_sock *socks[2] = { listening_sock, nullptr };
+       struct lttcomm_sock *new_sock = nullptr;
 
        ret = fd_tracker_open_unsuspendable_fd(
-                       the_fd_tracker, &out_fd,
-                       (const char **) &name,
-                       1, accept_sock, &socks);
+               the_fd_tracker, &out_fd, (const char **) &name, 1, accept_sock, &socks);
        if (ret) {
                goto end;
        }
@@ -1089,8 +1074,8 @@ end:
  */
 static void *relay_thread_listener(void *data __attribute__((unused)))
 {
-       int i, ret, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int i, ret, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct lttcomm_sock *control_sock, *data_sock;
 
@@ -1138,12 +1123,12 @@ static void *relay_thread_listener(void *data __attribute__((unused)))
                goto error_testpoint;
        }
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                DBG("Listener accepting connections");
 
-restart:
+       restart:
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
                health_poll_exit();
@@ -1161,15 +1146,15 @@ restart:
 
                DBG("Relay new connection received");
                for (i = 0; i < nb_fd; i++) {
-                       health_code_update();
-
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_thread_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       health_code_update();
+
+                       /* Activity on thread quit pipe, exiting. */
+                       if (relayd_is_thread_quit_pipe(pollfd)) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -1183,26 +1168,26 @@ restart:
                                 */
                                int val = 1;
                                struct relay_connection *new_conn;
-                               struct lttcomm_sock *newsock = NULL;
+                               struct lttcomm_sock *newsock = nullptr;
                                enum connection_type type;
 
                                if (pollfd == data_sock->fd) {
                                        type = RELAY_DATA;
                                        newsock = accept_relayd_sock(data_sock,
-                                                       "Data socket to relayd");
+                                                                    "Data socket to relayd");
                                } else {
                                        LTTNG_ASSERT(pollfd == control_sock->fd);
                                        type = RELAY_CONTROL;
                                        newsock = accept_relayd_sock(control_sock,
-                                                       "Control socket to relayd");
+                                                                    "Control socket to relayd");
                                }
                                if (!newsock) {
                                        PERROR("accepting sock");
                                        goto error;
                                }
 
-                               ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
-                                               sizeof(val));
+                               ret = setsockopt(
+                                       newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
                                if (ret < 0) {
                                        PERROR("setsockopt inet");
                                        lttcomm_destroy_sock(newsock);
@@ -1212,7 +1197,7 @@ restart:
                                ret = socket_apply_keep_alive_config(newsock->fd);
                                if (ret < 0) {
                                        ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
-                                                       newsock->fd);
+                                           newsock->fd);
                                        lttcomm_destroy_sock(newsock);
                                        goto error;
                                }
@@ -1226,8 +1211,7 @@ restart:
                                /* Enqueue request for the dispatcher thread. */
                                cds_wfcq_head_ptr_t head;
                                head.h = &relay_conn_queue.head;
-                               cds_wfcq_enqueue(head, &relay_conn_queue.tail,
-                                                &new_conn->qnode);
+                               cds_wfcq_enqueue(head, &relay_conn_queue.tail, &new_conn->qnode);
 
                                /*
                                 * Wake the dispatch queue futex.
@@ -1254,9 +1238,8 @@ error_create_poll:
        if (data_sock->fd >= 0) {
                int data_sock_fd = data_sock->fd;
 
-               ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                               &data_sock_fd, 1, close_sock,
-                               data_sock);
+               ret = fd_tracker_close_unsuspendable_fd(
+                       the_fd_tracker, &data_sock_fd, 1, close_sock, data_sock);
                if (ret) {
                        PERROR("Failed to close the data listener socket file descriptor");
                }
@@ -1267,9 +1250,8 @@ error_sock_relay:
        if (control_sock->fd >= 0) {
                int control_sock_fd = control_sock->fd;
 
-               ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
-                               &control_sock_fd, 1, close_sock,
-                               control_sock);
+               ret = fd_tracker_close_unsuspendable_fd(
+                       the_fd_tracker, &control_sock_fd, 1, close_sock, control_sock);
                if (ret) {
                        PERROR("Failed to close the control listener socket file descriptor");
                }
@@ -1285,7 +1267,7 @@ error_sock_control:
        rcu_unregister_thread();
        DBG("Relay listener thread cleanup complete");
        lttng_relay_stop_threads();
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1296,7 +1278,7 @@ static void *relay_thread_dispatcher(void *data __attribute__((unused)))
        int err = -1;
        ssize_t ret;
        struct cds_wfcq_node *node;
-       struct relay_connection *new_conn = NULL;
+       struct relay_connection *new_conn = nullptr;
 
        DBG("[thread] Relay dispatcher started");
 
@@ -1324,7 +1306,7 @@ static void *relay_thread_dispatcher(void *data __attribute__((unused)))
                        /* Dequeue commands */
                        node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
                                                         &relay_conn_queue.tail);
-                       if (node == NULL) {
+                       if (node == nullptr) {
                                DBG("Woken up but nothing in the relay command queue");
                                /* Continue thread execution */
                                break;
@@ -1339,13 +1321,19 @@ static void *relay_thread_dispatcher(void *data __attribute__((unused)))
                         * the data will be read at some point in time
                         * or wait to the end of the world :)
                         */
-                       ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
+                       ret = lttng_write(
+                               relay_conn_pipe[1], &new_conn, sizeof(new_conn)); /* NOLINT
+                                                                                    sizeof
+                                                                                    used
+                                                                                    on a
+                                                                                    pointer.
+                                                                                  */
                        if (ret < 0) {
                                PERROR("write connection pipe");
                                connection_put(new_conn);
                                goto error;
                        }
-               } while (node != NULL);
+               } while (node != nullptr);
 
                /* Futex wait on queue. Blocking call on futex() */
                health_poll_entry();
@@ -1365,7 +1353,7 @@ error_testpoint:
        health_unregister(health_relayd);
        DBG("Dispatch thread dying");
        lttng_relay_stop_threads();
-       return NULL;
+       return nullptr;
 }
 
 static bool session_streams_have_index(const struct relay_session *session)
@@ -1378,14 +1366,13 @@ static bool session_streams_have_index(const struct relay_session *session)
  *
  * On success, send back the session id or else return a negative value.
  */
-static int relay_create_session(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                               struct relay_connection *conn,
+                               const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        ssize_t send_ret;
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
        struct lttcomm_relayd_create_session_reply_2_11 reply = {};
        char session_name[LTTNG_NAME_MAX] = {};
        char hostname[LTTNG_HOST_NAME_MAX] = {};
@@ -1407,8 +1394,8 @@ static int relay_create_session(
                ret = 0;
        } else if (conn->minor >= 4 && conn->minor < 11) {
                /* From 2.4 to 2.10 */
-               ret = cmd_create_session_2_4(payload, session_name,
-                       hostname, &live_timer, &snapshot);
+               ret = cmd_create_session_2_4(
+                       payload, session_name, hostname, &live_timer, &snapshot);
        } else {
                bool has_current_chunk;
                uint64_t current_chunk_id_value;
@@ -1416,11 +1403,18 @@ static int relay_create_session(
                uint64_t id_sessiond_value;
 
                /* From 2.11 to ... */
-               ret = cmd_create_session_2_11(payload, session_name, hostname,
-                               base_path, &live_timer, &snapshot, &id_sessiond_value,
-                               sessiond_uuid, &has_current_chunk,
-                               &current_chunk_id_value, &creation_time_value,
-                               &session_name_contains_creation_timestamp);
+               ret = cmd_create_session_2_11(payload,
+                                             session_name,
+                                             hostname,
+                                             base_path,
+                                             &live_timer,
+                                             &snapshot,
+                                             &id_sessiond_value,
+                                             sessiond_uuid,
+                                             &has_current_chunk,
+                                             &current_chunk_id_value,
+                                             &creation_time_value,
+                                             &session_name_contains_creation_timestamp);
                if (lttng_uuid_is_nil(sessiond_uuid)) {
                        /* The nil UUID is reserved for pre-2.11 clients. */
                        ERR("Illegal nil UUID announced by peer in create session command");
@@ -1430,8 +1424,7 @@ static int relay_create_session(
                LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
                LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
                if (has_current_chunk) {
-                       LTTNG_OPTIONAL_SET(&current_chunk_id,
-                                       current_chunk_id_value);
+                       LTTNG_OPTIONAL_SET(&current_chunk_id, current_chunk_id_value);
                }
        }
 
@@ -1439,13 +1432,18 @@ static int relay_create_session(
                goto send_reply;
        }
 
-       session = session_create(session_name, hostname, base_path, live_timer,
-                       snapshot, sessiond_uuid,
-                       id_sessiond.is_set ? &id_sessiond.value : NULL,
-                       current_chunk_id.is_set ? &current_chunk_id.value : NULL,
-                       creation_time.is_set ? &creation_time.value : NULL,
-                       conn->major, conn->minor,
-                       session_name_contains_creation_timestamp);
+       session = session_create(session_name,
+                                hostname,
+                                base_path,
+                                live_timer,
+                                snapshot,
+                                sessiond_uuid,
+                                id_sessiond.is_set ? &id_sessiond.value : nullptr,
+                                current_chunk_id.is_set ? &current_chunk_id.value : nullptr,
+                                creation_time.is_set ? &creation_time.value : nullptr,
+                                conn->major,
+                                conn->minor,
+                                session_name_contains_creation_timestamp);
        if (!session) {
                ret = -1;
                goto send_reply;
@@ -1465,29 +1463,26 @@ send_reply:
 
        if (conn->minor < 11) {
                /* From 2.1 to 2.10 */
-               ret = lttng_dynamic_buffer_append(&reply_payload,
-                               &reply.generic, sizeof(reply.generic));
+               ret = lttng_dynamic_buffer_append(
+                       &reply_payload, &reply.generic, sizeof(reply.generic));
                if (ret) {
                        ERR("Failed to append \"create session\" command reply header to payload buffer");
                        ret = -1;
                        goto end;
                }
        } else {
-               const uint32_t output_path_length =
-                               session ? strlen(session->output_path) + 1 : 0;
+               const uint32_t output_path_length = session ? strlen(session->output_path) + 1 : 0;
 
                reply.output_path_length = htobe32(output_path_length);
-               ret = lttng_dynamic_buffer_append(
-                               &reply_payload, &reply, sizeof(reply));
+               ret = lttng_dynamic_buffer_append(&reply_payload, &reply, sizeof(reply));
                if (ret) {
                        ERR("Failed to append \"create session\" command reply header to payload buffer");
                        goto end;
                }
 
                if (output_path_length) {
-                       ret = lttng_dynamic_buffer_append(&reply_payload,
-                                       session->output_path,
-                                       output_path_length);
+                       ret = lttng_dynamic_buffer_append(
+                               &reply_payload, session->output_path, output_path_length);
                        if (ret) {
                                ERR("Failed to append \"create session\" command reply path to payload buffer");
                                goto end;
@@ -1495,11 +1490,11 @@ send_reply:
                }
        }
 
-       send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
-                       reply_payload.size, 0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data, reply_payload.size, 0);
        if (send_ret < (ssize_t) reply_payload.size) {
                ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
-                               reply_payload.size, send_ret);
+                   reply_payload.size,
+                   send_ret);
                ret = -1;
        }
 end:
@@ -1524,12 +1519,11 @@ static void publish_connection_local_streams(struct relay_connection *conn)
         * session lock.
         */
        pthread_mutex_lock(&session->lock);
-       rcu_read_lock();
-       cds_list_for_each_entry_rcu(stream, &session->recv_list,
-                       recv_node) {
+       lttng::urcu::read_lock_guard read_lock;
+       cds_list_for_each_entry_rcu(stream, &session->recv_list, recv_node)
+       {
                stream_publish(stream);
        }
-       rcu_read_unlock();
 
        /*
         * Inform the viewer that there are new streams in the session.
@@ -1537,6 +1531,7 @@ static void publish_connection_local_streams(struct relay_connection *conn)
        if (session->viewer_attached) {
                uatomic_set(&session->new_streams, 1);
        }
+
        pthread_mutex_unlock(&session->lock);
 }
 
@@ -1546,7 +1541,7 @@ static int conform_channel_path(char *channel_path)
 
        if (strstr("../", channel_path)) {
                ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
-                               channel_path);
+                   channel_path);
                ret = -1;
                goto end;
        }
@@ -1571,19 +1566,18 @@ end:
 /*
  * relay_add_stream: allocate a new stream for a session
  */
-static int relay_add_stream(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                           struct relay_connection *conn,
+                           const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
        struct relay_session *session = conn->session;
-       struct relay_stream *stream = NULL;
+       struct relay_stream *stream = nullptr;
        struct lttcomm_relayd_status_stream reply;
-       struct ctf_trace *trace = NULL;
+       struct ctf_trace *trace = nullptr;
        uint64_t stream_handle = -1ULL;
-       char *path_name = NULL, *channel_name = NULL;
+       char *path_name = nullptr, *channel_name = nullptr;
        uint64_t tracefile_size = 0, tracefile_count = 0;
        LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
 
@@ -1595,17 +1589,19 @@ static int relay_add_stream(
 
        if (session->minor == 1) {
                /* For 2.1 */
-               ret = cmd_recv_stream_2_1(payload, &path_name,
-                       &channel_name);
+               ret = cmd_recv_stream_2_1(payload, &path_name, &channel_name);
        } else if (session->minor > 1 && session->minor < 11) {
                /* From 2.2 to 2.10 */
-               ret = cmd_recv_stream_2_2(payload, &path_name,
-                       &channel_name, &tracefile_size, &tracefile_count);
+               ret = cmd_recv_stream_2_2(
+                       payload, &path_name, &channel_name, &tracefile_size, &tracefile_count);
        } else {
                /* From 2.11 to ... */
-               ret = cmd_recv_stream_2_11(payload, &path_name,
-                       &channel_name, &tracefile_size, &tracefile_count,
-                       &stream_chunk_id.value);
+               ret = cmd_recv_stream_2_11(payload,
+                                          &path_name,
+                                          &channel_name,
+                                          &tracefile_size,
+                                          &tracefile_count,
+                                          &stream_chunk_id.value);
                stream_chunk_id.is_set = true;
        }
 
@@ -1638,25 +1634,24 @@ static int relay_add_stream(
                         */
                        WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
                             " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
-                                       session->id, path_name);
+                            session->id,
+                            path_name);
                } else if (conn->minor >= 4 && conn->minor < 11) {
                        char *group_by_session_path_name;
 
                        LTTNG_ASSERT(session->session_name[0] != '\0');
 
-                       group_by_session_path_name =
-                                       backward_compat_group_by_session(
-                                                       path_name,
-                                                       session->session_name,
-                                                       session->creation_time.value);
+                       group_by_session_path_name = backward_compat_group_by_session(
+                               path_name, session->session_name, session->creation_time.value);
                        if (!group_by_session_path_name) {
                                ERR("Failed to apply group by session to stream of session %" PRIu64,
-                                               session->id);
+                                   session->id);
                                goto send_reply;
                        }
 
                        DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
-                                       path_name, group_by_session_path_name);
+                           path_name,
+                           group_by_session_path_name);
 
                        free(path_name);
                        path_name = group_by_session_path_name;
@@ -1674,10 +1669,10 @@ static int relay_add_stream(
        pthread_mutex_unlock(&last_relay_stream_id_lock);
 
        /* We pass ownership of path_name and channel_name. */
-       stream = stream_create(trace, stream_handle, path_name,
-               channel_name, tracefile_size, tracefile_count);
-       path_name = NULL;
-       channel_name = NULL;
+       stream = stream_create(
+               trace, stream_handle, path_name, channel_name, tracefile_size, tracefile_count);
+       path_name = nullptr;
+       channel_name = nullptr;
 
        /*
         * Streams are the owners of their trace. Reference to trace is
@@ -1694,11 +1689,10 @@ send_reply:
                reply.ret_code = htobe32(LTTNG_OK);
        }
 
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(struct lttcomm_relayd_status_stream), 0);
+       send_ret = conn->sock->ops->sendmsg(
+               conn->sock, &reply, sizeof(struct lttcomm_relayd_status_stream), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"add stream\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 
@@ -1711,10 +1705,9 @@ end_no_session:
 /*
  * relay_close_stream: close a specific stream
  */
-static int relay_close_stream(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                             struct relay_connection *conn,
+                             const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -1733,7 +1726,8 @@ static int relay_close_stream(
 
        if (payload->size < sizeof(stream_info)) {
                ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(stream_info), payload->size);
+                   sizeof(stream_info),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -1774,11 +1768,10 @@ end:
        } else {
                reply.ret_code = htobe32(LTTNG_OK);
        }
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(struct lttcomm_relayd_generic_reply), 0);
+       send_ret = conn->sock->ops->sendmsg(
+               conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"close stream\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 
@@ -1789,11 +1782,9 @@ end_no_session:
 /*
  * relay_reset_metadata: reset a metadata stream
  */
-static
-int relay_reset_metadata(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                               struct relay_connection *conn,
+                               const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -1812,7 +1803,8 @@ int relay_reset_metadata(
 
        if (payload->size < sizeof(stream_info)) {
                ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(stream_info), payload->size);
+                   sizeof(stream_info),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -1841,10 +1833,10 @@ int relay_reset_metadata(
 
        ret = stream_reset_file(stream);
        if (ret < 0) {
-               ERR("Failed to reset metadata stream %" PRIu64
-                               ": stream_path = %s, channel = %s",
-                               stream->stream_handle, stream->path_name,
-                               stream->channel_name);
+               ERR("Failed to reset metadata stream %" PRIu64 ": stream_path = %s, channel = %s",
+                   stream->stream_handle,
+                   stream->path_name,
+                   stream->channel_name);
                goto end_unlock;
        }
 end_unlock:
@@ -1858,11 +1850,10 @@ end:
        } else {
                reply.ret_code = htobe32(LTTNG_OK);
        }
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(struct lttcomm_relayd_generic_reply), 0);
+       send_ret = conn->sock->ops->sendmsg(
+               conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 
@@ -1890,10 +1881,9 @@ static void relay_unknown_command(struct relay_connection *conn)
  * relay_start: send an acknowledgment to the client to tell if we are
  * ready to receive data. We are ready if a session is established.
  */
-static int relay_start(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload __attribute__((unused)))
+static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                      struct relay_connection *conn,
+                      const struct lttng_buffer_view *payload __attribute__((unused)))
 {
        int ret = 0;
        ssize_t send_ret;
@@ -1907,11 +1897,9 @@ static int relay_start(
 
        memset(&reply, 0, sizeof(reply));
        reply.ret_code = htobe32(LTTNG_OK);
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(reply), 0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 
@@ -1922,8 +1910,8 @@ static int relay_start(
  * relay_recv_metadata: receive the metadata for the session.
  */
 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+                              struct relay_connection *conn,
+                              const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        struct relay_session *session = conn->session;
@@ -1943,15 +1931,12 @@ static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
                ret = -1;
                goto end;
        }
-       metadata_payload_size = recv_hdr->data_size -
-                       sizeof(struct lttcomm_relayd_metadata_payload);
+       metadata_payload_size =
+               recv_hdr->data_size - sizeof(struct lttcomm_relayd_metadata_payload);
 
-       memcpy(&metadata_payload_header, payload->data,
-                       sizeof(metadata_payload_header));
-       metadata_payload_header.stream_id = be64toh(
-                       metadata_payload_header.stream_id);
-       metadata_payload_header.padding_size = be32toh(
-                       metadata_payload_header.padding_size);
+       memcpy(&metadata_payload_header, payload->data, sizeof(metadata_payload_header));
+       metadata_payload_header.stream_id = be64toh(metadata_payload_header.stream_id);
+       metadata_payload_header.padding_size = be32toh(metadata_payload_header.padding_size);
 
        metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
        if (!metadata_stream) {
@@ -1959,8 +1944,8 @@ static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
                goto end;
        }
 
-       packet_view = lttng_buffer_view_from_view(payload,
-                       sizeof(metadata_payload_header), metadata_payload_size);
+       packet_view = lttng_buffer_view_from_view(
+               payload, sizeof(metadata_payload_header), metadata_payload_size);
        if (!lttng_buffer_view_is_valid(&packet_view)) {
                ERR("Invalid metadata packet length announced by header");
                ret = -1;
@@ -1968,10 +1953,9 @@ static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
        }
 
        pthread_mutex_lock(&metadata_stream->lock);
-       ret = stream_write(metadata_stream, &packet_view,
-                       metadata_payload_header.padding_size);
+       ret = stream_write(metadata_stream, &packet_view, metadata_payload_header.padding_size);
        pthread_mutex_unlock(&metadata_stream->lock);
-       if (ret){
+       if (ret) {
                ret = -1;
                goto end_put;
        }
@@ -1984,10 +1968,9 @@ end:
 /*
  * relay_send_version: send relayd version number
  */
-static int relay_send_version(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                             struct relay_connection *conn,
+                             const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -1999,7 +1982,8 @@ static int relay_send_version(
        /* Get version from the other side. */
        if (payload->size < sizeof(msg)) {
                ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(msg), payload->size);
+                   sizeof(msg),
+                   payload->size);
                ret = -1;
                goto end;
        }
@@ -2015,7 +1999,8 @@ static int relay_send_version(
        /* Major versions must be the same */
        if (reply.major != msg.major) {
                DBG("Incompatible major versions (%u vs %u), deleting session",
-                               reply.major, msg.major);
+                   reply.major,
+                   msg.major);
                compatible = false;
        }
 
@@ -2029,11 +2014,9 @@ static int relay_send_version(
 
        reply.major = htobe32(reply.major);
        reply.minor = htobe32(reply.minor);
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(reply), 0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"send version\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret);
                ret = -1;
                goto end;
        } else {
@@ -2045,8 +2028,7 @@ static int relay_send_version(
                goto end;
        }
 
-       DBG("Version check done using protocol %u.%u", conn->major,
-                       conn->minor);
+       DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
 
 end:
        return ret;
@@ -2055,10 +2037,9 @@ end:
 /*
  * Check for data pending for a given stream id from the session daemon.
  */
-static int relay_data_pending(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                             struct relay_connection *conn,
+                             const struct lttng_buffer_view *payload)
 {
        struct relay_session *session = conn->session;
        struct lttcomm_relayd_data_pending msg;
@@ -2078,7 +2059,8 @@ static int relay_data_pending(
 
        if (payload->size < sizeof(msg)) {
                ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(msg), payload->size);
+                   sizeof(msg),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -2087,7 +2069,7 @@ static int relay_data_pending(
        msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
 
        stream = stream_get_by_id(msg.stream_id);
-       if (stream == NULL) {
+       if (stream == nullptr) {
                ret = -1;
                goto end;
        }
@@ -2104,10 +2086,11 @@ static int relay_data_pending(
                stream_seq = stream->prev_data_seq;
        }
        DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
-                       ", prev_index_seq %" PRIu64
-                       ", and last_seq %" PRIu64, msg.stream_id,
-                       stream->prev_data_seq, stream->prev_index_seq,
-                       msg.last_net_seq_num);
+           ", prev_index_seq %" PRIu64 ", and last_seq %" PRIu64,
+           msg.stream_id,
+           stream->prev_data_seq,
+           stream->prev_index_seq,
+           msg.last_net_seq_num);
 
        /* Avoid wrapping issue */
        if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
@@ -2128,8 +2111,7 @@ end:
        reply.ret_code = htobe32(ret);
        send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"data pending\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 
@@ -2145,10 +2127,10 @@ end_no_session:
  * the control socket has been handled. So, this is why we simply return
  * OK here.
  */
-static int relay_quiescent_control(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr
+                                  __attribute__((unused)),
+                                  struct relay_connection *conn,
+                                  const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -2166,7 +2148,8 @@ static int relay_quiescent_control(
 
        if (payload->size < sizeof(msg)) {
                ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(msg), payload->size);
+                   sizeof(msg),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -2188,8 +2171,7 @@ reply:
        reply.ret_code = htobe32(LTTNG_OK);
        send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret);
                ret = -1;
        } else {
                ret = 0;
@@ -2207,8 +2189,8 @@ end_no_session:
  * This command returns to the client a LTTNG_OK code.
  */
 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+                                   struct relay_connection *conn,
+                                   const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -2230,7 +2212,8 @@ static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
 
        if (payload->size < sizeof(msg)) {
                ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(msg), payload->size);
+                   sizeof(msg),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -2243,22 +2226,25 @@ static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
         * to iterate over all streams to find the one associated with
         * the right session_id.
         */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
-                       node.node) {
-               if (!stream_get(stream)) {
-                       continue;
-               }
-               if (stream->trace->session->id == msg.session_id) {
-                       pthread_mutex_lock(&stream->lock);
-                       stream->data_pending_check_done = false;
-                       pthread_mutex_unlock(&stream->lock);
-                       DBG("Set begin data pending flag to stream %" PRIu64,
-                                       stream->stream_handle);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (relay_streams_ht->ht, &iter.iter, stream, node.node) {
+                       if (!stream_get(stream)) {
+                               continue;
+                       }
+
+                       if (stream->trace->session->id == msg.session_id) {
+                               pthread_mutex_lock(&stream->lock);
+                               stream->data_pending_check_done = false;
+                               pthread_mutex_unlock(&stream->lock);
+                               DBG("Set begin data pending flag to stream %" PRIu64,
+                                   stream->stream_handle);
+                       }
+
+                       stream_put(stream);
                }
-               stream_put(stream);
        }
-       rcu_read_unlock();
 
        memset(&reply, 0, sizeof(reply));
        /* All good, send back reply. */
@@ -2266,8 +2252,7 @@ static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
 
        send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
-                       send_ret);
+               ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret);
                ret = -1;
        } else {
                ret = 0;
@@ -2286,10 +2271,9 @@ end_no_session:
  *
  * Return to the client if there is data in flight or not with a ret_code.
  */
-static int relay_end_data_pending(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                                 struct relay_connection *conn,
+                                 const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -2309,7 +2293,8 @@ static int relay_end_data_pending(
 
        if (payload->size < sizeof(msg)) {
                ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
-                               sizeof(msg), payload->size);
+                   sizeof(msg),
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -2320,42 +2305,49 @@ static int relay_end_data_pending(
         * Iterate over all streams to see if the begin data pending
         * flag is set.
         */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
-                       node.node) {
-               if (!stream_get(stream)) {
-                       continue;
-               }
-               if (stream->trace->session->id != msg.session_id) {
-                       stream_put(stream);
-                       continue;
-               }
-               pthread_mutex_lock(&stream->lock);
-               if (!stream->data_pending_check_done) {
-                       uint64_t stream_seq;
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-                       if (session_streams_have_index(conn->session)) {
-                               /*
-                                * Ensure that both the index and stream data have been
-                                * flushed up to the requested point.
-                                */
-                               stream_seq = std::min(stream->prev_data_seq, stream->prev_index_seq);
-                       } else {
-                               stream_seq = stream->prev_data_seq;
+               cds_lfht_for_each_entry (relay_streams_ht->ht, &iter.iter, stream, node.node) {
+                       if (!stream_get(stream)) {
+                               continue;
                        }
-                       if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
-                               is_data_inflight = 1;
-                               DBG("Data is still in flight for stream %" PRIu64,
-                                               stream->stream_handle);
-                               pthread_mutex_unlock(&stream->lock);
+
+                       if (stream->trace->session->id != msg.session_id) {
                                stream_put(stream);
-                               break;
+                               continue;
+                       }
+
+                       pthread_mutex_lock(&stream->lock);
+                       if (!stream->data_pending_check_done) {
+                               uint64_t stream_seq;
+
+                               if (session_streams_have_index(conn->session)) {
+                                       /*
+                                        * Ensure that both the index and stream data have been
+                                        * flushed up to the requested point.
+                                        */
+                                       stream_seq = std::min(stream->prev_data_seq,
+                                                             stream->prev_index_seq);
+                               } else {
+                                       stream_seq = stream->prev_data_seq;
+                               }
+
+                               if (!stream->closed ||
+                                   !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
+                                       is_data_inflight = 1;
+                                       DBG("Data is still in flight for stream %" PRIu64,
+                                           stream->stream_handle);
+                                       pthread_mutex_unlock(&stream->lock);
+                                       stream_put(stream);
+                                       break;
+                               }
                        }
+
+                       pthread_mutex_unlock(&stream->lock);
+                       stream_put(stream);
                }
-               pthread_mutex_unlock(&stream->lock);
-               stream_put(stream);
        }
-       rcu_read_unlock();
 
        memset(&reply, 0, sizeof(reply));
        /* All good, send back reply. */
@@ -2363,8 +2355,7 @@ static int relay_end_data_pending(
 
        send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
-                       send_ret);
+               ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret);
                ret = -1;
        } else {
                ret = 0;
@@ -2379,10 +2370,9 @@ end_no_session:
  *
  * Return 0 on success else a negative value.
  */
-static int relay_recv_index(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                           struct relay_connection *conn,
+                           const struct lttng_buffer_view *payload)
 {
        int ret;
        ssize_t send_ret;
@@ -2402,12 +2392,12 @@ static int relay_recv_index(
                goto end_no_session;
        }
 
-       msg_len = lttcomm_relayd_index_len(
-                       lttng_to_index_major(conn->major, conn->minor),
-                       lttng_to_index_minor(conn->major, conn->minor));
+       msg_len = lttcomm_relayd_index_len(lttng_to_index_major(conn->major, conn->minor),
+                                          lttng_to_index_minor(conn->major, conn->minor));
        if (payload->size < msg_len) {
                ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
-                               msg_len, payload->size);
+                   msg_len,
+                   payload->size);
                ret = -1;
                goto end_no_session;
        }
@@ -2422,8 +2412,7 @@ static int relay_recv_index(
        index_info.stream_id = be64toh(index_info.stream_id);
 
        if (conn->minor >= 8) {
-               index_info.stream_instance_id =
-                               be64toh(index_info.stream_instance_id);
+               index_info.stream_instance_id = be64toh(index_info.stream_instance_id);
                index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
        } else {
                index_info.stream_instance_id = -1ULL;
@@ -2468,10 +2457,9 @@ end_no_session:
  *
  * Return 0 on success else a negative value.
  */
-static int relay_streams_sent(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload __attribute__((unused)))
+static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
+                             struct relay_connection *conn,
+                             const struct lttng_buffer_view *payload __attribute__((unused)))
 {
        int ret;
        ssize_t send_ret;
@@ -2497,8 +2485,7 @@ static int relay_streams_sent(
        reply.ret_code = htobe32(LTTNG_OK);
        send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
-                       send_ret);
+               ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret);
                ret = -1;
        } else {
                /* Success. */
@@ -2509,9 +2496,9 @@ end_no_session:
        return ret;
 }
 
-static ssize_t relay_unpack_rotate_streams_header(
-               const struct lttng_buffer_view *payload,
-               struct lttcomm_relayd_rotate_streams *_rotate_streams)
+static ssize_t
+relay_unpack_rotate_streams_header(const struct lttng_buffer_view *payload,
+                                  struct lttcomm_relayd_rotate_streams *_rotate_streams)
 {
        struct lttcomm_relayd_rotate_streams rotate_streams;
        /*
@@ -2522,13 +2509,13 @@ static ssize_t relay_unpack_rotate_streams_header(
         * See comment at the declaration of this structure for more information.
         */
        ssize_t header_len = sizeof(struct lttcomm_relayd_rotate_streams_packed);
-       size_t expected_payload_size_no_padding,
-               expected_payload_size_3_bytes_padding,
+       size_t expected_payload_size_no_padding, expected_payload_size_3_bytes_padding,
                expected_payload_size_7_bytes_padding;
 
        if (payload->size < header_len) {
                ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
-                               header_len, payload->size);
+                   header_len,
+                   payload->size);
                goto error;
        }
 
@@ -2552,14 +2539,14 @@ static ssize_t relay_unpack_rotate_streams_header(
         * Payload size expected given the possible padding lengths in
         * `struct lttcomm_relayd_rotate_streams`.
         */
-       expected_payload_size_no_padding = (rotate_streams.stream_count *
-               sizeof(*rotate_streams.rotation_positions)) +
+       expected_payload_size_no_padding =
+               (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
                sizeof(lttcomm_relayd_rotate_streams_packed);
-       expected_payload_size_3_bytes_padding = (rotate_streams.stream_count *
-               sizeof(*rotate_streams.rotation_positions)) +
+       expected_payload_size_3_bytes_padding =
+               (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
                sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding);
-       expected_payload_size_7_bytes_padding = (rotate_streams.stream_count *
-               sizeof(*rotate_streams.rotation_positions)) +
+       expected_payload_size_7_bytes_padding =
+               (rotate_streams.stream_count * sizeof(*rotate_streams.rotation_positions)) +
                sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding);
 
        if (payload->size == expected_payload_size_no_padding) {
@@ -2613,10 +2600,10 @@ static ssize_t relay_unpack_rotate_streams_header(
                header_len = sizeof(padded_rotate_streams);
        } else {
                ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
-                               expected_payload_size_no_padding,
-                               expected_payload_size_3_bytes_padding,
-                               expected_payload_size_7_bytes_padding,
-                               payload->size);
+                   expected_payload_size_no_padding,
+                   expected_payload_size_3_bytes_padding,
+                   expected_payload_size_7_bytes_padding,
+                   payload->size);
                goto error;
        }
 
@@ -2629,10 +2616,10 @@ error:
  * relay_rotate_session_stream: rotate a stream to a new tracefile for the
  * session rotation feature (not the tracefile rotation feature).
  */
-static int relay_rotate_session_streams(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr *recv_hdr
+                                       __attribute__((unused)),
+                                       struct relay_connection *conn,
+                                       const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        uint32_t i;
@@ -2641,8 +2628,8 @@ static int relay_rotate_session_streams(
        struct relay_session *session = conn->session;
        struct lttcomm_relayd_rotate_streams rotate_streams;
        struct lttcomm_relayd_generic_reply reply = {};
-       struct relay_stream *stream = NULL;
-       struct lttng_trace_chunk *next_trace_chunk = NULL;
+       struct relay_stream *stream = nullptr;
+       struct lttng_trace_chunk *next_trace_chunk = nullptr;
        struct lttng_buffer_view stream_positions;
        char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
        const char *chunk_id_str = "none";
@@ -2673,27 +2660,29 @@ static int relay_rotate_session_streams(
                 * before this command is received.
                 */
                next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
-                               sessiond_trace_chunk_registry,
-                               session->sessiond_uuid,
-                               conn->session->id_sessiond.is_set ?
-                                       conn->session->id_sessiond.value :
-                                       conn->session->id,
-                               rotate_streams.new_chunk_id.value);
+                       sessiond_trace_chunk_registry,
+                       session->sessiond_uuid,
+                       conn->session->id_sessiond.is_set ? conn->session->id_sessiond.value :
+                                                           conn->session->id,
+                       rotate_streams.new_chunk_id.value);
                if (!next_trace_chunk) {
                        char uuid_str[LTTNG_UUID_STR_LEN];
 
                        lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
                        ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
-                                       ", trace_chunk_id = %" PRIu64,
-                                       uuid_str, session->id,
-                                       rotate_streams.new_chunk_id.value);
+                           ", trace_chunk_id = %" PRIu64,
+                           uuid_str,
+                           session->id,
+                           rotate_streams.new_chunk_id.value);
                        reply_code = LTTNG_ERR_INVALID_PROTOCOL;
                        ret = -1;
                        goto end;
                }
 
-               ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
-                               rotate_streams.new_chunk_id.value);
+               ret = snprintf(chunk_id_buf,
+                              sizeof(chunk_id_buf),
+                              "%" PRIu64,
+                              rotate_streams.new_chunk_id.value);
                if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
                        chunk_id_str = "formatting error";
                } else {
@@ -2702,15 +2691,14 @@ static int relay_rotate_session_streams(
        }
 
        DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
-                       rotate_streams.stream_count, session->session_name,
-                       chunk_id_str);
+           rotate_streams.stream_count,
+           session->session_name,
+           chunk_id_str);
 
-       stream_positions = lttng_buffer_view_from_view(payload,
-                       header_len, -1);
+       stream_positions = lttng_buffer_view_from_view(payload, header_len, -1);
        if (!stream_positions.data ||
-                       stream_positions.size <
-                                       (rotate_streams.stream_count *
-                                                       sizeof(struct lttcomm_relayd_stream_rotation_position))) {
+           stream_positions.size < (rotate_streams.stream_count *
+                                    sizeof(struct lttcomm_relayd_stream_rotation_position))) {
                reply_code = LTTNG_ERR_INVALID_PROTOCOL;
                ret = -1;
                goto end;
@@ -2718,11 +2706,10 @@ static int relay_rotate_session_streams(
 
        for (i = 0; i < rotate_streams.stream_count; i++) {
                struct lttcomm_relayd_stream_rotation_position *position_comm =
-                               &((typeof(position_comm)) stream_positions.data)[i];
+                       &((typeof(position_comm)) stream_positions.data)[i];
                const struct lttcomm_relayd_stream_rotation_position pos = {
                        .stream_id = be64toh(position_comm->stream_id),
-                       .rotate_at_seq_num = be64toh(
-                                       position_comm->rotate_at_seq_num),
+                       .rotate_at_seq_num = be64toh(position_comm->rotate_at_seq_num),
                };
 
                stream = stream_get_by_id(pos.stream_id);
@@ -2733,8 +2720,7 @@ static int relay_rotate_session_streams(
                }
 
                pthread_mutex_lock(&stream->lock);
-               ret = stream_set_pending_rotation(stream, next_trace_chunk,
-                               pos.rotate_at_seq_num);
+               ret = stream_set_pending_rotation(stream, next_trace_chunk, pos.rotate_at_seq_num);
                pthread_mutex_unlock(&stream->lock);
                if (ret) {
                        reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
@@ -2742,7 +2728,7 @@ static int relay_rotate_session_streams(
                }
 
                stream_put(stream);
-               stream = NULL;
+               stream = nullptr;
        }
 
        reply_code = LTTNG_OK;
@@ -2753,11 +2739,10 @@ end:
        }
 
        reply.ret_code = htobe32((uint32_t) reply_code);
-       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
-                       sizeof(struct lttcomm_relayd_generic_reply), 0);
+       send_ret = conn->sock->ops->sendmsg(
+               conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 end_no_reply:
@@ -2768,10 +2753,10 @@ end_no_reply:
 /*
  * relay_create_trace_chunk: create a new trace chunk
  */
-static int relay_create_trace_chunk(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr
+                                   __attribute__((unused)),
+                                   struct relay_connection *conn,
+                                   const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        ssize_t send_ret;
@@ -2779,7 +2764,7 @@ static int relay_create_trace_chunk(
        struct lttcomm_relayd_create_trace_chunk *msg;
        struct lttcomm_relayd_generic_reply reply = {};
        struct lttng_buffer_view header_view;
-       struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr, *published_chunk = nullptr;
        enum lttng_error_code reply_code = LTTNG_OK;
        enum lttng_trace_chunk_status chunk_status;
        const char *new_path;
@@ -2812,9 +2797,9 @@ static int relay_create_trace_chunk(
        pthread_mutex_lock(&conn->session->lock);
        session->ongoing_rotation = true;
        if (session->current_trace_chunk &&
-                       !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
+           !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
                chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
-                                       DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
+                                                            DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Failed to rename old chunk");
                        ret = -1;
@@ -2826,13 +2811,12 @@ static int relay_create_trace_chunk(
                if (!session->has_rotated) {
                        new_path = "";
                } else {
-                       new_path = NULL;
+                       new_path = nullptr;
                }
        } else {
                new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
        }
-       chunk = lttng_trace_chunk_create(
-                       msg->chunk_id, msg->creation_timestamp, new_path);
+       chunk = lttng_trace_chunk_create(msg->chunk_id, msg->creation_timestamp, new_path);
        if (!chunk) {
                ERR("Failed to create trace chunk in trace chunk creation command");
                ret = -1;
@@ -2843,10 +2827,8 @@ static int relay_create_trace_chunk(
 
        if (msg->override_name_length) {
                const char *name;
-               const struct lttng_buffer_view chunk_name_view =
-                               lttng_buffer_view_from_view(payload,
-                                               sizeof(*msg),
-                                               msg->override_name_length);
+               const struct lttng_buffer_view chunk_name_view = lttng_buffer_view_from_view(
+                       payload, sizeof(*msg), msg->override_name_length);
 
                if (!lttng_buffer_view_is_valid(&chunk_name_view)) {
                        ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
@@ -2863,8 +2845,7 @@ static int relay_create_trace_chunk(
                        goto end;
                }
 
-               chunk_status = lttng_trace_chunk_override_name(
-                               chunk, chunk_name_view.data);
+               chunk_status = lttng_trace_chunk_override_name(chunk, chunk_name_view.data);
                switch (chunk_status) {
                case LTTNG_TRACE_CHUNK_STATUS_OK:
                        break;
@@ -2889,8 +2870,7 @@ static int relay_create_trace_chunk(
        }
 
        LTTNG_ASSERT(conn->session->output_directory);
-       chunk_status = lttng_trace_chunk_set_as_owner(chunk,
-                       conn->session->output_directory);
+       chunk_status = lttng_trace_chunk_set_as_owner(chunk, conn->session->output_directory);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                reply_code = LTTNG_ERR_UNK;
                ret = -1;
@@ -2898,20 +2878,20 @@ static int relay_create_trace_chunk(
        }
 
        published_chunk = sessiond_trace_chunk_registry_publish_chunk(
-                       sessiond_trace_chunk_registry,
-                       conn->session->sessiond_uuid,
-                       conn->session->id_sessiond.is_set ?
-                               conn->session->id_sessiond.value :
-                               conn->session->id,
-                       chunk);
+               sessiond_trace_chunk_registry,
+               conn->session->sessiond_uuid,
+               conn->session->id_sessiond.is_set ? conn->session->id_sessiond.value :
+                                                   conn->session->id,
+               chunk);
        if (!published_chunk) {
                char uuid_str[LTTNG_UUID_STR_LEN];
 
                lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
-               ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
-                               uuid_str,
-                               conn->session->id,
-                               msg->chunk_id);
+               ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
+                   ", chunk_id = %" PRIu64,
+                   uuid_str,
+                   conn->session->id,
+                   msg->chunk_id);
                ret = -1;
                reply_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -2927,23 +2907,19 @@ static int relay_create_trace_chunk(
                ret = -1;
                goto end;
        }
-       conn->session->pending_closure_trace_chunk =
-                       conn->session->current_trace_chunk;
+       conn->session->pending_closure_trace_chunk = conn->session->current_trace_chunk;
        conn->session->current_trace_chunk = published_chunk;
-       published_chunk = NULL;
+       published_chunk = nullptr;
        if (!conn->session->pending_closure_trace_chunk) {
                session->ongoing_rotation = false;
        }
 end:
        pthread_mutex_unlock(&conn->session->lock);
        reply.ret_code = htobe32((uint32_t) reply_code);
-       send_ret = conn->sock->ops->sendmsg(conn->sock,
-                       &reply,
-                       sizeof(struct lttcomm_relayd_generic_reply),
-                       0);
+       send_ret = conn->sock->ops->sendmsg(
+               conn->sock, &reply, sizeof(struct lttcomm_relayd_generic_reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 end_no_reply:
@@ -2955,10 +2931,10 @@ end_no_reply:
 /*
  * relay_close_trace_chunk: close a trace chunk
  */
-static int relay_close_trace_chunk(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr
+                                  __attribute__((unused)),
+                                  struct relay_connection *conn,
+                                  const struct lttng_buffer_view *payload)
 {
        int ret = 0, buf_ret;
        ssize_t send_ret;
@@ -2966,7 +2942,7 @@ static int relay_close_trace_chunk(
        struct lttcomm_relayd_close_trace_chunk *msg;
        struct lttcomm_relayd_close_trace_chunk_reply reply = {};
        struct lttng_buffer_view header_view;
-       struct lttng_trace_chunk *chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr;
        enum lttng_error_code reply_code = LTTNG_OK;
        enum lttng_trace_chunk_status chunk_status;
        uint64_t chunk_id;
@@ -2974,7 +2950,7 @@ static int relay_close_trace_chunk(
        time_t close_timestamp;
        char closed_trace_chunk_path[LTTNG_PATH_MAX];
        size_t path_length = 0;
-       const char *chunk_name = NULL;
+       const char *chunk_name = nullptr;
        struct lttng_dynamic_buffer reply_payload;
        const char *new_path;
 
@@ -3006,29 +2982,28 @@ static int relay_close_trace_chunk(
        close_command.value = (lttng_trace_chunk_command_type) be32toh(msg->close_command.value);
        close_command.is_set = msg->close_command.is_set;
 
-       chunk = sessiond_trace_chunk_registry_get_chunk(
-                       sessiond_trace_chunk_registry,
-                       conn->session->sessiond_uuid,
-                       conn->session->id_sessiond.is_set ?
-                               conn->session->id_sessiond.value :
-                               conn->session->id,
-                       chunk_id);
+       chunk = sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry,
+                                                       conn->session->sessiond_uuid,
+                                                       conn->session->id_sessiond.is_set ?
+                                                               conn->session->id_sessiond.value :
+                                                               conn->session->id,
+                                                       chunk_id);
        if (!chunk) {
                char uuid_str[LTTNG_UUID_STR_LEN];
 
                lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
-               ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
-                               uuid_str,
-                               conn->session->id,
-                               msg->chunk_id);
+               ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
+                   ", chunk_id = %" PRIu64,
+                   uuid_str,
+                   conn->session->id,
+                   msg->chunk_id);
                ret = -1;
                reply_code = LTTNG_ERR_NOMEM;
                goto end;
        }
 
        pthread_mutex_lock(&session->lock);
-       if (close_command.is_set &&
-                       close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
+       if (close_command.is_set && close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE) {
                /*
                 * Clear command. It is a protocol error to ask for a
                 * clear on a relay which does not allow it. Querying
@@ -3041,29 +3016,28 @@ static int relay_close_trace_chunk(
                        goto end_unlock_session;
                }
        }
-       if (session->pending_closure_trace_chunk &&
-                       session->pending_closure_trace_chunk != chunk) {
+       if (session->pending_closure_trace_chunk && session->pending_closure_trace_chunk != chunk) {
                ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
-                               session->session_name);
+                   session->session_name);
                reply_code = LTTNG_ERR_INVALID_PROTOCOL;
                ret = -1;
                goto end_unlock_session;
        }
 
        if (session->current_trace_chunk && session->current_trace_chunk != chunk &&
-                       !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
+           !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
                if (close_command.is_set &&
-                               close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
-                               !session->has_rotated) {
+                   close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE &&
+                   !session->has_rotated) {
                        /* New chunk stays in session output directory. */
                        new_path = "";
                } else {
                        /* Use chunk name for new chunk. */
-                       new_path = NULL;
+                       new_path = nullptr;
                }
                /* Rename new chunk path. */
-               chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
-                               new_path);
+               chunk_status =
+                       lttng_trace_chunk_rename_path(session->current_trace_chunk, new_path);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        goto end_unlock_session;
@@ -3071,14 +3045,14 @@ static int relay_close_trace_chunk(
                session->ongoing_rotation = false;
        }
        if ((!close_command.is_set ||
-                       close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
-                       !lttng_trace_chunk_get_name_overridden(chunk)) {
+            close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) &&
+           !lttng_trace_chunk_get_name_overridden(chunk)) {
                const char *old_path;
 
                if (!session->has_rotated) {
                        old_path = "";
                } else {
-                       old_path = NULL;
+                       old_path = nullptr;
                }
                /* We need to move back the .tmp_old_chunk to its rightful place. */
                chunk_status = lttng_trace_chunk_rename_path(chunk, old_path);
@@ -3087,8 +3061,7 @@ static int relay_close_trace_chunk(
                        goto end_unlock_session;
                }
        }
-       chunk_status = lttng_trace_chunk_set_close_timestamp(
-                       chunk, close_timestamp);
+       chunk_status = lttng_trace_chunk_set_close_timestamp(chunk, close_timestamp);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ERR("Failed to set trace chunk close timestamp");
                ret = -1;
@@ -3097,15 +3070,14 @@ static int relay_close_trace_chunk(
        }
 
        if (close_command.is_set) {
-               chunk_status = lttng_trace_chunk_set_close_command(
-                               chunk, close_command.value);
+               chunk_status = lttng_trace_chunk_set_close_command(chunk, close_command.value);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        reply_code = LTTNG_ERR_INVALID;
                        goto end_unlock_session;
                }
        }
-       chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
+       chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, nullptr);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ERR("Failed to get chunk name");
                ret = -1;
@@ -3114,12 +3086,12 @@ static int relay_close_trace_chunk(
        }
        if (!session->has_rotated && !session->snapshot) {
                ret = lttng_strncpy(closed_trace_chunk_path,
-                               session->output_path,
-                               sizeof(closed_trace_chunk_path));
+                                   session->output_path,
+                                   sizeof(closed_trace_chunk_path));
                if (ret) {
                        ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
-                                       strlen(session->output_path),
-                                       sizeof(closed_trace_chunk_path));
+                           strlen(session->output_path),
+                           sizeof(closed_trace_chunk_path));
                        reply_code = LTTNG_ERR_NOMEM;
                        ret = -1;
                        goto end_unlock_session;
@@ -3127,15 +3099,16 @@ static int relay_close_trace_chunk(
        } else {
                if (session->snapshot) {
                        ret = snprintf(closed_trace_chunk_path,
-                                       sizeof(closed_trace_chunk_path),
-                                       "%s/%s", session->output_path,
-                                       chunk_name);
+                                      sizeof(closed_trace_chunk_path),
+                                      "%s/%s",
+                                      session->output_path,
+                                      chunk_name);
                } else {
                        ret = snprintf(closed_trace_chunk_path,
-                                       sizeof(closed_trace_chunk_path),
-                                       "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
-                                       "/%s",
-                                       session->output_path, chunk_name);
+                                      sizeof(closed_trace_chunk_path),
+                                      "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
+                                      session->output_path,
+                                      chunk_name);
                }
                if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
                        ERR("Failed to format closed trace chunk resulting path");
@@ -3145,7 +3118,7 @@ static int relay_close_trace_chunk(
                }
        }
        if (close_command.is_set &&
-                       close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
+           close_command.value == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
                session->has_rotated = true;
        }
        DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
@@ -3167,39 +3140,36 @@ static int relay_close_trace_chunk(
                 * the last stream releases its reference to it.
                 */
                lttng_trace_chunk_put(session->current_trace_chunk);
-               session->current_trace_chunk = NULL;
+               session->current_trace_chunk = nullptr;
        }
        lttng_trace_chunk_put(session->pending_closure_trace_chunk);
-       session->pending_closure_trace_chunk = NULL;
+       session->pending_closure_trace_chunk = nullptr;
 end_unlock_session:
        pthread_mutex_unlock(&session->lock);
 
 end:
        reply.generic.ret_code = htobe32((uint32_t) reply_code);
        reply.path_length = htobe32((uint32_t) path_length);
-       buf_ret = lttng_dynamic_buffer_append(
-                       &reply_payload, &reply, sizeof(reply));
+       buf_ret = lttng_dynamic_buffer_append(&reply_payload, &reply, sizeof(reply));
        if (buf_ret) {
                ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
                goto end_no_reply;
        }
 
        if (reply_code == LTTNG_OK) {
-               buf_ret = lttng_dynamic_buffer_append(&reply_payload,
-                               closed_trace_chunk_path, path_length);
+               buf_ret = lttng_dynamic_buffer_append(
+                       &reply_payload, closed_trace_chunk_path, path_length);
                if (buf_ret) {
                        ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
                        goto end_no_reply;
                }
        }
 
-       send_ret = conn->sock->ops->sendmsg(conn->sock,
-                       reply_payload.data,
-                       reply_payload.size,
-                       0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data, reply_payload.size, 0);
        if (send_ret < reply_payload.size) {
                ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
-                               reply_payload.size, send_ret);
+                   reply_payload.size,
+                   send_ret);
                ret = -1;
                goto end_no_reply;
        }
@@ -3212,10 +3182,10 @@ end_no_reply:
 /*
  * relay_trace_chunk_exists: check if a trace chunk exists
  */
-static int relay_trace_chunk_exists(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr
+                                   __attribute__((unused)),
+                                   struct relay_connection *conn,
+                                   const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        ssize_t send_ret;
@@ -3249,24 +3219,23 @@ static int relay_trace_chunk_exists(
        msg = (typeof(msg)) header_view.data;
        chunk_id = be64toh(msg->chunk_id);
 
-       ret = sessiond_trace_chunk_registry_chunk_exists(
-                       sessiond_trace_chunk_registry,
-                       conn->session->sessiond_uuid,
-                       conn->session->id,
-                       chunk_id, &chunk_exists);
+       ret = sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry,
+                                                        conn->session->sessiond_uuid,
+                                                        conn->session->id,
+                                                        chunk_id,
+                                                        &chunk_exists);
        /*
         * If ret is not 0, send the reply and report the error to the caller.
         * It is a protocol (or internal) error and the session/connection
         * should be torn down.
         */
-       reply.generic.ret_code = htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
+       reply.generic.ret_code =
+               htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
        reply.trace_chunk_exists = ret == 0 ? chunk_exists : 0;
 
-       send_ret = conn->sock->ops->sendmsg(
-                       conn->sock, &reply, sizeof(reply), 0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 end_no_reply:
@@ -3276,10 +3245,10 @@ end_no_reply:
 /*
  * relay_get_configuration: query whether feature is available
  */
-static int relay_get_configuration(
-               const struct lttcomm_relayd_hdr *recv_hdr __attribute__((unused)),
-               struct relay_connection *conn,
-               const struct lttng_buffer_view *payload)
+static int relay_get_configuration(const struct lttcomm_relayd_hdr *recv_hdr
+                                  __attribute__((unused)),
+                                  struct relay_connection *conn,
+                                  const struct lttng_buffer_view *payload)
 {
        int ret = 0;
        ssize_t send_ret;
@@ -3309,14 +3278,13 @@ static int relay_get_configuration(
        }
        ret = 0;
 reply:
-       reply.generic.ret_code = htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
+       reply.generic.ret_code =
+               htobe32((uint32_t) (ret == 0 ? LTTNG_OK : LTTNG_ERR_INVALID_PROTOCOL));
        reply.relayd_configuration_flags = htobe64(result_flags);
 
-       send_ret = conn->sock->ops->sendmsg(
-                       conn->sock, &reply, sizeof(reply), 0);
+       send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
        if (send_ret < (ssize_t) sizeof(reply)) {
-               ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
-                               send_ret);
+               ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret);
                ret = -1;
        }
 end_no_reply:
@@ -3324,14 +3292,14 @@ end_no_reply:
 }
 
 static int relay_process_control_command(struct relay_connection *conn,
-               const struct lttcomm_relayd_hdr *header,
-               const struct lttng_buffer_view *payload)
+                                        const struct lttcomm_relayd_hdr *header,
+                                        const struct lttng_buffer_view *payload)
 {
        int ret = 0;
 
        DBG3("Processing \"%s\" command for socket %i",
-                       lttcomm_relayd_command_str((lttcomm_relayd_command) header->cmd),
-                       conn->sock->fd);
+            lttcomm_relayd_command_str((lttcomm_relayd_command) header->cmd),
+            conn->sock->fd);
        switch (header->cmd) {
        case RELAYD_CREATE_SESSION:
                ret = relay_create_session(header, conn, payload);
@@ -3399,15 +3367,14 @@ end:
        return ret;
 }
 
-static enum relay_connection_status relay_process_control_receive_payload(
-               struct relay_connection *conn)
+static enum relay_connection_status
+relay_process_control_receive_payload(struct relay_connection *conn)
 {
        int ret = 0;
        enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
-       struct lttng_dynamic_buffer *reception_buffer =
-                       &conn->protocol.ctrl.reception_buffer;
+       struct lttng_dynamic_buffer *reception_buffer = &conn->protocol.ctrl.reception_buffer;
        struct ctrl_connection_state_receive_payload *state =
-                       &conn->protocol.ctrl.state.receive_payload;
+               &conn->protocol.ctrl.state.receive_payload;
        struct lttng_buffer_view payload_view;
 
        if (state->left_to_receive == 0) {
@@ -3416,15 +3383,15 @@ static enum relay_connection_status relay_process_control_receive_payload(
        }
 
        ret = conn->sock->ops->recvmsg(conn->sock,
-                       reception_buffer->data + state->received,
-                       state->left_to_receive, MSG_DONTWAIT);
+                                      reception_buffer->data + state->received,
+                                      state->left_to_receive,
+                                      MSG_DONTWAIT);
        if (ret < 0) {
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_LOGICAL_OP
                if (errno != EAGAIN && errno != EWOULDBLOCK) {
-               DIAGNOSTIC_POP
-                       PERROR("Unable to receive command payload on sock %d",
-                                       conn->sock->fd);
+                       DIAGNOSTIC_POP
+                       PERROR("Unable to receive command payload on sock %d", conn->sock->fd);
                        status = RELAY_CONNECTION_STATUS_ERROR;
                }
                goto end;
@@ -3445,15 +3412,18 @@ static enum relay_connection_status relay_process_control_receive_payload(
                 * Can't transition to the protocol's next state, wait to
                 * receive the rest of the header.
                 */
-               DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
-                               state->received, state->left_to_receive,
-                               conn->sock->fd);
+               DBG3("Partial reception of control connection protocol payload (received %" PRIu64
+                    " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
+                    state->received,
+                    state->left_to_receive,
+                    conn->sock->fd);
                goto end;
        }
 
 reception_complete:
        DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
-                       conn->sock->fd, state->received);
+           conn->sock->fd,
+           state->received);
        /*
         * The payload required to process the command has been received.
         * A view to the reception buffer is forwarded to the various
@@ -3461,10 +3431,8 @@ reception_complete:
         *
         * Commands are responsible for sending their reply to the peer.
         */
-       payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
-                       0, -1);
-       ret = relay_process_control_command(conn,
-                       &state->header, &payload_view);
+       payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer, 0, -1);
+       ret = relay_process_control_command(conn, &state->header, &payload_view);
        if (ret < 0) {
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end;
@@ -3478,29 +3446,29 @@ end:
        return status;
 }
 
-static enum relay_connection_status relay_process_control_receive_header(
-               struct relay_connection *conn)
+static enum relay_connection_status
+relay_process_control_receive_header(struct relay_connection *conn)
 {
        int ret = 0;
        enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
        struct lttcomm_relayd_hdr header;
-       struct lttng_dynamic_buffer *reception_buffer =
-                       &conn->protocol.ctrl.reception_buffer;
+       struct lttng_dynamic_buffer *reception_buffer = &conn->protocol.ctrl.reception_buffer;
        struct ctrl_connection_state_receive_header *state =
-                       &conn->protocol.ctrl.state.receive_header;
+               &conn->protocol.ctrl.state.receive_header;
 
        LTTNG_ASSERT(state->left_to_receive != 0);
 
        ret = conn->sock->ops->recvmsg(conn->sock,
-                       reception_buffer->data + state->received,
-                       state->left_to_receive, MSG_DONTWAIT);
+                                      reception_buffer->data + state->received,
+                                      state->left_to_receive,
+                                      MSG_DONTWAIT);
        if (ret < 0) {
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_LOGICAL_OP
                if (errno != EAGAIN && errno != EWOULDBLOCK) {
-               DIAGNOSTIC_POP
+                       DIAGNOSTIC_POP
                        PERROR("Unable to receive control command header on sock %d",
-                                       conn->sock->fd);
+                              conn->sock->fd);
                        status = RELAY_CONNECTION_STATUS_ERROR;
                }
                goto end;
@@ -3521,39 +3489,41 @@ static enum relay_connection_status relay_process_control_receive_header(
                 * Can't transition to the protocol's next state, wait to
                 * receive the rest of the header.
                 */
-               DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
-                               state->received, state->left_to_receive,
-                               conn->sock->fd);
+               DBG3("Partial reception of control connection protocol header (received %" PRIu64
+                    " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
+                    state->received,
+                    state->left_to_receive,
+                    conn->sock->fd);
                goto end;
        }
 
        /* Transition to next state: receiving the command's payload. */
-       conn->protocol.ctrl.state_id =
-                       CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
+       conn->protocol.ctrl.state_id = CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
        memcpy(&header, reception_buffer->data, sizeof(header));
        header.circuit_id = be64toh(header.circuit_id);
        header.data_size = be64toh(header.data_size);
        header.cmd = be32toh(header.cmd);
        header.cmd_version = be32toh(header.cmd_version);
-       memcpy(&conn->protocol.ctrl.state.receive_payload.header,
-                       &header, sizeof(header));
+       memcpy(&conn->protocol.ctrl.state.receive_payload.header, &header, sizeof(header));
 
-       DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
-                       conn->sock->fd, lttcomm_relayd_command_str((enum lttcomm_relayd_command) header.cmd),
-                       header.cmd_version, header.data_size);
+       DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
+           ", payload size = %" PRIu64 " bytes",
+           conn->sock->fd,
+           lttcomm_relayd_command_str((enum lttcomm_relayd_command) header.cmd),
+           header.cmd_version,
+           header.data_size);
 
        if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
-               ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
-                               header.data_size);
+               ERR("Command header indicates a payload (%" PRIu64
+                   " bytes) that exceeds the maximal payload size allowed on a control connection.",
+                   header.data_size);
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end;
        }
 
-       conn->protocol.ctrl.state.receive_payload.left_to_receive =
-                       header.data_size;
+       conn->protocol.ctrl.state.receive_payload.left_to_receive = header.data_size;
        conn->protocol.ctrl.state.receive_payload.received = 0;
-       ret = lttng_dynamic_buffer_set_size(reception_buffer,
-                       header.data_size);
+       ret = lttng_dynamic_buffer_set_size(reception_buffer, header.data_size);
        if (ret) {
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end;
@@ -3573,8 +3543,7 @@ end:
 /*
  * Process the commands received on the control socket
  */
-static enum relay_connection_status relay_process_control(
-               struct relay_connection *conn)
+static enum relay_connection_status relay_process_control(struct relay_connection *conn)
 {
        enum relay_connection_status status;
 
@@ -3593,26 +3562,26 @@ static enum relay_connection_status relay_process_control(
        return status;
 }
 
-static enum relay_connection_status relay_process_data_receive_header(
-               struct relay_connection *conn)
+static enum relay_connection_status relay_process_data_receive_header(struct relay_connection *conn)
 {
        int ret;
        enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
        struct data_connection_state_receive_header *state =
-                       &conn->protocol.data.state.receive_header;
+               &conn->protocol.data.state.receive_header;
        struct lttcomm_relayd_data_hdr header;
        struct relay_stream *stream;
 
        LTTNG_ASSERT(state->left_to_receive != 0);
 
        ret = conn->sock->ops->recvmsg(conn->sock,
-                       state->header_reception_buffer + state->received,
-                       state->left_to_receive, MSG_DONTWAIT);
+                                      state->header_reception_buffer + state->received,
+                                      state->left_to_receive,
+                                      MSG_DONTWAIT);
        if (ret < 0) {
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_LOGICAL_OP
                if (errno != EAGAIN && errno != EWOULDBLOCK) {
-               DIAGNOSTIC_POP
+                       DIAGNOSTIC_POP
                        PERROR("Unable to receive data header on sock %d", conn->sock->fd);
                        status = RELAY_CONNECTION_STATUS_ERROR;
                }
@@ -3635,9 +3604,11 @@ static enum relay_connection_status relay_process_data_receive_header(
                 * Can't transition to the protocol's next state, wait to
                 * receive the rest of the header.
                 */
-               DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
-                               state->received, state->left_to_receive,
-                               conn->sock->fd);
+               DBG3("Partial reception of data connection header (received %" PRIu64
+                    " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
+                    state->received,
+                    state->left_to_receive,
+                    conn->sock->fd);
                goto end;
        }
 
@@ -3652,20 +3623,24 @@ static enum relay_connection_status relay_process_data_receive_header(
        header.padding_size = be32toh(header.padding_size);
        memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
 
-       conn->protocol.data.state.receive_payload.left_to_receive =
-                       header.data_size;
+       conn->protocol.data.state.receive_payload.left_to_receive = header.data_size;
        conn->protocol.data.state.receive_payload.received = 0;
        conn->protocol.data.state.receive_payload.rotate_index = false;
 
-       DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
-                       conn->sock->fd, header.circuit_id,
-                       header.stream_id, header.data_size,
-                       header.net_seq_num, header.padding_size);
+       DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
+           ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64
+           ", padding_size = %" PRIu32,
+           conn->sock->fd,
+           header.circuit_id,
+           header.stream_id,
+           header.data_size,
+           header.net_seq_num,
+           header.padding_size);
 
        stream = stream_get_by_id(header.stream_id);
        if (!stream) {
                DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
-                               header.stream_id);
+                   header.stream_id);
                /* Protocol error. */
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end;
@@ -3673,8 +3648,8 @@ static enum relay_connection_status relay_process_data_receive_header(
 
        pthread_mutex_lock(&stream->lock);
        /* Prepare stream for the reception of a new packet. */
-       ret = stream_init_packet(stream, header.data_size,
-                       &conn->protocol.data.state.receive_payload.rotate_index);
+       ret = stream_init_packet(
+               stream, header.data_size, &conn->protocol.data.state.receive_payload.rotate_index);
        pthread_mutex_unlock(&stream->lock);
        if (ret) {
                ERR("Failed to rotate stream output file");
@@ -3688,14 +3663,14 @@ end:
        return status;
 }
 
-static enum relay_connection_status relay_process_data_receive_payload(
-               struct relay_connection *conn)
+static enum relay_connection_status
+relay_process_data_receive_payload(struct relay_connection *conn)
 {
        int ret;
        enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
        struct relay_stream *stream;
        struct data_connection_state_receive_payload *state =
-                       &conn->protocol.data.state.receive_payload;
+               &conn->protocol.data.state.receive_payload;
        const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
        char data_buffer[chunk_size];
        bool partial_recv = false;
@@ -3703,15 +3678,18 @@ static enum relay_connection_status relay_process_data_receive_payload(
        uint64_t left_to_receive = state->left_to_receive;
        struct relay_session *session;
 
-       DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
-                       state->header.stream_id, state->header.net_seq_num,
-                       state->received, left_to_receive);
+       DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64
+            " bytes received, %" PRIu64 " bytes left to receive",
+            state->header.stream_id,
+            state->header.net_seq_num,
+            state->received,
+            left_to_receive);
 
        stream = stream_get_by_id(state->header.stream_id);
        if (!stream) {
                /* Protocol error. */
                ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
-                               state->header.stream_id);
+                   state->header.stream_id);
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end;
        }
@@ -3736,13 +3714,12 @@ static enum relay_connection_status relay_process_data_receive_payload(
                size_t recv_size = std::min<uint64_t>(left_to_receive, chunk_size);
                struct lttng_buffer_view packet_chunk;
 
-               ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
-                               recv_size, MSG_DONTWAIT);
+               ret = conn->sock->ops->recvmsg(conn->sock, data_buffer, recv_size, MSG_DONTWAIT);
                if (ret < 0) {
                        DIAGNOSTIC_PUSH
                        DIAGNOSTIC_IGNORE_LOGICAL_OP
                        if (errno != EAGAIN && errno != EWOULDBLOCK) {
-                       DIAGNOSTIC_POP
+                               DIAGNOSTIC_POP
                                PERROR("Socket %d error", conn->sock->fd);
                                status = RELAY_CONNECTION_STATUS_ERROR;
                        }
@@ -3750,7 +3727,7 @@ static enum relay_connection_status relay_process_data_receive_payload(
                } else if (ret == 0) {
                        /* No more data ready to be consumed on socket. */
                        DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
-                                       state->header.stream_id);
+                            state->header.stream_id);
                        status = RELAY_CONNECTION_STATUS_CLOSED;
                        break;
                } else if (ret < (int) recv_size) {
@@ -3762,8 +3739,7 @@ static enum relay_connection_status relay_process_data_receive_payload(
                        recv_size = ret;
                }
 
-               packet_chunk = lttng_buffer_view_init(data_buffer,
-                               0, recv_size);
+               packet_chunk = lttng_buffer_view_init(data_buffer, 0, recv_size);
                LTTNG_ASSERT(packet_chunk.data);
 
                ret = stream_write(stream, &packet_chunk, 0);
@@ -3783,26 +3759,32 @@ static enum relay_connection_status relay_process_data_receive_payload(
                 * Did not receive all the data expected, wait for more data to
                 * become available on the socket.
                 */
-               DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64 " bytes received, %" PRIu64 " bytes left to receive",
-                               state->header.stream_id, state->received,
-                               state->left_to_receive);
+               DBG3("Partial receive on data connection of stream id %" PRIu64 ", %" PRIu64
+                    " bytes received, %" PRIu64 " bytes left to receive",
+                    state->header.stream_id,
+                    state->received,
+                    state->left_to_receive);
                goto end_stream_unlock;
        }
 
-       ret = stream_write(stream, NULL, state->header.padding_size);
+       ret = stream_write(stream, nullptr, state->header.padding_size);
        if (ret) {
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end_stream_unlock;
        }
 
        if (session_streams_have_index(session)) {
-               ret = stream_update_index(stream, state->header.net_seq_num,
-                               state->rotate_index, &index_flushed,
-                               state->header.data_size + state->header.padding_size);
+               ret = stream_update_index(stream,
+                                         state->header.net_seq_num,
+                                         state->rotate_index,
+                                         &index_flushed,
+                                         state->header.data_size + state->header.padding_size);
                if (ret < 0) {
-                       ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64 " ret %d",
-                                       stream->stream_handle,
-                                       state->header.net_seq_num, ret);
+                       ERR("Failed to update index: stream %" PRIu64 " net_seq_num %" PRIu64
+                           " ret %d",
+                           stream->stream_handle,
+                           state->header.net_seq_num,
+                           ret);
                        status = RELAY_CONNECTION_STATUS_ERROR;
                        goto end_stream_unlock;
                }
@@ -3812,9 +3794,10 @@ static enum relay_connection_status relay_process_data_receive_payload(
                new_stream = true;
        }
 
-       ret = stream_complete_packet(stream, state->header.data_size +
-                       state->header.padding_size, state->header.net_seq_num,
-                       index_flushed);
+       ret = stream_complete_packet(stream,
+                                    state->header.data_size + state->header.padding_size,
+                                    state->header.net_seq_num,
+                                    index_flushed);
        if (ret) {
                status = RELAY_CONNECTION_STATUS_ERROR;
                goto end_stream_unlock;
@@ -3826,7 +3809,7 @@ static enum relay_connection_status relay_process_data_receive_payload(
         * the new state. Don't use it beyond this point.
         */
        connection_reset_protocol_state(conn);
-       state = NULL;
+       state = nullptr;
 
 end_stream_unlock:
        close_requested = stream->close_requested;
@@ -3849,8 +3832,7 @@ end:
 /*
  * relay_process_data: Process the data received on the data socket
  */
-static enum relay_connection_status relay_process_data(
-               struct relay_connection *conn)
+static enum relay_connection_status relay_process_data(struct relay_connection *conn)
 {
        enum relay_connection_status status;
 
@@ -3875,15 +3857,16 @@ static void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollf
 
        (void) lttng_poll_del(events, pollfd);
 
-       ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
-                       fd_tracker_util_close_fd, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(
+               the_fd_tracker, &pollfd, 1, fd_tracker_util_close_fd, nullptr);
        if (ret < 0) {
                ERR("Closing pollfd %d", pollfd);
        }
 }
 
 static void relay_thread_close_connection(struct lttng_poll_event *events,
-               int pollfd, struct relay_connection *conn)
+                                         int pollfd,
+                                         struct relay_connection *conn)
 {
        const char *type_str;
 
@@ -3918,7 +3901,7 @@ static void *relay_thread_worker(void *data __attribute__((unused)))
        struct lttng_poll_event events;
        struct lttng_ht *relay_connections_ht;
        struct lttng_ht_iter iter;
-       struct relay_connection *destroy_conn = NULL;
+       struct relay_connection *destroy_conn = nullptr;
 
        DBG("[thread] Relay worker started");
 
@@ -3949,7 +3932,7 @@ static void *relay_thread_worker(void *data __attribute__((unused)))
        }
 
 restart:
-       while (1) {
+       while (true) {
                int idx = -1, i, seen_control = 0, last_notdel_data_fd = -1;
 
                health_code_update();
@@ -3978,14 +3961,14 @@ restart:
                 */
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       uint32_t revents = LTTNG_POLL_GETEV(&events, i);
-                       int pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       ret = check_thread_quit_pipe(pollfd, revents);
-                       if (ret) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (relayd_is_thread_quit_pipe(pollfd)) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -3995,13 +3978,15 @@ restart:
                                if (revents & LPOLLIN) {
                                        struct relay_connection *conn;
 
-                                       ret = lttng_read(relay_conn_pipe[0], &conn, sizeof(conn));
+                                       ret = lttng_read(relay_conn_pipe[0],
+                                                        &conn,
+                                                        sizeof(conn)); /* NOLINT sizeof used on a
+                                                                          pointer. */
                                        if (ret < 0) {
                                                goto error;
                                        }
-                                       ret = lttng_poll_add(&events,
-                                                       conn->sock->fd,
-                                                       LPOLLIN | LPOLLRDHUP);
+                                       ret = lttng_poll_add(
+                                               &events, conn->sock->fd, LPOLLIN | LPOLLRDHUP);
                                        if (ret) {
                                                ERR("Failed to add new connection file descriptor to poll set");
                                                goto error;
@@ -4012,7 +3997,9 @@ restart:
                                        ERR("Relay connection pipe error");
                                        goto error;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                        } else {
@@ -4025,9 +4012,9 @@ restart:
                                if (ctrl_conn->type == RELAY_DATA) {
                                        if (revents & LPOLLIN) {
                                                /*
-                                                * Flag the last seen data fd not deleted. It will be
-                                                * used as the last seen fd if any fd gets deleted in
-                                                * this first loop.
+                                                * Flag the last seen data fd not deleted. It will
+                                                * be used as the last seen fd if any fd gets
+                                                * deleted in this first loop.
                                                 */
                                                last_notdel_data_fd = pollfd;
                                        }
@@ -4041,40 +4028,39 @@ restart:
                                        status = relay_process_control(ctrl_conn);
                                        if (status != RELAY_CONNECTION_STATUS_OK) {
                                                /*
-                                                * On socket error flag the session as aborted to force
-                                                * the cleanup of its stream otherwise it can leak
-                                                * during the lifetime of the relayd.
+                                                * On socket error flag the session as aborted to
+                                                * force the cleanup of its stream otherwise it can
+                                                * leak during the lifetime of the relayd.
                                                 *
                                                 * This prevents situations in which streams can be
                                                 * left opened because an index was received, the
                                                 * control connection is closed, and the data
-                                                * connection is closed (uncleanly) before the packet's
-                                                * data provided.
+                                                * connection is closed (uncleanly) before the
+                                                * packet's data provided.
                                                 *
-                                                * Since the control connection encountered an error,
-                                                * it is okay to be conservative and close the
-                                                * session right now as we can't rely on the protocol
-                                                * being respected anymore.
+                                                * Since the control connection encountered an
+                                                * error, it is okay to be conservative and close
+                                                * the session right now as we can't rely on the
+                                                * protocol being respected anymore.
                                                 */
                                                if (status == RELAY_CONNECTION_STATUS_ERROR) {
                                                        session_abort(ctrl_conn->session);
                                                }
 
                                                /* Clear the connection on error or close. */
-                                               relay_thread_close_connection(&events,
-                                                               pollfd,
-                                                               ctrl_conn);
+                                               relay_thread_close_connection(
+                                                       &events, pollfd, ctrl_conn);
                                        }
                                        seen_control = 1;
                                } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-                                       relay_thread_close_connection(&events,
-                                                       pollfd, ctrl_conn);
+                                       relay_thread_close_connection(&events, pollfd, ctrl_conn);
                                        if (last_seen_data_fd == pollfd) {
                                                last_seen_data_fd = last_notdel_data_fd;
                                        }
                                } else {
                                        ERR("Unexpected poll events %u for control sock %d",
-                                                       revents, pollfd);
+                                           revents,
+                                           pollfd);
                                        connection_put(ctrl_conn);
                                        goto error;
                                }
@@ -4158,8 +4144,7 @@ restart:
                                        if (status == RELAY_CONNECTION_STATUS_ERROR) {
                                                session_abort(data_conn->session);
                                        }
-                                       relay_thread_close_connection(&events, pollfd,
-                                                       data_conn);
+                                       relay_thread_close_connection(&events, pollfd, data_conn);
                                        /*
                                         * Every goto restart call sets the last seen fd where
                                         * here we don't really care since we gracefully
@@ -4172,11 +4157,9 @@ restart:
                                        goto restart;
                                }
                        } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-                               relay_thread_close_connection(&events, pollfd,
-                                               data_conn);
+                               relay_thread_close_connection(&events, pollfd, data_conn);
                        } else {
-                               ERR("Unknown poll events %u for data sock %d",
-                                               revents, pollfd);
+                               ERR("Unknown poll events %u for data sock %d", revents, pollfd);
                        }
                put_data_connection:
                        connection_put(data_conn);
@@ -4190,30 +4173,30 @@ restart:
 exit:
 error:
        /* Cleanup remaining connection object. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(relay_connections_ht->ht, &iter.iter,
-                       destroy_conn,
-                       sock_n.node) {
-               health_code_update();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               session_abort(destroy_conn->session);
+               cds_lfht_for_each_entry (
+                       relay_connections_ht->ht, &iter.iter, destroy_conn, sock_n.node) {
+                       health_code_update();
 
-               /*
-                * No need to grab another ref, because we own
-                * destroy_conn.
-                */
-               relay_thread_close_connection(&events, destroy_conn->sock->fd,
-                               destroy_conn);
+                       session_abort(destroy_conn->session);
+
+                       /*
+                        * No need to grab another ref, because we own
+                        * destroy_conn.
+                        */
+                       relay_thread_close_connection(
+                               &events, destroy_conn->sock->fd, destroy_conn);
+               }
        }
-       rcu_read_unlock();
 
        (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
 error_poll_create:
        lttng_ht_destroy(relay_connections_ht);
 relay_connections_ht_error:
        /* Close relay conn pipes */
-       (void) fd_tracker_util_pipe_close(the_fd_tracker,
-                       relay_conn_pipe);
+       (void) fd_tracker_util_pipe_close(the_fd_tracker, relay_conn_pipe);
        if (err) {
                DBG("Thread exited with error");
        }
@@ -4226,17 +4209,17 @@ error_testpoint:
        health_unregister(health_relayd);
        rcu_unregister_thread();
        lttng_relay_stop_threads();
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Create the relay command pipe to wake thread_manage_apps.
  * Closed in cleanup().
  */
-static int create_relay_conn_pipe(void)
+static int create_relay_conn_pipe()
 {
-       return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
-                       "Relayd connection pipe", relay_conn_pipe);
+       return fd_tracker_util_pipe_open_cloexec(
+               the_fd_tracker, "Relayd connection pipe", relay_conn_pipe);
 }
 
 static int stdio_open(void *data __attribute__((unused)), int *fds)
@@ -4246,13 +4229,12 @@ static int stdio_open(void *data __attribute__((unused)), int *fds)
        return 0;
 }
 
-static int track_stdio(void)
+static int track_stdio()
 {
        int fds[2];
        const char *names[] = { "stdout", "stderr" };
 
-       return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds,
-                       names, 2, stdio_open, NULL);
+       return fd_tracker_open_unsuspendable_fd(the_fd_tracker, fds, names, 2, stdio_open, nullptr);
 }
 
 /*
@@ -4263,7 +4245,7 @@ int main(int argc, char **argv)
        bool thread_is_rcu_registered = false;
        int ret = 0, retval = 0;
        void *status;
-       char *unlinked_file_directory_path = NULL, *output_path = NULL;
+       char *unlinked_file_directory_path = nullptr, *output_path = nullptr;
 
        /* Parse environment variables */
        ret = parse_env_options();
@@ -4311,8 +4293,7 @@ int main(int argc, char **argv)
                        goto exit_options;
                }
 
-               ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG,
-                               -1, -1);
+               ret = utils_mkdir_recursive(opt_output_path, S_IRWXU | S_IRWXG, -1, -1);
                if (ret < 0) {
                        ERR("Unable to create %s", opt_output_path);
                        retval = -1;
@@ -4322,8 +4303,7 @@ int main(int argc, char **argv)
 
        /* Daemonize */
        if (opt_daemon || opt_background) {
-               ret = lttng_daemonize(&child_ppid, &recv_child_signal,
-                       !opt_background);
+               ret = lttng_daemonize(&child_ppid, &recv_child_signal, !opt_background);
                if (ret < 0) {
                        retval = -1;
                        goto exit_options;
@@ -4360,16 +4340,17 @@ int main(int argc, char **argv)
                retval = -1;
                goto exit_options;
        }
-       ret = asprintf(&unlinked_file_directory_path, "%s/%s", output_path,
-                       DEFAULT_UNLINKED_FILES_DIRECTORY);
+       ret = asprintf(&unlinked_file_directory_path,
+                      "%s/%s",
+                      output_path,
+                      DEFAULT_UNLINKED_FILES_DIRECTORY);
        free(output_path);
        if (ret < 0) {
                ERR("Failed to format unlinked file directory path");
                retval = -1;
                goto exit_options;
        }
-       the_fd_tracker = fd_tracker_create(
-                       unlinked_file_directory_path, lttng_opt_fd_pool_size);
+       the_fd_tracker = fd_tracker_create(unlinked_file_directory_path, lttng_opt_fd_pool_size);
        free(unlinked_file_directory_path);
        if (!the_fd_tracker) {
                retval = -1;
@@ -4391,7 +4372,7 @@ int main(int argc, char **argv)
        }
 
        /* Create thread quit pipe */
-       if (init_thread_quit_pipe()) {
+       if (relayd_init_thread_quit_pipe()) {
                retval = -1;
                goto exit_options;
        }
@@ -4437,8 +4418,10 @@ int main(int argc, char **argv)
        }
 
        /* Create thread to manage the client socket */
-       ret = pthread_create(&health_thread, default_pthread_attr(),
-                       thread_manage_health_relayd, (void *) NULL);
+       ret = pthread_create(&health_thread,
+                            default_pthread_attr(),
+                            thread_manage_health_relayd,
+                            (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create health");
@@ -4447,8 +4430,10 @@ int main(int argc, char **argv)
        }
 
        /* Setup the dispatcher thread */
-       ret = pthread_create(&dispatcher_thread, default_pthread_attr(),
-                       relay_thread_dispatcher, (void *) NULL);
+       ret = pthread_create(&dispatcher_thread,
+                            default_pthread_attr(),
+                            relay_thread_dispatcher,
+                            (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create dispatcher");
@@ -4457,8 +4442,7 @@ int main(int argc, char **argv)
        }
 
        /* Setup the worker thread */
-       ret = pthread_create(&worker_thread, default_pthread_attr(),
-                       relay_thread_worker, NULL);
+       ret = pthread_create(&worker_thread, default_pthread_attr(), relay_thread_worker, nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create worker");
@@ -4467,8 +4451,8 @@ int main(int argc, char **argv)
        }
 
        /* Setup the listener thread */
-       ret = pthread_create(&listener_thread, default_pthread_attr(),
-                       relay_thread_listener, (void *) NULL);
+       ret = pthread_create(
+               &listener_thread, default_pthread_attr(), relay_thread_listener, (void *) nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_create listener");
index 6e29fbc741afd1efe32723f7342f8cc809fa9a3c..8ac4a510dc263f552e2b584256b328986c0e8aad 100644 (file)
@@ -8,23 +8,24 @@
  */
 
 #define _LGPL_SOURCE
+#include "ctf-trace.hpp"
+#include "lttng-relayd.hpp"
+#include "session.hpp"
+#include "sessiond-trace-chunks.hpp"
+#include "stream.hpp"
+#include "utils.hpp"
+
 #include <common/common.hpp>
 #include <common/compat/path.hpp>
+#include <common/defaults.hpp>
 #include <common/fd-tracker/utils.hpp>
 #include <common/time.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
 #include <common/uuid.hpp>
-#include <urcu/rculist.h>
 
 #include <sys/stat.h>
-
-#include "ctf-trace.hpp"
-#include "lttng-relayd.hpp"
-#include "session.hpp"
-#include "sessiond-trace-chunks.hpp"
-#include "stream.hpp"
-#include <common/defaults.hpp>
-#include "utils.hpp"
+#include <urcu/rculist.h>
 
 /* Global session id used in the session creation. */
 static uint64_t last_relay_session_id;
@@ -40,7 +41,7 @@ static int init_session_output_path_group_by_host(struct relay_session *session)
         * else
         *   hostname/base_path
         */
-       char *session_directory = NULL;
+       char *session_directory = nullptr;
        int ret = 0;
 
        if (session->output_path[0] != '\0') {
@@ -58,27 +59,27 @@ static int init_session_output_path_group_by_host(struct relay_session *session)
         * Otherwise, generate the path with session_name-<timestamp>.
         */
        if (session->base_path[0] != '\0') {
-               ret = asprintf(&session_directory, "%s/%s", session->hostname,
-                               session->base_path);
+               ret = asprintf(&session_directory, "%s/%s", session->hostname, session->base_path);
        } else if (session->session_name_contains_creation_time) {
-               ret = asprintf(&session_directory, "%s/%s", session->hostname,
-                               session->session_name);
+               ret = asprintf(
+                       &session_directory, "%s/%s", session->hostname, session->session_name);
        } else {
                char session_creation_datetime[DATETIME_STR_LEN];
 
-               ret = time_to_datetime_str(
-                               LTTNG_OPTIONAL_GET(session->creation_time),
-                               session_creation_datetime,
-                               sizeof(session_creation_datetime));
+               ret = time_to_datetime_str(LTTNG_OPTIONAL_GET(session->creation_time),
+                                          session_creation_datetime,
+                                          sizeof(session_creation_datetime));
                if (ret) {
                        ERR("Failed to format session creation timestamp while initializing session output directory handle");
                        ret = -1;
                        goto end;
                }
 
-               ret = asprintf(&session_directory, "%s/%s-%s",
-                               session->hostname, session->session_name,
-                               session_creation_datetime);
+               ret = asprintf(&session_directory,
+                              "%s/%s-%s",
+                              session->hostname,
+                              session->session_name,
+                              session_creation_datetime);
        }
        if (ret < 0) {
                PERROR("Failed to format session directory name");
@@ -98,8 +99,7 @@ end:
        return ret;
 }
 
-static int init_session_output_path_group_by_session(
-               struct relay_session *session)
+static int init_session_output_path_group_by_session(struct relay_session *session)
 {
        /*
         * session_directory:
@@ -111,7 +111,7 @@ static int init_session_output_path_group_by_session(
         * integral part of the name and how a user identify a session.
         */
        int ret = 0;
-       char *session_directory = NULL;
+       char *session_directory = nullptr;
        char creation_datetime[DATETIME_STR_LEN];
 
        if (session->output_path[0] != '\0') {
@@ -120,18 +120,21 @@ static int init_session_output_path_group_by_session(
        }
 
        ret = time_to_datetime_str(LTTNG_OPTIONAL_GET(session->creation_time),
-                       creation_datetime, sizeof(creation_datetime));
+                                  creation_datetime,
+                                  sizeof(creation_datetime));
        if (ret) {
                ERR("Failed to format session creation timestamp while initializing session output directory handle");
                ret = -1;
                goto end;
        }
 
-       ret = asprintf(&session_directory, "%s/%s-%s%s%s",
-                       session->session_name, session->hostname,
-                       creation_datetime,
-                       session->base_path[0] != '\0' ? "/" : "",
-                       session->base_path);
+       ret = asprintf(&session_directory,
+                      "%s/%s-%s%s%s",
+                      session->session_name,
+                      session->hostname,
+                      creation_datetime,
+                      session->base_path[0] != '\0' ? "/" : "",
+                      session->base_path);
        if (ret < 0) {
                PERROR("Failed to format session directory name");
                goto end;
@@ -171,16 +174,16 @@ static int init_session_output_path(struct relay_session *session)
        return ret;
 }
 
-static struct lttng_directory_handle *session_create_output_directory_handle(
-               struct relay_session *session)
+static struct lttng_directory_handle *
+session_create_output_directory_handle(struct relay_session *session)
 {
        int ret;
        /*
         * relayd_output_path/session_directory
         * e.g. /home/user/lttng-traces/hostname/session_name
         */
-       char *full_session_path = NULL;
-       struct lttng_directory_handle *handle = NULL;
+       char *full_session_path = nullptr;
+       struct lttng_directory_handle *handle = nullptr;
 
        pthread_mutex_lock(&session->lock);
        full_session_path = create_output_path(session->output_path);
@@ -188,11 +191,9 @@ static struct lttng_directory_handle *session_create_output_directory_handle(
                goto end;
        }
 
-       ret = utils_mkdir_recursive(
-                       full_session_path, S_IRWXU | S_IRWXG, -1, -1);
+       ret = utils_mkdir_recursive(full_session_path, S_IRWXU | S_IRWXG, -1, -1);
        if (ret) {
-               ERR("Failed to create session output path \"%s\"",
-                               full_session_path);
+               ERR("Failed to create session output path \"%s\"", full_session_path);
                goto end;
        }
 
@@ -206,7 +207,7 @@ end:
 static int session_set_anonymous_chunk(struct relay_session *session)
 {
        int ret = 0;
-       struct lttng_trace_chunk *chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr;
        enum lttng_trace_chunk_status status;
        struct lttng_directory_handle *output_directory;
 
@@ -234,7 +235,7 @@ static int session_set_anonymous_chunk(struct relay_session *session)
        }
 
        session->current_trace_chunk = chunk;
-       chunk = NULL;
+       chunk = nullptr;
 end:
        lttng_trace_chunk_put(chunk);
        lttng_directory_handle_put(output_directory);
@@ -260,12 +261,14 @@ static bool is_name_path_safe(const char *name)
        }
        /* Does not start with '.'. */
        if (name[0] == '.') {
-               WARN("Name \"%s\" is not allowed to be used in a path since it starts with '.'", name);
+               WARN("Name \"%s\" is not allowed to be used in a path since it starts with '.'",
+                    name);
                return false;
        }
        /* Does not contain a path-separator. */
        if (strchr(name, LTTNG_PATH_SEPARATOR)) {
-               WARN("Name \"%s\" is not allowed to be used in a path since it contains a path separator", name);
+               WARN("Name \"%s\" is not allowed to be used in a path since it contains a path separator",
+                    name);
                return false;
        }
 
@@ -278,19 +281,20 @@ static bool is_name_path_safe(const char *name)
  * Return allocated session or else NULL.
  */
 struct relay_session *session_create(const char *session_name,
-               const char *hostname, const char *base_path,
-               uint32_t live_timer,
-               bool snapshot,
-               const lttng_uuid& sessiond_uuid,
-               const uint64_t *id_sessiond,
-               const uint64_t *current_chunk_id,
-               const time_t *creation_time,
-               uint32_t major,
-               uint32_t minor,
-               bool session_name_contains_creation_time)
+                                    const char *hostname,
+                                    const char *base_path,
+                                    uint32_t live_timer,
+                                    bool snapshot,
+                                    const lttng_uuid& sessiond_uuid,
+                                    const uint64_t *id_sessiond,
+                                    const uint64_t *current_chunk_id,
+                                    const time_t *creation_time,
+                                    uint32_t major,
+                                    uint32_t minor,
+                                    bool session_name_contains_creation_time)
 {
        int ret;
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
 
        LTTNG_ASSERT(session_name);
        LTTNG_ASSERT(hostname);
@@ -305,8 +309,7 @@ struct relay_session *session_create(const char *session_name,
                goto error;
        }
        if (strstr(base_path, "../")) {
-               ERR("Invalid session base path walks up the path hierarchy: \"%s\"",
-                               base_path);
+               ERR("Invalid session base path walks up the path hierarchy: \"%s\"", base_path);
                goto error;
        }
 
@@ -323,35 +326,31 @@ struct relay_session *session_create(const char *session_name,
        lttng_ht_node_init_u64(&session->session_n, session->id);
        urcu_ref_init(&session->ref);
        CDS_INIT_LIST_HEAD(&session->recv_list);
-       pthread_mutex_init(&session->lock, NULL);
-       pthread_mutex_init(&session->recv_list_lock, NULL);
+       pthread_mutex_init(&session->lock, nullptr);
+       pthread_mutex_init(&session->recv_list_lock, nullptr);
 
-       if (lttng_strncpy(session->session_name, session_name,
-                       sizeof(session->session_name))) {
+       if (lttng_strncpy(session->session_name, session_name, sizeof(session->session_name))) {
                WARN("Session name exceeds maximal allowed length");
                goto error;
        }
-       if (lttng_strncpy(session->hostname, hostname,
-                       sizeof(session->hostname))) {
+       if (lttng_strncpy(session->hostname, hostname, sizeof(session->hostname))) {
                WARN("Hostname exceeds maximal allowed length");
                goto error;
        }
-       if (lttng_strncpy(session->base_path, base_path,
-                       sizeof(session->base_path))) {
+       if (lttng_strncpy(session->base_path, base_path, sizeof(session->base_path))) {
                WARN("Base path exceeds maximal allowed length");
                goto error;
        }
        if (creation_time) {
                LTTNG_OPTIONAL_SET(&session->creation_time, *creation_time);
        } else {
-               LTTNG_OPTIONAL_SET(&session->creation_time, time(NULL));
+               LTTNG_OPTIONAL_SET(&session->creation_time, time(nullptr));
                if (session->creation_time.value == (time_t) -1) {
                        PERROR("Failed to sample session creation time");
                        goto error;
                }
        }
-       session->session_name_contains_creation_time =
-                       session_name_contains_creation_time;
+       session->session_name_contains_creation_time = session_name_contains_creation_time;
 
        session->ctf_traces_ht = lttng_ht_new(0, LTTNG_HT_TYPE_STRING);
        if (!session->ctf_traces_ht) {
@@ -377,8 +376,8 @@ struct relay_session *session_create(const char *session_name,
                }
        }
 
-       ret = sessiond_trace_chunk_registry_session_created(
-                       sessiond_trace_chunk_registry, sessiond_uuid);
+       ret = sessiond_trace_chunk_registry_session_created(sessiond_trace_chunk_registry,
+                                                           sessiond_uuid);
        if (ret) {
                goto error;
        }
@@ -388,24 +387,24 @@ struct relay_session *session_create(const char *session_name,
                struct lttng_directory_handle *session_output_directory;
 
                session->current_trace_chunk =
-                               sessiond_trace_chunk_registry_get_chunk(
-                                       sessiond_trace_chunk_registry,
-                                       session->sessiond_uuid,
-                                       session->id_sessiond.value,
-                                       *current_chunk_id);
+                       sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry,
+                                                               session->sessiond_uuid,
+                                                               session->id_sessiond.value,
+                                                               *current_chunk_id);
                if (!session->current_trace_chunk) {
                        char uuid_str[LTTNG_UUID_STR_LEN];
 
                        lttng_uuid_to_str(sessiond_uuid, uuid_str);
-                       ERR("Could not find trace chunk: sessiond = {%s}, sessiond session id = %" PRIu64 ", trace chunk id = %" PRIu64,
-                                       uuid_str, *id_sessiond,
-                                       *current_chunk_id);
+                       ERR("Could not find trace chunk: sessiond = {%s}, sessiond session id = %" PRIu64
+                           ", trace chunk id = %" PRIu64,
+                           uuid_str,
+                           *id_sessiond,
+                           *current_chunk_id);
                        goto error;
                }
 
                chunk_status = lttng_trace_chunk_get_session_output_directory_handle(
-                               session->current_trace_chunk,
-                               &session_output_directory);
+                       session->current_trace_chunk, &session_output_directory);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        goto error;
                }
@@ -423,8 +422,7 @@ struct relay_session *session_create(const char *session_name,
                        goto error;
                }
        } else {
-               session->output_directory =
-                               session_create_output_directory_handle(session);
+               session->output_directory = session_create_output_directory_handle(session);
                if (!session->output_directory) {
                        goto error;
                }
@@ -435,7 +433,7 @@ struct relay_session *session_create(const char *session_name,
 
 error:
        session_put(session);
-       return NULL;
+       return nullptr;
 }
 
 /* Should be called with RCU read-side lock held. */
@@ -453,11 +451,11 @@ bool session_get(struct relay_session *session)
  */
 struct relay_session *session_get_by_id(uint64_t id)
 {
-       struct relay_session *session = NULL;
+       struct relay_session *session = nullptr;
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_lookup(sessions_ht, &id, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (!node) {
@@ -467,10 +465,9 @@ struct relay_session *session_get_by_id(uint64_t id)
        session = lttng::utils::container_of(node, &relay_session::session_n);
        DBG("Session find by ID %" PRIu64 " id found", id);
        if (!session_get(session)) {
-               session = NULL;
+               session = nullptr;
        }
 end:
-       rcu_read_unlock();
        return session;
 }
 
@@ -501,58 +498,60 @@ bool session_has_ongoing_rotation(const struct relay_session *session)
                goto end;
        }
 
-       rcu_read_lock();
        /*
         * Sample the 'ongoing_rotation' status of all relay sessions that
         * originate from the same session daemon session.
         */
-       cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, iterated_session,
-                       session_n.node) {
-               if (!session_get(iterated_session)) {
-                       continue;
-               }
-
-               if (session == iterated_session) {
-                       /* Skip this session. */
-                       goto next_session_no_unlock;
-               }
-
-               pthread_mutex_lock(&iterated_session->lock);
-
-               if (!iterated_session->id_sessiond.is_set) {
-                       /*
-                        * Session belongs to a peer that doesn't support
-                        * rotations.
-                        */
-                       goto next_session;
-               }
-
-               if (session->sessiond_uuid != iterated_session->sessiond_uuid) {
-                       /* Sessions do not originate from the same sessiond. */
-                       goto next_session;
-               }
-
-               if (LTTNG_OPTIONAL_GET(session->id_sessiond) !=
-                               LTTNG_OPTIONAL_GET(iterated_session->id_sessiond)) {
-                       /*
-                        * Sessions do not originate from the same sessiond
-                        * session.
-                        */
-                       goto next_session;
-               }
-
-               ongoing_rotation = iterated_session->ongoing_rotation;
-
-next_session:
-               pthread_mutex_unlock(&iterated_session->lock);
-next_session_no_unlock:
-               session_put(iterated_session);
-
-               if (ongoing_rotation) {
-                       break;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       sessions_ht->ht, &iter.iter, iterated_session, session_n.node) {
+                       if (!session_get(iterated_session)) {
+                               continue;
+                       }
+
+                       if (session == iterated_session) {
+                               /* Skip this session. */
+                               goto next_session_no_unlock;
+                       }
+
+                       pthread_mutex_lock(&iterated_session->lock);
+
+                       if (!iterated_session->id_sessiond.is_set) {
+                               /*
+                                * Session belongs to a peer that doesn't support
+                                * rotations.
+                                */
+                               goto next_session;
+                       }
+
+                       if (session->sessiond_uuid != iterated_session->sessiond_uuid) {
+                               /* Sessions do not originate from the same sessiond. */
+                               goto next_session;
+                       }
+
+                       if (LTTNG_OPTIONAL_GET(session->id_sessiond) !=
+                           LTTNG_OPTIONAL_GET(iterated_session->id_sessiond)) {
+                               /*
+                                * Sessions do not originate from the same sessiond
+                                * session.
+                                */
+                               goto next_session;
+                       }
+
+                       ongoing_rotation = iterated_session->ongoing_rotation;
+
+               next_session:
+                       pthread_mutex_unlock(&iterated_session->lock);
+               next_session_no_unlock:
+                       session_put(iterated_session);
+
+                       if (ongoing_rotation) {
+                               break;
+                       }
                }
        }
-       rcu_read_unlock();
 
 end:
        return ongoing_rotation;
@@ -560,9 +559,7 @@ end:
 
 static void rcu_destroy_session(struct rcu_head *rcu_head)
 {
-       struct relay_session *session =
-                       caa_container_of(rcu_head, struct relay_session,
-                               rcu_node);
+       struct relay_session *session = caa_container_of(rcu_head, struct relay_session, rcu_node);
        /*
         * Since each trace has a reference on the session, it means
         * that if we are at the point where we teardown the session, no
@@ -587,7 +584,6 @@ static int session_delete(struct relay_session *session)
        return lttng_ht_del(sessions_ht, &iter);
 }
 
-
 static void destroy_session(struct relay_session *session)
 {
        int ret;
@@ -595,21 +591,20 @@ static void destroy_session(struct relay_session *session)
        ret = session_delete(session);
        LTTNG_ASSERT(!ret);
        lttng_trace_chunk_put(session->current_trace_chunk);
-       session->current_trace_chunk = NULL;
+       session->current_trace_chunk = nullptr;
        lttng_trace_chunk_put(session->pending_closure_trace_chunk);
-       session->pending_closure_trace_chunk = NULL;
-       ret = sessiond_trace_chunk_registry_session_destroyed(
-                       sessiond_trace_chunk_registry, session->sessiond_uuid);
+       session->pending_closure_trace_chunk = nullptr;
+       ret = sessiond_trace_chunk_registry_session_destroyed(sessiond_trace_chunk_registry,
+                                                             session->sessiond_uuid);
        LTTNG_ASSERT(!ret);
        lttng_directory_handle_put(session->output_directory);
-       session->output_directory = NULL;
+       session->output_directory = nullptr;
        call_rcu(&session->rcu_node, rcu_destroy_session);
 }
 
 static void session_release(struct urcu_ref *ref)
 {
-       struct relay_session *session =
-                       lttng::utils::container_of(ref, &relay_session::ref);
+       struct relay_session *session = lttng::utils::container_of(ref, &relay_session::ref);
 
        destroy_session(session);
 }
@@ -619,9 +614,8 @@ void session_put(struct relay_session *session)
        if (!session) {
                return;
        }
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        urcu_ref_put(&session->ref, session_release);
-       rcu_read_unlock();
 }
 
 int session_close(struct relay_session *session)
@@ -633,28 +627,33 @@ int session_close(struct relay_session *session)
 
        pthread_mutex_lock(&session->lock);
        DBG("closing session %" PRIu64 ": is conn already closed %d",
-                       session->id, session->connection_closed);
+           session->id,
+           session->connection_closed);
        session->connection_closed = true;
        pthread_mutex_unlock(&session->lock);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(session->ctf_traces_ht->ht,
-                       &iter.iter, trace, node.node) {
-               ret = ctf_trace_close(trace);
-               if (ret) {
-                       goto rcu_unlock;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (session->ctf_traces_ht->ht, &iter.iter, trace, node.node) {
+                       ret = ctf_trace_close(trace);
+                       if (ret) {
+                               goto end;
+                       }
+               }
+
+               cds_list_for_each_entry_rcu(stream, &session->recv_list, recv_node)
+               {
+                       /* Close streams which have not been published yet. */
+                       try_stream_close(stream);
                }
        }
-       cds_list_for_each_entry_rcu(stream, &session->recv_list,
-                       recv_node) {
-               /* Close streams which have not been published yet. */
-               try_stream_close(stream);
-       }
-rcu_unlock:
-       rcu_read_unlock();
+
+end:
        if (ret) {
                return ret;
        }
+
        /* Put self-reference from create. */
        session_put(session);
        return ret;
@@ -675,7 +674,7 @@ int session_abort(struct relay_session *session)
        return ret;
 }
 
-void print_sessions(void)
+void print_sessions()
 {
        struct lttng_ht_iter iter;
        struct relay_session *session;
@@ -684,17 +683,18 @@ void print_sessions(void)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
-                       session_n.node) {
-               if (!session_get(session)) {
-                       continue;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (sessions_ht->ht, &iter.iter, session, session_n.node) {
+                       if (!session_get(session)) {
+                               continue;
+                       }
+                       DBG("session %p refcount %ld session %" PRIu64,
+                           session,
+                           session->ref.refcount,
+                           session->id);
+                       session_put(session);
                }
-               DBG("session %p refcount %ld session %" PRIu64,
-                       session,
-                       session->ref.refcount,
-                       session->id);
-               session_put(session);
        }
-       rcu_read_unlock();
 }
index 986eca68f041868b569ead28977034f8aaa88d2d..2a6c130dd61a02e4bc7aecced39c662eba5f971f 100644 (file)
  *
  */
 
-#include <limits.h>
+#include <common/hashtable/hashtable.hpp>
+#include <common/optional.hpp>
+#include <common/trace-chunk.hpp>
+#include <common/uuid.hpp>
+
+#include <lttng/constant.h>
+
 #include <inttypes.h>
+#include <limits.h>
 #include <pthread.h>
 #include <urcu/list.h>
 #include <urcu/ref.h>
 
-#include <lttng/constant.h>
-#include <common/hashtable/hashtable.hpp>
-#include <common/uuid.hpp>
-#include <common/trace-chunk.hpp>
-#include <common/optional.hpp>
-
 /*
  * Represents a session for the relay point of view
  */
@@ -107,7 +108,7 @@ struct relay_session {
         * Traversals are protected by RCU.
         * recv_list_lock also protects stream_count.
         */
-       struct cds_list_head recv_list; /* RCU list. */
+       struct cds_list_head recv_list; /* RCU list. */
        uint32_t stream_count;
        pthread_mutex_t recv_list_lock;
 
@@ -135,20 +136,21 @@ struct relay_session {
         */
        bool ongoing_rotation;
        struct lttng_directory_handle *output_directory;
-       struct rcu_head rcu_node;       /* For call_rcu teardown. */
+       struct rcu_head rcu_node; /* For call_rcu teardown. */
 };
 
 struct relay_session *session_create(const char *session_name,
-               const char *hostname, const char *base_path,
-               uint32_t live_timer,
-               bool snapshot,
-               const lttng_uuid& sessiond_uuid,
-               const uint64_t *id_sessiond,
-               const uint64_t *current_chunk_id,
-               const time_t *creation_time,
-               uint32_t major,
-               uint32_t minor,
-               bool session_name_contains_creation_timestamp);
+                                    const char *hostname,
+                                    const char *base_path,
+                                    uint32_t live_timer,
+                                    bool snapshot,
+                                    const lttng_uuid& sessiond_uuid,
+                                    const uint64_t *id_sessiond,
+                                    const uint64_t *current_chunk_id,
+                                    const time_t *creation_time,
+                                    uint32_t major,
+                                    uint32_t minor,
+                                    bool session_name_contains_creation_timestamp);
 struct relay_session *session_get_by_id(uint64_t id);
 bool session_get(struct relay_session *session);
 void session_put(struct relay_session *session);
@@ -158,6 +160,6 @@ int session_abort(struct relay_session *session);
 
 bool session_has_ongoing_rotation(const struct relay_session *session);
 
-void print_sessions(void);
+void print_sessions();
 
 #endif /* _SESSION_H */
index eba9a1989ab07fd2cf21c5865e089d6ca72099db..9d793c9bcf79315e722447fcb3c205f785a60c54 100644 (file)
@@ -6,18 +6,21 @@
  */
 
 #include "sessiond-trace-chunks.hpp"
-#include <urcu.h>
-#include <urcu/rculfhash.h>
-#include <urcu/ref.h>
-#include <common/macros.hpp>
-#include <common/hashtable/hashtable.hpp>
-#include <common/hashtable/utils.hpp>
-#include <common/trace-chunk-registry.hpp>
+
 #include <common/defaults.hpp>
 #include <common/error.hpp>
+#include <common/hashtable/hashtable.hpp>
+#include <common/hashtable/utils.hpp>
+#include <common/macros.hpp>
 #include <common/string-utils/format.hpp>
-#include <stdio.h>
+#include <common/trace-chunk-registry.hpp>
+#include <common/urcu.hpp>
+
 #include <inttypes.h>
+#include <stdio.h>
+#include <urcu.h>
+#include <urcu/rculfhash.h>
+#include <urcu/ref.h>
 
 /*
  * Lifetime of trace chunks within the relay daemon.
@@ -73,57 +76,46 @@ struct trace_chunk_registry_ht_element {
 };
 } /* namespace */
 
-static
-unsigned long trace_chunk_registry_ht_key_hash(
-               const struct trace_chunk_registry_ht_key *key)
+static unsigned long trace_chunk_registry_ht_key_hash(const struct trace_chunk_registry_ht_key *key)
 {
        const uint64_t uuid_h1 = *reinterpret_cast<const uint64_t *>(&key->sessiond_uuid[0]);
        const uint64_t uuid_h2 = *reinterpret_cast<const uint64_t *>(&key->sessiond_uuid[1]);
 
-       return hash_key_u64(&uuid_h1, lttng_ht_seed) ^
-                       hash_key_u64(&uuid_h2, lttng_ht_seed);
+       return hash_key_u64(&uuid_h1, lttng_ht_seed) ^ hash_key_u64(&uuid_h2, lttng_ht_seed);
 }
 
 /* cds_lfht match function */
-static
-int trace_chunk_registry_ht_key_match(struct cds_lfht_node *node,
-               const void *_key)
+static int trace_chunk_registry_ht_key_match(struct cds_lfht_node *node, const void *_key)
 {
-       const struct trace_chunk_registry_ht_key *key =
-                       (struct trace_chunk_registry_ht_key *) _key;
+       const struct trace_chunk_registry_ht_key *key = (struct trace_chunk_registry_ht_key *) _key;
        struct trace_chunk_registry_ht_element *registry;
 
        registry = lttng::utils::container_of(node, &trace_chunk_registry_ht_element::ht_node);
        return key->sessiond_uuid == registry->key.sessiond_uuid;
 }
 
-static
-void trace_chunk_registry_ht_element_free(struct rcu_head *node)
+static void trace_chunk_registry_ht_element_free(struct rcu_head *node)
 {
-       struct trace_chunk_registry_ht_element *element = lttng::utils::container_of(
-                       node, &trace_chunk_registry_ht_element::rcu_node);
+       struct trace_chunk_registry_ht_element *element =
+               lttng::utils::container_of(node, &trace_chunk_registry_ht_element::rcu_node);
 
        free(element);
 }
 
-static
-void trace_chunk_registry_ht_element_release(struct urcu_ref *ref)
+static void trace_chunk_registry_ht_element_release(struct urcu_ref *ref)
 {
        struct trace_chunk_registry_ht_element *element =
-                       lttng::utils::container_of(ref, &trace_chunk_registry_ht_element::ref);
+               lttng::utils::container_of(ref, &trace_chunk_registry_ht_element::ref);
        char uuid_str[LTTNG_UUID_STR_LEN];
 
        lttng_uuid_to_str(element->key.sessiond_uuid, uuid_str);
 
-       DBG("Destroying trace chunk registry associated to sessiond {%s}",
-                       uuid_str);
+       DBG("Destroying trace chunk registry associated to sessiond {%s}", uuid_str);
        if (element->sessiond_trace_chunk_registry) {
                /* Unpublish. */
-               rcu_read_lock();
-               cds_lfht_del(element->sessiond_trace_chunk_registry->ht,
-                               &element->ht_node);
-               rcu_read_unlock();
-               element->sessiond_trace_chunk_registry = NULL;
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_del(element->sessiond_trace_chunk_registry->ht, &element->ht_node);
+               element->sessiond_trace_chunk_registry = nullptr;
        }
 
        lttng_trace_chunk_registry_destroy(element->trace_chunk_registry);
@@ -131,16 +123,12 @@ void trace_chunk_registry_ht_element_release(struct urcu_ref *ref)
        call_rcu(&element->rcu_node, trace_chunk_registry_ht_element_free);
 }
 
-static
-bool trace_chunk_registry_ht_element_get(
-               struct trace_chunk_registry_ht_element *element)
+static bool trace_chunk_registry_ht_element_get(struct trace_chunk_registry_ht_element *element)
 {
        return urcu_ref_get_unless_zero(&element->ref);
 }
 
-static
-void trace_chunk_registry_ht_element_put(
-               struct trace_chunk_registry_ht_element *element)
+static void trace_chunk_registry_ht_element_put(struct trace_chunk_registry_ht_element *element)
 {
        if (!element) {
                return;
@@ -150,16 +138,15 @@ void trace_chunk_registry_ht_element_put(
 }
 
 /* Acquires a reference to the returned element on behalf of the caller. */
-static
-struct trace_chunk_registry_ht_element *trace_chunk_registry_ht_element_find(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const struct trace_chunk_registry_ht_key *key)
+static struct trace_chunk_registry_ht_element *
+trace_chunk_registry_ht_element_find(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                    const struct trace_chunk_registry_ht_key *key)
 {
-       struct trace_chunk_registry_ht_element *element = NULL;
+       struct trace_chunk_registry_ht_element *element = nullptr;
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(sessiond_registry->ht,
                        trace_chunk_registry_ht_key_hash(key),
                        trace_chunk_registry_ht_key_match,
@@ -167,24 +154,22 @@ struct trace_chunk_registry_ht_element *trace_chunk_registry_ht_element_find(
                        &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (node) {
-               element = lttng::utils::container_of(
-                               node, &trace_chunk_registry_ht_element::ht_node);
+               element =
+                       lttng::utils::container_of(node, &trace_chunk_registry_ht_element::ht_node);
                /*
                 * Only consider the look-up as successful if a reference
                 * could be acquired.
                 */
                if (!trace_chunk_registry_ht_element_get(element)) {
-                       element = NULL;
+                       element = nullptr;
                }
        }
-       rcu_read_unlock();
        return element;
 }
 
-static
-int trace_chunk_registry_ht_element_create(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const struct trace_chunk_registry_ht_key *key)
+static int
+trace_chunk_registry_ht_element_create(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                      const struct trace_chunk_registry_ht_key *key)
 {
        int ret = 0;
        struct trace_chunk_registry_ht_element *new_element;
@@ -209,70 +194,73 @@ int trace_chunk_registry_ht_element_create(
        urcu_ref_init(&new_element->ref);
        cds_lfht_node_init(&new_element->ht_node);
        new_element->trace_chunk_registry = trace_chunk_registry;
-       trace_chunk_registry = NULL;
+       trace_chunk_registry = nullptr;
 
        /* Attempt to publish the new element. */
-       rcu_read_lock();
-       while (1) {
-               struct cds_lfht_node *published_node;
-               struct trace_chunk_registry_ht_element *published_element;
+       {
+               /*
+                * Keep the rcu read lock is held accross all attempts
+                * purely for efficiency reasons.
+                */
+               lttng::urcu::read_lock_guard read_lock;
+               while (true) {
+                       struct cds_lfht_node *published_node;
+                       struct trace_chunk_registry_ht_element *published_element;
 
-               published_node = cds_lfht_add_unique(sessiond_registry->ht,
+                       published_node = cds_lfht_add_unique(
+                               sessiond_registry->ht,
                                trace_chunk_registry_ht_key_hash(&new_element->key),
                                trace_chunk_registry_ht_key_match,
                                &new_element->key,
                                &new_element->ht_node);
-               if (published_node == &new_element->ht_node) {
-                       /* New element published successfully. */
-                       DBG("Created trace chunk registry for sessiond {%s}",
-                                       uuid_str);
-                       new_element->sessiond_trace_chunk_registry =
-                                       sessiond_registry;
-                       break;
-               }
-
-               /*
-                * An equivalent element was published during the creation of
-                * this element. Attempt to acquire a reference to the one that
-                * was already published and release the reference to the copy
-                * we created if successful.
-                */
-               published_element = lttng::utils::container_of(published_node,
-                               &trace_chunk_registry_ht_element::ht_node);
-               if (trace_chunk_registry_ht_element_get(published_element)) {
-                       DBG("Acquired reference to trace chunk registry of sessiond {%s}",
-                                       uuid_str);
-                       trace_chunk_registry_ht_element_put(new_element);
-                       new_element = NULL;
-                       break;
+                       if (published_node == &new_element->ht_node) {
+                               /* New element published successfully. */
+                               DBG("Created trace chunk registry for sessiond {%s}", uuid_str);
+                               new_element->sessiond_trace_chunk_registry = sessiond_registry;
+                               break;
+                       }
+
+                       /*
+                        * An equivalent element was published during the creation of
+                        * this element. Attempt to acquire a reference to the one that
+                        * was already published and release the reference to the copy
+                        * we created if successful.
+                        */
+                       published_element = lttng::utils::container_of(
+                               published_node, &trace_chunk_registry_ht_element::ht_node);
+                       if (trace_chunk_registry_ht_element_get(published_element)) {
+                               DBG("Acquired reference to trace chunk registry of sessiond {%s}",
+                                   uuid_str);
+                               trace_chunk_registry_ht_element_put(new_element);
+                               new_element = nullptr;
+                               break;
+                       }
+                       /*
+                        * A reference to the previously published element could not
+                        * be acquired. Hence, retry to publish our copy of the
+                        * element.
+                        */
                }
-               /*
-                * A reference to the previously published element could not
-                * be acquired. Hence, retry to publish our copy of the
-                * element.
-                */
        }
-       rcu_read_unlock();
 end:
        if (ret < 0) {
-               ERR("Failed to create trace chunk registry for session daemon {%s}",
-                               uuid_str);
+               ERR("Failed to create trace chunk registry for session daemon {%s}", uuid_str);
        }
        lttng_trace_chunk_registry_destroy(trace_chunk_registry);
        return ret;
 }
 
-struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry_create(void)
+struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry_create()
 {
        struct sessiond_trace_chunk_registry *sessiond_registry =
-                       zmalloc<sessiond_trace_chunk_registry>();
+               zmalloc<sessiond_trace_chunk_registry>();
 
        if (!sessiond_registry) {
                goto end;
        }
 
-       sessiond_registry->ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       sessiond_registry->ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!sessiond_registry->ht) {
                goto error;
        }
@@ -281,21 +269,19 @@ end:
        return sessiond_registry;
 error:
        sessiond_trace_chunk_registry_destroy(sessiond_registry);
-       return NULL;
+       return nullptr;
 }
 
-void sessiond_trace_chunk_registry_destroy(
-               struct sessiond_trace_chunk_registry *sessiond_registry)
+void sessiond_trace_chunk_registry_destroy(struct sessiond_trace_chunk_registry *sessiond_registry)
 {
-       int ret = cds_lfht_destroy(sessiond_registry->ht, NULL);
+       int ret = cds_lfht_destroy(sessiond_registry->ht, nullptr);
 
        LTTNG_ASSERT(!ret);
        free(sessiond_registry);
 }
 
 int sessiond_trace_chunk_registry_session_created(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid)
+       struct sessiond_trace_chunk_registry *sessiond_registry, const lttng_uuid& sessiond_uuid)
 {
        int ret = 0;
        struct trace_chunk_registry_ht_key key;
@@ -308,20 +294,17 @@ int sessiond_trace_chunk_registry_session_created(
                char uuid_str[LTTNG_UUID_STR_LEN];
 
                lttng_uuid_to_str(sessiond_uuid, uuid_str);
-               DBG("Acquired reference to trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               DBG("Acquired reference to trace chunk registry of sessiond {%s}", uuid_str);
                goto end;
        } else {
-               ret = trace_chunk_registry_ht_element_create(
-                               sessiond_registry, &key);
+               ret = trace_chunk_registry_ht_element_create(sessiond_registry, &key);
        }
 end:
        return ret;
 }
 
 int sessiond_trace_chunk_registry_session_destroyed(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid)
+       struct sessiond_trace_chunk_registry *sessiond_registry, const lttng_uuid& sessiond_uuid)
 {
        int ret = 0;
        struct trace_chunk_registry_ht_key key;
@@ -333,8 +316,7 @@ int sessiond_trace_chunk_registry_session_destroyed(
 
        element = trace_chunk_registry_ht_element_find(sessiond_registry, &key);
        if (element) {
-               DBG("Releasing reference to trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               DBG("Releasing reference to trace chunk registry of sessiond {%s}", uuid_str);
                /*
                 * Release the reference held by the session and the reference
                 * acquired through the "find" operation.
@@ -342,26 +324,26 @@ int sessiond_trace_chunk_registry_session_destroyed(
                trace_chunk_registry_ht_element_put(element);
                trace_chunk_registry_ht_element_put(element);
        } else {
-               ERR("Failed to find trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               ERR("Failed to find trace chunk registry of sessiond {%s}", uuid_str);
                ret = -1;
        }
        return ret;
 }
 
-struct lttng_trace_chunk *sessiond_trace_chunk_registry_publish_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid, uint64_t session_id,
-               struct lttng_trace_chunk *new_chunk)
+struct lttng_trace_chunk *
+sessiond_trace_chunk_registry_publish_chunk(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                           const lttng_uuid& sessiond_uuid,
+                                           uint64_t session_id,
+                                           struct lttng_trace_chunk *new_chunk)
 {
        enum lttng_trace_chunk_status status;
        uint64_t chunk_id;
        bool is_anonymous_chunk;
        struct trace_chunk_registry_ht_key key;
-       struct trace_chunk_registry_ht_element *element = NULL;
+       struct trace_chunk_registry_ht_element *element = nullptr;
        char uuid_str[LTTNG_UUID_STR_LEN];
        char chunk_id_str[MAX_INT_DEC_LEN(typeof(chunk_id))] = "-1";
-       struct lttng_trace_chunk *published_chunk = NULL;
+       struct lttng_trace_chunk *published_chunk = nullptr;
        bool trace_chunk_already_published;
 
        lttng_uuid_to_str(sessiond_uuid, uuid_str);
@@ -371,8 +353,7 @@ struct lttng_trace_chunk *sessiond_trace_chunk_registry_publish_chunk(
        if (status == LTTNG_TRACE_CHUNK_STATUS_OK) {
                int ret;
 
-               ret = snprintf(chunk_id_str, sizeof(chunk_id_str), "%" PRIu64,
-                               chunk_id);
+               ret = snprintf(chunk_id_str, sizeof(chunk_id_str), "%" PRIu64, chunk_id);
                if (ret < 0) {
                        lttng_strncpy(chunk_id_str, "-1", sizeof(chunk_id_str));
                        WARN("Failed to format trace chunk id");
@@ -386,9 +367,10 @@ struct lttng_trace_chunk *sessiond_trace_chunk_registry_publish_chunk(
        }
 
        DBG("Attempting to publish trace chunk: sessiond {%s}, session_id = "
-                       "%" PRIu64 ", chunk_id = %s",
-                       uuid_str, session_id,
-                       is_anonymous_chunk ? "anonymous" : chunk_id_str);
+           "%" PRIu64 ", chunk_id = %s",
+           uuid_str,
+           session_id,
+           is_anonymous_chunk ? "anonymous" : chunk_id_str);
 
        element = trace_chunk_registry_ht_element_find(sessiond_registry, &key);
        if (!element) {
@@ -396,9 +378,10 @@ struct lttng_trace_chunk *sessiond_trace_chunk_registry_publish_chunk(
                goto end;
        }
 
-       published_chunk = lttng_trace_chunk_registry_publish_chunk(
-                       element->trace_chunk_registry, session_id, new_chunk,
-                       &trace_chunk_already_published);
+       published_chunk = lttng_trace_chunk_registry_publish_chunk(element->trace_chunk_registry,
+                                                                  session_id,
+                                                                  new_chunk,
+                                                                  &trace_chunk_already_published);
        /*
         * When the trace chunk is first published, two references to the
         * published chunks exist. One is taken by the registry while the other
@@ -425,13 +408,12 @@ end:
        return published_chunk;
 }
 
-struct lttng_trace_chunk *
-sessiond_trace_chunk_registry_get_anonymous_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id)
+struct lttng_trace_chunk *sessiond_trace_chunk_registry_get_anonymous_chunk(
+       struct sessiond_trace_chunk_registry *sessiond_registry,
+       const lttng_uuid& sessiond_uuid,
+       uint64_t session_id)
 {
-       struct lttng_trace_chunk *chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr;
        struct trace_chunk_registry_ht_element *element;
        struct trace_chunk_registry_ht_key key;
        char uuid_str[LTTNG_UUID_STR_LEN];
@@ -441,26 +423,24 @@ sessiond_trace_chunk_registry_get_anonymous_chunk(
        key.sessiond_uuid = sessiond_uuid;
        element = trace_chunk_registry_ht_element_find(sessiond_registry, &key);
        if (!element) {
-               ERR("Failed to find trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               ERR("Failed to find trace chunk registry of sessiond {%s}", uuid_str);
                goto end;
        }
 
-       chunk = lttng_trace_chunk_registry_find_anonymous_chunk(
-                       element->trace_chunk_registry,
-                       session_id);
+       chunk = lttng_trace_chunk_registry_find_anonymous_chunk(element->trace_chunk_registry,
+                                                               session_id);
        trace_chunk_registry_ht_element_put(element);
 end:
        return chunk;
 }
 
 struct lttng_trace_chunk *
-sessiond_trace_chunk_registry_get_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id, uint64_t chunk_id)
+sessiond_trace_chunk_registry_get_chunk(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                       const lttng_uuid& sessiond_uuid,
+                                       uint64_t session_id,
+                                       uint64_t chunk_id)
 {
-       struct lttng_trace_chunk *chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr;
        struct trace_chunk_registry_ht_element *element;
        struct trace_chunk_registry_ht_key key;
        char uuid_str[LTTNG_UUID_STR_LEN];
@@ -470,23 +450,23 @@ sessiond_trace_chunk_registry_get_chunk(
        key.sessiond_uuid = sessiond_uuid;
        element = trace_chunk_registry_ht_element_find(sessiond_registry, &key);
        if (!element) {
-               ERR("Failed to find trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               ERR("Failed to find trace chunk registry of sessiond {%s}", uuid_str);
                goto end;
        }
 
        chunk = lttng_trace_chunk_registry_find_chunk(
-                       element->trace_chunk_registry,
-                       session_id, chunk_id);
+               element->trace_chunk_registry, session_id, chunk_id);
        trace_chunk_registry_ht_element_put(element);
 end:
        return chunk;
 }
 
 int sessiond_trace_chunk_registry_chunk_exists(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id, uint64_t chunk_id, bool *chunk_exists)
+       struct sessiond_trace_chunk_registry *sessiond_registry,
+       const lttng_uuid& sessiond_uuid,
+       uint64_t session_id,
+       uint64_t chunk_id,
+       bool *chunk_exists)
 {
        int ret;
        struct trace_chunk_registry_ht_element *element;
@@ -505,15 +485,13 @@ int sessiond_trace_chunk_registry_chunk_exists(
                 * connection/registry. This would indicate a protocol
                 * (or internal) error.
                 */
-               ERR("Failed to find trace chunk registry of sessiond {%s}",
-                               uuid_str);
+               ERR("Failed to find trace chunk registry of sessiond {%s}", uuid_str);
                ret = -1;
                goto end;
        }
 
        ret = lttng_trace_chunk_registry_chunk_exists(
-                       element->trace_chunk_registry,
-                       session_id, chunk_id, chunk_exists);
+               element->trace_chunk_registry, session_id, chunk_id, chunk_exists);
        trace_chunk_registry_ht_element_put(element);
 end:
        return ret;
index 4d5759d87b28d663d88aabc1dd06b4ca475c2636..5b9f00a7edaf2ad5a0350bd2a6b245a61450b7c7 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef SESSIOND_TRACE_CHUNK_REGISTRY_H
 #define SESSIOND_TRACE_CHUNK_REGISTRY_H
 
-#include <common/uuid.hpp>
 #include <common/trace-chunk.hpp>
+#include <common/uuid.hpp>
+
 #include <stdint.h>
 
 /*
  */
 struct sessiond_trace_chunk_registry;
 
-struct sessiond_trace_chunk_registry *
-sessiond_trace_chunk_registry_create(void);
+struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry_create();
 
-void sessiond_trace_chunk_registry_destroy(
-               struct sessiond_trace_chunk_registry *sessiond_registry);
+void sessiond_trace_chunk_registry_destroy(struct sessiond_trace_chunk_registry *sessiond_registry);
 
 int sessiond_trace_chunk_registry_session_created(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid);
+       struct sessiond_trace_chunk_registry *sessiond_registry, const lttng_uuid& sessiond_uuid);
 
 int sessiond_trace_chunk_registry_session_destroyed(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid);
-
-struct lttng_trace_chunk *sessiond_trace_chunk_registry_publish_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid, uint64_t session_id,
-               struct lttng_trace_chunk *chunk);
+       struct sessiond_trace_chunk_registry *sessiond_registry, const lttng_uuid& sessiond_uuid);
 
 struct lttng_trace_chunk *
-sessiond_trace_chunk_registry_get_anonymous_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id);
+sessiond_trace_chunk_registry_publish_chunk(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                           const lttng_uuid& sessiond_uuid,
+                                           uint64_t session_id,
+                                           struct lttng_trace_chunk *chunk);
+
+struct lttng_trace_chunk *sessiond_trace_chunk_registry_get_anonymous_chunk(
+       struct sessiond_trace_chunk_registry *sessiond_registry,
+       const lttng_uuid& sessiond_uuid,
+       uint64_t session_id);
 
 struct lttng_trace_chunk *
-sessiond_trace_chunk_registry_get_chunk(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id, uint64_t chunk_id);
+sessiond_trace_chunk_registry_get_chunk(struct sessiond_trace_chunk_registry *sessiond_registry,
+                                       const lttng_uuid& sessiond_uuid,
+                                       uint64_t session_id,
+                                       uint64_t chunk_id);
 
 int sessiond_trace_chunk_registry_chunk_exists(
-               struct sessiond_trace_chunk_registry *sessiond_registry,
-               const lttng_uuid& sessiond_uuid,
-               uint64_t session_id, uint64_t chunk_id, bool *chunk_exists);
+       struct sessiond_trace_chunk_registry *sessiond_registry,
+       const lttng_uuid& sessiond_uuid,
+       uint64_t session_id,
+       uint64_t chunk_id,
+       bool *chunk_exists);
 
 #endif /* SESSIOND_TRACE_CHUNK_REGISTRY_H */
index fbecdc55804acdc151732a17188b13fa1b969186..a0935231d039280598ad538dfcaaa2f8189d3c27 100644 (file)
@@ -9,24 +9,25 @@
  */
 
 #define _LGPL_SOURCE
-#include <algorithm>
+#include "index.hpp"
+#include "lttng-relayd.hpp"
+#include "stream.hpp"
+#include "viewer-stream.hpp"
+
 #include <common/common.hpp>
 #include <common/defaults.hpp>
 #include <common/fs-handle.hpp>
 #include <common/sessiond-comm/relayd.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
-#include <sys/stat.h>
-#include <urcu/rculist.h>
 
-#include "lttng-relayd.hpp"
-#include "index.hpp"
-#include "stream.hpp"
-#include "viewer-stream.hpp"
-
-#include <sys/types.h>
+#include <algorithm>
 #include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <urcu/rculist.h>
 
-#define FILE_IO_STACK_BUFFER_SIZE              65536
+#define FILE_IO_STACK_BUFFER_SIZE 65536
 
 /* Should be called with RCU read-side lock held. */
 bool stream_get(struct relay_stream *stream)
@@ -45,9 +46,9 @@ struct relay_stream *stream_get_by_id(uint64_t stream_id)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct relay_stream *stream = NULL;
+       struct relay_stream *stream = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_lookup(relay_streams_ht, &stream_id, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (!node) {
@@ -56,10 +57,9 @@ struct relay_stream *stream_get_by_id(uint64_t stream_id)
        }
        stream = lttng::utils::container_of(node, &relay_stream::node);
        if (!stream_get(stream)) {
-               stream = NULL;
+               stream = nullptr;
        }
 end:
-       rcu_read_unlock();
        return stream;
 }
 
@@ -68,8 +68,7 @@ static void stream_complete_rotation(struct relay_stream *stream)
        DBG("Rotation completed for stream %" PRIu64, stream->stream_handle);
        if (stream->ongoing_rotation.value.next_trace_chunk) {
                tracefile_array_reset(stream->tfa);
-               tracefile_array_commit_seq(stream->tfa,
-                               stream->index_received_seqcount);
+               tracefile_array_commit_seq(stream->tfa, stream->index_received_seqcount);
        }
        lttng_trace_chunk_put(stream->trace_chunk);
        stream->trace_chunk = stream->ongoing_rotation.value.next_trace_chunk;
@@ -77,11 +76,10 @@ static void stream_complete_rotation(struct relay_stream *stream)
        stream->completed_rotation_count++;
 }
 
-static int stream_create_data_output_file_from_trace_chunk(
-               struct relay_stream *stream,
-               struct lttng_trace_chunk *trace_chunk,
-               bool force_unlink,
-               struct fs_handle **out_file)
+static int stream_create_data_output_file_from_trace_chunk(struct relay_stream *stream,
+                                                          struct lttng_trace_chunk *trace_chunk,
+                                                          bool force_unlink,
+                                                          struct fs_handle **out_file)
 {
        int ret;
        char stream_path[LTTNG_PATH_MAX];
@@ -91,9 +89,13 @@ static int stream_create_data_output_file_from_trace_chunk(
 
        ASSERT_LOCKED(stream->lock);
 
-       ret = utils_stream_file_path(stream->path_name, stream->channel_name,
-                       stream->tracefile_size, stream->tracefile_current_index,
-                       NULL, stream_path, sizeof(stream_path));
+       ret = utils_stream_file_path(stream->path_name,
+                                    stream->channel_name,
+                                    stream->tracefile_size,
+                                    stream->tracefile_current_index,
+                                    nullptr,
+                                    stream_path,
+                                    sizeof(stream_path));
        if (ret < 0) {
                goto end;
        }
@@ -107,10 +109,10 @@ static int stream_create_data_output_file_from_trace_chunk(
                 * content.
                 */
                status = (lttng_trace_chunk_status) lttng_trace_chunk_unlink_file(trace_chunk,
-                               stream_path);
+                                                                                 stream_path);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        PERROR("Failed to unlink stream file \"%s\" during trace file rotation",
-                                       stream_path);
+                              stream_path);
                        /*
                         * Don't abort if the file doesn't exist, it is
                         * unexpected, but should not be a fatal error.
@@ -122,8 +124,8 @@ static int stream_create_data_output_file_from_trace_chunk(
                }
        }
 
-       status = lttng_trace_chunk_open_fs_handle(trace_chunk, stream_path,
-                       flags, mode, out_file, false);
+       status = lttng_trace_chunk_open_fs_handle(
+               trace_chunk, stream_path, flags, mode, out_file, false);
        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ERR("Failed to open stream file \"%s\"", stream->channel_name);
                ret = -1;
@@ -138,11 +140,12 @@ static int stream_rotate_data_file(struct relay_stream *stream)
        int ret = 0;
 
        DBG("Rotating stream %" PRIu64 " data file with size %" PRIu64,
-                       stream->stream_handle, stream->tracefile_size_current);
+           stream->stream_handle,
+           stream->tracefile_size_current);
 
        if (stream->file) {
                fs_handle_close(stream->file);
-               stream->file = NULL;
+               stream->file = nullptr;
        }
 
        stream->tracefile_wrapped_around = false;
@@ -152,24 +155,27 @@ static int stream_rotate_data_file(struct relay_stream *stream)
                enum lttng_trace_chunk_status chunk_status;
 
                chunk_status = lttng_trace_chunk_create_subdirectory(
-                               stream->ongoing_rotation.value.next_trace_chunk,
-                               stream->path_name);
+                       stream->ongoing_rotation.value.next_trace_chunk, stream->path_name);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
                /* Rotate the data file. */
-               ret = stream_create_data_output_file_from_trace_chunk(stream,
-                               stream->ongoing_rotation.value.next_trace_chunk,
-                               false, &stream->file);
+               ret = stream_create_data_output_file_from_trace_chunk(
+                       stream,
+                       stream->ongoing_rotation.value.next_trace_chunk,
+                       false,
+                       &stream->file);
                if (ret < 0) {
                        ERR("Failed to rotate stream data file");
                        goto end;
                }
        }
        DBG("%s: reset tracefile_size_current for stream %" PRIu64 " was %" PRIu64,
-                       __func__, stream->stream_handle, stream->tracefile_size_current);
+           __func__,
+           stream->stream_handle,
+           stream->tracefile_size_current);
        stream->tracefile_size_current = 0;
        stream->pos_after_last_complete_data_index = 0;
        stream->ongoing_rotation.value.data_rotated = true;
@@ -197,15 +203,15 @@ static int rotate_truncate_stream(struct relay_stream *stream)
        off_t lseek_ret, previous_stream_copy_origin;
        uint64_t copy_bytes_left, misplaced_data_size;
        bool acquired_reference;
-       struct fs_handle *previous_stream_file = NULL;
-       struct lttng_trace_chunk *previous_chunk = NULL;
+       struct fs_handle *previous_stream_file = nullptr;
+       struct lttng_trace_chunk *previous_chunk = nullptr;
 
        if (!LTTNG_OPTIONAL_GET(stream->ongoing_rotation).next_trace_chunk) {
                ERR("Protocol error encoutered in %s(): stream rotation "
-                       "sequence number is before the current sequence number "
-                       "and the next trace chunk is unset. Honoring this "
-                       "rotation command would result in data loss",
-                               __FUNCTION__);
+                   "sequence number is before the current sequence number "
+                   "and the next trace chunk is unset. Honoring this "
+                   "rotation command would result in data loss",
+                   __FUNCTION__);
                ret = -1;
                goto end;
        }
@@ -230,13 +236,12 @@ static int rotate_truncate_stream(struct relay_stream *stream)
         */
        LTTNG_ASSERT(stream->file);
        previous_stream_file = stream->file;
-       stream->file = NULL;
+       stream->file = nullptr;
 
        LTTNG_ASSERT(!stream->is_metadata);
-       LTTNG_ASSERT(stream->tracefile_size_current >
-                       stream->pos_after_last_complete_data_index);
-       misplaced_data_size = stream->tracefile_size_current -
-                             stream->pos_after_last_complete_data_index;
+       LTTNG_ASSERT(stream->tracefile_size_current > stream->pos_after_last_complete_data_index);
+       misplaced_data_size =
+               stream->tracefile_size_current - stream->pos_after_last_complete_data_index;
        copy_bytes_left = misplaced_data_size;
        previous_stream_copy_origin = stream->pos_after_last_complete_data_index;
 
@@ -254,7 +259,7 @@ static int rotate_truncate_stream(struct relay_stream *stream)
        if (lseek_ret < 0) {
                PERROR("Failed to seek to offset %" PRIu64
                       " while copying extra data received before a stream rotation",
-                               (uint64_t) previous_stream_copy_origin);
+                      (uint64_t) previous_stream_copy_origin);
                ret = -1;
                goto end;
        }
@@ -263,43 +268,46 @@ static int rotate_truncate_stream(struct relay_stream *stream)
        while (copy_bytes_left) {
                ssize_t io_ret;
                char copy_buffer[FILE_IO_STACK_BUFFER_SIZE];
-               const off_t copy_size_this_pass = std::min<uint64_t>(copy_bytes_left, sizeof(copy_buffer));
+               const off_t copy_size_this_pass =
+                       std::min<uint64_t>(copy_bytes_left, sizeof(copy_buffer));
 
-               io_ret = fs_handle_read(previous_stream_file, copy_buffer,
-                               copy_size_this_pass);
+               io_ret = fs_handle_read(previous_stream_file, copy_buffer, copy_size_this_pass);
                if (io_ret < (ssize_t) copy_size_this_pass) {
                        if (io_ret == -1) {
                                PERROR("Failed to read %" PRIu64
                                       " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
-                                               copy_size_this_pass,
-                                               __FUNCTION__, io_ret,
-                                               stream->stream_handle);
+                                      copy_size_this_pass,
+                                      __FUNCTION__,
+                                      io_ret,
+                                      stream->stream_handle);
                        } else {
                                ERR("Failed to read %" PRIu64
-                                      " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
-                                               copy_size_this_pass,
-                                               __FUNCTION__, io_ret,
-                                               stream->stream_handle);
+                                   " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
+                                   copy_size_this_pass,
+                                   __FUNCTION__,
+                                   io_ret,
+                                   stream->stream_handle);
                        }
                        ret = -1;
                        goto end;
                }
 
-               io_ret = fs_handle_write(
-                               stream->file, copy_buffer, copy_size_this_pass);
+               io_ret = fs_handle_write(stream->file, copy_buffer, copy_size_this_pass);
                if (io_ret < (ssize_t) copy_size_this_pass) {
                        if (io_ret == -1) {
                                PERROR("Failed to write %" PRIu64
                                       " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
-                                               copy_size_this_pass,
-                                               __FUNCTION__, io_ret,
-                                               stream->stream_handle);
+                                      copy_size_this_pass,
+                                      __FUNCTION__,
+                                      io_ret,
+                                      stream->stream_handle);
                        } else {
                                ERR("Failed to write %" PRIu64
-                                      " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
-                                               copy_size_this_pass,
-                                               __FUNCTION__, io_ret,
-                                               stream->stream_handle);
+                                   " bytes from previous stream file in %s(), returned %zi: stream id = %" PRIu64,
+                                   copy_size_this_pass,
+                                   __FUNCTION__,
+                                   io_ret,
+                                   stream->stream_handle);
                        }
                        ret = -1;
                        goto end;
@@ -308,11 +316,10 @@ static int rotate_truncate_stream(struct relay_stream *stream)
        }
 
        /* Truncate the file to get rid of the excess data. */
-       ret = fs_handle_truncate(
-                       previous_stream_file, previous_stream_copy_origin);
+       ret = fs_handle_truncate(previous_stream_file, previous_stream_copy_origin);
        if (ret) {
                PERROR("Failed to truncate current stream file to offset %" PRIu64,
-                               previous_stream_copy_origin);
+                      previous_stream_copy_origin);
                goto end;
        }
 
@@ -356,31 +363,28 @@ static int try_rotate_stream_data(struct relay_stream *stream)
                goto end;
        }
 
-       DBG("%s: Stream %" PRIu64
-                               " (rotate_at_index_packet_seq_num = %" PRIu64
-                               ", rotate_at_prev_data_net_seq = %" PRIu64
-                               ", prev_data_seq = %" PRIu64 ")",
-                               __func__, stream->stream_handle,
-                               stream->ongoing_rotation.value.packet_seq_num,
-                               stream->ongoing_rotation.value.prev_data_net_seq,
-                               stream->prev_data_seq);
+       DBG("%s: Stream %" PRIu64 " (rotate_at_index_packet_seq_num = %" PRIu64
+           ", rotate_at_prev_data_net_seq = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
+           __func__,
+           stream->stream_handle,
+           stream->ongoing_rotation.value.packet_seq_num,
+           stream->ongoing_rotation.value.prev_data_net_seq,
+           stream->prev_data_seq);
 
        if (stream->prev_data_seq == -1ULL ||
-                       stream->ongoing_rotation.value.prev_data_net_seq == -1ULL ||
-                       stream->prev_data_seq <
-                       stream->ongoing_rotation.value.prev_data_net_seq) {
+           stream->ongoing_rotation.value.prev_data_net_seq == -1ULL ||
+           stream->prev_data_seq < stream->ongoing_rotation.value.prev_data_net_seq) {
                /*
                 * The next packet that will be written is not part of the next
                 * chunk yet.
                 */
                DBG("Stream %" PRIu64 " data not yet ready for rotation "
-                               "(rotate_at_index_packet_seq_num = %" PRIu64
-                               ", rotate_at_prev_data_net_seq = %" PRIu64
-                               ", prev_data_seq = %" PRIu64 ")",
-                               stream->stream_handle,
-                               stream->ongoing_rotation.value.packet_seq_num,
-                               stream->ongoing_rotation.value.prev_data_net_seq,
-                               stream->prev_data_seq);
+                   "(rotate_at_index_packet_seq_num = %" PRIu64
+                   ", rotate_at_prev_data_net_seq = %" PRIu64 ", prev_data_seq = %" PRIu64 ")",
+                   stream->stream_handle,
+                   stream->ongoing_rotation.value.packet_seq_num,
+                   stream->ongoing_rotation.value.prev_data_net_seq,
+                   stream->prev_data_seq);
                goto end;
        } else if (stream->prev_data_seq > stream->ongoing_rotation.value.prev_data_net_seq) {
                /*
@@ -388,8 +392,9 @@ static int try_rotate_stream_data(struct relay_stream *stream)
                 * commands are serialized with respect to each other.
                 */
                DBG("Rotation after too much data has been written in tracefile "
-                               "for stream %" PRIu64 ", need to truncate before "
-                               "rotating", stream->stream_handle);
+                   "for stream %" PRIu64 ", need to truncate before "
+                   "rotating",
+                   stream->stream_handle);
                ret = rotate_truncate_stream(stream);
                if (ret) {
                        ERR("Failed to truncate stream");
@@ -408,12 +413,11 @@ end:
  *
  * Return 0 on success, -1 on error.
  */
-static int create_index_file(struct relay_stream *stream,
-               struct lttng_trace_chunk *chunk)
+static int create_index_file(struct relay_stream *stream, struct lttng_trace_chunk *chunk)
 {
        int ret;
        uint32_t major, minor;
-       char *index_subpath = NULL;
+       char *index_subpath = nullptr;
        enum lttng_trace_chunk_status status;
 
        ASSERT_LOCKED(stream->lock);
@@ -421,7 +425,7 @@ static int create_index_file(struct relay_stream *stream,
        /* Put ref on previous index_file. */
        if (stream->index_file) {
                lttng_index_file_put(stream->index_file);
-               stream->index_file = NULL;
+               stream->index_file = nullptr;
        }
        major = stream->trace->session->major;
        minor = stream->trace->session->minor;
@@ -430,26 +434,26 @@ static int create_index_file(struct relay_stream *stream,
                ret = 0;
                goto end;
        }
-       ret = asprintf(&index_subpath, "%s/%s", stream->path_name,
-                       DEFAULT_INDEX_DIR);
+       ret = asprintf(&index_subpath, "%s/%s", stream->path_name, DEFAULT_INDEX_DIR);
        if (ret < 0) {
                goto end;
        }
 
-       status = lttng_trace_chunk_create_subdirectory(chunk,
-                       index_subpath);
+       status = lttng_trace_chunk_create_subdirectory(chunk, index_subpath);
        free(index_subpath);
        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end;
        }
-       status = lttng_index_file_create_from_trace_chunk(
-                       chunk, stream->path_name,
-                       stream->channel_name, stream->tracefile_size,
-                       stream->tracefile_current_index,
-                       lttng_to_index_major(major, minor),
-                       lttng_to_index_minor(major, minor), true,
-                       &stream->index_file);
+       status = lttng_index_file_create_from_trace_chunk(chunk,
+                                                         stream->path_name,
+                                                         stream->channel_name,
+                                                         stream->tracefile_size,
+                                                         stream->tracefile_current_index,
+                                                         lttng_to_index_major(major, minor),
+                                                         lttng_to_index_minor(major, minor),
+                                                         true,
+                                                         &stream->index_file);
        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end;
@@ -481,26 +485,25 @@ static int try_rotate_stream_index(struct relay_stream *stream)
                goto end;
        }
 
-       DBG("%s: Stream %" PRIu64
-                       " (rotate_at_packet_seq_num = %" PRIu64
-                       ", received_packet_seq_num = "
-                       "(value = %" PRIu64 ", is_set = %" PRIu8 "))",
-                       __func__, stream->stream_handle,
-                       stream->ongoing_rotation.value.packet_seq_num,
-                       stream->received_packet_seq_num.value,
-                       stream->received_packet_seq_num.is_set);
+       DBG("%s: Stream %" PRIu64 " (rotate_at_packet_seq_num = %" PRIu64
+           ", received_packet_seq_num = "
+           "(value = %" PRIu64 ", is_set = %" PRIu8 "))",
+           __func__,
+           stream->stream_handle,
+           stream->ongoing_rotation.value.packet_seq_num,
+           stream->received_packet_seq_num.value,
+           stream->received_packet_seq_num.is_set);
 
        if (!stream->received_packet_seq_num.is_set ||
-                       LTTNG_OPTIONAL_GET(stream->received_packet_seq_num) + 1 <
-                       stream->ongoing_rotation.value.packet_seq_num) {
+           LTTNG_OPTIONAL_GET(stream->received_packet_seq_num) + 1 <
+                   stream->ongoing_rotation.value.packet_seq_num) {
                DBG("Stream %" PRIu64 " index not yet ready for rotation "
-                               "(rotate_at_packet_seq_num = %" PRIu64
-                               ", received_packet_seq_num = "
-                               "(value = %" PRIu64 ", is_set = %" PRIu8 "))",
-                               stream->stream_handle,
-                               stream->ongoing_rotation.value.packet_seq_num,
-                               stream->received_packet_seq_num.value,
-                               stream->received_packet_seq_num.is_set);
+                   "(rotate_at_packet_seq_num = %" PRIu64 ", received_packet_seq_num = "
+                   "(value = %" PRIu64 ", is_set = %" PRIu8 "))",
+                   stream->stream_handle,
+                   stream->ongoing_rotation.value.packet_seq_num,
+                   stream->received_packet_seq_num.value,
+                   stream->received_packet_seq_num.is_set);
                goto end;
        } else {
                /*
@@ -509,12 +512,11 @@ static int try_rotate_stream_index(struct relay_stream *stream)
                 * rotation position.
                 */
                LTTNG_ASSERT(LTTNG_OPTIONAL_GET(stream->received_packet_seq_num) + 1 >=
-                               stream->ongoing_rotation.value.packet_seq_num);
-               DBG("Rotating stream %" PRIu64 " index file",
-                               stream->stream_handle);
+                            stream->ongoing_rotation.value.packet_seq_num);
+               DBG("Rotating stream %" PRIu64 " index file", stream->stream_handle);
                if (stream->index_file) {
                        lttng_index_file_put(stream->index_file);
-                       stream->index_file = NULL;
+                       stream->index_file = nullptr;
                }
                stream->ongoing_rotation.value.index_rotated = true;
 
@@ -522,13 +524,11 @@ static int try_rotate_stream_index(struct relay_stream *stream)
                 * Set the rotation pivot position for the data, now that we have the
                 * net_seq_num matching the packet_seq_num index pivot position.
                 */
-               stream->ongoing_rotation.value.prev_data_net_seq =
-                       stream->prev_index_seq;
+               stream->ongoing_rotation.value.prev_data_net_seq = stream->prev_index_seq;
                if (stream->ongoing_rotation.value.data_rotated &&
-                               stream->ongoing_rotation.value.index_rotated) {
+                   stream->ongoing_rotation.value.index_rotated) {
                        /* Rotation completed; reset its state. */
-                       DBG("Rotation completed for stream %" PRIu64,
-                                       stream->stream_handle);
+                       DBG("Rotation completed for stream %" PRIu64, stream->stream_handle);
                        stream_complete_rotation(stream);
                }
        }
@@ -537,15 +537,13 @@ end:
        return ret;
 }
 
-static int stream_set_trace_chunk(struct relay_stream *stream,
-               struct lttng_trace_chunk *chunk)
+static int stream_set_trace_chunk(struct relay_stream *stream, struct lttng_trace_chunk *chunk)
 {
        int ret = 0;
        enum lttng_trace_chunk_status status;
        bool acquired_reference;
 
-       status = lttng_trace_chunk_create_subdirectory(chunk,
-                       stream->path_name);
+       status = lttng_trace_chunk_create_subdirectory(chunk, stream->path_name);
        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end;
@@ -558,10 +556,9 @@ static int stream_set_trace_chunk(struct relay_stream *stream,
 
        if (stream->file) {
                fs_handle_close(stream->file);
-               stream->file = NULL;
+               stream->file = nullptr;
        }
-       ret = stream_create_data_output_file_from_trace_chunk(stream, chunk,
-                       false, &stream->file);
+       ret = stream_create_data_output_file_from_trace_chunk(stream, chunk, false, &stream->file);
 end:
        return ret;
 }
@@ -570,18 +567,20 @@ end:
  * We keep ownership of path_name and channel_name.
  */
 struct relay_stream *stream_create(struct ctf_trace *trace,
-       uint64_t stream_handle, char *path_name,
-       char *channel_name, uint64_t tracefile_size,
-       uint64_t tracefile_count)
+                                  uint64_t stream_handle,
+                                  char *path_name,
+                                  char *channel_name,
+                                  uint64_t tracefile_size,
+                                  uint64_t tracefile_count)
 {
        int ret;
-       struct relay_stream *stream = NULL;
+       struct relay_stream *stream = nullptr;
        struct relay_session *session = trace->session;
        bool acquired_reference = false;
        struct lttng_trace_chunk *current_trace_chunk;
 
        stream = zmalloc<relay_stream>();
-       if (stream == NULL) {
+       if (stream == nullptr) {
                PERROR("relay stream zmalloc");
                goto error_no_alloc;
        }
@@ -597,7 +596,7 @@ struct relay_stream *stream_create(struct ctf_trace *trace,
        stream->channel_name = channel_name;
        stream->beacon_ts_end = -1ULL;
        lttng_ht_node_init_u64(&stream->node, stream->stream_handle);
-       pthread_mutex_init(&stream->lock, NULL);
+       pthread_mutex_init(&stream->lock, nullptr);
        urcu_ref_init(&stream->ref);
        ctf_trace_get(trace);
        stream->trace = trace;
@@ -610,7 +609,7 @@ struct relay_stream *stream_create(struct ctf_trace *trace,
        pthread_mutex_unlock(&trace->session->lock);
        if (!acquired_reference) {
                ERR("Cannot create stream for channel \"%s\" as a reference to the session's current trace chunk could not be acquired",
-                               channel_name);
+                   channel_name);
                ret = -1;
                goto end;
        }
@@ -627,8 +626,8 @@ struct relay_stream *stream_create(struct ctf_trace *trace,
        pthread_mutex_unlock(&stream->lock);
        if (ret) {
                ERR("Failed to set the current trace chunk of session \"%s\" on newly created stream of channel \"%s\"",
-                               trace->session->session_name,
-                               stream->channel_name);
+                   trace->session->session_name,
+                   stream->channel_name);
                ret = -1;
                goto end;
        }
@@ -638,8 +637,7 @@ struct relay_stream *stream_create(struct ctf_trace *trace,
                goto end;
        }
 
-       stream->is_metadata = !strcmp(stream->channel_name,
-                       DEFAULT_METADATA_NAME);
+       stream->is_metadata = !strcmp(stream->channel_name, DEFAULT_METADATA_NAME);
        stream->in_recv_list = true;
 
        /*
@@ -658,18 +656,19 @@ struct relay_stream *stream_create(struct ctf_trace *trace,
        lttng_ht_add_unique_u64(relay_streams_ht, &stream->node);
        stream->in_stream_ht = true;
 
-       DBG("Relay new stream added %s with ID %" PRIu64, stream->channel_name,
-                       stream->stream_handle);
+       DBG("Relay new stream added %s with ID %" PRIu64,
+           stream->channel_name,
+           stream->stream_handle);
        ret = 0;
 
 end:
        if (ret) {
                if (stream->file) {
-                       fs_handle_close(stream->file);
-                       stream->file = NULL;
+                       fs_handle_close(stream->file);
+                       stream->file = nullptr;
                }
                stream_put(stream);
-               stream = NULL;
+               stream = nullptr;
        }
        if (acquired_reference) {
                lttng_trace_chunk_put(current_trace_chunk);
@@ -683,7 +682,7 @@ error_no_alloc:
         */
        free(path_name);
        free(channel_name);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -759,8 +758,7 @@ static void stream_destroy(struct relay_stream *stream)
 
 static void stream_destroy_rcu(struct rcu_head *rcu_head)
 {
-       struct relay_stream *stream =
-               lttng::utils::container_of(rcu_head, &relay_stream::rcu_node);
+       struct relay_stream *stream = lttng::utils::container_of(rcu_head, &relay_stream::rcu_node);
 
        stream_destroy(stream);
 }
@@ -771,8 +769,7 @@ static void stream_destroy_rcu(struct rcu_head *rcu_head)
  */
 static void stream_release(struct urcu_ref *ref)
 {
-       struct relay_stream *stream =
-               lttng::utils::container_of(ref, &relay_stream::ref);
+       struct relay_stream *stream = lttng::utils::container_of(ref, &relay_stream::ref);
        struct relay_session *session;
 
        session = stream->trace->session;
@@ -791,38 +788,37 @@ static void stream_release(struct urcu_ref *ref)
 
        if (stream->file) {
                fs_handle_close(stream->file);
-               stream->file = NULL;
+               stream->file = nullptr;
        }
        if (stream->index_file) {
                lttng_index_file_put(stream->index_file);
-               stream->index_file = NULL;
+               stream->index_file = nullptr;
        }
        if (stream->trace) {
                ctf_trace_put(stream->trace);
-               stream->trace = NULL;
+               stream->trace = nullptr;
        }
        stream_complete_rotation(stream);
        lttng_trace_chunk_put(stream->trace_chunk);
-       stream->trace_chunk = NULL;
+       stream->trace_chunk = nullptr;
 
        call_rcu(&stream->rcu_node, stream_destroy_rcu);
 }
 
 void stream_put(struct relay_stream *stream)
 {
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        LTTNG_ASSERT(stream->ref.refcount != 0);
        /*
         * Wait until we have processed all the stream packets before
         * actually putting our last stream reference.
         */
        urcu_ref_put(&stream->ref, stream_release);
-       rcu_read_unlock();
 }
 
 int stream_set_pending_rotation(struct relay_stream *stream,
-               struct lttng_trace_chunk *next_trace_chunk,
-               uint64_t rotation_sequence_number)
+                               struct lttng_trace_chunk *next_trace_chunk,
+                               uint64_t rotation_sequence_number)
 {
        int ret = 0;
        const struct relay_stream_rotation rotation = {
@@ -840,16 +836,16 @@ int stream_set_pending_rotation(struct relay_stream *stream,
        }
 
        if (next_trace_chunk) {
-               const bool reference_acquired =
-                               lttng_trace_chunk_get(next_trace_chunk);
+               const bool reference_acquired = lttng_trace_chunk_get(next_trace_chunk);
 
                LTTNG_ASSERT(reference_acquired);
        }
        LTTNG_OPTIONAL_SET(&stream->ongoing_rotation, rotation);
 
        DBG("Setting pending rotation: stream_id = %" PRIu64
-                       ", rotate_at_packet_seq_num = %" PRIu64,
-                       stream->stream_handle, rotation_sequence_number);
+           ", rotate_at_packet_seq_num = %" PRIu64,
+           stream->stream_handle,
+           rotation_sequence_number);
        if (stream->is_metadata) {
                /*
                 * A metadata stream has no index; consider it already rotated.
@@ -895,7 +891,8 @@ void try_stream_close(struct relay_stream *stream)
         */
        if (stream->closed) {
                pthread_mutex_unlock(&stream->lock);
-               DBG("closing stream %" PRIu64 " aborted since it is already marked as closed", stream->stream_handle);
+               DBG("closing stream %" PRIu64 " aborted since it is already marked as closed",
+                   stream->stream_handle);
                return;
        }
 
@@ -931,8 +928,8 @@ void try_stream_close(struct relay_stream *stream)
        }
 
        if (stream->last_net_seq_num != -1ULL &&
-                       ((int64_t) (stream->prev_data_seq - stream->last_net_seq_num)) < 0
-                       && !session_aborted) {
+           ((int64_t) (stream->prev_data_seq - stream->last_net_seq_num)) < 0 &&
+           !session_aborted) {
                /*
                 * Don't close since we still have data pending. This
                 * handles cases where an explicit close command has
@@ -950,7 +947,8 @@ void try_stream_close(struct relay_stream *stream)
                 * expected behavior.
                 */
                pthread_mutex_unlock(&stream->lock);
-               DBG("closing stream %" PRIu64 " aborted since it still has data pending", stream->stream_handle);
+               DBG("closing stream %" PRIu64 " aborted since it still has data pending",
+                   stream->stream_handle);
                return;
        }
        /*
@@ -973,29 +971,30 @@ void try_stream_close(struct relay_stream *stream)
        /* Put stream fd before put chunk. */
        if (stream->file) {
                fs_handle_close(stream->file);
-               stream->file = NULL;
+               stream->file = nullptr;
        }
        if (stream->index_file) {
                lttng_index_file_put(stream->index_file);
-               stream->index_file = NULL;
+               stream->index_file = nullptr;
        }
        lttng_trace_chunk_put(stream->trace_chunk);
-       stream->trace_chunk = NULL;
+       stream->trace_chunk = nullptr;
        pthread_mutex_unlock(&stream->lock);
        DBG("Succeeded in closing stream %" PRIu64, stream->stream_handle);
        stream_put(stream);
 }
 
-int stream_init_packet(struct relay_stream *stream, size_t packet_size,
-               bool *file_rotated)
+int stream_init_packet(struct relay_stream *stream, size_t packet_size, bool *file_rotated)
 {
        int ret = 0;
 
        ASSERT_LOCKED(stream->lock);
 
        if (!stream->file || !stream->trace_chunk) {
-               ERR("Protocol error: received a packet for a stream that doesn't have a current trace chunk: stream_id = %" PRIu64 ", channel_name = %s",
-                               stream->stream_handle, stream->channel_name);
+               ERR("Protocol error: received a packet for a stream that doesn't have a current trace chunk: stream_id = %" PRIu64
+                   ", channel_name = %s",
+                   stream->stream_handle,
+                   stream->channel_name);
                ret = -1;
                goto end;
        }
@@ -1008,34 +1007,34 @@ int stream_init_packet(struct relay_stream *stream, size_t packet_size,
        /*
         * Check if writing the new packet would exceed the maximal file size.
         */
-       if (caa_unlikely((stream->tracefile_size_current + packet_size) >
-                       stream->tracefile_size)) {
+       if (caa_unlikely((stream->tracefile_size_current + packet_size) > stream->tracefile_size)) {
                const uint64_t new_file_index =
-                               (stream->tracefile_current_index + 1) %
-                               stream->tracefile_count;
+                       (stream->tracefile_current_index + 1) % stream->tracefile_count;
 
                if (new_file_index < stream->tracefile_current_index) {
                        stream->tracefile_wrapped_around = true;
                }
                DBG("New stream packet causes stream file rotation: stream_id = %" PRIu64
-                               ", current_file_size = %" PRIu64
-                               ", packet_size = %zu, current_file_index = %" PRIu64
-                               " new_file_index = %" PRIu64,
-                               stream->stream_handle,
-                               stream->tracefile_size_current, packet_size,
-                               stream->tracefile_current_index, new_file_index);
+                   ", current_file_size = %" PRIu64
+                   ", packet_size = %zu, current_file_index = %" PRIu64
+                   " new_file_index = %" PRIu64,
+                   stream->stream_handle,
+                   stream->tracefile_size_current,
+                   packet_size,
+                   stream->tracefile_current_index,
+                   new_file_index);
                tracefile_array_file_rotate(stream->tfa, TRACEFILE_ROTATE_WRITE);
                stream->tracefile_current_index = new_file_index;
 
                if (stream->file) {
-                       fs_handle_close(stream->file);
-                       stream->file = NULL;
+                       fs_handle_close(stream->file);
+                       stream->file = nullptr;
                }
-               ret = stream_create_data_output_file_from_trace_chunk(stream,
-                               stream->trace_chunk, false, &stream->file);
+               ret = stream_create_data_output_file_from_trace_chunk(
+                       stream, stream->trace_chunk, false, &stream->file);
                if (ret) {
                        ERR("Failed to perform trace file rotation of stream %" PRIu64,
-                                       stream->stream_handle);
+                           stream->stream_handle);
                        goto end;
                }
 
@@ -1044,7 +1043,9 @@ int stream_init_packet(struct relay_stream *stream, size_t packet_size,
                 * rotation.
                 */
                DBG("%s: reset tracefile_size_current for stream %" PRIu64 " was %" PRIu64,
-                       __func__, stream->stream_handle, stream->tracefile_size_current);
+                   __func__,
+                   stream->stream_handle,
+                   stream->tracefile_size_current);
                stream->tracefile_size_current = 0;
                *file_rotated = true;
        } else {
@@ -1056,7 +1057,8 @@ end:
 
 /* Note that the packet is not necessarily complete. */
 int stream_write(struct relay_stream *stream,
-               const struct lttng_buffer_view *packet, size_t padding_len)
+                const struct lttng_buffer_view *packet,
+                size_t padding_len)
 {
        int ret = 0;
        ssize_t write_ret;
@@ -1064,22 +1066,22 @@ int stream_write(struct relay_stream *stream,
        char padding_buffer[FILE_IO_STACK_BUFFER_SIZE];
 
        ASSERT_LOCKED(stream->lock);
-       memset(padding_buffer, 0,
-                       std::min(sizeof(padding_buffer), padding_to_write));
+       memset(padding_buffer, 0, std::min(sizeof(padding_buffer), padding_to_write));
 
        if (!stream->file || !stream->trace_chunk) {
-               ERR("Protocol error: received a packet for a stream that doesn't have a current trace chunk: stream_id = %" PRIu64 ", channel_name = %s",
-                               stream->stream_handle, stream->channel_name);
+               ERR("Protocol error: received a packet for a stream that doesn't have a current trace chunk: stream_id = %" PRIu64
+                   ", channel_name = %s",
+                   stream->stream_handle,
+                   stream->channel_name);
                ret = -1;
                goto end;
        }
        if (packet) {
-               write_ret = fs_handle_write(
-                               stream->file, packet->data, packet->size);
+               write_ret = fs_handle_write(stream->file, packet->data, packet->size);
                if (write_ret != packet->size) {
                        PERROR("Failed to write to stream file of %sstream %" PRIu64,
-                                       stream->is_metadata ? "metadata " : "",
-                                       stream->stream_handle);
+                              stream->is_metadata ? "metadata " : "",
+                              stream->stream_handle);
                        ret = -1;
                        goto end;
                }
@@ -1087,14 +1089,14 @@ int stream_write(struct relay_stream *stream,
 
        while (padding_to_write > 0) {
                const size_t padding_to_write_this_pass =
-                               std::min(padding_to_write, sizeof(padding_buffer));
+                       std::min(padding_to_write, sizeof(padding_buffer));
 
-               write_ret = fs_handle_write(stream->file, padding_buffer,
-                               padding_to_write_this_pass);
+               write_ret =
+                       fs_handle_write(stream->file, padding_buffer, padding_to_write_this_pass);
                if (write_ret != padding_to_write_this_pass) {
                        PERROR("Failed to write padding to file of %sstream %" PRIu64,
-                                       stream->is_metadata ? "metadata " : "",
-                                       stream->stream_handle);
+                              stream->is_metadata ? "metadata " : "",
+                              stream->stream_handle);
                        ret = -1;
                        goto end;
                }
@@ -1107,15 +1109,13 @@ int stream_write(struct relay_stream *stream,
                recv_len = packet ? packet->size : 0;
                recv_len += padding_len;
                stream->metadata_received += recv_len;
-               if (recv_len) {
-                       stream->no_new_metadata_notified = false;
-               }
        }
 
        DBG("Wrote to %sstream %" PRIu64 ": data_length = %zu, padding_length = %zu",
-                       stream->is_metadata ? "metadata " : "",
-                       stream->stream_handle,
-                       packet ? packet->size : (size_t) 0, padding_len);
+           stream->is_metadata ? "metadata " : "",
+           stream->stream_handle,
+           packet ? packet->size : (size_t) 0,
+           padding_len);
 end:
        return ret;
 }
@@ -1127,8 +1127,11 @@ end:
  *
  * Return 0 on success else a negative value.
  */
-int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
-               bool rotate_index, bool *flushed, uint64_t total_size)
+int stream_update_index(struct relay_stream *stream,
+                       uint64_t net_seq_num,
+                       bool rotate_index,
+                       bool *flushed,
+                       uint64_t total_size)
 {
        int ret = 0;
        uint64_t data_offset;
@@ -1140,7 +1143,9 @@ int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
        data_offset = htobe64(stream->tracefile_size_current);
 
        DBG("handle_index_data: stream %" PRIu64 " net_seq_num %" PRIu64 " data offset %" PRIu64,
-                       stream->stream_handle, net_seq_num, stream->tracefile_size_current);
+           stream->stream_handle,
+           net_seq_num,
+           stream->tracefile_size_current);
 
        /*
         * Lookup for an existing index for that stream id/sequence
@@ -1157,10 +1162,10 @@ int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
                ret = create_index_file(stream, stream->trace_chunk);
                if (ret) {
                        ERR("Failed to create index file for stream %" PRIu64,
-                                       stream->stream_handle);
+                           stream->stream_handle);
                        /* Put self-ref for this index due to error. */
                        relay_index_put(index);
-                       index = NULL;
+                       index = nullptr;
                        goto end;
                }
        }
@@ -1169,7 +1174,7 @@ int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
                ret = -1;
                /* Put self-ref for this index due to error. */
                relay_index_put(index);
-               index = NULL;
+               index = nullptr;
                goto end;
        }
 
@@ -1179,7 +1184,7 @@ int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
                tracefile_array_commit_seq(stream->tfa, stream->index_received_seqcount);
                stream->index_received_seqcount++;
                LTTNG_OPTIONAL_SET(&stream->received_packet_seq_num,
-                       be64toh(index->index_data.packet_seq_num));
+                                  be64toh(index->index_data.packet_seq_num));
                *flushed = true;
        } else if (ret > 0) {
                index->total_size = total_size;
@@ -1199,8 +1204,10 @@ end:
        return ret;
 }
 
-int stream_complete_packet(struct relay_stream *stream, size_t packet_total_size,
-               uint64_t sequence_number, bool index_flushed)
+int stream_complete_packet(struct relay_stream *stream,
+                          size_t packet_total_size,
+                          uint64_t sequence_number,
+                          bool index_flushed)
 {
        int ret = 0;
 
@@ -1208,8 +1215,7 @@ int stream_complete_packet(struct relay_stream *stream, size_t packet_total_size
 
        stream->tracefile_size_current += packet_total_size;
        if (index_flushed) {
-               stream->pos_after_last_complete_data_index =
-                               stream->tracefile_size_current;
+               stream->pos_after_last_complete_data_index = stream->tracefile_size_current;
                stream->prev_index_seq = sequence_number;
                ret = try_rotate_stream_index(stream);
                if (ret < 0) {
@@ -1224,8 +1230,7 @@ end:
        return ret;
 }
 
-int stream_add_index(struct relay_stream *stream,
-               const struct lttcomm_relayd_index *index_info)
+int stream_add_index(struct relay_stream *stream, const struct lttcomm_relayd_index *index_info)
 {
        int ret = 0;
        struct relay_index *index;
@@ -1236,15 +1241,13 @@ int stream_add_index(struct relay_stream *stream,
 
        /* Live beacon handling */
        if (index_info->packet_size == 0) {
-               DBG("Received live beacon for stream %" PRIu64,
-                               stream->stream_handle);
+               DBG("Received live beacon for stream %" PRIu64, stream->stream_handle);
 
                /*
                 * Only flag a stream inactive when it has already
                 * received data and no indexes are in flight.
                 */
-               if (stream->index_received_seqcount > 0
-                               && stream->indexes_in_flight == 0) {
+               if (stream->index_received_seqcount > 0 && stream->indexes_in_flight == 0) {
                        stream->beacon_ts_end = index_info->timestamp_end;
                }
                ret = 0;
@@ -1260,12 +1263,10 @@ int stream_add_index(struct relay_stream *stream,
        index = relay_index_get_by_id_or_create(stream, index_info->net_seq_num);
        if (!index) {
                ret = -1;
-               ERR("Failed to get or create index %" PRIu64,
-                               index_info->net_seq_num);
+               ERR("Failed to get or create index %" PRIu64, index_info->net_seq_num);
                goto end;
        }
-       if (relay_index_set_control_data(index, index_info,
-                       stream->trace->session->minor)) {
+       if (relay_index_set_control_data(index, index_info, stream->trace->session->minor)) {
                ERR("set_index_control_data error");
                relay_index_put(index);
                ret = -1;
@@ -1278,8 +1279,7 @@ int stream_add_index(struct relay_stream *stream,
                stream->index_received_seqcount++;
                stream->pos_after_last_complete_data_index += index->total_size;
                stream->prev_index_seq = index_info->net_seq_num;
-               LTTNG_OPTIONAL_SET(&stream->received_packet_seq_num,
-                               index_info->packet_seq_num);
+               LTTNG_OPTIONAL_SET(&stream->received_packet_seq_num, index_info->packet_seq_num);
 
                ret = try_rotate_stream_index(stream);
                if (ret < 0) {
@@ -1311,20 +1311,20 @@ static void print_stream_indexes(struct relay_stream *stream)
        struct lttng_ht_iter iter;
        struct relay_index *index;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(stream->indexes_ht->ht, &iter.iter, index,
-                       index_n.node) {
-               DBG("index %p net_seq_num %" PRIu64 " refcount %ld"
-                               " stream %" PRIu64 " trace %" PRIu64
-                               " session %" PRIu64,
-                               index,
-                               index->index_n.key,
-                               stream->ref.refcount,
-                               index->stream->stream_handle,
-                               index->stream->trace->id,
-                               index->stream->trace->session->id);
-       }
-       rcu_read_unlock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (stream->indexes_ht->ht, &iter.iter, index, index_n.node) {
+                       DBG("index %p net_seq_num %" PRIu64 " refcount %ld"
+                           " stream %" PRIu64 " trace %" PRIu64 " session %" PRIu64,
+                           index,
+                           index->index_n.key,
+                           stream->ref.refcount,
+                           index->stream->stream_handle,
+                           index->stream->trace->id,
+                           index->stream->trace->session->id);
+               }
+       }
 }
 
 int stream_reset_file(struct relay_stream *stream)
@@ -1337,14 +1337,16 @@ int stream_reset_file(struct relay_stream *stream)
                ret = fs_handle_close(stream->file);
                if (ret) {
                        ERR("Failed to close stream file handle: channel name = \"%s\", id = %" PRIu64,
-                                       stream->channel_name,
-                                       stream->stream_handle);
+                           stream->channel_name,
+                           stream->stream_handle);
                }
-               stream->file = NULL;
+               stream->file = nullptr;
        }
 
        DBG("%s: reset tracefile_size_current for stream %" PRIu64 " was %" PRIu64,
-                       __func__, stream->stream_handle, stream->tracefile_size_current);
+           __func__,
+           stream->stream_handle,
+           stream->tracefile_size_current);
        stream->tracefile_size_current = 0;
        stream->prev_data_seq = 0;
        stream->prev_index_seq = 0;
@@ -1352,11 +1354,11 @@ int stream_reset_file(struct relay_stream *stream)
        stream->tracefile_current_index = 0;
        stream->pos_after_last_complete_data_index = 0;
 
-       return stream_create_data_output_file_from_trace_chunk(stream,
-                       stream->trace_chunk, true, &stream->file);
+       return stream_create_data_output_file_from_trace_chunk(
+               stream, stream->trace_chunk, true, &stream->file);
 }
 
-void print_relay_streams(void)
+void print_relay_streams()
 {
        struct lttng_ht_iter iter;
        struct relay_stream *stream;
@@ -1365,21 +1367,23 @@ void print_relay_streams(void)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
-                       node.node) {
-               if (!stream_get(stream)) {
-                       continue;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (relay_streams_ht->ht, &iter.iter, stream, node.node) {
+                       if (!stream_get(stream)) {
+                               continue;
+                       }
+
+                       DBG("stream %p refcount %ld stream %" PRIu64 " trace %" PRIu64
+                           " session %" PRIu64,
+                           stream,
+                           stream->ref.refcount,
+                           stream->stream_handle,
+                           stream->trace->id,
+                           stream->trace->session->id);
+                       print_stream_indexes(stream);
+                       stream_put(stream);
                }
-               DBG("stream %p refcount %ld stream %" PRIu64 " trace %" PRIu64
-                               " session %" PRIu64,
-                               stream,
-                               stream->ref.refcount,
-                               stream->stream_handle,
-                               stream->trace->id,
-                               stream->trace->session->id);
-               print_stream_indexes(stream);
-               stream_put(stream);
        }
-       rcu_read_unlock();
 }
index 6e09c5571c5428c1d4a09efba0419d2e91035f21..40d840398e2e9bafadd5bf693cc9f8e576d32092 100644 (file)
  *
  */
 
-#include <limits.h>
-#include <inttypes.h>
-#include <pthread.h>
-#include <urcu/list.h>
+#include "session.hpp"
+#include "tracefile-array.hpp"
 
+#include <common/buffer-view.hpp>
 #include <common/hashtable/hashtable.hpp>
-#include <common/trace-chunk.hpp>
 #include <common/optional.hpp>
-#include <common/buffer-view.hpp>
+#include <common/trace-chunk.hpp>
 
-#include "session.hpp"
-#include "tracefile-array.hpp"
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <urcu/list.h>
 
 struct lttcomm_relayd_index;
 
@@ -56,8 +56,7 @@ struct relay_stream {
        struct ctf_trace *trace;
 
        /*
-        * To protect from concurrent read/update. The viewer stream
-        * lock nests inside the stream lock. The stream lock nests
+        * To protect from concurrent read/update.The stream lock nests
         * inside the ctf_trace lock.
         */
        pthread_mutex_t lock;
@@ -118,8 +117,8 @@ struct relay_stream {
         */
        struct tracefile_array *tfa;
 
-       bool closed;            /* Stream is closed. */
-       bool close_requested;   /* Close command has been received. */
+       bool closed; /* Stream is closed. */
+       bool close_requested; /* Close command has been received. */
 
        /*
         * Counts number of indexes in indexes_ht. Redundant info.
@@ -163,14 +162,12 @@ struct relay_stream {
        struct cds_list_head recv_node;
        /* Protected by session lock. */
        bool published;
-       /* Notified viewer that no new metadata is available. */
-       bool no_new_metadata_notified;
        /*
         * Node of stream within global stream hash table.
         */
        struct lttng_ht_node_u64 node;
-       bool in_stream_ht;              /* is stream in stream hash table. */
-       struct rcu_head rcu_node;       /* For call_rcu teardown. */
+       bool in_stream_ht; /* is stream in stream hash table. */
+       struct rcu_head rcu_node; /* For call_rcu teardown. */
        /*
         * The trace chunk to which the file currently being produced (if any)
         * belongs.
@@ -186,35 +183,39 @@ struct relay_stream {
 };
 
 struct relay_stream *stream_create(struct ctf_trace *trace,
-       uint64_t stream_handle, char *path_name,
-       char *channel_name, uint64_t tracefile_size,
-       uint64_t tracefile_count);
+                                  uint64_t stream_handle,
+                                  char *path_name,
+                                  char *channel_name,
+                                  uint64_t tracefile_size,
+                                  uint64_t tracefile_count);
 
 struct relay_stream *stream_get_by_id(uint64_t stream_id);
 bool stream_get(struct relay_stream *stream);
 void stream_put(struct relay_stream *stream);
-int stream_rotate_output_files(struct relay_session *session,
-               struct relay_stream *stream);
+int stream_rotate_output_files(struct relay_session *session, struct relay_stream *stream);
 int stream_set_pending_rotation(struct relay_stream *stream,
-               struct lttng_trace_chunk *next_trace_chunk,
-               uint64_t rotation_sequence_number);
+                               struct lttng_trace_chunk *next_trace_chunk,
+                               uint64_t rotation_sequence_number);
 void try_stream_close(struct relay_stream *stream);
 void stream_publish(struct relay_stream *stream);
-int stream_init_packet(struct relay_stream *stream, size_t packet_size,
-               bool *file_rotated);
+int stream_init_packet(struct relay_stream *stream, size_t packet_size, bool *file_rotated);
 int stream_write(struct relay_stream *stream,
-               const struct lttng_buffer_view *packet, size_t padding_len);
+                const struct lttng_buffer_view *packet,
+                size_t padding_len);
 /* Called after the reception of a complete data packet. */
-int stream_update_index(struct relay_stream *stream, uint64_t net_seq_num,
-               bool rotate_index, bool *flushed, uint64_t total_size);
+int stream_update_index(struct relay_stream *stream,
+                       uint64_t net_seq_num,
+                       bool rotate_index,
+                       bool *flushed,
+                       uint64_t total_size);
 int stream_complete_packet(struct relay_stream *stream,
-               size_t packet_total_size, uint64_t sequence_number,
-               bool index_flushed);
+                          size_t packet_total_size,
+                          uint64_t sequence_number,
+                          bool index_flushed);
 /* Index info is in host endianness. */
-int stream_add_index(struct relay_stream *stream,
-               const struct lttcomm_relayd_index *index_info);
+int stream_add_index(struct relay_stream *stream, const struct lttcomm_relayd_index *index_info);
 int stream_reset_file(struct relay_stream *stream);
 
-void print_relay_streams(void);
+void print_relay_streams();
 
 #endif /* _STREAM_H */
index d632b77426966c7bbc80c7659e93b88cf3660455..93bc0b396e09a79055cedf5fb829f8e53fccfd16 100644 (file)
@@ -5,34 +5,34 @@
  *
  */
 
-#include <sys/types.h>
-#include <netinet/tcp.h>
-#include <stdbool.h>
-#include <sys/socket.h>
-#include <limits.h>
+#include "tcp_keep_alive.hpp"
 
 #include <common/compat/getenv.hpp>
-#include <common/time.hpp>
 #include <common/defaults.hpp>
 #include <common/ini-config/ini-config.hpp>
+#include <common/time.hpp>
 
-#include "tcp_keep_alive.hpp"
+#include <limits.h>
+#include <netinet/tcp.h>
+#include <stdbool.h>
+#include <sys/socket.h>
+#include <sys/types.h>
 
-#define SOLARIS_IDLE_TIME_MIN_S 10
-#define SOLARIS_IDLE_TIME_MAX_S 864000 /* 10 days */
+#define SOLARIS_IDLE_TIME_MIN_S              10
+#define SOLARIS_IDLE_TIME_MAX_S              864000 /* 10 days */
 #define SOLARIS_ABORT_THRESHOLD_MIN_S 1
 #define SOLARIS_ABORT_THRESHOLD_MAX_S 480 /* 8 minutes */
 
 /* Per-platform definitions of TCP socket options. */
-#if defined (__linux__)
+#if defined(__linux__)
 
-#define COMPAT_TCP_LEVEL SOL_TCP
+#define COMPAT_TCP_LEVEL          SOL_TCP
 #define COMPAT_TCP_ABORT_THRESHOLD 0 /* Does not exist on linux. */
-#define COMPAT_TCP_KEEPIDLE TCP_KEEPIDLE
-#define COMPAT_TCP_KEEPINTVL TCP_KEEPINTVL
-#define COMPAT_TCP_KEEPCNT TCP_KEEPCNT
+#define COMPAT_TCP_KEEPIDLE       TCP_KEEPIDLE
+#define COMPAT_TCP_KEEPINTVL      TCP_KEEPINTVL
+#define COMPAT_TCP_KEEPCNT        TCP_KEEPCNT
 
-#elif defined (__sun__) /* ! defined (__linux__) */
+#elif defined(__sun__) /* ! defined (__linux__) */
 
 #define COMPAT_TCP_LEVEL IPPROTO_TCP
 
 #endif /* TCP_KEEPALIVE_ABORT_THRESHOLD */
 
 #define COMPAT_TCP_KEEPINTVL 0 /* Does not exist on Solaris. */
-#define COMPAT_TCP_KEEPCNT 0 /* Does not exist on Solaris. */
+#define COMPAT_TCP_KEEPCNT   0 /* Does not exist on Solaris. */
 
 #else /* ! defined (__linux__) && ! defined (__sun__) */
 
-#define COMPAT_TCP_LEVEL 0
+#define COMPAT_TCP_LEVEL          0
 #define COMPAT_TCP_ABORT_THRESHOLD 0
-#define COMPAT_TCP_KEEPIDLE 0
-#define COMPAT_TCP_KEEPINTVL 0
-#define COMPAT_TCP_KEEPCNT 0
+#define COMPAT_TCP_KEEPIDLE       0
+#define COMPAT_TCP_KEEPINTVL      0
+#define COMPAT_TCP_KEEPCNT        0
 
 #endif /* ! defined (__linux__) && ! defined (__sun__) */
 
@@ -106,17 +106,17 @@ struct tcp_keep_alive_config {
        int abort_threshold;
 };
 
-struct tcp_keep_alive_config the_config = {.enabled = false,
-               .idle_time = -1,
-               .probe_interval = -1,
-               .max_probe_count = -1,
-               .abort_threshold = -1};
-
-struct tcp_keep_alive_support the_support = {.supported = false,
-               .idle_time_supported = false,
-               .probe_interval_supported = false,
-               .max_probe_count_supported = false,
-               .abort_threshold_supported = false};
+struct tcp_keep_alive_config the_config = { .enabled = false,
+                                           .idle_time = -1,
+                                           .probe_interval = -1,
+                                           .max_probe_count = -1,
+                                           .abort_threshold = -1 };
+
+struct tcp_keep_alive_support the_support = { .supported = false,
+                                             .idle_time_supported = false,
+                                             .probe_interval_supported = false,
+                                             .max_probe_count_supported = false,
+                                             .abort_threshold_supported = false };
 } /* namespace */
 
 /*
@@ -125,13 +125,11 @@ struct tcp_keep_alive_support the_support = {.supported = false,
  *
  * Returns -2 on invalid value.
  */
-static
-int get_env_int(const char *env_var,
-               const char *value)
+static int get_env_int(const char *env_var, const char *value)
 {
        int ret;
        long tmp;
-       char *endptr = NULL;
+       char *endptr = nullptr;
 
        errno = 0;
        tmp = strtol(value, &endptr, 0);
@@ -143,9 +141,9 @@ int get_env_int(const char *env_var,
        }
 
        if (endptr == value || *endptr != '\0') {
-           ERR("%s is not a valid number", env_var);
-           ret = -1;
-           goto end;
+               ERR("%s is not a valid number", env_var);
+               ret = -1;
+               goto end;
        }
 
        if (tmp < -1) {
@@ -153,7 +151,7 @@ int get_env_int(const char *env_var,
                ret = -2;
                goto end;
        }
-       if (tmp > INT_MAX){
+       if (tmp > INT_MAX) {
                ERR("%s is too big. Maximum value is %d", env_var, INT_MAX);
                ret = -2;
                goto end;
@@ -170,8 +168,7 @@ end:
  */
 #ifdef __sun__
 
-static
-int convert_idle_time(int value)
+static int convert_idle_time(int value)
 {
        int ret;
        unsigned int tmp_ms;
@@ -193,26 +190,24 @@ int convert_idle_time(int value)
         * Minimum 10s, maximum 10 days. Defined by
         * https://docs.oracle.com/cd/E23824_01/html/821-1475/tcp-7p.html#REFMAN7tcp-7p
         */
-       if ((value < SOLARIS_IDLE_TIME_MIN_S ||
-                       value > SOLARIS_IDLE_TIME_MAX_S)) {
+       if ((value < SOLARIS_IDLE_TIME_MIN_S || value > SOLARIS_IDLE_TIME_MAX_S)) {
                ERR("%s must be comprised between %d and %d inclusively on Solaris",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
-                               SOLARIS_IDLE_TIME_MIN_S,
-                               SOLARIS_IDLE_TIME_MAX_S);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
+                   SOLARIS_IDLE_TIME_MIN_S,
+                   SOLARIS_IDLE_TIME_MAX_S);
                ret = -2;
                goto end;
        }
 
        /* On Solaris idle time is given in milliseconds. */
        tmp_ms = ((unsigned int) value) * MSEC_PER_SEC;
-       if ((value != 0 && (tmp_ms / ((unsigned int) value)) != MSEC_PER_SEC)
-                       || tmp_ms > INT_MAX) {
+       if ((value != 0 && (tmp_ms / ((unsigned int) value)) != MSEC_PER_SEC) || tmp_ms > INT_MAX) {
                /* Overflow. */
                const int max_value = INT_MAX / MSEC_PER_SEC;
 
                ERR("%s is too big: maximum supported value is %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
-                               max_value);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
+                   max_value);
                ret = -2;
                goto end;
        }
@@ -225,8 +220,7 @@ end:
 
 #else /* ! defined(__sun__) */
 
-static
-int convert_idle_time(int value)
+static int convert_idle_time(int value)
 {
        return value;
 }
@@ -234,10 +228,9 @@ int convert_idle_time(int value)
 #endif /* ! defined(__sun__) */
 
 /* Per-platform support of tcp_keep_alive functionality. */
-#if defined (__linux__)
+#if defined(__linux__)
 
-static
-void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
+static void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
 {
        support->supported = true;
        support->idle_time_supported = true;
@@ -249,14 +242,14 @@ void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
 
 #elif defined(__sun__) /* ! defined (__linux__) */
 
-static
-void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
+static void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
 {
        support->supported = true;
 #ifdef TCP_KEEPALIVE_THRESHOLD
        support->idle_time_supported = true;
 #else
-       support->idle_time_supported = false;;
+       support->idle_time_supported = false;
+       ;
 #endif /* TCP_KEEPALIVE_THRESHOLD */
 
        /*
@@ -282,8 +275,7 @@ void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
 #else /* ! defined(__sun__) && ! defined(__linux__) */
 
 /* Assume nothing is supported on other platforms. */
-static
-void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
+static void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
 {
        support->supported = false;
        support->idle_time_supported = false;
@@ -300,8 +292,7 @@ void tcp_keep_alive_init_support(struct tcp_keep_alive_support *support)
  * Solaris specific modifier for abort threshold.
  * Return -2 on error.
  */
-static
-int convert_abort_threshold(int value)
+static int convert_abort_threshold(int value)
 {
        int ret;
        unsigned int tmp_ms;
@@ -330,23 +321,22 @@ int convert_abort_threshold(int value)
         */
        if ((value < SOLARIS_ABORT_THRESHOLD_MIN_S || value > SOLARIS_ABORT_THRESHOLD_MAX_S)) {
                ERR("%s must be comprised between %d and %d inclusively on Solaris",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
-                               SOLARIS_ABORT_THRESHOLD_MIN_S,
-                               SOLARIS_ABORT_THRESHOLD_MAX_S);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
+                   SOLARIS_ABORT_THRESHOLD_MIN_S,
+                   SOLARIS_ABORT_THRESHOLD_MAX_S);
                ret = -2;
                goto end;
        }
 
        /* Abort threshold is given in milliseconds. */
        tmp_ms = ((unsigned int) value) * MSEC_PER_SEC;
-       if ((value != 0 && (tmp_ms / ((unsigned int) value)) != MSEC_PER_SEC)
-                       || tmp_ms > INT_MAX) {
+       if ((value != 0 && (tmp_ms / ((unsigned int) value)) != MSEC_PER_SEC) || tmp_ms > INT_MAX) {
                /* Overflow */
                const int max_value = INT_MAX / MSEC_PER_SEC;
 
                ERR("%s is too big: maximum supported value is %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
-                               max_value);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
+                   max_value);
                ret = -2;
                goto end;
        }
@@ -359,8 +349,7 @@ end:
 
 #else
 
-static
-int convert_abort_threshold(int value)
+static int convert_abort_threshold(int value)
 {
        return value;
 }
@@ -371,9 +360,8 @@ int convert_abort_threshold(int value)
  * Retrieve settings from environment variables and warn for settings not
  * supported by the platform.
  */
-static
-int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
-               struct tcp_keep_alive_config *config)
+static int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
+                                     struct tcp_keep_alive_config *config)
 {
        int ret;
        const char *value;
@@ -382,7 +370,7 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
        if (!support->supported) {
                if (value) {
                        WARN("Using per-socket TCP keep-alive mechanism is not supported by this platform. Ignoring the %s environment variable.",
-                                       DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ENV);
+                            DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ENV);
                }
                config->enabled = false;
        } else if (value) {
@@ -394,21 +382,20 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
                }
                config->enabled = ret;
        }
-       DBG("TCP keep-alive mechanism %s", config->enabled ? "enabled": "disabled");
+       DBG("TCP keep-alive mechanism %s", config->enabled ? "enabled" : "disabled");
 
        /* Get value for tcp_keepalive_time in seconds. */
        value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV);
        if (!support->idle_time_supported && value) {
                WARN("Overriding the TCP keep-alive idle time threshold per-socket is not supported by this platform. Ignoring the %s environment variable.",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV);
+                    DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV);
                config->idle_time = -1;
        } else if (value) {
                int idle_time_platform;
                int idle_time_seconds;
 
-               idle_time_seconds = get_env_int(
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
-                               value);
+               idle_time_seconds =
+                       get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV, value);
                if (idle_time_seconds < -1) {
                        ret = 1;
                        goto error;
@@ -422,22 +409,21 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
 
                config->idle_time = idle_time_platform;
                DBG("Overriding %s to %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
-                               idle_time_seconds);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV,
+                   idle_time_seconds);
        }
 
        /* Get value for tcp_keepalive_intvl in seconds. */
-       value = lttng_secure_getenv(
-                       DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV);
+       value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV);
        if (!support->probe_interval_supported && value) {
                WARN("Overriding the TCP keep-alive probe interval time per-socket is not supported by this platform. Ignoring the %s environment variable.",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV);
+                    DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV);
                config->probe_interval = -1;
        } else if (value) {
                int probe_interval;
 
-               probe_interval = get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV,
-                               value);
+               probe_interval =
+                       get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV, value);
                if (probe_interval < -1) {
                        ret = 1;
                        goto error;
@@ -445,21 +431,21 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
 
                config->probe_interval = probe_interval;
                DBG("Overriding %s to %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV,
-                               config->probe_interval);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV,
+                   config->probe_interval);
        }
 
        /* Get value for tcp_keepalive_probes. */
        value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV);
        if (!support->max_probe_count_supported && value) {
                WARN("Overriding the TCP keep-alive maximum probe count per-socket is not supported by this platform. Ignoring the %s environment variable.",
-                                DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV);
+                    DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV);
                config->max_probe_count = -1;
        } else if (value) {
                int max_probe_count;
 
-               max_probe_count = get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV,
-                               value);
+               max_probe_count =
+                       get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV, value);
                if (max_probe_count < -1) {
                        ret = 1;
                        goto error;
@@ -467,31 +453,28 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
 
                config->max_probe_count = max_probe_count;
                DBG("Overriding %s to %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV,
-                               config->max_probe_count);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV,
+                   config->max_probe_count);
        }
 
        /* Get value for tcp_keepalive_abort_interval. */
-       value = lttng_secure_getenv(
-                       DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV);
+       value = lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV);
        if (!support->abort_threshold_supported && value) {
                WARN("Overriding the TCP keep-alive abort threshold per-socket is not supported by this platform. Ignoring the %s environment variable.",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV);
+                    DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV);
                config->abort_threshold = -1;
        } else if (value) {
                int abort_threshold_platform;
                int abort_threshold_seconds;
 
-               abort_threshold_seconds = get_env_int(
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV,
-                               value);
+               abort_threshold_seconds =
+                       get_env_int(DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV, value);
                if (abort_threshold_seconds < -1) {
                        ret = 1;
                        goto error;
                }
 
-               abort_threshold_platform = convert_abort_threshold(
-                               abort_threshold_seconds);
+               abort_threshold_platform = convert_abort_threshold(abort_threshold_seconds);
                if (abort_threshold_platform < -1) {
                        ret = 1;
                        goto error;
@@ -499,8 +482,8 @@ int tcp_keep_alive_init_config(struct tcp_keep_alive_support *support,
 
                config->abort_threshold = abort_threshold_platform;
                DBG("Overriding %s to %d",
-                               DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
-                               config->abort_threshold);
+                   DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV,
+                   config->abort_threshold);
        }
 
        ret = 0;
@@ -510,8 +493,7 @@ error:
 }
 
 /* Initialize the TCP keep-alive configuration. */
-__attribute__((constructor)) static
-void tcp_keep_alive_init(void)
+__attribute__((constructor)) static void tcp_keep_alive_init()
 {
        tcp_keep_alive_init_support(&the_support);
        (void) tcp_keep_alive_init_config(&the_support, &the_config);
@@ -532,8 +514,7 @@ int socket_apply_keep_alive_config(int socket_fd)
        }
 
        DBG("TCP keep-alive enabled for socket %d", socket_fd);
-       ret = setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, &val,
-                       sizeof(val));
+       ret = setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
        if (ret < 0) {
                PERROR("setsockopt so_keepalive");
                goto end;
@@ -542,24 +523,28 @@ int socket_apply_keep_alive_config(int socket_fd)
        /* TCP keep-alive idle time */
        if (the_support.idle_time_supported && the_config.idle_time > 0) {
                DBG("TCP keep-alive keep idle: %d enabled for socket %d",
-                               the_config.idle_time, socket_fd);
-               ret = setsockopt(socket_fd, COMPAT_TCP_LEVEL,
-                               COMPAT_TCP_KEEPIDLE, &the_config.idle_time,
-                               sizeof(the_config.idle_time));
+                   the_config.idle_time,
+                   socket_fd);
+               ret = setsockopt(socket_fd,
+                                COMPAT_TCP_LEVEL,
+                                COMPAT_TCP_KEEPIDLE,
+                                &the_config.idle_time,
+                                sizeof(the_config.idle_time));
                if (ret < 0) {
                        PERROR("setsockopt TCP_KEEPIDLE");
                        goto end;
                }
        }
        /* TCP keep-alive probe interval */
-       if (the_support.probe_interval_supported &&
-                       the_config.probe_interval > 0) {
+       if (the_support.probe_interval_supported && the_config.probe_interval > 0) {
                DBG("TCP keep-alive probe_interval: %d enabled for socket %d",
-                               the_config.probe_interval, socket_fd);
-               ret = setsockopt(socket_fd, COMPAT_TCP_LEVEL,
-                               COMPAT_TCP_KEEPINTVL,
-                               &the_config.probe_interval,
-                               sizeof(the_config.probe_interval));
+                   the_config.probe_interval,
+                   socket_fd);
+               ret = setsockopt(socket_fd,
+                                COMPAT_TCP_LEVEL,
+                                COMPAT_TCP_KEEPINTVL,
+                                &the_config.probe_interval,
+                                sizeof(the_config.probe_interval));
                if (ret < 0) {
                        PERROR("setsockopt TCP_KEEPINTVL");
                        goto end;
@@ -567,13 +552,15 @@ int socket_apply_keep_alive_config(int socket_fd)
        }
 
        /* TCP keep-alive max probe count */
-       if (the_support.max_probe_count_supported &&
-                       the_config.max_probe_count > 0) {
+       if (the_support.max_probe_count_supported && the_config.max_probe_count > 0) {
                DBG("TCP keep-alive max_probe: %d enabled for socket %d",
-                               the_config.max_probe_count, socket_fd);
-               ret = setsockopt(socket_fd, COMPAT_TCP_LEVEL,
-                               COMPAT_TCP_KEEPCNT, &the_config.max_probe_count,
-                               sizeof(the_config.max_probe_count));
+                   the_config.max_probe_count,
+                   socket_fd);
+               ret = setsockopt(socket_fd,
+                                COMPAT_TCP_LEVEL,
+                                COMPAT_TCP_KEEPCNT,
+                                &the_config.max_probe_count,
+                                sizeof(the_config.max_probe_count));
                if (ret < 0) {
                        PERROR("setsockopt TCP_KEEPCNT");
                        goto end;
@@ -581,14 +568,15 @@ int socket_apply_keep_alive_config(int socket_fd)
        }
 
        /* TCP keep-alive abort threshold */
-       if (the_support.abort_threshold_supported &&
-                       the_config.abort_threshold > 0) {
+       if (the_support.abort_threshold_supported && the_config.abort_threshold > 0) {
                DBG("TCP keep-alive abort threshold: %d enabled for socket %d",
-                               the_config.abort_threshold, socket_fd);
-               ret = setsockopt(socket_fd, COMPAT_TCP_LEVEL,
-                               COMPAT_TCP_ABORT_THRESHOLD,
-                               &the_config.abort_threshold,
-                               sizeof(the_config.max_probe_count));
+                   the_config.abort_threshold,
+                   socket_fd);
+               ret = setsockopt(socket_fd,
+                                COMPAT_TCP_LEVEL,
+                                COMPAT_TCP_ABORT_THRESHOLD,
+                                &the_config.abort_threshold,
+                                sizeof(the_config.max_probe_count));
                if (ret < 0) {
                        PERROR("setsockopt TCP_KEEPALIVE_ABORT_THRESHOLD");
                        goto end;
diff --git a/src/bin/lttng-relayd/thread-utils.cpp b/src/bin/lttng-relayd/thread-utils.cpp
new file mode 100644 (file)
index 0000000..8e09f6c
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2022 EfficiOS Inc.
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ *
+ */
+
+#include "lttng-relayd.hpp"
+
+#include <common/compat/poll.hpp>
+#include <common/error.hpp>
+#include <common/fd-tracker/utils.hpp>
+#include <common/readwrite.hpp>
+#include <common/utils.hpp>
+
+/*
+ * Quit pipe for all threads. This permits a single cancellation point
+ * for all threads when receiving an event on the pipe.
+ */
+static int thread_quit_pipe[2] = { -1, -1 };
+
+/*
+ * Write to writable pipe used to notify a thread.
+ */
+static int notify_thread_pipe(int wpipe)
+{
+       const auto ret = lttng_write(wpipe, "!", 1);
+
+       if (ret < 1) {
+               PERROR("Failed to write to thread pipe");
+               return -1;
+       }
+
+       return 0;
+}
+
+/*
+ * Initialize the thread quit pipe.
+ *
+ * Return -1 on error or 0 if all pipes are created.
+ */
+int relayd_init_thread_quit_pipe()
+{
+       return fd_tracker_util_pipe_open_cloexec(
+               the_fd_tracker, "Thread quit pipe", thread_quit_pipe);
+}
+
+/*
+ * Notify the threads to initiate shutdown.
+ *
+ * Return 0 on success or -1 on error.
+ */
+int relayd_notify_thread_quit_pipe()
+{
+       return notify_thread_pipe(thread_quit_pipe[1]);
+}
+
+/*
+ * Close the thread quit pipe.
+ */
+void relayd_close_thread_quit_pipe()
+{
+       if (thread_quit_pipe[0] != -1) {
+               (void) fd_tracker_util_pipe_close(the_fd_tracker, thread_quit_pipe);
+       }
+}
+
+/*
+ * Return 1 if 'fd' is the thread quit pipe read fd.
+ */
+bool relayd_is_thread_quit_pipe(const int fd)
+{
+       return (fd == thread_quit_pipe[0]);
+}
+
+/*
+ * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
+ */
+int create_named_thread_poll_set(struct lttng_poll_event *events, int size, const char *name)
+{
+       if (events == nullptr || size == 0) {
+               return -1;
+       }
+
+       const auto create_ret =
+               fd_tracker_util_poll_create(the_fd_tracker, name, events, 1, LTTNG_CLOEXEC);
+       if (create_ret) {
+               PERROR("Failed to create \"%s\" poll file descriptor", name);
+               return -1;
+       }
+
+       /* Add thread quit pipe to monitored events. */
+       const auto poll_add_ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN);
+       if (poll_add_ret < 0) {
+               return -1;
+       }
+
+       return 0;
+}
index 73a2887941517275c4a860e89f71dab92585f3c8..91baa74aa9f6e0248db2e61ffd236e8069af63b0 100644 (file)
@@ -6,15 +6,15 @@
  */
 
 #define _LGPL_SOURCE
+#include "tracefile-array.hpp"
+
 #include <common/common.hpp>
-#include <common/utils.hpp>
 #include <common/defaults.hpp>
-
-#include "tracefile-array.hpp"
+#include <common/utils.hpp>
 
 struct tracefile_array *tracefile_array_create(size_t count)
 {
-       struct tracefile_array *tfa = NULL;
+       struct tracefile_array *tfa = nullptr;
        int i;
 
        tfa = zmalloc<tracefile_array>();
@@ -39,7 +39,7 @@ error:
                free(tfa->tf);
        }
        free(tfa);
-       return NULL;
+       return nullptr;
 }
 
 void tracefile_array_destroy(struct tracefile_array *tfa)
@@ -67,8 +67,7 @@ void tracefile_array_reset(struct tracefile_array *tfa)
        tfa->file_tail = 0;
 }
 
-void tracefile_array_file_rotate(struct tracefile_array *tfa,
-               enum tracefile_rotate_type type)
+void tracefile_array_file_rotate(struct tracefile_array *tfa, enum tracefile_rotate_type type)
 {
        uint64_t *headp, *tailp;
 
@@ -109,8 +108,7 @@ void tracefile_array_file_rotate(struct tracefile_array *tfa,
        }
 }
 
-void tracefile_array_commit_seq(struct tracefile_array *tfa,
-               uint64_t new_seq_head)
+void tracefile_array_commit_seq(struct tracefile_array *tfa, uint64_t new_seq_head)
 {
        uint64_t *headp, *tailp;
 
@@ -157,8 +155,7 @@ uint64_t tracefile_array_get_seq_tail(struct tracefile_array *tfa)
        return tfa->seq_tail;
 }
 
-bool tracefile_array_seq_in_file(struct tracefile_array *tfa,
-               uint64_t file_index, uint64_t seq)
+bool tracefile_array_seq_in_file(struct tracefile_array *tfa, uint64_t file_index, uint64_t seq)
 {
        if (!tfa->count) {
                /*
@@ -171,10 +168,5 @@ bool tracefile_array_seq_in_file(struct tracefile_array *tfa,
        if (seq == -1ULL) {
                return false;
        }
-       if (seq >= tfa->tf[file_index].seq_tail
-                       && seq <= tfa->tf[file_index].seq_head) {
-               return true;
-       } else {
-               return false;
-       }
+       return seq >= tfa->tf[file_index].seq_tail && seq <= tfa->tf[file_index].seq_head;
 }
index 09c425fad43267f96e40b30063e28ebdf95159df..25b228016219ace106080b4b814b6c7d650b4695 100644 (file)
@@ -8,15 +8,15 @@
  *
  */
 
-#include <limits.h>
 #include <inttypes.h>
+#include <limits.h>
 #include <pthread.h>
 #include <stdbool.h>
 
 struct tracefile {
        /* Per-tracefile head/tail seq. */
-       uint64_t seq_head;      /* Newest seqcount. Inclusive. */
-       uint64_t seq_tail;      /* Oldest seqcount. Inclusive. */
+       uint64_t seq_head; /* Newest seqcount. Inclusive. */
+       uint64_t seq_tail; /* Oldest seqcount. Inclusive. */
 };
 
 enum tracefile_rotate_type {
@@ -54,8 +54,7 @@ struct tracefile_array *tracefile_array_create(size_t count);
 void tracefile_array_destroy(struct tracefile_array *tfa);
 
 void tracefile_array_file_rotate(struct tracefile_array *tfa, enum tracefile_rotate_type type);
-void tracefile_array_commit_seq(struct tracefile_array *tfa,
-               uint64_t new_seq_head);
+void tracefile_array_commit_seq(struct tracefile_array *tfa, uint64_t new_seq_head);
 void tracefile_array_reset(struct tracefile_array *tfa);
 
 uint64_t tracefile_array_get_read_file_index_head(struct tracefile_array *tfa);
@@ -66,7 +65,6 @@ uint64_t tracefile_array_get_file_index_tail(struct tracefile_array *tfa);
 /* May return -1ULL in the case where we have not received any indexes yet. */
 uint64_t tracefile_array_get_seq_tail(struct tracefile_array *tfa);
 
-bool tracefile_array_seq_in_file(struct tracefile_array *tfa,
-               uint64_t file_index, uint64_t seq);
+bool tracefile_array_seq_in_file(struct tracefile_array *tfa, uint64_t file_index, uint64_t seq);
 
 #endif /* _STREAM_H */
index ccfc3a92a745f85a68848556f78529f47ebc2a9e..3d02f6044b20cd66b5a9920fc18ebdcedcf04a05 100644 (file)
@@ -7,32 +7,31 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include "lttng-relayd.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/defaults.hpp>
-#include <common/utils.hpp>
 #include <common/path.hpp>
+#include <common/utils.hpp>
 
-#include "lttng-relayd.hpp"
-#include "utils.hpp"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 static char *create_output_path_auto(const char *path_name)
 {
        int ret;
-       char *traces_path = NULL;
+       char *traces_path = nullptr;
        const char *default_path;
 
        default_path = utils_get_home_dir();
-       if (default_path == NULL) {
+       if (default_path == nullptr) {
                ERR("Home path not found.\n \
                                Please specify an output path using -o, --output PATH");
                goto exit;
        }
-       ret = asprintf(&traces_path, "%s/" DEFAULT_TRACE_DIR_NAME
-                       "/%s", default_path, path_name);
+       ret = asprintf(&traces_path, "%s/" DEFAULT_TRACE_DIR_NAME "/%s", default_path, path_name);
        if (ret < 0) {
                PERROR("asprintf trace dir name");
                goto exit;
@@ -44,7 +43,7 @@ exit:
 static char *create_output_path_noauto(const char *path_name)
 {
        int ret;
-       char *traces_path = NULL;
+       char *traces_path = nullptr;
        char *full_path;
 
        full_path = utils_expand_path(opt_output_path);
@@ -71,7 +70,7 @@ char *create_output_path(const char *path_name)
 {
        LTTNG_ASSERT(path_name);
 
-       if (opt_output_path == NULL) {
+       if (opt_output_path == nullptr) {
                return create_output_path_auto(path_name);
        } else {
                return create_output_path_noauto(path_name);
index 194073f598783e011cf8b852515e34dba05950a3..45fa2dcacafff947a43de2945c948bf994694cd1 100644 (file)
@@ -8,17 +8,19 @@
  */
 
 #define _LGPL_SOURCE
-#include <common/common.hpp>
-#include <urcu/rculist.h>
-
-#include "lttng-relayd.hpp"
 #include "ctf-trace.hpp"
+#include "lttng-relayd.hpp"
 #include "session.hpp"
+#include "stream.hpp"
 #include "viewer-session.hpp"
 #include "viewer-stream.hpp"
-#include "stream.hpp"
 
-struct relay_viewer_session *viewer_session_create(void)
+#include <common/common.hpp>
+#include <common/urcu.hpp>
+
+#include <urcu/rculist.h>
+
+struct relay_viewer_session *viewer_session_create()
 {
        struct relay_viewer_session *vsession;
 
@@ -32,13 +34,13 @@ end:
 }
 
 int viewer_session_set_trace_chunk_copy(struct relay_viewer_session *vsession,
-               struct lttng_trace_chunk *relay_session_trace_chunk)
+                                       struct lttng_trace_chunk *relay_session_trace_chunk)
 {
        int ret = 0;
        struct lttng_trace_chunk *viewer_chunk;
 
        lttng_trace_chunk_put(vsession->current_trace_chunk);
-       vsession->current_trace_chunk = NULL;
+       vsession->current_trace_chunk = nullptr;
 
        DBG("Copying relay session's current trace chunk to the viewer session");
        if (!relay_session_trace_chunk) {
@@ -58,12 +60,10 @@ end:
 }
 
 /* The existence of session must be guaranteed by the caller. */
-enum lttng_viewer_attach_return_code viewer_session_attach(
-               struct relay_viewer_session *vsession,
-               struct relay_session *session)
+enum lttng_viewer_attach_return_code viewer_session_attach(struct relay_viewer_session *vsession,
+                                                          struct relay_session *session)
 {
-       enum lttng_viewer_attach_return_code viewer_attach_status =
-                       LTTNG_VIEWER_ATTACH_OK;
+       enum lttng_viewer_attach_return_code viewer_attach_status = LTTNG_VIEWER_ATTACH_OK;
 
        ASSERT_LOCKED(session->lock);
 
@@ -79,8 +79,7 @@ enum lttng_viewer_attach_return_code viewer_session_attach(
 
                session->viewer_attached = true;
 
-               ret = viewer_session_set_trace_chunk_copy(vsession,
-                               session->current_trace_chunk);
+               ret = viewer_session_set_trace_chunk_copy(vsession, session->current_trace_chunk);
                if (ret) {
                        /*
                         * The live protocol does not define a generic error
@@ -89,7 +88,7 @@ enum lttng_viewer_attach_return_code viewer_session_attach(
                         * failure as if the session didn't exist anymore.
                         */
                        DBG("Failed to create a viewer trace chunk from the current trace chunk of session \"%s\", returning LTTNG_VIEWER_ATTACH_UNK",
-                                       session->session_name);
+                           session->session_name);
                        viewer_attach_status = LTTNG_VIEWER_ATTACH_UNK;
                }
        }
@@ -97,8 +96,7 @@ enum lttng_viewer_attach_return_code viewer_session_attach(
        if (viewer_attach_status == LTTNG_VIEWER_ATTACH_OK) {
                pthread_mutex_lock(&vsession->session_list_lock);
                /* Ownership is transfered to the list. */
-               cds_list_add_rcu(&session->viewer_session_node,
-                               &vsession->session_list);
+               cds_list_add_rcu(&session->viewer_session_node, &vsession->session_list);
                pthread_mutex_unlock(&vsession->session_list_lock);
        } else {
                /* Put our local ref. */
@@ -110,7 +108,7 @@ end:
 
 /* The existence of session must be guaranteed by the caller. */
 static int viewer_session_detach(struct relay_viewer_session *vsession,
-               struct relay_session *session)
+                                struct relay_session *session)
 {
        int ret = 0;
 
@@ -143,7 +141,7 @@ void viewer_session_destroy(struct relay_viewer_session *vsession)
  * Release ownership of all the streams of one session and detach the viewer.
  */
 void viewer_session_close_one_session(struct relay_viewer_session *vsession,
-               struct relay_session *session)
+                                     struct relay_session *session)
 {
        struct lttng_ht_iter iter;
        struct relay_viewer_stream *vstream;
@@ -152,26 +150,31 @@ void viewer_session_close_one_session(struct relay_viewer_session *vsession,
         * TODO: improvement: create more efficient list of
         * vstream per session.
         */
-       cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter,
-                       vstream, stream_n.node) {
-               if (!viewer_stream_get(vstream)) {
-                       continue;
-               }
-               if (vstream->stream->trace->session != session) {
+       {
+               lttng::urcu::read_lock_guard read_guard;
+
+               cds_lfht_for_each_entry (
+                       viewer_streams_ht->ht, &iter.iter, vstream, stream_n.node) {
+                       if (!viewer_stream_get(vstream)) {
+                               continue;
+                       }
+                       if (vstream->stream->trace->session != session) {
+                               viewer_stream_put(vstream);
+                               continue;
+                       }
+                       /* Put local reference. */
+                       viewer_stream_put(vstream);
+                       /*
+                        * We have reached one of the viewer stream's lifetime
+                        * end condition. This "put" will cause the proper
+                        * teardown of the viewer stream.
+                        */
                        viewer_stream_put(vstream);
-                       continue;
                }
-               /* Put local reference. */
-               viewer_stream_put(vstream);
-               /*
-                * We have reached one of the viewer stream's lifetime
-                * end condition. This "put" will cause the proper
-                * teardown of the viewer stream.
-                */
-               viewer_stream_put(vstream);
        }
+
        lttng_trace_chunk_put(vsession->current_trace_chunk);
-       vsession->current_trace_chunk = NULL;
+       vsession->current_trace_chunk = nullptr;
        viewer_session_detach(vsession, session);
 }
 
@@ -179,20 +182,21 @@ void viewer_session_close(struct relay_viewer_session *vsession)
 {
        struct relay_session *session;
 
-       rcu_read_lock();
-       cds_list_for_each_entry_rcu(session,
-                       &vsession->session_list, viewer_session_node) {
-               viewer_session_close_one_session(vsession, session);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_list_for_each_entry_rcu(session, &vsession->session_list, viewer_session_node)
+               {
+                       viewer_session_close_one_session(vsession, session);
+               }
        }
-       rcu_read_unlock();
 }
 
 /*
  * Check if a connection is attached to a session.
  * Return 1 if attached, 0 if not attached, a negative value on error.
  */
-int viewer_session_is_attached(struct relay_viewer_session *vsession,
-               struct relay_session *session)
+int viewer_session_is_attached(struct relay_viewer_session *vsession, struct relay_session *session)
 {
        struct relay_session *iter;
        int found = 0;
@@ -204,17 +208,18 @@ int viewer_session_is_attached(struct relay_viewer_session *vsession,
        if (!session->viewer_attached) {
                goto end;
        }
-       rcu_read_lock();
-       cds_list_for_each_entry_rcu(iter,
-                       &vsession->session_list,
-                       viewer_session_node) {
-               if (session == iter) {
-                       found = 1;
-                       goto end_rcu_unlock;
+
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_list_for_each_entry_rcu(iter, &vsession->session_list, viewer_session_node)
+               {
+                       if (session == iter) {
+                               found = 1;
+                               break;
+                       }
                }
        }
-end_rcu_unlock:
-       rcu_read_unlock();
+
 end:
        pthread_mutex_unlock(&session->lock);
        return found;
index 65ad3e11a8165fe4fa3ec973f7bd42f49ff83e54..3dfa3acea809e1ccaf8dfa2c4c1006d0d082a6d9 100644 (file)
  *
  */
 
-#include <limits.h>
-#include <inttypes.h>
-#include <pthread.h>
-#include <urcu/list.h>
-#include <urcu/ref.h>
+#include "lttng-viewer-abi.hpp"
+#include "session.hpp"
 
 #include <common/hashtable/hashtable.hpp>
 #include <common/trace-chunk.hpp>
 
-#include "session.hpp"
-#include "lttng-viewer-abi.hpp"
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <urcu/list.h>
+#include <urcu/ref.h>
 
 struct relay_viewer_session {
        /*
@@ -29,8 +29,8 @@ struct relay_viewer_session {
         * This list limits the design to having the sessions in at most
         * one viewer session.
         */
-       struct cds_list_head session_list;      /* RCU list. */
-       pthread_mutex_t session_list_lock;      /* Protects list updates. */
+       struct cds_list_head session_list; /* RCU list. */
+       pthread_mutex_t session_list_lock; /* Protects list updates. */
        /*
         * The viewer session's current trace chunk is initially set, when
         * a viewer attaches to the viewer session, to a copy the corresponding
@@ -61,18 +61,17 @@ struct relay_viewer_session {
        struct lttng_trace_chunk *current_trace_chunk;
 };
 
-struct relay_viewer_session *viewer_session_create(void);
+struct relay_viewer_session *viewer_session_create();
 void viewer_session_destroy(struct relay_viewer_session *vsession);
 void viewer_session_close(struct relay_viewer_session *vsession);
 
-enum lttng_viewer_attach_return_code viewer_session_attach(
-               struct relay_viewer_session *vsession,
-               struct relay_session *session);
+enum lttng_viewer_attach_return_code viewer_session_attach(struct relay_viewer_session *vsession,
+                                                          struct relay_session *session);
 int viewer_session_is_attached(struct relay_viewer_session *vsession,
-               struct relay_session *session);
+                              struct relay_session *session);
 void viewer_session_close_one_session(struct relay_viewer_session *vsession,
-               struct relay_session *session);
+                                     struct relay_session *session);
 int viewer_session_set_trace_chunk_copy(struct relay_viewer_session *vsession,
-               struct lttng_trace_chunk *relay_session_trace_chunk);
+                                       struct lttng_trace_chunk *relay_session_trace_chunk);
 
 #endif /* _VIEWER_SESSION_H */
index f37d8e33040d991d7ea3ecd818508d1d9ac1f3f2..9ca54e67ea49b7be778cf054579ca54004289bcb 100644 (file)
@@ -8,34 +8,36 @@
  */
 
 #define _LGPL_SOURCE
+#include "lttng-relayd.hpp"
+#include "viewer-stream.hpp"
+
 #include <common/common.hpp>
-#include <common/index/index.hpp>
 #include <common/compat/string.hpp>
+#include <common/index/index.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <algorithm>
 
-#include "lttng-relayd.hpp"
-#include "viewer-stream.hpp"
+#include <algorithm>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 
 static void viewer_stream_release_composite_objects(struct relay_viewer_stream *vstream)
 {
        if (vstream->stream_file.handle) {
                fs_handle_close(vstream->stream_file.handle);
-               vstream->stream_file.handle = NULL;
+               vstream->stream_file.handle = nullptr;
        }
        if (vstream->index_file) {
                lttng_index_file_put(vstream->index_file);
-               vstream->index_file = NULL;
+               vstream->index_file = nullptr;
        }
        if (vstream->stream) {
                stream_put(vstream->stream);
-               vstream->stream = NULL;
+               vstream->stream = nullptr;
        }
        lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
-       vstream->stream_file.trace_chunk = NULL;
+       vstream->stream_file.trace_chunk = nullptr;
 }
 
 static void viewer_stream_destroy(struct relay_viewer_stream *vstream)
@@ -55,10 +57,10 @@ static void viewer_stream_destroy_rcu(struct rcu_head *head)
 
 /* Relay stream's lock must be held by the caller. */
 struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
-               struct lttng_trace_chunk *trace_chunk,
-               enum lttng_viewer_seek seek_t)
+                                                struct lttng_trace_chunk *trace_chunk,
+                                                enum lttng_viewer_seek seek_t)
 {
-       struct relay_viewer_stream *vstream = NULL;
+       struct relay_viewer_stream *vstream = nullptr;
 
        ASSERT_LOCKED(stream->lock);
 
@@ -69,21 +71,19 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
        }
 
        if (trace_chunk) {
-               const bool acquired_reference = lttng_trace_chunk_get(
-                               trace_chunk);
+               const bool acquired_reference = lttng_trace_chunk_get(trace_chunk);
 
                LTTNG_ASSERT(acquired_reference);
        }
 
        vstream->stream_file.trace_chunk = trace_chunk;
        vstream->path_name = lttng_strndup(stream->path_name, LTTNG_VIEWER_PATH_MAX);
-       if (vstream->path_name == NULL) {
+       if (vstream->path_name == nullptr) {
                PERROR("relay viewer path_name alloc");
                goto error;
        }
-       vstream->channel_name = lttng_strndup(stream->channel_name,
-                       LTTNG_VIEWER_NAME_MAX);
-       if (vstream->channel_name == NULL) {
+       vstream->channel_name = lttng_strndup(stream->channel_name, LTTNG_VIEWER_NAME_MAX);
+       if (vstream->channel_name == nullptr) {
                PERROR("relay viewer channel_name alloc");
                goto error;
        }
@@ -112,8 +112,7 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
                         */
                        seq_tail = 0;
                }
-               vstream->current_tracefile_id =
-                       tracefile_array_get_file_index_tail(stream->tfa);
+               vstream->current_tracefile_id = tracefile_array_get_file_index_tail(stream->tfa);
                vstream->index_sent_seqcount = seq_tail;
                break;
        }
@@ -127,8 +126,7 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
                 * We don't need to check the head position for -1ULL since the
                 * increment will set it to 0.
                 */
-               vstream->index_sent_seqcount =
-                               tracefile_array_get_seq_head(stream->tfa) + 1;
+               vstream->index_sent_seqcount = tracefile_array_get_seq_head(stream->tfa) + 1;
                break;
        default:
                goto error;
@@ -138,26 +136,26 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
         * If we never received an index for the current stream, delay
         * the opening of the index, otherwise open it right now.
         */
-       if (stream->index_file == NULL) {
-               vstream->index_file = NULL;
+       if (stream->index_file == nullptr) {
+               vstream->index_file = nullptr;
        } else if (vstream->stream_file.trace_chunk) {
                const uint32_t connection_major = stream->trace->session->major;
                const uint32_t connection_minor = stream->trace->session->minor;
                enum lttng_trace_chunk_status chunk_status;
 
                chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
-                               vstream->stream_file.trace_chunk,
-                               stream->path_name,
-                               stream->channel_name, stream->tracefile_size,
-                               vstream->current_tracefile_id,
-                               lttng_to_index_major(connection_major,
-                                               connection_minor),
-                               lttng_to_index_minor(connection_major,
-                                               connection_minor),
-                               true, &vstream->index_file);
+                       vstream->stream_file.trace_chunk,
+                       stream->path_name,
+                       stream->channel_name,
+                       stream->tracefile_size,
+                       vstream->current_tracefile_id,
+                       lttng_to_index_major(connection_major, connection_minor),
+                       lttng_to_index_minor(connection_major, connection_minor),
+                       true,
+                       &vstream->index_file);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
-                               vstream->index_file = NULL;
+                               vstream->index_file = nullptr;
                        } else {
                                goto error;
                        }
@@ -174,17 +172,22 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
                enum lttng_trace_chunk_status status;
 
                ret = utils_stream_file_path(stream->path_name,
-                               stream->channel_name, stream->tracefile_size,
-                               vstream->current_tracefile_id, NULL, file_path,
-                               sizeof(file_path));
+                                            stream->channel_name,
+                                            stream->tracefile_size,
+                                            vstream->current_tracefile_id,
+                                            nullptr,
+                                            file_path,
+                                            sizeof(file_path));
                if (ret < 0) {
                        goto error;
                }
 
-               status = lttng_trace_chunk_open_fs_handle(
-                               vstream->stream_file.trace_chunk, file_path,
-                               O_RDONLY, 0, &vstream->stream_file.handle,
-                               true);
+               status = lttng_trace_chunk_open_fs_handle(vstream->stream_file.trace_chunk,
+                                                         file_path,
+                                                         O_RDONLY,
+                                                         0,
+                                                         &vstream->stream_file.handle,
+                                                         true);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        goto error;
                }
@@ -193,15 +196,13 @@ struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
        if (seek_t == LTTNG_VIEWER_SEEK_LAST && vstream->index_file) {
                off_t lseek_ret;
 
-               lseek_ret = fs_handle_seek(
-                               vstream->index_file->file, 0, SEEK_END);
+               lseek_ret = fs_handle_seek(vstream->index_file->file, 0, SEEK_END);
                if (lseek_ret < 0) {
                        goto error;
                }
        }
        if (stream->is_metadata) {
-               rcu_assign_pointer(stream->trace->viewer_metadata_stream,
-                               vstream);
+               rcu_assign_pointer(stream->trace->viewer_metadata_stream, vstream);
        }
 
        vstream->last_seen_rotation_count = stream->completed_rotation_count;
@@ -219,7 +220,7 @@ error:
                viewer_stream_release_composite_objects(vstream);
                viewer_stream_destroy(vstream);
        }
-       return NULL;
+       return nullptr;
 }
 
 static void viewer_stream_unpublish(struct relay_viewer_stream *vstream)
@@ -234,8 +235,8 @@ static void viewer_stream_unpublish(struct relay_viewer_stream *vstream)
 
 static void viewer_stream_release(struct urcu_ref *ref)
 {
-       struct relay_viewer_stream *vstream = caa_container_of(ref,
-                       struct relay_viewer_stream, ref);
+       struct relay_viewer_stream *vstream =
+               caa_container_of(ref, struct relay_viewer_stream, ref);
 
        if (vstream->stream->is_metadata) {
                rcu_assign_pointer(vstream->stream->trace->viewer_metadata_stream, NULL);
@@ -260,9 +261,9 @@ struct relay_viewer_stream *viewer_stream_get_by_id(uint64_t id)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct relay_viewer_stream *vstream = NULL;
+       struct relay_viewer_stream *vstream = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_lookup(viewer_streams_ht, &id, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (!node) {
@@ -271,29 +272,27 @@ struct relay_viewer_stream *viewer_stream_get_by_id(uint64_t id)
        }
        vstream = lttng::utils::container_of(node, &relay_viewer_stream::stream_n);
        if (!viewer_stream_get(vstream)) {
-               vstream = NULL;
+               vstream = nullptr;
        }
 end:
-       rcu_read_unlock();
        return vstream;
 }
 
 void viewer_stream_put(struct relay_viewer_stream *vstream)
 {
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        urcu_ref_put(&vstream->ref, viewer_stream_release);
-       rcu_read_unlock();
 }
 
 void viewer_stream_close_files(struct relay_viewer_stream *vstream)
 {
        if (vstream->index_file) {
                lttng_index_file_put(vstream->index_file);
-               vstream->index_file = NULL;
+               vstream->index_file = nullptr;
        }
        if (vstream->stream_file.handle) {
-               fs_handle_close(vstream->stream_file.handle);
-               vstream->stream_file.handle = NULL;
+               fs_handle_close(vstream->stream_file.handle);
+               vstream->stream_file.handle = nullptr;
        }
 }
 
@@ -314,8 +313,7 @@ void viewer_stream_sync_tracefile_array_tail(struct relay_viewer_stream *vstream
         * index_sent_seqcount is already further than the tracefile
         * array tail position, keep its current position.
         */
-       vstream->index_sent_seqcount =
-                       std::max(seq_tail, vstream->index_sent_seqcount);
+       vstream->index_sent_seqcount = std::max(seq_tail, vstream->index_sent_seqcount);
 }
 
 /*
@@ -331,9 +329,8 @@ int viewer_stream_rotate(struct relay_viewer_stream *vstream)
        const struct relay_stream *stream = vstream->stream;
 
        /* Detect the last tracefile to open. */
-       if (stream->index_received_seqcount
-                       == vstream->index_sent_seqcount
-                       && stream->trace->session->connection_closed) {
+       if (stream->index_received_seqcount == vstream->index_sent_seqcount &&
+           stream->trace->session->connection_closed) {
                ret = 1;
                goto end;
        }
@@ -347,10 +344,8 @@ int viewer_stream_rotate(struct relay_viewer_stream *vstream)
        /*
         * Try to move to the next file.
         */
-       new_id = (vstream->current_tracefile_id + 1)
-                       % stream->tracefile_count;
-       if (tracefile_array_seq_in_file(stream->tfa, new_id,
-                       vstream->index_sent_seqcount)) {
+       new_id = (vstream->current_tracefile_id + 1) % stream->tracefile_count;
+       if (tracefile_array_seq_in_file(stream->tfa, new_id, vstream->index_sent_seqcount)) {
                vstream->current_tracefile_id = new_id;
        } else {
                uint64_t seq_tail = tracefile_array_get_seq_tail(stream->tfa);
@@ -364,8 +359,7 @@ int viewer_stream_rotate(struct relay_viewer_stream *vstream)
                /*
                 * We need to resync because we lag behind tail.
                 */
-               vstream->current_tracefile_id =
-                       tracefile_array_get_file_index_tail(stream->tfa);
+               vstream->current_tracefile_id = tracefile_array_get_file_index_tail(stream->tfa);
                vstream->index_sent_seqcount = seq_tail;
        }
        viewer_stream_close_files(vstream);
@@ -374,7 +368,7 @@ end:
        return ret;
 }
 
-void print_viewer_streams(void)
+void print_viewer_streams()
 {
        struct lttng_ht_iter iter;
        struct relay_viewer_stream *vstream;
@@ -383,20 +377,22 @@ void print_viewer_streams(void)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
-                       stream_n.node) {
-               if (!viewer_stream_get(vstream)) {
-                       continue;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       viewer_streams_ht->ht, &iter.iter, vstream, stream_n.node) {
+                       if (!viewer_stream_get(vstream)) {
+                               continue;
+                       }
+                       DBG("vstream %p refcount %ld stream %" PRIu64 " trace %" PRIu64
+                           " session %" PRIu64,
+                           vstream,
+                           vstream->ref.refcount,
+                           vstream->stream->stream_handle,
+                           vstream->stream->trace->id,
+                           vstream->stream->trace->session->id);
+                       viewer_stream_put(vstream);
                }
-               DBG("vstream %p refcount %ld stream %" PRIu64 " trace %" PRIu64
-                       " session %" PRIu64,
-                       vstream,
-                       vstream->ref.refcount,
-                       vstream->stream->stream_handle,
-                       vstream->stream->trace->id,
-                       vstream->stream->trace->session->id);
-               viewer_stream_put(vstream);
        }
-       rcu_read_unlock();
 }
index 42bdc1e208be4ac2a06bdc80ce6bd5b6f2ef4f96..ea6292b2cee78074f641d1c044bca7cdac5aedd7 100644 (file)
  *
  */
 
-#include <limits.h>
-#include <inttypes.h>
-#include <pthread.h>
-
-#include <common/hashtable/hashtable.hpp>
-
 #include "ctf-trace.hpp"
 #include "lttng-viewer-abi.hpp"
 #include "stream.hpp"
 
+#include <common/hashtable/hashtable.hpp>
+
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+
 struct relay_stream;
 
 /*
@@ -78,16 +78,15 @@ struct relay_viewer_stream {
 };
 
 struct relay_viewer_stream *viewer_stream_create(struct relay_stream *stream,
-               struct lttng_trace_chunk *viewer_trace_chunk,
-               enum lttng_viewer_seek seek_t);
+                                                struct lttng_trace_chunk *viewer_trace_chunk,
+                                                enum lttng_viewer_seek seek_t);
 
 struct relay_viewer_stream *viewer_stream_get_by_id(uint64_t id);
 bool viewer_stream_get(struct relay_viewer_stream *vstream);
 void viewer_stream_put(struct relay_viewer_stream *vstream);
 int viewer_stream_rotate(struct relay_viewer_stream *vstream);
-bool viewer_stream_is_tracefile_seq_readable(struct relay_viewer_stream *vstream,
-               uint64_t seq);
-void print_viewer_streams(void);
+bool viewer_stream_is_tracefile_seq_readable(struct relay_viewer_stream *vstream, uint64_t seq);
+void print_viewer_streams();
 void viewer_stream_close_files(struct relay_viewer_stream *vstream);
 void viewer_stream_sync_tracefile_array_tail(struct relay_viewer_stream *vstream);
 
index 7f8ac379c216709a028856788fd34d7393c0c03b..e9b6ac1f68639ca7dbfc215381f58956a378b179 100644 (file)
@@ -39,7 +39,6 @@ liblttng_sessiond_common_la_SOURCES = utils.cpp utils.hpp \
                        notification-thread-commands.hpp notification-thread-commands.cpp \
                        notification-thread-events.hpp notification-thread-events.cpp \
                        sessiond-config.hpp sessiond-config.cpp \
-                       rotate.hpp rotate.cpp \
                        rotation-thread.hpp rotation-thread.cpp \
                        timer.cpp timer.hpp \
                        globals.cpp \
@@ -76,7 +75,8 @@ liblttng_sessiond_common_la_SOURCES += trace-ust.cpp ust-registry.cpp ust-app.cp
                        ust-registry-channel.cpp ust-registry-channel.hpp \
                        ust-registry-session-uid.cpp ust-registry-session-uid.hpp \
                        ust-registry-session-pid.cpp ust-registry-session-pid.hpp \
-                       tsdl-trace-class-visitor.cpp tsdl-trace-class-visitor.hpp
+                       tsdl-trace-class-visitor.cpp tsdl-trace-class-visitor.hpp \
+                       ctf2-trace-class-visitor.cpp ctf2-trace-class-visitor.hpp
 endif
 
 # link on liblttngctl for check if sessiond is already alive.
index 23a99a1acbbb7ec94458ad79a5dc7d9a85ba68ee..3fbb87f431858b6232b412cfed2ea292e6305214 100644 (file)
 #include "notification-thread-internal.hpp"
 #include "session.hpp"
 #include "thread.hpp"
+
 #include <common/dynamic-array.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/urcu.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/list-internal.hpp>
 #include <lttng/action/list.h>
 #include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/lttng-error.h>
 #include <lttng/trigger/trigger-internal.hpp>
+
 #include <pthread.h>
 #include <stdbool.h>
 #include <stddef.h>
 #include <urcu/list.h>
 
-#define THREAD_NAME "Action Executor"
+#define THREAD_NAME          "Action Executor"
 #define MAX_QUEUED_WORK_COUNT 8192
 
 struct action_executor {
@@ -109,56 +113,48 @@ struct action_work_subitem {
 };
 } /* namespace */
 
-
 /*
  * Only return non-zero on a fatal error that should shut down the action
  * executor.
  */
-typedef int (*action_executor_handler)(struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *item);
+using action_executor_handler = int (*)(struct action_executor *,
+                                       const struct action_work_item *,
+                                       struct action_work_subitem *);
 
 static int action_executor_notify_handler(struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
-static int action_executor_start_session_handler(
-               struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
-static int action_executor_stop_session_handler(
-               struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
-static int action_executor_rotate_session_handler(
-               struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
-static int action_executor_snapshot_session_handler(
-               struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
+                                         const struct action_work_item *,
+                                         struct action_work_subitem *);
+static int action_executor_start_session_handler(struct action_executor *executor,
+                                                const struct action_work_item *,
+                                                struct action_work_subitem *);
+static int action_executor_stop_session_handler(struct action_executor *executor,
+                                               const struct action_work_item *,
+                                               struct action_work_subitem *);
+static int action_executor_rotate_session_handler(struct action_executor *executor,
+                                                 const struct action_work_item *,
+                                                 struct action_work_subitem *);
+static int action_executor_snapshot_session_handler(struct action_executor *executor,
+                                                   const struct action_work_item *,
+                                                   struct action_work_subitem *);
 static int action_executor_list_handler(struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
+                                       const struct action_work_item *,
+                                       struct action_work_subitem *);
 static int action_executor_generic_handler(struct action_executor *executor,
-               const struct action_work_item *,
-               struct action_work_subitem *);
+                                          const struct action_work_item *,
+                                          struct action_work_subitem *);
 
 static const action_executor_handler action_executors[] = {
-       action_executor_notify_handler,
-       action_executor_start_session_handler,
-       action_executor_stop_session_handler,
-       action_executor_rotate_session_handler,
-       action_executor_snapshot_session_handler,
-       action_executor_list_handler,
+       action_executor_notify_handler,           action_executor_start_session_handler,
+       action_executor_stop_session_handler,     action_executor_rotate_session_handler,
+       action_executor_snapshot_session_handler, action_executor_list_handler,
 };
 
 /* Forward declaration */
 static int add_action_to_subitem_array(struct lttng_action *action,
-               struct lttng_dynamic_array *subitems);
+                                      struct lttng_dynamic_array *subitems);
 
 static int populate_subitem_array_from_trigger(struct lttng_trigger *trigger,
-               struct lttng_dynamic_array *subitems);
+                                              struct lttng_dynamic_array *subitems);
 
 static void action_work_subitem_destructor(void *element)
 {
@@ -178,7 +174,7 @@ static const char *get_action_name(const struct lttng_action *action)
 
 /* Check if this trigger allowed to interect with a given session. */
 static bool is_trigger_allowed_for_session(const struct lttng_trigger *trigger,
-               struct ltt_session *session)
+                                          struct ltt_session *session)
 {
        bool is_allowed = false;
        const struct lttng_credentials session_creds = {
@@ -186,17 +182,16 @@ static bool is_trigger_allowed_for_session(const struct lttng_trigger *trigger,
                .gid = LTTNG_OPTIONAL_INIT_VALUE(session->gid),
        };
        /* Can never be NULL. */
-       const struct lttng_credentials *trigger_creds =
-                       lttng_trigger_get_credentials(trigger);
+       const struct lttng_credentials *trigger_creds = lttng_trigger_get_credentials(trigger);
 
        is_allowed = (lttng_credentials_is_equal_uid(trigger_creds, &session_creds)) ||
-                       (lttng_credentials_get_uid(trigger_creds) == 0);
+               (lttng_credentials_get_uid(trigger_creds) == 0);
        if (!is_allowed) {
                WARN("Trigger is not allowed to interact with session `%s`: session uid = %ld, session gid = %ld, trigger uid = %ld",
-                               session->name,
-                               (long int) session->uid,
-                               (long int) session->gid,
-                               (long int) lttng_credentials_get_uid(trigger_creds));
+                    session->name,
+                    (long int) session->uid,
+                    (long int) session->gid,
+                    (long int) lttng_credentials_get_uid(trigger_creds));
        }
 
        return is_allowed;
@@ -222,10 +217,9 @@ static const char *get_trigger_name(const struct lttng_trigger *trigger)
        return trigger_name;
 }
 
-static int client_handle_transmission_status(
-               struct notification_client *client,
-               enum client_transmission_status status,
-               void *user_data)
+static int client_handle_transmission_status(struct notification_client *client,
+                                            enum client_transmission_status status,
+                                            void *user_data)
 {
        int ret = 0;
        struct action_executor *executor = (action_executor *) user_data;
@@ -234,7 +228,7 @@ static int client_handle_transmission_status(
        switch (status) {
        case CLIENT_TRANSMISSION_STATUS_COMPLETE:
                DBG("Successfully sent full notification to client, client_id = %" PRIu64,
-                               client->id);
+                   client->id);
                /*
                 * There is no need to wake the (e)poll thread. If it was waiting for
                 * "out" events on the client's socket, it will see that no payload
@@ -248,15 +242,15 @@ static int client_handle_transmission_status(
                break;
        case CLIENT_TRANSMISSION_STATUS_QUEUED:
                DBG("Queued notification in client outgoing buffer, client_id = %" PRIu64,
-                               client->id);
+                   client->id);
                break;
        case CLIENT_TRANSMISSION_STATUS_FAIL:
                DBG("Communication error occurred while sending notification to client, client_id = %" PRIu64,
-                               client->id);
+                   client->id);
                break;
        default:
                ERR("Fatal error encoutered while sending notification to client, client_id = %" PRIu64,
-                               client->id);
+                   client->id);
                ret = -1;
                goto end;
        }
@@ -267,29 +261,28 @@ static int client_handle_transmission_status(
 
        /* Safe to read client's id without locking as it is immutable. */
        ret = notification_thread_client_communication_update(
-                       executor->notification_thread_handle, client->id,
-                       status);
+               executor->notification_thread_handle, client->id, status);
 end:
        return ret;
 }
 
 static int action_executor_notify_handler(struct action_executor *executor,
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item __attribute__((unused)))
+                                         const struct action_work_item *work_item,
+                                         struct action_work_subitem *item __attribute__((unused)))
 {
-       return notification_client_list_send_evaluation(work_item->client_list,
-                       work_item->trigger,
-                       work_item->evaluation,
-                       work_item->object_creds.is_set ?
-                                       &(work_item->object_creds.value) :
-                                       NULL,
-                       client_handle_transmission_status, executor);
+       return notification_client_list_send_evaluation(
+               work_item->client_list,
+               work_item->trigger,
+               work_item->evaluation,
+               work_item->object_creds.is_set ? &(work_item->object_creds.value) : nullptr,
+               client_handle_transmission_status,
+               executor);
 }
 
-static int action_executor_start_session_handler(
-               struct action_executor *executor __attribute__((unused)),
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item)
+static int action_executor_start_session_handler(struct action_executor *executor
+                                                __attribute__((unused)),
+                                                const struct action_work_item *work_item,
+                                                struct action_work_subitem *item)
 {
        int ret = 0;
        const char *session_name;
@@ -298,11 +291,11 @@ static int action_executor_start_session_handler(
        enum lttng_error_code cmd_ret;
        struct lttng_action *action = item->action;
 
-       action_status = lttng_action_start_session_get_session_name(
-                       action, &session_name);
+       lttng::urcu::read_lock_guard read_lock;
+
+       action_status = lttng_action_start_session_get_session_name(action, &session_name);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
-               ERR("Failed to get session name from `%s` action",
-                               get_action_name(action));
+               ERR("Failed to get session name from `%s` action", get_action_name(action));
                ret = -1;
                goto end;
        }
@@ -313,29 +306,32 @@ static int action_executor_start_session_handler(
         */
        if (!item->context.session_id.is_set) {
                DBG("Session `%s` was not present at the moment the work item was enqueued for `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto end;
        }
 
        session_lock_list();
-       rcu_read_lock();
        session = session_find_by_id(LTTNG_OPTIONAL_GET(item->context.session_id));
        if (!session) {
                DBG("Failed to find session `%s` by name while executing `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto error_unlock_list;
        }
 
        session_lock(session);
        if (session->destroyed) {
-               DBG("Session `%s` with id = %" PRIu64 " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
-                               session->name, session->id,
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+               DBG("Session `%s` with id = %" PRIu64
+                   " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
+                   session->name,
+                   session->id,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                goto error_unlock_session;
        }
 
@@ -347,16 +343,19 @@ static int action_executor_start_session_handler(
        switch (cmd_ret) {
        case LTTNG_OK:
                DBG("Successfully started session `%s` on behalf of trigger `%s`",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        case LTTNG_ERR_TRACE_ALREADY_STARTED:
                DBG("Attempted to start session `%s` on behalf of trigger `%s` but it was already started",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        default:
                WARN("Failed to start session `%s` on behalf of trigger `%s`: %s",
-                               session_name, get_trigger_name(work_item->trigger),
-                               lttng_strerror(-cmd_ret));
+                    session_name,
+                    get_trigger_name(work_item->trigger),
+                    lttng_strerror(-cmd_ret));
                lttng_action_increase_execution_failure_count(action);
                break;
        }
@@ -365,16 +364,15 @@ error_unlock_session:
        session_unlock(session);
        session_put(session);
 error_unlock_list:
-       rcu_read_unlock();
        session_unlock_list();
 end:
        return ret;
 }
 
-static int action_executor_stop_session_handler(
-               struct action_executor *executor __attribute__((unused)),
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item)
+static int action_executor_stop_session_handler(struct action_executor *executor
+                                               __attribute__((unused)),
+                                               const struct action_work_item *work_item,
+                                               struct action_work_subitem *item)
 {
        int ret = 0;
        const char *session_name;
@@ -383,11 +381,11 @@ static int action_executor_stop_session_handler(
        enum lttng_error_code cmd_ret;
        struct lttng_action *action = item->action;
 
-       action_status = lttng_action_stop_session_get_session_name(
-                       action, &session_name);
+       lttng::urcu::read_lock_guard read_lock;
+
+       action_status = lttng_action_stop_session_get_session_name(action, &session_name);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
-               ERR("Failed to get session name from `%s` action",
-                               get_action_name(action));
+               ERR("Failed to get session name from `%s` action", get_action_name(action));
                ret = -1;
                goto end;
        }
@@ -398,29 +396,32 @@ static int action_executor_stop_session_handler(
         */
        if (!item->context.session_id.is_set) {
                DBG("Session `%s` was not present at the moment the work item was enqueued for `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto end;
        }
 
        session_lock_list();
-       rcu_read_lock();
        session = session_find_by_id(LTTNG_OPTIONAL_GET(item->context.session_id));
        if (!session) {
                DBG("Failed to find session `%s` by name while executing `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto error_unlock_list;
        }
 
        session_lock(session);
        if (session->destroyed) {
-               DBG("Session `%s` with id = %" PRIu64 " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
-                               session->name, session->id,
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+               DBG("Session `%s` with id = %" PRIu64
+                   " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
+                   session->name,
+                   session->id,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                goto error_unlock_session;
        }
 
@@ -432,16 +433,19 @@ static int action_executor_stop_session_handler(
        switch (cmd_ret) {
        case LTTNG_OK:
                DBG("Successfully stopped session `%s` on behalf of trigger `%s`",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        case LTTNG_ERR_TRACE_ALREADY_STOPPED:
                DBG("Attempted to stop session `%s` on behalf of trigger `%s` but it was already stopped",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        default:
                WARN("Failed to stop session `%s` on behalf of trigger `%s`: %s",
-                               session_name, get_trigger_name(work_item->trigger),
-                               lttng_strerror(-cmd_ret));
+                    session_name,
+                    get_trigger_name(work_item->trigger),
+                    lttng_strerror(-cmd_ret));
                lttng_action_increase_execution_failure_count(action);
                break;
        }
@@ -450,16 +454,15 @@ error_unlock_session:
        session_unlock(session);
        session_put(session);
 error_unlock_list:
-       rcu_read_unlock();
        session_unlock_list();
 end:
        return ret;
 }
 
-static int action_executor_rotate_session_handler(
-               struct action_executor *executor __attribute__((unused)),
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item)
+static int action_executor_rotate_session_handler(struct action_executor *executor
+                                                 __attribute__((unused)),
+                                                 const struct action_work_item *work_item,
+                                                 struct action_work_subitem *item)
 {
        int ret = 0;
        const char *session_name;
@@ -468,11 +471,11 @@ static int action_executor_rotate_session_handler(
        enum lttng_error_code cmd_ret;
        struct lttng_action *action = item->action;
 
-       action_status = lttng_action_rotate_session_get_session_name(
-                       action, &session_name);
+       lttng::urcu::read_lock_guard read_lock;
+
+       action_status = lttng_action_rotate_session_get_session_name(action, &session_name);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
-               ERR("Failed to get session name from `%s` action",
-                               get_action_name(action));
+               ERR("Failed to get session name from `%s` action", get_action_name(action));
                ret = -1;
                goto end;
        }
@@ -483,29 +486,32 @@ static int action_executor_rotate_session_handler(
         */
        if (!item->context.session_id.is_set) {
                DBG("Session `%s` was not present at the moment the work item was enqueued for `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto end;
        }
 
        session_lock_list();
-       rcu_read_lock();
        session = session_find_by_id(LTTNG_OPTIONAL_GET(item->context.session_id));
        if (!session) {
                DBG("Failed to find session `%s` by name while executing `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto error_unlock_list;
        }
 
        session_lock(session);
        if (session->destroyed) {
-               DBG("Session `%s` with id = %" PRIu64 " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
-                               session->name, session->id,
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+               DBG("Session `%s` with id = %" PRIu64
+                   " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
+                   session->name,
+                   session->id,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                goto error_unlock_session;
        }
 
@@ -513,27 +519,31 @@ static int action_executor_rotate_session_handler(
                goto error_unlock_session;
        }
 
-       cmd_ret = (lttng_error_code) cmd_rotate_session(session, NULL, false,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
+       cmd_ret = (lttng_error_code) cmd_rotate_session(
+               session, nullptr, false, LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
        switch (cmd_ret) {
        case LTTNG_OK:
                DBG("Successfully started rotation of session `%s` on behalf of trigger `%s`",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        case LTTNG_ERR_ROTATION_PENDING:
                DBG("Attempted to start a rotation of session `%s` on behalf of trigger `%s` but a rotation is already ongoing",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                break;
        case LTTNG_ERR_ROTATION_MULTIPLE_AFTER_STOP:
        case LTTNG_ERR_ROTATION_AFTER_STOP_CLEAR:
                DBG("Attempted to start a rotation of session `%s` on behalf of trigger `%s` but a rotation has already been completed since the last stop or clear",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        default:
                WARN("Failed to start a rotation of session `%s` on behalf of trigger `%s`: %s",
-                               session_name, get_trigger_name(work_item->trigger),
-                               lttng_strerror(-cmd_ret));
+                    session_name,
+                    get_trigger_name(work_item->trigger),
+                    lttng_strerror(-cmd_ret));
                lttng_action_increase_execution_failure_count(action);
                break;
        }
@@ -542,77 +552,74 @@ error_unlock_session:
        session_unlock(session);
        session_put(session);
 error_unlock_list:
-       rcu_read_unlock();
        session_unlock_list();
 end:
        return ret;
 }
 
-static int action_executor_snapshot_session_handler(
-               struct action_executor *executor __attribute__((unused)),
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item)
+static int action_executor_snapshot_session_handler(struct action_executor *executor
+                                                   __attribute__((unused)),
+                                                   const struct action_work_item *work_item,
+                                                   struct action_work_subitem *item)
 {
        int ret = 0;
        const char *session_name;
        enum lttng_action_status action_status;
        struct ltt_session *session;
        lttng_snapshot_output default_snapshot_output;
-       const struct lttng_snapshot_output *snapshot_output =
-                       &default_snapshot_output;
+       const struct lttng_snapshot_output *snapshot_output = &default_snapshot_output;
        enum lttng_error_code cmd_ret;
        struct lttng_action *action = item->action;
 
        default_snapshot_output.max_size = UINT64_MAX;
 
+       lttng::urcu::read_lock_guard read_lock;
+
        /*
         * Validate if, at the moment the action was queued, the target session
         * existed. If not, skip the action altogether.
         */
        if (!item->context.session_id.is_set) {
                DBG("Session was not present at the moment the work item was enqueued for `%s` action of trigger `%s`",
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto end;
        }
 
-       action_status = lttng_action_snapshot_session_get_session_name(
-                       action, &session_name);
+       action_status = lttng_action_snapshot_session_get_session_name(action, &session_name);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
-               ERR("Failed to get session name from `%s` action",
-                               get_action_name(action));
+               ERR("Failed to get session name from `%s` action", get_action_name(action));
                ret = -1;
                goto end;
        }
 
-       action_status = lttng_action_snapshot_session_get_output(
-                       action, &snapshot_output);
-       if (action_status != LTTNG_ACTION_STATUS_OK &&
-                       action_status != LTTNG_ACTION_STATUS_UNSET) {
-               ERR("Failed to get output from `%s` action",
-                               get_action_name(action));
+       action_status = lttng_action_snapshot_session_get_output(action, &snapshot_output);
+       if (action_status != LTTNG_ACTION_STATUS_OK && action_status != LTTNG_ACTION_STATUS_UNSET) {
+               ERR("Failed to get output from `%s` action", get_action_name(action));
                ret = -1;
                goto end;
        }
 
        session_lock_list();
-       rcu_read_lock();
        session = session_find_by_id(LTTNG_OPTIONAL_GET(item->context.session_id));
        if (!session) {
                DBG("Failed to find session `%s` by name while executing `%s` action of trigger `%s`",
-                               session_name, get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                lttng_action_increase_execution_failure_count(action);
                goto error_unlock_list;
        }
 
        session_lock(session);
        if (session->destroyed) {
-               DBG("Session `%s` with id = %" PRIu64 " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
-                               session->name, session->id,
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger));
+               DBG("Session `%s` with id = %" PRIu64
+                   " is flagged as destroyed. Skipping: action = `%s`, trigger = `%s`",
+                   session->name,
+                   session->id,
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger));
                goto error_unlock_session;
        }
 
@@ -624,12 +631,14 @@ static int action_executor_snapshot_session_handler(
        switch (cmd_ret) {
        case LTTNG_OK:
                DBG("Successfully recorded snapshot of session `%s` on behalf of trigger `%s`",
-                               session_name, get_trigger_name(work_item->trigger));
+                   session_name,
+                   get_trigger_name(work_item->trigger));
                break;
        default:
                WARN("Failed to record snapshot of session `%s` on behalf of trigger `%s`: %s",
-                               session_name, get_trigger_name(work_item->trigger),
-                               lttng_strerror(-cmd_ret));
+                    session_name,
+                    get_trigger_name(work_item->trigger),
+                    lttng_strerror(-cmd_ret));
                lttng_action_increase_execution_failure_count(action);
                break;
        }
@@ -638,24 +647,23 @@ error_unlock_session:
        session_unlock(session);
        session_put(session);
 error_unlock_list:
-       rcu_read_unlock();
        session_unlock_list();
 end:
        return ret;
 }
 
-static int action_executor_list_handler(
-               struct action_executor *executor __attribute__((unused)),
-               const struct action_work_item *work_item __attribute__((unused)),
-               struct action_work_subitem *item __attribute__((unused)))
+static int action_executor_list_handler(struct action_executor *executor __attribute__((unused)),
+                                       const struct action_work_item *work_item
+                                       __attribute__((unused)),
+                                       struct action_work_subitem *item __attribute__((unused)))
 {
        ERR("Execution of a list action by the action executor should never occur");
        abort();
 }
 
 static int action_executor_generic_handler(struct action_executor *executor,
-               const struct action_work_item *work_item,
-               struct action_work_subitem *item)
+                                          const struct action_work_item *work_item,
+                                          struct action_work_subitem *item)
 {
        int ret;
        struct lttng_action *action = item->action;
@@ -666,46 +674,48 @@ static int action_executor_generic_handler(struct action_executor *executor,
        lttng_action_increase_execution_request_count(action);
        if (!lttng_action_should_execute(action)) {
                DBG("Policy prevented execution of action `%s` of trigger `%s` action work item %" PRIu64,
-                               get_action_name(action),
-                               get_trigger_name(work_item->trigger),
-                               work_item->id);
+                   get_action_name(action),
+                   get_trigger_name(work_item->trigger),
+                   work_item->id);
                ret = 0;
                goto end;
        }
 
        lttng_action_increase_execution_count(action);
        DBG("Executing action `%s` of trigger `%s` action work item %" PRIu64,
-                       get_action_name(action),
-                       get_trigger_name(work_item->trigger),
-                       work_item->id);
+           get_action_name(action),
+           get_trigger_name(work_item->trigger),
+           work_item->id);
        ret = action_executors[action_type](executor, work_item, item);
 end:
        return ret;
 }
 
 static int action_work_item_execute(struct action_executor *executor,
-               struct action_work_item *work_item)
+                                   struct action_work_item *work_item)
 {
        int ret;
        size_t count, i;
 
        DBG("Starting execution of action work item %" PRIu64 " of trigger `%s`",
-                       work_item->id, get_trigger_name(work_item->trigger));
+           work_item->id,
+           get_trigger_name(work_item->trigger));
 
        count = lttng_dynamic_array_get_count(&work_item->subitems);
        for (i = 0; i < count; i++) {
                struct action_work_subitem *item;
 
-               item = (action_work_subitem *) lttng_dynamic_array_get_element(&work_item->subitems, i);
-               ret = action_executor_generic_handler(
-                               executor, work_item, item);
+               item = (action_work_subitem *) lttng_dynamic_array_get_element(&work_item->subitems,
+                                                                              i);
+               ret = action_executor_generic_handler(executor, work_item, item);
                if (ret) {
                        goto end;
                }
        }
 end:
        DBG("Completed execution of action work item %" PRIu64 " of trigger `%s`",
-                       work_item->id, get_trigger_name(work_item->trigger));
+           work_item->id,
+           get_trigger_name(work_item->trigger));
        return ret;
 }
 
@@ -724,8 +734,7 @@ static void *action_executor_thread(void *_data)
 
        LTTNG_ASSERT(executor);
 
-       health_register(the_health_sessiond,
-                       HEALTH_SESSIOND_TYPE_ACTION_EXECUTOR);
+       health_register(the_health_sessiond, HEALTH_SESSIOND_TYPE_ACTION_EXECUTOR);
 
        rcu_register_thread();
        rcu_thread_online();
@@ -740,16 +749,15 @@ static void *action_executor_thread(void *_data)
                if (executor->work.pending_count == 0) {
                        health_poll_entry();
                        DBG("No work items enqueued, entering wait");
-                       pthread_cond_wait(&executor->work.cond,
-                                       &executor->work.lock);
+                       pthread_cond_wait(&executor->work.cond, &executor->work.lock);
                        DBG("Woke-up from wait");
                        health_poll_exit();
                        continue;
                }
 
                /* Pop item from front of the list with work lock held. */
-               work_item = cds_list_first_entry(&executor->work.list,
-                               struct action_work_item, list_node);
+               work_item = cds_list_first_entry(
+                       &executor->work.list, struct action_work_item, list_node);
                cds_list_del(&work_item->list_node);
                executor->work.pending_count--;
 
@@ -762,19 +770,21 @@ static void *action_executor_thread(void *_data)
                /* Execute item only if a trigger is registered. */
                lttng_trigger_lock(work_item->trigger);
                if (!lttng_trigger_is_registered(work_item->trigger)) {
-                       const char *trigger_name = NULL;
+                       const char *trigger_name = nullptr;
                        uid_t trigger_owner_uid;
                        enum lttng_trigger_status trigger_status;
 
                        trigger_name = get_trigger_name(work_item->trigger);
 
-                       trigger_status = lttng_trigger_get_owner_uid(
-                                       work_item->trigger, &trigger_owner_uid);
+                       trigger_status =
+                               lttng_trigger_get_owner_uid(work_item->trigger, &trigger_owner_uid);
                        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-                       DBG("Work item skipped since the associated trigger is no longer registered: work item id = %" PRIu64 ", trigger name = `%s`, trigger owner uid = %d",
-                                       work_item->id, trigger_name,
-                                       (int) trigger_owner_uid);
+                       DBG("Work item skipped since the associated trigger is no longer registered: work item id = %" PRIu64
+                           ", trigger name = `%s`, trigger owner uid = %d",
+                           work_item->id,
+                           trigger_name,
+                           (int) trigger_owner_uid);
                        ret = 0;
                        goto skip_execute;
                }
@@ -804,7 +814,7 @@ static void *action_executor_thread(void *_data)
        rcu_unregister_thread();
        health_unregister(the_health_sessiond);
 
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_action_executor_thread(void *_data)
@@ -829,8 +839,7 @@ static void clean_up_action_executor_thread(void *_data)
        free(executor);
 }
 
-struct action_executor *action_executor_create(
-               struct notification_thread_handle *handle)
+struct action_executor *action_executor_create(struct notification_thread_handle *handle)
 {
        struct action_executor *executor = zmalloc<action_executor>();
 
@@ -839,13 +848,15 @@ struct action_executor *action_executor_create(
        }
 
        CDS_INIT_LIST_HEAD(&executor->work.list);
-       pthread_cond_init(&executor->work.cond, NULL);
-       pthread_mutex_init(&executor->work.lock, NULL);
+       pthread_cond_init(&executor->work.cond, nullptr);
+       pthread_mutex_init(&executor->work.lock, nullptr);
        executor->notification_thread_handle = handle;
 
        executor->thread = lttng_thread_create(THREAD_NAME,
-                       action_executor_thread, shutdown_action_executor_thread,
-                       clean_up_action_executor_thread, executor);
+                                              action_executor_thread,
+                                              shutdown_action_executor_thread,
+                                              clean_up_action_executor_thread,
+                                              executor);
 end:
        return executor;
 }
@@ -859,17 +870,15 @@ void action_executor_destroy(struct action_executor *executor)
        pthread_mutex_lock(&executor->work.lock);
        if (executor->work.pending_count != 0) {
                WARN("%" PRIu64
-                       " trigger action%s still queued for execution and will be discarded",
-                               executor->work.pending_count,
-                               executor->work.pending_count == 1 ? " is" :
-                                                                   "s are");
+                    " trigger action%s still queued for execution and will be discarded",
+                    executor->work.pending_count,
+                    executor->work.pending_count == 1 ? " is" : "s are");
        }
 
-       cds_list_for_each_entry_safe (
-                       work_item, tmp, &executor->work.list, list_node) {
-               WARN("Discarding action work item %" PRIu64
-                               " associated to trigger `%s`",
-                               work_item->id, get_trigger_name(work_item->trigger));
+       cds_list_for_each_entry_safe (work_item, tmp, &executor->work.list, list_node) {
+               WARN("Discarding action work item %" PRIu64 " associated to trigger `%s`",
+                    work_item->id,
+                    get_trigger_name(work_item->trigger));
                cds_list_del(&work_item->list_node);
                action_work_item_destroy(work_item);
        }
@@ -878,12 +887,12 @@ void action_executor_destroy(struct action_executor *executor)
 }
 
 /* RCU read-lock must be held by the caller. */
-enum action_executor_status action_executor_enqueue_trigger(
-               struct action_executor *executor,
-               struct lttng_trigger *trigger,
-               struct lttng_evaluation *evaluation,
-               const struct lttng_credentials *object_creds,
-               struct notification_client_list *client_list)
+enum action_executor_status
+action_executor_enqueue_trigger(struct action_executor *executor,
+                               struct lttng_trigger *trigger,
+                               struct lttng_evaluation *evaluation,
+                               const struct lttng_credentials *object_creds,
+                               struct notification_client_list *client_list)
 {
        int ret;
        enum action_executor_status executor_status = ACTION_EXECUTOR_STATUS_OK;
@@ -899,7 +908,8 @@ enum action_executor_status action_executor_enqueue_trigger(
        if (executor->work.pending_count >= MAX_QUEUED_WORK_COUNT) {
                /* Most likely spammy, remove if it is the case. */
                DBG("Refusing to enqueue action for trigger (overflow): trigger name = `%s`, work item id = %" PRIu64,
-                               get_trigger_name(trigger), work_item_id);
+                   get_trigger_name(trigger),
+                   work_item_id);
                executor_status = ACTION_EXECUTOR_STATUS_OVERFLOW;
                goto error_unlock;
        }
@@ -907,15 +917,14 @@ enum action_executor_status action_executor_enqueue_trigger(
        work_item = zmalloc<action_work_item>();
        if (!work_item) {
                PERROR("Failed to allocate action executor work item: trigger name = `%s`",
-                               get_trigger_name(trigger));
+                      get_trigger_name(trigger));
                executor_status = ACTION_EXECUTOR_STATUS_ERROR;
                goto error_unlock;
        }
 
        lttng_trigger_get(trigger);
        if (client_list) {
-               const bool reference_acquired =
-                               notification_client_list_get(client_list);
+               const bool reference_acquired = notification_client_list_get(client_list);
 
                LTTNG_ASSERT(reference_acquired);
        }
@@ -925,7 +934,7 @@ enum action_executor_status action_executor_enqueue_trigger(
 
        /* Ownership transferred to the work item. */
        work_item->evaluation = evaluation;
-       evaluation = NULL;
+       evaluation = nullptr;
 
        work_item->client_list = client_list;
        work_item->object_creds.is_set = !!object_creds;
@@ -937,14 +946,13 @@ enum action_executor_status action_executor_enqueue_trigger(
 
        /* Build the array of action work subitems for the passed trigger. */
        lttng_dynamic_array_init(&work_item->subitems,
-                       sizeof(struct action_work_subitem),
-                       action_work_subitem_destructor);
+                                sizeof(struct action_work_subitem),
+                                action_work_subitem_destructor);
 
-       ret = populate_subitem_array_from_trigger(
-                       trigger, &work_item->subitems);
+       ret = populate_subitem_array_from_trigger(trigger, &work_item->subitems);
        if (ret) {
                ERR("Failed to populate work item sub items on behalf of trigger: trigger name = `%s`",
-                               get_trigger_name(trigger));
+                   get_trigger_name(trigger));
                executor_status = ACTION_EXECUTOR_STATUS_ERROR;
                goto error_unlock;
        }
@@ -952,7 +960,8 @@ enum action_executor_status action_executor_enqueue_trigger(
        cds_list_add_tail(&work_item->list_node, &executor->work.list);
        executor->work.pending_count++;
        DBG("Enqueued action for trigger: trigger name = `%s`, work item id = %" PRIu64,
-                       get_trigger_name(trigger), work_item_id);
+           get_trigger_name(trigger),
+           work_item_id);
        signal = true;
 
 error_unlock:
@@ -966,14 +975,14 @@ error_unlock:
 }
 
 static int add_action_to_subitem_array(struct lttng_action *action,
-               struct lttng_dynamic_array *subitems)
+                                      struct lttng_dynamic_array *subitems)
 {
        int ret = 0;
        enum lttng_action_type type = lttng_action_get_type(action);
-       const char *session_name = NULL;
+       const char *session_name = nullptr;
        enum lttng_action_status status;
        struct action_work_subitem subitem = {
-               .action = NULL,
+               .action = nullptr,
                .context = {
                        .session_id = LTTNG_OPTIONAL_INIT_UNSET,
                },
@@ -983,19 +992,10 @@ static int add_action_to_subitem_array(struct lttng_action *action,
        LTTNG_ASSERT(subitems);
 
        if (type == LTTNG_ACTION_TYPE_LIST) {
-               unsigned int count, i;
-
-               status = lttng_action_list_get_count(action, &count);
-               LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-
-               for (i = 0; i < count; i++) {
-                       struct lttng_action *inner_action = NULL;
-
-                       inner_action = lttng_action_list_borrow_mutable_at_index(
-                                       action, i);
+               for (auto inner_action : lttng::ctl::action_list_view(action)) {
                        LTTNG_ASSERT(inner_action);
-                       ret = add_action_to_subitem_array(
-                                       inner_action, subitems);
+
+                       ret = add_action_to_subitem_array(inner_action, subitems);
                        if (ret) {
                                goto end;
                        }
@@ -1013,23 +1013,19 @@ static int add_action_to_subitem_array(struct lttng_action *action,
        case LTTNG_ACTION_TYPE_NOTIFY:
                break;
        case LTTNG_ACTION_TYPE_START_SESSION:
-               status = lttng_action_start_session_get_session_name(
-                               action, &session_name);
+               status = lttng_action_start_session_get_session_name(action, &session_name);
                LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
                break;
        case LTTNG_ACTION_TYPE_STOP_SESSION:
-               status = lttng_action_stop_session_get_session_name(
-                               action, &session_name);
+               status = lttng_action_stop_session_get_session_name(action, &session_name);
                LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
                break;
        case LTTNG_ACTION_TYPE_ROTATE_SESSION:
-               status = lttng_action_rotate_session_get_session_name(
-                               action, &session_name);
+               status = lttng_action_rotate_session_get_session_name(action, &session_name);
                LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
                break;
        case LTTNG_ACTION_TYPE_SNAPSHOT_SESSION:
-               status = lttng_action_snapshot_session_get_session_name(
-                               action, &session_name);
+               status = lttng_action_snapshot_session_get_session_name(action, &session_name);
                LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
                break;
        case LTTNG_ACTION_TYPE_LIST:
@@ -1047,7 +1043,7 @@ static int add_action_to_subitem_array(struct lttng_action *action,
         * now we leave the decision to skip to the action executor for sake of
         * simplicity and consistency.
         */
-       if (session_name != NULL) {
+       if (session_name != nullptr) {
                uint64_t session_id;
 
                /*
@@ -1065,8 +1061,7 @@ static int add_action_to_subitem_array(struct lttng_action *action,
                 * execution time.
                 */
                if (sample_session_id_by_name(session_name, &session_id)) {
-                       LTTNG_OPTIONAL_SET(&subitem.context.session_id,
-                                       session_id);
+                       LTTNG_OPTIONAL_SET(&subitem.context.session_id, session_id);
                }
        }
 
@@ -1087,7 +1082,7 @@ end:
 }
 
 static int populate_subitem_array_from_trigger(struct lttng_trigger *trigger,
-               struct lttng_dynamic_array *subitems)
+                                              struct lttng_dynamic_array *subitems)
 {
        struct lttng_action *action;
 
index 85d5931fedb9fa09188652d0646036f9fc9d08da..4fc874f15b38773319a5121797df6e5c1d13a06f 100644 (file)
@@ -22,8 +22,7 @@ enum action_executor_status {
        ACTION_EXECUTOR_STATUS_INVALID,
 };
 
-struct action_executor *action_executor_create(
-               struct notification_thread_handle *handle);
+struct action_executor *action_executor_create(struct notification_thread_handle *handle);
 
 void action_executor_destroy(struct action_executor *executor);
 
@@ -37,11 +36,11 @@ void action_executor_destroy(struct action_executor *executor);
  * This function assumes the ownership of the `evaluation` both on success and
  * failure: the caller should no longer access it once the function returns.
  */
-enum action_executor_status action_executor_enqueue_trigger(
-               struct action_executor *executor,
-               struct lttng_trigger *trigger,
-               struct lttng_evaluation *evaluation,
-               const struct lttng_credentials *object_creds,
-               struct notification_client_list *list);
+enum action_executor_status
+action_executor_enqueue_trigger(struct action_executor *executor,
+                               struct lttng_trigger *trigger,
+                               struct lttng_evaluation *evaluation,
+                               const struct lttng_credentials *object_creds,
+                               struct notification_client_list *list);
 
 #endif /* ACTION_EXECUTOR_H */
index c8fab6164f0c68b05b9545aab7abe25bbb192749..23a26a8063b777a64a03f1892a6e61d66dc9fd6f 100644 (file)
@@ -7,20 +7,22 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/uri.hpp>
-#include <common/utils.hpp>
-
-#include <common/compat/endian.hpp>
-
-#include "fd-limit.hpp"
 #include "agent-thread.hpp"
 #include "agent.hpp"
+#include "fd-limit.hpp"
 #include "lttng-sessiond.hpp"
 #include "session.hpp"
-#include "utils.hpp"
 #include "thread.hpp"
+#include "utils.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
+#include <common/uri.hpp>
+#include <common/utils.hpp>
+
+#include <fcntl.h>
 
 namespace {
 struct thread_notifiers {
@@ -65,7 +67,7 @@ static void update_agent_app(const struct agent_app *app)
        list = session_get_list();
        LTTNG_ASSERT(list);
 
-       cds_list_for_each_entry_safe(session, stmp, &list->head, list) {
+       cds_list_for_each_entry_safe (session, stmp, &list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
@@ -74,37 +76,38 @@ static void update_agent_app(const struct agent_app *app)
                if (session->ust_session) {
                        const struct agent *agt;
 
-                       rcu_read_lock();
+                       lttng::urcu::read_lock_guard read_lock;
                        agt = trace_ust_find_agent(session->ust_session, app->domain);
                        if (agt) {
                                agent_update(agt, app);
                        }
-                       rcu_read_unlock();
                }
                session_unlock(session);
                session_put(session);
        }
 
-       rcu_read_lock();
-       /*
-        * We are protected against the addition of new events by the session
-        * list lock being held.
-        */
-       cds_lfht_for_each_entry(the_trigger_agents_ht_by_domain->ht,
-                       &iter.iter, trigger_agent, node.node) {
-               agent_update(trigger_agent, app);
+       {
+               /*
+                * We are protected against the addition of new events by the session
+                * list lock being held.
+                */
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       the_trigger_agents_ht_by_domain->ht, &iter.iter, trigger_agent, node.node) {
+                       agent_update(trigger_agent, app);
+               }
        }
-       rcu_read_unlock();
 }
 
 /*
  * Create and init socket from uri.
  */
-static struct lttcomm_sock *init_tcp_socket(void)
+static struct lttcomm_sock *init_tcp_socket()
 {
        int ret;
-       struct lttng_uri *uri = NULL;
-       struct lttcomm_sock *sock = NULL;
+       struct lttng_uri *uri = nullptr;
+       struct lttcomm_sock *sock = nullptr;
        unsigned int port;
        bool bind_succeeded = false;
 
@@ -119,7 +122,7 @@ static struct lttcomm_sock *init_tcp_socket(void)
 
        sock = lttcomm_alloc_sock_from_uri(uri);
        uri_free(uri);
-       if (sock == NULL) {
+       if (sock == nullptr) {
                ERR("agent allocating TCP socket");
                goto error;
        }
@@ -129,12 +132,11 @@ static struct lttcomm_sock *init_tcp_socket(void)
                goto error;
        }
 
-       for (port = the_config.agent_tcp_port.begin;
-                       port <= the_config.agent_tcp_port.end; port++) {
+       for (port = the_config.agent_tcp_port.begin; port <= the_config.agent_tcp_port.end;
+            port++) {
                ret = lttcomm_sock_set_port(sock, (uint16_t) port);
                if (ret) {
-                       ERR("Failed to set port %u on socket",
-                                       port);
+                       ERR("Failed to set port %u on socket", port);
                        goto error;
                }
                DBG3("Trying to bind on port %u", port);
@@ -145,8 +147,7 @@ static struct lttcomm_sock *init_tcp_socket(void)
                }
 
                if (errno == EADDRINUSE) {
-                       DBG("Failed to bind to port %u since it is already in use",
-                                       port);
+                       DBG("Failed to bind to port %u since it is already in use", port);
                } else {
                        PERROR("Failed to bind to port %u", port);
                        goto error;
@@ -154,17 +155,16 @@ static struct lttcomm_sock *init_tcp_socket(void)
        }
 
        if (!bind_succeeded) {
-               if (the_config.agent_tcp_port.begin ==
-                               the_config.agent_tcp_port.end) {
+               if (the_config.agent_tcp_port.begin == the_config.agent_tcp_port.end) {
                        WARN("Another process is already using the agent port %i. "
                             "Agent support will be deactivated.",
-                                       the_config.agent_tcp_port.begin);
+                            the_config.agent_tcp_port.begin);
                        goto error;
                } else {
                        WARN("All ports in the range [%i, %i] are already in use. "
                             "Agent support will be deactivated.",
-                                       the_config.agent_tcp_port.begin,
-                                       the_config.agent_tcp_port.end);
+                            the_config.agent_tcp_port.begin,
+                            the_config.agent_tcp_port.end);
                        goto error;
                }
        }
@@ -174,8 +174,7 @@ static struct lttcomm_sock *init_tcp_socket(void)
                goto error;
        }
 
-       DBG("Listening on TCP port %u and socket %d",
-                       port, sock->fd);
+       DBG("Listening on TCP port %u and socket %d", port, sock->fd);
 
        return sock;
 
@@ -183,7 +182,7 @@ error:
        if (sock) {
                lttcomm_destroy_sock(sock);
        }
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -202,8 +201,7 @@ static void destroy_tcp_socket(struct lttcomm_sock *sock)
                port = 0;
        }
 
-       DBG3("Destroy TCP socket on port %" PRIu16,
-                       port);
+       DBG3("Destroy TCP socket on port %" PRIu16, port);
 
        /* This will return gracefully if fd is invalid. */
        sock->ops->close(sock);
@@ -230,16 +228,17 @@ static const char *domain_type_str(enum lttng_domain_type domain_type)
        }
 }
 
-static bool is_agent_protocol_version_supported(
-               const struct agent_protocol_version *version)
+static bool is_agent_protocol_version_supported(const struct agent_protocol_version *version)
 {
        const bool is_supported = version->major == AGENT_MAJOR_VERSION &&
-                       version->minor == AGENT_MINOR_VERSION;
+               version->minor == AGENT_MINOR_VERSION;
 
        if (!is_supported) {
                WARN("Refusing agent connection: unsupported protocol version %ui.%ui, expected %i.%i",
-                               version->major, version->minor,
-                               AGENT_MAJOR_VERSION, AGENT_MINOR_VERSION);
+                    version->major,
+                    version->minor,
+                    AGENT_MAJOR_VERSION,
+                    AGENT_MINOR_VERSION);
        }
 
        return is_supported;
@@ -252,10 +251,9 @@ static bool is_agent_protocol_version_supported(
  * On success, the resulting socket is returned through `agent_app_socket`
  * and the application's reported id is updated through `agent_app_id`.
  */
-static int accept_agent_connection(
-               struct lttcomm_sock *reg_sock,
-               struct agent_app_id *agent_app_id,
-               struct lttcomm_sock **agent_app_socket)
+static int accept_agent_connection(struct lttcomm_sock *reg_sock,
+                                  struct agent_app_id *agent_app_id,
+                                  struct lttcomm_sock **agent_app_socket)
 {
        int ret;
        struct agent_protocol_version agent_version;
@@ -277,7 +275,8 @@ static int accept_agent_connection(
                        PERROR("Failed to register new agent application");
                } else if (size != 0) {
                        ERR("Failed to register new agent application: invalid registration message length: expected length = %zu, message length = %zd",
-                                       sizeof(msg), size);
+                           sizeof(msg),
+                           size);
                } else {
                        DBG("Failed to register new agent application: connection closed");
                }
@@ -285,7 +284,7 @@ static int accept_agent_connection(
                goto error_close_socket;
        }
 
-       agent_version = (struct agent_protocol_version) {
+       agent_version = (struct agent_protocol_version){
                be32toh(msg.major_version),
                be32toh(msg.minor_version),
        };
@@ -296,17 +295,18 @@ static int accept_agent_connection(
                goto error_close_socket;
        }
 
-       *agent_app_id = (struct agent_app_id) {
+       *agent_app_id = (struct agent_app_id){
                .pid = (pid_t) be32toh(msg.pid),
                .domain = (lttng_domain_type) be32toh(msg.domain),
        };
 
        DBG2("New registration for agent application: pid = %ld, domain = %s, socket fd = %d",
-                       (long) agent_app_id->pid,
-                       domain_type_str(agent_app_id->domain), new_sock->fd);
+            (long) agent_app_id->pid,
+            domain_type_str(agent_app_id->domain),
+            new_sock->fd);
 
        *agent_app_socket = new_sock;
-       new_sock = NULL;
+       new_sock = nullptr;
        ret = 0;
        goto end;
 
@@ -317,7 +317,7 @@ end:
        return ret;
 }
 
-bool agent_tracing_is_enabled(void)
+bool agent_tracing_is_enabled()
 {
        int enabled;
 
@@ -331,19 +331,16 @@ bool agent_tracing_is_enabled(void)
  */
 static int write_agent_port(uint16_t port)
 {
-       return utils_create_pid_file(
-                       (pid_t) port, the_config.agent_port_file_path.value);
+       return utils_create_pid_file((pid_t) port, the_config.agent_port_file_path.value);
 }
 
-static
-void mark_thread_as_ready(struct thread_notifiers *notifiers)
+static void mark_thread_as_ready(struct thread_notifiers *notifiers)
 {
        DBG("Marking agent management thread as ready");
        sem_post(&notifiers->ready);
 }
 
-static
-void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
+static void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
 {
        DBG("Waiting for agent management thread to be ready");
        sem_wait(&notifiers->ready);
@@ -355,13 +352,12 @@ void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
  */
 static void *thread_agent_management(void *data)
 {
-       int i, ret, pollfd;
-       uint32_t revents, nb_fd;
+       int i, ret;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct lttcomm_sock *reg_sock;
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(
-                       notifiers->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
 
        DBG("Manage agent application registration.");
 
@@ -377,8 +373,7 @@ static void *thread_agent_management(void *data)
                goto error_poll_create;
        }
 
-       ret = lttng_poll_add(&events, quit_pipe_read_fd,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                goto error_tcp_socket;
        }
@@ -411,20 +406,18 @@ static void *thread_agent_management(void *data)
        mark_thread_as_ready(notifiers);
 
        /* Add TCP socket to the poll set. */
-       ret = lttng_poll_add(&events, reg_sock->fd,
-                       LPOLLIN | LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+       ret = lttng_poll_add(&events, reg_sock->fd, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                goto error;
        }
 
-       while (1) {
+       while (true) {
                DBG3("Manage agent polling");
 
                /* Inifinite blocking call, waiting for transmission */
-restart:
+       restart:
                ret = lttng_poll_wait(&events, -1);
-               DBG3("Manage agent return from poll on %d fds",
-                               LTTNG_POLL_GETNB(&events));
+               DBG3("Manage agent return from poll on %d fds", LTTNG_POLL_GETNB(&events));
                if (ret < 0) {
                        /*
                         * Restart interrupted system call.
@@ -439,18 +432,19 @@ restart:
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       if (pollfd == quit_pipe_read_fd) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                goto exit;
                        }
 
                        /* Activity on the registration socket. */
                        if (revents & LPOLLIN) {
                                struct agent_app_id new_app_id;
-                               struct agent_app *new_app = NULL;
+                               struct agent_app *new_app = nullptr;
                                struct lttcomm_sock *new_app_socket;
                                int new_app_socket_fd;
 
@@ -467,24 +461,21 @@ restart:
                                 * new_app_socket's ownership has been
                                 * transferred to the new agent app.
                                 */
-                               new_app = agent_create_app(new_app_id.pid,
-                                               new_app_id.domain,
-                                               new_app_socket);
+                               new_app = agent_create_app(
+                                       new_app_id.pid, new_app_id.domain, new_app_socket);
                                if (!new_app) {
-                                       new_app_socket->ops->close(
-                                                       new_app_socket);
+                                       new_app_socket->ops->close(new_app_socket);
                                        continue;
                                }
                                new_app_socket_fd = new_app_socket->fd;
-                               new_app_socket = NULL;
+                               new_app_socket = nullptr;
 
                                /*
                                 * Since this is a command socket (write then
                                 * read), only add poll error event to only
                                 * detect shutdown.
                                 */
-                               ret = lttng_poll_add(&events, new_app_socket_fd,
-                                               LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+                               ret = lttng_poll_add(&events, new_app_socket_fd, LPOLLRDHUP);
                                if (ret < 0) {
                                        agent_destroy_app(new_app);
                                        continue;
@@ -507,8 +498,7 @@ restart:
                                if (ret < 0) {
                                        agent_destroy_app(new_app);
                                        /* Removing from the poll set. */
-                                       ret = lttng_poll_del(&events,
-                                                       new_app_socket_fd);
+                                       ret = lttng_poll_del(&events, new_app_socket_fd);
                                        if (ret < 0) {
                                                session_unlock_list();
                                                goto error;
@@ -546,7 +536,7 @@ error_poll_create:
        DBG("Cleaning up and stopping.");
        rcu_thread_offline();
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_agent_management_thread(void *data)
@@ -566,7 +556,7 @@ static void cleanup_agent_management_thread(void *data)
        free(notifiers);
 }
 
-bool launch_agent_management_thread(void)
+bool launch_agent_management_thread()
 {
        struct thread_notifiers *notifiers;
        struct lttng_thread *thread;
@@ -582,10 +572,10 @@ bool launch_agent_management_thread(void)
                goto error;
        }
        thread = lttng_thread_create("Agent management",
-                       thread_agent_management,
-                       shutdown_agent_management_thread,
-                       cleanup_agent_management_thread,
-                       notifiers);
+                                    thread_agent_management,
+                                    shutdown_agent_management_thread,
+                                    cleanup_agent_management_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index d84ea61721f21cacfb2d8879d7d2d65b9490ff61..0d56588ea31d211285ac51642ad3f2a1534443f7 100644 (file)
 
 #ifdef HAVE_LIBLTTNG_UST_CTL
 
-bool launch_agent_management_thread(void);
-bool agent_tracing_is_enabled(void);
+bool launch_agent_management_thread();
+bool agent_tracing_is_enabled();
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-bool launch_agent_management_thread(void)
+static inline bool launch_agent_management_thread(void)
 {
        return true;
 }
 
-static inline
-bool agent_tracing_is_enabled(void)
+static inline bool agent_tracing_is_enabled(void)
 {
        return false;
 }
index 31f1634bd70b70a681b6479433e0eb743fe72492..210ec9b0c6f2f997cab78ad26c6165192ea18360 100644 (file)
@@ -7,34 +7,33 @@
  */
 
 #define _LGPL_SOURCE
-#include <urcu/uatomic.h>
-#include <urcu/rculist.h>
+#include "agent.hpp"
+#include "common/error.hpp"
+#include "ust-app.hpp"
+#include "utils.hpp"
 
-#include <lttng/event-rule/event-rule.h>
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/sessiond-comm/agent.hpp>
+#include <common/urcu.hpp>
+
+#include <lttng/condition/condition.h>
+#include <lttng/condition/event-rule-matches.h>
+#include <lttng/domain-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
+#include <lttng/event-rule/event-rule.h>
 #include <lttng/event-rule/jul-logging.h>
 #include <lttng/event-rule/log4j-logging.h>
 #include <lttng/event-rule/python-logging.h>
-#include <lttng/condition/condition.h>
-#include <lttng/condition/event-rule-matches.h>
-#include <lttng/domain-internal.hpp>
 #include <lttng/log-level-rule-internal.hpp>
 
-#include <common/common.hpp>
-#include <common/sessiond-comm/agent.hpp>
-
-#include <common/compat/endian.hpp>
-
-#include "agent.hpp"
-#include "ust-app.hpp"
-#include "utils.hpp"
-#include "common/error.hpp"
+#include <urcu/rculist.h>
+#include <urcu/uatomic.h>
 
-typedef enum lttng_event_rule_status (*event_rule_logging_get_name_pattern)(
-               const struct lttng_event_rule *rule, const char **pattern);
-typedef enum lttng_event_rule_status (*event_rule_logging_get_log_level_rule)(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+using event_rule_logging_get_name_pattern =
+       enum lttng_event_rule_status (*)(const struct lttng_event_rule *, const char **);
+using event_rule_logging_get_log_level_rule = enum lttng_event_rule_status (*)(
+       const struct lttng_event_rule *, const struct lttng_log_level_rule **);
 
 /*
  * Agent application context representation.
@@ -55,8 +54,7 @@ struct agent_app_ctx {
 /*
  * Human readable agent return code.
  */
-static
-const char *lttcomm_agent_ret_code_str(lttcomm_agent_ret_code code)
+static const char *lttcomm_agent_ret_code_str(lttcomm_agent_ret_code code)
 {
        switch (code) {
        case AGENT_RET_CODE_SUCCESS:
@@ -70,8 +68,7 @@ const char *lttcomm_agent_ret_code_str(lttcomm_agent_ret_code code)
        }
 };
 
-static
-void log_reply_code(uint32_t in_reply_ret_code)
+static void log_reply_code(uint32_t in_reply_ret_code)
 {
        int level = PRINT_DBG3;
        /*
@@ -81,22 +78,21 @@ void log_reply_code(uint32_t in_reply_ret_code)
         */
        uint32_t reply_ret_code = in_reply_ret_code;
 
-       if (reply_ret_code < AGENT_RET_CODE_SUCCESS ||
-                       reply_ret_code >= AGENT_RET_CODE_NR) {
+       if (reply_ret_code < AGENT_RET_CODE_SUCCESS || reply_ret_code >= AGENT_RET_CODE_NR) {
                reply_ret_code = AGENT_RET_CODE_NR;
                level = PRINT_ERR;
        }
 
-       LOG(level, "Agent replied with retcode: %s (%" PRIu32 ")",
-                       lttcomm_agent_ret_code_str((lttcomm_agent_ret_code) reply_ret_code),
-                       in_reply_ret_code);
+       LOG(level,
+           "Agent replied with retcode: %s (%" PRIu32 ")",
+           lttcomm_agent_ret_code_str((lttcomm_agent_ret_code) reply_ret_code),
+           in_reply_ret_code);
 }
 
 /*
  * Match function for the events hash table lookup by name.
  */
-static int ht_match_event_by_name(struct cds_lfht_node *node,
-               const void *_key)
+static int ht_match_event_by_name(struct cds_lfht_node *node, const void *_key)
 {
        struct agent_event *event;
        const struct agent_ht_key *key;
@@ -124,8 +120,7 @@ no_match:
  * Match function for the events hash table lookup by name, log level and
  * filter expression.
  */
-static int ht_match_event(struct cds_lfht_node *node,
-               const void *_key)
+static int ht_match_event(struct cds_lfht_node *node, const void *_key)
 {
        struct agent_event *event;
        const struct agent_ht_key *key;
@@ -146,8 +141,10 @@ static int ht_match_event(struct cds_lfht_node *node,
 
        /* Event loglevel value and type. */
        ll_match = loglevels_match(event->loglevel_type,
-               event->loglevel_value, key->loglevel_type,
-               key->loglevel_value, LTTNG_EVENT_LOGLEVEL_ALL);
+                                  event->loglevel_value,
+                                  key->loglevel_type,
+                                  key->loglevel_value,
+                                  LTTNG_EVENT_LOGLEVEL_ALL);
 
        if (!ll_match) {
                goto no_match;
@@ -160,8 +157,9 @@ static int ht_match_event(struct cds_lfht_node *node,
        }
 
        if (event->filter_expression) {
-               if (strncmp(event->filter_expression, key->filter_expression,
-                               strlen(event->filter_expression)) != 0) {
+               if (strncmp(event->filter_expression,
+                           key->filter_expression,
+                           strlen(event->filter_expression)) != 0) {
                        goto no_match;
                }
        }
@@ -175,8 +173,7 @@ no_match:
 /*
  * Add unique agent event based on the event name and loglevel.
  */
-static void add_unique_agent_event(struct lttng_ht *ht,
-               struct agent_event *event)
+static void add_unique_agent_event(struct lttng_ht *ht, struct agent_event *event)
 {
        struct cds_lfht_node *node_ptr;
        struct agent_ht_key key;
@@ -191,8 +188,10 @@ static void add_unique_agent_event(struct lttng_ht *ht,
        key.filter_expression = event->filter_expression;
 
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct(event->node.key, lttng_ht_seed),
-                       ht_match_event, &key, &event->node.node);
+                                      ht->hash_fct(event->node.key, lttng_ht_seed),
+                                      ht_match_event,
+                                      &key,
+                                      &event->node.node);
        LTTNG_ASSERT(node_ptr == &event->node.node);
 }
 
@@ -201,10 +200,8 @@ static void add_unique_agent_event(struct lttng_ht *ht,
  */
 static void destroy_event_agent_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_str *node =
-               lttng::utils::container_of(head, &lttng_ht_node_str::head);
-       struct agent_event *event =
-               lttng::utils::container_of(node, &agent_event::node);
+       struct lttng_ht_node_str *node = lttng::utils::container_of(head, &lttng_ht_node_str::head);
+       struct agent_event *event = lttng::utils::container_of(node, &agent_event::node);
 
        agent_destroy_event(event);
 }
@@ -216,8 +213,7 @@ static void destroy_app_agent_rcu(struct rcu_head *head)
 {
        struct lttng_ht_node_ulong *node =
                lttng::utils::container_of(head, &lttng_ht_node_ulong::head);
-       struct agent_app *app =
-               lttng::utils::container_of(node, &agent_app::node);
+       struct agent_app *app = lttng::utils::container_of(node, &agent_app::node);
 
        free(app);
 }
@@ -228,8 +224,8 @@ static void destroy_app_agent_rcu(struct rcu_head *head)
  *
  * Return 0 on success or else a negative errno message of sendmsg() op.
  */
-static int send_header(struct lttcomm_sock *sock, uint64_t data_size,
-               uint32_t cmd, uint32_t cmd_version)
+static int
+send_header(struct lttcomm_sock *sock, uint64_t data_size, uint32_t cmd, uint32_t cmd_version)
 {
        int ret;
        ssize_t size;
@@ -259,8 +255,7 @@ error:
  *
  * Return 0 on success or else a negative errno value of sendmsg() op.
  */
-static int send_payload(struct lttcomm_sock *sock, const void *data,
-               size_t size)
+static int send_payload(struct lttcomm_sock *sock, const void *data, size_t size)
 {
        int ret;
        ssize_t len;
@@ -317,16 +312,15 @@ static ssize_t list_events(struct agent_app *app, struct lttng_event **events)
        uint32_t nb_event;
        size_t data_size;
        uint32_t reply_ret_code;
-       struct lttng_event *tmp_events = NULL;
-       struct lttcomm_agent_list_reply *reply = NULL;
+       struct lttng_event *tmp_events = nullptr;
+       struct lttcomm_agent_list_reply *reply = nullptr;
        struct lttcomm_agent_list_reply_hdr reply_hdr;
 
        LTTNG_ASSERT(app);
        LTTNG_ASSERT(app->sock);
        LTTNG_ASSERT(events);
 
-       DBG2("Agent listing events for app pid: %d and socket %d", app->pid,
-                       app->sock->fd);
+       DBG2("Agent listing events for app pid: %d and socket %d", app->pid, app->sock->fd);
 
        ret = send_header(app->sock, 0, AGENT_CMD_LIST, 0);
        if (ret < 0) {
@@ -371,8 +365,9 @@ static ssize_t list_events(struct agent_app *app, struct lttng_event **events)
 
        for (i = 0; i < nb_event; i++) {
                offset += len;
-               if (lttng_strncpy(tmp_events[i].name, reply->payload + offset,
-                               sizeof(tmp_events[i].name))) {
+               if (lttng_strncpy(tmp_events[i].name,
+                                 reply->payload + offset,
+                                 sizeof(tmp_events[i].name))) {
                        ret = LTTNG_ERR_INVALID;
                        goto error;
                }
@@ -392,7 +387,6 @@ error:
        free(reply);
        free(tmp_events);
        return -ret;
-
 }
 
 /*
@@ -415,8 +409,10 @@ static int enable_event(const struct agent_app *app, struct agent_event *event)
        LTTNG_ASSERT(app->sock);
        LTTNG_ASSERT(event);
 
-       DBG2("Agent enabling event %s for app pid: %d and socket %d", event->name,
-                       app->pid, app->sock->fd);
+       DBG2("Agent enabling event %s for app pid: %d and socket %d",
+            event->name,
+            app->pid,
+            app->sock->fd);
 
        /*
         * Calculate the payload's size, which is the fixed-size struct followed
@@ -451,8 +447,9 @@ static int enable_event(const struct agent_app *app, struct agent_event *event)
 
        memcpy(bytes_to_send, &msg, sizeof(msg));
        if (filter_expression_length > 0) {
-               memcpy(bytes_to_send + sizeof(msg), event->filter_expression,
-                               filter_expression_length);
+               memcpy(bytes_to_send + sizeof(msg),
+                      event->filter_expression,
+                      filter_expression_length);
        }
 
        ret = send_payload(app->sock, bytes_to_send, data_size);
@@ -490,8 +487,7 @@ error:
 /*
  * Send Pascal-style string. Size is sent as a 32-bit big endian integer.
  */
-static
-int send_pstring(struct lttcomm_sock *sock, const char *str, uint32_t len)
+static int send_pstring(struct lttcomm_sock *sock, const char *str, uint32_t len)
 {
        int ret;
        uint32_t len_be;
@@ -517,7 +513,8 @@ end:
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
 static int app_context_op(const struct agent_app *app,
-               const struct agent_app_ctx *ctx, enum lttcomm_agent_command cmd)
+                         const struct agent_app_ctx *ctx,
+                         enum lttcomm_agent_command cmd)
 {
        int ret;
        uint32_t reply_ret_code;
@@ -527,13 +524,14 @@ static int app_context_op(const struct agent_app *app,
        LTTNG_ASSERT(app);
        LTTNG_ASSERT(app->sock);
        LTTNG_ASSERT(ctx);
-       LTTNG_ASSERT(cmd == AGENT_CMD_APP_CTX_ENABLE ||
-                       cmd == AGENT_CMD_APP_CTX_DISABLE);
+       LTTNG_ASSERT(cmd == AGENT_CMD_APP_CTX_ENABLE || cmd == AGENT_CMD_APP_CTX_DISABLE);
 
        DBG2("Agent %s application %s:%s for app pid: %d and socket %d",
-                       cmd == AGENT_CMD_APP_CTX_ENABLE ? "enabling" : "disabling",
-                       ctx->provider_name, ctx->ctx_name,
-                       app->pid, app->sock->fd);
+            cmd == AGENT_CMD_APP_CTX_ENABLE ? "enabling" : "disabling",
+            ctx->provider_name,
+            ctx->ctx_name,
+            app->pid,
+            app->sock->fd);
 
        /*
         * Calculate the payload's size, which consists of the size (u32, BE)
@@ -543,29 +541,26 @@ static int app_context_op(const struct agent_app *app,
         */
        app_ctx_provider_name_len = strlen(ctx->provider_name) + 1;
        app_ctx_name_len = strlen(ctx->ctx_name) + 1;
-       data_size = sizeof(uint32_t) + app_ctx_provider_name_len +
-                       sizeof(uint32_t) + app_ctx_name_len;
+       data_size =
+               sizeof(uint32_t) + app_ctx_provider_name_len + sizeof(uint32_t) + app_ctx_name_len;
 
        ret = send_header(app->sock, data_size, cmd, 0);
        if (ret < 0) {
                goto error_io;
        }
 
-       if (app_ctx_provider_name_len > UINT32_MAX ||
-                       app_ctx_name_len > UINT32_MAX) {
+       if (app_ctx_provider_name_len > UINT32_MAX || app_ctx_name_len > UINT32_MAX) {
                ERR("Application context name > MAX_UINT32");
                ret = LTTNG_ERR_INVALID;
                goto error;
        }
 
-       ret = send_pstring(app->sock, ctx->provider_name,
-                       (uint32_t) app_ctx_provider_name_len);
+       ret = send_pstring(app->sock, ctx->provider_name, (uint32_t) app_ctx_provider_name_len);
        if (ret < 0) {
                goto error_io;
        }
 
-       ret = send_pstring(app->sock, ctx->ctx_name,
-                       (uint32_t) app_ctx_name_len);
+       ret = send_pstring(app->sock, ctx->ctx_name, (uint32_t) app_ctx_name_len);
        if (ret < 0) {
                goto error_io;
        }
@@ -611,8 +606,10 @@ static int disable_event(struct agent_app *app, struct agent_event *event)
        LTTNG_ASSERT(app->sock);
        LTTNG_ASSERT(event);
 
-       DBG2("Agent disabling event %s for app pid: %d and socket %d", event->name,
-                       app->pid, app->sock->fd);
+       DBG2("Agent disabling event %s for app pid: %d and socket %d",
+            event->name,
+            app->pid,
+            app->sock->fd);
 
        data_size = sizeof(msg);
        memset(&msg, 0, sizeof(msg));
@@ -678,8 +675,7 @@ int agent_send_registration_done(struct agent_app *app)
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int agent_enable_event(struct agent_event *event,
-               enum lttng_domain_type domain)
+int agent_enable_event(struct agent_event *event, enum lttng_domain_type domain)
 {
        int ret;
        struct agent_app *app;
@@ -687,18 +683,20 @@ int agent_enable_event(struct agent_event *event,
 
        LTTNG_ASSERT(event);
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(the_agent_apps_ht_by_sock->ht, &iter.iter, app,
-                       node.node) {
-               if (app->domain != domain) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (
+                       the_agent_apps_ht_by_sock->ht, &iter.iter, app, node.node) {
+                       if (app->domain != domain) {
+                               continue;
+                       }
 
-               /* Enable event on agent application through TCP socket. */
-               ret = enable_event(app, event);
-               if (ret != LTTNG_OK) {
-                       goto error;
+                       /* Enable event on agent application through TCP socket. */
+                       ret = enable_event(app, event);
+                       if (ret != LTTNG_OK) {
+                               goto error;
+                       }
                }
        }
 
@@ -706,22 +704,19 @@ int agent_enable_event(struct agent_event *event,
        ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
-static
-void destroy_app_ctx(struct agent_app_ctx *ctx)
+static void destroy_app_ctx(struct agent_app_ctx *ctx)
 {
        free(ctx->provider_name);
        free(ctx->ctx_name);
        free(ctx);
 }
 
-static
-struct agent_app_ctx *create_app_ctx(const struct lttng_event_context *ctx)
+static struct agent_app_ctx *create_app_ctx(const struct lttng_event_context *ctx)
 {
-       struct agent_app_ctx *agent_ctx = NULL;
+       struct agent_app_ctx *agent_ctx = nullptr;
 
        if (!ctx) {
                goto end;
@@ -737,7 +732,7 @@ struct agent_app_ctx *create_app_ctx(const struct lttng_event_context *ctx)
        agent_ctx->ctx_name = strdup(ctx->u.app_ctx.ctx_name);
        if (!agent_ctx->provider_name || !agent_ctx->ctx_name) {
                destroy_app_ctx(agent_ctx);
-               agent_ctx = NULL;
+               agent_ctx = nullptr;
        }
 end:
        return agent_ctx;
@@ -749,8 +744,7 @@ end:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int agent_enable_context(const struct lttng_event_context *ctx,
-               enum lttng_domain_type domain)
+int agent_enable_context(const struct lttng_event_context *ctx, enum lttng_domain_type domain)
 {
        int ret;
        struct agent_app *app;
@@ -762,34 +756,35 @@ int agent_enable_context(const struct lttng_event_context *ctx,
                goto error;
        }
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(the_agent_apps_ht_by_sock->ht, &iter.iter, app,
-                       node.node) {
-               struct agent_app_ctx *agent_ctx;
+               cds_lfht_for_each_entry (
+                       the_agent_apps_ht_by_sock->ht, &iter.iter, app, node.node) {
+                       struct agent_app_ctx *agent_ctx;
 
-               if (app->domain != domain) {
-                       continue;
-               }
+                       if (app->domain != domain) {
+                               continue;
+                       }
 
-               agent_ctx = create_app_ctx(ctx);
-               if (!agent_ctx) {
-                       ret = LTTNG_ERR_NOMEM;
-                       goto error_unlock;
-               }
+                       agent_ctx = create_app_ctx(ctx);
+                       if (!agent_ctx) {
+                               ret = LTTNG_ERR_NOMEM;
+                               goto error_unlock;
+                       }
 
-               /* Enable event on agent application through TCP socket. */
-               ret = app_context_op(app, agent_ctx, AGENT_CMD_APP_CTX_ENABLE);
-               destroy_app_ctx(agent_ctx);
-               if (ret != LTTNG_OK) {
-                       goto error_unlock;
+                       /* Enable event on agent application through TCP socket. */
+                       ret = app_context_op(app, agent_ctx, AGENT_CMD_APP_CTX_ENABLE);
+                       destroy_app_ctx(agent_ctx);
+                       if (ret != LTTNG_OK) {
+                               goto error_unlock;
+                       }
                }
        }
 
        ret = LTTNG_OK;
 
 error_unlock:
-       rcu_read_unlock();
 error:
        return ret;
 }
@@ -800,8 +795,7 @@ error:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int agent_disable_event(struct agent_event *event,
-               enum lttng_domain_type domain)
+int agent_disable_event(struct agent_event *event, enum lttng_domain_type domain)
 {
        int ret = LTTNG_OK;
        struct agent_app *app;
@@ -822,18 +816,20 @@ int agent_disable_event(struct agent_event *event,
                goto end;
        }
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(the_agent_apps_ht_by_sock->ht, &iter.iter, app,
-                       node.node) {
-               if (app->domain != domain) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (
+                       the_agent_apps_ht_by_sock->ht, &iter.iter, app, node.node) {
+                       if (app->domain != domain) {
+                               continue;
+                       }
 
-               /* Enable event on agent application through TCP socket. */
-               ret = disable_event(app, event);
-               if (ret != LTTNG_OK) {
-                       goto error;
+                       /* Enable event on agent application through TCP socket. */
+                       ret = disable_event(app, event);
+                       if (ret != LTTNG_OK) {
+                               goto error;
+                       }
                }
        }
 
@@ -841,7 +837,6 @@ int agent_disable_event(struct agent_event *event,
        LTTNG_ASSERT(!AGENT_EVENT_IS_ENABLED(event));
 
 error:
-       rcu_read_unlock();
 end:
        return ret;
 }
@@ -852,31 +847,31 @@ end:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-static int disable_context(struct agent_app_ctx *ctx,
-               enum lttng_domain_type domain)
+static int disable_context(struct agent_app_ctx *ctx, enum lttng_domain_type domain)
 {
        int ret = LTTNG_OK;
        struct agent_app *app;
        struct lttng_ht_iter iter;
 
        LTTNG_ASSERT(ctx);
+       DBG2("Disabling agent application context %s:%s", ctx->provider_name, ctx->ctx_name);
 
-       rcu_read_lock();
-       DBG2("Disabling agent application context %s:%s",
-                       ctx->provider_name, ctx->ctx_name);
-       cds_lfht_for_each_entry(the_agent_apps_ht_by_sock->ht, &iter.iter, app,
-                       node.node) {
-               if (app->domain != domain) {
-                       continue;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               ret = app_context_op(app, ctx, AGENT_CMD_APP_CTX_DISABLE);
-               if (ret != LTTNG_OK) {
-                       goto end;
+               cds_lfht_for_each_entry (
+                       the_agent_apps_ht_by_sock->ht, &iter.iter, app, node.node) {
+                       if (app->domain != domain) {
+                               continue;
+                       }
+
+                       ret = app_context_op(app, ctx, AGENT_CMD_APP_CTX_DISABLE);
+                       if (ret != LTTNG_OK) {
+                               goto end;
+                       }
                }
        }
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -886,13 +881,12 @@ end:
  *
  * Return the number of events or else a negative value.
  */
-int agent_list_events(struct lttng_event **events,
-               enum lttng_domain_type domain)
+int agent_list_events(struct lttng_event **events, enum lttng_domain_type domain)
 {
        int ret;
        size_t nbmem, count = 0;
        struct agent_app *app;
-       struct lttng_event *tmp_events = NULL;
+       struct lttng_event *tmp_events = nullptr;
        struct lttng_ht_iter iter;
 
        LTTNG_ASSERT(events);
@@ -907,58 +901,60 @@ int agent_list_events(struct lttng_event **events,
                goto error;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(the_agent_apps_ht_by_sock->ht, &iter.iter, app,
-                       node.node) {
-               ssize_t nb_ev;
-               struct lttng_event *agent_events;
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               /* Skip domain not asked by the list. */
-               if (app->domain != domain) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (
+                       the_agent_apps_ht_by_sock->ht, &iter.iter, app, node.node) {
+                       ssize_t nb_ev;
+                       struct lttng_event *agent_events;
 
-               nb_ev = list_events(app, &agent_events);
-               if (nb_ev < 0) {
-                       ret = nb_ev;
-                       goto error_unlock;
-               }
+                       /* Skip domain not asked by the list. */
+                       if (app->domain != domain) {
+                               continue;
+                       }
 
-               if (count + nb_ev > nbmem) {
-                       /* In case the realloc fails, we free the memory */
-                       struct lttng_event *new_tmp_events;
-                       size_t new_nbmem;
-
-                       new_nbmem = std::max(count + nb_ev, nbmem << 1);
-                       DBG2("Reallocating agent event list from %zu to %zu entries",
-                                       nbmem, new_nbmem);
-                       new_tmp_events = (lttng_event *) realloc(tmp_events,
-                               new_nbmem * sizeof(*new_tmp_events));
-                       if (!new_tmp_events) {
-                               PERROR("realloc agent events");
-                               ret = -ENOMEM;
-                               free(agent_events);
-                               goto error_unlock;
+                       nb_ev = list_events(app, &agent_events);
+                       if (nb_ev < 0) {
+                               ret = nb_ev;
+                               goto error;
+                       }
+
+                       if (count + nb_ev > nbmem) {
+                               /* In case the realloc fails, we free the memory */
+                               struct lttng_event *new_tmp_events;
+                               size_t new_nbmem;
+
+                               new_nbmem = std::max(count + nb_ev, nbmem << 1);
+                               DBG2("Reallocating agent event list from %zu to %zu entries",
+                                    nbmem,
+                                    new_nbmem);
+                               new_tmp_events = (lttng_event *) realloc(
+                                       tmp_events, new_nbmem * sizeof(*new_tmp_events));
+                               if (!new_tmp_events) {
+                                       PERROR("realloc agent events");
+                                       ret = -ENOMEM;
+                                       free(agent_events);
+                                       goto error;
+                               }
+
+                               /* Zero the new memory */
+                               memset(new_tmp_events + nbmem,
+                                      0,
+                                      (new_nbmem - nbmem) * sizeof(*new_tmp_events));
+                               nbmem = new_nbmem;
+                               tmp_events = new_tmp_events;
                        }
-                       /* Zero the new memory */
-                       memset(new_tmp_events + nbmem, 0,
-                               (new_nbmem - nbmem) * sizeof(*new_tmp_events));
-                       nbmem = new_nbmem;
-                       tmp_events = new_tmp_events;
+                       memcpy(tmp_events + count, agent_events, nb_ev * sizeof(*tmp_events));
+                       free(agent_events);
+                       count += nb_ev;
                }
-               memcpy(tmp_events + count, agent_events,
-                       nb_ev * sizeof(*tmp_events));
-               free(agent_events);
-               count += nb_ev;
        }
-       rcu_read_unlock();
 
        ret = count;
        *events = tmp_events;
        return ret;
 
-error_unlock:
-       rcu_read_unlock();
 error:
        free(tmp_events);
        return ret;
@@ -969,8 +965,8 @@ error:
  *
  * Return newly allocated object or else NULL on error.
  */
-struct agent_app *agent_create_app(pid_t pid, enum lttng_domain_type domain,
-               struct lttcomm_sock *sock)
+struct agent_app *
+agent_create_app(pid_t pid, enum lttng_domain_type domain, struct lttcomm_sock *sock)
 {
        struct agent_app *app;
 
@@ -1007,10 +1003,9 @@ struct agent_app *agent_find_app_by_sock(int sock)
        LTTNG_ASSERT(sock >= 0);
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(the_agent_apps_ht_by_sock,
-                       (void *) ((unsigned long) sock), &iter);
+       lttng_ht_lookup(the_agent_apps_ht_by_sock, (void *) ((unsigned long) sock), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto error;
        }
        app = lttng::utils::container_of(node, &agent_app::node);
@@ -1020,7 +1015,7 @@ struct agent_app *agent_find_app_by_sock(int sock)
 
 error:
        DBG3("Agent app NOT found by sock %d.", sock);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1128,7 +1123,7 @@ struct agent *agent_create(enum lttng_domain_type domain)
        ret = agent_init(agt);
        if (ret < 0) {
                free(agt);
-               agt = NULL;
+               agt = nullptr;
                goto error;
        }
 
@@ -1143,15 +1138,19 @@ error:
  * Return a new object else NULL on error.
  */
 struct agent_event *agent_create_event(const char *name,
-               enum lttng_loglevel_type loglevel_type, int loglevel_value,
-               struct lttng_bytecode *filter, char *filter_expression)
+                                      enum lttng_loglevel_type loglevel_type,
+                                      int loglevel_value,
+                                      struct lttng_bytecode *filter,
+                                      char *filter_expression)
 {
-       struct agent_event *event = NULL;
+       struct agent_event *event = nullptr;
 
        DBG3("Agent create new event with name %s, loglevel type %d, \
                        loglevel value %d and filter %s",
-                       name, loglevel_type, loglevel_value,
-                       filter_expression ? filter_expression : "NULL");
+            name,
+            loglevel_type,
+            loglevel_value,
+            filter_expression ? filter_expression : "NULL");
 
        if (!name) {
                ERR("Failed to create agent event; no name provided.");
@@ -1195,7 +1194,7 @@ void agent_add_event(struct agent_event *event, struct agent *agt)
 int agent_add_context(const struct lttng_event_context *ctx, struct agent *agt)
 {
        int ret = LTTNG_OK;
-       struct agent_app_ctx *agent_ctx = NULL;
+       struct agent_app_ctx *agent_ctx = nullptr;
 
        LTTNG_ASSERT(ctx);
        LTTNG_ASSERT(agt);
@@ -1208,8 +1207,7 @@ int agent_add_context(const struct lttng_event_context *ctx, struct agent *agt)
                goto end;
        }
 
-       DBG3("Agent adding context %s:%s", ctx->u.app_ctx.provider_name,
-                       ctx->u.app_ctx.ctx_name);
+       DBG3("Agent adding context %s:%s", ctx->u.app_ctx.provider_name, ctx->u.app_ctx.ctx_name);
        cds_list_add_tail_rcu(&agent_ctx->list_node, &agt->app_ctx_list);
 end:
        return ret;
@@ -1223,8 +1221,7 @@ end:
  *
  * Sets the given iterator.
  */
-void agent_find_events_by_name(const char *name, struct agent *agt,
-               struct lttng_ht_iter* iter)
+void agent_find_events_by_name(const char *name, struct agent *agt, struct lttng_ht_iter *iter)
 {
        struct lttng_ht *ht;
        struct agent_ht_key key;
@@ -1238,8 +1235,11 @@ void agent_find_events_by_name(const char *name, struct agent *agt,
        ht = agt->events;
        key.name = name;
 
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) name, lttng_ht_seed),
-                       ht_match_event_by_name, &key, &iter->iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) name, lttng_ht_seed),
+                       ht_match_event_by_name,
+                       &key,
+                       &iter->iter);
 }
 
 /*
@@ -1250,8 +1250,8 @@ void agent_find_events_by_name(const char *name, struct agent *agt,
  *
  * Return object if found else NULL.
  */
-struct agent_event *agent_find_event_by_trigger(
-               const struct lttng_trigger *trigger, struct agent *agt)
+struct agent_event *agent_find_event_by_trigger(const struct lttng_trigger *trigger,
+                                               struct agent *agt)
 {
        enum lttng_condition_status c_status;
        enum lttng_event_rule_status er_status;
@@ -1274,30 +1274,23 @@ struct agent_event *agent_find_event_by_trigger(
        condition = lttng_trigger_get_const_condition(trigger);
 
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       c_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &rule);
+       c_status = lttng_condition_event_rule_matches_get_rule(condition, &rule);
        LTTNG_ASSERT(c_status == LTTNG_CONDITION_STATUS_OK);
 
        switch (lttng_event_rule_get_type(rule)) {
        case LTTNG_EVENT_RULE_TYPE_JUL_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_jul_logging_get_name_pattern;
-               logging_get_log_level_rule =
-                               lttng_event_rule_jul_logging_get_log_level_rule;
+               logging_get_name_pattern = lttng_event_rule_jul_logging_get_name_pattern;
+               logging_get_log_level_rule = lttng_event_rule_jul_logging_get_log_level_rule;
                break;
        case LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_log4j_logging_get_name_pattern;
-               logging_get_log_level_rule =
-                               lttng_event_rule_log4j_logging_get_log_level_rule;
+               logging_get_name_pattern = lttng_event_rule_log4j_logging_get_name_pattern;
+               logging_get_log_level_rule = lttng_event_rule_log4j_logging_get_log_level_rule;
                break;
        case LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_python_logging_get_name_pattern;
-               logging_get_log_level_rule =
-                               lttng_event_rule_python_logging_get_log_level_rule;
+               logging_get_name_pattern = lttng_event_rule_python_logging_get_name_pattern;
+               logging_get_log_level_rule = lttng_event_rule_python_logging_get_log_level_rule;
                break;
        default:
                abort();
@@ -1306,7 +1299,7 @@ struct agent_event *agent_find_event_by_trigger(
 
        domain = lttng_event_rule_get_domain_type(rule);
        LTTNG_ASSERT(domain == LTTNG_DOMAIN_JUL || domain == LTTNG_DOMAIN_LOG4J ||
-                       domain == LTTNG_DOMAIN_PYTHON);
+                    domain == LTTNG_DOMAIN_PYTHON);
 
        /* Get the event's pattern name ('name' in the legacy terminology). */
        er_status = logging_get_name_pattern(rule, &name);
@@ -1326,8 +1319,7 @@ struct agent_event *agent_find_event_by_trigger(
                abort();
        }
 
-       return agent_find_event(name, loglevel_type, loglevel_value,
-                       filter_expression, agt);
+       return agent_find_event(name, loglevel_type, loglevel_value, filter_expression, agt);
 }
 
 /*
@@ -1337,8 +1329,7 @@ struct agent_event *agent_find_event_by_trigger(
  * The RCU read lock must be held during the iteration and for as long
  * as the object the iterator points to remains in use.
  */
-void agent_event_next_duplicate(const char *name,
-               struct agent *agt, struct lttng_ht_iter* iter)
+void agent_event_next_duplicate(const char *name, struct agent *agt, struct lttng_ht_iter *iter)
 {
        struct agent_ht_key key;
 
@@ -1346,8 +1337,7 @@ void agent_event_next_duplicate(const char *name,
 
        key.name = name;
 
-       cds_lfht_next_duplicate(agt->events->ht, ht_match_event_by_name,
-               &key, &iter->iter);
+       cds_lfht_next_duplicate(agt->events->ht, ht_match_event_by_name, &key, &iter->iter);
 }
 
 /*
@@ -1359,10 +1349,10 @@ void agent_event_next_duplicate(const char *name,
  * Return object if found else NULL.
  */
 struct agent_event *agent_find_event(const char *name,
-               enum lttng_loglevel_type loglevel_type,
-               int loglevel_value,
-               const char *filter_expression,
-               struct agent *agt)
+                                    enum lttng_loglevel_type loglevel_type,
+                                    int loglevel_value,
+                                    const char *filter_expression,
+                                    struct agent *agt)
 {
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
@@ -1380,10 +1370,13 @@ struct agent_event *agent_find_event(const char *name,
        key.loglevel_type = loglevel_type;
        key.filter_expression = filter_expression;
 
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) name, lttng_ht_seed),
-                       ht_match_event, &key, &iter.iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) name, lttng_ht_seed),
+                       ht_match_event,
+                       &key,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto error;
        }
 
@@ -1392,7 +1385,7 @@ struct agent_event *agent_find_event(const char *name,
 
 error:
        DBG3("Agent event NOT found %s.", name);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1410,11 +1403,9 @@ void agent_destroy_event(struct agent_event *event)
        free(event);
 }
 
-static
-void destroy_app_ctx_rcu(struct rcu_head *head)
+static void destroy_app_ctx_rcu(struct rcu_head *head)
 {
-       struct agent_app_ctx *ctx =
-                       lttng::utils::container_of(head, &agent_app_ctx::rcu_node);
+       struct agent_app_ctx *ctx = lttng::utils::container_of(head, &agent_app_ctx::rcu_node);
 
        destroy_app_ctx(ctx);
 }
@@ -1432,31 +1423,35 @@ void agent_destroy(struct agent *agt)
 
        DBG3("Agent destroy");
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(agt->events->ht, &iter.iter, node, node) {
-               int ret;
-               struct agent_event *event;
-
-               /*
-                * When destroying an event, we have to try to disable it on the
-                * agent side so the event stops generating data. The return
-                * value is not important since we have to continue anyway
-                * destroying the object.
-                */
-               event = lttng::utils::container_of(node, &agent_event::node);
-               (void) agent_disable_event(event, agt->domain);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (agt->events->ht, &iter.iter, node, node) {
+                       int ret;
+                       struct agent_event *event;
+
+                       /*
+                        * When destroying an event, we have to try to disable it on the
+                        * agent side so the event stops generating data. The return
+                        * value is not important since we have to continue anyway
+                        * destroying the object.
+                        */
+                       event = lttng::utils::container_of(node, &agent_event::node);
+                       (void) agent_disable_event(event, agt->domain);
+
+                       ret = lttng_ht_del(agt->events, &iter);
+                       LTTNG_ASSERT(!ret);
+                       call_rcu(&node->head, destroy_event_agent_rcu);
+               }
 
-               ret = lttng_ht_del(agt->events, &iter);
-               LTTNG_ASSERT(!ret);
-               call_rcu(&node->head, destroy_event_agent_rcu);
+               cds_list_for_each_entry_rcu(ctx, &agt->app_ctx_list, list_node)
+               {
+                       (void) disable_context(ctx, agt->domain);
+                       cds_list_del(&ctx->list_node);
+                       call_rcu(&ctx->rcu_node, destroy_app_ctx_rcu);
+               }
        }
 
-       cds_list_for_each_entry_rcu(ctx, &agt->app_ctx_list, list_node) {
-               (void) disable_context(ctx, agt->domain);
-               cds_list_del(&ctx->list_node);
-               call_rcu(&ctx->rcu_node, destroy_app_ctx_rcu);
-       }
-       rcu_read_unlock();
        lttng_ht_destroy(agt->events);
        free(agt);
 }
@@ -1464,7 +1459,7 @@ void agent_destroy(struct agent *agt)
 /*
  * Allocate agent_apps_ht_by_sock.
  */
-int agent_app_ht_alloc(void)
+int agent_app_ht_alloc()
 {
        the_agent_apps_ht_by_sock = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
        return the_agent_apps_ht_by_sock ? 0 : -1;
@@ -1484,7 +1479,7 @@ void agent_destroy_app_by_sock(int sock)
         * happen. The hash table deletion is ONLY done through this call when the
         * main sessiond thread is torn down.
         */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        app = agent_find_app_by_sock(sock);
        LTTNG_ASSERT(app);
 
@@ -1493,13 +1488,12 @@ void agent_destroy_app_by_sock(int sock)
 
        /* The application is freed in a RCU call but the socket is closed here. */
        agent_destroy_app(app);
-       rcu_read_unlock();
 }
 
 /*
  * Clean-up the agent app hash table and destroy it.
  */
-void agent_app_ht_clean(void)
+void agent_app_ht_clean()
 {
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
@@ -1507,15 +1501,17 @@ void agent_app_ht_clean(void)
        if (!the_agent_apps_ht_by_sock) {
                return;
        }
-       rcu_read_lock();
-       cds_lfht_for_each_entry(
-                       the_agent_apps_ht_by_sock->ht, &iter.iter, node, node) {
-               struct agent_app *app;
 
-               app = lttng::utils::container_of(node, &agent_app::node);
-               agent_destroy_app_by_sock(app->sock->fd);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (the_agent_apps_ht_by_sock->ht, &iter.iter, node, node) {
+                       struct agent_app *app;
+
+                       app = lttng::utils::container_of(node, &agent_app::node);
+                       agent_destroy_app_by_sock(app->sock->fd);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(the_agent_apps_ht_by_sock);
 }
@@ -1538,45 +1534,50 @@ void agent_update(const struct agent *agt, const struct agent_app *app)
 
        DBG("Agent updating app: pid = %ld", (long) app->pid);
 
-       rcu_read_lock();
        /*
         * We are in the registration path thus if the application is gone,
         * there is a serious code flow error.
         */
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(agt->events->ht, &iter.iter, event, node.node) {
-               /* Skip event if disabled. */
-               if (!AGENT_EVENT_IS_ENABLED(event)) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (agt->events->ht, &iter.iter, event, node.node) {
+                       /* Skip event if disabled. */
+                       if (!AGENT_EVENT_IS_ENABLED(event)) {
+                               continue;
+                       }
 
-               ret = enable_event(app, event);
-               if (ret != LTTNG_OK) {
-                       DBG2("Agent update unable to enable event %s on app pid: %d sock %d",
-                                       event->name, app->pid, app->sock->fd);
-                       /* Let's try the others here and don't assume the app is dead. */
-                       continue;
+                       ret = enable_event(app, event);
+                       if (ret != LTTNG_OK) {
+                               DBG2("Agent update unable to enable event %s on app pid: %d sock %d",
+                                    event->name,
+                                    app->pid,
+                                    app->sock->fd);
+                               /* Let's try the others here and don't assume the app is dead. */
+                               continue;
+                       }
                }
-       }
 
-       cds_list_for_each_entry_rcu(ctx, &agt->app_ctx_list, list_node) {
-               ret = app_context_op(app, ctx, AGENT_CMD_APP_CTX_ENABLE);
-               if (ret != LTTNG_OK) {
-                       DBG2("Agent update unable to add application context %s:%s on app pid: %d sock %d",
-                                       ctx->provider_name, ctx->ctx_name,
-                                       app->pid, app->sock->fd);
-                       continue;
+               cds_list_for_each_entry_rcu(ctx, &agt->app_ctx_list, list_node)
+               {
+                       ret = app_context_op(app, ctx, AGENT_CMD_APP_CTX_ENABLE);
+                       if (ret != LTTNG_OK) {
+                               DBG2("Agent update unable to add application context %s:%s on app pid: %d sock %d",
+                                    ctx->provider_name,
+                                    ctx->ctx_name,
+                                    app->pid,
+                                    app->sock->fd);
+                               continue;
+                       }
                }
        }
-
-       rcu_read_unlock();
 }
 
 /*
  * Allocate the per-event notifier domain agent hash table. It is lazily
  * populated as domains are used.
  */
-int agent_by_event_notifier_domain_ht_create(void)
+int agent_by_event_notifier_domain_ht_create()
 {
        the_trigger_agents_ht_by_domain = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        return the_trigger_agents_ht_by_domain ? 0 : -1;
@@ -1585,7 +1586,7 @@ int agent_by_event_notifier_domain_ht_create(void)
 /*
  * Clean-up the per-event notifier domain agent hash table and destroy it.
  */
-void agent_by_event_notifier_domain_ht_destroy(void)
+void agent_by_event_notifier_domain_ht_destroy()
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
@@ -1594,26 +1595,25 @@ void agent_by_event_notifier_domain_ht_destroy(void)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(the_trigger_agents_ht_by_domain->ht,
-                       &iter.iter, node, node) {
-               struct agent *agent =
-                               lttng::utils::container_of(node, &agent::node);
-               const int ret = lttng_ht_del(
-                               the_trigger_agents_ht_by_domain, &iter);
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               LTTNG_ASSERT(ret == 0);
-               agent_destroy(agent);
+               cds_lfht_for_each_entry (
+                       the_trigger_agents_ht_by_domain->ht, &iter.iter, node, node) {
+                       struct agent *agent = lttng::utils::container_of(node, &agent::node);
+                       const int ret = lttng_ht_del(the_trigger_agents_ht_by_domain, &iter);
+
+                       LTTNG_ASSERT(ret == 0);
+                       agent_destroy(agent);
+               }
        }
 
-       rcu_read_unlock();
        lttng_ht_destroy(the_trigger_agents_ht_by_domain);
 }
 
-struct agent *agent_find_by_event_notifier_domain(
-               enum lttng_domain_type domain_type)
+struct agent *agent_find_by_event_notifier_domain(enum lttng_domain_type domain_type)
 {
-       struct agent *agt = NULL;
+       struct agent *agt = nullptr;
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
        const uint64_t key = (uint64_t) domain_type;
@@ -1621,7 +1621,7 @@ struct agent *agent_find_by_event_notifier_domain(
        LTTNG_ASSERT(the_trigger_agents_ht_by_domain);
 
        DBG3("Per-event notifier domain agent lookup for domain '%s'",
-                       lttng_domain_type_str(domain_type));
+            lttng_domain_type_str(domain_type));
 
        lttng_ht_lookup(the_trigger_agents_ht_by_domain, &key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
index 2ad42c3f4a6a639e5b8824b414944414c16e0b49..f9d3cb656140c233f7c401de93368091857150d0 100644 (file)
@@ -9,14 +9,16 @@
 #ifndef LTTNG_SESSIOND_AGENT_H
 #define LTTNG_SESSIOND_AGENT_H
 
-#include <inttypes.h>
-
 #include <common/hashtable/hashtable.hpp>
+
 #include <lttng/lttng.h>
 
+#include <inttypes.h>
+#include <urcu/urcu.h>
+
 /* Agent protocol version that is verified during the agent registration. */
-#define AGENT_MAJOR_VERSION            2
-#define AGENT_MINOR_VERSION            0
+#define AGENT_MAJOR_VERSION 2
+#define AGENT_MINOR_VERSION 0
 
 /*
  * Hash table that contains the agent app created upon registration indexed by
@@ -103,7 +105,7 @@ struct agent_event {
        struct lttng_event_exclusion *exclusion;
 };
 
-#define AGENT_EVENT_IS_ENABLED(agent_event) (!!agent_event->enabled_count)
+#define AGENT_EVENT_IS_ENABLED(agent_event) (!!(agent_event)->enabled_count)
 
 /*
  * Agent object containing events enabled/disabled for a given domain in a
@@ -133,9 +135,9 @@ struct agent {
 };
 
 /* Allocate agent apps hash table */
-int agent_app_ht_alloc(void);
+int agent_app_ht_alloc();
 /* Clean-up agent apps hash table */
-void agent_app_ht_clean(void);
+void agent_app_ht_clean();
 
 /* Initialize an already allocated agent domain. */
 int agent_init(struct agent *agt);
@@ -145,32 +147,29 @@ void agent_add(struct agent *agt, struct lttng_ht *ht);
 
 /* Agent event API. */
 struct agent_event *agent_create_event(const char *name,
-               enum lttng_loglevel_type loglevel_type, int loglevel_value,
-               struct lttng_bytecode *filter,
-               char *filter_expression);
+                                      enum lttng_loglevel_type loglevel_type,
+                                      int loglevel_value,
+                                      struct lttng_bytecode *filter,
+                                      char *filter_expression);
 void agent_add_event(struct agent_event *event, struct agent *agt);
 
 struct agent_event *agent_find_event(const char *name,
-               enum lttng_loglevel_type loglevel_type,
-               int loglevel_value,
-               const char *filter_expression,
-               struct agent *agt);
-void agent_find_events_by_name(const char *name, struct agent *agt,
-               struct lttng_ht_iter* iter);
-void agent_event_next_duplicate(const char *name,
-               struct agent *agt, struct lttng_ht_iter* iter);
+                                    enum lttng_loglevel_type loglevel_type,
+                                    int loglevel_value,
+                                    const char *filter_expression,
+                                    struct agent *agt);
+void agent_find_events_by_name(const char *name, struct agent *agt, struct lttng_ht_iter *iter);
+void agent_event_next_duplicate(const char *name, struct agent *agt, struct lttng_ht_iter *iter);
 void agent_delete_event(struct agent_event *event, struct agent *agt);
 void agent_destroy_event(struct agent_event *event);
 
 /* Agent context API.*/
-int agent_enable_context(const struct lttng_event_context *ctx,
-               enum lttng_domain_type domain);
-int agent_add_context(const struct lttng_event_context *ctx,
-               struct agent *agt);
+int agent_enable_context(const struct lttng_event_context *ctx, enum lttng_domain_type domain);
+int agent_add_context(const struct lttng_event_context *ctx, struct agent *agt);
 
 /* Agent app API. */
-struct agent_app *agent_create_app(pid_t pid, enum lttng_domain_type domain,
-               struct lttcomm_sock *sock);
+struct agent_app *
+agent_create_app(pid_t pid, enum lttng_domain_type domain, struct lttcomm_sock *sock);
 void agent_add_app(struct agent_app *app);
 void agent_delete_app(struct agent_app *app);
 struct agent_app *agent_find_app_by_sock(int sock);
@@ -179,21 +178,17 @@ void agent_destroy_app_by_sock(int sock);
 int agent_send_registration_done(struct agent_app *app);
 
 /* Agent action API */
-int agent_enable_event(struct agent_event *event,
-               enum lttng_domain_type domain);
-int agent_disable_event(struct agent_event *event,
-               enum lttng_domain_type domain);
+int agent_enable_event(struct agent_event *event, enum lttng_domain_type domain);
+int agent_disable_event(struct agent_event *event, enum lttng_domain_type domain);
 void agent_update(const struct agent *agt, const struct agent_app *app);
-int agent_list_events(struct lttng_event **events,
-               enum lttng_domain_type domain);
+int agent_list_events(struct lttng_event **events, enum lttng_domain_type domain);
 
-struct agent_event *agent_find_event_by_trigger(
-               const struct lttng_trigger *trigger, struct agent *agt);
+struct agent_event *agent_find_event_by_trigger(const struct lttng_trigger *trigger,
+                                               struct agent *agt);
 
 /* Global event notifier per-domain agents. */
-struct agent *agent_find_by_event_notifier_domain(
-               enum lttng_domain_type domain_type);
-void agent_by_event_notifier_domain_ht_destroy(void);
-int agent_by_event_notifier_domain_ht_create(void);
+struct agent *agent_find_by_event_notifier_domain(enum lttng_domain_type domain_type);
+void agent_by_event_notifier_domain_ht_destroy();
+int agent_by_event_notifier_domain_ht_create();
 
 #endif /* LTTNG_SESSIOND_AGENT_H */
index ab7d11ae4f51f093c4907f74a23377034cff3cf5..b840a7fa91ef0b69931a0f8c2f59c97389d31073 100644 (file)
@@ -6,18 +6,19 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-
-#include <common/common.hpp>
-#include <common/hashtable/utils.hpp>
-
 #include "buffer-registry.hpp"
 #include "fd-limit.hpp"
-#include "ust-consumer.hpp"
 #include "lttng-ust-ctl.hpp"
 #include "lttng-ust-error.hpp"
+#include "ust-consumer.hpp"
 #include "utils.hpp"
 
+#include <common/common.hpp>
+#include <common/hashtable/utils.hpp>
+#include <common/urcu.hpp>
+
+#include <inttypes.h>
+
 /*
  * Set in main.c during initialization process of the daemon. This contains
  * buffer_reg_uid object which are global registry for per UID buffer. Object
@@ -48,9 +49,8 @@ static int ht_match_reg_uid(struct cds_lfht_node *node, const void *_key)
        LTTNG_ASSERT(reg);
        key = (buffer_reg_uid *) _key;
 
-       if (key->session_id != reg->session_id ||
-                       key->bits_per_long != reg->bits_per_long ||
-                       key->uid != reg->uid) {
+       if (key->session_id != reg->session_id || key->bits_per_long != reg->bits_per_long ||
+           key->uid != reg->uid) {
                goto no_match;
        }
 
@@ -71,14 +71,14 @@ static unsigned long ht_hash_reg_uid(const void *_key, unsigned long seed)
 
        LTTNG_ASSERT(key);
 
-       xored_key = (uint64_t)(key->session_id ^ key->bits_per_long ^ key->uid);
+       xored_key = (uint64_t) (key->session_id ^ key->bits_per_long ^ key->uid);
        return hash_key_u64(&xored_key, seed);
 }
 
 /*
  * Initialize global buffer per UID registry. Should only be called ONCE!.
  */
-void buffer_reg_init_uid_registry(void)
+void buffer_reg_init_uid_registry()
 {
        /* Should be called once. */
        LTTNG_ASSERT(!buffer_registry_uid);
@@ -95,12 +95,16 @@ void buffer_reg_init_uid_registry(void)
  *
  * Return 0 on success else a negative value and regp is untouched.
  */
-int buffer_reg_uid_create(uint64_t session_id, uint32_t bits_per_long, uid_t uid,
-               enum lttng_domain_type domain, struct buffer_reg_uid **regp,
-               const char *root_shm_path, const char *shm_path)
+int buffer_reg_uid_create(uint64_t session_id,
+                         uint32_t bits_per_long,
+                         uid_t uid,
+                         enum lttng_domain_type domain,
+                         struct buffer_reg_uid **regp,
+                         const char *root_shm_path,
+                         const char *shm_path)
 {
        int ret = 0;
-       struct buffer_reg_uid *reg = NULL;
+       struct buffer_reg_uid *reg = nullptr;
 
        LTTNG_ASSERT(regp);
 
@@ -128,7 +132,8 @@ int buffer_reg_uid_create(uint64_t session_id, uint32_t bits_per_long, uid_t uid
                strncpy(reg->shm_path, shm_path, sizeof(reg->shm_path));
                reg->shm_path[sizeof(reg->shm_path) - 1] = '\0';
                DBG3("shm path '%s' is assigned to uid buffer registry for session id %" PRIu64,
-                       reg->shm_path, session_id);
+                    reg->shm_path,
+                    session_id);
        }
        reg->registry->channels = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        if (!reg->registry->channels) {
@@ -140,7 +145,10 @@ int buffer_reg_uid_create(uint64_t session_id, uint32_t bits_per_long, uid_t uid
        *regp = reg;
 
        DBG3("Buffer registry per UID created id: %" PRIu64 ", ABI: %u, uid: %d, domain: %d",
-                       session_id, bits_per_long, uid, domain);
+            session_id,
+            bits_per_long,
+            uid,
+            domain);
 
        return 0;
 
@@ -161,14 +169,13 @@ void buffer_reg_uid_add(struct buffer_reg_uid *reg)
 
        LTTNG_ASSERT(reg);
 
-       DBG3("Buffer registry per UID adding to global registry with id: %" PRIu64 ,
-                       reg->session_id);
+       DBG3("Buffer registry per UID adding to global registry with id: %" PRIu64,
+            reg->session_id);
 
-       rcu_read_lock();
-       nodep = cds_lfht_add_unique(ht->ht, ht->hash_fct(reg, lttng_ht_seed),
-                       ht->match_fct, reg, &reg->node.node);
+       lttng::urcu::read_lock_guard read_lock;
+       nodep = cds_lfht_add_unique(
+               ht->ht, ht->hash_fct(reg, lttng_ht_seed), ht->match_fct, reg, &reg->node.node);
        LTTNG_ASSERT(nodep == &reg->node.node);
-       rcu_read_unlock();
 }
 
 /*
@@ -177,12 +184,11 @@ void buffer_reg_uid_add(struct buffer_reg_uid *reg)
  *
  * Return the object pointer or NULL on error.
  */
-struct buffer_reg_uid *buffer_reg_uid_find(uint64_t session_id,
-               uint32_t bits_per_long, uid_t uid)
+struct buffer_reg_uid *buffer_reg_uid_find(uint64_t session_id, uint32_t bits_per_long, uid_t uid)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct buffer_reg_uid *reg = NULL, key;
+       struct buffer_reg_uid *reg = nullptr, key;
        struct lttng_ht *ht = buffer_registry_uid;
 
        ASSERT_RCU_READ_LOCKED();
@@ -193,11 +199,12 @@ struct buffer_reg_uid *buffer_reg_uid_find(uint64_t session_id,
        key.uid = uid;
 
        DBG3("Buffer registry per UID find id: %" PRIu64 ", ABI: %u, uid: %d",
-                       session_id, bits_per_long, uid);
+            session_id,
+            bits_per_long,
+            uid);
 
        /* Custom lookup function since it's a different key. */
-       cds_lfht_lookup(ht->ht, ht->hash_fct(&key, lttng_ht_seed), ht->match_fct,
-                       &key, &iter.iter);
+       cds_lfht_lookup(ht->ht, ht->hash_fct(&key, lttng_ht_seed), ht->match_fct, &key, &iter.iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (!node) {
                goto end;
@@ -211,7 +218,7 @@ end:
 /*
  * Initialize global buffer per PID registry. Should only be called ONCE!.
  */
-void buffer_reg_init_pid_registry(void)
+void buffer_reg_init_pid_registry()
 {
        /* Should be called once. */
        LTTNG_ASSERT(!buffer_registry_pid);
@@ -226,11 +233,13 @@ void buffer_reg_init_pid_registry(void)
  *
  * Return 0 on success else a negative value and regp is untouched.
  */
-int buffer_reg_pid_create(uint64_t session_id, struct buffer_reg_pid **regp,
-               const char *root_shm_path, const char *shm_path)
+int buffer_reg_pid_create(uint64_t session_id,
+                         struct buffer_reg_pid **regp,
+                         const char *root_shm_path,
+                         const char *shm_path)
 {
        int ret = 0;
-       struct buffer_reg_pid *reg = NULL;
+       struct buffer_reg_pid *reg = nullptr;
 
        LTTNG_ASSERT(regp);
 
@@ -256,7 +265,8 @@ int buffer_reg_pid_create(uint64_t session_id, struct buffer_reg_pid **regp,
                strncpy(reg->shm_path, shm_path, sizeof(reg->shm_path));
                reg->shm_path[sizeof(reg->shm_path) - 1] = '\0';
                DBG3("shm path '%s' is assigned to pid buffer registry for session id %" PRIu64,
-                               reg->shm_path, session_id);
+                    reg->shm_path,
+                    session_id);
        }
        reg->registry->channels = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        if (!reg->registry->channels) {
@@ -267,8 +277,7 @@ int buffer_reg_pid_create(uint64_t session_id, struct buffer_reg_pid **regp,
        lttng_ht_node_init_u64(&reg->node, reg->session_id);
        *regp = reg;
 
-       DBG3("Buffer registry per PID created with session id: %" PRIu64,
-                       session_id);
+       DBG3("Buffer registry per PID created with session id: %" PRIu64, session_id);
 
        return 0;
 
@@ -287,11 +296,10 @@ void buffer_reg_pid_add(struct buffer_reg_pid *reg)
        LTTNG_ASSERT(reg);
 
        DBG3("Buffer registry per PID adding to global registry with id: %" PRIu64,
-                       reg->session_id);
+            reg->session_id);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_add_unique_u64(buffer_registry_pid, &reg->node);
-       rcu_read_unlock();
 }
 
 /*
@@ -304,7 +312,7 @@ struct buffer_reg_pid *buffer_reg_pid_find(uint64_t session_id)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct buffer_reg_pid *reg = NULL;
+       struct buffer_reg_pid *reg = nullptr;
        struct lttng_ht *ht = buffer_registry_pid;
 
        DBG3("Buffer registry per PID find id: %" PRIu64, session_id);
@@ -325,35 +333,36 @@ end:
  *
  * Return the matching key or -1 if not found.
  */
-int buffer_reg_uid_consumer_channel_key(
-               struct cds_list_head *buffer_reg_uid_list,
-               uint64_t chan_key, uint64_t *consumer_chan_key)
+int buffer_reg_uid_consumer_channel_key(struct cds_list_head *buffer_reg_uid_list,
+                                       uint64_t chan_key,
+                                       uint64_t *consumer_chan_key)
 {
        struct lttng_ht_iter iter;
-       struct buffer_reg_uid *uid_reg = NULL;
-       struct buffer_reg_session *session_reg = NULL;
+       struct buffer_reg_uid *uid_reg = nullptr;
+       struct buffer_reg_session *session_reg = nullptr;
        struct buffer_reg_channel *reg_chan;
        int ret = -1;
 
-       rcu_read_lock();
-       /*
-        * For the per-uid registry, we have to iterate since we don't have the
-        * uid and bitness key.
-        */
-       cds_list_for_each_entry(uid_reg, buffer_reg_uid_list, lnode) {
-               session_reg = uid_reg->registry;
-               cds_lfht_for_each_entry(session_reg->channels->ht,
-                               &iter.iter, reg_chan, node.node) {
-                       if (reg_chan->key == chan_key) {
-                               *consumer_chan_key = reg_chan->consumer_key;
-                               ret = 0;
-                               goto end;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               /*
+                * For the per-uid registry, we have to iterate since we don't have the
+                * uid and bitness key.
+                */
+               cds_list_for_each_entry (uid_reg, buffer_reg_uid_list, lnode) {
+                       session_reg = uid_reg->registry;
+                       cds_lfht_for_each_entry (
+                               session_reg->channels->ht, &iter.iter, reg_chan, node.node) {
+                               if (reg_chan->key == chan_key) {
+                                       *consumer_chan_key = reg_chan->consumer_key;
+                                       ret = 0;
+                                       goto end;
+                               }
                        }
                }
        }
-
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -379,7 +388,7 @@ int buffer_reg_channel_create(uint64_t key, struct buffer_reg_channel **regp)
 
        reg->key = key;
        CDS_INIT_LIST_HEAD(&reg->streams);
-       pthread_mutex_init(&reg->stream_list_lock, NULL);
+       pthread_mutex_init(&reg->stream_list_lock, nullptr);
 
        lttng_ht_node_init_u64(&reg->node, key);
        *regp = reg;
@@ -415,8 +424,7 @@ int buffer_reg_stream_create(struct buffer_reg_stream **regp)
 /*
  * Add stream to the list in the channel.
  */
-void buffer_reg_stream_add(struct buffer_reg_stream *stream,
-               struct buffer_reg_channel *channel)
+void buffer_reg_stream_add(struct buffer_reg_stream *stream, struct buffer_reg_channel *channel)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(channel);
@@ -430,15 +438,13 @@ void buffer_reg_stream_add(struct buffer_reg_stream *stream,
 /*
  * Add a buffer registry channel object to the given session.
  */
-void buffer_reg_channel_add(struct buffer_reg_session *session,
-               struct buffer_reg_channel *channel)
+void buffer_reg_channel_add(struct buffer_reg_session *session, struct buffer_reg_channel *channel)
 {
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(channel);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_add_unique_u64(session->channels, &channel->node);
-       rcu_read_unlock();
 }
 
 /*
@@ -448,12 +454,11 @@ void buffer_reg_channel_add(struct buffer_reg_session *session,
  *
  * Return the object pointer or NULL on error.
  */
-struct buffer_reg_channel *buffer_reg_channel_find(uint64_t key,
-               struct buffer_reg_uid *reg)
+struct buffer_reg_channel *buffer_reg_channel_find(uint64_t key, struct buffer_reg_uid *reg)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
-       struct buffer_reg_channel *chan = NULL;
+       struct buffer_reg_channel *chan = nullptr;
        struct lttng_ht *ht;
 
        LTTNG_ASSERT(reg);
@@ -481,25 +486,24 @@ end:
 /*
  * Destroy a buffer registry stream with the given domain.
  */
-void buffer_reg_stream_destroy(struct buffer_reg_stream *regp,
-               enum lttng_domain_type domain)
+void buffer_reg_stream_destroy(struct buffer_reg_stream *regp, enum lttng_domain_type domain)
 {
        if (!regp) {
                return;
        }
 
-       DBG3("Buffer registry stream destroy with handle %d",
-                       regp->obj.ust->handle);
+       DBG3("Buffer registry stream destroy with handle %d", regp->obj.ust->handle);
 
        switch (domain) {
        case LTTNG_DOMAIN_UST:
        {
                int ret;
 
-               ret = ust_app_release_object(NULL, regp->obj.ust);
+               ret = ust_app_release_object(nullptr, regp->obj.ust);
                if (ret < 0 && ret != -EPIPE && ret != -LTTNG_UST_ERR_EXITING) {
                        ERR("Buffer reg stream release obj handle %d failed with ret %d",
-                                       regp->obj.ust->handle, ret);
+                           regp->obj.ust->handle,
+                           ret);
                }
                free(regp->obj.ust);
                lttng_fd_put(LTTNG_FD_APPS, 2);
@@ -517,8 +521,7 @@ void buffer_reg_stream_destroy(struct buffer_reg_stream *regp,
  * Remove buffer registry channel object from the session hash table. RCU read
  * side lock MUST be acquired before calling this.
  */
-void buffer_reg_channel_remove(struct buffer_reg_session *session,
-               struct buffer_reg_channel *regp)
+void buffer_reg_channel_remove(struct buffer_reg_session *session, struct buffer_reg_channel *regp)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -534,8 +537,7 @@ void buffer_reg_channel_remove(struct buffer_reg_session *session,
 /*
  * Destroy a buffer registry channel with the given domain.
  */
-void buffer_reg_channel_destroy(struct buffer_reg_channel *regp,
-               enum lttng_domain_type domain)
+void buffer_reg_channel_destroy(struct buffer_reg_channel *regp, enum lttng_domain_type domain)
 {
        if (!regp) {
                return;
@@ -549,17 +551,18 @@ void buffer_reg_channel_destroy(struct buffer_reg_channel *regp,
                int ret;
                struct buffer_reg_stream *sreg, *stmp;
                /* Wipe stream */
-               cds_list_for_each_entry_safe(sreg, stmp, &regp->streams, lnode) {
+               cds_list_for_each_entry_safe (sreg, stmp, &regp->streams, lnode) {
                        cds_list_del(&sreg->lnode);
                        regp->stream_count--;
                        buffer_reg_stream_destroy(sreg, domain);
                }
 
                if (regp->obj.ust) {
-                       ret = ust_app_release_object(NULL, regp->obj.ust);
+                       ret = ust_app_release_object(nullptr, regp->obj.ust);
                        if (ret < 0 && ret != -EPIPE && ret != -LTTNG_UST_ERR_EXITING) {
                                ERR("Buffer reg channel release obj handle %d failed with ret %d",
-                                               regp->obj.ust->handle, ret);
+                                   regp->obj.ust->handle,
+                                   ret);
                        }
                        free(regp->obj.ust);
                }
@@ -578,7 +581,7 @@ void buffer_reg_channel_destroy(struct buffer_reg_channel *regp,
  * Destroy a buffer registry session with the given domain.
  */
 static void buffer_reg_session_destroy(struct buffer_reg_session *regp,
-               enum lttng_domain_type domain)
+                                      enum lttng_domain_type domain)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -587,14 +590,15 @@ static void buffer_reg_session_destroy(struct buffer_reg_session *regp,
        DBG3("Buffer registry session destroy");
 
        /* Destroy all channels. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(regp->channels->ht, &iter.iter, reg_chan,
-                       node.node) {
-               ret = lttng_ht_del(regp->channels, &iter);
-               LTTNG_ASSERT(!ret);
-               buffer_reg_channel_destroy(reg_chan, domain);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (regp->channels->ht, &iter.iter, reg_chan, node.node) {
+                       ret = lttng_ht_del(regp->channels, &iter);
+                       LTTNG_ASSERT(!ret);
+                       buffer_reg_channel_destroy(reg_chan, domain);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(regp->channels);
 
@@ -620,19 +624,16 @@ void buffer_reg_uid_remove(struct buffer_reg_uid *regp)
 
        LTTNG_ASSERT(regp);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        iter.iter.node = &regp->node.node;
        ret = lttng_ht_del(buffer_registry_uid, &iter);
        LTTNG_ASSERT(!ret);
-       rcu_read_unlock();
 }
 
 static void rcu_free_buffer_reg_uid(struct rcu_head *head)
 {
-       struct lttng_ht_node_u64 *node =
-               lttng::utils::container_of(head, &lttng_ht_node_u64::head);
-       struct buffer_reg_uid *reg =
-               lttng::utils::container_of(node, &buffer_reg_uid::node);
+       struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
+       struct buffer_reg_uid *reg = lttng::utils::container_of(node, &buffer_reg_uid::node);
 
        buffer_reg_session_destroy(reg->registry, reg->domain);
        free(reg);
@@ -640,10 +641,8 @@ static void rcu_free_buffer_reg_uid(struct rcu_head *head)
 
 static void rcu_free_buffer_reg_pid(struct rcu_head *head)
 {
-       struct lttng_ht_node_u64 *node =
-               lttng::utils::container_of(head, &lttng_ht_node_u64::head);
-       struct buffer_reg_pid *reg =
-               lttng::utils::container_of(node, &buffer_reg_pid::node);
+       struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
+       struct buffer_reg_pid *reg = lttng::utils::container_of(node, &buffer_reg_pid::node);
 
        buffer_reg_session_destroy(reg->registry, LTTNG_DOMAIN_UST);
        free(reg);
@@ -654,8 +653,7 @@ static void rcu_free_buffer_reg_pid(struct rcu_head *head)
  * list or hash table. Use buffer_reg_pid_remove() before calling this function
  * for the case that the object is in the global hash table.
  */
-void buffer_reg_uid_destroy(struct buffer_reg_uid *regp,
-               struct consumer_output *consumer)
+void buffer_reg_uid_destroy(struct buffer_reg_uid *regp, struct consumer_output *consumer)
 {
        struct consumer_socket *socket;
 
@@ -664,36 +662,36 @@ void buffer_reg_uid_destroy(struct buffer_reg_uid *regp,
        }
 
        DBG3("Buffer registry per UID destroy with id: %" PRIu64 ", ABI: %u, uid: %d",
-                       regp->session_id, regp->bits_per_long, regp->uid);
+            regp->session_id,
+            regp->bits_per_long,
+            regp->uid);
 
        if (!consumer) {
                goto destroy;
        }
 
-       rcu_read_lock();
-       /* Get the right socket from the consumer object. */
-       socket = consumer_find_socket_by_bitness(regp->bits_per_long,
-                       consumer);
-       if (!socket) {
-               goto unlock;
-       }
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               /* Get the right socket from the consumer object. */
+               socket = consumer_find_socket_by_bitness(regp->bits_per_long, consumer);
+               if (!socket) {
+                       goto destroy;
+               }
 
-       switch (regp->domain) {
-       case LTTNG_DOMAIN_UST:
-               if (regp->registry->reg.ust->_metadata_key) {
-                       /* Return value does not matter. This call will print errors. */
-                       (void) consumer_close_metadata(socket,
-                                       regp->registry->reg.ust->_metadata_key);
+               switch (regp->domain) {
+               case LTTNG_DOMAIN_UST:
+                       if (regp->registry->reg.ust->_metadata_key) {
+                               /* Return value does not matter. This call will print errors. */
+                               (void) consumer_close_metadata(
+                                       socket, regp->registry->reg.ust->_metadata_key);
+                       }
+                       break;
+               default:
+                       abort();
+                       return;
                }
-               break;
-       default:
-               abort();
-               rcu_read_unlock();
-               return;
        }
 
-unlock:
-       rcu_read_unlock();
 destroy:
        call_rcu(&regp->node.head, rcu_free_buffer_reg_uid);
 }
@@ -725,8 +723,7 @@ void buffer_reg_pid_destroy(struct buffer_reg_pid *regp)
                return;
        }
 
-       DBG3("Buffer registry per PID destroy with id: %" PRIu64,
-                       regp->session_id);
+       DBG3("Buffer registry per PID destroy with id: %" PRIu64, regp->session_id);
 
        /* This registry is only used by UST. */
        call_rcu(&regp->node.head, rcu_free_buffer_reg_pid);
@@ -735,7 +732,7 @@ void buffer_reg_pid_destroy(struct buffer_reg_pid *regp)
 /*
  * Destroy per PID and UID registry hash table.
  */
-void buffer_reg_destroy_registries(void)
+void buffer_reg_destroy_registries()
 {
        DBG3("Buffer registry destroy all registry");
        lttng_ht_destroy(buffer_registry_uid);
index 4641361f013d260f66ed797fcf3a7bed0a947094..2bdc58367b0705cce6aa72bd66d31285c4872283 100644 (file)
@@ -8,16 +8,17 @@
 #ifndef LTTNG_BUFFER_REGISTRY_H
 #define LTTNG_BUFFER_REGISTRY_H
 
-#include <stdint.h>
-#include <urcu/list.h>
-
-#include <lttng/lttng.h>
-#include <common/hashtable/hashtable.hpp>
-
 #include "consumer.hpp"
 #include "lttng-ust-ctl.hpp"
-#include "ust-registry.hpp"
 #include "ust-registry-session.hpp"
+#include "ust-registry.hpp"
+
+#include <common/hashtable/hashtable.hpp>
+
+#include <lttng/lttng.h>
+
+#include <stdint.h>
+#include <urcu/list.h>
 
 struct buffer_reg_stream {
        struct cds_list_head lnode;
@@ -68,9 +69,9 @@ struct buffer_reg_uid {
         * Keys to match this object in a hash table. The following three variables
         * identify a unique per UID buffer registry.
         */
-       uint64_t session_id;    /* Unique tracing session id. */
-       int bits_per_long;      /* ABI */
-       uid_t uid;                      /* Owner. */
+       uint64_t session_id; /* Unique tracing session id. */
+       int bits_per_long; /* ABI */
+       uid_t uid; /* Owner. */
 
        enum lttng_domain_type domain;
        struct buffer_reg_session *registry;
@@ -100,21 +101,25 @@ struct buffer_reg_pid {
 };
 
 /* Buffer registry per UID. */
-void buffer_reg_init_uid_registry(void);
-int buffer_reg_uid_create(uint64_t session_id, uint32_t bits_per_long, uid_t uid,
-               enum lttng_domain_type domain, struct buffer_reg_uid **regp,
-               const char *root_shm_path, const char *shm_path);
+void buffer_reg_init_uid_registry();
+int buffer_reg_uid_create(uint64_t session_id,
+                         uint32_t bits_per_long,
+                         uid_t uid,
+                         enum lttng_domain_type domain,
+                         struct buffer_reg_uid **regp,
+                         const char *root_shm_path,
+                         const char *shm_path);
 void buffer_reg_uid_add(struct buffer_reg_uid *reg);
-struct buffer_reg_uid *buffer_reg_uid_find(uint64_t session_id,
-               uint32_t bits_per_long, uid_t uid);
+struct buffer_reg_uid *buffer_reg_uid_find(uint64_t session_id, uint32_t bits_per_long, uid_t uid);
 void buffer_reg_uid_remove(struct buffer_reg_uid *regp);
-void buffer_reg_uid_destroy(struct buffer_reg_uid *regp,
-               struct consumer_output *consumer);
+void buffer_reg_uid_destroy(struct buffer_reg_uid *regp, struct consumer_output *consumer);
 
 /* Buffer registry per PID. */
-void buffer_reg_init_pid_registry(void);
-int buffer_reg_pid_create(uint64_t session_id, struct buffer_reg_pid **regp,
-               const char *root_shm_path, const char *shm_path);
+void buffer_reg_init_pid_registry();
+int buffer_reg_pid_create(uint64_t session_id,
+                         struct buffer_reg_pid **regp,
+                         const char *root_shm_path,
+                         const char *shm_path);
 void buffer_reg_pid_add(struct buffer_reg_pid *reg);
 struct buffer_reg_pid *buffer_reg_pid_find(uint64_t session_id);
 void buffer_reg_pid_remove(struct buffer_reg_pid *regp);
@@ -122,27 +127,21 @@ void buffer_reg_pid_destroy(struct buffer_reg_pid *regp);
 
 /* Channel */
 int buffer_reg_channel_create(uint64_t key, struct buffer_reg_channel **regp);
-void buffer_reg_channel_add(struct buffer_reg_session *session,
-               struct buffer_reg_channel *channel);
-struct buffer_reg_channel *buffer_reg_channel_find(uint64_t key,
-               struct buffer_reg_uid *reg);
-void buffer_reg_channel_remove(struct buffer_reg_session *session,
-               struct buffer_reg_channel *regp);
-void buffer_reg_channel_destroy(struct buffer_reg_channel *regp,
-               enum lttng_domain_type domain);
+void buffer_reg_channel_add(struct buffer_reg_session *session, struct buffer_reg_channel *channel);
+struct buffer_reg_channel *buffer_reg_channel_find(uint64_t key, struct buffer_reg_uid *reg);
+void buffer_reg_channel_remove(struct buffer_reg_session *session, struct buffer_reg_channel *regp);
+void buffer_reg_channel_destroy(struct buffer_reg_channel *regp, enum lttng_domain_type domain);
 
 /* Stream */
 int buffer_reg_stream_create(struct buffer_reg_stream **regp);
-void buffer_reg_stream_add(struct buffer_reg_stream *stream,
-               struct buffer_reg_channel *channel);
-void buffer_reg_stream_destroy(struct buffer_reg_stream *regp,
-               enum lttng_domain_type domain);
+void buffer_reg_stream_add(struct buffer_reg_stream *stream, struct buffer_reg_channel *channel);
+void buffer_reg_stream_destroy(struct buffer_reg_stream *regp, enum lttng_domain_type domain);
 
 /* Global registry. */
-void buffer_reg_destroy_registries(void);
+void buffer_reg_destroy_registries();
 
-int buffer_reg_uid_consumer_channel_key(
-               struct cds_list_head *buffer_reg_uid_list,
-               uint64_t chan_key, uint64_t *consumer_chan_key);
+int buffer_reg_uid_consumer_channel_key(struct cds_list_head *buffer_reg_uid_list,
+                                       uint64_t chan_key,
+                                       uint64_t *consumer_chan_key);
 
 #endif /* LTTNG_BUFFER_REGISTRY_H */
index 540fc973405de16ebcc4d3fddf450827e9018f03..4e5401295ed43f9d36d87b2e29a78b4f2ca52b72 100644 (file)
@@ -7,35 +7,34 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <common/common.hpp>
-#include <common/defaults.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-
+#include "agent.hpp"
 #include "channel.hpp"
-#include "lttng-sessiond.hpp"
 #include "kernel.hpp"
+#include "lttng-sessiond.hpp"
 #include "lttng-ust-ctl.hpp"
 #include "lttng-ust-error.hpp"
-#include "utils.hpp"
 #include "ust-app.hpp"
-#include "agent.hpp"
+#include "utils.hpp"
+
+#include <common/common.hpp>
+#include <common/defaults.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
 
 /*
  * Return allocated channel attributes.
  */
-struct lttng_channel *channel_new_default_attr(int dom,
-               enum lttng_buffer_type type)
+struct lttng_channel *channel_new_default_attr(int dom, enum lttng_buffer_type type)
 {
        struct lttng_channel *chan;
        const char *channel_name = DEFAULT_CHANNEL_NAME;
-       struct lttng_channel_extended *extended_attr = NULL;
+       struct lttng_channel_extended *extended_attr = nullptr;
 
        chan = zmalloc<lttng_channel>();
-       if (chan == NULL) {
+       if (chan == nullptr) {
                PERROR("zmalloc channel init");
                goto error_alloc;
        }
@@ -56,16 +55,14 @@ struct lttng_channel *channel_new_default_attr(int dom,
        switch (dom) {
        case LTTNG_DOMAIN_KERNEL:
                LTTNG_ASSERT(type == LTTNG_BUFFER_GLOBAL);
-               chan->attr.subbuf_size =
-                       default_get_kernel_channel_subbuf_size();
+               chan->attr.subbuf_size = default_get_kernel_channel_subbuf_size();
                chan->attr.num_subbuf = DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM;
                chan->attr.output = DEFAULT_KERNEL_CHANNEL_OUTPUT;
                chan->attr.switch_timer_interval = DEFAULT_KERNEL_CHANNEL_SWITCH_TIMER;
                chan->attr.read_timer_interval = DEFAULT_KERNEL_CHANNEL_READ_TIMER;
                chan->attr.live_timer_interval = DEFAULT_KERNEL_CHANNEL_LIVE_TIMER;
                extended_attr->blocking_timeout = DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT;
-               extended_attr->monitor_timer_interval =
-                       DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER;
+               extended_attr->monitor_timer_interval = DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER;
                break;
        case LTTNG_DOMAIN_JUL:
                channel_name = DEFAULT_JUL_CHANNEL_NAME;
@@ -77,18 +74,15 @@ struct lttng_channel *channel_new_default_attr(int dom,
                channel_name = DEFAULT_PYTHON_CHANNEL_NAME;
                goto common_ust;
        case LTTNG_DOMAIN_UST:
-common_ust:
+       common_ust:
                switch (type) {
                case LTTNG_BUFFER_PER_UID:
                        chan->attr.subbuf_size = default_get_ust_uid_channel_subbuf_size();
                        chan->attr.num_subbuf = DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM;
                        chan->attr.output = DEFAULT_UST_UID_CHANNEL_OUTPUT;
-                       chan->attr.switch_timer_interval =
-                               DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER;
-                       chan->attr.read_timer_interval =
-                               DEFAULT_UST_UID_CHANNEL_READ_TIMER;
-                       chan->attr.live_timer_interval =
-                               DEFAULT_UST_UID_CHANNEL_LIVE_TIMER;
+                       chan->attr.switch_timer_interval = DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER;
+                       chan->attr.read_timer_interval = DEFAULT_UST_UID_CHANNEL_READ_TIMER;
+                       chan->attr.live_timer_interval = DEFAULT_UST_UID_CHANNEL_LIVE_TIMER;
                        extended_attr->blocking_timeout = DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT;
                        extended_attr->monitor_timer_interval =
                                DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER;
@@ -98,12 +92,9 @@ common_ust:
                        chan->attr.subbuf_size = default_get_ust_pid_channel_subbuf_size();
                        chan->attr.num_subbuf = DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM;
                        chan->attr.output = DEFAULT_UST_PID_CHANNEL_OUTPUT;
-                       chan->attr.switch_timer_interval =
-                               DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER;
-                       chan->attr.read_timer_interval =
-                               DEFAULT_UST_PID_CHANNEL_READ_TIMER;
-                       chan->attr.live_timer_interval =
-                               DEFAULT_UST_PID_CHANNEL_LIVE_TIMER;
+                       chan->attr.switch_timer_interval = DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER;
+                       chan->attr.read_timer_interval = DEFAULT_UST_PID_CHANNEL_READ_TIMER;
+                       chan->attr.live_timer_interval = DEFAULT_UST_PID_CHANNEL_LIVE_TIMER;
                        extended_attr->blocking_timeout = DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT;
                        extended_attr->monitor_timer_interval =
                                DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER;
@@ -111,11 +102,10 @@ common_ust:
                }
                break;
        default:
-               goto error;     /* Not implemented */
+               goto error; /* Not implemented */
        }
 
-       if (snprintf(chan->name, sizeof(chan->name), "%s",
-                       channel_name) < 0) {
+       if (snprintf(chan->name, sizeof(chan->name), "%s", channel_name) < 0) {
                PERROR("snprintf default channel name");
                goto error;
        }
@@ -125,7 +115,7 @@ error:
        free(extended_attr);
        free(chan);
 error_alloc:
-       return NULL;
+       return nullptr;
 }
 
 void channel_attr_destroy(struct lttng_channel *channel)
@@ -140,8 +130,7 @@ void channel_attr_destroy(struct lttng_channel *channel)
 /*
  * Disable kernel channel of the kernel session.
  */
-int channel_kernel_disable(struct ltt_kernel_session *ksession,
-               char *channel_name)
+int channel_kernel_disable(struct ltt_kernel_session *ksession, char *channel_name)
 {
        int ret;
        struct ltt_kernel_channel *kchan;
@@ -150,13 +139,13 @@ int channel_kernel_disable(struct ltt_kernel_session *ksession,
        LTTNG_ASSERT(channel_name);
 
        kchan = trace_kernel_get_channel_by_name(channel_name, ksession);
-       if (kchan == NULL) {
+       if (kchan == nullptr) {
                ret = LTTNG_ERR_KERN_CHAN_NOT_FOUND;
                goto error;
        }
 
        /* Only if channel is enabled disable it. */
-       if (kchan->enabled == 1) {
+       if (kchan->enabled) {
                ret = kernel_disable_channel(kchan);
                if (ret < 0 && ret != -EEXIST) {
                        ret = LTTNG_ERR_KERN_CHAN_DISABLE_FAIL;
@@ -174,14 +163,14 @@ error:
  * Enable kernel channel of the kernel session.
  */
 enum lttng_error_code channel_kernel_enable(struct ltt_kernel_session *ksession,
-               struct ltt_kernel_channel *kchan)
+                                           struct ltt_kernel_channel *kchan)
 {
        enum lttng_error_code ret_code;
 
        LTTNG_ASSERT(ksession);
        LTTNG_ASSERT(kchan);
 
-       if (kchan->enabled == 0) {
+       if (!kchan->enabled) {
                if (kernel_enable_channel(kchan) < 0) {
                        ret_code = LTTNG_ERR_KERN_CHAN_ENABLE_FAIL;
                        goto error;
@@ -213,7 +202,7 @@ static int channel_validate(struct lttng_channel *attr)
 static int channel_validate_kernel(struct lttng_channel *attr)
 {
        /* Kernel channels do not support blocking timeout. */
-       if (((struct lttng_channel_extended *)attr->attr.extended.ptr)->blocking_timeout) {
+       if (((struct lttng_channel_extended *) attr->attr.extended.ptr)->blocking_timeout) {
                return -1;
        }
        return 0;
@@ -223,18 +212,18 @@ static int channel_validate_kernel(struct lttng_channel *attr)
  * Create kernel channel of the kernel session and notify kernel thread.
  */
 enum lttng_error_code channel_kernel_create(struct ltt_kernel_session *ksession,
-               struct lttng_channel *attr, int kernel_pipe)
+                                           struct lttng_channel *attr,
+                                           int kernel_pipe)
 {
        enum lttng_error_code ret_code;
-       struct lttng_channel *defattr = NULL;
+       struct lttng_channel *defattr = nullptr;
 
        LTTNG_ASSERT(ksession);
 
        /* Creating channel attributes if needed */
-       if (attr == NULL) {
-               defattr = channel_new_default_attr(LTTNG_DOMAIN_KERNEL,
-                               LTTNG_BUFFER_GLOBAL);
-               if (defattr == NULL) {
+       if (attr == nullptr) {
+               defattr = channel_new_default_attr(LTTNG_DOMAIN_KERNEL, LTTNG_BUFFER_GLOBAL);
+               if (defattr == nullptr) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto error;
                }
@@ -282,7 +271,7 @@ error:
  * Enable UST channel for session and domain.
  */
 enum lttng_error_code channel_ust_enable(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan)
+                                        struct ltt_ust_channel *uchan)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
 
@@ -295,7 +284,7 @@ enum lttng_error_code channel_ust_enable(struct ltt_ust_session *usess,
                ret_code = LTTNG_ERR_UST_CHAN_EXIST;
                goto end;
        } else {
-               uchan->enabled = 1;
+               uchan->enabled = true;
                DBG2("Channel %s enabled successfully", uchan->name);
        }
 
@@ -320,7 +309,6 @@ enum lttng_error_code channel_ust_enable(struct ltt_ust_session *usess,
         */
        (void) ust_app_enable_channel_glb(usess, uchan);
 
-
 end:
        return ret_code;
 }
@@ -329,20 +317,22 @@ end:
  * Create UST channel for session and domain.
  */
 enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
-               struct lttng_channel *attr, enum lttng_buffer_type type)
+                                        struct lttng_channel *attr,
+                                        enum lttng_buffer_type type)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
-       struct ltt_ust_channel *uchan = NULL;
-       struct lttng_channel *defattr = NULL;
+       struct ltt_ust_channel *uchan = nullptr;
+       struct lttng_channel *defattr = nullptr;
        enum lttng_domain_type domain = LTTNG_DOMAIN_UST;
        bool chan_published = false;
+       lttng::urcu::read_lock_guard read_lock;
 
        LTTNG_ASSERT(usess);
 
        /* Creating channel attributes if needed */
-       if (attr == NULL) {
+       if (attr == nullptr) {
                defattr = channel_new_default_attr(LTTNG_DOMAIN_UST, type);
-               if (defattr == NULL) {
+               if (defattr == nullptr) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto error;
                }
@@ -385,8 +375,7 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
         * and nonzero. We validate right here for UST, because applications will
         * not report the error to the user (unlike kernel tracing).
         */
-       if (!attr->attr.subbuf_size ||
-                       (attr->attr.subbuf_size & (attr->attr.subbuf_size - 1))) {
+       if (!attr->attr.subbuf_size || (attr->attr.subbuf_size & (attr->attr.subbuf_size - 1))) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
@@ -399,8 +388,7 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
                goto error;
        }
 
-       if (!attr->attr.num_subbuf ||
-                       (attr->attr.num_subbuf & (attr->attr.num_subbuf - 1))) {
+       if (!attr->attr.num_subbuf || (attr->attr.num_subbuf & (attr->attr.num_subbuf - 1))) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
@@ -415,7 +403,7 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
         * we won't be able to write the packets on disk
         */
        if ((attr->attr.tracefile_size > 0) &&
-                       (attr->attr.tracefile_size < attr->attr.subbuf_size)) {
+           (attr->attr.tracefile_size < attr->attr.subbuf_size)) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
@@ -433,20 +421,23 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
 
        /* Create UST channel */
        uchan = trace_ust_create_channel(attr, domain);
-       if (uchan == NULL) {
+       if (uchan == nullptr) {
                ret_code = LTTNG_ERR_FATAL;
                goto error;
        }
 
-       uchan->enabled = 1;
-       if (trace_ust_is_max_id(usess->used_channel_id)) {
+       uchan->enabled = true;
+       if (trace_ust_is_max_id(usess->used_event_container_id)) {
                ret_code = LTTNG_ERR_UST_CHAN_FAIL;
                goto error;
        }
-       uchan->id = trace_ust_get_next_chan_id(usess);
+
+       uchan->id = trace_ust_get_next_event_container_id(usess);
 
        DBG2("Channel %s is being created for UST with buffer %d and id %" PRIu64,
-                       uchan->name, type, uchan->id);
+            uchan->name,
+            type,
+            uchan->id);
 
        /* Flag session buffer type. */
        if (!usess->buffer_type_changed) {
@@ -459,9 +450,7 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
        }
 
        /* Adding the channel to the channel hash table. */
-       rcu_read_lock();
-       if (strncmp(uchan->name, DEFAULT_METADATA_NAME,
-                               sizeof(uchan->name))) {
+       if (strncmp(uchan->name, DEFAULT_METADATA_NAME, sizeof(uchan->name)) != 0) {
                lttng_ht_add_unique_str(usess->domain_global.channels, &uchan->node);
                chan_published = true;
        } else {
@@ -470,10 +459,8 @@ enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
                 * application exists we can access that data in the shadow copy during
                 * the global update of newly registered application.
                 */
-               memcpy(&usess->metadata_attr, &uchan->attr,
-                               sizeof(usess->metadata_attr));
+               memcpy(&usess->metadata_attr, &uchan->attr, sizeof(usess->metadata_attr));
        }
-       rcu_read_unlock();
 
        DBG2("Channel %s created successfully", uchan->name);
        if (domain != LTTNG_DOMAIN_UST) {
@@ -506,8 +493,7 @@ error:
 /*
  * Disable UST channel for session and domain.
  */
-int channel_ust_disable(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan)
+int channel_ust_disable(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan)
 {
        int ret = LTTNG_OK;
 
@@ -515,12 +501,12 @@ int channel_ust_disable(struct ltt_ust_session *usess,
        LTTNG_ASSERT(uchan);
 
        /* Already disabled */
-       if (uchan->enabled == 0) {
+       if (!uchan->enabled) {
                DBG2("Channel UST %s already disabled", uchan->name);
                goto end;
        }
 
-       uchan->enabled = 0;
+       uchan->enabled = false;
 
        /*
         * If session is inactive we don't notify the tracer right away. We
@@ -547,10 +533,9 @@ error:
        return ret;
 }
 
-struct lttng_channel *trace_ust_channel_to_lttng_channel(
-               const struct ltt_ust_channel *uchan)
+struct lttng_channel *trace_ust_channel_to_lttng_channel(const struct ltt_ust_channel *uchan)
 {
-       struct lttng_channel *channel = NULL, *ret = NULL;
+       struct lttng_channel *channel = nullptr, *ret = nullptr;
 
        channel = lttng_channel_create_internal();
        if (!channel) {
@@ -588,13 +573,11 @@ struct lttng_channel *trace_ust_channel_to_lttng_channel(
                break;
        }
 
-       lttng_channel_set_blocking_timeout(
-                       channel, uchan->attr.u.s.blocking_timeout);
-       lttng_channel_set_monitor_timer_interval(
-                       channel, uchan->monitor_timer_interval);
+       lttng_channel_set_blocking_timeout(channel, uchan->attr.u.s.blocking_timeout);
+       lttng_channel_set_monitor_timer_interval(channel, uchan->monitor_timer_interval);
 
        ret = channel;
-       channel = NULL;
+       channel = nullptr;
 
 end:
        lttng_channel_destroy(channel);
index 342e30f78a472e75113103527b7789b68885551f..f7156c6324574fc1dfe1a6e4a908cf5d3d9b60ff 100644 (file)
@@ -8,31 +8,28 @@
 #ifndef _LTT_CHANNEL_H
 #define _LTT_CHANNEL_H
 
-#include <lttng/lttng.h>
-
 #include "trace-kernel.hpp"
 #include "trace-ust.hpp"
 
-int channel_kernel_disable(struct ltt_kernel_session *ksession,
-               char *channel_name);
+#include <lttng/lttng.h>
+
+int channel_kernel_disable(struct ltt_kernel_session *ksession, char *channel_name);
 enum lttng_error_code channel_kernel_enable(struct ltt_kernel_session *ksession,
-               struct ltt_kernel_channel *kchan);
+                                           struct ltt_kernel_channel *kchan);
 enum lttng_error_code channel_kernel_create(struct ltt_kernel_session *ksession,
-               struct lttng_channel *chan,
-               int kernel_pipe);
+                                           struct lttng_channel *chan,
+                                           int kernel_pipe);
 
-struct lttng_channel *channel_new_default_attr(int domain,
-               enum lttng_buffer_type type);
+struct lttng_channel *channel_new_default_attr(int domain, enum lttng_buffer_type type);
 void channel_attr_destroy(struct lttng_channel *channel);
 
 enum lttng_error_code channel_ust_create(struct ltt_ust_session *usess,
-               struct lttng_channel *attr, enum lttng_buffer_type type);
+                                        struct lttng_channel *attr,
+                                        enum lttng_buffer_type type);
 enum lttng_error_code channel_ust_enable(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan);
-int channel_ust_disable(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan);
+                                        struct ltt_ust_channel *uchan);
+int channel_ust_disable(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan);
 
-struct lttng_channel *trace_ust_channel_to_lttng_channel(
-               const struct ltt_ust_channel *uchan);
+struct lttng_channel *trace_ust_channel_to_lttng_channel(const struct ltt_ust_channel *uchan);
 
 #endif /* _LTT_CHANNEL_H */
index 38268edd2e4362fb7dbdf1361c030a7de89e170a..ced9925943b83d543676ce45d191806f6d8472f2 100644 (file)
@@ -6,19 +6,19 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <string.h>
-#include <unistd.h>
+#include "clear.hpp"
+#include "cmd.hpp"
+#include "kernel.hpp"
+#include "session.hpp"
+#include "ust-app.hpp"
 
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/utils.hpp>
 
-#include "clear.hpp"
-#include "session.hpp"
-#include "ust-app.hpp"
-#include "kernel.hpp"
-#include "cmd.hpp"
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
 
 namespace {
 struct cmd_clear_session_reply_context {
@@ -26,16 +26,14 @@ struct cmd_clear_session_reply_context {
 };
 } /* namespace */
 
-static
-void cmd_clear_session_reply(const struct ltt_session *session,
-               void *_reply_context)
+static void cmd_clear_session_reply(const struct ltt_session *session, void *_reply_context)
 {
        int ret;
        ssize_t comm_ret;
        const struct cmd_clear_session_reply_context *reply_context =
-                       (cmd_clear_session_reply_context *) _reply_context;
+               (cmd_clear_session_reply_context *) _reply_context;
        struct lttcomm_lttng_msg llm = {
-               .cmd_type = LTTNG_CLEAR_SESSION,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION,
                .ret_code = LTTNG_OK,
                .pid = UINT32_MAX,
                .cmd_header_size = 0,
@@ -44,11 +42,9 @@ void cmd_clear_session_reply(const struct ltt_session *session,
        };
 
        DBG("End of clear command: replying to client");
-       comm_ret = lttcomm_send_unix_sock(reply_context->reply_sock_fd,
-                       &llm, sizeof(llm));
+       comm_ret = lttcomm_send_unix_sock(reply_context->reply_sock_fd, &llm, sizeof(llm));
        if (comm_ret != (ssize_t) sizeof(llm)) {
-               ERR("Failed to send result of session \"%s\" clear to client",
-                               session->name);
+               ERR("Failed to send result of session \"%s\" clear to client", session->name);
        }
        ret = close(reply_context->reply_sock_fd);
        if (ret) {
@@ -60,7 +56,7 @@ void cmd_clear_session_reply(const struct ltt_session *session,
 int cmd_clear_session(struct ltt_session *session, int *sock_fd)
 {
        int ret = LTTNG_OK;
-       struct cmd_clear_session_reply_context *reply_context = NULL;
+       struct cmd_clear_session_reply_context *reply_context = nullptr;
        bool session_was_active = false;
        struct ltt_kernel_session *ksession;
        struct ltt_ust_session *usess;
@@ -78,23 +74,22 @@ int cmd_clear_session(struct ltt_session *session, int *sock_fd)
        }
 
        if (!session->has_been_started) {
-                /*
-                 * Nothing to be cleared, this is not an error: there is
-                 * indeed nothing to do, and there is no reason why we
-                 * should return an error to the user.
-                 */
-                goto end;
+               /*
+                * Nothing to be cleared, this is not an error: there is
+                * indeed nothing to do, and there is no reason why we
+                * should return an error to the user.
+                */
+               goto end;
        }
 
        /* Unsupported feature in lttng-relayd before 2.11. */
        if (session->consumer->type == CONSUMER_DST_NET &&
-                       (session->consumer->relay_major_version == 2 &&
-                       session->consumer->relay_minor_version < 12)) {
+           (session->consumer->relay_major_version == 2 &&
+            session->consumer->relay_minor_version < 12)) {
                ret = LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY;
                goto end;
        }
-       if (session->consumer->type == CONSUMER_DST_NET &&
-                       !session->consumer->relay_allows_clear) {
+       if (session->consumer->type == CONSUMER_DST_NET && !session->consumer->relay_allows_clear) {
                ret = LTTNG_ERR_CLEAR_NOT_AVAILABLE_RELAY;
                goto end;
        }
@@ -153,9 +148,8 @@ int cmd_clear_session(struct ltt_session *session, int *sock_fd)
                 * Use rotation to delete local and remote stream files.
                 */
                if (reply_context) {
-                       ret = session_add_clear_notifier(session,
-                                       cmd_clear_session_reply,
-                                       (void *) reply_context);
+                       ret = session_add_clear_notifier(
+                               session, cmd_clear_session_reply, (void *) reply_context);
                        if (ret) {
                                ret = LTTNG_ERR_FATAL;
                                goto end;
@@ -164,11 +158,11 @@ int cmd_clear_session(struct ltt_session *session, int *sock_fd)
                         * On success, ownership of reply_context has been
                         * passed to session_add_clear_notifier().
                         */
-                       reply_context = NULL;
+                       reply_context = nullptr;
                        *sock_fd = -1;
                }
-               ret = cmd_rotate_session(session, NULL, true,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE);
+               ret = cmd_rotate_session(
+                       session, nullptr, true, LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -178,9 +172,8 @@ int cmd_clear_session(struct ltt_session *session, int *sock_fd)
        }
        if (session_was_active) {
                /* Kernel tracing */
-               if (ksession != NULL) {
-                       DBG("Start kernel tracing session \"%s\"",
-                                       session->name);
+               if (ksession != nullptr) {
+                       DBG("Start kernel tracing session \"%s\"", session->name);
                        ret = start_kernel_session(ksession);
                        if (ret != LTTNG_OK) {
                                goto end;
index a52062e07f877ddc08ccf84604a56c5f2ff1fd59..43a8b793e9ed366d5be2631feca34cc8f190ddef 100644 (file)
@@ -7,6 +7,10 @@
  *
  */
 
+#include "agent-thread.hpp"
+#include "clear.hpp"
+#include "client.hpp"
+#include "cmd.hpp"
 #include "common/buffer-view.hpp"
 #include "common/compat/socket.hpp"
 #include "common/dynamic-array.hpp"
 #include "common/payload-view.hpp"
 #include "common/payload.hpp"
 #include "common/sessiond-comm/sessiond-comm.hpp"
+#include "health-sessiond.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
 #include "lttng/lttng-error.h"
 #include "lttng/tracker.h"
+#include "manage-consumer.hpp"
+#include "save.hpp"
+#include "testpoint.hpp"
+#include "utils.hpp"
+
 #include <common/compat/getenv.hpp>
+#include <common/exception.hpp>
 #include <common/tracker.hpp>
 #include <common/unix.hpp>
 #include <common/utils.hpp>
+
 #include <lttng/error-query-internal.hpp>
 #include <lttng/event-internal.hpp>
 #include <lttng/session-descriptor-internal.hpp>
 #include <lttng/session-internal.hpp>
 #include <lttng/userspace-probe-internal.hpp>
+
+#include <fcntl.h>
 #include <pthread.h>
 #include <signal.h>
 #include <stddef.h>
 #include <sys/stat.h>
 #include <unistd.h>
 
-#include "agent-thread.hpp"
-#include "clear.hpp"
-#include "client.hpp"
-#include "cmd.hpp"
-#include "health-sessiond.hpp"
-#include "kernel.hpp"
-#include "lttng-sessiond.hpp"
-#include "manage-consumer.hpp"
-#include "save.hpp"
-#include "testpoint.hpp"
-#include "utils.hpp"
-
 namespace {
 bool is_root;
 
@@ -62,7 +66,7 @@ static void set_thread_status(bool running)
        sem_post(&thread_state.ready);
 }
 
-static bool wait_thread_status(void)
+static bool wait_thread_status()
 {
        DBG("Waiting for client thread to be ready");
        sem_wait(&thread_state.ready);
@@ -83,13 +87,15 @@ static bool wait_thread_status(void)
  * Return 0 on success, negative value on error.
  */
 static int setup_lttng_msg(struct command_ctx *cmd_ctx,
-       const void *payload_buf, size_t payload_len,
-       const void *cmd_header_buf, size_t cmd_header_len)
+                          const void *payload_buf,
+                          size_t payload_len,
+                          const void *cmd_header_buf,
+                          size_t cmd_header_len)
 {
        int ret = 0;
        const size_t header_len = sizeof(struct lttcomm_lttng_msg);
        const size_t total_msg_size = header_len + cmd_header_len + payload_len;
-       lttcomm_lttng_msg llm {};
+       lttcomm_lttng_msg llm{};
 
        llm.cmd_type = cmd_ctx->lsm.cmd_type;
        llm.pid = (uint32_t) cmd_ctx->lsm.domain.attr.pid;
@@ -106,8 +112,7 @@ static int setup_lttng_msg(struct command_ctx *cmd_ctx,
        cmd_ctx->lttng_msg_size = total_msg_size;
 
        /* Append reply header. */
-       ret = lttng_dynamic_buffer_append(
-                       &cmd_ctx->reply_payload.buffer, &llm, sizeof(llm));
+       ret = lttng_dynamic_buffer_append(&cmd_ctx->reply_payload.buffer, &llm, sizeof(llm));
        if (ret) {
                goto end;
        }
@@ -115,8 +120,7 @@ static int setup_lttng_msg(struct command_ctx *cmd_ctx,
        /* Append command header. */
        if (cmd_header_len) {
                ret = lttng_dynamic_buffer_append(
-                               &cmd_ctx->reply_payload.buffer, cmd_header_buf,
-                               cmd_header_len);
+                       &cmd_ctx->reply_payload.buffer, cmd_header_buf, cmd_header_len);
                if (ret) {
                        goto end;
                }
@@ -125,8 +129,7 @@ static int setup_lttng_msg(struct command_ctx *cmd_ctx,
        /* Append payload. */
        if (payload_len) {
                ret = lttng_dynamic_buffer_append(
-                               &cmd_ctx->reply_payload.buffer, payload_buf,
-                               payload_len);
+                       &cmd_ctx->reply_payload.buffer, payload_buf, payload_len);
                if (ret) {
                        goto end;
                }
@@ -147,8 +150,7 @@ static int setup_empty_lttng_msg(struct command_ctx *cmd_ctx)
        }
 
        /* Append place-holder reply header. */
-       ret = lttng_dynamic_buffer_append(
-                       &cmd_ctx->reply_payload.buffer, &llm, sizeof(llm));
+       ret = lttng_dynamic_buffer_append(&cmd_ctx->reply_payload.buffer, &llm, sizeof(llm));
        if (ret) {
                goto end;
        }
@@ -158,13 +160,12 @@ end:
        return ret;
 }
 
-static void update_lttng_msg(struct command_ctx *cmd_ctx, size_t cmd_header_len,
-               size_t payload_len)
+static void update_lttng_msg(struct command_ctx *cmd_ctx, size_t cmd_header_len, size_t payload_len)
 {
        const size_t header_len = sizeof(struct lttcomm_lttng_msg);
        const size_t total_msg_size = header_len + cmd_header_len + payload_len;
        struct lttcomm_lttng_msg *p_llm;
-       lttcomm_lttng_msg llm {};
+       lttcomm_lttng_msg llm{};
 
        llm.cmd_type = cmd_ctx->lsm.cmd_type;
        llm.pid = (uint32_t) cmd_ctx->lsm.domain.attr.pid;
@@ -226,9 +227,9 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                         * fallback on the 32-bit one,
                         */
                        DBG3("Looking for a kernel consumer at these locations:");
-                       DBG3("  1) %s", the_config.consumerd64_bin_path.value ? : "NULL");
+                       DBG3("  1) %s", the_config.consumerd64_bin_path.value ?: "NULL");
                        DBG3("  2) %s/%s", INSTALL_BIN_PATH, DEFAULT_CONSUMERD_FILE);
-                       DBG3("  3) %s", the_config.consumerd32_bin_path.value ? : "NULL");
+                       DBG3("  3) %s", the_config.consumerd32_bin_path.value ?: "NULL");
                        if (stat(the_config.consumerd64_bin_path.value, &st) == 0) {
                                DBG3("Found location #1");
                                consumer_to_use = the_config.consumerd64_bin_path.value;
@@ -236,7 +237,7 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                DBG3("Found location #2");
                                consumer_to_use = INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE;
                        } else if (the_config.consumerd32_bin_path.value &&
-                                       stat(the_config.consumerd32_bin_path.value, &st) == 0) {
+                                  stat(the_config.consumerd32_bin_path.value, &st) == 0) {
                                DBG3("Found location #3");
                                consumer_to_use = the_config.consumerd32_bin_path.value;
                        } else {
@@ -244,15 +245,18 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                ret = -EINVAL;
                                goto error;
                        }
-                       DBG("Using kernel consumer at: %s",  consumer_to_use);
-                       (void) execl(consumer_to_use, "lttng-consumerd",
-                                       verbosity, "-k", "--consumerd-cmd-sock",
-                                       consumer_data->cmd_unix_sock_path,
-                                       "--consumerd-err-sock",
-                                       consumer_data->err_unix_sock_path,
-                                       "--group",
-                                       the_config.tracing_group_name.value,
-                                       NULL);
+                       DBG("Using kernel consumer at: %s", consumer_to_use);
+                       (void) execl(consumer_to_use,
+                                    "lttng-consumerd",
+                                    verbosity,
+                                    "-k",
+                                    "--consumerd-cmd-sock",
+                                    consumer_data->cmd_unix_sock_path,
+                                    "--consumerd-err-sock",
+                                    consumer_data->err_unix_sock_path,
+                                    "--group",
+                                    the_config.tracing_group_name.value,
+                                    NULL);
                        break;
                case LTTNG_CONSUMER64_UST:
                {
@@ -265,7 +269,8 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                if (!tmp) {
                                        tmp = "";
                                }
-                               tmplen = strlen(the_config.consumerd64_lib_dir.value) + 1 /* : */ + strlen(tmp);
+                               tmplen = strlen(the_config.consumerd64_lib_dir.value) + 1 /* : */ +
+                                       strlen(tmp);
                                tmpnew = zmalloc<char>(tmplen + 1 /* \0 */);
                                if (!tmpnew) {
                                        ret = -ENOMEM;
@@ -284,16 +289,18 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                }
                        }
                        DBG("Using 64-bit UST consumer at: %s",
-                                       the_config.consumerd64_bin_path.value);
+                           the_config.consumerd64_bin_path.value);
                        (void) execl(the_config.consumerd64_bin_path.value,
-                                       "lttng-consumerd", verbosity, "-u",
-                                       "--consumerd-cmd-sock",
-                                       consumer_data->cmd_unix_sock_path,
-                                       "--consumerd-err-sock",
-                                       consumer_data->err_unix_sock_path,
-                                       "--group",
-                                       the_config.tracing_group_name.value,
-                                       NULL);
+                                    "lttng-consumerd",
+                                    verbosity,
+                                    "-u",
+                                    "--consumerd-cmd-sock",
+                                    consumer_data->cmd_unix_sock_path,
+                                    "--consumerd-err-sock",
+                                    consumer_data->err_unix_sock_path,
+                                    "--group",
+                                    the_config.tracing_group_name.value,
+                                    NULL);
                        break;
                }
                case LTTNG_CONSUMER32_UST:
@@ -307,7 +314,8 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                if (!tmp) {
                                        tmp = "";
                                }
-                               tmplen = strlen(the_config.consumerd32_lib_dir.value) + 1 /* : */ + strlen(tmp);
+                               tmplen = strlen(the_config.consumerd32_lib_dir.value) + 1 /* : */ +
+                                       strlen(tmp);
                                tmpnew = zmalloc<char>(tmplen + 1 /* \0 */);
                                if (!tmpnew) {
                                        ret = -ENOMEM;
@@ -326,16 +334,18 @@ static pid_t spawn_consumerd(struct consumer_data *consumer_data)
                                }
                        }
                        DBG("Using 32-bit UST consumer at: %s",
-                                       the_config.consumerd32_bin_path.value);
+                           the_config.consumerd32_bin_path.value);
                        (void) execl(the_config.consumerd32_bin_path.value,
-                                       "lttng-consumerd", verbosity, "-u",
-                                       "--consumerd-cmd-sock",
-                                       consumer_data->cmd_unix_sock_path,
-                                       "--consumerd-err-sock",
-                                       consumer_data->err_unix_sock_path,
-                                       "--group",
-                                       the_config.tracing_group_name.value,
-                                       NULL);
+                                    "lttng-consumerd",
+                                    verbosity,
+                                    "-u",
+                                    "--consumerd-cmd-sock",
+                                    consumer_data->cmd_unix_sock_path,
+                                    "--consumerd-err-sock",
+                                    consumer_data->err_unix_sock_path,
+                                    "--group",
+                                    the_config.tracing_group_name.value,
+                                    NULL);
                        break;
                }
                default:
@@ -441,8 +451,7 @@ static int copy_session_consumer(int domain, struct ltt_session *session)
                if (session->kernel_session->consumer) {
                        consumer_output_put(session->kernel_session->consumer);
                }
-               session->kernel_session->consumer =
-                       consumer_copy_output(session->consumer);
+               session->kernel_session->consumer = consumer_copy_output(session->consumer);
                /* Ease our life a bit for the next part */
                consumer = session->kernel_session->consumer;
                dir_name = DEFAULT_KERNEL_TRACE_DIR;
@@ -455,8 +464,7 @@ static int copy_session_consumer(int domain, struct ltt_session *session)
                if (session->ust_session->consumer) {
                        consumer_output_put(session->ust_session->consumer);
                }
-               session->ust_session->consumer =
-                       consumer_copy_output(session->consumer);
+               session->ust_session->consumer = consumer_copy_output(session->consumer);
                /* Ease our life a bit for the next part */
                consumer = session->ust_session->consumer;
                dir_name = DEFAULT_UST_TRACE_DIR;
@@ -467,8 +475,7 @@ static int copy_session_consumer(int domain, struct ltt_session *session)
        }
 
        /* Append correct directory to subdir */
-       ret = lttng_strncpy(consumer->domain_subdir, dir_name,
-                       sizeof(consumer->domain_subdir));
+       ret = lttng_strncpy(consumer->domain_subdir, dir_name, sizeof(consumer->domain_subdir));
        if (ret) {
                ret = LTTNG_ERR_UNK;
                goto error;
@@ -483,11 +490,10 @@ error:
 /*
  * Create an UST session and add it to the session ust list.
  */
-static int create_ust_session(struct ltt_session *session,
-               const struct lttng_domain *domain)
+static int create_ust_session(struct ltt_session *session, const struct lttng_domain *domain)
 {
        int ret;
-       struct ltt_ust_session *lus = NULL;
+       struct ltt_ust_session *lus = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(domain);
@@ -508,7 +514,7 @@ static int create_ust_session(struct ltt_session *session,
        DBG("Creating UST session");
 
        lus = trace_ust_create_session(session->id);
-       if (lus == NULL) {
+       if (lus == nullptr) {
                ret = LTTNG_ERR_UST_SESS_FAIL;
                goto error;
        }
@@ -520,14 +526,11 @@ static int create_ust_session(struct ltt_session *session,
        lus->live_timer_interval = session->live_timer;
        session->ust_session = lus;
        if (session->shm_path[0]) {
-               strncpy(lus->root_shm_path, session->shm_path,
-                       sizeof(lus->root_shm_path));
+               strncpy(lus->root_shm_path, session->shm_path, sizeof(lus->root_shm_path));
                lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
-               strncpy(lus->shm_path, session->shm_path,
-                       sizeof(lus->shm_path));
+               strncpy(lus->shm_path, session->shm_path, sizeof(lus->shm_path));
                lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
-               strncat(lus->shm_path, "/ust",
-                       sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
+               strncat(lus->shm_path, "/ust", sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
        }
        /* Copy session output to the newly created UST session */
        ret = copy_session_consumer(domain->type, session);
@@ -539,7 +542,7 @@ static int create_ust_session(struct ltt_session *session,
 
 error:
        free(lus);
-       session->ust_session = NULL;
+       session->ust_session = nullptr;
        return ret;
 }
 
@@ -577,7 +580,7 @@ static int create_kernel_session(struct ltt_session *session)
 
 error:
        trace_kernel_destroy_session(session->kernel_session);
-       session->kernel_session = NULL;
+       session->kernel_session = nullptr;
 error_create:
        return ret;
 }
@@ -585,22 +588,20 @@ error_create:
 /*
  * Count number of session permitted by uid/gid.
  */
-static unsigned int lttng_sessions_count(uid_t uid,
-               gid_t gid __attribute__((unused)))
+static unsigned int lttng_sessions_count(uid_t uid, gid_t gid __attribute__((unused)))
 {
        unsigned int i = 0;
        struct ltt_session *session;
        const struct ltt_session_list *session_list = session_get_list();
 
        DBG("Counting number of available session for UID %d", uid);
-       cds_list_for_each_entry(session, &session_list->head, list) {
+       cds_list_for_each_entry (session, &session_list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
                session_lock(session);
                /* Only count the sessions the user can control. */
-               if (session_access_ok(session, uid) &&
-                               !session->destroyed) {
+               if (session_access_ok(session, uid) && !session->destroyed) {
                        i++;
                }
                session_unlock(session);
@@ -610,28 +611,26 @@ static unsigned int lttng_sessions_count(uid_t uid,
 }
 
 static enum lttng_error_code receive_lttng_trigger(struct command_ctx *cmd_ctx,
-               int sock,
-               int *sock_error,
-               struct lttng_trigger **_trigger)
+                                                  int sock,
+                                                  int *sock_error,
+                                                  struct lttng_trigger **_trigger)
 {
        int ret;
        size_t trigger_len;
        ssize_t sock_recv_len;
        enum lttng_error_code ret_code;
        struct lttng_payload trigger_payload;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_trigger *trigger = nullptr;
 
        lttng_payload_init(&trigger_payload);
        trigger_len = (size_t) cmd_ctx->lsm.u.trigger.length;
-       ret = lttng_dynamic_buffer_set_size(
-                       &trigger_payload.buffer, trigger_len);
+       ret = lttng_dynamic_buffer_set_size(&trigger_payload.buffer, trigger_len);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
        }
 
-       sock_recv_len = lttcomm_recv_unix_sock(
-                       sock, trigger_payload.buffer.data, trigger_len);
+       sock_recv_len = lttcomm_recv_unix_sock(sock, trigger_payload.buffer.data, trigger_len);
        if (sock_recv_len < 0 || sock_recv_len != trigger_len) {
                ERR("Failed to receive trigger in command payload");
                *sock_error = 1;
@@ -642,17 +641,18 @@ static enum lttng_error_code receive_lttng_trigger(struct command_ctx *cmd_ctx,
        /* Receive fds, if any. */
        if (cmd_ctx->lsm.fd_count > 0) {
                sock_recv_len = lttcomm_recv_payload_fds_unix_sock(
-                               sock, cmd_ctx->lsm.fd_count, &trigger_payload);
-               if (sock_recv_len > 0 &&
-                               sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
+                       sock, cmd_ctx->lsm.fd_count, &trigger_payload);
+               if (sock_recv_len > 0 && sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
                        ERR("Failed to receive all file descriptors for trigger in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        *sock_error = 1;
                        goto end;
                } else if (sock_recv_len <= 0) {
                        ERR("Failed to receive file descriptors for trigger in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_FATAL;
                        *sock_error = 1;
                        goto end;
@@ -662,11 +662,9 @@ static enum lttng_error_code receive_lttng_trigger(struct command_ctx *cmd_ctx,
        /* Deserialize trigger. */
        {
                struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &trigger_payload, 0, -1);
+                       lttng_payload_view_from_payload(&trigger_payload, 0, -1);
 
-               if (lttng_trigger_create_from_payload(&view, &trigger) !=
-                               trigger_len) {
+               if (lttng_trigger_create_from_payload(&view, &trigger) != trigger_len) {
                        ERR("Invalid trigger received as part of command payload");
                        ret_code = LTTNG_ERR_INVALID_TRIGGER;
                        lttng_trigger_put(trigger);
@@ -683,16 +681,16 @@ end:
 }
 
 static enum lttng_error_code receive_lttng_error_query(struct command_ctx *cmd_ctx,
-               int sock,
-               int *sock_error,
-               struct lttng_error_query **_query)
+                                                      int sock,
+                                                      int *sock_error,
+                                                      struct lttng_error_query **_query)
 {
        int ret;
        size_t query_len;
        ssize_t sock_recv_len;
        enum lttng_error_code ret_code;
        struct lttng_payload query_payload;
-       struct lttng_error_query *query = NULL;
+       struct lttng_error_query *query = nullptr;
 
        lttng_payload_init(&query_payload);
        query_len = (size_t) cmd_ctx->lsm.u.error_query.length;
@@ -702,8 +700,7 @@ static enum lttng_error_code receive_lttng_error_query(struct command_ctx *cmd_c
                goto end;
        }
 
-       sock_recv_len = lttcomm_recv_unix_sock(
-                       sock, query_payload.buffer.data, query_len);
+       sock_recv_len = lttcomm_recv_unix_sock(sock, query_payload.buffer.data, query_len);
        if (sock_recv_len < 0 || sock_recv_len != query_len) {
                ERR("Failed to receive error query in command payload");
                *sock_error = 1;
@@ -714,17 +711,18 @@ static enum lttng_error_code receive_lttng_error_query(struct command_ctx *cmd_c
        /* Receive fds, if any. */
        if (cmd_ctx->lsm.fd_count > 0) {
                sock_recv_len = lttcomm_recv_payload_fds_unix_sock(
-                               sock, cmd_ctx->lsm.fd_count, &query_payload);
-               if (sock_recv_len > 0 &&
-                               sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
+                       sock, cmd_ctx->lsm.fd_count, &query_payload);
+               if (sock_recv_len > 0 && sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
                        ERR("Failed to receive all file descriptors for error query in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        *sock_error = 1;
                        goto end;
                } else if (sock_recv_len <= 0) {
                        ERR("Failed to receive file descriptors for error query in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_FATAL;
                        *sock_error = 1;
                        goto end;
@@ -734,11 +732,9 @@ static enum lttng_error_code receive_lttng_error_query(struct command_ctx *cmd_c
        /* Deserialize error query. */
        {
                struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &query_payload, 0, -1);
+                       lttng_payload_view_from_payload(&query_payload, 0, -1);
 
-               if (lttng_error_query_create_from_payload(&view, &query) !=
-                               query_len) {
+               if (lttng_error_query_create_from_payload(&view, &query) != query_len) {
                        ERR("Invalid error query received as part of command payload");
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        goto end;
@@ -754,27 +750,27 @@ end:
 }
 
 static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
-               int sock,
-               int *sock_error,
-               struct lttng_event **out_event,
-               char **out_filter_expression,
-               struct lttng_bytecode **out_bytecode,
-               struct lttng_event_exclusion **out_exclusion)
+                                                int sock,
+                                                int *sock_error,
+                                                struct lttng_event **out_event,
+                                                char **out_filter_expression,
+                                                struct lttng_bytecode **out_bytecode,
+                                                struct lttng_event_exclusion **out_exclusion)
 {
        int ret;
        size_t event_len;
        ssize_t sock_recv_len;
        enum lttng_error_code ret_code;
        struct lttng_payload event_payload;
-       struct lttng_event *local_event = NULL;
-       char *local_filter_expression = NULL;
-       struct lttng_bytecode *local_bytecode = NULL;
-       struct lttng_event_exclusion *local_exclusion = NULL;
+       struct lttng_event *local_event = nullptr;
+       char *local_filter_expression = nullptr;
+       struct lttng_bytecode *local_bytecode = nullptr;
+       struct lttng_event_exclusion *local_exclusion = nullptr;
 
        lttng_payload_init(&event_payload);
-       if (cmd_ctx->lsm.cmd_type == LTTNG_ENABLE_EVENT) {
+       if (cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT) {
                event_len = (size_t) cmd_ctx->lsm.u.enable.length;
-       } else if (cmd_ctx->lsm.cmd_type == LTTNG_DISABLE_EVENT) {
+       } else if (cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT) {
                event_len = (size_t) cmd_ctx->lsm.u.disable.length;
        } else {
                abort();
@@ -786,8 +782,7 @@ static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
                goto end;
        }
 
-       sock_recv_len = lttcomm_recv_unix_sock(
-                       sock, event_payload.buffer.data, event_len);
+       sock_recv_len = lttcomm_recv_unix_sock(sock, event_payload.buffer.data, event_len);
        if (sock_recv_len < 0 || sock_recv_len != event_len) {
                ERR("Failed to receive event in command payload");
                *sock_error = 1;
@@ -798,17 +793,18 @@ static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
        /* Receive fds, if any. */
        if (cmd_ctx->lsm.fd_count > 0) {
                sock_recv_len = lttcomm_recv_payload_fds_unix_sock(
-                               sock, cmd_ctx->lsm.fd_count, &event_payload);
-               if (sock_recv_len > 0 &&
-                               sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
+                       sock, cmd_ctx->lsm.fd_count, &event_payload);
+               if (sock_recv_len > 0 && sock_recv_len != cmd_ctx->lsm.fd_count * sizeof(int)) {
                        ERR("Failed to receive all file descriptors for event in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        *sock_error = 1;
                        goto end;
                } else if (sock_recv_len <= 0) {
                        ERR("Failed to receive file descriptors for event in command payload: expected fd count = %u, ret = %d",
-                                       cmd_ctx->lsm.fd_count, (int) ret);
+                           cmd_ctx->lsm.fd_count,
+                           (int) ret);
                        ret_code = LTTNG_ERR_FATAL;
                        *sock_error = 1;
                        goto end;
@@ -819,12 +815,13 @@ static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
        {
                ssize_t len;
                struct lttng_payload_view event_view =
-                               lttng_payload_view_from_payload(
-                                               &event_payload, 0, -1);
+                       lttng_payload_view_from_payload(&event_payload, 0, -1);
 
-               len = lttng_event_create_from_payload(&event_view, &local_event,
-                                   &local_exclusion, &local_filter_expression,
-                                   &local_bytecode);
+               len = lttng_event_create_from_payload(&event_view,
+                                                     &local_event,
+                                                     &local_exclusion,
+                                                     &local_filter_expression,
+                                                     &local_bytecode);
 
                if (len < 0) {
                        ERR("Failed to create an event from the received buffer");
@@ -833,7 +830,10 @@ static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
                }
 
                if (len != event_len) {
-                       ERR("Userspace probe location from the received buffer is not the advertised length: header length = %zu" PRIu32 ", payload length = %zd", event_len, len);
+                       ERR("Userspace probe location from the received buffer is not the advertised length: header length = %zu" PRIu32
+                           ", payload length = %zd",
+                           event_len,
+                           len);
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        goto end;
                }
@@ -843,10 +843,10 @@ static enum lttng_error_code receive_lttng_event(struct command_ctx *cmd_ctx,
        *out_exclusion = local_exclusion;
        *out_filter_expression = local_filter_expression;
        *out_bytecode = local_bytecode;
-       local_event = NULL;
-       local_exclusion = NULL;
-       local_filter_expression = NULL;
-       local_bytecode = NULL;
+       local_event = nullptr;
+       local_exclusion = nullptr;
+       local_filter_expression = nullptr;
+       local_bytecode = nullptr;
 
        ret_code = LTTNG_OK;
 
@@ -859,32 +859,29 @@ end:
        return ret_code;
 }
 
-static enum lttng_error_code receive_lttng_event_context(
-               const struct command_ctx *cmd_ctx,
-               int sock,
-               int *sock_error,
-               struct lttng_event_context **out_event_context)
+static enum lttng_error_code
+receive_lttng_event_context(const struct command_ctx *cmd_ctx,
+                           int sock,
+                           int *sock_error,
+                           struct lttng_event_context **out_event_context)
 {
        int ret;
-       const size_t event_context_len =
-                       (size_t) cmd_ctx->lsm.u.context.length;
+       const size_t event_context_len = (size_t) cmd_ctx->lsm.u.context.length;
        ssize_t sock_recv_len;
        enum lttng_error_code ret_code;
        struct lttng_payload event_context_payload;
-       struct lttng_event_context *context = NULL;
+       struct lttng_event_context *context = nullptr;
 
        lttng_payload_init(&event_context_payload);
 
-       ret = lttng_dynamic_buffer_set_size(&event_context_payload.buffer,
-                       event_context_len);
+       ret = lttng_dynamic_buffer_set_size(&event_context_payload.buffer, event_context_len);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
        }
 
-       sock_recv_len = lttcomm_recv_unix_sock(
-                       sock, event_context_payload.buffer.data,
-                       event_context_len);
+       sock_recv_len =
+               lttcomm_recv_unix_sock(sock, event_context_payload.buffer.data, event_context_len);
        if (sock_recv_len < 0 || sock_recv_len != event_context_len) {
                ERR("Failed to receive event context in command payload");
                *sock_error = 1;
@@ -896,11 +893,9 @@ static enum lttng_error_code receive_lttng_event_context(
        {
                ssize_t len;
                struct lttng_payload_view event_context_view =
-                               lttng_payload_view_from_payload(
-                                               &event_context_payload, 0, -1);
+                       lttng_payload_view_from_payload(&event_context_payload, 0, -1);
 
-               len = lttng_event_context_create_from_payload(
-                               &event_context_view, &context);
+               len = lttng_event_context_create_from_payload(&event_context_view, &context);
 
                if (len < 0) {
                        ERR("Failed to create a event context from the received buffer");
@@ -909,14 +904,16 @@ static enum lttng_error_code receive_lttng_event_context(
                }
 
                if (len != event_context_len) {
-                       ERR("Event context from the received buffer is not the advertised length: expected length = %zu, payload length = %zd", event_context_len, len);
+                       ERR("Event context from the received buffer is not the advertised length: expected length = %zu, payload length = %zd",
+                           event_context_len,
+                           len);
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        goto end;
                }
        }
 
        *out_event_context = context;
-       context = NULL;
+       context = nullptr;
        ret_code = LTTNG_OK;
 
 end:
@@ -928,22 +925,21 @@ end:
 /*
  * Version of setup_lttng_msg() without command header.
  */
-static int setup_lttng_msg_no_cmd_header(struct command_ctx *cmd_ctx,
-       void *payload_buf, size_t payload_len)
+static int
+setup_lttng_msg_no_cmd_header(struct command_ctx *cmd_ctx, void *payload_buf, size_t payload_len)
 {
-       return setup_lttng_msg(cmd_ctx, payload_buf, payload_len, NULL, 0);
+       return setup_lttng_msg(cmd_ctx, payload_buf, payload_len, nullptr, 0);
 }
 
 /*
  * Check if the current kernel tracer supports the session rotation feature.
  * Return 1 if it does, 0 otherwise.
  */
-static int check_rotate_compatible(void)
+static int check_rotate_compatible()
 {
        int ret = 1;
 
-       if (the_kernel_tracer_version.major != 2 ||
-                       the_kernel_tracer_version.minor < 11) {
+       if (the_kernel_tracer_version.major != 2 || the_kernel_tracer_version.minor < 11) {
                DBG("Kernel tracer version is not compatible with the rotation feature");
                ret = 0;
        }
@@ -967,8 +963,7 @@ static int send_unix_sock(int sock, struct lttng_payload_view *view)
                goto end;
        }
 
-       ret = lttcomm_send_unix_sock(
-                       sock, view->buffer.data, view->buffer.size);
+       ret = lttcomm_send_unix_sock(sock, view->buffer.data, view->buffer.size);
        if (ret < 0) {
                goto end;
        }
@@ -995,43 +990,50 @@ end:
  * A command may assume the ownership of the socket, in which case its value
  * should be set to -1.
  */
-static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
-               int *sock_error)
+static int process_client_msg(struct command_ctx *cmd_ctx, int *sock, int *sock_error)
 {
        int ret = LTTNG_OK;
        bool need_tracing_session = true;
        bool need_domain;
        bool need_consumerd;
 
+       if (!lttcomm_sessiond_command_is_valid((lttcomm_sessiond_command) cmd_ctx->lsm.cmd_type)) {
+               ERR("Unknown client command received: command id = %" PRIu32,
+                   cmd_ctx->lsm.cmd_type);
+               ret = LTTNG_ERR_UND;
+               goto error;
+       }
+
        DBG("Processing client command '%s\' (%d)",
-               lttcomm_sessiond_command_str((lttcomm_sessiond_command) cmd_ctx->lsm.cmd_type),
-               cmd_ctx->lsm.cmd_type);
+           lttcomm_sessiond_command_str((lttcomm_sessiond_command) cmd_ctx->lsm.cmd_type),
+           cmd_ctx->lsm.cmd_type);
 
        *sock_error = 0;
 
        switch (cmd_ctx->lsm.cmd_type) {
-       case LTTNG_CREATE_SESSION_EXT:
-       case LTTNG_DESTROY_SESSION:
-       case LTTNG_LIST_SESSIONS:
-       case LTTNG_LIST_DOMAINS:
-       case LTTNG_START_TRACE:
-       case LTTNG_STOP_TRACE:
-       case LTTNG_DATA_PENDING:
-       case LTTNG_SNAPSHOT_ADD_OUTPUT:
-       case LTTNG_SNAPSHOT_DEL_OUTPUT:
-       case LTTNG_SNAPSHOT_LIST_OUTPUT:
-       case LTTNG_SNAPSHOT_RECORD:
-       case LTTNG_SAVE_SESSION:
-       case LTTNG_SET_SESSION_SHM_PATH:
-       case LTTNG_REGENERATE_METADATA:
-       case LTTNG_REGENERATE_STATEDUMP:
-       case LTTNG_ROTATE_SESSION:
-       case LTTNG_ROTATION_GET_INFO:
-       case LTTNG_ROTATION_SET_SCHEDULE:
-       case LTTNG_SESSION_LIST_ROTATION_SCHEDULES:
-       case LTTNG_CLEAR_SESSION:
-       case LTTNG_LIST_TRIGGERS:
-       case LTTNG_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT:
+       case LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS:
+       case LTTCOMM_SESSIOND_COMMAND_START_TRACE:
+       case LTTCOMM_SESSIOND_COMMAND_STOP_TRACE:
+       case LTTCOMM_SESSIOND_COMMAND_DATA_PENDING:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_ADD_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_DEL_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_LIST_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_RECORD:
+       case LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_SET_SESSION_SHM_PATH:
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_METADATA:
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_STATEDUMP:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_SET_SCHEDULE:
+       case LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES:
+       case LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS:
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS:
                need_domain = false;
                break;
        default:
@@ -1040,9 +1042,9 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
 
        /* Needs a functioning consumerd? */
        switch (cmd_ctx->lsm.cmd_type) {
-       case LTTNG_REGISTER_TRIGGER:
-       case LTTNG_UNREGISTER_TRIGGER:
-       case LTTNG_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
                need_consumerd = false;
                break;
        default:
@@ -1051,7 +1053,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
        }
 
        if (the_config.no_kernel && need_domain &&
-                       cmd_ctx->lsm.domain.type == LTTNG_DOMAIN_KERNEL) {
+           cmd_ctx->lsm.domain.type == LTTNG_DOMAIN_KERNEL) {
                if (!is_root) {
                        ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
                } else {
@@ -1061,7 +1063,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
        }
 
        /* Deny register consumer if we already have a spawned consumer. */
-       if (cmd_ctx->lsm.cmd_type == LTTNG_REGISTER_CONSUMER) {
+       if (cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER) {
                pthread_mutex_lock(&the_kconsumer_data.pid_mutex);
                if (the_kconsumer_data.pid > 0) {
                        ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
@@ -1076,27 +1078,27 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
         * this here so we don't have to make the call for no payload at each
         * command.
         */
-       switch(cmd_ctx->lsm.cmd_type) {
-       case LTTNG_LIST_SESSIONS:
-       case LTTNG_LIST_TRACEPOINTS:
-       case LTTNG_LIST_TRACEPOINT_FIELDS:
-       case LTTNG_LIST_DOMAINS:
-       case LTTNG_LIST_CHANNELS:
-       case LTTNG_LIST_EVENTS:
-       case LTTNG_LIST_SYSCALLS:
-       case LTTNG_SESSION_LIST_ROTATION_SCHEDULES:
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY:
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
-       case LTTNG_DATA_PENDING:
-       case LTTNG_ROTATE_SESSION:
-       case LTTNG_ROTATION_GET_INFO:
-       case LTTNG_REGISTER_TRIGGER:
-       case LTTNG_LIST_TRIGGERS:
-       case LTTNG_EXECUTE_ERROR_QUERY:
+       switch (cmd_ctx->lsm.cmd_type) {
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_CHANNELS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_EVENTS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS:
+       case LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_POLICY:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
+       case LTTCOMM_SESSIOND_COMMAND_DATA_PENDING:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO:
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS:
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
                break;
        default:
                /* Setup lttng message with no payload */
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, nullptr, 0);
                if (ret < 0) {
                        /* This label does not try to unlock the session */
                        goto init_setup_error;
@@ -1105,16 +1107,17 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
 
        /* Commands that DO NOT need a session. */
        switch (cmd_ctx->lsm.cmd_type) {
-       case LTTNG_CREATE_SESSION_EXT:
-       case LTTNG_LIST_SESSIONS:
-       case LTTNG_LIST_TRACEPOINTS:
-       case LTTNG_LIST_SYSCALLS:
-       case LTTNG_LIST_TRACEPOINT_FIELDS:
-       case LTTNG_SAVE_SESSION:
-       case LTTNG_REGISTER_TRIGGER:
-       case LTTNG_UNREGISTER_TRIGGER:
-       case LTTNG_LIST_TRIGGERS:
-       case LTTNG_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS:
+       case LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS:
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS:
                need_tracing_session = false;
                break;
        default:
@@ -1126,7 +1129,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                 */
                session_lock_list();
                cmd_ctx->session = session_find_by_name(cmd_ctx->lsm.session.name);
-               if (cmd_ctx->session == NULL) {
+               if (cmd_ctx->session == nullptr) {
                        ret = LTTNG_ERR_SESS_NOT_FOUND;
                        goto error;
                } else {
@@ -1143,8 +1146,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
         * code path.
         */
        switch (cmd_ctx->lsm.cmd_type) {
-       case LTTNG_DISABLE_CHANNEL:
-       case LTTNG_DISABLE_EVENT:
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_CHANNEL:
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT:
                switch (cmd_ctx->lsm.domain.type) {
                case LTTNG_DOMAIN_KERNEL:
                        if (!cmd_ctx->session->kernel_session) {
@@ -1193,15 +1196,14 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                }
 
                /* Consumer is in an ERROR state. Report back to client */
-               if (need_consumerd && uatomic_read(&the_kernel_consumerd_state) ==
-                                               CONSUMER_ERROR) {
+               if (need_consumerd && uatomic_read(&the_kernel_consumerd_state) == CONSUMER_ERROR) {
                        ret = LTTNG_ERR_NO_KERNCONSUMERD;
                        goto error;
                }
 
                /* Need a session for kernel command */
                if (need_tracing_session) {
-                       if (cmd_ctx->session->kernel_session == NULL) {
+                       if (cmd_ctx->session->kernel_session == nullptr) {
                                ret = create_kernel_session(cmd_ctx->session);
                                if (ret != LTTNG_OK) {
                                        ret = LTTNG_ERR_KERN_SESS_FAIL;
@@ -1212,7 +1214,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                        /* Start the kernel consumer daemon */
                        pthread_mutex_lock(&the_kconsumer_data.pid_mutex);
                        if (the_kconsumer_data.pid == 0 &&
-                                       cmd_ctx->lsm.cmd_type != LTTNG_REGISTER_CONSUMER) {
+                           cmd_ctx->lsm.cmd_type != LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER) {
                                pthread_mutex_unlock(&the_kconsumer_data.pid_mutex);
                                ret = start_consumerd(&the_kconsumer_data);
                                if (ret < 0) {
@@ -1229,7 +1231,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                         * the consumer output of the session if exist.
                         */
                        ret = consumer_create_socket(&the_kconsumer_data,
-                                       cmd_ctx->session->kernel_session->consumer);
+                                                    cmd_ctx->session->kernel_session->consumer);
                        if (ret < 0) {
                                goto error;
                        }
@@ -1252,16 +1254,14 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                }
 
                /* Consumer is in an ERROR state. Report back to client */
-               if (need_consumerd &&
-                               uatomic_read(&the_ust_consumerd_state) ==
-                                               CONSUMER_ERROR) {
+               if (need_consumerd && uatomic_read(&the_ust_consumerd_state) == CONSUMER_ERROR) {
                        ret = LTTNG_ERR_NO_USTCONSUMERD;
                        goto error;
                }
 
                if (need_tracing_session) {
                        /* Create UST session if none exist. */
-                       if (cmd_ctx->session->ust_session == NULL) {
+                       if (cmd_ctx->session->ust_session == nullptr) {
                                lttng_domain domain = cmd_ctx->lsm.domain;
                                ret = create_ust_session(cmd_ctx->session, &domain);
                                if (ret != LTTNG_OK) {
@@ -1273,8 +1273,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                        /* 64-bit */
                        pthread_mutex_lock(&the_ustconsumer64_data.pid_mutex);
                        if (the_config.consumerd64_bin_path.value &&
-                                       the_ustconsumer64_data.pid == 0 &&
-                                       cmd_ctx->lsm.cmd_type != LTTNG_REGISTER_CONSUMER) {
+                           the_ustconsumer64_data.pid == 0 &&
+                           cmd_ctx->lsm.cmd_type != LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER) {
                                pthread_mutex_unlock(&the_ustconsumer64_data.pid_mutex);
                                ret = start_consumerd(&the_ustconsumer64_data);
                                if (ret < 0) {
@@ -1283,7 +1283,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                                        goto error;
                                }
 
-                               uatomic_set(&the_ust_consumerd64_fd, the_ustconsumer64_data.cmd_sock);
+                               uatomic_set(&the_ust_consumerd64_fd,
+                                           the_ustconsumer64_data.cmd_sock);
                                uatomic_set(&the_ust_consumerd_state, CONSUMER_STARTED);
                        } else {
                                pthread_mutex_unlock(&the_ustconsumer64_data.pid_mutex);
@@ -1294,7 +1295,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                         * since it was set above and can ONLY be set in this thread.
                         */
                        ret = consumer_create_socket(&the_ustconsumer64_data,
-                                       cmd_ctx->session->ust_session->consumer);
+                                                    cmd_ctx->session->ust_session->consumer);
                        if (ret < 0) {
                                goto error;
                        }
@@ -1302,8 +1303,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                        /* 32-bit */
                        pthread_mutex_lock(&the_ustconsumer32_data.pid_mutex);
                        if (the_config.consumerd32_bin_path.value &&
-                                       the_ustconsumer32_data.pid == 0 &&
-                                       cmd_ctx->lsm.cmd_type != LTTNG_REGISTER_CONSUMER) {
+                           the_ustconsumer32_data.pid == 0 &&
+                           cmd_ctx->lsm.cmd_type != LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER) {
                                pthread_mutex_unlock(&the_ustconsumer32_data.pid_mutex);
                                ret = start_consumerd(&the_ustconsumer32_data);
                                if (ret < 0) {
@@ -1312,7 +1313,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                                        goto error;
                                }
 
-                               uatomic_set(&the_ust_consumerd32_fd, the_ustconsumer32_data.cmd_sock);
+                               uatomic_set(&the_ust_consumerd32_fd,
+                                           the_ustconsumer32_data.cmd_sock);
                                uatomic_set(&the_ust_consumerd_state, CONSUMER_STARTED);
                        } else {
                                pthread_mutex_unlock(&the_ustconsumer32_data.pid_mutex);
@@ -1323,7 +1325,7 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
                         * since it was set above and can ONLY be set in this thread.
                         */
                        ret = consumer_create_socket(&the_ustconsumer32_data,
-                                       cmd_ctx->session->ust_session->consumer);
+                                                    cmd_ctx->session->ust_session->consumer);
                        if (ret < 0) {
                                goto error;
                        }
@@ -1336,8 +1338,8 @@ static int process_client_msg(struct command_ctx *cmd_ctx, int *sock,
 skip_domain:
 
        /* Validate consumer daemon state when start/stop trace command */
-       if (cmd_ctx->lsm.cmd_type == LTTNG_START_TRACE ||
-                       cmd_ctx->lsm.cmd_type == LTTNG_STOP_TRACE) {
+       if (cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_START_TRACE ||
+           cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_STOP_TRACE) {
                switch (cmd_ctx->lsm.domain.type) {
                case LTTNG_DOMAIN_NONE:
                        break;
@@ -1368,8 +1370,8 @@ skip_domain:
         */
        if (need_tracing_session) {
                if (!session_access_ok(cmd_ctx->session,
-                               LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds)) ||
-                               cmd_ctx->session->destroyed) {
+                                      LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds)) ||
+                   cmd_ctx->session->destroyed) {
                        ret = LTTNG_ERR_EPERM;
                        goto error;
                }
@@ -1392,12 +1394,11 @@ skip_domain:
 
        /* Process by command type */
        switch (cmd_ctx->lsm.cmd_type) {
-       case LTTNG_ADD_CONTEXT:
+       case LTTCOMM_SESSIOND_COMMAND_ADD_CONTEXT:
        {
-               struct lttng_event_context *event_context = NULL;
+               struct lttng_event_context *event_context = nullptr;
                const enum lttng_error_code ret_code =
-                       receive_lttng_event_context(
-                               cmd_ctx, *sock, sock_error, &event_context);
+                       receive_lttng_event_context(cmd_ctx, *sock, sock_error, &event_context);
 
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
@@ -1408,41 +1409,35 @@ skip_domain:
                lttng_event_context_destroy(event_context);
                break;
        }
-       case LTTNG_DISABLE_CHANNEL:
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_CHANNEL:
        {
-               ret = cmd_disable_channel(cmd_ctx->session, cmd_ctx->lsm.domain.type,
-                               cmd_ctx->lsm.u.disable.channel_name);
+               ret = cmd_disable_channel(cmd_ctx->session,
+                                         cmd_ctx->lsm.domain.type,
+                                         cmd_ctx->lsm.u.disable.channel_name);
                break;
        }
-       case LTTNG_ENABLE_CHANNEL:
+       case LTTCOMM_SESSIOND_COMMAND_ENABLE_CHANNEL:
        {
-               ret = cmd_enable_channel(
-                               cmd_ctx, *sock, the_kernel_poll_pipe[1]);
+               ret = cmd_enable_channel(cmd_ctx, *sock, the_kernel_poll_pipe[1]);
                break;
        }
-       case LTTNG_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE:
-       case LTTNG_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE:
        {
                struct lttng_dynamic_buffer payload;
                struct lttng_buffer_view payload_view;
-               const bool add_value =
-                               cmd_ctx->lsm.cmd_type ==
-                               LTTNG_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE;
+               const bool add_value = cmd_ctx->lsm.cmd_type ==
+                       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE;
                const size_t name_len =
-                               cmd_ctx->lsm.u.process_attr_tracker_add_remove_include_value
-                                               .name_len;
+                       cmd_ctx->lsm.u.process_attr_tracker_add_remove_include_value.name_len;
                const enum lttng_domain_type domain_type =
-                               (enum lttng_domain_type)
-                                               cmd_ctx->lsm.domain.type;
+                       (enum lttng_domain_type) cmd_ctx->lsm.domain.type;
                const enum lttng_process_attr process_attr =
-                               (enum lttng_process_attr) cmd_ctx->lsm.u
-                                               .process_attr_tracker_add_remove_include_value
-                                               .process_attr;
+                       (enum lttng_process_attr) cmd_ctx->lsm.u
+                               .process_attr_tracker_add_remove_include_value.process_attr;
                const enum lttng_process_attr_value_type value_type =
-                               (enum lttng_process_attr_value_type) cmd_ctx
-                                               ->lsm.u
-                                               .process_attr_tracker_add_remove_include_value
-                                               .value_type;
+                       (enum lttng_process_attr_value_type) cmd_ctx->lsm.u
+                               .process_attr_tracker_add_remove_include_value.value_type;
                struct process_attr_value *value;
                enum lttng_error_code ret_code;
                long login_name_max;
@@ -1464,8 +1459,9 @@ skip_domain:
                         * LOGIN_NAME_MAX is defined to 256.
                         */
                        ERR("Rejecting process attribute tracker value %s as the provided exceeds the maximal allowed length: argument length = %zu, maximal length = %ld",
-                                       add_value ? "addition" : "removal",
-                                       name_len, login_name_max);
+                           add_value ? "addition" : "removal",
+                           name_len,
+                           login_name_max);
                        ret = LTTNG_ERR_INVALID;
                        goto error;
                }
@@ -1479,24 +1475,22 @@ skip_domain:
                        ret = lttng_dynamic_buffer_set_size(&payload, name_len);
                        if (ret) {
                                ERR("Failed to allocate buffer to receive payload of %s process attribute tracker value argument",
-                                               add_value ? "add" : "remove");
+                                   add_value ? "add" : "remove");
                                ret = LTTNG_ERR_NOMEM;
                                goto error_add_remove_tracker_value;
                        }
 
-                       ret = lttcomm_recv_unix_sock(
-                                       *sock, payload.data, name_len);
+                       ret = lttcomm_recv_unix_sock(*sock, payload.data, name_len);
                        if (ret <= 0) {
                                ERR("Failed to receive payload of %s process attribute tracker value argument",
-                                               add_value ? "add" : "remove");
+                                   add_value ? "add" : "remove");
                                *sock_error = 1;
                                ret = LTTNG_ERR_INVALID_PROTOCOL;
                                goto error_add_remove_tracker_value;
                        }
                }
 
-               payload_view = lttng_buffer_view_from_dynamic_buffer(
-                               &payload, 0, name_len);
+               payload_view = lttng_buffer_view_from_dynamic_buffer(&payload, 0, name_len);
                if (name_len > 0 && !lttng_buffer_view_is_valid(&payload_view)) {
                        ret = LTTNG_ERR_INVALID_PROTOCOL;
                        goto error_add_remove_tracker_value;
@@ -1507,11 +1501,13 @@ skip_domain:
                 * attribute tracker that is specified and convert the value to
                 * add/remove to the internal sessiond representation.
                 */
-               ret_code = process_attr_value_from_comm(domain_type,
-                               process_attr, value_type,
-                               &cmd_ctx->lsm.u.process_attr_tracker_add_remove_include_value
-                                                .integral_value,
-                               &payload_view, &value);
+               ret_code = process_attr_value_from_comm(
+                       domain_type,
+                       process_attr,
+                       value_type,
+                       &cmd_ctx->lsm.u.process_attr_tracker_add_remove_include_value.integral_value,
+                       &payload_view,
+                       &value);
                if (ret_code != LTTNG_OK) {
                        ret = ret_code;
                        goto error_add_remove_tracker_value;
@@ -1519,39 +1515,34 @@ skip_domain:
 
                if (add_value) {
                        ret = cmd_process_attr_tracker_inclusion_set_add_value(
-                                       cmd_ctx->session, domain_type,
-                                       process_attr, value);
+                               cmd_ctx->session, domain_type, process_attr, value);
                } else {
                        ret = cmd_process_attr_tracker_inclusion_set_remove_value(
-                                       cmd_ctx->session, domain_type,
-                                       process_attr, value);
+                               cmd_ctx->session, domain_type, process_attr, value);
                }
                process_attr_value_destroy(value);
        error_add_remove_tracker_value:
                lttng_dynamic_buffer_reset(&payload);
                break;
        }
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_POLICY:
        {
                enum lttng_tracking_policy tracking_policy;
                const enum lttng_domain_type domain_type =
-                               (enum lttng_domain_type)
-                                               cmd_ctx->lsm.domain.type;
+                       (enum lttng_domain_type) cmd_ctx->lsm.domain.type;
                const enum lttng_process_attr process_attr =
-                               (enum lttng_process_attr) cmd_ctx->lsm.u
-                                               .process_attr_tracker_get_tracking_policy
-                                               .process_attr;
+                       (enum lttng_process_attr) cmd_ctx->lsm.u
+                               .process_attr_tracker_get_tracking_policy.process_attr;
 
                ret = cmd_process_attr_tracker_get_tracking_policy(
-                               cmd_ctx->session, domain_type, process_attr,
-                               &tracking_policy);
+                       cmd_ctx->session, domain_type, process_attr, &tracking_policy);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
                uint32_t tracking_policy_u32 = tracking_policy;
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
-                               &tracking_policy_u32, sizeof(uint32_t));
+               ret = setup_lttng_msg_no_cmd_header(
+                       cmd_ctx, &tracking_policy_u32, sizeof(uint32_t));
                if (ret < 0) {
                        ret = LTTNG_ERR_NOMEM;
                        goto error;
@@ -1559,43 +1550,36 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_PROCESS_ATTR_TRACKER_SET_POLICY:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_SET_POLICY:
        {
                const enum lttng_tracking_policy tracking_policy =
-                               (enum lttng_tracking_policy) cmd_ctx->lsm.u
-                                               .process_attr_tracker_set_tracking_policy
-                                               .tracking_policy;
+                       (enum lttng_tracking_policy) cmd_ctx->lsm.u
+                               .process_attr_tracker_set_tracking_policy.tracking_policy;
                const enum lttng_domain_type domain_type =
-                               (enum lttng_domain_type)
-                                               cmd_ctx->lsm.domain.type;
+                       (enum lttng_domain_type) cmd_ctx->lsm.domain.type;
                const enum lttng_process_attr process_attr =
-                               (enum lttng_process_attr) cmd_ctx->lsm.u
-                                               .process_attr_tracker_set_tracking_policy
-                                               .process_attr;
+                       (enum lttng_process_attr) cmd_ctx->lsm.u
+                               .process_attr_tracker_set_tracking_policy.process_attr;
 
                ret = cmd_process_attr_tracker_set_tracking_policy(
-                               cmd_ctx->session, domain_type, process_attr,
-                               tracking_policy);
+                       cmd_ctx->session, domain_type, process_attr, tracking_policy);
                if (ret != LTTNG_OK) {
                        goto error;
                }
                break;
        }
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
        {
                struct lttng_process_attr_values *values;
                struct lttng_dynamic_buffer reply;
                const enum lttng_domain_type domain_type =
-                               (enum lttng_domain_type)
-                                               cmd_ctx->lsm.domain.type;
+                       (enum lttng_domain_type) cmd_ctx->lsm.domain.type;
                const enum lttng_process_attr process_attr =
-                               (enum lttng_process_attr) cmd_ctx->lsm.u
-                                               .process_attr_tracker_get_inclusion_set
-                                               .process_attr;
+                       (enum lttng_process_attr)
+                               cmd_ctx->lsm.u.process_attr_tracker_get_inclusion_set.process_attr;
 
                ret = cmd_process_attr_tracker_get_inclusion_set(
-                               cmd_ctx->session, domain_type, process_attr,
-                               &values);
+                       cmd_ctx->session, domain_type, process_attr, &values);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -1606,8 +1590,7 @@ skip_domain:
                        goto error_tracker_get_inclusion_set;
                }
 
-               ret = setup_lttng_msg_no_cmd_header(
-                               cmd_ctx, reply.data, reply.size);
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, reply.data, reply.size);
                if (ret < 0) {
                        ret = LTTNG_ERR_NOMEM;
                        goto error_tracker_get_inclusion_set;
@@ -1619,16 +1602,20 @@ skip_domain:
                lttng_dynamic_buffer_reset(&reply);
                break;
        }
-       case LTTNG_ENABLE_EVENT:
-       case LTTNG_DISABLE_EVENT:
+       case LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT:
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT:
        {
                struct lttng_event *event;
                char *filter_expression;
                struct lttng_event_exclusion *exclusions;
                struct lttng_bytecode *bytecode;
-               const enum lttng_error_code ret_code = receive_lttng_event(
-                               cmd_ctx, *sock, sock_error, &event,
-                               &filter_expression, &bytecode, &exclusions);
+               const enum lttng_error_code ret_code = receive_lttng_event(cmd_ctx,
+                                                                          *sock,
+                                                                          sock_error,
+                                                                          &event,
+                                                                          &filter_expression,
+                                                                          &bytecode,
+                                                                          &exclusions);
 
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
@@ -1639,18 +1626,18 @@ skip_domain:
                 * Ownership of filter_expression, exclusions, and bytecode is
                 * always transferred.
                 */
-               ret = cmd_ctx->lsm.cmd_type == LTTNG_ENABLE_EVENT ?
-                               cmd_enable_event(cmd_ctx, event,
-                                               filter_expression, exclusions,
-                                               bytecode,
-                                               the_kernel_poll_pipe[1]) :
-                               cmd_disable_event(cmd_ctx, event,
-                                               filter_expression, bytecode,
-                                               exclusions);
+               ret = cmd_ctx->lsm.cmd_type == LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT ?
+                       cmd_enable_event(cmd_ctx,
+                                        event,
+                                        filter_expression,
+                                        exclusions,
+                                        bytecode,
+                                        the_kernel_poll_pipe[1]) :
+                       cmd_disable_event(cmd_ctx, event, filter_expression, bytecode, exclusions);
                lttng_event_destroy(event);
                break;
        }
-       case LTTNG_LIST_TRACEPOINTS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS:
        {
                enum lttng_error_code ret_code;
                size_t original_payload_size;
@@ -1666,22 +1653,21 @@ skip_domain:
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
                session_lock_list();
-               ret_code = cmd_list_tracepoints(cmd_ctx->lsm.domain.type,
-                               &cmd_ctx->reply_payload);
+               ret_code = cmd_list_tracepoints(cmd_ctx->lsm.domain.type, &cmd_ctx->reply_payload);
                session_unlock_list();
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                               command_header_size - original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - command_header_size -
+                       original_payload_size;
                update_lttng_msg(cmd_ctx, command_header_size, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_LIST_TRACEPOINT_FIELDS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS:
        {
                enum lttng_error_code ret_code;
                size_t original_payload_size;
@@ -1697,22 +1683,22 @@ skip_domain:
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
                session_lock_list();
-               ret_code = cmd_list_tracepoint_fields(
-                               cmd_ctx->lsm.domain.type, &cmd_ctx->reply_payload);
+               ret_code = cmd_list_tracepoint_fields(cmd_ctx->lsm.domain.type,
+                                                     &cmd_ctx->reply_payload);
                session_unlock_list();
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                               command_header_size - original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - command_header_size -
+                       original_payload_size;
                update_lttng_msg(cmd_ctx, command_header_size, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_LIST_SYSCALLS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS:
        {
                enum lttng_error_code ret_code;
                size_t original_payload_size;
@@ -1733,14 +1719,14 @@ skip_domain:
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                               command_header_size - original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - command_header_size -
+                       original_payload_size;
                update_lttng_msg(cmd_ctx, command_header_size, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_SET_CONSUMER_URI:
+       case LTTCOMM_SESSIOND_COMMAND_SET_CONSUMER_URI:
        {
                size_t nb_uri, len;
                struct lttng_uri *uris;
@@ -1754,7 +1740,7 @@ skip_domain:
                }
 
                uris = calloc<lttng_uri>(nb_uri);
-               if (uris == NULL) {
+               if (uris == nullptr) {
                        ret = LTTNG_ERR_FATAL;
                        goto error;
                }
@@ -1776,21 +1762,18 @@ skip_domain:
                        goto error;
                }
 
-
                break;
        }
-       case LTTNG_START_TRACE:
+       case LTTCOMM_SESSIOND_COMMAND_START_TRACE:
        {
                /*
                 * On the first start, if we have a kernel session and we have
                 * enabled time or size-based rotations, we have to make sure
                 * the kernel tracer supports it.
                 */
-               if (!cmd_ctx->session->has_been_started && \
-                               cmd_ctx->session->kernel_session && \
-                               (cmd_ctx->session->rotate_timer_period || \
-                                       cmd_ctx->session->rotate_size) && \
-                               !check_rotate_compatible()) {
+               if (!cmd_ctx->session->has_been_started && cmd_ctx->session->kernel_session &&
+                   (cmd_ctx->session->rotate_timer_period || cmd_ctx->session->rotate_size) &&
+                   !check_rotate_compatible()) {
                        DBG("Kernel tracer version is not compatible with the rotation feature");
                        ret = LTTNG_ERR_ROTATION_WRONG_VERSION;
                        goto error;
@@ -1798,21 +1781,20 @@ skip_domain:
                ret = cmd_start_trace(cmd_ctx->session);
                break;
        }
-       case LTTNG_STOP_TRACE:
+       case LTTCOMM_SESSIOND_COMMAND_STOP_TRACE:
        {
                ret = cmd_stop_trace(cmd_ctx->session);
                break;
        }
-       case LTTNG_DESTROY_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION:
        {
-               ret = cmd_destroy_session(cmd_ctx->session,
-                               the_notification_thread_handle, sock);
+               ret = cmd_destroy_session(cmd_ctx->session, sock);
                break;
        }
-       case LTTNG_LIST_DOMAINS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS:
        {
                ssize_t nb_dom;
-               struct lttng_domain *domains = NULL;
+               struct lttng_domain *domains = nullptr;
 
                nb_dom = cmd_list_domains(cmd_ctx->session, &domains);
                if (nb_dom < 0) {
@@ -1821,8 +1803,8 @@ skip_domain:
                        goto error;
                }
 
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, domains,
-                       nb_dom * sizeof(struct lttng_domain));
+               ret = setup_lttng_msg_no_cmd_header(
+                       cmd_ctx, domains, nb_dom * sizeof(struct lttng_domain));
                free(domains);
 
                if (ret < 0) {
@@ -1832,7 +1814,7 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_LIST_CHANNELS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_CHANNELS:
        {
                enum lttng_error_code ret_code;
                size_t original_payload_size;
@@ -1847,21 +1829,21 @@ skip_domain:
 
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
-               ret_code = cmd_list_channels(cmd_ctx->lsm.domain.type,
-                               cmd_ctx->session, &cmd_ctx->reply_payload);
+               ret_code = cmd_list_channels(
+                       cmd_ctx->lsm.domain.type, cmd_ctx->session, &cmd_ctx->reply_payload);
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                               command_header_size - original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - command_header_size -
+                       original_payload_size;
                update_lttng_msg(cmd_ctx, command_header_size, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_LIST_EVENTS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_EVENTS:
        {
                enum lttng_error_code ret_code;
                size_t original_payload_size;
@@ -1877,36 +1859,34 @@ skip_domain:
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
                ret_code = cmd_list_events(cmd_ctx->lsm.domain.type,
-                               cmd_ctx->session,
-                               cmd_ctx->lsm.u.list.channel_name, &cmd_ctx->reply_payload);
+                                          cmd_ctx->session,
+                                          cmd_ctx->lsm.u.list.channel_name,
+                                          &cmd_ctx->reply_payload);
                if (ret_code != LTTNG_OK) {
                        ret = (int) ret_code;
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                               command_header_size - original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - command_header_size -
+                       original_payload_size;
                update_lttng_msg(cmd_ctx, command_header_size, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_LIST_SESSIONS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS:
        {
                unsigned int nr_sessions;
                lttng_session *sessions_payload = nullptr;
                size_t payload_len = 0;
 
                session_lock_list();
-               nr_sessions = lttng_sessions_count(
-                               LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
-                               LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
+               nr_sessions = lttng_sessions_count(LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
+                                                  LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
 
                if (nr_sessions > 0) {
-                       payload_len = (sizeof(struct lttng_session) *
-                                                     nr_sessions) +
-                                       (sizeof(struct lttng_session_extended) *
-                                                       nr_sessions);
+                       payload_len = (sizeof(struct lttng_session) * nr_sessions) +
+                               (sizeof(struct lttng_session_extended) * nr_sessions);
                        sessions_payload = zmalloc<lttng_session>(payload_len);
                        if (!sessions_payload) {
                                session_unlock_list();
@@ -1914,15 +1894,15 @@ skip_domain:
                                goto setup_error;
                        }
 
-                       cmd_list_lttng_sessions(sessions_payload, nr_sessions,
-                                       LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
-                                       LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
+                       cmd_list_lttng_sessions(sessions_payload,
+                                               nr_sessions,
+                                               LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
+                                               LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
                }
 
                session_unlock_list();
 
-               ret = setup_lttng_msg_no_cmd_header(
-                               cmd_ctx, sessions_payload, payload_len);
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, sessions_payload, payload_len);
                free(sessions_payload);
 
                if (ret < 0) {
@@ -1932,7 +1912,7 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_REGISTER_CONSUMER:
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER:
        {
                struct consumer_data *cdata;
 
@@ -1945,11 +1925,30 @@ skip_domain:
                        goto error;
                }
 
-               ret = cmd_register_consumer(cmd_ctx->session, cmd_ctx->lsm.domain.type,
-                               cmd_ctx->lsm.u.reg.path, cdata);
+               ret = cmd_register_consumer(
+                       cmd_ctx->session, cmd_ctx->lsm.domain.type, cmd_ctx->lsm.u.reg.path, cdata);
+               break;
+       }
+       case LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS:
+       {
+               uint32_t u_status;
+               enum lttng_kernel_tracer_status status;
+
+               ret = cmd_kernel_tracer_status(&status);
+               if (ret != LTTNG_OK) {
+                       goto error;
+               }
+
+               u_status = (uint32_t) status;
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &u_status, 4);
+               if (ret < 0) {
+                       goto error;
+               }
+
+               ret = LTTNG_OK;
                break;
        }
-       case LTTNG_DATA_PENDING:
+       case LTTCOMM_SESSIOND_COMMAND_DATA_PENDING:
        {
                int pending_ret;
                uint8_t pending_ret_byte;
@@ -1970,19 +1969,18 @@ skip_domain:
                         * ret will be set to LTTNG_OK at the end of
                         * this function.
                         */
-               } else if (pending_ret < 0) {
+               } else if (pending_ret <= LTTNG_OK || pending_ret >= LTTNG_ERR_NR) {
                        ret = LTTNG_ERR_UNK;
-                       goto setup_error;
+                       goto error;
                } else {
                        ret = pending_ret;
-                       goto setup_error;
+                       goto error;
                }
 
                pending_ret_byte = (uint8_t) pending_ret;
 
                /* 1 byte to return whether or not data is pending */
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
-                       &pending_ret_byte, 1);
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &pending_ret_byte, 1);
 
                if (ret < 0) {
                        goto setup_error;
@@ -1991,22 +1989,19 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_SNAPSHOT_ADD_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_ADD_OUTPUT:
        {
                uint32_t snapshot_id;
                struct lttcomm_lttng_output_id reply;
                lttng_snapshot_output output = cmd_ctx->lsm.u.snapshot_output.output;
 
-               ret = cmd_snapshot_add_output(cmd_ctx->session,
-                               &output,
-                               &snapshot_id);
+               ret = cmd_snapshot_add_output(cmd_ctx->session, &output, &snapshot_id);
                if (ret != LTTNG_OK) {
                        goto error;
                }
                reply.id = snapshot_id;
 
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply,
-                       sizeof(reply));
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply, sizeof(reply));
                if (ret < 0) {
                        goto setup_error;
                }
@@ -2015,16 +2010,16 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_SNAPSHOT_DEL_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_DEL_OUTPUT:
        {
                lttng_snapshot_output output = cmd_ctx->lsm.u.snapshot_output.output;
                ret = cmd_snapshot_del_output(cmd_ctx->session, &output);
                break;
        }
-       case LTTNG_SNAPSHOT_LIST_OUTPUT:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_LIST_OUTPUT:
        {
                ssize_t nb_output;
-               struct lttng_snapshot_output *outputs = NULL;
+               struct lttng_snapshot_output *outputs = nullptr;
 
                nb_output = cmd_snapshot_list_outputs(cmd_ctx->session, &outputs);
                if (nb_output < 0) {
@@ -2033,8 +2028,8 @@ skip_domain:
                }
 
                LTTNG_ASSERT((nb_output > 0 && outputs) || nb_output == 0);
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, outputs,
-                               nb_output * sizeof(struct lttng_snapshot_output));
+               ret = setup_lttng_msg_no_cmd_header(
+                       cmd_ctx, outputs, nb_output * sizeof(struct lttng_snapshot_output));
                free(outputs);
 
                if (ret < 0) {
@@ -2044,17 +2039,18 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_SNAPSHOT_RECORD:
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_RECORD:
        {
                lttng_snapshot_output output = cmd_ctx->lsm.u.snapshot_record.output;
-               ret = cmd_snapshot_record(cmd_ctx->session,
-                               &output, 0); // RFC: set to zero since it's ignored by cmd_snapshot_record
+               ret = cmd_snapshot_record(cmd_ctx->session, &output, 0); // RFC: set to zero since
+                                                                        // it's ignored by
+                                                                        // cmd_snapshot_record
                break;
        }
-       case LTTNG_CREATE_SESSION_EXT:
+       case LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT:
        {
                struct lttng_dynamic_buffer payload;
-               struct lttng_session_descriptor *return_descriptor = NULL;
+               struct lttng_session_descriptor *return_descriptor = nullptr;
 
                lttng_dynamic_buffer_init(&payload);
                ret = cmd_create_session(cmd_ctx, *sock, &return_descriptor);
@@ -2062,16 +2058,14 @@ skip_domain:
                        goto error;
                }
 
-               ret = lttng_session_descriptor_serialize(return_descriptor,
-                               &payload);
+               ret = lttng_session_descriptor_serialize(return_descriptor, &payload);
                if (ret) {
                        ERR("Failed to serialize session descriptor in reply to \"create session\" command");
                        lttng_session_descriptor_destroy(return_descriptor);
                        ret = LTTNG_ERR_NOMEM;
                        goto error;
                }
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, payload.data,
-                               payload.size);
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, payload.data, payload.size);
                if (ret) {
                        lttng_session_descriptor_destroy(return_descriptor);
                        ret = LTTNG_ERR_NOMEM;
@@ -2082,29 +2076,28 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_SAVE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION:
        {
-               ret = cmd_save_sessions(&cmd_ctx->lsm.u.save_session.attr,
-                       &cmd_ctx->creds);
+               ret = cmd_save_sessions(&cmd_ctx->lsm.u.save_session.attr, &cmd_ctx->creds);
                break;
        }
-       case LTTNG_SET_SESSION_SHM_PATH:
+       case LTTCOMM_SESSIOND_COMMAND_SET_SESSION_SHM_PATH:
        {
                ret = cmd_set_session_shm_path(cmd_ctx->session,
-                               cmd_ctx->lsm.u.set_shm_path.shm_path);
+                                              cmd_ctx->lsm.u.set_shm_path.shm_path);
                break;
        }
-       case LTTNG_REGENERATE_METADATA:
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_METADATA:
        {
                ret = cmd_regenerate_metadata(cmd_ctx->session);
                break;
        }
-       case LTTNG_REGENERATE_STATEDUMP:
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_STATEDUMP:
        {
                ret = cmd_regenerate_statedump(cmd_ctx->session);
                break;
        }
-       case LTTNG_REGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER:
        {
                struct lttng_trigger *payload_trigger;
                struct lttng_trigger *return_trigger;
@@ -2121,18 +2114,18 @@ skip_domain:
                        goto setup_error;
                }
 
-               ret = receive_lttng_trigger(
-                               cmd_ctx, *sock, sock_error, &payload_trigger);
+               ret = receive_lttng_trigger(cmd_ctx, *sock, sock_error, &payload_trigger);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
                original_reply_payload_size = cmd_ctx->reply_payload.buffer.size;
 
-               ret = cmd_register_trigger(&cmd_creds, payload_trigger,
-                               cmd_ctx->lsm.u.trigger.is_trigger_anonymous,
-                               the_notification_thread_handle,
-                               &return_trigger);
+               ret = cmd_register_trigger(&cmd_creds,
+                                          payload_trigger,
+                                          cmd_ctx->lsm.u.trigger.is_trigger_anonymous,
+                                          the_notification_thread_handle,
+                                          &return_trigger);
                if (ret != LTTNG_OK) {
                        lttng_trigger_put(payload_trigger);
                        goto error;
@@ -2147,15 +2140,15 @@ skip_domain:
                        goto error;
                }
 
-               reply_payload_size = cmd_ctx->reply_payload.buffer.size -
-                       original_reply_payload_size;
+               reply_payload_size =
+                       cmd_ctx->reply_payload.buffer.size - original_reply_payload_size;
 
                update_lttng_msg(cmd_ctx, 0, reply_payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_UNREGISTER_TRIGGER:
+       case LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER:
        {
                struct lttng_trigger *payload_trigger;
                const struct lttng_credentials cmd_creds = {
@@ -2163,18 +2156,17 @@ skip_domain:
                        .gid = LTTNG_OPTIONAL_INIT_VALUE(cmd_ctx->creds.gid),
                };
 
-               ret = receive_lttng_trigger(
-                               cmd_ctx, *sock, sock_error, &payload_trigger);
+               ret = receive_lttng_trigger(cmd_ctx, *sock, sock_error, &payload_trigger);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
-               ret = cmd_unregister_trigger(&cmd_creds, payload_trigger,
-                               the_notification_thread_handle);
+               ret = cmd_unregister_trigger(
+                       &cmd_creds, payload_trigger, the_notification_thread_handle);
                lttng_trigger_put(payload_trigger);
                break;
        }
-       case LTTNG_ROTATE_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION:
        {
                struct lttng_rotate_session_return rotate_return;
 
@@ -2187,16 +2179,16 @@ skip_domain:
                        goto error;
                }
 
-               ret = cmd_rotate_session(cmd_ctx->session, &rotate_return,
-                       false,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
+               ret = cmd_rotate_session(cmd_ctx->session,
+                                        &rotate_return,
+                                        false,
+                                        LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
                if (ret < 0) {
                        ret = -ret;
                        goto error;
                }
 
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &rotate_return,
-                               sizeof(rotate_return));
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &rotate_return, sizeof(rotate_return));
                if (ret < 0) {
                        ret = -ret;
                        goto error;
@@ -2205,20 +2197,21 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_ROTATION_GET_INFO:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO:
        {
                struct lttng_rotation_get_info_return get_info_return;
 
                memset(&get_info_return, 0, sizeof(get_info_return));
-               ret = cmd_rotate_get_info(cmd_ctx->session, &get_info_return,
-                               cmd_ctx->lsm.u.get_rotation_info.rotation_id);
+               ret = cmd_rotate_get_info(cmd_ctx->session,
+                                         &get_info_return,
+                                         cmd_ctx->lsm.u.get_rotation_info.rotation_id);
                if (ret < 0) {
                        ret = -ret;
                        goto error;
                }
 
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &get_info_return,
-                               sizeof(get_info_return));
+               ret = setup_lttng_msg_no_cmd_header(
+                       cmd_ctx, &get_info_return, sizeof(get_info_return));
                if (ret < 0) {
                        ret = -ret;
                        goto error;
@@ -2227,7 +2220,7 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_ROTATION_SET_SCHEDULE:
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_SET_SCHEDULE:
        {
                bool set_schedule;
                enum lttng_rotation_schedule_type schedule_type;
@@ -2240,19 +2233,19 @@ skip_domain:
                }
 
                set_schedule = cmd_ctx->lsm.u.rotation_set_schedule.set == 1;
-               schedule_type = (enum lttng_rotation_schedule_type) cmd_ctx->lsm.u.rotation_set_schedule.type;
+               schedule_type = (enum lttng_rotation_schedule_type)
+                                       cmd_ctx->lsm.u.rotation_set_schedule.type;
                value = cmd_ctx->lsm.u.rotation_set_schedule.value;
 
-               ret = cmd_rotation_set_schedule(cmd_ctx->session, set_schedule,
-                               schedule_type, value,
-                               the_notification_thread_handle);
+               ret = cmd_rotation_set_schedule(
+                       cmd_ctx->session, set_schedule, schedule_type, value);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
                break;
        }
-       case LTTNG_SESSION_LIST_ROTATION_SCHEDULES:
+       case LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES:
        {
                lttng_session_list_schedules_return schedules;
 
@@ -2261,8 +2254,7 @@ skip_domain:
                schedules.size.set = !!cmd_ctx->session->rotate_size;
                schedules.size.value = cmd_ctx->session->rotate_size;
 
-               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &schedules,
-                               sizeof(schedules));
+               ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &schedules, sizeof(schedules));
                if (ret < 0) {
                        ret = -ret;
                        goto error;
@@ -2271,14 +2263,14 @@ skip_domain:
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_CLEAR_SESSION:
+       case LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION:
        {
                ret = cmd_clear_session(cmd_ctx->session, sock);
                break;
        }
-       case LTTNG_LIST_TRIGGERS:
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS:
        {
-               struct lttng_triggers *return_triggers = NULL;
+               struct lttng_triggers *return_triggers = nullptr;
                size_t original_payload_size;
                size_t payload_size;
 
@@ -2290,15 +2282,13 @@ skip_domain:
 
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
-               ret = cmd_list_triggers(cmd_ctx, the_notification_thread_handle,
-                               &return_triggers);
+               ret = cmd_list_triggers(cmd_ctx, the_notification_thread_handle, &return_triggers);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
                LTTNG_ASSERT(return_triggers);
-               ret = lttng_triggers_serialize(
-                               return_triggers, &cmd_ctx->reply_payload);
+               ret = lttng_triggers_serialize(return_triggers, &cmd_ctx->reply_payload);
                lttng_triggers_destroy(return_triggers);
                if (ret) {
                        ERR("Failed to serialize triggers in reply to `list triggers` command");
@@ -2306,22 +2296,21 @@ skip_domain:
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                       original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - original_payload_size;
 
                update_lttng_msg(cmd_ctx, 0, payload_size);
 
                ret = LTTNG_OK;
                break;
        }
-       case LTTNG_EXECUTE_ERROR_QUERY:
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
        {
                struct lttng_error_query *query;
                const struct lttng_credentials cmd_creds = {
                        .uid = LTTNG_OPTIONAL_INIT_VALUE(cmd_ctx->creds.uid),
                        .gid = LTTNG_OPTIONAL_INIT_VALUE(cmd_ctx->creds.gid),
                };
-               struct lttng_error_query_results *results = NULL;
+               struct lttng_error_query_results *results = nullptr;
                size_t original_payload_size;
                size_t payload_size;
 
@@ -2333,22 +2322,20 @@ skip_domain:
 
                original_payload_size = cmd_ctx->reply_payload.buffer.size;
 
-               ret = receive_lttng_error_query(
-                               cmd_ctx, *sock, sock_error, &query);
+               ret = receive_lttng_error_query(cmd_ctx, *sock, sock_error, &query);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
-               ret = cmd_execute_error_query(&cmd_creds, query, &results,
-                               the_notification_thread_handle);
+               ret = cmd_execute_error_query(
+                       &cmd_creds, query, &results, the_notification_thread_handle);
                lttng_error_query_destroy(query);
                if (ret != LTTNG_OK) {
                        goto error;
                }
 
                LTTNG_ASSERT(results);
-               ret = lttng_error_query_results_serialize(
-                               results, &cmd_ctx->reply_payload);
+               ret = lttng_error_query_results_serialize(results, &cmd_ctx->reply_payload);
                lttng_error_query_results_destroy(results);
                if (ret) {
                        ERR("Failed to serialize error query result set in reply to `execute error query` command");
@@ -2356,8 +2343,7 @@ skip_domain:
                        goto error;
                }
 
-               payload_size = cmd_ctx->reply_payload.buffer.size -
-                       original_payload_size;
+               payload_size = cmd_ctx->reply_payload.buffer.size - original_payload_size;
 
                update_lttng_msg(cmd_ctx, 0, payload_size);
 
@@ -2373,7 +2359,7 @@ skip_domain:
 error:
        if (cmd_ctx->reply_payload.buffer.size == 0) {
                DBG("Missing llm header, creating one.");
-               if (setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0) < 0) {
+               if (setup_lttng_msg_no_cmd_header(cmd_ctx, nullptr, 0) < 0) {
                        goto setup_error;
                }
        }
@@ -2383,7 +2369,7 @@ setup_error:
        if (cmd_ctx->session) {
                session_unlock(cmd_ctx->session);
                session_put(cmd_ctx->session);
-               cmd_ctx->session = NULL;
+               cmd_ctx->session = nullptr;
        }
        if (need_tracing_session) {
                session_unlock_list();
@@ -2393,16 +2379,14 @@ init_setup_error:
        return ret;
 }
 
-static int create_client_sock(void)
+static int create_client_sock()
 {
        int ret, client_sock;
 
        /* Create client tool unix socket */
-       client_sock = lttcomm_create_unix_sock(
-                       the_config.client_unix_sock_path.value);
+       client_sock = lttcomm_create_unix_sock(the_config.client_unix_sock_path.value);
        if (client_sock < 0) {
-               ERR("Create unix sock failed: %s",
-                               the_config.client_unix_sock_path.value);
+               ERR("Create unix sock failed: %s", the_config.client_unix_sock_path.value);
                ret = -1;
                goto end;
        }
@@ -2411,16 +2395,15 @@ static int create_client_sock(void)
        ret = utils_set_fd_cloexec(client_sock);
        if (ret < 0) {
                ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
-                               "Continuing but note that the consumer daemon will have a "
-                               "reference to this socket on exec()", client_sock);
+                   "Continuing but note that the consumer daemon will have a "
+                   "reference to this socket on exec()",
+                   client_sock);
        }
 
        /* File permission MUST be 660 */
-       ret = chmod(the_config.client_unix_sock_path.value,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       ret = chmod(the_config.client_unix_sock_path.value, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
        if (ret < 0) {
-               ERR("Set file permissions failed: %s",
-                               the_config.client_unix_sock_path.value);
+               ERR("Set file permissions failed: %s", the_config.client_unix_sock_path.value);
                PERROR("chmod");
                (void) lttcomm_close_unix_sock(client_sock);
                ret = -1;
@@ -2450,9 +2433,9 @@ static void thread_init_cleanup(void *data __attribute__((unused)))
  */
 static void *thread_manage_clients(void *data)
 {
-       int sock = -1, ret, i, pollfd, err = -1;
+       int sock = -1, ret, i, err = -1;
        int sock_error;
-       uint32_t revents, nb_fd;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        const int client_sock = thread_state.client_sock;
        struct lttng_pipe *quit_pipe = (lttng_pipe *) data;
@@ -2465,7 +2448,7 @@ static void *thread_manage_clients(void *data)
 
        is_root = (getuid() == 0);
 
-       pthread_cleanup_push(thread_init_cleanup, NULL);
+       pthread_cleanup_push(thread_init_cleanup, nullptr);
 
        rcu_register_thread();
 
@@ -2494,7 +2477,7 @@ static void *thread_manage_clients(void *data)
        }
 
        /* Add thread quit pipe */
-       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                goto error;
        }
@@ -2514,13 +2497,13 @@ static void *thread_manage_clients(void *data)
 
        health_code_update();
 
-       while (1) {
+       while (true) {
                const struct cmd_completion_handler *cmd_completion_handler;
 
                cmd_ctx.creds.uid = UINT32_MAX;
                cmd_ctx.creds.gid = UINT32_MAX;
                cmd_ctx.creds.pid = 0;
-               cmd_ctx.session = NULL;
+               cmd_ctx.session = nullptr;
                lttng_payload_clear(&cmd_ctx.reply_payload);
                cmd_ctx.lttng_msg_size = 0;
 
@@ -2544,25 +2527,28 @@ static void *thread_manage_clients(void *data)
                nb_fd = ret;
 
                for (i = 0; i < nb_fd; i++) {
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       /* Fetch once the poll data. */
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
+                       /* Activity on thread quit pipe, exiting. */
                        if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
+                       }
+
+                       /* Event on the registration socket */
+                       if (revents & LPOLLIN) {
+                               continue;
+                       } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
+                               ERR("Client socket poll error");
+                               goto error;
                        } else {
-                               /* Event on the registration socket */
-                               if (revents & LPOLLIN) {
-                                       continue;
-                               } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-                                       ERR("Client socket poll error");
-                                       goto error;
-                               } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
-                                       goto error;
-                               }
+                               ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                               goto error;
                        }
                }
 
@@ -2595,8 +2581,8 @@ static void *thread_manage_clients(void *data)
                 * the client.
                 */
                DBG("Receiving data from client ...");
-               ret = lttcomm_recv_creds_unix_sock(sock, &cmd_ctx.lsm,
-                               sizeof(struct lttcomm_session_msg), &cmd_ctx.creds);
+               ret = lttcomm_recv_creds_unix_sock(
+                       sock, &cmd_ctx.lsm, sizeof(struct lttcomm_session_msg), &cmd_ctx.creds);
                if (ret != sizeof(struct lttcomm_session_msg)) {
                        DBG("Incomplete recv() from client... continuing");
                        ret = close(sock);
@@ -2619,31 +2605,45 @@ static void *thread_manage_clients(void *data)
                 * informations for the client. The command context struct contains
                 * everything this function may needs.
                 */
-               ret = process_client_msg(&cmd_ctx, &sock, &sock_error);
-               rcu_thread_offline();
-               if (ret < 0) {
-                       if (sock >= 0) {
-                               ret = close(sock);
-                               if (ret) {
-                                       PERROR("close");
+               try {
+                       ret = process_client_msg(&cmd_ctx, &sock, &sock_error);
+                       rcu_thread_offline();
+                       if (ret < 0) {
+                               if (sock >= 0) {
+                                       ret = close(sock);
+                                       if (ret) {
+                                               PERROR("close");
+                                       }
                                }
+                               sock = -1;
+                               /*
+                                * TODO: Inform client somehow of the fatal error. At
+                                * this point, ret < 0 means that a zmalloc failed
+                                * (ENOMEM). Error detected but still accept
+                                * command, unless a socket error has been
+                                * detected.
+                                */
+                               continue;
                        }
-                       sock = -1;
-                       /*
-                        * TODO: Inform client somehow of the fatal error. At
-                        * this point, ret < 0 means that a zmalloc failed
-                        * (ENOMEM). Error detected but still accept
-                        * command, unless a socket error has been
-                        * detected.
-                        */
-                       continue;
+               } catch (const std::bad_alloc& ex) {
+                       WARN_FMT("Failed to allocate memory while handling client request: {}",
+                                ex.what());
+                       ret = LTTNG_ERR_NOMEM;
+               } catch (const lttng::ctl::error& ex) {
+                       WARN_FMT("Client request failed: {}", ex.what());
+                       ret = ex.code();
+               } catch (const std::exception& ex) {
+                       WARN_FMT("Client request failed: {}", ex.what());
+                       ret = LTTNG_ERR_UNK;
                }
 
                if (ret < LTTNG_OK || ret >= LTTNG_ERR_NR) {
                        WARN("Command returned an invalid status code, returning unknown error: "
-                                       "command type = %s (%d), ret = %d",
-                                       lttcomm_sessiond_command_str((lttcomm_sessiond_command) cmd_ctx.lsm.cmd_type),
-                                       cmd_ctx.lsm.cmd_type, ret);
+                            "command type = %s (%d), ret = %d",
+                            lttcomm_sessiond_command_str(
+                                    (lttcomm_sessiond_command) cmd_ctx.lsm.cmd_type),
+                            cmd_ctx.lsm.cmd_type,
+                            ret);
                        ret = LTTNG_ERR_UNK;
                }
 
@@ -2651,8 +2651,7 @@ static void *thread_manage_clients(void *data)
                if (cmd_completion_handler) {
                        enum lttng_error_code completion_code;
 
-                       completion_code = cmd_completion_handler->run(
-                                       cmd_completion_handler->data);
+                       completion_code = cmd_completion_handler->run(cmd_completion_handler->data);
                        if (completion_code != LTTNG_OK) {
                                continue;
                        }
@@ -2662,11 +2661,9 @@ static void *thread_manage_clients(void *data)
 
                if (sock >= 0) {
                        struct lttng_payload_view view =
-                                       lttng_payload_view_from_payload(
-                                                       &cmd_ctx.reply_payload,
-                                                       0, -1);
-                       struct lttcomm_lttng_msg *llm = (typeof(
-                                       llm)) cmd_ctx.reply_payload.buffer.data;
+                               lttng_payload_view_from_payload(&cmd_ctx.reply_payload, 0, -1);
+                       struct lttcomm_lttng_msg *llm =
+                               (typeof(llm)) cmd_ctx.reply_payload.buffer.data;
 
                        LTTNG_ASSERT(cmd_ctx.reply_payload.buffer.size >= sizeof(*llm));
                        LTTNG_ASSERT(cmd_ctx.lttng_msg_size == cmd_ctx.reply_payload.buffer.size);
@@ -2674,9 +2671,9 @@ static void *thread_manage_clients(void *data)
                        llm->fd_count = lttng_payload_view_get_fd_handle_count(&view);
 
                        DBG("Sending response (size: %d, retcode: %s (%d))",
-                                       cmd_ctx.lttng_msg_size,
-                                       lttng_strerror(-llm->ret_code),
-                                       llm->ret_code);
+                           cmd_ctx.lttng_msg_size,
+                           lttng_strerror(-llm->ret_code),
+                           llm->ret_code);
                        ret = send_unix_sock(sock, &view);
                        if (ret < 0) {
                                ERR("Failed to send data back to client");
@@ -2722,11 +2719,10 @@ error_create_poll:
        DBG("Client thread dying");
        lttng_payload_reset(&cmd_ctx.reply_payload);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
-static
-bool shutdown_client_thread(void *thread_data)
+static bool shutdown_client_thread(void *thread_data)
 {
        struct lttng_pipe *client_quit_pipe = (lttng_pipe *) thread_data;
        const int write_fd = lttng_pipe_get_writefd(client_quit_pipe);
@@ -2734,11 +2730,11 @@ bool shutdown_client_thread(void *thread_data)
        return notify_thread_pipe(write_fd) == 1;
 }
 
-struct lttng_thread *launch_client_thread(void)
+struct lttng_thread *launch_client_thread()
 {
        bool thread_running;
        struct lttng_pipe *client_quit_pipe;
-       struct lttng_thread *thread = NULL;
+       struct lttng_thread *thread = nullptr;
        int client_sock_fd = -1;
 
        sem_init(&thread_state.ready, 0, 0);
@@ -2754,16 +2750,16 @@ struct lttng_thread *launch_client_thread(void)
 
        thread_state.client_sock = client_sock_fd;
        thread = lttng_thread_create("Client management",
-                       thread_manage_clients,
-                       shutdown_client_thread,
-                       cleanup_client_thread,
-                       client_quit_pipe);
+                                    thread_manage_clients,
+                                    shutdown_client_thread,
+                                    cleanup_client_thread,
+                                    client_quit_pipe);
        if (!thread) {
                goto error;
        }
        /* The client thread now owns the client sock fd and the quit pipe. */
        client_sock_fd = -1;
-       client_quit_pipe = NULL;
+       client_quit_pipe = nullptr;
 
        /*
         * This thread is part of the threads that need to be fully
@@ -2782,5 +2778,5 @@ error:
        }
        lttng_thread_put(thread);
        cleanup_client_thread(client_quit_pipe);
-       return NULL;
+       return nullptr;
 }
index 49a454dfb025f7d87dbed158a541d38cfeb72a4a..a8d0adc126a9321ec61d23ce40947a0909e74a7c 100644 (file)
@@ -12,6 +12,6 @@
 
 #include "thread.hpp"
 
-struct lttng_thread *launch_client_thread(void);
+struct lttng_thread *launch_client_thread();
 
 #endif /* CLIENT_SESSIOND_H */
index d81a487e940ebeb5bac1b7c58aa0e19ef8a7ef11..bca451ba194d9dcdfb1ae917c5ee790b1ba30838 100644 (file)
@@ -9,15 +9,15 @@
 #include "trace-class.hpp"
 
 lttng::sessiond::trace::clock_class::clock_class(std::string in_name,
-               std::string in_description,
-               nonstd::optional<lttng_uuid> in_uuid,
-               scycles_t in_offset,
-               cycles_t in_frequency) :
-       name{std::move(in_name)},
-       description{std::move(in_description)},
-       uuid{std::move(in_uuid)},
-       offset{in_offset},
-       frequency{in_frequency}
+                                                std::string in_description,
+                                                nonstd::optional<lttng_uuid> in_uuid,
+                                                scycles_t in_offset,
+                                                cycles_t in_frequency) :
+       name{ std::move(in_name) },
+       description{ std::move(in_description) },
+       uuid{ std::move(in_uuid) },
+       offset{ in_offset },
+       frequency{ in_frequency }
 {
 }
 
index 58adc8eac5192a605fd85bdd6b75edd677ddd027..8fc1cb4cd00972860d5e6df9b0e36f071df6510e 100644 (file)
@@ -10,6 +10,7 @@
 
 #include <common/compat/time.hpp>
 #include <common/uuid.hpp>
+
 #include <vendor/optional.hpp>
 
 #include <stddef.h>
@@ -32,21 +33,26 @@ public:
        using scycles_t = int64_t;
        using cuptr = std::unique_ptr<const clock_class>;
 
+       virtual ~clock_class() = default;
+       clock_class(const clock_class&) = delete;
+       clock_class(clock_class&&) = delete;
+       clock_class& operator=(clock_class&&) = delete;
+       clock_class& operator=(const clock_class&) = delete;
+
+       virtual void accept(trace_class_visitor& visitor) const;
+
        const std::string name;
        const std::string description;
        const nonstd::optional<lttng_uuid> uuid;
        const scycles_t offset;
        const cycles_t frequency;
 
-       virtual void accept(trace_class_visitor& visitor) const;
-       virtual ~clock_class() = default;
-
 protected:
        clock_class(std::string name,
-                       std::string description,
-                       nonstd::optional<lttng_uuid> uuid,
-                       scycles_t offset,
-                       cycles_t frequency);
+                   std::string description,
+                   nonstd::optional<lttng_uuid> uuid,
+                   scycles_t offset,
+                   cycles_t frequency);
 };
 
 } /* namespace trace */
index 0b74920556d59230a5bf2a87adcef42590dd1627..b1e0c098594f26004bdf329567a6b6eb08731dac 100644 (file)
@@ -6,14 +6,27 @@
  *
  */
 
-
 #define _LGPL_SOURCE
-#include <algorithm>
-#include <inttypes.h>
-#include <stdio.h>
-#include <sys/stat.h>
-#include <urcu/list.h>
-#include <urcu/uatomic.h>
+#include "agent-thread.hpp"
+#include "agent.hpp"
+#include "buffer-registry.hpp"
+#include "channel.hpp"
+#include "cmd.hpp"
+#include "consumer.hpp"
+#include "event-notifier-error-accounting.hpp"
+#include "event.hpp"
+#include "health-sessiond.hpp"
+#include "kernel-consumer.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "lttng-syscall.hpp"
+#include "notification-thread-commands.hpp"
+#include "notification-thread.hpp"
+#include "rotation-thread.hpp"
+#include "session.hpp"
+#include "timer.hpp"
+#include "tracker.hpp"
+#include "utils.hpp"
 
 #include <common/buffer-view.hpp>
 #include <common/common.hpp>
@@ -27,7 +40,9 @@
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/string-utils/string-utils.hpp>
 #include <common/trace-chunk.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/action.h>
 #include <lttng/channel-internal.hpp>
@@ -40,6 +55,7 @@
 #include <lttng/event-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/event-rule.h>
+#include <lttng/kernel.h>
 #include <lttng/location-internal.hpp>
 #include <lttng/lttng-error.h>
 #include <lttng/rotate-internal.hpp>
 #include <lttng/trigger/trigger-internal.hpp>
 #include <lttng/userspace-probe-internal.hpp>
 
-#include "agent-thread.hpp"
-#include "agent.hpp"
-#include "buffer-registry.hpp"
-#include "channel.hpp"
-#include "cmd.hpp"
-#include "consumer.hpp"
-#include "event-notifier-error-accounting.hpp"
-#include "event.hpp"
-#include "health-sessiond.hpp"
-#include "kernel-consumer.hpp"
-#include "kernel.hpp"
-#include "lttng-sessiond.hpp"
-#include "lttng-syscall.hpp"
-#include "notification-thread-commands.hpp"
-#include "notification-thread.hpp"
-#include "rotate.hpp"
-#include "rotation-thread.hpp"
-#include "session.hpp"
-#include "timer.hpp"
-#include "tracker.hpp"
-#include "utils.hpp"
+#include <algorithm>
+#include <inttypes.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <urcu/list.h>
+#include <urcu/uatomic.h>
 
 /* Sleep for 100ms between each check for the shm path's deletion. */
 #define SESSION_DESTROY_SHM_PATH_CHECK_DELAY_US 100000
@@ -99,10 +100,7 @@ struct destroy_completion_handler {
        struct cmd_completion_handler handler;
        char shm_path[member_sizeof(struct ltt_session, shm_path)];
 } destroy_completion_handler = {
-       .handler = {
-               .run = wait_on_path,
-               .data = destroy_completion_handler.shm_path
-       },
+       .handler = { .run = wait_on_path, .data = destroy_completion_handler.shm_path },
        .shm_path = { 0 },
 };
 
@@ -119,27 +117,26 @@ uint64_t relayd_net_seq_idx;
 static struct cmd_completion_handler *current_completion_handler;
 static int validate_ust_event_name(const char *);
 static int cmd_enable_event_internal(struct ltt_session *session,
-               const struct lttng_domain *domain,
-               char *channel_name, struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               int wpipe);
-static enum lttng_error_code cmd_enable_channel_internal(
-               struct ltt_session *session,
-               const struct lttng_domain *domain,
-               const struct lttng_channel *_attr,
-               int wpipe);
+                                    const struct lttng_domain *domain,
+                                    char *channel_name,
+                                    struct lttng_event *event,
+                                    char *filter_expression,
+                                    struct lttng_bytecode *filter,
+                                    struct lttng_event_exclusion *exclusion,
+                                    int wpipe);
+static enum lttng_error_code cmd_enable_channel_internal(struct ltt_session *session,
+                                                        const struct lttng_domain *domain,
+                                                        const struct lttng_channel *_attr,
+                                                        int wpipe);
 
 /*
  * Create a session path used by list_lttng_sessions for the case that the
  * session consumer is on the network.
  */
-static int build_network_session_path(char *dst, size_t size,
-               struct ltt_session *session)
+static int build_network_session_path(char *dst, size_t size, struct ltt_session *session)
 {
        int ret, kdata_port, udata_port;
-       struct lttng_uri *kuri = NULL, *uuri = NULL, *uri = NULL;
+       struct lttng_uri *kuri = nullptr, *uuri = nullptr, *uri = nullptr;
        char tmp_uurl[PATH_MAX], tmp_urls[PATH_MAX];
 
        LTTNG_ASSERT(session);
@@ -160,7 +157,7 @@ static int build_network_session_path(char *dst, size_t size,
                udata_port = session->ust_session->consumer->dst.net.data.port;
        }
 
-       if (uuri == NULL && kuri == NULL) {
+       if (uuri == nullptr && kuri == nullptr) {
                uri = &session->consumer->dst.net.control;
                kdata_port = session->consumer->dst.net.data.port;
        } else if (kuri && uuri) {
@@ -176,9 +173,9 @@ static int build_network_session_path(char *dst, size_t size,
                } else {
                        uri = kuri;
                }
-       } else if (kuri && uuri == NULL) {
+       } else if (kuri && uuri == nullptr) {
                uri = kuri;
-       } else if (uuri && kuri == NULL) {
+       } else if (uuri && kuri == nullptr) {
                uri = uuri;
        }
 
@@ -192,8 +189,13 @@ static int build_network_session_path(char *dst, size_t size,
         * to print.
         */
        if (*tmp_uurl != '\0') {
-               ret = snprintf(dst, size, "[K]: %s [data: %d] -- [U]: %s [data: %d]",
-                               tmp_urls, kdata_port, tmp_uurl, udata_port);
+               ret = snprintf(dst,
+                              size,
+                              "[K]: %s [data: %d] -- [U]: %s [data: %d]",
+                              tmp_urls,
+                              kdata_port,
+                              tmp_uurl,
+                              udata_port);
        } else {
                int dport;
                if (kuri || (!kuri && !uuri)) {
@@ -214,8 +216,9 @@ error:
  * lost packets).
  */
 static int get_kernel_runtime_stats(struct ltt_session *session,
-               struct ltt_kernel_channel *kchan, uint64_t *discarded_events,
-               uint64_t *lost_packets)
+                                   struct ltt_kernel_channel *kchan,
+                                   uint64_t *discarded_events,
+                                   uint64_t *lost_packets)
 {
        int ret;
 
@@ -226,16 +229,14 @@ static int get_kernel_runtime_stats(struct ltt_session *session,
                goto end;
        }
 
-       ret = consumer_get_discarded_events(session->id, kchan->key,
-                       session->kernel_session->consumer,
-                       discarded_events);
+       ret = consumer_get_discarded_events(
+               session->id, kchan->key, session->kernel_session->consumer, discarded_events);
        if (ret < 0) {
                goto end;
        }
 
-       ret = consumer_get_lost_packets(session->id, kchan->key,
-                       session->kernel_session->consumer,
-                       lost_packets);
+       ret = consumer_get_lost_packets(
+               session->id, kchan->key, session->kernel_session->consumer, lost_packets);
        if (ret < 0) {
                goto end;
        }
@@ -249,8 +250,9 @@ end:
  * lost packets).
  */
 static int get_ust_runtime_stats(struct ltt_session *session,
-               struct ltt_ust_channel *uchan, uint64_t *discarded_events,
-               uint64_t *lost_packets)
+                                struct ltt_ust_channel *uchan,
+                                uint64_t *discarded_events,
+                                uint64_t *lost_packets)
 {
        int ret;
        struct ltt_ust_session *usess;
@@ -273,17 +275,19 @@ static int get_ust_runtime_stats(struct ltt_session *session,
 
        if (usess->buffer_type == LTTNG_BUFFER_PER_UID) {
                ret = ust_app_uid_get_channel_runtime_stats(usess->id,
-                               &usess->buffer_reg_uid_list,
-                               usess->consumer, uchan->id,
-                               uchan->attr.overwrite,
-                               discarded_events,
-                               lost_packets);
+                                                           &usess->buffer_reg_uid_list,
+                                                           usess->consumer,
+                                                           uchan->id,
+                                                           uchan->attr.overwrite,
+                                                           discarded_events,
+                                                           lost_packets);
        } else if (usess->buffer_type == LTTNG_BUFFER_PER_PID) {
                ret = ust_app_pid_get_channel_runtime_stats(usess,
-                               uchan, usess->consumer,
-                               uchan->attr.overwrite,
-                               discarded_events,
-                               lost_packets);
+                                                           uchan,
+                                                           usess->consumer,
+                                                           uchan->attr.overwrite,
+                                                           discarded_events,
+                                                           lost_packets);
                if (ret < 0) {
                        goto end;
                }
@@ -305,9 +309,9 @@ end:
  *
  * Return number of events in list on success or else a negative value.
  */
-static enum lttng_error_code list_lttng_agent_events(
-               struct agent *agt, struct lttng_payload *reply_payload,
-               unsigned int *nb_events)
+static enum lttng_error_code list_lttng_agent_events(struct agent *agt,
+                                                    struct lttng_payload *reply_payload,
+                                                    unsigned int *nb_events)
 {
        enum lttng_error_code ret_code;
        int ret = 0;
@@ -321,7 +325,6 @@ static enum lttng_error_code list_lttng_agent_events(
 
        DBG3("Listing agent events");
 
-       rcu_read_lock();
        agent_event_count = lttng_ht_get_count(agt->events);
        if (agent_event_count == 0) {
                /* Early exit. */
@@ -335,39 +338,46 @@ static enum lttng_error_code list_lttng_agent_events(
 
        local_nb_events = (unsigned int) agent_event_count;
 
-       cds_lfht_for_each_entry(agt->events->ht, &iter.iter, event, node.node) {
-               struct lttng_event *tmp_event = lttng_event_create();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (!tmp_event) {
-                       ret_code = LTTNG_ERR_NOMEM;
-                       goto error;
-               }
+               cds_lfht_for_each_entry (agt->events->ht, &iter.iter, event, node.node) {
+                       struct lttng_event *tmp_event = lttng_event_create();
 
-               if (lttng_strncpy(tmp_event->name, event->name, sizeof(tmp_event->name))) {
-                       lttng_event_destroy(tmp_event);
-                       ret_code = LTTNG_ERR_FATAL;
-                       goto error;
-               }
-               
-               tmp_event->name[sizeof(tmp_event->name) - 1] = '\0';
-               tmp_event->enabled = !!event->enabled_count;
-               tmp_event->loglevel = event->loglevel_value;
-               tmp_event->loglevel_type = event->loglevel_type;
+                       if (!tmp_event) {
+                               ret_code = LTTNG_ERR_NOMEM;
+                               goto error;
+                       }
 
-               ret = lttng_event_serialize(tmp_event, 0, NULL,
-                               event->filter_expression, 0, NULL, reply_payload);
-               lttng_event_destroy(tmp_event);
-               if (ret) {
-                       ret_code = LTTNG_ERR_FATAL;
-                       goto error;
+                       if (lttng_strncpy(tmp_event->name, event->name, sizeof(tmp_event->name))) {
+                               lttng_event_destroy(tmp_event);
+                               ret_code = LTTNG_ERR_FATAL;
+                               goto error;
+                       }
+
+                       tmp_event->name[sizeof(tmp_event->name) - 1] = '\0';
+                       tmp_event->enabled = !!event->enabled_count;
+                       tmp_event->loglevel = event->loglevel_value;
+                       tmp_event->loglevel_type = event->loglevel_type;
+
+                       ret = lttng_event_serialize(tmp_event,
+                                                   0,
+                                                   nullptr,
+                                                   event->filter_expression,
+                                                   0,
+                                                   nullptr,
+                                                   reply_payload);
+                       lttng_event_destroy(tmp_event);
+                       if (ret) {
+                               ret_code = LTTNG_ERR_FATAL;
+                               goto error;
+                       }
                }
        }
-
 end:
        ret_code = LTTNG_OK;
        *nb_events = local_nb_events;
 error:
-       rcu_read_unlock();
        return ret_code;
 }
 
@@ -375,9 +385,9 @@ error:
  * Create a list of ust global domain events.
  */
 static enum lttng_error_code list_lttng_ust_global_events(char *channel_name,
-               struct ltt_ust_domain_global *ust_global,
-               struct lttng_payload *reply_payload,
-               unsigned int *nb_events)
+                                                         struct ltt_ust_domain_global *ust_global,
+                                                         struct lttng_payload *reply_payload,
+                                                         unsigned int *nb_events)
 {
        enum lttng_error_code ret_code;
        int ret;
@@ -393,11 +403,11 @@ static enum lttng_error_code list_lttng_ust_global_events(char *channel_name,
 
        DBG("Listing UST global events for channel %s", channel_name);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        lttng_ht_lookup(ust_global->channels, (void *) channel_name, &iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                ret_code = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                goto error;
        }
@@ -420,8 +430,8 @@ static enum lttng_error_code list_lttng_ust_global_events(char *channel_name,
 
        DBG3("Listing UST global %d events", *nb_events);
 
-       cds_lfht_for_each_entry(uchan->events->ht, &iter.iter, uevent, node.node) {
-               struct lttng_event *tmp_event = NULL;
+       cds_lfht_for_each_entry (uchan->events->ht, &iter.iter, uevent, node.node) {
+               struct lttng_event *tmp_event = nullptr;
 
                if (uevent->internal) {
                        /* This event should remain hidden from clients */
@@ -435,8 +445,7 @@ static enum lttng_error_code list_lttng_ust_global_events(char *channel_name,
                        goto error;
                }
 
-               if (lttng_strncpy(tmp_event->name, uevent->attr.name,
-                               LTTNG_SYMBOL_NAME_LEN)) {
+               if (lttng_strncpy(tmp_event->name, uevent->attr.name, LTTNG_SYMBOL_NAME_LEN)) {
                        ret_code = LTTNG_ERR_FATAL;
                        lttng_event_destroy(tmp_event);
                        goto error;
@@ -476,13 +485,26 @@ static enum lttng_error_code list_lttng_ust_global_events(char *channel_name,
                        tmp_event->exclusion = 1;
                }
 
+               std::vector<const char *> exclusion_names;
+               if (uevent->exclusion) {
+                       for (int i = 0; i < uevent->exclusion->count; i++) {
+                               exclusion_names.emplace_back(
+                                       LTTNG_EVENT_EXCLUSION_NAME_AT(uevent->exclusion, i));
+                       }
+               }
+
                /*
                 * We do not care about the filter bytecode and the fd from the
                 * userspace_probe_location.
                 */
-               ret = lttng_event_serialize(tmp_event, uevent->exclusion ? uevent->exclusion->count : 0,
-                               uevent->exclusion ? (char **) uevent->exclusion ->names : NULL,
-                               uevent->filter_expression, 0, NULL, reply_payload);
+               ret = lttng_event_serialize(tmp_event,
+                                           exclusion_names.size(),
+                                           exclusion_names.size() ? exclusion_names.data() :
+                                                                    nullptr,
+                                           uevent->filter_expression,
+                                           0,
+                                           nullptr,
+                                           reply_payload);
                lttng_event_destroy(tmp_event);
                if (ret) {
                        ret_code = LTTNG_ERR_FATAL;
@@ -495,7 +517,6 @@ end:
        ret_code = LTTNG_OK;
        *nb_events = local_nb_events;
 error:
-       rcu_read_unlock();
        return ret_code;
 }
 
@@ -503,9 +524,9 @@ error:
  * Fill lttng_event array of all kernel events in the channel.
  */
 static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
-               struct ltt_kernel_session *kernel_session,
-               struct lttng_payload *reply_payload,
-               unsigned int *nb_events)
+                                                     struct ltt_kernel_session *kernel_session,
+                                                     struct lttng_payload *reply_payload,
+                                                     unsigned int *nb_events)
 {
        enum lttng_error_code ret_code;
        int ret;
@@ -515,7 +536,7 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
        assert(reply_payload);
 
        kchan = trace_kernel_get_channel_by_name(channel_name, kernel_session);
-       if (kchan == NULL) {
+       if (kchan == nullptr) {
                ret_code = LTTNG_ERR_KERN_CHAN_NOT_FOUND;
                goto end;
        }
@@ -530,7 +551,7 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
        }
 
        /* Kernel channels */
-       cds_list_for_each_entry(event, &kchan->events_list.head , list) {
+       cds_list_for_each_entry (event, &kchan->events_list.head, list) {
                struct lttng_event *tmp_event = lttng_event_create();
 
                if (!tmp_event) {
@@ -542,7 +563,6 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
                        lttng_event_destroy(tmp_event);
                        ret_code = LTTNG_ERR_FATAL;
                        goto end;
-
                }
 
                tmp_event->name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
@@ -555,21 +575,24 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
                        break;
                case LTTNG_KERNEL_ABI_KRETPROBE:
                        tmp_event->type = LTTNG_EVENT_FUNCTION;
-                       memcpy(&tmp_event->attr.probe, &event->event->u.kprobe,
-                                       sizeof(struct lttng_kernel_abi_kprobe));
+                       memcpy(&tmp_event->attr.probe,
+                              &event->event->u.kprobe,
+                              sizeof(struct lttng_kernel_abi_kprobe));
                        break;
                case LTTNG_KERNEL_ABI_KPROBE:
                        tmp_event->type = LTTNG_EVENT_PROBE;
-                       memcpy(&tmp_event->attr.probe, &event->event->u.kprobe,
-                                       sizeof(struct lttng_kernel_abi_kprobe));
+                       memcpy(&tmp_event->attr.probe,
+                              &event->event->u.kprobe,
+                              sizeof(struct lttng_kernel_abi_kprobe));
                        break;
                case LTTNG_KERNEL_ABI_UPROBE:
                        tmp_event->type = LTTNG_EVENT_USERSPACE_PROBE;
                        break;
                case LTTNG_KERNEL_ABI_FUNCTION:
                        tmp_event->type = LTTNG_EVENT_FUNCTION;
-                       memcpy(&(tmp_event->attr.ftrace), &event->event->u.ftrace,
-                                       sizeof(struct lttng_kernel_abi_function));
+                       memcpy(&(tmp_event->attr.ftrace),
+                              &event->event->u.ftrace,
+                              sizeof(struct lttng_kernel_abi_function));
                        break;
                case LTTNG_KERNEL_ABI_NOOP:
                        tmp_event->type = LTTNG_EVENT_NOOP;
@@ -586,8 +609,8 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
 
                if (event->userspace_probe_location) {
                        struct lttng_userspace_probe_location *location_copy =
-                                       lttng_userspace_probe_location_copy(
-                                                       event->userspace_probe_location);
+                               lttng_userspace_probe_location_copy(
+                                       event->userspace_probe_location);
 
                        if (!location_copy) {
                                lttng_event_destroy(tmp_event);
@@ -595,19 +618,17 @@ static enum lttng_error_code list_lttng_kernel_events(char *channel_name,
                                goto end;
                        }
 
-                       ret = lttng_event_set_userspace_probe_location(
-                                       tmp_event, location_copy);
+                       ret = lttng_event_set_userspace_probe_location(tmp_event, location_copy);
                        if (ret) {
                                lttng_event_destroy(tmp_event);
-                               lttng_userspace_probe_location_destroy(
-                                               location_copy);
+                               lttng_userspace_probe_location_destroy(location_copy);
                                ret_code = LTTNG_ERR_INVALID;
                                goto end;
                        }
                }
 
-               ret = lttng_event_serialize(tmp_event, 0, NULL,
-                               event->filter_expression, 0, NULL, reply_payload);
+               ret = lttng_event_serialize(
+                       tmp_event, 0, nullptr, event->filter_expression, 0, nullptr, reply_payload);
                lttng_event_destroy(tmp_event);
                if (ret) {
                        ret_code = LTTNG_ERR_FATAL;
@@ -624,17 +645,17 @@ end:
  * Add URI so the consumer output object. Set the correct path depending on the
  * domain adding the default trace directory.
  */
-static enum lttng_error_code add_uri_to_consumer(
-               const struct ltt_session *session,
-               struct consumer_output *consumer,
-               struct lttng_uri *uri, enum lttng_domain_type domain)
+static enum lttng_error_code add_uri_to_consumer(const struct ltt_session *session,
+                                                struct consumer_output *consumer,
+                                                struct lttng_uri *uri,
+                                                enum lttng_domain_type domain)
 {
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
 
        LTTNG_ASSERT(uri);
 
-       if (consumer == NULL) {
+       if (consumer == nullptr) {
                DBG("No consumer detected. Don't add URI. Stopping.");
                ret_code = LTTNG_ERR_NO_CONSUMER;
                goto error;
@@ -643,13 +664,13 @@ static enum lttng_error_code add_uri_to_consumer(
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
                ret = lttng_strncpy(consumer->domain_subdir,
-                               DEFAULT_KERNEL_TRACE_DIR,
-                               sizeof(consumer->domain_subdir));
+                                   DEFAULT_KERNEL_TRACE_DIR,
+                                   sizeof(consumer->domain_subdir));
                break;
        case LTTNG_DOMAIN_UST:
                ret = lttng_strncpy(consumer->domain_subdir,
-                               DEFAULT_UST_TRACE_DIR,
-                               sizeof(consumer->domain_subdir));
+                                   DEFAULT_UST_TRACE_DIR,
+                                   sizeof(consumer->domain_subdir));
                break;
        default:
                /*
@@ -657,8 +678,7 @@ static enum lttng_error_code add_uri_to_consumer(
                 * tracing session consumer object which in this case there is
                 * no subdir.
                 */
-               memset(consumer->domain_subdir, 0,
-                               sizeof(consumer->domain_subdir));
+               memset(consumer->domain_subdir, 0, sizeof(consumer->domain_subdir));
                ret = 0;
        }
        if (ret) {
@@ -674,9 +694,8 @@ static enum lttng_error_code add_uri_to_consumer(
 
                if (consumer->type == CONSUMER_DST_NET) {
                        if ((uri->stype == LTTNG_STREAM_CONTROL &&
-                               consumer->dst.net.control_isset) ||
-                               (uri->stype == LTTNG_STREAM_DATA &&
-                               consumer->dst.net.data_isset)) {
+                            consumer->dst.net.control_isset) ||
+                           (uri->stype == LTTNG_STREAM_DATA && consumer->dst.net.data_isset)) {
                                ret_code = LTTNG_ERR_URL_EXIST;
                                goto error;
                        }
@@ -703,13 +722,12 @@ static enum lttng_error_code add_uri_to_consumer(
                        ret_code = LTTNG_ERR_INVALID;
                        goto error;
                }
-               DBG2("Setting trace directory path from URI to %s",
-                               uri->dst.path);
+               DBG2("Setting trace directory path from URI to %s", uri->dst.path);
                memset(&consumer->dst, 0, sizeof(consumer->dst));
 
                ret = lttng_strncpy(consumer->dst.session_root_path,
-                               uri->dst.path,
-                               sizeof(consumer->dst.session_root_path));
+                                   uri->dst.path,
+                                   sizeof(consumer->dst.session_root_path));
                if (ret) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto error;
@@ -734,11 +752,11 @@ static int init_kernel_tracing(struct ltt_kernel_session *session)
 
        LTTNG_ASSERT(session);
 
-       rcu_read_lock();
+       if (session->consumer_fds_sent == 0 && session->consumer != nullptr) {
+               lttng::urcu::read_lock_guard read_lock;
 
-       if (session->consumer_fds_sent == 0 && session->consumer != NULL) {
-               cds_lfht_for_each_entry(session->consumer->socks->ht, &iter.iter,
-                               socket, node.node) {
+               cds_lfht_for_each_entry (
+                       session->consumer->socks->ht, &iter.iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
                        ret = kernel_consumer_send_session(socket, session);
                        pthread_mutex_unlock(socket->lock);
@@ -750,7 +768,6 @@ static int init_kernel_tracing(struct ltt_kernel_session *session)
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -761,15 +778,15 @@ error:
  * Else, it remains untouched and an LTTng error code is returned.
  */
 static enum lttng_error_code create_connect_relayd(struct lttng_uri *uri,
-               struct lttcomm_relayd_sock **relayd_sock,
-               struct consumer_output *consumer)
+                                                  struct lttcomm_relayd_sock **relayd_sock,
+                                                  struct consumer_output *consumer)
 {
        int ret;
        enum lttng_error_code status = LTTNG_OK;
        struct lttcomm_relayd_sock *rsock;
 
-       rsock = lttcomm_alloc_relayd_sock(uri, RELAYD_VERSION_COMM_MAJOR,
-                       RELAYD_VERSION_COMM_MINOR);
+       rsock = lttcomm_alloc_relayd_sock(
+               uri, RELAYD_VERSION_COMM_MAJOR, RELAYD_VERSION_COMM_MINOR);
        if (!rsock) {
                status = LTTNG_ERR_FATAL;
                goto error;
@@ -807,8 +824,7 @@ static enum lttng_error_code create_connect_relayd(struct lttng_uri *uri,
                }
                consumer->relay_major_version = rsock->major;
                consumer->relay_minor_version = rsock->minor;
-               ret = relayd_get_configuration(rsock, 0,
-                               &result_flags);
+               ret = relayd_get_configuration(rsock, 0, &result_flags);
                if (ret < 0) {
                        ERR("Unable to get relayd configuration");
                        status = LTTNG_ERR_RELAYD_CONNECT_FAIL;
@@ -846,19 +862,20 @@ error:
  *
  * Returns LTTNG_OK on success or an LTTng error code on failure.
  */
-static enum lttng_error_code send_consumer_relayd_socket(
-               unsigned int session_id,
-               struct lttng_uri *relayd_uri,
-               struct consumer_output *consumer,
-               struct consumer_socket *consumer_sock,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               const uint64_t *current_chunk_id,
-               time_t session_creation_time,
-               bool session_name_contains_creation_time)
+static enum lttng_error_code send_consumer_relayd_socket(unsigned int session_id,
+                                                        struct lttng_uri *relayd_uri,
+                                                        struct consumer_output *consumer,
+                                                        struct consumer_socket *consumer_sock,
+                                                        const char *session_name,
+                                                        const char *hostname,
+                                                        const char *base_path,
+                                                        int session_live_timer,
+                                                        const uint64_t *current_chunk_id,
+                                                        time_t session_creation_time,
+                                                        bool session_name_contains_creation_time)
 {
        int ret;
-       struct lttcomm_relayd_sock *rsock = NULL;
+       struct lttcomm_relayd_sock *rsock = nullptr;
        enum lttng_error_code status;
 
        /* Connect to relayd and make version check if uri is the control. */
@@ -881,11 +898,18 @@ static enum lttng_error_code send_consumer_relayd_socket(
        }
 
        /* Send relayd socket to consumer. */
-       ret = consumer_send_relayd_socket(consumer_sock, rsock, consumer,
-                       relayd_uri->stype, session_id,
-                       session_name, hostname, base_path,
-                       session_live_timer, current_chunk_id,
-                       session_creation_time, session_name_contains_creation_time);
+       ret = consumer_send_relayd_socket(consumer_sock,
+                                         rsock,
+                                         consumer,
+                                         relayd_uri->stype,
+                                         session_id,
+                                         session_name,
+                                         hostname,
+                                         base_path,
+                                         session_live_timer,
+                                         current_chunk_id,
+                                         session_creation_time,
+                                         session_name_contains_creation_time);
        if (ret < 0) {
                status = LTTNG_ERR_ENABLE_CONSUMER_FAIL;
                goto close_sock;
@@ -910,7 +934,7 @@ close_sock:
                 * since the relayd connection failed thus making any tracing or/and
                 * streaming not usable.
                 */
-               consumer->enabled = 0;
+               consumer->enabled = false;
        }
        (void) relayd_close(rsock);
        free(rsock);
@@ -928,12 +952,16 @@ relayd_comm_error:
  *
  * Returns LTTNG_OK, or an LTTng error code on failure.
  */
-static enum lttng_error_code send_consumer_relayd_sockets(
-               unsigned int session_id, struct consumer_output *consumer,
-               struct consumer_socket *sock, const char *session_name,
-               const char *hostname, const char *base_path, int session_live_timer,
-               const uint64_t *current_chunk_id, time_t session_creation_time,
-               bool session_name_contains_creation_time)
+static enum lttng_error_code send_consumer_relayd_sockets(unsigned int session_id,
+                                                         struct consumer_output *consumer,
+                                                         struct consumer_socket *sock,
+                                                         const char *session_name,
+                                                         const char *hostname,
+                                                         const char *base_path,
+                                                         int session_live_timer,
+                                                         const uint64_t *current_chunk_id,
+                                                         time_t session_creation_time,
+                                                         bool session_name_contains_creation_time)
 {
        enum lttng_error_code status = LTTNG_OK;
 
@@ -943,10 +971,16 @@ static enum lttng_error_code send_consumer_relayd_sockets(
        /* Sending control relayd socket. */
        if (!sock->control_sock_sent) {
                status = send_consumer_relayd_socket(session_id,
-                               &consumer->dst.net.control, consumer, sock,
-                               session_name, hostname, base_path, session_live_timer,
-                               current_chunk_id, session_creation_time,
-                               session_name_contains_creation_time);
+                                                    &consumer->dst.net.control,
+                                                    consumer,
+                                                    sock,
+                                                    session_name,
+                                                    hostname,
+                                                    base_path,
+                                                    session_live_timer,
+                                                    current_chunk_id,
+                                                    session_creation_time,
+                                                    session_name_contains_creation_time);
                if (status != LTTNG_OK) {
                        goto error;
                }
@@ -955,10 +989,16 @@ static enum lttng_error_code send_consumer_relayd_sockets(
        /* Sending data relayd socket. */
        if (!sock->data_sock_sent) {
                status = send_consumer_relayd_socket(session_id,
-                               &consumer->dst.net.data, consumer, sock,
-                               session_name, hostname, base_path, session_live_timer,
-                               current_chunk_id, session_creation_time,
-                               session_name_contains_creation_time);
+                                                    &consumer->dst.net.data,
+                                                    consumer,
+                                                    sock,
+                                                    session_name,
+                                                    hostname,
+                                                    base_path,
+                                                    session_live_timer,
+                                                    current_chunk_id,
+                                                    session_creation_time,
+                                                    session_name_contains_creation_time);
                if (status != LTTNG_OK) {
                        goto error;
                }
@@ -989,10 +1029,9 @@ int cmd_setup_relayd(struct ltt_session *session)
 
        DBG("Setting relayd for session %s", session->name);
 
-       rcu_read_lock();
        if (session->current_trace_chunk) {
                enum lttng_trace_chunk_status status = lttng_trace_chunk_get_id(
-                               session->current_trace_chunk, &current_chunk_id.value);
+                       session->current_trace_chunk, &current_chunk_id.value);
 
                if (status == LTTNG_TRACE_CHUNK_STATUS_OK) {
                        current_chunk_id.is_set = true;
@@ -1003,20 +1042,25 @@ int cmd_setup_relayd(struct ltt_session *session)
                }
        }
 
-       if (usess && usess->consumer && usess->consumer->type == CONSUMER_DST_NET
-                       && usess->consumer->enabled) {
+       if (usess && usess->consumer && usess->consumer->type == CONSUMER_DST_NET &&
+           usess->consumer->enabled) {
                /* For each consumer socket, send relayd sockets */
-               cds_lfht_for_each_entry(usess->consumer->socks->ht, &iter.iter,
-                               socket, node.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       usess->consumer->socks->ht, &iter.iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
-                       ret = send_consumer_relayd_sockets(session->id,
-                                       usess->consumer, socket,
-                                       session->name, session->hostname,
-                                       session->base_path,
-                                       session->live_timer,
-                                       current_chunk_id.is_set ? &current_chunk_id.value : NULL,
-                                       session->creation_time,
-                                       session->name_contains_creation_time);
+                       ret = send_consumer_relayd_sockets(
+                               session->id,
+                               usess->consumer,
+                               socket,
+                               session->name,
+                               session->hostname,
+                               session->base_path,
+                               session->live_timer,
+                               current_chunk_id.is_set ? &current_chunk_id.value : nullptr,
+                               session->creation_time,
+                               session->name_contains_creation_time);
                        pthread_mutex_unlock(socket->lock);
                        if (ret != LTTNG_OK) {
                                goto error;
@@ -1024,27 +1068,30 @@ int cmd_setup_relayd(struct ltt_session *session)
                        /* Session is now ready for network streaming. */
                        session->net_handle = 1;
                }
-               session->consumer->relay_major_version =
-                       usess->consumer->relay_major_version;
-               session->consumer->relay_minor_version =
-                       usess->consumer->relay_minor_version;
-               session->consumer->relay_allows_clear =
-                       usess->consumer->relay_allows_clear;
+
+               session->consumer->relay_major_version = usess->consumer->relay_major_version;
+               session->consumer->relay_minor_version = usess->consumer->relay_minor_version;
+               session->consumer->relay_allows_clear = usess->consumer->relay_allows_clear;
        }
 
-       if (ksess && ksess->consumer && ksess->consumer->type == CONSUMER_DST_NET
-                       && ksess->consumer->enabled) {
-               cds_lfht_for_each_entry(ksess->consumer->socks->ht, &iter.iter,
-                               socket, node.node) {
+       if (ksess && ksess->consumer && ksess->consumer->type == CONSUMER_DST_NET &&
+           ksess->consumer->enabled) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       ksess->consumer->socks->ht, &iter.iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
-                       ret = send_consumer_relayd_sockets(session->id,
-                                       ksess->consumer, socket,
-                                       session->name, session->hostname,
-                                       session->base_path,
-                                       session->live_timer,
-                                       current_chunk_id.is_set ? &current_chunk_id.value : NULL,
-                                       session->creation_time,
-                                       session->name_contains_creation_time);
+                       ret = send_consumer_relayd_sockets(
+                               session->id,
+                               ksess->consumer,
+                               socket,
+                               session->name,
+                               session->hostname,
+                               session->base_path,
+                               session->live_timer,
+                               current_chunk_id.is_set ? &current_chunk_id.value : nullptr,
+                               session->creation_time,
+                               session->name_contains_creation_time);
                        pthread_mutex_unlock(socket->lock);
                        if (ret != LTTNG_OK) {
                                goto error;
@@ -1052,16 +1099,13 @@ int cmd_setup_relayd(struct ltt_session *session)
                        /* Session is now ready for network streaming. */
                        session->net_handle = 1;
                }
-               session->consumer->relay_major_version =
-                       ksess->consumer->relay_major_version;
-               session->consumer->relay_minor_version =
-                       ksess->consumer->relay_minor_version;
-               session->consumer->relay_allows_clear =
-                       ksess->consumer->relay_allows_clear;
+
+               session->consumer->relay_major_version = ksess->consumer->relay_major_version;
+               session->consumer->relay_minor_version = ksess->consumer->relay_minor_version;
+               session->consumer->relay_allows_clear = ksess->consumer->relay_allows_clear;
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -1074,7 +1118,7 @@ int start_kernel_session(struct ltt_kernel_session *ksess)
        struct ltt_kernel_channel *kchan;
 
        /* Open kernel metadata */
-       if (ksess->metadata == NULL && ksess->output_traces) {
+       if (ksess->metadata == nullptr && ksess->output_traces) {
                ret = kernel_open_metadata(ksess);
                if (ret < 0) {
                        ret = LTTNG_ERR_KERN_META_FAIL;
@@ -1093,7 +1137,7 @@ int start_kernel_session(struct ltt_kernel_session *ksess)
        }
 
        /* For each channel */
-       cds_list_for_each_entry(kchan, &ksess->channel_list.head, list) {
+       cds_list_for_each_entry (kchan, &ksess->channel_list.head, list) {
                if (kchan->stream_count == 0) {
                        ret = kernel_open_channel_stream(kchan);
                        if (ret < 0) {
@@ -1122,7 +1166,7 @@ int start_kernel_session(struct ltt_kernel_session *ksess)
        /* Quiescent wait after starting trace */
        kernel_wait_quiescent();
 
-       ksess->active = 1;
+       ksess->active = true;
 
        ret = LTTNG_OK;
 
@@ -1159,7 +1203,7 @@ int stop_kernel_session(struct ltt_kernel_session *ksess)
        }
 
        /* Flush all buffers after stopping */
-       cds_list_for_each_entry(kchan, &ksess->channel_list.head, list) {
+       cds_list_for_each_entry (kchan, &ksess->channel_list.head, list) {
                ret = kernel_flush_buffer(kchan);
                if (ret < 0) {
                        ERR("Kernel flush buffer error");
@@ -1167,7 +1211,7 @@ int stop_kernel_session(struct ltt_kernel_session *ksess)
                }
        }
 
-       ksess->active = 0;
+       ksess->active = false;
        if (error_occurred) {
                ret = LTTNG_ERR_UNK;
        } else {
@@ -1181,20 +1225,20 @@ error:
  * Command LTTNG_DISABLE_CHANNEL processed by the client thread.
  */
 int cmd_disable_channel(struct ltt_session *session,
-               enum lttng_domain_type domain, char *channel_name)
+                       enum lttng_domain_type domain,
+                       char *channel_name)
 {
        int ret;
        struct ltt_ust_session *usess;
 
        usess = session->ust_session;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
        {
-               ret = channel_kernel_disable(session->kernel_session,
-                               channel_name);
+               ret = channel_kernel_disable(session->kernel_session, channel_name);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -1210,7 +1254,7 @@ int cmd_disable_channel(struct ltt_session *session,
                chan_ht = usess->domain_global.channels;
 
                uchan = trace_ust_find_channel_by_name(chan_ht, channel_name);
-               if (uchan == NULL) {
+               if (uchan == nullptr) {
                        ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                        goto error;
                }
@@ -1229,7 +1273,6 @@ int cmd_disable_channel(struct ltt_session *session,
        ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -1243,7 +1286,7 @@ int cmd_enable_channel(struct command_ctx *cmd_ctx, int sock, int wpipe)
        int ret;
        size_t channel_len;
        ssize_t sock_recv_len;
-       struct lttng_channel *channel = NULL;
+       struct lttng_channel *channel = nullptr;
        struct lttng_buffer_view view;
        struct lttng_dynamic_buffer channel_buffer;
        const struct lttng_domain command_domain = cmd_ctx->lsm.domain;
@@ -1256,8 +1299,7 @@ int cmd_enable_channel(struct command_ctx *cmd_ctx, int sock, int wpipe)
                goto end;
        }
 
-       sock_recv_len = lttcomm_recv_unix_sock(sock, channel_buffer.data,
-                       channel_len);
+       sock_recv_len = lttcomm_recv_unix_sock(sock, channel_buffer.data, channel_len);
        if (sock_recv_len < 0 || sock_recv_len != channel_len) {
                ERR("Failed to receive \"enable channel\" command payload");
                ret = LTTNG_ERR_INVALID;
@@ -1276,8 +1318,7 @@ int cmd_enable_channel(struct command_ctx *cmd_ctx, int sock, int wpipe)
                goto end;
        }
 
-       ret = cmd_enable_channel_internal(
-                       cmd_ctx->session, &command_domain, channel, wpipe);
+       ret = cmd_enable_channel_internal(cmd_ctx->session, &command_domain, channel, wpipe);
 
 end:
        lttng_dynamic_buffer_reset(&channel_buffer);
@@ -1285,22 +1326,23 @@ end:
        return ret;
 }
 
-static enum lttng_error_code cmd_enable_channel_internal(
-               struct ltt_session *session,
-               const struct lttng_domain *domain,
-               const struct lttng_channel *_attr,
-               int wpipe)
+static enum lttng_error_code cmd_enable_channel_internal(struct ltt_session *session,
+                                                        const struct lttng_domain *domain,
+                                                        const struct lttng_channel *_attr,
+                                                        int wpipe)
 {
        enum lttng_error_code ret_code;
        struct ltt_ust_session *usess = session->ust_session;
        struct lttng_ht *chan_ht;
        size_t len;
-       struct lttng_channel *attr = NULL;
+       struct lttng_channel *attr = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(_attr);
        LTTNG_ASSERT(domain);
 
+       lttng::urcu::read_lock_guard read_lock;
+
        attr = lttng_channel_copy(_attr);
        if (!attr) {
                ret_code = LTTNG_ERR_NOMEM;
@@ -1310,16 +1352,13 @@ static enum lttng_error_code cmd_enable_channel_internal(
        len = lttng_strnlen(attr->name, sizeof(attr->name));
 
        /* Validate channel name */
-       if (attr->name[0] == '.' ||
-               memchr(attr->name, '/', len) != NULL) {
+       if (attr->name[0] == '.' || memchr(attr->name, '/', len) != nullptr) {
                ret_code = LTTNG_ERR_INVALID_CHANNEL_NAME;
                goto end;
        }
 
        DBG("Enabling channel %s for session %s", attr->name, session->name);
 
-       rcu_read_lock();
-
        /*
         * If the session is a live session, remove the switch timer, the
         * live timer does the same thing but sends also synchronisation
@@ -1337,9 +1376,10 @@ static enum lttng_error_code cmd_enable_channel_internal(
                if (kernel_supports_ring_buffer_snapshot_sample_positions() != 1) {
                        /* Sampling position of buffer is not supported */
                        WARN("Kernel tracer does not support buffer monitoring. "
-                                       "Setting the monitor interval timer to 0 "
-                                       "(disabled) for channel '%s' of session '%s'",
-                                       attr->name, session->name);
+                            "Setting the monitor interval timer to 0 "
+                            "(disabled) for channel '%s' of session '%s'",
+                            attr->name,
+                            session->name);
                        lttng_channel_set_monitor_timer_interval(attr, 0);
                }
                break;
@@ -1365,9 +1405,8 @@ static enum lttng_error_code cmd_enable_channel_internal(
        {
                struct ltt_kernel_channel *kchan;
 
-               kchan = trace_kernel_get_channel_by_name(
-                               attr->name, session->kernel_session);
-               if (kchan == NULL) {
+               kchan = trace_kernel_get_channel_by_name(attr->name, session->kernel_session);
+               if (kchan == nullptr) {
                        /*
                         * Don't try to create a channel if the session has been started at
                         * some point in time before. The tracer does not allow it.
@@ -1377,13 +1416,11 @@ static enum lttng_error_code cmd_enable_channel_internal(
                                goto error;
                        }
 
-                       if (session->snapshot.nb_output > 0 ||
-                                       session->snapshot_mode) {
+                       if (session->snapshot.nb_output > 0 || session->snapshot_mode) {
                                /* Enforce mmap output for snapshot sessions. */
                                attr->attr.output = LTTNG_EVENT_MMAP;
                        }
-                       ret_code = channel_kernel_create(
-                                       session->kernel_session, attr, wpipe);
+                       ret_code = channel_kernel_create(session->kernel_session, attr, wpipe);
                        if (attr->name[0] != '\0') {
                                session->kernel_session->has_non_default_channel = 1;
                        }
@@ -1414,20 +1451,23 @@ static enum lttng_error_code cmd_enable_channel_internal(
                 * adhered to.
                 */
                if (domain->type == LTTNG_DOMAIN_JUL) {
-                       if (strncmp(attr->name, DEFAULT_JUL_CHANNEL_NAME,
-                                       LTTNG_SYMBOL_NAME_LEN)) {
+                       if (strncmp(attr->name,
+                                   DEFAULT_JUL_CHANNEL_NAME,
+                                   LTTNG_SYMBOL_NAME_LEN - 1) != 0) {
                                ret_code = LTTNG_ERR_INVALID_CHANNEL_NAME;
                                goto error;
                        }
                } else if (domain->type == LTTNG_DOMAIN_LOG4J) {
-                       if (strncmp(attr->name, DEFAULT_LOG4J_CHANNEL_NAME,
-                                       LTTNG_SYMBOL_NAME_LEN)) {
+                       if (strncmp(attr->name,
+                                   DEFAULT_LOG4J_CHANNEL_NAME,
+                                   LTTNG_SYMBOL_NAME_LEN - 1) != 0) {
                                ret_code = LTTNG_ERR_INVALID_CHANNEL_NAME;
                                goto error;
                        }
                } else if (domain->type == LTTNG_DOMAIN_PYTHON) {
-                       if (strncmp(attr->name, DEFAULT_PYTHON_CHANNEL_NAME,
-                                       LTTNG_SYMBOL_NAME_LEN)) {
+                       if (strncmp(attr->name,
+                                   DEFAULT_PYTHON_CHANNEL_NAME,
+                                   LTTNG_SYMBOL_NAME_LEN - 1) != 0) {
                                ret_code = LTTNG_ERR_INVALID_CHANNEL_NAME;
                                goto error;
                        }
@@ -1436,7 +1476,7 @@ static enum lttng_error_code cmd_enable_channel_internal(
                chan_ht = usess->domain_global.channels;
 
                uchan = trace_ust_find_channel_by_name(chan_ht, attr->name);
-               if (uchan == NULL) {
+               if (uchan == nullptr) {
                        /*
                         * Don't try to create a channel if the session has been started at
                         * some point in time before. The tracer does not allow it.
@@ -1464,17 +1504,16 @@ static enum lttng_error_code cmd_enable_channel_internal(
                session->has_non_mmap_channel = true;
        }
 error:
-       rcu_read_unlock();
 end:
        lttng_channel_destroy(attr);
        return ret_code;
 }
 
-enum lttng_error_code cmd_process_attr_tracker_get_tracking_policy(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy *policy)
+enum lttng_error_code
+cmd_process_attr_tracker_get_tracking_policy(struct ltt_session *session,
+                                            enum lttng_domain_type domain,
+                                            enum lttng_process_attr process_attr,
+                                            enum lttng_tracking_policy *policy)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
        const struct process_attr_tracker *tracker;
@@ -1485,16 +1524,14 @@ enum lttng_error_code cmd_process_attr_tracker_get_tracking_policy(
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
                }
-               tracker = kernel_get_process_attr_tracker(
-                               session->kernel_session, process_attr);
+               tracker = kernel_get_process_attr_tracker(session->kernel_session, process_attr);
                break;
        case LTTNG_DOMAIN_UST:
                if (!session->ust_session) {
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
                }
-               tracker = trace_ust_get_process_attr_tracker(
-                               session->ust_session, process_attr);
+               tracker = trace_ust_get_process_attr_tracker(session->ust_session, process_attr);
                break;
        default:
                ret_code = LTTNG_ERR_UNSUPPORTED_DOMAIN;
@@ -1509,11 +1546,11 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code cmd_process_attr_tracker_set_tracking_policy(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy)
+enum lttng_error_code
+cmd_process_attr_tracker_set_tracking_policy(struct ltt_session *session,
+                                            enum lttng_domain_type domain,
+                                            enum lttng_process_attr process_attr,
+                                            enum lttng_tracking_policy policy)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
 
@@ -1534,7 +1571,7 @@ enum lttng_error_code cmd_process_attr_tracker_set_tracking_policy(
                        goto end;
                }
                ret_code = kernel_process_attr_tracker_set_tracking_policy(
-                               session->kernel_session, process_attr, policy);
+                       session->kernel_session, process_attr, policy);
                break;
        case LTTNG_DOMAIN_UST:
                if (!session->ust_session) {
@@ -1542,7 +1579,7 @@ enum lttng_error_code cmd_process_attr_tracker_set_tracking_policy(
                        goto end;
                }
                ret_code = trace_ust_process_attr_tracker_set_tracking_policy(
-                               session->ust_session, process_attr, policy);
+                       session->ust_session, process_attr, policy);
                break;
        default:
                ret_code = LTTNG_ERR_UNSUPPORTED_DOMAIN;
@@ -1552,11 +1589,11 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code cmd_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+cmd_process_attr_tracker_inclusion_set_add_value(struct ltt_session *session,
+                                                enum lttng_domain_type domain,
+                                                enum lttng_process_attr process_attr,
+                                                const struct process_attr_value *value)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
 
@@ -1567,7 +1604,7 @@ enum lttng_error_code cmd_process_attr_tracker_inclusion_set_add_value(
                        goto end;
                }
                ret_code = kernel_process_attr_tracker_inclusion_set_add_value(
-                               session->kernel_session, process_attr, value);
+                       session->kernel_session, process_attr, value);
                break;
        case LTTNG_DOMAIN_UST:
                if (!session->ust_session) {
@@ -1575,7 +1612,7 @@ enum lttng_error_code cmd_process_attr_tracker_inclusion_set_add_value(
                        goto end;
                }
                ret_code = trace_ust_process_attr_tracker_inclusion_set_add_value(
-                               session->ust_session, process_attr, value);
+                       session->ust_session, process_attr, value);
                break;
        default:
                ret_code = LTTNG_ERR_UNSUPPORTED_DOMAIN;
@@ -1585,11 +1622,11 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code cmd_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+cmd_process_attr_tracker_inclusion_set_remove_value(struct ltt_session *session,
+                                                   enum lttng_domain_type domain,
+                                                   enum lttng_process_attr process_attr,
+                                                   const struct process_attr_value *value)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
 
@@ -1600,7 +1637,7 @@ enum lttng_error_code cmd_process_attr_tracker_inclusion_set_remove_value(
                        goto end;
                }
                ret_code = kernel_process_attr_tracker_inclusion_set_remove_value(
-                               session->kernel_session, process_attr, value);
+                       session->kernel_session, process_attr, value);
                break;
        case LTTNG_DOMAIN_UST:
                if (!session->ust_session) {
@@ -1608,7 +1645,7 @@ enum lttng_error_code cmd_process_attr_tracker_inclusion_set_remove_value(
                        goto end;
                }
                ret_code = trace_ust_process_attr_tracker_inclusion_set_remove_value(
-                               session->ust_session, process_attr, value);
+                       session->ust_session, process_attr, value);
                break;
        default:
                ret_code = LTTNG_ERR_UNSUPPORTED_DOMAIN;
@@ -1618,11 +1655,11 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code cmd_process_attr_tracker_get_inclusion_set(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               struct lttng_process_attr_values **values)
+enum lttng_error_code
+cmd_process_attr_tracker_get_inclusion_set(struct ltt_session *session,
+                                          enum lttng_domain_type domain,
+                                          enum lttng_process_attr process_attr,
+                                          struct lttng_process_attr_values **values)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
        const struct process_attr_tracker *tracker;
@@ -1634,16 +1671,14 @@ enum lttng_error_code cmd_process_attr_tracker_get_inclusion_set(
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
                }
-               tracker = kernel_get_process_attr_tracker(
-                               session->kernel_session, process_attr);
+               tracker = kernel_get_process_attr_tracker(session->kernel_session, process_attr);
                break;
        case LTTNG_DOMAIN_UST:
                if (!session->ust_session) {
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
                }
-               tracker = trace_ust_get_process_attr_tracker(
-                               session->ust_session, process_attr);
+               tracker = trace_ust_get_process_attr_tracker(session->ust_session, process_attr);
                break;
        default:
                ret_code = LTTNG_ERR_UNSUPPORTED_DOMAIN;
@@ -1679,10 +1714,10 @@ end:
  * Command LTTNG_DISABLE_EVENT processed by the client thread.
  */
 int cmd_disable_event(struct command_ctx *cmd_ctx,
-               struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *bytecode,
-               struct lttng_event_exclusion *exclusion)
+                     struct lttng_event *event,
+                     char *filter_expression,
+                     struct lttng_bytecode *bytecode,
+                     struct lttng_event_exclusion *exclusion)
 {
        int ret;
        const char *event_name;
@@ -1707,15 +1742,15 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
 
        event_name = event->name;
 
+       lttng::urcu::read_lock_guard read_lock;
+
        /* Error out on unhandled search criteria */
-       if (event->loglevel_type || event->loglevel != -1 || event->enabled
-                       || event->pid || event->filter || event->exclusion) {
+       if (event->loglevel_type || event->loglevel != -1 || event->enabled || event->pid ||
+           event->filter || event->exclusion) {
                ret = LTTNG_ERR_UNK;
                goto error;
        }
 
-       rcu_read_lock();
-
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
        {
@@ -1735,7 +1770,7 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
                }
 
                kchan = trace_kernel_get_channel_by_name(channel_name, ksess);
-               if (kchan == NULL) {
+               if (kchan == nullptr) {
                        ret = LTTNG_ERR_KERN_CHAN_NOT_FOUND;
                        goto error_unlock;
                }
@@ -1746,13 +1781,11 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
                case LTTNG_EVENT_SYSCALL:
                case LTTNG_EVENT_PROBE:
                case LTTNG_EVENT_FUNCTION:
-               case LTTNG_EVENT_FUNCTION_ENTRY:/* fall-through */
+               case LTTNG_EVENT_FUNCTION_ENTRY: /* fall-through */
                        if (event_name[0] == '\0') {
-                               ret = event_kernel_disable_event(kchan,
-                                       NULL, event->type);
+                               ret = event_kernel_disable_event(kchan, nullptr, event->type);
                        } else {
-                               ret = event_kernel_disable_event(kchan,
-                                       event_name, event->type);
+                               ret = event_kernel_disable_event(kchan, event_name, event->type);
                        }
                        if (ret != LTTNG_OK) {
                                goto error_unlock;
@@ -1788,9 +1821,8 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
                        goto error_unlock;
                }
 
-               uchan = trace_ust_find_channel_by_name(usess->domain_global.channels,
-                               channel_name);
-               if (uchan == NULL) {
+               uchan = trace_ust_find_channel_by_name(usess->domain_global.channels, channel_name);
+               if (uchan == nullptr) {
                        ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                        goto error_unlock;
                }
@@ -1804,8 +1836,7 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
                        if (event->name[0] == '\0') {
                                ret = event_ust_disable_all_tracepoints(usess, uchan);
                        } else {
-                               ret = event_ust_disable_tracepoint(usess, uchan,
-                                               event_name);
+                               ret = event_ust_disable_tracepoint(usess, uchan, event_name);
                        }
                        if (ret != LTTNG_OK) {
                                goto error_unlock;
@@ -1816,8 +1847,7 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
                        goto error_unlock;
                }
 
-               DBG3("Disable UST event %s in channel %s completed", event_name,
-                               channel_name);
+               DBG3("Disable UST event %s in channel %s completed", event_name, channel_name);
                break;
        }
        case LTTNG_DOMAIN_LOG4J:
@@ -1865,7 +1895,6 @@ int cmd_disable_event(struct command_ctx *cmd_ctx,
        ret = LTTNG_OK;
 
 error_unlock:
-       rcu_read_unlock();
 error:
        free(exclusion);
        free(bytecode);
@@ -1877,7 +1906,8 @@ error:
  * Command LTTNG_ADD_CONTEXT processed by the client thread.
  */
 int cmd_add_context(struct command_ctx *cmd_ctx,
-       const struct lttng_event_context *event_context, int kwpipe)
+                   const struct lttng_event_context *event_context,
+                   int kwpipe)
 {
        int ret, chan_kern_created = 0, chan_ust_created = 0;
        const enum lttng_domain_type domain = cmd_ctx->lsm.domain.type;
@@ -1900,15 +1930,14 @@ int cmd_add_context(struct command_ctx *cmd_ctx,
 
                if (session->kernel_session->channel_count == 0) {
                        /* Create default channel */
-                       ret = channel_kernel_create(session->kernel_session, NULL, kwpipe);
+                       ret = channel_kernel_create(session->kernel_session, nullptr, kwpipe);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
                        chan_kern_created = 1;
                }
                /* Add kernel context to kernel tracer */
-               ret = context_kernel_add(session->kernel_session,
-                               event_context, channel_name);
+               ret = context_kernel_add(session->kernel_session, event_context, channel_name);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -1924,13 +1953,11 @@ int cmd_add_context(struct command_ctx *cmd_ctx,
                 * name, return an error.
                 */
                if (domain == LTTNG_DOMAIN_JUL && *channel_name &&
-                               strcmp(channel_name,
-                               DEFAULT_JUL_CHANNEL_NAME)) {
+                   strcmp(channel_name, DEFAULT_JUL_CHANNEL_NAME) != 0) {
                        ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                        goto error;
                } else if (domain == LTTNG_DOMAIN_LOG4J && *channel_name &&
-                               strcmp(channel_name,
-                               DEFAULT_LOG4J_CHANNEL_NAME)) {
+                          strcmp(channel_name, DEFAULT_LOG4J_CHANNEL_NAME) != 0) {
                        ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                        goto error;
                }
@@ -1948,7 +1975,7 @@ int cmd_add_context(struct command_ctx *cmd_ctx,
                        struct lttng_channel *attr;
                        /* Create default channel */
                        attr = channel_new_default_attr(domain, usess->buffer_type);
-                       if (attr == NULL) {
+                       if (attr == nullptr) {
                                ret = LTTNG_ERR_FATAL;
                                goto error;
                        }
@@ -1962,8 +1989,7 @@ int cmd_add_context(struct command_ctx *cmd_ctx,
                        chan_ust_created = 1;
                }
 
-               ret = context_ust_add(usess, domain, event_context,
-                               channel_name);
+               ret = context_ust_add(usess, domain, event_context, channel_name);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -1979,24 +2005,20 @@ int cmd_add_context(struct command_ctx *cmd_ctx,
 
 error:
        if (chan_kern_created) {
-               struct ltt_kernel_channel *kchan =
-                       trace_kernel_get_channel_by_name(DEFAULT_CHANNEL_NAME,
-                                       session->kernel_session);
+               struct ltt_kernel_channel *kchan = trace_kernel_get_channel_by_name(
+                       DEFAULT_CHANNEL_NAME, session->kernel_session);
                /* Created previously, this should NOT fail. */
                LTTNG_ASSERT(kchan);
                kernel_destroy_channel(kchan);
        }
 
        if (chan_ust_created) {
-               struct ltt_ust_channel *uchan =
-                       trace_ust_find_channel_by_name(
-                                       session->ust_session->domain_global.channels,
-                                       DEFAULT_CHANNEL_NAME);
+               struct ltt_ust_channel *uchan = trace_ust_find_channel_by_name(
+                       session->ust_session->domain_global.channels, DEFAULT_CHANNEL_NAME);
                /* Created previously, this should NOT fail. */
                LTTNG_ASSERT(uchan);
                /* Remove from the channel list of the session. */
-               trace_ust_delete_channel(session->ust_session->domain_global.channels,
-                               uchan);
+               trace_ust_delete_channel(session->ust_session->domain_global.channels, uchan);
                trace_ust_destroy_channel(uchan);
        }
 end:
@@ -2025,8 +2047,8 @@ static int validate_ust_event_name(const char *name)
         * by the agents.
         */
        if (name_starts_with(name, DEFAULT_JUL_EVENT_COMPONENT) ||
-               name_starts_with(name, DEFAULT_LOG4J_EVENT_COMPONENT) ||
-               name_starts_with(name, DEFAULT_PYTHON_EVENT_COMPONENT)) {
+           name_starts_with(name, DEFAULT_LOG4J_EVENT_COMPONENT) ||
+           name_starts_with(name, DEFAULT_PYTHON_EVENT_COMPONENT)) {
                ret = -1;
        }
 
@@ -2041,15 +2063,17 @@ end:
  * enable the events through which all "agent" events are funeled.
  */
 static int _cmd_enable_event(struct ltt_session *session,
-               const struct lttng_domain *domain,
-               char *channel_name, struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               int wpipe, bool internal_event)
+                            const struct lttng_domain *domain,
+                            char *channel_name,
+                            struct lttng_event *event,
+                            char *filter_expression,
+                            struct lttng_bytecode *filter,
+                            struct lttng_event_exclusion *exclusion,
+                            int wpipe,
+                            bool internal_event)
 {
        int ret = 0, channel_created = 0;
-       struct lttng_channel *attr = NULL;
+       struct lttng_channel *attr = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(event);
@@ -2072,9 +2096,7 @@ static int _cmd_enable_event(struct ltt_session *session,
                }
        }
 
-       DBG("Enable event command for event \'%s\'", event->name);
-
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        switch (domain->type) {
        case LTTNG_DOMAIN_KERNEL:
@@ -2086,29 +2108,24 @@ static int _cmd_enable_event(struct ltt_session *session,
                 * session, explicitely require that -c chan_name needs
                 * to be provided.
                 */
-               if (session->kernel_session->has_non_default_channel
-                               && channel_name[0] == '\0') {
+               if (session->kernel_session->has_non_default_channel && channel_name[0] == '\0') {
                        ret = LTTNG_ERR_NEED_CHANNEL_NAME;
                        goto error;
                }
 
-               kchan = trace_kernel_get_channel_by_name(channel_name,
-                               session->kernel_session);
-               if (kchan == NULL) {
-                       attr = channel_new_default_attr(LTTNG_DOMAIN_KERNEL,
-                                       LTTNG_BUFFER_GLOBAL);
-                       if (attr == NULL) {
+               kchan = trace_kernel_get_channel_by_name(channel_name, session->kernel_session);
+               if (kchan == nullptr) {
+                       attr = channel_new_default_attr(LTTNG_DOMAIN_KERNEL, LTTNG_BUFFER_GLOBAL);
+                       if (attr == nullptr) {
                                ret = LTTNG_ERR_FATAL;
                                goto error;
                        }
-                       if (lttng_strncpy(attr->name, channel_name,
-                                       sizeof(attr->name))) {
+                       if (lttng_strncpy(attr->name, channel_name, sizeof(attr->name))) {
                                ret = LTTNG_ERR_INVALID;
                                goto error;
                        }
 
-                       ret = cmd_enable_channel_internal(
-                                       session, domain, attr, wpipe);
+                       ret = cmd_enable_channel_internal(session, domain, attr, wpipe);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -2116,9 +2133,8 @@ static int _cmd_enable_event(struct ltt_session *session,
                }
 
                /* Get the newly created kernel channel pointer */
-               kchan = trace_kernel_get_channel_by_name(channel_name,
-                               session->kernel_session);
-               if (kchan == NULL) {
+               kchan = trace_kernel_get_channel_by_name(channel_name, session->kernel_session);
+               if (kchan == nullptr) {
                        /* This sould not happen... */
                        ret = LTTNG_ERR_FATAL;
                        goto error;
@@ -2127,8 +2143,8 @@ static int _cmd_enable_event(struct ltt_session *session,
                switch (event->type) {
                case LTTNG_EVENT_ALL:
                {
-                       char *filter_expression_a = NULL;
-                       struct lttng_bytecode *filter_a = NULL;
+                       char *filter_expression_a = nullptr;
+                       struct lttng_bytecode *filter_a = nullptr;
 
                        /*
                         * We need to duplicate filter_expression and filter,
@@ -2151,12 +2167,11 @@ static int _cmd_enable_event(struct ltt_session *session,
                                }
                                memcpy(filter_a, filter, sizeof(*filter_a) + filter->len);
                        }
-                       event->type = LTTNG_EVENT_TRACEPOINT;   /* Hack */
-                       ret = event_kernel_enable_event(kchan, event,
-                               filter_expression, filter);
+                       event->type = LTTNG_EVENT_TRACEPOINT; /* Hack */
+                       ret = event_kernel_enable_event(kchan, event, filter_expression, filter);
                        /* We have passed ownership */
-                       filter_expression = NULL;
-                       filter = NULL;
+                       filter_expression = nullptr;
+                       filter = nullptr;
                        if (ret != LTTNG_OK) {
                                if (channel_created) {
                                        /* Let's not leak a useless channel. */
@@ -2166,12 +2181,12 @@ static int _cmd_enable_event(struct ltt_session *session,
                                free(filter_a);
                                goto error;
                        }
-                       event->type = LTTNG_EVENT_SYSCALL;      /* Hack */
-                       ret = event_kernel_enable_event(kchan, event,
-                               filter_expression_a, filter_a);
+                       event->type = LTTNG_EVENT_SYSCALL; /* Hack */
+                       ret = event_kernel_enable_event(
+                               kchan, event, filter_expression_a, filter_a);
                        /* We have passed ownership */
-                       filter_expression_a = NULL;
-                       filter_a = NULL;
+                       filter_expression_a = nullptr;
+                       filter_a = nullptr;
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -2182,11 +2197,10 @@ static int _cmd_enable_event(struct ltt_session *session,
                case LTTNG_EVENT_FUNCTION:
                case LTTNG_EVENT_FUNCTION_ENTRY:
                case LTTNG_EVENT_TRACEPOINT:
-                       ret = event_kernel_enable_event(kchan, event,
-                               filter_expression, filter);
+                       ret = event_kernel_enable_event(kchan, event, filter_expression, filter);
                        /* We have passed ownership */
-                       filter_expression = NULL;
-                       filter = NULL;
+                       filter_expression = nullptr;
+                       filter = nullptr;
                        if (ret != LTTNG_OK) {
                                if (channel_created) {
                                        /* Let's not leak a useless channel. */
@@ -2196,11 +2210,10 @@ static int _cmd_enable_event(struct ltt_session *session,
                        }
                        break;
                case LTTNG_EVENT_SYSCALL:
-                       ret = event_kernel_enable_event(kchan, event,
-                               filter_expression, filter);
+                       ret = event_kernel_enable_event(kchan, event, filter_expression, filter);
                        /* We have passed ownership */
-                       filter_expression = NULL;
-                       filter = NULL;
+                       filter_expression = nullptr;
+                       filter = nullptr;
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -2231,31 +2244,27 @@ static int _cmd_enable_event(struct ltt_session *session,
                }
 
                /* Get channel from global UST domain */
-               uchan = trace_ust_find_channel_by_name(usess->domain_global.channels,
-                               channel_name);
-               if (uchan == NULL) {
+               uchan = trace_ust_find_channel_by_name(usess->domain_global.channels, channel_name);
+               if (uchan == nullptr) {
                        /* Create default channel */
-                       attr = channel_new_default_attr(LTTNG_DOMAIN_UST,
-                                       usess->buffer_type);
-                       if (attr == NULL) {
+                       attr = channel_new_default_attr(LTTNG_DOMAIN_UST, usess->buffer_type);
+                       if (attr == nullptr) {
                                ret = LTTNG_ERR_FATAL;
                                goto error;
                        }
-                       if (lttng_strncpy(attr->name, channel_name,
-                                       sizeof(attr->name))) {
+                       if (lttng_strncpy(attr->name, channel_name, sizeof(attr->name))) {
                                ret = LTTNG_ERR_INVALID;
                                goto error;
                        }
 
-                       ret = cmd_enable_channel_internal(
-                                       session, domain, attr, wpipe);
+                       ret = cmd_enable_channel_internal(session, domain, attr, wpipe);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
 
                        /* Get the newly created channel reference back */
-                       uchan = trace_ust_find_channel_by_name(
-                                       usess->domain_global.channels, channel_name);
+                       uchan = trace_ust_find_channel_by_name(usess->domain_global.channels,
+                                                              channel_name);
                        LTTNG_ASSERT(uchan);
                }
 
@@ -2276,21 +2285,19 @@ static int _cmd_enable_event(struct ltt_session *session,
                         */
                        ret = validate_ust_event_name(event->name);
                        if (ret) {
-                               WARN("Userspace event name %s failed validation.",
-                                               event->name);
+                               WARN("Userspace event name %s failed validation.", event->name);
                                ret = LTTNG_ERR_INVALID_EVENT_NAME;
                                goto error;
                        }
                }
 
                /* At this point, the session and channel exist on the tracer */
-               ret = event_ust_enable_tracepoint(usess, uchan, event,
-                               filter_expression, filter, exclusion,
-                               internal_event);
+               ret = event_ust_enable_tracepoint(
+                       usess, uchan, event, filter_expression, filter, exclusion, internal_event);
                /* We have passed ownership */
-               filter_expression = NULL;
-               filter = NULL;
-               exclusion = NULL;
+               filter_expression = nullptr;
+               filter = nullptr;
+               exclusion = nullptr;
                if (ret == LTTNG_ERR_UST_EVENT_ENABLED) {
                        goto already_enabled;
                } else if (ret != LTTNG_OK) {
@@ -2330,8 +2337,8 @@ static int _cmd_enable_event(struct ltt_session *session,
                memset(&uevent, 0, sizeof(uevent));
                uevent.type = LTTNG_EVENT_TRACEPOINT;
                uevent.loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               default_event_name = event_get_default_agent_ust_name(
-                               domain->type);
+               uevent.loglevel = -1;
+               default_event_name = event_get_default_agent_ust_name(domain->type);
                if (!default_event_name) {
                        ret = LTTNG_ERR_FATAL;
                        goto error;
@@ -2363,13 +2370,12 @@ static int _cmd_enable_event(struct ltt_session *session,
                }
 
                {
-                       char *filter_expression_copy = NULL;
-                       struct lttng_bytecode *filter_copy = NULL;
+                       char *filter_expression_copy = nullptr;
+                       struct lttng_bytecode *filter_copy = nullptr;
 
                        if (filter) {
-                               const size_t filter_size = sizeof(
-                                               struct lttng_bytecode)
-                                               + filter->len;
+                               const size_t filter_size =
+                                       sizeof(struct lttng_bytecode) + filter->len;
 
                                filter_copy = zmalloc<lttng_bytecode>(filter_size);
                                if (!filter_copy) {
@@ -2378,8 +2384,7 @@ static int _cmd_enable_event(struct ltt_session *session,
                                }
                                memcpy(filter_copy, filter, filter_size);
 
-                               filter_expression_copy =
-                                               strdup(filter_expression);
+                               filter_expression_copy = strdup(filter_expression);
                                if (!filter_expression) {
                                        ret = LTTNG_ERR_NOMEM;
                                }
@@ -2391,10 +2396,14 @@ static int _cmd_enable_event(struct ltt_session *session,
                                }
                        }
 
-                       ret = cmd_enable_event_internal(session, &tmp_dom,
-                                       (char *) default_chan_name,
-                                       &uevent, filter_expression_copy,
-                                       filter_copy, NULL, wpipe);
+                       ret = cmd_enable_event_internal(session,
+                                                       &tmp_dom,
+                                                       (char *) default_chan_name,
+                                                       &uevent,
+                                                       filter_expression_copy,
+                                                       filter_copy,
+                                                       nullptr,
+                                                       wpipe);
                }
 
                if (ret == LTTNG_ERR_UST_EVENT_ENABLED) {
@@ -2405,14 +2414,12 @@ static int _cmd_enable_event(struct ltt_session *session,
 
                /* The wild card * means that everything should be enabled. */
                if (strncmp(event->name, "*", 1) == 0 && strlen(event->name) == 1) {
-                       ret = event_agent_enable_all(usess, agt, event, filter,
-                                       filter_expression);
+                       ret = event_agent_enable_all(usess, agt, event, filter, filter_expression);
                } else {
-                       ret = event_agent_enable(usess, agt, event, filter,
-                                       filter_expression);
+                       ret = event_agent_enable(usess, agt, event, filter, filter_expression);
                }
-               filter = NULL;
-               filter_expression = NULL;
+               filter = nullptr;
+               filter_expression = nullptr;
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -2432,7 +2439,6 @@ error:
        free(filter);
        free(exclusion);
        channel_attr_destroy(attr);
-       rcu_read_unlock();
        return ret;
 }
 
@@ -2441,11 +2447,11 @@ error:
  * We own filter, exclusion, and filter_expression.
  */
 int cmd_enable_event(struct command_ctx *cmd_ctx,
-               struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_event_exclusion *exclusion,
-               struct lttng_bytecode *bytecode,
-               int wpipe)
+                    struct lttng_event *event,
+                    char *filter_expression,
+                    struct lttng_event_exclusion *exclusion,
+                    struct lttng_bytecode *bytecode,
+                    int wpipe)
 {
        int ret;
        /*
@@ -2462,12 +2468,17 @@ int cmd_enable_event(struct command_ctx *cmd_ctx,
         *  - exclusion
         */
        ret = _cmd_enable_event(cmd_ctx->session,
-                       &command_domain,
-                       cmd_ctx->lsm.u.enable.channel_name, event,
-                       filter_expression, bytecode, exclusion, wpipe, false);
-       filter_expression = NULL;
-       bytecode = NULL;
-       exclusion = NULL;
+                               &command_domain,
+                               cmd_ctx->lsm.u.enable.channel_name,
+                               event,
+                               filter_expression,
+                               bytecode,
+                               exclusion,
+                               wpipe,
+                               false);
+       filter_expression = nullptr;
+       bytecode = nullptr;
+       exclusion = nullptr;
        return ret;
 }
 
@@ -2477,27 +2488,35 @@ int cmd_enable_event(struct command_ctx *cmd_ctx,
  * reserved names.
  */
 static int cmd_enable_event_internal(struct ltt_session *session,
-               const struct lttng_domain *domain,
-               char *channel_name, struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               int wpipe)
+                                    const struct lttng_domain *domain,
+                                    char *channel_name,
+                                    struct lttng_event *event,
+                                    char *filter_expression,
+                                    struct lttng_bytecode *filter,
+                                    struct lttng_event_exclusion *exclusion,
+                                    int wpipe)
 {
-       return _cmd_enable_event(session, domain, channel_name, event,
-                       filter_expression, filter, exclusion, wpipe, true);
+       return _cmd_enable_event(session,
+                                domain,
+                                channel_name,
+                                event,
+                                filter_expression,
+                                filter,
+                                exclusion,
+                                wpipe,
+                                true);
 }
 
 /*
  * Command LTTNG_LIST_TRACEPOINTS processed by the client thread.
  */
 enum lttng_error_code cmd_list_tracepoints(enum lttng_domain_type domain,
-               struct lttng_payload *reply_payload)
+                                          struct lttng_payload *reply_payload)
 {
        enum lttng_error_code ret_code;
        int ret;
        ssize_t i, nb_events = 0;
-       struct lttng_event *events = NULL;
+       struct lttng_event *events = nullptr;
        struct lttcomm_list_command_header reply_command_header = {};
        size_t reply_command_header_offset;
 
@@ -2506,8 +2525,8 @@ enum lttng_error_code cmd_list_tracepoints(enum lttng_domain_type domain,
        /* Reserve space for command reply header. */
        reply_command_header_offset = reply_payload->buffer.size;
        ret = lttng_dynamic_buffer_set_size(&reply_payload->buffer,
-                       reply_command_header_offset +
-                                       sizeof(struct lttcomm_list_command_header));
+                                           reply_command_header_offset +
+                                                   sizeof(struct lttcomm_list_command_header));
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto error;
@@ -2543,8 +2562,8 @@ enum lttng_error_code cmd_list_tracepoints(enum lttng_domain_type domain,
        }
 
        for (i = 0; i < nb_events; i++) {
-               ret = lttng_event_serialize(&events[i], 0, NULL, NULL, 0, NULL,
-                               reply_payload);
+               ret = lttng_event_serialize(
+                       &events[i], 0, nullptr, nullptr, 0, nullptr, reply_payload);
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto error;
@@ -2559,8 +2578,9 @@ enum lttng_error_code cmd_list_tracepoints(enum lttng_domain_type domain,
 
        /* Update command reply header. */
        reply_command_header.count = (uint32_t) nb_events;
-       memcpy(reply_payload->buffer.data + reply_command_header_offset, &reply_command_header,
-                       sizeof(reply_command_header));
+       memcpy(reply_payload->buffer.data + reply_command_header_offset,
+              &reply_command_header,
+              sizeof(reply_command_header));
 
        ret_code = LTTNG_OK;
 error:
@@ -2572,12 +2592,12 @@ error:
  * Command LTTNG_LIST_TRACEPOINT_FIELDS processed by the client thread.
  */
 enum lttng_error_code cmd_list_tracepoint_fields(enum lttng_domain_type domain,
-               struct lttng_payload *reply)
+                                                struct lttng_payload *reply)
 {
        enum lttng_error_code ret_code;
        int ret;
        unsigned int i, nb_fields;
-       struct lttng_event_field *fields = NULL;
+       struct lttng_event_field *fields = nullptr;
        struct lttcomm_list_command_header reply_command_header = {};
        size_t reply_command_header_offset;
 
@@ -2586,8 +2606,8 @@ enum lttng_error_code cmd_list_tracepoint_fields(enum lttng_domain_type domain,
        /* Reserve space for command reply header. */
        reply_command_header_offset = reply->buffer.size;
        ret = lttng_dynamic_buffer_set_size(&reply->buffer,
-                       reply_command_header_offset +
-                               sizeof(struct lttcomm_list_command_header));
+                                           reply_command_header_offset +
+                                                   sizeof(struct lttcomm_list_command_header));
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto error;
@@ -2603,7 +2623,7 @@ enum lttng_error_code cmd_list_tracepoint_fields(enum lttng_domain_type domain,
 
                break;
        case LTTNG_DOMAIN_KERNEL:
-       default:        /* fall-through */
+       default: /* fall-through */
                ret_code = LTTNG_ERR_UND;
                goto error;
        }
@@ -2627,8 +2647,9 @@ enum lttng_error_code cmd_list_tracepoint_fields(enum lttng_domain_type domain,
        /* Update command reply header. */
        reply_command_header.count = (uint32_t) nb_fields;
 
-       memcpy(reply->buffer.data + reply_command_header_offset, &reply_command_header,
-                       sizeof(reply_command_header));
+       memcpy(reply->buffer.data + reply_command_header_offset,
+              &reply_command_header,
+              sizeof(reply_command_header));
 
        ret_code = LTTNG_OK;
 
@@ -2637,13 +2658,12 @@ error:
        return ret_code;
 }
 
-enum lttng_error_code cmd_list_syscalls(
-               struct lttng_payload *reply_payload)
+enum lttng_error_code cmd_list_syscalls(struct lttng_payload *reply_payload)
 {
        enum lttng_error_code ret_code;
        ssize_t nb_events, i;
        int ret;
-       struct lttng_event *events = NULL;
+       struct lttng_event *events = nullptr;
        struct lttcomm_list_command_header reply_command_header = {};
        size_t reply_command_header_offset;
 
@@ -2652,8 +2672,8 @@ enum lttng_error_code cmd_list_syscalls(
        /* Reserve space for command reply header. */
        reply_command_header_offset = reply_payload->buffer.size;
        ret = lttng_dynamic_buffer_set_size(&reply_payload->buffer,
-                       reply_command_header_offset +
-                                       sizeof(struct lttcomm_list_command_header));
+                                           reply_command_header_offset +
+                                                   sizeof(struct lttcomm_list_command_header));
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -2661,13 +2681,13 @@ enum lttng_error_code cmd_list_syscalls(
 
        nb_events = syscall_table_list(&events);
        if (nb_events < 0) {
-               ret_code = (enum lttng_error_code) -nb_events;
+               ret_code = (enum lttng_error_code) - nb_events;
                goto end;
        }
 
        for (i = 0; i < nb_events; i++) {
-               ret = lttng_event_serialize(&events[i], 0, NULL, NULL, 0, NULL,
-                               reply_payload);
+               ret = lttng_event_serialize(
+                       &events[i], 0, nullptr, nullptr, 0, nullptr, reply_payload);
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -2682,8 +2702,9 @@ enum lttng_error_code cmd_list_syscalls(
 
        /* Update command reply header. */
        reply_command_header.count = (uint32_t) nb_events;
-       memcpy(reply_payload->buffer.data + reply_command_header_offset, &reply_command_header,
-                       sizeof(reply_command_header));
+       memcpy(reply_payload->buffer.data + reply_command_header_offset,
+              &reply_command_header,
+              sizeof(reply_command_header));
 
        ret_code = LTTNG_OK;
 end:
@@ -2702,10 +2723,8 @@ int cmd_start_trace(struct ltt_session *session)
        unsigned long nb_chan = 0;
        struct ltt_kernel_session *ksession;
        struct ltt_ust_session *usess;
-       const bool session_rotated_after_last_stop =
-                       session->rotated_after_last_stop;
-       const bool session_cleared_after_last_stop =
-                       session->cleared_after_last_stop;
+       const bool session_rotated_after_last_stop = session->rotated_after_last_stop;
+       const bool session_cleared_after_last_stop = session->cleared_after_last_stop;
 
        LTTNG_ASSERT(session);
 
@@ -2721,7 +2740,7 @@ int cmd_start_trace(struct ltt_session *session)
        }
 
        if (session->rotation_state == LTTNG_ROTATION_STATE_ONGOING &&
-                       !session->current_trace_chunk) {
+           !session->current_trace_chunk) {
                /*
                 * A rotation was launched while the session was stopped and
                 * it has not been completed yet. It is not possible to start
@@ -2731,7 +2750,7 @@ int cmd_start_trace(struct ltt_session *session)
                 * supported.
                 */
                WARN("Refusing to start session \"%s\" as a rotation launched after the last \"stop\" is still ongoing",
-                               session->name);
+                    session->name);
                ret = LTTNG_ERR_ROTATION_PENDING;
                goto error;
        }
@@ -2751,24 +2770,23 @@ int cmd_start_trace(struct ltt_session *session)
                goto error;
        }
 
-       session->active = 1;
+       session->active = true;
        session->rotated_after_last_stop = false;
        session->cleared_after_last_stop = false;
        if (session->output_traces && !session->current_trace_chunk) {
                if (!session->has_been_started) {
                        struct lttng_trace_chunk *trace_chunk;
 
-                       DBG("Creating initial trace chunk of session \"%s\"",
-                                       session->name);
-                       trace_chunk = session_create_new_trace_chunk(
-                                       session, NULL, NULL, NULL);
+                       DBG("Creating initial trace chunk of session \"%s\"", session->name);
+                       trace_chunk =
+                               session_create_new_trace_chunk(session, nullptr, nullptr, nullptr);
                        if (!trace_chunk) {
                                ret = LTTNG_ERR_CREATE_DIR_FAIL;
                                goto error;
                        }
                        LTTNG_ASSERT(!session->current_trace_chunk);
-                       ret = (lttng_error_code) session_set_trace_chunk(session, trace_chunk,
-                                       NULL);
+                       ret = (lttng_error_code) session_set_trace_chunk(
+                               session, trace_chunk, nullptr);
                        lttng_trace_chunk_put(trace_chunk);
                        if (ret) {
                                ret = LTTNG_ERR_CREATE_TRACE_CHUNK_FAIL_CONSUMER;
@@ -2776,7 +2794,7 @@ int cmd_start_trace(struct ltt_session *session)
                        }
                } else {
                        DBG("Rotating session \"%s\" from its current \"NULL\" trace chunk to a new chunk",
-                                       session->name);
+                           session->name);
                        /*
                         * Rotate existing streams into the new chunk.
                         * This is a "quiet" rotation has no client has
@@ -2787,8 +2805,8 @@ int cmd_start_trace(struct ltt_session *session)
                         * was produced as the session was stopped, so the
                         * rotation should happen on reception of the command.
                         */
-                       ret = (lttng_error_code) cmd_rotate_session(session, NULL, true,
-                                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION);
+                       ret = (lttng_error_code) cmd_rotate_session(
+                               session, nullptr, true, LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -2796,7 +2814,7 @@ int cmd_start_trace(struct ltt_session *session)
        }
 
        /* Kernel tracing */
-       if (ksession != NULL) {
+       if (ksession != nullptr) {
                DBG("Start kernel tracing session %s", session->name);
                ret = (lttng_error_code) start_kernel_session(ksession);
                if (ret != LTTNG_OK) {
@@ -2832,7 +2850,7 @@ int cmd_start_trace(struct ltt_session *session)
 
        if (session->rotate_timer_period && !session->rotation_schedule_timer_enabled) {
                int int_ret = timer_session_rotation_schedule_timer_start(
-                               session, session->rotate_timer_period);
+                       session, session->rotate_timer_period);
 
                if (int_ret < 0) {
                        ERR("Failed to enable rotate timer");
@@ -2846,14 +2864,12 @@ int cmd_start_trace(struct ltt_session *session)
 error:
        if (ret == LTTNG_OK) {
                /* Flag this after a successful start. */
-               session->has_been_started |= 1;
+               session->has_been_started = true;
        } else {
-               session->active = 0;
+               session->active = false;
                /* Restore initial state on error. */
-               session->rotated_after_last_stop =
-                               session_rotated_after_last_stop;
-               session->cleared_after_last_stop =
-                               session_cleared_after_last_stop;
+               session->rotated_after_last_stop = session_rotated_after_last_stop;
+               session->cleared_after_last_stop = session_cleared_after_last_stop;
        }
 end:
        return ret;
@@ -2894,10 +2910,9 @@ int cmd_stop_trace(struct ltt_session *session)
                }
        }
 
-       DBG("Completed stop session \"%s\" (id %" PRIu64 ")", session->name,
-                       session->id);
+       DBG("Completed stop session \"%s\" (id %" PRIu64 ")", session->name, session->id);
        /* Flag inactive after a successful stop. */
-       session->active = 0;
+       session->active = false;
        ret = LTTNG_OK;
 
 error:
@@ -2908,35 +2923,35 @@ error:
  * Set the base_path of the session only if subdir of a control uris is set.
  * Return LTTNG_OK on success, otherwise LTTNG_ERR_*.
  */
-static int set_session_base_path_from_uris(struct ltt_session *session,
-               size_t nb_uri,
-               struct lttng_uri *uris)
+static int
+set_session_base_path_from_uris(struct ltt_session *session, size_t nb_uri, struct lttng_uri *uris)
 {
        int ret;
        size_t i;
 
        for (i = 0; i < nb_uri; i++) {
-               if (uris[i].stype != LTTNG_STREAM_CONTROL ||
-                               uris[i].subdir[0] == '\0') {
+               if (uris[i].stype != LTTNG_STREAM_CONTROL || uris[i].subdir[0] == '\0') {
                        /* Not interested in these URIs */
                        continue;
                }
 
-               if (session->base_path != NULL) {
+               if (session->base_path != nullptr) {
                        free(session->base_path);
-                       session->base_path = NULL;
+                       session->base_path = nullptr;
                }
 
                /* Set session base_path */
                session->base_path = strdup(uris[i].subdir);
                if (!session->base_path) {
                        PERROR("Failed to copy base path \"%s\" to session \"%s\"",
-                                       uris[i].subdir, session->name);
+                              uris[i].subdir,
+                              session->name);
                        ret = LTTNG_ERR_NOMEM;
                        goto error;
                }
                DBG2("Setting base path \"%s\" for session \"%s\"",
-                               session->base_path, session->name);
+                    session->base_path,
+                    session->name);
        }
        ret = LTTNG_OK;
 error:
@@ -2946,8 +2961,7 @@ error:
 /*
  * Command LTTNG_SET_CONSUMER_URI processed by the client thread.
  */
-int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri,
-               struct lttng_uri *uris)
+int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri, struct lttng_uri *uris)
 {
        int ret, i;
        struct ltt_kernel_session *ksess = session->kernel_session;
@@ -2975,8 +2989,7 @@ int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri,
 
        /* Set the "global" consumer URIs */
        for (i = 0; i < nb_uri; i++) {
-               ret = add_uri_to_consumer(session, session->consumer, &uris[i],
-                               LTTNG_DOMAIN_NONE);
+               ret = add_uri_to_consumer(session, session->consumer, &uris[i], LTTNG_DOMAIN_NONE);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -2986,8 +2999,9 @@ int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri,
        if (session->ust_session) {
                for (i = 0; i < nb_uri; i++) {
                        ret = add_uri_to_consumer(session,
-                                       session->ust_session->consumer,
-                                       &uris[i], LTTNG_DOMAIN_UST);
+                                                 session->ust_session->consumer,
+                                                 &uris[i],
+                                                 LTTNG_DOMAIN_UST);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -2998,8 +3012,9 @@ int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri,
        if (session->kernel_session) {
                for (i = 0; i < nb_uri; i++) {
                        ret = add_uri_to_consumer(session,
-                                       session->kernel_session->consumer,
-                                       &uris[i], LTTNG_DOMAIN_KERNEL);
+                                                 session->kernel_session->consumer,
+                                                 &uris[i],
+                                                 LTTNG_DOMAIN_KERNEL);
                        if (ret != LTTNG_OK) {
                                goto error;
                        }
@@ -3026,17 +3041,16 @@ error:
        return ret;
 }
 
-static
-enum lttng_error_code set_session_output_from_descriptor(
-               struct ltt_session *session,
-               const struct lttng_session_descriptor *descriptor)
+static enum lttng_error_code
+set_session_output_from_descriptor(struct ltt_session *session,
+                                  const struct lttng_session_descriptor *descriptor)
 {
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        enum lttng_session_descriptor_type session_type =
-                       lttng_session_descriptor_get_type(descriptor);
+               lttng_session_descriptor_get_type(descriptor);
        enum lttng_session_descriptor_output_type output_type =
-                       lttng_session_descriptor_get_output_type(descriptor);
+               lttng_session_descriptor_get_output_type(descriptor);
        struct lttng_uri uris[2] = {};
        size_t uri_count = 0;
 
@@ -3044,13 +3058,11 @@ enum lttng_error_code set_session_output_from_descriptor(
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
                goto end;
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL:
-               lttng_session_descriptor_get_local_output_uri(descriptor,
-                               &uris[0]);
+               lttng_session_descriptor_get_local_output_uri(descriptor, &uris[0]);
                uri_count = 1;
                break;
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
-               lttng_session_descriptor_get_network_output_uris(descriptor,
-                               &uris[0], &uris[1]);
+               lttng_session_descriptor_get_network_output_uris(descriptor, &uris[0], &uris[1]);
                uri_count = 2;
                break;
        default:
@@ -3061,7 +3073,7 @@ enum lttng_error_code set_session_output_from_descriptor(
        switch (session_type) {
        case LTTNG_SESSION_DESCRIPTOR_TYPE_SNAPSHOT:
        {
-               struct snapshot_output *new_output = NULL;
+               struct snapshot_output *new_output = nullptr;
 
                new_output = snapshot_output_alloc();
                if (!new_output) {
@@ -3070,12 +3082,15 @@ enum lttng_error_code set_session_output_from_descriptor(
                }
 
                ret = snapshot_output_init_with_uri(session,
-                               DEFAULT_SNAPSHOT_MAX_SIZE,
-                               NULL, uris, uri_count, session->consumer,
-                               new_output, &session->snapshot);
+                                                   DEFAULT_SNAPSHOT_MAX_SIZE,
+                                                   nullptr,
+                                                   uris,
+                                                   uri_count,
+                                                   session->consumer,
+                                                   new_output,
+                                                   &session->snapshot);
                if (ret < 0) {
-                       ret_code = (ret == -ENOMEM) ?
-                                       LTTNG_ERR_NOMEM : LTTNG_ERR_INVALID;
+                       ret_code = (ret == -ENOMEM) ? LTTNG_ERR_NOMEM : LTTNG_ERR_INVALID;
                        snapshot_output_destroy(new_output);
                        goto end;
                }
@@ -3096,16 +3111,15 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code cmd_create_session_from_descriptor(
-               struct lttng_session_descriptor *descriptor,
-               const lttng_sock_cred *creds,
-               const char *home_path)
+static enum lttng_error_code
+cmd_create_session_from_descriptor(struct lttng_session_descriptor *descriptor,
+                                  const lttng_sock_cred *creds,
+                                  const char *home_path)
 {
        int ret;
        enum lttng_error_code ret_code;
        const char *session_name;
-       struct ltt_session *new_session = NULL;
+       struct ltt_session *new_session = nullptr;
        enum lttng_session_descriptor_status descriptor_status;
 
        session_lock_list();
@@ -3117,74 +3131,71 @@ enum lttng_error_code cmd_create_session_from_descriptor(
                }
        }
 
-       descriptor_status = lttng_session_descriptor_get_session_name(
-                       descriptor, &session_name);
+       descriptor_status = lttng_session_descriptor_get_session_name(descriptor, &session_name);
        switch (descriptor_status) {
        case LTTNG_SESSION_DESCRIPTOR_STATUS_OK:
                break;
        case LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET:
-               session_name = NULL;
+               session_name = nullptr;
                break;
        default:
                ret_code = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret_code = session_create(session_name, creds->uid, creds->gid,
-                       &new_session);
+       ret_code = session_create(session_name, creds->uid, creds->gid, &new_session);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        ret_code = notification_thread_command_add_session(the_notification_thread_handle,
-                       new_session->id, new_session->name, new_session->uid, new_session->gid);
+                                                          new_session->id,
+                                                          new_session->name,
+                                                          new_session->uid,
+                                                          new_session->gid);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        /* Announce the session's destruction to the notification thread when it is destroyed. */
        ret = session_add_destroy_notifier(
-                       new_session,
-                       [](const struct ltt_session *session,
-                                       void *user_data __attribute__((unused))) {
-                               (void) notification_thread_command_remove_session(
-                                               the_notification_thread_handle, session->id);
-                       },
-                       NULL);
+               new_session,
+               [](const struct ltt_session *session, void *user_data __attribute__((unused))) {
+                       (void) notification_thread_command_remove_session(
+                               the_notification_thread_handle, session->id);
+               },
+               nullptr);
        if (ret) {
                PERROR("Failed to add notification thread command to session's destroy notifiers: session name = %s",
-                               new_session->name);
+                      new_session->name);
                ret = LTTNG_ERR_NOMEM;
                goto end;
        }
 
        if (!session_name) {
-               ret = lttng_session_descriptor_set_session_name(descriptor,
-                               new_session->name);
+               ret = lttng_session_descriptor_set_session_name(descriptor, new_session->name);
                if (ret) {
                        ret_code = LTTNG_ERR_SESSION_FAIL;
                        goto end;
                }
        }
 
-       if (!lttng_session_descriptor_is_output_destination_initialized(
-                       descriptor)) {
+       if (!lttng_session_descriptor_is_output_destination_initialized(descriptor)) {
                /*
                 * Only include the session's creation time in the output
                 * destination if the name of the session itself was
                 * not auto-generated.
                 */
                ret_code = lttng_session_descriptor_set_default_output(
-                               descriptor,
-                               session_name ? &new_session->creation_time : NULL,
-                               home_path);
+                       descriptor,
+                       session_name ? &new_session->creation_time : nullptr,
+                       home_path);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
        } else {
                new_session->has_user_specified_directory =
-                               lttng_session_descriptor_has_output_directory(
-                                       descriptor);
+                       lttng_session_descriptor_has_output_directory(descriptor);
        }
 
        switch (lttng_session_descriptor_get_type(descriptor)) {
@@ -3193,8 +3204,7 @@ enum lttng_error_code cmd_create_session_from_descriptor(
                break;
        case LTTNG_SESSION_DESCRIPTOR_TYPE_LIVE:
                new_session->live_timer =
-                               lttng_session_descriptor_live_get_timer_interval(
-                                       descriptor);
+                       lttng_session_descriptor_live_get_timer_interval(descriptor);
                break;
        default:
                break;
@@ -3204,7 +3214,7 @@ enum lttng_error_code cmd_create_session_from_descriptor(
        if (ret_code != LTTNG_OK) {
                goto end;
        }
-       new_session->consumer->enabled = 1;
+       new_session->consumer->enabled = true;
        ret_code = LTTNG_OK;
 end:
        /* Release reference provided by the session_create function. */
@@ -3217,31 +3227,31 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx, int sock,
-               struct lttng_session_descriptor **return_descriptor)
+enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx,
+                                        int sock,
+                                        struct lttng_session_descriptor **return_descriptor)
 {
        int ret;
        size_t payload_size;
        struct lttng_dynamic_buffer payload;
        struct lttng_buffer_view home_dir_view;
        struct lttng_buffer_view session_descriptor_view;
-       struct lttng_session_descriptor *session_descriptor = NULL;
+       struct lttng_session_descriptor *session_descriptor = nullptr;
        enum lttng_error_code ret_code;
 
        lttng_dynamic_buffer_init(&payload);
-       if (cmd_ctx->lsm.u.create_session.home_dir_size >=
-                       LTTNG_PATH_MAX) {
+       if (cmd_ctx->lsm.u.create_session.home_dir_size >= LTTNG_PATH_MAX) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
        if (cmd_ctx->lsm.u.create_session.session_descriptor_size >
-                       LTTNG_SESSION_DESCRIPTOR_MAX_LEN) {
+           LTTNG_SESSION_DESCRIPTOR_MAX_LEN) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
 
        payload_size = cmd_ctx->lsm.u.create_session.home_dir_size +
-                       cmd_ctx->lsm.u.create_session.session_descriptor_size;
+               cmd_ctx->lsm.u.create_session.session_descriptor_size;
        ret = lttng_dynamic_buffer_set_size(&payload, payload_size);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
@@ -3256,28 +3266,26 @@ enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx, int sock,
        }
 
        home_dir_view = lttng_buffer_view_from_dynamic_buffer(
-                       &payload,
-                       0,
-                       cmd_ctx->lsm.u.create_session.home_dir_size);
+               &payload, 0, cmd_ctx->lsm.u.create_session.home_dir_size);
        if (cmd_ctx->lsm.u.create_session.home_dir_size > 0 &&
-                       !lttng_buffer_view_is_valid(&home_dir_view)) {
+           !lttng_buffer_view_is_valid(&home_dir_view)) {
                ERR("Invalid payload in \"create session\" command: buffer too short to contain home directory");
                ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                goto error;
        }
 
        session_descriptor_view = lttng_buffer_view_from_dynamic_buffer(
-                       &payload,
-                       cmd_ctx->lsm.u.create_session.home_dir_size,
-                       cmd_ctx->lsm.u.create_session.session_descriptor_size);
+               &payload,
+               cmd_ctx->lsm.u.create_session.home_dir_size,
+               cmd_ctx->lsm.u.create_session.session_descriptor_size);
        if (!lttng_buffer_view_is_valid(&session_descriptor_view)) {
                ERR("Invalid payload in \"create session\" command: buffer too short to contain session descriptor");
                ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                goto error;
        }
 
-       ret = lttng_session_descriptor_create_from_buffer(
-                       &session_descriptor_view, &session_descriptor);
+       ret = lttng_session_descriptor_create_from_buffer(&session_descriptor_view,
+                                                         &session_descriptor);
        if (ret < 0) {
                ERR("Failed to create session descriptor from payload of \"create session\" command");
                ret_code = LTTNG_ERR_INVALID;
@@ -3289,38 +3297,36 @@ enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx, int sock,
         * needed.
         */
        ret_code = cmd_create_session_from_descriptor(session_descriptor,
-                       &cmd_ctx->creds,
-                       home_dir_view.size ? home_dir_view.data : NULL);
+                                                     &cmd_ctx->creds,
+                                                     home_dir_view.size ? home_dir_view.data :
+                                                                          nullptr);
        if (ret_code != LTTNG_OK) {
                goto error;
        }
 
        ret_code = LTTNG_OK;
        *return_descriptor = session_descriptor;
-       session_descriptor = NULL;
+       session_descriptor = nullptr;
 error:
        lttng_dynamic_buffer_reset(&payload);
        lttng_session_descriptor_destroy(session_descriptor);
        return ret_code;
 }
 
-static
-void cmd_destroy_session_reply(const struct ltt_session *session,
-               void *_reply_context)
+static void cmd_destroy_session_reply(const struct ltt_session *session, void *_reply_context)
 {
        int ret;
        ssize_t comm_ret;
        const struct cmd_destroy_session_reply_context *reply_context =
-                       (cmd_destroy_session_reply_context *) _reply_context;
+               (cmd_destroy_session_reply_context *) _reply_context;
        struct lttng_dynamic_buffer payload;
        struct lttcomm_session_destroy_command_header cmd_header;
-       struct lttng_trace_archive_location *location = NULL;
+       struct lttng_trace_archive_location *location = nullptr;
        struct lttcomm_lttng_msg llm = {
-               .cmd_type = LTTNG_DESTROY_SESSION,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION,
                .ret_code = reply_context->destruction_status,
                .pid = UINT32_MAX,
-               .cmd_header_size =
-                       sizeof(struct lttcomm_session_destroy_command_header),
+               .cmd_header_size = sizeof(struct lttcomm_session_destroy_command_header),
                .data_size = 0,
                .fd_count = 0,
        };
@@ -3334,12 +3340,10 @@ void cmd_destroy_session_reply(const struct ltt_session *session,
                goto error;
        }
 
-       cmd_header.rotation_state =
-                       (int32_t) (reply_context->implicit_rotation_on_destroy ?
-                               session->rotation_state :
-                               LTTNG_ROTATION_STATE_NO_ROTATION);
-       ret = lttng_dynamic_buffer_append(&payload, &cmd_header,
-                       sizeof(cmd_header));
+       cmd_header.rotation_state = (int32_t) (reply_context->implicit_rotation_on_destroy ?
+                                                      session->rotation_state :
+                                                      LTTNG_ROTATION_STATE_NO_ROTATION);
+       ret = lttng_dynamic_buffer_append(&payload, &cmd_header, sizeof(cmd_header));
        if (ret) {
                ERR("Failed to append session destruction command header");
                goto error;
@@ -3347,40 +3351,38 @@ void cmd_destroy_session_reply(const struct ltt_session *session,
 
        if (!reply_context->implicit_rotation_on_destroy) {
                DBG("No implicit rotation performed during the destruction of session \"%s\", sending reply",
-                               session->name);
+                   session->name);
                goto send_reply;
        }
        if (session->rotation_state != LTTNG_ROTATION_STATE_COMPLETED) {
                DBG("Rotation state of session \"%s\" is not \"completed\", sending session destruction reply",
-                               session->name);
+                   session->name);
                goto send_reply;
        }
 
        location = session_get_trace_archive_location(session);
        if (!location) {
                ERR("Failed to get the location of the trace archive produced during the destruction of session \"%s\"",
-                               session->name);
+                   session->name);
                goto error;
        }
 
        payload_size_before_location = payload.size;
-       comm_ret = lttng_trace_archive_location_serialize(location,
-                       &payload);
+       comm_ret = lttng_trace_archive_location_serialize(location, &payload);
        lttng_trace_archive_location_put(location);
        if (comm_ret < 0) {
                ERR("Failed to serialize the location of the trace archive produced during the destruction of session \"%s\"",
-                               session->name);
+                   session->name);
                goto error;
        }
        /* Update the message to indicate the location's length. */
        ((struct lttcomm_lttng_msg *) payload.data)->data_size =
-                       payload.size - payload_size_before_location;
+               payload.size - payload_size_before_location;
 send_reply:
-       comm_ret = lttcomm_send_unix_sock(reply_context->reply_sock_fd,
-                       payload.data, payload.size);
+       comm_ret = lttcomm_send_unix_sock(reply_context->reply_sock_fd, payload.data, payload.size);
        if (comm_ret != (ssize_t) payload.size) {
                ERR("Failed to send result of the destruction of session \"%s\" to client",
-                               session->name);
+                   session->name);
        }
 error:
        ret = close(reply_context->reply_sock_fd);
@@ -3396,13 +3398,11 @@ error:
  *
  * Called with session lock held.
  */
-int cmd_destroy_session(struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle,
-               int *sock_fd)
+int cmd_destroy_session(struct ltt_session *session, int *sock_fd)
 {
        int ret;
        enum lttng_error_code destruction_last_error = LTTNG_OK;
-       struct cmd_destroy_session_reply_context *reply_context = NULL;
+       struct cmd_destroy_session_reply_context *reply_context = nullptr;
 
        if (sock_fd) {
                reply_context = zmalloc<cmd_destroy_session_reply_context>();
@@ -3417,31 +3417,38 @@ int cmd_destroy_session(struct ltt_session *session,
        /* Safety net */
        LTTNG_ASSERT(session);
 
-       DBG("Begin destroy session %s (id %" PRIu64 ")", session->name,
-                       session->id);
+       DBG("Begin destroy session %s (id %" PRIu64 ")", session->name, session->id);
        if (session->active) {
                DBG("Session \"%s\" is active, attempting to stop it before destroying it",
-                               session->name);
+                   session->name);
                ret = cmd_stop_trace(session);
                if (ret != LTTNG_OK && ret != LTTNG_ERR_TRACE_ALREADY_STOPPED) {
                        /* Carry on with the destruction of the session. */
                        ERR("Failed to stop session \"%s\" as part of its destruction: %s",
-                                       session->name, lttng_strerror(-ret));
+                           session->name,
+                           lttng_strerror(-ret));
                        destruction_last_error = (lttng_error_code) ret;
                }
        }
 
        if (session->rotation_schedule_timer_enabled) {
-               if (timer_session_rotation_schedule_timer_stop(
-                               session)) {
+               if (timer_session_rotation_schedule_timer_stop(session)) {
                        ERR("Failed to stop the \"rotation schedule\" timer of session %s",
-                                       session->name);
+                           session->name);
                        destruction_last_error = LTTNG_ERR_TIMER_STOP_ERROR;
                }
        }
 
        if (session->rotate_size) {
-               unsubscribe_session_consumed_size_rotation(session, notification_thread_handle);
+               try {
+                       the_rotation_thread_handle->unsubscribe_session_consumed_size_rotation(
+                               *session);
+               } catch (const std::exception& e) {
+                       /* Continue the destruction of the session anyway. */
+                       ERR("Failed to unsubscribe rotation thread notification channel from consumed size condition during session destruction: %s",
+                           e.what());
+               }
+
                session->rotate_size = 0;
        }
 
@@ -3450,11 +3457,12 @@ int cmd_destroy_session(struct ltt_session *session,
                 * Perform a last rotation on destruction if rotations have
                 * occurred during the session's lifetime.
                 */
-               ret = cmd_rotate_session(session, NULL, false,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
+               ret = cmd_rotate_session(
+                       session, nullptr, false, LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
                if (ret != LTTNG_OK) {
                        ERR("Failed to perform an implicit rotation as part of the destruction of session \"%s\": %s",
-                                       session->name, lttng_strerror(-ret));
+                           session->name,
+                           lttng_strerror(-ret));
                        destruction_last_error = (lttng_error_code) -ret;
                }
                if (reply_context) {
@@ -3470,8 +3478,8 @@ int cmd_destroy_session(struct ltt_session *session,
                 * emitted and no renaming of the current trace chunk takes
                 * place.
                 */
-               ret = cmd_rotate_session(session, NULL, true,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION);
+               ret = cmd_rotate_session(
+                       session, nullptr, true, LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION);
                /*
                 * Rotation operations may not be supported by the kernel
                 * tracer. Hence, do not consider this implicit rotation as
@@ -3479,10 +3487,10 @@ int cmd_destroy_session(struct ltt_session *session,
                 * the session and waited for pending data; there is nothing
                 * left to do but complete the destruction of the session.
                 */
-               if (ret != LTTNG_OK &&
-                               ret != -LTTNG_ERR_ROTATION_NOT_AVAILABLE_KERNEL) {
+               if (ret != LTTNG_OK && ret != -LTTNG_ERR_ROTATION_NOT_AVAILABLE_KERNEL) {
                        ERR("Failed to perform a quiet rotation as part of the destruction of session \"%s\": %s",
-                           session->name, lttng_strerror(ret));
+                           session->name,
+                           lttng_strerror(ret));
                        destruction_last_error = (lttng_error_code) -ret;
                }
        }
@@ -3536,8 +3544,8 @@ int cmd_destroy_session(struct ltt_session *session,
                 */
                current_completion_handler = &destroy_completion_handler.handler;
                ret = lttng_strncpy(destroy_completion_handler.shm_path,
-                               session->shm_path,
-                               sizeof(destroy_completion_handler.shm_path));
+                                   session->shm_path,
+                                   sizeof(destroy_completion_handler.shm_path));
                LTTNG_ASSERT(!ret);
        }
 
@@ -3549,9 +3557,8 @@ int cmd_destroy_session(struct ltt_session *session,
        session_destroy(session);
        if (reply_context) {
                reply_context->destruction_status = destruction_last_error;
-               ret = session_add_destroy_notifier(session,
-                               cmd_destroy_session_reply,
-                               (void *) reply_context);
+               ret = session_add_destroy_notifier(
+                       session, cmd_destroy_session_reply, (void *) reply_context);
                if (ret) {
                        ret = LTTNG_ERR_FATAL;
                        goto end;
@@ -3568,11 +3575,12 @@ end:
  * Command LTTNG_REGISTER_CONSUMER processed by the client thread.
  */
 int cmd_register_consumer(struct ltt_session *session,
-               enum lttng_domain_type domain, const char *sock_path,
-               struct consumer_data *cdata)
+                         enum lttng_domain_type domain,
+                         const char *sock_path,
+                         struct consumer_data *cdata)
 {
        int ret, sock;
-       struct consumer_socket *socket = NULL;
+       struct consumer_socket *socket = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(cdata);
@@ -3599,7 +3607,7 @@ int cmd_register_consumer(struct ltt_session *session,
                cdata->cmd_sock = sock;
 
                socket = consumer_allocate_socket(&cdata->cmd_sock);
-               if (socket == NULL) {
+               if (socket == nullptr) {
                        ret = close(sock);
                        if (ret < 0) {
                                PERROR("close register consumer");
@@ -3610,18 +3618,17 @@ int cmd_register_consumer(struct ltt_session *session,
                }
 
                socket->lock = zmalloc<pthread_mutex_t>();
-               if (socket->lock == NULL) {
+               if (socket->lock == nullptr) {
                        PERROR("zmalloc pthread mutex");
                        ret = LTTNG_ERR_FATAL;
                        goto error;
                }
 
-               pthread_mutex_init(socket->lock, NULL);
+               pthread_mutex_init(socket->lock, nullptr);
                socket->registered = 1;
 
-               rcu_read_lock();
+               lttng::urcu::read_lock_guard read_lock;
                consumer_add_socket(socket, ksess->consumer);
-               rcu_read_unlock();
 
                pthread_mutex_lock(&cdata->pid_mutex);
                cdata->pid = -1;
@@ -3647,31 +3654,30 @@ error:
 /*
  * Command LTTNG_LIST_DOMAINS processed by the client thread.
  */
-ssize_t cmd_list_domains(struct ltt_session *session,
-               struct lttng_domain **domains)
+ssize_t cmd_list_domains(struct ltt_session *session, struct lttng_domain **domains)
 {
        int ret, index = 0;
        ssize_t nb_dom = 0;
        struct agent *agt;
        struct lttng_ht_iter iter;
 
-       if (session->kernel_session != NULL) {
+       if (session->kernel_session != nullptr) {
                DBG3("Listing domains found kernel domain");
                nb_dom++;
        }
 
-       if (session->ust_session != NULL) {
+       if (session->ust_session != nullptr) {
                DBG3("Listing domains found UST global domain");
                nb_dom++;
 
-               rcu_read_lock();
-               cds_lfht_for_each_entry(session->ust_session->agents->ht, &iter.iter,
-                               agt, node.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       session->ust_session->agents->ht, &iter.iter, agt, node.node) {
                        if (agt->being_used) {
                                nb_dom++;
                        }
                }
-               rcu_read_unlock();
        }
 
        if (!nb_dom) {
@@ -3679,12 +3685,12 @@ ssize_t cmd_list_domains(struct ltt_session *session,
        }
 
        *domains = calloc<lttng_domain>(nb_dom);
-       if (*domains == NULL) {
+       if (*domains == nullptr) {
                ret = LTTNG_ERR_FATAL;
                goto error;
        }
 
-       if (session->kernel_session != NULL) {
+       if (session->kernel_session != nullptr) {
                (*domains)[index].type = LTTNG_DOMAIN_KERNEL;
 
                /* Kernel session buffer type is always GLOBAL */
@@ -3693,21 +3699,24 @@ ssize_t cmd_list_domains(struct ltt_session *session,
                index++;
        }
 
-       if (session->ust_session != NULL) {
+       if (session->ust_session != nullptr) {
                (*domains)[index].type = LTTNG_DOMAIN_UST;
                (*domains)[index].buf_type = session->ust_session->buffer_type;
                index++;
 
-               rcu_read_lock();
-               cds_lfht_for_each_entry(session->ust_session->agents->ht, &iter.iter,
-                               agt, node.node) {
-                       if (agt->being_used) {
-                               (*domains)[index].type = agt->domain;
-                               (*domains)[index].buf_type = session->ust_session->buffer_type;
-                               index++;
+               {
+                       lttng::urcu::read_lock_guard read_lock;
+
+                       cds_lfht_for_each_entry (
+                               session->ust_session->agents->ht, &iter.iter, agt, node.node) {
+                               if (agt->being_used) {
+                                       (*domains)[index].type = agt->domain;
+                                       (*domains)[index].buf_type =
+                                               session->ust_session->buffer_type;
+                                       index++;
+                               }
                        }
                }
-               rcu_read_unlock();
        }
 end:
        return nb_dom;
@@ -3717,13 +3726,12 @@ error:
        return -ret;
 }
 
-
 /*
  * Command LTTNG_LIST_CHANNELS processed by the client thread.
  */
 enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
-               struct ltt_session *session,
-               struct lttng_payload *payload)
+                                       struct ltt_session *session,
+                                       struct lttng_payload *payload)
 {
        int ret = 0;
        unsigned int i = 0;
@@ -3740,7 +3748,7 @@ enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
 
        /* Reserve space for command reply header. */
        ret = lttng_dynamic_buffer_set_size(&payload->buffer,
-                       cmd_header_offset + sizeof(cmd_header));
+                                           cmd_header_offset + sizeof(cmd_header));
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -3751,17 +3759,17 @@ enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
        {
                /* Kernel channels */
                struct ltt_kernel_channel *kchan;
-               if (session->kernel_session != NULL) {
-                       cds_list_for_each_entry(kchan,
-                                       &session->kernel_session->channel_list.head, list) {
+               if (session->kernel_session != nullptr) {
+                       cds_list_for_each_entry (
+                               kchan, &session->kernel_session->channel_list.head, list) {
                                uint64_t discarded_events, lost_packets;
                                struct lttng_channel_extended *extended;
 
                                extended = (struct lttng_channel_extended *)
-                                               kchan->channel->attr.extended.ptr;
+                                                  kchan->channel->attr.extended.ptr;
 
-                               ret = get_kernel_runtime_stats(session, kchan,
-                                               &discarded_events, &lost_packets);
+                               ret = get_kernel_runtime_stats(
+                                       session, kchan, &discarded_events, &lost_packets);
                                if (ret < 0) {
                                        ret_code = LTTNG_ERR_UNK;
                                        goto end;
@@ -3774,11 +3782,10 @@ enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
                                extended->discarded_events = discarded_events;
                                extended->lost_packets = lost_packets;
 
-                               ret = lttng_channel_serialize(
-                                               kchan->channel, &payload->buffer);
+                               ret = lttng_channel_serialize(kchan->channel, &payload->buffer);
                                if (ret) {
                                        ERR("Failed to serialize lttng_channel: channel name = '%s'",
-                                                       kchan->channel->name);
+                                           kchan->channel->name);
                                        ret_code = LTTNG_ERR_UNK;
                                        goto end;
                                }
@@ -3793,47 +3800,51 @@ enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
                struct lttng_ht_iter iter;
                struct ltt_ust_channel *uchan;
 
-               rcu_read_lock();
-               cds_lfht_for_each_entry(session->ust_session->domain_global.channels->ht,
-                               &iter.iter, uchan, node.node) {
-                       uint64_t discarded_events = 0, lost_packets = 0;
-                       struct lttng_channel *channel = NULL;
-                       struct lttng_channel_extended *extended;
+               {
+                       lttng::urcu::read_lock_guard read_lock;
+
+                       cds_lfht_for_each_entry (session->ust_session->domain_global.channels->ht,
+                                                &iter.iter,
+                                                uchan,
+                                                node.node) {
+                               uint64_t discarded_events = 0, lost_packets = 0;
+                               struct lttng_channel *channel = nullptr;
+                               struct lttng_channel_extended *extended;
 
-                       channel = trace_ust_channel_to_lttng_channel(uchan);
-                       if (!channel) {
-                               ret_code = LTTNG_ERR_NOMEM;
-                               goto end;
-                       }
+                               channel = trace_ust_channel_to_lttng_channel(uchan);
+                               if (!channel) {
+                                       ret_code = LTTNG_ERR_NOMEM;
+                                       goto end;
+                               }
 
-                       extended = (struct lttng_channel_extended *)
+                               extended = (struct lttng_channel_extended *)
                                                   channel->attr.extended.ptr;
 
-                       ret = get_ust_runtime_stats(session, uchan,
-                                       &discarded_events, &lost_packets);
-                       if (ret < 0) {
-                               lttng_channel_destroy(channel);
-                               ret_code = LTTNG_ERR_UNK;
-                               goto end;
-                       }
+                               ret = get_ust_runtime_stats(
+                                       session, uchan, &discarded_events, &lost_packets);
+                               if (ret < 0) {
+                                       lttng_channel_destroy(channel);
+                                       ret_code = LTTNG_ERR_UNK;
+                                       goto end;
+                               }
 
-                       extended->discarded_events = discarded_events;
-                       extended->lost_packets = lost_packets;
+                               extended->discarded_events = discarded_events;
+                               extended->lost_packets = lost_packets;
+
+                               ret = lttng_channel_serialize(channel, &payload->buffer);
+                               if (ret) {
+                                       ERR("Failed to serialize lttng_channel: channel name = '%s'",
+                                           channel->name);
+                                       lttng_channel_destroy(channel);
+                                       ret_code = LTTNG_ERR_UNK;
+                                       goto end;
+                               }
 
-                       ret = lttng_channel_serialize(
-                                       channel, &payload->buffer);
-                       if (ret) {
-                               ERR("Failed to serialize lttng_channel: channel name = '%s'",
-                                               channel->name);
                                lttng_channel_destroy(channel);
-                               ret_code = LTTNG_ERR_UNK;
-                               goto end;
+                               i++;
                        }
-
-                       lttng_channel_destroy(channel);
-                       i++;
                }
-               rcu_read_unlock();
+
                break;
        }
        default:
@@ -3848,8 +3859,7 @@ enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
 
        /* Update command reply header. */
        cmd_header.count = (uint32_t) i;
-       memcpy(payload->buffer.data + cmd_header_offset, &cmd_header,
-                       sizeof(cmd_header));
+       memcpy(payload->buffer.data + cmd_header_offset, &cmd_header, sizeof(cmd_header));
        ret_code = LTTNG_OK;
 
 end:
@@ -3860,9 +3870,9 @@ end:
  * Command LTTNG_LIST_EVENTS processed by the client thread.
  */
 enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
-               struct ltt_session *session,
-               char *channel_name,
-               struct lttng_payload *reply_payload)
+                                     struct ltt_session *session,
+                                     char *channel_name,
+                                     struct lttng_payload *reply_payload)
 {
        int buffer_resize_ret;
        enum lttng_error_code ret_code = LTTNG_OK;
@@ -3874,9 +3884,9 @@ enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
 
        /* Reserve space for command reply header. */
        reply_command_header_offset = reply_payload->buffer.size;
-       buffer_resize_ret = lttng_dynamic_buffer_set_size(&reply_payload->buffer,
-                       reply_command_header_offset +
-                                       sizeof(struct lttcomm_list_command_header));
+       buffer_resize_ret = lttng_dynamic_buffer_set_size(
+               &reply_payload->buffer,
+               reply_command_header_offset + sizeof(struct lttcomm_list_command_header));
        if (buffer_resize_ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -3884,18 +3894,20 @@ enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
 
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
-               if (session->kernel_session != NULL) {
-                       ret_code = list_lttng_kernel_events(channel_name,
-                                       session->kernel_session, reply_payload, &nb_events);
+               if (session->kernel_session != nullptr) {
+                       ret_code = list_lttng_kernel_events(
+                               channel_name, session->kernel_session, reply_payload, &nb_events);
                }
 
                break;
        case LTTNG_DOMAIN_UST:
        {
-               if (session->ust_session != NULL) {
-                       ret_code = list_lttng_ust_global_events(channel_name,
-                                       &session->ust_session->domain_global,
-                                       reply_payload, &nb_events);
+               if (session->ust_session != nullptr) {
+                       ret_code =
+                               list_lttng_ust_global_events(channel_name,
+                                                            &session->ust_session->domain_global,
+                                                            reply_payload,
+                                                            &nb_events);
                }
 
                break;
@@ -3907,17 +3919,16 @@ enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
                        struct lttng_ht_iter iter;
                        struct agent *agt;
 
-                       rcu_read_lock();
-                       cds_lfht_for_each_entry(session->ust_session->agents->ht,
-                                       &iter.iter, agt, node.node) {
+                       lttng::urcu::read_lock_guard read_lock;
+
+                       cds_lfht_for_each_entry (
+                               session->ust_session->agents->ht, &iter.iter, agt, node.node) {
                                if (agt->domain == domain) {
                                        ret_code = list_lttng_agent_events(
-                                                       agt, reply_payload, &nb_events);
+                                               agt, reply_payload, &nb_events);
                                        break;
                                }
                        }
-
-                       rcu_read_unlock();
                }
                break;
        default:
@@ -3932,8 +3943,9 @@ enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
 
        /* Update command reply header. */
        reply_command_header.count = (uint32_t) nb_events;
-       memcpy(reply_payload->buffer.data + reply_command_header_offset, &reply_command_header,
-                       sizeof(reply_command_header));
+       memcpy(reply_payload->buffer.data + reply_command_header_offset,
+              &reply_command_header,
+              sizeof(reply_command_header));
 
 end:
        return ret_code;
@@ -3947,30 +3959,29 @@ end:
  * session_lock_list() and session_unlock_list().
  */
 void cmd_list_lttng_sessions(struct lttng_session *sessions,
-               size_t session_count, uid_t uid, gid_t gid)
+                            size_t session_count,
+                            uid_t uid,
+                            gid_t gid)
 {
        int ret;
        unsigned int i = 0;
        struct ltt_session *session;
        struct ltt_session_list *list = session_get_list();
-       struct lttng_session_extended *extended =
-                       (typeof(extended)) (&sessions[session_count]);
+       struct lttng_session_extended *extended = (typeof(extended)) (&sessions[session_count]);
 
-       DBG("Getting all available session for UID %d GID %d",
-                       uid, gid);
+       DBG("Getting all available session for UID %d GID %d", uid, gid);
        /*
         * Iterate over session list and append data after the control struct in
         * the buffer.
         */
-       cds_list_for_each_entry(session, &list->head, list) {
+       cds_list_for_each_entry (session, &list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
                /*
                 * Only list the sessions the user can control.
                 */
-               if (!session_access_ok(session, uid) ||
-                               session->destroyed) {
+               if (!session_access_ok(session, uid) || session->destroyed) {
                        session_put(session);
                        continue;
                }
@@ -3979,13 +3990,15 @@ void cmd_list_lttng_sessions(struct lttng_session *sessions,
                struct ltt_ust_session *usess = session->ust_session;
 
                if (session->consumer->type == CONSUMER_DST_NET ||
-                               (ksess && ksess->consumer->type == CONSUMER_DST_NET) ||
-                               (usess && usess->consumer->type == CONSUMER_DST_NET)) {
-                       ret = build_network_session_path(sessions[i].path,
-                                       sizeof(sessions[i].path), session);
+                   (ksess && ksess->consumer->type == CONSUMER_DST_NET) ||
+                   (usess && usess->consumer->type == CONSUMER_DST_NET)) {
+                       ret = build_network_session_path(
+                               sessions[i].path, sizeof(sessions[i].path), session);
                } else {
-                       ret = snprintf(sessions[i].path, sizeof(sessions[i].path), "%s",
-                                       session->consumer->dst.session_root_path);
+                       ret = snprintf(sessions[i].path,
+                                      sizeof(sessions[i].path),
+                                      "%s",
+                                      session->consumer->dst.session_root_path);
                }
                if (ret < 0) {
                        PERROR("snprintf session path");
@@ -4005,6 +4018,19 @@ void cmd_list_lttng_sessions(struct lttng_session *sessions,
        }
 }
 
+/*
+ * Command LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS
+ */
+enum lttng_error_code cmd_kernel_tracer_status(enum lttng_kernel_tracer_status *status)
+{
+       if (status == nullptr) {
+               return LTTNG_ERR_INVALID;
+       }
+
+       *status = get_kernel_tracer_status();
+       return LTTNG_OK;
+}
+
 /*
  * Command LTTNG_DATA_PENDING returning 0 if the data is NOT pending meaning
  * ready for trace analysis (or any kind of reader) or else 1 for pending data.
@@ -4076,7 +4102,8 @@ error:
  * Return LTTNG_OK on success or else a LTTNG_ERR code.
  */
 int cmd_snapshot_add_output(struct ltt_session *session,
-               const struct lttng_snapshot_output *output, uint32_t *id)
+                           const struct lttng_snapshot_output *output,
+                           uint32_t *id)
 {
        int ret;
        struct snapshot_output *new_output;
@@ -4111,9 +4138,14 @@ int cmd_snapshot_add_output(struct ltt_session *session,
                goto error;
        }
 
-       ret = snapshot_output_init(session, output->max_size, output->name,
-                       output->ctrl_url, output->data_url, session->consumer, new_output,
-                       &session->snapshot);
+       ret = snapshot_output_init(session,
+                                  output->max_size,
+                                  output->name,
+                                  output->ctrl_url,
+                                  output->data_url,
+                                  session->consumer,
+                                  new_output,
+                                  &session->snapshot);
        if (ret < 0) {
                if (ret == -ENOMEM) {
                        ret = LTTNG_ERR_NOMEM;
@@ -4123,12 +4155,10 @@ int cmd_snapshot_add_output(struct ltt_session *session,
                goto free_error;
        }
 
-       rcu_read_lock();
        snapshot_add_output(&session->snapshot, new_output);
        if (id) {
                *id = new_output->id;
        }
-       rcu_read_unlock();
 
        return LTTNG_OK;
 
@@ -4143,16 +4173,15 @@ error:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR code.
  */
-int cmd_snapshot_del_output(struct ltt_session *session,
-               const struct lttng_snapshot_output *output)
+int cmd_snapshot_del_output(struct ltt_session *session, const struct lttng_snapshot_output *output)
 {
        int ret;
-       struct snapshot_output *sout = NULL;
+       struct snapshot_output *sout = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(output);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * Permission denied to create an output if the session is not
@@ -4164,12 +4193,12 @@ int cmd_snapshot_del_output(struct ltt_session *session,
        }
 
        if (output->id) {
-               DBG("Cmd snapshot del output id %" PRIu32 " for session %s", output->id,
-                               session->name);
+               DBG("Cmd snapshot del output id %" PRIu32 " for session %s",
+                   output->id,
+                   session->name);
                sout = snapshot_find_output_by_id(output->id, &session->snapshot);
        } else if (*output->name != '\0') {
-               DBG("Cmd snapshot del output name %s for session %s", output->name,
-                               session->name);
+               DBG("Cmd snapshot del output name %s for session %s", output->name, session->name);
                sout = snapshot_find_output_by_name(output->name, &session->snapshot);
        }
        if (!sout) {
@@ -4182,7 +4211,6 @@ int cmd_snapshot_del_output(struct ltt_session *session,
        ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -4194,10 +4222,10 @@ error:
  * Return the size of the newly allocated outputs or a negative LTTNG_ERR code.
  */
 ssize_t cmd_snapshot_list_outputs(struct ltt_session *session,
-               struct lttng_snapshot_output **outputs)
+                                 struct lttng_snapshot_output **outputs)
 {
        int ret, idx = 0;
-       struct lttng_snapshot_output *list = NULL;
+       struct lttng_snapshot_output *list = nullptr;
        struct lttng_ht_iter iter;
        struct snapshot_output *output;
 
@@ -4227,49 +4255,54 @@ ssize_t cmd_snapshot_list_outputs(struct ltt_session *session,
        }
 
        /* Copy list from session to the new list object. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(session->snapshot.output_ht->ht, &iter.iter,
-                       output, node.node) {
-               LTTNG_ASSERT(output->consumer);
-               list[idx].id = output->id;
-               list[idx].max_size = output->max_size;
-               if (lttng_strncpy(list[idx].name, output->name,
-                               sizeof(list[idx].name))) {
-                       ret = -LTTNG_ERR_INVALID;
-                       goto error;
-               }
-               if (output->consumer->type == CONSUMER_DST_LOCAL) {
-                       if (lttng_strncpy(list[idx].ctrl_url,
-                                       output->consumer->dst.session_root_path,
-                                       sizeof(list[idx].ctrl_url))) {
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       session->snapshot.output_ht->ht, &iter.iter, output, node.node) {
+                       LTTNG_ASSERT(output->consumer);
+                       list[idx].id = output->id;
+                       list[idx].max_size = output->max_size;
+                       if (lttng_strncpy(list[idx].name, output->name, sizeof(list[idx].name))) {
                                ret = -LTTNG_ERR_INVALID;
                                goto error;
                        }
-               } else {
-                       /* Control URI. */
-                       ret = uri_to_str_url(&output->consumer->dst.net.control,
-                                       list[idx].ctrl_url, sizeof(list[idx].ctrl_url));
-                       if (ret < 0) {
-                               ret = -LTTNG_ERR_NOMEM;
-                               goto error;
-                       }
 
-                       /* Data URI. */
-                       ret = uri_to_str_url(&output->consumer->dst.net.data,
-                                       list[idx].data_url, sizeof(list[idx].data_url));
-                       if (ret < 0) {
-                               ret = -LTTNG_ERR_NOMEM;
-                               goto error;
+                       if (output->consumer->type == CONSUMER_DST_LOCAL) {
+                               if (lttng_strncpy(list[idx].ctrl_url,
+                                                 output->consumer->dst.session_root_path,
+                                                 sizeof(list[idx].ctrl_url))) {
+                                       ret = -LTTNG_ERR_INVALID;
+                                       goto error;
+                               }
+                       } else {
+                               /* Control URI. */
+                               ret = uri_to_str_url(&output->consumer->dst.net.control,
+                                                    list[idx].ctrl_url,
+                                                    sizeof(list[idx].ctrl_url));
+                               if (ret < 0) {
+                                       ret = -LTTNG_ERR_NOMEM;
+                                       goto error;
+                               }
+
+                               /* Data URI. */
+                               ret = uri_to_str_url(&output->consumer->dst.net.data,
+                                                    list[idx].data_url,
+                                                    sizeof(list[idx].data_url));
+                               if (ret < 0) {
+                                       ret = -LTTNG_ERR_NOMEM;
+                                       goto error;
+                               }
                        }
+
+                       idx++;
                }
-               idx++;
        }
 
        *outputs = list;
-       list = NULL;
+       list = nullptr;
        ret = session->snapshot.nb_output;
 error:
-       rcu_read_unlock();
        free(list);
 end:
        return ret;
@@ -4281,8 +4314,7 @@ end:
  *
  * Return 0 if the metadata can be generated, a LTTNG_ERR code otherwise.
  */
-static
-int check_regenerate_metadata_support(struct ltt_session *session)
+static int check_regenerate_metadata_support(struct ltt_session *session)
 {
        int ret;
 
@@ -4310,7 +4342,7 @@ int check_regenerate_metadata_support(struct ltt_session *session)
                }
        }
        if (session->consumer->type == CONSUMER_DST_NET &&
-                       session->consumer->relay_minor_version < 8) {
+           session->consumer->relay_minor_version < 8) {
                ret = LTTNG_ERR_RELAYD_VERSION_FAIL;
                goto end;
        }
@@ -4341,8 +4373,7 @@ int cmd_regenerate_metadata(struct ltt_session *session)
        }
 
        if (session->kernel_session) {
-               ret = kernctl_session_regenerate_metadata(
-                               session->kernel_session->fd);
+               ret = kernctl_session_regenerate_metadata(session->kernel_session->fd);
                if (ret < 0) {
                        ERR("Failed to regenerate the kernel metadata");
                        goto end;
@@ -4382,8 +4413,7 @@ int cmd_regenerate_statedump(struct ltt_session *session)
        }
 
        if (session->kernel_session) {
-               ret = kernctl_session_regenerate_statedump(
-                               session->kernel_session->fd);
+               ret = kernctl_session_regenerate_statedump(session->kernel_session->fd);
                /*
                 * Currently, the statedump in kernel can only fail if out
                 * of memory.
@@ -4417,31 +4447,28 @@ end:
        return ret;
 }
 
-static
-enum lttng_error_code synchronize_tracer_notifier_register(
-               struct notification_thread_handle *notification_thread,
-               struct lttng_trigger *trigger, const struct lttng_credentials *cmd_creds)
+static enum lttng_error_code
+synchronize_tracer_notifier_register(struct notification_thread_handle *notification_thread,
+                                    struct lttng_trigger *trigger,
+                                    const struct lttng_credentials *cmd_creds)
 {
        enum lttng_error_code ret_code;
-       const struct lttng_condition *condition =
-                       lttng_trigger_get_const_condition(trigger);
+       const struct lttng_condition *condition = lttng_trigger_get_const_condition(trigger);
        const char *trigger_name;
        uid_t trigger_owner;
        enum lttng_trigger_status trigger_status;
        const enum lttng_domain_type trigger_domain =
-                       lttng_trigger_get_underlying_domain_type_restriction(
-                                       trigger);
+               lttng_trigger_get_underlying_domain_type_restriction(trigger);
 
        trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_owner);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
        trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
-       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
+       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
 
        session_lock_list();
        switch (trigger_domain) {
@@ -4452,16 +4479,18 @@ enum lttng_error_code synchronize_tracer_notifier_register(
                        enum lttng_error_code notif_thread_unregister_ret;
 
                        notif_thread_unregister_ret =
-                                       notification_thread_command_unregister_trigger(
-                                               notification_thread, trigger);
+                               notification_thread_command_unregister_trigger(notification_thread,
+                                                                              trigger);
 
                        if (notif_thread_unregister_ret != LTTNG_OK) {
                                /* Return the original error code. */
                                ERR("Failed to unregister trigger from notification thread during error recovery: trigger name = '%s', trigger owner uid = %d, error code = %d",
-                                               trigger_name,
-                                               (int) trigger_owner,
-                                               ret_code);
+                                   trigger_name,
+                                   (int) trigger_owner,
+                                   ret_code);
                        }
+
+                       goto end_unlock_session_list;
                }
                break;
        }
@@ -4473,8 +4502,7 @@ enum lttng_error_code synchronize_tracer_notifier_register(
        case LTTNG_DOMAIN_PYTHON:
        {
                /* Agent domains. */
-               struct agent *agt = agent_find_by_event_notifier_domain(
-                               trigger_domain);
+               struct agent *agt = agent_find_by_event_notifier_domain(trigger_domain);
 
                if (!agt) {
                        agt = agent_create(trigger_domain);
@@ -4505,10 +4533,10 @@ end_unlock_session_list:
 }
 
 enum lttng_error_code cmd_register_trigger(const struct lttng_credentials *cmd_creds,
-               struct lttng_trigger *trigger,
-               bool is_trigger_anonymous,
-               struct notification_thread_handle *notification_thread,
-               struct lttng_trigger **return_trigger)
+                                          struct lttng_trigger *trigger,
+                                          bool is_trigger_anonymous,
+                                          struct notification_thread_handle *notification_thread,
+                                          struct lttng_trigger **return_trigger)
 {
        enum lttng_error_code ret_code;
        const char *trigger_name;
@@ -4516,29 +4544,27 @@ enum lttng_error_code cmd_register_trigger(const struct lttng_credentials *cmd_c
        enum lttng_trigger_status trigger_status;
 
        trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
-       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
+       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
 
-       trigger_status = lttng_trigger_get_owner_uid(
-               trigger, &trigger_owner);
+       trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_owner);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        DBG("Running register trigger command: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                       trigger_name, (int) trigger_owner,
-                       (int) lttng_credentials_get_uid(cmd_creds));
+           trigger_name,
+           (int) trigger_owner,
+           (int) lttng_credentials_get_uid(cmd_creds));
 
        /*
         * Validate the trigger credentials against the command credentials.
         * Only the root user can register a trigger with non-matching
         * credentials.
         */
-       if (!lttng_credentials_is_equal_uid(
-                       lttng_trigger_get_credentials(trigger),
-                       cmd_creds)) {
+       if (!lttng_credentials_is_equal_uid(lttng_trigger_get_credentials(trigger), cmd_creds)) {
                if (lttng_credentials_get_uid(cmd_creds) != 0) {
                        ERR("Trigger credentials do not match the command credentials: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                                       trigger_name, (int) trigger_owner,
-                                       (int) lttng_credentials_get_uid(cmd_creds));
+                           trigger_name,
+                           (int) trigger_owner,
+                           (int) lttng_credentials_get_uid(cmd_creds));
                        ret_code = LTTNG_ERR_INVALID_TRIGGER;
                        goto end;
                }
@@ -4551,7 +4577,9 @@ enum lttng_error_code cmd_register_trigger(const struct lttng_credentials *cmd_c
        ret_code = lttng_trigger_generate_bytecode(trigger, cmd_creds);
        if (ret_code != LTTNG_OK) {
                ERR("Failed to generate bytecode of trigger: trigger name = '%s', trigger owner uid = %d, error code = %d",
-                               trigger_name, (int) trigger_owner, ret_code);
+                   trigger_name,
+                   (int) trigger_owner,
+                   ret_code);
                goto end;
        }
 
@@ -4566,26 +4594,26 @@ enum lttng_error_code cmd_register_trigger(const struct lttng_credentials *cmd_c
         * immutable.
         */
        ret_code = notification_thread_command_register_trigger(
-                       notification_thread, trigger, is_trigger_anonymous);
+               notification_thread, trigger, is_trigger_anonymous);
        if (ret_code != LTTNG_OK) {
                DBG("Failed to register trigger to notification thread: trigger name = '%s', trigger owner uid = %d, error code = %d",
-                               trigger_name, (int) trigger_owner, ret_code);
+                   trigger_name,
+                   (int) trigger_owner,
+                   ret_code);
                goto end;
        }
 
        trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
-       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
+       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
 
        /*
         * Synchronize tracers if the trigger adds an event notifier.
         */
        if (lttng_trigger_needs_tracer_notifier(trigger)) {
-               ret_code = synchronize_tracer_notifier_register(notification_thread,
-                               trigger, cmd_creds);
+               ret_code = synchronize_tracer_notifier_register(
+                       notification_thread, trigger, cmd_creds);
                if (ret_code != LTTNG_OK) {
-                       ERR("Error registering tracer notifier: %s",
-                                       lttng_strerror(-ret_code));
+                       ERR("Error registering tracer notifier: %s", lttng_strerror(-ret_code));
                        goto end;
                }
        }
@@ -4601,26 +4629,23 @@ enum lttng_error_code cmd_register_trigger(const struct lttng_credentials *cmd_c
                lttng_trigger_get(trigger);
                *return_trigger = trigger;
                /* Ownership of trigger was transferred to caller. */
-               trigger = NULL;
+               trigger = nullptr;
        }
 end:
        return ret_code;
 }
 
-static
-enum lttng_error_code synchronize_tracer_notifier_unregister(
-               const struct lttng_trigger *trigger)
+static enum lttng_error_code
+synchronize_tracer_notifier_unregister(const struct lttng_trigger *trigger)
 {
        enum lttng_error_code ret_code;
-       const struct lttng_condition *condition =
-                       lttng_trigger_get_const_condition(trigger);
+       const struct lttng_condition *condition = lttng_trigger_get_const_condition(trigger);
        const enum lttng_domain_type trigger_domain =
-                       lttng_trigger_get_underlying_domain_type_restriction(
-                                       trigger);
+               lttng_trigger_get_underlying_domain_type_restriction(trigger);
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
        session_lock_list();
        switch (trigger_domain) {
@@ -4639,8 +4664,7 @@ enum lttng_error_code synchronize_tracer_notifier_unregister(
        case LTTNG_DOMAIN_PYTHON:
        {
                /* Agent domains. */
-               struct agent *agt = agent_find_by_event_notifier_domain(
-                               trigger_domain);
+               struct agent *agt = agent_find_by_event_notifier_domain(trigger_domain);
 
                /*
                 * This trigger was never registered in the first place. Calling
@@ -4667,14 +4691,14 @@ end_unlock_session_list:
 }
 
 enum lttng_error_code cmd_unregister_trigger(const struct lttng_credentials *cmd_creds,
-               const struct lttng_trigger *trigger,
-               struct notification_thread_handle *notification_thread)
+                                            const struct lttng_trigger *trigger,
+                                            struct notification_thread_handle *notification_thread)
 {
        enum lttng_error_code ret_code;
        const char *trigger_name;
        uid_t trigger_owner;
        enum lttng_trigger_status trigger_status;
-       struct lttng_trigger *sessiond_trigger = NULL;
+       struct lttng_trigger *sessiond_trigger = nullptr;
 
        trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
        trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
@@ -4682,21 +4706,21 @@ enum lttng_error_code cmd_unregister_trigger(const struct lttng_credentials *cmd
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        DBG("Running unregister trigger command: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                       trigger_name, (int) trigger_owner,
-                       (int) lttng_credentials_get_uid(cmd_creds));
+           trigger_name,
+           (int) trigger_owner,
+           (int) lttng_credentials_get_uid(cmd_creds));
 
        /*
         * Validate the trigger credentials against the command credentials.
         * Only the root user can unregister a trigger with non-matching
         * credentials.
         */
-       if (!lttng_credentials_is_equal_uid(
-                       lttng_trigger_get_credentials(trigger),
-                       cmd_creds)) {
+       if (!lttng_credentials_is_equal_uid(lttng_trigger_get_credentials(trigger), cmd_creds)) {
                if (lttng_credentials_get_uid(cmd_creds) != 0) {
                        ERR("Trigger credentials do not match the command credentials: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                                       trigger_name, (int) trigger_owner,
-                                       (int) lttng_credentials_get_uid(cmd_creds));
+                           trigger_name,
+                           (int) trigger_owner,
+                           (int) lttng_credentials_get_uid(cmd_creds));
                        ret_code = LTTNG_ERR_INVALID_TRIGGER;
                        goto end;
                }
@@ -4704,10 +4728,12 @@ enum lttng_error_code cmd_unregister_trigger(const struct lttng_credentials *cmd
 
        /* Fetch the sessiond side trigger object. */
        ret_code = notification_thread_command_get_trigger(
-                       notification_thread, trigger, &sessiond_trigger);
+               notification_thread, trigger, &sessiond_trigger);
        if (ret_code != LTTNG_OK) {
                DBG("Failed to get trigger from notification thread during unregister: trigger name = '%s', trigger owner uid = %d, error code = %d",
-                               trigger_name, (int) trigger_owner, ret_code);
+                   trigger_name,
+                   (int) trigger_owner,
+                   ret_code);
                goto end;
        }
 
@@ -4724,11 +4750,12 @@ enum lttng_error_code cmd_unregister_trigger(const struct lttng_credentials *cmd
         */
        lttng_trigger_set_as_unregistered(sessiond_trigger);
 
-       ret_code = notification_thread_command_unregister_trigger(notification_thread,
-                                                                 trigger);
+       ret_code = notification_thread_command_unregister_trigger(notification_thread, trigger);
        if (ret_code != LTTNG_OK) {
                DBG("Failed to unregister trigger from notification thread: trigger name = '%s', trigger owner uid = %d, error code = %d",
-                               trigger_name, (int) trigger_owner, ret_code);
+                   trigger_name,
+                   (int) trigger_owner,
+                   ret_code);
                goto end;
        }
 
@@ -4744,7 +4771,6 @@ enum lttng_error_code cmd_unregister_trigger(const struct lttng_credentials *cmd
                        ERR("Error unregistering trigger to tracer.");
                        goto end;
                }
-
        }
 
 end:
@@ -4753,16 +4779,16 @@ end:
 }
 
 enum lttng_error_code cmd_list_triggers(struct command_ctx *cmd_ctx,
-               struct notification_thread_handle *notification_thread,
-               struct lttng_triggers **return_triggers)
+                                       struct notification_thread_handle *notification_thread,
+                                       struct lttng_triggers **return_triggers)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
 
        /* Get the set of triggers from the notification thread. */
        ret_code = notification_thread_command_list_triggers(
-                       notification_thread, cmd_ctx->creds.uid, &triggers);
+               notification_thread, cmd_ctx->creds.uid, &triggers);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
@@ -4774,38 +4800,37 @@ enum lttng_error_code cmd_list_triggers(struct command_ctx *cmd_ctx,
        }
 
        *return_triggers = triggers;
-       triggers = NULL;
+       triggers = nullptr;
        ret_code = LTTNG_OK;
 end:
        lttng_triggers_destroy(triggers);
        return ret_code;
 }
 
-enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cmd_creds,
-               const struct lttng_error_query *query,
-               struct lttng_error_query_results **_results,
-               struct notification_thread_handle *notification_thread)
+enum lttng_error_code
+cmd_execute_error_query(const struct lttng_credentials *cmd_creds,
+                       const struct lttng_error_query *query,
+                       struct lttng_error_query_results **_results,
+                       struct notification_thread_handle *notification_thread)
 {
        enum lttng_error_code ret_code;
        const struct lttng_trigger *query_target_trigger;
-       const struct lttng_action *query_target_action = NULL;
-       struct lttng_trigger *matching_trigger = NULL;
+       const struct lttng_action *query_target_action = nullptr;
+       struct lttng_trigger *matching_trigger = nullptr;
        const char *trigger_name;
        uid_t trigger_owner;
        enum lttng_trigger_status trigger_status;
-       struct lttng_error_query_results *results = NULL;
+       struct lttng_error_query_results *results = nullptr;
 
        switch (lttng_error_query_get_target_type(query)) {
        case LTTNG_ERROR_QUERY_TARGET_TYPE_TRIGGER:
                query_target_trigger = lttng_error_query_trigger_borrow_target(query);
                break;
        case LTTNG_ERROR_QUERY_TARGET_TYPE_CONDITION:
-               query_target_trigger =
-                               lttng_error_query_condition_borrow_target(query);
+               query_target_trigger = lttng_error_query_condition_borrow_target(query);
                break;
        case LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION:
-               query_target_trigger = lttng_error_query_action_borrow_trigger_target(
-                               query);
+               query_target_trigger = lttng_error_query_action_borrow_trigger_target(query);
                break;
        default:
                abort();
@@ -4813,28 +4838,24 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
 
        LTTNG_ASSERT(query_target_trigger);
 
-       ret_code = notification_thread_command_get_trigger(notification_thread,
-                       query_target_trigger, &matching_trigger);
+       ret_code = notification_thread_command_get_trigger(
+               notification_thread, query_target_trigger, &matching_trigger);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        /* No longer needed. */
-       query_target_trigger = NULL;
+       query_target_trigger = nullptr;
 
-       if (lttng_error_query_get_target_type(query) ==
-                       LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION) {
+       if (lttng_error_query_get_target_type(query) == LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION) {
                /* Get the sessiond-side version of the target action. */
                query_target_action =
-                               lttng_error_query_action_borrow_action_target(
-                                               query, matching_trigger);
+                       lttng_error_query_action_borrow_action_target(query, matching_trigger);
        }
 
        trigger_status = lttng_trigger_get_name(matching_trigger, &trigger_name);
-       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
-       trigger_status = lttng_trigger_get_owner_uid(matching_trigger,
-                       &trigger_owner);
+       trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
+       trigger_status = lttng_trigger_get_owner_uid(matching_trigger, &trigger_owner);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        results = lttng_error_query_results_create();
@@ -4844,21 +4865,22 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
        }
 
        DBG("Running \"execute error query\" command: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                       trigger_name, (int) trigger_owner,
-                       (int) lttng_credentials_get_uid(cmd_creds));
+           trigger_name,
+           (int) trigger_owner,
+           (int) lttng_credentials_get_uid(cmd_creds));
 
        /*
         * Validate the trigger credentials against the command credentials.
         * Only the root user can target a trigger with non-matching
         * credentials.
         */
-       if (!lttng_credentials_is_equal_uid(
-                       lttng_trigger_get_credentials(matching_trigger),
-                       cmd_creds)) {
+       if (!lttng_credentials_is_equal_uid(lttng_trigger_get_credentials(matching_trigger),
+                                           cmd_creds)) {
                if (lttng_credentials_get_uid(cmd_creds) != 0) {
                        ERR("Trigger credentials do not match the command credentials: trigger name = '%s', trigger owner uid = %d, command creds uid = %d",
-                                       trigger_name, (int) trigger_owner,
-                                       (int) lttng_credentials_get_uid(cmd_creds));
+                           trigger_name,
+                           (int) trigger_owner,
+                           (int) lttng_credentials_get_uid(cmd_creds));
                        ret_code = LTTNG_ERR_INVALID_TRIGGER;
                        goto end;
                }
@@ -4866,8 +4888,7 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
 
        switch (lttng_error_query_get_target_type(query)) {
        case LTTNG_ERROR_QUERY_TARGET_TYPE_TRIGGER:
-               trigger_status = lttng_trigger_add_error_results(
-                               matching_trigger, results);
+               trigger_status = lttng_trigger_add_error_results(matching_trigger, results);
 
                switch (trigger_status) {
                case LTTNG_TRIGGER_STATUS_OK:
@@ -4880,8 +4901,8 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
                break;
        case LTTNG_ERROR_QUERY_TARGET_TYPE_CONDITION:
        {
-               trigger_status = lttng_trigger_condition_add_error_results(
-                               matching_trigger, results);
+               trigger_status =
+                       lttng_trigger_condition_add_error_results(matching_trigger, results);
 
                switch (trigger_status) {
                case LTTNG_TRIGGER_STATUS_OK:
@@ -4896,8 +4917,7 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
        case LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION:
        {
                const enum lttng_action_status action_status =
-                               lttng_action_add_error_query_results(
-                                               query_target_action, results);
+                       lttng_action_add_error_query_results(query_target_action, results);
 
                switch (action_status) {
                case LTTNG_ACTION_STATUS_OK:
@@ -4915,7 +4935,7 @@ enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cm
        }
 
        *_results = results;
-       results = NULL;
+       results = nullptr;
        ret_code = LTTNG_OK;
 end:
        lttng_trigger_put(matching_trigger);
@@ -4929,9 +4949,8 @@ end:
  *
  * Return LTTNG_OK on success or a LTTNG_ERR code.
  */
-static enum lttng_error_code set_relayd_for_snapshot(
-               struct consumer_output *output,
-               const struct ltt_session *session)
+static enum lttng_error_code set_relayd_for_snapshot(struct consumer_output *output,
+                                                    const struct ltt_session *session)
 {
        enum lttng_error_code status = LTTNG_OK;
        struct lttng_ht_iter iter;
@@ -4945,10 +4964,8 @@ static enum lttng_error_code set_relayd_for_snapshot(
        DBG2("Set relayd object from snapshot output");
 
        if (session->current_trace_chunk) {
-               enum lttng_trace_chunk_status chunk_status =
-                               lttng_trace_chunk_get_id(
-                                               session->current_trace_chunk,
-                                               &current_chunk_id.value);
+               enum lttng_trace_chunk_status chunk_status = lttng_trace_chunk_get_id(
+                       session->current_trace_chunk, &current_chunk_id.value);
 
                if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK) {
                        current_chunk_id.is_set = true;
@@ -4978,25 +4995,28 @@ static enum lttng_error_code set_relayd_for_snapshot(
         * For each consumer socket, create and send the relayd object of the
         * snapshot output.
         */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(output->socks->ht, &iter.iter,
-                       socket, node.node) {
-               pthread_mutex_lock(socket->lock);
-               status = send_consumer_relayd_sockets(session->id,
-                               output, socket,
-                               session->name, session->hostname,
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (output->socks->ht, &iter.iter, socket, node.node) {
+                       pthread_mutex_lock(socket->lock);
+                       status = send_consumer_relayd_sockets(
+                               session->id,
+                               output,
+                               socket,
+                               session->name,
+                               session->hostname,
                                base_path,
                                session->live_timer,
-                               current_chunk_id.is_set ? &current_chunk_id.value : NULL,
+                               current_chunk_id.is_set ? &current_chunk_id.value : nullptr,
                                session->creation_time,
                                session->name_contains_creation_time);
-               pthread_mutex_unlock(socket->lock);
-               if (status != LTTNG_OK) {
-                       rcu_read_unlock();
-                       goto error;
+                       pthread_mutex_unlock(socket->lock);
+                       if (status != LTTNG_OK) {
+                               goto error;
+                       }
                }
        }
-       rcu_read_unlock();
 
 error:
        return status;
@@ -5007,11 +5027,10 @@ error:
  *
  * Return LTTNG_OK on success or a LTTNG_ERR code.
  */
-static enum lttng_error_code record_kernel_snapshot(
-               struct ltt_kernel_session *ksess,
-               const struct consumer_output *output,
-               const struct ltt_session *session,
-               uint64_t nb_packets_per_stream)
+static enum lttng_error_code record_kernel_snapshot(struct ltt_kernel_session *ksess,
+                                                   const struct consumer_output *output,
+                                                   const struct ltt_session *session,
+                                                   uint64_t nb_packets_per_stream)
 {
        enum lttng_error_code status;
 
@@ -5019,8 +5038,7 @@ static enum lttng_error_code record_kernel_snapshot(
        LTTNG_ASSERT(output);
        LTTNG_ASSERT(session);
 
-       status = kernel_snapshot_record(
-                       ksess, output, nb_packets_per_stream);
+       status = kernel_snapshot_record(ksess, output, nb_packets_per_stream);
        return status;
 }
 
@@ -5030,9 +5048,9 @@ static enum lttng_error_code record_kernel_snapshot(
  * Returns LTTNG_OK on success or a LTTNG_ERR error code.
  */
 static enum lttng_error_code record_ust_snapshot(struct ltt_ust_session *usess,
-               const struct consumer_output *output,
-               const struct ltt_session *session,
-               uint64_t nb_packets_per_stream)
+                                                const struct consumer_output *output,
+                                                const struct ltt_session *session,
+                                                uint64_t nb_packets_per_stream)
 {
        enum lttng_error_code status;
 
@@ -5040,23 +5058,20 @@ static enum lttng_error_code record_ust_snapshot(struct ltt_ust_session *usess,
        LTTNG_ASSERT(output);
        LTTNG_ASSERT(session);
 
-       status = ust_app_snapshot_record(
-                       usess, output, nb_packets_per_stream);
+       status = ust_app_snapshot_record(usess, output, nb_packets_per_stream);
        return status;
 }
 
-static
-uint64_t get_session_size_one_more_packet_per_stream(
-               const struct ltt_session *session, uint64_t cur_nr_packets)
+static uint64_t get_session_size_one_more_packet_per_stream(const struct ltt_session *session,
+                                                           uint64_t cur_nr_packets)
 {
        uint64_t tot_size = 0;
 
        if (session->kernel_session) {
                struct ltt_kernel_channel *chan;
-               const struct ltt_kernel_session *ksess =
-                               session->kernel_session;
+               const struct ltt_kernel_session *ksess = session->kernel_session;
 
-               cds_list_for_each_entry(chan, &ksess->channel_list.head, list) {
+               cds_list_for_each_entry (chan, &ksess->channel_list.head, list) {
                        if (cur_nr_packets >= chan->channel->attr.num_subbuf) {
                                /*
                                 * Don't take channel into account if we
@@ -5064,16 +5079,14 @@ uint64_t get_session_size_one_more_packet_per_stream(
                                 */
                                continue;
                        }
-                       tot_size += chan->channel->attr.subbuf_size
-                               * chan->stream_count;
+                       tot_size += chan->channel->attr.subbuf_size * chan->stream_count;
                }
        }
 
        if (session->ust_session) {
                const struct ltt_ust_session *usess = session->ust_session;
 
-               tot_size += ust_app_get_size_one_more_packet_per_stream(usess,
-                               cur_nr_packets);
+               tot_size += ust_app_get_size_one_more_packet_per_stream(usess, cur_nr_packets);
        }
 
        return tot_size;
@@ -5099,23 +5112,22 @@ uint64_t get_session_size_one_more_packet_per_stream(
  * an approximation: for instance, applications could appear/disappear
  * in between this call and actually grabbing data.
  */
-static
-int64_t get_session_nb_packets_per_stream(const struct ltt_session *session,
-               uint64_t max_size)
+static int64_t get_session_nb_packets_per_stream(const struct ltt_session *session,
+                                                uint64_t max_size)
 {
        int64_t size_left;
        uint64_t cur_nb_packets = 0;
 
        if (!max_size) {
-               return 0;       /* Infinite */
+               return 0; /* Infinite */
        }
 
        size_left = max_size;
        for (;;) {
                uint64_t one_more_packet_tot_size;
 
-               one_more_packet_tot_size = get_session_size_one_more_packet_per_stream(
-                               session, cur_nb_packets);
+               one_more_packet_tot_size =
+                       get_session_size_one_more_packet_per_stream(session, cur_nb_packets);
                if (!one_more_packet_tot_size) {
                        /* We are already grabbing all packets. */
                        break;
@@ -5133,33 +5145,34 @@ int64_t get_session_nb_packets_per_stream(const struct ltt_session *session,
        return cur_nb_packets;
 }
 
-static
-enum lttng_error_code snapshot_record(struct ltt_session *session,
-               const struct snapshot_output *snapshot_output)
+static enum lttng_error_code snapshot_record(struct ltt_session *session,
+                                            const struct snapshot_output *snapshot_output)
 {
        int64_t nb_packets_per_stream;
        char snapshot_chunk_name[LTTNG_NAME_MAX];
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        struct lttng_trace_chunk *snapshot_trace_chunk;
-       struct consumer_output *original_ust_consumer_output = NULL;
-       struct consumer_output *original_kernel_consumer_output = NULL;
-       struct consumer_output *snapshot_ust_consumer_output = NULL;
-       struct consumer_output *snapshot_kernel_consumer_output = NULL;
-
-       ret = snprintf(snapshot_chunk_name, sizeof(snapshot_chunk_name),
-                       "%s-%s-%" PRIu64,
-                       snapshot_output->name,
-                       snapshot_output->datetime,
-                       snapshot_output->nb_snapshot);
+       struct consumer_output *original_ust_consumer_output = nullptr;
+       struct consumer_output *original_kernel_consumer_output = nullptr;
+       struct consumer_output *snapshot_ust_consumer_output = nullptr;
+       struct consumer_output *snapshot_kernel_consumer_output = nullptr;
+
+       ret = snprintf(snapshot_chunk_name,
+                      sizeof(snapshot_chunk_name),
+                      "%s-%s-%" PRIu64,
+                      snapshot_output->name,
+                      snapshot_output->datetime,
+                      snapshot_output->nb_snapshot);
        if (ret < 0 || ret >= sizeof(snapshot_chunk_name)) {
                ERR("Failed to format snapshot name");
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
        DBG("Recording snapshot \"%s\" for session \"%s\" with chunk name \"%s\"",
-                       snapshot_output->name, session->name,
-                       snapshot_chunk_name);
+           snapshot_output->name,
+           session->name,
+           snapshot_chunk_name);
        if (!session->kernel_session && !session->ust_session) {
                ERR("Failed to record snapshot as no channels exist");
                ret_code = LTTNG_ERR_NO_CHANNEL;
@@ -5167,86 +5180,76 @@ enum lttng_error_code snapshot_record(struct ltt_session *session,
        }
 
        if (session->kernel_session) {
-               original_kernel_consumer_output =
-                               session->kernel_session->consumer;
-               snapshot_kernel_consumer_output =
-                               consumer_copy_output(snapshot_output->consumer);
-               strcpy(snapshot_kernel_consumer_output->chunk_path,
-                       snapshot_chunk_name);
+               original_kernel_consumer_output = session->kernel_session->consumer;
+               snapshot_kernel_consumer_output = consumer_copy_output(snapshot_output->consumer);
+               strcpy(snapshot_kernel_consumer_output->chunk_path, snapshot_chunk_name);
 
                /* Copy the original domain subdir. */
                strcpy(snapshot_kernel_consumer_output->domain_subdir,
-                               original_kernel_consumer_output->domain_subdir);
+                      original_kernel_consumer_output->domain_subdir);
 
                ret = consumer_copy_sockets(snapshot_kernel_consumer_output,
-                               original_kernel_consumer_output);
+                                           original_kernel_consumer_output);
                if (ret < 0) {
                        ERR("Failed to copy consumer sockets from snapshot output configuration");
                        ret_code = LTTNG_ERR_NOMEM;
                        goto error;
                }
-               ret_code = set_relayd_for_snapshot(
-                               snapshot_kernel_consumer_output, session);
+               ret_code = set_relayd_for_snapshot(snapshot_kernel_consumer_output, session);
                if (ret_code != LTTNG_OK) {
                        ERR("Failed to setup relay daemon for kernel tracer snapshot");
                        goto error;
                }
-               session->kernel_session->consumer =
-                               snapshot_kernel_consumer_output;
+               session->kernel_session->consumer = snapshot_kernel_consumer_output;
        }
        if (session->ust_session) {
                original_ust_consumer_output = session->ust_session->consumer;
-               snapshot_ust_consumer_output =
-                               consumer_copy_output(snapshot_output->consumer);
-               strcpy(snapshot_ust_consumer_output->chunk_path,
-                       snapshot_chunk_name);
+               snapshot_ust_consumer_output = consumer_copy_output(snapshot_output->consumer);
+               strcpy(snapshot_ust_consumer_output->chunk_path, snapshot_chunk_name);
 
                /* Copy the original domain subdir. */
                strcpy(snapshot_ust_consumer_output->domain_subdir,
-                               original_ust_consumer_output->domain_subdir);
+                      original_ust_consumer_output->domain_subdir);
 
                ret = consumer_copy_sockets(snapshot_ust_consumer_output,
-                               original_ust_consumer_output);
+                                           original_ust_consumer_output);
                if (ret < 0) {
                        ERR("Failed to copy consumer sockets from snapshot output configuration");
                        ret_code = LTTNG_ERR_NOMEM;
                        goto error;
                }
-               ret_code = set_relayd_for_snapshot(
-                               snapshot_ust_consumer_output, session);
+               ret_code = set_relayd_for_snapshot(snapshot_ust_consumer_output, session);
                if (ret_code != LTTNG_OK) {
                        ERR("Failed to setup relay daemon for userspace tracer snapshot");
                        goto error;
                }
-               session->ust_session->consumer =
-                               snapshot_ust_consumer_output;
+               session->ust_session->consumer = snapshot_ust_consumer_output;
        }
 
-       snapshot_trace_chunk = session_create_new_trace_chunk(session,
-                       snapshot_kernel_consumer_output ?:
-                                       snapshot_ust_consumer_output,
-                       consumer_output_get_base_path(
-                                       snapshot_output->consumer),
-                       snapshot_chunk_name);
+       snapshot_trace_chunk = session_create_new_trace_chunk(
+               session,
+               snapshot_kernel_consumer_output ?: snapshot_ust_consumer_output,
+               consumer_output_get_base_path(snapshot_output->consumer),
+               snapshot_chunk_name);
        if (!snapshot_trace_chunk) {
                ERR("Failed to create temporary trace chunk to record a snapshot of session \"%s\"",
-                               session->name);
+                   session->name);
                ret_code = LTTNG_ERR_CREATE_DIR_FAIL;
                goto error;
        }
        LTTNG_ASSERT(!session->current_trace_chunk);
-       ret = session_set_trace_chunk(session, snapshot_trace_chunk, NULL);
+       ret = session_set_trace_chunk(session, snapshot_trace_chunk, nullptr);
        lttng_trace_chunk_put(snapshot_trace_chunk);
-       snapshot_trace_chunk = NULL;
+       snapshot_trace_chunk = nullptr;
        if (ret) {
                ERR("Failed to set temporary trace chunk to record a snapshot of session \"%s\"",
-                               session->name);
+                   session->name);
                ret_code = LTTNG_ERR_CREATE_TRACE_CHUNK_FAIL_CONSUMER;
                goto error;
        }
 
-       nb_packets_per_stream = get_session_nb_packets_per_stream(session,
-                       snapshot_output->max_size);
+       nb_packets_per_stream =
+               get_session_nb_packets_per_stream(session, snapshot_output->max_size);
        if (nb_packets_per_stream < 0) {
                ret_code = LTTNG_ERR_MAX_SIZE_INVALID;
                goto error_close_trace_chunk;
@@ -5254,8 +5257,9 @@ enum lttng_error_code snapshot_record(struct ltt_session *session,
 
        if (session->kernel_session) {
                ret_code = record_kernel_snapshot(session->kernel_session,
-                               snapshot_kernel_consumer_output, session,
-                               nb_packets_per_stream);
+                                                 snapshot_kernel_consumer_output,
+                                                 session,
+                                                 nb_packets_per_stream);
                if (ret_code != LTTNG_OK) {
                        goto error_close_trace_chunk;
                }
@@ -5263,40 +5267,40 @@ enum lttng_error_code snapshot_record(struct ltt_session *session,
 
        if (session->ust_session) {
                ret_code = record_ust_snapshot(session->ust_session,
-                               snapshot_ust_consumer_output, session,
-                               nb_packets_per_stream);
+                                              snapshot_ust_consumer_output,
+                                              session,
+                                              nb_packets_per_stream);
                if (ret_code != LTTNG_OK) {
                        goto error_close_trace_chunk;
                }
        }
 
 error_close_trace_chunk:
-       if (session_set_trace_chunk(session, NULL, &snapshot_trace_chunk)) {
-               ERR("Failed to release the current trace chunk of session \"%s\"",
-                               session->name);
+       if (session_set_trace_chunk(session, nullptr, &snapshot_trace_chunk)) {
+               ERR("Failed to release the current trace chunk of session \"%s\"", session->name);
                ret_code = LTTNG_ERR_UNK;
        }
 
-       if (session_close_trace_chunk(session, snapshot_trace_chunk,
-                       LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION, NULL)) {
+       if (session_close_trace_chunk(session,
+                                     snapshot_trace_chunk,
+                                     LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION,
+                                     nullptr)) {
                /*
                 * Don't goto end; make sure the chunk is closed for the session
                 * to allow future snapshots.
                 */
-               ERR("Failed to close snapshot trace chunk of session \"%s\"",
-                               session->name);
+               ERR("Failed to close snapshot trace chunk of session \"%s\"", session->name);
                ret_code = LTTNG_ERR_CLOSE_TRACE_CHUNK_FAIL_CONSUMER;
        }
 
        lttng_trace_chunk_put(snapshot_trace_chunk);
-       snapshot_trace_chunk = NULL;
+       snapshot_trace_chunk = nullptr;
 error:
        if (original_ust_consumer_output) {
                session->ust_session->consumer = original_ust_consumer_output;
        }
        if (original_kernel_consumer_output) {
-               session->kernel_session->consumer =
-                               original_kernel_consumer_output;
+               session->kernel_session->consumer = original_kernel_consumer_output;
        }
        consumer_output_put(snapshot_ust_consumer_output);
        consumer_output_put(snapshot_kernel_consumer_output);
@@ -5312,14 +5316,14 @@ error:
  * Return LTTNG_OK on success or else a LTTNG_ERR code.
  */
 int cmd_snapshot_record(struct ltt_session *session,
-               const struct lttng_snapshot_output *output,
-               int wait __attribute__((unused)))
+                       const struct lttng_snapshot_output *output,
+                       int wait __attribute__((unused)))
 {
        enum lttng_error_code cmd_ret = LTTNG_OK;
        int ret;
        unsigned int snapshot_success = 0;
        char datetime[16];
-       struct snapshot_output *tmp_output = NULL;
+       struct snapshot_output *tmp_output = nullptr;
 
        LTTNG_ASSERT(session);
        LTTNG_ASSERT(output);
@@ -5327,8 +5331,7 @@ int cmd_snapshot_record(struct ltt_session *session,
        DBG("Cmd snapshot record for session %s", session->name);
 
        /* Get the datetime for the snapshot output directory. */
-       ret = utils_get_current_time_str("%Y%m%d-%H%M%S", datetime,
-                       sizeof(datetime));
+       ret = utils_get_current_time_str("%Y%m%d-%H%M%S", datetime, sizeof(datetime));
        if (!ret) {
                cmd_ret = LTTNG_ERR_INVALID;
                goto error;
@@ -5357,11 +5360,14 @@ int cmd_snapshot_record(struct ltt_session *session,
                        goto error;
                }
 
-               ret = snapshot_output_init(session, output->max_size,
-                               output->name,
-                               output->ctrl_url, output->data_url,
-                               session->consumer,
-                               tmp_output, NULL);
+               ret = snapshot_output_init(session,
+                                          output->max_size,
+                                          output->name,
+                                          output->ctrl_url,
+                                          output->data_url,
+                                          session->consumer,
+                                          tmp_output,
+                                          nullptr);
                if (ret < 0) {
                        if (ret == -ENOMEM) {
                                cmd_ret = LTTNG_ERR_NOMEM;
@@ -5384,9 +5390,10 @@ int cmd_snapshot_record(struct ltt_session *session,
                struct snapshot_output *sout;
                struct lttng_ht_iter iter;
 
-               rcu_read_lock();
-               cds_lfht_for_each_entry(session->snapshot.output_ht->ht,
-                               &iter.iter, sout, node.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       session->snapshot.output_ht->ht, &iter.iter, sout, node.node) {
                        struct snapshot_output output_copy;
 
                        /*
@@ -5401,28 +5408,25 @@ int cmd_snapshot_record(struct ltt_session *session,
                        }
 
                        output_copy.nb_snapshot = session->snapshot.nb_snapshot;
-                       memcpy(output_copy.datetime, datetime,
-                                       sizeof(datetime));
+                       memcpy(output_copy.datetime, datetime, sizeof(datetime));
 
                        /* Use temporary name. */
                        if (*output->name != '\0') {
                                if (lttng_strncpy(output_copy.name,
-                                               output->name,
-                                               sizeof(output_copy.name))) {
+                                                 output->name,
+                                                 sizeof(output_copy.name))) {
                                        cmd_ret = LTTNG_ERR_INVALID;
-                                       rcu_read_unlock();
                                        goto error;
                                }
                        }
 
                        cmd_ret = snapshot_record(session, &output_copy);
                        if (cmd_ret != LTTNG_OK) {
-                               rcu_read_unlock();
                                goto error;
                        }
+
                        snapshot_success = 1;
                }
-               rcu_read_unlock();
        }
 
        if (snapshot_success) {
@@ -5435,14 +5439,14 @@ error:
        if (tmp_output) {
                snapshot_output_destroy(tmp_output);
        }
+
        return cmd_ret;
 }
 
 /*
  * Command LTTNG_SET_SESSION_SHM_PATH processed by the client thread.
  */
-int cmd_set_session_shm_path(struct ltt_session *session,
-               const char *shm_path)
+int cmd_set_session_shm_path(struct ltt_session *session, const char *shm_path)
 {
        /* Safety net */
        LTTNG_ASSERT(session);
@@ -5454,8 +5458,7 @@ int cmd_set_session_shm_path(struct ltt_session *session,
                return LTTNG_ERR_SESSION_STARTED;
        }
 
-       strncpy(session->shm_path, shm_path,
-               sizeof(session->shm_path));
+       strncpy(session->shm_path, shm_path, sizeof(session->shm_path));
        session->shm_path[sizeof(session->shm_path) - 1] = '\0';
 
        return LTTNG_OK;
@@ -5470,15 +5473,15 @@ int cmd_set_session_shm_path(struct ltt_session *session,
  * Returns LTTNG_OK on success or else a negative LTTng error code.
  */
 int cmd_rotate_session(struct ltt_session *session,
-               struct lttng_rotate_session_return *rotate_return,
-               bool quiet_rotation,
-               enum lttng_trace_chunk_command_type command)
+                      struct lttng_rotate_session_return *rotate_return,
+                      bool quiet_rotation,
+                      enum lttng_trace_chunk_command_type command)
 {
        int ret;
        uint64_t ongoing_rotation_chunk_id;
        enum lttng_error_code cmd_ret = LTTNG_OK;
-       struct lttng_trace_chunk *chunk_being_archived = NULL;
-       struct lttng_trace_chunk *new_trace_chunk = NULL;
+       struct lttng_trace_chunk *chunk_being_archived = nullptr;
+       struct lttng_trace_chunk *new_trace_chunk = nullptr;
        enum lttng_trace_chunk_status chunk_status;
        bool failed_to_rotate = false;
        enum lttng_error_code rotation_fail_code = LTTNG_OK;
@@ -5496,16 +5499,15 @@ int cmd_rotate_session(struct ltt_session *session,
         * destroy.
         * Rotation is not supported for snapshot traces (no output).
         */
-       if ((!quiet_rotation && session->live_timer) ||
-                       !session->output_traces) {
+       if ((!quiet_rotation && session->live_timer) || !session->output_traces) {
                cmd_ret = LTTNG_ERR_ROTATION_NOT_AVAILABLE;
                goto end;
        }
 
        /* Unsupported feature in lttng-relayd before 2.11. */
        if (!quiet_rotation && session->consumer->type == CONSUMER_DST_NET &&
-                       (session->consumer->relay_major_version == 2 &&
-                       session->consumer->relay_minor_version < 11)) {
+           (session->consumer->relay_major_version == 2 &&
+            session->consumer->relay_minor_version < 11)) {
                cmd_ret = LTTNG_ERR_ROTATION_NOT_AVAILABLE_RELAY;
                goto end;
        }
@@ -5518,7 +5520,7 @@ int cmd_rotate_session(struct ltt_session *session,
 
        if (session->rotation_state == LTTNG_ROTATION_STATE_ONGOING) {
                DBG("Refusing to launch a rotation; a rotation is already in progress for session %s",
-                               session->name);
+                   session->name);
                cmd_ret = LTTNG_ERR_ROTATION_PENDING;
                goto end;
        }
@@ -5529,7 +5531,7 @@ int cmd_rotate_session(struct ltt_session *session,
         */
        if (session->rotated_after_last_stop) {
                DBG("Session \"%s\" was already rotated after stop, refusing rotation",
-                               session->name);
+                   session->name);
                cmd_ret = LTTNG_ERR_ROTATION_MULTIPLE_AFTER_STOP;
                goto end;
        }
@@ -5540,14 +5542,14 @@ int cmd_rotate_session(struct ltt_session *session,
         */
        if (session->cleared_after_last_stop) {
                DBG("Session \"%s\" was already cleared after stop, refusing rotation",
-                               session->name);
+                   session->name);
                cmd_ret = LTTNG_ERR_ROTATION_AFTER_STOP_CLEAR;
                goto end;
        }
 
        if (session->active) {
-               new_trace_chunk = session_create_new_trace_chunk(session, NULL,
-                               NULL, NULL);
+               new_trace_chunk =
+                       session_create_new_trace_chunk(session, nullptr, nullptr, nullptr);
                if (!new_trace_chunk) {
                        cmd_ret = LTTNG_ERR_CREATE_DIR_FAIL;
                        goto error;
@@ -5561,8 +5563,7 @@ int cmd_rotate_session(struct ltt_session *session,
         * be closed on the consumer(s), otherwise it will never be
         * cleaned-up, which will result in a leak.
         */
-       ret = session_set_trace_chunk(session, new_trace_chunk,
-                       &chunk_being_archived);
+       ret = session_set_trace_chunk(session, new_trace_chunk, &chunk_being_archived);
        if (ret) {
                cmd_ret = LTTNG_ERR_CREATE_TRACE_CHUNK_FAIL_CONSUMER;
                goto error;
@@ -5589,7 +5590,7 @@ int cmd_rotate_session(struct ltt_session *session,
 
        if (!chunk_being_archived) {
                DBG("Rotating session \"%s\" from a \"NULL\" trace chunk to a new trace chunk, skipping completion check",
-                               session->name);
+                   session->name);
                if (failed_to_rotate) {
                        cmd_ret = rotation_fail_code;
                        goto error;
@@ -5599,12 +5600,11 @@ int cmd_rotate_session(struct ltt_session *session,
        }
 
        session->rotation_state = LTTNG_ROTATION_STATE_ONGOING;
-       chunk_status = lttng_trace_chunk_get_id(chunk_being_archived,
-                       &ongoing_rotation_chunk_id);
+       chunk_status = lttng_trace_chunk_get_id(chunk_being_archived, &ongoing_rotation_chunk_id);
        LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
 
-       ret = session_close_trace_chunk(session, chunk_being_archived,
-               command, session->last_chunk_path);
+       ret = session_close_trace_chunk(
+               session, chunk_being_archived, command, session->last_chunk_path);
        if (ret) {
                cmd_ret = LTTNG_ERR_CLOSE_TRACE_CHUNK_FAIL_CONSUMER;
                goto error;
@@ -5616,8 +5616,7 @@ int cmd_rotate_session(struct ltt_session *session,
        }
 
        session->quiet_rotation = quiet_rotation;
-       ret = timer_session_rotation_pending_check_start(session,
-                       DEFAULT_ROTATE_PENDING_TIMER);
+       ret = timer_session_rotation_pending_check_start(session, DEFAULT_ROTATE_PENDING_TIMER);
        if (ret) {
                cmd_ret = LTTNG_ERR_UNK;
                goto error;
@@ -5628,30 +5627,28 @@ int cmd_rotate_session(struct ltt_session *session,
        }
 
        session->chunk_being_archived = chunk_being_archived;
-       chunk_being_archived = NULL;
+       chunk_being_archived = nullptr;
        if (!quiet_rotation) {
                ret = notification_thread_command_session_rotation_ongoing(
-                               the_notification_thread_handle, session->id,
-                               ongoing_rotation_chunk_id);
+                       the_notification_thread_handle, session->id, ongoing_rotation_chunk_id);
                if (ret != LTTNG_OK) {
                        ERR("Failed to notify notification thread that a session rotation is ongoing for session %s",
-                                       session->name);
+                           session->name);
                        cmd_ret = (lttng_error_code) ret;
                }
        }
 
        DBG("Cmd rotate session %s, archive_id %" PRIu64 " sent",
-                       session->name, ongoing_rotation_chunk_id);
+           session->name,
+           ongoing_rotation_chunk_id);
 end:
        lttng_trace_chunk_put(new_trace_chunk);
        lttng_trace_chunk_put(chunk_being_archived);
        ret = (cmd_ret == LTTNG_OK) ? cmd_ret : -((int) cmd_ret);
        return ret;
 error:
-       if (session_reset_rotation_state(session,
-                       LTTNG_ROTATION_STATE_ERROR)) {
-               ERR("Failed to reset rotation state of session \"%s\"",
-                               session->name);
+       if (session_reset_rotation_state(*session, LTTNG_ROTATION_STATE_ERROR)) {
+               ERR("Failed to reset rotation state of session \"%s\"", session->name);
        }
        goto end;
 }
@@ -5664,30 +5661,28 @@ error:
  * Return LTTNG_OK on success or else an LTTNG_ERR code.
  */
 int cmd_rotate_get_info(struct ltt_session *session,
-               struct lttng_rotation_get_info_return *info_return,
-               uint64_t rotation_id)
+                       struct lttng_rotation_get_info_return *info_return,
+                       uint64_t rotation_id)
 {
        enum lttng_error_code cmd_ret = LTTNG_OK;
        enum lttng_rotation_state rotation_state;
 
-       DBG("Cmd rotate_get_info session %s, rotation id %" PRIu64, session->name,
-                       session->most_recent_chunk_id.value);
+       DBG("Cmd rotate_get_info session %s, rotation id %" PRIu64,
+           session->name,
+           session->most_recent_chunk_id.value);
 
        if (session->chunk_being_archived) {
                enum lttng_trace_chunk_status chunk_status;
                uint64_t chunk_id;
 
-               chunk_status = lttng_trace_chunk_get_id(
-                               session->chunk_being_archived,
-                               &chunk_id);
+               chunk_status = lttng_trace_chunk_get_id(session->chunk_being_archived, &chunk_id);
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
 
-               rotation_state = rotation_id == chunk_id ?
-                               LTTNG_ROTATION_STATE_ONGOING :
-                               LTTNG_ROTATION_STATE_EXPIRED;
+               rotation_state = rotation_id == chunk_id ? LTTNG_ROTATION_STATE_ONGOING :
+                                                          LTTNG_ROTATION_STATE_EXPIRED;
        } else {
                if (session->last_archived_chunk_id.is_set &&
-                               rotation_id != session->last_archived_chunk_id.value) {
+                   rotation_id != session->last_archived_chunk_id.value) {
                        rotation_state = LTTNG_ROTATION_STATE_EXPIRED;
                } else {
                        rotation_state = session->rotation_state;
@@ -5697,15 +5692,18 @@ int cmd_rotate_get_info(struct ltt_session *session,
        switch (rotation_state) {
        case LTTNG_ROTATION_STATE_NO_ROTATION:
                DBG("Reporting that no rotation has occurred within the lifetime of session \"%s\"",
-                               session->name);
+                   session->name);
                goto end;
        case LTTNG_ROTATION_STATE_EXPIRED:
-               DBG("Reporting that the rotation state of rotation id %" PRIu64 " of session \"%s\" has expired",
-                               rotation_id, session->name);
+               DBG("Reporting that the rotation state of rotation id %" PRIu64
+                   " of session \"%s\" has expired",
+                   rotation_id,
+                   session->name);
                break;
        case LTTNG_ROTATION_STATE_ONGOING:
                DBG("Reporting that rotation id %" PRIu64 " of session \"%s\" is still pending",
-                               rotation_id, session->name);
+                   rotation_id,
+                   session->name);
                break;
        case LTTNG_ROTATION_STATE_COMPLETED:
        {
@@ -5715,20 +5713,20 @@ int cmd_rotate_get_info(struct ltt_session *session,
                size_t current_tracing_path_reply_len;
 
                DBG("Reporting that rotation id %" PRIu64 " of session \"%s\" is completed",
-                               rotation_id, session->name);
+                   rotation_id,
+                   session->name);
 
                switch (session_get_consumer_destination_type(session)) {
                case CONSUMER_DST_LOCAL:
-                       current_tracing_path_reply =
-                                       info_return->location.local.absolute_path;
+                       current_tracing_path_reply = info_return->location.local.absolute_path;
                        current_tracing_path_reply_len =
-                                       sizeof(info_return->location.local.absolute_path);
+                               sizeof(info_return->location.local.absolute_path);
                        info_return->location_type =
-                                       (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL;
+                               (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL;
                        fmt_ret = asprintf(&chunk_path,
-                                       "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
-                                       session_get_base_path(session),
-                                       session->last_archived_chunk_name);
+                                          "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
+                                          session_get_base_path(session),
+                                          session->last_archived_chunk_name);
                        if (fmt_ret == -1) {
                                PERROR("Failed to format the path of the last archived trace chunk");
                                info_return->status = LTTNG_ROTATION_STATUS_ERROR;
@@ -5740,17 +5738,16 @@ int cmd_rotate_get_info(struct ltt_session *session,
                {
                        uint16_t ctrl_port, data_port;
 
-                       current_tracing_path_reply =
-                                       info_return->location.relay.relative_path;
+                       current_tracing_path_reply = info_return->location.relay.relative_path;
                        current_tracing_path_reply_len =
-                                       sizeof(info_return->location.relay.relative_path);
+                               sizeof(info_return->location.relay.relative_path);
                        /* Currently the only supported relay protocol. */
                        info_return->location.relay.protocol =
-                                       (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_RELAY_PROTOCOL_TYPE_TCP;
+                               (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_RELAY_PROTOCOL_TYPE_TCP;
 
                        fmt_ret = lttng_strncpy(info_return->location.relay.host,
-                                       session_get_net_consumer_hostname(session),
-                                       sizeof(info_return->location.relay.host));
+                                               session_get_net_consumer_hostname(session),
+                                               sizeof(info_return->location.relay.host));
                        if (fmt_ret) {
                                ERR("Failed to copy host name to rotate_get_info reply");
                                info_return->status = LTTNG_ROTATION_STATUS_ERROR;
@@ -5762,7 +5759,7 @@ int cmd_rotate_get_info(struct ltt_session *session,
                        info_return->location.relay.ports.control = ctrl_port;
                        info_return->location.relay.ports.data = data_port;
                        info_return->location_type =
-                                       (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY;
+                               (int8_t) LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY;
                        chunk_path = strdup(session->last_chunk_path);
                        if (!chunk_path) {
                                ERR("Failed to allocate the path of the last archived trace chunk");
@@ -5776,8 +5773,8 @@ int cmd_rotate_get_info(struct ltt_session *session,
                        abort();
                }
 
-               fmt_ret = lttng_strncpy(current_tracing_path_reply,
-                               chunk_path, current_tracing_path_reply_len);
+               fmt_ret = lttng_strncpy(
+                       current_tracing_path_reply, chunk_path, current_tracing_path_reply_len);
                free(chunk_path);
                if (fmt_ret) {
                        ERR("Failed to copy path of the last archived trace chunk to rotate_get_info reply");
@@ -5789,8 +5786,10 @@ int cmd_rotate_get_info(struct ltt_session *session,
                break;
        }
        case LTTNG_ROTATION_STATE_ERROR:
-               DBG("Reporting that an error occurred during rotation %" PRIu64 " of session \"%s\"",
-                               rotation_id, session->name);
+               DBG("Reporting that an error occurred during rotation %" PRIu64
+                   " of session \"%s\"",
+                   rotation_id,
+                   session->name);
                break;
        default:
                abort();
@@ -5813,9 +5812,9 @@ end:
  * Return LTTNG_OK on success or else a positive LTTNG_ERR code.
  */
 int cmd_rotation_set_schedule(struct ltt_session *session,
-               bool activate, enum lttng_rotation_schedule_type schedule_type,
-               uint64_t new_value,
-               struct notification_thread_handle *notification_thread_handle)
+                             bool activate,
+                             enum lttng_rotation_schedule_type schedule_type,
+                             uint64_t new_value)
 {
        int ret;
        uint64_t *parameter_value;
@@ -5837,8 +5836,10 @@ int cmd_rotation_set_schedule(struct ltt_session *session,
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
                parameter_value = &session->rotate_timer_period;
                if (new_value >= UINT_MAX) {
-                       DBG("Failing ROTATION_SET_SCHEDULE command as the value requested for a periodic rotation schedule is invalid: %" PRIu64 " > %u (UINT_MAX)",
-                                       new_value, UINT_MAX);
+                       DBG("Failing ROTATION_SET_SCHEDULE command as the value requested for a periodic rotation schedule is invalid: %" PRIu64
+                           " > %u (UINT_MAX)",
+                           new_value,
+                           UINT_MAX);
                        ret = LTTNG_ERR_INVALID;
                        goto end;
                }
@@ -5898,16 +5899,14 @@ int cmd_rotation_set_schedule(struct ltt_session *session,
                         * Only start the timer if the session is active,
                         * otherwise it will be started when the session starts.
                         */
-                       ret = timer_session_rotation_schedule_timer_start(
-                                       session, new_value);
+                       ret = timer_session_rotation_schedule_timer_start(session, new_value);
                        if (ret) {
                                ERR("Failed to enable session rotation timer in ROTATION_SET_SCHEDULE command");
                                ret = LTTNG_ERR_UNK;
                                goto end;
                        }
                } else {
-                       ret = timer_session_rotation_schedule_timer_stop(
-                                       session);
+                       ret = timer_session_rotation_schedule_timer_stop(session);
                        if (ret) {
                                ERR("Failed to disable session rotation timer in ROTATION_SET_SCHEDULE command");
                                ret = LTTNG_ERR_UNK;
@@ -5917,22 +5916,25 @@ int cmd_rotation_set_schedule(struct ltt_session *session,
                break;
        case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
                if (activate) {
-                       ret = subscribe_session_consumed_size_rotation(session,
-                                       new_value, notification_thread_handle);
-                       if (ret) {
-                               ERR("Failed to enable consumed-size notification in ROTATION_SET_SCHEDULE command");
+                       try {
+                               the_rotation_thread_handle->subscribe_session_consumed_size_rotation(
+                                       *session, new_value);
+                       } catch (const std::exception& e) {
+                               ERR("Failed to enable consumed-size notification in ROTATION_SET_SCHEDULE command: %s",
+                                   e.what());
                                ret = LTTNG_ERR_UNK;
                                goto end;
                        }
                } else {
-                       ret = unsubscribe_session_consumed_size_rotation(session,
-                                       notification_thread_handle);
-                       if (ret) {
-                               ERR("Failed to disable consumed-size notification in ROTATION_SET_SCHEDULE command");
+                       try {
+                               the_rotation_thread_handle
+                                       ->unsubscribe_session_consumed_size_rotation(*session);
+                       } catch (const std::exception& e) {
+                               ERR("Failed to disable consumed-size notification in ROTATION_SET_SCHEDULE command: %s",
+                                   e.what());
                                ret = LTTNG_ERR_UNK;
                                goto end;
                        }
-
                }
                break;
        default:
@@ -5954,7 +5956,7 @@ static enum lttng_error_code wait_on_path(void *path_data)
        const char *shm_path = (const char *) path_data;
 
        DBG("Waiting for the shm path at %s to be removed before completing session destruction",
-                       shm_path);
+           shm_path);
        while (true) {
                int ret;
                struct stat st;
@@ -5970,7 +5972,7 @@ static enum lttng_error_code wait_on_path(void *path_data)
                } else {
                        if (!S_ISDIR(st.st_mode)) {
                                ERR("The type of shm path %s returned by stat() is not a directory; aborting the wait for shm path removal",
-                                               shm_path);
+                                   shm_path);
                                break;
                        }
                }
@@ -5983,18 +5985,18 @@ static enum lttng_error_code wait_on_path(void *path_data)
  * Returns a pointer to a handler to run on completion of a command.
  * Returns NULL if no handler has to be run for the last command executed.
  */
-const struct cmd_completion_handler *cmd_pop_completion_handler(void)
+const struct cmd_completion_handler *cmd_pop_completion_handler()
 {
        struct cmd_completion_handler *handler = current_completion_handler;
 
-       current_completion_handler = NULL;
+       current_completion_handler = nullptr;
        return handler;
 }
 
 /*
  * Init command subsystem.
  */
-void cmd_init(void)
+void cmd_init()
 {
        /*
         * Set network sequence index to 1 for streams to match a relayd
index 8727e741bca66a715237ed5e275c0000fc0d1a01..a470a088166ca2d39a3b800f024576ed2aa7228b 100644 (file)
 #include "lttng-sessiond.hpp"
 #include "lttng/tracker.h"
 #include "session.hpp"
+
 #include <common/tracker.hpp>
 
+#include <lttng/kernel.h>
+
 struct notification_thread_handle;
 struct lttng_dynamic_buffer;
 
@@ -25,7 +28,7 @@ struct lttng_dynamic_buffer;
  * completed successfully. On failure, the handler's return code should
  * be the only reply sent to the client.
  */
-typedef enum lttng_error_code (*completion_handler_function)(void *);
+using completion_handler_function = enum lttng_error_code (*)(void *);
 struct cmd_completion_handler {
        completion_handler_function run;
        void *data;
@@ -35,65 +38,67 @@ struct cmd_completion_handler {
  * Init the command subsystem. Must be called before using any of the functions
  * above. This is called in the main() of the session daemon.
  */
-void cmd_init(void);
+void cmd_init();
 
 /* Session commands */
-enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx, int sock,
-               struct lttng_session_descriptor **return_descriptor);
-int cmd_destroy_session(struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle,
-               int *sock_fd);
+enum lttng_error_code cmd_create_session(struct command_ctx *cmd_ctx,
+                                        int sock,
+                                        struct lttng_session_descriptor **return_descriptor);
+int cmd_destroy_session(struct ltt_session *session, int *sock_fd);
 
 /* Channel commands */
 int cmd_disable_channel(struct ltt_session *session,
-               enum lttng_domain_type domain, char *channel_name);
+                       enum lttng_domain_type domain,
+                       char *channel_name);
 int cmd_enable_channel(struct command_ctx *cmd_ctx, int sock, int wpipe);
 
 /* Process attribute tracker commands */
-enum lttng_error_code cmd_process_attr_tracker_get_tracking_policy(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy *policy);
-enum lttng_error_code cmd_process_attr_tracker_set_tracking_policy(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy);
-enum lttng_error_code cmd_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-enum lttng_error_code cmd_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-enum lttng_error_code cmd_process_attr_tracker_get_inclusion_set(
-               struct ltt_session *session,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               struct lttng_process_attr_values **values);
+enum lttng_error_code
+cmd_process_attr_tracker_get_tracking_policy(struct ltt_session *session,
+                                            enum lttng_domain_type domain,
+                                            enum lttng_process_attr process_attr,
+                                            enum lttng_tracking_policy *policy);
+enum lttng_error_code
+cmd_process_attr_tracker_set_tracking_policy(struct ltt_session *session,
+                                            enum lttng_domain_type domain,
+                                            enum lttng_process_attr process_attr,
+                                            enum lttng_tracking_policy policy);
+enum lttng_error_code
+cmd_process_attr_tracker_inclusion_set_add_value(struct ltt_session *session,
+                                                enum lttng_domain_type domain,
+                                                enum lttng_process_attr process_attr,
+                                                const struct process_attr_value *value);
+enum lttng_error_code
+cmd_process_attr_tracker_inclusion_set_remove_value(struct ltt_session *session,
+                                                   enum lttng_domain_type domain,
+                                                   enum lttng_process_attr process_attr,
+                                                   const struct process_attr_value *value);
+enum lttng_error_code
+cmd_process_attr_tracker_get_inclusion_set(struct ltt_session *session,
+                                          enum lttng_domain_type domain,
+                                          enum lttng_process_attr process_attr,
+                                          struct lttng_process_attr_values **values);
 
 /* Event commands */
 int cmd_disable_event(struct command_ctx *cmd_ctx,
-               struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion);
+                     struct lttng_event *event,
+                     char *filter_expression,
+                     struct lttng_bytecode *filter,
+                     struct lttng_event_exclusion *exclusion);
 int cmd_add_context(struct command_ctx *cmd_ctx,
-               const struct lttng_event_context *event_context,
-               int kwpipe);
-int cmd_set_filter(struct ltt_session *session, enum lttng_domain_type domain,
-               char *channel_name, struct lttng_event *event,
-               struct lttng_bytecode *bytecode);
+                   const struct lttng_event_context *event_context,
+                   int kwpipe);
+int cmd_set_filter(struct ltt_session *session,
+                  enum lttng_domain_type domain,
+                  char *channel_name,
+                  struct lttng_event *event,
+                  struct lttng_bytecode *bytecode);
 int cmd_enable_event(struct command_ctx *cmd_ctx,
-               struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_event_exclusion *exclusion,
-               struct lttng_bytecode *bytecode,
-               int wpipe);
+                    struct lttng_event *event,
+                    char *filter_expression,
+                    struct lttng_event_exclusion *exclusion,
+                    struct lttng_bytecode *bytecode,
+                    int wpipe);
 
 /* Trace session action commands */
 int cmd_start_trace(struct ltt_session *session);
@@ -101,80 +106,84 @@ int cmd_stop_trace(struct ltt_session *session);
 
 /* Consumer commands */
 int cmd_register_consumer(struct ltt_session *session,
-               enum lttng_domain_type domain,
-               const char *sock_path, struct consumer_data *cdata);
-int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri,
-               struct lttng_uri *uris);
+                         enum lttng_domain_type domain,
+                         const char *sock_path,
+                         struct consumer_data *cdata);
+int cmd_set_consumer_uri(struct ltt_session *session, size_t nb_uri, struct lttng_uri *uris);
 int cmd_setup_relayd(struct ltt_session *session);
 
 /* Listing commands */
-ssize_t cmd_list_domains(struct ltt_session *session,
-               struct lttng_domain **domains);
+ssize_t cmd_list_domains(struct ltt_session *session, struct lttng_domain **domains);
 enum lttng_error_code cmd_list_events(enum lttng_domain_type domain,
-               struct ltt_session *session,
-               char *channel_name,
-               struct lttng_payload *payload);
+                                     struct ltt_session *session,
+                                     char *channel_name,
+                                     struct lttng_payload *payload);
 enum lttng_error_code cmd_list_channels(enum lttng_domain_type domain,
-               struct ltt_session *session,
-               struct lttng_payload *payload);
+                                       struct ltt_session *session,
+                                       struct lttng_payload *payload);
 void cmd_list_lttng_sessions(struct lttng_session *sessions,
-               size_t session_count, uid_t uid, gid_t gid);
+                            size_t session_count,
+                            uid_t uid,
+                            gid_t gid);
 enum lttng_error_code cmd_list_tracepoint_fields(enum lttng_domain_type domain,
-               struct lttng_payload *reply);
+                                                struct lttng_payload *reply);
 enum lttng_error_code cmd_list_tracepoints(enum lttng_domain_type domain,
-               struct lttng_payload *reply_payload);
+                                          struct lttng_payload *reply_payload);
 ssize_t cmd_snapshot_list_outputs(struct ltt_session *session,
-               struct lttng_snapshot_output **outputs);
-enum lttng_error_code cmd_list_syscalls(
-               struct lttng_payload *reply_payload);
+                                 struct lttng_snapshot_output **outputs);
+enum lttng_error_code cmd_list_syscalls(struct lttng_payload *reply_payload);
 
 int cmd_data_pending(struct ltt_session *session);
+enum lttng_error_code cmd_kernel_tracer_status(enum lttng_kernel_tracer_status *status);
 
 /* Snapshot */
 int cmd_snapshot_add_output(struct ltt_session *session,
-               const struct lttng_snapshot_output *output, uint32_t *id);
+                           const struct lttng_snapshot_output *output,
+                           uint32_t *id);
 int cmd_snapshot_del_output(struct ltt_session *session,
-               const struct lttng_snapshot_output *output);
+                           const struct lttng_snapshot_output *output);
 int cmd_snapshot_record(struct ltt_session *session,
-               const struct lttng_snapshot_output *output, int wait);
+                       const struct lttng_snapshot_output *output,
+                       int wait);
 
-int cmd_set_session_shm_path(struct ltt_session *session,
-               const char *shm_path);
+int cmd_set_session_shm_path(struct ltt_session *session, const char *shm_path);
 int cmd_regenerate_metadata(struct ltt_session *session);
 int cmd_regenerate_statedump(struct ltt_session *session);
 
-enum lttng_error_code cmd_register_trigger(
-               const struct lttng_credentials *cmd_creds,
-               struct lttng_trigger *trigger,
-               bool is_anonymous_trigger,
-               struct notification_thread_handle *notification_thread_handle,
-               struct lttng_trigger **return_trigger);
-enum lttng_error_code cmd_unregister_trigger(
-               const struct lttng_credentials *cmd_creds,
-               const struct lttng_trigger *trigger,
-               struct notification_thread_handle *notification_thread_handle);
-
-enum lttng_error_code cmd_list_triggers(struct command_ctx *cmd_ctx,
-               struct notification_thread_handle *notification_thread_handle,
-               struct lttng_triggers **return_triggers);
-enum lttng_error_code cmd_execute_error_query(const struct lttng_credentials *cmd_creds,
-               const struct lttng_error_query *query,
-               struct lttng_error_query_results **_results,
-               struct notification_thread_handle *notification_thread);
+enum lttng_error_code
+cmd_register_trigger(const struct lttng_credentials *cmd_creds,
+                    struct lttng_trigger *trigger,
+                    bool is_anonymous_trigger,
+                    struct notification_thread_handle *notification_thread_handle,
+                    struct lttng_trigger **return_trigger);
+enum lttng_error_code
+cmd_unregister_trigger(const struct lttng_credentials *cmd_creds,
+                      const struct lttng_trigger *trigger,
+                      struct notification_thread_handle *notification_thread_handle);
+
+enum lttng_error_code
+cmd_list_triggers(struct command_ctx *cmd_ctx,
+                 struct notification_thread_handle *notification_thread_handle,
+                 struct lttng_triggers **return_triggers);
+enum lttng_error_code
+cmd_execute_error_query(const struct lttng_credentials *cmd_creds,
+                       const struct lttng_error_query *query,
+                       struct lttng_error_query_results **_results,
+                       struct notification_thread_handle *notification_thread);
 
 int cmd_rotate_session(struct ltt_session *session,
-               struct lttng_rotate_session_return *rotate_return,
-               bool quiet_rotation,
-               enum lttng_trace_chunk_command_type command);
+                      struct lttng_rotate_session_return *rotate_return,
+                      bool quiet_rotation,
+                      enum lttng_trace_chunk_command_type command);
 int cmd_rotate_get_info(struct ltt_session *session,
-               struct lttng_rotation_get_info_return *info_return,
-               uint64_t rotate_id);
+                       struct lttng_rotation_get_info_return *info_return,
+                       uint64_t rotate_id);
 int cmd_rotation_set_schedule(struct ltt_session *session,
-               bool activate, enum lttng_rotation_schedule_type schedule_type,
-               uint64_t value,
-               struct notification_thread_handle *notification_thread_handle);
+                             bool activate,
+                             enum lttng_rotation_schedule_type schedule_type,
+                             uint64_t value);
 
-const struct cmd_completion_handler *cmd_pop_completion_handler(void);
+const struct cmd_completion_handler *cmd_pop_completion_handler();
 int start_kernel_session(struct ltt_kernel_session *ksess);
 int stop_kernel_session(struct ltt_kernel_session *ksess);
 
index d932fac13bd139c723c3b1ef4aca1a3866245045..ee7b4305ad813172d23238a547efd0dc2c033ed6 100644 (file)
@@ -5,30 +5,27 @@
  *
  */
 
-#include <common/hashtable/utils.hpp>
+#include "condition-internal.hpp"
+
 #include <common/hashtable/hashtable.hpp>
+#include <common/hashtable/utils.hpp>
 
-#include <lttng/condition/condition.h>
-#include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/buffer-usage-internal.hpp>
-#include <lttng/condition/session-consumed-size-internal.hpp>
-#include <lttng/condition/session-rotation-internal.hpp>
+#include <lttng/condition/condition-internal.hpp>
+#include <lttng/condition/condition.h>
 #include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/condition/event-rule-matches.h>
+#include <lttng/condition/session-consumed-size-internal.hpp>
+#include <lttng/condition/session-rotation-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
-#include <lttng/condition/event-rule-matches-internal.hpp>
-#include "condition-internal.hpp"
 
-static
-unsigned long lttng_condition_buffer_usage_hash(
-       const struct lttng_condition *_condition)
+static unsigned long lttng_condition_buffer_usage_hash(const struct lttng_condition *_condition)
 {
        unsigned long hash;
        unsigned long condition_type;
        struct lttng_condition_buffer_usage *condition;
 
-       condition = lttng::utils::container_of(_condition,
-                       &lttng_condition_buffer_usage::parent);
+       condition = lttng::utils::container_of(_condition, &lttng_condition_buffer_usage::parent);
 
        condition_type = (unsigned long) condition->parent.type;
        hash = hash_key_ulong((void *) condition_type, lttng_ht_seed);
@@ -39,9 +36,7 @@ unsigned long lttng_condition_buffer_usage_hash(
                hash ^= hash_key_str(condition->channel_name, lttng_ht_seed);
        }
        if (condition->domain.set) {
-               hash ^= hash_key_ulong(
-                               (void *) condition->domain.type,
-                               lttng_ht_seed);
+               hash ^= hash_key_ulong((void *) condition->domain.type, lttng_ht_seed);
        }
        if (condition->threshold_ratio.set) {
                hash ^= hash_key_u64(&condition->threshold_ratio.value, lttng_ht_seed);
@@ -54,18 +49,16 @@ unsigned long lttng_condition_buffer_usage_hash(
        return hash;
 }
 
-static
-unsigned long lttng_condition_session_consumed_size_hash(
-       const struct lttng_condition *_condition)
+static unsigned long
+lttng_condition_session_consumed_size_hash(const struct lttng_condition *_condition)
 {
        unsigned long hash;
-       unsigned long condition_type =
-                       (unsigned long) LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE;
+       unsigned long condition_type = (unsigned long) LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE;
        struct lttng_condition_session_consumed_size *condition;
        uint64_t val;
 
        condition = lttng::utils::container_of(_condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                              &lttng_condition_session_consumed_size::parent);
 
        hash = hash_key_ulong((void *) condition_type, lttng_ht_seed);
        if (condition->session_name) {
@@ -76,15 +69,13 @@ unsigned long lttng_condition_session_consumed_size_hash(
        return hash;
 }
 
-static
-unsigned long lttng_condition_session_rotation_hash(
-       const struct lttng_condition *_condition)
+static unsigned long lttng_condition_session_rotation_hash(const struct lttng_condition *_condition)
 {
        unsigned long hash, condition_type;
        struct lttng_condition_session_rotation *condition;
 
-       condition = lttng::utils::container_of(_condition,
-                       &lttng_condition_session_rotation::parent);
+       condition =
+               lttng::utils::container_of(_condition, &lttng_condition_session_rotation::parent);
        condition_type = (unsigned long) condition->parent.type;
        hash = hash_key_ulong((void *) condition_type, lttng_ht_seed);
        LTTNG_ASSERT(condition->session_name);
@@ -92,16 +83,15 @@ unsigned long lttng_condition_session_rotation_hash(
        return hash;
 }
 
-static unsigned long lttng_condition_event_rule_matches_hash(
-               const struct lttng_condition *condition)
+static unsigned long
+lttng_condition_event_rule_matches_hash(const struct lttng_condition *condition)
 {
        unsigned long hash, condition_type;
        enum lttng_condition_status condition_status;
        const struct lttng_event_rule *event_rule;
 
        condition_type = (unsigned long) condition->type;
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        hash = hash_key_ulong((void *) condition_type, lttng_ht_seed);
@@ -135,7 +125,7 @@ struct lttng_condition *lttng_condition_copy(const struct lttng_condition *condi
 {
        int ret;
        struct lttng_payload copy_buffer;
-       struct lttng_condition *copy = NULL;
+       struct lttng_condition *copy = nullptr;
 
        lttng_payload_init(&copy_buffer);
 
@@ -146,13 +136,11 @@ struct lttng_condition *lttng_condition_copy(const struct lttng_condition *condi
 
        {
                struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &copy_buffer, 0, -1);
+                       lttng_payload_view_from_payload(&copy_buffer, 0, -1);
 
-               ret = lttng_condition_create_from_payload(
-                               &view, &copy);
+               ret = lttng_condition_create_from_payload(&view, &copy);
                if (ret < 0) {
-                       copy = NULL;
+                       copy = nullptr;
                        goto end;
                }
        }
index 49a074952a5bed638661adcf6e8e579aee500b91..23d2c229e0e831352eeedd13449b7b2341e93fb9 100644 (file)
@@ -17,7 +17,6 @@
  */
 unsigned long lttng_condition_hash(const struct lttng_condition *condition);
 
-struct lttng_condition *lttng_condition_copy(
-               const struct lttng_condition *condition);
+struct lttng_condition *lttng_condition_copy(const struct lttng_condition *condition);
 
 #endif /* LTTNG_SESSIOND_CONDITION_INTERNAL_H */
index c0f8eb5894e8fae8cb070109d4820ebec62ddff2..13c18325d75d363e5da76674734b4e3aedcd0c07 100644 (file)
@@ -7,25 +7,26 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <inttypes.h>
+#include "consumer.hpp"
+#include "health-sessiond.hpp"
+#include "lttng-sessiond.hpp"
+#include "ust-app.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/defaults.hpp>
-#include <common/uri.hpp>
 #include <common/relayd/relayd.hpp>
 #include <common/string-utils/format.hpp>
+#include <common/urcu.hpp>
+#include <common/uri.hpp>
 
-#include "consumer.hpp"
-#include "health-sessiond.hpp"
-#include "ust-app.hpp"
-#include "utils.hpp"
-#include "lttng-sessiond.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 /*
  * Return allocated full pathname of the session using the consumer trace path
@@ -35,7 +36,8 @@
  * returned.
  */
 char *setup_channel_trace_path(struct consumer_output *consumer,
-               const char *session_path, size_t *consumer_path_offset)
+                              const char *session_path,
+                              size_t *consumer_path_offset)
 {
        int ret;
        char *pathname;
@@ -55,21 +57,22 @@ char *setup_channel_trace_path(struct consumer_output *consumer,
        }
 
        /* Get correct path name destination */
-       if (consumer->type == CONSUMER_DST_NET &&
-                       consumer->relay_major_version == 2 &&
-                       consumer->relay_minor_version < 11) {
-               ret = snprintf(pathname, LTTNG_PATH_MAX, "%s%s/%s/%s",
-                               consumer->dst.net.base_dir,
-                               consumer->chunk_path, consumer->domain_subdir,
-                               session_path);
+       if (consumer->type == CONSUMER_DST_NET && consumer->relay_major_version == 2 &&
+           consumer->relay_minor_version < 11) {
+               ret = snprintf(pathname,
+                              LTTNG_PATH_MAX,
+                              "%s%s/%s/%s",
+                              consumer->dst.net.base_dir,
+                              consumer->chunk_path,
+                              consumer->domain_subdir,
+                              session_path);
                *consumer_path_offset = 0;
        } else {
-               ret = snprintf(pathname, LTTNG_PATH_MAX, "%s/%s",
-                               consumer->domain_subdir, session_path);
+               ret = snprintf(
+                       pathname, LTTNG_PATH_MAX, "%s/%s", consumer->domain_subdir, session_path);
                *consumer_path_offset = strlen(consumer->domain_subdir) + 1;
        }
-       DBG3("Consumer trace path relative to current trace chunk: \"%s\"",
-                       pathname);
+       DBG3("Consumer trace path relative to current trace chunk: \"%s\"", pathname);
        if (ret < 0) {
                PERROR("Failed to format channel path");
                goto error;
@@ -81,7 +84,7 @@ char *setup_channel_trace_path(struct consumer_output *consumer,
        return pathname;
 error:
        free(pathname);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -92,8 +95,7 @@ error:
  *
  * Return 0 on success else a negative value on error.
  */
-int consumer_socket_send(
-               struct consumer_socket *socket, const void *msg, size_t len)
+int consumer_socket_send(struct consumer_socket *socket, const void *msg, size_t len)
 {
        int fd;
        ssize_t size;
@@ -213,7 +215,8 @@ end:
  * negative value is sent back and both parameters are untouched.
  */
 int consumer_recv_status_channel(struct consumer_socket *sock,
-               uint64_t *key, unsigned int *stream_count)
+                                uint64_t *key,
+                                unsigned int *stream_count)
 {
        int ret;
        struct lttcomm_consumer_status_channel reply;
@@ -246,8 +249,7 @@ end:
  *
  * On success return positive value. On error, negative value.
  */
-int consumer_send_destroy_relayd(struct consumer_socket *sock,
-               struct consumer_output *consumer)
+int consumer_send_destroy_relayd(struct consumer_socket *sock, struct consumer_output *consumer)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -290,19 +292,17 @@ void consumer_output_send_destroy_relayd(struct consumer_output *consumer)
 
        /* Destroy any relayd connection */
        if (consumer->type == CONSUMER_DST_NET) {
-               rcu_read_lock();
-               cds_lfht_for_each_entry(consumer->socks->ht, &iter.iter, socket,
-                               node.node) {
-                       int ret;
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (consumer->socks->ht, &iter.iter, socket, node.node) {
+                       /* Send destroy relayd command. */
+                       const int ret = consumer_send_destroy_relayd(socket, consumer);
 
-                       /* Send destroy relayd command */
-                       ret = consumer_send_destroy_relayd(socket, consumer);
                        if (ret < 0) {
                                DBG("Unable to send destroy relayd command to consumer");
                                /* Continue since we MUST delete everything at this point. */
                        }
                }
-               rcu_read_unlock();
        }
 }
 
@@ -312,15 +312,16 @@ void consumer_output_send_destroy_relayd(struct consumer_output *consumer)
  *
  * Return 0 on success, else negative value on error
  */
-int consumer_create_socket(struct consumer_data *data,
-               struct consumer_output *output)
+int consumer_create_socket(struct consumer_data *data, struct consumer_output *output)
 {
        int ret = 0;
        struct consumer_socket *socket;
 
        LTTNG_ASSERT(data);
 
-       if (output == NULL || data->cmd_sock < 0) {
+       lttng::urcu::read_lock_guard read_lock;
+
+       if (output == nullptr || data->cmd_sock < 0) {
                /*
                 * Not an error. Possible there is simply not spawned consumer or it's
                 * disabled for the tracing session asking the socket.
@@ -328,27 +329,22 @@ int consumer_create_socket(struct consumer_data *data,
                goto error;
        }
 
-       rcu_read_lock();
        socket = consumer_find_socket(data->cmd_sock, output);
-       rcu_read_unlock();
-       if (socket == NULL) {
+       if (socket == nullptr) {
                socket = consumer_allocate_socket(&data->cmd_sock);
-               if (socket == NULL) {
+               if (socket == nullptr) {
                        ret = -1;
                        goto error;
                }
 
                socket->registered = 0;
                socket->lock = &data->lock;
-               rcu_read_lock();
                consumer_add_socket(socket, output);
-               rcu_read_unlock();
        }
 
        socket->type = data->type;
 
-       DBG3("Consumer socket created (fd: %d) and added to output",
-                       data->cmd_sock);
+       DBG3("Consumer socket created (fd: %d) and added to output", data->cmd_sock);
 
 error:
        return ret;
@@ -362,10 +358,10 @@ error:
  * object reference is not needed anymore.
  */
 struct consumer_socket *consumer_find_socket_by_bitness(int bits,
-               const struct consumer_output *consumer)
+                                                       const struct consumer_output *consumer)
 {
        int consumer_fd;
-       struct consumer_socket *socket = NULL;
+       struct consumer_socket *socket = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
@@ -383,8 +379,7 @@ struct consumer_socket *consumer_find_socket_by_bitness(int bits,
 
        socket = consumer_find_socket(consumer_fd, consumer);
        if (!socket) {
-               ERR("Consumer socket fd %d not found in consumer obj %p",
-                               consumer_fd, consumer);
+               ERR("Consumer socket fd %d not found in consumer obj %p", consumer_fd, consumer);
        }
 
 end:
@@ -396,24 +391,22 @@ end:
  * be acquired before calling this function and across use of the
  * returned consumer_socket.
  */
-struct consumer_socket *consumer_find_socket(int key,
-               const struct consumer_output *consumer)
+struct consumer_socket *consumer_find_socket(int key, const struct consumer_output *consumer)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_ulong *node;
-       struct consumer_socket *socket = NULL;
+       struct consumer_socket *socket = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
        /* Negative keys are lookup failures */
-       if (key < 0 || consumer == NULL) {
-               return NULL;
+       if (key < 0 || consumer == nullptr) {
+               return nullptr;
        }
 
-       lttng_ht_lookup(consumer->socks, (void *)((unsigned long) key),
-                       &iter);
+       lttng_ht_lookup(consumer->socks, (void *) ((unsigned long) key), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node != NULL) {
+       if (node != nullptr) {
                socket = lttng::utils::container_of(node, &consumer_socket::node);
        }
 
@@ -425,12 +418,12 @@ struct consumer_socket *consumer_find_socket(int key,
  */
 struct consumer_socket *consumer_allocate_socket(int *fd)
 {
-       struct consumer_socket *socket = NULL;
+       struct consumer_socket *socket = nullptr;
 
        LTTNG_ASSERT(fd);
 
        socket = zmalloc<consumer_socket>();
-       if (socket == NULL) {
+       if (socket == nullptr) {
                PERROR("zmalloc consumer socket");
                goto error;
        }
@@ -446,8 +439,7 @@ error:
  * Add consumer socket to consumer output object. Read side lock must be
  * acquired before calling this function.
  */
-void consumer_add_socket(struct consumer_socket *sock,
-               struct consumer_output *consumer)
+void consumer_add_socket(struct consumer_socket *sock, struct consumer_output *consumer)
 {
        LTTNG_ASSERT(sock);
        LTTNG_ASSERT(consumer);
@@ -460,8 +452,7 @@ void consumer_add_socket(struct consumer_socket *sock,
  * Delete consumer socket to consumer output object. Read side lock must be
  * acquired before calling this function.
  */
-void consumer_del_socket(struct consumer_socket *sock,
-               struct consumer_output *consumer)
+void consumer_del_socket(struct consumer_socket *sock, struct consumer_output *consumer)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -482,8 +473,7 @@ static void destroy_socket_rcu(struct rcu_head *head)
 {
        struct lttng_ht_node_ulong *node =
                lttng::utils::container_of(head, &lttng_ht_node_ulong::head);
-       struct consumer_socket *socket =
-               lttng::utils::container_of(node, &consumer_socket::node);
+       struct consumer_socket *socket = lttng::utils::container_of(node, &consumer_socket::node);
 
        free(socket);
 }
@@ -518,16 +508,16 @@ void consumer_destroy_socket(struct consumer_socket *sock)
  */
 struct consumer_output *consumer_create_output(enum consumer_dst_type type)
 {
-       struct consumer_output *output = NULL;
+       struct consumer_output *output = nullptr;
 
        output = zmalloc<consumer_output>();
-       if (output == NULL) {
+       if (output == nullptr) {
                PERROR("zmalloc consumer_output");
                goto error;
        }
 
        /* By default, consumer output is enabled */
-       output->enabled = 1;
+       output->enabled = true;
        output->type = type;
        output->net_seq_index = (uint64_t) -1ULL;
        urcu_ref_init(&output->ref);
@@ -552,12 +542,14 @@ void consumer_destroy_output_sockets(struct consumer_output *obj)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(obj->socks->ht, &iter.iter, socket, node.node) {
-               consumer_del_socket(socket, obj);
-               consumer_destroy_socket(socket);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (obj->socks->ht, &iter.iter, socket, node.node) {
+                       consumer_del_socket(socket, obj);
+                       consumer_destroy_socket(socket);
+               }
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -565,8 +557,7 @@ void consumer_destroy_output_sockets(struct consumer_output *obj)
  */
 static void consumer_release_output(struct urcu_ref *ref)
 {
-       struct consumer_output *obj =
-               lttng::utils::container_of(ref, &consumer_output::ref);
+       struct consumer_output *obj = lttng::utils::container_of(ref, &consumer_output::ref);
 
        consumer_destroy_output_sockets(obj);
 
@@ -608,13 +599,12 @@ struct consumer_output *consumer_copy_output(struct consumer_output *src)
        LTTNG_ASSERT(src);
 
        output = consumer_create_output(src->type);
-       if (output == NULL) {
+       if (output == nullptr) {
                goto end;
        }
        output->enabled = src->enabled;
        output->net_seq_index = src->net_seq_index;
-       memcpy(output->domain_subdir, src->domain_subdir,
-                       sizeof(output->domain_subdir));
+       memcpy(output->domain_subdir, src->domain_subdir, sizeof(output->domain_subdir));
        output->snapshot = src->snapshot;
        output->relay_major_version = src->relay_major_version;
        output->relay_minor_version = src->relay_minor_version;
@@ -629,7 +619,7 @@ end:
 
 error_put:
        consumer_output_put(output);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -637,8 +627,7 @@ error_put:
  *
  * Return 0 on success or else a negative value.
  */
-int consumer_copy_sockets(struct consumer_output *dst,
-               struct consumer_output *src)
+int consumer_copy_sockets(struct consumer_output *dst, struct consumer_output *src)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -647,32 +636,33 @@ int consumer_copy_sockets(struct consumer_output *dst,
        LTTNG_ASSERT(dst);
        LTTNG_ASSERT(src);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(src->socks->ht, &iter.iter, socket, node.node) {
-               /* Ignore socket that are already there. */
-               copy_sock = consumer_find_socket(*socket->fd_ptr, dst);
-               if (copy_sock) {
-                       continue;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               /* Create new socket object. */
-               copy_sock = consumer_allocate_socket(socket->fd_ptr);
-               if (copy_sock == NULL) {
-                       rcu_read_unlock();
-                       ret = -ENOMEM;
-                       goto error;
-               }
+               cds_lfht_for_each_entry (src->socks->ht, &iter.iter, socket, node.node) {
+                       /* Ignore socket that are already there. */
+                       copy_sock = consumer_find_socket(*socket->fd_ptr, dst);
+                       if (copy_sock) {
+                               continue;
+                       }
 
-               copy_sock->registered = socket->registered;
-               /*
-                * This is valid because this lock is shared accross all consumer
-                * object being the global lock of the consumer data structure of the
-                * session daemon.
-                */
-               copy_sock->lock = socket->lock;
-               consumer_add_socket(copy_sock, dst);
+                       /* Create new socket object. */
+                       copy_sock = consumer_allocate_socket(socket->fd_ptr);
+                       if (copy_sock == nullptr) {
+                               ret = -ENOMEM;
+                               goto error;
+                       }
+
+                       copy_sock->registered = socket->registered;
+                       /*
+                        * This is valid because this lock is shared accross all consumer
+                        * object being the global lock of the consumer data structure of the
+                        * session daemon.
+                        */
+                       copy_sock->lock = socket->lock;
+                       consumer_add_socket(copy_sock, dst);
+               }
        }
-       rcu_read_unlock();
 
 error:
        return ret;
@@ -685,11 +675,11 @@ error:
  * error.
  */
 int consumer_set_network_uri(const struct ltt_session *session,
-               struct consumer_output *output,
-               struct lttng_uri *uri)
+                            struct consumer_output *output,
+                            struct lttng_uri *uri)
 {
        int ret;
-       struct lttng_uri *dst_uri = NULL;
+       struct lttng_uri *dst_uri = nullptr;
 
        /* Code flow error safety net. */
        LTTNG_ASSERT(output);
@@ -703,8 +693,7 @@ int consumer_set_network_uri(const struct ltt_session *session,
                        /* Assign default port. */
                        uri->port = DEFAULT_NETWORK_CONTROL_PORT;
                } else {
-                       if (output->dst.net.data_isset && uri->port ==
-                                       output->dst.net.data.port) {
+                       if (output->dst.net.data_isset && uri->port == output->dst.net.data.port) {
                                ret = -LTTNG_ERR_INVALID;
                                goto error;
                        }
@@ -718,8 +707,8 @@ int consumer_set_network_uri(const struct ltt_session *session,
                        /* Assign default port. */
                        uri->port = DEFAULT_NETWORK_DATA_PORT;
                } else {
-                       if (output->dst.net.control_isset && uri->port ==
-                                       output->dst.net.control.port) {
+                       if (output->dst.net.control_isset &&
+                           uri->port == output->dst.net.control.port) {
                                ret = -LTTNG_ERR_INVALID;
                                goto error;
                        }
@@ -776,14 +765,17 @@ int consumer_set_network_uri(const struct ltt_session *session,
                        goto error;
                }
                ret = snprintf(output->dst.net.base_dir,
-                               sizeof(output->dst.net.base_dir),
-                               "/%s/%s/", session->hostname, uri->subdir);
+                              sizeof(output->dst.net.base_dir),
+                              "/%s/%s/",
+                              session->hostname,
+                              uri->subdir);
        } else {
                if (session->has_auto_generated_name) {
                        ret = snprintf(output->dst.net.base_dir,
-                                       sizeof(output->dst.net.base_dir),
-                                       "/%s/%s/", session->hostname,
-                                       session->name);
+                                      sizeof(output->dst.net.base_dir),
+                                      "/%s/%s/",
+                                      session->hostname,
+                                      session->name);
                } else {
                        char session_creation_datetime[16];
                        size_t strftime_ret;
@@ -795,18 +787,20 @@ int consumer_set_network_uri(const struct ltt_session *session,
                                goto error;
                        }
                        strftime_ret = strftime(session_creation_datetime,
-                                       sizeof(session_creation_datetime),
-                                       "%Y%m%d-%H%M%S", timeinfo);
+                                               sizeof(session_creation_datetime),
+                                               "%Y%m%d-%H%M%S",
+                                               timeinfo);
                        if (strftime_ret == 0) {
                                ERR("Failed to format session creation timestamp while setting network URI");
                                ret = -LTTNG_ERR_FATAL;
                                goto error;
                        }
                        ret = snprintf(output->dst.net.base_dir,
-                                       sizeof(output->dst.net.base_dir),
-                                       "/%s/%s-%s/", session->hostname,
-                                       session->name,
-                                       session_creation_datetime);
+                                      sizeof(output->dst.net.base_dir),
+                                      "/%s/%s-%s/",
+                                      session->hostname,
+                                      session->name,
+                                      session_creation_datetime);
                }
        }
        if (ret >= sizeof(output->dst.net.base_dir)) {
@@ -819,8 +813,7 @@ int consumer_set_network_uri(const struct ltt_session *session,
                goto error;
        }
 
-       DBG3("Consumer set network uri base_dir path %s",
-                       output->dst.net.base_dir);
+       DBG3("Consumer set network uri base_dir path %s", output->dst.net.base_dir);
 
 end:
        return 0;
@@ -835,8 +828,7 @@ error:
  *
  * The consumer socket lock must be held by the caller.
  */
-int consumer_send_fds(struct consumer_socket *sock, const int *fds,
-               size_t nb_fd)
+int consumer_send_fds(struct consumer_socket *sock, const int *fds, size_t nb_fd)
 {
        int ret;
 
@@ -862,8 +854,7 @@ error:
  *
  * The consumer socket lock must be held by the caller.
  */
-int consumer_send_msg(struct consumer_socket *sock,
-               const struct lttcomm_consumer_msg *msg)
+int consumer_send_msg(struct consumer_socket *sock, const struct lttcomm_consumer_msg *msg)
 {
        int ret;
 
@@ -887,8 +878,7 @@ error:
  *
  * The consumer socket lock must be held by the caller.
  */
-int consumer_send_channel(struct consumer_socket *sock,
-               struct lttcomm_consumer_msg *msg)
+int consumer_send_channel(struct consumer_socket *sock, struct lttcomm_consumer_msg *msg)
 {
        int ret;
 
@@ -909,33 +899,33 @@ error:
  * information.
  */
 void consumer_init_ask_channel_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t subbuf_size,
-               uint64_t num_subbuf,
-               int overwrite,
-               unsigned int switch_timer_interval,
-               unsigned int read_timer_interval,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               unsigned int monitor_timer_interval,
-               int output,
-               int type,
-               uint64_t session_id,
-               const char *pathname,
-               const char *name,
-               uint64_t relayd_id,
-               uint64_t key,
-               const lttng_uuid& uuid,
-               uint32_t chan_id,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               uint64_t session_id_per_pid,
-               unsigned int monitor,
-               uint32_t ust_app_uid,
-               int64_t blocking_timeout,
-               const char *root_shm_path,
-               const char *shm_path,
-               struct lttng_trace_chunk *trace_chunk,
-               const struct lttng_credentials *buffer_credentials)
+                                       uint64_t subbuf_size,
+                                       uint64_t num_subbuf,
+                                       int overwrite,
+                                       unsigned int switch_timer_interval,
+                                       unsigned int read_timer_interval,
+                                       unsigned int live_timer_interval,
+                                       bool is_in_live_session,
+                                       unsigned int monitor_timer_interval,
+                                       int output,
+                                       int type,
+                                       uint64_t session_id,
+                                       const char *pathname,
+                                       const char *name,
+                                       uint64_t relayd_id,
+                                       uint64_t key,
+                                       const lttng_uuid& uuid,
+                                       uint32_t chan_id,
+                                       uint64_t tracefile_size,
+                                       uint64_t tracefile_count,
+                                       uint64_t session_id_per_pid,
+                                       unsigned int monitor,
+                                       uint32_t ust_app_uid,
+                                       int64_t blocking_timeout,
+                                       const char *root_shm_path,
+                                       const char *shm_path,
+                                       struct lttng_trace_chunk *trace_chunk,
+                                       const struct lttng_credentials *buffer_credentials)
 {
        LTTNG_ASSERT(msg);
 
@@ -952,14 +942,12 @@ void consumer_init_ask_channel_comm_msg(struct lttcomm_consumer_msg *msg,
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
                LTTNG_OPTIONAL_SET(&msg->u.ask_channel.chunk_id, chunk_id);
        }
-       msg->u.ask_channel.buffer_credentials.uid =
-                       lttng_credentials_get_uid(buffer_credentials);
-       msg->u.ask_channel.buffer_credentials.gid =
-                       lttng_credentials_get_gid(buffer_credentials);
+       msg->u.ask_channel.buffer_credentials.uid = lttng_credentials_get_uid(buffer_credentials);
+       msg->u.ask_channel.buffer_credentials.gid = lttng_credentials_get_gid(buffer_credentials);
 
        msg->cmd_type = LTTNG_CONSUMER_ASK_CHANNEL_CREATION;
        msg->u.ask_channel.subbuf_size = subbuf_size;
-       msg->u.ask_channel.num_subbuf = num_subbuf ;
+       msg->u.ask_channel.num_subbuf = num_subbuf;
        msg->u.ask_channel.overwrite = overwrite;
        msg->u.ask_channel.switch_timer_interval = switch_timer_interval;
        msg->u.ask_channel.read_timer_interval = read_timer_interval;
@@ -982,22 +970,22 @@ void consumer_init_ask_channel_comm_msg(struct lttcomm_consumer_msg *msg,
        std::copy(uuid.begin(), uuid.end(), msg->u.ask_channel.uuid);
 
        if (pathname) {
-               strncpy(msg->u.ask_channel.pathname, pathname,
-                               sizeof(msg->u.ask_channel.pathname));
-               msg->u.ask_channel.pathname[sizeof(msg->u.ask_channel.pathname)-1] = '\0';
+               strncpy(msg->u.ask_channel.pathname, pathname, sizeof(msg->u.ask_channel.pathname));
+               msg->u.ask_channel.pathname[sizeof(msg->u.ask_channel.pathname) - 1] = '\0';
        }
 
        strncpy(msg->u.ask_channel.name, name, sizeof(msg->u.ask_channel.name));
        msg->u.ask_channel.name[sizeof(msg->u.ask_channel.name) - 1] = '\0';
 
        if (root_shm_path) {
-               strncpy(msg->u.ask_channel.root_shm_path, root_shm_path,
+               strncpy(msg->u.ask_channel.root_shm_path,
+                       root_shm_path,
                        sizeof(msg->u.ask_channel.root_shm_path));
-               msg->u.ask_channel.root_shm_path[sizeof(msg->u.ask_channel.root_shm_path) - 1] = '\0';
+               msg->u.ask_channel.root_shm_path[sizeof(msg->u.ask_channel.root_shm_path) - 1] =
+                       '\0';
        }
        if (shm_path) {
-               strncpy(msg->u.ask_channel.shm_path, shm_path,
-                       sizeof(msg->u.ask_channel.shm_path));
+               strncpy(msg->u.ask_channel.shm_path, shm_path, sizeof(msg->u.ask_channel.shm_path));
                msg->u.ask_channel.shm_path[sizeof(msg->u.ask_channel.shm_path) - 1] = '\0';
        }
 }
@@ -1006,21 +994,21 @@ void consumer_init_ask_channel_comm_msg(struct lttcomm_consumer_msg *msg,
  * Init channel communication message structure.
  */
 void consumer_init_add_channel_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t channel_key,
-               uint64_t session_id,
-               const char *pathname,
-               uint64_t relayd_id,
-               const char *name,
-               unsigned int nb_init_streams,
-               enum lttng_event_output output,
-               int type,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               unsigned int monitor,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               unsigned int monitor_timer_interval,
-               struct lttng_trace_chunk *trace_chunk)
+                                       uint64_t channel_key,
+                                       uint64_t session_id,
+                                       const char *pathname,
+                                       uint64_t relayd_id,
+                                       const char *name,
+                                       unsigned int nb_init_streams,
+                                       enum lttng_event_output output,
+                                       int type,
+                                       uint64_t tracefile_size,
+                                       uint64_t tracefile_count,
+                                       unsigned int monitor,
+                                       unsigned int live_timer_interval,
+                                       bool is_in_live_session,
+                                       unsigned int monitor_timer_interval,
+                                       struct lttng_trace_chunk *trace_chunk)
 {
        LTTNG_ASSERT(msg);
 
@@ -1051,8 +1039,7 @@ void consumer_init_add_channel_comm_msg(struct lttcomm_consumer_msg *msg,
        msg->u.channel.is_live = is_in_live_session;
        msg->u.channel.monitor_timer_interval = monitor_timer_interval;
 
-       strncpy(msg->u.channel.pathname, pathname,
-                       sizeof(msg->u.channel.pathname));
+       strncpy(msg->u.channel.pathname, pathname, sizeof(msg->u.channel.pathname));
        msg->u.channel.pathname[sizeof(msg->u.channel.pathname) - 1] = '\0';
 
        strncpy(msg->u.channel.name, name, sizeof(msg->u.channel.name));
@@ -1063,9 +1050,9 @@ void consumer_init_add_channel_comm_msg(struct lttcomm_consumer_msg *msg,
  * Init stream communication message structure.
  */
 void consumer_init_add_stream_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t channel_key,
-               uint64_t stream_key,
-               int32_t cpu)
+                                      uint64_t channel_key,
+                                      uint64_t stream_key,
+                                      int32_t cpu)
 {
        LTTNG_ASSERT(msg);
 
@@ -1078,8 +1065,9 @@ void consumer_init_add_stream_comm_msg(struct lttcomm_consumer_msg *msg,
 }
 
 void consumer_init_streams_sent_comm_msg(struct lttcomm_consumer_msg *msg,
-               enum lttng_consumer_command cmd,
-               uint64_t channel_key, uint64_t net_seq_idx)
+                                        enum lttng_consumer_command cmd,
+                                        uint64_t channel_key,
+                                        uint64_t net_seq_idx)
 {
        LTTNG_ASSERT(msg);
 
@@ -1094,8 +1082,10 @@ void consumer_init_streams_sent_comm_msg(struct lttcomm_consumer_msg *msg,
  * Send stream communication structure to the consumer.
  */
 int consumer_send_stream(struct consumer_socket *sock,
-               struct consumer_output *dst, struct lttcomm_consumer_msg *msg,
-               const int *fds, size_t nb_fd)
+                        struct consumer_output *dst,
+                        struct lttcomm_consumer_msg *msg,
+                        const int *fds,
+                        size_t nb_fd)
 {
        int ret;
 
@@ -1126,12 +1116,17 @@ error:
  * On success return positive value. On error, negative value.
  */
 int consumer_send_relayd_socket(struct consumer_socket *consumer_sock,
-               struct lttcomm_relayd_sock *rsock, struct consumer_output *consumer,
-               enum lttng_stream_type type, uint64_t session_id,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               const uint64_t *current_chunk_id, time_t session_creation_time,
-               bool session_name_contains_creation_time)
+                               struct lttcomm_relayd_sock *rsock,
+                               struct consumer_output *consumer,
+                               enum lttng_stream_type type,
+                               uint64_t session_id,
+                               const char *session_name,
+                               const char *hostname,
+                               const char *base_path,
+                               int session_live_timer,
+                               const uint64_t *current_chunk_id,
+                               time_t session_creation_time,
+                               bool session_name_contains_creation_time)
 {
        int ret;
        int fd;
@@ -1153,21 +1148,26 @@ int consumer_send_relayd_socket(struct consumer_socket *consumer_sock,
                char output_path[LTTNG_PATH_MAX] = {};
                uint64_t relayd_session_id;
 
-               ret = relayd_create_session(rsock, &relayd_session_id,
-                               session_name, hostname, base_path,
-                               session_live_timer, consumer->snapshot,
-                               session_id, the_sessiond_uuid, current_chunk_id,
-                               session_creation_time,
-                               session_name_contains_creation_time,
-                               output_path);
+               ret = relayd_create_session(rsock,
+                                           &relayd_session_id,
+                                           session_name,
+                                           hostname,
+                                           base_path,
+                                           session_live_timer,
+                                           consumer->snapshot,
+                                           session_id,
+                                           the_sessiond_uuid,
+                                           current_chunk_id,
+                                           session_creation_time,
+                                           session_name_contains_creation_time,
+                                           output_path);
                if (ret < 0) {
                        /* Close the control socket. */
                        (void) relayd_close(rsock);
                        goto error;
                }
                msg.u.relayd_sock.relayd_session_id = relayd_session_id;
-               DBG("Created session on relay, output path reply: %s",
-                       output_path);
+               DBG("Created session on relay, output path reply: %s", output_path);
        }
 
        msg.cmd_type = LTTNG_CONSUMER_ADD_RELAYD_SOCKET;
@@ -1202,9 +1202,8 @@ error:
        return ret;
 }
 
-static
-int consumer_send_pipe(struct consumer_socket *consumer_sock,
-               enum lttng_consumer_command cmd, int pipe)
+static int
+consumer_send_pipe(struct consumer_socket *consumer_sock, enum lttng_consumer_command cmd, int pipe)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -1217,8 +1216,7 @@ int consumer_send_pipe(struct consumer_socket *consumer_sock,
                command_name = "SET_CHANNEL_MONITOR_PIPE";
                break;
        default:
-               ERR("Unexpected command received in %s (cmd = %d)", __func__,
-                               (int) cmd);
+               ERR("Unexpected command received in %s (cmd = %d)", __func__, (int) cmd);
                abort();
        }
 
@@ -1234,9 +1232,7 @@ int consumer_send_pipe(struct consumer_socket *consumer_sock,
                goto error;
        }
 
-       DBG3("Sending %s pipe %d to consumer on socket %d",
-                       pipe_name,
-                       pipe, *consumer_sock->fd_ptr);
+       DBG3("Sending %s pipe %d to consumer on socket %d", pipe_name, pipe, *consumer_sock->fd_ptr);
        ret = consumer_send_fds(consumer_sock, &pipe, 1);
        if (ret < 0) {
                goto error;
@@ -1248,22 +1244,19 @@ error:
        return ret;
 }
 
-int consumer_send_channel_monitor_pipe(struct consumer_socket *consumer_sock,
-               int pipe)
+int consumer_send_channel_monitor_pipe(struct consumer_socket *consumer_sock, int pipe)
 {
-       return consumer_send_pipe(consumer_sock,
-                       LTTNG_CONSUMER_SET_CHANNEL_MONITOR_PIPE, pipe);
+       return consumer_send_pipe(consumer_sock, LTTNG_CONSUMER_SET_CHANNEL_MONITOR_PIPE, pipe);
 }
 
 /*
  * Ask the consumer if the data is pending for the specific session id.
  * Returns 1 if data is pending, 0 otherwise, or < 0 on error.
  */
-int consumer_is_data_pending(uint64_t session_id,
-               struct consumer_output *consumer)
+int consumer_is_data_pending(uint64_t session_id, struct consumer_output *consumer)
 {
        int ret;
-       int32_t ret_code = 0;  /* Default is that the data is NOT pending */
+       int32_t ret_code = 0; /* Default is that the data is NOT pending */
        struct consumer_socket *socket;
        struct lttng_ht_iter iter;
        struct lttcomm_consumer_msg msg;
@@ -1276,41 +1269,42 @@ int consumer_is_data_pending(uint64_t session_id,
        msg.cmd_type = LTTNG_CONSUMER_DATA_PENDING;
        msg.u.data_pending.session_id = session_id;
 
-       /* Send command for each consumer */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(consumer->socks->ht, &iter.iter, socket,
-                       node.node) {
-               pthread_mutex_lock(socket->lock);
-               ret = consumer_socket_send(socket, &msg, sizeof(msg));
-               if (ret < 0) {
-                       pthread_mutex_unlock(socket->lock);
-                       goto error_unlock;
-               }
+       {
+               /* Send command for each consumer. */
+               lttng::urcu::read_lock_guard read_lock;
 
-               /*
-                * No need for a recv reply status because the answer to the command is
-                * the reply status message.
-                */
+               cds_lfht_for_each_entry (consumer->socks->ht, &iter.iter, socket, node.node) {
+                       pthread_mutex_lock(socket->lock);
+                       ret = consumer_socket_send(socket, &msg, sizeof(msg));
+                       if (ret < 0) {
+                               pthread_mutex_unlock(socket->lock);
+                               goto error_unlock;
+                       }
+
+                       /*
+                        * No need for a recv reply status because the answer to the command is
+                        * the reply status message.
+                        */
+                       ret = consumer_socket_recv(socket, &ret_code, sizeof(ret_code));
+                       if (ret < 0) {
+                               pthread_mutex_unlock(socket->lock);
+                               goto error_unlock;
+                       }
 
-               ret = consumer_socket_recv(socket, &ret_code, sizeof(ret_code));
-               if (ret < 0) {
                        pthread_mutex_unlock(socket->lock);
-                       goto error_unlock;
-               }
-               pthread_mutex_unlock(socket->lock);
 
-               if (ret_code == 1) {
-                       break;
+                       if (ret_code == 1) {
+                               break;
+                       }
                }
        }
-       rcu_read_unlock();
 
        DBG("Consumer data is %s pending for session id %" PRIu64,
-                       ret_code == 1 ? "" : "NOT", session_id);
+           ret_code == 1 ? "" : "NOT",
+           session_id);
        return ret_code;
 
 error_unlock:
-       rcu_read_unlock();
        return -1;
 }
 
@@ -1384,8 +1378,7 @@ end:
  *
  * Return 0 on success else a negative value.
  */
-int consumer_close_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key)
+int consumer_close_metadata(struct consumer_socket *socket, uint64_t metadata_key)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -1417,8 +1410,7 @@ end:
  *
  * Return 0 on success else a negative value.
  */
-int consumer_setup_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key)
+int consumer_setup_metadata(struct consumer_socket *socket, uint64_t metadata_key)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -1452,8 +1444,11 @@ end:
  * Return 0 on success else a negative value.
  */
 int consumer_push_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key, char *metadata_str, size_t len,
-               size_t target_offset, uint64_t version)
+                          uint64_t metadata_key,
+                          char *metadata_str,
+                          size_t len,
+                          size_t target_offset,
+                          uint64_t version)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -1478,8 +1473,7 @@ int consumer_push_metadata(struct consumer_socket *socket,
                goto end;
        }
 
-       DBG3("Consumer pushing metadata on sock %d of len %zu", *socket->fd_ptr,
-                       len);
+       DBG3("Consumer pushing metadata on sock %d of len %zu", *socket->fd_ptr, len);
 
        ret = consumer_socket_send(socket, metadata_str, len);
        if (ret < 0) {
@@ -1504,9 +1498,11 @@ end:
  * Returns LTTNG_OK on success or else an LTTng error code.
  */
 enum lttng_error_code consumer_snapshot_channel(struct consumer_socket *socket,
-               uint64_t key, const struct consumer_output *output, int metadata,
-               const char *channel_path,
-               uint64_t nb_packets_per_stream)
+                                               uint64_t key,
+                                               const struct consumer_output *output,
+                                               int metadata,
+                                               const char *channel_path,
+                                               uint64_t nb_packets_per_stream)
 {
        int ret;
        enum lttng_error_code status = LTTNG_OK;
@@ -1524,20 +1520,19 @@ enum lttng_error_code consumer_snapshot_channel(struct consumer_socket *socket,
        msg.u.snapshot_channel.metadata = metadata;
 
        if (output->type == CONSUMER_DST_NET) {
-               msg.u.snapshot_channel.relayd_id =
-                               output->net_seq_index;
+               msg.u.snapshot_channel.relayd_id = output->net_seq_index;
                msg.u.snapshot_channel.use_relayd = 1;
        } else {
                msg.u.snapshot_channel.relayd_id = (uint64_t) -1ULL;
        }
        ret = lttng_strncpy(msg.u.snapshot_channel.pathname,
-                       channel_path,
-                       sizeof(msg.u.snapshot_channel.pathname));
+                           channel_path,
+                           sizeof(msg.u.snapshot_channel.pathname));
        if (ret < 0) {
                ERR("Snapshot path exceeds the maximal allowed length of %zu bytes (%zu bytes required) with path \"%s\"",
-                               sizeof(msg.u.snapshot_channel.pathname),
-                               strlen(channel_path),
-                               channel_path);
+                   sizeof(msg.u.snapshot_channel.pathname),
+                   strlen(channel_path),
+                   channel_path);
                status = LTTNG_ERR_SNAPSHOT_FAIL;
                goto error;
        }
@@ -1566,8 +1561,10 @@ error:
 /*
  * Ask the consumer the number of discarded events for a channel.
  */
-int consumer_get_discarded_events(uint64_t session_id, uint64_t channel_key,
-               struct consumer_output *consumer, uint64_t *discarded)
+int consumer_get_discarded_events(uint64_t session_id,
+                                 uint64_t channel_key,
+                                 struct consumer_output *consumer,
+                                 uint64_t *discarded)
 {
        int ret;
        struct consumer_socket *socket;
@@ -1585,46 +1582,51 @@ int consumer_get_discarded_events(uint64_t session_id, uint64_t channel_key,
 
        *discarded = 0;
 
-       /* Send command for each consumer */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(consumer->socks->ht, &iter.iter, socket,
-                       node.node) {
-               uint64_t consumer_discarded = 0;
-               pthread_mutex_lock(socket->lock);
-               ret = consumer_socket_send(socket, &msg, sizeof(msg));
-               if (ret < 0) {
-                       pthread_mutex_unlock(socket->lock);
-                       goto end;
-               }
+       /* Send command for each consumer. */
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (consumer->socks->ht, &iter.iter, socket, node.node) {
+                       uint64_t consumer_discarded = 0;
+
+                       pthread_mutex_lock(socket->lock);
+                       ret = consumer_socket_send(socket, &msg, sizeof(msg));
+                       if (ret < 0) {
+                               pthread_mutex_unlock(socket->lock);
+                               goto end;
+                       }
+
+                       /*
+                        * No need for a recv reply status because the answer to the
+                        * command is the reply status message.
+                        */
+                       ret = consumer_socket_recv(
+                               socket, &consumer_discarded, sizeof(consumer_discarded));
+                       if (ret < 0) {
+                               ERR("get discarded events");
+                               pthread_mutex_unlock(socket->lock);
+                               goto end;
+                       }
 
-               /*
-                * No need for a recv reply status because the answer to the
-                * command is the reply status message.
-                */
-               ret = consumer_socket_recv(socket, &consumer_discarded,
-                               sizeof(consumer_discarded));
-               if (ret < 0) {
-                       ERR("get discarded events");
                        pthread_mutex_unlock(socket->lock);
-                       goto end;
+                       *discarded += consumer_discarded;
                }
-               pthread_mutex_unlock(socket->lock);
-               *discarded += consumer_discarded;
        }
+
        ret = 0;
-       DBG("Consumer discarded %" PRIu64 " events in session id %" PRIu64,
-                       *discarded, session_id);
+       DBG("Consumer discarded %" PRIu64 " events in session id %" PRIu64, *discarded, session_id);
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
 /*
  * Ask the consumer the number of lost packets for a channel.
  */
-int consumer_get_lost_packets(uint64_t session_id, uint64_t channel_key,
-               struct consumer_output *consumer, uint64_t *lost)
+int consumer_get_lost_packets(uint64_t session_id,
+                             uint64_t channel_key,
+                             struct consumer_output *consumer,
+                             uint64_t *lost)
 {
        int ret;
        struct consumer_socket *socket;
@@ -1642,38 +1644,38 @@ int consumer_get_lost_packets(uint64_t session_id, uint64_t channel_key,
 
        *lost = 0;
 
-       /* Send command for each consumer */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(consumer->socks->ht, &iter.iter, socket,
-                       node.node) {
-               uint64_t consumer_lost = 0;
-               pthread_mutex_lock(socket->lock);
-               ret = consumer_socket_send(socket, &msg, sizeof(msg));
-               if (ret < 0) {
-                       pthread_mutex_unlock(socket->lock);
-                       goto end;
-               }
+       /* Send command for each consumer. */
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               /*
-                * No need for a recv reply status because the answer to the
-                * command is the reply status message.
-                */
-               ret = consumer_socket_recv(socket, &consumer_lost,
-                               sizeof(consumer_lost));
-               if (ret < 0) {
-                       ERR("get lost packets");
+               cds_lfht_for_each_entry (consumer->socks->ht, &iter.iter, socket, node.node) {
+                       uint64_t consumer_lost = 0;
+                       pthread_mutex_lock(socket->lock);
+                       ret = consumer_socket_send(socket, &msg, sizeof(msg));
+                       if (ret < 0) {
+                               pthread_mutex_unlock(socket->lock);
+                               goto end;
+                       }
+
+                       /*
+                        * No need for a recv reply status because the answer to the
+                        * command is the reply status message.
+                        */
+                       ret = consumer_socket_recv(socket, &consumer_lost, sizeof(consumer_lost));
+                       if (ret < 0) {
+                               ERR("get lost packets");
+                               pthread_mutex_unlock(socket->lock);
+                               goto end;
+                       }
                        pthread_mutex_unlock(socket->lock);
-                       goto end;
+                       *lost += consumer_lost;
                }
-               pthread_mutex_unlock(socket->lock);
-               *lost += consumer_lost;
        }
+
        ret = 0;
-       DBG("Consumer lost %" PRIu64 " packets in session id %" PRIu64,
-                       *lost, session_id);
+       DBG("Consumer lost %" PRIu64 " packets in session id %" PRIu64, *lost, session_id);
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -1684,9 +1686,10 @@ end:
  * when the rotation started. On the relay, this allows to keep track in which
  * chunk each stream is currently writing to (for the rotate_pending operation).
  */
-int consumer_rotate_channel(struct consumer_socket *socket, uint64_t key,
-               struct consumer_output *output,
-               bool is_metadata_channel)
+int consumer_rotate_channel(struct consumer_socket *socket,
+                           uint64_t key,
+                           struct consumer_output *output,
+                           bool is_metadata_channel)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -1781,8 +1784,7 @@ error_socket:
        return ret;
 }
 
-int consumer_init(struct consumer_socket *socket,
-               const lttng_uuid& sessiond_uuid)
+int consumer_init(struct consumer_socket *socket, const lttng_uuid& sessiond_uuid)
 {
        int ret;
        struct lttcomm_consumer_msg msg = {
@@ -1812,15 +1814,16 @@ error:
  * Called with the consumer socket lock held.
  */
 int consumer_create_trace_chunk(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               const char *domain_subdir)
+                               uint64_t relayd_id,
+                               uint64_t session_id,
+                               struct lttng_trace_chunk *chunk,
+                               const char *domain_subdir)
 {
        int ret;
        enum lttng_trace_chunk_status chunk_status;
        struct lttng_credentials chunk_credentials;
-       const struct lttng_directory_handle *chunk_directory_handle = NULL;
-       struct lttng_directory_handle *domain_handle = NULL;
+       const struct lttng_directory_handle *chunk_directory_handle = nullptr;
+       struct lttng_directory_handle *domain_handle = nullptr;
        int domain_dirfd;
        const char *chunk_name;
        bool chunk_name_overridden;
@@ -1840,44 +1843,38 @@ int consumer_create_trace_chunk(struct consumer_socket *socket,
        LTTNG_ASSERT(chunk);
 
        if (relayd_id != -1ULL) {
-               LTTNG_OPTIONAL_SET(&msg.u.create_trace_chunk.relayd_id,
-                               relayd_id);
+               LTTNG_OPTIONAL_SET(&msg.u.create_trace_chunk.relayd_id, relayd_id);
        }
 
-       chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name,
-                       &chunk_name_overridden);
+       chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, &chunk_name_overridden);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK &&
-                       chunk_status != LTTNG_TRACE_CHUNK_STATUS_NONE) {
+           chunk_status != LTTNG_TRACE_CHUNK_STATUS_NONE) {
                ERR("Failed to get name of trace chunk");
                ret = -LTTNG_ERR_FATAL;
                goto error;
        }
        if (chunk_name_overridden) {
                ret = lttng_strncpy(msg.u.create_trace_chunk.override_name,
-                               chunk_name,
-                               sizeof(msg.u.create_trace_chunk.override_name));
+                                   chunk_name,
+                                   sizeof(msg.u.create_trace_chunk.override_name));
                if (ret) {
                        ERR("Trace chunk name \"%s\" exceeds the maximal length allowed by the consumer protocol",
-                                       chunk_name);
+                           chunk_name);
                        ret = -LTTNG_ERR_FATAL;
                        goto error;
                }
        }
 
-       chunk_status = lttng_trace_chunk_get_creation_timestamp(chunk,
-                       &creation_timestamp);
+       chunk_status = lttng_trace_chunk_get_creation_timestamp(chunk, &creation_timestamp);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -LTTNG_ERR_FATAL;
                goto error;
        }
-       msg.u.create_trace_chunk.creation_timestamp =
-                       (uint64_t) creation_timestamp;
+       msg.u.create_trace_chunk.creation_timestamp = (uint64_t) creation_timestamp;
        /* Only used for logging purposes. */
-       ret = time_to_iso8601_str(creation_timestamp,
-                       creation_timestamp_buffer,
-                       sizeof(creation_timestamp_buffer));
-       creation_timestamp_str = !ret ? creation_timestamp_buffer :
-                       "(formatting error)";
+       ret = time_to_iso8601_str(
+               creation_timestamp, creation_timestamp_buffer, sizeof(creation_timestamp_buffer));
+       creation_timestamp_str = !ret ? creation_timestamp_buffer : "(formatting error)";
 
        chunk_status = lttng_trace_chunk_get_id(chunk, &chunk_id);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
@@ -1893,13 +1890,12 @@ int consumer_create_trace_chunk(struct consumer_socket *socket,
 
        if (chunk_has_local_output) {
                chunk_status = lttng_trace_chunk_borrow_chunk_directory_handle(
-                               chunk, &chunk_directory_handle);
+                       chunk, &chunk_directory_handle);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -LTTNG_ERR_FATAL;
                        goto error;
                }
-               chunk_status = lttng_trace_chunk_get_credentials(
-                               chunk, &chunk_credentials);
+               chunk_status = lttng_trace_chunk_get_credentials(chunk, &chunk_credentials);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        /*
                         * Not associating credentials to a sessiond chunk is a
@@ -1908,17 +1904,15 @@ int consumer_create_trace_chunk(struct consumer_socket *socket,
                        ret = -LTTNG_ERR_FATAL;
                        goto error;
                }
-               tc_status = lttng_trace_chunk_create_subdirectory(
-                               chunk, domain_subdir);
+               tc_status = lttng_trace_chunk_create_subdirectory(chunk, domain_subdir);
                if (tc_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        PERROR("Failed to create chunk domain output directory \"%s\"",
-                               domain_subdir);
+                              domain_subdir);
                        ret = -LTTNG_ERR_FATAL;
                        goto error;
                }
-               domain_handle = lttng_directory_handle_create_from_handle(
-                               domain_subdir,
-                               chunk_directory_handle);
+               domain_handle = lttng_directory_handle_create_from_handle(domain_subdir,
+                                                                         chunk_directory_handle);
                if (!domain_handle) {
                        ret = -LTTNG_ERR_FATAL;
                        goto error;
@@ -1932,22 +1926,22 @@ int consumer_create_trace_chunk(struct consumer_socket *socket,
                 * The ownership of the chunk directory handle's is maintained
                 * by the trace chunk.
                 */
-               domain_dirfd = lttng_directory_handle_get_dirfd(
-                               domain_handle);
+               domain_dirfd = lttng_directory_handle_get_dirfd(domain_handle);
                LTTNG_ASSERT(domain_dirfd >= 0);
 
                msg.u.create_trace_chunk.credentials.value.uid =
-                               lttng_credentials_get_uid(&chunk_credentials);
+                       lttng_credentials_get_uid(&chunk_credentials);
                msg.u.create_trace_chunk.credentials.value.gid =
-                               lttng_credentials_get_gid(&chunk_credentials);
+                       lttng_credentials_get_gid(&chunk_credentials);
                msg.u.create_trace_chunk.credentials.is_set = 1;
        }
 
        DBG("Sending consumer create trace chunk command: relayd_id = %" PRId64
-                       ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
-                       ", creation_timestamp = %s",
-                       relayd_id, session_id, chunk_id,
-                       creation_timestamp_str);
+           ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", creation_timestamp = %s",
+           relayd_id,
+           session_id,
+           chunk_id,
+           creation_timestamp_str);
        health_code_update();
        ret = consumer_send_msg(socket, &msg);
        health_code_update();
@@ -1979,9 +1973,10 @@ error:
  * Called with the consumer socket lock held.
  */
 int consumer_close_trace_chunk(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               char *closed_trace_chunk_path)
+                              uint64_t relayd_id,
+                              uint64_t session_id,
+                              struct lttng_trace_chunk *chunk,
+                              char *closed_trace_chunk_path)
 {
        int ret;
        enum lttng_trace_chunk_status chunk_status;
@@ -2002,16 +1997,14 @@ int consumer_close_trace_chunk(struct consumer_socket *socket,
        lttng_dynamic_buffer_init(&path_reception_buffer);
 
        if (relayd_id != -1ULL) {
-               LTTNG_OPTIONAL_SET(
-                               &msg.u.close_trace_chunk.relayd_id, relayd_id);
+               LTTNG_OPTIONAL_SET(&msg.u.close_trace_chunk.relayd_id, relayd_id);
        }
 
-       chunk_status = lttng_trace_chunk_get_close_command(
-                       chunk, &close_command);
+       chunk_status = lttng_trace_chunk_get_close_command(chunk, &close_command);
        switch (chunk_status) {
        case LTTNG_TRACE_CHUNK_STATUS_OK:
                LTTNG_OPTIONAL_SET(&msg.u.close_trace_chunk.close_command,
-                               (uint32_t) close_command);
+                                  (uint32_t) close_command);
                break;
        case LTTNG_TRACE_CHUNK_STATUS_NONE:
                break;
@@ -2030,8 +2023,7 @@ int consumer_close_trace_chunk(struct consumer_socket *socket,
        LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
        msg.u.close_trace_chunk.chunk_id = chunk_id;
 
-       chunk_status = lttng_trace_chunk_get_close_timestamp(chunk,
-                       &close_timestamp);
+       chunk_status = lttng_trace_chunk_get_close_timestamp(chunk, &close_timestamp);
        /*
         * A trace chunk should be closed locally before being closed remotely.
         * Otherwise, the close timestamp would never be transmitted to the
@@ -2041,13 +2033,14 @@ int consumer_close_trace_chunk(struct consumer_socket *socket,
        msg.u.close_trace_chunk.close_timestamp = (uint64_t) close_timestamp;
 
        if (msg.u.close_trace_chunk.close_command.is_set) {
-               close_command_name = lttng_trace_chunk_command_type_get_name(
-                               close_command);
+               close_command_name = lttng_trace_chunk_command_type_get_name(close_command);
        }
        DBG("Sending consumer close trace chunk command: relayd_id = %" PRId64
-                       ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
-                       ", close command = \"%s\"",
-                       relayd_id, session_id, chunk_id, close_command_name);
+           ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", close command = \"%s\"",
+           relayd_id,
+           session_id,
+           chunk_id,
+           close_command_name);
 
        health_code_update();
        ret = consumer_socket_send(socket, &msg, sizeof(struct lttcomm_consumer_msg));
@@ -2061,20 +2054,20 @@ int consumer_close_trace_chunk(struct consumer_socket *socket,
                goto error;
        }
        if (reply.path_length >= LTTNG_PATH_MAX) {
-               ERR("Invalid path returned by relay daemon: %" PRIu32 "bytes exceeds maximal allowed length of %d bytes",
-                               reply.path_length, LTTNG_PATH_MAX);
+               ERR("Invalid path returned by relay daemon: %" PRIu32
+                   "bytes exceeds maximal allowed length of %d bytes",
+                   reply.path_length,
+                   LTTNG_PATH_MAX);
                ret = -LTTNG_ERR_INVALID_PROTOCOL;
                goto error;
        }
-       ret = lttng_dynamic_buffer_set_size(&path_reception_buffer,
-                       reply.path_length);
+       ret = lttng_dynamic_buffer_set_size(&path_reception_buffer, reply.path_length);
        if (ret) {
                ERR("Failed to allocate reception buffer of path returned by the \"close trace chunk\" command");
                ret = -LTTNG_ERR_NOMEM;
                goto error;
        }
-       ret = consumer_socket_recv(socket, path_reception_buffer.data,
-                       path_reception_buffer.size);
+       ret = consumer_socket_recv(socket, path_reception_buffer.data, path_reception_buffer.size);
        if (ret < 0) {
                ERR("Communication error while receiving path of closed trace chunk");
                ret = -LTTNG_ERR_CLOSE_TRACE_CHUNK_FAIL_CONSUMER;
@@ -2090,8 +2083,9 @@ int consumer_close_trace_chunk(struct consumer_socket *socket,
                 * closed_trace_chunk_path is assumed to have a length >=
                 * LTTNG_PATH_MAX
                 */
-               memcpy(closed_trace_chunk_path, path_reception_buffer.data,
-                               path_reception_buffer.size);
+               memcpy(closed_trace_chunk_path,
+                      path_reception_buffer.data,
+                      path_reception_buffer.size);
        }
 error:
        lttng_dynamic_buffer_reset(&path_reception_buffer);
@@ -2106,9 +2100,10 @@ error:
  * Returns 0 on success, or a negative value on error.
  */
 int consumer_trace_chunk_exists(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               enum consumer_trace_chunk_exists_status *result)
+                               uint64_t relayd_id,
+                               uint64_t session_id,
+                               struct lttng_trace_chunk *chunk,
+                               enum consumer_trace_chunk_exists_status *result)
 {
        int ret;
        enum lttng_trace_chunk_status chunk_status;
@@ -2124,8 +2119,7 @@ int consumer_trace_chunk_exists(struct consumer_socket *socket,
        LTTNG_ASSERT(socket);
 
        if (relayd_id != -1ULL) {
-               LTTNG_OPTIONAL_SET(&msg.u.trace_chunk_exists.relayd_id,
-                               relayd_id);
+               LTTNG_OPTIONAL_SET(&msg.u.trace_chunk_exists.relayd_id, relayd_id);
        }
 
        chunk_status = lttng_trace_chunk_get_id(chunk, &chunk_id);
@@ -2141,8 +2135,10 @@ int consumer_trace_chunk_exists(struct consumer_socket *socket,
        msg.u.trace_chunk_exists.chunk_id = chunk_id;
 
        DBG("Sending consumer trace chunk exists command: relayd_id = %" PRId64
-                       ", session_id = %" PRIu64
-                       ", chunk_id = %" PRIu64, relayd_id, session_id, chunk_id);
+           ", session_id = %" PRIu64 ", chunk_id = %" PRIu64,
+           relayd_id,
+           session_id,
+           chunk_id);
 
        health_code_update();
        ret = consumer_send_msg(socket, &msg);
@@ -2164,8 +2160,7 @@ int consumer_trace_chunk_exists(struct consumer_socket *socket,
                ret = -1;
                goto error;
        }
-       DBG("Consumer reply to TRACE_CHUNK_EXISTS command: %s",
-                       consumer_reply_str);
+       DBG("Consumer reply to TRACE_CHUNK_EXISTS command: %s", consumer_reply_str);
        ret = 0;
 error:
        health_code_update();
index d76ec025f85d6773a31747b8092d562932897e6a..6c334875b26012650169d71d30dda47e2bb73926 100644 (file)
@@ -8,13 +8,15 @@
 #ifndef _CONSUMER_H
 #define _CONSUMER_H
 
+#include "snapshot.hpp"
+
 #include <common/consumer/consumer.hpp>
 #include <common/hashtable/hashtable.hpp>
+
 #include <lttng/lttng.h>
-#include <urcu/ref.h>
-#include <algorithm>
 
-#include "snapshot.hpp"
+#include <algorithm>
+#include <urcu/ref.h>
 
 struct snapshot;
 struct snapshot_output;
@@ -27,8 +29,8 @@ struct ltt_session;
  * C++.
  */
 static_assert(__cplusplus == 201103L, "");
-template <typename T>
-constexpr T max_constexpr(T l, T r)
+template <typename NumericalType>
+constexpr NumericalType max_constexpr(NumericalType l, NumericalType r)
 {
        return l > r ? l : r;
 }
@@ -75,9 +77,9 @@ struct consumer_socket {
 };
 
 struct consumer_data {
-       consumer_data (lttng_consumer_type type_)
-               : type(type_)
-       {}
+       explicit consumer_data(lttng_consumer_type type_) : type(type_)
+       {
+       }
 
        enum lttng_consumer_type type;
 
@@ -144,10 +146,10 @@ struct consumer_net {
  * Consumer output object describing where and how to send data.
  */
 struct consumer_output {
-       struct urcu_ref ref;    /* Refcount */
+       struct urcu_ref ref; /* Refcount */
 
        /* If the consumer is enabled meaning that should be used */
-       unsigned int enabled;
+       bool enabled;
        enum consumer_dst_type type;
 
        /*
@@ -167,9 +169,8 @@ struct consumer_output {
         * Subdirectory path name used for both local and network
         * consumer ("kernel", "ust", or empty).
         */
-       char domain_subdir[
-               max_constexpr(sizeof(DEFAULT_KERNEL_TRACE_DIR),
-                       sizeof(DEFAULT_UST_TRACE_DIR))];
+       char domain_subdir[max_constexpr(sizeof(DEFAULT_KERNEL_TRACE_DIR),
+                                        sizeof(DEFAULT_UST_TRACE_DIR))];
 
        /*
         * Hashtable of consumer_socket index by the file descriptor value. For
@@ -193,152 +194,161 @@ struct consumer_output {
        char chunk_path[LTTNG_PATH_MAX];
 };
 
-struct consumer_socket *consumer_find_socket(int key,
-               const struct consumer_output *consumer);
+struct consumer_socket *consumer_find_socket(int key, const struct consumer_output *consumer);
 struct consumer_socket *consumer_find_socket_by_bitness(int bits,
-               const struct consumer_output *consumer);
+                                                       const struct consumer_output *consumer);
 struct consumer_socket *consumer_allocate_socket(int *fd);
-void consumer_add_socket(struct consumer_socket *sock,
-               struct consumer_output *consumer);
-void consumer_del_socket(struct consumer_socket *sock,
-               struct consumer_output *consumer);
+void consumer_add_socket(struct consumer_socket *sock, struct consumer_output *consumer);
+void consumer_del_socket(struct consumer_socket *sock, struct consumer_output *consumer);
 void consumer_destroy_socket(struct consumer_socket *sock);
-int consumer_copy_sockets(struct consumer_output *dst,
-               struct consumer_output *src);
+int consumer_copy_sockets(struct consumer_output *dst, struct consumer_output *src);
 void consumer_destroy_output_sockets(struct consumer_output *obj);
-int consumer_socket_send(struct consumer_socket *socket, const void *msg,
-               size_t len);
-int consumer_socket_recv(struct consumer_socket *socket, void *msg,
-               size_t len);
+int consumer_socket_send(struct consumer_socket *socket, const void *msg, size_t len);
+int consumer_socket_recv(struct consumer_socket *socket, void *msg, size_t len);
 
 struct consumer_output *consumer_create_output(enum consumer_dst_type type);
 struct consumer_output *consumer_copy_output(struct consumer_output *obj);
 void consumer_output_get(struct consumer_output *obj);
 void consumer_output_put(struct consumer_output *obj);
 int consumer_set_network_uri(const struct ltt_session *session,
-               struct consumer_output *obj,
-               struct lttng_uri *uri);
-int consumer_send_fds(struct consumer_socket *sock, const int *fds,
-               size_t nb_fd);
-int consumer_send_msg(struct consumer_socket *sock,
-               const struct lttcomm_consumer_msg *msg);
+                            struct consumer_output *obj,
+                            struct lttng_uri *uri);
+int consumer_send_fds(struct consumer_socket *sock, const int *fds, size_t nb_fd);
+int consumer_send_msg(struct consumer_socket *sock, const struct lttcomm_consumer_msg *msg);
 int consumer_send_stream(struct consumer_socket *sock,
-               struct consumer_output *dst, struct lttcomm_consumer_msg *msg,
-               const int *fds, size_t nb_fd);
-int consumer_send_channel(struct consumer_socket *sock,
-               struct lttcomm_consumer_msg *msg);
+                        struct consumer_output *dst,
+                        struct lttcomm_consumer_msg *msg,
+                        const int *fds,
+                        size_t nb_fd);
+int consumer_send_channel(struct consumer_socket *sock, struct lttcomm_consumer_msg *msg);
 int consumer_send_relayd_socket(struct consumer_socket *consumer_sock,
-               struct lttcomm_relayd_sock *rsock, struct consumer_output *consumer,
-               enum lttng_stream_type type, uint64_t session_id,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               const uint64_t *current_chunk_id, time_t session_creation_time,
-               bool session_name_contains_creation_time);
-int consumer_send_channel_monitor_pipe(struct consumer_socket *consumer_sock,
-               int pipe);
-int consumer_send_destroy_relayd(struct consumer_socket *sock,
-               struct consumer_output *consumer);
+                               struct lttcomm_relayd_sock *rsock,
+                               struct consumer_output *consumer,
+                               enum lttng_stream_type type,
+                               uint64_t session_id,
+                               const char *session_name,
+                               const char *hostname,
+                               const char *base_path,
+                               int session_live_timer,
+                               const uint64_t *current_chunk_id,
+                               time_t session_creation_time,
+                               bool session_name_contains_creation_time);
+int consumer_send_channel_monitor_pipe(struct consumer_socket *consumer_sock, int pipe);
+int consumer_send_destroy_relayd(struct consumer_socket *sock, struct consumer_output *consumer);
 int consumer_recv_status_reply(struct consumer_socket *sock);
 int consumer_recv_status_channel(struct consumer_socket *sock,
-               uint64_t *key, unsigned int *stream_count);
+                                uint64_t *key,
+                                unsigned int *stream_count);
 void consumer_output_send_destroy_relayd(struct consumer_output *consumer);
-int consumer_create_socket(struct consumer_data *data,
-               struct consumer_output *output);
+int consumer_create_socket(struct consumer_data *data, struct consumer_output *output);
 
 void consumer_init_ask_channel_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t subbuf_size,
-               uint64_t num_subbuf,
-               int overwrite,
-               unsigned int switch_timer_interval,
-               unsigned int read_timer_interval,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               unsigned int monitor_timer_interval,
-               int output,
-               int type,
-               uint64_t session_id,
-               const char *pathname,
-               const char *name,
-               uint64_t relayd_id,
-               uint64_t key,
-               const lttng_uuid& uuid,
-               uint32_t chan_id,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               uint64_t session_id_per_pid,
-               unsigned int monitor,
-               uint32_t ust_app_uid,
-               int64_t blocking_timeout,
-               const char *root_shm_path,
-               const char *shm_path,
-               struct lttng_trace_chunk *trace_chunk,
-               const struct lttng_credentials *buffer_credentials);
+                                       uint64_t subbuf_size,
+                                       uint64_t num_subbuf,
+                                       int overwrite,
+                                       unsigned int switch_timer_interval,
+                                       unsigned int read_timer_interval,
+                                       unsigned int live_timer_interval,
+                                       bool is_in_live_session,
+                                       unsigned int monitor_timer_interval,
+                                       int output,
+                                       int type,
+                                       uint64_t session_id,
+                                       const char *pathname,
+                                       const char *name,
+                                       uint64_t relayd_id,
+                                       uint64_t key,
+                                       const lttng_uuid& uuid,
+                                       uint32_t chan_id,
+                                       uint64_t tracefile_size,
+                                       uint64_t tracefile_count,
+                                       uint64_t session_id_per_pid,
+                                       unsigned int monitor,
+                                       uint32_t ust_app_uid,
+                                       int64_t blocking_timeout,
+                                       const char *root_shm_path,
+                                       const char *shm_path,
+                                       struct lttng_trace_chunk *trace_chunk,
+                                       const struct lttng_credentials *buffer_credentials);
 void consumer_init_add_stream_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t channel_key,
-               uint64_t stream_key,
-               int32_t cpu);
+                                      uint64_t channel_key,
+                                      uint64_t stream_key,
+                                      int32_t cpu);
 void consumer_init_streams_sent_comm_msg(struct lttcomm_consumer_msg *msg,
-               enum lttng_consumer_command cmd,
-               uint64_t channel_key, uint64_t net_seq_idx);
+                                        enum lttng_consumer_command cmd,
+                                        uint64_t channel_key,
+                                        uint64_t net_seq_idx);
 void consumer_init_add_channel_comm_msg(struct lttcomm_consumer_msg *msg,
-               uint64_t channel_key,
-               uint64_t session_id,
-               const char *pathname,
-               uint64_t relayd_id,
-               const char *name,
-               unsigned int nb_init_streams,
-               enum lttng_event_output output,
-               int type,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               unsigned int monitor,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               unsigned int monitor_timer_interval,
-               struct lttng_trace_chunk *trace_chunk);
-int consumer_is_data_pending(uint64_t session_id,
-               struct consumer_output *consumer);
-int consumer_close_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key);
-int consumer_setup_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key);
+                                       uint64_t channel_key,
+                                       uint64_t session_id,
+                                       const char *pathname,
+                                       uint64_t relayd_id,
+                                       const char *name,
+                                       unsigned int nb_init_streams,
+                                       enum lttng_event_output output,
+                                       int type,
+                                       uint64_t tracefile_size,
+                                       uint64_t tracefile_count,
+                                       unsigned int monitor,
+                                       unsigned int live_timer_interval,
+                                       bool is_in_live_session,
+                                       unsigned int monitor_timer_interval,
+                                       struct lttng_trace_chunk *trace_chunk);
+int consumer_is_data_pending(uint64_t session_id, struct consumer_output *consumer);
+int consumer_close_metadata(struct consumer_socket *socket, uint64_t metadata_key);
+int consumer_setup_metadata(struct consumer_socket *socket, uint64_t metadata_key);
 int consumer_push_metadata(struct consumer_socket *socket,
-               uint64_t metadata_key, char *metadata_str, size_t len,
-               size_t target_offset, uint64_t version);
+                          uint64_t metadata_key,
+                          char *metadata_str,
+                          size_t len,
+                          size_t target_offset,
+                          uint64_t version);
 int consumer_flush_channel(struct consumer_socket *socket, uint64_t key);
 int consumer_clear_quiescent_channel(struct consumer_socket *socket, uint64_t key);
-int consumer_get_discarded_events(uint64_t session_id, uint64_t channel_key,
-               struct consumer_output *consumer, uint64_t *discarded);
-int consumer_get_lost_packets(uint64_t session_id, uint64_t channel_key,
-               struct consumer_output *consumer, uint64_t *lost);
+int consumer_get_discarded_events(uint64_t session_id,
+                                 uint64_t channel_key,
+                                 struct consumer_output *consumer,
+                                 uint64_t *discarded);
+int consumer_get_lost_packets(uint64_t session_id,
+                             uint64_t channel_key,
+                             struct consumer_output *consumer,
+                             uint64_t *lost);
 
 /* Snapshot command. */
 enum lttng_error_code consumer_snapshot_channel(struct consumer_socket *socket,
-               uint64_t key, const struct consumer_output *output, int metadata,
-               const char *channel_path, uint64_t nb_packets_per_stream);
+                                               uint64_t key,
+                                               const struct consumer_output *output,
+                                               int metadata,
+                                               const char *channel_path,
+                                               uint64_t nb_packets_per_stream);
 
 /* Rotation commands. */
-int consumer_rotate_channel(struct consumer_socket *socket, uint64_t key,
-               struct consumer_output *output, bool is_metadata_channel);
-int consumer_init(struct consumer_socket *socket,
-               const lttng_uuid& sessiond_uuid);
+int consumer_rotate_channel(struct consumer_socket *socket,
+                           uint64_t key,
+                           struct consumer_output *output,
+                           bool is_metadata_channel);
+int consumer_init(struct consumer_socket *socket, const lttng_uuid& sessiond_uuid);
 
 int consumer_create_trace_chunk(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               const char *domain_subdir);
+                               uint64_t relayd_id,
+                               uint64_t session_id,
+                               struct lttng_trace_chunk *chunk,
+                               const char *domain_subdir);
 int consumer_close_trace_chunk(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               char *closed_trace_chunk_path);
+                              uint64_t relayd_id,
+                              uint64_t session_id,
+                              struct lttng_trace_chunk *chunk,
+                              char *closed_trace_chunk_path);
 int consumer_trace_chunk_exists(struct consumer_socket *socket,
-               uint64_t relayd_id, uint64_t session_id,
-               struct lttng_trace_chunk *chunk,
-               enum consumer_trace_chunk_exists_status *result);
+                               uint64_t relayd_id,
+                               uint64_t session_id,
+                               struct lttng_trace_chunk *chunk,
+                               enum consumer_trace_chunk_exists_status *result);
 int consumer_open_channel_packets(struct consumer_socket *socket, uint64_t key);
 
 char *setup_channel_trace_path(struct consumer_output *consumer,
-               const char *session_path, size_t *consumer_path_offset);
+                              const char *session_path,
+                              size_t *consumer_path_offset);
 
 /* Clear command */
 int consumer_clear_channel(struct consumer_socket *socket, uint64_t key);
index 8dc82fbe82e70b538d41c2df88a1deb377df9412..79c454809cdb3f65f97da0526130c635e16207a2 100644 (file)
@@ -7,20 +7,19 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <urcu/list.h>
+#include "agent.hpp"
+#include "context.hpp"
+#include "kernel.hpp"
+#include "trace-ust.hpp"
+#include "ust-app.hpp"
 
 #include <common/error.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
 
-#include "context.hpp"
-#include "kernel.hpp"
-#include "ust-app.hpp"
-#include "trace-ust.hpp"
-#include "agent.hpp"
+#include <stdio.h>
+#include <unistd.h>
+#include <urcu/list.h>
 
 /*
  * Add kernel context to all channel.
@@ -28,7 +27,7 @@
  * Assumes the ownership of kctx.
  */
 static int add_kctx_all_channels(struct ltt_kernel_session *ksession,
-               struct ltt_kernel_context *kctx)
+                                struct ltt_kernel_context *kctx)
 {
        int ret;
        struct ltt_kernel_channel *kchan;
@@ -39,7 +38,7 @@ static int add_kctx_all_channels(struct ltt_kernel_session *ksession,
        DBG("Adding kernel context to all channels");
 
        /* Go over all channels */
-       cds_list_for_each_entry(kchan, &ksession->channel_list.head, list) {
+       cds_list_for_each_entry (kchan, &ksession->channel_list.head, list) {
                struct ltt_kernel_context *kctx_copy;
 
                kctx_copy = trace_kernel_copy_context(kctx);
@@ -51,7 +50,7 @@ static int add_kctx_all_channels(struct ltt_kernel_session *ksession,
 
                /* Ownership of kctx_copy is transferred to the callee. */
                ret = kernel_add_channel_context(kchan, kctx_copy);
-               kctx_copy = NULL;
+               kctx_copy = nullptr;
                if (ret != 0) {
                        goto error;
                }
@@ -69,8 +68,7 @@ error:
  *
  * Assumes the ownership of kctx.
  */
-static int add_kctx_to_channel(struct ltt_kernel_context *kctx,
-               struct ltt_kernel_channel *kchan)
+static int add_kctx_to_channel(struct ltt_kernel_context *kctx, struct ltt_kernel_channel *kchan)
 {
        int ret;
 
@@ -81,7 +79,7 @@ static int add_kctx_to_channel(struct ltt_kernel_context *kctx,
 
        /* Ownership of kctx is transferred to the callee. */
        ret = kernel_add_channel_context(kchan, kctx);
-       kctx = NULL;
+       kctx = nullptr;
        if (ret != 0) {
                goto error;
        }
@@ -96,25 +94,25 @@ error:
  * Add UST context to channel.
  */
 static int add_uctx_to_channel(struct ltt_ust_session *usess,
-               enum lttng_domain_type domain,
-               struct ltt_ust_channel *uchan,
-               const struct lttng_event_context *ctx)
+                              enum lttng_domain_type domain,
+                              struct ltt_ust_channel *uchan,
+                              const struct lttng_event_context *ctx)
 {
        int ret;
-       struct ltt_ust_context *uctx = NULL;
+       struct ltt_ust_context *uctx = nullptr;
 
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(uchan);
        LTTNG_ASSERT(ctx);
 
        /* Check if context is duplicate */
-       cds_list_for_each_entry(uctx, &uchan->ctx_list, list) {
+       cds_list_for_each_entry (uctx, &uchan->ctx_list, list) {
                if (trace_ust_match_context(uctx, ctx)) {
                        ret = LTTNG_ERR_UST_CONTEXT_EXIST;
                        goto duplicate;
                }
        }
-       uctx = NULL;
+       uctx = nullptr;
 
        switch (domain) {
        case LTTNG_DOMAIN_JUL:
@@ -155,7 +153,7 @@ static int add_uctx_to_channel(struct ltt_ust_session *usess,
 
        /* Create ltt UST context */
        uctx = trace_ust_create_context(ctx);
-       if (uctx == NULL) {
+       if (uctx == nullptr) {
                ret = LTTNG_ERR_UST_CONTEXT_INVAL;
                goto error;
        }
@@ -187,8 +185,8 @@ duplicate:
  * Add kernel context to tracer.
  */
 int context_kernel_add(struct ltt_kernel_session *ksession,
-               const struct lttng_event_context *ctx,
-               const char *channel_name)
+                      const struct lttng_event_context *ctx,
+                      const char *channel_name)
 {
        int ret;
        struct ltt_kernel_channel *kchan;
@@ -198,7 +196,7 @@ int context_kernel_add(struct ltt_kernel_session *ksession,
        LTTNG_ASSERT(ctx);
        LTTNG_ASSERT(channel_name);
 
-       kctx = trace_kernel_create_context(NULL);
+       kctx = trace_kernel_create_context(nullptr);
        if (!kctx) {
                ret = -LTTNG_ERR_NOMEM;
                goto error;
@@ -325,28 +323,27 @@ int context_kernel_add(struct ltt_kernel_session *ksession,
 
        kctx->ctx.u.perf_counter.type = ctx->u.perf_counter.type;
        kctx->ctx.u.perf_counter.config = ctx->u.perf_counter.config;
-       strncpy(kctx->ctx.u.perf_counter.name, ctx->u.perf_counter.name,
-                       LTTNG_SYMBOL_NAME_LEN);
+       strncpy(kctx->ctx.u.perf_counter.name, ctx->u.perf_counter.name, LTTNG_SYMBOL_NAME_LEN);
        kctx->ctx.u.perf_counter.name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
 
        if (*channel_name == '\0') {
                ret = add_kctx_all_channels(ksession, kctx);
                /* Ownership of kctx is transferred to the callee. */
-               kctx = NULL;
+               kctx = nullptr;
                if (ret != LTTNG_OK) {
                        goto error;
                }
        } else {
                /* Get kernel channel */
                kchan = trace_kernel_get_channel_by_name(channel_name, ksession);
-               if (kchan == NULL) {
+               if (kchan == nullptr) {
                        ret = LTTNG_ERR_KERN_CHAN_NOT_FOUND;
                        goto error;
                }
 
                ret = add_kctx_to_channel(kctx, kchan);
                /* Ownership of kctx is transferred to the callee. */
-               kctx = NULL;
+               kctx = nullptr;
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -365,27 +362,27 @@ error:
  * Add UST context to tracer.
  */
 int context_ust_add(struct ltt_ust_session *usess,
-               enum lttng_domain_type domain,
-               const struct lttng_event_context *ctx,
-               const char *channel_name)
+                   enum lttng_domain_type domain,
+                   const struct lttng_event_context *ctx,
+                   const char *channel_name)
 {
        int ret = LTTNG_OK;
        struct lttng_ht_iter iter;
        struct lttng_ht *chan_ht;
-       struct ltt_ust_channel *uchan = NULL;
+       struct ltt_ust_channel *uchan = nullptr;
 
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(ctx);
        LTTNG_ASSERT(channel_name);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        chan_ht = usess->domain_global.channels;
 
        /* Get UST channel if defined */
        if (channel_name[0] != '\0') {
                uchan = trace_ust_find_channel_by_name(chan_ht, channel_name);
-               if (uchan == NULL) {
+               if (uchan == nullptr) {
                        ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                        goto error;
                }
@@ -395,17 +392,14 @@ int context_ust_add(struct ltt_ust_session *usess,
                /* Add ctx to channel */
                ret = add_uctx_to_channel(usess, domain, uchan, ctx);
        } else {
-               rcu_read_lock();
                /* Add ctx all events, all channels */
-               cds_lfht_for_each_entry(chan_ht->ht, &iter.iter, uchan, node.node) {
+               cds_lfht_for_each_entry (chan_ht->ht, &iter.iter, uchan, node.node) {
                        ret = add_uctx_to_channel(usess, domain, uchan, ctx);
                        if (ret) {
-                               ERR("Failed to add context to channel %s",
-                                               uchan->name);
+                               ERR("Failed to add context to channel %s", uchan->name);
                                continue;
                        }
                }
-               rcu_read_unlock();
        }
 
        switch (ret) {
@@ -431,6 +425,5 @@ int context_ust_add(struct ltt_ust_session *usess,
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
index a55f571161d9f14d6aaa26b2d9194ce49e5a0c27..4a9653333d5bc8914b9c91af2cfdf41fda635020 100644 (file)
@@ -8,18 +8,18 @@
 #ifndef _LTT_CONTEXT_H
 #define _LTT_CONTEXT_H
 
-#include <lttng/lttng.h>
-
+#include "lttng-ust-ctl.hpp"
 #include "trace-kernel.hpp"
 #include "trace-ust.hpp"
-#include "lttng-ust-ctl.hpp"
+
+#include <lttng/lttng.h>
 
 int context_kernel_add(struct ltt_kernel_session *ksession,
-               const struct lttng_event_context *ctx,
-               const char *channel_name);
+                      const struct lttng_event_context *ctx,
+                      const char *channel_name);
 int context_ust_add(struct ltt_ust_session *usess,
-               enum lttng_domain_type domain,
-               const struct lttng_event_context *ctx,
-               const char *channel_name);
+                   enum lttng_domain_type domain,
+                   const struct lttng_event_context *ctx,
+                   const char *channel_name);
 
 #endif /* _LTT_CONTEXT_H */
diff --git a/src/bin/lttng-sessiond/ctf2-trace-class-visitor.cpp b/src/bin/lttng-sessiond/ctf2-trace-class-visitor.cpp
new file mode 100644 (file)
index 0000000..71a2e48
--- /dev/null
@@ -0,0 +1,485 @@
+/*
+ * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ * Copyright (C) 2022 Simon Marchi <simon.marchi@efficios.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ *
+ */
+
+#include "clock-class.hpp"
+#include "ctf2-trace-class-visitor.hpp"
+
+#include <common/exception.hpp>
+#include <common/format.hpp>
+
+#include <vendor/nlohmann/json.hpp>
+
+#include <algorithm>
+#include <utility>
+
+namespace lsc = lttng::sessiond::ctf2;
+namespace lst = lttng::sessiond::trace;
+
+namespace json = nlohmann;
+
+namespace {
+const unsigned int spaces_per_indent = 2;
+const std::string record_separator = "\x1e";
+
+json::json make_json_fragment(const char *type)
+{
+       return { { "type", type } };
+}
+
+json::json to_json(const lst::field_location& location)
+{
+       json::json location_array;
+
+       switch (location.root_) {
+       case lst::field_location::root::PACKET_HEADER:
+               location_array.push_back("packet-header");
+               break;
+       case lst::field_location::root::PACKET_CONTEXT:
+               location_array.push_back("packet-context");
+               break;
+       case lst::field_location::root::EVENT_RECORD_HEADER:
+               location_array.push_back("event-record-header");
+               break;
+       case lst::field_location::root::EVENT_RECORD_COMMON_CONTEXT:
+               location_array.push_back("event-record-common-context");
+               break;
+       case lst::field_location::root::EVENT_RECORD_SPECIFIC_CONTEXT:
+               location_array.push_back("event-record-specific-context");
+               break;
+       case lst::field_location::root::EVENT_RECORD_PAYLOAD:
+               location_array.push_back("event-record-payload");
+               break;
+       }
+
+       std::copy(location.elements_.begin(),
+                 location.elements_.end(),
+                 std::back_inserter(location_array));
+       return location_array;
+}
+
+const char *get_role_name(lst::integer_type::role role)
+{
+       switch (role) {
+       case lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP:
+               return "default-clock-timestamp";
+       case lst::integer_type::role::DATA_STREAM_CLASS_ID:
+               return "data-stream-class-id";
+       case lst::integer_type::role::DATA_STREAM_ID:
+               return "data-stream-id";
+       case lst::integer_type::role::PACKET_MAGIC_NUMBER:
+               return "packet-magic-number";
+       case lst::integer_type::role::DISCARDED_EVENT_RECORD_COUNTER_SNAPSHOT:
+               return "discarded-event-record-counter-snapshot";
+       case lst::integer_type::role::PACKET_CONTENT_LENGTH:
+               return "packet-content-length";
+       case lst::integer_type::role::PACKET_END_DEFAULT_CLOCK_TIMESTAMP:
+               return "packet-end-default-clock-timestamp";
+       case lst::integer_type::role::PACKET_SEQUENCE_NUMBER:
+               return "packet-sequence-number";
+       case lst::integer_type::role::PACKET_TOTAL_LENGTH:
+               return "packet-total-length";
+       case lst::integer_type::role::EVENT_RECORD_CLASS_ID:
+               return "event-record-class-id";
+       default:
+               abort();
+       }
+}
+
+const char *get_role_name(lst::static_length_blob_type::role role)
+{
+       switch (role) {
+       case lst::static_length_blob_type::role::METADATA_STREAM_UUID:
+               return "metadata-stream-uuid";
+       default:
+               abort();
+       }
+}
+
+namespace ctf2 {
+class trace_environment_visitor : public lst::trace_class_environment_visitor {
+public:
+       trace_environment_visitor() = default; /* NOLINT clang-tidy 14 identifies this as a move
+                                                 constructor. */
+
+       void visit(const lst::environment_field<int64_t>& field) override
+       {
+               _visit(field);
+       }
+
+       void visit(const lst::environment_field<const char *>& field) override
+       {
+               _visit(field);
+       }
+
+       /* Only call once. */
+       json::json move_fragment()
+       {
+               return std::move(_environment);
+       }
+
+private:
+       template <class FieldType>
+       void _visit(const FieldType& field)
+       {
+               _environment[field.name] = field.value;
+       }
+
+       json::json _environment;
+};
+
+class field_visitor : public lttng::sessiond::trace::field_visitor,
+                     public lttng::sessiond::trace::type_visitor {
+public:
+       field_visitor() = default; /* NOLINT clang-tidy 14 identifies this as a move constructor. */
+
+       /* Only call once. */
+       json::json move_fragment()
+       {
+               return std::move(_fragment);
+       }
+
+private:
+       void visit(const lst::field& field) final
+       {
+               field_visitor field_type_visitor;
+               field.get_type().accept(field_type_visitor);
+
+               _fragment["name"] = field.name;
+               _fragment["field-class"] = field_type_visitor.move_fragment();
+       }
+
+       void visit(const lst::integer_type& type) final
+       {
+               _fragment["type"] = type.signedness_ == lst::integer_type::signedness::SIGNED ?
+                       "fixed-length-signed-integer" :
+                       "fixed-length-unsigned-integer";
+               _fragment["length"] = type.size;
+               _fragment["byte-order"] = type.byte_order == lst::byte_order::BIG_ENDIAN_ ?
+                       "big-endian" :
+                       "little-endian";
+               _fragment["alignment"] = type.alignment;
+               _fragment["preferred-display-base"] = (unsigned int) type.base_;
+
+               if (!type.roles_.empty()) {
+                       json::json role_array = json::json::array();
+
+                       for (const auto role : type.roles_) {
+                               role_array.push_back(get_role_name(role));
+                       }
+
+                       _fragment["roles"] = std::move(role_array);
+               }
+       }
+
+       void visit(const lst::floating_point_type& type) final
+       {
+               _fragment["type"] = "fixed-length-floating-point-number";
+               _fragment["length"] = type.exponent_digits + type.mantissa_digits;
+               _fragment["byte-order"] = type.byte_order == lst::byte_order::BIG_ENDIAN_ ?
+                       "big-endian" :
+                       "little-endian";
+               _fragment["alignment"] = type.alignment;
+       }
+
+       template <class EnumerationType>
+       void visit_enumeration(const EnumerationType& type)
+       {
+               _fragment["type"] =
+                       std::is_signed<
+                               typename EnumerationType::mapping::range_t::range_integer_t>::value ?
+                       "fixed-length-signed-enumeration" :
+                       "fixed-length-unsigned-enumeration";
+               _fragment["length"] = type.size;
+               _fragment["byte-order"] = type.byte_order == lst::byte_order::BIG_ENDIAN_ ?
+                       "big-endian" :
+                       "little-endian";
+               _fragment["alignment"] = type.alignment;
+               _fragment["preferred-display-base"] = (unsigned int) type.base_;
+
+               if (!type.roles_.empty()) {
+                       if (std::is_signed<typename EnumerationType::mapping::range_t::
+                                                  range_integer_t>::value) {
+                               LTTNG_THROW_ERROR(
+                                       lttng::format("Failed to serialize {}: unexpected role",
+                                                     _fragment["type"]));
+                       }
+
+                       auto role_array = json::json::array();
+
+                       for (const auto role : type.roles_) {
+                               role_array.push_back(get_role_name(role));
+                       }
+
+                       _fragment["roles"] = std::move(role_array);
+               }
+
+               if (type.mappings_->size() < 1) {
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Failed to serialize {}: enumeration must have at least one mapping",
+                               _fragment["type"]));
+               }
+
+               json::json mappings_value;
+               for (const auto& mapping : *type.mappings_) {
+                       mappings_value[mapping.name] = { { mapping.range.begin,
+                                                          mapping.range.end } };
+               }
+
+               _fragment["mappings"] = std::move(mappings_value);
+       }
+
+       void visit(const lst::signed_enumeration_type& type) final
+       {
+               visit_enumeration(type);
+       }
+
+       void visit(const lst::unsigned_enumeration_type& type) final
+       {
+               visit_enumeration(type);
+       }
+
+       void visit(const lst::static_length_array_type& type) final
+       {
+               _fragment["type"] = "static-length-array";
+
+               ::ctf2::field_visitor element_visitor;
+               type.element_type->accept(element_visitor);
+               _fragment["element-field-class"] = element_visitor.move_fragment();
+
+               if (type.alignment != 0) {
+                       _fragment["minimum-alignment"] = type.alignment;
+               }
+
+               _fragment["length"] = type.length;
+       }
+
+       void visit(const lst::dynamic_length_array_type& type) final
+       {
+               _fragment["type"] = "dynamic-length-array";
+
+               ::ctf2::field_visitor element_visitor;
+               type.element_type->accept(element_visitor);
+               _fragment["element-field-class"] = element_visitor.move_fragment();
+
+               if (type.alignment != 0) {
+                       _fragment["minimum-alignment"] = type.alignment;
+               }
+
+               _fragment["length-field-location"] = to_json(type.length_field_location);
+       }
+
+       void visit(const lst::static_length_blob_type& type) final
+       {
+               _fragment["type"] = "static-length-blob";
+               _fragment["length"] = type.length_bytes;
+
+               if (!type.roles_.empty()) {
+                       auto role_array = json::json::array();
+
+                       for (const auto role : type.roles_) {
+                               role_array.push_back(get_role_name(role));
+                       }
+
+                       _fragment["roles"] = std::move(role_array);
+               }
+       }
+
+       void visit(const lst::dynamic_length_blob_type& type) final
+       {
+               _fragment["type"] = "dynamic-length-blob";
+               _fragment["length-field-location"] = to_json(type.length_field_location);
+       }
+
+       void visit(const lst::null_terminated_string_type& type __attribute__((unused))) final
+       {
+               _fragment["type"] = "null-terminated-string";
+       }
+
+       void visit(const lst::structure_type& type) final
+       {
+               _fragment["type"] = "structure";
+
+               if (type.alignment != 0) {
+                       _fragment["minimum-alignment"] = type.alignment;
+               }
+
+               auto member_classes_value = json::json::array();
+               for (const auto& field : type.fields_) {
+                       ::ctf2::field_visitor member_visitor;
+                       json::json member_class;
+
+                       field->accept(member_visitor);
+                       member_classes_value.emplace_back(member_visitor.move_fragment());
+               }
+
+               _fragment["member-classes"] = std::move(member_classes_value);
+       }
+
+       template <class MappingIntegerType>
+       void visit_variant(const lst::variant_type<MappingIntegerType>& type)
+       {
+               _fragment["type"] = "variant";
+               _fragment["selector-field-location"] = to_json(type.selector_field_location);
+
+               auto options_value = json::json::array();
+               for (const auto& option : type.choices_) {
+                       ::ctf2::field_visitor option_visitor;
+                       json::json member_class;
+
+                       /* TODO missing selector-field-range. */
+                       member_class["selector-field-ranges"] = { { option.first.range.begin,
+                                                                   option.first.range.end } };
+                       option.second->accept(option_visitor);
+                       member_class["field-class"] = option_visitor.move_fragment();
+                       options_value.emplace_back(std::move(member_class));
+               }
+
+               _fragment["options"] = std::move(options_value);
+       }
+
+       void visit(const lst::variant_type<int64_t>& type) final
+       {
+               visit_variant(type);
+       }
+
+       void visit(const lst::variant_type<uint64_t>& type) final
+       {
+               visit_variant(type);
+       }
+
+       void visit(const lst::static_length_string_type& type) final
+       {
+               _fragment["type"] = "static-length-string";
+               _fragment["length"] = type.length;
+       }
+
+       void visit(const lst::dynamic_length_string_type& type) final
+       {
+               _fragment["type"] = "dynamic-length-string";
+               _fragment["length-field-location"] = to_json(type.length_field_location);
+       }
+
+       json::json _fragment;
+};
+} /* namespace ctf2 */
+
+}; /* namespace */
+
+lsc::trace_class_visitor::trace_class_visitor(
+       lsc::append_metadata_fragment_function append_metadata_fragment) :
+       _append_metadata_fragment(std::move(append_metadata_fragment))
+{
+}
+
+void lsc::trace_class_visitor::visit(const lst::trace_class& trace_class)
+{
+       {
+               auto preamble_fragment = make_json_fragment("preamble");
+
+               preamble_fragment["version"] = 2;
+               preamble_fragment["uuid"] = trace_class.uuid;
+               append_metadata_fragment(preamble_fragment);
+       }
+
+       auto trace_class_fragment = make_json_fragment("trace-class");
+
+       ::ctf2::trace_environment_visitor environment_visitor;
+       trace_class.accept(environment_visitor);
+       trace_class_fragment["environment"] = environment_visitor.move_fragment();
+
+       const auto packet_header = trace_class.packet_header();
+       if (packet_header) {
+               ::ctf2::field_visitor field_visitor;
+
+               packet_header->accept(field_visitor);
+               trace_class_fragment["packet-header-field-class"] = field_visitor.move_fragment();
+       }
+
+       append_metadata_fragment(trace_class_fragment);
+}
+
+void lsc::trace_class_visitor::visit(const lst::clock_class& clock_class)
+{
+       auto clock_class_fragment = make_json_fragment("clock-class");
+
+       json::json offset;
+       offset.update({ { "seconds", clock_class.offset / clock_class.frequency },
+                       { "cycles", clock_class.offset % clock_class.frequency } });
+
+       clock_class_fragment.update({ { "name", clock_class.name },
+                                     { "description", clock_class.description },
+                                     { "frequency", clock_class.frequency },
+                                     { "offset", std::move(offset) } });
+
+       if (clock_class.uuid) {
+               clock_class_fragment["uuid"] = *clock_class.uuid;
+       }
+
+       append_metadata_fragment(clock_class_fragment);
+}
+
+void lsc::trace_class_visitor::visit(const lst::stream_class& stream_class)
+{
+       auto stream_class_fragment = make_json_fragment("data-stream-class");
+
+       stream_class_fragment["id"] = stream_class.id;
+       if (stream_class.default_clock_class_name) {
+               stream_class_fragment["default-clock-class-name"] =
+                       *stream_class.default_clock_class_name;
+       }
+
+       const auto packet_context = stream_class.packet_context();
+       if (packet_context) {
+               ::ctf2::field_visitor visitor;
+
+               packet_context->accept(visitor);
+               stream_class_fragment["packet-context-field-class"] = visitor.move_fragment();
+       }
+
+       const auto event_header = stream_class.event_header();
+       if (event_header) {
+               ::ctf2::field_visitor visitor;
+
+               event_header->accept(visitor);
+               stream_class_fragment["event-record-header-field-class"] = visitor.move_fragment();
+       }
+
+       const auto event_context = stream_class.event_context();
+       if (event_context) {
+               ::ctf2::field_visitor visitor;
+
+               event_context->accept(visitor);
+               stream_class_fragment["event-record-common-context-field-class"] =
+                       visitor.move_fragment();
+       }
+
+       append_metadata_fragment(stream_class_fragment);
+}
+
+void lsc::trace_class_visitor::visit(const lst::event_class& event_class)
+{
+       auto event_class_fragment = make_json_fragment("event-record-class");
+
+       event_class_fragment["id"] = event_class.id;
+       event_class_fragment["data-stream-class-id"] = event_class.stream_class_id;
+       event_class_fragment["name"] = event_class.name;
+
+       if (event_class.payload) {
+               ::ctf2::field_visitor visitor;
+
+               event_class.payload->accept(visitor);
+               event_class_fragment["payload-field-class"] = visitor.move_fragment();
+       }
+
+       append_metadata_fragment(event_class_fragment);
+}
+
+void lsc::trace_class_visitor::append_metadata_fragment(const nlohmann::json& fragment) const
+{
+       _append_metadata_fragment(record_separator + fragment.dump(spaces_per_indent).c_str());
+}
diff --git a/src/bin/lttng-sessiond/ctf2-trace-class-visitor.hpp b/src/bin/lttng-sessiond/ctf2-trace-class-visitor.hpp
new file mode 100644 (file)
index 0000000..d484423
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ *
+ */
+
+#ifndef LTTNG_CTF2_TRACE_CLASS_VISITOR_H
+#define LTTNG_CTF2_TRACE_CLASS_VISITOR_H
+
+#include "event-class.hpp"
+#include "stream-class.hpp"
+#include "trace-class.hpp"
+
+#include <vendor/nlohmann/json.hpp>
+#include <vendor/optional.hpp>
+
+#include <functional>
+
+namespace lttng {
+namespace sessiond {
+namespace ctf2 {
+
+using append_metadata_fragment_function = std::function<void(const std::string& fragment)>;
+
+class trace_class_visitor : public lttng::sessiond::trace::trace_class_visitor {
+public:
+       explicit trace_class_visitor(append_metadata_fragment_function append_metadata);
+
+       void visit(const lttng::sessiond::trace::trace_class& trace_class) final;
+       void visit(const lttng::sessiond::trace::clock_class& clock_class) final;
+       void visit(const lttng::sessiond::trace::stream_class& stream_class) final;
+       void visit(const lttng::sessiond::trace::event_class& event_class) final;
+
+private:
+       void append_metadata_fragment(const nlohmann::json& fragment) const;
+
+       const append_metadata_fragment_function _append_metadata_fragment;
+};
+
+} /* namespace ctf2 */
+} /* namespace sessiond */
+} /* namespace lttng */
+
+#endif /* LTTNG_CTF2_TRACE_CLASS_VISITOR_H */
index 82bf1c2d3128a026a0d8eb62b18eb9a4b2e70353..141d8b4d051c5e11af482e817d8df7faea49d77c 100644 (file)
@@ -7,19 +7,21 @@
  *
  */
 
-#include <stddef.h>
-#include <stdlib.h>
-#include <urcu.h>
-#include <common/futex.hpp>
-#include <common/macros.hpp>
-
 #include "dispatch.hpp"
-#include "ust-app.hpp"
-#include "testpoint.hpp"
 #include "fd-limit.hpp"
 #include "health-sessiond.hpp"
 #include "lttng-sessiond.hpp"
+#include "testpoint.hpp"
 #include "thread.hpp"
+#include "ust-app.hpp"
+
+#include <common/futex.hpp>
+#include <common/macros.hpp>
+#include <common/urcu.hpp>
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <urcu.h>
 
 namespace {
 struct thread_notifiers {
@@ -46,31 +48,29 @@ static void update_ust_app(int app_sock)
                return;
        }
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        LTTNG_ASSERT(app_sock >= 0);
        app = ust_app_find_by_sock(app_sock);
-       if (app == NULL) {
+       if (app == nullptr) {
                /*
                 * Application can be unregistered before so
                 * this is possible hence simply stopping the
                 * update.
                 */
-               DBG3("UST app update failed to find app sock %d",
-                       app_sock);
-               goto unlock_rcu;
+               DBG3("UST app update failed to find app sock %d", app_sock);
+               return;
        }
 
        /* Update all event notifiers for the app. */
        ust_app_global_update_event_notifier_rules(app);
 
        /* For all tracing session(s) */
-       cds_list_for_each_entry_safe(sess, stmp, &session_list->head, list) {
+       cds_list_for_each_entry_safe (sess, stmp, &session_list->head, list) {
                if (!session_get(sess)) {
                        continue;
                }
                session_lock(sess);
-               if (!sess->active || !sess->ust_session ||
-                               !sess->ust_session->active) {
+               if (!sess->active || !sess->ust_session || !sess->ust_session->active) {
                        goto unlock_session;
                }
 
@@ -79,9 +79,6 @@ static void update_ust_app(int app_sock)
                session_unlock(sess);
                session_put(sess);
        }
-
-unlock_rcu:
-       rcu_read_unlock();
 }
 
 /*
@@ -94,7 +91,7 @@ static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
        int ret, nb_fd = 0, i;
        unsigned int fd_added = 0;
        struct lttng_poll_event events;
-       struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
+       struct ust_reg_wait_node *wait_node = nullptr, *tmp_wait_node;
 
        LTTNG_ASSERT(wait_queue);
 
@@ -110,11 +107,9 @@ static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
                goto error_create;
        }
 
-       cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
-                       &wait_queue->head, head) {
+       cds_list_for_each_entry_safe (wait_node, tmp_wait_node, &wait_queue->head, head) {
                LTTNG_ASSERT(wait_node->app);
-               ret = lttng_poll_add(&events, wait_node->app->sock,
-                               LPOLLHUP | LPOLLERR);
+               ret = lttng_poll_add(&events, wait_node->app->sock, LPOLLIN);
                if (ret < 0) {
                        goto error;
                }
@@ -141,20 +136,19 @@ static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
                uint32_t revents = LTTNG_POLL_GETEV(&events, i);
                int pollfd = LTTNG_POLL_GETFD(&events, i);
 
-               cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
-                               &wait_queue->head, head) {
-                       if (pollfd == wait_node->app->sock &&
-                                       (revents & (LPOLLHUP | LPOLLERR))) {
+               cds_list_for_each_entry_safe (wait_node, tmp_wait_node, &wait_queue->head, head) {
+                       if (pollfd == wait_node->app->sock && (revents & (LPOLLHUP | LPOLLERR))) {
                                cds_list_del(&wait_node->head);
                                wait_queue->count--;
-                               ust_app_destroy(wait_node->app);
+                               ust_app_put(wait_node->app);
                                free(wait_node);
+
                                /*
                                 * Silence warning of use-after-free in
                                 * cds_list_for_each_entry_safe which uses
                                 * __typeof__(*wait_node).
                                 */
-                               wait_node = NULL;
+                               wait_node = nullptr;
                                break;
                        } else {
                                ERR("Unexpected poll events %u for sock %d", revents, pollfd);
@@ -229,8 +223,8 @@ static void *thread_dispatch_ust_registration(void *data)
 {
        int ret, err = -1;
        struct cds_wfcq_node *node;
-       struct ust_command *ust_cmd = NULL;
-       struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
+       struct ust_command *ust_cmd = nullptr;
+       struct ust_reg_wait_node *wait_node = nullptr, *tmp_wait_node;
        struct ust_reg_wait_queue wait_queue = {
                .count = 0,
                .head = {},
@@ -239,8 +233,7 @@ static void *thread_dispatch_ust_registration(void *data)
 
        rcu_register_thread();
 
-       health_register(the_health_sessiond,
-                       HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
+       health_register(the_health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
 
        if (testpoint(sessiond_thread_app_reg_dispatch)) {
                goto error_testpoint;
@@ -263,8 +256,8 @@ static void *thread_dispatch_ust_registration(void *data)
                }
 
                do {
-                       struct ust_app *app = NULL;
-                       ust_cmd = NULL;
+                       struct ust_app *app = nullptr;
+                       ust_cmd = nullptr;
 
                        /*
                         * Make sure we don't have node(s) that have hung up before receiving
@@ -275,10 +268,9 @@ static void *thread_dispatch_ust_registration(void *data)
 
                        health_code_update();
                        /* Dequeue command for registration */
-                       node = cds_wfcq_dequeue_blocking(
-                                       &notifiers->ust_cmd_queue->head,
-                                       &notifiers->ust_cmd_queue->tail);
-                       if (node == NULL) {
+                       node = cds_wfcq_dequeue_blocking(&notifiers->ust_cmd_queue->head,
+                                                        &notifiers->ust_cmd_queue->tail);
+                       if (node == nullptr) {
                                DBG("Woken up but nothing in the UST command queue");
                                /* Continue thread execution */
                                break;
@@ -287,11 +279,15 @@ static void *thread_dispatch_ust_registration(void *data)
                        ust_cmd = lttng::utils::container_of(node, &ust_command::node);
 
                        DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
-                                       " gid:%d sock:%d name:%s (version %d.%d)",
-                                       ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
-                                       ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
-                                       ust_cmd->sock, ust_cmd->reg_msg.name,
-                                       ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
+                           " gid:%d sock:%d name:%s (version %d.%d)",
+                           ust_cmd->reg_msg.pid,
+                           ust_cmd->reg_msg.ppid,
+                           ust_cmd->reg_msg.uid,
+                           ust_cmd->reg_msg.gid,
+                           ust_cmd->sock,
+                           ust_cmd->reg_msg.name,
+                           ust_cmd->reg_msg.major,
+                           ust_cmd->reg_msg.minor);
 
                        if (ust_cmd->reg_msg.type == LTTNG_UST_CTL_SOCKET_CMD) {
                                wait_node = zmalloc<ust_reg_wait_node>();
@@ -303,14 +299,13 @@ static void *thread_dispatch_ust_registration(void *data)
                                        }
                                        lttng_fd_put(LTTNG_FD_APPS, 1);
                                        free(ust_cmd);
-                                       ust_cmd = NULL;
+                                       ust_cmd = nullptr;
                                        goto error;
                                }
                                CDS_INIT_LIST_HEAD(&wait_node->head);
 
                                /* Create application object if socket is CMD. */
-                               wait_node->app = ust_app_create(&ust_cmd->reg_msg,
-                                               ust_cmd->sock);
+                               wait_node->app = ust_app_create(&ust_cmd->reg_msg, ust_cmd->sock);
                                if (!wait_node->app) {
                                        ret = close(ust_cmd->sock);
                                        if (ret < 0) {
@@ -318,9 +313,9 @@ static void *thread_dispatch_ust_registration(void *data)
                                        }
                                        lttng_fd_put(LTTNG_FD_APPS, 1);
                                        free(wait_node);
-                                       wait_node = NULL;
+                                       wait_node = nullptr;
                                        free(ust_cmd);
-                                       ust_cmd = NULL;
+                                       ust_cmd = nullptr;
                                        continue;
                                }
                                /*
@@ -331,7 +326,7 @@ static void *thread_dispatch_ust_registration(void *data)
                                wait_queue.count++;
 
                                free(ust_cmd);
-                               ust_cmd = NULL;
+                               ust_cmd = nullptr;
                                /*
                                 * We have to continue here since we don't have the notify
                                 * socket and the application MUST be added to the hash table
@@ -343,8 +338,8 @@ static void *thread_dispatch_ust_registration(void *data)
                                 * Look for the application in the local wait queue and set the
                                 * notify socket if found.
                                 */
-                               cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
-                                               &wait_queue.head, head) {
+                               cds_list_for_each_entry_safe (
+                                       wait_node, tmp_wait_node, &wait_queue.head, head) {
                                        health_code_update();
                                        if (wait_node->app->pid == ust_cmd->reg_msg.pid) {
                                                wait_node->app->notify_sock = ust_cmd->sock;
@@ -352,8 +347,9 @@ static void *thread_dispatch_ust_registration(void *data)
                                                wait_queue.count--;
                                                app = wait_node->app;
                                                free(wait_node);
-                                               wait_node = NULL;
-                                               DBG3("UST app notify socket %d is set", ust_cmd->sock);
+                                               wait_node = nullptr;
+                                               DBG3("UST app notify socket %d is set",
+                                                    ust_cmd->sock);
                                                break;
                                        }
                                }
@@ -371,7 +367,7 @@ static void *thread_dispatch_ust_registration(void *data)
                                        lttng_fd_put(LTTNG_FD_APPS, 1);
                                }
                                free(ust_cmd);
-                               ust_cmd = NULL;
+                               ust_cmd = nullptr;
                        }
 
                        if (app) {
@@ -383,7 +379,7 @@ static void *thread_dispatch_ust_registration(void *data)
                                 * and change its state.
                                 */
                                session_lock_list();
-                               rcu_read_lock();
+                               lttng::urcu::read_lock_guard read_lock;
 
                                /*
                                 * Add application to the global hash table. This needs to be
@@ -399,10 +395,8 @@ static void *thread_dispatch_ust_registration(void *data)
 
                                /* Send notify socket through the notify pipe. */
                                ret = send_socket_to_thread(
-                                               notifiers->apps_cmd_notify_pipe_write_fd,
-                                               app->notify_sock);
+                                       notifiers->apps_cmd_notify_pipe_write_fd, app->notify_sock);
                                if (ret < 0) {
-                                       rcu_read_unlock();
                                        session_unlock_list();
                                        /*
                                         * No notify thread, stop the UST tracing. However, this is
@@ -430,11 +424,9 @@ static void *thread_dispatch_ust_registration(void *data)
                                 * to the thread and unregistration will take place at that
                                 * place.
                                 */
-                               ret = send_socket_to_thread(
-                                               notifiers->apps_cmd_pipe_write_fd,
-                                               app->sock);
+                               ret = send_socket_to_thread(notifiers->apps_cmd_pipe_write_fd,
+                                                           app->sock);
                                if (ret < 0) {
-                                       rcu_read_unlock();
                                        session_unlock_list();
                                        /*
                                         * No apps. thread, stop the UST tracing. However, this is
@@ -445,10 +437,9 @@ static void *thread_dispatch_ust_registration(void *data)
                                        goto error;
                                }
 
-                               rcu_read_unlock();
                                session_unlock_list();
                        }
-               } while (node != NULL);
+               } while (node != nullptr);
 
                health_poll_entry();
                /* Futex wait on queue. Blocking call on futex() */
@@ -460,8 +451,7 @@ static void *thread_dispatch_ust_registration(void *data)
 
 error:
        /* Clean up wait queue. */
-       cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
-                       &wait_queue.head, head) {
+       cds_list_for_each_entry_safe (wait_node, tmp_wait_node, &wait_queue.head, head) {
                cds_list_del(&wait_node->head);
                wait_queue.count--;
                free(wait_node);
@@ -470,10 +460,9 @@ error:
        /* Empty command queue. */
        for (;;) {
                /* Dequeue command for registration */
-               node = cds_wfcq_dequeue_blocking(
-                               &notifiers->ust_cmd_queue->head,
-                               &notifiers->ust_cmd_queue->tail);
-               if (node == NULL) {
+               node = cds_wfcq_dequeue_blocking(&notifiers->ust_cmd_queue->head,
+                                                &notifiers->ust_cmd_queue->tail);
+               if (node == nullptr) {
                        break;
                }
                ust_cmd = lttng::utils::container_of(node, &ust_command::node);
@@ -493,7 +482,7 @@ error_testpoint:
        }
        health_unregister(the_health_sessiond);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_ust_dispatch_thread(void *data)
@@ -506,8 +495,8 @@ static bool shutdown_ust_dispatch_thread(void *data)
 }
 
 bool launch_ust_dispatch_thread(struct ust_cmd_queue *cmd_queue,
-               int apps_cmd_pipe_write_fd,
-               int apps_cmd_notify_pipe_write_fd)
+                               int apps_cmd_pipe_write_fd,
+                               int apps_cmd_notify_pipe_write_fd)
 {
        struct lttng_thread *thread;
        struct thread_notifiers *notifiers;
@@ -521,10 +510,10 @@ bool launch_ust_dispatch_thread(struct ust_cmd_queue *cmd_queue,
        notifiers->apps_cmd_notify_pipe_write_fd = apps_cmd_notify_pipe_write_fd;
 
        thread = lttng_thread_create("UST registration dispatch",
-                       thread_dispatch_ust_registration,
-                       shutdown_ust_dispatch_thread,
-                       cleanup_ust_dispatch_thread,
-                       notifiers);
+                                    thread_dispatch_ust_registration,
+                                    shutdown_ust_dispatch_thread,
+                                    cleanup_ust_dispatch_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index d5ec8c9c32ca27702fe92a8442edeb33afff4c00..d3e57368a092095429a30a3dba3ed1165f48ce95 100644 (file)
 #ifndef SESSIOND_UST_DISPATCH_THREAD_H
 #define SESSIOND_UST_DISPATCH_THREAD_H
 
-#include <stdbool.h>
 #include "lttng-sessiond.hpp"
 
+#include <stdbool.h>
+
 bool launch_ust_dispatch_thread(struct ust_cmd_queue *cmd_queue,
-               int apps_cmd_pipe_write_fd,
-               int apps_cmd_notify_write_fd);
+                               int apps_cmd_pipe_write_fd,
+                               int apps_cmd_notify_write_fd);
 
 #endif /* SESSIOND_UST_DISPATCH_THREAD_H */
index 9d36703a014a45c15424ed7b290ab245d0e4b337..19dceb4ad9d4806827ca8874dbe3c8dffab38862 100644 (file)
@@ -6,21 +6,22 @@
  */
 
 #include "event-class.hpp"
+#include "trace-class.hpp"
 
 namespace lst = lttng::sessiond::trace;
 
 lst::event_class::event_class(unsigned int in_id,
-               unsigned int in_stream_class_id,
-               int in_log_level,
-               std::string in_name,
-               nonstd::optional<std::string> in_model_emf_uri,
-               lttng::sessiond::trace::type::cuptr in_payload) :
-       id{in_id},
-       stream_class_id{in_stream_class_id},
-       log_level{in_log_level},
-       name{std::move(in_name)},
-       model_emf_uri{std::move(in_model_emf_uri)},
-       payload{std::move(in_payload)}
+                             unsigned int in_stream_class_id,
+                             int in_log_level,
+                             std::string in_name,
+                             nonstd::optional<std::string> in_model_emf_uri,
+                             lttng::sessiond::trace::type::cuptr in_payload) :
+       id{ in_id },
+       stream_class_id{ in_stream_class_id },
+       log_level{ in_log_level },
+       name{ std::move(in_name) },
+       model_emf_uri{ std::move(in_model_emf_uri) },
+       payload{ std::move(in_payload) }
 {
 }
 
index d42d764aaa4a6b8346686bee12bc945a52d98efc..81b27f8d0447145b944eafa563cee776b5f4de14 100644 (file)
@@ -11,6 +11,7 @@
 #include "field.hpp"
 
 #include <common/uuid.hpp>
+
 #include <vendor/optional.hpp>
 
 #include <string>
@@ -23,9 +24,14 @@ class trace_class_visitor;
 
 class event_class {
 public:
-       virtual void accept(trace_class_visitor& visitor) const;
+       event_class(const event_class&) = delete;
+       event_class(event_class&&) = delete;
+       event_class& operator=(event_class&&) = delete;
+       event_class& operator=(const event_class&) = delete;
        virtual ~event_class() = default;
 
+       virtual void accept(trace_class_visitor& visitor) const;
+
        const unsigned int id;
        const unsigned int stream_class_id;
        const int log_level;
@@ -35,11 +41,11 @@ public:
 
 protected:
        event_class(unsigned int id,
-                       unsigned int stream_class_id,
-                       int log_level,
-                       std::string name,
-                       nonstd::optional<std::string> model_emf_uri,
-                       lttng::sessiond::trace::type::cuptr payload);
+                   unsigned int stream_class_id,
+                   int log_level,
+                   std::string name,
+                   nonstd::optional<std::string> model_emf_uri,
+                   lttng::sessiond::trace::type::cuptr payload);
 };
 
 } /* namespace trace */
index 70ffb86ef01bf74a8423d54c9202774102b763e9..7fa54bc93080b54c361306ca3405b580f8b58f07 100644 (file)
@@ -5,23 +5,25 @@
  *
  */
 
-#include <fcntl.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <urcu/compiler.h>
-#include <pthread.h>
+#include "event-notifier-error-accounting.hpp"
+#include "lttng-ust-error.hpp"
+#include "ust-app.hpp"
 
 #include <common/error.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/index-allocator.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
 #include <common/shm.hpp>
+#include <common/urcu.hpp>
+
 #include <lttng/trigger/trigger-internal.hpp>
 
-#include "event-notifier-error-accounting.hpp"
-#include "lttng-ust-error.hpp"
-#include "ust-app.hpp"
+#include <fcntl.h>
+#include <pthread.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <urcu/compiler.h>
 
 #define ERROR_COUNTER_INDEX_HT_INITIAL_SIZE 16
 
@@ -71,8 +73,8 @@ struct error_accounting_state kernel_state;
 } /* namespace */
 
 static inline void get_trigger_info_for_log(const struct lttng_trigger *trigger,
-               const char **trigger_name,
-               uid_t *trigger_owner_uid)
+                                           const char **trigger_name,
+                                           uid_t *trigger_owner_uid)
 {
        enum lttng_trigger_status trigger_status;
 
@@ -87,14 +89,12 @@ static inline void get_trigger_info_for_log(const struct lttng_trigger *trigger,
                abort();
        }
 
-       trigger_status = lttng_trigger_get_owner_uid(trigger,
-                       trigger_owner_uid);
+       trigger_status = lttng_trigger_get_owner_uid(trigger, trigger_owner_uid);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 }
 
-static inline
-const char *error_accounting_status_str(
-               enum event_notifier_error_accounting_status status)
+static inline const char *
+error_accounting_status_str(enum event_notifier_error_accounting_status status)
 {
        switch (status) {
        case EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK:
@@ -128,7 +128,7 @@ static void free_ust_error_accounting_entry(struct rcu_head *head)
 {
        int i;
        struct ust_error_accounting_entry *entry =
-                       lttng::utils::container_of(head, &ust_error_accounting_entry::rcu_head);
+               lttng::utils::container_of(head, &ust_error_accounting_entry::rcu_head);
 
        for (i = 0; i < entry->nr_counter_cpu_fds; i++) {
                lttng_ust_ctl_release_object(-1, entry->cpu_counters[i]);
@@ -145,27 +145,22 @@ static void free_ust_error_accounting_entry(struct rcu_head *head)
        free(entry);
 }
 
-static
-bool ust_error_accounting_entry_get(struct ust_error_accounting_entry *entry)
+static bool ust_error_accounting_entry_get(struct ust_error_accounting_entry *entry)
 {
        return urcu_ref_get_unless_zero(&entry->ref);
 }
 
-static
-void ust_error_accounting_entry_release(struct urcu_ref *entry_ref)
+static void ust_error_accounting_entry_release(struct urcu_ref *entry_ref)
 {
        struct ust_error_accounting_entry *entry =
-                       lttng::utils::container_of(entry_ref, &ust_error_accounting_entry::ref);
+               lttng::utils::container_of(entry_ref, &ust_error_accounting_entry::ref);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_del(error_counter_uid_ht->ht, &entry->node.node);
        call_rcu(&entry->rcu_head, free_ust_error_accounting_entry);
-       rcu_read_unlock();
 }
 
-
-static
-void ust_error_accounting_entry_put(struct ust_error_accounting_entry *entry)
+static void ust_error_accounting_entry_put(struct ust_error_accounting_entry *entry)
 {
        if (!entry) {
                return;
@@ -177,49 +172,47 @@ void ust_error_accounting_entry_put(struct ust_error_accounting_entry *entry)
 /*
  * Put one reference to every UID entries.
  */
-static
-void put_ref_all_ust_error_accounting_entry(void)
+static void put_ref_all_ust_error_accounting_entry()
 {
        struct lttng_ht_iter iter;
        struct ust_error_accounting_entry *uid_entry;
 
        ASSERT_LOCKED(the_event_notifier_counter.lock);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(error_counter_uid_ht->ht, &iter.iter,
-                       uid_entry, node.node) {
-               ust_error_accounting_entry_put(uid_entry);
-       }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       rcu_read_unlock();
+               cds_lfht_for_each_entry (
+                       error_counter_uid_ht->ht, &iter.iter, uid_entry, node.node) {
+                       ust_error_accounting_entry_put(uid_entry);
+               }
+       }
 }
 
 /*
  * Get one reference to every UID entries.
  */
-static
-void get_ref_all_ust_error_accounting_entry(void)
+static void get_ref_all_ust_error_accounting_entry()
 {
        struct lttng_ht_iter iter;
        struct ust_error_accounting_entry *uid_entry;
 
        ASSERT_LOCKED(the_event_notifier_counter.lock);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(error_counter_uid_ht->ht, &iter.iter,
-                       uid_entry, node.node) {
-               ust_error_accounting_entry_get(uid_entry);
-       }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       rcu_read_unlock();
+               cds_lfht_for_each_entry (
+                       error_counter_uid_ht->ht, &iter.iter, uid_entry, node.node) {
+                       ust_error_accounting_entry_get(uid_entry);
+               }
+       }
 }
 
 #endif /* HAVE_LIBLTTNG_UST_CTL */
 
-static
-enum event_notifier_error_accounting_status
-init_error_accounting_state(struct error_accounting_state *state,
-               uint64_t index_count)
+static enum event_notifier_error_accounting_status
+init_error_accounting_state(struct error_accounting_state *state, uint64_t index_count)
 {
        enum event_notifier_error_accounting_status status;
 
@@ -234,8 +227,7 @@ init_error_accounting_state(struct error_accounting_state *state,
                goto end;
        }
 
-       state->indices_ht = lttng_ht_new(ERROR_COUNTER_INDEX_HT_INITIAL_SIZE,
-                       LTTNG_HT_TYPE_U64);
+       state->indices_ht = lttng_ht_new(ERROR_COUNTER_INDEX_HT_INITIAL_SIZE, LTTNG_HT_TYPE_U64);
        if (!state->indices_ht) {
                ERR("Failed to allocate error counter indices hash table");
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOMEM;
@@ -247,13 +239,12 @@ init_error_accounting_state(struct error_accounting_state *state,
 
 error_indices_ht:
        lttng_index_allocator_destroy(state->index_allocator);
-       state->index_allocator = NULL;
+       state->index_allocator = nullptr;
 end:
        return status;
 }
 
-static
-void fini_error_accounting_state(struct error_accounting_state *state)
+static void fini_error_accounting_state(struct error_accounting_state *state)
 {
        LTTNG_ASSERT(state);
 
@@ -266,27 +257,25 @@ void fini_error_accounting_state(struct error_accounting_state *state)
 }
 
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_init(uint64_t buffer_size_kernel,
-               uint64_t buffer_size_ust)
+event_notifier_error_accounting_init(uint64_t buffer_size_kernel, uint64_t buffer_size_ust)
 {
        enum event_notifier_error_accounting_status status;
 
        status = init_error_accounting_state(&kernel_state, buffer_size_kernel);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                ERR("Failed to initialize kernel event notifier accounting state: status = %s",
-                               error_accounting_status_str(status));
+                   error_accounting_status_str(status));
                goto end;
        }
 
        status = init_error_accounting_state(&ust_state, buffer_size_ust);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                ERR("Failed to initialize UST event notifier accounting state: status = %s",
-                               error_accounting_status_str(status));
+                   error_accounting_status_str(status));
                goto error_ust_state;
        }
 
-       error_counter_uid_ht = lttng_ht_new(
-                       ERROR_COUNTER_INDEX_HT_INITIAL_SIZE, LTTNG_HT_TYPE_U64);
+       error_counter_uid_ht = lttng_ht_new(ERROR_COUNTER_INDEX_HT_INITIAL_SIZE, LTTNG_HT_TYPE_U64);
        if (!error_counter_uid_ht) {
                ERR("Failed to allocate UID to error counter accountant hash table");
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOMEM;
@@ -308,17 +297,15 @@ end:
  * Return the error counteur index associated to this event notifier tracer
  * token. Returns _STATUS_OK if found and _STATUS_NOT_FOUND otherwise.
  */
-static
-enum event_notifier_error_accounting_status get_error_counter_index_for_token(
-               struct error_accounting_state *state, uint64_t tracer_token,
-               uint64_t *error_counter_index)
+static enum event_notifier_error_accounting_status get_error_counter_index_for_token(
+       struct error_accounting_state *state, uint64_t tracer_token, uint64_t *error_counter_index)
 {
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
        const struct index_ht_entry *index_entry;
        enum event_notifier_error_accounting_status status;
+       lttng::urcu::read_lock_guard read_guard;
 
-       rcu_read_lock();
        lttng_ht_lookup(state->indices_ht, &tracer_token, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (node) {
@@ -329,7 +316,6 @@ enum event_notifier_error_accounting_status get_error_counter_index_for_token(
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOT_FOUND;
        }
 
-       rcu_read_unlock();
        return status;
 }
 
@@ -338,9 +324,8 @@ enum event_notifier_error_accounting_status get_error_counter_index_for_token(
  * Find the entry for this app's UID, the caller acquires a reference if the
  * entry is found.
  */
-static
-struct ust_error_accounting_entry *ust_error_accounting_entry_find(
-               struct lttng_ht *uid_ht, const struct ust_app *app)
+static struct ust_error_accounting_entry *ust_error_accounting_entry_find(struct lttng_ht *uid_ht,
+                                                                         const struct ust_app *app)
 {
        struct ust_error_accounting_entry *entry;
        struct lttng_ht_node_u64 *node;
@@ -349,17 +334,16 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_find(
 
        lttng_ht_lookup(uid_ht, &key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if(node == NULL) {
-               entry = NULL;
+       if (node == nullptr) {
+               entry = nullptr;
        } else {
                bool got_ref;
 
-               entry = caa_container_of(node,
-                               struct ust_error_accounting_entry, node);
+               entry = caa_container_of(node, struct ust_error_accounting_entry, node);
 
                got_ref = ust_error_accounting_entry_get(entry);
                if (!got_ref) {
-                       entry = NULL;
+                       entry = nullptr;
                }
        }
 
@@ -370,15 +354,14 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_find(
  * Create the entry for this app's UID, the caller acquires a reference to the
  * entry,
  */
-static
-struct ust_error_accounting_entry *ust_error_accounting_entry_create(
-               const struct ust_app *app)
+static struct ust_error_accounting_entry *
+ust_error_accounting_entry_create(const struct ust_app *app)
 {
-       int i, ret, *cpu_counter_fds = NULL;
+       int i, ret, *cpu_counter_fds = nullptr;
        struct lttng_ust_ctl_daemon_counter *daemon_counter;
        struct lttng_ust_abi_object_data *counter, **cpu_counters;
-       struct ust_error_accounting_entry *entry = NULL;
-       lttng_ust_ctl_counter_dimension dimension;
+       struct ust_error_accounting_entry *entry = nullptr;
+       lttng_ust_ctl_counter_dimension dimension = {};
 
        dimension.size = ust_state.number_indices;
        dimension.has_underflow = false;
@@ -386,7 +369,8 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
 
        if (!ust_app_supports_counters(app)) {
                DBG("Refusing to create accounting entry for application (unsupported feature): app name = '%s', app ppid = %d",
-                               app->name, (int) app->ppid);
+                   app->name,
+                   (int) app->ppid);
                goto error;
        }
 
@@ -403,8 +387,10 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
        cpu_counter_fds = calloc<int>(entry->nr_counter_cpu_fds);
        if (!cpu_counter_fds) {
                PERROR("Failed to allocate event notifier error counter file descriptors array: application uid = %d, application name = '%s', pid = %d, allocation size = %zu",
-                               (int) app->uid, app->name, (int) app->pid,
-                               entry->nr_counter_cpu_fds * sizeof(*cpu_counter_fds));
+                      (int) app->uid,
+                      app->name,
+                      (int) app->pid,
+                      entry->nr_counter_cpu_fds * sizeof(*cpu_counter_fds));
                goto error_counter_cpu_fds_alloc;
        }
 
@@ -416,8 +402,10 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
        cpu_counters = calloc<lttng_ust_abi_object_data *>(entry->nr_counter_cpu_fds);
        if (!cpu_counters) {
                PERROR("Failed to allocate event notifier error counter lttng_ust_abi_object_data array: application uid = %d, application name = '%s', pid = %d, allocation size = %zu",
-                               (int) app->uid, app->name, (int) app->pid,
-                               entry->nr_counter_cpu_fds * sizeof(struct lttng_ust_abi_object_data *));
+                      (int) app->uid,
+                      app->name,
+                      (int) app->pid,
+                      entry->nr_counter_cpu_fds * sizeof(struct lttng_ust_abi_object_data *));
                goto error_counter_cpus_alloc;
        }
 
@@ -425,7 +413,9 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
                cpu_counter_fds[i] = shm_create_anonymous("event-notifier-error-accounting");
                if (cpu_counter_fds[i] == -1) {
                        ERR("Failed to create event notifier error accounting shared memory for application user: application uid = %d, pid = %d, application name = '%s'",
-                                       (int) app->uid, (int) app->pid, app->name);
+                           (int) app->uid,
+                           (int) app->pid,
+                           app->name);
                        goto error_shm_alloc;
                }
        }
@@ -433,12 +423,16 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
        /*
         * Ownership of the file descriptors transferred to the ustctl object.
         */
-       daemon_counter = lttng_ust_ctl_create_counter(1, &dimension, 0, -1,
-                       entry->nr_counter_cpu_fds, cpu_counter_fds,
-                       LTTNG_UST_CTL_COUNTER_BITNESS_32,
-                       LTTNG_UST_CTL_COUNTER_ARITHMETIC_MODULAR,
-                       LTTNG_UST_CTL_COUNTER_ALLOC_PER_CPU,
-                       false);
+       daemon_counter = lttng_ust_ctl_create_counter(1,
+                                                     &dimension,
+                                                     0,
+                                                     -1,
+                                                     entry->nr_counter_cpu_fds,
+                                                     cpu_counter_fds,
+                                                     LTTNG_UST_CTL_COUNTER_BITNESS_32,
+                                                     LTTNG_UST_CTL_COUNTER_ARITHMETIC_MODULAR,
+                                                     LTTNG_UST_CTL_COUNTER_ALLOC_PER_CPU,
+                                                     false);
        if (!daemon_counter) {
                goto error_create_daemon_counter;
        }
@@ -446,17 +440,19 @@ struct ust_error_accounting_entry *ust_error_accounting_entry_create(
        ret = lttng_ust_ctl_create_counter_data(daemon_counter, &counter);
        if (ret) {
                ERR("Failed to create userspace tracer counter data for application user: uid = %d, pid = %d, application name = '%s'",
-                               (int) app->uid, (int) app->pid, app->name);
+                   (int) app->uid,
+                   (int) app->pid,
+                   app->name);
                goto error_create_counter_data;
        }
 
        for (i = 0; i < entry->nr_counter_cpu_fds; i++) {
-               ret = lttng_ust_ctl_create_counter_cpu_data(daemon_counter, i,
-                               &cpu_counters[i]);
+               ret = lttng_ust_ctl_create_counter_cpu_data(daemon_counter, i, &cpu_counters[i]);
                if (ret) {
                        ERR("Failed to create userspace tracer counter cpu data for application user: uid = %d, pid = %d, application name = '%s'",
-                                       (int) app->uid, (int) app->pid,
-                                       app->name);
+                           (int) app->uid,
+                           (int) app->pid,
+                           app->name);
                        goto error_create_counter_cpu_data;
                }
        }
@@ -505,7 +501,7 @@ error_shm_alloc:
                        ret = close(cpu_counter_fds[i]);
                        if (ret) {
                                PERROR("Failed to close error counter per-CPU shm file descriptor: fd = %d",
-                                               cpu_counter_fds[i]);
+                                      cpu_counter_fds[i]);
                        }
                }
        }
@@ -515,33 +511,35 @@ error_counter_cpus_alloc:
 error_counter_cpu_fds_alloc:
        free(entry);
 error:
-       entry = NULL;
+       entry = nullptr;
 end:
        free(cpu_counter_fds);
        return entry;
 }
 
-static
-enum event_notifier_error_accounting_status send_counter_data_to_ust(
-               struct ust_app *app,
-               struct lttng_ust_abi_object_data *new_counter)
+static enum event_notifier_error_accounting_status
+send_counter_data_to_ust(struct ust_app *app, struct lttng_ust_abi_object_data *new_counter)
 {
        int ret;
        enum event_notifier_error_accounting_status status;
 
        /* Attach counter to trigger group. */
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_send_counter_data_to_ust(app->sock,
-                       app->event_notifier_group.object->handle, new_counter);
+       ret = lttng_ust_ctl_send_counter_data_to_ust(
+               app->sock, app->event_notifier_group.object->handle, new_counter);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret != -EPIPE && ret != -LTTNG_UST_ERR_EXITING) {
                        ERR("Failed to send counter data to application: application name = '%s', pid = %d, ret = %d",
-                                       app->name, app->pid, ret);
+                           app->name,
+                           app->pid,
+                           ret);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                } else {
                        DBG3("Failed to send counter data to application (application is dead): application name = '%s', pid = %d, ret = %d",
-                                       app->name, app->pid, ret);
+                            app->name,
+                            app->pid,
+                            ret);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_APP_DEAD;
                }
 
@@ -553,27 +551,29 @@ end:
        return status;
 }
 
-static
-enum event_notifier_error_accounting_status send_counter_cpu_data_to_ust(
-               struct ust_app *app,
-               struct lttng_ust_abi_object_data *counter,
-               struct lttng_ust_abi_object_data *counter_cpu)
+static enum event_notifier_error_accounting_status
+send_counter_cpu_data_to_ust(struct ust_app *app,
+                            struct lttng_ust_abi_object_data *counter,
+                            struct lttng_ust_abi_object_data *counter_cpu)
 {
        int ret;
        enum event_notifier_error_accounting_status status;
 
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_send_counter_cpu_data_to_ust(app->sock,
-                       counter, counter_cpu);
+       ret = lttng_ust_ctl_send_counter_cpu_data_to_ust(app->sock, counter, counter_cpu);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret != -EPIPE && ret != -LTTNG_UST_ERR_EXITING) {
                        ERR("Failed to send counter CPU data to application: application name = '%s', pid = %d, ret = %d",
-                                       app->name, app->pid, ret);
+                           app->name,
+                           app->pid,
+                           ret);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                } else {
                        DBG3("Failed to send counter CPU data to application: application name = '%s', pid = %d, ret = %d",
-                                       app->name, app->pid, ret);
+                            app->name,
+                            app->pid,
+                            ret);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_APP_DEAD;
                }
 
@@ -594,6 +594,7 @@ event_notifier_error_accounting_register_app(struct ust_app *app)
        struct ust_error_accounting_entry *entry;
        enum event_notifier_error_accounting_status status;
        struct lttng_ust_abi_object_data **cpu_counters;
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!ust_app_supports_counters(app)) {
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_UNSUPPORTED;
@@ -604,9 +605,8 @@ event_notifier_error_accounting_register_app(struct ust_app *app)
         * Check if we already have a error counter for the user id of this
         * app. If not, create one.
         */
-       rcu_read_lock();
        entry = ust_error_accounting_entry_find(error_counter_uid_ht, app);
-       if (entry == NULL) {
+       if (entry == nullptr) {
                /*
                 * Take the event notifier counter lock before creating the new
                 * entry to ensure that no event notifier is registered between
@@ -634,11 +634,12 @@ event_notifier_error_accounting_register_app(struct ust_app *app)
        }
 
        /* Duplicate counter object data. */
-       ret = lttng_ust_ctl_duplicate_ust_object_data(&new_counter,
-                       entry->counter);
+       ret = lttng_ust_ctl_duplicate_ust_object_data(&new_counter, entry->counter);
        if (ret) {
                ERR("Failed to duplicate event notifier error accounting counter for application user: application uid = %d, pid = %d, application name = '%s'",
-                               (int) app->uid, (int) app->pid, app->name);
+                   (int) app->uid,
+                   (int) app->pid,
+                   app->name);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto error_duplicate_counter;
        }
@@ -650,8 +651,10 @@ event_notifier_error_accounting_register_app(struct ust_app *app)
                }
 
                ERR("Failed to send counter data to application tracer: status = %s, application uid = %d, pid = %d, application name = '%s'",
-                               error_accounting_status_str(status),
-                               (int) app->uid, (int) app->pid, app->name);
+                   error_accounting_status_str(status),
+                   (int) app->uid,
+                   (int) app->pid,
+                   app->name);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto error_send_counter_data;
        }
@@ -659,49 +662,52 @@ event_notifier_error_accounting_register_app(struct ust_app *app)
        cpu_counters = calloc<lttng_ust_abi_object_data *>(entry->nr_counter_cpu_fds);
        if (!cpu_counters) {
                PERROR("Failed to allocate event notifier error counter lttng_ust_abi_object_data array: application uid = %d, application name = '%s', pid = %d, allocation size = %zu",
-                               (int) app->uid, app->name, (int) app->pid,
-                               entry->nr_counter_cpu_fds * sizeof(**cpu_counters));
+                      (int) app->uid,
+                      app->name,
+                      (int) app->pid,
+                      entry->nr_counter_cpu_fds * sizeof(**cpu_counters));
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOMEM;
                goto error_allocate_cpu_counters;
        }
 
        for (i = 0; i < entry->nr_counter_cpu_fds; i++) {
-               struct lttng_ust_abi_object_data *new_counter_cpu = NULL;
+               struct lttng_ust_abi_object_data *new_counter_cpu = nullptr;
 
                ret = lttng_ust_ctl_duplicate_ust_object_data(&new_counter_cpu,
-                               entry->cpu_counters[i]);
+                                                             entry->cpu_counters[i]);
                if (ret) {
                        ERR("Failed to duplicate userspace tracer counter cpu data for application user: uid = %d, pid = %d, application name = '%s'",
-                                       (int) app->uid, (int) app->pid,
-                                       app->name);
+                           (int) app->uid,
+                           (int) app->pid,
+                           app->name);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOMEM;
                        goto error_duplicate_cpu_counter;
                }
 
                cpu_counters[i] = new_counter_cpu;
 
-               status = send_counter_cpu_data_to_ust(app, new_counter,
-                               new_counter_cpu);
+               status = send_counter_cpu_data_to_ust(app, new_counter, new_counter_cpu);
                if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                        if (status == EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_APP_DEAD) {
                                goto error_send_cpu_counter_data;
                        }
 
                        ERR("Failed to send counter cpu data to application tracer: status = %s, application uid = %d, pid = %d, application name = '%s'",
-                                       error_accounting_status_str(status),
-                                       (int) app->uid, (int) app->pid,
-                                       app->name);
+                           error_accounting_status_str(status),
+                           (int) app->uid,
+                           (int) app->pid,
+                           app->name);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                        goto error_send_cpu_counter_data;
                }
        }
 
        app->event_notifier_group.counter = new_counter;
-       new_counter = NULL;
+       new_counter = nullptr;
        app->event_notifier_group.nr_counter_cpu = entry->nr_counter_cpu_fds;
        app->event_notifier_group.counter_cpu = cpu_counters;
-       cpu_counters = NULL;
-       goto end_unlock;
+       cpu_counters = nullptr;
+       goto end;
 
 error_send_cpu_counter_data:
 error_duplicate_cpu_counter:
@@ -728,9 +734,7 @@ error_send_counter_data:
 error_duplicate_counter:
        ust_error_accounting_entry_put(entry);
 error_creating_entry:
-       app->event_notifier_group.counter = NULL;
-end_unlock:
-       rcu_read_unlock();
+       app->event_notifier_group.counter = nullptr;
 end:
        return status;
 }
@@ -742,7 +746,7 @@ event_notifier_error_accounting_unregister_app(struct ust_app *app)
        struct ust_error_accounting_entry *entry;
        int i;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* If an error occurred during app registration no entry was created. */
        if (!app->event_notifier_group.counter) {
@@ -751,9 +755,10 @@ event_notifier_error_accounting_unregister_app(struct ust_app *app)
        }
 
        entry = ust_error_accounting_entry_find(error_counter_uid_ht, app);
-       if (entry == NULL) {
+       if (entry == nullptr) {
                ERR("Failed to find event notitifier error accounting entry on application teardown: pid = %d, application name = '%s'",
-                               app->pid, app->name);
+                   app->pid,
+                   app->name);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto end;
        } else {
@@ -766,8 +771,7 @@ event_notifier_error_accounting_unregister_app(struct ust_app *app)
        }
 
        for (i = 0; i < app->event_notifier_group.nr_counter_cpu; i++) {
-               lttng_ust_ctl_release_object(app->sock,
-                               app->event_notifier_group.counter_cpu[i]);
+               lttng_ust_ctl_release_object(app->sock, app->event_notifier_group.counter_cpu[i]);
                free(app->event_notifier_group.counter_cpu[i]);
        }
 
@@ -778,14 +782,11 @@ event_notifier_error_accounting_unregister_app(struct ust_app *app)
 
        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 end:
-       rcu_read_unlock();
        return status;
 }
 
-static
-enum event_notifier_error_accounting_status
-event_notifier_error_accounting_ust_get_count(
-               const struct lttng_trigger *trigger, uint64_t *count)
+static enum event_notifier_error_accounting_status
+event_notifier_error_accounting_ust_get_count(const struct lttng_trigger *trigger, uint64_t *count)
 {
        struct lttng_ht_iter iter;
        struct ust_error_accounting_entry *uid_entry;
@@ -796,19 +797,18 @@ event_notifier_error_accounting_ust_get_count(
        uid_t trigger_owner_uid;
        const char *trigger_name;
 
-
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
-       status = get_error_counter_index_for_token(&ust_state, tracer_token,
-                       &error_counter_index);
+       status = get_error_counter_index_for_token(&ust_state, tracer_token, &error_counter_index);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
-
-               ERR("Failed to retrieve index for tracer token: token = %" PRIu64 ", trigger name = '%s', trigger owner uid = %d, status = %s",
-                               tracer_token, trigger_name,
-                               (int) trigger_owner_uid,
-                               error_accounting_status_str(status));
+               ERR("Failed to retrieve index for tracer token: token = %" PRIu64
+                   ", trigger name = '%s', trigger owner uid = %d, status = %s",
+                   tracer_token,
+                   trigger_name,
+                   (int) trigger_owner_uid,
+                   error_accounting_status_str(status));
                goto end;
        }
 
@@ -821,25 +821,26 @@ event_notifier_error_accounting_ust_get_count(
         * a trigger to a given sessiond is also allowed to create an event
         * notifier on all apps that this sessiond is aware of.
         */
-       cds_lfht_for_each_entry(error_counter_uid_ht->ht, &iter.iter,
-                       uid_entry, node.node) {
+       cds_lfht_for_each_entry (error_counter_uid_ht->ht, &iter.iter, uid_entry, node.node) {
                int ret;
                int64_t local_value = 0;
                bool overflow = false, underflow = false;
 
                ret = lttng_ust_ctl_counter_aggregate(uid_entry->daemon_counter,
-                               dimension_indexes, &local_value, &overflow,
-                               &underflow);
+                                                     dimension_indexes,
+                                                     &local_value,
+                                                     &overflow,
+                                                     &underflow);
                if (ret || local_value < 0) {
                        if (ret) {
                                ERR("Failed to aggregate event notifier error counter values of trigger: trigger name = '%s', trigger owner uid = %d",
-                                               trigger_name,
-                                               (int) trigger_owner_uid);
+                                   trigger_name,
+                                   (int) trigger_owner_uid);
                        } else if (local_value < 0) {
                                ERR("Negative event notifier error counter value encountered during aggregation: trigger name = '%s', trigger owner uid = %d, value = %" PRId64,
-                                               trigger_name,
-                                               (int) trigger_owner_uid,
-                                               local_value);
+                                   trigger_name,
+                                   (int) trigger_owner_uid,
+                                   local_value);
                        } else {
                                abort();
                        }
@@ -856,13 +857,11 @@ event_notifier_error_accounting_ust_get_count(
        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 
 end:
-       rcu_read_unlock();
        return status;
 }
 
-static
-enum event_notifier_error_accounting_status event_notifier_error_accounting_ust_clear(
-               const struct lttng_trigger *trigger)
+static enum event_notifier_error_accounting_status
+event_notifier_error_accounting_ust_clear(const struct lttng_trigger *trigger)
 {
        struct lttng_ht_iter iter;
        struct ust_error_accounting_entry *uid_entry;
@@ -871,20 +870,21 @@ enum event_notifier_error_accounting_status event_notifier_error_accounting_ust_
        size_t dimension_index;
        const uint64_t tracer_token = lttng_trigger_get_tracer_token(trigger);
 
-       rcu_read_lock();
-       status = get_error_counter_index_for_token(&ust_state, tracer_token,
-                       &error_counter_index);
+       lttng::urcu::read_lock_guard read_lock;
+
+       status = get_error_counter_index_for_token(&ust_state, tracer_token, &error_counter_index);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                uid_t trigger_owner_uid;
                const char *trigger_name;
 
-               get_trigger_info_for_log(trigger, &trigger_name,
-                                        &trigger_owner_uid);
+               get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
-               ERR("Failed to retrieve index for tracer token: token = %" PRIu64 ", trigger name = '%s', trigger owner uid = %d, status = %s",
-                               tracer_token, trigger_name,
-                               (int) trigger_owner_uid,
-                               error_accounting_status_str(status));
+               ERR("Failed to retrieve index for tracer token: token = %" PRIu64
+                   ", trigger name = '%s', trigger owner uid = %d, status = %s",
+                   tracer_token,
+                   trigger_name,
+                   (int) trigger_owner_uid,
+                   error_accounting_status_str(status));
                goto end;
        }
 
@@ -895,20 +895,19 @@ enum event_notifier_error_accounting_status event_notifier_error_accounting_ust_
         * errors) can be generated from any applications that this session
         * daemon is managing.
         */
-       cds_lfht_for_each_entry(error_counter_uid_ht->ht, &iter.iter,
-                       uid_entry, node.node) {
-               const int ret = lttng_ust_ctl_counter_clear(uid_entry->daemon_counter,
-                               &dimension_index);
+       cds_lfht_for_each_entry (error_counter_uid_ht->ht, &iter.iter, uid_entry, node.node) {
+               const int ret =
+                       lttng_ust_ctl_counter_clear(uid_entry->daemon_counter, &dimension_index);
 
                if (ret) {
                        uid_t trigger_owner_uid;
                        const char *trigger_name;
 
-                       get_trigger_info_for_log(trigger, &trigger_name,
-                                                &trigger_owner_uid);
+                       get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
                        ERR("Failed to clear event notifier counter value for trigger: counter uid = %d, trigger name = '%s', trigger owner uid = %d",
-                                       (int) uid_entry->node.key, trigger_name,
-                                       (int) trigger_owner_uid);
+                           (int) uid_entry->node.key,
+                           trigger_name,
+                           (int) trigger_owner_uid);
                        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                        goto end;
                }
@@ -916,52 +915,46 @@ enum event_notifier_error_accounting_status event_notifier_error_accounting_ust_
 
        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 end:
-       rcu_read_unlock();
        return status;
 }
 #endif /* HAVE_LIBLTTNG_UST_CTL */
 
-static
-enum event_notifier_error_accounting_status
-event_notifier_error_accounting_kernel_clear(
-               const struct lttng_trigger *trigger)
+static enum event_notifier_error_accounting_status
+event_notifier_error_accounting_kernel_clear(const struct lttng_trigger *trigger)
 {
        int ret;
        uint64_t error_counter_index;
        enum event_notifier_error_accounting_status status;
        struct lttng_kernel_abi_counter_clear counter_clear = {};
 
-       status = get_error_counter_index_for_token(&kernel_state,
-                       lttng_trigger_get_tracer_token(trigger),
-                       &error_counter_index);
+       status = get_error_counter_index_for_token(
+               &kernel_state, lttng_trigger_get_tracer_token(trigger), &error_counter_index);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                uid_t trigger_owner_uid;
                const char *trigger_name;
 
-               get_trigger_info_for_log(
-                               trigger, &trigger_name, &trigger_owner_uid);
+               get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
                ERR("Failed to get event notifier error counter index: trigger owner uid = %d, trigger name = '%s', status = '%s'",
-                               trigger_owner_uid, trigger_name,
-                               error_accounting_status_str(status));
+                   trigger_owner_uid,
+                   trigger_name,
+                   error_accounting_status_str(status));
                goto end;
        }
 
        counter_clear.index.number_dimensions = 1;
        counter_clear.index.dimension_indexes[0] = error_counter_index;
 
-       ret = kernctl_counter_clear(
-                       kernel_error_accounting_entry.error_counter_fd,
-                       &counter_clear);
+       ret = kernctl_counter_clear(kernel_error_accounting_entry.error_counter_fd, &counter_clear);
        if (ret) {
                uid_t trigger_owner_uid;
                const char *trigger_name;
 
-               get_trigger_info_for_log(
-                               trigger, &trigger_name, &trigger_owner_uid);
+               get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
                ERR("Failed to clear kernel event notifier error counter: trigger owner uid = %d, trigger name = '%s'",
-                               trigger_owner_uid, trigger_name);
+                   trigger_owner_uid,
+                   trigger_name);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto end;
        }
@@ -972,16 +965,15 @@ end:
 }
 
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_register_kernel(
-               int kernel_event_notifier_group_fd)
+event_notifier_error_accounting_register_kernel(int kernel_event_notifier_group_fd)
 {
        int error_counter_fd = -1, ret;
        enum event_notifier_error_accounting_status status;
        lttng_kernel_abi_counter_conf error_counter_conf = {
                .arithmetic = LTTNG_KERNEL_ABI_COUNTER_ARITHMETIC_MODULAR,
                .bitness = sizeof(void *) == sizeof(uint32_t) ?
-                               LTTNG_KERNEL_ABI_COUNTER_BITNESS_32 :
-                               LTTNG_KERNEL_ABI_COUNTER_BITNESS_64,
+                       LTTNG_KERNEL_ABI_COUNTER_BITNESS_32 :
+                       LTTNG_KERNEL_ABI_COUNTER_BITNESS_64,
                .number_dimensions = 1,
                .global_sum_step = 0,
                .dimensions = {},
@@ -992,11 +984,11 @@ event_notifier_error_accounting_register_kernel(
        error_counter_conf.dimensions[0].has_underflow = false;
        error_counter_conf.dimensions[0].has_overflow = false;
 
-       ret = kernctl_create_event_notifier_group_error_counter(
-                       kernel_event_notifier_group_fd, &error_counter_conf);
+       ret = kernctl_create_event_notifier_group_error_counter(kernel_event_notifier_group_fd,
+                                                               &error_counter_conf);
        if (ret < 0) {
                PERROR("Failed to create event notifier group error counter through kernel ioctl: kernel_event_notifier_group_fd = %d",
-                               kernel_event_notifier_group_fd);
+                      kernel_event_notifier_group_fd);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto error;
        }
@@ -1007,26 +999,22 @@ event_notifier_error_accounting_register_kernel(
        ret = fcntl(error_counter_fd, F_SETFD, FD_CLOEXEC);
        if (ret < 0) {
                PERROR("Failed to set FD_CLOEXEC flag on event notifier error counter file descriptor: error_counter_fd = %d",
-                               error_counter_fd);
+                      error_counter_fd);
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
                goto error;
        }
 
-       DBG("Created kernel event notifier group error counter: fd = %d",
-                       error_counter_fd);
+       DBG("Created kernel event notifier group error counter: fd = %d", error_counter_fd);
 
-       kernel_error_accounting_entry.error_counter_fd =
-                       error_counter_fd;
+       kernel_error_accounting_entry.error_counter_fd = error_counter_fd;
        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 
 error:
        return status;
 }
 
-static
-enum event_notifier_error_accounting_status create_error_counter_index_for_token(
-               struct error_accounting_state *state, uint64_t tracer_token,
-               uint64_t *error_counter_index)
+static enum event_notifier_error_accounting_status create_error_counter_index_for_token(
+       struct error_accounting_state *state, uint64_t tracer_token, uint64_t *error_counter_index)
 {
        struct index_ht_entry *index_entry;
        enum lttng_index_allocator_status index_alloc_status;
@@ -1036,14 +1024,13 @@ enum event_notifier_error_accounting_status create_error_counter_index_for_token
        LTTNG_ASSERT(state);
 
        /* Allocate a new index for that counter. */
-       index_alloc_status = lttng_index_allocator_alloc(state->index_allocator,
-                       &local_error_counter_index);
+       index_alloc_status =
+               lttng_index_allocator_alloc(state->index_allocator, &local_error_counter_index);
        switch (index_alloc_status) {
        case LTTNG_INDEX_ALLOCATOR_STATUS_EMPTY:
                DBG("No indices left in the configured event notifier error counter: "
-                               "number-of-indices = %" PRIu64,
-                               lttng_index_allocator_get_index_count(
-                                       state->index_allocator));
+                   "number-of-indices = %" PRIu64,
+                   lttng_index_allocator_get_index_count(state->index_allocator));
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NO_INDEX_AVAILABLE;
                goto end;
        case LTTNG_INDEX_ALLOCATOR_STATUS_OK:
@@ -1054,7 +1041,7 @@ enum event_notifier_error_accounting_status create_error_counter_index_for_token
        }
 
        index_entry = zmalloc<index_ht_entry>();
-       if (index_entry == NULL) {
+       if (index_entry == nullptr) {
                PERROR("Failed to allocate event notifier error counter hash table entry");
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOMEM;
                goto end;
@@ -1064,8 +1051,10 @@ enum event_notifier_error_accounting_status create_error_counter_index_for_token
        lttng_ht_node_init_u64(&index_entry->node, tracer_token);
        lttng_ht_add_unique_u64(state->indices_ht, &index_entry->node);
 
-       DBG("Allocated error counter index for tracer token: tracer token = %" PRIu64 ", index = %" PRIu64,
-                       tracer_token, local_error_counter_index);
+       DBG("Allocated error counter index for tracer token: tracer token = %" PRIu64
+           ", index = %" PRIu64,
+           tracer_token,
+           local_error_counter_index);
        *error_counter_index = local_error_counter_index;
        status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 end:
@@ -1073,9 +1062,8 @@ end:
 }
 
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_register_event_notifier(
-               const struct lttng_trigger *trigger,
-               uint64_t *error_counter_index)
+event_notifier_error_accounting_register_event_notifier(const struct lttng_trigger *trigger,
+                                                       uint64_t *error_counter_index)
 {
        enum event_notifier_error_accounting_status status;
        uint64_t local_error_counter_index;
@@ -1099,29 +1087,28 @@ event_notifier_error_accounting_register_event_notifier(
         * Check if this event notifier already has a error counter index
         * assigned.
         */
-       status = get_error_counter_index_for_token(state,
-                       lttng_trigger_get_tracer_token(trigger),
-                       &local_error_counter_index);
+       status = get_error_counter_index_for_token(
+               state, lttng_trigger_get_tracer_token(trigger), &local_error_counter_index);
        switch (status) {
        case EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NOT_FOUND:
        {
                uid_t trigger_owner_uid;
                const char *trigger_name;
 
-               get_trigger_info_for_log(
-                               trigger, &trigger_name, &trigger_owner_uid);
+               get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
                DBG("Event notifier error counter index not found for tracer token (allocating a new one): trigger name = '%s', trigger owner uid = %d, tracer token = %" PRIu64,
-                               trigger_name, trigger_owner_uid,
-                               lttng_trigger_get_tracer_token(trigger));
+                   trigger_name,
+                   trigger_owner_uid,
+                   lttng_trigger_get_tracer_token(trigger));
 
-               status = create_error_counter_index_for_token(state,
-                               lttng_trigger_get_tracer_token(trigger),
-                               &local_error_counter_index);
+               status = create_error_counter_index_for_token(
+                       state, lttng_trigger_get_tracer_token(trigger), &local_error_counter_index);
                if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                        ERR("Error creating index for token: status = %s, trigger name = '%s', trigger owner uid = %d",
-                                       error_accounting_status_str(status),
-                                       trigger_name, trigger_owner_uid);
+                           error_accounting_status_str(status),
+                           trigger_name,
+                           trigger_owner_uid);
                        goto end;
                }
        }
@@ -1158,27 +1145,24 @@ event_notifier_error_accounting_register_event_notifier(
        }
 #endif /* HAVE_LIBLTTNG_UST_CTL */
 
-
 end:
        return status;
 }
 
-static
-enum event_notifier_error_accounting_status
-event_notifier_error_accounting_kernel_get_count(
-               const struct lttng_trigger *trigger, uint64_t *count)
+static enum event_notifier_error_accounting_status
+event_notifier_error_accounting_kernel_get_count(const struct lttng_trigger *trigger,
+                                                uint64_t *count)
 {
        struct lttng_kernel_abi_counter_aggregate counter_aggregate = {};
        enum event_notifier_error_accounting_status status;
        uint64_t error_counter_index;
        int ret;
 
-       status = get_error_counter_index_for_token(&kernel_state,
-                       lttng_trigger_get_tracer_token(trigger),
-                       &error_counter_index);
+       status = get_error_counter_index_for_token(
+               &kernel_state, lttng_trigger_get_tracer_token(trigger), &error_counter_index);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                ERR("Error getting index for token: status=%s",
-                               error_accounting_status_str(status));
+                   error_accounting_status_str(status));
                goto end;
        }
 
@@ -1187,23 +1171,24 @@ event_notifier_error_accounting_kernel_get_count(
 
        LTTNG_ASSERT(kernel_error_accounting_entry.error_counter_fd);
 
-       ret = kernctl_counter_get_aggregate_value(
-                       kernel_error_accounting_entry.error_counter_fd,
-                       &counter_aggregate);
+       ret = kernctl_counter_get_aggregate_value(kernel_error_accounting_entry.error_counter_fd,
+                                                 &counter_aggregate);
        if (ret || counter_aggregate.value.value < 0) {
                uid_t trigger_owner_uid;
                const char *trigger_name;
 
-               get_trigger_info_for_log(trigger, &trigger_name,
-                               &trigger_owner_uid);
+               get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
                if (counter_aggregate.value.value < 0) {
                        ERR("Invalid negative event notifier error counter value: trigger owner = %d, trigger name = '%s', value = %" PRId64,
-                                       trigger_owner_uid, trigger_name,
-                                       counter_aggregate.value.value);
+                           trigger_owner_uid,
+                           trigger_name,
+                           counter_aggregate.value.value);
                } else {
                        ERR("Failed to getting event notifier error count: trigger owner = %d, trigger name = '%s', ret = %d",
-                                       trigger_owner_uid, trigger_name, ret);
+                           trigger_owner_uid,
+                           trigger_name,
+                           ret);
                }
 
                status = EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_ERR;
@@ -1221,20 +1206,17 @@ end:
 }
 
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_get_count(
-               const struct lttng_trigger *trigger, uint64_t *count)
+event_notifier_error_accounting_get_count(const struct lttng_trigger *trigger, uint64_t *count)
 {
        switch (lttng_trigger_get_underlying_domain_type_restriction(trigger)) {
        case LTTNG_DOMAIN_KERNEL:
-               return event_notifier_error_accounting_kernel_get_count(
-                               trigger, count);
+               return event_notifier_error_accounting_kernel_get_count(trigger, count);
        case LTTNG_DOMAIN_UST:
        case LTTNG_DOMAIN_PYTHON:
        case LTTNG_DOMAIN_JUL:
        case LTTNG_DOMAIN_LOG4J:
 #ifdef HAVE_LIBLTTNG_UST_CTL
-               return event_notifier_error_accounting_ust_get_count(trigger,
-                               count);
+               return event_notifier_error_accounting_ust_get_count(trigger, count);
 #else
                *count = 0;
                return EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
@@ -1244,8 +1226,7 @@ event_notifier_error_accounting_get_count(
        }
 }
 
-static
-enum event_notifier_error_accounting_status
+static enum event_notifier_error_accounting_status
 event_notifier_error_accounting_clear(const struct lttng_trigger *trigger)
 {
        switch (lttng_trigger_get_underlying_domain_type_restriction(trigger)) {
@@ -1267,14 +1248,12 @@ event_notifier_error_accounting_clear(const struct lttng_trigger *trigger)
 
 static void free_index_ht_entry(struct rcu_head *head)
 {
-       struct index_ht_entry *entry = caa_container_of(head,
-                       struct index_ht_entry, rcu_head);
+       struct index_ht_entry *entry = caa_container_of(head, struct index_ht_entry, rcu_head);
 
        free(entry);
 }
 
-void event_notifier_error_accounting_unregister_event_notifier(
-               const struct lttng_trigger *trigger)
+void event_notifier_error_accounting_unregister_event_notifier(const struct lttng_trigger *trigger)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
@@ -1282,16 +1261,16 @@ void event_notifier_error_accounting_unregister_event_notifier(
        enum event_notifier_error_accounting_status status;
        struct error_accounting_state *state;
 
+       lttng::urcu::read_lock_guard read_lock;
+
        status = event_notifier_error_accounting_clear(trigger);
        if (status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                /* Trigger details already logged by callee on error. */
                ERR("Failed to clear event notifier error counter during unregistration of event notifier: status = '%s'",
-                               error_accounting_status_str(status));
+                   error_accounting_status_str(status));
                goto end;
        }
 
-       rcu_read_lock();
-
        switch (lttng_trigger_get_underlying_domain_type_restriction(trigger)) {
        case LTTNG_DOMAIN_KERNEL:
                state = &kernel_state;
@@ -1306,7 +1285,6 @@ void event_notifier_error_accounting_unregister_event_notifier(
                pthread_mutex_lock(&the_event_notifier_counter.lock);
                the_event_notifier_counter.count--;
                if (the_event_notifier_counter.count == 0) {
-
                        /*
                         * When unregistering the last event notifier, put one
                         * reference to every uid entries on the behalf of all
@@ -1328,22 +1306,22 @@ void event_notifier_error_accounting_unregister_event_notifier(
        if (node) {
                int del_ret;
                struct index_ht_entry *index_entry =
-                               lttng::utils::container_of(node, &index_ht_entry::node);
+                       lttng::utils::container_of(node, &index_ht_entry::node);
                enum lttng_index_allocator_status index_alloc_status;
 
                index_alloc_status = lttng_index_allocator_release(
-                               state->index_allocator,
-                               index_entry->error_counter_index);
+                       state->index_allocator, index_entry->error_counter_index);
                if (index_alloc_status != LTTNG_INDEX_ALLOCATOR_STATUS_OK) {
                        uid_t trigger_owner_uid;
                        const char *trigger_name;
 
-                       get_trigger_info_for_log(trigger, &trigger_name,
-                                       &trigger_owner_uid);
+                       get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
 
-                       ERR("Failed to release event notifier error counter index: index = %" PRIu64 ", trigger name = '%s', trigger owner uid = %d",
-                                       index_entry->error_counter_index,
-                                       trigger_name, (int) trigger_owner_uid);
+                       ERR("Failed to release event notifier error counter index: index = %" PRIu64
+                           ", trigger name = '%s', trigger owner uid = %d",
+                           index_entry->error_counter_index,
+                           trigger_name,
+                           (int) trigger_owner_uid);
                        /* Don't exit, perform the rest of the clean-up. */
                }
 
@@ -1351,12 +1329,11 @@ void event_notifier_error_accounting_unregister_event_notifier(
                LTTNG_ASSERT(!del_ret);
                call_rcu(&index_entry->rcu_head, free_index_ht_entry);
        }
-
 end:
-       rcu_read_unlock();
+       return;
 }
 
-void event_notifier_error_accounting_fini(void)
+void event_notifier_error_accounting_fini()
 {
        if (kernel_error_accounting_entry.error_counter_fd) {
                const int ret = close(kernel_error_accounting_entry.error_counter_fd);
index 89466bd441605bf9b1336e289b92ac10b2105843..79a9f515c73f88664f135faea16c928d4410fb60 100644 (file)
@@ -8,11 +8,11 @@
 #ifndef _EVENT_NOTIFIER_ERROR_ACCOUNTING_H
 #define _EVENT_NOTIFIER_ERROR_ACCOUNTING_H
 
-#include <stdint.h>
+#include "ust-app.hpp"
 
 #include <lttng/trigger/trigger.h>
 
-#include "ust-app.hpp"
+#include <stdint.h>
 
 enum event_notifier_error_accounting_status {
        EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK,
@@ -30,16 +30,14 @@ enum event_notifier_error_accounting_status {
  * to be allocated for each domain.
  */
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_init(uint64_t buffer_size_kernel,
-               uint64_t buffer_size_ust);
+event_notifier_error_accounting_init(uint64_t buffer_size_kernel, uint64_t buffer_size_ust);
 
 /*
  * Register the kernel event notifier group.
  * This allocates the counter object on the kernel side.
  */
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_register_kernel(
-               int kernel_event_notifier_group_fd);
+event_notifier_error_accounting_register_kernel(int kernel_event_notifier_group_fd);
 
 #ifdef HAVE_LIBLTTNG_UST_CTL
 
@@ -59,18 +57,14 @@ event_notifier_error_accounting_unregister_app(struct ust_app *app);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-enum event_notifier_error_accounting_status
-event_notifier_error_accounting_register_app(
-               struct ust_app *app __attribute__((unused)))
+static inline enum event_notifier_error_accounting_status
+event_notifier_error_accounting_register_app(struct ust_app *app __attribute__((unused)))
 {
        return EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 }
 
-static inline
-enum event_notifier_error_accounting_status
-event_notifier_error_accounting_unregister_app(
-               struct ust_app *app __attribute__((unused)))
+static inline enum event_notifier_error_accounting_status
+event_notifier_error_accounting_unregister_app(struct ust_app *app __attribute__((unused)))
 {
        return EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK;
 }
@@ -80,18 +74,14 @@ event_notifier_error_accounting_unregister_app(
  * Allocates, reserves and returns the error counter index for that trigger.
  */
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_register_event_notifier(
-               const struct lttng_trigger *trigger,
-               uint64_t *error_counter_index);
+event_notifier_error_accounting_register_event_notifier(const struct lttng_trigger *trigger,
+                                                       uint64_t *error_counter_index);
 
 enum event_notifier_error_accounting_status
-event_notifier_error_accounting_get_count(
-               const struct lttng_trigger *trigger,
-               uint64_t *count);
+event_notifier_error_accounting_get_count(const struct lttng_trigger *trigger, uint64_t *count);
 
-void event_notifier_error_accounting_unregister_event_notifier(
-               const struct lttng_trigger *trigger);
+void event_notifier_error_accounting_unregister_event_notifier(const struct lttng_trigger *trigger);
 
-void event_notifier_error_accounting_fini(void);
+void event_notifier_error_accounting_fini();
 
 #endif /* _EVENT_NOTIFIER_ERROR_ACCOUNTING_H */
index 65b7220ef13603ad1d84f9952e1bde0854dd80de..462ed2f0db588fdd1ad37debd9bf6d2609ef079c 100644 (file)
@@ -7,38 +7,39 @@
  */
 
 #define _LGPL_SOURCE
-#include <urcu/list.h>
-#include <string.h>
-
-#include <common/compat/errno.hpp>
-#include <lttng/lttng.h>
-#include <lttng/condition/condition.h>
-#include <lttng/condition/event-rule-matches.h>
-#include <lttng/event-rule/event-rule.h>
-#include <lttng/event-rule/event-rule-internal.hpp>
-#include <common/bytecode/bytecode.hpp>
-#include <common/error.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/filter.hpp>
-#include <common/context.hpp>
-
+#include "agent.hpp"
 #include "channel.hpp"
 #include "event.hpp"
 #include "kernel.hpp"
 #include "lttng-sessiond.hpp"
 #include "lttng-ust-ctl.hpp"
 #include "lttng-ust-error.hpp"
-#include "ust-app.hpp"
 #include "trace-kernel.hpp"
 #include "trace-ust.hpp"
-#include "agent.hpp"
+#include "ust-app.hpp"
 #include "utils.hpp"
 
+#include <common/bytecode/bytecode.hpp>
+#include <common/compat/errno.hpp>
+#include <common/context.hpp>
+#include <common/error.hpp>
+#include <common/filter.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
+
+#include <lttng/condition/condition.h>
+#include <lttng/condition/event-rule-matches.h>
+#include <lttng/event-rule/event-rule-internal.hpp>
+#include <lttng/event-rule/event-rule.h>
+#include <lttng/lttng.h>
+
+#include <string.h>
+#include <urcu/list.h>
+
 /*
  * Add unique UST event based on the event name, filter bytecode and loglevel.
  */
-static void add_unique_ust_event(struct lttng_ht *ht,
-               struct ltt_ust_event *event)
+static void add_unique_ust_event(struct lttng_ht *ht, struct ltt_ust_event *event)
 {
        struct cds_lfht_node *node_ptr;
        struct ltt_ust_ht_key key;
@@ -54,8 +55,10 @@ static void add_unique_ust_event(struct lttng_ht *ht,
        key.exclusion = event->exclusion;
 
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct(event->node.key, lttng_ht_seed),
-                       trace_ust_ht_match_event, &key, &event->node.node);
+                                      ht->hash_fct(event->node.key, lttng_ht_seed),
+                                      trace_ust_ht_match_event,
+                                      &key,
+                                      &event->node.node);
        LTTNG_ASSERT(node_ptr == &event->node.node);
 }
 
@@ -66,7 +69,8 @@ static void add_unique_ust_event(struct lttng_ht *ht,
  * If event_name is NULL all events of the specified type are disabled.
  */
 int event_kernel_disable_event(struct ltt_kernel_channel *kchan,
-               const char *event_name, enum lttng_event_type type)
+                              const char *event_name,
+                              enum lttng_event_type type)
 {
        int ret, error = 0, found = 0;
        struct ltt_kernel_event *kevent;
@@ -74,10 +78,10 @@ int event_kernel_disable_event(struct ltt_kernel_channel *kchan,
        LTTNG_ASSERT(kchan);
 
        /* For each event in the kernel session */
-       cds_list_for_each_entry(kevent, &kchan->events_list.head, list) {
+       cds_list_for_each_entry (kevent, &kchan->events_list.head, list) {
                if (type != LTTNG_EVENT_ALL && kevent->type != type)
                        continue;
-               if (event_name != NULL && strcmp(event_name, kevent->event->name)) {
+               if (event_name != nullptr && strcmp(event_name, kevent->event->name) != 0) {
                        continue;
                }
                found++;
@@ -88,9 +92,11 @@ int event_kernel_disable_event(struct ltt_kernel_channel *kchan,
                }
        }
        DBG("Disable kernel event: found %d events with name: %s and type: %d",
-                       found, event_name ? event_name : "NULL", type);
+           found,
+           event_name ? event_name : "NULL",
+           type);
 
-       if (event_name != NULL && !found) {
+       if (event_name != nullptr && !found) {
                ret = LTTNG_ERR_NO_EVENT;
        } else {
                ret = error ? LTTNG_ERR_KERN_DISABLE_FAIL : LTTNG_OK;
@@ -104,8 +110,9 @@ int event_kernel_disable_event(struct ltt_kernel_channel *kchan,
  * We own filter_expression and filter.
  */
 int event_kernel_enable_event(struct ltt_kernel_channel *kchan,
-               struct lttng_event *event, char *filter_expression,
-               struct lttng_bytecode *filter)
+                             struct lttng_event *event,
+                             char *filter_expression,
+                             struct lttng_bytecode *filter)
 {
        int ret;
        struct ltt_kernel_event *kevent;
@@ -113,17 +120,16 @@ int event_kernel_enable_event(struct ltt_kernel_channel *kchan,
        LTTNG_ASSERT(kchan);
        LTTNG_ASSERT(event);
 
-       kevent = trace_kernel_find_event(event->name, kchan,
-                       event->type, filter);
-       if (kevent == NULL) {
+       kevent = trace_kernel_find_event(event->name, kchan, event->type, filter);
+       if (kevent == nullptr) {
                ret = kernel_create_event(event, kchan, filter_expression, filter);
                /* We have passed ownership */
-               filter_expression = NULL;
-               filter = NULL;
+               filter_expression = nullptr;
+               filter = nullptr;
                if (ret) {
                        goto end;
                }
-       } else if (kevent->enabled == 0) {
+       } else if (!kevent->enabled) {
                ret = kernel_enable_event(kevent);
                if (ret < 0) {
                        ret = LTTNG_ERR_KERN_ENABLE_FAIL;
@@ -153,11 +159,12 @@ end:
  * We own filter_expression, filter, and exclusion.
  */
 int event_ust_enable_tracepoint(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               bool internal_event)
+                               struct ltt_ust_channel *uchan,
+                               struct lttng_event *event,
+                               char *filter_expression,
+                               struct lttng_bytecode *filter,
+                               struct lttng_event_exclusion *exclusion,
+                               bool internal_event)
 {
        int ret = LTTNG_OK, to_create = 0;
        struct ltt_ust_event *uevent;
@@ -166,18 +173,21 @@ int event_ust_enable_tracepoint(struct ltt_ust_session *usess,
        LTTNG_ASSERT(uchan);
        LTTNG_ASSERT(event);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
-       uevent = trace_ust_find_event(uchan->events, event->name, filter,
-                       (enum lttng_ust_abi_loglevel_type) event->loglevel_type,
-                       event->loglevel, exclusion);
+       uevent = trace_ust_find_event(uchan->events,
+                                     event->name,
+                                     filter,
+                                     (enum lttng_ust_abi_loglevel_type) event->loglevel_type,
+                                     event->loglevel,
+                                     exclusion);
        if (!uevent) {
-               ret = trace_ust_create_event(event, filter_expression,
-                               filter, exclusion, internal_event, &uevent);
+               ret = trace_ust_create_event(
+                       event, filter_expression, filter, exclusion, internal_event, &uevent);
                /* We have passed ownership */
-               filter_expression = NULL;
-               filter = NULL;
-               exclusion = NULL;
+               filter_expression = nullptr;
+               filter = nullptr;
+               exclusion = nullptr;
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -193,7 +203,7 @@ int event_ust_enable_tracepoint(struct ltt_ust_session *usess,
                goto end;
        }
 
-       uevent->enabled = 1;
+       uevent->enabled = true;
        if (to_create) {
                /* Add ltt ust event to channel */
                add_unique_ust_event(uchan->events, uevent);
@@ -220,13 +230,14 @@ int event_ust_enable_tracepoint(struct ltt_ust_session *usess,
                goto end;
        }
 
-       DBG("Event UST %s %s in channel %s", uevent->attr.name,
-                       to_create ? "created" : "enabled", uchan->name);
+       DBG("Event UST %s %s in channel %s",
+           uevent->attr.name,
+           to_create ? "created" : "enabled",
+           uchan->name);
 
        ret = LTTNG_OK;
 
 end:
-       rcu_read_unlock();
        free(filter_expression);
        free(filter);
        free(exclusion);
@@ -237,7 +248,8 @@ end:
  * Disable UST tracepoint of a channel from a UST session.
  */
 int event_ust_disable_tracepoint(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, const char *event_name)
+                                struct ltt_ust_channel *uchan,
+                                const char *event_name)
 {
        int ret;
        struct ltt_ust_event *uevent;
@@ -251,16 +263,19 @@ int event_ust_disable_tracepoint(struct ltt_ust_session *usess,
 
        ht = uchan->events;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * We use a custom lookup since we need the iterator for the next_duplicate
         * call in the do while loop below.
         */
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) event_name, lttng_ht_seed),
-                       trace_ust_ht_match_event_by_name, event_name, &iter.iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) event_name, lttng_ht_seed),
+                       trace_ust_ht_match_event_by_name,
+                       event_name,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("Trace UST event NOT found by name %s", event_name);
                ret = LTTNG_ERR_UST_EVENT_NOT_FOUND;
                goto error;
@@ -270,13 +285,12 @@ int event_ust_disable_tracepoint(struct ltt_ust_session *usess,
                uevent = lttng::utils::container_of(node, &ltt_ust_event::node);
                LTTNG_ASSERT(uevent);
 
-               if (uevent->enabled == 0) {
+               if (!uevent->enabled) {
                        /* It's already disabled so everything is OK */
                        goto next;
                }
-               uevent->enabled = 0;
-               DBG2("Event UST %s disabled in channel %s", uevent->attr.name,
-                               uchan->name);
+               uevent->enabled = false;
+               DBG2("Event UST %s disabled in channel %s", uevent->attr.name, uchan->name);
 
                if (!usess->active) {
                        goto next;
@@ -286,45 +300,43 @@ int event_ust_disable_tracepoint(struct ltt_ust_session *usess,
                        ret = LTTNG_ERR_UST_DISABLE_FAIL;
                        goto error;
                }
-next:
+       next:
                /* Get next duplicate event by name. */
-               cds_lfht_next_duplicate(ht->ht, trace_ust_ht_match_event_by_name,
-                               event_name, &iter.iter);
+               cds_lfht_next_duplicate(
+                       ht->ht, trace_ust_ht_match_event_by_name, event_name, &iter.iter);
                node = lttng_ht_iter_get_node_str(&iter);
        } while (node);
 
        ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
 /*
  * Disable all UST tracepoints for a channel from a UST session.
  */
-int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan)
+int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan)
 {
        int ret, i, size, error = 0;
        struct lttng_ht_iter iter;
-       struct ltt_ust_event *uevent = NULL;
-       struct lttng_event *events = NULL;
+       struct ltt_ust_event *uevent = nullptr;
+       struct lttng_event *events = nullptr;
 
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(uchan);
 
-       rcu_read_lock();
-
        /* Disabling existing events */
-       cds_lfht_for_each_entry(uchan->events->ht, &iter.iter, uevent,
-                       node.node) {
-               if (uevent->enabled == 1) {
-                       ret = event_ust_disable_tracepoint(usess, uchan,
-                                       uevent->attr.name);
-                       if (ret < 0) {
-                               error = LTTNG_ERR_UST_DISABLE_FAIL;
-                               continue;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (uchan->events->ht, &iter.iter, uevent, node.node) {
+                       if (uevent->enabled) {
+                               ret = event_ust_disable_tracepoint(usess, uchan, uevent->attr.name);
+                               if (ret < 0) {
+                                       error = LTTNG_ERR_UST_DISABLE_FAIL;
+                                       continue;
+                               }
                        }
                }
        }
@@ -337,8 +349,7 @@ int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess,
        }
 
        for (i = 0; i < size; i++) {
-               ret = event_ust_disable_tracepoint(usess, uchan,
-                               events[i].name);
+               ret = event_ust_disable_tracepoint(usess, uchan, events[i].name);
                if (ret < 0) {
                        /* Continue to disable the rest... */
                        error = LTTNG_ERR_UST_DISABLE_FAIL;
@@ -348,7 +359,6 @@ int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess,
 
        ret = error ? error : LTTNG_OK;
 error:
-       rcu_read_unlock();
        free(events);
        return ret;
 }
@@ -358,13 +368,14 @@ static void agent_enable_all(struct agent *agt)
        struct agent_event *aevent;
        struct lttng_ht_iter iter;
 
-       /* Flag every event as enabled. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry (
-                       agt->events->ht, &iter.iter, aevent, node.node) {
-               aevent->enabled_count++;
+       {
+               /* Flag every event as enabled. */
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (agt->events->ht, &iter.iter, aevent, node.node) {
+                       aevent->enabled_count++;
+               }
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -373,8 +384,10 @@ static void agent_enable_all(struct agent *agt)
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
 int event_agent_enable_all(struct ltt_ust_session *usess,
-               struct agent *agt, struct lttng_event *event,
-               struct lttng_bytecode *filter ,char *filter_expression)
+                          struct agent *agt,
+                          struct lttng_event *event,
+                          struct lttng_bytecode *filter,
+                          char *filter_expression)
 {
        int ret;
 
@@ -404,12 +417,12 @@ error:
  * the lttng-ctl library.
  */
 static int add_filter_app_ctx(struct lttng_bytecode *bytecode,
-               const char *filter_expression, struct agent *agt)
+                             const char *filter_expression,
+                             struct agent *agt)
 {
        int ret = LTTNG_OK;
-       char *provider_name = NULL, *ctx_name = NULL;
-       struct bytecode_symbol_iterator *it =
-                       bytecode_symbol_iterator_create(bytecode);
+       char *provider_name = nullptr, *ctx_name = nullptr;
+       struct bytecode_symbol_iterator *it = bytecode_symbol_iterator_create(bytecode);
 
        if (!it) {
                ret = LTTNG_ERR_NOMEM;
@@ -418,11 +431,9 @@ static int add_filter_app_ctx(struct lttng_bytecode *bytecode,
 
        do {
                struct lttng_event_context ctx;
-               const char *symbol_name =
-                               bytecode_symbol_iterator_get_name(it);
+               const char *symbol_name = bytecode_symbol_iterator_get_name(it);
 
-               if (parse_application_context(symbol_name, &provider_name,
-                               &ctx_name)) {
+               if (parse_application_context(symbol_name, &provider_name, &ctx_name)) {
                        /* Not an application context. */
                        continue;
                }
@@ -433,25 +444,25 @@ static int add_filter_app_ctx(struct lttng_bytecode *bytecode,
 
                /* Recognized an application context. */
                DBG("Enabling event with filter expression \"%s\" requires enabling the %s:%s application context.",
-                               filter_expression, provider_name, ctx_name);
+                   filter_expression,
+                   provider_name,
+                   ctx_name);
 
                ret = agent_add_context(&ctx, agt);
                if (ret != LTTNG_OK) {
-                       ERR("Failed to add application context %s:%s.",
-                                       provider_name, ctx_name);
+                       ERR("Failed to add application context %s:%s.", provider_name, ctx_name);
                        goto end;
                }
 
                ret = agent_enable_context(&ctx, agt->domain);
                if (ret != LTTNG_OK) {
-                       ERR("Failed to enable application context %s:%s.",
-                                       provider_name, ctx_name);
+                       ERR("Failed to enable application context %s:%s.", provider_name, ctx_name);
                        goto end;
                }
 
                free(provider_name);
                free(ctx_name);
-               provider_name = ctx_name = NULL;
+               provider_name = ctx_name = nullptr;
        } while (bytecode_symbol_iterator_next(it) == 0);
 end:
        free(provider_name);
@@ -461,9 +472,9 @@ end:
 }
 
 static int agent_enable(struct agent *agt,
-               struct lttng_event *event,
-               struct lttng_bytecode *filter,
-               char *filter_expression)
+                       struct lttng_event *event,
+                       struct lttng_bytecode *filter,
+                       char *filter_expression)
 {
        int ret, created = 0;
        struct agent_event *aevent;
@@ -471,26 +482,27 @@ static int agent_enable(struct agent *agt,
        LTTNG_ASSERT(event);
        LTTNG_ASSERT(agt);
 
-       rcu_read_lock();
-       aevent = agent_find_event(event->name, event->loglevel_type,
-                       event->loglevel, filter_expression, agt);
+       lttng::urcu::read_lock_guard read_lock;
+       aevent = agent_find_event(
+               event->name, event->loglevel_type, event->loglevel, filter_expression, agt);
        if (!aevent) {
-               aevent = agent_create_event(event->name, event->loglevel_type,
-                               event->loglevel, filter,
-                               filter_expression);
+               aevent = agent_create_event(event->name,
+                                           event->loglevel_type,
+                                           event->loglevel,
+                                           filter,
+                                           filter_expression);
                if (!aevent) {
                        ret = LTTNG_ERR_NOMEM;
                        goto error;
                }
-               filter = NULL;
-               filter_expression = NULL;
+               filter = nullptr;
+               filter_expression = nullptr;
                created = 1;
                LTTNG_ASSERT(!AGENT_EVENT_IS_ENABLED(aevent));
        }
 
        if (created && aevent->filter) {
-               ret = add_filter_app_ctx(
-                               aevent->filter, aevent->filter_expression, agt);
+               ret = add_filter_app_ctx(aevent->filter, aevent->filter_expression, agt);
                if (ret != LTTNG_OK) {
                        goto error;
                }
@@ -520,7 +532,6 @@ error:
                agent_destroy_event(aevent);
        }
 end:
-       rcu_read_unlock();
        free(filter);
        free(filter_expression);
        return ret;
@@ -532,19 +543,22 @@ end:
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
 int event_agent_enable(struct ltt_ust_session *usess,
-               struct agent *agt,
-               struct lttng_event *event,
-               struct lttng_bytecode *filter,
-               char *filter_expression)
+                      struct agent *agt,
+                      struct lttng_event *event,
+                      struct lttng_bytecode *filter,
+                      char *filter_expression)
 {
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(event);
        LTTNG_ASSERT(agt);
 
-       DBG("Enabling agent event: event pattern = '%s', session id = %" PRIu64 ", loglevel type = %d, loglevel = %d, filter expression = '%s'",
-                       event->name, usess->id, event->loglevel_type,
-                       event->loglevel,
-                       filter_expression ? filter_expression : "(none)");
+       DBG("Enabling agent event: event pattern = '%s', session id = %" PRIu64
+           ", loglevel type = %d, loglevel = %d, filter expression = '%s'",
+           event->name,
+           usess->id,
+           event->loglevel_type,
+           event->loglevel,
+           filter_expression ? filter_expression : "(none)");
 
        return agent_enable(agt, event, filter, filter_expression);
 }
@@ -563,10 +577,10 @@ int trigger_agent_enable(const struct lttng_trigger *trigger, struct agent *agt)
        const struct lttng_condition *condition;
        const struct lttng_event_rule *rule;
        const char *filter_expression;
-       char *filter_expression_copy = NULL;
+       char *filter_expression_copy = nullptr;
        const struct lttng_bytecode *filter_bytecode;
-       struct lttng_bytecode *filter_bytecode_copy = NULL;
-       struct lttng_event *event = NULL;
+       struct lttng_bytecode *filter_bytecode_copy = nullptr;
+       struct lttng_event *event = nullptr;
        uid_t trigger_owner_uid = 0;
        const char *trigger_name;
 
@@ -584,10 +598,9 @@ int trigger_agent_enable(const struct lttng_trigger *trigger, struct agent *agt)
        condition = lttng_trigger_get_const_condition(trigger);
 
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       c_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &rule);
+       c_status = lttng_condition_event_rule_matches_get_rule(condition, &rule);
        LTTNG_ASSERT(c_status == LTTNG_CONDITION_STATUS_OK);
 
        switch (lttng_event_rule_get_type(rule)) {
@@ -621,8 +634,7 @@ int trigger_agent_enable(const struct lttng_trigger *trigger, struct agent *agt)
                /* Get the filter bytecode */
                filter_bytecode = lttng_event_rule_get_filter_bytecode(rule);
                if (filter_bytecode) {
-                       filter_bytecode_copy =
-                                       lttng_bytecode_copy(filter_bytecode);
+                       filter_bytecode_copy = lttng_bytecode_copy(filter_bytecode);
                        if (!filter_bytecode_copy) {
                                ret = LTTNG_ERR_NOMEM;
                                goto end;
@@ -631,14 +643,14 @@ int trigger_agent_enable(const struct lttng_trigger *trigger, struct agent *agt)
        }
 
        DBG("Enabling agent event from trigger: trigger name = '%s', trigger owner uid = %d, token = %" PRIu64,
-                       trigger_name, trigger_owner_uid,
-                       lttng_trigger_get_tracer_token(trigger));
+           trigger_name,
+           trigger_owner_uid,
+           lttng_trigger_get_tracer_token(trigger));
 
-       ret = agent_enable(agt, event, filter_bytecode_copy,
-                       filter_expression_copy);
+       ret = agent_enable(agt, event, filter_bytecode_copy, filter_expression_copy);
        /* Ownership was passed even in case of error. */
-       filter_expression_copy = NULL;
-       filter_bytecode_copy = NULL;
+       filter_expression_copy = nullptr;
+       filter_bytecode_copy = nullptr;
 
 end:
        free(filter_expression_copy);
@@ -653,7 +665,7 @@ end:
  */
 const char *event_get_default_agent_ust_name(enum lttng_domain_type domain)
 {
-       const char *default_event_name = NULL;
+       const char *default_event_name = nullptr;
 
        switch (domain) {
        case LTTNG_DOMAIN_LOG4J:
@@ -673,8 +685,8 @@ const char *event_get_default_agent_ust_name(enum lttng_domain_type domain)
 }
 
 static int trigger_agent_disable_one(const struct lttng_trigger *trigger,
-               struct agent *agt,
-               struct agent_event *aevent)
+                                    struct agent *agt,
+                                    struct agent_event *aevent)
 
 {
        int ret;
@@ -689,8 +701,10 @@ static int trigger_agent_disable_one(const struct lttng_trigger *trigger,
         */
 
        DBG("Event agent disabling %s (loglevel type %d, loglevel value %d) for trigger %" PRIu64,
-                       aevent->name, aevent->loglevel_type,
-                       aevent->loglevel_value, lttng_trigger_get_tracer_token(trigger));
+           aevent->name,
+           aevent->loglevel_type,
+           aevent->loglevel_value,
+           lttng_trigger_get_tracer_token(trigger));
 
        /* Already disabled? */
        if (!AGENT_EVENT_IS_ENABLED(aevent)) {
@@ -716,11 +730,12 @@ error:
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
 static int event_agent_disable_one(struct ltt_ust_session *usess,
-               struct agent *agt, struct agent_event *aevent)
+                                  struct agent *agt,
+                                  struct agent_event *aevent)
 {
        int ret;
-       struct ltt_ust_event *uevent = NULL;
-       struct ltt_ust_channel *uchan = NULL;
+       struct ltt_ust_event *uevent = nullptr;
+       struct ltt_ust_channel *uchan = nullptr;
        const char *ust_event_name, *ust_channel_name;
 
        LTTNG_ASSERT(agt);
@@ -728,8 +743,10 @@ static int event_agent_disable_one(struct ltt_ust_session *usess,
        LTTNG_ASSERT(aevent);
 
        DBG("Event agent disabling %s (loglevel type %d, loglevel value %d) for session %" PRIu64,
-               aevent->name, aevent->loglevel_type, aevent->loglevel_value,
-               usess->id);
+           aevent->name,
+           aevent->loglevel_type,
+           aevent->loglevel_value,
+           usess->id);
 
        /* Already disabled? */
        if (!AGENT_EVENT_IS_ENABLED(aevent)) {
@@ -752,7 +769,7 @@ static int event_agent_disable_one(struct ltt_ust_session *usess,
         * the event and finally disable it.
         */
        uchan = trace_ust_find_channel_by_name(usess->domain_global.channels,
-                       (char *) ust_channel_name);
+                                              (char *) ust_channel_name);
        if (!uchan) {
                ret = LTTNG_ERR_UST_CHAN_NOT_FOUND;
                goto error;
@@ -770,8 +787,12 @@ static int event_agent_disable_one(struct ltt_ust_session *usess,
         * happens thanks to an UST filter. The following -1 is actually
         * ignored since the type is LTTNG_UST_LOGLEVEL_ALL.
         */
-       uevent = trace_ust_find_event(uchan->events, (char *) ust_event_name,
-                       aevent->filter, LTTNG_UST_ABI_LOGLEVEL_ALL, -1, NULL);
+       uevent = trace_ust_find_event(uchan->events,
+                                     (char *) ust_event_name,
+                                     aevent->filter,
+                                     LTTNG_UST_ABI_LOGLEVEL_ALL,
+                                     -1,
+                                     nullptr);
        /* If the agent event exists, it must be available on the UST side. */
        LTTNG_ASSERT(uevent);
 
@@ -787,7 +808,7 @@ static int event_agent_disable_one(struct ltt_ust_session *usess,
         * Flag event that it's disabled so the shadow copy on the ust app side
         * will disable it if an application shows up.
         */
-       uevent->enabled = 0;
+       uevent->enabled = false;
 
        ret = agent_disable_event(aevent, agt->domain);
        if (ret != LTTNG_OK) {
@@ -806,8 +827,7 @@ error:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int trigger_agent_disable(
-               const struct lttng_trigger *trigger, struct agent *agt)
+int trigger_agent_disable(const struct lttng_trigger *trigger, struct agent *agt)
 {
        int ret = LTTNG_OK;
        struct agent_event *aevent;
@@ -815,15 +835,14 @@ int trigger_agent_disable(
        LTTNG_ASSERT(trigger);
        LTTNG_ASSERT(agt);
 
-       DBG("Event agent disabling for trigger %" PRIu64,
-                       lttng_trigger_get_tracer_token(trigger));
+       DBG("Event agent disabling for trigger %" PRIu64, lttng_trigger_get_tracer_token(trigger));
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        aevent = agent_find_event_by_trigger(trigger, agt);
 
-       if (aevent == NULL) {
+       if (aevent == nullptr) {
                DBG2("Event agent NOT found by trigger %" PRIu64,
-                               lttng_trigger_get_tracer_token(trigger));
+                    lttng_trigger_get_tracer_token(trigger));
                ret = LTTNG_ERR_UST_EVENT_NOT_FOUND;
                goto end;
        }
@@ -835,7 +854,6 @@ int trigger_agent_disable(
        }
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -844,8 +862,7 @@ end:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt,
-               const char *event_name)
+int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt, const char *event_name)
 {
        int ret = LTTNG_OK;
        struct agent_event *aevent;
@@ -858,11 +875,11 @@ int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt,
 
        DBG("Event agent disabling %s (all loglevels) for session %" PRIu64, event_name, usess->id);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        agent_find_events_by_name(event_name, agt, &iter);
        node = lttng_ht_iter_get_node_str(&iter);
 
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("Event agent NOT found by name %s", event_name);
                ret = LTTNG_ERR_UST_EVENT_NOT_FOUND;
                goto end;
@@ -881,7 +898,6 @@ int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt,
                node = lttng_ht_iter_get_node_str(&iter);
        } while (node);
 end:
-       rcu_read_unlock();
        return ret;
 }
 /*
@@ -889,8 +905,7 @@ end:
  *
  * Return LTTNG_OK on success or else a LTTNG_ERR* code.
  */
-int event_agent_disable_all(struct ltt_ust_session *usess,
-               struct agent *agt)
+int event_agent_disable_all(struct ltt_ust_session *usess, struct agent *agt)
 {
        int ret;
        struct agent_event *aevent;
@@ -909,22 +924,24 @@ int event_agent_disable_all(struct ltt_ust_session *usess,
        }
 
        /* Disable every event. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(agt->events->ht, &iter.iter, aevent,
-                       node.node) {
-               if (!AGENT_EVENT_IS_ENABLED(aevent)) {
-                       continue;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               ret = event_agent_disable(usess, agt, aevent->name);
-               if (ret != LTTNG_OK) {
-                       goto error_unlock;
+               cds_lfht_for_each_entry (agt->events->ht, &iter.iter, aevent, node.node) {
+                       if (!AGENT_EVENT_IS_ENABLED(aevent)) {
+                               continue;
+                       }
+
+                       ret = event_agent_disable(usess, agt, aevent->name);
+                       if (ret != LTTNG_OK) {
+                               goto error_unlock;
+                       }
                }
        }
+
        ret = LTTNG_OK;
 
 error_unlock:
-       rcu_read_unlock();
 error:
        return ret;
 }
index efc4ad5d07b3547197542551e5c3ae6244dd1c0e..efd72f4ccd14f037d7dbd7c12bb97f907a9a3b39 100644 (file)
 struct agent;
 
 int event_kernel_disable_event(struct ltt_kernel_channel *kchan,
-               const char *event_name, enum lttng_event_type event_type);
+                              const char *event_name,
+                              enum lttng_event_type event_type);
 
 int event_kernel_enable_event(struct ltt_kernel_channel *kchan,
-               struct lttng_event *event, char *filter_expression,
-               struct lttng_bytecode *filter);
+                             struct lttng_event *event,
+                             char *filter_expression,
+                             struct lttng_bytecode *filter);
 
 int event_ust_enable_tracepoint(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct lttng_event *event,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               bool internal_event);
+                               struct ltt_ust_channel *uchan,
+                               struct lttng_event *event,
+                               char *filter_expression,
+                               struct lttng_bytecode *filter,
+                               struct lttng_event_exclusion *exclusion,
+                               bool internal_event);
 int event_ust_disable_tracepoint(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, const char *event_name);
-
-int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan);
-
-int event_agent_enable(struct ltt_ust_session *usess, struct agent *agt,
-               struct lttng_event *event, struct lttng_bytecode *filter,
-               char *filter_expression);
-int event_agent_enable_all(struct ltt_ust_session *usess, struct agent *agt,
-               struct lttng_event *event, struct lttng_bytecode *filter,
-               char *filter_expression);
-
-int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt,
-               const char *event_name);
+                                struct ltt_ust_channel *uchan,
+                                const char *event_name);
+
+int event_ust_disable_all_tracepoints(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan);
+
+int event_agent_enable(struct ltt_ust_session *usess,
+                      struct agent *agt,
+                      struct lttng_event *event,
+                      struct lttng_bytecode *filter,
+                      char *filter_expression);
+int event_agent_enable_all(struct ltt_ust_session *usess,
+                          struct agent *agt,
+                          struct lttng_event *event,
+                          struct lttng_bytecode *filter,
+                          char *filter_expression);
+
+int event_agent_disable(struct ltt_ust_session *usess, struct agent *agt, const char *event_name);
 int event_agent_disable_all(struct ltt_ust_session *usess, struct agent *agt);
 
-int trigger_agent_enable(
-               const struct lttng_trigger *trigger, struct agent *agt);
-int trigger_agent_disable(
-               const struct lttng_trigger *trigger, struct agent *agt);
+int trigger_agent_enable(const struct lttng_trigger *trigger, struct agent *agt);
+int trigger_agent_disable(const struct lttng_trigger *trigger, struct agent *agt);
 
 const char *event_get_default_agent_ust_name(enum lttng_domain_type domain);
 
index ac5c83f4b19775beed137606c483d20dadb3ecd9..ae63ccc06ad7c5b6bff887da22c13b44fe0a3cc0 100644 (file)
@@ -6,13 +6,15 @@
  */
 
 #define _LGPL_SOURCE
-#include <urcu/uatomic.h>
-#include <sys/time.h>
-#include <sys/resource.h>
-#include <stdio.h>
 #include "fd-limit.hpp"
-#include <common/error.hpp>
+
 #include <common/compat/errno.hpp>
+#include <common/error.hpp>
+
+#include <stdio.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <urcu/uatomic.h>
 
 /* total count of fd. */
 static long fd_count;
@@ -35,21 +37,19 @@ int lttng_fd_get(enum lttng_fd_type type, unsigned int nr)
        }
 
        newval = uatomic_add_return(&fd_count, (long) nr);
-       if ((long) (newval * 100)
-                       - (long) (max_nr_fd * fd_threshold[type]) > 0) {
+       if ((long) (newval * 100) - (long) (max_nr_fd * fd_threshold[type]) > 0) {
                uatomic_sub(&fd_count, (long) nr);
                return -EPERM;
        }
        return 0;
 }
 
-void lttng_fd_put(enum lttng_fd_type type __attribute__((unused)),
-               unsigned int nr)
+void lttng_fd_put(enum lttng_fd_type type __attribute__((unused)), unsigned int nr)
 {
        uatomic_sub(&fd_count, (long) nr);
 }
 
-void lttng_fd_init(void)
+void lttng_fd_init()
 {
        struct rlimit rlim;
        int ret;
index 8666cdc009e820f3ef1a8029844b913527c5d879..516129962d8e1dfc0d089e8d824c3c479a19fb66 100644 (file)
@@ -15,6 +15,6 @@ enum lttng_fd_type {
 
 int lttng_fd_get(enum lttng_fd_type type, unsigned int nr);
 void lttng_fd_put(enum lttng_fd_type type, unsigned int nr);
-void lttng_fd_init(void);
+void lttng_fd_init();
 
 #endif /* _LTTNG_FD_LIMIT_H */
index 604092a3b86c9c5352a3ab3cd649f6ad77cc2312..94d002167556a87fe3901359a25d9f28d49c4872 100644 (file)
 namespace lst = lttng::sessiond::trace;
 
 namespace {
-template <class FieldTypeSet>
-bool fields_are_equal(const FieldTypeSet& a, const FieldTypeSet& b)
+template <class FieldTypeContainerType>
+bool fields_are_equal(const FieldTypeContainerType& a, const FieldTypeContainerType& b)
 {
        if (a.size() != b.size()) {
                return false;
        }
 
-       return std::equal(a.cbegin(), a.cend(), b.cbegin(),
-                       [](typename FieldTypeSet::const_reference field_a,
-                                       typename FieldTypeSet::const_reference field_b) {
-                               return *field_a == *field_b;
-                       });
+       return std::equal(a.cbegin(),
+                         a.cend(),
+                         b.cbegin(),
+                         [](typename FieldTypeContainerType::const_reference field_a,
+                            typename FieldTypeContainerType::const_reference field_b) {
+                                 return *field_a == *field_b;
+                         });
 }
 } /* namespace */
 
-lst::type::type(unsigned int in_alignment) : alignment{in_alignment}
+lst::field_location::field_location(lst::field_location::root in_lookup_root,
+                                   lst::field_location::elements in_elements) :
+       root_{ in_lookup_root }, elements_{ std::move(in_elements) }
 {
 }
 
-lst::type::~type()
+bool lst::field_location::operator==(const lst::field_location& other) const noexcept
 {
+       return root_ == other.root_ && elements_ == other.elements_;
 }
 
+lst::type::type(unsigned int in_alignment) : alignment{ in_alignment }
+{
+}
+
+lst::type::~type() = default;
+
 bool lst::type::operator==(const lst::type& other) const noexcept
 {
-       return typeid(*this) == typeid(other) &&
-               alignment == other.alignment &&
+       return typeid(*this) == typeid(other) && alignment == other.alignment &&
                /* defer to concrete type comparison */
                this->_is_equal(other);
 }
@@ -52,8 +62,12 @@ bool lst::type::operator!=(const lst::type& other) const noexcept
 }
 
 lst::field::field(std::string in_name, lst::type::cuptr in_type) :
-       name{std::move(in_name)}, _type{std::move(in_type)}
+       name{ std::move(in_name) }, _type{ std::move(in_type) }
 {
+       if (!_type) {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Invalid type used to create field: field name = `{}`", name));
+       }
 }
 
 void lst::field::accept(lst::field_visitor& visitor) const
@@ -66,27 +80,50 @@ bool lst::field::operator==(const lst::field& other) const noexcept
        return name == other.name && *_type == *other._type;
 }
 
+lst::type::cuptr lst::field::move_type() noexcept
+{
+       return std::move(_type);
+}
+
+const lst::type& lst::field::get_type() const
+{
+       if (_type) {
+               return *_type;
+       } else {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Invalid attempt to access field type after transfer: field name = `{}`",
+                       name));
+       }
+}
+
 lst::integer_type::integer_type(unsigned int in_alignment,
-               enum lst::byte_order in_byte_order,
-               unsigned int in_size,
-               enum lst::integer_type::signedness in_signedness,
-               enum lst::integer_type::base in_base) :
+                               enum lst::byte_order in_byte_order,
+                               unsigned int in_size,
+                               enum lst::integer_type::signedness in_signedness,
+                               enum lst::integer_type::base in_base,
+                               roles in_roles) :
        type(in_alignment),
-       byte_order{in_byte_order},
-       size{in_size},
-       signedness_{in_signedness},
-       base_{in_base}
+       byte_order{ in_byte_order },
+       size{ in_size },
+       signedness_{ in_signedness },
+       base_{ in_base },
+       roles_{ std::move(in_roles) }
+{
+}
+
+lst::type::cuptr lst::integer_type::copy() const
 {
+       return lttng::make_unique<integer_type>(
+               alignment, byte_order, size, signedness_, base_, roles_);
 }
 
-bool lst::integer_type::_is_equal(const type &base_other) const noexcept
+bool lst::integer_type::_is_equal(const typebase_other) const noexcept
 {
        const auto& other = static_cast<decltype(*this)&>(base_other);
 
-       return this->byte_order == other.byte_order &&
-               this->size == other.size &&
-               this->signedness_ == other.signedness_ &&
-               this->base_ == other.base_;
+       return this->byte_order == other.byte_order && this->size == other.size &&
+               this->signedness_ == other.signedness_ && this->base_ == other.base_ &&
+               this->roles_ == other.roles_;
 }
 
 void lst::integer_type::accept(type_visitor& visitor) const
@@ -104,30 +141,35 @@ lst::byte_order lst::type::reverse_byte_order(lst::byte_order byte_order) noexce
 }
 
 lst::floating_point_type::floating_point_type(unsigned int in_alignment,
-               lst::byte_order in_byte_order,
-               unsigned int in_exponent_digits,
-               unsigned int in_mantissa_digits) :
+                                             lst::byte_order in_byte_order,
+                                             unsigned int in_exponent_digits,
+                                             unsigned int in_mantissa_digits) :
        type(in_alignment),
        byte_order(in_byte_order),
-       exponent_digits{in_exponent_digits},
+       exponent_digits{ in_exponent_digits },
        mantissa_digits(in_mantissa_digits)
 {
        /* Allowed (exponent, mantissa) pairs. */
        static const std::set<std::pair<unsigned int, unsigned int>> allowed_pairs{
-                       {5, 11}, /* binary16 */
-                       {8, 24}, /* binary32 */
-                       {11, 53}, /* binary64 */
-                       {15, 113}, /* binary128 */
+               { 5, 11 }, /* binary16 */
+               { 8, 24 }, /* binary32 */
+               { 11, 53 }, /* binary64 */
+               { 15, 113 }, /* binary128 */
        };
 
-       if (allowed_pairs.find({exponent_digits, mantissa_digits}) != allowed_pairs.end()) {
+       if (allowed_pairs.find({ exponent_digits, mantissa_digits }) != allowed_pairs.end()) {
                /* mantissa and exponent digits is a valid pair. */
                return;
        }
 
-       LTTNG_THROW_INVALID_ARGUMENT_ERROR(
-                       fmt::format("Invalid exponent/mantissa values provided while creating {}",
-                                       typeid(*this)));
+       LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+               "Invalid exponent/mantissa values provided while creating {}", typeid(*this)));
+}
+
+lst::type::cuptr lst::floating_point_type::copy() const
+{
+       return lttng::make_unique<floating_point_type>(
+               alignment, byte_order, exponent_digits, mantissa_digits);
 }
 
 void lst::floating_point_type::accept(type_visitor& visitor) const
@@ -140,30 +182,51 @@ bool lst::floating_point_type::_is_equal(const type& base_other) const noexcept
        const auto& other = static_cast<decltype(*this)&>(base_other);
 
        return this->byte_order == other.byte_order &&
-                       this->exponent_digits == other.exponent_digits &&
-                       this->mantissa_digits == other.mantissa_digits;
+               this->exponent_digits == other.exponent_digits &&
+               this->mantissa_digits == other.mantissa_digits;
 }
 
 lst::enumeration_type::enumeration_type(unsigned int in_alignment,
-               enum lst::byte_order in_byte_order,
-               unsigned int in_size,
-               enum signedness in_signedness,
-               enum base in_base) :
-       integer_type(in_alignment, in_byte_order, in_size, in_signedness, in_base)
+                                       enum lst::byte_order in_byte_order,
+                                       unsigned int in_size,
+                                       enum signedness in_signedness,
+                                       enum base in_base,
+                                       lst::integer_type::roles in_roles) :
+       integer_type(
+               in_alignment, in_byte_order, in_size, in_signedness, in_base, std::move(in_roles))
 {
 }
 
+/*
+ * Due to a bug in g++ < 7.1, these specializations must be enclosed in the namespaces
+ * rather than using the usual `namespace::namespace::function` notation:
+ * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480.
+ */
 namespace lttng {
 namespace sessiond {
 namespace trace {
 template <>
-void lst::signed_enumeration_type::accept(type_visitor& visitor) const
+void signed_enumeration_type::accept(type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
 
 template <>
-void lst::unsigned_enumeration_type::accept(type_visitor& visitor) const
+void unsigned_enumeration_type::accept(type_visitor& visitor) const
+{
+       visitor.visit(*this);
+}
+
+template <>
+void variant_type<lst::signed_enumeration_type::mapping::range_t::range_integer_t>::accept(
+       lst::type_visitor& visitor) const
+{
+       visitor.visit(*this);
+}
+
+template <>
+void variant_type<lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>::accept(
+       lst::type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
@@ -172,7 +235,7 @@ void lst::unsigned_enumeration_type::accept(type_visitor& visitor) const
 } /* namespace lttng */
 
 lst::array_type::array_type(unsigned int in_alignment, type::cuptr in_element_type) :
-       type(in_alignment), element_type{std::move(in_element_type)}
+       type(in_alignment), element_type{ std::move(in_element_type) }
 {
 }
 
@@ -184,10 +247,9 @@ bool lst::array_type::_is_equal(const type& base_other) const noexcept
 }
 
 lst::static_length_array_type::static_length_array_type(unsigned int in_alignment,
-               type::cuptr in_element_type,
-               uint64_t in_length) :
-       array_type(in_alignment, std::move(in_element_type)),
-       length{in_length}
+                                                       type::cuptr in_element_type,
+                                                       uint64_t in_length) :
+       array_type(in_alignment, std::move(in_element_type)), length{ in_length }
 {
 }
 
@@ -198,16 +260,23 @@ bool lst::static_length_array_type::_is_equal(const type& base_other) const noex
        return array_type::_is_equal(base_other) && this->length == other.length;
 }
 
+lst::type::cuptr lst::static_length_array_type::copy() const
+{
+       return lttng::make_unique<static_length_array_type>(
+               alignment, element_type->copy(), length);
+}
+
 void lst::static_length_array_type::accept(type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
 
-lst::dynamic_length_array_type::dynamic_length_array_type(unsigned int in_alignment,
-               type::cuptr in_element_type,
-               std::string in_length_field_name) :
+lst::dynamic_length_array_type::dynamic_length_array_type(
+       unsigned int in_alignment,
+       type::cuptr in_element_type,
+       lst::field_location in_length_field_location) :
        array_type(in_alignment, std::move(in_element_type)),
-       length_field_name{std::move(in_length_field_name)}
+       length_field_location{ std::move(in_length_field_location) }
 {
 }
 
@@ -216,7 +285,13 @@ bool lst::dynamic_length_array_type::_is_equal(const type& base_other) const noe
        const auto& other = static_cast<decltype(*this)&>(base_other);
 
        return array_type::_is_equal(base_other) &&
-                       this->length_field_name == other.length_field_name;
+               this->length_field_location == other.length_field_location;
+}
+
+lst::type::cuptr lst::dynamic_length_array_type::copy() const
+{
+       return lttng::make_unique<dynamic_length_array_type>(
+               alignment, element_type->copy(), length_field_location);
 }
 
 void lst::dynamic_length_array_type::accept(type_visitor& visitor) const
@@ -224,8 +299,55 @@ void lst::dynamic_length_array_type::accept(type_visitor& visitor) const
        visitor.visit(*this);
 }
 
+lst::static_length_blob_type::static_length_blob_type(unsigned int in_alignment,
+                                                     uint64_t in_length_bytes,
+                                                     roles in_roles) :
+       type(in_alignment), length_bytes{ in_length_bytes }, roles_{ std::move(in_roles) }
+{
+}
+
+bool lst::static_length_blob_type::_is_equal(const type& base_other) const noexcept
+{
+       const auto& other = static_cast<decltype(*this)&>(base_other);
+
+       return length_bytes == other.length_bytes && roles_ == other.roles_;
+}
+
+lst::type::cuptr lst::static_length_blob_type::copy() const
+{
+       return lttng::make_unique<static_length_blob_type>(alignment, length_bytes, roles_);
+}
+
+void lst::static_length_blob_type::accept(type_visitor& visitor) const
+{
+       visitor.visit(*this);
+}
+
+lst::dynamic_length_blob_type::dynamic_length_blob_type(
+       unsigned int in_alignment, lst::field_location in_length_field_location) :
+       type(in_alignment), length_field_location{ std::move(in_length_field_location) }
+{
+}
+
+bool lst::dynamic_length_blob_type::_is_equal(const type& base_other) const noexcept
+{
+       const auto& other = dynamic_cast<decltype(*this)&>(base_other);
+
+       return length_field_location == other.length_field_location;
+}
+
+lst::type::cuptr lst::dynamic_length_blob_type::copy() const
+{
+       return lttng::make_unique<dynamic_length_blob_type>(alignment, length_field_location);
+}
+
+void lst::dynamic_length_blob_type::accept(type_visitor& visitor) const
+{
+       visitor.visit(*this);
+}
+
 lst::string_type::string_type(unsigned int in_alignment, enum encoding in_encoding) :
-       type(in_alignment), encoding_{in_encoding}
+       type(in_alignment), encoding_{ in_encoding }
 {
 }
 
@@ -236,9 +358,10 @@ bool lst::string_type::_is_equal(const type& base_other) const noexcept
        return this->encoding_ == other.encoding_;
 }
 
-lst::static_length_string_type::static_length_string_type(
-               unsigned int in_alignment, enum encoding in_encoding, uint64_t in_length) :
-       string_type(in_alignment, in_encoding), length{in_length}
+lst::static_length_string_type::static_length_string_type(unsigned int in_alignment,
+                                                         enum encoding in_encoding,
+                                                         uint64_t in_length) :
+       string_type(in_alignment, in_encoding), length{ in_length }
 {
 }
 
@@ -249,15 +372,22 @@ bool lst::static_length_string_type::_is_equal(const type& base_other) const noe
        return string_type::_is_equal(base_other) && this->length == other.length;
 }
 
+lst::type::cuptr lst::static_length_string_type::copy() const
+{
+       return lttng::make_unique<static_length_string_type>(alignment, encoding_, length);
+}
+
 void lst::static_length_string_type::accept(type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
 
-lst::dynamic_length_string_type::dynamic_length_string_type(unsigned int in_alignment,
-               enum encoding in_encoding,
-               std::string in_length_field_name) :
-       string_type(in_alignment, in_encoding), length_field_name{std::move(in_length_field_name)}
+lst::dynamic_length_string_type::dynamic_length_string_type(
+       unsigned int in_alignment,
+       enum encoding in_encoding,
+       field_location in_length_field_location) :
+       string_type(in_alignment, in_encoding),
+       length_field_location{ std::move(in_length_field_location) }
 {
 }
 
@@ -266,7 +396,13 @@ bool lst::dynamic_length_string_type::_is_equal(const type& base_other) const no
        const auto& other = static_cast<decltype(*this)&>(base_other);
 
        return string_type::_is_equal(base_other) &&
-                       this->length_field_name == other.length_field_name;
+               this->length_field_location == other.length_field_location;
+}
+
+lst::type::cuptr lst::dynamic_length_string_type::copy() const
+{
+       return lttng::make_unique<dynamic_length_string_type>(
+               alignment, encoding_, length_field_location);
 }
 
 void lst::dynamic_length_string_type::accept(type_visitor& visitor) const
@@ -275,51 +411,47 @@ void lst::dynamic_length_string_type::accept(type_visitor& visitor) const
 }
 
 lst::null_terminated_string_type::null_terminated_string_type(unsigned int in_alignment,
-               enum encoding in_encoding) :
+                                                             enum encoding in_encoding) :
        string_type(in_alignment, in_encoding)
 {
 }
 
+lst::type::cuptr lst::null_terminated_string_type::copy() const
+{
+       return lttng::make_unique<null_terminated_string_type>(alignment, encoding_);
+}
+
 void lst::null_terminated_string_type::accept(type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
 
 lst::structure_type::structure_type(unsigned int in_alignment, fields in_fields) :
-       type(in_alignment), _fields{std::move(in_fields)}
+       type(in_alignment), fields_{ std::move(in_fields) }
 {
 }
 
 bool lst::structure_type::_is_equal(const type& base_other) const noexcept
 {
-       const auto &other = static_cast<decltype(*this)&>(base_other);
+       const autoother = static_cast<decltype(*this)&>(base_other);
 
-       return fields_are_equal(this->_fields, other._fields);
+       return fields_are_equal(this->fields_, other.fields_);
 }
 
-void lst::structure_type::accept(type_visitor& visitor) const
+lst::type::cuptr lst::structure_type::copy() const
 {
-       visitor.visit(*this);
-}
+       structure_type::fields copy_of_fields;
 
-lst::variant_type::variant_type(unsigned int in_alignment,
-               std::string in_tag_name,
-               choices in_choices) :
-       type(in_alignment),
-       tag_name{std::move(in_tag_name)},
-       _choices{std::move(in_choices)}
-{
-}
-
-bool lst::variant_type::_is_equal(const type& base_other) const noexcept
-{
-       const auto &other = static_cast<decltype(*this)&>(base_other);
+       copy_of_fields.reserve(fields_.size());
+       for (const auto& field : fields_) {
+               copy_of_fields.emplace_back(
+                       lttng::make_unique<lst::field>(field->name, field->get_type().copy()));
+       }
 
-       return this->tag_name == other.tag_name &&
-                       fields_are_equal(this->_choices, other._choices);
+       return lttng::make_unique<structure_type>(alignment, std::move(copy_of_fields));
 }
 
-void lst::variant_type::accept(type_visitor& visitor) const
+void lst::structure_type::accept(type_visitor& visitor) const
 {
        visitor.visit(*this);
 }
index f66fdbe7f440dc3c51a237c58fa75977002d84c6..5180574a1c0cb721aa175cec0d818e7481cd9ddf 100644 (file)
@@ -8,15 +8,17 @@
 #ifndef LTTNG_FIELD_H
 #define LTTNG_FIELD_H
 
-#include "trace-class.hpp"
+#include <common/format.hpp>
+#include <common/make-unique.hpp>
 
+#include <vendor/optional.hpp>
+
+#include <algorithm>
 #include <memory>
 #include <string>
 #include <type_traits>
 #include <vector>
 
-#include <vendor/optional.hpp>
-
 namespace lttng {
 namespace sessiond {
 namespace trace {
@@ -24,6 +26,31 @@ namespace trace {
 class field_visitor;
 class type_visitor;
 
+enum class byte_order {
+       BIG_ENDIAN_,
+       LITTLE_ENDIAN_,
+};
+
+class field_location {
+public:
+       enum class root {
+               PACKET_HEADER,
+               PACKET_CONTEXT,
+               EVENT_RECORD_HEADER,
+               EVENT_RECORD_COMMON_CONTEXT,
+               EVENT_RECORD_SPECIFIC_CONTEXT,
+               EVENT_RECORD_PAYLOAD,
+       };
+
+       using elements = std::vector<std::string>;
+
+       field_location(root lookup_root, elements elements);
+       bool operator==(const field_location& other) const noexcept;
+
+       const root root_;
+       const elements elements_;
+};
+
 /*
  * Field, and the various field types, represents fields as exposed by the
  * LTTng tracers. These classes do not attempt to describe the complete spectrum of the CTF
@@ -38,13 +65,22 @@ public:
 
        bool operator==(const type& other) const noexcept;
        bool operator!=(const type& other) const noexcept;
+
        virtual ~type();
+       type(const type&) = delete;
+       type(type&&) = delete;
+       type& operator=(type&&) = delete;
+       type& operator=(const type&) = delete;
+
+       /* Obtain an independent copy of `type`. */
+       virtual type::cuptr copy() const = 0;
+
        virtual void accept(type_visitor& visitor) const = 0;
 
        const unsigned int alignment;
 
 protected:
-       type(unsigned int alignment);
+       explicit type(unsigned int alignment);
 
 private:
        virtual bool _is_equal(const type& rhs) const noexcept = 0;
@@ -52,14 +88,20 @@ private:
 
 class field {
 public:
+       using uptr = std::unique_ptr<field>;
        using cuptr = std::unique_ptr<const field>;
 
        field(std::string name, type::cuptr type);
        void accept(field_visitor& visitor) const;
        bool operator==(const field& other) const noexcept;
 
+       const type& get_type() const;
+       type::cuptr move_type() noexcept;
+
        const std::string name;
-       const type::cuptr _type;
+
+private:
+       type::cuptr _type;
 };
 
 class integer_type : public type {
@@ -76,13 +118,34 @@ public:
                HEXADECIMAL = 16,
        };
 
+       enum class role {
+               DEFAULT_CLOCK_TIMESTAMP,
+               /* Packet header field class specific roles. */
+               DATA_STREAM_CLASS_ID,
+               DATA_STREAM_ID,
+               PACKET_MAGIC_NUMBER,
+               /* Packet context field class specific roles. */
+               DISCARDED_EVENT_RECORD_COUNTER_SNAPSHOT,
+               PACKET_CONTENT_LENGTH,
+               PACKET_END_DEFAULT_CLOCK_TIMESTAMP,
+               PACKET_SEQUENCE_NUMBER,
+               PACKET_TOTAL_LENGTH,
+               /* Event record field class roles. */
+               EVENT_RECORD_CLASS_ID,
+       };
+
+       using roles = std::vector<role>;
+
        integer_type(unsigned int alignment,
-                       byte_order byte_order,
-                       unsigned int size,
-                       signedness signedness,
-                       base base);
+                    byte_order byte_order,
+                    unsigned int size,
+                    signedness signedness,
+                    base base,
+                    roles roles = {});
 
-       virtual void accept(type_visitor& visitor) const override;
+       type::cuptr copy() const override;
+
+       void accept(type_visitor& visitor) const override;
 
        const enum byte_order byte_order;
        const unsigned int size;
@@ -93,37 +156,48 @@ public:
         */
        const signedness signedness_;
        const base base_;
+       const roles roles_;
 
 protected:
-       virtual bool _is_equal(const type& other) const noexcept override;
+       bool _is_equal(const type& other) const noexcept override;
 };
 
 class floating_point_type : public type {
 public:
        floating_point_type(unsigned int alignment,
-                       byte_order byte_order,
-                       unsigned int exponent_digits,
-                       unsigned int mantissa_digits);
+                           byte_order byte_order,
+                           unsigned int exponent_digits,
+                           unsigned int mantissa_digits);
+
+       type::cuptr copy() const final;
 
-       virtual void accept(type_visitor& visitor) const override final;
+       void accept(type_visitor& visitor) const final;
 
        const enum byte_order byte_order;
        const unsigned int exponent_digits;
        const unsigned int mantissa_digits;
 
 private:
-       virtual bool _is_equal(const type& other) const noexcept override final;
+       bool _is_equal(const type& other) const noexcept final;
 };
 
 class enumeration_type : public integer_type {
+public:
+       ~enumeration_type() override = default;
+       enumeration_type(const enumeration_type&) = delete;
+       enumeration_type(enumeration_type&&) = delete;
+       enumeration_type& operator=(enumeration_type&&) = delete;
+       enumeration_type& operator=(const enumeration_type&) = delete;
+
 protected:
        enumeration_type(unsigned int alignment,
-                       enum byte_order byte_order,
-                       unsigned int size,
-                       enum signedness signedness,
-                       enum base base);
+                        enum byte_order byte_order,
+                        unsigned int size,
+                        enum signedness signedness,
+                        enum base base,
+                        integer_type::roles roles = {});
 
-       virtual void accept(type_visitor& visitor) const = 0;
+       void accept(type_visitor& visitor) const override = 0;
 };
 
 namespace details {
@@ -133,7 +207,7 @@ public:
        using range_integer_t = MappingIntegerType;
 
        enumeration_mapping_range(MappingIntegerType in_begin, MappingIntegerType in_end) :
-               begin{in_begin}, end{in_end}
+               begin{ in_begin }, end{ in_end }
        {
        }
 
@@ -152,23 +226,33 @@ class enumeration_mapping {
 public:
        using range_t = enumeration_mapping_range<MappingIntegerType>;
 
-       enumeration_mapping(const enumeration_mapping<MappingIntegerType>& other) = delete;
-       enumeration_mapping(const enumeration_mapping<MappingIntegerType>&& other) :
-               name{std::move(other.name)}, range{other.range}
+       enumeration_mapping(std::string in_name, MappingIntegerType value) :
+               name{ std::move(in_name) }, range{ value, value }
        {
        }
 
-       /* Mapping with an implicit value. */
-       enumeration_mapping(std::string in_name) : name{std::move(in_name)}
+       enumeration_mapping(std::string in_name, range_t in_range) :
+               name{ std::move(in_name) }, range{ in_range }
        {
        }
 
-       enumeration_mapping(std::string in_name, range_t in_range) : name{std::move(in_name)}, range{in_range}
+       enumeration_mapping(const enumeration_mapping<MappingIntegerType>& other) = default;
+       enumeration_mapping(enumeration_mapping<MappingIntegerType>&& other) noexcept :
+               name{ std::move(other.name) }, range{ other.range }
        {
        }
 
+       enumeration_mapping& operator=(enumeration_mapping&&) = delete;
+       enumeration_mapping& operator=(const enumeration_mapping&) = delete;
+       ~enumeration_mapping() = default;
+
        const std::string name;
-       const nonstd::optional<range_t> range;
+       /*
+        * Only one range per mapping is supported for the moment as
+        * the tracers (and CTF 1.8) can't express multiple ranges per
+        * mapping, which is allowed by CTF 2.
+        */
+       const range_t range;
 };
 
 template <class MappingIntegerType>
@@ -179,42 +263,51 @@ bool operator==(const enumeration_mapping<MappingIntegerType>& lhs,
 }
 } /* namespace details */
 
-template <class MappingIntegerType>
+template <typename MappingIntegerType>
 class typed_enumeration_type : public enumeration_type {
 public:
        using mapping = details::enumeration_mapping<MappingIntegerType>;
        using mappings = std::vector<mapping>;
 
        static_assert(std::is_integral<MappingIntegerType>::value &&
-                                       sizeof(MappingIntegerType) == 8,
-                       "MappingIntegerType must be either int64_t or uint64_t");
+                             sizeof(MappingIntegerType) == 8,
+                     "MappingIntegerType must be either int64_t or uint64_t");
 
        typed_enumeration_type(unsigned int in_alignment,
-                       enum byte_order in_byte_order,
-                       unsigned int in_size,
-                       enum signedness in_signedness,
-                       enum base in_base,
-                       const std::shared_ptr<const mappings>& in_mappings) :
+                              enum byte_order in_byte_order,
+                              unsigned int in_size,
+                              enum base in_base,
+                              const std::shared_ptr<const mappings>& in_mappings,
+                              integer_type::roles in_roles = {}) :
                enumeration_type(in_alignment,
-                               in_byte_order,
-                               in_size,
-                               in_signedness,
-                               in_base),
-               _mappings{std::move(in_mappings)}
+                                in_byte_order,
+                                in_size,
+                                std::is_signed<MappingIntegerType>::value ?
+                                        integer_type::signedness::SIGNED :
+                                        integer_type::signedness::UNSIGNED,
+                                in_base,
+                                std::move(in_roles)),
+               mappings_{ std::move(in_mappings) }
        {
        }
 
-       virtual void accept(type_visitor& visitor) const override final;
+       type::cuptr copy() const override
+       {
+               return lttng::make_unique<typed_enumeration_type<MappingIntegerType>>(
+                       alignment, byte_order, size, base_, mappings_, roles_);
+       }
+
+       void accept(type_visitor& visitor) const final;
 
-       const std::shared_ptr<const mappings> _mappings;
+       const std::shared_ptr<const mappings> mappings_;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final
+       bool _is_equal(const type& base_other) const noexcept final
        {
-               const auto& other = static_cast<const typed_enumeration_type<MappingIntegerType>&>(
-                               base_other);
+               const auto& other =
+                       static_cast<const typed_enumeration_type<MappingIntegerType>&>(base_other);
 
-               return integer_type::_is_equal(base_other) && *this->_mappings == *other._mappings;
+               return integer_type::_is_equal(base_other) && *this->mappings_ == *other.mappings_;
        }
 };
 
@@ -229,35 +322,75 @@ public:
        const type::cuptr element_type;
 
 protected:
-       virtual bool _is_equal(const type& base_other) const noexcept override;
+       bool _is_equal(const type& base_other) const noexcept override;
 };
 
 class static_length_array_type : public array_type {
 public:
        static_length_array_type(unsigned int alignment,
-                       type::cuptr element_type,
-                       uint64_t in_length);
+                                type::cuptr element_type,
+                                uint64_t in_length);
+
+       type::cuptr copy() const final;
 
-       virtual void accept(type_visitor& visitor) const override final;
+       void accept(type_visitor& visitor) const final;
 
        const uint64_t length;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       bool _is_equal(const type& base_other) const noexcept final;
 };
 
 class dynamic_length_array_type : public array_type {
 public:
        dynamic_length_array_type(unsigned int alignment,
-                       type::cuptr element_type,
-                       std::string length_field_name);
+                                 type::cuptr element_type,
+                                 field_location length_field_location);
 
-       virtual void accept(type_visitor& visitor) const override final;
+       type::cuptr copy() const final;
 
-       const std::string length_field_name;
+       void accept(type_visitor& visitor) const final;
+
+       const field_location length_field_location;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       bool _is_equal(const type& base_other) const noexcept final;
+};
+
+class static_length_blob_type : public type {
+public:
+       enum class role {
+               /* Packet header field class specific role. */
+               METADATA_STREAM_UUID,
+       };
+
+       using roles = std::vector<role>;
+
+       static_length_blob_type(unsigned int alignment, uint64_t in_length_bytes, roles roles = {});
+
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
+
+       const uint64_t length_bytes;
+       const roles roles_;
+
+private:
+       bool _is_equal(const type& base_other) const noexcept final;
+};
+
+class dynamic_length_blob_type : public type {
+public:
+       dynamic_length_blob_type(unsigned int alignment, field_location length_field_location);
+
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
+
+       const field_location length_field_location;
+
+private:
+       bool _is_equal(const type& base_other) const noexcept final;
 };
 
 class string_type : public type {
@@ -277,38 +410,48 @@ public:
        const encoding encoding_;
 
 protected:
-       virtual bool _is_equal(const type& base_other) const noexcept override;
+       bool _is_equal(const type& base_other) const noexcept override;
 };
 
 class static_length_string_type : public string_type {
 public:
-       static_length_string_type(
-                       unsigned int alignment, enum encoding in_encoding, uint64_t length);
-       virtual void accept(type_visitor& visitor) const override final;
+       static_length_string_type(unsigned int alignment,
+                                 enum encoding in_encoding,
+                                 uint64_t length);
+
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
 
        const uint64_t length;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       bool _is_equal(const type& base_other) const noexcept final;
 };
 
 class dynamic_length_string_type : public string_type {
 public:
        dynamic_length_string_type(unsigned int alignment,
-                       enum encoding in_encoding,
-                       std::string length_field_name);
-       virtual void accept(type_visitor& visitor) const override final;
+                                  enum encoding in_encoding,
+                                  field_location length_field_location);
 
-       const std::string length_field_name;
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
+
+       const field_location length_field_location;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       bool _is_equal(const type& base_other) const noexcept final;
 };
 
 class null_terminated_string_type : public string_type {
 public:
        null_terminated_string_type(unsigned int alignment, enum encoding in_encoding);
-       virtual void accept(type_visitor& visitor) const override final;
+
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
 };
 
 class structure_type : public type {
@@ -317,32 +460,92 @@ public:
 
        structure_type(unsigned int alignment, fields in_fields);
 
-       virtual void accept(type_visitor& visitor) const override final;
+       type::cuptr copy() const final;
+
+       void accept(type_visitor& visitor) const final;
 
-       const fields _fields;
+       const fields fields_;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       bool _is_equal(const type& base_other) const noexcept final;
 };
 
+template <typename MappingIntegerType>
 class variant_type : public type {
+       static_assert(
+               std::is_same<MappingIntegerType,
+                            unsigned_enumeration_type::mapping::range_t::range_integer_t>::value ||
+                       std::is_same<
+                               MappingIntegerType,
+                               signed_enumeration_type::mapping::range_t::range_integer_t>::value,
+               "Variant mapping integer type must be one of those allowed by typed_enumeration_type");
+
 public:
-       using choices = std::vector<field::cuptr>;
+       using choice =
+               std::pair<const details::enumeration_mapping<MappingIntegerType>, type::cuptr>;
+       using choices = std::vector<choice>;
+
+       variant_type(unsigned int in_alignment,
+                    field_location in_selector_field_location,
+                    choices in_choices) :
+               type(in_alignment),
+               selector_field_location{ std::move(in_selector_field_location) },
+               choices_{ std::move(in_choices) }
+       {
+       }
+
+       type::cuptr copy() const final
+       {
+               choices copy_of_choices;
+
+               copy_of_choices.reserve(choices_.size());
+               for (const auto& current_choice : choices_) {
+                       copy_of_choices.emplace_back(current_choice.first,
+                                                    current_choice.second->copy());
+               }
 
-       variant_type(unsigned int alignment, std::string tag_name, choices in_choices);
+               return lttng::make_unique<variant_type<MappingIntegerType>>(
+                       alignment, selector_field_location, std::move(copy_of_choices));
+       }
 
-       virtual void accept(type_visitor& visitor) const override final;
+       void accept(type_visitor& visitor) const final;
 
-       const std::string tag_name;
-       const choices _choices;
+       const field_location selector_field_location;
+       const choices choices_;
 
 private:
-       virtual bool _is_equal(const type& base_other) const noexcept override final;
+       static bool _choices_are_equal(const choices& a, const choices& b)
+       {
+               if (a.size() != b.size()) {
+                       return false;
+               }
+
+               return std::equal(a.cbegin(),
+                                 a.cend(),
+                                 b.cbegin(),
+                                 [](const choice& choice_a, const choice& choice_b) {
+                                         return choice_a.first == choice_b.first &&
+                                                 *choice_a.second == *choice_b.second;
+                                 });
+       }
+
+       bool _is_equal(const type& base_other) const noexcept final
+       {
+               const auto& other = static_cast<decltype(*this)&>(base_other);
+
+               return selector_field_location == other.selector_field_location &&
+                       _choices_are_equal(choices_, other.choices_);
+       }
 };
 
 class field_visitor {
 public:
        virtual ~field_visitor() = default;
+       field_visitor(field_visitor&&) = delete;
+       field_visitor(const field_visitor&) = delete;
+       field_visitor& operator=(const field_visitor&) = delete;
+       field_visitor& operator=(field_visitor&&) = delete;
+
        virtual void visit(const field& field) = 0;
 
 protected:
@@ -352,17 +555,29 @@ protected:
 class type_visitor {
 public:
        virtual ~type_visitor() = default;
+       type_visitor(type_visitor&&) = delete;
+       type_visitor(const type_visitor&) = delete;
+       type_visitor& operator=(const type_visitor&) = delete;
+       type_visitor& operator=(type_visitor&&) = delete;
+
        virtual void visit(const integer_type& type) = 0;
        virtual void visit(const floating_point_type& type) = 0;
        virtual void visit(const signed_enumeration_type& type) = 0;
        virtual void visit(const unsigned_enumeration_type& type) = 0;
        virtual void visit(const static_length_array_type& type) = 0;
        virtual void visit(const dynamic_length_array_type& type) = 0;
+       virtual void visit(const static_length_blob_type& type) = 0;
+       virtual void visit(const dynamic_length_blob_type& type) = 0;
        virtual void visit(const null_terminated_string_type& type) = 0;
        virtual void visit(const static_length_string_type& type) = 0;
        virtual void visit(const dynamic_length_string_type& type) = 0;
        virtual void visit(const structure_type& type) = 0;
-       virtual void visit(const variant_type& type) = 0;
+       virtual void
+       visit(const variant_type<signed_enumeration_type::mapping::range_t::range_integer_t>&
+                     type) = 0;
+       virtual void
+       visit(const variant_type<unsigned_enumeration_type::mapping::range_t::range_integer_t>&
+                     type) = 0;
 
 protected:
        type_visitor() = default;
@@ -372,4 +587,94 @@ protected:
 } /* namespace sessiond */
 } /* namespace lttng */
 
+/*
+ * Field formatters for libfmt.
+ *
+ * Due to a bug in g++ < 7.1, this specialization must be enclosed in the fmt namespace,
+ * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480.
+ */
+namespace fmt {
+template <>
+struct formatter<lttng::sessiond::trace::field_location> : formatter<std::string> {
+       template <typename FormatContextType>
+       typename FormatContextType::iterator
+       format(const lttng::sessiond::trace::field_location& location, FormatContextType& ctx)
+       {
+               std::string location_str{ "[" };
+
+               switch (location.root_) {
+               case lttng::sessiond::trace::field_location::root::PACKET_HEADER:
+                       location_str += "\"packet-header\"";
+                       break;
+               case lttng::sessiond::trace::field_location::root::PACKET_CONTEXT:
+                       location_str += "\"packet-context\"";
+                       break;
+               case lttng::sessiond::trace::field_location::root::EVENT_RECORD_HEADER:
+                       location_str += "\"event-record-header\"";
+                       break;
+               case lttng::sessiond::trace::field_location::root::EVENT_RECORD_COMMON_CONTEXT:
+                       location_str += "\"event-record-common-context\"";
+                       break;
+               case lttng::sessiond::trace::field_location::root::EVENT_RECORD_SPECIFIC_CONTEXT:
+                       location_str += "\"event-record-specific-context\"";
+                       break;
+               case lttng::sessiond::trace::field_location::root::EVENT_RECORD_PAYLOAD:
+                       location_str += "\"event-record-payload\"";
+                       break;
+               }
+
+               for (const auto& name : location.elements_) {
+                       location_str += ", \"" + name + "\"";
+               }
+
+               location_str += "]";
+               return format_to(ctx.out(), location_str);
+       }
+};
+
+namespace details {
+template <typename MappingIntegerType>
+::std::string format_mapping_range(typename lttng::sessiond::trace::typed_enumeration_type<
+                                  MappingIntegerType>::mapping::range_t range)
+{
+       if (range.begin == range.end) {
+               return ::lttng::format("[{}]", range.begin);
+       } else {
+               return ::lttng::format("[{}, {}]", range.begin, range.end);
+       }
+}
+} /* namespace details */
+
+template <>
+struct formatter<typename lttng::sessiond::trace::signed_enumeration_type::mapping::range_t>
+       : formatter<std::string> {
+       template <typename FormatContextType>
+       typename FormatContextType::iterator
+       format(typename lttng::sessiond::trace::signed_enumeration_type::mapping::range_t range,
+              FormatContextType& ctx)
+       {
+               return format_to(ctx.out(),
+                                details::format_mapping_range<
+                                        lttng::sessiond::trace::signed_enumeration_type::mapping::
+                                                range_t::range_integer_t>(range));
+       }
+};
+
+template <>
+struct formatter<typename lttng::sessiond::trace::unsigned_enumeration_type::mapping::range_t>
+       : formatter<std::string> {
+       template <typename FormatContextType>
+       typename FormatContextType::iterator
+       format(typename lttng::sessiond::trace::unsigned_enumeration_type::mapping::range_t range,
+              FormatContextType& ctx)
+       {
+               return format_to(ctx.out(),
+                                details::format_mapping_range<
+                                        lttng::sessiond::trace::unsigned_enumeration_type::
+                                                mapping::range_t::range_integer_t>(range));
+       }
+};
+
+} /* namespace fmt */
+
 #endif /* LTTNG_FIELD_H */
index c8710d62abeac9764e31c2b04d3d98139ba77d5d..ad9a8bf850d461fc217ed3381ded5c3819661770 100644 (file)
@@ -8,6 +8,7 @@
  */
 
 #include "lttng-sessiond.hpp"
+
 #include <common/uuid.hpp>
 
 lttng_uuid the_sessiond_uuid;
@@ -20,14 +21,15 @@ long the_page_size;
 struct health_app *the_health_sessiond;
 
 struct notification_thread_handle *the_notification_thread_handle;
+lttng::sessiond::rotation_thread::uptr the_rotation_thread_handle;
 
-struct lttng_ht *the_agent_apps_ht_by_sock = NULL;
-struct lttng_ht *the_trigger_agents_ht_by_domain = NULL;
+struct lttng_ht *the_agent_apps_ht_by_sock = nullptr;
+struct lttng_ht *the_trigger_agents_ht_by_domain = nullptr;
 
 struct lttng_kernel_abi_tracer_version the_kernel_tracer_version;
 struct lttng_kernel_abi_tracer_abi_version the_kernel_tracer_abi_version;
 
-int the_kernel_poll_pipe[2] = {-1, -1};
+int the_kernel_poll_pipe[2] = { -1, -1 };
 
 pid_t the_ppid;
 pid_t the_child_ppid;
@@ -41,7 +43,7 @@ consumer_data the_ustconsumer32_data(LTTNG_CONSUMER32_UST);
 enum consumerd_state the_ust_consumerd_state;
 enum consumerd_state the_kernel_consumerd_state;
 
-static void __attribute__((constructor)) init_sessiond_uuid(void)
+static void __attribute__((constructor)) init_sessiond_uuid()
 {
        if (lttng_uuid_generate(the_sessiond_uuid)) {
                ERR("Failed to generate a session daemon UUID");
index 52f38e2d89df47145b5155e82644261c607ab2a4..453b87e5bb68f2fb9b400724a3062248fb9be701 100644 (file)
@@ -9,20 +9,21 @@
  */
 
 #include <lttng/health-internal.hpp>
+
 #include <stdbool.h>
 
 enum health_type_sessiond {
-       HEALTH_SESSIOND_TYPE_CMD                = 0,
-       HEALTH_SESSIOND_TYPE_APP_MANAGE         = 1,
-       HEALTH_SESSIOND_TYPE_APP_REG            = 2,
-       HEALTH_SESSIOND_TYPE_KERNEL             = 3,
-       HEALTH_SESSIOND_TYPE_CONSUMER           = 4,
-       HEALTH_SESSIOND_TYPE_APP_MANAGE_NOTIFY  = 6,
-       HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH   = 7,
-       HEALTH_SESSIOND_TYPE_NOTIFICATION       = 8,
-       HEALTH_SESSIOND_TYPE_ROTATION           = 9,
-       HEALTH_SESSIOND_TYPE_TIMER              = 10,
-       HEALTH_SESSIOND_TYPE_ACTION_EXECUTOR    = 11,
+       HEALTH_SESSIOND_TYPE_CMD = 0,
+       HEALTH_SESSIOND_TYPE_APP_MANAGE = 1,
+       HEALTH_SESSIOND_TYPE_APP_REG = 2,
+       HEALTH_SESSIOND_TYPE_KERNEL = 3,
+       HEALTH_SESSIOND_TYPE_CONSUMER = 4,
+       HEALTH_SESSIOND_TYPE_APP_MANAGE_NOTIFY = 6,
+       HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH = 7,
+       HEALTH_SESSIOND_TYPE_NOTIFICATION = 8,
+       HEALTH_SESSIOND_TYPE_ROTATION = 9,
+       HEALTH_SESSIOND_TYPE_TIMER = 10,
+       HEALTH_SESSIOND_TYPE_ACTION_EXECUTOR = 11,
 
        NR_HEALTH_SESSIOND_TYPES,
 };
@@ -30,6 +31,6 @@ enum health_type_sessiond {
 /* Application health monitoring */
 extern struct health_app *the_health_sessiond;
 
-bool launch_health_management_thread(void);
+bool launch_health_management_thread();
 
 #endif /* HEALTH_SESSIOND_H */
index 0735907a26ad3ae67d9fc26d6f543e8f7f0c98fa..4aa4275629e0d92fea6014c3ad5f304bcb9ed075 100644 (file)
@@ -6,16 +6,19 @@
  *
  */
 
-#include "lttng-sessiond.hpp"
 #include "health-sessiond.hpp"
-#include <common/macros.hpp>
+#include "lttng-sessiond.hpp"
+#include "thread.hpp"
+#include "utils.hpp"
+
 #include <common/error.hpp>
-#include <common/utils.hpp>
+#include <common/macros.hpp>
 #include <common/pipe.hpp>
+#include <common/utils.hpp>
+
+#include <fcntl.h>
 #include <inttypes.h>
 #include <sys/stat.h>
-#include "utils.hpp"
-#include "thread.hpp"
 
 namespace {
 struct thread_notifiers {
@@ -24,15 +27,13 @@ struct thread_notifiers {
 };
 } /* namespace */
 
-static
-void mark_thread_as_ready(struct thread_notifiers *notifiers)
+static void mark_thread_as_ready(struct thread_notifiers *notifiers)
 {
        DBG("Marking health management thread as ready");
        sem_post(&notifiers->ready);
 }
 
-static
-void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
+static void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
 {
        DBG("Waiting for health management thread to be ready");
        sem_wait(&notifiers->ready);
@@ -54,15 +55,14 @@ static void cleanup_health_management_thread(void *data)
 static void *thread_manage_health(void *data)
 {
        const bool is_root = (getuid() == 0);
-       int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int sock = -1, new_sock = -1, ret, i, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct health_comm_msg msg;
        struct health_comm_reply reply;
        /* Thread-specific quit pipe. */
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(
-                       notifiers->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
 
        DBG("[thread] Manage health check started");
 
@@ -70,7 +70,7 @@ static void *thread_manage_health(void *data)
 
        /*
         * Created with a size of two for:
-        *   - client socket
+        *   - health client socket
         *   - thread quit pipe
         */
        ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
@@ -103,9 +103,10 @@ static void *thread_manage_health(void *data)
                }
 
                ret = chmod(the_config.health_unix_sock_path.value,
-                               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+                           S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
                if (ret < 0) {
-                       ERR("Unable to set permissions on %s", the_config.health_unix_sock_path.value);
+                       ERR("Unable to set permissions on %s",
+                           the_config.health_unix_sock_path.value);
                        PERROR("chmod");
                        goto error;
                }
@@ -122,23 +123,23 @@ static void *thread_manage_health(void *data)
                goto error;
        }
 
-       ret = lttng_poll_add(&events, quit_pipe_read_fd, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                goto error;
        }
 
-       /* Add the application registration socket */
+       /* Add the health client socket. */
        ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLPRI);
        if (ret < 0) {
                goto error;
        }
 
        mark_thread_as_ready(notifiers);
-       while (1) {
+       while (true) {
                DBG("Health check ready");
 
                /* Infinite blocking call, waiting for transmission */
-restart:
+       restart:
                ret = lttng_poll_wait(&events, -1);
                if (ret < 0) {
                        /*
@@ -154,25 +155,26 @@ restart:
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
-
-                       /* Event on the registration socket */
-                       if (pollfd == sock) {
-                               if (revents & LPOLLIN) {
-                                       continue;
-                               } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-                                       ERR("Health socket poll error");
-                                       goto error;
-                               } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
-                                       goto error;
-                               }
-                       } else {
-                               /* Event on the thread's quit pipe. */
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
+
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
+
+                       /* Event on the health client socket. */
+                       if (revents & LPOLLIN) {
+                               continue;
+                       } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
+                               ERR("Health socket poll error");
+                               goto error;
+                       } else {
+                               ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                               goto error;
+                       }
                }
 
                new_sock = lttcomm_accept_unix_sock(sock);
@@ -187,7 +189,7 @@ restart:
                (void) utils_set_fd_cloexec(new_sock);
 
                DBG("Receiving data from client for health...");
-               ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
+               ret = lttcomm_recv_unix_sock(new_sock, (void *) &msg, sizeof(msg));
                if (ret <= 0) {
                        DBG("Nothing recv() from client... continuing");
                        ret = close(new_sock);
@@ -212,8 +214,7 @@ restart:
 
                DBG2("Health check return value %" PRIx64, reply.ret_code);
 
-               ret = lttcomm_send_unix_sock(new_sock, (void *) &reply,
-                               sizeof(reply));
+               ret = lttcomm_send_unix_sock(new_sock, (void *) &reply, sizeof(reply));
                if (ret < 0) {
                        ERR("Failed to send health data back to client");
                }
@@ -241,18 +242,18 @@ error:
 
        lttng_poll_clean(&events);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_health_management_thread(void *data)
 {
-       struct thread_notifiers *notifiers = ( thread_notifiers *) data;
+       struct thread_notifiers *notifiers = (thread_notifiers *) data;
        const int write_fd = lttng_pipe_get_writefd(notifiers->quit_pipe);
 
        return notify_thread_pipe(write_fd) == 1;
 }
 
-bool launch_health_management_thread(void)
+bool launch_health_management_thread()
 {
        struct thread_notifiers *notifiers;
        struct lttng_thread *thread;
@@ -268,10 +269,10 @@ bool launch_health_management_thread(void)
                goto error;
        }
        thread = lttng_thread_create("Health management",
-                       thread_manage_health,
-                       shutdown_health_management_thread,
-                       cleanup_health_management_thread,
-                       notifiers);
+                                    thread_manage_health,
+                                    shutdown_health_management_thread,
+                                    cleanup_health_management_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index d91436256cb6903c4efa5b702dc6db161ece17e5..54a642b7441b4bd956f9778b98441f5a461bd3fb 100644 (file)
 /*
  * Compatible lttng-modules version.
  */
-#define KERN_MODULES_PRE_MAJOR     1
-#define KERN_MODULES_PRE_MINOR     9
+#define KERN_MODULES_PRE_MAJOR 1
+#define KERN_MODULES_PRE_MINOR 9
 
-#define KERN_MODULES_MAJOR         2
-#define KERN_MODULES_MINOR         0
+#define KERN_MODULES_MAJOR 2
+#define KERN_MODULES_MINOR 0
 
 enum kernel_module_property_load_policy {
        KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED = 0,
@@ -24,7 +24,7 @@ enum kernel_module_property_load_policy {
 
 struct kern_modules_param {
        char *name;
-    enum kernel_module_property_load_policy load_policy;
+       enum kernel_module_property_load_policy load_policy;
        bool loaded;
 };
 
index b51b56c3e772e2e1a213853266f10b79f30591ab..b5ccd47dd27ac2947e40b944c3f1ea778fe8f61f 100644 (file)
@@ -6,59 +6,61 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <inttypes.h>
-
-#include <common/common.hpp>
-#include <common/defaults.hpp>
-#include <common/compat/string.hpp>
-
 #include "consumer.hpp"
 #include "health-sessiond.hpp"
 #include "kernel-consumer.hpp"
+#include "lttng-sessiond.hpp"
 #include "notification-thread-commands.hpp"
 #include "session.hpp"
-#include "lttng-sessiond.hpp"
 
-static char *create_channel_path(struct consumer_output *consumer,
-               size_t *consumer_path_offset)
+#include <common/common.hpp>
+#include <common/compat/string.hpp>
+#include <common/defaults.hpp>
+#include <common/urcu.hpp>
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static char *create_channel_path(struct consumer_output *consumer, size_t *consumer_path_offset)
 {
        int ret;
        char tmp_path[PATH_MAX];
-       char *pathname = NULL;
+       char *pathname = nullptr;
 
        LTTNG_ASSERT(consumer);
 
        /* Get the right path name destination */
        if (consumer->type == CONSUMER_DST_LOCAL ||
-                       (consumer->type == CONSUMER_DST_NET &&
-                                       consumer->relay_major_version == 2 &&
-                                       consumer->relay_minor_version >= 11)) {
+           (consumer->type == CONSUMER_DST_NET && consumer->relay_major_version == 2 &&
+            consumer->relay_minor_version >= 11)) {
                pathname = strdup(consumer->domain_subdir);
                if (!pathname) {
                        PERROR("Failed to copy domain subdirectory string %s",
-                                       consumer->domain_subdir);
+                              consumer->domain_subdir);
                        goto error;
                }
                *consumer_path_offset = strlen(consumer->domain_subdir);
                DBG3("Kernel local consumer trace path relative to current trace chunk: \"%s\"",
-                               pathname);
+                    pathname);
        } else {
                /* Network output, relayd < 2.11. */
-               ret = snprintf(tmp_path, sizeof(tmp_path), "%s%s",
-                               consumer->dst.net.base_dir,
-                               consumer->domain_subdir);
+               ret = snprintf(tmp_path,
+                              sizeof(tmp_path),
+                              "%s%s",
+                              consumer->dst.net.base_dir,
+                              consumer->domain_subdir);
                if (ret < 0) {
                        PERROR("snprintf kernel metadata path");
                        goto error;
                } else if (ret >= sizeof(tmp_path)) {
                        ERR("Kernel channel path exceeds the maximal allowed length of of %zu bytes (%i bytes required) with path \"%s%s\"",
-                                       sizeof(tmp_path), ret,
-                                       consumer->dst.net.base_dir,
-                                       consumer->domain_subdir);
+                           sizeof(tmp_path),
+                           ret,
+                           consumer->dst.net.base_dir,
+                           consumer->domain_subdir);
                        goto error;
                }
                pathname = lttng_strndup(tmp_path, sizeof(tmp_path));
@@ -74,27 +76,27 @@ static char *create_channel_path(struct consumer_output *consumer,
 
 error:
        free(pathname);
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Sending a single channel to the consumer with command ADD_CHANNEL.
  */
-static
-int kernel_consumer_add_channel(struct consumer_socket *sock,
-               struct ltt_kernel_channel *channel,
-               struct ltt_kernel_session *ksession,
-               unsigned int monitor)
+static int kernel_consumer_add_channel(struct consumer_socket *sock,
+                                      struct ltt_kernel_channel *channel,
+                                      struct ltt_kernel_session *ksession,
+                                      unsigned int monitor)
 {
        int ret;
-       char *pathname = NULL;
+       char *pathname = nullptr;
        struct lttcomm_consumer_msg lkm;
        struct consumer_output *consumer;
        enum lttng_error_code status;
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
        struct lttng_channel_extended *channel_attr_extended;
        bool is_local_trace;
        size_t consumer_path_offset = 0;
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Safety net */
        LTTNG_ASSERT(channel);
@@ -102,11 +104,10 @@ int kernel_consumer_add_channel(struct consumer_socket *sock,
        LTTNG_ASSERT(ksession->consumer);
 
        consumer = ksession->consumer;
-       channel_attr_extended = (struct lttng_channel_extended *)
-                       channel->channel->attr.extended.ptr;
+       channel_attr_extended =
+               (struct lttng_channel_extended *) channel->channel->attr.extended.ptr;
 
-       DBG("Kernel consumer adding channel %s to kernel consumer",
-                       channel->channel->name);
+       DBG("Kernel consumer adding channel %s to kernel consumer", channel->channel->name);
        is_local_trace = consumer->net_seq_index == -1ULL;
 
        pathname = create_channel_path(consumer, &consumer_path_offset);
@@ -119,8 +120,7 @@ int kernel_consumer_add_channel(struct consumer_socket *sock,
                enum lttng_trace_chunk_status chunk_status;
                char *pathname_index;
 
-               ret = asprintf(&pathname_index, "%s/" DEFAULT_INDEX_DIR,
-                               pathname);
+               ret = asprintf(&pathname_index, "%s/" DEFAULT_INDEX_DIR, pathname);
                if (ret < 0) {
                        ERR("Failed to format channel index directory");
                        ret = -1;
@@ -131,8 +131,8 @@ int kernel_consumer_add_channel(struct consumer_socket *sock,
                 * Create the index subdirectory which will take care
                 * of implicitly creating the channel's path.
                 */
-               chunk_status = lttng_trace_chunk_create_subdirectory(
-                               ksession->current_trace_chunk, pathname_index);
+               chunk_status = lttng_trace_chunk_create_subdirectory(ksession->current_trace_chunk,
+                                                                    pathname_index);
                free(pathname_index);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
@@ -142,21 +142,21 @@ int kernel_consumer_add_channel(struct consumer_socket *sock,
 
        /* Prep channel message structure */
        consumer_init_add_channel_comm_msg(&lkm,
-                       channel->key,
-                       ksession->id,
-                       &pathname[consumer_path_offset],
-                       consumer->net_seq_index,
-                       channel->channel->name,
-                       channel->stream_count,
-                       channel->channel->attr.output,
-                       CONSUMER_CHANNEL_TYPE_DATA,
-                       channel->channel->attr.tracefile_size,
-                       channel->channel->attr.tracefile_count,
-                       monitor,
-                       channel->channel->attr.live_timer_interval,
-                       ksession->is_live_session,
-                       channel_attr_extended->monitor_timer_interval,
-                       ksession->current_trace_chunk);
+                                          channel->key,
+                                          ksession->id,
+                                          &pathname[consumer_path_offset],
+                                          consumer->net_seq_index,
+                                          channel->channel->name,
+                                          channel->stream_count,
+                                          channel->channel->attr.output,
+                                          CONSUMER_CHANNEL_TYPE_DATA,
+                                          channel->channel->attr.tracefile_size,
+                                          channel->channel->attr.tracefile_count,
+                                          monitor,
+                                          channel->channel->attr.live_timer_interval,
+                                          ksession->is_live_session,
+                                          channel_attr_extended->monitor_timer_interval,
+                                          ksession->current_trace_chunk);
 
        health_code_update();
 
@@ -166,16 +166,18 @@ int kernel_consumer_add_channel(struct consumer_socket *sock,
        }
 
        health_code_update();
-       rcu_read_lock();
        session = session_find_by_id(ksession->id);
        LTTNG_ASSERT(session);
        ASSERT_LOCKED(session->lock);
        ASSERT_SESSION_LIST_LOCKED();
 
        status = notification_thread_command_add_channel(the_notification_thread_handle,
-                       session->id, channel->channel->name, channel->key, LTTNG_DOMAIN_KERNEL,
-                       channel->channel->attr.subbuf_size * channel->channel->attr.num_subbuf);
-       rcu_read_unlock();
+                                                        session->id,
+                                                        channel->channel->name,
+                                                        channel->key,
+                                                        LTTNG_DOMAIN_KERNEL,
+                                                        channel->channel->attr.subbuf_size *
+                                                                channel->channel->attr.num_subbuf);
        if (status != LTTNG_OK) {
                ret = -1;
                goto error;
@@ -197,42 +199,42 @@ error:
  * The consumer socket lock must be held by the caller.
  */
 int kernel_consumer_add_metadata(struct consumer_socket *sock,
-               struct ltt_kernel_session *ksession, unsigned int monitor)
+                                struct ltt_kernel_session *ksession,
+                                unsigned int monitor)
 {
        int ret;
        struct lttcomm_consumer_msg lkm;
        struct consumer_output *consumer;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Safety net */
        LTTNG_ASSERT(ksession);
        LTTNG_ASSERT(ksession->consumer);
        LTTNG_ASSERT(sock);
 
-       DBG("Sending metadata %d to kernel consumer",
-                       ksession->metadata_stream_fd);
+       DBG("Sending metadata %d to kernel consumer", ksession->metadata_stream_fd);
 
        /* Get consumer output pointer */
        consumer = ksession->consumer;
 
        /* Prep channel message structure */
        consumer_init_add_channel_comm_msg(&lkm,
-                       ksession->metadata->key,
-                       ksession->id,
-                       "",
-                       consumer->net_seq_index,
-                       ksession->metadata->conf->name,
-                       1,
-                       ksession->metadata->conf->attr.output,
-                       CONSUMER_CHANNEL_TYPE_METADATA,
-                       ksession->metadata->conf->attr.tracefile_size,
-                       ksession->metadata->conf->attr.tracefile_count,
-                       monitor,
-                       ksession->metadata->conf->attr.live_timer_interval,
-                       ksession->is_live_session,
-                       0,
-                       ksession->current_trace_chunk);
+                                          ksession->metadata->key,
+                                          ksession->id,
+                                          "",
+                                          consumer->net_seq_index,
+                                          ksession->metadata->conf->name,
+                                          1,
+                                          ksession->metadata->conf->attr.output,
+                                          CONSUMER_CHANNEL_TYPE_METADATA,
+                                          ksession->metadata->conf->attr.tracefile_size,
+                                          ksession->metadata->conf->attr.tracefile_count,
+                                          monitor,
+                                          ksession->metadata->conf->attr.live_timer_interval,
+                                          ksession->is_live_session,
+                                          0,
+                                          ksession->current_trace_chunk);
 
        health_code_update();
 
@@ -245,15 +247,14 @@ int kernel_consumer_add_metadata(struct consumer_socket *sock,
 
        /* Prep stream message structure */
        consumer_init_add_stream_comm_msg(&lkm,
-                       ksession->metadata->key,
-                       ksession->metadata_stream_fd,
-                       0 /* CPU: 0 for metadata. */);
+                                         ksession->metadata->key,
+                                         ksession->metadata_stream_fd,
+                                         0 /* CPU: 0 for metadata. */);
 
        health_code_update();
 
        /* Send stream and file descriptor */
-       ret = consumer_send_stream(sock, consumer, &lkm,
-                       &ksession->metadata_stream_fd, 1);
+       ret = consumer_send_stream(sock, consumer, &lkm, &ksession->metadata_stream_fd, 1);
        if (ret < 0) {
                goto error;
        }
@@ -261,18 +262,16 @@ int kernel_consumer_add_metadata(struct consumer_socket *sock,
        health_code_update();
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
 /*
  * Sending a single stream to the consumer with command ADD_STREAM.
  */
-static
-int kernel_consumer_add_stream(struct consumer_socket *sock,
-               struct ltt_kernel_channel *channel,
-               struct ltt_kernel_stream *stream,
-               struct ltt_kernel_session *session)
+static int kernel_consumer_add_stream(struct consumer_socket *sock,
+                                     struct ltt_kernel_channel *channel,
+                                     struct ltt_kernel_stream *stream,
+                                     struct ltt_kernel_session *session)
 {
        int ret;
        struct lttcomm_consumer_msg lkm;
@@ -285,16 +284,14 @@ int kernel_consumer_add_stream(struct consumer_socket *sock,
        LTTNG_ASSERT(sock);
 
        DBG("Sending stream %d of channel %s to kernel consumer",
-                       stream->fd, channel->channel->name);
+           stream->fd,
+           channel->channel->name);
 
        /* Get consumer output pointer */
        consumer = session->consumer;
 
        /* Prep stream consumer message */
-       consumer_init_add_stream_comm_msg(&lkm,
-                       channel->key,
-                       stream->fd,
-                       stream->cpu);
+       consumer_init_add_stream_comm_msg(&lkm, channel->key, stream->fd, stream->cpu);
 
        health_code_update();
 
@@ -314,7 +311,8 @@ error:
  * Sending the notification that all streams were sent with STREAMS_SENT.
  */
 int kernel_consumer_streams_sent(struct consumer_socket *sock,
-               struct ltt_kernel_session *session, uint64_t channel_key)
+                                struct ltt_kernel_session *session,
+                                uint64_t channel_key)
 {
        int ret;
        struct lttcomm_consumer_msg lkm;
@@ -328,9 +326,8 @@ int kernel_consumer_streams_sent(struct consumer_socket *sock,
        consumer = session->consumer;
 
        /* Prep stream consumer message */
-       consumer_init_streams_sent_comm_msg(&lkm,
-                       LTTNG_CONSUMER_STREAMS_SENT,
-                       channel_key, consumer->net_seq_index);
+       consumer_init_streams_sent_comm_msg(
+               &lkm, LTTNG_CONSUMER_STREAMS_SENT, channel_key, consumer->net_seq_index);
 
        health_code_update();
 
@@ -350,8 +347,9 @@ error:
  * The consumer socket lock must be held by the caller.
  */
 int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
-               struct ltt_kernel_channel *channel, struct ltt_kernel_session *ksession,
-               unsigned int monitor)
+                                        struct ltt_kernel_channel *channel,
+                                        struct ltt_kernel_session *ksession,
+                                        unsigned int monitor)
 {
        int ret = LTTNG_OK;
        struct ltt_kernel_stream *stream;
@@ -362,7 +360,7 @@ int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
        LTTNG_ASSERT(ksession->consumer);
        LTTNG_ASSERT(sock);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Bail out if consumer is disabled */
        if (!ksession->consumer->enabled) {
@@ -370,8 +368,7 @@ int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
                goto error;
        }
 
-       DBG("Sending streams of channel %s to kernel consumer",
-                       channel->channel->name);
+       DBG("Sending streams of channel %s to kernel consumer", channel->channel->name);
 
        if (!channel->sent_to_consumer) {
                ret = kernel_consumer_add_channel(sock, channel, ksession, monitor);
@@ -382,14 +379,13 @@ int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
        }
 
        /* Send streams */
-       cds_list_for_each_entry(stream, &channel->stream_list.head, list) {
+       cds_list_for_each_entry (stream, &channel->stream_list.head, list) {
                if (!stream->fd || stream->sent_to_consumer) {
                        continue;
                }
 
                /* Add stream on the kernel consumer side. */
-               ret = kernel_consumer_add_stream(sock, channel, stream,
-                               ksession);
+               ret = kernel_consumer_add_stream(sock, channel, stream, ksession);
                if (ret < 0) {
                        goto error;
                }
@@ -397,7 +393,6 @@ int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -406,8 +401,7 @@ error:
  *
  * The consumer socket lock must be held by the caller.
  */
-int kernel_consumer_send_session(struct consumer_socket *sock,
-               struct ltt_kernel_session *session)
+int kernel_consumer_send_session(struct consumer_socket *sock, struct ltt_kernel_session *session)
 {
        int ret, monitor = 0;
        struct ltt_kernel_channel *chan;
@@ -438,9 +432,8 @@ int kernel_consumer_send_session(struct consumer_socket *sock,
        }
 
        /* Send channel and streams of it */
-       cds_list_for_each_entry(chan, &session->channel_list.head, list) {
-               ret = kernel_consumer_send_channel_streams(sock, chan, session,
-                               monitor);
+       cds_list_for_each_entry (chan, &session->channel_list.head, list) {
+               ret = kernel_consumer_send_channel_streams(sock, chan, session, monitor);
                if (ret < 0) {
                        goto error;
                }
@@ -466,7 +459,7 @@ error:
 }
 
 int kernel_consumer_destroy_channel(struct consumer_socket *socket,
-               struct ltt_kernel_channel *channel)
+                                   struct ltt_kernel_channel *channel)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -495,7 +488,7 @@ error:
 }
 
 int kernel_consumer_destroy_metadata(struct consumer_socket *socket,
-               struct ltt_kernel_metadata *metadata)
+                                    struct ltt_kernel_metadata *metadata)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
index 276312e6c24b5906dad8740ec58d9c6f4ffdba67..9164085676acb2fb3d9678950a46a241d5bceece 100644 (file)
@@ -5,27 +5,29 @@
  *
  */
 
-#include <sys/types.h>
+#include "trace-kernel.hpp"
 
 #include <common/sessiond-comm/sessiond-comm.hpp>
 
-#include "trace-kernel.hpp"
+#include <sys/types.h>
 
 int kernel_consumer_send_channel_streams(struct consumer_socket *sock,
-               struct ltt_kernel_channel *channel, struct ltt_kernel_session *session,
-               unsigned int monitor);
+                                        struct ltt_kernel_channel *channel,
+                                        struct ltt_kernel_session *session,
+                                        unsigned int monitor);
 
-int kernel_consumer_send_session(struct consumer_socket *sock,
-               struct ltt_kernel_session *session);
+int kernel_consumer_send_session(struct consumer_socket *sock, struct ltt_kernel_session *session);
 
 int kernel_consumer_add_metadata(struct consumer_socket *sock,
-               struct ltt_kernel_session *session, unsigned int monitor);
+                                struct ltt_kernel_session *session,
+                                unsigned int monitor);
 
 int kernel_consumer_destroy_channel(struct consumer_socket *socket,
-               struct ltt_kernel_channel *channel);
+                                   struct ltt_kernel_channel *channel);
 
 int kernel_consumer_destroy_metadata(struct consumer_socket *socket,
-               struct ltt_kernel_metadata *metadata);
+                                    struct ltt_kernel_metadata *metadata);
 
 int kernel_consumer_streams_sent(struct consumer_socket *sock,
-               struct ltt_kernel_session *session, uint64_t channel_key);
+                                struct ltt_kernel_session *session,
+                                uint64_t channel_key);
index f7d232ffc01aadb346b5fdf6d8c4928ea5163727..4cc51a279806e8f68b217b344057eebf03908bdf 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <inttypes.h>
-#include <sys/types.h>
+#include "condition-internal.hpp"
+#include "consumer.hpp"
+#include "event-notifier-error-accounting.hpp"
+#include "kern-modules.hpp"
+#include "kernel-consumer.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "lttng-syscall.hpp"
+#include "modprobe.hpp"
+#include "notification-thread-commands.hpp"
+#include "sessiond-config.hpp"
+#include "tracker.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/hashtable/utils.hpp>
-#include <common/trace-chunk.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
 #include <common/kernel-ctl/kernel-ioctl.hpp>
+#include <common/scope-exit.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/trace-chunk.hpp>
 #include <common/tracker.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
-#include <lttng/event.h>
-#include <lttng/lttng-error.h>
-#include <lttng/tracker.h>
 
-#include <lttng/userspace-probe.h>
-#include <lttng/userspace-probe-internal.hpp>
-#include <lttng/condition/event-rule-matches.h>
 #include <lttng/condition/event-rule-matches-internal.hpp>
-#include <lttng/event-rule/event-rule.h>
+#include <lttng/condition/event-rule-matches.h>
 #include <lttng/event-rule/event-rule-internal.hpp>
+#include <lttng/event-rule/event-rule.h>
 #include <lttng/event-rule/kernel-uprobe-internal.hpp>
+#include <lttng/event.h>
+#include <lttng/lttng-error.h>
+#include <lttng/tracker.h>
+#include <lttng/userspace-probe-internal.hpp>
+#include <lttng/userspace-probe.h>
 
-#include "event-notifier-error-accounting.hpp"
-#include "lttng-sessiond.hpp"
-#include "lttng-syscall.hpp"
-#include "condition-internal.hpp"
-#include "consumer.hpp"
-#include "kernel.hpp"
-#include "kernel-consumer.hpp"
-#include "kern-modules.hpp"
-#include "sessiond-config.hpp"
-#include "utils.hpp"
-#include "rotate.hpp"
-#include "modprobe.hpp"
-#include "tracker.hpp"
-#include "notification-thread-commands.hpp"
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
 
+namespace {
 /*
  * Key used to reference a channel between the sessiond and the consumer. This
  * is only read and updated with the session_list lock held.
  */
-static uint64_t next_kernel_channel_key;
+uint64_t next_kernel_channel_key;
 
-static const char *module_proc_lttng = "/proc/lttng";
+const char *module_proc_lttng = "/proc/lttng";
 
-static int kernel_tracer_fd = -1;
-static int kernel_tracer_event_notifier_group_fd = -1;
-static int kernel_tracer_event_notifier_group_notification_fd = -1;
-static struct cds_lfht *kernel_token_to_event_notifier_rule_ht;
+int kernel_tracer_fd = -1;
+nonstd::optional<enum lttng_kernel_tracer_status> kernel_tracer_status = nonstd::nullopt;
+int kernel_tracer_event_notifier_group_fd = -1;
+int kernel_tracer_event_notifier_group_notification_fd = -1;
+struct cds_lfht *kernel_token_to_event_notifier_rule_ht;
+
+const char *kernel_tracer_status_to_str(lttng_kernel_tracer_status status)
+{
+       switch (status) {
+       case LTTNG_KERNEL_TRACER_STATUS_INITIALIZED:
+               return "LTTNG_KERNEL_TRACER_STATUS_INITIALIZED";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_UNKNOWN:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_UNKNOWN";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_NEED_ROOT:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_NEED_ROOT";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_OPEN_PROC_LTTNG:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_OPEN_PROC_LTTNG";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_VERSION_MISMATCH:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_VERSION_MISMATCH";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_UNKNOWN:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_UNKNOWN";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_MISSING:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_MISSING";
+       case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_SIGNATURE:
+               return "LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_SIGNATURE";
+       }
+
+       abort();
+}
+
+/*
+ * On some architectures, calling convention details are embedded in the symbol
+ * addresses. Uprobe requires a "clean" symbol offset (or at least, an address
+ * where an instruction boundary would be legal) to add
+ * instrumentation. sanitize_uprobe_offset implements that sanitization logic on
+ * a per-architecture basis.
+ */
+#if defined(__arm__) || defined(__aarch64__)
+static inline uint64_t sanitize_uprobe_offset(uint64_t raw_offset)
+{
+       /*
+        * The least significant bit is used when branching to switch to thumb
+        * ISA. However, it's an invalid address for us; mask the least
+        * significant bit.
+        */
+       return raw_offset &= ~0b1;
+}
+#else /* defined(__arm__) || defined(__aarch64__) */
+static inline uint64_t sanitize_uprobe_offset(uint64_t raw_offset)
+{
+       return raw_offset;
+}
+#endif
+} /* namespace */
 
 /*
  * Add context on a kernel channel.
  *
  * Assumes the ownership of ctx.
  */
-int kernel_add_channel_context(struct ltt_kernel_channel *chan,
-               struct ltt_kernel_context *ctx)
+int kernel_add_channel_context(struct ltt_kernel_channel *chan, struct ltt_kernel_context *ctx)
 {
        int ret;
 
@@ -98,7 +151,7 @@ int kernel_add_channel_context(struct ltt_kernel_channel *chan,
 end:
        cds_list_add_tail(&ctx->list, &chan->ctx_list);
        ctx->in_list = true;
-       ctx = NULL;
+       ctx = nullptr;
 error:
        if (ctx) {
                trace_kernel_destroy_context(ctx);
@@ -119,7 +172,7 @@ int kernel_create_session(struct ltt_session *session)
 
        /* Allocate data structure */
        lks = trace_kernel_create_session();
-       if (lks == NULL) {
+       if (lks == nullptr) {
                ret = -1;
                goto error;
        }
@@ -155,13 +208,15 @@ int kernel_create_session(struct ltt_session *session)
        }
        if (ret) {
                WARN("Could not set kernel session name for session %" PRIu64 " name: %s",
-                       session->id, session->name);
+                    session->id,
+                    session->name);
        }
 
        ret = kernctl_session_set_creation_time(lks->fd, session->creation_time);
        if (ret) {
                WARN("Could not set kernel session creation time for session %" PRIu64 " name: %s",
-                       session->id, session->name);
+                    session->id,
+                    session->name);
        }
 
        return 0;
@@ -178,8 +233,7 @@ error:
  * Create a kernel channel, register it to the kernel tracer and add it to the
  * kernel session.
  */
-int kernel_create_channel(struct ltt_kernel_session *session,
-               struct lttng_channel *chan)
+int kernel_create_channel(struct ltt_kernel_session *session, struct lttng_channel *chan)
 {
        int ret;
        struct ltt_kernel_channel *lkc;
@@ -189,15 +243,19 @@ int kernel_create_channel(struct ltt_kernel_session *session,
 
        /* Allocate kernel channel */
        lkc = trace_kernel_create_channel(chan);
-       if (lkc == NULL) {
+       if (lkc == nullptr) {
                goto error;
        }
 
        DBG3("Kernel create channel %s with attr: %d, %" PRIu64 ", %" PRIu64 ", %u, %u, %d, %d",
-                       chan->name, lkc->channel->attr.overwrite,
-                       lkc->channel->attr.subbuf_size, lkc->channel->attr.num_subbuf,
-                       lkc->channel->attr.switch_timer_interval, lkc->channel->attr.read_timer_interval,
-                       lkc->channel->attr.live_timer_interval, lkc->channel->attr.output);
+            chan->name,
+            lkc->channel->attr.overwrite,
+            lkc->channel->attr.subbuf_size,
+            lkc->channel->attr.num_subbuf,
+            lkc->channel->attr.switch_timer_interval,
+            lkc->channel->attr.read_timer_interval,
+            lkc->channel->attr.live_timer_interval,
+            lkc->channel->attr.output);
 
        /* Kernel tracer channel creation */
        ret = kernctl_create_channel(session->fd, &lkc->channel->attr);
@@ -221,7 +279,9 @@ int kernel_create_channel(struct ltt_kernel_session *session,
        lkc->key = ++next_kernel_channel_key;
 
        DBG("Kernel channel %s created (fd: %d, key: %" PRIu64 ")",
-                       lkc->channel->name, lkc->fd, lkc->key);
+           lkc->channel->name,
+           lkc->fd,
+           lkc->key);
 
        return 0;
 
@@ -258,7 +318,7 @@ static int kernel_create_event_notifier_group(int *event_notifier_group_fd)
        ret = fcntl(local_fd, F_SETFD, FD_CLOEXEC);
        if (ret < 0) {
                PERROR("Failed to set FD_CLOEXEC on kernel event notifier group file descriptor: fd = %d",
-                               local_fd);
+                      local_fd);
                goto error;
        }
 
@@ -271,7 +331,7 @@ error:
                ret = close(local_fd);
                if (ret) {
                        PERROR("Failed to close kernel event notifier group file descriptor: fd = %d",
-                                       local_fd);
+                              local_fd);
                }
        }
 
@@ -286,35 +346,33 @@ error:
  * elf symbol
  * Returns -1 on error
  */
-static
-int extract_userspace_probe_offset_function_elf(
-               const struct lttng_userspace_probe_location *probe_location,
-               uid_t uid, gid_t gid, uint64_t *offset)
+static int extract_userspace_probe_offset_function_elf(
+       const struct lttng_userspace_probe_location *probe_location,
+       uid_t uid,
+       gid_t gid,
+       uint64_t *offset)
 {
        int fd;
        int ret = 0;
-       const char *symbol = NULL;
-       const struct lttng_userspace_probe_location_lookup_method *lookup = NULL;
+       const char *symbol = nullptr;
+       const struct lttng_userspace_probe_location_lookup_method *lookup = nullptr;
        enum lttng_userspace_probe_location_lookup_method_type lookup_method_type;
 
        LTTNG_ASSERT(lttng_userspace_probe_location_get_type(probe_location) ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
+                    LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
 
-       lookup = lttng_userspace_probe_location_get_lookup_method(
-                       probe_location);
+       lookup = lttng_userspace_probe_location_get_lookup_method(probe_location);
        if (!lookup) {
                ret = -1;
                goto end;
        }
 
-       lookup_method_type =
-                       lttng_userspace_probe_location_lookup_method_get_type(lookup);
+       lookup_method_type = lttng_userspace_probe_location_lookup_method_get_type(lookup);
 
        LTTNG_ASSERT(lookup_method_type ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF);
+                    LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF);
 
-       symbol = lttng_userspace_probe_location_function_get_function_name(
-                       probe_location);
+       symbol = lttng_userspace_probe_location_function_get_function_name(probe_location);
        if (!symbol) {
                ret = -1;
                goto end;
@@ -329,11 +387,12 @@ int extract_userspace_probe_offset_function_elf(
        ret = run_as_extract_elf_symbol_offset(fd, symbol, uid, gid, offset);
        if (ret < 0) {
                DBG("userspace probe offset calculation failed for "
-                               "function %s", symbol);
+                   "function %s",
+                   symbol);
                goto end;
        }
 
-       DBG("userspace probe elf offset for %s is 0x%jd", symbol, (intmax_t)(*offset));
+       DBG("userspace probe elf offset for %s is 0x%jd", symbol, (intmax_t) (*offset));
 end:
        return ret;
 }
@@ -347,20 +406,21 @@ end:
  * SDT tracepoint.
  * Returns -1 on error.
  */
-static
-int extract_userspace_probe_offset_tracepoint_sdt(
-               const struct lttng_userspace_probe_location *probe_location,
-               uid_t uid, gid_t gid, uint64_t **offsets,
-               uint32_t *offsets_count)
+static int extract_userspace_probe_offset_tracepoint_sdt(
+       const struct lttng_userspace_probe_location *probe_location,
+       uid_t uid,
+       gid_t gid,
+       uint64_t **offsets,
+       uint32_t *offsets_count)
 {
        enum lttng_userspace_probe_location_lookup_method_type lookup_method_type;
-       const struct lttng_userspace_probe_location_lookup_method *lookup = NULL;
-       const char *probe_name = NULL, *provider_name = NULL;
+       const struct lttng_userspace_probe_location_lookup_method *lookup = nullptr;
+       const char *probe_name = nullptr, *provider_name = nullptr;
        int ret = 0;
        int fd, i;
 
        LTTNG_ASSERT(lttng_userspace_probe_location_get_type(probe_location) ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
+                    LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
 
        lookup = lttng_userspace_probe_location_get_lookup_method(probe_location);
        if (!lookup) {
@@ -368,22 +428,18 @@ int extract_userspace_probe_offset_tracepoint_sdt(
                goto end;
        }
 
-       lookup_method_type =
-                       lttng_userspace_probe_location_lookup_method_get_type(lookup);
+       lookup_method_type = lttng_userspace_probe_location_lookup_method_get_type(lookup);
 
        LTTNG_ASSERT(lookup_method_type ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT);
-
+                    LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT);
 
-       probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(
-                       probe_location);
+       probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(probe_location);
        if (!probe_name) {
                ret = -1;
                goto end;
        }
 
-       provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(
-                       probe_location);
+       provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(probe_location);
        if (!provider_name) {
                ret = -1;
                goto end;
@@ -395,11 +451,13 @@ int extract_userspace_probe_offset_tracepoint_sdt(
                goto end;
        }
 
-       ret = run_as_extract_sdt_probe_offsets(fd, provider_name, probe_name,
-                       uid, gid, offsets, offsets_count);
+       ret = run_as_extract_sdt_probe_offsets(
+               fd, provider_name, probe_name, uid, gid, offsets, offsets_count);
        if (ret < 0) {
                DBG("userspace probe offset calculation failed for sdt "
-                               "probe %s:%s", provider_name, probe_name);
+                   "probe %s:%s",
+                   provider_name,
+                   probe_name);
                goto end;
        }
 
@@ -409,20 +467,22 @@ int extract_userspace_probe_offset_tracepoint_sdt(
        }
 
        DBG("%u userspace probe SDT offsets found for %s:%s at:",
-                       *offsets_count, provider_name, probe_name);
+           *offsets_count,
+           provider_name,
+           probe_name);
        for (i = 0; i < *offsets_count; i++) {
-               DBG("\t0x%jd", (intmax_t)((*offsets)[i]));
+               DBG("\t0x%jd", (intmax_t) ((*offsets)[i]));
        }
 end:
        return ret;
 }
 
-static
-int userspace_probe_add_callsite(
-               const struct lttng_userspace_probe_location *location,
-               uid_t uid, gid_t gid, int fd)
+static int userspace_probe_add_callsite(const struct lttng_userspace_probe_location *location,
+                                       uid_t uid,
+                                       gid_t gid,
+                                       int fd)
 {
-       const struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
        enum lttng_userspace_probe_location_lookup_method_type type;
        int ret;
 
@@ -439,14 +499,13 @@ int userspace_probe_add_callsite(
                struct lttng_kernel_abi_event_callsite callsite;
                uint64_t offset;
 
-               ret = extract_userspace_probe_offset_function_elf(location,
-                               uid, gid, &offset);
+               ret = extract_userspace_probe_offset_function_elf(location, uid, gid, &offset);
                if (ret) {
                        ret = LTTNG_ERR_PROBE_LOCATION_INVAL;
                        goto end;
                }
 
-               callsite.u.uprobe.offset = offset;
+               callsite.u.uprobe.offset = sanitize_uprobe_offset(offset);
                ret = kernctl_add_callsite(fd, &callsite);
                if (ret) {
                        WARN("Failed to add callsite to ELF userspace probe.");
@@ -458,7 +517,7 @@ int userspace_probe_add_callsite(
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
        {
                int i;
-               uint64_t *offsets = NULL;
+               uint64_t *offsets = nullptr;
                uint32_t offsets_count;
                struct lttng_kernel_abi_event_callsite callsite;
 
@@ -466,14 +525,14 @@ int userspace_probe_add_callsite(
                 * This call allocates the offsets buffer. This buffer must be freed
                 * by the caller
                 */
-               ret = extract_userspace_probe_offset_tracepoint_sdt(location,
-                               uid, gid, &offsets, &offsets_count);
+               ret = extract_userspace_probe_offset_tracepoint_sdt(
+                       location, uid, gid, &offsets, &offsets_count);
                if (ret) {
                        ret = LTTNG_ERR_PROBE_LOCATION_INVAL;
                        goto end;
                }
                for (i = 0; i < offsets_count; i++) {
-                       callsite.u.uprobe.offset = offsets[i];
+                       callsite.u.uprobe.offset = sanitize_uprobe_offset(offsets[i]);
                        ret = kernctl_add_callsite(fd, &callsite);
                        if (ret) {
                                WARN("Failed to add callsite to SDT userspace probe");
@@ -497,12 +556,12 @@ end:
  * Extract the offsets of the instrumentation point for the different lookup
  * methods.
  */
-static
-int userspace_probe_event_add_callsites(struct lttng_event *ev,
-                       struct ltt_kernel_session *session, int fd)
+static int userspace_probe_event_add_callsites(struct lttng_event *ev,
+                                              struct ltt_kernel_session *session,
+                                              int fd)
 {
        int ret;
-       const struct lttng_userspace_probe_location *location = NULL;
+       const struct lttng_userspace_probe_location *location = nullptr;
 
        LTTNG_ASSERT(ev);
        LTTNG_ASSERT(ev->type == LTTNG_EVENT_USERSPACE_PROBE);
@@ -513,11 +572,9 @@ int userspace_probe_event_add_callsites(struct lttng_event *ev,
                goto end;
        }
 
-       ret = userspace_probe_add_callsite(location, session->uid, session->gid,
-               fd);
+       ret = userspace_probe_add_callsite(location, session->uid, session->gid, fd);
        if (ret) {
-               WARN("Failed to add callsite to userspace probe event '%s'",
-                               ev->name);
+               WARN("Failed to add callsite to userspace probe event '%s'", ev->name);
        }
 
 end:
@@ -528,15 +585,14 @@ end:
  * Extract the offsets of the instrumentation point for the different look-up
  * methods.
  */
-static int userspace_probe_event_rule_add_callsites(
-               const struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds,
-               int fd)
+static int userspace_probe_event_rule_add_callsites(const struct lttng_event_rule *rule,
+                                                   const struct lttng_credentials *creds,
+                                                   int fd)
 {
        int ret;
        enum lttng_event_rule_status status;
        enum lttng_event_rule_type event_rule_type;
-       const struct lttng_userspace_probe_location *location = NULL;
+       const struct lttng_userspace_probe_location *location = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(creds);
@@ -550,12 +606,10 @@ static int userspace_probe_event_rule_add_callsites(
                goto end;
        }
 
-       ret = userspace_probe_add_callsite(location,
-                       lttng_credentials_get_uid(creds),
-                       lttng_credentials_get_gid(creds), fd);
+       ret = userspace_probe_add_callsite(
+               location, lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds), fd);
        if (ret) {
-               WARN("Failed to add callsite to user space probe object: fd = %d",
-                               fd);
+               WARN("Failed to add callsite to user space probe object: fd = %d", fd);
        }
 
 end:
@@ -568,9 +622,9 @@ end:
  * We own filter_expression and filter.
  */
 int kernel_create_event(struct lttng_event *ev,
-               struct ltt_kernel_channel *channel,
-               char *filter_expression,
-               struct lttng_bytecode *filter)
+                       struct ltt_kernel_channel *channel,
+                       char *filter_expression,
+                       struct lttng_bytecode *filter)
 {
        int err, fd;
        enum lttng_error_code ret;
@@ -580,8 +634,7 @@ int kernel_create_event(struct lttng_event *ev,
        LTTNG_ASSERT(channel);
 
        /* We pass ownership of filter_expression and filter */
-       ret = trace_kernel_create_event(ev, filter_expression,
-                       filter, &event);
+       ret = trace_kernel_create_event(ev, filter_expression, filter, &event);
        if (ret != LTTNG_OK) {
                goto error;
        }
@@ -631,8 +684,8 @@ int kernel_create_event(struct lttng_event *ev,
        }
 
        if (ev->type == LTTNG_EVENT_USERSPACE_PROBE) {
-               ret = (lttng_error_code) userspace_probe_event_add_callsites(ev, channel->session,
-                               event->fd);
+               ret = (lttng_error_code) userspace_probe_event_add_callsites(
+                       ev, channel->session, event->fd);
                if (ret) {
                        goto add_callsite_error;
                }
@@ -663,14 +716,14 @@ int kernel_create_event(struct lttng_event *ev,
 add_callsite_error:
 enable_error:
 filter_error:
-       {
-               int closeret;
+{
+       int closeret;
 
-               closeret = close(event->fd);
-               if (closeret) {
-                       PERROR("close event fd");
-               }
+       closeret = close(event->fd);
+       if (closeret) {
+               PERROR("close event fd");
        }
+}
 free_event:
        free(event);
 error:
@@ -692,9 +745,11 @@ int kernel_disable_channel(struct ltt_kernel_channel *chan)
                goto error;
        }
 
-       chan->enabled = 0;
+       chan->enabled = false;
        DBG("Kernel channel %s disabled (fd: %d, key: %" PRIu64 ")",
-                       chan->channel->name, chan->fd, chan->key);
+           chan->channel->name,
+           chan->fd,
+           chan->key);
 
        return 0;
 
@@ -717,9 +772,11 @@ int kernel_enable_channel(struct ltt_kernel_channel *chan)
                goto error;
        }
 
-       chan->enabled = 1;
+       chan->enabled = true;
        DBG("Kernel channel %s enabled (fd: %d, key: %" PRIu64 ")",
-                       chan->channel->name, chan->fd, chan->key);
+           chan->channel->name,
+           chan->fd,
+           chan->key);
 
        return 0;
 
@@ -749,7 +806,7 @@ int kernel_enable_event(struct ltt_kernel_event *event)
                goto error;
        }
 
-       event->enabled = 1;
+       event->enabled = true;
        DBG("Kernel event %s enabled (fd: %d)", event->event->name, event->fd);
 
        return 0;
@@ -770,11 +827,12 @@ int kernel_disable_event(struct ltt_kernel_event *event)
        ret = kernctl_disable(event->fd);
        if (ret < 0) {
                PERROR("Failed to disable kernel event: name = '%s', fd = %d",
-                               event->event->name, event->fd);
+                      event->event->name,
+                      event->fd);
                goto error;
        }
 
-       event->enabled = 0;
+       event->enabled = false;
        DBG("Kernel event %s disabled (fd: %d)", event->event->name, event->fd);
 
        return 0;
@@ -786,36 +844,33 @@ error:
 /*
  * Disable a kernel event notifier.
  */
-static
-int kernel_disable_event_notifier_rule(struct ltt_kernel_event_notifier_rule *event)
+static int kernel_disable_event_notifier_rule(struct ltt_kernel_event_notifier_rule *event)
 {
        int ret;
 
        LTTNG_ASSERT(event);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_del(kernel_token_to_event_notifier_rule_ht, &event->ht_node);
-       rcu_read_unlock();
 
        ret = kernctl_disable(event->fd);
        if (ret < 0) {
                PERROR("Failed to disable kernel event notifier: fd = %d, token = %" PRIu64,
-                               event->fd, event->token);
+                      event->fd,
+                      event->token);
                goto error;
        }
 
-       event->enabled = 0;
-       DBG("Disabled kernel event notifier: fd = %d, token = %" PRIu64,
-                       event->fd, event->token);
+       event->enabled = false;
+       DBG("Disabled kernel event notifier: fd = %d, token = %" PRIu64, event->fd, event->token);
 
 error:
        return ret;
 }
 
-static
-struct process_attr_tracker *_kernel_get_process_attr_tracker(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr)
+static struct process_attr_tracker *
+_kernel_get_process_attr_tracker(struct ltt_kernel_session *session,
+                                enum lttng_process_attr process_attr)
 {
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_PROCESS_ID:
@@ -831,27 +886,27 @@ struct process_attr_tracker *_kernel_get_process_attr_tracker(
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                return session->tracker_vgid;
        default:
-               return NULL;
+               return nullptr;
        }
 }
 
-const struct process_attr_tracker *kernel_get_process_attr_tracker(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr)
+const struct process_attr_tracker *
+kernel_get_process_attr_tracker(struct ltt_kernel_session *session,
+                               enum lttng_process_attr process_attr)
 {
-       return (const struct process_attr_tracker *)
-                       _kernel_get_process_attr_tracker(session, process_attr);
+       return (const struct process_attr_tracker *) _kernel_get_process_attr_tracker(session,
+                                                                                     process_attr);
 }
 
-enum lttng_error_code kernel_process_attr_tracker_set_tracking_policy(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy)
+enum lttng_error_code
+kernel_process_attr_tracker_set_tracking_policy(struct ltt_kernel_session *session,
+                                               enum lttng_process_attr process_attr,
+                                               enum lttng_tracking_policy policy)
 {
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        struct process_attr_tracker *tracker =
-                       _kernel_get_process_attr_tracker(session, process_attr);
+               _kernel_get_process_attr_tracker(session, process_attr);
        enum lttng_tracking_policy previous_policy;
 
        if (!tracker) {
@@ -922,10 +977,10 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+kernel_process_attr_tracker_inclusion_set_add_value(struct ltt_kernel_session *session,
+                                                   enum lttng_process_attr process_attr,
+                                                   const struct process_attr_value *value)
 {
        int ret, integral_value;
        enum lttng_error_code ret_code;
@@ -946,8 +1001,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME) {
                        uid_t uid;
 
-                       ret_code = utils_user_id_from_name(
-                                       value->value.user_name, &uid);
+                       ret_code = utils_user_id_from_name(value->value.user_name, &uid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -961,8 +1015,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME) {
                        gid_t gid;
 
-                       ret_code = utils_group_id_from_name(
-                                       value->value.group_name, &gid);
+                       ret_code = utils_group_id_from_name(value->value.group_name, &gid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1000,8 +1053,9 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
        }
 
        DBG("Kernel track %s %d for session id %" PRIu64,
-                       lttng_process_attr_to_string(process_attr),
-                       integral_value, session->id);
+           lttng_process_attr_to_string(process_attr),
+           integral_value,
+           session->id);
        if (process_attr == LTTNG_PROCESS_ATTR_PROCESS_ID) {
                /*
                 * Maintain a special case for the process ID process attribute
@@ -1009,8 +1063,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
                 */
                ret = kernctl_track_pid(session->fd, integral_value);
        } else {
-               ret = kernctl_track_id(
-                               session->fd, process_attr, integral_value);
+               ret = kernctl_track_id(session->fd, process_attr, integral_value);
        }
        if (ret == 0) {
                ret_code = LTTNG_OK;
@@ -1039,21 +1092,20 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
        }
 
        /* Attempt to remove the value from the tracker. */
-       status = process_attr_tracker_inclusion_set_remove_value(
-                       tracker, value);
+       status = process_attr_tracker_inclusion_set_remove_value(tracker, value);
        if (status != PROCESS_ATTR_TRACKER_STATUS_OK) {
                ERR("Failed to roll-back the tracking of kernel %s process attribute %d while handling a kern-ctl error",
-                               lttng_process_attr_to_string(process_attr),
-                               integral_value);
+                   lttng_process_attr_to_string(process_attr),
+                   integral_value);
        }
 end:
        return ret_code;
 }
 
-enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+kernel_process_attr_tracker_inclusion_set_remove_value(struct ltt_kernel_session *session,
+                                                      enum lttng_process_attr process_attr,
+                                                      const struct process_attr_value *value)
 {
        int ret, integral_value;
        enum lttng_error_code ret_code;
@@ -1074,8 +1126,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME) {
                        uid_t uid;
 
-                       ret_code = utils_user_id_from_name(
-                                       value->value.user_name, &uid);
+                       ret_code = utils_user_id_from_name(value->value.user_name, &uid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1089,8 +1140,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME) {
                        gid_t gid;
 
-                       ret_code = utils_group_id_from_name(
-                                       value->value.group_name, &gid);
+                       ret_code = utils_group_id_from_name(value->value.group_name, &gid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1110,8 +1160,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
                goto end;
        }
 
-       status = process_attr_tracker_inclusion_set_remove_value(
-                       tracker, value);
+       status = process_attr_tracker_inclusion_set_remove_value(tracker, value);
        if (status != PROCESS_ATTR_TRACKER_STATUS_OK) {
                switch (status) {
                case PROCESS_ATTR_TRACKER_STATUS_MISSING:
@@ -1129,8 +1178,9 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
        }
 
        DBG("Kernel track %s %d for session id %" PRIu64,
-                       lttng_process_attr_to_string(process_attr),
-                       integral_value, session->id);
+           lttng_process_attr_to_string(process_attr),
+           integral_value,
+           session->id);
        if (process_attr == LTTNG_PROCESS_ATTR_PROCESS_ID) {
                /*
                 * Maintain a special case for the process ID process attribute
@@ -1138,8 +1188,7 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
                 */
                ret = kernctl_untrack_pid(session->fd, integral_value);
        } else {
-               ret = kernctl_untrack_id(
-                               session->fd, process_attr, integral_value);
+               ret = kernctl_untrack_id(session->fd, process_attr, integral_value);
        }
        if (ret == 0) {
                ret_code = LTTNG_OK;
@@ -1167,12 +1216,11 @@ enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
        }
 
        /* Attempt to add the value to the tracker. */
-       status = process_attr_tracker_inclusion_set_add_value(
-                       tracker, value);
+       status = process_attr_tracker_inclusion_set_add_value(tracker, value);
        if (status != PROCESS_ATTR_TRACKER_STATUS_OK) {
                ERR("Failed to roll-back the tracking of kernel %s process attribute %d while handling a kern-ctl error",
-                               lttng_process_attr_to_string(process_attr),
-                               integral_value);
+                   lttng_process_attr_to_string(process_attr),
+                   integral_value);
        }
 end:
        return ret_code;
@@ -1185,13 +1233,13 @@ end:
 int kernel_open_metadata(struct ltt_kernel_session *session)
 {
        int ret;
-       struct ltt_kernel_metadata *lkm = NULL;
+       struct ltt_kernel_metadata *lkm = nullptr;
 
        LTTNG_ASSERT(session);
 
        /* Allocate kernel metadata */
        lkm = trace_kernel_create_metadata();
-       if (lkm == NULL) {
+       if (lkm == nullptr) {
                goto error;
        }
 
@@ -1247,7 +1295,7 @@ error:
 /*
  * Make a kernel wait to make sure in-flight probe have completed.
  */
-void kernel_wait_quiescent(void)
+void kernel_wait_quiescent()
 {
        int ret;
        int fd = kernel_tracer_fd;
@@ -1290,13 +1338,12 @@ int kernel_flush_buffer(struct ltt_kernel_channel *channel)
 
        DBG("Flush buffer for channel %s", channel->channel->name);
 
-       cds_list_for_each_entry(stream, &channel->stream_list.head, list) {
+       cds_list_for_each_entry (stream, &channel->stream_list.head, list) {
                DBG("Flushing channel stream %d", stream->fd);
                ret = kernctl_buffer_flush(stream->fd);
                if (ret < 0) {
                        PERROR("ioctl");
-                       ERR("Fail to flush buffer for stream %d (ret: %d)",
-                                       stream->fd, ret);
+                       ERR("Fail to flush buffer for stream %d (ret: %d)", stream->fd, ret);
                }
        }
 
@@ -1343,9 +1390,8 @@ int kernel_open_channel_stream(struct ltt_kernel_channel *channel)
        LTTNG_ASSERT(channel);
 
        while ((ret = kernctl_create_stream(channel->fd)) >= 0) {
-               lks = trace_kernel_create_stream(channel->channel->name,
-                               channel->stream_count);
-               if (lks == NULL) {
+               lks = trace_kernel_create_stream(channel->channel->name, channel->stream_count);
+               if (lks == nullptr) {
                        ret = close(ret);
                        if (ret) {
                                PERROR("close");
@@ -1367,8 +1413,7 @@ int kernel_open_channel_stream(struct ltt_kernel_channel *channel)
                cds_list_add(&lks->list, &channel->stream_list.head);
                channel->stream_count++;
 
-               DBG("Kernel stream %s created (fd: %d, state: %d)", lks->name, lks->fd,
-                               lks->state);
+               DBG("Kernel stream %s created (fd: %d, state: %d)", lks->name, lks->fd, lks->state);
        }
 
        return channel->stream_count;
@@ -1426,7 +1471,7 @@ ssize_t kernel_list_events(struct lttng_event **events)
        }
 
        fp = fdopen(fd, "r");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                PERROR("kernel tracepoint list fdopen");
                goto error_fp;
        }
@@ -1437,7 +1482,7 @@ ssize_t kernel_list_events(struct lttng_event **events)
         */
        nbmem = KERNEL_EVENT_INIT_LIST_SIZE;
        elist = calloc<lttng_event>(nbmem);
-       if (elist == NULL) {
+       if (elist == nullptr) {
                PERROR("alloc list events");
                count = -ENOMEM;
                goto end;
@@ -1449,10 +1494,10 @@ ssize_t kernel_list_events(struct lttng_event **events)
                        size_t new_nbmem;
 
                        new_nbmem = nbmem << 1;
-                       DBG("Reallocating event list from %zu to %zu bytes",
-                                       nbmem, new_nbmem);
-                       new_elist = (lttng_event *) realloc(elist, new_nbmem * sizeof(struct lttng_event));
-                       if (new_elist == NULL) {
+                       DBG("Reallocating event list from %zu to %zu bytes", nbmem, new_nbmem);
+                       new_elist = (lttng_event *) realloc(elist,
+                                                           new_nbmem * sizeof(struct lttng_event));
+                       if (new_elist == nullptr) {
                                PERROR("realloc list events");
                                free(event);
                                free(elist);
@@ -1460,8 +1505,9 @@ ssize_t kernel_list_events(struct lttng_event **events)
                                goto end;
                        }
                        /* Zero the new memory */
-                       memset(new_elist + nbmem, 0,
-                               (new_nbmem - nbmem) * sizeof(struct lttng_event));
+                       memset(new_elist + nbmem,
+                              0,
+                              (new_nbmem - nbmem) * sizeof(struct lttng_event));
                        nbmem = new_nbmem;
                        elist = new_elist;
                }
@@ -1475,7 +1521,7 @@ ssize_t kernel_list_events(struct lttng_event **events)
        *events = elist;
        DBG("Kernel list events done (%zu events)", count);
 end:
-       ret = fclose(fp);       /* closes both fp and fd */
+       ret = fclose(fp); /* closes both fp and fd */
        if (ret) {
                PERROR("fclose");
        }
@@ -1494,7 +1540,7 @@ error:
  * Get kernel version and validate it.
  */
 int kernel_validate_version(struct lttng_kernel_abi_tracer_version *version,
-               struct lttng_kernel_abi_tracer_abi_version *abi_version)
+                           struct lttng_kernel_abi_tracer_abi_version *abi_version)
 {
        int ret;
 
@@ -1507,7 +1553,8 @@ int kernel_validate_version(struct lttng_kernel_abi_tracer_version *version,
        /* Validate version */
        if (version->major != VERSION_MAJOR) {
                ERR("Kernel tracer major version (%d) is not compatible with lttng-tools major version (%d)",
-                       version->major, VERSION_MAJOR);
+                   version->major,
+                   VERSION_MAJOR);
                goto error_version;
        }
        ret = kernctl_tracer_abi_version(kernel_tracer_fd, abi_version);
@@ -1517,13 +1564,16 @@ int kernel_validate_version(struct lttng_kernel_abi_tracer_version *version,
        }
        if (abi_version->major != LTTNG_KERNEL_ABI_MAJOR_VERSION) {
                ERR("Kernel tracer ABI version (%d.%d) does not match the expected ABI major version (%d.*)",
-                       abi_version->major, abi_version->minor,
-                       LTTNG_KERNEL_ABI_MAJOR_VERSION);
+                   abi_version->major,
+                   abi_version->minor,
+                   LTTNG_KERNEL_ABI_MAJOR_VERSION);
                goto error;
        }
        DBG2("Kernel tracer version validated (%d.%d, ABI %d.%d)",
-                       version->major, version->minor,
-                       abi_version->major, abi_version->minor);
+            version->major,
+            version->minor,
+            abi_version->major,
+            abi_version->minor);
        return 0;
 
 error_version:
@@ -1537,7 +1587,7 @@ error:
 /*
  * Kernel work-arounds called at the start of sessiond main().
  */
-int init_kernel_workarounds(void)
+int init_kernel_workarounds()
 {
        int ret;
        FILE *fp;
@@ -1574,7 +1624,7 @@ void kernel_destroy_session(struct ltt_kernel_session *ksess)
 {
        struct lttng_trace_chunk *trace_chunk;
 
-       if (ksess == NULL) {
+       if (ksess == nullptr) {
                DBG3("No kernel session when tearing down session");
                return;
        }
@@ -1593,13 +1643,14 @@ void kernel_destroy_session(struct ltt_kernel_session *ksess)
                struct lttng_ht_iter iter;
 
                /* For each consumer socket. */
-               rcu_read_lock();
-               cds_lfht_for_each_entry(ksess->consumer->socks->ht, &iter.iter,
-                               socket, node.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       ksess->consumer->socks->ht, &iter.iter, socket, node.node) {
                        struct ltt_kernel_channel *chan;
 
                        /* For each channel, ask the consumer to destroy it. */
-                       cds_list_for_each_entry(chan, &ksess->channel_list.head, list) {
+                       cds_list_for_each_entry (chan, &ksess->channel_list.head, list) {
                                ret = kernel_consumer_destroy_channel(socket, chan);
                                if (ret < 0) {
                                        /* Consumer is probably dead. Use next socket. */
@@ -1607,7 +1658,6 @@ void kernel_destroy_session(struct ltt_kernel_session *ksess)
                                }
                        }
                }
-               rcu_read_unlock();
        }
 
        /* Close any relayd session */
@@ -1620,7 +1670,7 @@ void kernel_destroy_session(struct ltt_kernel_session *ksess)
 /* Teardown of data required by destroy notifiers. */
 void kernel_free_session(struct ltt_kernel_session *ksess)
 {
-       if (ksess == NULL) {
+       if (ksess == nullptr) {
                return;
        }
        trace_kernel_free_session(ksess);
@@ -1631,7 +1681,7 @@ void kernel_free_session(struct ltt_kernel_session *ksess)
  */
 void kernel_destroy_channel(struct ltt_kernel_channel *kchan)
 {
-       struct ltt_kernel_session *ksess = NULL;
+       struct ltt_kernel_session *ksess = nullptr;
 
        LTTNG_ASSERT(kchan);
        LTTNG_ASSERT(kchan->channel);
@@ -1661,17 +1711,16 @@ void kernel_destroy_channel(struct ltt_kernel_channel *kchan)
  *
  * Return LTTNG_OK on success or else return a LTTNG_ERR code.
  */
-enum lttng_error_code kernel_snapshot_record(
-               struct ltt_kernel_session *ksess,
-               const struct consumer_output *output,
-               uint64_t nb_packets_per_stream)
+enum lttng_error_code kernel_snapshot_record(struct ltt_kernel_session *ksess,
+                                            const struct consumer_output *output,
+                                            uint64_t nb_packets_per_stream)
 {
        int err, ret, saved_metadata_fd;
        enum lttng_error_code status = LTTNG_OK;
        struct consumer_socket *socket;
        struct lttng_ht_iter iter;
        struct ltt_kernel_metadata *saved_metadata;
-       char *trace_path = NULL;
+       char *trace_path = nullptr;
        size_t consumer_path_offset = 0;
 
        LTTNG_ASSERT(ksess);
@@ -1684,8 +1733,6 @@ enum lttng_error_code kernel_snapshot_record(
        saved_metadata = ksess->metadata;
        saved_metadata_fd = ksess->metadata_stream_fd;
 
-       rcu_read_lock();
-
        ret = kernel_open_metadata(ksess);
        if (ret < 0) {
                status = LTTNG_ERR_KERN_META_FAIL;
@@ -1698,50 +1745,61 @@ enum lttng_error_code kernel_snapshot_record(
                goto error_open_stream;
        }
 
-       trace_path = setup_channel_trace_path(ksess->consumer,
-                       "", &consumer_path_offset);
+       trace_path = setup_channel_trace_path(ksess->consumer, "", &consumer_path_offset);
        if (!trace_path) {
                status = LTTNG_ERR_INVALID;
                goto error;
        }
-       /* Send metadata to consumer and snapshot everything. */
-       cds_lfht_for_each_entry(output->socks->ht, &iter.iter,
-                       socket, node.node) {
-               struct ltt_kernel_channel *chan;
 
-               pthread_mutex_lock(socket->lock);
-               /* This stream must not be monitored by the consumer. */
-               ret = kernel_consumer_add_metadata(socket, ksess, 0);
-               pthread_mutex_unlock(socket->lock);
-               if (ret < 0) {
-                       status = LTTNG_ERR_KERN_META_FAIL;
-                       goto error_consumer;
-               }
+       {
+               /* Send metadata to consumer and snapshot everything. */
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (output->socks->ht, &iter.iter, socket, node.node) {
+                       struct ltt_kernel_channel *chan;
+
+                       pthread_mutex_lock(socket->lock);
+                       /* This stream must not be monitored by the consumer. */
+                       ret = kernel_consumer_add_metadata(socket, ksess, 0);
+                       pthread_mutex_unlock(socket->lock);
+                       if (ret < 0) {
+                               status = LTTNG_ERR_KERN_META_FAIL;
+                               goto error_consumer;
+                       }
+
+                       /* For each channel, ask the consumer to snapshot it. */
+                       cds_list_for_each_entry (chan, &ksess->channel_list.head, list) {
+                               status =
+                                       consumer_snapshot_channel(socket,
+                                                                 chan->key,
+                                                                 output,
+                                                                 0,
+                                                                 &trace_path[consumer_path_offset],
+                                                                 nb_packets_per_stream);
+                               if (status != LTTNG_OK) {
+                                       (void) kernel_consumer_destroy_metadata(socket,
+                                                                               ksess->metadata);
+                                       goto error_consumer;
+                               }
+                       }
 
-               /* For each channel, ask the consumer to snapshot it. */
-               cds_list_for_each_entry(chan, &ksess->channel_list.head, list) {
-                       status = consumer_snapshot_channel(socket, chan->key, output, 0,
-                                       &trace_path[consumer_path_offset],
-                                       nb_packets_per_stream);
+                       /* Snapshot metadata, */
+                       status = consumer_snapshot_channel(socket,
+                                                          ksess->metadata->key,
+                                                          output,
+                                                          1,
+                                                          &trace_path[consumer_path_offset],
+                                                          0);
                        if (status != LTTNG_OK) {
-                               (void) kernel_consumer_destroy_metadata(socket,
-                                               ksess->metadata);
                                goto error_consumer;
                        }
-               }
 
-               /* Snapshot metadata, */
-               status = consumer_snapshot_channel(socket, ksess->metadata->key, output,
-                               1, &trace_path[consumer_path_offset], 0);
-               if (status != LTTNG_OK) {
-                       goto error_consumer;
+                       /*
+                        * The metadata snapshot is done, ask the consumer to destroy it since
+                        * it's not monitored on the consumer side.
+                        */
+                       (void) kernel_consumer_destroy_metadata(socket, ksess->metadata);
                }
-
-               /*
-                * The metadata snapshot is done, ask the consumer to destroy it since
-                * it's not monitored on the consumer side.
-                */
-               (void) kernel_consumer_destroy_metadata(socket, ksess->metadata);
        }
 
 error_consumer:
@@ -1757,7 +1815,6 @@ error:
        /* Restore metadata state.*/
        ksess->metadata = saved_metadata;
        ksess->metadata_stream_fd = saved_metadata_fd;
-       rcu_read_unlock();
        free(trace_path);
        return status;
 }
@@ -1776,8 +1833,7 @@ int kernel_syscall_mask(int chan_fd, char **syscall_mask, uint32_t *nr_bits)
        return kernctl_syscall_mask(chan_fd, syscall_mask, nr_bits);
 }
 
-static
-int kernel_tracer_abi_greater_or_equal(unsigned int major, unsigned int minor)
+static int kernel_tracer_abi_greater_or_equal(unsigned int major, unsigned int minor)
 {
        int ret;
        struct lttng_kernel_abi_tracer_abi_version abi;
@@ -1800,7 +1856,7 @@ error:
  * Return 1 on success, 0 when feature is not supported, negative value in case
  * of errors.
  */
-int kernel_supports_ring_buffer_snapshot_sample_positions(void)
+int kernel_supports_ring_buffer_snapshot_sample_positions()
 {
        /*
         * RING_BUFFER_SNAPSHOT_SAMPLE_POSITIONS was introduced in 2.3
@@ -1814,7 +1870,7 @@ int kernel_supports_ring_buffer_snapshot_sample_positions(void)
  * Return 1 on success, 0 when feature is not supported, negative value in case
  * of errors.
  */
-int kernel_supports_ring_buffer_packet_sequence_number(void)
+int kernel_supports_ring_buffer_packet_sequence_number()
 {
        /*
         * Packet sequence number was introduced in LTTng 2.8,
@@ -1829,7 +1885,7 @@ int kernel_supports_ring_buffer_packet_sequence_number(void)
  * Return 1 on success, 0 when feature is not supported, negative value in case
  * of errors.
  */
-int kernel_supports_event_notifiers(void)
+int kernel_supports_event_notifiers()
 {
        /*
         * Event notifiers were introduced in LTTng 2.13, lttng-modules ABI 2.6.
@@ -1853,56 +1909,58 @@ enum lttng_error_code kernel_rotate_session(struct ltt_session *session)
        LTTNG_ASSERT(ksess);
        LTTNG_ASSERT(ksess->consumer);
 
-       DBG("Rotate kernel session %s started (session %" PRIu64 ")",
-                       session->name, session->id);
+       DBG("Rotate kernel session %s started (session %" PRIu64 ")", session->name, session->id);
 
-       rcu_read_lock();
+       {
+               /*
+                * Note that this loop will end after one iteration given that there is
+                * only one kernel consumer.
+                */
+               lttng::urcu::read_lock_guard read_lock;
 
-       /*
-        * Note that this loop will end after one iteration given that there is
-        * only one kernel consumer.
-        */
-       cds_lfht_for_each_entry(ksess->consumer->socks->ht, &iter.iter,
-                       socket, node.node) {
-               struct ltt_kernel_channel *chan;
-
-               /* For each channel, ask the consumer to rotate it. */
-               cds_list_for_each_entry(chan, &ksess->channel_list.head, list) {
-                       DBG("Rotate kernel channel %" PRIu64 ", session %s",
-                                       chan->key, session->name);
-                       ret = consumer_rotate_channel(socket, chan->key,
-                                       ksess->consumer,
-                                       /* is_metadata_channel */ false);
+               cds_lfht_for_each_entry (
+                       ksess->consumer->socks->ht, &iter.iter, socket, node.node) {
+                       struct ltt_kernel_channel *chan;
+
+                       /* For each channel, ask the consumer to rotate it. */
+                       cds_list_for_each_entry (chan, &ksess->channel_list.head, list) {
+                               DBG("Rotate kernel channel %" PRIu64 ", session %s",
+                                   chan->key,
+                                   session->name);
+                               ret = consumer_rotate_channel(socket,
+                                                             chan->key,
+                                                             ksess->consumer,
+                                                             /* is_metadata_channel */ false);
+                               if (ret < 0) {
+                                       status = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
+                                       goto error;
+                               }
+                       }
+
+                       /*
+                        * Rotate the metadata channel.
+                        */
+                       ret = consumer_rotate_channel(socket,
+                                                     ksess->metadata->key,
+                                                     ksess->consumer,
+                                                     /* is_metadata_channel */ true);
                        if (ret < 0) {
                                status = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
                                goto error;
                        }
                }
-
-               /*
-                * Rotate the metadata channel.
-                */
-               ret = consumer_rotate_channel(socket, ksess->metadata->key,
-                               ksess->consumer,
-                               /* is_metadata_channel */ true);
-               if (ret < 0) {
-                       status = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
-                       goto error;
-               }
        }
 
 error:
-       rcu_read_unlock();
        return status;
 }
 
-enum lttng_error_code kernel_create_channel_subdirectories(
-               const struct ltt_kernel_session *ksess)
+enum lttng_error_code kernel_create_channel_subdirectories(const struct ltt_kernel_session *ksess)
 {
        enum lttng_error_code ret = LTTNG_OK;
        enum lttng_trace_chunk_status chunk_status;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        LTTNG_ASSERT(ksess->current_trace_chunk);
 
        /*
@@ -1910,28 +1968,74 @@ enum lttng_error_code kernel_create_channel_subdirectories(
         * of implicitly creating the channel's path.
         */
        chunk_status = lttng_trace_chunk_create_subdirectory(
-                       ksess->current_trace_chunk,
-                       DEFAULT_KERNEL_TRACE_DIR "/" DEFAULT_INDEX_DIR);
+               ksess->current_trace_chunk, DEFAULT_KERNEL_TRACE_DIR "/" DEFAULT_INDEX_DIR);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = LTTNG_ERR_CREATE_DIR_FAIL;
                goto error;
        }
 error:
-       rcu_read_unlock();
        return ret;
 }
 
+/*
+ * Get current kernel tracer status
+ */
+enum lttng_kernel_tracer_status get_kernel_tracer_status()
+{
+       if (!kernel_tracer_status) {
+               return LTTNG_KERNEL_TRACER_STATUS_ERR_UNKNOWN;
+       }
+
+       return *kernel_tracer_status;
+}
+
+/*
+ * Sets the kernel tracer status based on the positive errno code
+ */
+void set_kernel_tracer_status_from_modules_ret(int code)
+{
+       switch (code) {
+       case ENOENT:
+       {
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_MISSING);
+               break;
+       }
+       case ENOKEY:
+       case EKEYEXPIRED:
+       case EKEYREVOKED:
+       case EKEYREJECTED:
+       {
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_SIGNATURE);
+               break;
+       }
+       default:
+       {
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_UNKNOWN);
+               break;
+       }
+       }
+}
+
 /*
  * Setup necessary data for kernel tracer action.
  */
-int init_kernel_tracer(void)
+int init_kernel_tracer()
 {
        int ret;
        bool is_root = !getuid();
 
+       const auto log_status_on_exit = lttng::make_scope_exit([]() noexcept {
+               DBG_FMT("Kernel tracer status set to `{}`",
+                       kernel_tracer_status_to_str(*kernel_tracer_status));
+       });
+
        /* Modprobe lttng kernel modules */
        ret = modprobe_lttng_control();
        if (ret < 0) {
+               set_kernel_tracer_status_from_modules_ret(-ret);
                goto error;
        }
 
@@ -1939,18 +2043,22 @@ int init_kernel_tracer(void)
        kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
        if (kernel_tracer_fd < 0) {
                DBG("Failed to open %s", module_proc_lttng);
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_OPEN_PROC_LTTNG);
                goto error_open;
        }
 
        /* Validate kernel version */
-       ret = kernel_validate_version(&the_kernel_tracer_version,
-                       &the_kernel_tracer_abi_version);
+       ret = kernel_validate_version(&the_kernel_tracer_version, &the_kernel_tracer_abi_version);
        if (ret < 0) {
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_VERSION_MISMATCH);
                goto error_version;
        }
 
        ret = modprobe_lttng_data();
        if (ret < 0) {
+               set_kernel_tracer_status_from_modules_ret(-ret);
                goto error_modules;
        }
 
@@ -1960,13 +2068,15 @@ int init_kernel_tracer(void)
        }
        if (ret < 1) {
                WARN("Kernel tracer does not support buffer monitoring. "
-                       "The monitoring timer of channels in the kernel domain "
-                       "will be set to 0 (disabled).");
+                    "The monitoring timer of channels in the kernel domain "
+                    "will be set to 0 (disabled).");
        }
 
        ret = kernel_supports_event_notifiers();
        if (ret < 0) {
                ERR("Failed to check for kernel tracer event notifier support");
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER);
                goto error_modules;
        }
        ret = kernel_create_event_notifier_group(&kernel_tracer_event_notifier_group_fd);
@@ -1977,59 +2087,64 @@ int init_kernel_tracer(void)
        } else {
                enum event_notifier_error_accounting_status error_accounting_status;
                enum lttng_error_code error_code_ret =
-                               kernel_create_event_notifier_group_notification_fd(
-                                               &kernel_tracer_event_notifier_group_notification_fd);
+                       kernel_create_event_notifier_group_notification_fd(
+                               &kernel_tracer_event_notifier_group_notification_fd);
 
                if (error_code_ret != LTTNG_OK) {
+                       kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                               LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER);
                        goto error_modules;
                }
 
                error_accounting_status = event_notifier_error_accounting_register_kernel(
-                               kernel_tracer_event_notifier_group_fd);
+                       kernel_tracer_event_notifier_group_fd);
                if (error_accounting_status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                        ERR("Failed to initialize event notifier error accounting for kernel tracer");
                        error_code_ret = LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING;
+                       kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                               LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER);
                        goto error_modules;
                }
 
                kernel_token_to_event_notifier_rule_ht = cds_lfht_new(
-                               DEFAULT_HT_SIZE, 1, 0,
-                               CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING,
-                               NULL);
+                       DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
                if (!kernel_token_to_event_notifier_rule_ht) {
+                       kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                               LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER);
                        goto error_token_ht;
                }
        }
 
        DBG("Kernel tracer initialized: kernel tracer fd = %d, event notifier group fd = %d, event notifier group notification fd = %d",
-                       kernel_tracer_fd, kernel_tracer_event_notifier_group_fd,
-                       kernel_tracer_event_notifier_group_notification_fd);
+           kernel_tracer_fd,
+           kernel_tracer_event_notifier_group_fd,
+           kernel_tracer_event_notifier_group_notification_fd);
 
        ret = syscall_init_table(kernel_tracer_fd);
        if (ret < 0) {
                ERR("Unable to populate syscall table. Syscall tracing won't "
-                       "work for this session daemon.");
+                   "work for this session daemon.");
        }
 
+       kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+               LTTNG_KERNEL_TRACER_STATUS_INITIALIZED);
        return 0;
 
 error_version:
        modprobe_remove_lttng_control();
        ret = close(kernel_tracer_fd);
        if (ret) {
-               PERROR("Failed to close kernel tracer file descriptor: fd = %d",
-                               kernel_tracer_fd);
+               PERROR("Failed to close kernel tracer file descriptor: fd = %d", kernel_tracer_fd);
        }
 
        kernel_tracer_fd = -1;
        return LTTNG_ERR_KERN_VERSION;
 
-
 error_token_ht:
        ret = close(kernel_tracer_event_notifier_group_notification_fd);
        if (ret) {
                PERROR("Failed to close kernel tracer event notifier group notification file descriptor: fd = %d",
-                               kernel_tracer_event_notifier_group_notification_fd);
+                      kernel_tracer_event_notifier_group_notification_fd);
        }
 
        kernel_tracer_event_notifier_group_notification_fd = -1;
@@ -2038,15 +2153,14 @@ error_modules:
        ret = close(kernel_tracer_event_notifier_group_fd);
        if (ret) {
                PERROR("Failed to close kernel tracer event notifier group file descriptor: fd = %d",
-                               kernel_tracer_event_notifier_group_fd);
+                      kernel_tracer_event_notifier_group_fd);
        }
 
        kernel_tracer_event_notifier_group_fd = -1;
 
        ret = close(kernel_tracer_fd);
        if (ret) {
-               PERROR("Failed to close kernel tracer file descriptor: fd = %d",
-                               kernel_tracer_fd);
+               PERROR("Failed to close kernel tracer file descriptor: fd = %d", kernel_tracer_fd);
        }
 
        kernel_tracer_fd = -1;
@@ -2058,19 +2172,21 @@ error:
        WARN("No kernel tracer available");
        kernel_tracer_fd = -1;
        if (!is_root) {
+               kernel_tracer_status = nonstd::optional<enum lttng_kernel_tracer_status>(
+                       LTTNG_KERNEL_TRACER_STATUS_ERR_NEED_ROOT);
                return LTTNG_ERR_NEED_ROOT_SESSIOND;
        } else {
                return LTTNG_ERR_KERN_NA;
        }
 }
 
-void cleanup_kernel_tracer(void)
+void cleanup_kernel_tracer()
 {
        DBG2("Closing kernel event notifier group notification file descriptor");
        if (kernel_tracer_event_notifier_group_notification_fd >= 0) {
                int ret = notification_thread_command_remove_tracer_event_source(
-                               the_notification_thread_handle,
-                               kernel_tracer_event_notifier_group_notification_fd);
+                       the_notification_thread_handle,
+                       kernel_tracer_event_notifier_group_notification_fd);
                if (ret != LTTNG_OK) {
                        ERR("Failed to remove kernel event notifier notification from notification thread");
                }
@@ -2078,15 +2194,14 @@ void cleanup_kernel_tracer(void)
                ret = close(kernel_tracer_event_notifier_group_notification_fd);
                if (ret) {
                        PERROR("Failed to close kernel event notifier group notification file descriptor: fd = %d",
-                                       kernel_tracer_event_notifier_group_notification_fd);
+                              kernel_tracer_event_notifier_group_notification_fd);
                }
 
                kernel_tracer_event_notifier_group_notification_fd = -1;
        }
 
        if (kernel_token_to_event_notifier_rule_ht) {
-               const int ret = cds_lfht_destroy(
-                               kernel_token_to_event_notifier_rule_ht, NULL);
+               const int ret = cds_lfht_destroy(kernel_token_to_event_notifier_rule_ht, nullptr);
                LTTNG_ASSERT(ret == 0);
        }
 
@@ -2096,7 +2211,7 @@ void cleanup_kernel_tracer(void)
 
                if (ret) {
                        PERROR("Failed to close kernel event notifier group file descriptor: fd = %d",
-                                       kernel_tracer_event_notifier_group_fd);
+                              kernel_tracer_event_notifier_group_fd);
                }
 
                kernel_tracer_event_notifier_group_fd = -1;
@@ -2108,16 +2223,17 @@ void cleanup_kernel_tracer(void)
 
                if (ret) {
                        PERROR("Failed to close kernel tracer file descriptor: fd = %d",
-                                       kernel_tracer_fd);
+                              kernel_tracer_fd);
                }
 
                kernel_tracer_fd = -1;
        }
 
+       kernel_tracer_status = nonstd::nullopt;
        free(syscall_table);
 }
 
-bool kernel_tracer_is_initialized(void)
+bool kernel_tracer_is_initialized()
 {
        return kernel_tracer_fd >= 0;
 }
@@ -2138,10 +2254,7 @@ enum lttng_error_code kernel_clear_session(struct ltt_session *session)
        LTTNG_ASSERT(ksess);
        LTTNG_ASSERT(ksess->consumer);
 
-       DBG("Clear kernel session %s (session %" PRIu64 ")",
-                       session->name, session->id);
-
-       rcu_read_lock();
+       DBG("Clear kernel session %s (session %" PRIu64 ")", session->name, session->id);
 
        if (ksess->active) {
                ERR("Expecting inactive session %s (%" PRIu64 ")", session->name, session->id);
@@ -2149,41 +2262,46 @@ enum lttng_error_code kernel_clear_session(struct ltt_session *session)
                goto end;
        }
 
-       /*
-        * Note that this loop will end after one iteration given that there is
-        * only one kernel consumer.
-        */
-       cds_lfht_for_each_entry(ksess->consumer->socks->ht, &iter.iter,
-                       socket, node.node) {
-               struct ltt_kernel_channel *chan;
-
-               /* For each channel, ask the consumer to clear it. */
-               cds_list_for_each_entry(chan, &ksess->channel_list.head, list) {
-                       DBG("Clear kernel channel %" PRIu64 ", session %s",
-                                       chan->key, session->name);
-                       ret = consumer_clear_channel(socket, chan->key);
-                       if (ret < 0) {
-                               goto error;
+       {
+               /*
+                * Note that this loop will end after one iteration given that there is
+                * only one kernel consumer.
+                */
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       ksess->consumer->socks->ht, &iter.iter, socket, node.node) {
+                       struct ltt_kernel_channel *chan;
+
+                       /* For each channel, ask the consumer to clear it. */
+                       cds_list_for_each_entry (chan, &ksess->channel_list.head, list) {
+                               DBG("Clear kernel channel %" PRIu64 ", session %s",
+                                   chan->key,
+                                   session->name);
+                               ret = consumer_clear_channel(socket, chan->key);
+                               if (ret < 0) {
+                                       goto error;
+                               }
+                       }
+
+                       if (!ksess->metadata) {
+                               /*
+                                * Nothing to do for the metadata.
+                                * This is a snapshot session.
+                                * The metadata is genererated on the fly.
+                                */
+                               continue;
                        }
-               }
 
-               if (!ksess->metadata) {
                        /*
-                        * Nothing to do for the metadata.
-                        * This is a snapshot session.
-                        * The metadata is genererated on the fly.
+                        * Clear the metadata channel.
+                        * Metadata channel is not cleared per se but we still need to
+                        * perform a rotation operation on it behind the scene.
                         */
-                       continue;
-               }
-
-               /*
-                * Clear the metadata channel.
-                * Metadata channel is not cleared per se but we still need to
-                * perform a rotation operation on it behind the scene.
-                */
-               ret = consumer_clear_channel(socket, ksess->metadata->key);
-               if (ret < 0) {
-                       goto error;
+                       ret = consumer_clear_channel(socket, ksess->metadata->key);
+                       if (ret < 0) {
+                               goto error;
+                       }
                }
        }
 
@@ -2191,19 +2309,18 @@ enum lttng_error_code kernel_clear_session(struct ltt_session *session)
 error:
        switch (-ret) {
        case LTTCOMM_CONSUMERD_RELAYD_CLEAR_DISALLOWED:
-             status = LTTNG_ERR_CLEAR_RELAY_DISALLOWED;
-             break;
+               status = LTTNG_ERR_CLEAR_RELAY_DISALLOWED;
+               break;
        default:
-             status = LTTNG_ERR_CLEAR_FAIL_CONSUMER;
-             break;
+               status = LTTNG_ERR_CLEAR_FAIL_CONSUMER;
+               break;
        }
 end:
-       rcu_read_unlock();
        return status;
 }
 
-enum lttng_error_code kernel_create_event_notifier_group_notification_fd(
-               int *event_notifier_group_notification_fd)
+enum lttng_error_code
+kernel_create_event_notifier_group_notification_fd(int *event_notifier_group_notification_fd)
 {
        int local_fd = -1, ret;
        enum lttng_error_code error_code_ret;
@@ -2211,7 +2328,7 @@ enum lttng_error_code kernel_create_event_notifier_group_notification_fd(
        LTTNG_ASSERT(event_notifier_group_notification_fd);
 
        ret = kernctl_create_event_notifier_group_notification_fd(
-                       kernel_tracer_event_notifier_group_fd);
+               kernel_tracer_event_notifier_group_fd);
        if (ret < 0) {
                PERROR("Failed to create kernel event notifier group notification file descriptor");
                error_code_ret = LTTNG_ERR_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD;
@@ -2224,13 +2341,12 @@ enum lttng_error_code kernel_create_event_notifier_group_notification_fd(
        ret = fcntl(local_fd, F_SETFD, FD_CLOEXEC);
        if (ret < 0) {
                PERROR("Failed to set FD_CLOEXEC on kernel event notifier group notification file descriptor: fd = %d",
-                               local_fd);
+                      local_fd);
                error_code_ret = LTTNG_ERR_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD;
                goto error;
        }
 
-       DBG("Created kernel notifier group notification file descriptor: fd = %d",
-                       local_fd);
+       DBG("Created kernel notifier group notification file descriptor: fd = %d", local_fd);
        error_code_ret = LTTNG_OK;
        *event_notifier_group_notification_fd = local_fd;
        local_fd = -1;
@@ -2240,55 +2356,51 @@ error:
                ret = close(local_fd);
                if (ret) {
                        PERROR("Failed to close kernel event notifier group notification file descriptor: fd = %d",
-                                       local_fd);
+                              local_fd);
                }
        }
 
        return error_code_ret;
 }
 
-enum lttng_error_code kernel_destroy_event_notifier_group_notification_fd(
-               int event_notifier_group_notification_fd)
+enum lttng_error_code
+kernel_destroy_event_notifier_group_notification_fd(int event_notifier_group_notification_fd)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
 
        DBG("Closing event notifier group notification file descriptor: fd = %d",
-                       event_notifier_group_notification_fd);
+           event_notifier_group_notification_fd);
        if (event_notifier_group_notification_fd >= 0) {
                const int ret = close(event_notifier_group_notification_fd);
                if (ret) {
                        PERROR("Failed to close event notifier group notification file descriptor: fd = %d",
-                                       event_notifier_group_notification_fd);
+                              event_notifier_group_notification_fd);
                }
        }
 
        return ret_code;
 }
 
-static
-unsigned long hash_trigger(const struct lttng_trigger *trigger)
+static unsigned long hash_trigger(const struct lttng_trigger *trigger)
 {
-       const struct lttng_condition *condition =
-                       lttng_trigger_get_const_condition(trigger);
+       const struct lttng_condition *condition = lttng_trigger_get_const_condition(trigger);
 
        return lttng_condition_hash(condition);
 }
 
-static
-int match_trigger(struct cds_lfht_node *node, const void *key)
+static int match_trigger(struct cds_lfht_node *node, const void *key)
 {
        const struct ltt_kernel_event_notifier_rule *event_notifier_rule;
        const struct lttng_trigger *trigger = (lttng_trigger *) key;
 
-       event_notifier_rule = caa_container_of(node,
-                       const struct ltt_kernel_event_notifier_rule, ht_node);
+       event_notifier_rule =
+               caa_container_of(node, const struct ltt_kernel_event_notifier_rule, ht_node);
 
        return lttng_trigger_is_equal(trigger, event_notifier_rule->trigger);
 }
 
 static enum lttng_error_code kernel_create_event_notifier_rule(
-               struct lttng_trigger *trigger,
-               const struct lttng_credentials *creds, uint64_t token)
+       struct lttng_trigger *trigger, const struct lttng_credentials *creds, uint64_t token)
 {
        int err, fd, ret = 0;
        enum lttng_error_code error_code_ret;
@@ -2298,8 +2410,8 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
        struct ltt_kernel_event_notifier_rule *event_notifier_rule;
        struct lttng_kernel_abi_event_notifier kernel_event_notifier = {};
        unsigned int capture_bytecode_count = 0, i;
-       const struct lttng_condition *condition = NULL;
-       const struct lttng_event_rule *event_rule = NULL;
+       const struct lttng_condition *condition = nullptr;
+       const struct lttng_event_rule *event_rule = nullptr;
        enum lttng_condition_status cond_status;
 
        LTTNG_ASSERT(trigger);
@@ -2311,36 +2423,34 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
        LTTNG_ASSERT(condition_type == LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
        /* Does not acquire a reference. */
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(event_rule);
 
        event_rule_type = lttng_event_rule_get_type(event_rule);
        LTTNG_ASSERT(event_rule_type != LTTNG_EVENT_RULE_TYPE_UNKNOWN);
 
-       error_code_ret = trace_kernel_create_event_notifier_rule(trigger, token,
-                       lttng_condition_event_rule_matches_get_error_counter_index(
-                                       condition),
-                       &event_notifier_rule);
+       error_code_ret = trace_kernel_create_event_notifier_rule(
+               trigger,
+               token,
+               lttng_condition_event_rule_matches_get_error_counter_index(condition),
+               &event_notifier_rule);
        if (error_code_ret != LTTNG_OK) {
                goto error;
        }
 
-       error_code_ret = trace_kernel_init_event_notifier_from_event_rule(
-                       event_rule, &kernel_event_notifier);
+       error_code_ret = trace_kernel_init_event_notifier_from_event_rule(event_rule,
+                                                                         &kernel_event_notifier);
        if (error_code_ret != LTTNG_OK) {
                goto free_event;
        }
 
        kernel_event_notifier.event.token = event_notifier_rule->token;
        kernel_event_notifier.error_counter_idx =
-                       lttng_condition_event_rule_matches_get_error_counter_index(
-                                       condition);
+               lttng_condition_event_rule_matches_get_error_counter_index(condition);
 
-       fd = kernctl_create_event_notifier(
-                       kernel_tracer_event_notifier_group_fd,
-                       &kernel_event_notifier);
+       fd = kernctl_create_event_notifier(kernel_tracer_event_notifier_group_fd,
+                                          &kernel_event_notifier);
        if (fd < 0) {
                switch (-fd) {
                case EEXIST:
@@ -2352,12 +2462,13 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
                        break;
                case ENOENT:
                        WARN("Failed to create kernel event notifier: not found: name = '%s'",
-                                       kernel_event_notifier.event.name);
+                            kernel_event_notifier.event.name);
                        error_code_ret = LTTNG_ERR_KERN_ENABLE_FAIL;
                        break;
                default:
                        PERROR("Failed to create kernel event notifier: error code = %d, name = '%s'",
-                                       fd, kernel_event_notifier.event.name);
+                              fd,
+                              kernel_event_notifier.event.name);
                        error_code_ret = LTTNG_ERR_KERN_ENABLE_FAIL;
                }
                goto free_event;
@@ -2368,7 +2479,7 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
        err = fcntl(event_notifier_rule->fd, F_SETFD, FD_CLOEXEC);
        if (err < 0) {
                PERROR("Failed to set FD_CLOEXEC on kernel event notifier file descriptor: fd = %d",
-                               fd);
+                      fd);
                error_code_ret = LTTNG_ERR_FATAL;
                goto set_cloexec_error;
        }
@@ -2388,10 +2499,9 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
                }
        }
 
-       if (lttng_event_rule_get_type(event_rule) ==
-                       LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE) {
+       if (lttng_event_rule_get_type(event_rule) == LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE) {
                ret = userspace_probe_event_rule_add_callsites(
-                               event_rule, creds, event_notifier_rule->fd);
+                       event_rule, creds, event_notifier_rule->fd);
                if (ret) {
                        error_code_ret = LTTNG_ERR_KERN_ENABLE_FAIL;
                        goto add_callsite_error;
@@ -2400,15 +2510,15 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
 
        /* Set the capture bytecode if any. */
        cond_status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &capture_bytecode_count);
+               condition, &capture_bytecode_count);
        LTTNG_ASSERT(cond_status == LTTNG_CONDITION_STATUS_OK);
 
        for (i = 0; i < capture_bytecode_count; i++) {
                const struct lttng_bytecode *capture_bytecode =
-                               lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
-                                               condition, i);
+                       lttng_condition_event_rule_matches_get_capture_bytecode_at_index(condition,
+                                                                                        i);
 
-               if (capture_bytecode == NULL) {
+               if (capture_bytecode == nullptr) {
                        ERR("Unexpected NULL capture bytecode on condition");
                        error_code_ret = LTTNG_ERR_KERN_ENABLE_FAIL;
                        goto capture_error;
@@ -2417,7 +2527,7 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
                ret = kernctl_capture(event_notifier_rule->fd, capture_bytecode);
                if (ret < 0) {
                        ERR("Failed to set capture bytecode on event notifier rule fd: fd = %d",
-                                       event_notifier_rule->fd);
+                           event_notifier_rule->fd);
                        error_code_ret = LTTNG_ERR_KERN_ENABLE_FAIL;
                        goto capture_error;
                }
@@ -2438,14 +2548,16 @@ static enum lttng_error_code kernel_create_event_notifier_rule(
        }
 
        /* Add trigger to kernel token mapping in the hash table. */
-       rcu_read_lock();
-       cds_lfht_add(kernel_token_to_event_notifier_rule_ht, hash_trigger(trigger),
-                       &event_notifier_rule->ht_node);
-       rcu_read_unlock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_add(kernel_token_to_event_notifier_rule_ht,
+                            hash_trigger(trigger),
+                            &event_notifier_rule->ht_node);
+       }
 
        DBG("Created kernel event notifier: name = '%s', fd = %d",
-                       kernel_event_notifier.event.name,
-                       event_notifier_rule->fd);
+           kernel_event_notifier.event.name,
+           event_notifier_rule->fd);
 
        return LTTNG_OK;
 
@@ -2454,37 +2566,34 @@ add_callsite_error:
 enable_error:
 set_cloexec_error:
 filter_error:
-       {
-               const int close_ret = close(event_notifier_rule->fd);
+{
+       const int close_ret = close(event_notifier_rule->fd);
 
-               if (close_ret) {
-                       PERROR("Failed to close kernel event notifier file descriptor: fd = %d",
-                                       event_notifier_rule->fd);
-               }
+       if (close_ret) {
+               PERROR("Failed to close kernel event notifier file descriptor: fd = %d",
+                      event_notifier_rule->fd);
        }
+}
 free_event:
        free(event_notifier_rule);
 error:
        return error_code_ret;
 }
 
-enum lttng_error_code kernel_register_event_notifier(
-               struct lttng_trigger *trigger,
-               const struct lttng_credentials *cmd_creds)
+enum lttng_error_code kernel_register_event_notifier(struct lttng_trigger *trigger,
+                                                    const struct lttng_credentials *cmd_creds)
 {
        enum lttng_error_code ret;
        enum lttng_condition_status status;
        enum lttng_domain_type domain_type;
        const struct lttng_event_rule *event_rule;
-       const struct lttng_condition *const condition =
-                       lttng_trigger_get_const_condition(trigger);
+       const struct lttng_condition *const condition = lttng_trigger_get_const_condition(trigger);
        const uint64_t token = lttng_trigger_get_tracer_token(trigger);
 
        LTTNG_ASSERT(condition);
 
        /* Does not acquire a reference to the event rule. */
-       status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
 
        domain_type = lttng_event_rule_get_domain_type(event_rule);
@@ -2498,8 +2607,7 @@ enum lttng_error_code kernel_register_event_notifier(
        return ret;
 }
 
-enum lttng_error_code kernel_unregister_event_notifier(
-               const struct lttng_trigger *trigger)
+enum lttng_error_code kernel_unregister_event_notifier(const struct lttng_trigger *trigger)
 {
        struct ltt_kernel_event_notifier_rule *token_event_rule_element;
        struct cds_lfht_node *node;
@@ -2507,10 +2615,13 @@ enum lttng_error_code kernel_unregister_event_notifier(
        enum lttng_error_code error_code_ret;
        int ret;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        cds_lfht_lookup(kernel_token_to_event_notifier_rule_ht,
-                       hash_trigger(trigger), match_trigger, trigger, &iter);
+                       hash_trigger(trigger),
+                       match_trigger,
+                       trigger,
+                       &iter);
 
        node = cds_lfht_iter_get_node(&iter);
        if (!node) {
@@ -2518,8 +2629,8 @@ enum lttng_error_code kernel_unregister_event_notifier(
                goto error;
        }
 
-       token_event_rule_element = caa_container_of(node,
-                       struct ltt_kernel_event_notifier_rule, ht_node);
+       token_event_rule_element =
+               caa_container_of(node, struct ltt_kernel_event_notifier_rule, ht_node);
 
        ret = kernel_disable_event_notifier_rule(token_event_rule_element);
        if (ret) {
@@ -2531,12 +2642,11 @@ enum lttng_error_code kernel_unregister_event_notifier(
        error_code_ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
 
        return error_code_ret;
 }
 
-int kernel_get_notification_fd(void)
+int kernel_get_notification_fd()
 {
        return kernel_tracer_event_notifier_group_notification_fd;
 }
index bb01651213dfd211dd75ba459e70f59f9c91916c..6cb89a19ff53782c15dd9a954f9b2c95237b3526 100644 (file)
  */
 #define KERNEL_EVENT_INIT_LIST_SIZE 64
 
-int kernel_add_channel_context(struct ltt_kernel_channel *chan,
-               struct ltt_kernel_context *ctx);
+int kernel_add_channel_context(struct ltt_kernel_channel *chan, struct ltt_kernel_context *ctx);
 int kernel_create_session(struct ltt_session *session);
-int kernel_create_channel(struct ltt_kernel_session *session,
-               struct lttng_channel *chan);
-int kernel_create_event(struct lttng_event *ev, struct ltt_kernel_channel *channel,
-               char *filter_expression, struct lttng_bytecode *filter);
+int kernel_create_channel(struct ltt_kernel_session *session, struct lttng_channel *chan);
+int kernel_create_event(struct lttng_event *ev,
+                       struct ltt_kernel_channel *channel,
+                       char *filter_expression,
+                       struct lttng_bytecode *filter);
 int kernel_disable_channel(struct ltt_kernel_channel *chan);
 int kernel_disable_event(struct ltt_kernel_event *event);
 int kernel_enable_event(struct ltt_kernel_event *event);
 int kernel_enable_channel(struct ltt_kernel_channel *chan);
-enum lttng_error_code kernel_process_attr_tracker_set_tracking_policy(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy);
-enum lttng_error_code kernel_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-enum lttng_error_code kernel_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-const struct process_attr_tracker *kernel_get_process_attr_tracker(
-               struct ltt_kernel_session *session,
-               enum lttng_process_attr process_attr);
+enum lttng_error_code
+kernel_process_attr_tracker_set_tracking_policy(struct ltt_kernel_session *session,
+                                               enum lttng_process_attr process_attr,
+                                               enum lttng_tracking_policy policy);
+enum lttng_error_code
+kernel_process_attr_tracker_inclusion_set_add_value(struct ltt_kernel_session *session,
+                                                   enum lttng_process_attr process_attr,
+                                                   const struct process_attr_value *value);
+enum lttng_error_code
+kernel_process_attr_tracker_inclusion_set_remove_value(struct ltt_kernel_session *session,
+                                                      enum lttng_process_attr process_attr,
+                                                      const struct process_attr_value *value);
+const struct process_attr_tracker *
+kernel_get_process_attr_tracker(struct ltt_kernel_session *session,
+                               enum lttng_process_attr process_attr);
 int kernel_open_metadata(struct ltt_kernel_session *session);
 int kernel_open_metadata_stream(struct ltt_kernel_session *session);
 int kernel_open_channel_stream(struct ltt_kernel_channel *channel);
@@ -57,42 +57,40 @@ int kernel_metadata_flush_buffer(int fd);
 int kernel_start_session(struct ltt_kernel_session *session);
 int kernel_stop_session(struct ltt_kernel_session *session);
 ssize_t kernel_list_events(struct lttng_event **event_list);
-void kernel_wait_quiescent(void);
+void kernel_wait_quiescent();
 int kernel_validate_version(struct lttng_kernel_abi_tracer_version *kernel_tracer_version,
-               struct lttng_kernel_abi_tracer_abi_version *kernel_tracer_abi_version);
+                           struct lttng_kernel_abi_tracer_abi_version *kernel_tracer_abi_version);
 void kernel_destroy_session(struct ltt_kernel_session *ksess);
 void kernel_free_session(struct ltt_kernel_session *ksess);
 void kernel_destroy_channel(struct ltt_kernel_channel *kchan);
-enum lttng_error_code kernel_snapshot_record(
-               struct ltt_kernel_session *ksess,
-               const struct consumer_output *output,
-               uint64_t nb_packets_per_stream);
+enum lttng_error_code kernel_snapshot_record(struct ltt_kernel_session *ksess,
+                                            const struct consumer_output *output,
+                                            uint64_t nb_packets_per_stream);
 int kernel_syscall_mask(int chan_fd, char **syscall_mask, uint32_t *nr_bits);
 enum lttng_error_code kernel_rotate_session(struct ltt_session *session);
 enum lttng_error_code kernel_clear_session(struct ltt_session *session);
 
-int init_kernel_workarounds(void);
-int kernel_supports_ring_buffer_snapshot_sample_positions(void);
-int kernel_supports_ring_buffer_packet_sequence_number(void);
-int kernel_supports_event_notifiers(void);
-int init_kernel_tracer(void);
-void cleanup_kernel_tracer(void);
-bool kernel_tracer_is_initialized(void);
+int init_kernel_workarounds();
+int kernel_supports_ring_buffer_snapshot_sample_positions();
+int kernel_supports_ring_buffer_packet_sequence_number();
+int kernel_supports_event_notifiers();
+enum lttng_kernel_tracer_status get_kernel_tracer_status();
+void set_kernel_tracer_status_from_modules_ret(int);
+int init_kernel_tracer();
+void cleanup_kernel_tracer();
+bool kernel_tracer_is_initialized();
 
-enum lttng_error_code kernel_create_channel_subdirectories(
-               const struct ltt_kernel_session *ksess);
+enum lttng_error_code kernel_create_channel_subdirectories(const struct ltt_kernel_session *ksess);
 
-enum lttng_error_code kernel_create_event_notifier_group_notification_fd(
-               int *event_notifier_group_notification_fd);
-enum lttng_error_code kernel_destroy_event_notifier_group_notification_fd(
-               int event_notifier_group_notification_fd);
+enum lttng_error_code
+kernel_create_event_notifier_group_notification_fd(int *event_notifier_group_notification_fd);
+enum lttng_error_code
+kernel_destroy_event_notifier_group_notification_fd(int event_notifier_group_notification_fd);
 
-enum lttng_error_code kernel_register_event_notifier(
-               struct lttng_trigger *trigger,
-               const struct lttng_credentials *cmd_creds);
-enum lttng_error_code kernel_unregister_event_notifier(
-               const struct lttng_trigger *trigger);
+enum lttng_error_code kernel_register_event_notifier(struct lttng_trigger *trigger,
+                                                    const struct lttng_credentials *cmd_creds);
+enum lttng_error_code kernel_unregister_event_notifier(const struct lttng_trigger *trigger);
 
-int kernel_get_notification_fd(void);
+int kernel_get_notification_fd();
 
 #endif /* _LTT_KERNEL_CTL_H */
index fa4601d695405df8e1ad705d9aa0c31b525bda64..a10586bb891a80c5017245bb919a83775bffe51f 100644 (file)
@@ -9,19 +9,20 @@
 #ifndef _LTT_SESSIOND_H
 #define _LTT_SESSIOND_H
 
-#include <urcu.h>
-#include <urcu/wfcqueue.h>
+#include "notification-thread.hpp"
+#include "rotation-thread.hpp"
+#include "session.hpp"
+#include "sessiond-config.hpp"
+#include "ust-app.hpp"
 
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/payload.hpp>
 #include <common/compat/poll.hpp>
 #include <common/compat/socket.hpp>
+#include <common/payload.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/uuid.hpp>
 
-#include "session.hpp"
-#include "ust-app.hpp"
-#include "notification-thread.hpp"
-#include "sessiond-config.hpp"
+#include <urcu.h>
+#include <urcu/wfcqueue.h>
 
 /*
  * Consumer daemon state which is changed when spawning it, killing it or in
@@ -30,7 +31,7 @@
 enum consumerd_state {
        CONSUMER_STARTED = 1,
        CONSUMER_STOPPED = 2,
-       CONSUMER_ERROR   = 3,
+       CONSUMER_ERROR = 3,
 };
 
 /* Unique identifier of a session daemon instance. */
@@ -67,6 +68,9 @@ extern struct lttng_kernel_abi_tracer_abi_version the_kernel_tracer_abi_version;
 /* Notification thread handle. */
 extern struct notification_thread_handle *the_notification_thread_handle;
 
+/* Rotation thread handle. */
+extern lttng::sessiond::rotation_thread::uptr the_rotation_thread_handle;
+
 /*
  * This contains extra data needed for processing a command received by the
  * session daemon from the lttng client.
@@ -140,17 +144,16 @@ extern struct consumer_data the_ustconsumer32_data;
 extern struct consumer_data the_ustconsumer64_data;
 extern struct consumer_data the_kconsumer_data;
 
-int sessiond_init_thread_quit_pipe(void);
-int sessiond_check_thread_quit_pipe(int fd, uint32_t events);
-int sessiond_wait_for_quit_pipe(int timeout_ms);
-int sessiond_notify_quit_pipe(void);
-void sessiond_close_quit_pipe(void);
+int sessiond_init_main_quit_pipe();
+int sessiond_wait_for_main_quit_pipe(int timeout_ms);
+int sessiond_notify_main_quit_pipe();
+void sessiond_close_main_quit_pipe();
 
 int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size);
-void sessiond_signal_parents(void);
+void sessiond_signal_parents();
 
 void sessiond_set_client_thread_state(bool running);
-void sessiond_wait_client_thread_stopped(void);
+void sessiond_wait_client_thread_stopped();
 
 void *thread_manage_consumer(void *data);
 
index 8a4ce39ea8e6bcd6b9fbf71d9cd39f02d2f99ad1..821bbaa34f80b6e1c6d572192909c0ec0257aab2 100644 (file)
@@ -6,15 +6,16 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdbool.h>
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "lttng-syscall.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
+#include <common/urcu.hpp>
 
-#include "lttng-sessiond.hpp"
-#include "kernel.hpp"
-#include "lttng-syscall.hpp"
-#include "utils.hpp"
+#include <stdbool.h>
 
 /* Global syscall table. */
 struct syscall *syscall_table;
@@ -40,7 +41,7 @@ int syscall_init_table(int tracer_fd)
        char name[SYSCALL_NAME_LEN];
 
 #if (SYSCALL_NAME_LEN == 255)
-#define SYSCALL_NAME_LEN_SCANF_IS_A_BROKEN_API "254"
+#define SYSCALL_NAME_LEN_SCANF_IS_A_BROKEN_API "254"
 #endif
 
        DBG3("Syscall init system call table");
@@ -68,10 +69,12 @@ int syscall_init_table(int tracer_fd)
        }
 
        while (fscanf(fp,
-                               "syscall { index = %zu; \
+                     "syscall { index = %zu; \
                                name = %" SYSCALL_NAME_LEN_SCANF_IS_A_BROKEN_API "[^;]; \
                                bitness = %u; };\n",
-                               &index, name, &bitness) == 3) {
+                     &index,
+                     name,
+                     &bitness) == 3) {
                at_least_one_syscall = true;
                if (index >= nbmem) {
                        struct syscall *new_list;
@@ -83,14 +86,14 @@ int syscall_init_table(int tracer_fd)
                                /* Overflow, stop everything, something went really wrong. */
                                ERR("Syscall listing memory size overflow. Stopping");
                                free(syscall_table);
-                               syscall_table = NULL;
+                               syscall_table = nullptr;
                                ret = -EINVAL;
                                goto error;
                        }
 
-                       DBG("Reallocating syscall table from %zu to %zu entries", nbmem,
-                                       new_nbmem);
-                       new_list = (struct syscall *) realloc(syscall_table, new_nbmem * sizeof(*new_list));
+                       DBG("Reallocating syscall table from %zu to %zu entries", nbmem, new_nbmem);
+                       new_list = (struct syscall *) realloc(syscall_table,
+                                                             new_nbmem * sizeof(*new_list));
                        if (!new_list) {
                                ret = -errno;
                                PERROR("syscall list realloc");
@@ -98,18 +101,17 @@ int syscall_init_table(int tracer_fd)
                        }
 
                        /* Zero out the new memory. */
-                       memset(new_list + nbmem, 0,
-                                       (new_nbmem - nbmem) * sizeof(*new_list));
+                       memset(new_list + nbmem, 0, (new_nbmem - nbmem) * sizeof(*new_list));
                        nbmem = new_nbmem;
                        syscall_table = new_list;
                }
                syscall_table[index].index = index;
                syscall_table[index].bitness = bitness;
-               if (lttng_strncpy(syscall_table[index].name, name,
-                               sizeof(syscall_table[index].name))) {
+               if (lttng_strncpy(
+                           syscall_table[index].name, name, sizeof(syscall_table[index].name))) {
                        ret = -EINVAL;
                        free(syscall_table);
-                       syscall_table = NULL;
+                       syscall_table = nullptr;
                        goto error;
                }
                /*
@@ -149,28 +151,31 @@ error_ioctl:
  * syscall hashtable used to track duplicate between 32 and 64 bit arch.
  *
  * This empty the hash table and destroys it after. After this, the pointer is
- * unsuable. RCU read side lock MUST be acquired before calling this.
+ * unsuable. RCU read side lock MUST NOT be acquired before calling this.
  */
 static void destroy_syscall_ht(struct lttng_ht *ht)
 {
        struct lttng_ht_iter iter;
        struct syscall *ksyscall;
 
-       ASSERT_RCU_READ_LOCKED();
-
        DBG3("Destroying syscall hash table.");
 
        if (!ht) {
                return;
        }
 
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, ksyscall, node.node) {
-               int ret;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, ksyscall, node.node) {
+                       int ret;
 
-               ret = lttng_ht_del(ht, &iter);
-               LTTNG_ASSERT(!ret);
-               free(ksyscall);
+                       ret = lttng_ht_del(ht, &iter);
+                       LTTNG_ASSERT(!ret);
+                       free(ksyscall);
+               }
        }
+
        lttng_ht_destroy(ht);
 }
 
@@ -196,13 +201,15 @@ static int init_syscall_ht(struct lttng_ht **ht)
 /*
  * Lookup a syscall in the given hash table by name.
  *
+ * RCU read lock MUST be acquired by the callers of this function.
+ *
  * Return syscall object if found or else NULL.
  */
 static struct syscall *lookup_syscall(struct lttng_ht *ht, const char *name)
 {
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
-       struct syscall *ksyscall = NULL;
+       struct syscall *ksyscall = nullptr;
 
        LTTNG_ASSERT(ht);
        LTTNG_ASSERT(name);
@@ -221,14 +228,17 @@ static struct syscall *lookup_syscall(struct lttng_ht *ht, const char *name)
  * syscall at index in the syscall table.
  */
 static void update_event_syscall_bitness(struct lttng_event *events,
-               unsigned int index, unsigned int syscall_index)
+                                        unsigned int index,
+                                        unsigned int syscall_index)
 {
        LTTNG_ASSERT(events);
 
        if (syscall_table[index].bitness == 32) {
-               events[syscall_index].flags = (lttng_event_flag) (events[syscall_index].flags | LTTNG_EVENT_FLAG_SYSCALL_32);
+               events[syscall_index].flags = (lttng_event_flag) (events[syscall_index].flags |
+                                                                 LTTNG_EVENT_FLAG_SYSCALL_32);
        } else {
-               events[syscall_index].flags = (lttng_event_flag) (events[syscall_index].flags | LTTNG_EVENT_FLAG_SYSCALL_64);
+               events[syscall_index].flags = (lttng_event_flag) (events[syscall_index].flags |
+                                                                 LTTNG_EVENT_FLAG_SYSCALL_64);
        }
 }
 
@@ -237,8 +247,7 @@ static void update_event_syscall_bitness(struct lttng_event *events,
  *
  * Return 0 on success else -LTTNG_ERR_NOMEM.
  */
-static int add_syscall_to_ht(struct lttng_ht *ht, unsigned int index,
-               unsigned int syscall_index)
+static int add_syscall_to_ht(struct lttng_ht *ht, unsigned int index, unsigned int syscall_index)
 {
        int ret;
        struct syscall *ksyscall;
@@ -251,8 +260,7 @@ static int add_syscall_to_ht(struct lttng_ht *ht, unsigned int index,
                goto error;
        }
 
-       strncpy(ksyscall->name, syscall_table[index].name,
-                       sizeof(ksyscall->name));
+       strncpy(ksyscall->name, syscall_table[index].name, sizeof(ksyscall->name));
        ksyscall->bitness = syscall_table[index].bitness;
        ksyscall->index = syscall_index;
        lttng_ht_node_init_str(&ksyscall->node, ksyscall->name);
@@ -275,14 +283,12 @@ ssize_t syscall_table_list(struct lttng_event **_events)
        ssize_t ret;
        struct lttng_event *events;
        /* Hash table used to filter duplicate out. */
-       struct lttng_ht *syscalls_ht = NULL;
+       struct lttng_ht *syscalls_ht = nullptr;
 
        LTTNG_ASSERT(_events);
 
        DBG("Syscall table listing.");
 
-       rcu_read_lock();
-
        /*
         * Allocate at least the number of total syscall we have even if some of
         * them might not be valid. The count below will make sure to return the
@@ -301,17 +307,20 @@ ssize_t syscall_table_list(struct lttng_event **_events)
        }
 
        for (i = 0; i < syscall_table_nb_entry; i++) {
-               struct syscall *ksyscall;
-
                /* Skip empty syscalls. */
                if (*syscall_table[i].name == '\0') {
                        continue;
                }
 
-               ksyscall = lookup_syscall(syscalls_ht, syscall_table[i].name);
-               if (ksyscall) {
-                       update_event_syscall_bitness(events, i, ksyscall->index);
-                       continue;
+               {
+                       lttng::urcu::read_lock_guard read_lock;
+                       struct syscall *ksyscall;
+
+                       ksyscall = lookup_syscall(syscalls_ht, syscall_table[i].name);
+                       if (ksyscall) {
+                               update_event_syscall_bitness(events, i, ksyscall->index);
+                               continue;
+                       }
                }
 
                ret = add_syscall_to_ht(syscalls_ht, i, index);
@@ -320,8 +329,7 @@ ssize_t syscall_table_list(struct lttng_event **_events)
                }
 
                /* Copy the event information in the event's array. */
-               strncpy(events[index].name, syscall_table[i].name,
-                               sizeof(events[index].name));
+               strncpy(events[index].name, syscall_table[i].name, sizeof(events[index].name));
                update_event_syscall_bitness(events, i, index);
                events[index].type = LTTNG_EVENT_SYSCALL;
                /* This makes the command line not print the enabled/disabled field. */
@@ -331,12 +339,10 @@ ssize_t syscall_table_list(struct lttng_event **_events)
 
        destroy_syscall_ht(syscalls_ht);
        *_events = events;
-       rcu_read_unlock();
        return index;
 
 error:
        destroy_syscall_ht(syscalls_ht);
        free(events);
-       rcu_read_unlock();
        return ret;
 }
index 78691f95dc7eb2c6658c7c32970e605712539422..8ba8c7ea095294448511091dc8cf75b8c2f54afc 100644 (file)
@@ -8,19 +8,20 @@
 #ifndef LTTNG_SYSCALL_H
 #define LTTNG_SYSCALL_H
 
+#include "trace-kernel.hpp"
+
 #include <common/hashtable/hashtable.hpp>
-#include <lttng/event.h>
 
-#include "trace-kernel.hpp"
+#include <lttng/event.h>
 
 /*
  * Default size of the kernel system call array. With this size, we usually
  * reallocate twice considering a 32 bit compat layer also.
  */
-#define SYSCALL_TABLE_INIT_SIZE    256
+#define SYSCALL_TABLE_INIT_SIZE 256
 
 /* Maximum length of a syscall name. */
-#define SYSCALL_NAME_LEN           255
+#define SYSCALL_NAME_LEN 255
 
 /*
  * Represent a kernel syscall and used when we are populating the internal
index cf7aa9e9e67bc94c971982133ef8ea49ed7fd128..bfd53e7e47041818996b55d9bb15266901688ebf 100644 (file)
@@ -8,8 +8,62 @@
  */
 
 #define _LGPL_SOURCE
+#include "agent-thread.hpp"
+#include "agent.hpp"
+#include "buffer-registry.hpp"
+#include "channel.hpp"
+#include "client.hpp"
+#include "cmd.hpp"
+#include "consumer.hpp"
+#include "context.hpp"
+#include "dispatch.hpp"
+#include "event-notifier-error-accounting.hpp"
+#include "event.hpp"
+#include "fd-limit.hpp"
+#include "health-sessiond.hpp"
+#include "kernel-consumer.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "lttng-ust-ctl.hpp"
+#include "manage-apps.hpp"
+#include "manage-kernel.hpp"
+#include "modprobe.hpp"
+#include "notification-thread-commands.hpp"
+#include "notification-thread.hpp"
+#include "notify-apps.hpp"
+#include "register.hpp"
+#include "rotation-thread.hpp"
+#include "save.hpp"
+#include "sessiond-config.hpp"
+#include "testpoint.hpp"
+#include "thread.hpp"
+#include "timer.hpp"
+#include "ust-consumer.hpp"
+#include "ust-sigbus.hpp"
+#include "utils.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/getenv.hpp>
+#include <common/compat/socket.hpp>
+#include <common/config/session-config.hpp>
+#include <common/daemonize.hpp>
+#include <common/defaults.hpp>
+#include <common/dynamic-buffer.hpp>
+#include <common/futex.hpp>
+#include <common/ini-config/ini-config.hpp>
+#include <common/kernel-consumer/kernel-consumer.hpp>
+#include <common/lockfile.hpp>
+#include <common/logging-utils.hpp>
+#include <common/path.hpp>
+#include <common/relayd/relayd.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/event-internal.hpp>
+
+#include <ctype.h>
 #include <getopt.h>
 #include <grp.h>
+#include <inttypes.h>
 #include <limits.h>
 #include <paths.h>
 #include <pthread.h>
@@ -17,7 +71,6 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <inttypes.h>
 #include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/wait.h>
-#include <urcu/uatomic.h>
 #include <unistd.h>
-#include <ctype.h>
-
-#include <common/common.hpp>
-#include <common/compat/socket.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/defaults.hpp>
-#include <common/kernel-consumer/kernel-consumer.hpp>
-#include <common/futex.hpp>
-#include <common/relayd/relayd.hpp>
-#include <common/utils.hpp>
-#include <common/path.hpp>
-#include <common/daemonize.hpp>
-#include <common/config/session-config.hpp>
-#include <common/ini-config/ini-config.hpp>
-#include <common/dynamic-buffer.hpp>
-#include <lttng/event-internal.hpp>
-#include "lttng-sessiond.hpp"
-#include "buffer-registry.hpp"
-#include "channel.hpp"
-#include "cmd.hpp"
-#include "consumer.hpp"
-#include "context.hpp"
-#include "event.hpp"
-#include "event-notifier-error-accounting.hpp"
-#include "kernel.hpp"
-#include "kernel-consumer.hpp"
-#include "lttng-ust-ctl.hpp"
-#include "ust-consumer.hpp"
-#include "utils.hpp"
-#include "fd-limit.hpp"
-#include "health-sessiond.hpp"
-#include "testpoint.hpp"
-#include "notify-apps.hpp"
-#include "agent-thread.hpp"
-#include "save.hpp"
-#include "notification-thread.hpp"
-#include "notification-thread-commands.hpp"
-#include "rotation-thread.hpp"
-#include "agent.hpp"
-#include "sessiond-config.hpp"
-#include "timer.hpp"
-#include "thread.hpp"
-#include "client.hpp"
-#include "dispatch.hpp"
-#include "register.hpp"
-#include "manage-apps.hpp"
-#include "manage-kernel.hpp"
-#include "modprobe.hpp"
-#include "ust-sigbus.hpp"
+#include <urcu/uatomic.h>
 
 static const char *help_msg =
 #ifdef LTTNG_EMBED_HELP
 #include <lttng-sessiond.8.h>
 #else
-NULL
+       nullptr
 #endif
-;
+       ;
 
 #define EVENT_NOTIFIER_ERROR_COUNTER_NUMBER_OF_BUCKET_MAX 65535
-#define EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR \
-               "event-notifier-error-buffer-size"
+#define EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR  "event-notifier-error-buffer-size"
 #define EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR \
-               EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR "-kernel"
+       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR "-kernel"
 #define EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR \
-               EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR "-userspace"
-
+       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_BASE_OPTION_STR "-userspace"
 
 const char *progname;
 static int lockfile_fd = -1;
@@ -103,37 +105,37 @@ static int recv_child_signal;
 
 /* Command line options */
 static const struct option long_options[] = {
-       { "client-sock", required_argument, 0, 'c' },
-       { "apps-sock", required_argument, 0, 'a' },
-       { "kconsumerd-cmd-sock", required_argument, 0, '\0' },
-       { "kconsumerd-err-sock", required_argument, 0, '\0' },
-       { "ustconsumerd32-cmd-sock", required_argument, 0, '\0' },
-       { "ustconsumerd32-err-sock", required_argument, 0, '\0' },
-       { "ustconsumerd64-cmd-sock", required_argument, 0, '\0' },
-       { "ustconsumerd64-err-sock", required_argument, 0, '\0' },
-       { "consumerd32-path", required_argument, 0, '\0' },
-       { "consumerd32-libdir", required_argument, 0, '\0' },
-       { "consumerd64-path", required_argument, 0, '\0' },
-       { "consumerd64-libdir", required_argument, 0, '\0' },
-       { "daemonize", no_argument, 0, 'd' },
-       { "background", no_argument, 0, 'b' },
-       { "sig-parent", no_argument, 0, 'S' },
-       { "help", no_argument, 0, 'h' },
-       { "group", required_argument, 0, 'g' },
-       { "version", no_argument, 0, 'V' },
-       { "quiet", no_argument, 0, 'q' },
-       { "verbose", no_argument, 0, 'v' },
-       { "verbose-consumer", no_argument, 0, '\0' },
-       { "no-kernel", no_argument, 0, '\0' },
-       { "pidfile", required_argument, 0, 'p' },
-       { "agent-tcp-port", required_argument, 0, '\0' },
-       { "config", required_argument, 0, 'f' },
-       { "load", required_argument, 0, 'l' },
-       { "kmod-probes", required_argument, 0, '\0' },
-       { "extra-kmod-probes", required_argument, 0, '\0' },
-       { EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR, required_argument, 0, '\0' },
-       { EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR, required_argument, 0, '\0' },
-       { NULL, 0, 0, 0 }
+       { "client-sock", required_argument, nullptr, 'c' },
+       { "apps-sock", required_argument, nullptr, 'a' },
+       { "kconsumerd-cmd-sock", required_argument, nullptr, '\0' },
+       { "kconsumerd-err-sock", required_argument, nullptr, '\0' },
+       { "ustconsumerd32-cmd-sock", required_argument, nullptr, '\0' },
+       { "ustconsumerd32-err-sock", required_argument, nullptr, '\0' },
+       { "ustconsumerd64-cmd-sock", required_argument, nullptr, '\0' },
+       { "ustconsumerd64-err-sock", required_argument, nullptr, '\0' },
+       { "consumerd32-path", required_argument, nullptr, '\0' },
+       { "consumerd32-libdir", required_argument, nullptr, '\0' },
+       { "consumerd64-path", required_argument, nullptr, '\0' },
+       { "consumerd64-libdir", required_argument, nullptr, '\0' },
+       { "daemonize", no_argument, nullptr, 'd' },
+       { "background", no_argument, nullptr, 'b' },
+       { "sig-parent", no_argument, nullptr, 'S' },
+       { "help", no_argument, nullptr, 'h' },
+       { "group", required_argument, nullptr, 'g' },
+       { "version", no_argument, nullptr, 'V' },
+       { "quiet", no_argument, nullptr, 'q' },
+       { "verbose", no_argument, nullptr, 'v' },
+       { "verbose-consumer", no_argument, nullptr, '\0' },
+       { "no-kernel", no_argument, nullptr, '\0' },
+       { "pidfile", required_argument, nullptr, 'p' },
+       { "agent-tcp-port", required_argument, nullptr, '\0' },
+       { "config", required_argument, nullptr, 'f' },
+       { "load", required_argument, nullptr, 'l' },
+       { "kmod-probes", required_argument, nullptr, '\0' },
+       { "extra-kmod-probes", required_argument, nullptr, '\0' },
+       { EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR, required_argument, nullptr, '\0' },
+       { EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR, required_argument, nullptr, '\0' },
+       { nullptr, 0, nullptr, 0 }
 };
 
 /* Command line options to ignore from configuration file */
@@ -160,30 +162,31 @@ static struct ust_cmd_queue ust_cmd_queue;
 /*
  * Section name to look for in the daemon configuration file.
  */
-static const char * const config_section_name = "sessiond";
+static const char *const config_section_name = "sessiond";
 
 /* Am I root or not. Set to 1 if the daemon is running as root */
 static int is_root;
 
 /*
- * Stop all threads by closing the thread quit pipe.
+ * Notify the main thread to initiate the teardown of the worker threads by
+ * writing to the main quit pipe.
  */
-static void stop_threads(void)
+static void notify_main_quit_pipe()
 {
        int ret;
 
        /* Stopping all threads */
-       DBG("Terminating all threads");
-       ret = sessiond_notify_quit_pipe();
+       DBG("Notify the main thread to terminate all worker threads");
+       ret = sessiond_notify_main_quit_pipe();
        if (ret < 0) {
-               ERR("write error on thread quit pipe");
+               ERR("write error on main quit pipe");
        }
 }
 
 /*
  * Close every consumer sockets.
  */
-static void close_consumer_sockets(void)
+static void close_consumer_sockets()
 {
        int ret;
 
@@ -258,14 +261,12 @@ static void wait_consumer(struct consumer_data *consumer_data)
                return;
        }
 
-       DBG("Waiting for complete teardown of consumerd (PID: %d)",
-                       consumer_data->pid);
+       DBG("Waiting for complete teardown of consumerd (PID: %d)", consumer_data->pid);
        ret = waitpid(consumer_data->pid, &status, 0);
        if (ret == -1) {
                PERROR("consumerd waitpid pid: %d", consumer_data->pid)
-       } else  if (!WIFEXITED(status)) {
-               ERR("consumerd termination with error: %d",
-                               WEXITSTATUS(ret));
+       } else if (!WIFEXITED(status)) {
+               ERR("consumerd termination with error: %d", WEXITSTATUS(ret));
        }
        consumer_data->pid = 0;
 }
@@ -273,7 +274,7 @@ static void wait_consumer(struct consumer_data *consumer_data)
 /*
  * Cleanup the session daemon's data structures.
  */
-static void sessiond_cleanup(void)
+static void sessiond_cleanup()
 {
        int ret;
        struct ltt_session_list *session_list = session_get_list();
@@ -281,10 +282,12 @@ static void sessiond_cleanup(void)
        DBG("Cleanup sessiond");
 
        /*
-        * Close the thread quit pipe. It has already done its job,
-        * since we are now called.
+        * Close the main quit pipe. It has already done its job, since we are
+        * now cleaning up.
         */
-       sessiond_close_quit_pipe();
+       sessiond_close_main_quit_pipe();
+
+       /* Close all other pipes. */
        utils_close_pipe(apps_cmd_pipe);
        utils_close_pipe(apps_cmd_notify_pipe);
        utils_close_pipe(the_kernel_poll_pipe);
@@ -294,8 +297,7 @@ static void sessiond_cleanup(void)
                PERROR("remove pidfile %s", the_config.pid_file_path.value);
        }
 
-       DBG("Removing sessiond and consumerd content of directory %s",
-                       the_config.rundir.value);
+       DBG("Removing sessiond and consumerd content of directory %s", the_config.rundir.value);
 
        /* sessiond */
        DBG("Removing %s", the_config.pid_file_path.value);
@@ -356,7 +358,7 @@ static void sessiond_cleanup(void)
 /*
  * Cleanup the daemon's option data structures.
  */
-static void sessiond_cleanup_options(void)
+static void sessiond_cleanup_options()
 {
        DBG("Cleaning up options");
 
@@ -387,10 +389,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-c, --client-sock");
+                            "-c, --client-sock");
                } else {
-                       config_string_set(&the_config.client_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.client_unix_sock_path, strdup(arg));
                        if (!the_config.client_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -403,10 +404,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-a, --apps-sock");
+                            "-a, --apps-sock");
                } else {
-                       config_string_set(&the_config.apps_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.apps_unix_sock_path, strdup(arg));
                        if (!the_config.apps_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -423,10 +423,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-g, --group");
+                            "-g, --group");
                } else {
-                       config_string_set(&the_config.tracing_group_name,
-                                       strdup(arg));
+                       config_string_set(&the_config.tracing_group_name, strdup(arg));
                        if (!the_config.tracing_group_name.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -450,11 +449,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--kconsumerd-err-sock");
+                            "--kconsumerd-err-sock");
                } else {
-                       config_string_set(
-                                       &the_config.kconsumerd_err_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.kconsumerd_err_unix_sock_path, strdup(arg));
                        if (!the_config.kconsumerd_err_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -467,11 +464,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--kconsumerd-cmd-sock");
+                            "--kconsumerd-cmd-sock");
                } else {
-                       config_string_set(
-                                       &the_config.kconsumerd_cmd_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.kconsumerd_cmd_unix_sock_path, strdup(arg));
                        if (!the_config.kconsumerd_cmd_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -484,11 +479,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--ustconsumerd64-err-sock");
+                            "--ustconsumerd64-err-sock");
                } else {
-                       config_string_set(
-                                       &the_config.consumerd64_err_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd64_err_unix_sock_path, strdup(arg));
                        if (!the_config.consumerd64_err_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -501,11 +494,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--ustconsumerd64-cmd-sock");
+                            "--ustconsumerd64-cmd-sock");
                } else {
-                       config_string_set(
-                                       &the_config.consumerd64_cmd_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd64_cmd_unix_sock_path, strdup(arg));
                        if (!the_config.consumerd64_cmd_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -518,11 +509,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--ustconsumerd32-err-sock");
+                            "--ustconsumerd32-err-sock");
                } else {
-                       config_string_set(
-                                       &the_config.consumerd32_err_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd32_err_unix_sock_path, strdup(arg));
                        if (!the_config.consumerd32_err_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -535,11 +524,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--ustconsumerd32-cmd-sock");
+                            "--ustconsumerd32-cmd-sock");
                } else {
-                       config_string_set(
-                                       &the_config.consumerd32_cmd_unix_sock_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd32_cmd_unix_sock_path, strdup(arg));
                        if (!the_config.consumerd32_cmd_unix_sock_path.value) {
                                ret = -ENOMEM;
                                PERROR("strdup");
@@ -560,9 +547,8 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                /* Clamp value to [0, 3] */
                the_config.verbose = the_config.verbose < 0 ?
-                                     0 :
-                                     (the_config.verbose <= 3 ? the_config.verbose :
-                                                                3);
+                       0 :
+                       (the_config.verbose <= 3 ? the_config.verbose : 3);
        } else if (string_match(optname, "verbose-consumer")) {
                if (arg) {
                        the_config.verbose_consumer = config_parse_value(arg);
@@ -576,10 +562,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--consumerd32-path");
+                            "--consumerd32-path");
                } else {
-                       config_string_set(&the_config.consumerd32_bin_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd32_bin_path, strdup(arg));
                        if (!the_config.consumerd32_bin_path.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -592,10 +577,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--consumerd32-libdir");
+                            "--consumerd32-libdir");
                } else {
-                       config_string_set(&the_config.consumerd32_lib_dir,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd32_lib_dir, strdup(arg));
                        if (!the_config.consumerd32_lib_dir.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -608,10 +592,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--consumerd64-path");
+                            "--consumerd64-path");
                } else {
-                       config_string_set(&the_config.consumerd64_bin_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd64_bin_path, strdup(arg));
                        if (!the_config.consumerd64_bin_path.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -624,10 +607,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--consumerd64-libdir");
+                            "--consumerd64-libdir");
                } else {
-                       config_string_set(&the_config.consumerd64_lib_dir,
-                                       strdup(arg));
+                       config_string_set(&the_config.consumerd64_lib_dir, strdup(arg));
                        if (!the_config.consumerd64_lib_dir.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -640,10 +622,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-p, --pidfile");
+                            "-p, --pidfile");
                } else {
-                       config_string_set(
-                                       &the_config.pid_file_path, strdup(arg));
+                       config_string_set(&the_config.pid_file_path, strdup(arg));
                        if (!the_config.pid_file_path.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -656,12 +637,12 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--agent-tcp-port");
+                            "--agent-tcp-port");
                } else {
                        unsigned long v;
 
                        errno = 0;
-                       v = strtoul(arg, NULL, 0);
+                       v = strtoul(arg, nullptr, 0);
                        if (errno != 0 || !isdigit(arg[0])) {
                                ERR("Wrong value in --agent-tcp-port parameter: %s", arg);
                                return -1;
@@ -670,8 +651,7 @@ static int set_option(int opt, const char *arg, const char *optname)
                                ERR("Port overflow in --agent-tcp-port parameter: %s", arg);
                                return -1;
                        }
-                       the_config.agent_tcp_port.begin =
-                                       the_config.agent_tcp_port.end = (int) v;
+                       the_config.agent_tcp_port.begin = the_config.agent_tcp_port.end = (int) v;
                        DBG3("Agent TCP port set to non default: %i", (int) v);
                }
        } else if (string_match(optname, "load") || opt == 'l') {
@@ -681,10 +661,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-l, --load");
+                            "-l, --load");
                } else {
-                       config_string_set(&the_config.load_session_path,
-                                       strdup(arg));
+                       config_string_set(&the_config.load_session_path, strdup(arg));
                        if (!the_config.load_session_path.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -697,10 +676,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--kmod-probes");
+                            "--kmod-probes");
                } else {
-                       config_string_set(&the_config.kmod_probes_list,
-                                       strdup(arg));
+                       config_string_set(&the_config.kmod_probes_list, strdup(arg));
                        if (!the_config.kmod_probes_list.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -713,10 +691,9 @@ static int set_option(int opt, const char *arg, const char *optname)
                }
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "--extra-kmod-probes");
+                            "--extra-kmod-probes");
                } else {
-                       config_string_set(&the_config.kmod_extra_probes_list,
-                                       strdup(arg));
+                       config_string_set(&the_config.kmod_extra_probes_list, strdup(arg));
                        if (!the_config.kmod_extra_probes_list.value) {
                                PERROR("strdup");
                                ret = -ENOMEM;
@@ -726,39 +703,43 @@ static int set_option(int opt, const char *arg, const char *optname)
                unsigned long v;
 
                errno = 0;
-               v = strtoul(arg, NULL, 0);
+               v = strtoul(arg, nullptr, 0);
                if (errno != 0 || !isdigit(arg[0])) {
                        ERR("Wrong value in --%s parameter: %s",
-                                       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR, arg);
+                           EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR,
+                           arg);
                        return -1;
                }
                if (v == 0 || v >= EVENT_NOTIFIER_ERROR_COUNTER_NUMBER_OF_BUCKET_MAX) {
                        ERR("Value out of range for --%s parameter: %s",
-                                       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR, arg);
+                           EVENT_NOTIFIER_ERROR_BUFFER_SIZE_KERNEL_OPTION_STR,
+                           arg);
                        return -1;
                }
                the_config.event_notifier_buffer_size_kernel = (int) v;
                DBG3("Number of event notifier error buffer kernel size to non default: %i",
-                               the_config.event_notifier_buffer_size_kernel);
+                    the_config.event_notifier_buffer_size_kernel);
                goto end;
        } else if (string_match(optname, EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR)) {
                unsigned long v;
 
                errno = 0;
-               v = strtoul(arg, NULL, 0);
+               v = strtoul(arg, nullptr, 0);
                if (errno != 0 || !isdigit(arg[0])) {
                        ERR("Wrong value in --%s parameter: %s",
-                                       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR, arg);
+                           EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR,
+                           arg);
                        return -1;
                }
                if (v == 0 || v >= EVENT_NOTIFIER_ERROR_COUNTER_NUMBER_OF_BUCKET_MAX) {
                        ERR("Value out of range for --%s parameter: %s",
-                                       EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR, arg);
+                           EVENT_NOTIFIER_ERROR_BUFFER_SIZE_USERSPACE_OPTION_STR,
+                           arg);
                        return -1;
                }
                the_config.event_notifier_buffer_size_userspace = (int) v;
                DBG3("Number of event notifier error buffer userspace size to non default: %i",
-                               the_config.event_notifier_buffer_size_userspace);
+                    the_config.event_notifier_buffer_size_userspace);
                goto end;
        } else if (string_match(optname, "config") || opt == 'f') {
                /* This is handled in set_options() thus silent skip. */
@@ -774,16 +755,14 @@ end:
                const char *opt_name = "unknown";
                int i;
 
-               for (i = 0; i < sizeof(long_options) / sizeof(struct option);
-                       i++) {
+               for (i = 0; i < sizeof(long_options) / sizeof(struct option); i++) {
                        if (opt == long_options[i].val) {
                                opt_name = long_options[i].name;
                                break;
                        }
                }
 
-               WARN("Invalid argument provided for option \"%s\", using default value.",
-                       opt_name);
+               WARN("Invalid argument provided for option \"%s\", using default value.", opt_name);
        }
 
        return ret;
@@ -795,7 +774,7 @@ end:
  * return value conventions.
  */
 static int config_entry_handler(const struct config_entry *entry,
-               void *unused __attribute__((unused)))
+                               void *unused __attribute__((unused)))
 {
        int ret = 0, i;
 
@@ -811,11 +790,9 @@ static int config_entry_handler(const struct config_entry *entry,
                }
        }
 
-       for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1;
-               i++) {
-
+       for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
                /* Ignore if not fully matched. */
-               if (strcmp(entry->name, long_options[i].name)) {
+               if (strcmp(entry->name, long_options[i].name) != 0) {
                        continue;
                }
 
@@ -829,7 +806,8 @@ static int config_entry_handler(const struct config_entry *entry,
                        if (ret <= 0) {
                                if (ret) {
                                        WARN("Invalid configuration value \"%s\" for option %s",
-                                                       entry->value, entry->name);
+                                            entry->value,
+                                            entry->name);
                                }
                                /* False, skip boolean config option. */
                                goto end;
@@ -846,7 +824,8 @@ end:
        return ret;
 }
 
-static void print_version(void) {
+static void print_version()
+{
        fprintf(stdout, "%s\n", VERSION);
 }
 
@@ -858,18 +837,17 @@ static int set_options(int argc, char **argv)
        int ret = 0, c = 0, option_index = 0;
        int orig_optopt = optopt, orig_optind = optind;
        char *optstring;
-       char *config_path = NULL;
+       char *config_path = nullptr;
 
        optstring = utils_generate_optstring(long_options,
-                       sizeof(long_options) / sizeof(struct option));
+                                            sizeof(long_options) / sizeof(struct option));
        if (!optstring) {
                ret = -ENOMEM;
                goto end;
        }
 
        /* Check for the --config option */
-       while ((c = getopt_long(argc, argv, optstring, long_options,
-                                       &option_index)) != -1) {
+       while ((c = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) {
                if (c == '?') {
                        ret = -EINVAL;
                        goto end;
@@ -880,7 +858,7 @@ static int set_options(int argc, char **argv)
 
                if (lttng_is_setuid_setgid()) {
                        WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
-                               "-f, --config");
+                            "-f, --config");
                } else {
                        free(config_path);
                        config_path = utils_expand_path(optarg);
@@ -890,8 +868,8 @@ static int set_options(int argc, char **argv)
                }
        }
 
-       ret = config_get_section_entries(config_path, config_section_name,
-                       config_entry_handler, NULL);
+       ret = config_get_section_entries(
+               config_path, config_section_name, config_entry_handler, nullptr);
        if (ret) {
                if (ret > 0) {
                        ERR("Invalid configuration option at line %i", ret);
@@ -903,14 +881,13 @@ static int set_options(int argc, char **argv)
        /* Reset getopt's global state */
        optopt = orig_optopt;
        optind = orig_optind;
-       while (1) {
+       while (true) {
                option_index = -1;
                /*
                 * getopt_long() will not set option_index if it encounters a
                 * short option.
                 */
-               c = getopt_long(argc, argv, optstring, long_options,
-                               &option_index);
+               c = getopt_long(argc, argv, optstring, long_options, &option_index);
                if (c == -1) {
                        break;
                }
@@ -919,9 +896,8 @@ static int set_options(int argc, char **argv)
                 * Pass NULL as the long option name if popt left the index
                 * unset.
                 */
-               ret = set_option(c, optarg,
-                               option_index < 0 ? NULL :
-                               long_options[option_index].name);
+               ret = set_option(
+                       c, optarg, option_index < 0 ? nullptr : long_options[option_index].name);
                if (ret < 0) {
                        break;
                }
@@ -936,7 +912,7 @@ end:
 /*
  * Create lockfile using the rundir and return its fd.
  */
-static int create_lockfile(void)
+static int create_lockfile()
 {
        return utils_create_lock_file(the_config.lock_file_path.value);
 }
@@ -947,7 +923,7 @@ static int create_lockfile(void)
  *
  * Also attempts to create and hold the lock file.
  */
-static int check_existing_daemon(void)
+static int check_existing_daemon()
 {
        int ret = 0;
 
@@ -966,7 +942,7 @@ end:
        return ret;
 }
 
-static void sessiond_cleanup_lock_file(void)
+static void sessiond_cleanup_lock_file()
 {
        int ret;
 
@@ -997,8 +973,7 @@ static int set_permissions(char *rundir)
        int ret;
        gid_t gid;
 
-       ret = utils_get_group_id(
-                       the_config.tracing_group_name.value, true, &gid);
+       ret = utils_get_group_id(the_config.tracing_group_name.value, true, &gid);
        if (ret) {
                /* Default to root group. */
                gid = 0;
@@ -1025,32 +1000,28 @@ static int set_permissions(char *rundir)
        /* lttng client socket path */
        ret = chown(the_config.client_unix_sock_path.value, 0, gid);
        if (ret < 0) {
-               ERR("Unable to set group on %s",
-                               the_config.client_unix_sock_path.value);
+               ERR("Unable to set group on %s", the_config.client_unix_sock_path.value);
                PERROR("chown");
        }
 
        /* kconsumer error socket path */
        ret = chown(the_kconsumer_data.err_unix_sock_path, 0, 0);
        if (ret < 0) {
-               ERR("Unable to set group on %s",
-                               the_kconsumer_data.err_unix_sock_path);
+               ERR("Unable to set group on %s", the_kconsumer_data.err_unix_sock_path);
                PERROR("chown");
        }
 
        /* 64-bit ustconsumer error socket path */
        ret = chown(the_ustconsumer64_data.err_unix_sock_path, 0, 0);
        if (ret < 0) {
-               ERR("Unable to set group on %s",
-                               the_ustconsumer64_data.err_unix_sock_path);
+               ERR("Unable to set group on %s", the_ustconsumer64_data.err_unix_sock_path);
                PERROR("chown");
        }
 
        /* 32-bit ustconsumer compat32 error socket path */
        ret = chown(the_ustconsumer32_data.err_unix_sock_path, 0, 0);
        if (ret < 0) {
-               ERR("Unable to set group on %s",
-                               the_ustconsumer32_data.err_unix_sock_path);
+               ERR("Unable to set group on %s", the_ustconsumer32_data.err_unix_sock_path);
                PERROR("chown");
        }
 
@@ -1062,7 +1033,7 @@ static int set_permissions(char *rundir)
 /*
  * Create the lttng run directory needed for all global sockets and pipe.
  */
-static int create_lttng_rundir(void)
+static int create_lttng_rundir()
 {
        int ret;
 
@@ -1089,7 +1060,7 @@ error:
 static int set_consumer_sockets(struct consumer_data *consumer_data)
 {
        int ret;
-       char *path = NULL;
+       char *path = nullptr;
 
        switch (consumer_data->type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -1119,8 +1090,7 @@ static int set_consumer_sockets(struct consumer_data *consumer_data)
        if (is_root) {
                gid_t gid;
 
-               ret = utils_get_group_id(the_config.tracing_group_name.value,
-                               true, &gid);
+               ret = utils_get_group_id(the_config.tracing_group_name.value, true, &gid);
                if (ret) {
                        /* Default to root group. */
                        gid = 0;
@@ -1135,8 +1105,7 @@ static int set_consumer_sockets(struct consumer_data *consumer_data)
        }
 
        /* Create the consumerd error unix socket */
-       consumer_data->err_sock =
-               lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
+       consumer_data->err_sock = lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
        if (consumer_data->err_sock < 0) {
                ERR("Create unix sock failed: %s", consumer_data->err_unix_sock_path);
                ret = -1;
@@ -1154,8 +1123,7 @@ static int set_consumer_sockets(struct consumer_data *consumer_data)
        }
 
        /* File permission MUST be 660 */
-       ret = chmod(consumer_data->err_unix_sock_path,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       ret = chmod(consumer_data->err_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
        if (ret < 0) {
                ERR("Set file permissions failed: %s", consumer_data->err_unix_sock_path);
                PERROR("chmod");
@@ -1172,17 +1140,16 @@ error:
  * Simply stop all worker threads, leaving main() return gracefully after
  * joining all threads and calling cleanup().
  */
-static void sighandler(int sig, siginfo_t *siginfo,
-               void *arg __attribute__((unused)))
+static void sighandler(int sig, siginfo_t *siginfo, void *arg __attribute__((unused)))
 {
        switch (sig) {
        case SIGINT:
                DBG("SIGINT caught");
-               stop_threads();
+               notify_main_quit_pipe();
                break;
        case SIGTERM:
                DBG("SIGTERM caught");
-               stop_threads();
+               notify_main_quit_pipe();
                break;
        case SIGUSR1:
                CMM_STORE_SHARED(recv_child_signal, 1);
@@ -1213,7 +1180,7 @@ static void sighandler(int sig, siginfo_t *siginfo,
  * Setup signal handler for :
  *             SIGINT, SIGTERM, SIGPIPE
  */
-static int set_signal_handler(void)
+static int set_signal_handler()
 {
        int ret = 0;
        struct sigaction sa;
@@ -1228,29 +1195,29 @@ static int set_signal_handler(void)
        sa.sa_flags = SA_SIGINFO;
 
        sa.sa_sigaction = sighandler;
-       if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGTERM, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGINT, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGUSR1, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
-       if ((ret = sigaction(SIGBUS, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGBUS, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
 
        sa.sa_flags = 0;
        sa.sa_handler = SIG_IGN;
-       if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGPIPE, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                return ret;
        }
@@ -1264,7 +1231,7 @@ static int set_signal_handler(void)
  * Set open files limit to unlimited. This daemon can open a large number of
  * file descriptors in order to consume multiple kernel traces.
  */
-static void set_ulimit(void)
+static void set_ulimit()
 {
        int ret;
        struct rlimit lim;
@@ -1279,22 +1246,22 @@ static void set_ulimit(void)
        }
 }
 
-static int write_pidfile(void)
+static int write_pidfile()
 {
        return utils_create_pid_file(getpid(), the_config.pid_file_path.value);
 }
 
-static int set_clock_plugin_env(void)
+static int set_clock_plugin_env()
 {
        int ret = 0;
-       char *env_value = NULL;
+       char *env_value = nullptr;
 
        if (!the_config.lttng_ust_clock_plugin.value) {
                goto end;
        }
 
-       ret = asprintf(&env_value, "LTTNG_UST_CLOCK_PLUGIN=%s",
-                       the_config.lttng_ust_clock_plugin.value);
+       ret = asprintf(
+               &env_value, "LTTNG_UST_CLOCK_PLUGIN=%s", the_config.lttng_ust_clock_plugin.value);
        if (ret < 0) {
                PERROR("asprintf");
                goto end;
@@ -1308,12 +1275,12 @@ static int set_clock_plugin_env(void)
        }
 
        DBG("Updated LTTNG_UST_CLOCK_PLUGIN environment variable to \"%s\"",
-                       the_config.lttng_ust_clock_plugin.value);
+           the_config.lttng_ust_clock_plugin.value);
 end:
        return ret;
 }
 
-static void destroy_all_sessions_and_wait(void)
+static void destroy_all_sessions_and_wait()
 {
        struct ltt_session *session, *tmp;
        struct ltt_session_list *session_list;
@@ -1327,8 +1294,7 @@ static void destroy_all_sessions_and_wait(void)
 
        session_lock_list();
        /* Initiate the destruction of all sessions. */
-       cds_list_for_each_entry_safe(session, tmp,
-                       &session_list->head, list) {
+       cds_list_for_each_entry_safe (session, tmp, &session_list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
@@ -1338,8 +1304,7 @@ static void destroy_all_sessions_and_wait(void)
                        goto unlock_session;
                }
                (void) cmd_stop_trace(session);
-               (void) cmd_destroy_session(
-                               session, the_notification_thread_handle, NULL);
+               (void) cmd_destroy_session(session, nullptr);
        unlock_session:
                session_unlock(session);
                session_put(session);
@@ -1352,11 +1317,11 @@ static void destroy_all_sessions_and_wait(void)
        DBG("Destruction of all sessions completed");
 }
 
-static void unregister_all_triggers(void)
+static void unregister_all_triggers()
 {
        enum lttng_error_code ret_code;
        enum lttng_trigger_status trigger_status;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count, i;
        const struct lttng_credentials creds = {
                .uid = LTTNG_OPTIONAL_INIT_VALUE(0),
@@ -1369,8 +1334,7 @@ static void unregister_all_triggers(void)
         * List all triggers as "root" since we wish to unregister all triggers.
         */
        ret_code = notification_thread_command_list_triggers(
-                       the_notification_thread_handle, creds.uid.value,
-                       &triggers);
+               the_notification_thread_handle, creds.uid.value, &triggers);
        if (ret_code != LTTNG_OK) {
                ERR("Failed to list triggers while unregistering all triggers");
                goto end;
@@ -1382,28 +1346,27 @@ static void unregister_all_triggers(void)
        for (i = 0; i < trigger_count; i++) {
                uid_t trigger_owner;
                const char *trigger_name;
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
 
                LTTNG_ASSERT(trigger);
 
-               trigger_status = lttng_trigger_get_owner_uid(
-                               trigger, &trigger_owner);
+               trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_owner);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
                trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
-               trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ?
-                               trigger_name : "(anonymous)";
+               trigger_name = trigger_status == LTTNG_TRIGGER_STATUS_OK ? trigger_name :
+                                                                          "(anonymous)";
 
                DBG("Unregistering trigger: trigger owner uid = %d, trigger name = '%s'",
-                               (int) trigger_owner, trigger_name);
+                   (int) trigger_owner,
+                   trigger_name);
 
-               ret_code = cmd_unregister_trigger(&creds, trigger,
-                               the_notification_thread_handle);
+               ret_code = cmd_unregister_trigger(&creds, trigger, the_notification_thread_handle);
                if (ret_code != LTTNG_OK) {
                        ERR("Failed to unregister trigger: trigger owner uid = %d, trigger name = '%s', error: '%s'",
-                                       (int) trigger_owner, trigger_name,
-                                       lttng_strerror(-ret_code));
+                           (int) trigger_owner,
+                           trigger_name,
+                           lttng_strerror(-ret_code));
                        /* Continue to unregister the remaining triggers. */
                }
        }
@@ -1427,11 +1390,10 @@ static int launch_run_as_worker(const char *procname)
         * be leaked as the process forks a run-as worker (and performs
         * no exec*()). The same would apply to any opened fd.
         */
-       return run_as_create_worker(
-                       procname, run_as_worker_post_fork_cleanup, &the_config);
+       return run_as_create_worker(procname, run_as_worker_post_fork_cleanup, &the_config);
 }
 
-static void sessiond_uuid_log(void)
+static void sessiond_uuid_log()
 {
        char uuid_str[LTTNG_UUID_STR_LEN];
 
@@ -1442,21 +1404,19 @@ static void sessiond_uuid_log(void)
 /*
  * main
  */
-int main(int argc, char **argv)
+static int _main(int argc, char **argv)
 {
        int ret = 0, retval = 0;
        const char *env_app_timeout;
-       struct lttng_pipe *ust32_channel_monitor_pipe = NULL,
-                       *ust64_channel_monitor_pipe = NULL,
-                       *kernel_channel_monitor_pipe = NULL;
+       struct lttng_pipe *ust32_channel_monitor_pipe = nullptr,
+                         *ust64_channel_monitor_pipe = nullptr,
+                         *kernel_channel_monitor_pipe = nullptr;
        struct timer_thread_parameters timer_thread_parameters;
-       /* Rotation thread handle. */
-       struct rotation_thread_handle *rotation_thread_handle = NULL;
        /* Queue of rotation jobs populated by the sessiond-timer. */
-       struct rotation_thread_timer_queue *rotation_timer_queue = NULL;
-       struct lttng_thread *client_thread = NULL;
-       struct lttng_thread *notification_thread = NULL;
-       struct lttng_thread *register_apps_thread = NULL;
+       lttng::sessiond::rotation_thread_timer_queue *rotation_timer_queue = nullptr;
+       struct lttng_thread *client_thread = nullptr;
+       struct lttng_thread *notification_thread = nullptr;
+       struct lttng_thread *register_apps_thread = nullptr;
        enum event_notifier_error_accounting_status event_notifier_error_accounting_status;
 
        logger_set_thread_name("Main", false);
@@ -1519,22 +1479,17 @@ int main(int argc, char **argv)
        /* Apply config. */
        lttng_opt_verbose = the_config.verbose;
        lttng_opt_quiet = the_config.quiet;
-       the_kconsumer_data.err_unix_sock_path =
-                       the_config.kconsumerd_err_unix_sock_path.value;
-       the_kconsumer_data.cmd_unix_sock_path =
-                       the_config.kconsumerd_cmd_unix_sock_path.value;
-       the_ustconsumer32_data.err_unix_sock_path =
-                       the_config.consumerd32_err_unix_sock_path.value;
-       the_ustconsumer32_data.cmd_unix_sock_path =
-                       the_config.consumerd32_cmd_unix_sock_path.value;
-       the_ustconsumer64_data.err_unix_sock_path =
-                       the_config.consumerd64_err_unix_sock_path.value;
-       the_ustconsumer64_data.cmd_unix_sock_path =
-                       the_config.consumerd64_cmd_unix_sock_path.value;
+       the_kconsumer_data.err_unix_sock_path = the_config.kconsumerd_err_unix_sock_path.value;
+       the_kconsumer_data.cmd_unix_sock_path = the_config.kconsumerd_cmd_unix_sock_path.value;
+       the_ustconsumer32_data.err_unix_sock_path = the_config.consumerd32_err_unix_sock_path.value;
+       the_ustconsumer32_data.cmd_unix_sock_path = the_config.consumerd32_cmd_unix_sock_path.value;
+       the_ustconsumer64_data.err_unix_sock_path = the_config.consumerd64_err_unix_sock_path.value;
+       the_ustconsumer64_data.cmd_unix_sock_path = the_config.consumerd64_cmd_unix_sock_path.value;
        set_clock_plugin_env();
 
        sessiond_config_log(&the_config);
        sessiond_uuid_log();
+       lttng::logging::log_system_information(PRINT_DBG);
 
        if (opt_print_version) {
                print_version();
@@ -1558,8 +1513,7 @@ int main(int argc, char **argv)
        if (the_config.daemonize || the_config.background) {
                int i;
 
-               ret = lttng_daemonize(&the_child_ppid, &recv_child_signal,
-                               !the_config.background);
+               ret = lttng_daemonize(&the_child_ppid, &recv_child_signal, !the_config.background);
                if (ret < 0) {
                        retval = -1;
                        goto exit_options;
@@ -1598,8 +1552,8 @@ int main(int argc, char **argv)
                goto stop_threads;
        }
 
-       /* Create thread quit pipe */
-       if (sessiond_init_thread_quit_pipe()) {
+       /* Create main quit pipe */
+       if (sessiond_init_main_quit_pipe()) {
                retval = -1;
                goto stop_threads;
        }
@@ -1616,8 +1570,7 @@ int main(int argc, char **argv)
                        goto stop_threads;
                }
                the_kconsumer_data.channel_monitor_pipe =
-                               lttng_pipe_release_writefd(
-                                               kernel_channel_monitor_pipe);
+                       lttng_pipe_release_writefd(kernel_channel_monitor_pipe);
                if (the_kconsumer_data.channel_monitor_pipe < 0) {
                        retval = -1;
                        goto stop_threads;
@@ -1635,7 +1588,7 @@ int main(int argc, char **argv)
                goto stop_threads;
        }
        the_ustconsumer32_data.channel_monitor_pipe =
-                       lttng_pipe_release_writefd(ust32_channel_monitor_pipe);
+               lttng_pipe_release_writefd(ust32_channel_monitor_pipe);
        if (the_ustconsumer32_data.channel_monitor_pipe < 0) {
                retval = -1;
                goto stop_threads;
@@ -1646,13 +1599,12 @@ int main(int argc, char **argv)
         * sessiond timer thread and the rotation thread. The main thread keeps
         * its ownership and destroys it when both threads have been joined.
         */
-       rotation_timer_queue = rotation_thread_timer_queue_create();
+       rotation_timer_queue = lttng::sessiond::rotation_thread_timer_queue_create();
        if (!rotation_timer_queue) {
                retval = -1;
                goto stop_threads;
        }
-       timer_thread_parameters.rotation_thread_job_queue =
-                       rotation_timer_queue;
+       timer_thread_parameters.rotation_thread_job_queue = rotation_timer_queue;
 
        ust64_channel_monitor_pipe = lttng_pipe_open(0);
        if (!ust64_channel_monitor_pipe) {
@@ -1661,7 +1613,7 @@ int main(int argc, char **argv)
                goto stop_threads;
        }
        the_ustconsumer64_data.channel_monitor_pipe =
-                       lttng_pipe_release_writefd(ust64_channel_monitor_pipe);
+               lttng_pipe_release_writefd(ust64_channel_monitor_pipe);
        if (the_ustconsumer64_data.channel_monitor_pipe < 0) {
                retval = -1;
                goto stop_threads;
@@ -1678,8 +1630,8 @@ int main(int argc, char **argv)
        }
 
        event_notifier_error_accounting_status = event_notifier_error_accounting_init(
-                       the_config.event_notifier_buffer_size_kernel,
-                       the_config.event_notifier_buffer_size_userspace);
+               the_config.event_notifier_buffer_size_kernel,
+               the_config.event_notifier_buffer_size_userspace);
        if (event_notifier_error_accounting_status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                ERR("Failed to initialize event notifier error accounting system");
                retval = -1;
@@ -1795,9 +1747,10 @@ int main(int argc, char **argv)
        }
 
        /* notification_thread_data acquires the pipes' read side. */
-       the_notification_thread_handle = notification_thread_handle_create(
-                       ust32_channel_monitor_pipe, ust64_channel_monitor_pipe,
-                       kernel_channel_monitor_pipe);
+       the_notification_thread_handle =
+               notification_thread_handle_create(ust32_channel_monitor_pipe,
+                                                 ust64_channel_monitor_pipe,
+                                                 kernel_channel_monitor_pipe);
        if (!the_notification_thread_handle) {
                retval = -1;
                ERR("Failed to create notification thread shared data");
@@ -1805,8 +1758,7 @@ int main(int argc, char **argv)
        }
 
        /* Create notification thread. */
-       notification_thread = launch_notification_thread(
-                       the_notification_thread_handle);
+       notification_thread = launch_notification_thread(the_notification_thread_handle);
        if (!notification_thread) {
                retval = -1;
                goto stop_threads;
@@ -1818,19 +1770,20 @@ int main(int argc, char **argv)
                goto stop_threads;
        }
 
-       /* rotation_thread_data acquires the pipes' read side. */
-       rotation_thread_handle = rotation_thread_handle_create(
-                       rotation_timer_queue, the_notification_thread_handle);
-       if (!rotation_thread_handle) {
+       try {
+               the_rotation_thread_handle = lttng::make_unique<lttng::sessiond::rotation_thread>(
+                       *rotation_timer_queue, *the_notification_thread_handle);
+       } catch (const std::exception& e) {
                retval = -1;
-               ERR("Failed to create rotation thread shared data");
-               stop_threads();
+               ERR("Failed to create rotation thread: %s", e.what());
                goto stop_threads;
        }
 
-       /* Create rotation thread. */
-       if (!launch_rotation_thread(rotation_thread_handle)) {
+       try {
+               the_rotation_thread_handle->launch_thread();
+       } catch (const std::exception& e) {
                retval = -1;
+               ERR("Failed to launch rotation thread: %s", e.what());
                goto stop_threads;
        }
 
@@ -1847,15 +1800,13 @@ int main(int argc, char **argv)
                goto stop_threads;
        }
 
-       if (!launch_ust_dispatch_thread(&ust_cmd_queue, apps_cmd_pipe[1],
-                       apps_cmd_notify_pipe[1])) {
+       if (!launch_ust_dispatch_thread(&ust_cmd_queue, apps_cmd_pipe[1], apps_cmd_notify_pipe[1])) {
                retval = -1;
                goto stop_threads;
        }
 
        /* Create thread to manage application registration. */
-       register_apps_thread = launch_application_registration_thread(
-                       &ust_cmd_queue);
+       register_apps_thread = launch_application_registration_thread(&ust_cmd_queue);
        if (!register_apps_thread) {
                retval = -1;
                goto stop_threads;
@@ -1889,9 +1840,9 @@ int main(int argc, char **argv)
 
                if (kernel_get_notification_fd() >= 0) {
                        ret = notification_thread_command_add_tracer_event_source(
-                                       the_notification_thread_handle,
-                                       kernel_get_notification_fd(),
-                                       LTTNG_DOMAIN_KERNEL);
+                               the_notification_thread_handle,
+                               kernel_get_notification_fd(),
+                               LTTNG_DOMAIN_KERNEL);
                        if (ret != LTTNG_OK) {
                                ERR("Failed to add kernel trigger event source to notification thread");
                                retval = -1;
@@ -1901,8 +1852,7 @@ int main(int argc, char **argv)
        }
 
        /* Load sessions. */
-       ret = config_load_session(
-                       the_config.load_session_path.value, NULL, 1, 1, NULL);
+       ret = config_load_session(the_config.load_session_path.value, nullptr, 1, 1, nullptr);
        if (ret) {
                ERR("Session load failed: %s", error_get_str(ret));
                retval = -1;
@@ -1917,11 +1867,13 @@ int main(int argc, char **argv)
         * signal that asks threads to teardown).
         */
 
-       /* Initiate teardown once activity occurs on the quit pipe. */
-       sessiond_wait_for_quit_pipe(-1);
+       /* Initiate teardown once activity occurs on the main quit pipe. */
+       sessiond_wait_for_main_quit_pipe(-1);
 
 stop_threads:
 
+       DBG("Terminating all threads");
+
        /*
         * Ensure that the client thread is no longer accepting new commands,
         * which could cause new sessions to be created.
@@ -1986,16 +1938,12 @@ stop_threads:
         */
        if (is_root && !the_config.no_kernel) {
                DBG("Unloading kernel modules");
-               modprobe_remove_lttng_all();
+               modprobe_remove_lttng_all();
        }
 
        rcu_thread_offline();
        rcu_unregister_thread();
 
-       if (rotation_thread_handle) {
-               rotation_thread_handle_destroy(rotation_thread_handle);
-       }
-
        /*
         * After the rotation and timer thread have quit, we can safely destroy
         * the rotation_timer_queue.
@@ -2007,8 +1955,7 @@ stop_threads:
         * of the active session and channels at the moment of the teardown.
         */
        if (the_notification_thread_handle) {
-               notification_thread_handle_destroy(
-                               the_notification_thread_handle);
+               notification_thread_handle_destroy(the_notification_thread_handle);
        }
        lttng_pipe_destroy(ust32_channel_monitor_pipe);
        lttng_pipe_destroy(ust64_channel_monitor_pipe);
@@ -2029,3 +1976,13 @@ exit_set_signal_handler:
                exit(EXIT_FAILURE);
        }
 }
+
+int main(int argc, char **argv)
+{
+       try {
+               return _main(argc, argv);
+       } catch (const std::exception& e) {
+               ERR_FMT("Unhandled exception caught by main thread: {}", e.what());
+               abort();
+       }
+}
index f8297a6df82820a975bf514702d692de7057ba21..ef55b452e8b54b63a37366fcd25a5a8d39089a4a 100644 (file)
@@ -7,11 +7,13 @@
  *
  */
 
+#include "health-sessiond.hpp"
 #include "manage-apps.hpp"
 #include "testpoint.hpp"
-#include "health-sessiond.hpp"
-#include "utils.hpp"
 #include "thread.hpp"
+#include "utils.hpp"
+
+#include <fcntl.h>
 
 namespace {
 struct thread_notifiers {
@@ -35,7 +37,7 @@ static void cleanup_application_management_thread(void *data)
  *
  * At that point, it flushes the data (tracing and metadata) associated
  * with this application and tears down ust app sessions and other
- * associated data structures through ust_app_unregister().
+ * associated data structures through ust_app_unregister_by_socket().
  *
  * Note that this thread never sends commands to the applications
  * through the command sockets; it merely listens for hang-ups
@@ -43,13 +45,12 @@ static void cleanup_application_management_thread(void *data)
  */
 static void *thread_application_management(void *data)
 {
-       int i, ret, pollfd, err = -1;
+       int i, ret, err = -1;
        ssize_t size_ret;
-       uint32_t revents, nb_fd;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(
-                       notifiers->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
 
        DBG("[thread] Manage application started");
 
@@ -69,13 +70,12 @@ static void *thread_application_management(void *data)
                goto error_poll_create;
        }
 
-       ret = lttng_poll_add(&events, notifiers->apps_cmd_pipe_read_fd,
-                       LPOLLIN | LPOLLRDHUP);
+       ret = lttng_poll_add(&events, notifiers->apps_cmd_pipe_read_fd, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                goto error;
        }
 
-       ret = lttng_poll_add(&events, quit_pipe_read_fd, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                goto error;
        }
@@ -86,15 +86,14 @@ static void *thread_application_management(void *data)
 
        health_code_update();
 
-       while (1) {
+       while (true) {
                DBG("Apps thread polling");
 
                /* Inifinite blocking call, waiting for transmission */
        restart:
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
-               DBG("Apps thread return from poll on %d fds",
-                               LTTNG_POLL_GETNB(&events));
+               DBG("Apps thread return from poll on %d fds", LTTNG_POLL_GETNB(&events));
                health_poll_exit();
                if (ret < 0) {
                        /*
@@ -110,23 +109,27 @@ static void *thread_application_management(void *data)
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
-                       if (pollfd == quit_pipe_read_fd) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
-                       } else if (pollfd == notifiers->apps_cmd_pipe_read_fd) {
+                       }
+
+                       if (pollfd == notifiers->apps_cmd_pipe_read_fd) {
                                /* Inspect the apps cmd pipe */
                                if (revents & LPOLLIN) {
                                        int sock;
 
                                        /* Empty pipe */
-                                       size_ret = lttng_read(
-                                                       notifiers->apps_cmd_pipe_read_fd,
-                                                       &sock, sizeof(sock));
+                                       size_ret = lttng_read(notifiers->apps_cmd_pipe_read_fd,
+                                                             &sock,
+                                                             sizeof(sock));
                                        if (size_ret < sizeof(sock)) {
                                                PERROR("read apps cmd pipe");
                                                goto error;
@@ -138,8 +141,7 @@ static void *thread_application_management(void *data)
                                         * Since this is a command socket (write then read),
                                         * we only monitor the error events of the socket.
                                         */
-                                       ret = lttng_poll_add(&events, sock,
-                                                       LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+                                       ret = lttng_poll_add(&events, sock, LPOLLRDHUP);
                                        if (ret < 0) {
                                                goto error;
                                        }
@@ -165,9 +167,11 @@ static void *thread_application_management(void *data)
                                        }
 
                                        /* Socket closed on remote end. */
-                                       ust_app_unregister(pollfd);
+                                       ust_app_unregister_by_socket(pollfd);
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                        }
@@ -196,7 +200,7 @@ error_testpoint:
        DBG("Application communication apps thread cleanup complete");
        rcu_thread_offline();
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_application_management_thread(void *data)
@@ -210,7 +214,7 @@ static bool shutdown_application_management_thread(void *data)
 bool launch_application_management_thread(int apps_cmd_pipe_read_fd)
 {
        struct lttng_pipe *quit_pipe;
-       struct thread_notifiers *notifiers = NULL;
+       struct thread_notifiers *notifiers = nullptr;
        struct lttng_thread *thread;
 
        notifiers = zmalloc<thread_notifiers>();
@@ -225,10 +229,10 @@ bool launch_application_management_thread(int apps_cmd_pipe_read_fd)
        notifiers->apps_cmd_pipe_read_fd = apps_cmd_pipe_read_fd;
 
        thread = lttng_thread_create("UST application management",
-                       thread_application_management,
-                       shutdown_application_management_thread,
-                       cleanup_application_management_thread,
-                       notifiers);
+                                    thread_application_management,
+                                    shutdown_application_management_thread,
+                                    cleanup_application_management_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index a865d9a8fc344947e33e04d306dfea1d35a4e55d..6d4c7a62548368f6ebb4e9e58e86cc1474581c66 100644 (file)
 #ifndef SESSIOND_APPLICATION_MANAGEMENT_THREAD_H
 #define SESSIOND_APPLICATION_MANAGEMENT_THREAD_H
 
-#include <stdbool.h>
 #include "lttng-sessiond.hpp"
 
+#include <stdbool.h>
+
 bool launch_application_management_thread(int apps_cmd_pipe_read_fd);
 
 #endif /* SESSIOND_APPLICATION_MANAGEMENT_THREAD_H */
index a3bb816f9459457ab0a1a74379bab796283a228b..27a368e7f19d80d7dbaed75ee6c64f3eb61b28ca 100644 (file)
@@ -7,17 +7,18 @@
  *
  */
 
-#include <signal.h>
-
-#include <common/pipe.hpp>
-#include <common/utils.hpp>
-
+#include "health-sessiond.hpp"
 #include "manage-consumer.hpp"
 #include "testpoint.hpp"
-#include "health-sessiond.hpp"
-#include "utils.hpp"
 #include "thread.hpp"
 #include "ust-consumer.hpp"
+#include "utils.hpp"
+
+#include <common/pipe.hpp>
+#include <common/utils.hpp>
+
+#include <fcntl.h>
+#include <signal.h>
 
 namespace {
 struct thread_notifiers {
@@ -35,8 +36,7 @@ static void mark_thread_as_ready(struct thread_notifiers *notifiers)
        sem_post(&notifiers->ready);
 }
 
-static void mark_thread_intialization_as_failed(
-               struct thread_notifiers *notifiers)
+static void mark_thread_intialization_as_failed(struct thread_notifiers *notifiers)
 {
        ERR("Consumer management thread entering error state");
        notifiers->initialization_result = -1;
@@ -55,14 +55,14 @@ static void wait_until_thread_is_ready(struct thread_notifiers *notifiers)
  */
 static void *thread_consumer_management(void *data)
 {
-       int sock = -1, i, ret, pollfd, err = -1, should_quit = 0;
-       uint32_t revents, nb_fd;
+       int sock = -1, i, ret, err = -1, should_quit = 0;
+       uint32_t nb_fd;
        enum lttcomm_return_code code;
        struct lttng_poll_event events;
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
        struct consumer_data *consumer_data = notifiers->consumer_data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
-       struct consumer_socket *cmd_socket_wrapper = NULL;
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
+       struct consumer_socket *cmd_socket_wrapper = nullptr;
 
        DBG("[thread] Manage consumer started");
 
@@ -83,7 +83,7 @@ static void *thread_consumer_management(void *data)
                goto error_poll;
        }
 
-       ret = lttng_poll_add(&events, quit_pipe_read_fd, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                mark_thread_intialization_as_failed(notifiers);
                goto error;
@@ -121,13 +121,14 @@ static void *thread_consumer_management(void *data)
 
        for (i = 0; i < nb_fd; i++) {
                /* Fetch once the poll data */
-               revents = LTTNG_POLL_GETEV(&events, i);
-               pollfd = LTTNG_POLL_GETFD(&events, i);
+               const auto revents = LTTNG_POLL_GETEV(&events, i);
+               const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                health_code_update();
 
-               /* Thread quit pipe has been closed. Killing thread. */
-               if (pollfd == quit_pipe_read_fd) {
+               /* Activity on thread quit pipe, exiting. */
+               if (pollfd == thread_quit_pipe_fd) {
+                       DBG("Activity on thread quit pipe");
                        err = 0;
                        mark_thread_intialization_as_failed(notifiers);
                        goto exit;
@@ -163,9 +164,13 @@ static void *thread_consumer_management(void *data)
 
        DBG2("Receiving code from consumer err_sock");
 
-       /* Getting status code from kconsumerd */
-       ret = lttcomm_recv_unix_sock(sock, &code,
-                       sizeof(enum lttcomm_return_code));
+       /* Getting status code from consumerd */
+       {
+               std::int32_t comm_code = 0;
+
+               ret = lttcomm_recv_unix_sock(sock, &comm_code, sizeof(comm_code));
+               code = static_cast<decltype(code)>(comm_code);
+       }
        if (ret <= 0) {
                mark_thread_intialization_as_failed(notifiers);
                goto error;
@@ -174,18 +179,14 @@ static void *thread_consumer_management(void *data)
        health_code_update();
        if (code != LTTCOMM_CONSUMERD_COMMAND_SOCK_READY) {
                ERR("consumer error when waiting for SOCK_READY : %s",
-                               lttcomm_get_readable_code((lttcomm_return_code) -code));
+                   lttcomm_get_readable_code((lttcomm_return_code) -code));
                mark_thread_intialization_as_failed(notifiers);
                goto error;
        }
 
        /* Connect both command and metadata sockets. */
-       consumer_data->cmd_sock =
-                       lttcomm_connect_unix_sock(
-                               consumer_data->cmd_unix_sock_path);
-       consumer_data->metadata_fd =
-                       lttcomm_connect_unix_sock(
-                               consumer_data->cmd_unix_sock_path);
+       consumer_data->cmd_sock = lttcomm_connect_unix_sock(consumer_data->cmd_unix_sock_path);
+       consumer_data->metadata_fd = lttcomm_connect_unix_sock(consumer_data->cmd_unix_sock_path);
        if (consumer_data->cmd_sock < 0 || consumer_data->metadata_fd < 0) {
                PERROR("consumer connect cmd socket");
                mark_thread_intialization_as_failed(notifiers);
@@ -196,16 +197,15 @@ static void *thread_consumer_management(void *data)
 
        /* Create metadata socket lock. */
        consumer_data->metadata_sock.lock = zmalloc<pthread_mutex_t>();
-       if (consumer_data->metadata_sock.lock == NULL) {
+       if (consumer_data->metadata_sock.lock == nullptr) {
                PERROR("zmalloc pthread mutex");
                mark_thread_intialization_as_failed(notifiers);
                goto error;
        }
-       pthread_mutex_init(consumer_data->metadata_sock.lock, NULL);
+       pthread_mutex_init(consumer_data->metadata_sock.lock, nullptr);
 
        DBG("Consumer command socket ready (fd: %d)", consumer_data->cmd_sock);
-       DBG("Consumer metadata socket ready (fd: %d)",
-                       consumer_data->metadata_fd);
+       DBG("Consumer metadata socket ready (fd: %d)", consumer_data->metadata_fd);
 
        /*
         * Remove the consumerd error sock since we've established a connection.
@@ -224,8 +224,7 @@ static void *thread_consumer_management(void *data)
        }
 
        /* Add metadata socket that is successfully connected. */
-       ret = lttng_poll_add(&events, consumer_data->metadata_fd,
-                       LPOLLIN | LPOLLRDHUP);
+       ret = lttng_poll_add(&events, consumer_data->metadata_fd, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                mark_thread_intialization_as_failed(notifiers);
                goto error;
@@ -255,7 +254,7 @@ static void *thread_consumer_management(void *data)
        pthread_mutex_unlock(cmd_socket_wrapper->lock);
 
        ret = consumer_send_channel_monitor_pipe(cmd_socket_wrapper,
-                       consumer_data->channel_monitor_pipe);
+                                                consumer_data->channel_monitor_pipe);
        if (ret) {
                mark_thread_intialization_as_failed(notifiers);
                goto error;
@@ -263,13 +262,13 @@ static void *thread_consumer_management(void *data)
 
        /* Discard the socket wrapper as it is no longer needed. */
        consumer_destroy_socket(cmd_socket_wrapper);
-       cmd_socket_wrapper = NULL;
+       cmd_socket_wrapper = nullptr;
 
        /* The thread is completely initialized, signal that it is ready. */
        mark_thread_as_ready(notifiers);
 
        /* Infinite blocking call, waiting for transmission */
-       while (1) {
+       while (true) {
                health_code_update();
 
                /* Exit the thread because the thread quit pipe has been triggered. */
@@ -290,8 +289,8 @@ static void *thread_consumer_management(void *data)
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
@@ -300,37 +299,41 @@ static void *thread_consumer_management(void *data)
                         * but continue the current loop to handle potential data from
                         * consumer.
                         */
-                       if (pollfd == quit_pipe_read_fd) {
+                       if (pollfd == thread_quit_pipe_fd) {
                                should_quit = 1;
                        } else if (pollfd == sock) {
                                /* Event on the consumerd socket */
-                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
-                                               && !(revents & LPOLLIN)) {
+                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP) &&
+                                   !(revents & LPOLLIN)) {
                                        ERR("consumer err socket second poll error");
                                        goto error;
                                }
                                health_code_update();
-                               /* Wait for any kconsumerd error */
-                               ret = lttcomm_recv_unix_sock(sock, &code,
-                                               sizeof(enum lttcomm_return_code));
+                               /* Wait for any consumerd error */
+                               {
+                                       std::int32_t comm_code = 0;
+
+                                       ret = lttcomm_recv_unix_sock(
+                                               sock, &comm_code, sizeof(comm_code));
+                                       code = static_cast<decltype(code)>(comm_code);
+                               }
                                if (ret <= 0) {
                                        ERR("consumer closed the command socket");
                                        goto error;
                                }
 
                                ERR("consumer return code : %s",
-                                               lttcomm_get_readable_code((lttcomm_return_code) -code));
+                                   lttcomm_get_readable_code((lttcomm_return_code) -code));
 
                                goto exit;
                        } else if (pollfd == consumer_data->metadata_fd) {
-                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
-                                               && !(revents & LPOLLIN)) {
+                               if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP) &&
+                                   !(revents & LPOLLIN)) {
                                        ERR("consumer err metadata socket second poll error");
                                        goto error;
                                }
                                /* UST metadata requests */
-                               ret = ust_consumer_metadata_request(
-                                               &consumer_data->metadata_sock);
+                               ret = ust_consumer_metadata_request(&consumer_data->metadata_sock);
                                if (ret < 0) {
                                        ERR("Handling metadata request");
                                        goto error;
@@ -354,7 +357,7 @@ error:
        if (consumer_data->type == LTTNG_CONSUMER_KERNEL) {
                uatomic_set(&the_kernel_consumerd_state, CONSUMER_ERROR);
        } else if (consumer_data->type == LTTNG_CONSUMER64_UST ||
-                       consumer_data->type == LTTNG_CONSUMER32_UST) {
+                  consumer_data->type == LTTNG_CONSUMER32_UST) {
                uatomic_set(&the_ust_consumerd_state, CONSUMER_ERROR);
        } else {
                /* Code flow error... */
@@ -375,8 +378,7 @@ error:
                }
                consumer_data->cmd_sock = -1;
        }
-       if (consumer_data->metadata_sock.fd_ptr &&
-           *consumer_data->metadata_sock.fd_ptr >= 0) {
+       if (consumer_data->metadata_sock.fd_ptr && *consumer_data->metadata_sock.fd_ptr >= 0) {
                ret = close(*consumer_data->metadata_sock.fd_ptr);
                if (ret) {
                        PERROR("close");
@@ -414,7 +416,7 @@ error_poll:
        rcu_thread_offline();
        rcu_unregister_thread();
 
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_consumer_management_thread(void *data)
@@ -436,7 +438,7 @@ static void cleanup_consumer_management_thread(void *data)
 bool launch_consumer_management_thread(struct consumer_data *consumer_data)
 {
        struct lttng_pipe *quit_pipe;
-       struct thread_notifiers *notifiers = NULL;
+       struct thread_notifiers *notifiers = nullptr;
        struct lttng_thread *thread;
 
        notifiers = zmalloc<thread_notifiers>();
@@ -453,19 +455,16 @@ bool launch_consumer_management_thread(struct consumer_data *consumer_data)
        sem_init(&notifiers->ready, 0, 0);
 
        thread = lttng_thread_create("Consumer management",
-                       thread_consumer_management,
-                       shutdown_consumer_management_thread,
-                       cleanup_consumer_management_thread,
-                       notifiers);
+                                    thread_consumer_management,
+                                    shutdown_consumer_management_thread,
+                                    cleanup_consumer_management_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
        wait_until_thread_is_ready(notifiers);
        lttng_thread_put(thread);
-       if (notifiers->initialization_result) {
-               return false;
-       }
-       return true;
+       return notifiers->initialization_result == 0;
 error:
        cleanup_consumer_management_thread(notifiers);
 error_alloc:
index 9e35a9051b4806f63ce83a5be69d15b40fc1c415..e2b29cc5b914765151db48208f1ae516517cec90 100644 (file)
 #ifndef SESSIOND_CONSUMER_MANAGEMENT_THREAD_H
 #define SESSIOND_CONSUMER_MANAGEMENT_THREAD_H
 
-#include <stdbool.h>
 #include "lttng-sessiond.hpp"
 
+#include <stdbool.h>
+
 bool launch_consumer_management_thread(struct consumer_data *consumer_data);
 
 #endif /* SESSIOND_CONSUMER_MANAGEMENT_THREAD_H */
index 8d2795466bb32400beda37fd2757aa1b94cb5441..fe7f21c6fe36774c19a015239baabd3eb7882af4 100644 (file)
@@ -7,16 +7,19 @@
  *
  */
 
-#include <common/pipe.hpp>
-#include <common/utils.hpp>
-
+#include "health-sessiond.hpp"
+#include "kernel-consumer.hpp"
+#include "kernel.hpp"
 #include "manage-kernel.hpp"
 #include "testpoint.hpp"
-#include "health-sessiond.hpp"
-#include "utils.hpp"
 #include "thread.hpp"
-#include "kernel.hpp"
-#include "kernel-consumer.hpp"
+#include "utils.hpp"
+
+#include <common/pipe.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
+#include <fcntl.h>
 
 namespace {
 struct thread_notifiers {
@@ -39,19 +42,19 @@ static int update_kernel_poll(struct lttng_poll_event *events)
        DBG("Updating kernel poll set");
 
        session_lock_list();
-       cds_list_for_each_entry(session, &session_list->head, list) {
+       cds_list_for_each_entry (session, &session_list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
                session_lock(session);
-               if (session->kernel_session == NULL) {
+               if (session->kernel_session == nullptr) {
                        session_unlock(session);
                        session_put(session);
                        continue;
                }
 
-               cds_list_for_each_entry(channel,
-                               &session->kernel_session->channel_list.head, list) {
+               cds_list_for_each_entry (
+                       channel, &session->kernel_session->channel_list.head, list) {
                        /* Add channel fd to the kernel poll set */
                        ret = lttng_poll_add(events, channel->fd, LPOLLIN | LPOLLRDNORM);
                        if (ret < 0) {
@@ -90,20 +93,21 @@ static int update_kernel_stream(int fd)
        DBG("Updating kernel streams for channel fd %d", fd);
 
        session_lock_list();
-       cds_list_for_each_entry(session, &session_list->head, list) {
+       cds_list_for_each_entry (session, &session_list->head, list) {
                if (!session_get(session)) {
                        continue;
                }
+
                session_lock(session);
-               if (session->kernel_session == NULL) {
+               if (session->kernel_session == nullptr) {
                        session_unlock(session);
                        session_put(session);
                        continue;
                }
+
                ksess = session->kernel_session;
 
-               cds_list_for_each_entry(channel,
-                               &ksess->channel_list.head, list) {
+               cds_list_for_each_entry (channel, &ksess->channel_list.head, list) {
                        struct lttng_ht_iter iter;
                        struct consumer_socket *socket;
 
@@ -123,27 +127,30 @@ static int update_kernel_stream(int fd)
                         * means that tracing is started so it is safe to send
                         * our updated stream fds.
                         */
-                       if (ksess->consumer_fds_sent != 1
-                                       || ksess->consumer == NULL) {
+                       if (ksess->consumer_fds_sent != 1 || ksess->consumer == nullptr) {
                                ret = -1;
                                goto error;
                        }
 
-                       rcu_read_lock();
-                       cds_lfht_for_each_entry(ksess->consumer->socks->ht,
-                                       &iter.iter, socket, node.node) {
-                               pthread_mutex_lock(socket->lock);
-                               ret = kernel_consumer_send_channel_streams(socket,
-                                               channel, ksess,
+                       {
+                               lttng::urcu::read_lock_guard read_lock;
+
+                               cds_lfht_for_each_entry (
+                                       ksess->consumer->socks->ht, &iter.iter, socket, node.node) {
+                                       pthread_mutex_lock(socket->lock);
+                                       ret = kernel_consumer_send_channel_streams(
+                                               socket,
+                                               channel,
+                                               ksess,
                                                session->output_traces ? 1 : 0);
-                               pthread_mutex_unlock(socket->lock);
-                               if (ret < 0) {
-                                       rcu_read_unlock();
-                                       goto error;
+                                       pthread_mutex_unlock(socket->lock);
+                                       if (ret < 0) {
+                                               goto error;
+                                       }
                                }
                        }
-                       rcu_read_unlock();
                }
+
                session_unlock(session);
                session_put(session);
        }
@@ -165,12 +172,12 @@ error:
  */
 static void *thread_kernel_management(void *data)
 {
-       int ret, i, pollfd, update_poll_flag = 1, err = -1;
-       uint32_t revents, nb_fd;
+       int ret, i, update_poll_flag = 1, err = -1;
+       uint32_t nb_fd;
        char tmp;
        struct lttng_poll_event events;
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
 
        DBG("[thread] Thread manage kernel started");
 
@@ -192,7 +199,7 @@ static void *thread_kernel_management(void *data)
                goto error_testpoint;
        }
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                if (update_poll_flag == 1) {
@@ -204,16 +211,12 @@ static void *thread_kernel_management(void *data)
                                goto error_poll_create;
                        }
 
-                       ret = lttng_poll_add(&events,
-                                       notifiers->kernel_poll_pipe_read_fd,
-                                       LPOLLIN);
+                       ret = lttng_poll_add(&events, notifiers->kernel_poll_pipe_read_fd, LPOLLIN);
                        if (ret < 0) {
                                goto error;
                        }
 
-                       ret = lttng_poll_add(&events,
-                                       quit_pipe_read_fd,
-                                       LPOLLIN);
+                       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
                        if (ret < 0) {
                                goto error;
                        }
@@ -232,8 +235,7 @@ static void *thread_kernel_management(void *data)
        restart:
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
-               DBG("Thread kernel return from poll on %d fds",
-                               LTTNG_POLL_GETNB(&events));
+               DBG("Thread kernel return from poll on %d fds", LTTNG_POLL_GETNB(&events));
                health_poll_exit();
                if (ret < 0) {
                        /*
@@ -246,7 +248,7 @@ static void *thread_kernel_management(void *data)
                } else if (ret == 0) {
                        /* Should not happen since timeout is infinite */
                        ERR("Return value of poll is 0 with an infinite timeout.\n"
-                               "This should not have happened! Continuing...");
+                           "This should not have happened! Continuing...");
                        continue;
                }
 
@@ -254,12 +256,14 @@ static void *thread_kernel_management(void *data)
 
                for (i = 0; i < nb_fd; i++) {
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
                        health_code_update();
 
-                       if (pollfd == quit_pipe_read_fd) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
                        }
@@ -267,11 +271,11 @@ static void *thread_kernel_management(void *data)
                        /* Check for data on kernel pipe */
                        if (revents & LPOLLIN) {
                                if (pollfd == notifiers->kernel_poll_pipe_read_fd) {
-                                       (void) lttng_read(notifiers->kernel_poll_pipe_read_fd,
-                                               &tmp, 1);
+                                       (void) lttng_read(
+                                               notifiers->kernel_poll_pipe_read_fd, &tmp, 1);
                                        /*
-                                        * Ret value is useless here, if this pipe gets any actions an
-                                        * update is required anyway.
+                                        * Ret value is useless here, if this pipe gets any actions
+                                        * an update is required anyway.
                                         */
                                        update_poll_flag = 1;
                                        continue;
@@ -305,11 +309,11 @@ error_testpoint:
                health_error();
                ERR("Health error occurred in %s", __func__);
                WARN("Kernel thread died unexpectedly. "
-                               "Kernel tracing can continue but CPU hotplug is disabled.");
+                    "Kernel tracing can continue but CPU hotplug is disabled.");
        }
        health_unregister(the_health_sessiond);
        DBG("Kernel thread dying");
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_kernel_management_thread(void *data)
@@ -331,7 +335,7 @@ static void cleanup_kernel_management_thread(void *data)
 bool launch_kernel_management_thread(int kernel_poll_pipe_read_fd)
 {
        struct lttng_pipe *quit_pipe;
-       struct thread_notifiers *notifiers = NULL;
+       struct thread_notifiers *notifiers = nullptr;
        struct lttng_thread *thread;
 
        notifiers = zmalloc<thread_notifiers>();
@@ -346,10 +350,10 @@ bool launch_kernel_management_thread(int kernel_poll_pipe_read_fd)
        notifiers->kernel_poll_pipe_read_fd = kernel_poll_pipe_read_fd;
 
        thread = lttng_thread_create("Kernel management",
-                       thread_kernel_management,
-                       shutdown_kernel_management_thread,
-                       cleanup_kernel_management_thread,
-                       notifiers);
+                                    thread_kernel_management,
+                                    shutdown_kernel_management_thread,
+                                    cleanup_kernel_management_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index fe0d8b0130f803836873edc03244f335b531dee9..c514d6042718448ef87ac65f89b126a1e9f9857c 100644 (file)
 #ifndef SESSIOND_KERNEL_MANAGEMENT_THREAD_H
 #define SESSIOND_KERNEL_MANAGEMENT_THREAD_H
 
-#include <stdbool.h>
 #include "lttng-sessiond.hpp"
 
+#include <stdbool.h>
+
 bool launch_kernel_management_thread(int kernel_poll_pipe_read_fd);
 
 #endif /* SESSIOND_KERNEL_MANAGEMENT_THREAD_H */
index 90ed3ff14479b43a9dcdbf43ad5440358d311923..0b274c9a3fae6e4986f4704c9bdc5e7c4ba221f7 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/wait.h>
+#include "kern-modules.hpp"
+#include "lttng-sessiond.hpp"
+#include "modprobe.hpp"
 
 #include <common/common.hpp>
 #include <common/utils.hpp>
 
-#include "modprobe.hpp"
-#include "kern-modules.hpp"
-#include "lttng-sessiond.hpp"
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/wait.h>
 
 /* LTTng kernel tracer mandatory core modules list */
 struct kern_modules_param kern_modules_control_core[] = {
@@ -299,13 +299,13 @@ static int probes_capacity;
 /**
  * @brief Logging function for libkmod integration.
  */
-static ATTR_FORMAT_PRINTF(6, 0)
-void log_kmod(void *data __attribute__((unused)),
-               int priority __attribute__((unused)),
-               const char *file __attribute__((unused)),
-               int line __attribute__((unused)),
-               const char *fn __attribute__((unused)),
-               const char *format, va_list args)
+static ATTR_FORMAT_PRINTF(6, 0) void log_kmod(void *data __attribute__((unused)),
+                                             int priority __attribute__((unused)),
+                                             const char *file __attribute__((unused)),
+                                             int line __attribute__((unused)),
+                                             const char *fn __attribute__((unused)),
+                                             const char *format,
+                                             va_list args)
 {
        char *str;
 
@@ -330,7 +330,7 @@ static int setup_kmod_ctx(struct kmod_ctx **ctx)
 {
        int ret = 0;
 
-       *ctx = kmod_new(NULL, NULL);
+       *ctx = kmod_new(nullptr, nullptr);
        if (!ctx) {
                PERROR("Unable to create kmod library context");
                ret = -ENOMEM;
@@ -344,7 +344,7 @@ static int setup_kmod_ctx(struct kmod_ctx **ctx)
         */
        DIAGNOSTIC_PUSH
        DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
-       kmod_set_log_fn(*ctx, log_kmod, NULL);
+       kmod_set_log_fn(*ctx, log_kmod, nullptr);
        DIAGNOSTIC_POP
        ret = kmod_load_resources(*ctx);
        if (ret < 0) {
@@ -368,8 +368,7 @@ error:
  * @returns            \c 0 on success
  *                     \c < 0 on error
  */
-static int modprobe_lttng(struct kern_modules_param *modules,
-               int entries)
+static int modprobe_lttng(struct kern_modules_param *modules, int entries)
 {
        int ret = 0, i;
        struct kmod_ctx *ctx;
@@ -380,7 +379,7 @@ static int modprobe_lttng(struct kern_modules_param *modules,
        }
 
        for (i = 0; i < entries; i++) {
-               struct kmod_module *mod = NULL;
+               struct kmod_module *mod = nullptr;
 
                ret = kmod_module_new_from_name(ctx, modules[i].name, &mod);
                if (ret < 0) {
@@ -388,19 +387,17 @@ static int modprobe_lttng(struct kern_modules_param *modules,
                        goto error;
                }
 
-               ret = kmod_module_probe_insert_module(mod, 0,
-                               NULL, NULL, NULL, NULL);
+               ret = kmod_module_probe_insert_module(mod, 0, nullptr, nullptr, nullptr, nullptr);
                if (ret == -EEXIST) {
                        DBG("Module %s is already loaded", modules[i].name);
                        ret = 0;
                } else if (ret < 0) {
                        if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED) {
-                               ERR("Unable to load required module %s",
-                                               modules[i].name);
+                               PERROR("Unable to load required module `%s`", modules[i].name)
                                goto error;
                        } else {
-                               DBG("Unable to load optional module %s; continuing",
-                                               modules[i].name);
+                               PERROR("Unable to load optional module `%s`; continuing",
+                                      modules[i].name);
                                ret = 0;
                        }
                } else {
@@ -430,7 +427,8 @@ error:
  * @returns            \c 0 on success
  *                     \c < 0 on error
  */
-static int rmmod_recurse(struct kmod_module *mod) {
+static int rmmod_recurse(struct kmod_module *mod)
+{
        int ret = 0;
        struct kmod_list *deps, *itr;
 
@@ -442,12 +440,12 @@ static int rmmod_recurse(struct kmod_module *mod) {
        ret = kmod_module_remove_module(mod, 0);
 
        deps = kmod_module_get_dependencies(mod);
-       if (deps != NULL) {
-               kmod_list_foreach(itr, deps) {
+       if (deps != nullptr) {
+               kmod_list_foreach(itr, deps)
+               {
                        struct kmod_module *dep = kmod_module_get_module(itr);
                        if (kmod_module_get_refcnt(dep) == 0) {
-                               DBG("Recursive remove module %s",
-                                               kmod_module_get_name(dep));
+                               DBG("Recursive remove module %s", kmod_module_get_name(dep));
                                rmmod_recurse(dep);
                        }
                        kmod_module_unref(dep);
@@ -465,8 +463,7 @@ static int rmmod_recurse(struct kmod_module *mod) {
  * @param entries      Number of modules in the list
  *
  */
-static void modprobe_remove_lttng(const struct kern_modules_param *modules,
-               int entries)
+static void modprobe_remove_lttng(const struct kern_modules_param *modules, int entries)
 {
        int ret = 0, i;
        struct kmod_ctx *ctx;
@@ -477,7 +474,7 @@ static void modprobe_remove_lttng(const struct kern_modules_param *modules,
        }
 
        for (i = entries - 1; i >= 0; i--) {
-               struct kmod_module *mod = NULL;
+               struct kmod_module *mod = nullptr;
 
                if (!modules[i].loaded) {
                        continue;
@@ -492,11 +489,11 @@ static void modprobe_remove_lttng(const struct kern_modules_param *modules,
                ret = rmmod_recurse(mod);
                if (ret == -EEXIST) {
                        DBG("Module %s is not in kernel.", modules[i].name);
-               } else if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED && ret < 0) {
-                       ERR("Unable to remove module %s", modules[i].name);
+               } else if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED &&
+                          ret < 0) {
+                       PERROR("Unable to remove module `%s`", modules[i].name);
                } else {
-                       DBG("Modprobe removal successful %s",
-                               modules[i].name);
+                       DBG("Modprobe removal successful %s", modules[i].name);
                }
 
                kmod_module_unref(mod);
@@ -510,17 +507,20 @@ error:
 
 #else /* HAVE_KMOD */
 
-static int modprobe_lttng(struct kern_modules_param *modules,
-               int entries)
+static int modprobe_lttng(struct kern_modules_param *modules, int entries)
 {
        int ret = 0, i;
        char modprobe[256];
 
        for (i = 0; i < entries; i++) {
-               ret = snprintf(modprobe, sizeof(modprobe),
-                               "/sbin/modprobe %s%s",
-                               modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED ? "" : "-q ",
-                               modules[i].name);
+               ret = snprintf(modprobe,
+                              sizeof(modprobe),
+                              "/sbin/modprobe %s%s",
+                              modules[i].load_policy ==
+                                              KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED ?
+                                      "" :
+                                      "-q ",
+                              modules[i].name);
                if (ret < 0) {
                        PERROR("snprintf modprobe");
                        goto error;
@@ -530,21 +530,24 @@ static int modprobe_lttng(struct kern_modules_param *modules,
                if (ret == -1) {
                        if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED) {
                                ERR("Unable to launch modprobe for required module %s",
-                                               modules[i].name);
+                                   modules[i].name);
                                goto error;
                        } else {
                                DBG("Unable to launch modprobe for optional module %s; continuing",
-                                               modules[i].name);
+                                   modules[i].name);
                                ret = 0;
                        }
                } else if (WEXITSTATUS(ret) != 0) {
                        if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED) {
-                               ERR("Unable to load required module %s",
-                                               modules[i].name);
+                               ERR("Unable to load required module %s", modules[i].name);
+                               /* Force negative return code */
+                               if (ret > 0) {
+                                       ret = -ret;
+                               }
                                goto error;
                        } else {
                                DBG("Unable to load optional module %s; continuing",
-                                               modules[i].name);
+                                   modules[i].name);
                                ret = 0;
                        }
                } else {
@@ -557,8 +560,7 @@ error:
        return ret;
 }
 
-static void modprobe_remove_lttng(const struct kern_modules_param *modules,
-               int entries)
+static void modprobe_remove_lttng(const struct kern_modules_param *modules, int entries)
 {
        int ret = 0, i;
        char modprobe[256];
@@ -567,9 +569,8 @@ static void modprobe_remove_lttng(const struct kern_modules_param *modules,
                if (!modules[i].loaded) {
                        continue;
                }
-               ret = snprintf(modprobe, sizeof(modprobe),
-                               "/sbin/modprobe -r -q %s",
-                               modules[i].name);
+               ret = snprintf(
+                       modprobe, sizeof(modprobe), "/sbin/modprobe -r -q %s", modules[i].name);
                if (ret < 0) {
                        PERROR("snprintf modprobe -r");
                        return;
@@ -579,18 +580,16 @@ static void modprobe_remove_lttng(const struct kern_modules_param *modules,
                if (ret == -1) {
                        if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED) {
                                ERR("Unable to launch modprobe -r for required module %s",
-                                               modules[i].name);
+                                   modules[i].name);
                        } else {
                                DBG("Unable to launch modprobe -r for optional module %s",
-                                               modules[i].name);
+                                   modules[i].name);
                        }
                } else if (WEXITSTATUS(ret) != 0) {
                        if (modules[i].load_policy == KERNEL_MODULE_PROPERTY_LOAD_POLICY_REQUIRED) {
-                               ERR("Unable to remove required module %s",
-                                               modules[i].name);
+                               ERR("Unable to remove required module %s", modules[i].name);
                        } else {
-                               DBG("Unable to remove optional module %s",
-                                               modules[i].name);
+                               DBG("Unable to remove optional module %s", modules[i].name);
                        }
                } else {
                        DBG("Modprobe removal successful %s", modules[i].name);
@@ -603,13 +602,12 @@ static void modprobe_remove_lttng(const struct kern_modules_param *modules,
 /*
  * Remove control kernel module(s) in reverse load order.
  */
-void modprobe_remove_lttng_control(void)
+void modprobe_remove_lttng_control()
 {
-       modprobe_remove_lttng(kern_modules_control_core,
-                       ARRAY_SIZE(kern_modules_control_core));
+       modprobe_remove_lttng(kern_modules_control_core, ARRAY_SIZE(kern_modules_control_core));
 }
 
-static void free_probes(void)
+static void free_probes()
 {
        int i;
 
@@ -620,14 +618,14 @@ static void free_probes(void)
                free(probes[i].name);
        }
        free(probes);
-       probes = NULL;
+       probes = nullptr;
        nr_probes = 0;
 }
 
 /*
  * Remove data kernel modules in reverse load order.
  */
-void modprobe_remove_lttng_data(void)
+void modprobe_remove_lttng_data()
 {
        if (!probes) {
                return;
@@ -640,7 +638,7 @@ void modprobe_remove_lttng_data(void)
 /*
  * Remove all kernel modules in reverse order.
  */
-void modprobe_remove_lttng_all(void)
+void modprobe_remove_lttng_all()
 {
        modprobe_remove_lttng_data();
        modprobe_remove_lttng_control();
@@ -649,17 +647,16 @@ void modprobe_remove_lttng_all(void)
 /*
  * Load control kernel module(s).
  */
-int modprobe_lttng_control(void)
+int modprobe_lttng_control()
 {
-       return modprobe_lttng(kern_modules_control_core,
-                       ARRAY_SIZE(kern_modules_control_core));
+       return modprobe_lttng(kern_modules_control_core, ARRAY_SIZE(kern_modules_control_core));
 }
 
 /**
  * Grow global list of probes (double capacity or set it to 1 if
  * currently 0 and copy existing data).
  */
-static int grow_probes(void)
+static int grow_probes()
 {
        int i;
        struct kern_modules_param *tmp_probes;
@@ -723,7 +720,7 @@ static int append_list_to_probes(const char *list)
                if (!next) {
                        break;
                }
-               cur_list = NULL;
+               cur_list = nullptr;
 
                /* filter leading spaces */
                while (*next == ' ') {
@@ -772,7 +769,7 @@ error:
 /*
  * Load data kernel module(s).
  */
-int modprobe_lttng_data(void)
+int modprobe_lttng_data()
 {
        int ret, i;
        char *list;
@@ -801,7 +798,7 @@ int modprobe_lttng_data(void)
                nr_probes = probes_capacity = def_len;
 
                for (i = 0; i < def_len; ++i) {
-                       charname = strdup(kern_modules_probes_default[i].name);
+                       char *name = strdup(kern_modules_probes_default[i].name);
 
                        if (!name) {
                                PERROR("strdup probe item");
index f0ad01c9c3420835081fa67f9136d1f6f6c501f6..a006d009f789a3d030c864a537c70864344d2179 100644 (file)
@@ -8,10 +8,10 @@
 #ifndef _MODPROBE_H
 #define _MODPROBE_H
 
-void modprobe_remove_lttng_all(void);
-void modprobe_remove_lttng_control(void);
-void modprobe_remove_lttng_data(void);
-int modprobe_lttng_control(void);
-int modprobe_lttng_data(void);
+void modprobe_remove_lttng_all();
+void modprobe_remove_lttng_control();
+void modprobe_remove_lttng_data();
+int modprobe_lttng_control();
+int modprobe_lttng_data();
 
 #endif /* _MODPROBE_H */
index 25c987b67fcb1f6cc11cab7846982a1f1c5da864..2f275477b133e9c488d21beb38cdccbe6e516e6f 100644 (file)
@@ -5,36 +5,38 @@
  *
  */
 
-#include <lttng/trigger/trigger.h>
-#include <lttng/lttng-error.h>
-#include "notification-thread.hpp"
 #include "notification-thread-commands.hpp"
+#include "notification-thread.hpp"
+
 #include <common/error.hpp>
-#include <unistd.h>
-#include <stdint.h>
+
+#include <lttng/lttng-error.h>
+#include <lttng/trigger/trigger.h>
+
 #include <inttypes.h>
+#include <stdint.h>
+#include <unistd.h>
 
-static
-void init_notification_thread_command(struct notification_thread_command *cmd)
+static void init_notification_thread_command(struct notification_thread_command *cmd)
 {
        CDS_INIT_LIST_HEAD(&cmd->cmd_list_node);
-       lttng_waiter_init(&cmd->reply_waiter);
 }
 
-static
-int run_command_wait(struct notification_thread_handle *handle,
-               struct notification_thread_command *cmd)
+static int run_command_wait(struct notification_thread_handle *handle,
+                           struct notification_thread_command *cmd)
 {
        int ret;
        uint64_t notification_counter = 1;
 
+       lttng::synchro::waiter command_completion_waiter;
+       cmd->command_completed_waker.emplace(command_completion_waiter.get_waker());
+
        pthread_mutex_lock(&handle->cmd_queue.lock);
        /* Add to queue. */
-       cds_list_add_tail(&cmd->cmd_list_node,
-                       &handle->cmd_queue.list);
+       cds_list_add_tail(&cmd->cmd_list_node, &handle->cmd_queue.list);
        /* Wake-up thread. */
-       ret = lttng_write(handle->cmd_queue.event_fd,
-                       &notification_counter, sizeof(notification_counter));
+       ret = lttng_write(
+               handle->cmd_queue.event_fd, &notification_counter, sizeof(notification_counter));
        if (ret != sizeof(notification_counter)) {
                PERROR("write to notification thread's queue event fd");
                /*
@@ -46,38 +48,37 @@ int run_command_wait(struct notification_thread_handle *handle,
        }
        pthread_mutex_unlock(&handle->cmd_queue.lock);
 
-       lttng_waiter_wait(&cmd->reply_waiter);
+       command_completion_waiter.wait();
+       ;
        return 0;
 error_unlock_queue:
        pthread_mutex_unlock(&handle->cmd_queue.lock);
        return -1;
 }
 
-static
-struct notification_thread_command *notification_thread_command_copy(
-       const struct notification_thread_command *original_cmd)
+static struct notification_thread_command *
+notification_thread_command_copy(const struct notification_thread_command *original_cmd)
 {
        struct notification_thread_command *new_cmd;
 
-       new_cmd = zmalloc<notification_thread_command>();
-       if (!new_cmd) {
-               goto end;
+       try {
+               new_cmd = new notification_thread_command;
+       } catch (const std::bad_alloc& e) {
+               ERR("Failed to allocate notification_thread_command: %s", e.what());
+               return nullptr;
        }
 
        *new_cmd = *original_cmd;
        init_notification_thread_command(new_cmd);
-end:
        return new_cmd;
 }
 
-static
-int run_command_no_wait(struct notification_thread_handle *handle,
-               const struct notification_thread_command *in_cmd)
+static int run_command_no_wait(struct notification_thread_handle *handle,
+                              const struct notification_thread_command *in_cmd)
 {
        int ret;
        uint64_t notification_counter = 1;
-       struct notification_thread_command *new_cmd =
-                       notification_thread_command_copy(in_cmd);
+       struct notification_thread_command *new_cmd = notification_thread_command_copy(in_cmd);
 
        if (!new_cmd) {
                goto error;
@@ -86,11 +87,10 @@ int run_command_no_wait(struct notification_thread_handle *handle,
 
        pthread_mutex_lock(&handle->cmd_queue.lock);
        /* Add to queue. */
-       cds_list_add_tail(&new_cmd->cmd_list_node,
-                       &handle->cmd_queue.list);
+       cds_list_add_tail(&new_cmd->cmd_list_node, &handle->cmd_queue.list);
        /* Wake-up thread. */
-       ret = lttng_write(handle->cmd_queue.event_fd,
-                       &notification_counter, sizeof(notification_counter));
+       ret = lttng_write(
+               handle->cmd_queue.event_fd, &notification_counter, sizeof(notification_counter));
        if (ret != sizeof(notification_counter)) {
                PERROR("write to notification thread's queue event fd");
                /*
@@ -100,23 +100,25 @@ int run_command_no_wait(struct notification_thread_handle *handle,
                cds_list_del(&new_cmd->cmd_list_node);
                goto error_unlock_queue;
        }
+
        pthread_mutex_unlock(&handle->cmd_queue.lock);
        return 0;
 error_unlock_queue:
-       free(new_cmd);
+
+       delete new_cmd;
        pthread_mutex_unlock(&handle->cmd_queue.lock);
 error:
        return -1;
 }
 
-enum lttng_error_code notification_thread_command_register_trigger(
-               struct notification_thread_handle *handle,
-               struct lttng_trigger *trigger,
-               bool is_trigger_anonymous)
+enum lttng_error_code
+notification_thread_command_register_trigger(struct notification_thread_handle *handle,
+                                            struct lttng_trigger *trigger,
+                                            bool is_trigger_anonymous)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        LTTNG_ASSERT(trigger);
        init_notification_thread_command(&cmd);
@@ -124,8 +126,7 @@ enum lttng_error_code notification_thread_command_register_trigger(
        cmd.type = NOTIFICATION_COMMAND_TYPE_REGISTER_TRIGGER;
        lttng_trigger_get(trigger);
        cmd.parameters.register_trigger.trigger = trigger;
-       cmd.parameters.register_trigger.is_trigger_anonymous =
-                       is_trigger_anonymous;
+       cmd.parameters.register_trigger.is_trigger_anonymous = is_trigger_anonymous;
 
        ret = run_command_wait(handle, &cmd);
        if (ret) {
@@ -137,13 +138,13 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_unregister_trigger(
-               struct notification_thread_handle *handle,
-               const struct lttng_trigger *trigger)
+enum lttng_error_code
+notification_thread_command_unregister_trigger(struct notification_thread_handle *handle,
+                                              const struct lttng_trigger *trigger)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -160,13 +161,16 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_add_session(
-               struct notification_thread_handle *handle,
-               uint64_t session_id, const char *session_name, uid_t session_uid, gid_t session_gid)
+enum lttng_error_code
+notification_thread_command_add_session(struct notification_thread_handle *handle,
+                                       uint64_t session_id,
+                                       const char *session_name,
+                                       uid_t session_uid,
+                                       gid_t session_gid)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -186,13 +190,13 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_remove_session(
-               struct notification_thread_handle *handle,
-               uint64_t session_id)
+enum lttng_error_code
+notification_thread_command_remove_session(struct notification_thread_handle *handle,
+                                          uint64_t session_id)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -209,15 +213,17 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_add_channel(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               char *channel_name, uint64_t key,
-               enum lttng_domain_type domain, uint64_t capacity)
+enum lttng_error_code
+notification_thread_command_add_channel(struct notification_thread_handle *handle,
+                                       uint64_t session_id,
+                                       char *channel_name,
+                                       uint64_t key,
+                                       enum lttng_domain_type domain,
+                                       uint64_t capacity)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -239,12 +245,11 @@ end:
 }
 
 enum lttng_error_code notification_thread_command_remove_channel(
-               struct notification_thread_handle *handle,
-               uint64_t key, enum lttng_domain_type domain)
+       struct notification_thread_handle *handle, uint64_t key, enum lttng_domain_type domain)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -262,21 +267,20 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_session_rotation_ongoing(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               uint64_t trace_archive_chunk_id)
+enum lttng_error_code
+notification_thread_command_session_rotation_ongoing(struct notification_thread_handle *handle,
+                                                    uint64_t session_id,
+                                                    uint64_t trace_archive_chunk_id)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
        cmd.type = NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_ONGOING;
        cmd.parameters.session_rotation.session_id = session_id;
-       cmd.parameters.session_rotation.trace_archive_chunk_id =
-                       trace_archive_chunk_id;
+       cmd.parameters.session_rotation.trace_archive_chunk_id = trace_archive_chunk_id;
 
        ret = run_command_wait(handle, &cmd);
        if (ret) {
@@ -289,21 +293,20 @@ end:
 }
 
 enum lttng_error_code notification_thread_command_session_rotation_completed(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               uint64_t trace_archive_chunk_id,
-               struct lttng_trace_archive_location *location)
+       struct notification_thread_handle *handle,
+       uint64_t session_id,
+       uint64_t trace_archive_chunk_id,
+       struct lttng_trace_archive_location *location)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
        cmd.type = NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_COMPLETED;
        cmd.parameters.session_rotation.session_id = session_id;
-       cmd.parameters.session_rotation.trace_archive_chunk_id =
-                       trace_archive_chunk_id;
+       cmd.parameters.session_rotation.trace_archive_chunk_id = trace_archive_chunk_id;
        cmd.parameters.session_rotation.location = location;
 
        ret = run_command_wait(handle, &cmd);
@@ -316,22 +319,21 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_add_tracer_event_source(
-               struct notification_thread_handle *handle,
-               int tracer_event_source_fd,
-               enum lttng_domain_type domain)
+enum lttng_error_code
+notification_thread_command_add_tracer_event_source(struct notification_thread_handle *handle,
+                                                   int tracer_event_source_fd,
+                                                   enum lttng_domain_type domain)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        LTTNG_ASSERT(tracer_event_source_fd >= 0);
 
        init_notification_thread_command(&cmd);
 
        cmd.type = NOTIFICATION_COMMAND_TYPE_ADD_TRACER_EVENT_SOURCE;
-       cmd.parameters.tracer_event_source.tracer_event_source_fd =
-                       tracer_event_source_fd;
+       cmd.parameters.tracer_event_source.tracer_event_source_fd = tracer_event_source_fd;
        cmd.parameters.tracer_event_source.domain = domain;
 
        ret = run_command_wait(handle, &cmd);
@@ -345,19 +347,18 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code notification_thread_command_remove_tracer_event_source(
-               struct notification_thread_handle *handle,
-               int tracer_event_source_fd)
+enum lttng_error_code
+notification_thread_command_remove_tracer_event_source(struct notification_thread_handle *handle,
+                                                      int tracer_event_source_fd)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
        cmd.type = NOTIFICATION_COMMAND_TYPE_REMOVE_TRACER_EVENT_SOURCE;
-       cmd.parameters.tracer_event_source.tracer_event_source_fd =
-                       tracer_event_source_fd;
+       cmd.parameters.tracer_event_source.tracer_event_source_fd = tracer_event_source_fd;
 
        ret = run_command_wait(handle, &cmd);
        if (ret) {
@@ -371,13 +372,11 @@ end:
 }
 
 enum lttng_error_code notification_thread_command_list_triggers(
-               struct notification_thread_handle *handle,
-               uid_t uid,
-               struct lttng_triggers **triggers)
+       struct notification_thread_handle *handle, uid_t uid, struct lttng_triggers **triggers)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        LTTNG_ASSERT(handle);
        LTTNG_ASSERT(triggers);
@@ -400,11 +399,10 @@ end:
        return ret_code;
 }
 
-void notification_thread_command_quit(
-               struct notification_thread_handle *handle)
+void notification_thread_command_quit(struct notification_thread_handle *handle)
 {
        int ret;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -414,11 +412,11 @@ void notification_thread_command_quit(
 }
 
 int notification_thread_client_communication_update(
-               struct notification_thread_handle *handle,
-               notification_client_id id,
-               enum client_transmission_status transmission_status)
+       struct notification_thread_handle *handle,
+       notification_client_id id,
+       enum client_transmission_status transmission_status)
 {
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -428,14 +426,14 @@ int notification_thread_client_communication_update(
        return run_command_no_wait(handle, &cmd);
 }
 
-enum lttng_error_code notification_thread_command_get_trigger(
-               struct notification_thread_handle *handle,
-               const struct lttng_trigger *trigger,
-               struct lttng_trigger **real_trigger)
+enum lttng_error_code
+notification_thread_command_get_trigger(struct notification_thread_handle *handle,
+                                       const struct lttng_trigger *trigger,
+                                       struct lttng_trigger **real_trigger)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct notification_thread_command cmd = {};
+       notification_thread_command cmd;
 
        init_notification_thread_command(&cmd);
 
@@ -458,18 +456,15 @@ end:
  * Takes ownership of the payload if present.
  */
 struct lttng_event_notifier_notification *lttng_event_notifier_notification_create(
-               uint64_t tracer_token,
-               enum lttng_domain_type domain,
-               char *payload,
-               size_t payload_size)
+       uint64_t tracer_token, enum lttng_domain_type domain, char *payload, size_t payload_size)
 {
-       struct lttng_event_notifier_notification *notification = NULL;
+       struct lttng_event_notifier_notification *notification = nullptr;
 
        LTTNG_ASSERT(domain != LTTNG_DOMAIN_NONE);
        LTTNG_ASSERT((payload && payload_size) || (!payload && !payload_size));
 
        notification = zmalloc<lttng_event_notifier_notification>();
-       if (notification == NULL) {
+       if (notification == nullptr) {
                ERR("Error allocating notification");
                goto end;
        }
@@ -484,7 +479,7 @@ end:
 }
 
 void lttng_event_notifier_notification_destroy(
-               struct lttng_event_notifier_notification *notification)
+       struct lttng_event_notifier_notification *notification)
 {
        if (!notification) {
                return;
index 293a0b4b79ec685cd81c121b589ccd6e05941622..8a3150ae32d72987b5c46a20b9096188649e97a1 100644 (file)
@@ -8,14 +8,19 @@
 #ifndef NOTIFICATION_THREAD_COMMANDS_H
 #define NOTIFICATION_THREAD_COMMANDS_H
 
-#include <lttng/domain.h>
-#include <lttng/lttng-error.h>
-#include <urcu/rculfhash.h>
-#include "notification-thread.hpp"
-#include "notification-thread-internal.hpp"
 #include "notification-thread-events.hpp"
+#include "notification-thread-internal.hpp"
+#include "notification-thread.hpp"
+
 #include <common/waiter.hpp>
+
+#include <lttng/domain.h>
+#include <lttng/lttng-error.h>
+
+#include <vendor/optional.hpp>
+
 #include <stdbool.h>
+#include <urcu/rculfhash.h>
 
 struct notification_thread_data;
 struct lttng_trigger;
@@ -38,9 +43,9 @@ enum notification_thread_command_type {
 };
 
 struct notification_thread_command {
-       struct cds_list_head cmd_list_node;
+       struct cds_list_head cmd_list_node = {};
 
-       enum notification_thread_command_type type;
+       notification_thread_command_type type = NOTIFICATION_COMMAND_TYPE_QUIT;
        union {
                /* Register trigger. */
                struct {
@@ -105,7 +110,7 @@ struct notification_thread_command {
                        const struct lttng_trigger *trigger;
                } get_trigger;
 
-       } parameters;
+       } parameters = {};
 
        union {
                struct {
@@ -114,54 +119,56 @@ struct notification_thread_command {
                struct {
                        struct lttng_trigger *trigger;
                } get_trigger;
-       } reply;
-       /* lttng_waiter on which to wait for command reply (optional). */
-       struct lttng_waiter reply_waiter;
-       enum lttng_error_code reply_code;
-       bool is_async;
-};
-
-enum lttng_error_code notification_thread_command_register_trigger(
-               struct notification_thread_handle *handle,
-               struct lttng_trigger *trigger,
-               bool is_anonymous_trigger);
-
-enum lttng_error_code notification_thread_command_unregister_trigger(
-               struct notification_thread_handle *handle,
-               const struct lttng_trigger *trigger);
+       } reply = {};
 
-enum lttng_error_code notification_thread_command_add_session(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               const char *session_name,
-               uid_t session_uid,
-               gid_t session_gid);
-
-enum lttng_error_code notification_thread_command_remove_session(
-               struct notification_thread_handle *handle,
-               uint64_t session_id);
+       /* Used to wake origin thread for synchroneous commands. */
+       nonstd::optional<lttng::synchro::waker> command_completed_waker = nonstd::nullopt;
+       lttng_error_code reply_code = LTTNG_ERR_UNK;
+       bool is_async = false;
+};
 
-enum lttng_error_code notification_thread_command_add_channel(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               char *channel_name, uint64_t key,
-               enum lttng_domain_type domain, uint64_t capacity);
+enum lttng_error_code
+notification_thread_command_register_trigger(struct notification_thread_handle *handle,
+                                            struct lttng_trigger *trigger,
+                                            bool is_anonymous_trigger);
+
+enum lttng_error_code
+notification_thread_command_unregister_trigger(struct notification_thread_handle *handle,
+                                              const struct lttng_trigger *trigger);
+
+enum lttng_error_code
+notification_thread_command_add_session(struct notification_thread_handle *handle,
+                                       uint64_t session_id,
+                                       const char *session_name,
+                                       uid_t session_uid,
+                                       gid_t session_gid);
+
+enum lttng_error_code
+notification_thread_command_remove_session(struct notification_thread_handle *handle,
+                                          uint64_t session_id);
+
+enum lttng_error_code
+notification_thread_command_add_channel(struct notification_thread_handle *handle,
+                                       uint64_t session_id,
+                                       char *channel_name,
+                                       uint64_t key,
+                                       enum lttng_domain_type domain,
+                                       uint64_t capacity);
 
 enum lttng_error_code notification_thread_command_remove_channel(
-               struct notification_thread_handle *handle,
-               uint64_t key, enum lttng_domain_type domain);
+       struct notification_thread_handle *handle, uint64_t key, enum lttng_domain_type domain);
 
-enum lttng_error_code notification_thread_command_session_rotation_ongoing(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               uint64_t trace_archive_chunk_id);
+enum lttng_error_code
+notification_thread_command_session_rotation_ongoing(struct notification_thread_handle *handle,
+                                                    uint64_t session_id,
+                                                    uint64_t trace_archive_chunk_id);
 
 /* Ownership of location is transferred. */
 enum lttng_error_code notification_thread_command_session_rotation_completed(
-               struct notification_thread_handle *handle,
-               uint64_t session_id,
-               uint64_t trace_archive_chunk_id,
-               struct lttng_trace_archive_location *location);
+       struct notification_thread_handle *handle,
+       uint64_t session_id,
+       uint64_t trace_archive_chunk_id,
+       struct lttng_trace_archive_location *location);
 
 /*
  * Return the set of triggers visible to a given client.
@@ -176,30 +183,29 @@ enum lttng_error_code notification_thread_command_session_rotation_completed(
  *
  * The caller has the exclusive ownership of the returned trigger set.
  */
-enum lttng_error_code notification_thread_command_list_triggers(
-               struct notification_thread_handle *handle,
-               uid_t client_uid,
-               struct lttng_triggers **triggers);
+enum lttng_error_code
+notification_thread_command_list_triggers(struct notification_thread_handle *handle,
+                                         uid_t client_uid,
+                                         struct lttng_triggers **triggers);
 
 /*
  * The ownership of trigger_event_application_pipe is _not_ transferred to
  * the notification thread.
  */
-enum lttng_error_code notification_thread_command_add_tracer_event_source(
-               struct notification_thread_handle *handle,
-               int tracer_event_source_fd,
-               enum lttng_domain_type domain);
-
-enum lttng_error_code notification_thread_command_remove_tracer_event_source(
-               struct notification_thread_handle *handle,
-               int tracer_event_source_fd);
-
-void notification_thread_command_quit(
-               struct notification_thread_handle *handle);
-
-enum lttng_error_code notification_thread_command_get_trigger(
-               struct notification_thread_handle *handle,
-               const struct lttng_trigger *trigger,
-               struct lttng_trigger **real_trigger);
+enum lttng_error_code
+notification_thread_command_add_tracer_event_source(struct notification_thread_handle *handle,
+                                                   int tracer_event_source_fd,
+                                                   enum lttng_domain_type domain);
+
+enum lttng_error_code
+notification_thread_command_remove_tracer_event_source(struct notification_thread_handle *handle,
+                                                      int tracer_event_source_fd);
+
+void notification_thread_command_quit(struct notification_thread_handle *handle);
+
+enum lttng_error_code
+notification_thread_command_get_trigger(struct notification_thread_handle *handle,
+                                       const struct lttng_trigger *trigger,
+                                       struct lttng_trigger **real_trigger);
 
 #endif /* NOTIFICATION_THREAD_COMMANDS_H */
index 6fb691be59f91d54e3c9107731ee9ee560670e30..8065cd7323b20f8c9ca8bfa137d88ff44d9c5810 100644 (file)
@@ -8,47 +8,48 @@
 #include "lttng/action/action.h"
 #include "lttng/trigger/trigger-internal.hpp"
 #define _LGPL_SOURCE
-#include <urcu.h>
-#include <urcu/rculfhash.h>
+#include "condition-internal.hpp"
+#include "event-notifier-error-accounting.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "notification-thread-commands.hpp"
+#include "notification-thread-events.hpp"
+#include "notification-thread.hpp"
 
 #include <common/defaults.hpp>
+#include <common/dynamic-buffer.hpp>
 #include <common/error.hpp>
 #include <common/futex.hpp>
-#include <common/unix.hpp>
-#include <common/dynamic-buffer.hpp>
 #include <common/hashtable/utils.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/macros.hpp>
-#include <lttng/condition/condition.h>
+#include <common/pthread-lock.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/unix.hpp>
+#include <common/urcu.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/list-internal.hpp>
-#include <lttng/domain-internal.hpp>
-#include <lttng/notification/notification-internal.hpp>
-#include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/buffer-usage-internal.hpp>
+#include <lttng/condition/condition-internal.hpp>
+#include <lttng/condition/condition.h>
+#include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/condition/session-consumed-size-internal.hpp>
 #include <lttng/condition/session-rotation-internal.hpp>
-#include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/domain-internal.hpp>
-#include <lttng/notification/channel-internal.hpp>
-#include <lttng/trigger/trigger-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/location-internal.hpp>
+#include <lttng/notification/channel-internal.hpp>
+#include <lttng/notification/notification-internal.hpp>
+#include <lttng/trigger/trigger-internal.hpp>
 
+#include <fcntl.h>
+#include <inttypes.h>
 #include <time.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <fcntl.h>
-
-#include "condition-internal.hpp"
-#include "event-notifier-error-accounting.hpp"
-#include "notification-thread.hpp"
-#include "notification-thread-events.hpp"
-#include "notification-thread-commands.hpp"
-#include "lttng-sessiond.hpp"
-#include "kernel.hpp"
+#include <urcu.h>
+#include <urcu/rculfhash.h>
 
-#define CLIENT_POLL_EVENTS_IN (LPOLLIN | LPOLLERR | LPOLLHUP | LPOLLRDHUP)
+#define CLIENT_POLL_EVENTS_IN    (LPOLLIN | LPOLLRDHUP)
 #define CLIENT_POLL_EVENTS_IN_OUT (CLIENT_POLL_EVENTS_IN | LPOLLOUT)
 
 /* The tracers currently limit the capture size to PIPE_BUF (4kb on linux). */
@@ -141,167 +142,138 @@ struct channel_state_sample {
 
 static unsigned long hash_channel_key(struct channel_key *key);
 static int evaluate_buffer_condition(const struct lttng_condition *condition,
-               struct lttng_evaluation **evaluation,
-               const struct notification_thread_state *state,
-               const struct channel_state_sample *previous_sample,
-               const struct channel_state_sample *latest_sample,
-               struct channel_info *channel_info);
-static
-int send_evaluation_to_clients(const struct lttng_trigger *trigger,
-               const struct lttng_evaluation *evaluation,
-               struct notification_client_list *client_list,
-               struct notification_thread_state *state,
-               uid_t channel_uid, gid_t channel_gid);
-
+                                    struct lttng_evaluation **evaluation,
+                                    const struct notification_thread_state *state,
+                                    const struct channel_state_sample *previous_sample,
+                                    const struct channel_state_sample *latest_sample,
+                                    struct channel_info *channel_info);
+static int send_evaluation_to_clients(const struct lttng_trigger *trigger,
+                                     const struct lttng_evaluation *evaluation,
+                                     struct notification_client_list *client_list,
+                                     struct notification_thread_state *state,
+                                     uid_t channel_uid,
+                                     gid_t channel_gid);
 
 /* session_info API */
-static
-void session_info_destroy(void *_data);
-static
-void session_info_get(struct session_info *session_info);
-static
-void session_info_put(struct session_info *session_info);
-static
-struct session_info *session_info_create(uint64_t id,
-               const char *name,
-               uid_t uid,
-               gid_t gid,
-               struct lttng_session_trigger_list *trigger_list,
-               struct cds_lfht *sessions_ht);
-static void session_info_add_channel(
-               struct session_info *session_info, struct channel_info *channel_info);
-static
-void session_info_remove_channel(struct session_info *session_info,
-               struct channel_info *channel_info);
+static void session_info_destroy(void *_data);
+static void session_info_get(struct session_info *session_info);
+static void session_info_put(struct session_info *session_info);
+static struct session_info *session_info_create(uint64_t id,
+                                               const char *name,
+                                               uid_t uid,
+                                               gid_t gid,
+                                               struct lttng_session_trigger_list *trigger_list,
+                                               struct cds_lfht *sessions_ht);
+static void session_info_add_channel(struct session_info *session_info,
+                                    struct channel_info *channel_info);
+static void session_info_remove_channel(struct session_info *session_info,
+                                       struct channel_info *channel_info);
 
 /* lttng_session_trigger_list API */
-static
-struct lttng_session_trigger_list *lttng_session_trigger_list_create(
-               const char *session_name,
-               struct cds_lfht *session_triggers_ht);
-static
-struct lttng_session_trigger_list *lttng_session_trigger_list_build(
-               const struct notification_thread_state *state,
-               const char *session_name);
-static
-void lttng_session_trigger_list_destroy(
-               struct lttng_session_trigger_list *list);
-static
-int lttng_session_trigger_list_add(struct lttng_session_trigger_list *list,
-               struct lttng_trigger *trigger);
-
-static
-int client_handle_transmission_status(
-               struct notification_client *client,
-               enum client_transmission_status transmission_status,
-               struct notification_thread_state *state);
-
-static
-int handle_one_event_notifier_notification(
-               struct notification_thread_state *state,
-               int pipe, enum lttng_domain_type domain);
-
-static
-void free_lttng_trigger_ht_element_rcu(struct rcu_head *node);
-
-static
-int match_client_socket(struct cds_lfht_node *node, const void *key)
+static struct lttng_session_trigger_list *
+lttng_session_trigger_list_create(const char *session_name, struct cds_lfht *session_triggers_ht);
+static struct lttng_session_trigger_list *
+lttng_session_trigger_list_build(const struct notification_thread_state *state,
+                                const char *session_name);
+static void lttng_session_trigger_list_destroy(struct lttng_session_trigger_list *list);
+static int lttng_session_trigger_list_add(struct lttng_session_trigger_list *list,
+                                         struct lttng_trigger *trigger);
+
+static int client_handle_transmission_status(struct notification_client *client,
+                                            enum client_transmission_status transmission_status,
+                                            struct notification_thread_state *state);
+
+static int handle_one_event_notifier_notification(struct notification_thread_state *state,
+                                                 int pipe,
+                                                 enum lttng_domain_type domain);
+
+static void free_lttng_trigger_ht_element_rcu(struct rcu_head *node);
+
+static int match_client_socket(struct cds_lfht_node *node, const void *key)
 {
        /* This double-cast is intended to supress pointer-to-cast warning. */
        const int socket = (int) (intptr_t) key;
-       const struct notification_client *client = caa_container_of(node,
-                       struct notification_client, client_socket_ht_node);
+       const struct notification_client *client =
+               caa_container_of(node, struct notification_client, client_socket_ht_node);
 
        return client->socket == socket;
 }
 
-static
-int match_client_id(struct cds_lfht_node *node, const void *key)
+static int match_client_id(struct cds_lfht_node *node, const void *key)
 {
        /* This double-cast is intended to supress pointer-to-cast warning. */
        const notification_client_id id = *((notification_client_id *) key);
-       const struct notification_client *client = lttng::utils::container_of(
-                       node, &notification_client::client_id_ht_node);
+       const struct notification_client *client =
+               lttng::utils::container_of(node, &notification_client::client_id_ht_node);
 
        return client->id == id;
 }
 
-static
-int match_channel_trigger_list(struct cds_lfht_node *node, const void *key)
+static int match_channel_trigger_list(struct cds_lfht_node *node, const void *key)
 {
        struct channel_key *channel_key = (struct channel_key *) key;
        struct lttng_channel_trigger_list *trigger_list;
 
-       trigger_list = caa_container_of(node, struct lttng_channel_trigger_list,
-                       channel_triggers_ht_node);
+       trigger_list =
+               caa_container_of(node, struct lttng_channel_trigger_list, channel_triggers_ht_node);
 
        return !!((channel_key->key == trigger_list->channel_key.key) &&
-                       (channel_key->domain == trigger_list->channel_key.domain));
+                 (channel_key->domain == trigger_list->channel_key.domain));
 }
 
-static
-int match_session_trigger_list(struct cds_lfht_node *node, const void *key)
+static int match_session_trigger_list(struct cds_lfht_node *node, const void *key)
 {
        const char *session_name = (const char *) key;
        struct lttng_session_trigger_list *trigger_list;
 
-       trigger_list = caa_container_of(node, struct lttng_session_trigger_list,
-                       session_triggers_ht_node);
+       trigger_list =
+               caa_container_of(node, struct lttng_session_trigger_list, session_triggers_ht_node);
 
        return !!(strcmp(trigger_list->session_name, session_name) == 0);
 }
 
-static
-int match_channel_state_sample(struct cds_lfht_node *node, const void *key)
+static int match_channel_state_sample(struct cds_lfht_node *node, const void *key)
 {
        struct channel_key *channel_key = (struct channel_key *) key;
        struct channel_state_sample *sample;
 
-       sample = caa_container_of(node, struct channel_state_sample,
-                       channel_state_ht_node);
+       sample = caa_container_of(node, struct channel_state_sample, channel_state_ht_node);
 
        return !!((channel_key->key == sample->key.key) &&
-                       (channel_key->domain == sample->key.domain));
+                 (channel_key->domain == sample->key.domain));
 }
 
-static
-int match_channel_info(struct cds_lfht_node *node, const void *key)
+static int match_channel_info(struct cds_lfht_node *node, const void *key)
 {
        struct channel_key *channel_key = (struct channel_key *) key;
        struct channel_info *channel_info;
 
-       channel_info = caa_container_of(node, struct channel_info,
-                       channels_ht_node);
+       channel_info = caa_container_of(node, struct channel_info, channels_ht_node);
 
        return !!((channel_key->key == channel_info->key.key) &&
-                       (channel_key->domain == channel_info->key.domain));
+                 (channel_key->domain == channel_info->key.domain));
 }
 
-static
-int match_trigger(struct cds_lfht_node *node, const void *key)
+static int match_trigger(struct cds_lfht_node *node, const void *key)
 {
        struct lttng_trigger *trigger_key = (struct lttng_trigger *) key;
        struct lttng_trigger_ht_element *trigger_ht_element;
 
-       trigger_ht_element = caa_container_of(node, struct lttng_trigger_ht_element,
-                       node);
+       trigger_ht_element = caa_container_of(node, struct lttng_trigger_ht_element, node);
 
        return !!lttng_trigger_is_equal(trigger_key, trigger_ht_element->trigger);
 }
 
-static
-int match_trigger_token(struct cds_lfht_node *node, const void *key)
+static int match_trigger_token(struct cds_lfht_node *node, const void *key)
 {
        const uint64_t *_key = (uint64_t *) key;
        struct notification_trigger_tokens_ht_element *element;
 
-       element = caa_container_of(node,
-                       struct notification_trigger_tokens_ht_element, node);
+       element = caa_container_of(node, struct notification_trigger_tokens_ht_element, node);
        return *_key == element->token;
 }
 
-static
-int match_client_list_condition(struct cds_lfht_node *node, const void *key)
+static int match_client_list_condition(struct cds_lfht_node *node, const void *key)
 {
        struct lttng_condition *condition_key = (struct lttng_condition *) key;
        struct notification_client_list *client_list;
@@ -309,73 +281,64 @@ int match_client_list_condition(struct cds_lfht_node *node, const void *key)
 
        LTTNG_ASSERT(condition_key);
 
-       client_list = caa_container_of(node, struct notification_client_list,
-                       notification_trigger_clients_ht_node);
+       client_list = caa_container_of(
+               node, struct notification_client_list, notification_trigger_clients_ht_node);
        condition = client_list->condition;
 
        return !!lttng_condition_is_equal(condition_key, condition);
 }
 
-static
-int match_session_info(struct cds_lfht_node *node, const void *key)
+static int match_session_info(struct cds_lfht_node *node, const void *key)
 {
        const auto session_id = *((uint64_t *) key);
-       const auto *session_info = lttng::utils::container_of(
-               node, &session_info::sessions_ht_node);
+       const auto *session_info =
+               lttng::utils::container_of(node, &session_info::sessions_ht_node);
 
        return session_id == session_info->id;
 }
 
-static
-unsigned long hash_session_info_id(uint64_t id)
+static unsigned long hash_session_info_id(uint64_t id)
 {
        return hash_key_u64(&id, lttng_ht_seed);
 }
 
-static
-unsigned long hash_session_info(const struct session_info *session_info)
+static unsigned long hash_session_info(const struct session_info *session_info)
 {
        return hash_session_info_id(session_info->id);
 }
 
-static
-struct session_info *get_session_info_by_id(
-               const struct notification_thread_state *state, uint64_t id)
+static struct session_info *get_session_info_by_id(const struct notification_thread_state *state,
+                                                  uint64_t id)
 {
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
        lttng::urcu::read_lock_guard read_lock_guard;
 
-       cds_lfht_lookup(state->sessions_ht,
-                       hash_session_info_id(id),
-                       match_session_info,
-                       &id,
-                       &iter);
+       cds_lfht_lookup(
+               state->sessions_ht, hash_session_info_id(id), match_session_info, &id, &iter);
        node = cds_lfht_iter_get_node(&iter);
 
        if (node) {
-               auto session_info = lttng::utils::container_of(node, &session_info::sessions_ht_node);
+               auto session_info =
+                       lttng::utils::container_of(node, &session_info::sessions_ht_node);
 
                session_info_get(session_info);
                return session_info;
        }
 
-       return NULL;
+       return nullptr;
 }
 
-static
-struct session_info *get_session_info_by_name(
-               const struct notification_thread_state *state, const char *name)
+static struct session_info *get_session_info_by_name(const struct notification_thread_state *state,
+                                                    const char *name)
 {
        uint64_t session_id;
        const auto found = sample_session_id_by_name(name, &session_id);
 
-       return found ? get_session_info_by_id(state, session_id) : NULL;
+       return found ? get_session_info_by_id(state, session_id) : nullptr;
 }
 
-static
-const char *notification_command_type_str(
-               enum notification_thread_command_type type)
+static const char *notification_command_type_str(enum notification_thread_command_type type)
 {
        switch (type) {
        case NOTIFICATION_COMMAND_TYPE_REGISTER_TRIGGER:
@@ -415,9 +378,7 @@ const char *notification_command_type_str(
  * Match trigger based on name and credentials only.
  * Name duplication is NOT allowed for the same uid.
  */
-static
-int match_trigger_by_name_uid(struct cds_lfht_node *node,
-               const void *key)
+static int match_trigger_by_name_uid(struct cds_lfht_node *node, const void *key)
 {
        bool match = false;
        const char *element_trigger_name;
@@ -425,20 +386,15 @@ int match_trigger_by_name_uid(struct cds_lfht_node *node,
        enum lttng_trigger_status status;
        const struct lttng_credentials *key_creds;
        const struct lttng_credentials *node_creds;
-       const struct lttng_trigger *trigger_key =
-                       (const struct lttng_trigger *) key;
+       const struct lttng_trigger *trigger_key = (const struct lttng_trigger *) key;
        const struct lttng_trigger_ht_element *trigger_ht_element =
-                       caa_container_of(node,
-                               struct lttng_trigger_ht_element,
-                               node_by_name_uid);
+               caa_container_of(node, struct lttng_trigger_ht_element, node_by_name_uid);
 
-       status = lttng_trigger_get_name(trigger_ht_element->trigger,
-                       &element_trigger_name);
-       element_trigger_name = status == LTTNG_TRIGGER_STATUS_OK ?
-                       element_trigger_name : NULL;
+       status = lttng_trigger_get_name(trigger_ht_element->trigger, &element_trigger_name);
+       element_trigger_name = status == LTTNG_TRIGGER_STATUS_OK ? element_trigger_name : nullptr;
 
        status = lttng_trigger_get_name(trigger_key, &key_name);
-       key_name = status == LTTNG_TRIGGER_STATUS_OK ? key_name : NULL;
+       key_name = status == LTTNG_TRIGGER_STATUS_OK ? key_name : nullptr;
 
        /*
         * Compare the names.
@@ -467,8 +423,7 @@ end:
 /*
  * Hash trigger based on name and credentials only.
  */
-static
-unsigned long hash_trigger_by_name_uid(const struct lttng_trigger *trigger)
+static unsigned long hash_trigger_by_name_uid(const struct lttng_trigger *trigger)
 {
        unsigned long hash = 0;
        const struct lttng_credentials *trigger_creds;
@@ -482,29 +437,26 @@ unsigned long hash_trigger_by_name_uid(const struct lttng_trigger *trigger)
 
        trigger_creds = lttng_trigger_get_credentials(trigger);
        hash ^= hash_key_ulong((void *) (unsigned long) LTTNG_OPTIONAL_GET(trigger_creds->uid),
-                       lttng_ht_seed);
+                              lttng_ht_seed);
 
        return hash;
 }
 
-static
-unsigned long hash_channel_key(struct channel_key *key)
+static unsigned long hash_channel_key(struct channel_key *key)
 {
        unsigned long key_hash = hash_key_u64(&key->key, lttng_ht_seed);
-       unsigned long domain_hash = hash_key_ulong(
-               (void *) (unsigned long) key->domain, lttng_ht_seed);
+       unsigned long domain_hash =
+               hash_key_ulong((void *) (unsigned long) key->domain, lttng_ht_seed);
 
        return key_hash ^ domain_hash;
 }
 
-static
-unsigned long hash_client_socket(int socket)
+static unsigned long hash_client_socket(int socket)
 {
        return hash_key_ulong((void *) (unsigned long) socket, lttng_ht_seed);
 }
 
-static
-unsigned long hash_client_id(notification_client_id id)
+static unsigned long hash_client_id(notification_client_id id)
 {
        return hash_key_u64(&id, lttng_ht_seed);
 }
@@ -517,9 +469,7 @@ unsigned long hash_client_id(notification_client_id id)
  * For instance, a condition bound to a channel will be evaluated everytime
  * the channel's state is changed by a channel monitoring sample.
  */
-static
-enum lttng_object_type get_condition_binding_object(
-               const struct lttng_condition *condition)
+static enum lttng_object_type get_condition_binding_object(const struct lttng_condition *condition)
 {
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
@@ -536,22 +486,19 @@ enum lttng_object_type get_condition_binding_object(
        }
 }
 
-static
-void free_channel_info_rcu(struct rcu_head *node)
+static void free_channel_info_rcu(struct rcu_head *node)
 {
        free(lttng::utils::container_of(node, &channel_info::rcu_node));
 }
 
-static
-void channel_info_destroy(struct channel_info *channel_info)
+static void channel_info_destroy(struct channel_info *channel_info)
 {
        if (!channel_info) {
                return;
        }
 
        if (channel_info->session_info) {
-               session_info_remove_channel(channel_info->session_info,
-                               channel_info);
+               session_info_remove_channel(channel_info->session_info, channel_info);
                session_info_put(channel_info->session_info);
        }
        if (channel_info->name) {
@@ -560,39 +507,34 @@ void channel_info_destroy(struct channel_info *channel_info)
        call_rcu(&channel_info->rcu_node, free_channel_info_rcu);
 }
 
-static
-void free_session_info_rcu(struct rcu_head *node)
+static void free_session_info_rcu(struct rcu_head *node)
 {
        free(lttng::utils::container_of(node, &session_info::rcu_node));
 }
 
 /* Don't call directly, use the ref-counting mechanism. */
-static
-void session_info_destroy(void *_data)
+static void session_info_destroy(void *_data)
 {
        struct session_info *session_info = (struct session_info *) _data;
        int ret;
 
        LTTNG_ASSERT(session_info);
        if (session_info->channel_infos_ht) {
-               ret = cds_lfht_destroy(session_info->channel_infos_ht, NULL);
+               ret = cds_lfht_destroy(session_info->channel_infos_ht, nullptr);
                if (ret) {
                        ERR("Failed to destroy channel information hash table");
                }
        }
        lttng_session_trigger_list_destroy(session_info->trigger_list);
 
-       rcu_read_lock();
-       cds_lfht_del(session_info->sessions_ht,
-                       &session_info->sessions_ht_node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_del(session_info->sessions_ht, &session_info->sessions_ht_node);
        free(session_info->name);
        lttng_trace_archive_location_put(session_info->last_state_sample.rotation.location);
        call_rcu(&session_info->rcu_node, free_session_info_rcu);
 }
 
-static
-void session_info_get(struct session_info *session_info)
+static void session_info_get(struct session_info *session_info)
 {
        if (!session_info) {
                return;
@@ -600,8 +542,7 @@ void session_info_get(struct session_info *session_info)
        lttng_ref_get(&session_info->ref);
 }
 
-static
-void session_info_put(struct session_info *session_info)
+static void session_info_put(struct session_info *session_info)
 {
        if (!session_info) {
                return;
@@ -609,13 +550,12 @@ void session_info_put(struct session_info *session_info)
        lttng_ref_put(&session_info->ref);
 }
 
-static
-struct session_info *session_info_create(uint64_t id,
-               const char *name,
-               uid_t uid,
-               gid_t gid,
-               struct lttng_session_trigger_list *trigger_list,
-               struct cds_lfht *sessions_ht)
+static struct session_info *session_info_create(uint64_t id,
+                                               const char *name,
+                                               uid_t uid,
+                                               gid_t gid,
+                                               struct lttng_session_trigger_list *trigger_list,
+                                               struct cds_lfht *sessions_ht)
 {
        struct session_info *session_info;
 
@@ -628,8 +568,8 @@ struct session_info *session_info_create(uint64_t id,
 
        lttng_ref_init(&session_info->ref, session_info_destroy);
 
-       session_info->channel_infos_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       session_info->channel_infos_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!session_info->channel_infos_ht) {
                goto error;
        }
@@ -649,34 +589,29 @@ end:
        return session_info;
 error:
        session_info_put(session_info);
-       return NULL;
+       return nullptr;
 }
 
-static
-void session_info_add_channel(struct session_info *session_info,
-               struct channel_info *channel_info)
+static void session_info_add_channel(struct session_info *session_info,
+                                    struct channel_info *channel_info)
 {
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_add(session_info->channel_infos_ht,
-                       hash_channel_key(&channel_info->key),
-                       &channel_info->session_info_channels_ht_node);
-       rcu_read_unlock();
+                    hash_channel_key(&channel_info->key),
+                    &channel_info->session_info_channels_ht_node);
 }
 
-static
-void session_info_remove_channel(struct session_info *session_info,
-               struct channel_info *channel_info)
+static void session_info_remove_channel(struct session_info *session_info,
+                                       struct channel_info *channel_info)
 {
-       rcu_read_lock();
-       cds_lfht_del(session_info->channel_infos_ht,
-                       &channel_info->session_info_channels_ht_node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_del(session_info->channel_infos_ht, &channel_info->session_info_channels_ht_node);
 }
 
-static
-struct channel_info *channel_info_create(const char *channel_name,
-               struct channel_key *channel_key, uint64_t channel_capacity,
-               struct session_info *session_info)
+static struct channel_info *channel_info_create(const char *channel_name,
+                                               struct channel_key *channel_key,
+                                               uint64_t channel_capacity,
+                                               struct session_info *session_info)
 {
        struct channel_info *channel_info = zmalloc<struct channel_info>();
 
@@ -706,7 +641,7 @@ end:
        return channel_info;
 error:
        channel_info_destroy(channel_info);
-       return NULL;
+       return nullptr;
 }
 
 bool notification_client_list_get(struct notification_client_list *list)
@@ -714,32 +649,27 @@ bool notification_client_list_get(struct notification_client_list *list)
        return urcu_ref_get_unless_zero(&list->ref);
 }
 
-static
-void free_notification_client_list_rcu(struct rcu_head *node)
+static void free_notification_client_list_rcu(struct rcu_head *node)
 {
-       free(caa_container_of(node, struct notification_client_list,
-                       rcu_node));
+       free(caa_container_of(node, struct notification_client_list, rcu_node));
 }
 
-static
-void notification_client_list_release(struct urcu_ref *list_ref)
+static void notification_client_list_release(struct urcu_ref *list_ref)
 {
        struct notification_client_list *list =
-                       lttng::utils::container_of(list_ref, &notification_client_list::ref);
+               lttng::utils::container_of(list_ref, &notification_client_list::ref);
        struct notification_client_list_element *client_list_element, *tmp;
 
        lttng_condition_put(list->condition);
 
        if (list->notification_trigger_clients_ht) {
-               rcu_read_lock();
+               lttng::urcu::read_lock_guard read_lock;
 
                cds_lfht_del(list->notification_trigger_clients_ht,
-                               &list->notification_trigger_clients_ht_node);
-               rcu_read_unlock();
-               list->notification_trigger_clients_ht = NULL;
+                            &list->notification_trigger_clients_ht_node);
+               list->notification_trigger_clients_ht = nullptr;
        }
-       cds_list_for_each_entry_safe(client_list_element, tmp,
-                                    &list->clients_list, node) {
+       cds_list_for_each_entry_safe (client_list_element, tmp, &list->clients_list, node) {
                free(client_list_element);
        }
 
@@ -749,18 +679,14 @@ void notification_client_list_release(struct urcu_ref *list_ref)
        call_rcu(&list->rcu_node, free_notification_client_list_rcu);
 }
 
-static
-bool condition_applies_to_client(const struct lttng_condition *condition,
-               struct notification_client *client)
+static bool condition_applies_to_client(const struct lttng_condition *condition,
+                                       struct notification_client *client)
 {
        bool applies = false;
        struct lttng_condition_list_element *condition_list_element;
 
-       cds_list_for_each_entry(condition_list_element, &client->condition_list,
-                       node) {
-               applies = lttng_condition_is_equal(
-                               condition_list_element->condition,
-                               condition);
+       cds_list_for_each_entry (condition_list_element, &client->condition_list, node) {
+               applies = lttng_condition_is_equal(condition_list_element->condition, condition);
                if (applies) {
                        break;
                }
@@ -769,10 +695,9 @@ bool condition_applies_to_client(const struct lttng_condition *condition,
        return applies;
 }
 
-static
-struct notification_client_list *notification_client_list_create(
-               struct notification_thread_state *state,
-               const struct lttng_condition *condition)
+static struct notification_client_list *
+notification_client_list_create(struct notification_thread_state *state,
+                               const struct lttng_condition *condition)
 {
        struct notification_client *client;
        struct cds_lfht_iter iter;
@@ -784,7 +709,7 @@ struct notification_client_list *notification_client_list_create(
                goto end;
        }
 
-       pthread_mutex_init(&client_list->lock, NULL);
+       pthread_mutex_init(&client_list->lock, nullptr);
        /*
         * The trigger that owns the condition has the first reference to this
         * client list.
@@ -801,43 +726,48 @@ struct notification_client_list *notification_client_list_create(
         */
        client_list->condition = lttng_condition_copy(condition);
 
-       /* Build a list of clients to which this new condition applies. */
-       cds_lfht_for_each_entry (state->client_socket_ht, &iter, client,
-                       client_socket_ht_node) {
-               struct notification_client_list_element *client_list_element;
+       {
+               /* Build a list of clients to which this new condition applies. */
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (!condition_applies_to_client(condition, client)) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (
+                       state->client_socket_ht, &iter, client, client_socket_ht_node) {
+                       struct notification_client_list_element *client_list_element;
 
-               client_list_element = zmalloc<notification_client_list_element>();
-               if (!client_list_element) {
-                       goto error_put_client_list;
-               }
+                       if (!condition_applies_to_client(condition, client)) {
+                               continue;
+                       }
 
-               CDS_INIT_LIST_HEAD(&client_list_element->node);
-               client_list_element->client = client;
-               cds_list_add(&client_list_element->node, &client_list->clients_list);
+                       client_list_element = zmalloc<notification_client_list_element>();
+                       if (!client_list_element) {
+                               goto error_put_client_list;
+                       }
+
+                       CDS_INIT_LIST_HEAD(&client_list_element->node);
+                       client_list_element->client = client;
+                       cds_list_add(&client_list_element->node, &client_list->clients_list);
+               }
        }
 
-       client_list->notification_trigger_clients_ht =
-                       state->notification_trigger_clients_ht;
+       client_list->notification_trigger_clients_ht = state->notification_trigger_clients_ht;
 
-       rcu_read_lock();
        /*
         * Add the client list to the global list of client list.
         */
-       cds_lfht_add_unique(state->notification_trigger_clients_ht,
-                       lttng_condition_hash(client_list->condition),
-                       match_client_list_condition,
-                       client_list->condition,
-                       &client_list->notification_trigger_clients_ht_node);
-       rcu_read_unlock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_add_unique(state->notification_trigger_clients_ht,
+                                   lttng_condition_hash(client_list->condition),
+                                   match_client_list_condition,
+                                   client_list->condition,
+                                   &client_list->notification_trigger_clients_ht_node);
+       }
        goto end;
 
 error_put_client_list:
        notification_client_list_put(client_list);
-       client_list = NULL;
+       client_list = nullptr;
 
 end:
        return client_list;
@@ -852,16 +782,15 @@ void notification_client_list_put(struct notification_client_list *list)
 }
 
 /* Provides a reference to the returned list. */
-static
-struct notification_client_list *get_client_list_from_condition(
-       struct notification_thread_state *state,
-       const struct lttng_condition *condition)
+static struct notification_client_list *
+get_client_list_from_condition(struct notification_thread_state *state,
+                              const struct lttng_condition *condition)
 {
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
-       struct notification_client_list *list = NULL;
+       struct notification_client_list *list = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(state->notification_trigger_clients_ht,
                        lttng_condition_hash(condition),
                        match_client_list_condition,
@@ -869,45 +798,41 @@ struct notification_client_list *get_client_list_from_condition(
                        &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (node) {
-               list = lttng::utils::container_of(node,
-                               &notification_client_list::notification_trigger_clients_ht_node);
-               list = notification_client_list_get(list) ? list : NULL;
+               list = lttng::utils::container_of(
+                       node, &notification_client_list::notification_trigger_clients_ht_node);
+               list = notification_client_list_get(list) ? list : nullptr;
        }
 
-       rcu_read_unlock();
        return list;
 }
 
-static
-int evaluate_channel_condition_for_client(
-               const struct lttng_condition *condition,
-               struct notification_thread_state *state,
-               struct lttng_evaluation **evaluation,
-               uid_t *session_uid, gid_t *session_gid)
+static int evaluate_channel_condition_for_client(const struct lttng_condition *condition,
+                                                struct notification_thread_state *state,
+                                                struct lttng_evaluation **evaluation,
+                                                uid_t *session_uid,
+                                                gid_t *session_gid)
 {
        int ret;
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
-       struct channel_info *channel_info = NULL;
-       struct channel_key *channel_key = NULL;
-       struct channel_state_sample *last_sample = NULL;
-       struct lttng_channel_trigger_list *channel_trigger_list = NULL;
+       struct channel_info *channel_info = nullptr;
+       struct channel_key *channel_key = nullptr;
+       struct channel_state_sample *last_sample = nullptr;
+       struct lttng_channel_trigger_list *channel_trigger_list = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Find the channel associated with the condition. */
-       cds_lfht_for_each_entry(state->channel_triggers_ht, &iter,
-                       channel_trigger_list, channel_triggers_ht_node) {
+       cds_lfht_for_each_entry (
+               state->channel_triggers_ht, &iter, channel_trigger_list, channel_triggers_ht_node) {
                struct lttng_trigger_list_element *element;
 
-               cds_list_for_each_entry(element, &channel_trigger_list->list, node) {
+               cds_list_for_each_entry (element, &channel_trigger_list->list, node) {
                        const struct lttng_condition *current_condition =
-                                       lttng_trigger_get_const_condition(
-                                               element->trigger);
+                               lttng_trigger_get_const_condition(element->trigger);
 
                        LTTNG_ASSERT(current_condition);
-                       if (!lttng_condition_is_equal(condition,
-                                       current_condition)) {
+                       if (!lttng_condition_is_equal(condition, current_condition)) {
                                continue;
                        }
 
@@ -921,7 +846,7 @@ int evaluate_channel_condition_for_client(
                }
        }
 
-       if (!channel_key){
+       if (!channel_key) {
                /* No channel found; normal exit. */
                DBG("No known channel associated with newly subscribed-to condition");
                ret = 0;
@@ -936,8 +861,7 @@ int evaluate_channel_condition_for_client(
                        &iter);
        node = cds_lfht_iter_get_node(&iter);
        LTTNG_ASSERT(node);
-       channel_info = caa_container_of(node, struct channel_info,
-                       channels_ht_node);
+       channel_info = caa_container_of(node, struct channel_info, channels_ht_node);
 
        /* Retrieve the channel's last sample, if it exists. */
        cds_lfht_lookup(state->channel_state_ht,
@@ -947,9 +871,8 @@ int evaluate_channel_condition_for_client(
                        &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (node) {
-               last_sample = caa_container_of(node,
-                               struct channel_state_sample,
-                               channel_state_ht_node);
+               last_sample =
+                       caa_container_of(node, struct channel_state_sample, channel_state_ht_node);
        } else {
                /* Nothing to evaluate, no sample was ever taken. Normal exit */
                DBG("No channel sample associated with newly subscribed-to condition");
@@ -957,9 +880,8 @@ int evaluate_channel_condition_for_client(
                goto end;
        }
 
-       ret = evaluate_buffer_condition(condition, evaluation, state,
-                       NULL, last_sample,
-                       channel_info);
+       ret = evaluate_buffer_condition(
+               condition, evaluation, state, nullptr, last_sample, channel_info);
        if (ret) {
                WARN("Fatal error occurred while evaluating a newly subscribed-to condition");
                goto end;
@@ -968,30 +890,27 @@ int evaluate_channel_condition_for_client(
        *session_uid = channel_info->session_info->uid;
        *session_gid = channel_info->session_info->gid;
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-static
-const char *get_condition_session_name(const struct lttng_condition *condition)
+static const char *get_condition_session_name(const struct lttng_condition *condition)
 {
-       const char *session_name = NULL;
+       const char *session_name = nullptr;
        enum lttng_condition_status status;
 
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
-               status = lttng_condition_buffer_usage_get_session_name(
-                               condition, &session_name);
+               status = lttng_condition_buffer_usage_get_session_name(condition, &session_name);
                break;
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
-               status = lttng_condition_session_consumed_size_get_session_name(
-                               condition, &session_name);
+               status = lttng_condition_session_consumed_size_get_session_name(condition,
+                                                                               &session_name);
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED:
-               status = lttng_condition_session_rotation_get_session_name(
-                               condition, &session_name);
+               status =
+                       lttng_condition_session_rotation_get_session_name(condition, &session_name);
                break;
        default:
                abort();
@@ -1004,27 +923,26 @@ end:
        return session_name;
 }
 
-static
-bool evaluate_session_rotation_ongoing_condition(const struct lttng_condition *condition
-               __attribute__((unused)),
-               const struct session_state_sample *sample)
+static bool evaluate_session_rotation_ongoing_condition(const struct lttng_condition *condition
+                                                       __attribute__((unused)),
+                                                       const struct session_state_sample *sample)
 {
        return sample->rotation.ongoing;
 }
 
-static
-bool evaluate_session_consumed_size_condition(
-               const struct lttng_condition *condition,
-               const struct session_state_sample *sample)
+static bool evaluate_session_consumed_size_condition(const struct lttng_condition *condition,
+                                                    const struct session_state_sample *sample)
 {
        uint64_t threshold;
        const struct lttng_condition_session_consumed_size *size_condition =
-                       lttng::utils::container_of(condition,
-                               &lttng_condition_session_consumed_size::parent);
+               lttng::utils::container_of(condition,
+                                          &lttng_condition_session_consumed_size::parent);
 
        threshold = size_condition->consumed_threshold_bytes.value;
-       DBG("Session consumed size condition being evaluated: threshold = %" PRIu64 ", current size = %" PRIu64,
-                       threshold, sample->consumed_data_size);
+       DBG("Session consumed size condition being evaluated: threshold = %" PRIu64
+           ", current size = %" PRIu64,
+           threshold,
+           sample->consumed_data_size);
        return sample->consumed_data_size >= threshold;
 }
 
@@ -1033,12 +951,10 @@ bool evaluate_session_consumed_size_condition(
  * state transition. A client subscribed or a trigger was registered and
  * we wish to perform an initial evaluation.
  */
-static
-int evaluate_session_condition(
-               const struct lttng_condition *condition,
-               const struct session_info *session_info,
-               const struct session_state_sample *new_state,
-               struct lttng_evaluation **evaluation)
+static int evaluate_session_condition(const struct lttng_condition *condition,
+                                     const struct session_info *session_info,
+                                     const struct session_state_sample *new_state,
+                                     struct lttng_evaluation **evaluation)
 {
        int ret;
        bool previous_result, newest_result;
@@ -1047,25 +963,25 @@ int evaluate_session_condition(
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
                if (new_state) {
                        previous_result = evaluate_session_rotation_ongoing_condition(
-                                       condition, &session_info->last_state_sample);
-                       newest_result = evaluate_session_rotation_ongoing_condition(
-                                       condition, new_state);
+                               condition, &session_info->last_state_sample);
+                       newest_result =
+                               evaluate_session_rotation_ongoing_condition(condition, new_state);
                } else {
                        previous_result = false;
                        newest_result = evaluate_session_rotation_ongoing_condition(
-                                       condition, &session_info->last_state_sample);
+                               condition, &session_info->last_state_sample);
                }
                break;
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
                if (new_state) {
                        previous_result = evaluate_session_consumed_size_condition(
-                                       condition, &session_info->last_state_sample);
-                       newest_result = evaluate_session_consumed_size_condition(
-                                       condition, new_state);
+                               condition, &session_info->last_state_sample);
+                       newest_result =
+                               evaluate_session_consumed_size_condition(condition, new_state);
                } else {
                        previous_result = false;
                        newest_result = evaluate_session_consumed_size_condition(
-                                       condition, &session_info->last_state_sample);
+                               condition, &session_info->last_state_sample);
                }
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED:
@@ -1098,9 +1014,8 @@ int evaluate_session_condition(
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
        {
-               const auto rotation_id = new_state ?
-                               new_state->rotation.id :
-                                     session_info->last_state_sample.rotation.id;
+               const auto rotation_id = new_state ? new_state->rotation.id :
+                                                    session_info->last_state_sample.rotation.id;
 
                *evaluation = lttng_evaluation_session_rotation_ongoing_create(rotation_id);
                break;
@@ -1112,17 +1027,17 @@ int evaluate_session_condition(
 
                /* Callee acquires a reference to location. */
                *evaluation = lttng_evaluation_session_rotation_completed_create(
-                               rotation_id, sample.rotation.location);
+                       rotation_id, sample.rotation.location);
                break;
        }
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
        {
                const auto latest_session_consumed_total = new_state ?
-                               new_state->consumed_data_size :
-                                     session_info->last_state_sample.consumed_data_size;
+                       new_state->consumed_data_size :
+                       session_info->last_state_sample.consumed_data_size;
 
                *evaluation = lttng_evaluation_session_consumed_size_create(
-                               latest_session_consumed_total);
+                       latest_session_consumed_total);
                break;
        }
        default:
@@ -1132,7 +1047,7 @@ int evaluate_session_condition(
        if (!*evaluation) {
                /* Fatal error. */
                ERR("Failed to create session condition evaluation: session name = `%s`",
-                               session_info->name);
+                   session_info->name);
                ret = -1;
                goto end;
        }
@@ -1142,21 +1057,20 @@ end:
        return ret;
 }
 
-static
-int evaluate_condition_for_client(const struct lttng_trigger *trigger,
-               const struct lttng_condition *condition,
-               struct notification_client *client,
-               struct notification_thread_state *state)
+static int evaluate_condition_for_client(const struct lttng_trigger *trigger,
+                                        const struct lttng_condition *condition,
+                                        struct notification_client *client,
+                                        struct notification_thread_state *state)
 {
        int ret;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
        struct notification_client_list client_list = {
                .lock = PTHREAD_MUTEX_INITIALIZER,
                .ref = {},
-               .condition = NULL,
+               .condition = nullptr,
                .triggers_list = {},
                .clients_list = {},
-               .notification_trigger_clients_ht = NULL,
+               .notification_trigger_clients_ht = nullptr,
                .notification_trigger_clients_ht_node = {},
                .rcu_node = {},
        };
@@ -1178,7 +1092,7 @@ int evaluate_condition_for_client(const struct lttng_trigger *trigger,
                if (!session_info) {
                        /* Not an error, the session doesn't exist yet. */
                        DBG("Session not found while evaluating session condition for client: session name = `%s`",
-                                       session_name);
+                           session_name);
                        ret = 0;
                        goto end;
                }
@@ -1186,13 +1100,13 @@ int evaluate_condition_for_client(const struct lttng_trigger *trigger,
                object_uid = session_info->uid;
                object_gid = session_info->gid;
 
-               ret = evaluate_session_condition(condition, session_info, NULL, &evaluation);
+               ret = evaluate_session_condition(condition, session_info, nullptr, &evaluation);
                session_info_put(session_info);
                break;
        }
        case LTTNG_OBJECT_TYPE_CHANNEL:
-               ret = evaluate_channel_condition_for_client(condition, state,
-                               &evaluation, &object_uid, &object_gid);
+               ret = evaluate_channel_condition_for_client(
+                       condition, state, &evaluation, &object_uid, &object_gid);
                break;
        case LTTNG_OBJECT_TYPE_NONE:
                DBG("Newly subscribed-to condition not bound to object, nothing to evaluate");
@@ -1227,34 +1141,31 @@ int evaluate_condition_for_client(const struct lttng_trigger *trigger,
 
        /* Send evaluation result to the newly-subscribed client. */
        DBG("Newly subscribed-to condition evaluated to true, notifying client");
-       ret = send_evaluation_to_clients(trigger, evaluation, &client_list,
-                       state, object_uid, object_gid);
+       ret = send_evaluation_to_clients(
+               trigger, evaluation, &client_list, state, object_uid, object_gid);
 
 end:
        return ret;
 }
 
-static
-int notification_thread_client_subscribe(struct notification_client *client,
-               struct lttng_condition *condition,
-               struct notification_thread_state *state,
-               enum lttng_notification_channel_status *_status)
+static int notification_thread_client_subscribe(struct notification_client *client,
+                                               struct lttng_condition *condition,
+                                               struct notification_thread_state *state,
+                                               enum lttng_notification_channel_status *_status)
 {
        int ret = 0;
-       struct notification_client_list *client_list = NULL;
-       struct lttng_condition_list_element *condition_list_element = NULL;
-       struct notification_client_list_element *client_list_element = NULL;
+       struct notification_client_list *client_list = nullptr;
+       struct lttng_condition_list_element *condition_list_element = nullptr;
+       struct notification_client_list_element *client_list_element = nullptr;
        struct lttng_trigger_ht_element *trigger_ht_element;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
 
        /*
         * Ensure that the client has not already subscribed to this condition
         * before.
         */
-       cds_list_for_each_entry(condition_list_element, &client->condition_list, node) {
-               if (lttng_condition_is_equal(condition_list_element->condition,
-                               condition)) {
+       cds_list_for_each_entry (condition_list_element, &client->condition_list, node) {
+               if (lttng_condition_is_equal(condition_list_element->condition, condition)) {
                        status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ALREADY_SUBSCRIBED;
                        goto end;
                }
@@ -1276,11 +1187,10 @@ int notification_thread_client_subscribe(struct notification_client *client,
         */
        CDS_INIT_LIST_HEAD(&condition_list_element->node);
        condition_list_element->condition = condition;
-       condition = NULL;
+       condition = nullptr;
        cds_list_add(&condition_list_element->node, &client->condition_list);
 
-       client_list = get_client_list_from_condition(
-                       state, condition_list_element->condition);
+       client_list = get_client_list_from_condition(state, condition_list_element->condition);
        if (!client_list) {
                /*
                 * No notification-emiting trigger registered with this
@@ -1302,10 +1212,12 @@ int notification_thread_client_subscribe(struct notification_client *client,
         * all triggers that have a `notify` action that have this condition.
         */
        pthread_mutex_lock(&client_list->lock);
-       cds_list_for_each_entry(trigger_ht_element,
-                       &client_list->triggers_list, client_list_trigger_node) {
-               if (evaluate_condition_for_client(trigger_ht_element->trigger, condition_list_element->condition,
-                               client, state)) {
+       cds_list_for_each_entry (
+               trigger_ht_element, &client_list->triggers_list, client_list_trigger_node) {
+               if (evaluate_condition_for_client(trigger_ht_element->trigger,
+                                                 condition_list_element->condition,
+                                                 client,
+                                                 state)) {
                        WARN("Evaluation of a condition on client subscription failed, aborting.");
                        ret = -1;
                        free(client_list_element);
@@ -1342,27 +1254,21 @@ error:
        return ret;
 }
 
-static
-int notification_thread_client_unsubscribe(
-               struct notification_client *client,
-               struct lttng_condition *condition,
-               struct notification_thread_state *state,
-               enum lttng_notification_channel_status *_status)
+static int notification_thread_client_unsubscribe(struct notification_client *client,
+                                                 struct lttng_condition *condition,
+                                                 struct notification_thread_state *state,
+                                                 enum lttng_notification_channel_status *_status)
 {
        struct notification_client_list *client_list;
-       struct lttng_condition_list_element *condition_list_element,
-                       *condition_tmp;
-       struct notification_client_list_element *client_list_element,
-                       *client_tmp;
+       struct lttng_condition_list_element *condition_list_element, *condition_tmp;
+       struct notification_client_list_element *client_list_element, *client_tmp;
        bool condition_found = false;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
 
        /* Remove the condition from the client's condition list. */
-       cds_list_for_each_entry_safe(condition_list_element, condition_tmp,
-                       &client->condition_list, node) {
-               if (!lttng_condition_is_equal(condition_list_element->condition,
-                               condition)) {
+       cds_list_for_each_entry_safe (
+               condition_list_element, condition_tmp, &client->condition_list, node) {
+               if (!lttng_condition_is_equal(condition_list_element->condition, condition)) {
                        continue;
                }
 
@@ -1373,8 +1279,7 @@ int notification_thread_client_unsubscribe(
                 * will be destroyed at the end.
                 */
                if (condition != condition_list_element->condition) {
-                       lttng_condition_destroy(
-                                       condition_list_element->condition);
+                       lttng_condition_destroy(condition_list_element->condition);
                }
                free(condition_list_element);
                condition_found = true;
@@ -1396,8 +1301,8 @@ int notification_thread_client_unsubscribe(
        }
 
        pthread_mutex_lock(&client_list->lock);
-       cds_list_for_each_entry_safe(client_list_element, client_tmp,
-                       &client_list->clients_list, node) {
+       cds_list_for_each_entry_safe (
+               client_list_element, client_tmp, &client_list->clients_list, node) {
                if (client_list_element->client->id != client->id) {
                        continue;
                }
@@ -1407,7 +1312,7 @@ int notification_thread_client_unsubscribe(
        }
        pthread_mutex_unlock(&client_list->lock);
        notification_client_list_put(client_list);
-       client_list = NULL;
+       client_list = nullptr;
 end:
        lttng_condition_destroy(condition);
        if (_status) {
@@ -1416,14 +1321,12 @@ end:
        return 0;
 }
 
-static
-void free_notification_client_rcu(struct rcu_head *node)
+static void free_notification_client_rcu(struct rcu_head *node)
 {
        free(lttng::utils::container_of(node, &notification_client::rcu_node));
 }
 
-static
-void notification_client_destroy(struct notification_client *client)
+static void notification_client_destroy(struct notification_client *client)
 {
        if (!client) {
                return;
@@ -1448,13 +1351,12 @@ void notification_client_destroy(struct notification_client *client)
  * Call with rcu_read_lock held (and hold for the lifetime of the returned
  * client pointer).
  */
-static
-struct notification_client *get_client_from_socket(int socket,
-               struct notification_thread_state *state)
+static struct notification_client *get_client_from_socket(int socket,
+                                                         struct notification_thread_state *state)
 {
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
-       struct notification_client *client = NULL;
+       struct notification_client *client = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
@@ -1468,8 +1370,7 @@ struct notification_client *get_client_from_socket(int socket,
                goto end;
        }
 
-       client = caa_container_of(node, struct notification_client,
-                       client_socket_ht_node);
+       client = caa_container_of(node, struct notification_client, client_socket_ht_node);
 end:
        return client;
 }
@@ -1478,61 +1379,50 @@ end:
  * Call with rcu_read_lock held (and hold for the lifetime of the returned
  * client pointer).
  */
-static
-struct notification_client *get_client_from_id(notification_client_id id,
-               struct notification_thread_state *state)
+static struct notification_client *get_client_from_id(notification_client_id id,
+                                                     struct notification_thread_state *state)
 {
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
-       struct notification_client *client = NULL;
+       struct notification_client *client = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
-       cds_lfht_lookup(state->client_id_ht,
-                       hash_client_id(id),
-                       match_client_id,
-                       &id,
-                       &iter);
+       cds_lfht_lookup(state->client_id_ht, hash_client_id(id), match_client_id, &id, &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (!node) {
                goto end;
        }
 
-       client = caa_container_of(node, struct notification_client,
-                       client_id_ht_node);
+       client = caa_container_of(node, struct notification_client, client_id_ht_node);
 end:
        return client;
 }
 
-static
-bool buffer_usage_condition_applies_to_channel(
-               const struct lttng_condition *condition,
-               const struct channel_info *channel_info)
+static bool buffer_usage_condition_applies_to_channel(const struct lttng_condition *condition,
+                                                     const struct channel_info *channel_info)
 {
        enum lttng_condition_status status;
        enum lttng_domain_type condition_domain;
-       const char *condition_session_name = NULL;
-       const char *condition_channel_name = NULL;
+       const char *condition_session_name = nullptr;
+       const char *condition_channel_name = nullptr;
 
-       status = lttng_condition_buffer_usage_get_domain_type(condition,
-                       &condition_domain);
+       status = lttng_condition_buffer_usage_get_domain_type(condition, &condition_domain);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        if (channel_info->key.domain != condition_domain) {
                goto fail;
        }
 
-       status = lttng_condition_buffer_usage_get_session_name(
-                       condition, &condition_session_name);
+       status = lttng_condition_buffer_usage_get_session_name(condition, &condition_session_name);
        LTTNG_ASSERT((status == LTTNG_CONDITION_STATUS_OK) && condition_session_name);
 
-       status = lttng_condition_buffer_usage_get_channel_name(
-                       condition, &condition_channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(condition, &condition_channel_name);
        LTTNG_ASSERT((status == LTTNG_CONDITION_STATUS_OK) && condition_channel_name);
 
-       if (strcmp(channel_info->session_info->name, condition_session_name)) {
+       if (strcmp(channel_info->session_info->name, condition_session_name) != 0) {
                goto fail;
        }
-       if (strcmp(channel_info->name, condition_channel_name)) {
+       if (strcmp(channel_info->name, condition_channel_name) != 0) {
                goto fail;
        }
 
@@ -1541,9 +1431,8 @@ fail:
        return false;
 }
 
-static
-bool trigger_applies_to_channel(const struct lttng_trigger *trigger,
-               const struct channel_info *channel_info)
+static bool trigger_applies_to_channel(const struct lttng_trigger *trigger,
+                                      const struct channel_info *channel_info)
 {
        const struct lttng_condition *condition;
        bool trigger_applies;
@@ -1556,8 +1445,8 @@ bool trigger_applies_to_channel(const struct lttng_trigger *trigger,
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
-               trigger_applies = buffer_usage_condition_applies_to_channel(
-                               condition, channel_info);
+               trigger_applies =
+                       buffer_usage_condition_applies_to_channel(condition, channel_info);
                break;
        default:
                goto fail;
@@ -1569,12 +1458,10 @@ fail:
 }
 
 /* Must be called with RCU read lock held. */
-static
-struct lttng_session_trigger_list *get_session_trigger_list(
-               struct notification_thread_state *state,
-               const char *session_name)
+static struct lttng_session_trigger_list *
+get_session_trigger_list(struct notification_thread_state *state, const char *session_name)
 {
-       struct lttng_session_trigger_list *list = NULL;
+       struct lttng_session_trigger_list *list = nullptr;
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
 
@@ -1592,13 +1479,11 @@ struct lttng_session_trigger_list *get_session_trigger_list(
                 * will be initialized when the session is created.
                 */
                DBG("No trigger list found for session \"%s\" as it is not yet known to the notification system",
-                               session_name);
+                   session_name);
                goto end;
        }
 
-       list = caa_container_of(node,
-                       struct lttng_session_trigger_list,
-                       session_triggers_ht_node);
+       list = caa_container_of(node, struct lttng_session_trigger_list, session_triggers_ht_node);
 end:
        return list;
 }
@@ -1607,12 +1492,10 @@ end:
  * Allocate an empty lttng_session_trigger_list for the session named
  * 'session_name'.
  */
-static
-struct lttng_session_trigger_list *lttng_session_trigger_list_create(
-               const char *session_name,
-               struct cds_lfht *session_triggers_ht)
+static struct lttng_session_trigger_list *
+lttng_session_trigger_list_create(const char *session_name, struct cds_lfht *session_triggers_ht)
 {
-       struct lttng_session_trigger_list *list = NULL;
+       struct lttng_session_trigger_list *list = nullptr;
        char *session_name_copy = strdup(session_name);
 
        if (!session_name_copy) {
@@ -1631,52 +1514,46 @@ struct lttng_session_trigger_list *lttng_session_trigger_list_create(
        cds_lfht_node_init(&list->session_triggers_ht_node);
        list->session_triggers_ht = session_triggers_ht;
 
-       rcu_read_lock();
        /* Publish the list through the session_triggers_ht. */
-       cds_lfht_add(session_triggers_ht,
-                       hash_key_str(session_name, lttng_ht_seed),
-                       &list->session_triggers_ht_node);
-       rcu_read_unlock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_add(session_triggers_ht,
+                            hash_key_str(session_name, lttng_ht_seed),
+                            &list->session_triggers_ht_node);
+       }
 end:
        return list;
 }
 
-static
-void free_session_trigger_list_rcu(struct rcu_head *node)
+static void free_session_trigger_list_rcu(struct rcu_head *node)
 {
        struct lttng_session_trigger_list *list =
-                       caa_container_of(node, struct lttng_session_trigger_list, rcu_node);
+               caa_container_of(node, struct lttng_session_trigger_list, rcu_node);
 
        free(list->session_name);
        free(list);
 }
 
-static
-void lttng_session_trigger_list_destroy(struct lttng_session_trigger_list *list)
+static void lttng_session_trigger_list_destroy(struct lttng_session_trigger_list *list)
 {
        struct lttng_trigger_list_element *trigger_list_element, *tmp;
 
        /* Empty the list element by element, and then free the list itself. */
-       cds_list_for_each_entry_safe(trigger_list_element, tmp,
-                       &list->list, node) {
+       cds_list_for_each_entry_safe (trigger_list_element, tmp, &list->list, node) {
                cds_list_del(&trigger_list_element->node);
                free(trigger_list_element);
        }
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        /* Unpublish the list from the session_triggers_ht. */
-       cds_lfht_del(list->session_triggers_ht,
-                       &list->session_triggers_ht_node);
-       rcu_read_unlock();
+       cds_lfht_del(list->session_triggers_ht, &list->session_triggers_ht_node);
        call_rcu(&list->rcu_node, free_session_trigger_list_rcu);
 }
 
-static
-int lttng_session_trigger_list_add(struct lttng_session_trigger_list *list,
-               struct lttng_trigger *trigger)
+static int lttng_session_trigger_list_add(struct lttng_session_trigger_list *list,
+                                         struct lttng_trigger *trigger)
 {
        int ret = 0;
-       struct lttng_trigger_list_element *new_element =
-                       zmalloc<lttng_trigger_list_element>();
+       struct lttng_trigger_list_element *new_element = zmalloc<lttng_trigger_list_element>();
 
        if (!new_element) {
                ret = -1;
@@ -1689,9 +1566,8 @@ end:
        return ret;
 }
 
-static
-bool trigger_applies_to_session(const struct lttng_trigger *trigger,
-               const char *session_name)
+static bool trigger_applies_to_session(const struct lttng_trigger *trigger,
+                                      const char *session_name)
 {
        bool applies = false;
        const struct lttng_condition *condition;
@@ -1720,112 +1596,117 @@ end:
  * Allocate and initialize an lttng_session_trigger_list which contains
  * all triggers that apply to the session named 'session_name'.
  */
-static
-struct lttng_session_trigger_list *lttng_session_trigger_list_build(
-               const struct notification_thread_state *state,
-               const char *session_name)
+static struct lttng_session_trigger_list *
+lttng_session_trigger_list_build(const struct notification_thread_state *state,
+                                const char *session_name)
 {
        int trigger_count = 0;
-       struct lttng_session_trigger_list *session_trigger_list = NULL;
-       struct lttng_trigger_ht_element *trigger_ht_element = NULL;
+       struct lttng_session_trigger_list *session_trigger_list = nullptr;
+       struct lttng_trigger_ht_element *trigger_ht_element = nullptr;
        struct cds_lfht_iter iter;
 
-       session_trigger_list = lttng_session_trigger_list_create(session_name,
-                       state->session_triggers_ht);
+       session_trigger_list =
+               lttng_session_trigger_list_create(session_name, state->session_triggers_ht);
 
-       /* Add all triggers applying to the session named 'session_name'. */
-       cds_lfht_for_each_entry(state->triggers_ht, &iter, trigger_ht_element,
-                       node) {
-               int ret;
+       {
+               /* Add all triggers applying to the session named 'session_name'. */
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (!trigger_applies_to_session(trigger_ht_element->trigger,
-                               session_name)) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (state->triggers_ht, &iter, trigger_ht_element, node) {
+                       int ret;
 
-               ret = lttng_session_trigger_list_add(session_trigger_list,
-                               trigger_ht_element->trigger);
-               if (ret) {
-                       goto error;
-               }
+                       if (!trigger_applies_to_session(trigger_ht_element->trigger,
+                                                       session_name)) {
+                               continue;
+                       }
 
-               trigger_count++;
+                       ret = lttng_session_trigger_list_add(session_trigger_list,
+                                                            trigger_ht_element->trigger);
+                       if (ret) {
+                               goto error;
+                       }
+
+                       trigger_count++;
+               }
        }
 
-       DBG("Found %i triggers that apply to newly created session",
-                       trigger_count);
+       DBG("Found %i triggers that apply to newly created session", trigger_count);
        return session_trigger_list;
 error:
        lttng_session_trigger_list_destroy(session_trigger_list);
-       return NULL;
+       return nullptr;
 }
 
-static
-struct session_info *create_and_publish_session_info(struct notification_thread_state *state,
-               uint64_t id,
-               const char *name,
-               uid_t uid,
-               gid_t gid)
+static struct session_info *create_and_publish_session_info(struct notification_thread_state *state,
+                                                           uint64_t id,
+                                                           const char *name,
+                                                           uid_t uid,
+                                                           gid_t gid)
 {
-       struct session_info *session = NULL;
+       struct session_info *session = nullptr;
        struct lttng_session_trigger_list *trigger_list;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        trigger_list = lttng_session_trigger_list_build(state, name);
        if (!trigger_list) {
                goto error;
        }
 
-       session = session_info_create(id, name, uid, gid, trigger_list,
-                       state->sessions_ht);
+       session = session_info_create(id, name, uid, gid, trigger_list, state->sessions_ht);
        if (!session) {
                ERR("Failed to allocation session info for session \"%s\" (uid = %i, gid = %i)",
-                               name, uid, gid);
+                   name,
+                   uid,
+                   gid);
                lttng_session_trigger_list_destroy(trigger_list);
                goto error;
        }
 
        /* Transferred ownership to the new session. */
-       trigger_list = NULL;
+       trigger_list = nullptr;
 
-       if (cds_lfht_add_unique(state->sessions_ht, hash_session_info(session), match_session_info,
-                           &id, &session->sessions_ht_node) != &session->sessions_ht_node) {
+       if (cds_lfht_add_unique(state->sessions_ht,
+                               hash_session_info(session),
+                               match_session_info,
+                               &id,
+                               &session->sessions_ht_node) != &session->sessions_ht_node) {
                ERR("Duplicate session found: name = `%s`, id = %" PRIu64, name, id);
                goto error;
        }
 
-       rcu_read_unlock();
        return session;
 error:
-       rcu_read_unlock();
        session_info_put(session);
-       return NULL;
+       return nullptr;
 }
 
-static
-int handle_notification_thread_command_add_channel(struct notification_thread_state *state,
-               uint64_t session_id,
-               const char *channel_name,
-               enum lttng_domain_type channel_domain,
-               uint64_t channel_key_int,
-               uint64_t channel_capacity,
-               enum lttng_error_code *cmd_result)
+static int handle_notification_thread_command_add_channel(struct notification_thread_state *state,
+                                                         uint64_t session_id,
+                                                         const char *channel_name,
+                                                         enum lttng_domain_type channel_domain,
+                                                         uint64_t channel_key_int,
+                                                         uint64_t channel_capacity,
+                                                         enum lttng_error_code *cmd_result)
 {
        struct cds_list_head trigger_list;
-       struct channel_info *new_channel_info = NULL;
+       struct channel_info *new_channel_info = nullptr;
        struct channel_key channel_key = {
                .key = channel_key_int,
                .domain = channel_domain,
        };
-       struct lttng_channel_trigger_list *channel_trigger_list = NULL;
-       struct lttng_trigger_ht_element *trigger_ht_element = NULL;
+       struct lttng_channel_trigger_list *channel_trigger_list = nullptr;
+       struct lttng_trigger_ht_element *trigger_ht_element = nullptr;
        int trigger_count = 0;
        struct cds_lfht_iter iter;
-       struct session_info *session_info = NULL;
+       struct session_info *session_info = nullptr;
+       lttng::urcu::read_lock_guard read_lock;
 
-       DBG("Adding channel: channel name = `%s`, session id = %" PRIu64 ", channel key = %" PRIu64 ", domain = %s",
-                       channel_name, session_id, channel_key_int,
-                       lttng_domain_type_str(channel_domain));
+       DBG("Adding channel: channel name = `%s`, session id = %" PRIu64 ", channel key = %" PRIu64
+           ", domain = %s",
+           channel_name,
+           session_id,
+           channel_key_int,
+           lttng_domain_type_str(channel_domain));
 
        CDS_INIT_LIST_HEAD(&trigger_list);
 
@@ -1833,30 +1714,26 @@ int handle_notification_thread_command_add_channel(struct notification_thread_st
        if (!session_info) {
                /* Fatal logic error. */
                ERR("Failed to find session while adding channel: session id = %" PRIu64,
-                               session_id);
+                   session_id);
                goto error;
        }
 
-       new_channel_info = channel_info_create(channel_name, &channel_key,
-                       channel_capacity, session_info);
+       new_channel_info =
+               channel_info_create(channel_name, &channel_key, channel_capacity, session_info);
        if (!new_channel_info) {
                goto error;
        }
 
-       rcu_read_lock();
        /* Build a list of all triggers applying to the new channel. */
-       cds_lfht_for_each_entry(state->triggers_ht, &iter, trigger_ht_element,
-                       node) {
+       cds_lfht_for_each_entry (state->triggers_ht, &iter, trigger_ht_element, node) {
                struct lttng_trigger_list_element *new_element;
 
-               if (!trigger_applies_to_channel(trigger_ht_element->trigger,
-                               new_channel_info)) {
+               if (!trigger_applies_to_channel(trigger_ht_element->trigger, new_channel_info)) {
                        continue;
                }
 
                new_element = zmalloc<lttng_trigger_list_element>();
                if (!new_element) {
-                       rcu_read_unlock();
                        goto error;
                }
                CDS_INIT_LIST_HEAD(&new_element->node);
@@ -1864,10 +1741,8 @@ int handle_notification_thread_command_add_channel(struct notification_thread_st
                cds_list_add(&new_element->node, &trigger_list);
                trigger_count++;
        }
-       rcu_read_unlock();
 
-       DBG("Found %i triggers that apply to newly added channel",
-                       trigger_count);
+       DBG("Found %i triggers that apply to newly added channel", trigger_count);
        channel_trigger_list = zmalloc<lttng_channel_trigger_list>();
        if (!channel_trigger_list) {
                goto error;
@@ -1877,19 +1752,17 @@ int handle_notification_thread_command_add_channel(struct notification_thread_st
        cds_lfht_node_init(&channel_trigger_list->channel_triggers_ht_node);
        cds_list_splice(&trigger_list, &channel_trigger_list->list);
 
-       rcu_read_lock();
        /* Add channel to the channel_ht which owns the channel_infos. */
        cds_lfht_add(state->channels_ht,
-                       hash_channel_key(&new_channel_info->key),
-                       &new_channel_info->channels_ht_node);
+                    hash_channel_key(&new_channel_info->key),
+                    &new_channel_info->channels_ht_node);
        /*
         * Add the list of triggers associated with this channel to the
         * channel_triggers_ht.
         */
        cds_lfht_add(state->channel_triggers_ht,
-                       hash_channel_key(&new_channel_info->key),
-                       &channel_trigger_list->channel_triggers_ht_node);
-       rcu_read_unlock();
+                    hash_channel_key(&new_channel_info->key),
+                    &channel_trigger_list->channel_triggers_ht_node);
        session_info_put(session_info);
        *cmd_result = LTTNG_OK;
        return 0;
@@ -1899,23 +1772,31 @@ error:
        return 1;
 }
 
-static
-int handle_notification_thread_command_add_session(struct notification_thread_state *state,
-               uint64_t session_id,
-               const char *session_name,
-               uid_t session_uid,
-               gid_t session_gid,
-               enum lttng_error_code *cmd_result)
+static int handle_notification_thread_command_add_session(struct notification_thread_state *state,
+                                                         uint64_t session_id,
+                                                         const char *session_name,
+                                                         uid_t session_uid,
+                                                         gid_t session_gid,
+                                                         enum lttng_error_code *cmd_result)
 {
        int ret;
 
-       DBG("Adding session: session name = `%s`, session id = %" PRIu64 ", session uid = %d, session gid = %d",
-                       session_name, session_id, session_uid, session_gid);
+       DBG("Adding session: session name = `%s`, session id = %" PRIu64
+           ", session uid = %d, session gid = %d",
+           session_name,
+           session_id,
+           session_uid,
+           session_gid);
 
-       auto session = create_and_publish_session_info(state, session_id, session_name, session_uid, session_gid);
+       auto session = create_and_publish_session_info(
+               state, session_id, session_name, session_uid, session_gid);
        if (!session) {
-               PERROR("Failed to add session: session name = `%s`, session id = %" PRIu64 ", session uid = %d, session gid = %d",
-                               session_name, session_id, session_uid, session_gid);
+               PERROR("Failed to add session: session name = `%s`, session id = %" PRIu64
+                      ", session uid = %d, session gid = %d",
+                      session_name,
+                      session_id,
+                      session_uid,
+                      session_gid);
                ret = -1;
                *cmd_result = LTTNG_ERR_NOMEM;
                goto end;
@@ -1933,11 +1814,10 @@ end:
        return ret;
 }
 
-static
-int handle_notification_thread_command_remove_session(
-               struct notification_thread_state *state,
-               uint64_t session_id,
-               enum lttng_error_code *cmd_result)
+static int
+handle_notification_thread_command_remove_session(struct notification_thread_state *state,
+                                                 uint64_t session_id,
+                                                 enum lttng_error_code *cmd_result)
 {
        int ret;
 
@@ -1960,25 +1840,21 @@ end:
        return ret;
 }
 
-static
-void free_channel_trigger_list_rcu(struct rcu_head *node)
+static void free_channel_trigger_list_rcu(struct rcu_head *node)
 {
-       free(caa_container_of(node, struct lttng_channel_trigger_list,
-                       rcu_node));
+       free(caa_container_of(node, struct lttng_channel_trigger_list, rcu_node));
 }
 
-static
-void free_channel_state_sample_rcu(struct rcu_head *node)
+static void free_channel_state_sample_rcu(struct rcu_head *node)
 {
-       free(caa_container_of(node, struct channel_state_sample,
-                       rcu_node));
+       free(caa_container_of(node, struct channel_state_sample, rcu_node));
 }
 
-static
-int handle_notification_thread_command_remove_channel(
-       struct notification_thread_state *state,
-       uint64_t channel_key, enum lttng_domain_type domain,
-       enum lttng_error_code *cmd_result)
+static int
+handle_notification_thread_command_remove_channel(struct notification_thread_state *state,
+                                                 uint64_t channel_key,
+                                                 enum lttng_domain_type domain,
+                                                 enum lttng_error_code *cmd_result)
 {
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
@@ -1988,9 +1864,10 @@ int handle_notification_thread_command_remove_channel(
        struct channel_info *channel_info;
 
        DBG("Removing channel key = %" PRIu64 " in %s domain",
-                       channel_key, lttng_domain_type_str(domain));
+           channel_key,
+           lttng_domain_type_str(domain));
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        cds_lfht_lookup(state->channel_triggers_ht,
                        hash_channel_key(&key),
@@ -2008,10 +1885,9 @@ int handle_notification_thread_command_remove_channel(
        }
 
        /* Free the list of triggers associated with this channel. */
-       trigger_list = caa_container_of(node, struct lttng_channel_trigger_list,
-                       channel_triggers_ht_node);
-       cds_list_for_each_entry_safe(trigger_list_element, tmp,
-                       &trigger_list->list, node) {
+       trigger_list =
+               caa_container_of(node, struct lttng_channel_trigger_list, channel_triggers_ht_node);
+       cds_list_for_each_entry_safe (trigger_list_element, tmp, &trigger_list->list, node) {
                cds_list_del(&trigger_list_element->node);
                free(trigger_list_element);
        }
@@ -2030,40 +1906,33 @@ int handle_notification_thread_command_remove_channel(
         * received a sample.
         */
        if (node) {
-               struct channel_state_sample *sample = caa_container_of(node,
-                               struct channel_state_sample,
-                               channel_state_ht_node);
+               struct channel_state_sample *sample =
+                       caa_container_of(node, struct channel_state_sample, channel_state_ht_node);
 
                cds_lfht_del(state->channel_state_ht, node);
                call_rcu(&sample->rcu_node, free_channel_state_sample_rcu);
        }
 
        /* Remove the channel from the channels_ht and free it. */
-       cds_lfht_lookup(state->channels_ht,
-                       hash_channel_key(&key),
-                       match_channel_info,
-                       &key,
-                       &iter);
+       cds_lfht_lookup(
+               state->channels_ht, hash_channel_key(&key), match_channel_info, &key, &iter);
        node = cds_lfht_iter_get_node(&iter);
        LTTNG_ASSERT(node);
-       channel_info = caa_container_of(node, struct channel_info,
-                       channels_ht_node);
+       channel_info = caa_container_of(node, struct channel_info, channels_ht_node);
        cds_lfht_del(state->channels_ht, node);
        channel_info_destroy(channel_info);
 end:
-       rcu_read_unlock();
        *cmd_result = LTTNG_OK;
        return 0;
 }
 
-static
-int handle_notification_thread_command_session_rotation(
-       struct notification_thread_state *state,
-       enum notification_thread_command_type cmd_type,
-       uint64_t session_id,
-       uint64_t trace_archive_chunk_id,
-       struct lttng_trace_archive_location *location,
-       enum lttng_error_code *_cmd_result)
+static int
+handle_notification_thread_command_session_rotation(struct notification_thread_state *state,
+                                                   enum notification_thread_command_type cmd_type,
+                                                   uint64_t session_id,
+                                                   uint64_t trace_archive_chunk_id,
+                                                   struct lttng_trace_archive_location *location,
+                                                   enum lttng_error_code *_cmd_result)
 {
        int ret = 0;
        enum lttng_error_code cmd_result = LTTNG_OK;
@@ -2073,13 +1942,13 @@ int handle_notification_thread_command_session_rotation(
        struct lttng_credentials session_creds;
        struct session_state_sample new_session_state;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        session_info = get_session_info_by_id(state, session_id);
        if (!session_info) {
                /* Fatal logic error. */
                ERR("Failed to find session while handling rotation state change: session id = %" PRIu64,
-                               session_id);
+                   session_id);
                ret = -1;
                cmd_result = LTTNG_ERR_FATAL;
                goto end;
@@ -2090,7 +1959,7 @@ int handle_notification_thread_command_session_rotation(
                lttng_trace_archive_location_get(location);
                new_session_state.rotation.location = location;
        } else {
-               new_session_state.rotation.location = NULL;
+               new_session_state.rotation.location = nullptr;
        }
 
        session_creds = {
@@ -2099,18 +1968,17 @@ int handle_notification_thread_command_session_rotation(
        };
 
        new_session_state.rotation.ongoing = cmd_type ==
-                       NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_ONGOING;
+               NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_ONGOING;
        new_session_state.rotation.id = trace_archive_chunk_id;
 
        trigger_list = get_session_trigger_list(state, session_info->name);
        LTTNG_ASSERT(trigger_list);
 
-       cds_list_for_each_entry(trigger_list_element, &trigger_list->list,
-                       node) {
+       cds_list_for_each_entry (trigger_list_element, &trigger_list->list, node) {
                const struct lttng_condition *condition;
                struct lttng_trigger *trigger;
                struct notification_client_list *client_list;
-               struct lttng_evaluation *evaluation = NULL;
+               struct lttng_evaluation *evaluation = nullptr;
                enum action_executor_status executor_status;
 
                trigger = trigger_list_element->trigger;
@@ -2118,7 +1986,7 @@ int handle_notification_thread_command_session_rotation(
                LTTNG_ASSERT(condition);
 
                ret = evaluate_session_condition(
-                               condition, session_info, &new_session_state, &evaluation);
+                       condition, session_info, &new_session_state, &evaluation);
                if (ret) {
                        ret = -1;
                        cmd_result = LTTNG_ERR_NOMEM;
@@ -2136,10 +2004,9 @@ int handle_notification_thread_command_session_rotation(
                 */
                client_list = get_client_list_from_condition(state, condition);
                executor_status = action_executor_enqueue_trigger(
-                               state->executor, trigger, evaluation,
-                               &session_creds, client_list);
+                       state->executor, trigger, evaluation, &session_creds, client_list);
                notification_client_list_put(client_list);
-               evaluation = NULL;
+               evaluation = nullptr;
                switch (executor_status) {
                case ACTION_EXECUTOR_STATUS_OK:
                        break;
@@ -2176,20 +2043,18 @@ end:
 
        session_info_put(session_info);
        *_cmd_result = cmd_result;
-       rcu_read_unlock();
        return ret;
 }
 
-static
-int handle_notification_thread_command_add_tracer_event_source(
-               struct notification_thread_state *state,
-               int tracer_event_source_fd,
-               enum lttng_domain_type domain_type,
-               enum lttng_error_code *_cmd_result)
+static int
+handle_notification_thread_command_add_tracer_event_source(struct notification_thread_state *state,
+                                                          int tracer_event_source_fd,
+                                                          enum lttng_domain_type domain_type,
+                                                          enum lttng_error_code *_cmd_result)
 {
        int ret = 0;
        enum lttng_error_code cmd_result = LTTNG_OK;
-       struct notification_event_tracer_event_source_element *element = NULL;
+       struct notification_event_tracer_event_source_element *element = nullptr;
 
        element = zmalloc<notification_event_tracer_event_source_element>();
        if (!element) {
@@ -2204,15 +2069,15 @@ int handle_notification_thread_command_add_tracer_event_source(
        cds_list_add(&element->node, &state->tracer_event_sources_list);
 
        DBG3("Adding tracer event source fd to poll set: tracer_event_source_fd = %d, domain = '%s'",
-                       tracer_event_source_fd,
-                       lttng_domain_type_str(domain_type));
+            tracer_event_source_fd,
+            lttng_domain_type_str(domain_type));
 
        /* Adding the read side pipe to the event poll. */
-       ret = lttng_poll_add(&state->events, tracer_event_source_fd, LPOLLPRI | LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&state->events, tracer_event_source_fd, LPOLLPRI | LPOLLIN);
        if (ret < 0) {
                ERR("Failed to add tracer event source to poll set: tracer_event_source_fd = %d, domain = '%s'",
-                               tracer_event_source_fd,
-                               lttng_domain_type_str(element->domain));
+                   tracer_event_source_fd,
+                   lttng_domain_type_str(element->domain));
                cds_list_del(&element->node);
                free(element);
                goto end;
@@ -2225,10 +2090,9 @@ end:
        return ret;
 }
 
-static
-int drain_event_notifier_notification_pipe(
-               struct notification_thread_state *state,
-               int pipe, enum lttng_domain_type domain)
+static int drain_event_notifier_notification_pipe(struct notification_thread_state *state,
+                                                 int pipe,
+                                                 enum lttng_domain_type domain)
 {
        struct lttng_poll_event events = {};
        int ret;
@@ -2242,7 +2106,7 @@ int drain_event_notifier_notification_pipe(
        ret = lttng_poll_add(&events, pipe, LPOLLIN);
        if (ret < 0) {
                ERR("Error adding fd event notifier notification pipe to lttng_poll_event: fd = %d",
-                               pipe);
+                   pipe);
                goto end;
        }
 
@@ -2270,7 +2134,7 @@ int drain_event_notifier_notification_pipe(
                ret = handle_one_event_notifier_notification(state, pipe, domain);
                if (ret) {
                        ERR("Error consuming an event notifier notification from pipe: fd = %d",
-                                       pipe);
+                           pipe);
                }
        }
 end:
@@ -2278,44 +2142,41 @@ end:
        return ret;
 }
 
-static
-struct notification_event_tracer_event_source_element *
+static struct notification_event_tracer_event_source_element *
 find_tracer_event_source_element(struct notification_thread_state *state,
-               int tracer_event_source_fd)
+                                int tracer_event_source_fd)
 {
        struct notification_event_tracer_event_source_element *source_element;
 
-       cds_list_for_each_entry(source_element,
-                       &state->tracer_event_sources_list, node) {
+       cds_list_for_each_entry (source_element, &state->tracer_event_sources_list, node) {
                if (source_element->fd == tracer_event_source_fd) {
                        goto end;
                }
        }
 
-       source_element = NULL;
+       source_element = nullptr;
 end:
        return source_element;
 }
 
-static
-int remove_tracer_event_source_from_pollset(
-               struct notification_thread_state *state,
-               struct notification_event_tracer_event_source_element *source_element)
+static int remove_tracer_event_source_from_pollset(
+       struct notification_thread_state *state,
+       struct notification_event_tracer_event_source_element *source_element)
 {
        int ret = 0;
 
        LTTNG_ASSERT(source_element->is_fd_in_poll_set);
 
        DBG3("Removing tracer event source from poll set: tracer_event_source_fd = %d, domain = '%s'",
-                       source_element->fd,
-                       lttng_domain_type_str(source_element->domain));
+            source_element->fd,
+            lttng_domain_type_str(source_element->domain));
 
        /* Removing the fd from the event poll set. */
        ret = lttng_poll_del(&state->events, source_element->fd);
        if (ret < 0) {
                ERR("Failed to remove tracer event source from poll set: tracer_event_source_fd = %d, domain = '%s'",
-                               source_element->fd,
-                               lttng_domain_type_str(source_element->domain));
+                   source_element->fd,
+                   lttng_domain_type_str(source_element->domain));
                ret = -1;
                goto end;
        }
@@ -2328,12 +2189,12 @@ int remove_tracer_event_source_from_pollset(
         */
        state->restart_poll = true;
 
-       ret = drain_event_notifier_notification_pipe(state, source_element->fd,
-                       source_element->domain);
+       ret = drain_event_notifier_notification_pipe(
+               state, source_element->fd, source_element->domain);
        if (ret) {
                ERR("Error draining event notifier notification: tracer_event_source_fd = %d, domain = %s",
-                               source_element->fd,
-                               lttng_domain_type_str(source_element->domain));
+                   source_element->fd,
+                   lttng_domain_type_str(source_element->domain));
                ret = -1;
                goto end;
        }
@@ -2342,15 +2203,13 @@ end:
        return ret;
 }
 
-int handle_notification_thread_tracer_event_source_died(
-               struct notification_thread_state *state,
-               int tracer_event_source_fd)
+int handle_notification_thread_tracer_event_source_died(struct notification_thread_state *state,
+                                                       int tracer_event_source_fd)
 {
        int ret = 0;
        struct notification_event_tracer_event_source_element *source_element;
 
-       source_element = find_tracer_event_source_element(state,
-                       tracer_event_source_fd);
+       source_element = find_tracer_event_source_element(state, tracer_event_source_fd);
 
        LTTNG_ASSERT(source_element);
 
@@ -2362,18 +2221,16 @@ int handle_notification_thread_tracer_event_source_died(
        return ret;
 }
 
-static
-int handle_notification_thread_command_remove_tracer_event_source(
-               struct notification_thread_state *state,
-               int tracer_event_source_fd,
-               enum lttng_error_code *_cmd_result)
+static int handle_notification_thread_command_remove_tracer_event_source(
+       struct notification_thread_state *state,
+       int tracer_event_source_fd,
+       enum lttng_error_code *_cmd_result)
 {
        int ret = 0;
        enum lttng_error_code cmd_result = LTTNG_OK;
-       struct notification_event_tracer_event_source_element *source_element = NULL;
+       struct notification_event_tracer_event_source_element *source_element = nullptr;
 
-       source_element = find_tracer_event_source_element(state,
-                       tracer_event_source_fd);
+       source_element = find_tracer_event_source_element(state, tracer_event_source_fd);
 
        LTTNG_ASSERT(source_element);
 
@@ -2397,21 +2254,22 @@ end:
        return ret;
 }
 
-static int handle_notification_thread_command_list_triggers(
-               struct notification_thread_handle *handle __attribute__((unused)),
-               struct notification_thread_state *state,
-               uid_t client_uid,
-               struct lttng_triggers **triggers,
-               enum lttng_error_code *_cmd_result)
+static int
+handle_notification_thread_command_list_triggers(struct notification_thread_handle *handle
+                                                __attribute__((unused)),
+                                                struct notification_thread_state *state,
+                                                uid_t client_uid,
+                                                struct lttng_triggers **triggers,
+                                                enum lttng_error_code *_cmd_result)
 {
        int ret = 0;
        enum lttng_error_code cmd_result = LTTNG_OK;
        struct cds_lfht_iter iter;
        struct lttng_trigger_ht_element *trigger_ht_element;
-       struct lttng_triggers *local_triggers = NULL;
+       struct lttng_triggers *local_triggers = nullptr;
        const struct lttng_credentials *creds;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        local_triggers = lttng_triggers_create();
        if (!local_triggers) {
@@ -2420,8 +2278,7 @@ static int handle_notification_thread_command_list_triggers(
                goto end;
        }
 
-       cds_lfht_for_each_entry(state->triggers_ht, &iter,
-                       trigger_ht_element, node) {
+       cds_lfht_for_each_entry (state->triggers_ht, &iter, trigger_ht_element, node) {
                /*
                 * Only return the triggers to which the client has access.
                 * The root user has visibility over all triggers.
@@ -2431,8 +2288,7 @@ static int handle_notification_thread_command_list_triggers(
                        continue;
                }
 
-               ret = lttng_triggers_add(local_triggers,
-                               trigger_ht_element->trigger);
+               ret = lttng_triggers_add(local_triggers, trigger_ht_element->trigger);
                if (ret < 0) {
                        /* Not a fatal error. */
                        ret = 0;
@@ -2443,18 +2299,17 @@ static int handle_notification_thread_command_list_triggers(
 
        /* Transferring ownership to the caller. */
        *triggers = local_triggers;
-       local_triggers = NULL;
+       local_triggers = nullptr;
 
 end:
-       rcu_read_unlock();
        lttng_triggers_destroy(local_triggers);
        *_cmd_result = cmd_result;
        return ret;
 }
 
 static inline void get_trigger_info_for_log(const struct lttng_trigger *trigger,
-               const char **trigger_name,
-               uid_t *trigger_owner_uid)
+                                           const char **trigger_name,
+                                           uid_t *trigger_owner_uid)
 {
        enum lttng_trigger_status trigger_status;
 
@@ -2469,16 +2324,14 @@ static inline void get_trigger_info_for_log(const struct lttng_trigger *trigger,
                abort();
        }
 
-       trigger_status = lttng_trigger_get_owner_uid(trigger,
-                       trigger_owner_uid);
+       trigger_status = lttng_trigger_get_owner_uid(trigger, trigger_owner_uid);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 }
 
-static int handle_notification_thread_command_get_trigger(
-               struct notification_thread_state *state,
-               const struct lttng_trigger *trigger,
-               struct lttng_trigger **registered_trigger,
-               enum lttng_error_code *_cmd_result)
+static int handle_notification_thread_command_get_trigger(struct notification_thread_state *state,
+                                                         const struct lttng_trigger *trigger,
+                                                         struct lttng_trigger **registered_trigger,
+                                                         enum lttng_error_code *_cmd_result)
 {
        int ret = -1;
        struct cds_lfht_iter iter;
@@ -2487,36 +2340,35 @@ static int handle_notification_thread_command_get_trigger(
        const char *trigger_name;
        uid_t trigger_owner_uid;
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(
-                       state->triggers_ht, &iter, trigger_ht_element, node) {
-               if (lttng_trigger_is_equal(
-                                   trigger, trigger_ht_element->trigger)) {
-                       /* Take one reference on the return trigger. */
-                       *registered_trigger = trigger_ht_element->trigger;
-                       lttng_trigger_get(*registered_trigger);
-                       ret = 0;
-                       cmd_result = LTTNG_OK;
-                       goto end;
+               cds_lfht_for_each_entry (state->triggers_ht, &iter, trigger_ht_element, node) {
+                       if (lttng_trigger_is_equal(trigger, trigger_ht_element->trigger)) {
+                               /* Take one reference on the return trigger. */
+                               *registered_trigger = trigger_ht_element->trigger;
+                               lttng_trigger_get(*registered_trigger);
+                               ret = 0;
+                               cmd_result = LTTNG_OK;
+                               goto end;
+                       }
                }
        }
 
        /* Not a fatal error if the trigger is not found. */
        get_trigger_info_for_log(trigger, &trigger_name, &trigger_owner_uid);
        DBG("Failed to retrieve registered version of trigger: trigger name = '%s', trigger owner uid = %d",
-                       trigger_name, (int) trigger_owner_uid);
+           trigger_name,
+           (int) trigger_owner_uid);
 
        ret = 0;
 
 end:
-       rcu_read_unlock();
        *_cmd_result = cmd_result;
        return ret;
 }
 
-static
-bool condition_is_supported(struct lttng_condition *condition)
+static bool condition_is_supported(struct lttng_condition *condition)
 {
        bool is_supported;
 
@@ -2527,8 +2379,7 @@ bool condition_is_supported(struct lttng_condition *condition)
                int ret;
                enum lttng_domain_type domain;
 
-               ret = lttng_condition_buffer_usage_get_domain_type(condition,
-                               &domain);
+               ret = lttng_condition_buffer_usage_get_domain_type(condition, &domain);
                LTTNG_ASSERT(ret == 0);
 
                if (domain != LTTNG_DOMAIN_KERNEL) {
@@ -2551,8 +2402,7 @@ bool condition_is_supported(struct lttng_condition *condition)
                const struct lttng_event_rule *event_rule;
                enum lttng_domain_type domain;
                const enum lttng_condition_status status =
-                               lttng_condition_event_rule_matches_get_rule(
-                                               condition, &event_rule);
+                       lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
 
                LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
 
@@ -2580,9 +2430,8 @@ end:
 }
 
 /* Must be called with RCU read lock held. */
-static
-int bind_trigger_to_matching_session(struct lttng_trigger *trigger,
-               struct notification_thread_state *state)
+static int bind_trigger_to_matching_session(struct lttng_trigger *trigger,
+                                           struct notification_thread_state *state)
 {
        int ret = 0;
        const struct lttng_condition *condition;
@@ -2597,22 +2446,19 @@ int bind_trigger_to_matching_session(struct lttng_trigger *trigger,
        trigger_list = get_session_trigger_list(state, session_name);
        if (!trigger_list) {
                DBG("Unable to bind trigger applying to session \"%s\" as it is not yet known to the notification system",
-                               session_name);
+                   session_name);
                goto end;
-
        }
 
-       DBG("Newly registered trigger bound to session \"%s\"",
-                       session_name);
+       DBG("Newly registered trigger bound to session \"%s\"", session_name);
        ret = lttng_session_trigger_list_add(trigger_list, trigger);
 end:
        return ret;
 }
 
 /* Must be called with RCU read lock held. */
-static
-int bind_trigger_to_matching_channels(struct lttng_trigger *trigger,
-               struct notification_thread_state *state)
+static int bind_trigger_to_matching_channels(struct lttng_trigger *trigger,
+                                            struct notification_thread_state *state)
 {
        int ret = 0;
        struct cds_lfht_node *node;
@@ -2621,8 +2467,7 @@ int bind_trigger_to_matching_channels(struct lttng_trigger *trigger,
 
        ASSERT_RCU_READ_LOCKED();
 
-       cds_lfht_for_each_entry(state->channels_ht, &iter, channel,
-                       channels_ht_node) {
+       cds_lfht_for_each_entry (state->channels_ht, &iter, channel, channels_ht_node) {
                struct lttng_trigger_list_element *trigger_list_element;
                struct lttng_channel_trigger_list *trigger_list;
                struct cds_lfht_iter lookup_iter;
@@ -2638,9 +2483,8 @@ int bind_trigger_to_matching_channels(struct lttng_trigger *trigger,
                                &lookup_iter);
                node = cds_lfht_iter_get_node(&lookup_iter);
                LTTNG_ASSERT(node);
-               trigger_list = caa_container_of(node,
-                               struct lttng_channel_trigger_list,
-                               channel_triggers_ht_node);
+               trigger_list = caa_container_of(
+                       node, struct lttng_channel_trigger_list, channel_triggers_ht_node);
 
                trigger_list_element = zmalloc<lttng_trigger_list_element>();
                if (!trigger_list_element) {
@@ -2650,21 +2494,16 @@ int bind_trigger_to_matching_channels(struct lttng_trigger *trigger,
                CDS_INIT_LIST_HEAD(&trigger_list_element->node);
                trigger_list_element->trigger = trigger;
                cds_list_add(&trigger_list_element->node, &trigger_list->list);
-               DBG("Newly registered trigger bound to channel \"%s\"",
-                               channel->name);
+               DBG("Newly registered trigger bound to channel \"%s\"", channel->name);
        }
 end:
        return ret;
 }
 
-static
-bool is_trigger_action_notify(const struct lttng_trigger *trigger)
+static bool is_trigger_action_notify(const struct lttng_trigger *trigger)
 {
        bool is_notify = false;
-       unsigned int i, count;
-       enum lttng_action_status action_status;
-       const struct lttng_action *action =
-                       lttng_trigger_get_const_action(trigger);
+       const struct lttng_action *action = lttng_trigger_get_const_action(trigger);
        enum lttng_action_type action_type;
 
        LTTNG_ASSERT(action);
@@ -2676,16 +2515,8 @@ bool is_trigger_action_notify(const struct lttng_trigger *trigger)
                goto end;
        }
 
-       action_status = lttng_action_list_get_count(action, &count);
-       LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
-
-       for (i = 0; i < count; i++) {
-               const struct lttng_action *inner_action =
-                               lttng_action_list_get_at_index(
-                                               action, i);
-
-               action_type = lttng_action_get_type(inner_action);
-               if (action_type == LTTNG_ACTION_TYPE_NOTIFY) {
+       for (auto inner_action : lttng::ctl::const_action_list_view(action)) {
+               if (lttng_action_get_type(inner_action) == LTTNG_ACTION_TYPE_NOTIFY) {
                        is_notify = true;
                        goto end;
                }
@@ -2696,7 +2527,7 @@ end:
 }
 
 static bool trigger_name_taken(struct notification_thread_state *state,
-               const struct lttng_trigger *trigger)
+                              const struct lttng_trigger *trigger)
 {
        struct cds_lfht_iter iter;
 
@@ -2712,18 +2543,17 @@ static bool trigger_name_taken(struct notification_thread_state *state,
        return !!cds_lfht_iter_get_node(&iter);
 }
 
-static
-enum lttng_error_code generate_trigger_name(
-               struct notification_thread_state *state,
-               struct lttng_trigger *trigger, const char **name)
+static enum lttng_error_code generate_trigger_name(struct notification_thread_state *state,
+                                                  struct lttng_trigger *trigger,
+                                                  const char **name)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
        bool taken = false;
        enum lttng_trigger_status status;
 
        do {
-               const int ret = lttng_trigger_generate_name(trigger,
-                               state->trigger_id.name_offset++);
+               const int ret =
+                       lttng_trigger_generate_name(trigger, state->trigger_id.name_offset++);
                if (ret) {
                        /* The only reason this can fail right now. */
                        ret_code = LTTNG_ERR_NOMEM;
@@ -2739,10 +2569,9 @@ enum lttng_error_code generate_trigger_name(
        return ret_code;
 }
 
-static inline
-void notif_thread_state_remove_trigger_ht_elem(
-               struct notification_thread_state *state,
-               struct lttng_trigger_ht_element *trigger_ht_element)
+static inline void
+notif_thread_state_remove_trigger_ht_elem(struct notification_thread_state *state,
+                                         struct lttng_trigger_ht_element *trigger_ht_element)
 {
        LTTNG_ASSERT(state);
        LTTNG_ASSERT(trigger_ht_element);
@@ -2751,17 +2580,15 @@ void notif_thread_state_remove_trigger_ht_elem(
        cds_lfht_del(state->triggers_by_name_uid_ht, &trigger_ht_element->node_by_name_uid);
 }
 
-static
-enum lttng_error_code setup_tracer_notifier(
-               struct notification_thread_state *state,
-               struct lttng_trigger *trigger)
+static enum lttng_error_code setup_tracer_notifier(struct notification_thread_state *state,
+                                                  struct lttng_trigger *trigger)
 {
        enum lttng_error_code ret;
        enum event_notifier_error_accounting_status error_accounting_status;
        struct cds_lfht_node *node;
        uint64_t error_counter_index = 0;
        struct lttng_condition *condition = lttng_trigger_get_condition(trigger);
-       struct notification_trigger_tokens_ht_element *trigger_tokens_ht_element = NULL;
+       struct notification_trigger_tokens_ht_element *trigger_tokens_ht_element = nullptr;
 
        trigger_tokens_ht_element = zmalloc<notification_trigger_tokens_ht_element>();
        if (!trigger_tokens_ht_element) {
@@ -2775,19 +2602,20 @@ enum lttng_error_code setup_tracer_notifier(
        trigger_tokens_ht_element->trigger = trigger;
 
        node = cds_lfht_add_unique(state->trigger_tokens_ht,
-                       hash_key_u64(&trigger_tokens_ht_element->token, lttng_ht_seed),
-                       match_trigger_token,
-                       &trigger_tokens_ht_element->token,
-                       &trigger_tokens_ht_element->node);
+                                  hash_key_u64(&trigger_tokens_ht_element->token, lttng_ht_seed),
+                                  match_trigger_token,
+                                  &trigger_tokens_ht_element->token,
+                                  &trigger_tokens_ht_element->node);
        if (node != &trigger_tokens_ht_element->node) {
                ret = LTTNG_ERR_TRIGGER_EXISTS;
                goto error_free_ht_element;
        }
 
        error_accounting_status = event_notifier_error_accounting_register_event_notifier(
-                       trigger, &error_counter_index);
+               trigger, &error_counter_index);
        if (error_accounting_status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
-               if (error_accounting_status == EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NO_INDEX_AVAILABLE) {
+               if (error_accounting_status ==
+                   EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_NO_INDEX_AVAILABLE) {
                        DBG("Trigger list error accounting counter full.");
                        ret = LTTNG_ERR_EVENT_NOTIFIER_ERROR_ACCOUNTING_FULL;
                } else {
@@ -2798,8 +2626,7 @@ enum lttng_error_code setup_tracer_notifier(
                goto error_remove_ht_element;
        }
 
-       lttng_condition_event_rule_matches_set_error_counter_index(
-                       condition, error_counter_index);
+       lttng_condition_event_rule_matches_set_error_counter_index(condition, error_counter_index);
 
        ret = LTTNG_OK;
        goto end;
@@ -2827,39 +2654,35 @@ end:
  * If a non-fatal error occurs, just set the cmd_result to the appropriate
  * error code.
  */
-static
-int handle_notification_thread_command_register_trigger(
-               struct notification_thread_state *state,
-               struct lttng_trigger *trigger,
-               bool is_trigger_anonymous,
-               enum lttng_error_code *cmd_result)
+static int
+handle_notification_thread_command_register_trigger(struct notification_thread_state *state,
+                                                   struct lttng_trigger *trigger,
+                                                   bool is_trigger_anonymous,
+                                                   enum lttng_error_code *cmd_result)
 {
        int ret = 0;
        struct lttng_condition *condition;
-       struct notification_client_list *client_list = NULL;
-       struct lttng_trigger_ht_element *trigger_ht_element = NULL;
+       struct notification_client_list *client_list = nullptr;
+       struct lttng_trigger_ht_element *trigger_ht_element = nullptr;
        struct cds_lfht_node *node;
-       const chartrigger_name;
+       const char *trigger_name;
        bool free_trigger = true;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
        struct lttng_credentials object_creds;
        uid_t object_uid;
        gid_t object_gid;
        enum action_executor_status executor_status;
-       const uint64_t trigger_tracer_token =
-                       state->trigger_id.next_tracer_token++;
+       const uint64_t trigger_tracer_token = state->trigger_id.next_tracer_token++;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Set the trigger's tracer token. */
        lttng_trigger_set_tracer_token(trigger, trigger_tracer_token);
 
        if (!is_trigger_anonymous) {
-               if (lttng_trigger_get_name(trigger, &trigger_name) ==
-                               LTTNG_TRIGGER_STATUS_UNSET) {
+               if (lttng_trigger_get_name(trigger, &trigger_name) == LTTNG_TRIGGER_STATUS_UNSET) {
                        const enum lttng_error_code ret_code =
-                                       generate_trigger_name(state, trigger,
-                                                       &trigger_name);
+                               generate_trigger_name(state, trigger, &trigger_name);
 
                        if (ret_code != LTTNG_OK) {
                                /* Fatal error. */
@@ -2898,10 +2721,10 @@ int handle_notification_thread_command_register_trigger(
        trigger_ht_element->trigger = trigger;
 
        node = cds_lfht_add_unique(state->triggers_ht,
-                       lttng_condition_hash(condition),
-                       match_trigger,
-                       trigger,
-                       &trigger_ht_element->node);
+                                  lttng_condition_hash(condition),
+                                  match_trigger,
+                                  trigger,
+                                  &trigger_ht_element->node);
        if (node != &trigger_ht_element->node) {
                /* Not a fatal error, simply report it to the client. */
                *cmd_result = LTTNG_ERR_TRIGGER_EXISTS;
@@ -2909,10 +2732,10 @@ int handle_notification_thread_command_register_trigger(
        }
 
        node = cds_lfht_add_unique(state->triggers_by_name_uid_ht,
-                       hash_trigger_by_name_uid(trigger),
-                       match_trigger_by_name_uid,
-                       trigger,
-                       &trigger_ht_element->node_by_name_uid);
+                                  hash_trigger_by_name_uid(trigger),
+                                  match_trigger_by_name_uid,
+                                  trigger,
+                                  &trigger_ht_element->node_by_name_uid);
        if (node != &trigger_ht_element->node_by_name_uid) {
                /* Internal error: add to triggers_ht should have failed. */
                ret = -1;
@@ -2931,8 +2754,7 @@ int handle_notification_thread_command_register_trigger(
 
                error_code = setup_tracer_notifier(state, trigger);
                if (error_code != LTTNG_OK) {
-                       notif_thread_state_remove_trigger_ht_elem(state,
-                                       trigger_ht_element);
+                       notif_thread_state_remove_trigger_ht_elem(state, trigger_ht_element);
                        if (error_code == LTTNG_ERR_NOMEM) {
                                ret = -1;
                        } else {
@@ -2963,7 +2785,8 @@ int handle_notification_thread_command_register_trigger(
                         */
                        client_list = notification_client_list_create(state, condition);
                        if (!client_list) {
-                               ERR("Error creating notification client list for trigger %s", trigger->name);
+                               ERR("Error creating notification client list for trigger %s",
+                                   trigger->name);
                                ret = -1;
                                goto error_free_ht_element;
                        }
@@ -2972,7 +2795,8 @@ int handle_notification_thread_command_register_trigger(
                CDS_INIT_LIST_HEAD(&trigger_ht_element->client_list_trigger_node);
 
                pthread_mutex_lock(&client_list->lock);
-               cds_list_add(&trigger_ht_element->client_list_trigger_node, &client_list->triggers_list);
+               cds_list_add(&trigger_ht_element->client_list_trigger_node,
+                            &client_list->triggers_list);
                pthread_mutex_unlock(&client_list->lock);
        }
 
@@ -2980,7 +2804,7 @@ int handle_notification_thread_command_register_trigger(
         * Ownership of the trigger and of its wrapper was transfered to
         * the triggers_ht. Same for token ht element if necessary.
         */
-       trigger_ht_element = NULL;
+       trigger_ht_element = nullptr;
        free_trigger = false;
 
        switch (get_condition_binding_object(condition)) {
@@ -3047,7 +2871,7 @@ int handle_notification_thread_command_register_trigger(
                if (!session_info) {
                        /* Not an error, the session doesn't exist yet. */
                        DBG("Session not found while evaluating session condition during registration of trigger: session name = `%s`",
-                                       session_name);
+                           session_name);
                        ret = 0;
                        goto success;
                }
@@ -3055,14 +2879,13 @@ int handle_notification_thread_command_register_trigger(
                LTTNG_OPTIONAL_SET(&object_creds.uid, session_info->uid);
                LTTNG_OPTIONAL_SET(&object_creds.gid, session_info->gid);
 
-               ret = evaluate_session_condition(condition, session_info, NULL, &evaluation);
+               ret = evaluate_session_condition(condition, session_info, nullptr, &evaluation);
                session_info_put(session_info);
                break;
        }
        case LTTNG_OBJECT_TYPE_CHANNEL:
-               ret = evaluate_channel_condition_for_client(condition, state,
-                               &evaluation, &object_uid,
-                               &object_gid);
+               ret = evaluate_channel_condition_for_client(
+                       condition, state, &evaluation, &object_uid, &object_gid);
                LTTNG_OPTIONAL_SET(&object_creds.uid, object_uid);
                LTTNG_OPTIONAL_SET(&object_creds.gid, object_gid);
                break;
@@ -3080,8 +2903,7 @@ int handle_notification_thread_command_register_trigger(
                goto error_free_ht_element;
        }
 
-       DBG("Newly registered trigger's condition evaluated to %s",
-                       evaluation ? "true" : "false");
+       DBG("Newly registered trigger's condition evaluated to %s", evaluation ? "true" : "false");
        if (!evaluation) {
                /* Evaluation yielded nothing. Normal exit. */
                ret = 0;
@@ -3092,9 +2914,9 @@ int handle_notification_thread_command_register_trigger(
         * Ownership of `evaluation` transferred to the action executor
         * no matter the result.
         */
-       executor_status = action_executor_enqueue_trigger(state->executor,
-                       trigger, evaluation, &object_creds, client_list);
-       evaluation = NULL;
+       executor_status = action_executor_enqueue_trigger(
+               state->executor, trigger, evaluation, &object_creds, client_list);
+       evaluation = nullptr;
        switch (executor_status) {
        case ACTION_EXECUTOR_STATUS_OK:
                break;
@@ -3124,14 +2946,14 @@ int handle_notification_thread_command_register_trigger(
 success:
        *cmd_result = LTTNG_OK;
        DBG("Registered trigger: name = `%s`, tracer token = %" PRIu64,
-                       trigger_name, trigger_tracer_token);
+           trigger_name,
+           trigger_tracer_token);
        goto end;
 
 error_free_ht_element:
        if (trigger_ht_element) {
                /* Delayed removal due to RCU constraint on delete. */
-               call_rcu(&trigger_ht_element->rcu_node,
-                               free_lttng_trigger_ht_element_rcu);
+               call_rcu(&trigger_ht_element->rcu_node, free_lttng_trigger_ht_element_rcu);
        }
 error:
        if (free_trigger) {
@@ -3143,58 +2965,52 @@ error:
                lttng_trigger_destroy(trigger);
        }
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-static
-void free_lttng_trigger_ht_element_rcu(struct rcu_head *node)
+static void free_lttng_trigger_ht_element_rcu(struct rcu_head *node)
 {
-       free(caa_container_of(node, struct lttng_trigger_ht_element,
-                       rcu_node));
+       free(caa_container_of(node, struct lttng_trigger_ht_element, rcu_node));
 }
 
-static
-void free_notification_trigger_tokens_ht_element_rcu(struct rcu_head *node)
+static void free_notification_trigger_tokens_ht_element_rcu(struct rcu_head *node)
 {
-       free(caa_container_of(node, struct notification_trigger_tokens_ht_element,
-                       rcu_node));
+       free(caa_container_of(node, struct notification_trigger_tokens_ht_element, rcu_node));
 }
 
-static
-void teardown_tracer_notifier(struct notification_thread_state *state,
-               const struct lttng_trigger *trigger)
+static void teardown_tracer_notifier(struct notification_thread_state *state,
+                                    const struct lttng_trigger *trigger)
 {
        struct cds_lfht_iter iter;
        struct notification_trigger_tokens_ht_element *trigger_tokens_ht_element;
 
-       cds_lfht_for_each_entry(state->trigger_tokens_ht, &iter,
-                       trigger_tokens_ht_element, node) {
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (!lttng_trigger_is_equal(trigger,
-                                       trigger_tokens_ht_element->trigger)) {
-                       continue;
-               }
+               cds_lfht_for_each_entry (
+                       state->trigger_tokens_ht, &iter, trigger_tokens_ht_element, node) {
+                       if (!lttng_trigger_is_equal(trigger, trigger_tokens_ht_element->trigger)) {
+                               continue;
+                       }
 
-               event_notifier_error_accounting_unregister_event_notifier(
+                       event_notifier_error_accounting_unregister_event_notifier(
                                trigger_tokens_ht_element->trigger);
 
-               /* TODO talk to all app and remove it */
-               DBG("Removed trigger from tokens_ht");
-               cds_lfht_del(state->trigger_tokens_ht,
-                               &trigger_tokens_ht_element->node);
+                       /* TODO talk to all app and remove it */
+                       DBG("Removed trigger from tokens_ht");
+                       cds_lfht_del(state->trigger_tokens_ht, &trigger_tokens_ht_element->node);
 
-               call_rcu(&trigger_tokens_ht_element->rcu_node,
-                               free_notification_trigger_tokens_ht_element_rcu);
+                       call_rcu(&trigger_tokens_ht_element->rcu_node,
+                                free_notification_trigger_tokens_ht_element_rcu);
 
-               break;
+                       break;
+               }
        }
 }
 
-static
-void remove_trigger_from_session_trigger_list(
-       struct lttng_session_trigger_list *trigger_list,
-       const struct lttng_trigger *trigger)
+static void
+remove_trigger_from_session_trigger_list(struct lttng_session_trigger_list *trigger_list,
+                                        const struct lttng_trigger *trigger)
 {
        bool found = false;
        struct lttng_trigger_list_element *trigger_element, *tmp;
@@ -3214,33 +3030,28 @@ void remove_trigger_from_session_trigger_list(
 
        if (!found) {
                ERR("Failed to find trigger associated with session: session name = `%s`",
-                               trigger_list->session_name);
+                   trigger_list->session_name);
        }
 
        LTTNG_ASSERT(found);
 }
 
-static
-int handle_notification_thread_command_unregister_trigger(
-               struct notification_thread_state *state,
-               const struct lttng_trigger *trigger,
-               enum lttng_error_code *_cmd_reply)
+static int
+handle_notification_thread_command_unregister_trigger(struct notification_thread_state *state,
+                                                     const struct lttng_trigger *trigger,
+                                                     enum lttng_error_code *_cmd_reply)
 {
        struct cds_lfht_iter iter;
        struct cds_lfht_node *triggers_ht_node;
        struct notification_client_list *client_list;
-       struct lttng_trigger_ht_element *trigger_ht_element = NULL;
-       const struct lttng_condition *condition = lttng_trigger_get_const_condition(
-                       trigger);
+       struct lttng_trigger_ht_element *trigger_ht_element = nullptr;
+       const struct lttng_condition *condition = lttng_trigger_get_const_condition(trigger);
        enum lttng_error_code cmd_reply;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_lookup(state->triggers_ht,
-                       lttng_condition_hash(condition),
-                       match_trigger,
-                       trigger,
-                       &iter);
+       cds_lfht_lookup(
+               state->triggers_ht, lttng_condition_hash(condition), match_trigger, trigger, &iter);
        triggers_ht_node = cds_lfht_iter_get_node(&iter);
        if (!triggers_ht_node) {
                cmd_reply = LTTNG_ERR_TRIGGER_NOT_FOUND;
@@ -3249,8 +3060,8 @@ int handle_notification_thread_command_unregister_trigger(
                cmd_reply = LTTNG_OK;
        }
 
-       trigger_ht_element = caa_container_of(triggers_ht_node,
-                       struct lttng_trigger_ht_element, node);
+       trigger_ht_element =
+               caa_container_of(triggers_ht_node, struct lttng_trigger_ht_element, node);
 
        switch (get_condition_binding_object(condition)) {
        case LTTNG_OBJECT_TYPE_CHANNEL:
@@ -3266,12 +3077,12 @@ int handle_notification_thread_command_unregister_trigger(
                 *
                 * Iterate on all lists since we don't know the target channels' keys.
                 */
-               cds_lfht_for_each_entry(state->channel_triggers_ht, &iter, trigger_list,
-                               channel_triggers_ht_node) {
+               cds_lfht_for_each_entry (
+                       state->channel_triggers_ht, &iter, trigger_list, channel_triggers_ht_node) {
                        struct lttng_trigger_list_element *trigger_element, *tmp;
 
-                       cds_list_for_each_entry_safe(
-                                       trigger_element, tmp, &trigger_list->list, node) {
+                       cds_list_for_each_entry_safe (
+                               trigger_element, tmp, &trigger_list->list, node) {
                                if (!lttng_trigger_is_equal(trigger, trigger_element->trigger)) {
                                        continue;
                                }
@@ -3287,8 +3098,8 @@ int handle_notification_thread_command_unregister_trigger(
        }
        case LTTNG_OBJECT_TYPE_SESSION:
        {
-               auto session = get_session_info_by_name(
-                               state, get_condition_session_name(condition));
+               auto session =
+                       get_session_info_by_name(state, get_condition_session_name(condition));
 
                /* Session doesn't exist, no trigger to remove. */
                if (!session) {
@@ -3324,7 +3135,7 @@ int handle_notification_thread_command_unregister_trigger(
                /* Put new reference and the hashtable's reference. */
                notification_client_list_put(client_list);
                notification_client_list_put(client_list);
-               client_list = NULL;
+               client_list = nullptr;
        }
 
        /* Remove trigger from triggers_ht. */
@@ -3334,125 +3145,125 @@ int handle_notification_thread_command_unregister_trigger(
        lttng_trigger_destroy(trigger_ht_element->trigger);
        call_rcu(&trigger_ht_element->rcu_node, free_lttng_trigger_ht_element_rcu);
 end:
-       rcu_read_unlock();
        if (_cmd_reply) {
                *_cmd_reply = cmd_reply;
        }
        return 0;
 }
 
-static
-int pop_cmd_queue(struct notification_thread_handle *handle,
-               struct notification_thread_command **cmd)
+static notification_thread_command *pop_cmd_queue(notification_thread_handle *handle)
 {
-       int ret;
-       uint64_t counter;
+       lttng::pthread::lock_guard queue_lock(handle->cmd_queue.lock);
 
-       pthread_mutex_lock(&handle->cmd_queue.lock);
-       ret = lttng_read(handle->cmd_queue.event_fd, &counter, sizeof(counter));
-       if (ret != sizeof(counter)) {
-               ret = -1;
-               goto error_unlock;
+       uint64_t counter;
+       const auto read_ret = lttng_read(handle->cmd_queue.event_fd, &counter, sizeof(counter));
+       if (read_ret != sizeof(counter)) {
+               if (read_ret < 0) {
+                       LTTNG_THROW_POSIX("Failed to read counter value from event_fd", errno);
+               } else {
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Failed to read counter value from event_fd because of a truncated read: ret={}, expected read size={}",
+                               read_ret,
+                               sizeof(counter)));
+               }
        }
 
-       *cmd = cds_list_first_entry(&handle->cmd_queue.list,
-                       struct notification_thread_command, cmd_list_node);
-       cds_list_del(&((*cmd)->cmd_list_node));
-       ret = 0;
-
-error_unlock:
-       pthread_mutex_unlock(&handle->cmd_queue.lock);
-       return ret;
+       auto command = cds_list_first_entry(
+               &handle->cmd_queue.list, struct notification_thread_command, cmd_list_node);
+       cds_list_del(&((command)->cmd_list_node));
+       return command;
 }
 
 /* Returns 0 on success, 1 on exit requested, negative value on error. */
-int handle_notification_thread_command(
-               struct notification_thread_handle *handle,
-               struct notification_thread_state *state)
+int handle_notification_thread_command(struct notification_thread_handle *handle,
+                                      struct notification_thread_state *state)
 {
        int ret;
-       struct notification_thread_command *cmd;
+       struct notification_thread_command *cmd = nullptr;
 
-       ret = pop_cmd_queue(handle, &cmd);
-       if (ret) {
+       try {
+               cmd = pop_cmd_queue(handle);
+       } catch (const std::exception& ex) {
+               ERR("Failed to get next notification thread command: %s", ex.what());
                goto error;
        }
 
-       DBG("Received `%s` command",
-                       notification_command_type_str(cmd->type));
+       DBG("Received `%s` command", notification_command_type_str(cmd->type));
        switch (cmd->type) {
        case NOTIFICATION_COMMAND_TYPE_REGISTER_TRIGGER:
-               ret = handle_notification_thread_command_register_trigger(state,
-                               cmd->parameters.register_trigger.trigger,
-                               cmd->parameters.register_trigger.is_trigger_anonymous,
-                               &cmd->reply_code);
+               ret = handle_notification_thread_command_register_trigger(
+                       state,
+                       cmd->parameters.register_trigger.trigger,
+                       cmd->parameters.register_trigger.is_trigger_anonymous,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_UNREGISTER_TRIGGER:
                ret = handle_notification_thread_command_unregister_trigger(
-                               state,
-                               cmd->parameters.unregister_trigger.trigger,
-                               &cmd->reply_code);
+                       state, cmd->parameters.unregister_trigger.trigger, &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_ADD_CHANNEL:
                ret = handle_notification_thread_command_add_channel(
-                               state,
-                               cmd->parameters.add_channel.session.id,
-                               cmd->parameters.add_channel.channel.name,
-                               cmd->parameters.add_channel.channel.domain,
-                               cmd->parameters.add_channel.channel.key,
-                               cmd->parameters.add_channel.channel.capacity,
-                               &cmd->reply_code);
+                       state,
+                       cmd->parameters.add_channel.session.id,
+                       cmd->parameters.add_channel.channel.name,
+                       cmd->parameters.add_channel.channel.domain,
+                       cmd->parameters.add_channel.channel.key,
+                       cmd->parameters.add_channel.channel.capacity,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_REMOVE_CHANNEL:
                ret = handle_notification_thread_command_remove_channel(
-                               state, cmd->parameters.remove_channel.key,
-                               cmd->parameters.remove_channel.domain,
-                               &cmd->reply_code);
+                       state,
+                       cmd->parameters.remove_channel.key,
+                       cmd->parameters.remove_channel.domain,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_ADD_SESSION:
-               ret = handle_notification_thread_command_add_session(state,
-                               cmd->parameters.add_session.session_id,
-                               cmd->parameters.add_session.session_name,
-                               cmd->parameters.add_session.session_uid,
-                               cmd->parameters.add_session.session_gid, &cmd->reply_code);
+               ret = handle_notification_thread_command_add_session(
+                       state,
+                       cmd->parameters.add_session.session_id,
+                       cmd->parameters.add_session.session_name,
+                       cmd->parameters.add_session.session_uid,
+                       cmd->parameters.add_session.session_gid,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_REMOVE_SESSION:
                ret = handle_notification_thread_command_remove_session(
-                               state, cmd->parameters.remove_session.session_id, &cmd->reply_code);
+                       state, cmd->parameters.remove_session.session_id, &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_ONGOING:
        case NOTIFICATION_COMMAND_TYPE_SESSION_ROTATION_COMPLETED:
                ret = handle_notification_thread_command_session_rotation(
-                               state,
-                               cmd->type,
-                               cmd->parameters.session_rotation.session_id,
-                               cmd->parameters.session_rotation.trace_archive_chunk_id,
-                               cmd->parameters.session_rotation.location,
-                               &cmd->reply_code);
+                       state,
+                       cmd->type,
+                       cmd->parameters.session_rotation.session_id,
+                       cmd->parameters.session_rotation.trace_archive_chunk_id,
+                       cmd->parameters.session_rotation.location,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_ADD_TRACER_EVENT_SOURCE:
                ret = handle_notification_thread_command_add_tracer_event_source(
-                               state,
-                               cmd->parameters.tracer_event_source.tracer_event_source_fd,
-                               cmd->parameters.tracer_event_source.domain,
-                               &cmd->reply_code);
+                       state,
+                       cmd->parameters.tracer_event_source.tracer_event_source_fd,
+                       cmd->parameters.tracer_event_source.domain,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_REMOVE_TRACER_EVENT_SOURCE:
                ret = handle_notification_thread_command_remove_tracer_event_source(
-                               state,
-                               cmd->parameters.tracer_event_source.tracer_event_source_fd,
-                               &cmd->reply_code);
+                       state,
+                       cmd->parameters.tracer_event_source.tracer_event_source_fd,
+                       &cmd->reply_code);
                break;
        case NOTIFICATION_COMMAND_TYPE_LIST_TRIGGERS:
        {
-               struct lttng_triggers *triggers = NULL;
+               struct lttng_triggers *triggers = nullptr;
 
                ret = handle_notification_thread_command_list_triggers(
-                               handle,
-                               state,
-                               cmd->parameters.list_triggers.uid,
-                               &triggers,
-                               &cmd->reply_code);
+                       handle,
+                       state,
+                       cmd->parameters.list_triggers.uid,
+                       &triggers,
+                       &cmd->reply_code);
                cmd->reply.list_triggers.triggers = triggers;
                ret = 0;
                break;
@@ -3463,24 +3274,22 @@ int handle_notification_thread_command(
                goto end;
        case NOTIFICATION_COMMAND_TYPE_GET_TRIGGER:
        {
-               struct lttng_trigger *trigger = NULL;
+               struct lttng_trigger *trigger = nullptr;
 
-               ret = handle_notification_thread_command_get_trigger(state,
-                               cmd->parameters.get_trigger.trigger, &trigger,
-                               &cmd->reply_code);
+               ret = handle_notification_thread_command_get_trigger(
+                       state, cmd->parameters.get_trigger.trigger, &trigger, &cmd->reply_code);
                cmd->reply.get_trigger.trigger = trigger;
                break;
        }
        case NOTIFICATION_COMMAND_TYPE_CLIENT_COMMUNICATION_UPDATE:
        {
                const enum client_transmission_status client_status =
-                               cmd->parameters.client_communication_update
-                                               .status;
+                       cmd->parameters.client_communication_update.status;
                const notification_client_id client_id =
-                               cmd->parameters.client_communication_update.id;
+                       cmd->parameters.client_communication_update.id;
                struct notification_client *client;
 
-               rcu_read_lock();
+               lttng::urcu::read_lock_guard read_lock;
                client = get_client_from_id(client_id, state);
 
                if (!client) {
@@ -3490,13 +3299,11 @@ int handle_notification_thread_command(
                         * gracefully while this command was queued.
                         */
                        DBG("Failed to find notification client to update communication status, client id = %" PRIu64,
-                                       client_id);
+                           client_id);
                        ret = 0;
                } else {
-                       ret = client_handle_transmission_status(
-                                       client, client_status, state);
+                       ret = client_handle_transmission_status(client, client_status, state);
                }
-               rcu_read_unlock();
                break;
        }
        default:
@@ -3507,25 +3314,29 @@ int handle_notification_thread_command(
        if (ret) {
                goto error_unlock;
        }
+
 end:
-       if (cmd->is_async) {
-               free(cmd);
-               cmd = NULL;
-       } else {
-               lttng_waiter_wake_up(&cmd->reply_waiter);
+       if (cmd) {
+               if (cmd->is_async) {
+                       delete cmd;
+                       cmd = nullptr;
+               } else {
+                       cmd->command_completed_waker->wake();
+               }
        }
+
        return ret;
+
 error_unlock:
        /* Wake-up and return a fatal error to the calling thread. */
-       lttng_waiter_wake_up(&cmd->reply_waiter);
        cmd->reply_code = LTTNG_ERR_FATAL;
+
 error:
-       /* Indicate a fatal error to the caller. */
-       return -1;
+       ret = -1;
+       goto end;
 }
 
-static
-int socket_set_non_blocking(int socket)
+static int socket_set_non_blocking(int socket)
 {
        int ret, flags;
 
@@ -3547,29 +3358,24 @@ end:
        return ret;
 }
 
-static
-int client_reset_inbound_state(struct notification_client *client)
+static int client_reset_inbound_state(struct notification_client *client)
 {
        int ret;
 
-
        lttng_payload_clear(&client->communication.inbound.payload);
 
        client->communication.inbound.bytes_to_receive =
-                       sizeof(struct lttng_notification_channel_message);
-       client->communication.inbound.msg_type =
-                       LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNKNOWN;
+               sizeof(struct lttng_notification_channel_message);
+       client->communication.inbound.msg_type = LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNKNOWN;
        LTTNG_SOCK_SET_UID_CRED(&client->communication.inbound.creds, -1);
        LTTNG_SOCK_SET_GID_CRED(&client->communication.inbound.creds, -1);
-       ret = lttng_dynamic_buffer_set_size(
-                       &client->communication.inbound.payload.buffer,
-                       client->communication.inbound.bytes_to_receive);
+       ret = lttng_dynamic_buffer_set_size(&client->communication.inbound.payload.buffer,
+                                           client->communication.inbound.bytes_to_receive);
 
        return ret;
 }
 
-int handle_notification_thread_client_connect(
-               struct notification_thread_state *state)
+int handle_notification_thread_client_connect(struct notification_thread_state *state)
 {
        int ret;
        struct notification_client *client;
@@ -3583,7 +3389,7 @@ int handle_notification_thread_client_connect(
                goto error;
        }
 
-       pthread_mutex_init(&client->lock, NULL);
+       pthread_mutex_init(&client->lock, nullptr);
        client->id = state->next_notification_client_id++;
        CDS_INIT_LIST_HEAD(&client->condition_list);
        lttng_payload_init(&client->communication.inbound.payload);
@@ -3620,24 +3426,25 @@ int handle_notification_thread_client_connect(
        }
 
        client->communication.current_poll_events = CLIENT_POLL_EVENTS_IN;
-       ret = lttng_poll_add(&state->events, client->socket,
-                       client->communication.current_poll_events);
+       ret = lttng_poll_add(
+               &state->events, client->socket, client->communication.current_poll_events);
        if (ret < 0) {
                ERR("Failed to add notification channel client socket to poll set");
                ret = 0;
                goto error;
        }
-       DBG("Added new notification channel client socket (%i) to poll set",
-                       client->socket);
+       DBG("Added new notification channel client socket (%i) to poll set", client->socket);
 
-       rcu_read_lock();
-       cds_lfht_add(state->client_socket_ht,
-                       hash_client_socket(client->socket),
-                       &client->client_socket_ht_node);
-       cds_lfht_add(state->client_id_ht,
-                       hash_client_id(client->id),
-                       &client->client_id_ht_node);
-       rcu_read_unlock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_add(state->client_socket_ht,
+                            hash_client_socket(client->socket),
+                            &client->client_socket_ht_node);
+               cds_lfht_add(state->client_id_ht,
+                            hash_client_id(client->id),
+                            &client->client_id_ht_node);
+       }
 
        return ret;
 
@@ -3650,10 +3457,8 @@ error:
  * RCU read-lock must be held by the caller.
  * Client lock must _not_ be held by the caller.
  */
-static
-int notification_thread_client_disconnect(
-               struct notification_client *client,
-               struct notification_thread_state *state)
+static int notification_thread_client_disconnect(struct notification_client *client,
+                                                struct notification_thread_state *state)
 {
        int ret;
        struct lttng_condition_list_element *condition_list_element, *tmp;
@@ -3669,15 +3474,13 @@ int notification_thread_client_disconnect(
 
        ret = lttng_poll_del(&state->events, client->socket);
        if (ret) {
-               ERR("Failed to remove client socket %d from poll set",
-                               client->socket);
+               ERR("Failed to remove client socket %d from poll set", client->socket);
        }
 
        /* Release all conditions to which the client was subscribed. */
-       cds_list_for_each_entry_safe(condition_list_element, tmp,
-                       &client->condition_list, node) {
-               (void) notification_thread_client_unsubscribe(client,
-                               condition_list_element->condition, state, NULL);
+       cds_list_for_each_entry_safe (condition_list_element, tmp, &client->condition_list, node) {
+               (void) notification_thread_client_unsubscribe(
+                       client, condition_list_element->condition, state, nullptr);
        }
 
        /*
@@ -3688,90 +3491,83 @@ int notification_thread_client_disconnect(
        return ret;
 }
 
-int handle_notification_thread_client_disconnect(
-               int client_socket, struct notification_thread_state *state)
+int handle_notification_thread_client_disconnect(int client_socket,
+                                                struct notification_thread_state *state)
 {
        int ret = 0;
        struct notification_client *client;
 
-       rcu_read_lock();
-       DBG("Closing client connection (socket fd = %i)",
-                       client_socket);
+       lttng::urcu::read_lock_guard read_lock;
+
+       DBG("Closing client connection (socket fd = %i)", client_socket);
        client = get_client_from_socket(client_socket, state);
        if (!client) {
                /* Internal state corruption, fatal error. */
-               ERR("Unable to find client (socket fd = %i)",
-                               client_socket);
+               ERR("Unable to find client (socket fd = %i)", client_socket);
                ret = -1;
                goto end;
        }
 
        ret = notification_thread_client_disconnect(client, state);
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-int handle_notification_thread_client_disconnect_all(
-               struct notification_thread_state *state)
+int handle_notification_thread_client_disconnect_all(struct notification_thread_state *state)
 {
        struct cds_lfht_iter iter;
        struct notification_client *client;
        bool error_encoutered = false;
 
-       rcu_read_lock();
        DBG("Closing all client connections");
-       cds_lfht_for_each_entry(state->client_socket_ht, &iter, client,
-                       client_socket_ht_node) {
-               int ret;
 
-               ret = notification_thread_client_disconnect(
-                               client, state);
-               if (ret) {
-                       error_encoutered = true;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       state->client_socket_ht, &iter, client, client_socket_ht_node) {
+                       int ret;
+
+                       ret = notification_thread_client_disconnect(client, state);
+                       if (ret) {
+                               error_encoutered = true;
+                       }
                }
        }
-       rcu_read_unlock();
+
        return error_encoutered ? 1 : 0;
 }
 
-int handle_notification_thread_trigger_unregister_all(
-               struct notification_thread_state *state)
+int handle_notification_thread_trigger_unregister_all(struct notification_thread_state *state)
 {
        bool error_occurred = false;
        struct cds_lfht_iter iter;
        struct lttng_trigger_ht_element *trigger_ht_element;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(state->triggers_ht, &iter, trigger_ht_element,
-                       node) {
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_for_each_entry (state->triggers_ht, &iter, trigger_ht_element, node) {
                int ret = handle_notification_thread_command_unregister_trigger(
-                               state, trigger_ht_element->trigger, NULL);
+                       state, trigger_ht_element->trigger, nullptr);
                if (ret) {
                        error_occurred = true;
                }
        }
-       rcu_read_unlock();
        return error_occurred ? -1 : 0;
 }
 
-static
-bool client_has_outbound_data_left(
-               const struct notification_client *client)
+static bool client_has_outbound_data_left(const struct notification_client *client)
 {
-       const struct lttng_payload_view pv = lttng_payload_view_from_payload(
-                       &client->communication.outbound.payload, 0, -1);
+       const struct lttng_payload_view pv =
+               lttng_payload_view_from_payload(&client->communication.outbound.payload, 0, -1);
        const bool has_data = pv.buffer.size != 0;
        const bool has_fds = lttng_payload_view_get_fd_handle_count(&pv);
 
        return has_data || has_fds;
 }
 
-static
-int client_handle_transmission_status(
-               struct notification_client *client,
-               enum client_transmission_status transmission_status,
-               struct notification_thread_state *state)
+static int client_handle_transmission_status(struct notification_client *client,
+                                            enum client_transmission_status transmission_status,
+                                            struct notification_thread_state *state)
 {
        int ret = 0;
 
@@ -3806,15 +3602,14 @@ int client_handle_transmission_status(
                pthread_mutex_lock(&client->lock);
                current_poll_events = client->communication.current_poll_events;
                new_poll_events = client_has_outbound_data_left(client) ?
-                               CLIENT_POLL_EVENTS_IN_OUT :
-                                     CLIENT_POLL_EVENTS_IN;
+                       CLIENT_POLL_EVENTS_IN_OUT :
+                       CLIENT_POLL_EVENTS_IN;
                client->communication.current_poll_events = new_poll_events;
                pthread_mutex_unlock(&client->lock);
 
                /* Update the monitored event set only if it changed. */
                if (current_poll_events != new_poll_events) {
-                       ret = lttng_poll_mod(&state->events, client->socket,
-                                       new_poll_events);
+                       ret = lttng_poll_mod(&state->events, client->socket, new_poll_events);
                        if (ret) {
                                goto end;
                        }
@@ -3839,17 +3634,15 @@ end:
 }
 
 /* Client lock must be acquired by caller. */
-static
-enum client_transmission_status client_flush_outgoing_queue(
-               struct notification_client *client)
+static enum client_transmission_status
+client_flush_outgoing_queue(struct notification_client *client)
 {
        ssize_t ret;
        size_t to_send_count;
        enum client_transmission_status status;
-       struct lttng_payload_view pv = lttng_payload_view_from_payload(
-                       &client->communication.outbound.payload, 0, -1);
-       const int fds_to_send_count =
-                       lttng_payload_view_get_fd_handle_count(&pv);
+       struct lttng_payload_view pv =
+               lttng_payload_view_from_payload(&client->communication.outbound.payload, 0, -1);
+       const int fds_to_send_count = lttng_payload_view_get_fd_handle_count(&pv);
 
        ASSERT_LOCKED(client->lock);
 
@@ -3869,24 +3662,19 @@ enum client_transmission_status client_flush_outgoing_queue(
 
        /* Send data. */
        to_send_count = pv.buffer.size;
-       DBG("Flushing client (socket fd = %i) outgoing queue",
-                       client->socket);
+       DBG("Flushing client (socket fd = %i) outgoing queue", client->socket);
 
-       ret = lttcomm_send_unix_sock_non_block(client->socket,
-                       pv.buffer.data,
-                       to_send_count);
+       ret = lttcomm_send_unix_sock_non_block(client->socket, pv.buffer.data, to_send_count);
        if ((ret >= 0 && ret < to_send_count)) {
                DBG("Client (socket fd = %i) outgoing queue could not be completely flushed",
-                               client->socket);
+                   client->socket);
                to_send_count -= std::max(ret, (ssize_t) 0);
 
                memmove(client->communication.outbound.payload.buffer.data,
-                               pv.buffer.data +
-                               pv.buffer.size - to_send_count,
-                               to_send_count);
-               ret = lttng_dynamic_buffer_set_size(
-                               &client->communication.outbound.payload.buffer,
-                               to_send_count);
+                       pv.buffer.data + pv.buffer.size - to_send_count,
+                       to_send_count);
+               ret = lttng_dynamic_buffer_set_size(&client->communication.outbound.payload.buffer,
+                                                   to_send_count);
                if (ret) {
                        goto error;
                }
@@ -3896,7 +3684,7 @@ enum client_transmission_status client_flush_outgoing_queue(
        } else if (ret < 0) {
                /* Generic error, disable the client's communication. */
                ERR("Failed to flush outgoing queue, disconnecting client (socket fd = %i)",
-                               client->socket);
+                   client->socket);
                client->communication.active = false;
                status = CLIENT_TRANSMISSION_STATUS_FAIL;
                goto end;
@@ -3909,8 +3697,8 @@ enum client_transmission_status client_flush_outgoing_queue(
                 * direct caller knows that the transmission is complete, we
                 * need to set the buffer size to zero.
                 */
-               ret = lttng_dynamic_buffer_set_size(
-                               &client->communication.outbound.payload.buffer, 0);
+               ret = lttng_dynamic_buffer_set_size(&client->communication.outbound.payload.buffer,
+                                                   0);
                if (ret) {
                        goto error;
                }
@@ -3923,12 +3711,11 @@ send_fds:
                goto end;
        }
 
-       ret = lttcomm_send_payload_view_fds_unix_sock_non_block(
-                       client->socket, &pv);
+       ret = lttcomm_send_payload_view_fds_unix_sock_non_block(client->socket, &pv);
        if (ret < 0) {
                /* Generic error, disable the client's communication. */
                ERR("Failed to flush outgoing fds queue, disconnecting client (socket fd = %i)",
-                               client->socket);
+                   client->socket);
                client->communication.active = false;
                status = CLIENT_TRANSMISSION_STATUS_FAIL;
                goto end;
@@ -3945,8 +3732,7 @@ send_fds:
                 * need to clear the _fd_array for the queuing check.
                 */
                lttng_dynamic_pointer_array_clear(
-                               &client->communication.outbound.payload
-                                                ._fd_handles);
+                       &client->communication.outbound.payload._fd_handles);
        }
 
 end:
@@ -3962,10 +3748,9 @@ error:
 }
 
 /* Client lock must _not_ be held by the caller. */
-static
-int client_send_command_reply(struct notification_client *client,
-               struct notification_thread_state *state,
-               enum lttng_notification_channel_status status)
+static int client_send_command_reply(struct notification_client *client,
+                                    struct notification_thread_state *state,
+                                    enum lttng_notification_channel_status status)
 {
        int ret;
        struct lttng_notification_channel_command_reply reply = {
@@ -3991,8 +3776,7 @@ int client_send_command_reply(struct notification_client *client,
 
        /* Enqueue buffer to outgoing queue and flush it. */
        ret = lttng_dynamic_buffer_append(
-                       &client->communication.outbound.payload.buffer,
-                       buffer, sizeof(buffer));
+               &client->communication.outbound.payload.buffer, buffer, sizeof(buffer));
        if (ret) {
                goto error_unlock;
        }
@@ -4005,8 +3789,7 @@ int client_send_command_reply(struct notification_client *client,
        }
 
        pthread_mutex_unlock(&client->lock);
-       ret = client_handle_transmission_status(
-                       client, transmission_status, state);
+       ret = client_handle_transmission_status(client, transmission_status, state);
        if (ret) {
                goto error;
        }
@@ -4018,9 +3801,9 @@ error:
        return -1;
 }
 
-static
-int client_handle_message_unknown(struct notification_client *client,
-               struct notification_thread_state *state __attribute__((unused)))
+static int client_handle_message_unknown(struct notification_client *client,
+                                        struct notification_thread_state *state
+                                        __attribute__((unused)))
 {
        int ret;
        /*
@@ -4032,12 +3815,10 @@ int client_handle_message_unknown(struct notification_client *client,
 
        LTTNG_ASSERT(sizeof(*msg) == client->communication.inbound.payload.buffer.size);
        msg = (const struct lttng_notification_channel_message *)
-                             client->communication.inbound.payload.buffer.data;
+                     client->communication.inbound.payload.buffer.data;
 
-       if (msg->size == 0 ||
-                       msg->size > DEFAULT_MAX_NOTIFICATION_CLIENT_MESSAGE_PAYLOAD_SIZE) {
-               ERR("Invalid notification channel message: length = %u",
-                               msg->size);
+       if (msg->size == 0 || msg->size > DEFAULT_MAX_NOTIFICATION_CLIENT_MESSAGE_PAYLOAD_SIZE) {
+               ERR("Invalid notification channel message: length = %u", msg->size);
                ret = -1;
                goto end;
        }
@@ -4056,29 +3837,27 @@ int client_handle_message_unknown(struct notification_client *client,
        client->communication.inbound.bytes_to_receive = msg->size;
        client->communication.inbound.fds_to_receive = msg->fds;
        client->communication.inbound.msg_type =
-                       (enum lttng_notification_channel_message_type) msg->type;
-       ret = lttng_dynamic_buffer_set_size(
-                       &client->communication.inbound.payload.buffer, msg->size);
+               (enum lttng_notification_channel_message_type) msg->type;
+       ret = lttng_dynamic_buffer_set_size(&client->communication.inbound.payload.buffer,
+                                           msg->size);
 
        /* msg is not valid anymore due to lttng_dynamic_buffer_set_size. */
-       msg = NULL;
+       msg = nullptr;
 end:
        return ret;
 }
 
-static
-int client_handle_message_handshake(struct notification_client *client,
-               struct notification_thread_state *state)
+static int client_handle_message_handshake(struct notification_client *client,
+                                          struct notification_thread_state *state)
 {
        int ret;
        struct lttng_notification_channel_command_handshake *handshake_client;
        const struct lttng_notification_channel_command_handshake handshake_reply = {
-                       .major = LTTNG_NOTIFICATION_CHANNEL_VERSION_MAJOR,
-                       .minor = LTTNG_NOTIFICATION_CHANNEL_VERSION_MINOR,
+               .major = LTTNG_NOTIFICATION_CHANNEL_VERSION_MAJOR,
+               .minor = LTTNG_NOTIFICATION_CHANNEL_VERSION_MINOR,
        };
        struct lttng_notification_channel_message msg_header;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        char send_buffer[sizeof(msg_header) + sizeof(handshake_reply)];
 
        msg_header.type = LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_HANDSHAKE;
@@ -4086,13 +3865,10 @@ int client_handle_message_handshake(struct notification_client *client,
        msg_header.fds = 0;
 
        memcpy(send_buffer, &msg_header, sizeof(msg_header));
-       memcpy(send_buffer + sizeof(msg_header), &handshake_reply,
-                       sizeof(handshake_reply));
+       memcpy(send_buffer + sizeof(msg_header), &handshake_reply, sizeof(handshake_reply));
 
-       handshake_client =
-                       (struct lttng_notification_channel_command_handshake *)
-                                       client->communication.inbound.payload.buffer
-                                                       .data;
+       handshake_client = (struct lttng_notification_channel_command_handshake *)
+                                  client->communication.inbound.payload.buffer.data;
        client->major = handshake_client->major;
        client->minor = handshake_client->minor;
        if (!client->communication.inbound.creds_received) {
@@ -4101,26 +3877,25 @@ int client_handle_message_handshake(struct notification_client *client,
                goto end;
        }
 
-       client->uid = LTTNG_SOCK_GET_UID_CRED(
-                       &client->communication.inbound.creds);
-       client->gid = LTTNG_SOCK_GET_GID_CRED(
-                       &client->communication.inbound.creds);
-       client->is_sessiond = LTTNG_SOCK_GET_PID_CRED(&client->communication.inbound.creds) == getpid();
+       client->uid = LTTNG_SOCK_GET_UID_CRED(&client->communication.inbound.creds);
+       client->gid = LTTNG_SOCK_GET_GID_CRED(&client->communication.inbound.creds);
+       client->is_sessiond = LTTNG_SOCK_GET_PID_CRED(&client->communication.inbound.creds) ==
+               getpid();
        DBG("Received handshake from client: uid = %u, gid = %u, protocol version = %i.%i, client is sessiond = %s",
-                       client->uid, client->gid, (int) client->major,
-                       (int) client->minor,
-                       client->is_sessiond ? "true" : "false");
+           client->uid,
+           client->gid,
+           (int) client->major,
+           (int) client->minor,
+           client->is_sessiond ? "true" : "false");
 
-       if (handshake_client->major !=
-                       LTTNG_NOTIFICATION_CHANNEL_VERSION_MAJOR) {
+       if (handshake_client->major != LTTNG_NOTIFICATION_CHANNEL_VERSION_MAJOR) {
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_UNSUPPORTED_VERSION;
        }
 
        pthread_mutex_lock(&client->lock);
        /* Outgoing queue will be flushed when the command reply is sent. */
        ret = lttng_dynamic_buffer_append(
-                       &client->communication.outbound.payload.buffer, send_buffer,
-                       sizeof(send_buffer));
+               &client->communication.outbound.payload.buffer, send_buffer, sizeof(send_buffer));
        if (ret) {
                ERR("Failed to send protocol version to notification channel client");
                goto end_unlock;
@@ -4151,20 +3926,15 @@ end:
        return ret;
 }
 
-static
-int client_handle_message_subscription(
-               struct notification_client *client,
-               enum lttng_notification_channel_message_type msg_type,
-               struct notification_thread_state *state)
+static int client_handle_message_subscription(struct notification_client *client,
+                                             enum lttng_notification_channel_message_type msg_type,
+                                             struct notification_thread_state *state)
 {
        int ret;
        struct lttng_condition *condition;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        struct lttng_payload_view condition_view =
-                       lttng_payload_view_from_payload(
-                                       &client->communication.inbound.payload,
-                                       0, -1);
+               lttng_payload_view_from_payload(&client->communication.inbound.payload, 0, -1);
        size_t expected_condition_size;
 
        /*
@@ -4181,11 +3951,9 @@ int client_handle_message_subscription(
 
        /* Ownership of condition is always transferred. */
        if (msg_type == LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_SUBSCRIBE) {
-               ret = notification_thread_client_subscribe(
-                               client, condition, state, &status);
+               ret = notification_thread_client_subscribe(client, condition, state, &status);
        } else {
-               ret = notification_thread_client_unsubscribe(
-                               client, condition, state, &status);
+               ret = notification_thread_client_unsubscribe(client, condition, state, &status);
        }
 
        if (ret) {
@@ -4209,17 +3977,16 @@ end:
        return ret;
 }
 
-static
-int client_dispatch_message(struct notification_client *client,
-               struct notification_thread_state *state)
+static int client_dispatch_message(struct notification_client *client,
+                                  struct notification_thread_state *state)
 {
        int ret = 0;
 
        if (client->communication.inbound.msg_type !=
-                       LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_HANDSHAKE &&
-                       client->communication.inbound.msg_type !=
-                               LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNKNOWN &&
-                       !client->validated) {
+                   LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_HANDSHAKE &&
+           client->communication.inbound.msg_type !=
+                   LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNKNOWN &&
+           !client->validated) {
                WARN("client attempted a command before handshake");
                ret = -1;
                goto end;
@@ -4239,8 +4006,8 @@ int client_dispatch_message(struct notification_client *client,
        case LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_SUBSCRIBE:
        case LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNSUBSCRIBE:
        {
-               ret = client_handle_message_subscription(client,
-                               client->communication.inbound.msg_type, state);
+               ret = client_handle_message_subscription(
+                       client, client->communication.inbound.msg_type, state);
                break;
        }
        default:
@@ -4251,15 +4018,14 @@ end:
 }
 
 /* Incoming data from client. */
-int handle_notification_thread_client_in(
-               struct notification_thread_state *state, int socket)
+int handle_notification_thread_client_in(struct notification_thread_state *state, int socket)
 {
        int ret = 0;
        struct notification_client *client;
        ssize_t recv_ret;
        size_t offset;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        client = get_client_from_socket(socket, state);
        if (!client) {
                /* Internal error, abort. */
@@ -4268,26 +4034,28 @@ int handle_notification_thread_client_in(
        }
 
        if (client->communication.inbound.bytes_to_receive == 0 &&
-                       client->communication.inbound.fds_to_receive != 0) {
+           client->communication.inbound.fds_to_receive != 0) {
                /* Only FDs left to receive. */
                goto receive_fds;
        }
 
        offset = client->communication.inbound.payload.buffer.size -
-                       client->communication.inbound.bytes_to_receive;
+               client->communication.inbound.bytes_to_receive;
        if (client->communication.inbound.expect_creds) {
-               recv_ret = lttcomm_recv_creds_unix_sock(socket,
-                               client->communication.inbound.payload.buffer.data + offset,
-                               client->communication.inbound.bytes_to_receive,
-                               &client->communication.inbound.creds);
+               recv_ret = lttcomm_recv_creds_unix_sock(
+                       socket,
+                       client->communication.inbound.payload.buffer.data + offset,
+                       client->communication.inbound.bytes_to_receive,
+                       &client->communication.inbound.creds);
                if (recv_ret > 0) {
                        client->communication.inbound.expect_creds = false;
                        client->communication.inbound.creds_received = true;
                }
        } else {
-               recv_ret = lttcomm_recv_unix_sock_non_block(socket,
-                               client->communication.inbound.payload.buffer.data + offset,
-                               client->communication.inbound.bytes_to_receive);
+               recv_ret = lttcomm_recv_unix_sock_non_block(
+                       socket,
+                       client->communication.inbound.payload.buffer.data + offset,
+                       client->communication.inbound.bytes_to_receive);
        }
        if (recv_ret >= 0) {
                client->communication.inbound.bytes_to_receive -= recv_ret;
@@ -4307,9 +4075,9 @@ receive_fds:
        /* Receive fds. */
        if (client->communication.inbound.fds_to_receive != 0) {
                ret = lttcomm_recv_payload_fds_unix_sock_non_block(
-                               client->socket,
-                               client->communication.inbound.fds_to_receive,
-                               &client->communication.inbound.payload);
+                       client->socket,
+                       client->communication.inbound.fds_to_receive,
+                       &client->communication.inbound.payload);
                if (ret > 0) {
                        /*
                         * Fds received. non blocking fds passing is all
@@ -4317,9 +4085,7 @@ receive_fds:
                         */
                        ssize_t expected_size;
 
-                       expected_size = sizeof(int) *
-                                       client->communication.inbound
-                                                       .fds_to_receive;
+                       expected_size = sizeof(int) * client->communication.inbound.fds_to_receive;
                        LTTNG_ASSERT(ret == expected_size);
                        client->communication.inbound.fds_to_receive = 0;
                } else if (ret == 0) {
@@ -4333,7 +4099,7 @@ receive_fds:
 
        /* At this point the message is complete.*/
        LTTNG_ASSERT(client->communication.inbound.bytes_to_receive == 0 &&
-                       client->communication.inbound.fds_to_receive == 0);
+                    client->communication.inbound.fds_to_receive == 0);
        ret = client_dispatch_message(client, state);
        if (ret) {
                /*
@@ -4344,7 +4110,6 @@ receive_fds:
        }
 
 end:
-       rcu_read_unlock();
        return ret;
 
 error_disconnect_client:
@@ -4353,14 +4118,13 @@ error_disconnect_client:
 }
 
 /* Client ready to receive outgoing data. */
-int handle_notification_thread_client_out(
-               struct notification_thread_state *state, int socket)
+int handle_notification_thread_client_out(struct notification_thread_state *state, int socket)
 {
        int ret;
        struct notification_client *client;
        enum client_transmission_status transmission_status;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        client = get_client_from_socket(socket, state);
        if (!client) {
                /* Internal error, abort. */
@@ -4412,26 +4176,23 @@ int handle_notification_thread_client_out(
        }
        pthread_mutex_unlock(&client->lock);
 
-       ret = client_handle_transmission_status(
-                       client, transmission_status, state);
+       ret = client_handle_transmission_status(client, transmission_status, state);
        if (ret) {
                goto end;
        }
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-static
-bool evaluate_buffer_usage_condition(const struct lttng_condition *condition,
-               const struct channel_state_sample *sample,
-               uint64_t buffer_capacity)
+static bool evaluate_buffer_usage_condition(const struct lttng_condition *condition,
+                                           const struct channel_state_sample *sample,
+                                           uint64_t buffer_capacity)
 {
        bool result = false;
        uint64_t threshold;
        enum lttng_condition_type condition_type;
-       const struct lttng_condition_buffer_usage *use_condition = lttng::utils::container_of(
-                       condition, &lttng_condition_buffer_usage::parent);
+       const struct lttng_condition_buffer_usage *use_condition =
+               lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
 
        if (use_condition->threshold_bytes.set) {
                threshold = use_condition->threshold_bytes.value;
@@ -4449,13 +4210,15 @@ bool evaluate_buffer_usage_condition(const struct lttng_condition *condition,
                 * that all channels matching my_chann* have the same size...)
                 */
                threshold = (uint64_t) (use_condition->threshold_ratio.value *
-                               (double) buffer_capacity);
+                                       (double) buffer_capacity);
        }
 
        condition_type = lttng_condition_get_type(condition);
        if (condition_type == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW) {
-               DBG("Low buffer usage condition being evaluated: threshold = %" PRIu64 ", highest usage = %" PRIu64,
-                               threshold, sample->highest_usage);
+               DBG("Low buffer usage condition being evaluated: threshold = %" PRIu64
+                   ", highest usage = %" PRIu64,
+                   threshold,
+                   sample->highest_usage);
 
                /*
                 * The low condition should only be triggered once _all_ of the
@@ -4465,8 +4228,10 @@ bool evaluate_buffer_usage_condition(const struct lttng_condition *condition,
                        result = true;
                }
        } else {
-               DBG("High buffer usage condition being evaluated: threshold = %" PRIu64 ", highest usage = %" PRIu64,
-                               threshold, sample->highest_usage);
+               DBG("High buffer usage condition being evaluated: threshold = %" PRIu64
+                   ", highest usage = %" PRIu64,
+                   threshold,
+                   sample->highest_usage);
 
                /*
                 * For high buffer usage scenarios, we want to trigger whenever
@@ -4480,13 +4245,13 @@ bool evaluate_buffer_usage_condition(const struct lttng_condition *condition,
        return result;
 }
 
-static
-int evaluate_buffer_condition(const struct lttng_condition *condition,
-               struct lttng_evaluation **evaluation,
-               const struct notification_thread_state *state __attribute__((unused)),
-               const struct channel_state_sample *previous_sample,
-               const struct channel_state_sample *latest_sample,
-               struct channel_info *channel_info)
+static int evaluate_buffer_condition(const struct lttng_condition *condition,
+                                    struct lttng_evaluation **evaluation,
+                                    const struct notification_thread_state *state
+                                    __attribute__((unused)),
+                                    const struct channel_state_sample *previous_sample,
+                                    const struct channel_state_sample *latest_sample,
+                                    struct channel_info *channel_info)
 {
        int ret = 0;
        enum lttng_condition_type condition_type;
@@ -4500,21 +4265,18 @@ int evaluate_buffer_condition(const struct lttng_condition *condition,
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
                if (caa_likely(previous_sample_available)) {
-                       previous_sample_result =
-                               evaluate_buffer_usage_condition(condition,
-                                       previous_sample, channel_info->capacity);
+                       previous_sample_result = evaluate_buffer_usage_condition(
+                               condition, previous_sample, channel_info->capacity);
                }
                latest_sample_result = evaluate_buffer_usage_condition(
-                               condition, latest_sample,
-                               channel_info->capacity);
+                       condition, latest_sample, channel_info->capacity);
                break;
        default:
                /* Unknown condition type; internal error. */
                abort();
        }
 
-       if (!latest_sample_result ||
-                       (previous_sample_result == latest_sample_result)) {
+       if (!latest_sample_result || (previous_sample_result == latest_sample_result)) {
                /*
                 * Only trigger on a condition evaluation transition.
                 *
@@ -4532,9 +4294,7 @@ int evaluate_buffer_condition(const struct lttng_condition *condition,
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
                *evaluation = lttng_evaluation_buffer_usage_create(
-                               condition_type,
-                               latest_sample->highest_usage,
-                               channel_info->capacity);
+                       condition_type, latest_sample->highest_usage, channel_info->capacity);
                break;
        default:
                abort();
@@ -4548,8 +4308,7 @@ end:
        return ret;
 }
 
-static
-int client_notification_overflow(struct notification_client *client)
+static int client_notification_overflow(struct notification_client *client)
 {
        int ret = 0;
        struct lttng_notification_channel_message msg;
@@ -4560,8 +4319,7 @@ int client_notification_overflow(struct notification_client *client)
 
        ASSERT_LOCKED(client->lock);
 
-       DBG("Dropping notification addressed to client (socket fd = %i)",
-                       client->socket);
+       DBG("Dropping notification addressed to client (socket fd = %i)", client->socket);
        if (client->communication.outbound.dropped_notification) {
                /*
                 * The client already has a "notification dropped" message
@@ -4573,31 +4331,29 @@ int client_notification_overflow(struct notification_client *client)
 
        client->communication.outbound.dropped_notification = true;
        ret = lttng_dynamic_buffer_append(
-                       &client->communication.outbound.payload.buffer, &msg,
-                       sizeof(msg));
+               &client->communication.outbound.payload.buffer, &msg, sizeof(msg));
        if (ret) {
                PERROR("Failed to enqueue \"dropped notification\" message in client's (socket fd = %i) outgoing queue",
-                               client->socket);
+                      client->socket);
        }
 end:
        return ret;
 }
 
-static int client_handle_transmission_status_wrapper(
-               struct notification_client *client,
-               enum client_transmission_status status,
-               void *user_data)
+static int client_handle_transmission_status_wrapper(struct notification_client *client,
+                                                    enum client_transmission_status status,
+                                                    void *user_data)
 {
-       return client_handle_transmission_status(client, status,
-                       (struct notification_thread_state *) user_data);
+       return client_handle_transmission_status(
+               client, status, (struct notification_thread_state *) user_data);
 }
 
-static
-int send_evaluation_to_clients(const struct lttng_trigger *trigger,
-               const struct lttng_evaluation *evaluation,
-               struct notification_client_list* client_list,
-               struct notification_thread_state *state,
-               uid_t object_uid, gid_t object_gid)
+static int send_evaluation_to_clients(const struct lttng_trigger *trigger,
+                                     const struct lttng_evaluation *evaluation,
+                                     struct notification_client_list *client_list,
+                                     struct notification_thread_state *state,
+                                     uid_t object_uid,
+                                     gid_t object_gid)
 {
        const struct lttng_credentials creds = {
                .uid = LTTNG_OPTIONAL_INIT_VALUE(object_uid),
@@ -4605,9 +4361,11 @@ int send_evaluation_to_clients(const struct lttng_trigger *trigger,
        };
 
        return notification_client_list_send_evaluation(client_list,
-                       trigger, evaluation,
-                       &creds,
-                       client_handle_transmission_status_wrapper, state);
+                                                       trigger,
+                                                       evaluation,
+                                                       &creds,
+                                                       client_handle_transmission_status_wrapper,
+                                                       state);
 }
 
 /*
@@ -4643,13 +4401,12 @@ int send_evaluation_to_clients(const struct lttng_trigger *trigger,
  * interference from external users (those could, for instance, unregister
  * their triggers).
  */
-int notification_client_list_send_evaluation(
-               struct notification_client_list *client_list,
-               const struct lttng_trigger *trigger,
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_credentials *source_object_creds,
-               report_client_transmission_result_cb client_report,
-               void *user_data)
+int notification_client_list_send_evaluation(struct notification_client_list *client_list,
+                                            const struct lttng_trigger *trigger,
+                                            const struct lttng_evaluation *evaluation,
+                                            const struct lttng_credentials *source_object_creds,
+                                            report_client_transmission_result_cb client_report,
+                                            void *user_data)
 {
        int ret = 0;
        struct lttng_payload msg_payload;
@@ -4659,8 +4416,7 @@ int notification_client_list_send_evaluation(
                .evaluation = (struct lttng_evaluation *) evaluation,
        };
        struct lttng_notification_channel_message msg_header;
-       const struct lttng_credentials *trigger_creds =
-                       lttng_trigger_get_credentials(trigger);
+       const struct lttng_credentials *trigger_creds = lttng_trigger_get_credentials(trigger);
 
        lttng_payload_init(&msg_payload);
 
@@ -4668,8 +4424,7 @@ int notification_client_list_send_evaluation(
        msg_header.size = 0;
        msg_header.fds = 0;
 
-       ret = lttng_dynamic_buffer_append(&msg_payload.buffer, &msg_header,
-                       sizeof(msg_header));
+       ret = lttng_dynamic_buffer_append(&msg_payload.buffer, &msg_header, sizeof(msg_header));
        if (ret) {
                goto end;
        }
@@ -4682,26 +4437,22 @@ int notification_client_list_send_evaluation(
        }
 
        /* Update payload size. */
-       ((struct lttng_notification_channel_message *) msg_payload.buffer.data)
-                       ->size = (uint32_t)(
-                       msg_payload.buffer.size - sizeof(msg_header));
+       ((struct lttng_notification_channel_message *) msg_payload.buffer.data)->size =
+               (uint32_t) (msg_payload.buffer.size - sizeof(msg_header));
 
        /* Update the payload number of fds. */
        {
-               const struct lttng_payload_view pv = lttng_payload_view_from_payload(
-                               &msg_payload, 0, -1);
+               const struct lttng_payload_view pv =
+                       lttng_payload_view_from_payload(&msg_payload, 0, -1);
 
-               ((struct lttng_notification_channel_message *)
-                               msg_payload.buffer.data)->fds = (uint32_t)
-                               lttng_payload_view_get_fd_handle_count(&pv);
+               ((struct lttng_notification_channel_message *) msg_payload.buffer.data)->fds =
+                       (uint32_t) lttng_payload_view_get_fd_handle_count(&pv);
        }
 
        pthread_mutex_lock(&client_list->lock);
-       cds_list_for_each_entry_safe(client_list_element, tmp,
-                       &client_list->clients_list, node) {
+       cds_list_for_each_entry_safe (client_list_element, tmp, &client_list->clients_list, node) {
                enum client_transmission_status transmission_status;
-               struct notification_client *client =
-                               client_list_element->client;
+               struct notification_client *client = client_list_element->client;
 
                ret = 0;
                pthread_mutex_lock(&client->lock);
@@ -4725,8 +4476,8 @@ int notification_client_list_send_evaluation(
 
                if (source_object_creds) {
                        if (client->uid != lttng_credentials_get_uid(source_object_creds) &&
-                                       client->gid != lttng_credentials_get_gid(source_object_creds) &&
-                                       client->uid != 0) {
+                           client->gid != lttng_credentials_get_gid(source_object_creds) &&
+                           client->uid != 0) {
                                /*
                                 * Client is not allowed to monitor this
                                 * object.
@@ -4742,7 +4493,8 @@ int notification_client_list_send_evaluation(
                }
 
                DBG("Sending notification to client (fd = %i, %zu bytes)",
-                               client->socket, msg_payload.buffer.size);
+                   client->socket,
+                   msg_payload.buffer.size);
 
                if (client_has_outbound_data_left(client)) {
                        /*
@@ -4775,7 +4527,7 @@ int notification_client_list_send_evaluation(
 
                continue;
 
-skip_client:
+       skip_client:
                pthread_mutex_unlock(&client->lock);
                if (ret) {
                        /* Fatal error. */
@@ -4791,14 +4543,13 @@ end:
        return ret;
 }
 
-static
-struct lttng_event_notifier_notification *recv_one_event_notifier_notification(
-               int notification_pipe_read_fd, enum lttng_domain_type domain)
+static struct lttng_event_notifier_notification *
+recv_one_event_notifier_notification(int notification_pipe_read_fd, enum lttng_domain_type domain)
 {
        int ret;
        uint64_t token;
-       struct lttng_event_notifier_notification *notification = NULL;
-       char *capture_buffer = NULL;
+       struct lttng_event_notifier_notification *notification = nullptr;
+       char *capture_buffer = nullptr;
        size_t capture_buffer_size;
        void *reception_buffer;
        size_t reception_size;
@@ -4807,7 +4558,7 @@ struct lttng_event_notifier_notification *recv_one_event_notifier_notification(
        struct lttng_kernel_abi_event_notifier_notification kernel_notification;
 
        /* Init lttng_event_notifier_notification */
-       switch(domain) {
+       switch (domain) {
        case LTTNG_DOMAIN_UST:
                reception_buffer = (void *) &ust_notification;
                reception_size = sizeof(ust_notification);
@@ -4824,16 +4575,17 @@ struct lttng_event_notifier_notification *recv_one_event_notifier_notification(
         * The monitoring pipe only holds messages smaller than PIPE_BUF,
         * ensuring that read/write of tracer notifications are atomic.
         */
-       ret = lttng_read(notification_pipe_read_fd, reception_buffer,
-                       reception_size);
+       ret = lttng_read(notification_pipe_read_fd, reception_buffer, reception_size);
        if (ret != reception_size) {
                PERROR("Failed to read from event source notification pipe: fd = %d, size to read = %zu, ret = %d",
-                               notification_pipe_read_fd, reception_size, ret);
+                      notification_pipe_read_fd,
+                      reception_size,
+                      ret);
                ret = -1;
                goto end;
        }
 
-       switch(domain) {
+       switch (domain) {
        case LTTNG_DOMAIN_UST:
                token = ust_notification.token;
                capture_buffer_size = ust_notification.capture_buf_size;
@@ -4847,13 +4599,14 @@ struct lttng_event_notifier_notification *recv_one_event_notifier_notification(
        }
 
        if (capture_buffer_size == 0) {
-               capture_buffer = NULL;
+               capture_buffer = nullptr;
                goto skip_capture;
        }
 
        if (capture_buffer_size > MAX_CAPTURE_SIZE) {
                ERR("Event notifier has a capture payload size which exceeds the maximum allowed size: capture_payload_size = %zu bytes, max allowed size = %d bytes",
-                               capture_buffer_size, MAX_CAPTURE_SIZE);
+                   capture_buffer_size,
+                   MAX_CAPTURE_SIZE);
                goto end;
        }
 
@@ -4866,46 +4619,47 @@ struct lttng_event_notifier_notification *recv_one_event_notifier_notification(
        /* Fetch additional payload (capture). */
        ret = lttng_read(notification_pipe_read_fd, capture_buffer, capture_buffer_size);
        if (ret != capture_buffer_size) {
-               ERR("Failed to read from event source pipe (fd = %i)",
-                               notification_pipe_read_fd);
+               ERR("Failed to read from event source pipe (fd = %i)", notification_pipe_read_fd);
                goto end;
        }
 
 skip_capture:
-       notification = lttng_event_notifier_notification_create(token, domain,
-                       capture_buffer, capture_buffer_size);
-       if (notification == NULL) {
+       notification = lttng_event_notifier_notification_create(
+               token, domain, capture_buffer, capture_buffer_size);
+       if (notification == nullptr) {
                goto end;
        }
 
        /*
         * Ownership transfered to the lttng_event_notifier_notification object.
         */
-       capture_buffer = NULL;
+       capture_buffer = nullptr;
 
 end:
        free(capture_buffer);
        return notification;
 }
 
-static
-int dispatch_one_event_notifier_notification(struct notification_thread_state *state,
-               struct lttng_event_notifier_notification *notification)
+static int
+dispatch_one_event_notifier_notification(struct notification_thread_state *state,
+                                        struct lttng_event_notifier_notification *notification)
 {
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
        struct notification_trigger_tokens_ht_element *element;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
        enum action_executor_status executor_status;
-       struct notification_client_list *client_list = NULL;
+       struct notification_client_list *client_list = nullptr;
        int ret;
        unsigned int capture_count = 0;
 
        /* Find triggers associated with this token. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(state->trigger_tokens_ht,
                        hash_key_u64(&notification->tracer_token, lttng_ht_seed),
-                       match_trigger_token, &notification->tracer_token, &iter);
+                       match_trigger_token,
+                       &notification->tracer_token,
+                       &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (caa_unlikely(!node)) {
                /*
@@ -4918,13 +4672,11 @@ int dispatch_one_event_notifier_notification(struct notification_thread_state *s
                goto end_unlock;
        }
 
-       element = caa_container_of(node,
-                       struct notification_trigger_tokens_ht_element,
-                       node);
+       element = caa_container_of(node, struct notification_trigger_tokens_ht_element, node);
 
        if (lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                           lttng_trigger_get_const_condition(element->trigger),
-                           &capture_count) != LTTNG_CONDITION_STATUS_OK) {
+                   lttng_trigger_get_const_condition(element->trigger), &capture_count) !=
+           LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to get capture count");
                ret = -1;
                goto end;
@@ -4937,30 +4689,29 @@ int dispatch_one_event_notifier_notification(struct notification_thread_state *s
        }
 
        evaluation = lttng_evaluation_event_rule_matches_create(
-                       lttng::utils::container_of(lttng_trigger_get_const_condition(
-                                                    element->trigger),
-                                       &lttng_condition_event_rule_matches::parent),
-                       notification->capture_buffer,
-                       notification->capture_buf_size, false);
+               lttng::utils::container_of(lttng_trigger_get_const_condition(element->trigger),
+                                          &lttng_condition_event_rule_matches::parent),
+               notification->capture_buffer,
+               notification->capture_buf_size,
+               false);
 
-       if (evaluation == NULL) {
+       if (evaluation == nullptr) {
                ERR("Failed to create event rule matches evaluation while creating and enqueuing action executor job");
                ret = -1;
                goto end_unlock;
        }
 
-       client_list = get_client_list_from_condition(state,
-                       lttng_trigger_get_const_condition(element->trigger));
-       executor_status = action_executor_enqueue_trigger(state->executor,
-                       element->trigger, evaluation, NULL, client_list);
+       client_list = get_client_list_from_condition(
+               state, lttng_trigger_get_const_condition(element->trigger));
+       executor_status = action_executor_enqueue_trigger(
+               state->executor, element->trigger, evaluation, nullptr, client_list);
        switch (executor_status) {
        case ACTION_EXECUTOR_STATUS_OK:
                ret = 0;
                break;
        case ACTION_EXECUTOR_STATUS_OVERFLOW:
        {
-               struct notification_client_list_element *client_list_element,
-                               *tmp;
+               struct notification_client_list_element *client_list_element, *tmp;
 
                /*
                 * Not a fatal error; this is expected and simply means the
@@ -4975,11 +4726,10 @@ int dispatch_one_event_notifier_notification(struct notification_thread_state *s
 
                /* Warn clients that a notification (or more) was dropped. */
                pthread_mutex_lock(&client_list->lock);
-               cds_list_for_each_entry_safe(client_list_element, tmp,
-                               &client_list->clients_list, node) {
+               cds_list_for_each_entry_safe (
+                       client_list_element, tmp, &client_list->clients_list, node) {
                        enum client_transmission_status transmission_status;
-                       struct notification_client *client =
-                                       client_list_element->client;
+                       struct notification_client *client = client_list_element->client;
 
                        pthread_mutex_lock(&client->lock);
                        ret = client_notification_overflow(client);
@@ -4988,15 +4738,13 @@ int dispatch_one_event_notifier_notification(struct notification_thread_state *s
                                goto next_client;
                        }
 
-                       transmission_status =
-                                       client_flush_outgoing_queue(client);
-                       ret = client_handle_transmission_status(
-                                       client, transmission_status, state);
+                       transmission_status = client_flush_outgoing_queue(client);
+                       ret = client_handle_transmission_status(client, transmission_status, state);
                        if (ret) {
                                /* Fatal error. */
                                goto next_client;
                        }
-next_client:
+               next_client:
                        pthread_mutex_unlock(&client->lock);
                        if (ret) {
                                break;
@@ -5019,31 +4767,31 @@ next_client:
 
 end_unlock:
        notification_client_list_put(client_list);
-       rcu_read_unlock();
 end:
        return ret;
 }
 
-static
-int handle_one_event_notifier_notification(
-               struct notification_thread_state *state,
-               int pipe, enum lttng_domain_type domain)
+static int handle_one_event_notifier_notification(struct notification_thread_state *state,
+                                                 int pipe,
+                                                 enum lttng_domain_type domain)
 {
        int ret = 0;
-       struct lttng_event_notifier_notification *notification = NULL;
+       struct lttng_event_notifier_notification *notification = nullptr;
 
        notification = recv_one_event_notifier_notification(pipe, domain);
-       if (notification == NULL) {
+       if (notification == nullptr) {
                /* Reception failed, don't consider it fatal. */
                ERR("Error receiving an event notifier notification from tracer: fd = %i, domain = %s",
-                               pipe, lttng_domain_type_str(domain));
+                   pipe,
+                   lttng_domain_type_str(domain));
                goto end;
        }
 
        ret = dispatch_one_event_notifier_notification(state, notification);
        if (ret) {
                ERR("Error dispatching an event notifier notification from tracer: fd = %i, domain = %s",
-                               pipe, lttng_domain_type_str(domain));
+                   pipe,
+                   lttng_domain_type_str(domain));
                goto end;
        }
 
@@ -5053,18 +4801,19 @@ end:
 }
 
 int handle_notification_thread_event_notification(struct notification_thread_state *state,
-               int pipe, enum lttng_domain_type domain)
+                                                 int pipe,
+                                                 enum lttng_domain_type domain)
 {
        return handle_one_event_notifier_notification(state, pipe, domain);
 }
 
-int handle_notification_thread_channel_sample(
-               struct notification_thread_state *state, int pipe,
-               enum lttng_domain_type domain)
+int handle_notification_thread_channel_sample(struct notification_thread_state *state,
+                                             int pipe,
+                                             enum lttng_domain_type domain)
 {
        int ret = 0;
        struct lttcomm_consumer_channel_monitor_msg sample_msg;
-       struct channel_info *channel_info = NULL;
+       struct channel_info *channel_info = nullptr;
        struct cds_lfht_node *node;
        struct cds_lfht_iter iter;
        struct lttng_channel_trigger_list *channel_trigger_list;
@@ -5076,6 +4825,7 @@ int handle_notification_thread_channel_sample(
        struct lttng_credentials channel_creds = {};
        struct lttng_credentials session_creds = {};
        struct session_info *session;
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * The monitoring pipe only holds messages smaller than PIPE_BUF,
@@ -5083,8 +4833,7 @@ int handle_notification_thread_channel_sample(
         */
        ret = lttng_read(pipe, &sample_msg, sizeof(sample_msg));
        if (ret != sizeof(sample_msg)) {
-               ERR("Failed to read from monitoring pipe (fd = %i)",
-                               pipe);
+               ERR("Failed to read from monitoring pipe (fd = %i)", pipe);
                ret = -1;
                goto end;
        }
@@ -5095,12 +4844,10 @@ int handle_notification_thread_channel_sample(
        channel_new_sample.highest_usage = sample_msg.highest;
        channel_new_sample.lowest_usage = sample_msg.lowest;
 
-       rcu_read_lock();
-
        session = get_session_info_by_id(state, sample_msg.session_id);
        if (!session) {
                DBG("Received a sample for an unknown session from consumerd: session id = %" PRIu64,
-                               sample_msg.session_id);
+                   sample_msg.session_id);
                goto end_unlock;
        }
 
@@ -5113,12 +4860,11 @@ int handle_notification_thread_channel_sample(
 
        session_trigger_list = get_session_trigger_list(state, session->name);
        LTTNG_ASSERT(session_trigger_list);
-       cds_list_for_each_entry(trigger_list_element, &session_trigger_list->list,
-                       node) {
+       cds_list_for_each_entry (trigger_list_element, &session_trigger_list->list, node) {
                const struct lttng_condition *condition;
                struct lttng_trigger *trigger;
-               struct notification_client_list *client_list = NULL;
-               struct lttng_evaluation *evaluation = NULL;
+               struct notification_client_list *client_list = nullptr;
+               struct lttng_evaluation *evaluation = nullptr;
                enum action_executor_status executor_status;
 
                ret = 0;
@@ -5127,7 +4873,7 @@ int handle_notification_thread_channel_sample(
                LTTNG_ASSERT(condition);
 
                ret = evaluate_session_condition(
-                               condition, session, &session_new_sample, &evaluation);
+                       condition, session, &session_new_sample, &evaluation);
                if (caa_unlikely(ret)) {
                        break;
                }
@@ -5143,10 +4889,9 @@ int handle_notification_thread_channel_sample(
                 */
                client_list = get_client_list_from_condition(state, condition);
                executor_status = action_executor_enqueue_trigger(
-                               state->executor, trigger, evaluation,
-                               &session_creds, client_list);
+                       state->executor, trigger, evaluation, &session_creds, client_list);
                notification_client_list_put(client_list);
-               evaluation = NULL;
+               evaluation = nullptr;
                switch (executor_status) {
                case ACTION_EXECUTOR_STATUS_OK:
                        break;
@@ -5188,21 +4933,23 @@ int handle_notification_thread_channel_sample(
                 * channel's destruction before we get a chance to process that
                 * sample.
                 */
-               DBG("Received a sample for an unknown channel from consumerd, key = %" PRIu64 " in %s domain",
-                               channel_new_sample.key.key,
-                               lttng_domain_type_str(domain));
+               DBG("Received a sample for an unknown channel from consumerd, key = %" PRIu64
+                   " in %s domain",
+                   channel_new_sample.key.key,
+                   lttng_domain_type_str(domain));
                goto end_unlock;
        }
 
-       channel_info = caa_container_of(node, struct channel_info,
-                       channels_ht_node);
-       DBG("Handling channel sample for channel %s (key = %" PRIu64 ") in session %s (highest usage = %" PRIu64 ", lowest usage = %" PRIu64", consumed since last sample = %" PRIu64")",
-                       channel_info->name,
-                       channel_new_sample.key.key,
-                       channel_info->session_info->name,
-                       channel_new_sample.highest_usage,
-                       channel_new_sample.lowest_usage,
-                       sample_msg.consumed_since_last_sample);
+       channel_info = caa_container_of(node, struct channel_info, channels_ht_node);
+       DBG("Handling channel sample for channel %s (key = %" PRIu64
+           ") in session %s (highest usage = %" PRIu64 ", lowest usage = %" PRIu64
+           ", consumed since last sample = %" PRIu64 ")",
+           channel_info->name,
+           channel_new_sample.key.key,
+           channel_info->session_info->name,
+           channel_new_sample.highest_usage,
+           channel_new_sample.lowest_usage,
+           sample_msg.consumed_since_last_sample);
 
        /* Retrieve the channel's last sample, if it exists, and update it. */
        cds_lfht_lookup(state->channel_state_ht,
@@ -5215,12 +4962,10 @@ int handle_notification_thread_channel_sample(
                struct channel_state_sample *stored_sample;
 
                /* Update the sample stored. */
-               stored_sample = caa_container_of(node,
-                               struct channel_state_sample,
-                               channel_state_ht_node);
+               stored_sample =
+                       caa_container_of(node, struct channel_state_sample, channel_state_ht_node);
 
-               memcpy(&channel_previous_sample, stored_sample,
-                               sizeof(channel_previous_sample));
+               memcpy(&channel_previous_sample, stored_sample, sizeof(channel_previous_sample));
                stored_sample->highest_usage = channel_new_sample.highest_usage;
                stored_sample->lowest_usage = channel_new_sample.lowest_usage;
                previous_sample_available = true;
@@ -5240,8 +4985,8 @@ int handle_notification_thread_channel_sample(
                memcpy(stored_sample, &channel_new_sample, sizeof(*stored_sample));
                cds_lfht_node_init(&stored_sample->channel_state_ht_node);
                cds_lfht_add(state->channel_state_ht,
-                               hash_channel_key(&stored_sample->key),
-                               &stored_sample->channel_state_ht_node);
+                            hash_channel_key(&stored_sample->key),
+                            &stored_sample->channel_state_ht_node);
        }
 
        /* Find triggers associated with this channel. */
@@ -5253,19 +4998,18 @@ int handle_notification_thread_channel_sample(
        node = cds_lfht_iter_get_node(&iter);
        LTTNG_ASSERT(node);
 
-       channel_creds = (typeof(channel_creds)) {
+       channel_creds = (typeof(channel_creds)){
                .uid = LTTNG_OPTIONAL_INIT_VALUE(channel_info->session_info->uid),
                .gid = LTTNG_OPTIONAL_INIT_VALUE(channel_info->session_info->gid),
        };
 
-       channel_trigger_list = caa_container_of(node, struct lttng_channel_trigger_list,
-                       channel_triggers_ht_node);
-       cds_list_for_each_entry(trigger_list_element, &channel_trigger_list->list,
-                       node) {
+       channel_trigger_list =
+               caa_container_of(node, struct lttng_channel_trigger_list, channel_triggers_ht_node);
+       cds_list_for_each_entry (trigger_list_element, &channel_trigger_list->list, node) {
                const struct lttng_condition *condition;
                struct lttng_trigger *trigger;
-               struct notification_client_list *client_list = NULL;
-               struct lttng_evaluation *evaluation = NULL;
+               struct notification_client_list *client_list = nullptr;
+               struct lttng_evaluation *evaluation = nullptr;
                enum action_executor_status executor_status;
 
                ret = 0;
@@ -5273,10 +5017,13 @@ int handle_notification_thread_channel_sample(
                condition = lttng_trigger_get_const_condition(trigger);
                LTTNG_ASSERT(condition);
 
-               ret = evaluate_buffer_condition(condition, &evaluation, state,
-                               previous_sample_available ? &channel_previous_sample : NULL,
-                               &channel_new_sample,
-                               channel_info);
+               ret = evaluate_buffer_condition(
+                       condition,
+                       &evaluation,
+                       state,
+                       previous_sample_available ? &channel_previous_sample : nullptr,
+                       &channel_new_sample,
+                       channel_info);
                if (caa_unlikely(ret)) {
                        break;
                }
@@ -5292,10 +5039,9 @@ int handle_notification_thread_channel_sample(
                 */
                client_list = get_client_list_from_condition(state, condition);
                executor_status = action_executor_enqueue_trigger(
-                               state->executor, trigger, evaluation,
-                               &channel_creds, client_list);
+                       state->executor, trigger, evaluation, &channel_creds, client_list);
                notification_client_list_put(client_list);
-               evaluation = NULL;
+               evaluation = nullptr;
                switch (executor_status) {
                case ACTION_EXECUTOR_STATUS_OK:
                        break;
@@ -5327,7 +5073,6 @@ end_unlock:
                session->last_state_sample = session_new_sample;
        }
        session_info_put(session);
-       rcu_read_unlock();
 end:
        return ret;
 }
index 50abad916117fa6f24f8669726b24bf7e82a58db..955b16cddd299c0bacb1b00929e6d7fe645c4bc1 100644 (file)
@@ -8,48 +8,39 @@
 #ifndef NOTIFICATION_THREAD_EVENTS_H
 #define NOTIFICATION_THREAD_EVENTS_H
 
-#include <lttng/domain.h>
 #include "notification-thread.hpp"
 
+#include <lttng/domain.h>
+
 /**
  * Event handling function shall only return an error if
  * the thread should be stopped.
  */
-int handle_notification_thread_command(
-               struct notification_thread_handle *handle,
-               struct notification_thread_state *state);
+int handle_notification_thread_command(struct notification_thread_handle *handle,
+                                      struct notification_thread_state *state);
 
-int handle_notification_thread_client_connect(
-               struct notification_thread_state *state);
+int handle_notification_thread_client_connect(struct notification_thread_state *state);
 
-int handle_notification_thread_client_disconnect(
-               int client_fd,
-               struct notification_thread_state *state);
+int handle_notification_thread_client_disconnect(int client_fd,
+                                                struct notification_thread_state *state);
 
-int handle_notification_thread_client_disconnect_all(
-               struct notification_thread_state *state);
+int handle_notification_thread_client_disconnect_all(struct notification_thread_state *state);
 
-int handle_notification_thread_trigger_unregister_all(
-               struct notification_thread_state *state);
+int handle_notification_thread_trigger_unregister_all(struct notification_thread_state *state);
 
-int handle_notification_thread_tracer_event_source_died(
-               struct notification_thread_state *state,
-               int tracer_event_source_fd);
+int handle_notification_thread_tracer_event_source_died(struct notification_thread_state *state,
+                                                       int tracer_event_source_fd);
 
-int handle_notification_thread_client_in(
-               struct notification_thread_state *state,
-               int socket);
+int handle_notification_thread_client_in(struct notification_thread_state *state, int socket);
 
-int handle_notification_thread_client_out(
-               struct notification_thread_state *state,
-               int socket);
+int handle_notification_thread_client_out(struct notification_thread_state *state, int socket);
 
-int handle_notification_thread_channel_sample(
-               struct notification_thread_state *state, int pipe,
-               enum lttng_domain_type domain);
+int handle_notification_thread_channel_sample(struct notification_thread_state *state,
+                                             int pipe,
+                                             enum lttng_domain_type domain);
 
-int handle_notification_thread_event_notification(
-               struct notification_thread_state *state, int pipe,
-               enum lttng_domain_type domain);
+int handle_notification_thread_event_notification(struct notification_thread_state *state,
+                                                 int pipe,
+                                                 enum lttng_domain_type domain);
 
 #endif /* NOTIFICATION_THREAD_EVENTS_H */
index 1cab09d9707347530d34c1b5bbb5e87f46aec1b4..864593cefa28f204123b7fe84fb2d605fcef07c2 100644 (file)
@@ -8,17 +8,20 @@
 #ifndef NOTIFICATION_THREAD_INTERNAL_H
 #define NOTIFICATION_THREAD_INTERNAL_H
 
+#include "notification-thread.hpp"
+
 #include <common/compat/socket.hpp>
 #include <common/credentials.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/notification/channel-internal.hpp>
 #include <lttng/ref-internal.hpp>
+
 #include <stdbool.h>
 #include <unistd.h>
+#include <urcu/call-rcu.h>
 #include <urcu/rculfhash.h>
 #include <urcu/ref.h>
-#include <urcu/call-rcu.h>
-#include "notification-thread.hpp"
 
 struct lttng_evaluation;
 struct notification_thread_handle;
@@ -239,34 +242,29 @@ bool notification_client_list_get(struct notification_client_list *list);
 void notification_client_list_put(struct notification_client_list *list);
 
 /* Only returns a non-zero value if a fatal error occurred. */
-typedef int (*report_client_transmission_result_cb)(
-               struct notification_client *client,
-               enum client_transmission_status status,
-               void *user_data);
+using report_client_transmission_result_cb = int (*)(struct notification_client *,
+                                                    enum client_transmission_status,
+                                                    void *);
 
-int notification_client_list_send_evaluation(
-               struct notification_client_list *list,
-               const struct lttng_trigger *trigger,
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_credentials *source_object_creds,
-               report_client_transmission_result_cb client_report,
-               void *user_data);
+int notification_client_list_send_evaluation(struct notification_client_list *list,
+                                            const struct lttng_trigger *trigger,
+                                            const struct lttng_evaluation *evaluation,
+                                            const struct lttng_credentials *source_object_creds,
+                                            report_client_transmission_result_cb client_report,
+                                            void *user_data);
 
 int notification_thread_client_communication_update(
-               struct notification_thread_handle *handle,
-               notification_client_id id,
-               enum client_transmission_status transmission_status);
+       struct notification_thread_handle *handle,
+       notification_client_id id,
+       enum client_transmission_status transmission_status);
 
 /*
  * Takes ownership of the payload if present.
  */
 struct lttng_event_notifier_notification *lttng_event_notifier_notification_create(
-               uint64_t tracer_token,
-               enum lttng_domain_type domain,
-               char *payload,
-               size_t payload_size);
+       uint64_t tracer_token, enum lttng_domain_type domain, char *payload, size_t payload_size);
 
 void lttng_event_notifier_notification_destroy(
-               struct lttng_event_notifier_notification *event_notifier_notification);
+       struct lttng_event_notifier_notification *event_notifier_notification);
 
 #endif /* NOTIFICATION_THREAD_INTERNAL_H */
index 7d9f4ed12dd72bae638db763f757ee8ffa7021a0..72aa08292141c7b8d7439fc3d9579ca8d3183c40 100644 (file)
@@ -6,33 +6,33 @@
  */
 
 #define _LGPL_SOURCE
-#include <lttng/trigger/trigger.h>
-#include <lttng/notification/channel-internal.hpp>
-#include <lttng/notification/notification-internal.hpp>
-#include <lttng/condition/condition-internal.hpp>
-#include <lttng/condition/buffer-usage-internal.hpp>
-#include <common/error.hpp>
-#include <common/config/session-config.hpp>
-#include <common/defaults.hpp>
-#include <common/utils.hpp>
-#include <common/align.hpp>
-#include <common/time.hpp>
-#include <sys/stat.h>
-#include <sys/eventfd.h>
-#include <time.h>
-#include <signal.h>
-
-#include "notification-thread.hpp"
-#include "notification-thread-events.hpp"
-#include "notification-thread-commands.hpp"
-#include "lttng-sessiond.hpp"
 #include "health-sessiond.hpp"
-#include "thread.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "notification-thread-commands.hpp"
+#include "notification-thread-events.hpp"
+#include "notification-thread.hpp"
 #include "testpoint.hpp"
+#include "thread.hpp"
 
-#include "kernel.hpp"
+#include <common/align.hpp>
+#include <common/config/session-config.hpp>
+#include <common/defaults.hpp>
+#include <common/error.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
+#include <common/time.hpp>
+#include <common/utils.hpp>
 
+#include <lttng/condition/buffer-usage-internal.hpp>
+#include <lttng/condition/condition-internal.hpp>
+#include <lttng/notification/channel-internal.hpp>
+#include <lttng/notification/notification-internal.hpp>
+#include <lttng/trigger/trigger.h>
+
+#include <signal.h>
+#include <sys/eventfd.h>
+#include <sys/stat.h>
+#include <time.h>
 #include <urcu.h>
 #include <urcu/list.h>
 #include <urcu/rculfhash.h>
@@ -47,8 +47,7 @@ LTTNG_EXPORT int notifier_consumption_paused;
 /*
  * Destroy the thread data previously created by the init function.
  */
-void notification_thread_handle_destroy(
-               struct notification_thread_handle *handle)
+void notification_thread_handle_destroy(struct notification_thread_handle *handle)
 {
        int ret;
 
@@ -89,10 +88,10 @@ end:
        free(handle);
 }
 
-struct notification_thread_handle *notification_thread_handle_create(
-               struct lttng_pipe *ust32_channel_monitor_pipe,
-               struct lttng_pipe *ust64_channel_monitor_pipe,
-               struct lttng_pipe *kernel_channel_monitor_pipe)
+struct notification_thread_handle *
+notification_thread_handle_create(struct lttng_pipe *ust32_channel_monitor_pipe,
+                                 struct lttng_pipe *ust64_channel_monitor_pipe,
+                                 struct lttng_pipe *kernel_channel_monitor_pipe)
 {
        int ret;
        struct notification_thread_handle *handle;
@@ -105,7 +104,7 @@ struct notification_thread_handle *notification_thread_handle_create(
 
        sem_init(&handle->ready, 0, 0);
 
-       event_fd =  eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE);
+       event_fd = eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE);
        if (event_fd < 0) {
                PERROR("event_fd creation");
                goto error;
@@ -114,15 +113,14 @@ struct notification_thread_handle *notification_thread_handle_create(
        handle->cmd_queue.event_fd = event_fd;
 
        CDS_INIT_LIST_HEAD(&handle->cmd_queue.list);
-       ret = pthread_mutex_init(&handle->cmd_queue.lock, NULL);
+       ret = pthread_mutex_init(&handle->cmd_queue.lock, nullptr);
        if (ret) {
                goto error;
        }
 
        if (ust32_channel_monitor_pipe) {
                handle->channel_monitoring_pipes.ust32_consumer =
-                               lttng_pipe_release_readfd(
-                                       ust32_channel_monitor_pipe);
+                       lttng_pipe_release_readfd(ust32_channel_monitor_pipe);
                if (handle->channel_monitoring_pipes.ust32_consumer < 0) {
                        goto error;
                }
@@ -131,8 +129,7 @@ struct notification_thread_handle *notification_thread_handle_create(
        }
        if (ust64_channel_monitor_pipe) {
                handle->channel_monitoring_pipes.ust64_consumer =
-                               lttng_pipe_release_readfd(
-                                       ust64_channel_monitor_pipe);
+                       lttng_pipe_release_readfd(ust64_channel_monitor_pipe);
                if (handle->channel_monitoring_pipes.ust64_consumer < 0) {
                        goto error;
                }
@@ -141,8 +138,7 @@ struct notification_thread_handle *notification_thread_handle_create(
        }
        if (kernel_channel_monitor_pipe) {
                handle->channel_monitoring_pipes.kernel_consumer =
-                               lttng_pipe_release_readfd(
-                                       kernel_channel_monitor_pipe);
+                       lttng_pipe_release_readfd(kernel_channel_monitor_pipe);
                if (handle->channel_monitoring_pipes.kernel_consumer < 0) {
                        goto error;
                }
@@ -154,11 +150,10 @@ end:
        return handle;
 error:
        notification_thread_handle_destroy(handle);
-       return NULL;
+       return nullptr;
 }
 
-static
-char *get_notification_channel_sock_path(void)
+static char *get_notification_channel_sock_path()
 {
        int ret;
        bool is_root = !getuid();
@@ -170,8 +165,8 @@ char *get_notification_channel_sock_path(void)
        }
 
        if (is_root) {
-               ret = snprintf(sock_path, LTTNG_PATH_MAX,
-                               DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK);
+               ret = snprintf(
+                       sock_path, LTTNG_PATH_MAX, DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK);
                if (ret < 0) {
                        goto error;
                }
@@ -183,9 +178,10 @@ char *get_notification_channel_sock_path(void)
                        goto error;
                }
 
-               ret = snprintf(sock_path, LTTNG_PATH_MAX,
-                               DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK,
-                               home_path);
+               ret = snprintf(sock_path,
+                              LTTNG_PATH_MAX,
+                              DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK,
+                              home_path);
                if (ret < 0) {
                        goto error;
                }
@@ -194,11 +190,10 @@ char *get_notification_channel_sock_path(void)
        return sock_path;
 error:
        free(sock_path);
-       return NULL;
+       return nullptr;
 }
 
-static
-void notification_channel_socket_destroy(int fd)
+static void notification_channel_socket_destroy(int fd)
 {
        int ret;
        char *sock_path = get_notification_channel_sock_path();
@@ -219,14 +214,12 @@ void notification_channel_socket_destroy(int fd)
        }
 }
 
-static
-int notification_channel_socket_create(void)
+static int notification_channel_socket_create()
 {
        int fd = -1, ret;
        char *sock_path = get_notification_channel_sock_path();
 
-       DBG("Creating notification channel UNIX socket at %s",
-                       sock_path);
+       DBG("Creating notification channel UNIX socket at %s", sock_path);
 
        ret = lttcomm_create_unix_sock(sock_path);
        if (ret < 0) {
@@ -245,8 +238,7 @@ int notification_channel_socket_create(void)
        if (getuid() == 0) {
                gid_t gid;
 
-               ret = utils_get_group_id(the_config.tracing_group_name.value,
-                               true, &gid);
+               ret = utils_get_group_id(the_config.tracing_group_name.value, true, &gid);
                if (ret) {
                        /* Default to root group. */
                        gid = 0;
@@ -260,8 +252,7 @@ int notification_channel_socket_create(void)
                }
        }
 
-       DBG("Notification channel UNIX socket created (fd = %i)",
-                       fd);
+       DBG("Notification channel UNIX socket created (fd = %i)", fd);
        free(sock_path);
        return fd;
 error:
@@ -272,10 +263,9 @@ error:
        return ret;
 }
 
-static
-int init_poll_set(struct lttng_poll_event *poll_set,
-               struct notification_thread_handle *handle,
-               int notification_channel_socket)
+static int init_poll_set(struct lttng_poll_event *poll_set,
+                        struct notification_thread_handle *handle,
+                        int notification_channel_socket)
 {
        int ret;
 
@@ -292,28 +282,22 @@ int init_poll_set(struct lttng_poll_event *poll_set,
                goto end;
        }
 
-       ret = lttng_poll_add(poll_set, notification_channel_socket,
-                       LPOLLIN | LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+       ret = lttng_poll_add(poll_set, notification_channel_socket, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                ERR("Failed to add notification channel socket to pollset");
                goto error;
        }
-       ret = lttng_poll_add(poll_set, handle->cmd_queue.event_fd,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(poll_set, handle->cmd_queue.event_fd, LPOLLIN);
        if (ret < 0) {
                ERR("Failed to add notification command queue event fd to pollset");
                goto error;
        }
-       ret = lttng_poll_add(poll_set,
-                       handle->channel_monitoring_pipes.ust32_consumer,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(poll_set, handle->channel_monitoring_pipes.ust32_consumer, LPOLLIN);
        if (ret < 0) {
                ERR("Failed to add ust-32 channel monitoring pipe fd to pollset");
                goto error;
        }
-       ret = lttng_poll_add(poll_set,
-                       handle->channel_monitoring_pipes.ust64_consumer,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(poll_set, handle->channel_monitoring_pipes.ust64_consumer, LPOLLIN);
        if (ret < 0) {
                ERR("Failed to add ust-64 channel monitoring pipe fd to pollset");
                goto error;
@@ -321,9 +305,7 @@ int init_poll_set(struct lttng_poll_event *poll_set,
        if (handle->channel_monitoring_pipes.kernel_consumer < 0) {
                goto end;
        }
-       ret = lttng_poll_add(poll_set,
-                       handle->channel_monitoring_pipes.kernel_consumer,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(poll_set, handle->channel_monitoring_pipes.kernel_consumer, LPOLLIN);
        if (ret < 0) {
                ERR("Failed to add kernel channel monitoring pipe fd to pollset");
                goto error;
@@ -335,54 +317,52 @@ error:
        return ret;
 }
 
-static
-void fini_thread_state(struct notification_thread_state *state)
+static void fini_thread_state(struct notification_thread_state *state)
 {
        int ret;
 
        if (state->client_socket_ht) {
                ret = handle_notification_thread_client_disconnect_all(state);
                LTTNG_ASSERT(!ret);
-               ret = cds_lfht_destroy(state->client_socket_ht, NULL);
+               ret = cds_lfht_destroy(state->client_socket_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->client_id_ht) {
-               ret = cds_lfht_destroy(state->client_id_ht, NULL);
+               ret = cds_lfht_destroy(state->client_id_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->triggers_ht) {
                ret = handle_notification_thread_trigger_unregister_all(state);
                LTTNG_ASSERT(!ret);
-               ret = cds_lfht_destroy(state->triggers_ht, NULL);
+               ret = cds_lfht_destroy(state->triggers_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->channel_triggers_ht) {
-               ret = cds_lfht_destroy(state->channel_triggers_ht, NULL);
+               ret = cds_lfht_destroy(state->channel_triggers_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->channel_state_ht) {
-               ret = cds_lfht_destroy(state->channel_state_ht, NULL);
+               ret = cds_lfht_destroy(state->channel_state_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->notification_trigger_clients_ht) {
-               ret = cds_lfht_destroy(state->notification_trigger_clients_ht,
-                               NULL);
+               ret = cds_lfht_destroy(state->notification_trigger_clients_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->channels_ht) {
-               ret = cds_lfht_destroy(state->channels_ht, NULL);
+               ret = cds_lfht_destroy(state->channels_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->sessions_ht) {
-               ret = cds_lfht_destroy(state->sessions_ht, NULL);
+               ret = cds_lfht_destroy(state->sessions_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->triggers_by_name_uid_ht) {
-               ret = cds_lfht_destroy(state->triggers_by_name_uid_ht, NULL);
+               ret = cds_lfht_destroy(state->triggers_by_name_uid_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->trigger_tokens_ht) {
-               ret = cds_lfht_destroy(state->trigger_tokens_ht, NULL);
+               ret = cds_lfht_destroy(state->trigger_tokens_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        /*
@@ -390,12 +370,11 @@ void fini_thread_state(struct notification_thread_state *state)
         * See comment in struct lttng_session_trigger_list.
         */
        if (state->session_triggers_ht) {
-               ret = cds_lfht_destroy(state->session_triggers_ht, NULL);
+               ret = cds_lfht_destroy(state->session_triggers_ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        if (state->notification_channel_socket >= 0) {
-               notification_channel_socket_destroy(
-                               state->notification_channel_socket);
+               notification_channel_socket_destroy(state->notification_channel_socket);
        }
 
        LTTNG_ASSERT(cds_list_empty(&state->tracer_event_sources_list));
@@ -406,24 +385,21 @@ void fini_thread_state(struct notification_thread_state *state)
        lttng_poll_clean(&state->events);
 }
 
-static
-void mark_thread_as_ready(struct notification_thread_handle *handle)
+static void mark_thread_as_ready(struct notification_thread_handle *handle)
 {
        DBG("Marking notification thread as ready");
        sem_post(&handle->ready);
 }
 
-static
-void wait_until_thread_is_ready(struct notification_thread_handle *handle)
+static void wait_until_thread_is_ready(struct notification_thread_handle *handle)
 {
        DBG("Waiting for notification thread to be ready");
        sem_wait(&handle->ready);
        DBG("Notification thread is ready");
 }
 
-static
-int init_thread_state(struct notification_thread_handle *handle,
-               struct notification_thread_state *state)
+static int init_thread_state(struct notification_thread_handle *handle,
+                            struct notification_thread_state *state)
 {
        int ret;
 
@@ -438,8 +414,7 @@ int init_thread_state(struct notification_thread_handle *handle,
        }
        state->notification_channel_socket = ret;
 
-       ret = init_poll_set(&state->events, handle,
-                       state->notification_channel_socket);
+       ret = init_poll_set(&state->events, handle, state->notification_channel_socket);
        if (ret) {
                goto end;
        }
@@ -451,65 +426,65 @@ int init_thread_state(struct notification_thread_handle *handle,
                goto error;
        }
 
-       state->client_socket_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->client_socket_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->client_socket_ht) {
                goto error;
        }
 
-       state->client_id_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->client_id_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->client_id_ht) {
                goto error;
        }
 
-       state->channel_triggers_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->channel_triggers_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->channel_triggers_ht) {
                goto error;
        }
 
-       state->session_triggers_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->session_triggers_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->session_triggers_ht) {
                goto error;
        }
 
-       state->channel_state_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->channel_state_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->channel_state_ht) {
                goto error;
        }
 
-       state->notification_trigger_clients_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->notification_trigger_clients_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->notification_trigger_clients_ht) {
                goto error;
        }
 
-       state->channels_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->channels_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->channels_ht) {
                goto error;
        }
-       state->sessions_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->sessions_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->sessions_ht) {
                goto error;
        }
-       state->triggers_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->triggers_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->triggers_ht) {
                goto error;
        }
-       state->triggers_by_name_uid_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->triggers_by_name_uid_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->triggers_by_name_uid_ht) {
                goto error;
        }
 
-       state->trigger_tokens_ht = cds_lfht_new(DEFAULT_HT_SIZE,
-                       1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       state->trigger_tokens_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!state->trigger_tokens_ht) {
                goto error;
        }
@@ -531,16 +506,16 @@ error:
        return -1;
 }
 
-static
-int handle_channel_monitoring_pipe(int fd, uint32_t revents,
-               struct notification_thread_handle *handle,
-               struct notification_thread_state *state)
+static int handle_channel_monitoring_pipe(int fd,
+                                         uint32_t revents,
+                                         struct notification_thread_handle *handle,
+                                         struct notification_thread_state *state)
 {
        int ret = 0;
        enum lttng_domain_type domain;
 
        if (fd == handle->channel_monitoring_pipes.ust32_consumer ||
-                       fd == handle->channel_monitoring_pipes.ust64_consumer) {
+           fd == handle->channel_monitoring_pipes.ust64_consumer) {
                domain = LTTNG_DOMAIN_UST;
        } else if (fd == handle->channel_monitoring_pipes.kernel_consumer) {
                domain = LTTNG_DOMAIN_KERNEL;
@@ -556,8 +531,7 @@ int handle_channel_monitoring_pipe(int fd, uint32_t revents,
                goto end;
        }
 
-       ret = handle_notification_thread_channel_sample(
-                       state, fd, domain);
+       ret = handle_notification_thread_channel_sample(state, fd, domain);
        if (ret) {
                ERR("Consumer sample handling error occurred");
                ret = -1;
@@ -568,18 +542,17 @@ end:
 }
 
 static int handle_event_notification_pipe(int event_source_fd,
-               enum lttng_domain_type domain,
-               uint32_t revents,
-               struct notification_thread_state *state)
+                                         enum lttng_domain_type domain,
+                                         uint32_t revents,
+                                         struct notification_thread_state *state)
 {
        int ret = 0;
 
        if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-               ret = handle_notification_thread_tracer_event_source_died(
-                               state, event_source_fd);
+               ret = handle_notification_thread_tracer_event_source_died(state, event_source_fd);
                if (ret) {
                        ERR("Failed to remove event notification pipe from poll set: fd = %d",
-                                       event_source_fd);
+                           event_source_fd);
                }
                goto end;
        }
@@ -595,11 +568,9 @@ static int handle_event_notification_pipe(int event_source_fd,
                goto end;
        }
 
-       ret = handle_notification_thread_event_notification(
-                       state, event_source_fd, domain);
+       ret = handle_notification_thread_event_notification(state, event_source_fd, domain);
        if (ret) {
-               ERR("Event notification handling error occurred for fd: %d",
-                               event_source_fd);
+               ERR("Event notification handling error occurred for fd: %d", event_source_fd);
                ret = -1;
                goto end;
        }
@@ -612,15 +583,14 @@ end:
  * Return the event source domain type via parameter.
  */
 static bool fd_is_event_notification_source(const struct notification_thread_state *state,
-               int fd,
-               enum lttng_domain_type *domain)
+                                           int fd,
+                                           enum lttng_domain_type *domain)
 {
        struct notification_event_tracer_event_source_element *source_element;
 
        LTTNG_ASSERT(domain);
 
-       cds_list_for_each_entry(source_element,
-                       &state->tracer_event_sources_list, node) {
+       cds_list_for_each_entry (source_element, &state->tracer_event_sources_list, node) {
                if (source_element->fd != fd) {
                        continue;
                }
@@ -636,8 +606,7 @@ static bool fd_is_event_notification_source(const struct notification_thread_sta
  * This thread services notification channel clients and commands received
  * from various lttng-sessiond components over a command queue.
  */
-static
-void *thread_notification(void *data)
+static void *thread_notification(void *data)
 {
        int ret;
        struct notification_thread_handle *handle = (notification_thread_handle *) data;
@@ -700,22 +669,21 @@ void *thread_notification(void *data)
 
                        if (fd == state.notification_channel_socket) {
                                if (revents & LPOLLIN) {
-                                       ret = handle_notification_thread_client_connect(
-                                                       &state);
+                                       ret = handle_notification_thread_client_connect(&state);
                                        if (ret < 0) {
                                                goto error;
                                        }
-                               } else if (revents &
-                                               (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
+                               } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
                                        ERR("Notification socket poll error");
                                        goto error;
                                } else {
-                                       ERR("Unexpected poll events %u for notification socket %i", revents, fd);
+                                       ERR("Unexpected poll events %u for notification socket %i",
+                                           revents,
+                                           fd);
                                        goto error;
                                }
                        } else if (fd == handle->cmd_queue.event_fd) {
-                               ret = handle_notification_thread_command(handle,
-                                               &state);
+                               ret = handle_notification_thread_command(handle, &state);
                                if (ret < 0) {
                                        DBG("Error encountered while servicing command queue");
                                        goto error;
@@ -723,10 +691,9 @@ void *thread_notification(void *data)
                                        goto exit;
                                }
                        } else if (fd == handle->channel_monitoring_pipes.ust32_consumer ||
-                                       fd == handle->channel_monitoring_pipes.ust64_consumer ||
-                                       fd == handle->channel_monitoring_pipes.kernel_consumer) {
-                               ret = handle_channel_monitoring_pipe(fd,
-                                               revents, handle, &state);
+                                  fd == handle->channel_monitoring_pipes.ust64_consumer ||
+                                  fd == handle->channel_monitoring_pipes.kernel_consumer) {
+                               ret = handle_channel_monitoring_pipe(fd, revents, handle, &state);
                                if (ret) {
                                        goto error;
                                }
@@ -745,23 +712,23 @@ void *thread_notification(void *data)
                                         * receive the notifications to which
                                         * it was subscribing or unsubscribing.
                                         */
-                                       ret = handle_notification_thread_client_disconnect(
-                                                       fd, &state);
+                                       ret = handle_notification_thread_client_disconnect(fd,
+                                                                                          &state);
                                        if (ret) {
                                                goto error;
                                        }
                                } else {
                                        if (revents & LPOLLIN) {
-                                               ret = handle_notification_thread_client_in(
-                                                       &state, fd);
+                                               ret = handle_notification_thread_client_in(&state,
+                                                                                          fd);
                                                if (ret) {
                                                        goto error;
                                                }
                                        }
 
                                        if (revents & LPOLLOUT) {
-                                               ret = handle_notification_thread_client_out(
-                                                       &state, fd);
+                                               ret = handle_notification_thread_client_out(&state,
+                                                                                           fd);
                                                if (ret) {
                                                        goto error;
                                                }
@@ -786,11 +753,10 @@ end:
        rcu_thread_offline();
        rcu_unregister_thread();
        health_unregister(the_health_sessiond);
-       return NULL;
+       return nullptr;
 }
 
-static
-bool shutdown_notification_thread(void *thread_data)
+static bool shutdown_notification_thread(void *thread_data)
 {
        struct notification_thread_handle *handle = (notification_thread_handle *) thread_data;
 
@@ -798,16 +764,12 @@ bool shutdown_notification_thread(void *thread_data)
        return true;
 }
 
-struct lttng_thread *launch_notification_thread(
-               struct notification_thread_handle *handle)
+struct lttng_thread *launch_notification_thread(struct notification_thread_handle *handle)
 {
        struct lttng_thread *thread;
 
-       thread = lttng_thread_create("Notification",
-                       thread_notification,
-                       shutdown_notification_thread,
-                       NULL,
-                       handle);
+       thread = lttng_thread_create(
+               "Notification", thread_notification, shutdown_notification_thread, nullptr, handle);
        if (!thread) {
                goto error;
        }
@@ -820,5 +782,5 @@ struct lttng_thread *launch_notification_thread(
        wait_until_thread_is_ready(handle);
        return thread;
 error:
-       return NULL;
+       return nullptr;
 }
index 2ff86dc0613a04fb3e4e75618516c07fb83a9ccb..c995fc951d8e515c30c1c237b6be25b894bf20eb 100644 (file)
 
 #include "action-executor.hpp"
 #include "thread.hpp"
+
 #include <common/compat/poll.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/pipe.hpp>
-#include <lttng/trigger/trigger.h>
+
 #include <lttng/domain.h>
+#include <lttng/trigger/trigger.h>
+
 #include <pthread.h>
 #include <semaphore.h>
 #include <urcu.h>
 #include <urcu/list.h>
 #include <urcu/rculfhash.h>
 
-typedef uint64_t notification_client_id;
+using notification_client_id = uint64_t;
 
 /*
  * The notification thread holds no ownership of the tracer event source pipe
@@ -151,8 +154,8 @@ struct notification_thread_handle {
  *             for lookup on registration.
  *   - tracer_event_sources_list:
  *             A list of tracer event source (read side fd) of type
-*              struct notification_event_tracer_event_source_element.
-*
+ *              struct notification_event_tracer_event_source_element.
+ *
  *
  * The thread reacts to the following internal events:
  *   1) creation of a tracing channel,
@@ -315,13 +318,11 @@ struct notification_thread_state {
 };
 
 /* notification_thread_data takes ownership of the channel monitor pipes. */
-struct notification_thread_handle *notification_thread_handle_create(
-               struct lttng_pipe *ust32_channel_monitor_pipe,
-               struct lttng_pipe *ust64_channel_monitor_pipe,
-               struct lttng_pipe *kernel_channel_monitor_pipe);
-void notification_thread_handle_destroy(
-               struct notification_thread_handle *handle);
-struct lttng_thread *launch_notification_thread(
-               struct notification_thread_handle *handle);
+struct notification_thread_handle *
+notification_thread_handle_create(struct lttng_pipe *ust32_channel_monitor_pipe,
+                                 struct lttng_pipe *ust64_channel_monitor_pipe,
+                                 struct lttng_pipe *kernel_channel_monitor_pipe);
+void notification_thread_handle_destroy(struct notification_thread_handle *handle);
+struct lttng_thread *launch_notification_thread(struct notification_thread_handle *handle);
 
 #endif /* NOTIFICATION_THREAD_H */
index 1fff92d071ba01f1f70aac518493194c791485e0..03ac5866c83d562289c948c219d36a72d49a2f75 100644 (file)
@@ -7,16 +7,18 @@
 
 #define _LGPL_SOURCE
 
-#include <common/common.hpp>
-#include <common/utils.hpp>
-
 #include "fd-limit.hpp"
+#include "health-sessiond.hpp"
 #include "lttng-sessiond.hpp"
 #include "notify-apps.hpp"
-#include "health-sessiond.hpp"
 #include "testpoint.hpp"
-#include "utils.hpp"
 #include "thread.hpp"
+#include "utils.hpp"
+
+#include <common/common.hpp>
+#include <common/utils.hpp>
+
+#include <fcntl.h>
 
 namespace {
 struct thread_notifiers {
@@ -30,20 +32,19 @@ struct thread_notifiers {
  */
 static void *thread_application_notification(void *data)
 {
-       int i, ret, pollfd, err = -1;
+       int i, ret, err = -1;
        ssize_t size_ret;
-       uint32_t revents, nb_fd;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        struct thread_notifiers *notifiers = (thread_notifiers *) data;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(notifiers->quit_pipe);
 
        DBG("[ust-thread] Manage application notify command");
 
        rcu_register_thread();
        rcu_thread_online();
 
-       health_register(the_health_sessiond,
-                       HEALTH_SESSIOND_TYPE_APP_MANAGE_NOTIFY);
+       health_register(the_health_sessiond, HEALTH_SESSIOND_TYPE_APP_MANAGE_NOTIFY);
 
        if (testpoint(sessiond_thread_app_manage_notify)) {
                goto error_testpoint;
@@ -57,29 +58,28 @@ static void *thread_application_notification(void *data)
        }
 
        /* Add notify pipe to the pollset. */
-       ret = lttng_poll_add(&events, notifiers->apps_cmd_notify_pipe_read_fd,
-                       LPOLLIN | LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+       ret = lttng_poll_add(
+               &events, notifiers->apps_cmd_notify_pipe_read_fd, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                goto error;
        }
 
-       ret = lttng_poll_add(&events, quit_pipe_read_fd,
-                       LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN);
        if (ret < 0) {
                goto error;
        }
 
        health_code_update();
 
-       while (1) {
+       while (true) {
                DBG3("[ust-thread] Manage notify polling");
 
                /* Inifinite blocking call, waiting for transmission */
-restart:
+       restart:
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
                DBG3("[ust-thread] Manage notify return from poll on %d fds",
-                               LTTNG_POLL_GETNB(&events));
+                    LTTNG_POLL_GETNB(&events));
                health_poll_exit();
                if (ret < 0) {
                        /*
@@ -97,33 +97,38 @@ restart:
                        health_code_update();
 
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       if (pollfd == quit_pipe_read_fd) {
+                       /* Activity on thread quit pipe, exiting. */
+                       if (pollfd == thread_quit_pipe_fd) {
+                               DBG("Activity on thread quit pipe");
                                err = 0;
                                goto exit;
-                       } else if (pollfd == notifiers->apps_cmd_notify_pipe_read_fd) {
+                       }
+
+                       if (pollfd == notifiers->apps_cmd_notify_pipe_read_fd) {
                                /* Inspect the apps cmd pipe */
                                int sock;
 
                                if (revents & LPOLLIN) {
                                        /* Get socket from dispatch thread. */
-                                       size_ret = lttng_read(notifiers->apps_cmd_notify_pipe_read_fd,
-                                                       &sock, sizeof(sock));
+                                       size_ret =
+                                               lttng_read(notifiers->apps_cmd_notify_pipe_read_fd,
+                                                          &sock,
+                                                          sizeof(sock));
                                        if (size_ret < sizeof(sock)) {
                                                PERROR("read apps notify pipe");
                                                goto error;
                                        }
                                        health_code_update();
 
-                                       ret = lttng_poll_add(&events, sock,
-                                                       LPOLLIN | LPOLLERR | LPOLLHUP | LPOLLRDHUP);
+                                       ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLRDHUP);
                                        if (ret < 0) {
                                                /*
-                                                * It's possible we've reached the max poll fd allowed.
-                                                * Let's close the socket but continue normal execution.
+                                                * It's possible we've reached the max poll fd
+                                                * allowed. Let's close the socket but continue
+                                                * normal execution.
                                                 */
                                                ret = close(sock);
                                                if (ret) {
@@ -137,7 +142,9 @@ restart:
                                        ERR("Apps notify command pipe error");
                                        goto error;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                        } else {
@@ -154,7 +161,8 @@ restart:
                                                        goto error;
                                                }
 
-                                               /* The socket is closed after a grace period here. */
+                                               /* The socket is closed after a grace period here.
+                                                */
                                                ust_app_notify_sock_unregister(pollfd);
                                        }
                                } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
@@ -167,7 +175,9 @@ restart:
                                        /* The socket is closed after a grace period here. */
                                        ust_app_notify_sock_unregister(pollfd);
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto error;
                                }
                                health_code_update();
@@ -189,7 +199,7 @@ error_testpoint:
        health_unregister(the_health_sessiond);
        rcu_thread_offline();
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_application_notification_thread(void *data)
@@ -227,10 +237,10 @@ bool launch_application_notification_thread(int apps_cmd_notify_pipe_read_fd)
        notifiers->quit_pipe = quit_pipe;
 
        thread = lttng_thread_create("Application notification",
-                       thread_application_notification,
-                       shutdown_application_notification_thread,
-                       cleanup_application_notification_thread,
-                       notifiers);
+                                    thread_application_notification,
+                                    shutdown_application_notification_thread,
+                                    cleanup_application_notification_thread,
+                                    notifiers);
        if (!thread) {
                goto error;
        }
index 152a52a2058b431936ed4f3b5842001fb7287ec7..75301e2020aab55e6b77a93d338c661b8b5b67bd 100644 (file)
@@ -14,9 +14,8 @@ bool launch_application_notification_thread(int apps_cmd_notify_pipe_read_fd);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static
-bool launch_application_notification_thread(
-               int apps_cmd_notify_pipe_read_fd __attribute__((unused)))
+static bool launch_application_notification_thread(int apps_cmd_notify_pipe_read_fd
+                                                  __attribute__((unused)))
 {
        return true;
 }
index a3122da758395bb4a3a0db341e0f6df81a72c03f..ebc8bb548755e7983f40354427668d67d6be3ccb 100644 (file)
@@ -7,11 +7,12 @@
  *
  */
 
-#include <signal.h>
 #include "lttng-sessiond.hpp"
 
+#include <signal.h>
+
 /* Notify parents that we are ready for cmd and health check */
-void sessiond_signal_parents(void)
+void sessiond_signal_parents()
 {
        /*
         * Notify parent pid that we are ready to accept command
index 34efeac40f57729fd0811806e56cb7665847fefc..0191adc9420f04cc0c96943e3477f4a945f51b14 100644 (file)
@@ -7,22 +7,24 @@
  *
  */
 
-#include <stddef.h>
-#include <stdlib.h>
-#include <urcu.h>
+#include "fd-limit.hpp"
+#include "health-sessiond.hpp"
+#include "lttng-sessiond.hpp"
+#include "register.hpp"
+#include "testpoint.hpp"
+#include "thread.hpp"
+#include "utils.hpp"
+
 #include <common/futex.hpp>
 #include <common/macros.hpp>
 #include <common/shm.hpp>
 #include <common/utils.hpp>
-#include <sys/stat.h>
 
-#include "register.hpp"
-#include "lttng-sessiond.hpp"
-#include "testpoint.hpp"
-#include "health-sessiond.hpp"
-#include "fd-limit.hpp"
-#include "utils.hpp"
-#include "thread.hpp"
+#include <fcntl.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <urcu.h>
 
 namespace {
 struct thread_state {
@@ -37,17 +39,15 @@ struct thread_state {
 /*
  * Creates the application socket.
  */
-static int create_application_socket(void)
+static int create_application_socket()
 {
        int ret = 0;
        int apps_sock;
 
        /* Create the application unix socket */
-       apps_sock = lttcomm_create_unix_sock(
-                       the_config.apps_unix_sock_path.value);
+       apps_sock = lttcomm_create_unix_sock(the_config.apps_unix_sock_path.value);
        if (apps_sock < 0) {
-               ERR("Create unix sock failed: %s",
-                               the_config.apps_unix_sock_path.value);
+               ERR("Create unix sock failed: %s", the_config.apps_unix_sock_path.value);
                ret = -1;
                goto end;
        }
@@ -56,17 +56,16 @@ static int create_application_socket(void)
        ret = utils_set_fd_cloexec(apps_sock);
        if (ret < 0) {
                ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
-                               "Continuing but note that the consumer daemon will have a "
-                               "reference to this socket on exec()", apps_sock);
+                   "Continuing but note that the consumer daemon will have a "
+                   "reference to this socket on exec()",
+                   apps_sock);
        }
 
        /* File permission MUST be 666 */
        ret = chmod(the_config.apps_unix_sock_path.value,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |
-                                       S_IWOTH);
+                   S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
        if (ret < 0) {
-               PERROR("Set file permissions failed on %s",
-                               the_config.apps_unix_sock_path.value);
+               PERROR("Set file permissions failed on %s", the_config.apps_unix_sock_path.value);
                goto error_close_socket;
        }
 
@@ -93,9 +92,8 @@ static int notify_ust_apps(int active, bool is_root)
        DBG("Notifying applications of session daemon state: %d", active);
 
        /* See shm.c for this call implying mmap, shm and futex calls */
-       wait_shm_mmap = shm_ust_get_mmap(
-                       the_config.wait_shm_path.value, is_root);
-       if (wait_shm_mmap == NULL) {
+       wait_shm_mmap = shm_ust_get_mmap(the_config.wait_shm_path.value, is_root);
+       if (wait_shm_mmap == nullptr) {
                goto error;
        }
 
@@ -153,19 +151,18 @@ static void thread_init_cleanup(void *data)
  */
 static void *thread_application_registration(void *data)
 {
-       int sock = -1, i, ret, pollfd, err = -1;
-       uint32_t revents, nb_fd;
+       int sock = -1, i, ret, err = -1;
+       uint32_t nb_fd;
        struct lttng_poll_event events;
        /*
         * Gets allocated in this thread, enqueued to a global queue, dequeued
         * and freed in the manage apps thread.
         */
-       struct ust_command *ust_cmd = NULL;
+       struct ust_command *ust_cmd = nullptr;
        const bool is_root = (getuid() == 0);
        struct thread_state *thread_state = (struct thread_state *) data;
        const int application_socket = thread_state->application_socket;
-       const int quit_pipe_read_fd = lttng_pipe_get_readfd(
-                       thread_state->quit_pipe);
+       const auto thread_quit_pipe_fd = lttng_pipe_get_readfd(thread_state->quit_pipe);
 
        DBG("[thread] Manage application registration started");
 
@@ -193,7 +190,7 @@ static void *thread_application_registration(void *data)
        }
 
        /* Add the application registration socket */
-       ret = lttng_poll_add(&events, quit_pipe_read_fd, LPOLLIN | LPOLLRDHUP);
+       ret = lttng_poll_add(&events, thread_quit_pipe_fd, LPOLLIN | LPOLLRDHUP);
        if (ret < 0) {
                goto error_poll_add;
        }
@@ -205,7 +202,7 @@ static void *thread_application_registration(void *data)
                goto error_poll_add;
        }
 
-       while (1) {
+       while (true) {
                DBG("Accepting application registration");
 
                /* Inifinite blocking call, waiting for transmission */
@@ -229,116 +226,119 @@ static void *thread_application_registration(void *data)
                        health_code_update();
 
                        /* Fetch once the poll data */
-                       revents = LTTNG_POLL_GETEV(&events, i);
-                       pollfd = LTTNG_POLL_GETFD(&events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&events, i);
+                       const auto pollfd = LTTNG_POLL_GETFD(&events, i);
 
-                       /* Thread quit pipe has been closed. Killing thread. */
-                       if (pollfd == quit_pipe_read_fd) {
+                       /* Activity on thread quit pipe, closing. */
+                       if (pollfd == thread_quit_pipe_fd) {
                                err = 0;
                                goto exit;
-                       } else {
-                               /* Event on the registration socket */
-                               if (revents & LPOLLIN) {
-                                       sock = lttcomm_accept_unix_sock(application_socket);
-                                       if (sock < 0) {
-                                               goto error;
-                                       }
+                       }
 
-                                       /*
-                                        * Set socket timeout for both receiving and ending.
-                                        * app_socket_timeout is in seconds, whereas
-                                        * lttcomm_setsockopt_rcv_timeout and
-                                        * lttcomm_setsockopt_snd_timeout expect msec as
-                                        * parameter.
-                                        */
-                                       if (the_config.app_socket_timeout >= 0) {
-                                               (void) lttcomm_setsockopt_rcv_timeout(sock,
-                                                               the_config.app_socket_timeout * 1000);
-                                               (void) lttcomm_setsockopt_snd_timeout(sock,
-                                                               the_config.app_socket_timeout * 1000);
-                                       }
+                       /* Event on the registration socket. */
+                       if (revents & LPOLLIN) {
+                               sock = lttcomm_accept_unix_sock(application_socket);
+                               if (sock < 0) {
+                                       goto error;
+                               }
 
-                                       /*
-                                        * Set the CLOEXEC flag. Return code is useless because
-                                        * either way, the show must go on.
-                                        */
-                                       (void) utils_set_fd_cloexec(sock);
-
-                                       /* Create UST registration command for enqueuing */
-                                       ust_cmd = zmalloc<ust_command>();
-                                       if (ust_cmd == NULL) {
-                                               PERROR("ust command zmalloc");
-                                               ret = close(sock);
-                                               if (ret) {
-                                                       PERROR("close");
-                                               }
-                                               sock = -1;
-                                               goto error;
-                                       }
+                               /*
+                                * Set socket timeout for both receiving and ending.
+                                * app_socket_timeout is in seconds, whereas
+                                * lttcomm_setsockopt_rcv_timeout and
+                                * lttcomm_setsockopt_snd_timeout expect msec as
+                                * parameter.
+                                */
+                               if (the_config.app_socket_timeout >= 0) {
+                                       (void) lttcomm_setsockopt_rcv_timeout(
+                                               sock, the_config.app_socket_timeout * 1000);
+                                       (void) lttcomm_setsockopt_snd_timeout(
+                                               sock, the_config.app_socket_timeout * 1000);
+                               }
 
-                                       /*
-                                        * Using message-based transmissions to ensure we don't
-                                        * have to deal with partially received messages.
-                                        */
-                                       ret = lttng_fd_get(LTTNG_FD_APPS, 1);
-                                       if (ret < 0) {
-                                               ERR("Exhausted file descriptors allowed for applications.");
-                                               free(ust_cmd);
-                                               ret = close(sock);
-                                               if (ret) {
-                                                       PERROR("close");
-                                               }
-                                               sock = -1;
-                                               continue;
+                               /*
+                                * Set the CLOEXEC flag. Return code is useless because
+                                * either way, the show must go on.
+                                */
+                               (void) utils_set_fd_cloexec(sock);
+
+                               /* Create UST registration command for enqueuing */
+                               ust_cmd = zmalloc<ust_command>();
+                               if (ust_cmd == nullptr) {
+                                       PERROR("ust command zmalloc");
+                                       ret = close(sock);
+                                       if (ret) {
+                                               PERROR("close");
                                        }
+                                       sock = -1;
+                                       goto error;
+                               }
 
-                                       health_code_update();
-                                       ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
-                                       if (ret < 0) {
-                                               free(ust_cmd);
-                                               /* Close socket of the application. */
-                                               ret = close(sock);
-                                               if (ret) {
-                                                       PERROR("close");
-                                               }
-                                               lttng_fd_put(LTTNG_FD_APPS, 1);
-                                               sock = -1;
-                                               continue;
+                               /*
+                                * Using message-based transmissions to ensure we don't
+                                * have to deal with partially received messages.
+                                */
+                               ret = lttng_fd_get(LTTNG_FD_APPS, 1);
+                               if (ret < 0) {
+                                       ERR("Exhausted file descriptors allowed for applications.");
+                                       free(ust_cmd);
+                                       ret = close(sock);
+                                       if (ret) {
+                                               PERROR("close");
                                        }
-                                       health_code_update();
-
-                                       ust_cmd->sock = sock;
                                        sock = -1;
+                                       continue;
+                               }
 
-                                       DBG("UST registration received with pid:%d ppid:%d uid:%d"
-                                                       " gid:%d sock:%d name:%s (version %d.%d)",
-                                                       ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
-                                                       ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
-                                                       ust_cmd->sock, ust_cmd->reg_msg.name,
-                                                       ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
-
-                                       /*
-                                        * Lock free enqueue the registration request. The red pill
-                                        * has been taken! This apps will be part of the *system*.
-                                        */
-                                       cds_wfcq_head_ptr_t head;
-                                       head.h = &thread_state->ust_cmd_queue->head;
-                                       cds_wfcq_enqueue(head,
-                                                       &thread_state->ust_cmd_queue->tail,
-                                                       &ust_cmd->node);
-
-                                       /*
-                                        * Wake the registration queue futex. Implicit memory
-                                        * barrier with the exchange in cds_wfcq_enqueue.
-                                        */
-                                       futex_nto1_wake(&thread_state->ust_cmd_queue->futex);
-                               } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
-                                       ERR("Register apps socket poll error");
-                                       goto error;
-                               } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
-                                       goto error;
+                               health_code_update();
+                               ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
+                               if (ret < 0) {
+                                       free(ust_cmd);
+                                       /* Close socket of the application. */
+                                       ret = close(sock);
+                                       if (ret) {
+                                               PERROR("close");
+                                       }
+                                       lttng_fd_put(LTTNG_FD_APPS, 1);
+                                       sock = -1;
+                                       continue;
                                }
+                               health_code_update();
+
+                               ust_cmd->sock = sock;
+                               sock = -1;
+
+                               DBG("UST registration received with pid:%d ppid:%d uid:%d"
+                                   " gid:%d sock:%d name:%s (version %d.%d)",
+                                   ust_cmd->reg_msg.pid,
+                                   ust_cmd->reg_msg.ppid,
+                                   ust_cmd->reg_msg.uid,
+                                   ust_cmd->reg_msg.gid,
+                                   ust_cmd->sock,
+                                   ust_cmd->reg_msg.name,
+                                   ust_cmd->reg_msg.major,
+                                   ust_cmd->reg_msg.minor);
+
+                               /*
+                                * Lock free enqueue the registration request. The red pill
+                                * has been taken! This apps will be part of the *system*.
+                                */
+                               cds_wfcq_head_ptr_t head;
+                               head.h = &thread_state->ust_cmd_queue->head;
+                               cds_wfcq_enqueue(
+                                       head, &thread_state->ust_cmd_queue->tail, &ust_cmd->node);
+
+                               /*
+                                * Wake the registration queue futex. Implicit memory
+                                * barrier with the exchange in cds_wfcq_enqueue.
+                                */
+                               futex_nto1_wake(&thread_state->ust_cmd_queue->futex);
+                       } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
+                               ERR("Register apps socket poll error");
+                               goto error;
+                       } else {
+                               ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                               goto error;
                        }
                }
        }
@@ -371,7 +371,7 @@ error_create_poll:
                ERR("Health error occurred in %s", __func__);
        }
        health_unregister(the_health_sessiond);
-       return NULL;
+       return nullptr;
 }
 
 static bool shutdown_application_registration_thread(void *data)
@@ -382,13 +382,12 @@ static bool shutdown_application_registration_thread(void *data)
        return notify_thread_pipe(write_fd) == 1;
 }
 
-struct lttng_thread *launch_application_registration_thread(
-               struct ust_cmd_queue *cmd_queue)
+struct lttng_thread *launch_application_registration_thread(struct ust_cmd_queue *cmd_queue)
 {
        int ret;
        struct lttng_pipe *quit_pipe;
-       struct thread_state *thread_state = NULL;
-       struct lttng_thread *thread = NULL;
+       struct thread_state *thread_state = nullptr;
+       struct lttng_thread *thread = nullptr;
        const bool is_root = (getuid() == 0);
        int application_socket = -1;
 
@@ -410,10 +409,10 @@ struct lttng_thread *launch_application_registration_thread(
        sem_init(&thread_state->ready, 0, 0);
 
        thread = lttng_thread_create("UST application registration",
-                       thread_application_registration,
-                       shutdown_application_registration_thread,
-                       cleanup_application_registration_thread,
-                       thread_state);
+                                    thread_application_registration,
+                                    shutdown_application_registration_thread,
+                                    cleanup_application_registration_thread,
+                                    thread_state);
        if (!thread) {
                goto error;
        }
@@ -424,7 +423,7 @@ struct lttng_thread *launch_application_registration_thread(
         */
        application_socket = -1;
        if (!wait_thread_status(thread_state)) {
-               thread_state = NULL;
+               thread_state = nullptr;
                goto error;
        }
 
@@ -432,8 +431,8 @@ struct lttng_thread *launch_application_registration_thread(
        ret = notify_ust_apps(1, is_root);
        if (ret < 0) {
                ERR("Failed to notify applications or create the wait shared memory.\n"
-                       "Execution continues but there might be problems for already\n"
-                       "running applications that wishes to register.");
+                   "Execution continues but there might be problems for already\n"
+                   "running applications that wishes to register.");
        }
 
        return thread;
@@ -446,5 +445,5 @@ error:
                }
        }
 error_alloc:
-       return NULL;
+       return nullptr;
 }
index ef82a2ca286dcd8f56affdaf3d61af7156452a4d..2071475de7e9eb3c3114f080e3de73c40a7f91d2 100644 (file)
 #ifndef SESSIOND_APPLICATION_REGISTRATION_THREAD_H
 #define SESSIOND_APPLICATION_REGISTRATION_THREAD_H
 
-#include <stdbool.h>
 #include "lttng-sessiond.hpp"
 
-struct lttng_thread *launch_application_registration_thread(
-               struct ust_cmd_queue *cmd_queue);
+#include <stdbool.h>
+
+struct lttng_thread *launch_application_registration_thread(struct ust_cmd_queue *cmd_queue);
 
 #endif /* SESSIOND_APPLICATION_REGISTRATION_THREAD_H */
diff --git a/src/bin/lttng-sessiond/rotate.cpp b/src/bin/lttng-sessiond/rotate.cpp
deleted file mode 100644 (file)
index d1be8f6..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2017 Julien Desfossez <jdesfossez@efficios.com>
- * Copyright (C) 2018 Jérémie Galarneau <jeremie.galarneau@efficios.com>
- *
- * SPDX-License-Identifier: GPL-2.0-only
- *
- */
-
-#define _LGPL_SOURCE
-#include <lttng/trigger/trigger.h>
-#include <common/error.hpp>
-#include <common/config/session-config.hpp>
-#include <common/defaults.hpp>
-#include <common/utils.hpp>
-#include <common/futex.hpp>
-#include <common/align.hpp>
-#include <common/time.hpp>
-#include <common/hashtable/utils.hpp>
-#include <common/kernel-ctl/kernel-ctl.hpp>
-#include <common/credentials.hpp>
-#include <sys/stat.h>
-#include <time.h>
-#include <signal.h>
-#include <inttypes.h>
-
-#include <lttng/notification/channel-internal.hpp>
-#include <lttng/rotate-internal.hpp>
-#include <lttng/condition/condition-internal.hpp>
-#include <lttng/action/action-internal.hpp>
-
-#include "session.hpp"
-#include "rotate.hpp"
-#include "rotation-thread.hpp"
-#include "lttng-sessiond.hpp"
-#include "health-sessiond.hpp"
-#include "cmd.hpp"
-#include "utils.hpp"
-#include "notification-thread-commands.hpp"
-
-#include <urcu.h>
-#include <urcu/list.h>
-#include <urcu/rculfhash.h>
-
-int subscribe_session_consumed_size_rotation(struct ltt_session *session, uint64_t size,
-               struct notification_thread_handle *notification_thread_handle)
-{
-       int ret;
-       enum lttng_condition_status condition_status;
-       enum lttng_notification_channel_status nc_status;
-       struct lttng_condition *rotate_condition = nullptr;
-       struct lttng_action *notify_action = nullptr;
-       const struct lttng_credentials session_creds = {
-               .uid = LTTNG_OPTIONAL_INIT_VALUE(session->uid),
-               .gid = LTTNG_OPTIONAL_INIT_VALUE(session->gid),
-       };
-
-       rotate_condition = lttng_condition_session_consumed_size_create();
-       if (!rotate_condition) {
-               ERR("Failed to create session consumed size condition object");
-               ret = -1;
-               goto end;
-       }
-
-       condition_status = lttng_condition_session_consumed_size_set_threshold(
-                       rotate_condition, size);
-       if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               ERR("Could not set session consumed size condition threshold (size = %" PRIu64 ")",
-                               size);
-               ret = -1;
-               goto end;
-       }
-
-       condition_status =
-                       lttng_condition_session_consumed_size_set_session_name(
-                               rotate_condition, session->name);
-       if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               ERR("Could not set session consumed size condition session name (name = %s)",
-                               session->name);
-               ret = -1;
-               goto end;
-       }
-
-       notify_action = lttng_action_notify_create();
-       if (!notify_action) {
-               ERR("Could not create notify action");
-               ret = -1;
-               goto end;
-       }
-
-       LTTNG_ASSERT(!session->rotate_trigger);
-       session->rotate_trigger = lttng_trigger_create(rotate_condition,
-                       notify_action);
-       if (!session->rotate_trigger) {
-               ERR("Could not create size-based rotation trigger");
-               ret = -1;
-               goto end;
-       }
-
-       /* Ensure this trigger is not visible to external users. */
-       lttng_trigger_set_hidden(session->rotate_trigger);
-       lttng_trigger_set_credentials(
-                       session->rotate_trigger, &session_creds);
-
-       nc_status = lttng_notification_channel_subscribe(
-                       rotate_notification_channel, rotate_condition);
-       if (nc_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
-               ERR("Could not subscribe to session consumed size notification");
-               ret = -1;
-               goto end;
-       }
-
-       ret = notification_thread_command_register_trigger(
-                       notification_thread_handle, session->rotate_trigger,
-                       true);
-       if (ret < 0 && ret != -LTTNG_ERR_TRIGGER_EXISTS) {
-               ERR("Register trigger, %s", lttng_strerror(ret));
-               ret = -1;
-               goto end;
-       }
-
-       ret = 0;
-
-end:
-       lttng_condition_put(rotate_condition);
-       lttng_action_put(notify_action);
-       if (ret) {
-               lttng_trigger_put(session->rotate_trigger);
-       }
-       return ret;
-}
-
-int unsubscribe_session_consumed_size_rotation(struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle)
-{
-       int ret = 0;
-       enum lttng_notification_channel_status status;
-
-       LTTNG_ASSERT(session->rotate_trigger);
-       status = lttng_notification_channel_unsubscribe(
-                       rotate_notification_channel,
-                       lttng_trigger_get_const_condition(session->rotate_trigger));
-       if (status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
-               ERR("Session unsubscribe error: %d", (int) status);
-               ret = -1;
-               goto end;
-       }
-
-       ret = notification_thread_command_unregister_trigger(
-                       notification_thread_handle, session->rotate_trigger);
-       if (ret != LTTNG_OK) {
-               ERR("Session unregister trigger error: %d", ret);
-               goto end;
-       }
-
-       lttng_trigger_put(session->rotate_trigger);
-       session->rotate_trigger = nullptr;
-
-       ret = 0;
-end:
-       return ret;
-}
diff --git a/src/bin/lttng-sessiond/rotate.hpp b/src/bin/lttng-sessiond/rotate.hpp
deleted file mode 100644 (file)
index 965a8c7..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2017 Julien Desfossez <jdesfossez@efficios.com>
- * Copyright (C) 2018 Jérémie Galarneau <jeremie.galarneau@efficios.com>
- *
- * SPDX-License-Identifier: GPL-2.0-only
- *
- */
-
-#ifndef ROTATE_H
-#define ROTATE_H
-
-#include "rotation-thread.hpp"
-#include <stdint.h>
-
-/*
- * Subscribe/unsubscribe the notification_channel from the rotation_thread to
- * session usage notifications to perform size-based rotations.
- */
-int subscribe_session_consumed_size_rotation(struct ltt_session *session,
-               uint64_t size,
-               struct notification_thread_handle *notification_thread_handle);
-int unsubscribe_session_consumed_size_rotation(struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle);
-
-#endif /* ROTATE_H */
index 22891dd13ec4d5f20c99d10aa650c0fe0af65e7c..a26b38eebca970230f3a02d8bee8c9fdcba92bc0 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <lttng/trigger/trigger.h>
-#include <common/error.hpp>
+#include "cmd.hpp"
+#include "health-sessiond.hpp"
+#include "lttng-sessiond.hpp"
+#include "notification-thread-commands.hpp"
+#include "rotation-thread.hpp"
+#include "session.hpp"
+#include "thread.hpp"
+#include "timer.hpp"
+#include "utils.hpp"
+
+#include <common/align.hpp>
 #include <common/config/session-config.hpp>
 #include <common/defaults.hpp>
-#include <common/utils.hpp>
+#include <common/error.hpp>
+#include <common/eventfd.hpp>
+#include <common/exception.hpp>
+#include <common/file-descriptor.hpp>
+#include <common/format.hpp>
 #include <common/futex.hpp>
-#include <common/align.hpp>
-#include <common/time.hpp>
 #include <common/hashtable/utils.hpp>
-#include <sys/stat.h>
-#include <time.h>
-#include <signal.h>
-#include <inttypes.h>
-
 #include <common/kernel-ctl/kernel-ctl.hpp>
-#include <lttng/notification/channel-internal.hpp>
-#include <lttng/rotate-internal.hpp>
-#include <lttng/location-internal.hpp>
+#include <common/locked-reference.hpp>
+#include <common/make-unique-wrapper.hpp>
+#include <common/pthread-lock.hpp>
+#include <common/scope-exit.hpp>
+#include <common/time.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/action/action-internal.hpp>
 #include <lttng/condition/condition-internal.hpp>
+#include <lttng/location-internal.hpp>
+#include <lttng/notification/channel-internal.hpp>
 #include <lttng/notification/notification-internal.hpp>
+#include <lttng/rotate-internal.hpp>
+#include <lttng/trigger/trigger.h>
 
-#include "rotation-thread.hpp"
-#include "lttng-sessiond.hpp"
-#include "health-sessiond.hpp"
-#include "rotate.hpp"
-#include "cmd.hpp"
-#include "session.hpp"
-#include "timer.hpp"
-#include "notification-thread-commands.hpp"
-#include "utils.hpp"
-#include "thread.hpp"
-
+#include <fcntl.h>
+#include <inttypes.h>
+#include <memory>
+#include <signal.h>
+#include <sys/eventfd.h>
+#include <sys/stat.h>
+#include <time.h>
 #include <urcu.h>
 #include <urcu/list.h>
 
-struct lttng_notification_channel *rotate_notification_channel = NULL;
-
-struct rotation_thread {
-       struct lttng_poll_event events;
-};
+namespace ls = lttng::sessiond;
 
 /*
  * The timer thread enqueues jobs and wakes up the rotation thread.
  * When the rotation thread wakes up, it empties the queue.
  */
-struct rotation_thread_timer_queue {
+struct ls::rotation_thread_timer_queue {
        struct lttng_pipe *event_pipe;
        struct cds_list_head list;
        pthread_mutex_t lock;
 };
 
-struct rotation_thread_handle {
-       struct rotation_thread_timer_queue *rotation_timer_queue;
-       /* Access to the notification thread cmd_queue */
-       struct notification_thread_handle *notification_thread_handle;
-       /* Thread-specific quit pipe. */
-       struct lttng_pipe *quit_pipe;
-};
-
 namespace {
 struct rotation_thread_job {
-       enum rotation_thread_job_type type;
+       using uptr =
+               std::unique_ptr<rotation_thread_job,
+                               lttng::memory::create_deleter_class<rotation_thread_job,
+                                                                   lttng::memory::free>::deleter>;
+
+       enum ls::rotation_thread_job_type type;
        struct ltt_session *session;
        /* List member in struct rotation_thread_timer_queue. */
        struct cds_list_head head;
 };
-} /* namespace */
 
-static
-const char *get_job_type_str(enum rotation_thread_job_type job_type)
+const char *get_job_type_str(enum ls::rotation_thread_job_type job_type)
 {
        switch (job_type) {
-       case ROTATION_THREAD_JOB_TYPE_CHECK_PENDING_ROTATION:
+       case ls::rotation_thread_job_type::CHECK_PENDING_ROTATION:
                return "CHECK_PENDING_ROTATION";
-       case ROTATION_THREAD_JOB_TYPE_SCHEDULED_ROTATION:
+       case ls::rotation_thread_job_type::SCHEDULED_ROTATION:
                return "SCHEDULED_ROTATION";
        default:
                abort();
        }
 }
 
-struct rotation_thread_timer_queue *rotation_thread_timer_queue_create(void)
-{
-       struct rotation_thread_timer_queue *queue = NULL;
-
-       queue = zmalloc<rotation_thread_timer_queue>();
-       if (!queue) {
-               PERROR("Failed to allocate timer rotate queue");
-               goto end;
-       }
-
-       queue->event_pipe = lttng_pipe_open(FD_CLOEXEC | O_NONBLOCK);
-       CDS_INIT_LIST_HEAD(&queue->list);
-       pthread_mutex_init(&queue->lock, NULL);
-end:
-       return queue;
-}
-
-void rotation_thread_timer_queue_destroy(
-               struct rotation_thread_timer_queue *queue)
-{
-       if (!queue) {
-               return;
-       }
-
-       lttng_pipe_destroy(queue->event_pipe);
-
-       pthread_mutex_lock(&queue->lock);
-       LTTNG_ASSERT(cds_list_empty(&queue->list));
-       pthread_mutex_unlock(&queue->lock);
-       pthread_mutex_destroy(&queue->lock);
-       free(queue);
-}
-
-/*
- * Destroy the thread data previously created by the init function.
- */
-void rotation_thread_handle_destroy(
-               struct rotation_thread_handle *handle)
-{
-       lttng_pipe_destroy(handle->quit_pipe);
-       free(handle);
-}
-
-struct rotation_thread_handle *rotation_thread_handle_create(
-               struct rotation_thread_timer_queue *rotation_timer_queue,
-               struct notification_thread_handle *notification_thread_handle)
-{
-       struct rotation_thread_handle *handle;
-
-       handle = zmalloc<rotation_thread_handle>();
-       if (!handle) {
-               goto end;
-       }
-
-       handle->rotation_timer_queue = rotation_timer_queue;
-       handle->notification_thread_handle = notification_thread_handle;
-       handle->quit_pipe = lttng_pipe_open(FD_CLOEXEC);
-       if (!handle->quit_pipe) {
-               goto error;
-       }
-
-end:
-       return handle;
-error:
-       rotation_thread_handle_destroy(handle);
-       return NULL;
-}
-
 /*
  * Called with the rotation_thread_timer_queue lock held.
  * Return true if the same timer job already exists in the queue, false if not.
  */
-static
-bool timer_job_exists(const struct rotation_thread_timer_queue *queue,
-               enum rotation_thread_job_type job_type,
-               struct ltt_session *session)
+bool timer_job_exists(const ls::rotation_thread_timer_queue *queue,
+                     ls::rotation_thread_job_type job_type,
+                     ltt_session *session)
 {
        bool exists = false;
        struct rotation_thread_job *job;
 
-       cds_list_for_each_entry(job, &queue->list, head) {
+       cds_list_for_each_entry (job, &queue->list, head) {
                if (job->session == session && job->type == job_type) {
                        exists = true;
                        goto end;
@@ -178,151 +112,7 @@ end:
        return exists;
 }
 
-void rotation_thread_enqueue_job(struct rotation_thread_timer_queue *queue,
-               enum rotation_thread_job_type job_type,
-               struct ltt_session *session)
-{
-       int ret;
-       const char dummy = '!';
-       struct rotation_thread_job *job = NULL;
-       const char *job_type_str = get_job_type_str(job_type);
-
-       pthread_mutex_lock(&queue->lock);
-       if (timer_job_exists(queue, job_type, session)) {
-               /*
-                * This timer job is already pending, we don't need to add
-                * it.
-                */
-               goto end;
-       }
-
-       job = zmalloc<rotation_thread_job>();
-       if (!job) {
-               PERROR("Failed to allocate rotation thread job of type \"%s\" for session \"%s\"",
-                               job_type_str, session->name);
-               goto end;
-       }
-       /* No reason for this to fail as the caller must hold a reference. */
-       (void) session_get(session);
-
-       job->session = session;
-       job->type = job_type;
-       cds_list_add_tail(&job->head, &queue->list);
-
-       ret = lttng_write(lttng_pipe_get_writefd(queue->event_pipe), &dummy,
-                       sizeof(dummy));
-       if (ret < 0) {
-               /*
-                * We do not want to block in the timer handler, the job has
-                * been enqueued in the list, the wakeup pipe is probably full,
-                * the job will be processed when the rotation_thread catches
-                * up.
-                */
-               DIAGNOSTIC_PUSH
-               DIAGNOSTIC_IGNORE_LOGICAL_OP
-               if (errno == EAGAIN || errno == EWOULDBLOCK) {
-               DIAGNOSTIC_POP
-                       /*
-                        * Not an error, but would be surprising and indicate
-                        * that the rotation thread can't keep up with the
-                        * current load.
-                        */
-                       DBG("Wake-up pipe of rotation thread job queue is full");
-                       goto end;
-               }
-               PERROR("Failed to wake-up the rotation thread after pushing a job of type \"%s\" for session \"%s\"",
-                               job_type_str, session->name);
-               goto end;
-       }
-
-end:
-       pthread_mutex_unlock(&queue->lock);
-}
-
-static
-int init_poll_set(struct lttng_poll_event *poll_set,
-               struct rotation_thread_handle *handle)
-{
-       int ret;
-
-       /*
-        * Create pollset with size 3:
-        *      - rotation thread quit pipe,
-        *      - rotation thread timer queue pipe,
-        *      - notification channel sock,
-        */
-       ret = lttng_poll_create(poll_set, 5, LTTNG_CLOEXEC);
-       if (ret < 0) {
-               goto error;
-       }
-
-       ret = lttng_poll_add(poll_set,
-                       lttng_pipe_get_readfd(handle->quit_pipe),
-                       LPOLLIN | LPOLLERR);
-       if (ret < 0) {
-               ERR("Failed to add quit pipe read fd to poll set");
-               goto error;
-       }
-
-       ret = lttng_poll_add(poll_set,
-                       lttng_pipe_get_readfd(handle->rotation_timer_queue->event_pipe),
-                       LPOLLIN | LPOLLERR);
-       if (ret < 0) {
-               ERR("Failed to add rotate_pending fd to poll set");
-               goto error;
-       }
-
-       return ret;
-error:
-       lttng_poll_clean(poll_set);
-       return ret;
-}
-
-static
-void fini_thread_state(struct rotation_thread *state)
-{
-       lttng_poll_clean(&state->events);
-       if (rotate_notification_channel) {
-               lttng_notification_channel_destroy(rotate_notification_channel);
-       }
-}
-
-static
-int init_thread_state(struct rotation_thread_handle *handle,
-               struct rotation_thread *state)
-{
-       int ret;
-
-       memset(state, 0, sizeof(*state));
-       lttng_poll_init(&state->events);
-
-       ret = init_poll_set(&state->events, handle);
-       if (ret) {
-               ERR("Failed to initialize rotation thread poll set");
-               goto end;
-       }
-
-       rotate_notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
-       if (!rotate_notification_channel) {
-               ERR("Could not create notification channel");
-               ret = -1;
-               goto end;
-       }
-       ret = lttng_poll_add(&state->events, rotate_notification_channel->socket,
-                       LPOLLIN | LPOLLERR);
-       if (ret < 0) {
-               ERR("Failed to add notification fd to pollset");
-               goto end;
-       }
-
-end:
-       return ret;
-}
-
-static
-void check_session_rotation_pending_on_consumers(struct ltt_session *session,
-               bool *_rotation_completed)
+void check_session_rotation_pending_on_consumers(ltt_session& session, bool& _rotation_completed)
 {
        int ret = 0;
        struct consumer_socket *socket;
@@ -331,92 +121,89 @@ void check_session_rotation_pending_on_consumers(struct ltt_session *session,
        uint64_t relayd_id;
        bool chunk_exists_on_peer = false;
        enum lttng_trace_chunk_status chunk_status;
+       lttng::urcu::read_lock_guard read_lock;
 
-       LTTNG_ASSERT(session->chunk_being_archived);
+       LTTNG_ASSERT(session.chunk_being_archived);
 
        /*
         * Check for a local pending rotation on all consumers (32-bit
         * user space, 64-bit user space, and kernel).
         */
-       rcu_read_lock();
-       if (!session->ust_session) {
+       if (!session.ust_session) {
                goto skip_ust;
        }
-       cds_lfht_for_each_entry(session->ust_session->consumer->socks->ht,
-                       &iter, socket, node.node) {
-               relayd_id = session->ust_session->consumer->type == CONSUMER_DST_LOCAL ?
-                               -1ULL :
-                               session->ust_session->consumer->net_seq_index;
 
-               pthread_mutex_lock(socket->lock);
+       cds_lfht_for_each_entry (
+               session.ust_session->consumer->socks->ht, &iter, socket, node.node) {
+               relayd_id = session.ust_session->consumer->type == CONSUMER_DST_LOCAL ?
+                       -1ULL :
+                       session.ust_session->consumer->net_seq_index;
+
+               lttng::pthread::lock_guard socket_lock(*socket->lock);
                ret = consumer_trace_chunk_exists(socket,
-                               relayd_id,
-                               session->id, session->chunk_being_archived,
-                               &exists_status);
+                                                 relayd_id,
+                                                 session.id,
+                                                 session.chunk_being_archived,
+                                                 &exists_status);
                if (ret) {
-                       pthread_mutex_unlock(socket->lock);
                        ERR("Error occurred while checking rotation status on consumer daemon");
                        goto end;
                }
 
                if (exists_status != CONSUMER_TRACE_CHUNK_EXISTS_STATUS_UNKNOWN_CHUNK) {
-                       pthread_mutex_unlock(socket->lock);
                        chunk_exists_on_peer = true;
                        goto end;
                }
-               pthread_mutex_unlock(socket->lock);
        }
 
 skip_ust:
-       if (!session->kernel_session) {
+       if (!session.kernel_session) {
                goto skip_kernel;
        }
-       cds_lfht_for_each_entry(session->kernel_session->consumer->socks->ht,
-                               &iter, socket, node.node) {
-               pthread_mutex_lock(socket->lock);
-               relayd_id = session->kernel_session->consumer->type == CONSUMER_DST_LOCAL ?
-                               -1ULL :
-                               session->kernel_session->consumer->net_seq_index;
+
+       cds_lfht_for_each_entry (
+               session.kernel_session->consumer->socks->ht, &iter, socket, node.node) {
+               lttng::pthread::lock_guard socket_lock(*socket->lock);
+
+               relayd_id = session.kernel_session->consumer->type == CONSUMER_DST_LOCAL ?
+                       -1ULL :
+                       session.kernel_session->consumer->net_seq_index;
 
                ret = consumer_trace_chunk_exists(socket,
-                               relayd_id,
-                               session->id, session->chunk_being_archived,
-                               &exists_status);
+                                                 relayd_id,
+                                                 session.id,
+                                                 session.chunk_being_archived,
+                                                 &exists_status);
                if (ret) {
-                       pthread_mutex_unlock(socket->lock);
                        ERR("Error occurred while checking rotation status on consumer daemon");
                        goto end;
                }
 
                if (exists_status != CONSUMER_TRACE_CHUNK_EXISTS_STATUS_UNKNOWN_CHUNK) {
-                       pthread_mutex_unlock(socket->lock);
                        chunk_exists_on_peer = true;
                        goto end;
                }
-               pthread_mutex_unlock(socket->lock);
        }
 skip_kernel:
 end:
-       rcu_read_unlock();
 
        if (!chunk_exists_on_peer) {
                uint64_t chunk_being_archived_id;
 
-               chunk_status = lttng_trace_chunk_get_id(
-                               session->chunk_being_archived,
-                               &chunk_being_archived_id);
+               chunk_status = lttng_trace_chunk_get_id(session.chunk_being_archived,
+                                                       &chunk_being_archived_id);
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
-               DBG("Rotation of trace archive %" PRIu64 " of session \"%s\" is complete on all consumers",
-                               chunk_being_archived_id,
-                               session->name);
+               DBG("Rotation of trace archive %" PRIu64
+                   " of session \"%s\" is complete on all consumers",
+                   chunk_being_archived_id,
+                   session.name);
        }
-       *_rotation_completed = !chunk_exists_on_peer;
+
+       _rotation_completed = !chunk_exists_on_peer;
        if (ret) {
-               ret = session_reset_rotation_state(session,
-                               LTTNG_ROTATION_STATE_ERROR);
+               ret = session_reset_rotation_state(session, LTTNG_ROTATION_STATE_ERROR);
                if (ret) {
-                       ERR("Failed to reset rotation state of session \"%s\"",
-                                       session->name);
+                       ERR("Failed to reset rotation state of session \"%s\"", session.name);
                }
        }
 }
@@ -426,9 +213,8 @@ end:
  * Should only return non-zero in the event of a fatal error. Doing so will
  * shutdown the thread.
  */
-static
-int check_session_rotation_pending(struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle)
+int check_session_rotation_pending(ltt_session& session,
+                                  notification_thread_handle& notification_thread_handle)
 {
        int ret;
        struct lttng_trace_archive_location *location;
@@ -437,17 +223,18 @@ int check_session_rotation_pending(struct ltt_session *session,
        const char *archived_chunk_name;
        uint64_t chunk_being_archived_id;
 
-       if (!session->chunk_being_archived) {
+       if (!session.chunk_being_archived) {
                ret = 0;
                goto end;
        }
 
-       chunk_status = lttng_trace_chunk_get_id(session->chunk_being_archived,
-                       &chunk_being_archived_id);
+       chunk_status =
+               lttng_trace_chunk_get_id(session.chunk_being_archived, &chunk_being_archived_id);
        LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
 
        DBG("Checking for pending rotation on session \"%s\", trace archive %" PRIu64,
-                       session->name, chunk_being_archived_id);
+           session.name,
+           chunk_being_archived_id);
 
        /*
         * The rotation-pending check timer of a session is launched in
@@ -462,10 +249,8 @@ int check_session_rotation_pending(struct ltt_session *session,
                goto check_ongoing_rotation;
        }
 
-       check_session_rotation_pending_on_consumers(session,
-                       &rotation_completed);
-       if (!rotation_completed ||
-                       session->rotation_state == LTTNG_ROTATION_STATE_ERROR) {
+       check_session_rotation_pending_on_consumers(session, rotation_completed);
+       if (!rotation_completed || session.rotation_state == LTTNG_ROTATION_STATE_ERROR) {
                goto check_ongoing_rotation;
        }
 
@@ -473,42 +258,43 @@ int check_session_rotation_pending(struct ltt_session *session,
         * Now we can clear the "ONGOING" state in the session. New
         * rotations can start now.
         */
-       chunk_status = lttng_trace_chunk_get_name(session->chunk_being_archived,
-                       &archived_chunk_name, NULL);
+       chunk_status = lttng_trace_chunk_get_name(
+               session.chunk_being_archived, &archived_chunk_name, nullptr);
        LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
-       free(session->last_archived_chunk_name);
-       session->last_archived_chunk_name = strdup(archived_chunk_name);
-       if (!session->last_archived_chunk_name) {
+       free(session.last_archived_chunk_name);
+       session.last_archived_chunk_name = strdup(archived_chunk_name);
+       if (!session.last_archived_chunk_name) {
                PERROR("Failed to duplicate archived chunk name");
        }
+
        session_reset_rotation_state(session, LTTNG_ROTATION_STATE_COMPLETED);
 
-       if (!session->quiet_rotation) {
-               location = session_get_trace_archive_location(session);
+       if (!session.quiet_rotation) {
+               location = session_get_trace_archive_location(&session);
                ret = notification_thread_command_session_rotation_completed(
-                               notification_thread_handle,
-                               session->id,
-                               session->last_archived_chunk_id.value,
-                               location);
+                       &notification_thread_handle,
+                       session.id,
+                       session.last_archived_chunk_id.value,
+                       location);
                lttng_trace_archive_location_put(location);
                if (ret != LTTNG_OK) {
                        ERR("Failed to notify notification thread of completed rotation for session %s",
-                                       session->name);
+                           session.name);
                }
        }
 
        ret = 0;
 check_ongoing_rotation:
-       if (session->rotation_state == LTTNG_ROTATION_STATE_ONGOING) {
-               chunk_status = lttng_trace_chunk_get_id(
-                               session->chunk_being_archived,
-                               &chunk_being_archived_id);
+       if (session.rotation_state == LTTNG_ROTATION_STATE_ONGOING) {
+               chunk_status = lttng_trace_chunk_get_id(session.chunk_being_archived,
+                                                       &chunk_being_archived_id);
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
 
                DBG("Rotation of trace archive %" PRIu64 " is still pending for session %s",
-                               chunk_being_archived_id, session->name);
-               ret = timer_session_rotation_pending_check_start(session,
-                               DEFAULT_ROTATE_PENDING_TIMER);
+                   chunk_being_archived_id,
+                   session.name);
+               ret = timer_session_rotation_pending_check_start(&session,
+                                                                DEFAULT_ROTATE_PENDING_TIMER);
                if (ret) {
                        ERR("Failed to re-enable rotation pending timer");
                        ret = -1;
@@ -521,180 +307,317 @@ end:
 }
 
 /* Call with the session and session_list locks held. */
-static
-int launch_session_rotation(struct ltt_session *session)
+int launch_session_rotation(ltt_session& session)
 {
        int ret;
        struct lttng_rotate_session_return rotation_return;
 
-       DBG("Launching scheduled time-based rotation on session \"%s\"",
-                       session->name);
+       DBG("Launching scheduled time-based rotation on session \"%s\"", session.name);
+
+       ASSERT_SESSION_LIST_LOCKED();
+       ASSERT_LOCKED(session.lock);
 
-       ret = cmd_rotate_session(session, &rotation_return, false,
-               LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
+       ret = cmd_rotate_session(&session,
+                                &rotation_return,
+                                false,
+                                LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
        if (ret == LTTNG_OK) {
                DBG("Scheduled time-based rotation successfully launched on session \"%s\"",
-                               session->name);
+                   session.name);
        } else {
                /* Don't consider errors as fatal. */
                DBG("Scheduled time-based rotation aborted for session %s: %s",
-                               session->name, lttng_strerror(ret));
+                   session.name,
+                   lttng_strerror(ret));
        }
+
        return 0;
 }
 
-static
-int run_job(struct rotation_thread_job *job, struct ltt_session *session,
-               struct notification_thread_handle *notification_thread_handle)
+int run_job(const rotation_thread_job& job,
+           ltt_session& session,
+           notification_thread_handle& notification_thread_handle)
 {
        int ret;
 
-       switch (job->type) {
-       case ROTATION_THREAD_JOB_TYPE_SCHEDULED_ROTATION:
+       switch (job.type) {
+       case ls::rotation_thread_job_type::SCHEDULED_ROTATION:
                ret = launch_session_rotation(session);
                break;
-       case ROTATION_THREAD_JOB_TYPE_CHECK_PENDING_ROTATION:
-               ret = check_session_rotation_pending(session,
-                               notification_thread_handle);
+       case ls::rotation_thread_job_type::CHECK_PENDING_ROTATION:
+               ret = check_session_rotation_pending(session, notification_thread_handle);
                break;
        default:
                abort();
        }
+
        return ret;
 }
 
-static
-int handle_job_queue(struct rotation_thread_handle *handle,
-               struct rotation_thread *state __attribute__((unused)),
-               struct rotation_thread_timer_queue *queue)
+bool shutdown_rotation_thread(void *thread_data)
 {
-       int ret = 0;
+       auto *handle = reinterpret_cast<const ls::rotation_thread *>(thread_data);
 
-       for (;;) {
-               struct ltt_session *session;
-               struct rotation_thread_job *job;
+       return handle->shutdown();
+}
+} /* namespace */
 
-               /* Take the queue lock only to pop an element from the list. */
-               pthread_mutex_lock(&queue->lock);
-               if (cds_list_empty(&queue->list)) {
-                       pthread_mutex_unlock(&queue->lock);
-                       break;
+ls::rotation_thread_timer_queue *ls::rotation_thread_timer_queue_create()
+{
+       auto queue = zmalloc<ls::rotation_thread_timer_queue>();
+       if (!queue) {
+               PERROR("Failed to allocate timer rotate queue");
+               goto end;
+       }
+
+       queue->event_pipe = lttng_pipe_open(FD_CLOEXEC | O_NONBLOCK);
+       CDS_INIT_LIST_HEAD(&queue->list);
+       pthread_mutex_init(&queue->lock, nullptr);
+end:
+       return queue;
+}
+
+void ls::rotation_thread_timer_queue_destroy(struct rotation_thread_timer_queue *queue)
+{
+       if (!queue) {
+               return;
+       }
+
+       lttng_pipe_destroy(queue->event_pipe);
+
+       {
+               lttng::pthread::lock_guard queue_lock(queue->lock);
+
+               LTTNG_ASSERT(cds_list_empty(&queue->list));
+       }
+
+       pthread_mutex_destroy(&queue->lock);
+       free(queue);
+}
+
+ls::rotation_thread::rotation_thread(rotation_thread_timer_queue& rotation_timer_queue,
+                                    notification_thread_handle& notification_thread_handle) :
+       _rotation_timer_queue(rotation_timer_queue),
+       _notification_thread_handle(notification_thread_handle)
+{
+       _quit_pipe.reset([]() {
+               auto raw_pipe = lttng_pipe_open(FD_CLOEXEC);
+               if (!raw_pipe) {
+                       LTTNG_THROW_POSIX("Failed to rotation thread's quit pipe", errno);
                }
-               job = cds_list_first_entry(&queue->list,
-                               typeof(*job), head);
-               cds_list_del(&job->head);
-               pthread_mutex_unlock(&queue->lock);
 
-               session_lock_list();
-               session = job->session;
-               if (!session) {
-                       DBG("Session \"%s\" not found",
-                                       session->name != NULL ? session->name : "");
+               return raw_pipe;
+       }());
+
+       _notification_channel.reset([]() {
+               auto channel = lttng_notification_channel_create(
+                       lttng_session_daemon_notification_endpoint);
+               if (!channel) {
+                       LTTNG_THROW_ERROR(
+                               "Failed to create notification channel of rotation thread");
+               }
+
+               return channel;
+       }());
+
+       lttng_poll_init(&_events);
+
+       /*
+        * Create pollset with size 4:
+        *      - rotation thread quit pipe,
+        *      - rotation thread timer queue pipe,
+        *      - notification channel sock,
+        *      - subscribtion change event fd
+        */
+       if (lttng_poll_create(&_events, 4, LTTNG_CLOEXEC) < 0) {
+               LTTNG_THROW_ERROR("Failed to create poll object for rotation thread");
+       }
+
+       if (lttng_poll_add(&_events, lttng_pipe_get_readfd(_quit_pipe.get()), LPOLLIN) < 0) {
+               LTTNG_THROW_ERROR("Failed to add quit pipe read fd to poll set");
+       }
+
+       if (lttng_poll_add(&_events,
+                          lttng_pipe_get_readfd(_rotation_timer_queue.event_pipe),
+                          LPOLLIN) < 0) {
+               LTTNG_THROW_ERROR("Failed to add rotation timer queue event pipe fd to poll set");
+       }
+
+       if (lttng_poll_add(&_events,
+                          _notification_channel_subscribtion_change_eventfd.fd(),
+                          LPOLLIN) < 0) {
+               LTTNG_THROW_ERROR(
+                       "Failed to add rotation thread notification channel subscription change eventfd to poll set");
+       }
+
+       if (lttng_poll_add(&_events, _notification_channel->socket, LPOLLIN) < 0) {
+               LTTNG_THROW_ERROR("Failed to add notification channel socket fd to pollset");
+       }
+}
+
+ls::rotation_thread::~rotation_thread()
+{
+       lttng_poll_clean(&_events);
+}
+
+void ls::rotation_thread_enqueue_job(ls::rotation_thread_timer_queue *queue,
+                                    ls::rotation_thread_job_type job_type,
+                                    ltt_session *session)
+{
+       const char dummy = '!';
+       struct rotation_thread_job *job = nullptr;
+       const char *job_type_str = get_job_type_str(job_type);
+       lttng::pthread::lock_guard queue_lock(queue->lock);
+
+       if (timer_job_exists(queue, job_type, session)) {
+               /*
+                * This timer job is already pending, we don't need to add
+                * it.
+                */
+               return;
+       }
+
+       job = zmalloc<rotation_thread_job>();
+       if (!job) {
+               PERROR("Failed to allocate rotation thread job of type \"%s\" for session \"%s\"",
+                      job_type_str,
+                      session->name);
+               return;
+       }
+
+       /* No reason for this to fail as the caller must hold a reference. */
+       (void) session_get(session);
+
+       job->session = session;
+       job->type = job_type;
+       cds_list_add_tail(&job->head, &queue->list);
+
+       const int write_ret =
+               lttng_write(lttng_pipe_get_writefd(queue->event_pipe), &dummy, sizeof(dummy));
+       if (write_ret < 0) {
+               /*
+                * We do not want to block in the timer handler, the job has
+                * been enqueued in the list, the wakeup pipe is probably full,
+                * the job will be processed when the rotation_thread catches
+                * up.
+                */
+               DIAGNOSTIC_PUSH
+               DIAGNOSTIC_IGNORE_LOGICAL_OP
+               if (errno == EAGAIN || errno == EWOULDBLOCK) {
+                       DIAGNOSTIC_POP
                        /*
-                        * This is a non-fatal error, and we cannot report it to
-                        * the user (timer), so just print the error and
-                        * continue the processing.
-                        *
-                        * While the timer thread will purge pending signals for
-                        * a session on the session's destruction, it is
-                        * possible for a job targeting that session to have
-                        * already been queued before it was destroyed.
+                        * Not an error, but would be surprising and indicate
+                        * that the rotation thread can't keep up with the
+                        * current load.
                         */
-                       free(job);
-                       session_put(session);
-                       session_unlock_list();
-                       continue;
+                       DBG("Wake-up pipe of rotation thread job queue is full");
+                       return;
                }
 
-               session_lock(session);
-               ret = run_job(job, session, handle->notification_thread_handle);
-               session_unlock(session);
-               /* Release reference held by the job. */
-               session_put(session);
-               session_unlock_list();
-               free(job);
-               if (ret) {
-                       goto end;
-               }
+               PERROR("Failed to wake-up the rotation thread after pushing a job of type \"%s\" for session \"%s\"",
+                      job_type_str,
+                      session->name);
+               return;
        }
+}
 
-       ret = 0;
+void ls::rotation_thread::_handle_job_queue()
+{
+       for (;;) {
+               rotation_thread_job::uptr job;
+
+               {
+                       /* Take the queue lock only to pop an element from the list. */
+                       lttng::pthread::lock_guard rotation_timer_queue_lock(
+                               _rotation_timer_queue.lock);
+                       if (cds_list_empty(&_rotation_timer_queue.list)) {
+                               break;
+                       }
 
-end:
-       return ret;
+                       job.reset(cds_list_first_entry(
+                               &_rotation_timer_queue.list, typeof(rotation_thread_job), head));
+                       cds_list_del(&job->head);
+               }
+
+               session_lock_list();
+               const auto unlock_list =
+                       lttng::make_scope_exit([]() noexcept { session_unlock_list(); });
+
+               /* locked_ptr will unlock the session and release the ref held by the job. */
+               session_lock(job->session);
+               auto session = ltt_session::locked_ptr(job->session);
+
+               if (run_job(*job, *session, _notification_thread_handle)) {
+                       return;
+               }
+       }
 }
 
-static
-int handle_condition(const struct lttng_notification *notification,
-               struct notification_thread_handle *notification_thread_handle)
+void ls::rotation_thread::_handle_notification(const lttng_notification& notification)
 {
        int ret = 0;
-       const char *condition_session_name = NULL;
-       enum lttng_condition_type condition_type;
+       const char *condition_session_name = nullptr;
        enum lttng_condition_status condition_status;
        enum lttng_evaluation_status evaluation_status;
        uint64_t consumed;
-       struct ltt_session *session;
-       const struct lttng_condition *condition =
-                       lttng_notification_get_const_condition(notification);
-       const struct lttng_evaluation *evaluation =
-                       lttng_notification_get_const_evaluation(notification);
-
-       condition_type = lttng_condition_get_type(condition);
+       auto *condition = lttng_notification_get_const_condition(&notification);
+       auto *evaluation = lttng_notification_get_const_evaluation(&notification);
+       const auto condition_type = lttng_condition_get_type(condition);
 
        if (condition_type != LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE) {
-               ret = -1;
-               ERR("Condition type and session usage type are not the same");
-               goto end;
+               LTTNG_THROW_ERROR("Unexpected condition type");
        }
 
-       /* Fetch info to test */
+       /* Fetch info to test. */
        condition_status = lttng_condition_session_consumed_size_get_session_name(
-                       condition, &condition_session_name);
+               condition, &condition_session_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               ERR("Session name could not be fetched");
-               ret = -1;
-               goto end;
+               LTTNG_THROW_ERROR("Session name could not be fetched from notification");
        }
-       evaluation_status = lttng_evaluation_session_consumed_size_get_consumed_size(evaluation,
-                       &consumed);
+
+       evaluation_status =
+               lttng_evaluation_session_consumed_size_get_consumed_size(evaluation, &consumed);
        if (evaluation_status != LTTNG_EVALUATION_STATUS_OK) {
-               ERR("Failed to get evaluation");
-               ret = -1;
-               goto end;
+               LTTNG_THROW_ERROR("Failed to get consumed size from evaluation");
        }
 
+       DBG_FMT("Handling session consumed size condition: session_name=`{}`, consumed_size={}",
+               condition_session_name,
+               consumed);
+
        session_lock_list();
-       session = session_find_by_name(condition_session_name);
+       const auto unlock_list = lttng::make_scope_exit([]() noexcept { session_unlock_list(); });
+
+       ltt_session::locked_ptr session{ [&condition_session_name]() {
+               auto raw_session_ptr = session_find_by_name(condition_session_name);
+
+               if (raw_session_ptr) {
+                       session_lock(raw_session_ptr);
+               }
+
+               return raw_session_ptr;
+       }() };
        if (!session) {
-               DBG("Failed to find session while handling notification: notification type = %s, session name = `%s`",
-                               lttng_condition_type_str(condition_type),
-                               condition_session_name);
+               DBG_FMT("Failed to find session while handling notification: notification_type={}, session name=`{}`",
+                       lttng_condition_type_str(condition_type),
+                       condition_session_name);
                /*
                 * Not a fatal error: a session can be destroyed before we get
                 * the chance to handle the notification.
                 */
-               ret = 0;
-               session_unlock_list();
-               goto end;
+               return;
        }
-       session_lock(session);
 
        if (!lttng_trigger_is_equal(session->rotate_trigger,
-                       lttng_notification_get_const_trigger(notification))) {
-               /* Notification does not originate from our rotation trigger. */
-               ret = 0;
-               goto end_unlock;
+                                   lttng_notification_get_const_trigger(&notification))) {
+               DBG("Notification does not originate from the internal size-based scheduled rotation trigger, skipping");
+               return;
        }
 
-       ret = unsubscribe_session_consumed_size_rotation(session,
-                       notification_thread_handle);
-       if (ret) {
-               goto end_unlock;
-       }
+       unsubscribe_session_consumed_size_rotation(*session);
 
        ret = cmd_rotate_session(
-                       session, NULL, false, LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
+               session.get(), nullptr, false, LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED);
        switch (ret) {
        case LTTNG_OK:
                break;
@@ -708,147 +631,149 @@ int handle_condition(const struct lttng_notification *notification,
                DBG("Rotation already happened since last stop and clear, subscribe to the next threshold value");
                break;
        default:
-               ERR("Failed to rotate on size notification with error: %s", lttng_strerror(ret));
-               ret = -1;
-               goto end_unlock;
+               LTTNG_THROW_CTL("Failed to rotate on consumed size notification",
+                               static_cast<lttng_error_code>(-ret));
        }
 
-       ret = subscribe_session_consumed_size_rotation(
-                       session, consumed + session->rotate_size, notification_thread_handle);
-       if (ret) {
-               ERR("Failed to subscribe to session consumed size condition");
-               goto end_unlock;
-       }
-       ret = 0;
-
-end_unlock:
-       session_unlock(session);
-       session_put(session);
-       session_unlock_list();
-end:
-       return ret;
+       subscribe_session_consumed_size_rotation(*session, consumed + session->rotate_size);
 }
 
-static
-int handle_notification_channel(int fd __attribute__((unused)),
-               struct rotation_thread_handle *handle,
-               struct rotation_thread *state __attribute__((unused)))
+void ls::rotation_thread::_handle_notification_channel_activity()
 {
-       int ret;
-       bool notification_pending;
-       struct lttng_notification *notification = NULL;
-       enum lttng_notification_channel_status status;
-
-       status = lttng_notification_channel_has_pending_notification(
-                       rotate_notification_channel, &notification_pending);
-       if (status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
-               ERR("Error occurred while checking for pending notification");
-               ret = -1;
-               goto end;
-       }
+       bool notification_pending = true;
 
-       if (!notification_pending) {
-               ret = 0;
-               goto end;
-       }
+       /*
+        * A notification channel may have multiple notifications queued-up internally in
+        * its buffers. This is because a notification channel multiplexes command replies
+        * and notifications. The current protocol specifies that multiple notifications can be
+        * received before the reply to a command.
+        *
+        * In such cases, the notification channel client implementation internally queues them and
+        * provides them on the next calls to lttng_notification_channel_get_next_notification().
+        * This is correct with respect to the public API, which is intended to be used in "blocking
+        * mode".
+        *
+        * However, this internal user relies on poll/epoll to wake-up when data is available
+        * on the notification channel's socket. As such, it can't assume that a wake-up means only
+        * one notification is available for consumption since many of them may have been queued in
+        * the channel's internal buffers.
+        */
+       while (notification_pending) {
+               const auto pending_status = lttng_notification_channel_has_pending_notification(
+                       _notification_channel.get(), &notification_pending);
+               if (pending_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
+                       LTTNG_THROW_ERROR("Error occurred while checking for pending notification");
+               }
 
-       /* Receive the next notification. */
-       status = lttng_notification_channel_get_next_notification(
-                       rotate_notification_channel,
-                       &notification);
+               if (!notification_pending) {
+                       return;
+               }
 
-       switch (status) {
-       case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
-               break;
-       case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
-               /* Not an error, we will wait for the next one */
-               ret = 0;
-               goto end;;
-       case LTTNG_NOTIFICATION_CHANNEL_STATUS_CLOSED:
-               ERR("Notification channel was closed");
-               ret = -1;
-               goto end;
-       default:
-               /* Unhandled conditions / errors. */
-               ERR("Unknown notification channel status");
-               ret = -1;
-               goto end;
-       }
+               /* Receive the next notification. */
+               lttng_notification::uptr notification;
+               enum lttng_notification_channel_status next_notification_status;
 
-       ret = handle_condition(notification,
-                       handle->notification_thread_handle);
+               {
+                       struct lttng_notification *raw_notification_ptr;
 
-end:
-       lttng_notification_destroy(notification);
-       return ret;
+                       next_notification_status = lttng_notification_channel_get_next_notification(
+                               _notification_channel.get(), &raw_notification_ptr);
+                       notification.reset(raw_notification_ptr);
+               }
+
+               switch (next_notification_status) {
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
+                       break;
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
+                       WARN("Dropped notification detected on notification channel used by the rotation management thread.");
+                       return;
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_CLOSED:
+                       LTTNG_THROW_ERROR("Notification channel was closed");
+               default:
+                       /* Unhandled conditions / errors. */
+                       LTTNG_THROW_ERROR("Unknown notification channel status");
+               }
+
+               _handle_notification(*notification);
+       }
 }
 
-static
-void *thread_rotation(void *data)
+void ls::rotation_thread::_thread_function() noexcept
 {
-       int ret;
-       struct rotation_thread_handle *handle = (rotation_thread_handle *) data;
-       struct rotation_thread thread;
-       int queue_pipe_fd;
-
        DBG("Started rotation thread");
-       rcu_register_thread();
-       rcu_thread_online();
-       health_register(the_health_sessiond, HEALTH_SESSIOND_TYPE_ROTATION);
-       health_code_update();
 
-       if (!handle) {
-               ERR("Invalid thread context provided");
-               goto end;
+       try {
+               _run();
+       } catch (const std::exception& e) {
+               ERR_FMT("Fatal rotation thread error: {}", e.what());
        }
 
-       queue_pipe_fd = lttng_pipe_get_readfd(
-                       handle->rotation_timer_queue->event_pipe);
+       DBG("Thread exit");
+}
 
+void ls::rotation_thread::_run()
+{
+       rcu_register_thread();
+       const auto unregister_rcu_thread =
+               lttng::make_scope_exit([]() noexcept { rcu_unregister_thread(); });
 
-       ret = init_thread_state(handle, &thread);
-       if (ret) {
-               goto error;
-       }
+       rcu_thread_online();
+       const auto offline_rcu_thread =
+               lttng::make_scope_exit([]() noexcept { rcu_thread_offline(); });
 
-       while (true) {
-               int fd_count, i;
+       health_register(the_health_sessiond, HEALTH_SESSIOND_TYPE_ROTATION);
+       health_code_update();
+       const auto unregister_health =
+               lttng::make_scope_exit([]() noexcept { health_unregister(the_health_sessiond); });
 
+       const auto queue_pipe_fd = lttng_pipe_get_readfd(_rotation_timer_queue.event_pipe);
+
+       while (true) {
                health_poll_entry();
                DBG("Entering poll wait");
-               ret = lttng_poll_wait(&thread.events, -1);
-               DBG("Poll wait returned (%i)", ret);
+               auto poll_wait_ret = lttng_poll_wait(&_events, -1);
+               DBG_FMT("Poll wait returned: ret={}", poll_wait_ret);
                health_poll_exit();
-               if (ret < 0) {
+               if (poll_wait_ret < 0) {
                        /*
                         * Restart interrupted system call.
                         */
                        if (errno == EINTR) {
                                continue;
                        }
-                       ERR("Error encountered during lttng_poll_wait (%i)", ret);
-                       goto error;
+
+                       LTTNG_THROW_POSIX("Error encountered during lttng_poll_wait", errno);
                }
 
-               fd_count = ret;
-               for (i = 0; i < fd_count; i++) {
-                       int fd = LTTNG_POLL_GETFD(&thread.events, i);
-                       uint32_t revents = LTTNG_POLL_GETEV(&thread.events, i);
+               const auto fd_count = poll_wait_ret;
+               for (int i = 0; i < fd_count; i++) {
+                       const auto fd = LTTNG_POLL_GETFD(&_events, i);
+                       const auto revents = LTTNG_POLL_GETEV(&_events, i);
 
-                       DBG("Handling fd (%i) activity (%u)",
-                                       fd, revents);
+                       DBG_FMT("Handling descriptor activity: fd={}, events={:b}", fd, revents);
 
                        if (revents & LPOLLERR) {
-                               ERR("Polling returned an error on fd %i", fd);
-                               goto error;
+                               LTTNG_THROW_ERROR(lttng::format(
+                                       "Polling returned an error on fd: fd={}", fd));
                        }
 
-                       if (fd == rotate_notification_channel->socket) {
-                               ret = handle_notification_channel(fd, handle,
-                                               &thread);
-                               if (ret) {
-                                       ERR("Error occurred while handling activity on notification channel socket");
-                                       goto error;
+                       if (fd == _notification_channel->socket ||
+                           fd == _notification_channel_subscribtion_change_eventfd.fd()) {
+                               try {
+                                       _handle_notification_channel_activity();
+                               } catch (const lttng::ctl::error& e) {
+                                       /*
+                                        * The only non-fatal error (rotation failed), others
+                                        * are caught at the top-level.
+                                        */
+                                       DBG_FMT("Control error occurred while handling activity on notification channel socket: {}",
+                                               e.what());
+                                       continue;
+                               }
+
+                               if (fd == _notification_channel_subscribtion_change_eventfd.fd()) {
+                                       _notification_channel_subscribtion_change_eventfd
+                                               .decrement();
                                }
                        } else {
                                /* Job queue or quit pipe activity. */
@@ -859,62 +784,161 @@ void *thread_rotation(void *data)
                                 * flushed and all references held in the queue
                                 * are released.
                                 */
-                               ret = handle_job_queue(handle, &thread,
-                                               handle->rotation_timer_queue);
-                               if (ret) {
-                                       ERR("Failed to handle rotation timer pipe event");
-                                       goto error;
-                               }
-
+                               _handle_job_queue();
                                if (fd == queue_pipe_fd) {
                                        char buf;
 
-                                       ret = lttng_read(fd, &buf, 1);
-                                       if (ret != 1) {
-                                               ERR("Failed to read from wakeup pipe (fd = %i)", fd);
-                                               goto error;
+                                       if (lttng_read(fd, &buf, 1) != 1) {
+                                               LTTNG_THROW_POSIX(
+                                                       lttng::format(
+                                                               "Failed to read from wakeup pipe: fd={}",
+                                                               fd),
+                                                       errno);
                                        }
                                } else {
                                        DBG("Quit pipe activity");
-                                       goto exit;
+                                       return;
                                }
                        }
                }
        }
-exit:
-error:
-       DBG("Thread exit");
-       fini_thread_state(&thread);
-end:
-       health_unregister(the_health_sessiond);
-       rcu_thread_offline();
-       rcu_unregister_thread();
-       return NULL;
 }
 
-static
-bool shutdown_rotation_thread(void *thread_data)
+bool ls::rotation_thread::shutdown() const noexcept
 {
-       struct rotation_thread_handle *handle = (rotation_thread_handle *) thread_data;
-       const int write_fd = lttng_pipe_get_writefd(handle->quit_pipe);
+       const int write_fd = lttng_pipe_get_writefd(_quit_pipe.get());
 
        return notify_thread_pipe(write_fd) == 1;
 }
 
-bool launch_rotation_thread(struct rotation_thread_handle *handle)
+void ls::rotation_thread::launch_thread()
 {
-       struct lttng_thread *thread;
-
-       thread = lttng_thread_create("Rotation",
-                       thread_rotation,
-                       shutdown_rotation_thread,
-                       NULL,
-                       handle);
+       auto thread = lttng_thread_create(
+               "Rotation",
+               [](void *ptr) {
+                       auto handle = reinterpret_cast<rotation_thread *>(ptr);
+
+                       handle->_thread_function();
+                       return static_cast<void *>(nullptr);
+               },
+               shutdown_rotation_thread,
+               nullptr,
+               this);
        if (!thread) {
-               goto error;
+               LTTNG_THROW_ERROR("Failed to launch rotation thread");
        }
+
        lttng_thread_put(thread);
-       return true;
-error:
-       return false;
+}
+
+void ls::rotation_thread::subscribe_session_consumed_size_rotation(ltt_session& session,
+                                                                  std::uint64_t size)
+{
+       const struct lttng_credentials session_creds = {
+               .uid = LTTNG_OPTIONAL_INIT_VALUE(session.uid),
+               .gid = LTTNG_OPTIONAL_INIT_VALUE(session.gid),
+       };
+
+       ASSERT_LOCKED(session.lock);
+
+       auto rotate_condition = lttng::make_unique_wrapper<lttng_condition, lttng_condition_put>(
+               lttng_condition_session_consumed_size_create());
+       if (!rotate_condition) {
+               LTTNG_THROW_POSIX("Failed to create session consumed size condition object", errno);
+       }
+
+       auto condition_status =
+               lttng_condition_session_consumed_size_set_threshold(rotate_condition.get(), size);
+       if (condition_status != LTTNG_CONDITION_STATUS_OK) {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Could not set session consumed size condition threshold: size={}", size));
+       }
+
+       condition_status = lttng_condition_session_consumed_size_set_session_name(
+               rotate_condition.get(), session.name);
+       if (condition_status != LTTNG_CONDITION_STATUS_OK) {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Could not set session consumed size condition session name: name=`{}`",
+                       session.name));
+       }
+
+       auto notify_action = lttng::make_unique_wrapper<lttng_action, lttng_action_put>(
+               lttng_action_notify_create());
+       if (!notify_action) {
+               LTTNG_THROW_POSIX("Could not create notify action", errno);
+       }
+
+       LTTNG_ASSERT(!session.rotate_trigger);
+       /* trigger acquires its own reference to condition and action on success. */
+       auto trigger = lttng::make_unique_wrapper<lttng_trigger, lttng_trigger_put>(
+               lttng_trigger_create(rotate_condition.get(), notify_action.get()));
+       if (!trigger) {
+               LTTNG_THROW_POSIX("Could not create size-based rotation trigger", errno);
+       }
+
+       /* Ensure this trigger is not visible to external users. */
+       lttng_trigger_set_hidden(trigger.get());
+       lttng_trigger_set_credentials(trigger.get(), &session_creds);
+
+       auto nc_status = lttng_notification_channel_subscribe(_notification_channel.get(),
+                                                             rotate_condition.get());
+       if (nc_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
+               LTTNG_THROW_ERROR("Could not subscribe to session consumed size notification");
+       }
+
+       /*
+        * Ensure any notification queued during the subscription are consumed by queueing an
+        * event.
+        */
+       _notification_channel_subscribtion_change_eventfd.increment();
+
+       const auto register_ret = notification_thread_command_register_trigger(
+               &_notification_thread_handle, trigger.get(), true);
+       if (register_ret != LTTNG_OK) {
+               LTTNG_THROW_CTL(
+                       lttng::format(
+                               "Failed to register trigger for automatic size-based rotation: session_name{}, size={}",
+                               session.name,
+                               size),
+                       register_ret);
+       }
+
+       /* Ownership transferred to the session. */
+       session.rotate_trigger = trigger.release();
+}
+
+void ls::rotation_thread::unsubscribe_session_consumed_size_rotation(ltt_session& session)
+{
+       LTTNG_ASSERT(session.rotate_trigger);
+
+       const auto remove_session_trigger = lttng::make_scope_exit([&session]() noexcept {
+               lttng_trigger_put(session.rotate_trigger);
+               session.rotate_trigger = nullptr;
+       });
+
+       const auto unsubscribe_status = lttng_notification_channel_unsubscribe(
+               _notification_channel.get(),
+               lttng_trigger_get_const_condition(session.rotate_trigger));
+       if (unsubscribe_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Failed to unsubscribe from consumed size condition used to control automatic size-based rotations: session_name=`{}` return_code={}",
+                       session.name,
+                       static_cast<int>(unsubscribe_status)));
+       }
+
+       /*
+        * Ensure any notification queued during the un-subscription are consumed by queueing an
+        * event.
+        */
+       _notification_channel_subscribtion_change_eventfd.increment();
+
+       const auto unregister_status = notification_thread_command_unregister_trigger(
+               &_notification_thread_handle, session.rotate_trigger);
+       if (unregister_status != LTTNG_OK) {
+               LTTNG_THROW_CTL(
+                       lttng::format(
+                               "Failed to unregister trigger for automatic size-based rotation: session_name{}",
+                               session.name),
+                       unregister_status);
+       }
 }
index d2bbf2966b9e33a06d6b3d7b153be833ffcf7b0a..5e9b9d75e07c6741216d75578753133cfcc127bb 100644 (file)
@@ -9,43 +9,85 @@
 #ifndef ROTATION_THREAD_H
 #define ROTATION_THREAD_H
 
-#include <urcu/list.h>
-#include <urcu.h>
-#include <urcu/rculfhash.h>
-#include <lttng/domain.h>
-#include <common/pipe.hpp>
+#include "notification-thread.hpp"
+#include "session.hpp"
+
 #include <common/compat/poll.hpp>
+#include <common/eventfd.hpp>
 #include <common/hashtable/hashtable.hpp>
+#include <common/make-unique-wrapper.hpp>
+#include <common/pipe.hpp>
+
+#include <lttng/domain.h>
+#include <lttng/notification/channel-internal.hpp>
+
+#include <memory>
 #include <pthread.h>
 #include <semaphore.h>
-#include "session.hpp"
-#include "notification-thread.hpp"
+#include <urcu.h>
+#include <urcu/list.h>
+#include <urcu/rculfhash.h>
 
-extern struct lttng_notification_channel *rotate_notification_channel;
+namespace lttng {
+namespace sessiond {
 
-enum rotation_thread_job_type {
-       ROTATION_THREAD_JOB_TYPE_SCHEDULED_ROTATION,
-       ROTATION_THREAD_JOB_TYPE_CHECK_PENDING_ROTATION
-};
+enum class rotation_thread_job_type { SCHEDULED_ROTATION, CHECK_PENDING_ROTATION };
 
 struct rotation_thread_timer_queue;
-struct rotation_thread_handle;
 
-struct rotation_thread_timer_queue *rotation_thread_timer_queue_create(void);
-void rotation_thread_timer_queue_destroy(
-               struct rotation_thread_timer_queue *queue);
+class rotation_thread {
+public:
+       using uptr = std::unique_ptr<rotation_thread>;
+
+       rotation_thread(rotation_thread_timer_queue& rotation_timer_queue,
+                       notification_thread_handle& notification_thread_handle);
+       rotation_thread(const rotation_thread&) = delete;
+       rotation_thread(rotation_thread&&) = delete;
+       rotation_thread& operator=(const rotation_thread&) = delete;
+       rotation_thread& operator=(rotation_thread&&) = delete;
+       ~rotation_thread();
+
+       /* Only use through the lttng_thread facilities. */
+       void launch_thread();
+       bool shutdown() const noexcept;
 
-struct rotation_thread_handle *rotation_thread_handle_create(
-               struct rotation_thread_timer_queue *rotation_timer_queue,
-               struct notification_thread_handle *notification_thread_handle);
+       /*
+        * Subscribe/unsubscribe the rotation_thread's notification_channel to/from
+        * session usage notifications to perform size-based rotations.
+        */
+       void subscribe_session_consumed_size_rotation(ltt_session& session, std::uint64_t size);
+       void unsubscribe_session_consumed_size_rotation(ltt_session& session);
 
-void rotation_thread_handle_destroy(
-               struct rotation_thread_handle *handle);
+private:
+       void _thread_function() noexcept;
+       void _run();
+       void _handle_job_queue();
+       void _handle_notification(const lttng_notification& notification);
+       void _handle_notification_channel_activity();
+
+       struct rotation_thread_timer_queue& _rotation_timer_queue;
+       /* Access to the notification thread cmd_queue */
+       notification_thread_handle& _notification_thread_handle;
+       /* Thread-specific quit pipe. */
+       lttng_pipe::uptr _quit_pipe;
+       lttng_notification_channel::uptr _notification_channel;
+       /*
+        * Use an event_fd to wake-up the rotation thread whenever a command
+        * completes on the notification channel. This ensures that any
+        * notification that was queued while waiting for a reply to the command is
+        * eventually consumed.
+        */
+       lttng::eventfd _notification_channel_subscribtion_change_eventfd;
+       lttng_poll_event _events;
+};
 
+struct rotation_thread_timer_queue *rotation_thread_timer_queue_create();
+void rotation_thread_timer_queue_destroy(struct rotation_thread_timer_queue *queue);
 void rotation_thread_enqueue_job(struct rotation_thread_timer_queue *queue,
-               enum rotation_thread_job_type job_type,
-               struct ltt_session *session);
+                                enum rotation_thread_job_type job_type,
+                                struct ltt_session *session);
 
-bool launch_rotation_thread(struct rotation_thread_handle *handle);
+} /* namespace sessiond */
+} /* namespace lttng */
 
 #endif /* ROTATION_THREAD_H */
index 5db70faef47e98f0c865e65e69916365beab3a89..b4ca4c080fdd8f119a98a2fe31682be6d9cec42e 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <string.h>
-#include <urcu/uatomic.h>
-#include <unistd.h>
+#include "agent.hpp"
+#include "kernel.hpp"
+#include "lttng-syscall.hpp"
+#include "save.hpp"
+#include "session.hpp"
+#include "trace-ust.hpp"
 
+#include <common/config/session-config.hpp>
 #include <common/defaults.hpp>
 #include <common/error.hpp>
-#include <common/config/session-config.hpp>
-#include <common/utils.hpp>
 #include <common/runas.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
 #include <lttng/save-internal.hpp>
 
-#include "kernel.hpp"
-#include "save.hpp"
-#include "session.hpp"
-#include "lttng-syscall.hpp"
-#include "trace-ust.hpp"
-#include "agent.hpp"
+#include <fcntl.h>
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
+#include <urcu/uatomic.h>
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_channel_attributes(struct config_writer *writer,
-       struct lttng_channel_attr *attr)
+static int save_kernel_channel_attributes(struct config_writer *writer,
+                                         struct lttng_channel_attr *attr)
 {
        int ret;
 
        ret = config_writer_write_element_string(writer,
-               config_element_overwrite_mode,
-               attr->overwrite ? config_overwrite_mode_overwrite :
-                       config_overwrite_mode_discard);
+                                                config_element_overwrite_mode,
+                                                attr->overwrite ? config_overwrite_mode_overwrite :
+                                                                  config_overwrite_mode_discard);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_subbuf_size, attr->subbuf_size);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_subbuf_size, attr->subbuf_size);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_num_subbuf,
-               attr->num_subbuf);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_num_subbuf, attr->num_subbuf);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_switch_timer_interval,
-               attr->switch_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_switch_timer_interval, attr->switch_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_read_timer_interval,
-               attr->read_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_read_timer_interval, attr->read_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        ret = config_writer_write_element_string(writer,
-               config_element_output_type,
-               attr->output == LTTNG_EVENT_SPLICE ?
-               config_output_type_splice : config_output_type_mmap);
+                                                config_element_output_type,
+                                                attr->output == LTTNG_EVENT_SPLICE ?
+                                                        config_output_type_splice :
+                                                        config_output_type_mmap);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_size, attr->tracefile_size);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_size, attr->tracefile_size);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_count,
-               attr->tracefile_count);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_count, attr->tracefile_count);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_live_timer_interval,
-               attr->live_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_live_timer_interval, attr->live_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        if (attr->extended.ptr) {
-               struct lttng_channel_extended *ext = NULL;
+               struct lttng_channel_extended *ext = nullptr;
 
                ext = (struct lttng_channel_extended *) attr->extended.ptr;
-               ret = config_writer_write_element_unsigned_int(writer,
-                               config_element_monitor_timer_interval,
-                               ext->monitor_timer_interval);
+               ret = config_writer_write_element_unsigned_int(
+                       writer, config_element_monitor_timer_interval, ext->monitor_timer_interval);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = config_writer_write_element_signed_int(writer,
-                               config_element_blocking_timeout,
-                               ext->blocking_timeout);
+               ret = config_writer_write_element_signed_int(
+                       writer, config_element_blocking_timeout, ext->blocking_timeout);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -131,65 +127,61 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_channel_attributes(struct config_writer *writer,
-       struct lttng_ust_abi_channel_attr *attr)
+static int save_ust_channel_attributes(struct config_writer *writer,
+                                      struct lttng_ust_abi_channel_attr *attr)
 {
        int ret;
-       struct ltt_ust_channel *channel = NULL;
+       struct ltt_ust_channel *channel = nullptr;
 
        ret = config_writer_write_element_string(writer,
-               config_element_overwrite_mode,
-               attr->overwrite ? config_overwrite_mode_overwrite :
-                       config_overwrite_mode_discard);
+                                                config_element_overwrite_mode,
+                                                attr->overwrite ? config_overwrite_mode_overwrite :
+                                                                  config_overwrite_mode_discard);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_subbuf_size, attr->subbuf_size);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_subbuf_size, attr->subbuf_size);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_num_subbuf,
-               attr->num_subbuf);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_num_subbuf, attr->num_subbuf);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_switch_timer_interval,
-               attr->switch_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_switch_timer_interval, attr->switch_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_read_timer_interval,
-               attr->read_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_read_timer_interval, attr->read_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        ret = config_writer_write_element_string(writer,
-               config_element_output_type,
-               attr->output == LTTNG_UST_ABI_MMAP ?
-               config_output_type_mmap : config_output_type_splice);
+                                                config_element_output_type,
+                                                attr->output == LTTNG_UST_ABI_MMAP ?
+                                                        config_output_type_mmap :
+                                                        config_output_type_splice);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_signed_int(writer,
-                       config_element_blocking_timeout,
-                       attr->u.s.blocking_timeout);
+       ret = config_writer_write_element_signed_int(
+               writer, config_element_blocking_timeout, attr->u.s.blocking_timeout);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -200,9 +192,8 @@ int save_ust_channel_attributes(struct config_writer *writer,
         * lttng_ust_channel_attr
         */
        channel = lttng::utils::container_of(attr, &ltt_ust_channel::attr);
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_monitor_timer_interval,
-               channel->monitor_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_monitor_timer_interval, channel->monitor_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -213,9 +204,8 @@ end:
        return ret;
 }
 
-static
-const char *get_kernel_instrumentation_string(
-       enum lttng_kernel_abi_instrumentation instrumentation)
+static const char *
+get_kernel_instrumentation_string(enum lttng_kernel_abi_instrumentation instrumentation)
 {
        const char *instrumentation_string;
 
@@ -245,15 +235,13 @@ const char *get_kernel_instrumentation_string(
                instrumentation_string = config_event_type_syscall;
                break;
        default:
-               instrumentation_string = NULL;
+               instrumentation_string = nullptr;
        }
 
        return instrumentation_string;
 }
 
-static
-const char *get_kernel_context_type_string(
-       enum lttng_kernel_abi_context_type context_type)
+static const char *get_kernel_context_type_string(enum lttng_kernel_abi_context_type context_type)
 {
        const char *context_type_string;
 
@@ -367,15 +355,13 @@ const char *get_kernel_context_type_string(
                context_type_string = config_event_context_vsgid;
                break;
        default:
-               context_type_string = NULL;
+               context_type_string = nullptr;
        }
 
        return context_type_string;
 }
 
-static
-const char *get_ust_context_type_string(
-       enum lttng_ust_abi_context_type context_type)
+static const char *get_ust_context_type_string(enum lttng_ust_abi_context_type context_type)
 {
        const char *context_type_string;
 
@@ -446,16 +432,14 @@ const char *get_ust_context_type_string(
                 * are stored as a node of type event_perf_context_type.
                 */
        default:
-               context_type_string = NULL;
+               context_type_string = nullptr;
                break;
        }
 
        return context_type_string;
 }
 
-static
-const char *get_buffer_type_string(
-       enum lttng_buffer_type buffer_type)
+static const char *get_buffer_type_string(enum lttng_buffer_type buffer_type)
 {
        const char *buffer_type_string;
 
@@ -470,15 +454,13 @@ const char *get_buffer_type_string(
                buffer_type_string = config_buffer_type_global;
                break;
        default:
-               buffer_type_string = NULL;
+               buffer_type_string = nullptr;
        }
 
        return buffer_type_string;
 }
 
-static
-const char *get_loglevel_type_string(
-       enum lttng_ust_abi_loglevel_type loglevel_type)
+static const char *get_loglevel_type_string(enum lttng_ust_abi_loglevel_type loglevel_type)
 {
        const char *loglevel_type_string;
 
@@ -493,16 +475,14 @@ const char *get_loglevel_type_string(
                loglevel_type_string = config_loglevel_type_single;
                break;
        default:
-               loglevel_type_string = NULL;
+               loglevel_type_string = nullptr;
        }
 
        return loglevel_type_string;
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_function_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_function_event(struct config_writer *writer, struct ltt_kernel_event *event)
 {
        int ret;
 
@@ -512,8 +492,8 @@ int save_kernel_function_event(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_name,
-                       event->event->u.ftrace.symbol_name);
+       ret = config_writer_write_element_string(
+               writer, config_element_name, event->event->u.ftrace.symbol_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -529,9 +509,7 @@ end:
        return ret;
 }
 
-static
-int save_kernel_kprobe_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_kprobe_event(struct config_writer *writer, struct ltt_kernel_event *event)
 {
        int ret;
        const char *symbol_name;
@@ -546,15 +524,14 @@ int save_kernel_kprobe_event(struct config_writer *writer,
                 */
                addr = event->event->u.kprobe.addr;
                offset = event->event->u.kprobe.offset;
-               symbol_name = addr ? NULL : event->event->u.kprobe.symbol_name;
+               symbol_name = addr ? nullptr : event->event->u.kprobe.symbol_name;
                break;
        case LTTNG_KERNEL_ABI_KRETPROBE:
                addr = event->event->u.kretprobe.addr;
                offset = event->event->u.kretprobe.offset;
-               symbol_name = addr ? NULL : event->event->u.kretprobe.symbol_name;
+               symbol_name = addr ? nullptr : event->event->u.kretprobe.symbol_name;
                break;
        default:
-               LTTNG_ASSERT(1);
                ERR("Unsupported kernel instrumentation type.");
                ret = LTTNG_ERR_INVALID;
                goto end;
@@ -567,23 +544,23 @@ int save_kernel_kprobe_event(struct config_writer *writer,
        }
 
        if (addr) {
-               ret = config_writer_write_element_unsigned_int( writer,
-                               config_element_address, addr);
+               ret = config_writer_write_element_unsigned_int(
+                       writer, config_element_address, addr);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
        } else if (symbol_name) {
-               ret = config_writer_write_element_string(writer,
-                                config_element_symbol_name, symbol_name);
+               ret = config_writer_write_element_string(
+                       writer, config_element_symbol_name, symbol_name);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
                /* If the offset is non-zero, write it.*/
                if (offset) {
-                       ret = config_writer_write_element_unsigned_int(writer,
-                               config_element_offset, offset);
+                       ret = config_writer_write_element_unsigned_int(
+                               writer, config_element_offset, offset);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
@@ -599,7 +576,6 @@ int save_kernel_kprobe_event(struct config_writer *writer,
                goto end;
        }
 
-
        ret = config_writer_close_element(writer);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
@@ -613,9 +589,8 @@ end:
  * Save the userspace probe tracepoint event associated with the event to the
  * config writer.
  */
-static
-int save_kernel_userspace_probe_tracepoint_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_userspace_probe_tracepoint_event(struct config_writer *writer,
+                                                       struct ltt_kernel_event *event)
 {
        int ret = 0;
        const char *probe_name, *provider_name, *binary_path;
@@ -641,31 +616,29 @@ int save_kernel_userspace_probe_tracepoint_event(struct config_writer *writer,
 
        /* Get the binary path, probe name and provider name. */
        binary_path =
-               lttng_userspace_probe_location_tracepoint_get_binary_path(
-                               userspace_probe_location);
+               lttng_userspace_probe_location_tracepoint_get_binary_path(userspace_probe_location);
        if (!binary_path) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        probe_name =
-               lttng_userspace_probe_location_tracepoint_get_probe_name(
-                               userspace_probe_location);
+               lttng_userspace_probe_location_tracepoint_get_probe_name(userspace_probe_location);
        if (!probe_name) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       provider_name =
-               lttng_userspace_probe_location_tracepoint_get_provider_name(
-                               userspace_probe_location);
+       provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(
+               userspace_probe_location);
        if (!provider_name) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        /* Open a userspace probe tracepoint attribute. */
-       ret = config_writer_open_element(writer, config_element_userspace_probe_tracepoint_attributes);
+       ret = config_writer_open_element(writer,
+                                        config_element_userspace_probe_tracepoint_attributes);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -673,9 +646,10 @@ int save_kernel_userspace_probe_tracepoint_event(struct config_writer *writer,
 
        switch (lookup_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
-               ret = config_writer_write_element_string(writer,
-                               config_element_userspace_probe_lookup,
-                               config_element_userspace_probe_lookup_tracepoint_sdt);
+               ret = config_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_lookup,
+                       config_element_userspace_probe_lookup_tracepoint_sdt);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -688,25 +662,24 @@ int save_kernel_userspace_probe_tracepoint_event(struct config_writer *writer,
        }
 
        /* Write the binary path, provider name and the probe name. */
-       ret = config_writer_write_element_string(writer,
-                       config_element_userspace_probe_location_binary_path,
-                       binary_path);
+       ret = config_writer_write_element_string(
+               writer, config_element_userspace_probe_location_binary_path, binary_path);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_userspace_probe_tracepoint_location_provider_name,
-                       provider_name);
+       ret = config_writer_write_element_string(
+               writer,
+               config_element_userspace_probe_tracepoint_location_provider_name,
+               provider_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_userspace_probe_tracepoint_location_probe_name,
-                       probe_name);
+       ret = config_writer_write_element_string(
+               writer, config_element_userspace_probe_tracepoint_location_probe_name, probe_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -727,9 +700,8 @@ end:
  * Save the userspace probe function event associated with the event to the
  * config writer.
  */
-static
-int save_kernel_userspace_probe_function_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_userspace_probe_function_event(struct config_writer *writer,
+                                                     struct ltt_kernel_event *event)
 {
        int ret = 0;
        const char *function_name, *binary_path;
@@ -745,8 +717,7 @@ int save_kernel_userspace_probe_function_event(struct config_writer *writer,
        }
 
        /* Get lookup method and lookup method type. */
-       lookup_method = lttng_userspace_probe_location_get_lookup_method(
-                       userspace_probe_location);
+       lookup_method = lttng_userspace_probe_location_get_lookup_method(userspace_probe_location);
        if (!lookup_method) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -754,16 +725,14 @@ int save_kernel_userspace_probe_function_event(struct config_writer *writer,
 
        /* Get the binary path and the function name. */
        binary_path =
-               lttng_userspace_probe_location_function_get_binary_path(
-                               userspace_probe_location);
+               lttng_userspace_probe_location_function_get_binary_path(userspace_probe_location);
        if (!binary_path) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        function_name =
-               lttng_userspace_probe_location_function_get_function_name(
-                               userspace_probe_location);
+               lttng_userspace_probe_location_function_get_function_name(userspace_probe_location);
        if (!function_name) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -771,7 +740,7 @@ int save_kernel_userspace_probe_function_event(struct config_writer *writer,
 
        /* Open a userspace probe function attribute. */
        ret = config_writer_open_element(writer,
-                       config_element_userspace_probe_function_attributes);
+                                        config_element_userspace_probe_function_attributes);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -780,18 +749,20 @@ int save_kernel_userspace_probe_function_event(struct config_writer *writer,
        lookup_type = lttng_userspace_probe_location_lookup_method_get_type(lookup_method);
        switch (lookup_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
-               ret = config_writer_write_element_string(writer,
-                               config_element_userspace_probe_lookup,
-                               config_element_userspace_probe_lookup_function_elf);
+               ret = config_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_lookup,
+                       config_element_userspace_probe_lookup_function_elf);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT:
-               ret = config_writer_write_element_string(writer,
-                               config_element_userspace_probe_lookup,
-                               config_element_userspace_probe_lookup_function_default);
+               ret = config_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_lookup,
+                       config_element_userspace_probe_lookup_function_default);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -804,17 +775,17 @@ int save_kernel_userspace_probe_function_event(struct config_writer *writer,
        }
 
        /* Write the binary path and the function name. */
-       ret = config_writer_write_element_string(writer,
-                       config_element_userspace_probe_location_binary_path,
-                       binary_path);
+       ret = config_writer_write_element_string(
+               writer, config_element_userspace_probe_location_binary_path, binary_path);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_userspace_probe_function_location_function_name,
-                       function_name);
+       ret = config_writer_write_element_string(
+               writer,
+               config_element_userspace_probe_function_location_function_name,
+               function_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -831,9 +802,8 @@ end:
        return ret;
 }
 
-static
-int save_kernel_userspace_probe_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_userspace_probe_event(struct config_writer *writer,
+                                            struct ltt_kernel_event *event)
 {
        int ret;
        struct lttng_userspace_probe_location *userspace_probe_location;
@@ -845,7 +815,7 @@ int save_kernel_userspace_probe_event(struct config_writer *writer,
                goto end;
        }
 
-       switch(lttng_userspace_probe_location_get_type(userspace_probe_location)) {
+       switch (lttng_userspace_probe_location_get_type(userspace_probe_location)) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
        {
                ret = save_kernel_userspace_probe_function_event(writer, event);
@@ -875,9 +845,7 @@ end:
        return ret;
 }
 
-static
-int save_kernel_event(struct config_writer *writer,
-               struct ltt_kernel_event *event)
+static int save_kernel_event(struct config_writer *writer, struct ltt_kernel_event *event)
 {
        int ret;
        const char *instrumentation_type;
@@ -889,39 +857,35 @@ int save_kernel_event(struct config_writer *writer,
        }
 
        if (event->event->name[0]) {
-               ret = config_writer_write_element_string(writer,
-                       config_element_name, event->event->name);
+               ret = config_writer_write_element_string(
+                       writer, config_element_name, event->event->name);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_enabled,
-               event->enabled);
+       ret = config_writer_write_element_bool(writer, config_element_enabled, event->enabled);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       instrumentation_type = get_kernel_instrumentation_string(
-               event->event->instrumentation);
+       instrumentation_type = get_kernel_instrumentation_string(event->event->instrumentation);
        if (!instrumentation_type) {
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_type,
-               instrumentation_type);
+       ret = config_writer_write_element_string(writer, config_element_type, instrumentation_type);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        if (event->filter_expression) {
-               ret = config_writer_write_element_string(writer,
-                               config_element_filter,
-                               event->filter_expression);
+               ret = config_writer_write_element_string(
+                       writer, config_element_filter, event->filter_expression);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -929,12 +893,10 @@ int save_kernel_event(struct config_writer *writer,
        }
 
        if (event->event->instrumentation == LTTNG_KERNEL_ABI_FUNCTION ||
-               event->event->instrumentation == LTTNG_KERNEL_ABI_KPROBE ||
-               event->event->instrumentation == LTTNG_KERNEL_ABI_UPROBE ||
-               event->event->instrumentation == LTTNG_KERNEL_ABI_KRETPROBE) {
-
-               ret = config_writer_open_element(writer,
-                       config_element_attributes);
+           event->event->instrumentation == LTTNG_KERNEL_ABI_KPROBE ||
+           event->event->instrumentation == LTTNG_KERNEL_ABI_UPROBE ||
+           event->event->instrumentation == LTTNG_KERNEL_ABI_KRETPROBE) {
+               ret = config_writer_open_element(writer, config_element_attributes);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -988,9 +950,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_events(struct config_writer *writer,
-       struct ltt_kernel_channel *kchan)
+static int save_kernel_events(struct config_writer *writer, struct ltt_kernel_channel *kchan)
 {
        int ret;
        struct ltt_kernel_event *event;
@@ -1001,7 +961,7 @@ int save_kernel_events(struct config_writer *writer,
                goto end;
        }
 
-       cds_list_for_each_entry(event, &kchan->events_list.head, list) {
+       cds_list_for_each_entry (event, &kchan->events_list.head, list) {
                ret = save_kernel_event(writer, event);
                if (ret != LTTNG_OK) {
                        goto end;
@@ -1021,9 +981,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_event(struct config_writer *writer,
-       struct ltt_ust_event *event)
+static int save_ust_event(struct config_writer *writer, struct ltt_ust_event *event)
 {
        int ret;
        const char *loglevel_type_string;
@@ -1035,16 +993,15 @@ int save_ust_event(struct config_writer *writer,
        }
 
        if (event->attr.name[0]) {
-               ret = config_writer_write_element_string(writer,
-                       config_element_name, event->attr.name);
+               ret = config_writer_write_element_string(
+                       writer, config_element_name, event->attr.name);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_enabled,
-               event->enabled);
+       ret = config_writer_write_element_bool(writer, config_element_enabled, event->enabled);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1055,23 +1012,23 @@ int save_ust_event(struct config_writer *writer,
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
-       ret = config_writer_write_element_string(writer, config_element_type,
-               config_event_type_tracepoint);
+       ret = config_writer_write_element_string(
+               writer, config_element_type, config_event_type_tracepoint);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       loglevel_type_string = get_loglevel_type_string(
-               (lttng_ust_abi_loglevel_type) event->attr.loglevel_type);
+       loglevel_type_string =
+               get_loglevel_type_string((lttng_ust_abi_loglevel_type) event->attr.loglevel_type);
        if (!loglevel_type_string) {
                ERR("Unsupported UST loglevel type.");
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-               config_element_loglevel_type, loglevel_type_string);
+       ret = config_writer_write_element_string(
+               writer, config_element_loglevel_type, loglevel_type_string);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1079,8 +1036,8 @@ int save_ust_event(struct config_writer *writer,
 
        /* The log level is irrelevant if no "filtering" is enabled */
        if (event->attr.loglevel_type != LTTNG_UST_ABI_LOGLEVEL_ALL) {
-               ret = config_writer_write_element_signed_int(writer,
-                               config_element_loglevel, event->attr.loglevel);
+               ret = config_writer_write_element_signed_int(
+                       writer, config_element_loglevel, event->attr.loglevel);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -1088,8 +1045,8 @@ int save_ust_event(struct config_writer *writer,
        }
 
        if (event->filter_expression) {
-               ret = config_writer_write_element_string(writer,
-                       config_element_filter, event->filter_expression);
+               ret = config_writer_write_element_string(
+                       writer, config_element_filter, event->filter_expression);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -1099,18 +1056,17 @@ int save_ust_event(struct config_writer *writer,
        if (event->exclusion && event->exclusion->count) {
                uint32_t i;
 
-               ret = config_writer_open_element(writer,
-                       config_element_exclusions);
+               ret = config_writer_open_element(writer, config_element_exclusions);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
                for (i = 0; i < event->exclusion->count; i++) {
-                       ret = config_writer_write_element_string(writer,
+                       ret = config_writer_write_element_string(
+                               writer,
                                config_element_exclusion,
-                               LTTNG_EVENT_EXCLUSION_NAME_AT(
-                                       event->exclusion, i));
+                               LTTNG_EVENT_EXCLUSION_NAME_AT(event->exclusion, i));
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
@@ -1138,9 +1094,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_events(struct config_writer *writer,
-       struct lttng_ht *events)
+static int save_ust_events(struct config_writer *writer, struct lttng_ht *events)
 {
        int ret;
        struct ltt_ust_event *event;
@@ -1153,21 +1107,22 @@ int save_ust_events(struct config_writer *writer,
                goto end;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(events->ht, &iter.iter, node, node) {
-               event = lttng::utils::container_of(node, &ltt_ust_event::node);
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               if (event->internal) {
-                       /* Internal events must not be exposed to clients */
-                       continue;
-               }
-               ret = save_ust_event(writer, event);
-               if (ret != LTTNG_OK) {
-                       rcu_read_unlock();
-                       goto end;
+               cds_lfht_for_each_entry (events->ht, &iter.iter, node, node) {
+                       event = lttng::utils::container_of(node, &ltt_ust_event::node);
+
+                       if (event->internal) {
+                               /* Internal events must not be exposed to clients */
+                               continue;
+                       }
+                       ret = save_ust_event(writer, event);
+                       if (ret != LTTNG_OK) {
+                               goto end;
+                       }
                }
        }
-       rcu_read_unlock();
 
        /* /events */
        ret = config_writer_close_element(writer);
@@ -1182,17 +1137,15 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int init_ust_event_from_agent_event(struct ltt_ust_event *ust_event,
-               struct agent_event *agent_event)
+static int init_ust_event_from_agent_event(struct ltt_ust_event *ust_event,
+                                          struct agent_event *agent_event)
 {
        int ret;
        enum lttng_ust_abi_loglevel_type ust_loglevel_type;
 
        ust_event->enabled = AGENT_EVENT_IS_ENABLED(agent_event);
        ust_event->attr.instrumentation = LTTNG_UST_ABI_TRACEPOINT;
-       if (lttng_strncpy(ust_event->attr.name, agent_event->name,
-                       LTTNG_SYMBOL_NAME_LEN)) {
+       if (lttng_strncpy(ust_event->attr.name, agent_event->name, LTTNG_SYMBOL_NAME_LEN)) {
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
@@ -1223,9 +1176,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_agent_events(struct config_writer *writer,
-               struct agent *agent)
+static int save_agent_events(struct config_writer *writer, struct agent *agent)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -1237,32 +1188,32 @@ int save_agent_events(struct config_writer *writer,
                goto end;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(agent->events->ht, &iter.iter, node, node) {
-               struct agent_event *agent_event;
-               struct ltt_ust_event fake_event;
-
-               memset(&fake_event, 0, sizeof(fake_event));
-               agent_event = lttng::utils::container_of(node, &agent_event::node);
-
-               /*
-                * Initialize a fake ust event to reuse the same serialization
-                * function since UST and agent events contain the same info
-                * (and one could wonder why they don't reuse the same
-                * structures...).
-                */
-               ret = init_ust_event_from_agent_event(&fake_event, agent_event);
-               if (ret != LTTNG_OK) {
-                       rcu_read_unlock();
-                       goto end;
-               }
-               ret = save_ust_event(writer, &fake_event);
-               if (ret != LTTNG_OK) {
-                       rcu_read_unlock();
-                       goto end;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (agent->events->ht, &iter.iter, node, node) {
+                       struct agent_event *agent_event;
+                       struct ltt_ust_event fake_event;
+
+                       memset(&fake_event, 0, sizeof(fake_event));
+                       agent_event = lttng::utils::container_of(node, &agent_event::node);
+
+                       /*
+                        * Initialize a fake ust event to reuse the same serialization
+                        * function since UST and agent events contain the same info
+                        * (and one could wonder why they don't reuse the same
+                        * structures...).
+                        */
+                       ret = init_ust_event_from_agent_event(&fake_event, agent_event);
+                       if (ret != LTTNG_OK) {
+                               goto end;
+                       }
+                       ret = save_ust_event(writer, &fake_event);
+                       if (ret != LTTNG_OK) {
+                               goto end;
+                       }
                }
        }
-       rcu_read_unlock();
 
        /* /events */
        ret = config_writer_close_element(writer);
@@ -1277,9 +1228,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_context(struct config_writer *writer,
-       struct lttng_kernel_abi_context *ctx)
+static int save_kernel_context(struct config_writer *writer, struct lttng_kernel_abi_context *ctx)
 {
        int ret = LTTNG_OK;
 
@@ -1294,29 +1243,28 @@ int save_kernel_context(struct config_writer *writer,
        }
 
        if (ctx->ctx == LTTNG_KERNEL_ABI_CONTEXT_PERF_CPU_COUNTER) {
-               ret = config_writer_open_element(writer,
-                               config_element_context_perf);
+               ret = config_writer_open_element(writer, config_element_context_perf);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = config_writer_write_element_unsigned_int(writer,
-                       config_element_type, ctx->u.perf_counter.type);
+               ret = config_writer_write_element_unsigned_int(
+                       writer, config_element_type, ctx->u.perf_counter.type);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = config_writer_write_element_unsigned_int(writer,
-                       config_element_config, ctx->u.perf_counter.config);
+               ret = config_writer_write_element_unsigned_int(
+                       writer, config_element_config, ctx->u.perf_counter.config);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = config_writer_write_element_string(writer,
-                       config_element_name, ctx->u.perf_counter.name);
+               ret = config_writer_write_element_string(
+                       writer, config_element_name, ctx->u.perf_counter.name);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -1329,8 +1277,7 @@ int save_kernel_context(struct config_writer *writer,
                        goto end;
                }
        } else {
-               const char *context_type_string =
-                       get_kernel_context_type_string(ctx->ctx);
+               const char *context_type_string = get_kernel_context_type_string(ctx->ctx);
 
                if (!context_type_string) {
                        ERR("Unsupported kernel context type.");
@@ -1338,8 +1285,8 @@ int save_kernel_context(struct config_writer *writer,
                        goto end;
                }
 
-               ret = config_writer_write_element_string(writer,
-                       config_element_type, context_type_string);
+               ret = config_writer_write_element_string(
+                       writer, config_element_type, context_type_string);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -1359,9 +1306,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_contexts(struct config_writer *writer,
-               struct ltt_kernel_channel *kchan)
+static int save_kernel_contexts(struct config_writer *writer, struct ltt_kernel_channel *kchan)
 {
        int ret;
        struct ltt_kernel_context *ctx;
@@ -1377,7 +1322,7 @@ int save_kernel_contexts(struct config_writer *writer,
                goto end;
        }
 
-       cds_list_for_each_entry(ctx, &kchan->ctx_list, list) {
+       cds_list_for_each_entry (ctx, &kchan->ctx_list, list) {
                ret = save_kernel_context(writer, &ctx->ctx);
                if (ret != LTTNG_OK) {
                        goto end;
@@ -1397,9 +1342,8 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_context_perf_thread_counter(struct config_writer *writer,
-               struct ltt_ust_context *ctx)
+static int save_ust_context_perf_thread_counter(struct config_writer *writer,
+                                               struct ltt_ust_context *ctx)
 {
        int ret;
 
@@ -1413,22 +1357,22 @@ int save_ust_context_perf_thread_counter(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-                       config_element_type, ctx->ctx.u.perf_counter.type);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_type, ctx->ctx.u.perf_counter.type);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-                       config_element_config, ctx->ctx.u.perf_counter.config);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_config, ctx->ctx.u.perf_counter.config);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_name,
-                       ctx->ctx.u.perf_counter.name);
+       ret = config_writer_write_element_string(
+               writer, config_element_name, ctx->ctx.u.perf_counter.name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1447,9 +1391,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_context_app_ctx(struct config_writer *writer,
-               struct ltt_ust_context *ctx)
+static int save_ust_context_app_ctx(struct config_writer *writer, struct ltt_ust_context *ctx)
 {
        int ret;
 
@@ -1463,17 +1405,15 @@ int save_ust_context_app_ctx(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_context_app_provider_name,
-                       ctx->ctx.u.app_ctx.provider_name);
+       ret = config_writer_write_element_string(
+               writer, config_element_context_app_provider_name, ctx->ctx.u.app_ctx.provider_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_context_app_ctx_name,
-                       ctx->ctx.u.app_ctx.ctx_name);
+       ret = config_writer_write_element_string(
+               writer, config_element_context_app_ctx_name, ctx->ctx.u.app_ctx.ctx_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1492,9 +1432,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_context_generic(struct config_writer *writer,
-               struct ltt_ust_context *ctx)
+static int save_ust_context_generic(struct config_writer *writer, struct ltt_ust_context *ctx)
 {
        int ret;
        const char *context_type_string;
@@ -1503,16 +1441,14 @@ int save_ust_context_generic(struct config_writer *writer,
        LTTNG_ASSERT(ctx);
 
        /* Save context as event_context_type_type */
-       context_type_string = get_ust_context_type_string(
-                       ctx->ctx.ctx);
+       context_type_string = get_ust_context_type_string(ctx->ctx.ctx);
        if (!context_type_string) {
                ERR("Unsupported UST context type.");
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_type, context_type_string);
+       ret = config_writer_write_element_string(writer, config_element_type, context_type_string);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1524,9 +1460,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_context(struct config_writer *writer,
-       struct cds_list_head *ctx_list)
+static int save_ust_context(struct config_writer *writer, struct cds_list_head *ctx_list)
 {
        int ret;
        struct ltt_ust_context *ctx;
@@ -1540,9 +1474,8 @@ int save_ust_context(struct config_writer *writer,
                goto end;
        }
 
-       cds_list_for_each_entry(ctx, ctx_list, list) {
-               ret = config_writer_open_element(writer,
-                       config_element_context);
+       cds_list_for_each_entry (ctx, ctx_list, list) {
+               ret = config_writer_open_element(writer, config_element_context);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -1584,9 +1517,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_channel(struct config_writer *writer,
-       struct ltt_kernel_channel *kchan)
+static int save_kernel_channel(struct config_writer *writer, struct ltt_kernel_channel *kchan)
 {
        int ret;
 
@@ -1599,15 +1530,14 @@ int save_kernel_channel(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_name,
-               kchan->channel->name);
+       ret = config_writer_write_element_string(writer, config_element_name, kchan->channel->name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_enabled,
-               kchan->channel->enabled);
+       ret = config_writer_write_element_bool(
+               writer, config_element_enabled, kchan->channel->enabled);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1641,10 +1571,9 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_channel(struct config_writer *writer,
-       struct ltt_ust_channel *ust_chan,
-       struct ltt_ust_session *session)
+static int save_ust_channel(struct config_writer *writer,
+                           struct ltt_ust_channel *ust_chan,
+                           struct ltt_ust_session *session)
 {
        int ret;
 
@@ -1658,15 +1587,13 @@ int save_ust_channel(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_name,
-               ust_chan->name);
+       ret = config_writer_write_element_string(writer, config_element_name, ust_chan->name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_enabled,
-               ust_chan->enabled);
+       ret = config_writer_write_element_bool(writer, config_element_enabled, ust_chan->enabled);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1677,23 +1604,22 @@ int save_ust_channel(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_size, ust_chan->tracefile_size);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_size, ust_chan->tracefile_size);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_count, ust_chan->tracefile_count);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_count, ust_chan->tracefile_count);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-               config_element_live_timer_interval,
-               session->live_timer_interval);
+       ret = config_writer_write_element_unsigned_int(
+               writer, config_element_live_timer_interval, session->live_timer_interval);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1705,7 +1631,7 @@ int save_ust_channel(struct config_writer *writer,
                        goto end;
                }
        } else {
-               struct agent *agent = NULL;
+               struct agent *agent = nullptr;
 
                agent = trace_ust_find_agent(session, ust_chan->domain);
                if (!agent) {
@@ -1744,9 +1670,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_kernel_session(struct config_writer *writer,
-       struct ltt_session *session)
+static int save_kernel_session(struct config_writer *writer, struct ltt_session *session)
 {
        int ret;
        struct ltt_kernel_channel *kchan;
@@ -1754,29 +1678,27 @@ int save_kernel_session(struct config_writer *writer,
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(session);
 
-       ret = config_writer_write_element_string(writer, config_element_type,
-               config_domain_type_kernel);
+       ret = config_writer_write_element_string(
+               writer, config_element_type, config_domain_type_kernel);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-               config_element_buffer_type, config_buffer_type_global);
+       ret = config_writer_write_element_string(
+               writer, config_element_buffer_type, config_buffer_type_global);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       ret = config_writer_open_element(writer,
-               config_element_channels);
+       ret = config_writer_open_element(writer, config_element_channels);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       cds_list_for_each_entry(kchan, &session->kernel_session->channel_list.head,
-                       list) {
+       cds_list_for_each_entry (kchan, &session->kernel_session->channel_list.head, list) {
                ret = save_kernel_channel(writer, kchan);
                if (ret != LTTNG_OK) {
                        goto end;
@@ -1795,8 +1717,7 @@ end:
        return ret;
 }
 
-static
-const char *get_config_domain_str(enum lttng_domain_type domain)
+static const char *get_config_domain_str(enum lttng_domain_type domain)
 {
        const char *str_dom;
 
@@ -1825,15 +1746,15 @@ const char *get_config_domain_str(enum lttng_domain_type domain)
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
 static int save_process_attr_tracker(struct config_writer *writer,
-               struct ltt_session *sess,
-               int domain,
-               enum lttng_process_attr process_attr)
+                                    struct ltt_session *sess,
+                                    int domain,
+                                    enum lttng_process_attr process_attr)
 {
        int ret = LTTNG_OK;
        const char *element_id_tracker, *element_target_id, *element_id;
        const struct process_attr_tracker *tracker;
        enum lttng_tracking_policy tracking_policy;
-       struct lttng_process_attr_values *values = NULL;
+       struct lttng_process_attr_values *values = nullptr;
 
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_PROCESS_ID:
@@ -1874,15 +1795,13 @@ static int save_process_attr_tracker(struct config_writer *writer,
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
        {
-               tracker = kernel_get_process_attr_tracker(
-                               sess->kernel_session, process_attr);
+               tracker = kernel_get_process_attr_tracker(sess->kernel_session, process_attr);
                LTTNG_ASSERT(tracker);
                break;
        }
        case LTTNG_DOMAIN_UST:
        {
-               tracker = trace_ust_get_process_attr_tracker(
-                               sess->ust_session, process_attr);
+               tracker = trace_ust_get_process_attr_tracker(sess->ust_session, process_attr);
                LTTNG_ASSERT(tracker);
                break;
        }
@@ -1907,8 +1826,7 @@ static int save_process_attr_tracker(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_open_element(
-                       writer, config_element_process_attr_values);
+       ret = config_writer_open_element(writer, config_element_process_attr_values);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -1917,8 +1835,7 @@ static int save_process_attr_tracker(struct config_writer *writer,
        if (tracking_policy == LTTNG_TRACKING_POLICY_INCLUDE_SET) {
                unsigned int i, count;
                enum process_attr_tracker_status status =
-                               process_attr_tracker_get_inclusion_set(
-                                               tracker, &values);
+                       process_attr_tracker_get_inclusion_set(tracker, &values);
 
                if (status != PROCESS_ATTR_TRACKER_STATUS_OK) {
                        ret = LTTNG_ERR_NOMEM;
@@ -1929,14 +1846,12 @@ static int save_process_attr_tracker(struct config_writer *writer,
 
                for (i = 0; i < count; i++) {
                        unsigned int integral_value = UINT_MAX;
-                       const char *name = NULL;
+                       const char *name = nullptr;
                        const struct process_attr_value *value =
-                                       lttng_process_attr_tracker_values_get_at_index(
-                                                       values, i);
+                               lttng_process_attr_tracker_values_get_at_index(values, i);
 
                        LTTNG_ASSERT(value);
-                       ret = config_writer_open_element(
-                                       writer, element_target_id);
+                       ret = config_writer_open_element(writer, element_target_id);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
@@ -1944,16 +1859,13 @@ static int save_process_attr_tracker(struct config_writer *writer,
 
                        switch (value->type) {
                        case LTTNG_PROCESS_ATTR_VALUE_TYPE_PID:
-                               integral_value =
-                                               (unsigned int) value->value.pid;
+                               integral_value = (unsigned int) value->value.pid;
                                break;
                        case LTTNG_PROCESS_ATTR_VALUE_TYPE_UID:
-                               integral_value =
-                                               (unsigned int) value->value.uid;
+                               integral_value = (unsigned int) value->value.uid;
                                break;
                        case LTTNG_PROCESS_ATTR_VALUE_TYPE_GID:
-                               integral_value =
-                                               (unsigned int) value->value.gid;
+                               integral_value = (unsigned int) value->value.gid;
                                break;
                        case LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME:
                                name = value->value.user_name;
@@ -1968,12 +1880,11 @@ static int save_process_attr_tracker(struct config_writer *writer,
                        }
 
                        if (name) {
-                               ret = config_writer_write_element_string(writer,
-                                               config_element_name, name);
+                               ret = config_writer_write_element_string(
+                                       writer, config_element_name, name);
                        } else {
                                ret = config_writer_write_element_unsigned_int(
-                                               writer, element_id,
-                                               integral_value);
+                                       writer, element_id, integral_value);
                        }
 
                        if (ret) {
@@ -2011,58 +1922,55 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static int save_process_attr_trackers(struct config_writer *writer,
-               struct ltt_session *sess,
-               int domain)
+static int
+save_process_attr_trackers(struct config_writer *writer, struct ltt_session *sess, int domain)
 {
        int ret;
 
        switch (domain) {
        case LTTNG_DOMAIN_KERNEL:
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_PROCESS_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_PROCESS_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_USER_ID);
+               ret = save_process_attr_tracker(writer, sess, domain, LTTNG_PROCESS_ATTR_USER_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_GROUP_ID);
+               ret = save_process_attr_tracker(writer, sess, domain, LTTNG_PROCESS_ATTR_GROUP_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
                break;
        case LTTNG_DOMAIN_UST:
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
-               ret = save_process_attr_tracker(writer, sess, domain,
-                               LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
+               ret = save_process_attr_tracker(
+                       writer, sess, domain, LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -2077,9 +1985,9 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_ust_domain(struct config_writer *writer,
-       struct ltt_session *session, enum lttng_domain_type domain)
+static int save_ust_domain(struct config_writer *writer,
+                          struct ltt_session *session,
+                          enum lttng_domain_type domain)
 {
        int ret;
        struct ltt_ust_channel *ust_chan;
@@ -2091,8 +1999,7 @@ int save_ust_domain(struct config_writer *writer,
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(session);
 
-       ret = config_writer_open_element(writer,
-                       config_element_domain);
+       ret = config_writer_open_element(writer, config_element_domain);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -2104,23 +2011,21 @@ int save_ust_domain(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_type, config_domain_name);
+       ret = config_writer_write_element_string(writer, config_element_type, config_domain_name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       buffer_type_string = get_buffer_type_string(
-                       session->ust_session->buffer_type);
+       buffer_type_string = get_buffer_type_string(session->ust_session->buffer_type);
        if (!buffer_type_string) {
                ERR("Unsupported buffer type.");
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer,
-                       config_element_buffer_type, buffer_type_string);
+       ret = config_writer_write_element_string(
+               writer, config_element_buffer_type, buffer_type_string);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -2132,19 +2037,20 @@ int save_ust_domain(struct config_writer *writer,
                goto end;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(session->ust_session->domain_global.channels->ht,
-                       &iter.iter, node, node) {
-               ust_chan = lttng::utils::container_of(node, &ltt_ust_channel::node);
-               if (domain == ust_chan->domain) {
-                       ret = save_ust_channel(writer, ust_chan, session->ust_session);
-                       if (ret != LTTNG_OK) {
-                               rcu_read_unlock();
-                               goto end;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       session->ust_session->domain_global.channels->ht, &iter.iter, node, node) {
+                       ust_chan = lttng::utils::container_of(node, &ltt_ust_channel::node);
+                       if (domain == ust_chan->domain) {
+                               ret = save_ust_channel(writer, ust_chan, session->ust_session);
+                               if (ret != LTTNG_OK) {
+                                       goto end;
+                               }
                        }
                }
        }
-       rcu_read_unlock();
 
        /* /channels */
        ret = config_writer_close_element(writer);
@@ -2154,15 +2060,13 @@ int save_ust_domain(struct config_writer *writer,
        }
 
        if (domain == LTTNG_DOMAIN_UST) {
-               ret = config_writer_open_element(
-                               writer, config_element_process_attr_trackers);
+               ret = config_writer_open_element(writer, config_element_process_attr_trackers);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = save_process_attr_trackers(
-                               writer, session, LTTNG_DOMAIN_UST);
+               ret = save_process_attr_trackers(writer, session, LTTNG_DOMAIN_UST);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -2188,8 +2092,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_domains(struct config_writer *writer, struct ltt_session *session)
+static int save_domains(struct config_writer *writer, struct ltt_session *session)
 {
        int ret = LTTNG_OK;
 
@@ -2207,8 +2110,7 @@ int save_domains(struct config_writer *writer, struct ltt_session *session)
        }
 
        if (session->kernel_session) {
-               ret = config_writer_open_element(writer,
-                       config_element_domain);
+               ret = config_writer_open_element(writer, config_element_domain);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -2219,15 +2121,13 @@ int save_domains(struct config_writer *writer, struct ltt_session *session)
                        goto end;
                }
 
-               ret = config_writer_open_element(
-                               writer, config_element_process_attr_trackers);
+               ret = config_writer_open_element(writer, config_element_process_attr_trackers);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
                }
 
-               ret = save_process_attr_trackers(
-                               writer, session, LTTNG_DOMAIN_KERNEL);
+               ret = save_process_attr_trackers(writer, session, LTTNG_DOMAIN_KERNEL);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -2281,9 +2181,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_consumer_output(struct config_writer *writer,
-       struct consumer_output *output)
+static int save_consumer_output(struct config_writer *writer, struct consumer_output *output)
 {
        int ret;
 
@@ -2296,8 +2194,7 @@ int save_consumer_output(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_enabled,
-                       output->enabled);
+       ret = config_writer_write_element_bool(writer, config_element_enabled, output->enabled);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
@@ -2311,8 +2208,8 @@ int save_consumer_output(struct config_writer *writer,
 
        switch (output->type) {
        case CONSUMER_DST_LOCAL:
-               ret = config_writer_write_element_string(writer,
-                       config_element_path, output->dst.session_root_path);
+               ret = config_writer_write_element_string(
+                       writer, config_element_path, output->dst.session_root_path);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -2334,16 +2231,15 @@ int save_consumer_output(struct config_writer *writer,
                        goto end_net_output;
                }
 
-               if (output->dst.net.control_isset &&
-                       output->dst.net.data_isset) {
+               if (output->dst.net.control_isset && output->dst.net.data_isset) {
                        ret = uri_to_str_url(&output->dst.net.control, uri, PATH_MAX);
                        if (ret < 0) {
                                ret = LTTNG_ERR_INVALID;
                                goto end_net_output;
                        }
 
-                       ret = config_writer_write_element_string(writer,
-                                       config_element_control_uri, uri);
+                       ret = config_writer_write_element_string(
+                               writer, config_element_control_uri, uri);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end_net_output;
@@ -2355,22 +2251,21 @@ int save_consumer_output(struct config_writer *writer,
                                goto end_net_output;
                        }
 
-                       ret = config_writer_write_element_string(writer,
-                                       config_element_data_uri, uri);
+                       ret = config_writer_write_element_string(
+                               writer, config_element_data_uri, uri);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end_net_output;
                        }
                        ret = LTTNG_OK;
-end_net_output:
+               end_net_output:
                        free(uri);
                        if (ret != LTTNG_OK) {
                                goto end;
                        }
                } else {
-                       ret = !output->dst.net.control_isset ?
-                               LTTNG_ERR_URL_CTRL_MISS :
-                               LTTNG_ERR_URL_DATA_MISS;
+                       ret = !output->dst.net.control_isset ? LTTNG_ERR_URL_CTRL_MISS :
+                                                              LTTNG_ERR_URL_DATA_MISS;
                        free(uri);
                        goto end;
                }
@@ -2408,9 +2303,7 @@ end:
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_snapshot_outputs(struct config_writer *writer,
-       struct snapshot *snapshot)
+static int save_snapshot_outputs(struct config_writer *writer, struct snapshot *snapshot)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -2425,43 +2318,43 @@ int save_snapshot_outputs(struct config_writer *writer,
                goto end;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(snapshot->output_ht->ht, &iter.iter, output,
-                       node.node) {
-               ret = config_writer_open_element(writer,
-                       config_element_output);
-               if (ret) {
-                       ret = LTTNG_ERR_SAVE_IO_FAIL;
-                       goto end_unlock;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               ret = config_writer_write_element_string(writer,
-                       config_element_name, output->name);
-               if (ret) {
-                       ret = LTTNG_ERR_SAVE_IO_FAIL;
-                       goto end_unlock;
-               }
+               cds_lfht_for_each_entry (snapshot->output_ht->ht, &iter.iter, output, node.node) {
+                       ret = config_writer_open_element(writer, config_element_output);
+                       if (ret) {
+                               ret = LTTNG_ERR_SAVE_IO_FAIL;
+                               goto end_unlock;
+                       }
 
-               ret = config_writer_write_element_unsigned_int(writer,
-                       config_element_max_size, output->max_size);
-               if (ret) {
-                       ret = LTTNG_ERR_SAVE_IO_FAIL;
-                       goto end_unlock;
-               }
+                       ret = config_writer_write_element_string(
+                               writer, config_element_name, output->name);
+                       if (ret) {
+                               ret = LTTNG_ERR_SAVE_IO_FAIL;
+                               goto end_unlock;
+                       }
 
-               ret = save_consumer_output(writer, output->consumer);
-               if (ret != LTTNG_OK) {
-                       goto end_unlock;
-               }
+                       ret = config_writer_write_element_unsigned_int(
+                               writer, config_element_max_size, output->max_size);
+                       if (ret) {
+                               ret = LTTNG_ERR_SAVE_IO_FAIL;
+                               goto end_unlock;
+                       }
 
-               /* /output */
-               ret = config_writer_close_element(writer);
-               if (ret) {
-                       ret = LTTNG_ERR_SAVE_IO_FAIL;
-                       goto end_unlock;
+                       ret = save_consumer_output(writer, output->consumer);
+                       if (ret != LTTNG_OK) {
+                               goto end_unlock;
+                       }
+
+                       /* /output */
+                       ret = config_writer_close_element(writer);
+                       if (ret) {
+                               ret = LTTNG_ERR_SAVE_IO_FAIL;
+                               goto end_unlock;
+                       }
                }
        }
-       rcu_read_unlock();
 
        /* /snapshot_outputs */
        ret = config_writer_close_element(writer);
@@ -2474,14 +2367,11 @@ int save_snapshot_outputs(struct config_writer *writer,
 end:
        return ret;
 end_unlock:
-       rcu_read_unlock();
        return ret;
 }
 
 /* Return LTTNG_OK on success else a LTTNG_ERR* code. */
-static
-int save_session_output(struct config_writer *writer,
-       struct ltt_session *session)
+static int save_session_output(struct config_writer *writer, struct ltt_session *session)
 {
        int ret;
 
@@ -2489,7 +2379,7 @@ int save_session_output(struct config_writer *writer,
        LTTNG_ASSERT(session);
 
        if ((session->snapshot_mode && session->snapshot.nb_output == 0) ||
-               (!session->snapshot_mode && !session->consumer)) {
+           (!session->snapshot_mode && !session->consumer)) {
                /* Session is in no output mode */
                ret = LTTNG_OK;
                goto end;
@@ -2526,9 +2416,9 @@ end:
        return ret;
 }
 
-static
-int save_session_rotation_schedule(struct config_writer *writer,
-               enum lttng_rotation_schedule_type type, uint64_t value)
+static int save_session_rotation_schedule(struct config_writer *writer,
+                                         enum lttng_rotation_schedule_type type,
+                                         uint64_t value)
 {
        int ret = 0;
        const char *element_name;
@@ -2537,11 +2427,11 @@ int save_session_rotation_schedule(struct config_writer *writer,
        switch (type) {
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
                element_name = config_element_rotation_schedule_periodic;
-               value_name = config_element_rotation_schedule_periodic_time_us;
+               value_name = config_element_rotation_schedule_periodic_time_us;
                break;
        case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
                element_name = config_element_rotation_schedule_size_threshold;
-               value_name = config_element_rotation_schedule_size_threshold_bytes;
+               value_name = config_element_rotation_schedule_size_threshold_bytes;
                break;
        default:
                ret = -1;
@@ -2553,8 +2443,7 @@ int save_session_rotation_schedule(struct config_writer *writer,
                goto end;
        }
 
-       ret = config_writer_write_element_unsigned_int(writer,
-                       value_name, value);
+       ret = config_writer_write_element_unsigned_int(writer, value_name, value);
        if (ret) {
                goto end;
        }
@@ -2568,29 +2457,26 @@ end:
        return ret;
 }
 
-static
-int save_session_rotation_schedules(struct config_writer *writer,
-       struct ltt_session *session)
+static int save_session_rotation_schedules(struct config_writer *writer,
+                                          struct ltt_session *session)
 {
        int ret;
 
-       ret = config_writer_open_element(writer,
-                       config_element_rotation_schedules);
+       ret = config_writer_open_element(writer, config_element_rotation_schedules);
        if (ret) {
                goto end;
        }
        if (session->rotate_timer_period) {
                ret = save_session_rotation_schedule(writer,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC,
-                               session->rotate_timer_period);
+                                                    LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC,
+                                                    session->rotate_timer_period);
                if (ret) {
                        goto close_schedules;
                }
        }
        if (session->rotate_size) {
-               ret = save_session_rotation_schedule(writer,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD,
-                               session->rotate_size);
+               ret = save_session_rotation_schedule(
+                       writer, LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD, session->rotate_size);
                if (ret) {
                        goto close_schedules;
                }
@@ -2611,14 +2497,14 @@ end:
  *
  * Return LTTNG_OK on success else a LTTNG_ERR* code.
  */
-static
-int save_session(struct ltt_session *session,
-       struct lttng_save_session_attr *attr, lttng_sock_cred *creds)
+static int save_session(struct ltt_session *session,
+                       struct lttng_save_session_attr *attr,
+                       lttng_sock_cred *creds)
 {
        int ret, fd = -1;
        char config_file_path[LTTNG_PATH_MAX];
        size_t len;
-       struct config_writer *writer = NULL;
+       struct config_writer *writer = nullptr;
        size_t session_name_len;
        const char *provided_path;
        int file_open_flags = O_CREAT | O_WRONLY | O_TRUNC;
@@ -2630,8 +2516,7 @@ int save_session(struct ltt_session *session,
        session_name_len = strlen(session->name);
        memset(config_file_path, 0, sizeof(config_file_path));
 
-       if (!session_access_ok(session,
-               LTTNG_SOCK_GET_UID_CRED(creds)) || session->destroyed) {
+       if (!session_access_ok(session, LTTNG_SOCK_GET_UID_CRED(creds)) || session->destroyed) {
                ret = LTTNG_ERR_EPERM;
                goto end;
        }
@@ -2647,15 +2532,16 @@ int save_session(struct ltt_session *session,
                strncpy(config_file_path, provided_path, sizeof(config_file_path));
        } else {
                ssize_t ret_len;
-               char *home_dir = utils_get_user_home_dir(
-                       LTTNG_SOCK_GET_UID_CRED(creds));
+               char *home_dir = utils_get_user_home_dir(LTTNG_SOCK_GET_UID_CRED(creds));
                if (!home_dir) {
                        ret = LTTNG_ERR_SET_URL;
                        goto end;
                }
 
-               ret_len = snprintf(config_file_path, sizeof(config_file_path),
-                               DEFAULT_SESSION_HOME_CONFIGPATH, home_dir);
+               ret_len = snprintf(config_file_path,
+                                  sizeof(config_file_path),
+                                  DEFAULT_SESSION_HOME_CONFIGPATH,
+                                  home_dir);
                free(home_dir);
                if (ret_len < 0) {
                        PERROR("snprintf save session");
@@ -2669,15 +2555,16 @@ int save_session(struct ltt_session *session,
         * Check the path fits in the config file path dst including the '/'
         * followed by trailing .lttng extension and the NULL terminated string.
         */
-       if ((len + session_name_len + 2 +
-                       sizeof(DEFAULT_SESSION_CONFIG_FILE_EXTENSION))
-                       > sizeof(config_file_path)) {
+       if ((len + session_name_len + 2 + sizeof(DEFAULT_SESSION_CONFIG_FILE_EXTENSION)) >
+           sizeof(config_file_path)) {
                ret = LTTNG_ERR_SET_URL;
                goto end;
        }
 
-       ret = run_as_mkdir_recursive(config_file_path, S_IRWXU | S_IRWXG,
-                       LTTNG_SOCK_GET_UID_CRED(creds), LTTNG_SOCK_GET_GID_CRED(creds));
+       ret = run_as_mkdir_recursive(config_file_path,
+                                    S_IRWXU | S_IRWXG,
+                                    LTTNG_SOCK_GET_UID_CRED(creds),
+                                    LTTNG_SOCK_GET_GID_CRED(creds));
        if (ret) {
                ret = LTTNG_ERR_SET_URL;
                goto end;
@@ -2698,9 +2585,11 @@ int save_session(struct ltt_session *session,
                file_open_flags |= O_EXCL;
        }
 
-       fd = run_as_open(config_file_path, file_open_flags,
-               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
-               LTTNG_SOCK_GET_UID_CRED(creds), LTTNG_SOCK_GET_GID_CRED(creds));
+       fd = run_as_open(config_file_path,
+                        file_open_flags,
+                        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
+                        LTTNG_SOCK_GET_UID_CRED(creds),
+                        LTTNG_SOCK_GET_GID_CRED(creds));
        if (fd < 0) {
                PERROR("Could not create configuration file");
                switch (errno) {
@@ -2735,17 +2624,15 @@ int save_session(struct ltt_session *session,
                goto end;
        }
 
-       ret = config_writer_write_element_string(writer, config_element_name,
-                       session->name);
+       ret = config_writer_write_element_string(writer, config_element_name, session->name);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
        if (session->shm_path[0] != '\0') {
-               ret = config_writer_write_element_string(writer,
-                               config_element_shared_memory_path,
-                               session->shm_path);
+               ret = config_writer_write_element_string(
+                       writer, config_element_shared_memory_path, session->shm_path);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
                        goto end;
@@ -2757,15 +2644,14 @@ int save_session(struct ltt_session *session,
                goto end;
        }
 
-       ret = config_writer_write_element_bool(writer, config_element_started,
-                       session->active);
+       ret = config_writer_write_element_bool(writer, config_element_started, session->active);
        if (ret) {
                ret = LTTNG_ERR_SAVE_IO_FAIL;
                goto end;
        }
 
-       if (session->snapshot_mode || session->live_timer ||
-                       session->rotate_timer_period || session->rotate_size) {
+       if (session->snapshot_mode || session->live_timer || session->rotate_timer_period ||
+           session->rotate_size) {
                ret = config_writer_open_element(writer, config_element_attributes);
                if (ret) {
                        ret = LTTNG_ERR_SAVE_IO_FAIL;
@@ -2773,23 +2659,22 @@ int save_session(struct ltt_session *session,
                }
 
                if (session->snapshot_mode) {
-                       ret = config_writer_write_element_bool(writer,
-                                       config_element_snapshot_mode, 1);
+                       ret = config_writer_write_element_bool(
+                               writer, config_element_snapshot_mode, 1);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
                        }
                } else if (session->live_timer) {
-                       ret = config_writer_write_element_unsigned_int(writer,
-                                       config_element_live_timer_interval, session->live_timer);
+                       ret = config_writer_write_element_unsigned_int(
+                               writer, config_element_live_timer_interval, session->live_timer);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
                        }
                }
                if (session->rotate_timer_period || session->rotate_size) {
-                       ret = save_session_rotation_schedules(writer,
-                                       session);
+                       ret = save_session_rotation_schedules(writer, session);
                        if (ret) {
                                ret = LTTNG_ERR_SAVE_IO_FAIL;
                                goto end;
@@ -2848,8 +2733,7 @@ end:
        return ret;
 }
 
-int cmd_save_sessions(struct lttng_save_session_attr *attr,
-       lttng_sock_cred *creds)
+int cmd_save_sessions(struct lttng_save_session_attr *attr, lttng_sock_cred *creds)
 {
        int ret;
        const char *session_name;
@@ -2875,7 +2759,7 @@ int cmd_save_sessions(struct lttng_save_session_attr *attr,
        } else {
                struct ltt_session_list *list = session_get_list();
 
-               cds_list_for_each_entry(session, &list->head, list) {
+               cds_list_for_each_entry (session, &list->head, list) {
                        if (!session_get(session)) {
                                continue;
                        }
index 367b41c17912acb4c6c9517de786591461db4ac8..ec2af8d506d8abda869821ca3408f79cd9ff4c2a 100644 (file)
@@ -8,10 +8,10 @@
 #ifndef SAVE_H
 #define SAVE_H
 
-#include <lttng/save.h>
 #include <common/compat/socket.hpp>
 
-int cmd_save_sessions(struct lttng_save_session_attr *attr,
-       lttng_sock_cred *creds);
+#include <lttng/save.h>
+
+int cmd_save_sessions(struct lttng_save_session_attr *attr, lttng_sock_cred *creds);
 
 #endif /* SAVE_H */
index e9d7261031d632fc44e4f820621a8e471a3e9e74..0ad891e3252e4e294aaf23026abac9a394080117 100644 (file)
@@ -6,6 +6,22 @@
  */
 
 #define _LGPL_SOURCE
+#include "cmd.hpp"
+#include "kernel.hpp"
+#include "lttng-sessiond.hpp"
+#include "session.hpp"
+#include "timer.hpp"
+#include "trace-ust.hpp"
+#include "utils.hpp"
+
+#include <common/common.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/trace-chunk.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/location-internal.hpp>
+
 #include <dirent.h>
 #include <inttypes.h>
 #include <limits.h>
 #include <sys/types.h>
 #include <urcu.h>
 
-#include <common/common.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/trace-chunk.hpp>
-#include <common/urcu.hpp>
-#include <common/utils.hpp>
-
-#include "lttng-sessiond.hpp"
-#include <lttng/location-internal.hpp>
-
-#include "cmd.hpp"
-#include "kernel.hpp"
-#include "session.hpp"
-#include "timer.hpp"
-#include "trace-ust.hpp"
-#include "utils.hpp"
-
 namespace {
 struct ltt_session_destroy_notifier_element {
        ltt_session_destroy_notifier notifier;
@@ -59,9 +59,9 @@ namespace ls = lttng::sessiond;
 const char *forbidden_name_chars = "/";
 
 /* Global hash table to keep the sessions, indexed by id. */
-struct lttng_ht *ltt_sessions_ht_by_id = NULL;
+struct lttng_ht *ltt_sessions_ht_by_id = nullptr;
 /* Global hash table to keep the sessions, indexed by name. */
-struct lttng_ht *ltt_sessions_ht_by_name = NULL;
+struct lttng_ht *ltt_sessions_ht_by_name = nullptr;
 
 /*
  * Init tracing session list.
@@ -138,7 +138,7 @@ static void del_session_list(struct ltt_session *ls)
 /*
  * Return a pointer to the session list.
  */
-struct ltt_session_list *session_get_list(void)
+struct ltt_session_list *session_get_list()
 {
        return &the_session_list;
 }
@@ -146,12 +146,11 @@ struct ltt_session_list *session_get_list(void)
 /*
  * Returns once the session list is empty.
  */
-void session_list_wait_empty(void)
+void session_list_wait_empty()
 {
        pthread_mutex_lock(&the_session_list.lock);
        while (!cds_list_empty(&the_session_list.head)) {
-               pthread_cond_wait(&the_session_list.removal_cond,
-                               &the_session_list.lock);
+               pthread_cond_wait(&the_session_list.removal_cond, &the_session_list.lock);
        }
        pthread_mutex_unlock(&the_session_list.lock);
 }
@@ -159,7 +158,7 @@ void session_list_wait_empty(void)
 /*
  * Acquire session list lock
  */
-void session_lock_list(void)
+void session_lock_list() noexcept
 {
        pthread_mutex_lock(&the_session_list.lock);
 }
@@ -167,7 +166,7 @@ void session_lock_list(void)
 /*
  * Try to acquire session list lock
  */
-int session_trylock_list(void)
+int session_trylock_list() noexcept
 {
        return pthread_mutex_trylock(&the_session_list.lock);
 }
@@ -175,7 +174,7 @@ int session_trylock_list(void)
 /*
  * Release session list lock
  */
-void session_unlock_list(void)
+void session_unlock_list() noexcept
 {
        pthread_mutex_unlock(&the_session_list.lock);
 }
@@ -185,17 +184,15 @@ void session_unlock_list(void)
  *
  * The caller must hold the session lock.
  */
-enum consumer_dst_type session_get_consumer_destination_type(
-               const struct ltt_session *session)
+enum consumer_dst_type session_get_consumer_destination_type(const struct ltt_session *session)
 {
        /*
         * The output information is duplicated in both of those session types.
         * Hence, it doesn't matter from which it is retrieved. However, it is
         * possible for only one of them to be set.
         */
-       return session->kernel_session ?
-                       session->kernel_session->consumer->type :
-                       session->ust_session->consumer->type;
+       return session->kernel_session ? session->kernel_session->consumer->type :
+                                        session->ust_session->consumer->type;
 }
 
 /*
@@ -206,12 +203,11 @@ enum consumer_dst_type session_get_consumer_destination_type(
  */
 const char *session_get_net_consumer_hostname(const struct ltt_session *session)
 {
-       const char *hostname = NULL;
+       const char *hostname = nullptr;
        const struct consumer_output *output;
 
-       output = session->kernel_session ?
-                       session->kernel_session->consumer :
-                       session->ust_session->consumer;
+       output = session->kernel_session ? session->kernel_session->consumer :
+                                          session->ust_session->consumer;
 
        /*
         * hostname is assumed to be the same for both control and data
@@ -237,13 +233,13 @@ const char *session_get_net_consumer_hostname(const struct ltt_session *session)
  * The caller must hold the session lock.
  */
 void session_get_net_consumer_ports(const struct ltt_session *session,
-               uint16_t *control_port, uint16_t *data_port)
+                                   uint16_t *control_port,
+                                   uint16_t *data_port)
 {
        const struct consumer_output *output;
 
-       output = session->kernel_session ?
-                       session->kernel_session->consumer :
-                       session->ust_session->consumer;
+       output = session->kernel_session ? session->kernel_session->consumer :
+                                          session->ust_session->consumer;
        *control_port = output->dst.net.control.port;
        *data_port = output->dst.net.data.port;
 }
@@ -253,29 +249,28 @@ void session_get_net_consumer_ports(const struct ltt_session *session,
  *
  * The caller must hold the session lock.
  */
-struct lttng_trace_archive_location *session_get_trace_archive_location(
-               const struct ltt_session *session)
+struct lttng_trace_archive_location *
+session_get_trace_archive_location(const struct ltt_session *session)
 {
        int ret;
-       struct lttng_trace_archive_location *location = NULL;
-       char *chunk_path = NULL;
+       struct lttng_trace_archive_location *location = nullptr;
+       char *chunk_path = nullptr;
 
        if (session->rotation_state != LTTNG_ROTATION_STATE_COMPLETED ||
-                       !session->last_archived_chunk_name) {
+           !session->last_archived_chunk_name) {
                goto end;
        }
 
        switch (session_get_consumer_destination_type(session)) {
        case CONSUMER_DST_LOCAL:
                ret = asprintf(&chunk_path,
-                               "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
-                               session_get_base_path(session),
-                               session->last_archived_chunk_name);
+                              "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "/%s",
+                              session_get_base_path(session),
+                              session->last_archived_chunk_name);
                if (ret == -1) {
                        goto end;
                }
-               location = lttng_trace_archive_location_local_create(
-                               chunk_path);
+               location = lttng_trace_archive_location_local_create(chunk_path);
                break;
        case CONSUMER_DST_NET:
        {
@@ -283,13 +278,13 @@ struct lttng_trace_archive_location *session_get_trace_archive_location(
                uint16_t control_port, data_port;
 
                hostname = session_get_net_consumer_hostname(session);
-               session_get_net_consumer_ports(session,
-                               &control_port,
-                               &data_port);
+               session_get_net_consumer_ports(session, &control_port, &data_port);
                location = lttng_trace_archive_location_relay_create(
-                               hostname,
-                               LTTNG_TRACE_ARCHIVE_LOCATION_RELAY_PROTOCOL_TYPE_TCP,
-                               control_port, data_port, session->last_chunk_path);
+                       hostname,
+                       LTTNG_TRACE_ARCHIVE_LOCATION_RELAY_PROTOCOL_TYPE_TCP,
+                       control_port,
+                       data_port,
+                       session->last_chunk_path);
                break;
        }
        default:
@@ -305,7 +300,7 @@ end:
  *
  * The session list lock must be held.
  */
-static int ltt_sessions_ht_alloc(void)
+static int ltt_sessions_ht_alloc()
 {
        int ret = 0;
 
@@ -334,16 +329,16 @@ end:
  *
  * The session list lock must be held.
  */
-static void ltt_sessions_ht_destroy(void)
+static void ltt_sessions_ht_destroy()
 {
        if (ltt_sessions_ht_by_id) {
                lttng_ht_destroy(ltt_sessions_ht_by_id);
-               ltt_sessions_ht_by_id = NULL;
+               ltt_sessions_ht_by_id = nullptr;
        }
 
        if (ltt_sessions_ht_by_name) {
                lttng_ht_destroy(ltt_sessions_ht_by_name);
-               ltt_sessions_ht_by_name = NULL;
+               ltt_sessions_ht_by_name = nullptr;
        }
 
        return;
@@ -386,7 +381,7 @@ end:
  * Return `false` if hash table objects are null.
  * The session list lock must be held.
  */
-static bool ltt_sessions_ht_empty(void)
+static bool ltt_sessions_ht_empty()
 {
        bool empty = false;
 
@@ -468,10 +463,9 @@ void session_unlock(struct ltt_session *session)
        pthread_mutex_unlock(&session->lock);
 }
 
-static
-int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
-               struct lttng_trace_chunk *new_trace_chunk,
-               struct lttng_trace_chunk **_current_trace_chunk)
+static int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
+                                                 struct lttng_trace_chunk *new_trace_chunk,
+                                                 struct lttng_trace_chunk **_current_trace_chunk)
 {
        int ret = 0;
        unsigned int i, refs_to_acquire = 0, refs_acquired = 0, refs_to_release = 0;
@@ -481,22 +475,20 @@ int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
        uint64_t chunk_id;
        enum lttng_trace_chunk_status chunk_status;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        /*
         * Ownership of current trace chunk is transferred to
         * `current_trace_chunk`.
         */
        current_trace_chunk = session->current_trace_chunk;
-       session->current_trace_chunk = NULL;
+       session->current_trace_chunk = nullptr;
        if (session->ust_session) {
-               lttng_trace_chunk_put(
-                               session->ust_session->current_trace_chunk);
-               session->ust_session->current_trace_chunk = NULL;
+               lttng_trace_chunk_put(session->ust_session->current_trace_chunk);
+               session->ust_session->current_trace_chunk = nullptr;
        }
        if (session->kernel_session) {
-               lttng_trace_chunk_put(
-                               session->kernel_session->current_trace_chunk);
-               session->kernel_session->current_trace_chunk = NULL;
+               lttng_trace_chunk_put(session->kernel_session->current_trace_chunk);
+               session->kernel_session->current_trace_chunk = nullptr;
        }
        if (!new_trace_chunk) {
                ret = 0;
@@ -509,40 +501,37 @@ int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
        refs_to_acquire += !!session->ust_session;
        refs_to_acquire += !!session->kernel_session;
 
-       for (refs_acquired = 0; refs_acquired < refs_to_acquire;
-                       refs_acquired++) {
+       for (refs_acquired = 0; refs_acquired < refs_to_acquire; refs_acquired++) {
                if (!lttng_trace_chunk_get(new_trace_chunk)) {
                        ERR("Failed to acquire reference to new trace chunk of session \"%s\"",
-                                       session->name);
+                           session->name);
                        goto error;
                }
        }
 
        if (session->ust_session) {
-               const uint64_t relayd_id =
-                               session->ust_session->consumer->net_seq_index;
-               const bool is_local_trace =
-                               session->ust_session->consumer->type ==
-                               CONSUMER_DST_LOCAL;
+               const uint64_t relayd_id = session->ust_session->consumer->net_seq_index;
+               const bool is_local_trace = session->ust_session->consumer->type ==
+                       CONSUMER_DST_LOCAL;
 
                session->ust_session->current_trace_chunk = new_trace_chunk;
                if (is_local_trace) {
                        enum lttng_error_code ret_error_code;
 
-                       ret_error_code = ust_app_create_channel_subdirectories(
-                                       session->ust_session);
+                       ret_error_code =
+                               ust_app_create_channel_subdirectories(session->ust_session);
                        if (ret_error_code != LTTNG_OK) {
                                goto error;
                        }
                }
-               cds_lfht_for_each_entry(
-                               session->ust_session->consumer->socks->ht,
-                               &iter, socket, node.node) {
+               cds_lfht_for_each_entry (
+                       session->ust_session->consumer->socks->ht, &iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
                        ret = consumer_create_trace_chunk(socket,
-                                       relayd_id,
-                                       session->id, new_trace_chunk,
-                                       DEFAULT_UST_TRACE_DIR);
+                                                         relayd_id,
+                                                         session->id,
+                                                         new_trace_chunk,
+                                                         DEFAULT_UST_TRACE_DIR);
                        pthread_mutex_unlock(socket->lock);
                        if (ret) {
                                goto error;
@@ -550,30 +539,28 @@ int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
                }
        }
        if (session->kernel_session) {
-               const uint64_t relayd_id =
-                               session->kernel_session->consumer->net_seq_index;
-               const bool is_local_trace =
-                               session->kernel_session->consumer->type ==
-                               CONSUMER_DST_LOCAL;
+               const uint64_t relayd_id = session->kernel_session->consumer->net_seq_index;
+               const bool is_local_trace = session->kernel_session->consumer->type ==
+                       CONSUMER_DST_LOCAL;
 
                session->kernel_session->current_trace_chunk = new_trace_chunk;
                if (is_local_trace) {
                        enum lttng_error_code ret_error_code;
 
-                       ret_error_code = kernel_create_channel_subdirectories(
-                                       session->kernel_session);
+                       ret_error_code =
+                               kernel_create_channel_subdirectories(session->kernel_session);
                        if (ret_error_code != LTTNG_OK) {
                                goto error;
                        }
                }
-               cds_lfht_for_each_entry(
-                               session->kernel_session->consumer->socks->ht,
-                               &iter, socket, node.node) {
+               cds_lfht_for_each_entry (
+                       session->kernel_session->consumer->socks->ht, &iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
                        ret = consumer_create_trace_chunk(socket,
-                                       relayd_id,
-                                       session->id, new_trace_chunk,
-                                       DEFAULT_KERNEL_TRACE_DIR);
+                                                         relayd_id,
+                                                         session->id,
+                                                         new_trace_chunk,
+                                                         DEFAULT_KERNEL_TRACE_DIR);
                        pthread_mutex_unlock(socket->lock);
                        if (ret) {
                                goto error;
@@ -590,18 +577,17 @@ int _session_set_trace_chunk_no_lock_check(struct ltt_session *session,
 end:
        if (_current_trace_chunk) {
                *_current_trace_chunk = current_trace_chunk;
-               current_trace_chunk = NULL;
+               current_trace_chunk = nullptr;
        }
 end_no_move:
-       rcu_read_unlock();
        lttng_trace_chunk_put(current_trace_chunk);
        return ret;
 error:
        if (session->ust_session) {
-               session->ust_session->current_trace_chunk = NULL;
+               session->ust_session->current_trace_chunk = nullptr;
        }
        if (session->kernel_session) {
-               session->kernel_session->current_trace_chunk = NULL;
+               session->kernel_session->current_trace_chunk = nullptr;
        }
        /*
         * Release references taken in the case where all references could not
@@ -615,19 +601,19 @@ error:
        goto end_no_move;
 }
 
-struct lttng_trace_chunk *session_create_new_trace_chunk(
-               const struct ltt_session *session,
-               const struct consumer_output *consumer_output_override,
-               const char *session_base_path_override,
-               const char *chunk_name_override)
+struct lttng_trace_chunk *
+session_create_new_trace_chunk(const struct ltt_session *session,
+                              const struct consumer_output *consumer_output_override,
+                              const char *session_base_path_override,
+                              const char *chunk_name_override)
 {
        int ret;
-       struct lttng_trace_chunk *trace_chunk = NULL;
+       struct lttng_trace_chunk *trace_chunk = nullptr;
        enum lttng_trace_chunk_status chunk_status;
-       const time_t chunk_creation_ts = time(NULL);
+       const time_t chunk_creation_ts = time(nullptr);
        bool is_local_trace;
        const char *base_path;
-       struct lttng_directory_handle *session_output_directory = NULL;
+       struct lttng_directory_handle *session_output_directory = nullptr;
        const struct lttng_credentials session_credentials = {
                .uid = LTTNG_OPTIONAL_INIT_VALUE(session->uid),
                .gid = LTTNG_OPTIONAL_INIT_VALUE(session->gid),
@@ -640,28 +626,26 @@ struct lttng_trace_chunk *session_create_new_trace_chunk(
                output = consumer_output_override;
        } else {
                LTTNG_ASSERT(session->ust_session || session->kernel_session);
-               output = session->ust_session ?
-                                        session->ust_session->consumer :
-                                        session->kernel_session->consumer;
+               output = session->ust_session ? session->ust_session->consumer :
+                                               session->kernel_session->consumer;
        }
 
        is_local_trace = output->type == CONSUMER_DST_LOCAL;
-       base_path = session_base_path_override ? :
-                       consumer_output_get_base_path(output);
+       base_path = session_base_path_override ?: consumer_output_get_base_path(output);
 
        if (chunk_creation_ts == (time_t) -1) {
                PERROR("Failed to sample time while creation session \"%s\" trace chunk",
-                               session->name);
+                      session->name);
                goto error;
        }
 
-       next_chunk_id = session->most_recent_chunk_id.is_set ?
-                       session->most_recent_chunk_id.value + 1 : 0;
+       next_chunk_id =
+               session->most_recent_chunk_id.is_set ? session->most_recent_chunk_id.value + 1 : 0;
 
        if (session->current_trace_chunk &&
-                       !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
+           !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
                chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
-                                       DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
+                                                            DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        goto error;
                }
@@ -670,21 +654,19 @@ struct lttng_trace_chunk *session_create_new_trace_chunk(
                if (!session->rotated) {
                        new_path = "";
                } else {
-                       new_path = NULL;
+                       new_path = nullptr;
                }
        } else {
                new_path = DEFAULT_CHUNK_TMP_NEW_DIRECTORY;
        }
 
-       trace_chunk = lttng_trace_chunk_create(next_chunk_id,
-                       chunk_creation_ts, new_path);
+       trace_chunk = lttng_trace_chunk_create(next_chunk_id, chunk_creation_ts, new_path);
        if (!trace_chunk) {
                goto error;
        }
 
        if (chunk_name_override) {
-               chunk_status = lttng_trace_chunk_override_name(trace_chunk,
-                               chunk_name_override);
+               chunk_status = lttng_trace_chunk_override_name(trace_chunk, chunk_name_override);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        goto error;
                }
@@ -698,16 +680,13 @@ struct lttng_trace_chunk *session_create_new_trace_chunk(
                goto end;
        }
 
-       chunk_status = lttng_trace_chunk_set_credentials(trace_chunk,
-                       &session_credentials);
+       chunk_status = lttng_trace_chunk_set_credentials(trace_chunk, &session_credentials);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                goto error;
        }
 
-       DBG("Creating base output directory of session \"%s\" at %s",
-                       session->name, base_path);
-       ret = utils_mkdir_recursive(base_path, S_IRWXU | S_IRWXG,
-                       session->uid, session->gid);
+       DBG("Creating base output directory of session \"%s\" at %s", session->name, base_path);
+       ret = utils_mkdir_recursive(base_path, S_IRWXU | S_IRWXG, session->uid, session->gid);
        if (ret) {
                goto error;
        }
@@ -715,10 +694,9 @@ struct lttng_trace_chunk *session_create_new_trace_chunk(
        if (!session_output_directory) {
                goto error;
        }
-       chunk_status = lttng_trace_chunk_set_as_owner(trace_chunk,
-                       session_output_directory);
+       chunk_status = lttng_trace_chunk_set_as_owner(trace_chunk, session_output_directory);
        lttng_directory_handle_put(session_output_directory);
-       session_output_directory = NULL;
+       session_output_directory = nullptr;
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                goto error;
        }
@@ -727,25 +705,24 @@ end:
 error:
        lttng_directory_handle_put(session_output_directory);
        lttng_trace_chunk_put(trace_chunk);
-       trace_chunk = NULL;
+       trace_chunk = nullptr;
        goto end;
 }
 
 int session_close_trace_chunk(struct ltt_session *session,
-               struct lttng_trace_chunk *trace_chunk,
-               enum lttng_trace_chunk_command_type close_command,
-               char *closed_trace_chunk_path)
+                             struct lttng_trace_chunk *trace_chunk,
+                             enum lttng_trace_chunk_command_type close_command,
+                             char *closed_trace_chunk_path)
 {
        int ret = 0;
        bool error_occurred = false;
        struct cds_lfht_iter iter;
        struct consumer_socket *socket;
        enum lttng_trace_chunk_status chunk_status;
-       const time_t chunk_close_timestamp = time(NULL);
+       const time_t chunk_close_timestamp = time(nullptr);
        const char *new_path;
 
-       chunk_status = lttng_trace_chunk_set_close_command(
-                       trace_chunk, close_command);
+       chunk_status = lttng_trace_chunk_set_close_command(trace_chunk, close_command);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end;
@@ -753,7 +730,7 @@ int session_close_trace_chunk(struct ltt_session *session,
 
        if (chunk_close_timestamp == (time_t) -1) {
                ERR("Failed to sample the close timestamp of the current trace chunk of session \"%s\"",
-                               session->name);
+                   session->name);
                ret = -1;
                goto end;
        }
@@ -763,30 +740,29 @@ int session_close_trace_chunk(struct ltt_session *session,
                new_path = "";
        } else {
                /* Use chunk name for new chunk. */
-               new_path = NULL;
+               new_path = nullptr;
        }
        if (session->current_trace_chunk &&
-                       !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
+           !lttng_trace_chunk_get_name_overridden(session->current_trace_chunk)) {
                /* Rename new chunk path. */
-               chunk_status = lttng_trace_chunk_rename_path(session->current_trace_chunk,
-                                       new_path);
+               chunk_status =
+                       lttng_trace_chunk_rename_path(session->current_trace_chunk, new_path);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
        }
        if (!lttng_trace_chunk_get_name_overridden(trace_chunk) &&
-                       close_command == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) {
+           close_command == LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION) {
                const char *old_path;
 
                if (!session->rotated) {
                        old_path = "";
                } else {
-                       old_path = NULL;
+                       old_path = nullptr;
                }
                /* We need to move back the .tmp_old_chunk to its rightful place. */
-               chunk_status = lttng_trace_chunk_rename_path(trace_chunk,
-                                       old_path);
+               chunk_status = lttng_trace_chunk_rename_path(trace_chunk, old_path);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        goto end;
@@ -795,27 +771,25 @@ int session_close_trace_chunk(struct ltt_session *session,
        if (close_command == LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED) {
                session->rotated = true;
        }
-       chunk_status = lttng_trace_chunk_set_close_timestamp(trace_chunk,
-                       chunk_close_timestamp);
+       chunk_status = lttng_trace_chunk_set_close_timestamp(trace_chunk, chunk_close_timestamp);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ERR("Failed to set the close timestamp of the current trace chunk of session \"%s\"",
-                               session->name);
+                   session->name);
                ret = -1;
                goto end;
        }
 
        if (session->ust_session) {
-               const uint64_t relayd_id =
-                               session->ust_session->consumer->net_seq_index;
+               const uint64_t relayd_id = session->ust_session->consumer->net_seq_index;
 
-               cds_lfht_for_each_entry(
-                               session->ust_session->consumer->socks->ht,
-                               &iter, socket, node.node) {
+               cds_lfht_for_each_entry (
+                       session->ust_session->consumer->socks->ht, &iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
                        ret = consumer_close_trace_chunk(socket,
-                                       relayd_id,
-                                       session->id,
-                                       trace_chunk, closed_trace_chunk_path);
+                                                        relayd_id,
+                                                        session->id,
+                                                        trace_chunk,
+                                                        closed_trace_chunk_path);
                        pthread_mutex_unlock(socket->lock);
                        if (ret) {
                                ERR("Failed to close trace chunk on user space consumer");
@@ -824,17 +798,16 @@ int session_close_trace_chunk(struct ltt_session *session,
                }
        }
        if (session->kernel_session) {
-               const uint64_t relayd_id =
-                               session->kernel_session->consumer->net_seq_index;
+               const uint64_t relayd_id = session->kernel_session->consumer->net_seq_index;
 
-               cds_lfht_for_each_entry(
-                               session->kernel_session->consumer->socks->ht,
-                               &iter, socket, node.node) {
+               cds_lfht_for_each_entry (
+                       session->kernel_session->consumer->socks->ht, &iter, socket, node.node) {
                        pthread_mutex_lock(socket->lock);
                        ret = consumer_close_trace_chunk(socket,
-                                       relayd_id,
-                                       session->id,
-                                       trace_chunk, closed_trace_chunk_path);
+                                                        relayd_id,
+                                                        session->id,
+                                                        trace_chunk,
+                                                        closed_trace_chunk_path);
                        pthread_mutex_unlock(socket->lock);
                        if (ret) {
                                ERR("Failed to close trace chunk on kernel consumer");
@@ -863,8 +836,7 @@ end:
  * daemon as the same "offset" in a metadata stream will no longer point
  * to the same content.
  */
-static
-enum lttng_error_code session_kernel_open_packets(struct ltt_session *session)
+static enum lttng_error_code session_kernel_open_packets(struct ltt_session *session)
 {
        enum lttng_error_code ret = LTTNG_OK;
        struct consumer_socket *socket;
@@ -872,19 +844,20 @@ enum lttng_error_code session_kernel_open_packets(struct ltt_session *session)
        struct cds_lfht_node *node;
        struct ltt_kernel_channel *chan;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        cds_lfht_first(session->kernel_session->consumer->socks->ht, &iter.iter);
        node = cds_lfht_iter_get_node(&iter.iter);
        socket = caa_container_of(node, typeof(*socket), node.node);
 
-       cds_list_for_each_entry(chan,
-                       &session->kernel_session->channel_list.head, list) {
+       cds_list_for_each_entry (chan, &session->kernel_session->channel_list.head, list) {
                int open_ret;
 
                DBG("Open packet of kernel channel: channel key = %" PRIu64
-                               ", session name = %s, session_id = %" PRIu64,
-                               chan->key, session->name, session->id);
+                   ", session name = %s, session_id = %" PRIu64,
+                   chan->key,
+                   session->name,
+                   session->id);
 
                open_ret = consumer_open_channel_packets(socket, chan->key);
                if (open_ret < 0) {
@@ -895,7 +868,6 @@ enum lttng_error_code session_kernel_open_packets(struct ltt_session *session)
        }
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -904,7 +876,8 @@ enum lttng_error_code session_open_packets(struct ltt_session *session)
        enum lttng_error_code ret = LTTNG_OK;
 
        DBG("Opening packets of session channels: session name = %s, session id = %" PRIu64,
-                       session->name, session->id);
+           session->name,
+           session->id);
 
        if (session->ust_session) {
                ret = ust_app_open_packets(session);
@@ -930,25 +903,23 @@ end:
  * Must be called with the session lock held.
  */
 int session_set_trace_chunk(struct ltt_session *session,
-               struct lttng_trace_chunk *new_trace_chunk,
-               struct lttng_trace_chunk **current_trace_chunk)
+                           struct lttng_trace_chunk *new_trace_chunk,
+                           struct lttng_trace_chunk **current_trace_chunk)
 {
        ASSERT_LOCKED(session->lock);
-       return _session_set_trace_chunk_no_lock_check(session, new_trace_chunk,
-                       current_trace_chunk);
+       return _session_set_trace_chunk_no_lock_check(
+               session, new_trace_chunk, current_trace_chunk);
 }
 
-static
-void session_notify_destruction(const struct ltt_session *session)
+static void session_notify_destruction(const struct ltt_session *session)
 {
        size_t i;
-       const size_t count = lttng_dynamic_array_get_count(
-                       &session->destroy_notifiers);
+       const size_t count = lttng_dynamic_array_get_count(&session->destroy_notifiers);
 
        for (i = 0; i < count; i++) {
                const struct ltt_session_destroy_notifier_element *element =
                        (ltt_session_destroy_notifier_element *) lttng_dynamic_array_get_element(
-                                       &session->destroy_notifiers, i);
+                               &session->destroy_notifiers, i);
 
                element->notifier(session, element->user_data);
        }
@@ -957,24 +928,22 @@ void session_notify_destruction(const struct ltt_session *session)
 /*
  * Fire each clear notifier once, and remove them from the array.
  */
-void session_notify_clear(struct ltt_session *session)
+void session_notify_clear(ltt_session& session)
 {
        size_t i;
-       const size_t count = lttng_dynamic_array_get_count(
-                       &session->clear_notifiers);
+       const size_t count = lttng_dynamic_array_get_count(&session.clear_notifiers);
 
        for (i = 0; i < count; i++) {
                const struct ltt_session_clear_notifier_element *element =
                        (ltt_session_clear_notifier_element *) lttng_dynamic_array_get_element(
-                                       &session->clear_notifiers, i);
+                               &session.clear_notifiers, i);
 
-               element->notifier(session, element->user_data);
+               element->notifier(&session, element->user_data);
        }
-       lttng_dynamic_array_clear(&session->clear_notifiers);
+       lttng_dynamic_array_clear(&session.clear_notifiers);
 }
 
-static
-void session_release(struct urcu_ref *ref)
+static void session_release(struct urcu_ref *ref)
 {
        int ret;
        struct ltt_ust_session *usess;
@@ -1029,10 +998,10 @@ void session_release(struct urcu_ref *ref)
 
        consumer_output_put(session->consumer);
        kernel_free_session(ksess);
-       session->kernel_session = NULL;
+       session->kernel_session = nullptr;
        if (usess) {
                trace_ust_free_session(usess);
-               session->ust_session = NULL;
+               session->ust_session = nullptr;
        }
        lttng_dynamic_array_reset(&session->destroy_notifiers);
        lttng_dynamic_array_reset(&session->clear_notifiers);
@@ -1110,27 +1079,23 @@ void session_destroy(struct ltt_session *session)
 }
 
 int session_add_destroy_notifier(struct ltt_session *session,
-               ltt_session_destroy_notifier notifier, void *user_data)
+                                ltt_session_destroy_notifier notifier,
+                                void *user_data)
 {
-       const struct ltt_session_destroy_notifier_element element = {
-               .notifier = notifier,
-               .user_data = user_data
-       };
+       const struct ltt_session_destroy_notifier_element element = { .notifier = notifier,
+                                                                     .user_data = user_data };
 
-       return lttng_dynamic_array_add_element(&session->destroy_notifiers,
-                       &element);
+       return lttng_dynamic_array_add_element(&session->destroy_notifiers, &element);
 }
 
 int session_add_clear_notifier(struct ltt_session *session,
-               ltt_session_clear_notifier notifier, void *user_data)
+                              ltt_session_clear_notifier notifier,
+                              void *user_data)
 {
-       const struct ltt_session_clear_notifier_element element = {
-               .notifier = notifier,
-               .user_data = user_data
-       };
+       const struct ltt_session_clear_notifier_element element = { .notifier = notifier,
+                                                                   .user_data = user_data };
 
-       return lttng_dynamic_array_add_element(&session->clear_notifiers,
-                       &element);
+       return lttng_dynamic_array_add_element(&session->clear_notifiers, &element);
 }
 
 /*
@@ -1148,16 +1113,15 @@ struct ltt_session *session_find_by_name(const char *name)
 
        DBG2("Trying to find session by name %s", name);
 
-       cds_list_for_each_entry(iter, &the_session_list.head, list) {
-               if (!strncmp(iter->name, name, NAME_MAX) &&
-                               !iter->destroyed) {
+       cds_list_for_each_entry (iter, &the_session_list.head, list) {
+               if (!strncmp(iter->name, name, NAME_MAX) && !iter->destroyed) {
                        goto found;
                }
        }
 
-       return NULL;
+       return nullptr;
 found:
-       return session_get(iter) ? iter : NULL;
+       return session_get(iter) ? iter : nullptr;
 }
 
 /*
@@ -1180,29 +1144,29 @@ struct ltt_session *session_find_by_id(uint64_t id)
 
        lttng_ht_lookup(ltt_sessions_ht_by_id, &id, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto end;
        }
        ls = lttng::utils::container_of(node, &ltt_session::node);
 
        DBG3("Session %" PRIu64 " found by id.", id);
-       return session_get(ls) ? ls : NULL;
+       return session_get(ls) ? ls : nullptr;
 
 end:
        DBG3("Session %" PRIu64 " NOT found by id", id);
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Create a new session and add it to the session list.
  * Session list lock must be held by the caller.
  */
-enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
-               struct ltt_session **out_session)
+enum lttng_error_code
+session_create(const char *name, uid_t uid, gid_t gid, struct ltt_session **out_session)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct ltt_session *new_session = NULL;
+       struct ltt_session *new_session = nullptr;
 
        ASSERT_LOCKED(the_session_list.lock);
        if (name) {
@@ -1223,15 +1187,15 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
        }
 
        lttng_dynamic_array_init(&new_session->destroy_notifiers,
-                       sizeof(struct ltt_session_destroy_notifier_element),
-                       NULL);
+                                sizeof(struct ltt_session_destroy_notifier_element),
+                                nullptr);
        lttng_dynamic_array_init(&new_session->clear_notifiers,
-                       sizeof(struct ltt_session_clear_notifier_element),
-                       NULL);
+                                sizeof(struct ltt_session_clear_notifier_element),
+                                nullptr);
        urcu_ref_init(&new_session->ref);
-       pthread_mutex_init(&new_session->lock, NULL);
+       pthread_mutex_init(&new_session->lock, nullptr);
 
-       new_session->creation_time = time(NULL);
+       new_session->creation_time = time(nullptr);
        if (new_session->creation_time == (time_t) -1) {
                PERROR("Failed to sample session creation time");
                ret_code = LTTNG_ERR_SESSION_FAIL;
@@ -1240,7 +1204,7 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
 
        /* Create default consumer output. */
        new_session->consumer = consumer_create_output(CONSUMER_DST_LOCAL);
-       if (new_session->consumer == NULL) {
+       if (new_session->consumer == nullptr) {
                ret_code = LTTNG_ERR_NOMEM;
                goto error;
        }
@@ -1273,16 +1237,17 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
 
                        if (i == 0) {
                                ret = snprintf(new_session->name,
-                                               sizeof(new_session->name),
-                                               "%s-%s",
-                                               DEFAULT_SESSION_NAME,
-                                               datetime);
+                                              sizeof(new_session->name),
+                                              "%s-%s",
+                                              DEFAULT_SESSION_NAME,
+                                              datetime);
                        } else {
                                ret = snprintf(new_session->name,
-                                               sizeof(new_session->name),
-                                               "%s%d-%s",
-                                               DEFAULT_SESSION_NAME, i,
-                                               datetime);
+                                              sizeof(new_session->name),
+                                              "%s%d-%s",
+                                              DEFAULT_SESSION_NAME,
+                                              i,
+                                              datetime);
                        }
                        new_session->name_contains_creation_time = true;
                        if (ret == -1 || ret >= sizeof(new_session->name)) {
@@ -1295,8 +1260,7 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
                                goto error;
                        }
 
-                       clashing_session =
-                                       session_find_by_name(new_session->name);
+                       clashing_session = session_find_by_name(new_session->name);
                        session_put(clashing_session);
                        if (!clashing_session) {
                                found_name = true;
@@ -1318,7 +1282,7 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
                if (errno == ENAMETOOLONG) {
                        new_session->hostname[sizeof(new_session->hostname) - 1] = '\0';
                        ERR("Hostname exceeds the maximal permitted length and has been truncated to %s",
-                                       new_session->hostname);
+                           new_session->hostname);
                } else {
                        ret_code = LTTNG_ERR_SESSION_FAIL;
                        goto error;
@@ -1353,8 +1317,10 @@ enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
         * set it up and, if valid, assign it to the session.
         */
        DBG("Tracing session %s created with ID %" PRIu64 " by uid = %d, gid = %d",
-                       new_session->name, new_session->id, new_session->uid,
-                       new_session->gid);
+           new_session->name,
+           new_session->id,
+           new_session->uid,
+           new_session->gid);
        ret_code = LTTNG_OK;
 end:
        if (new_session) {
@@ -1364,7 +1330,7 @@ end:
        return ret_code;
 error:
        session_put(new_session);
-       new_session = NULL;
+       new_session = nullptr;
        goto end;
 }
 
@@ -1393,30 +1359,26 @@ bool session_access_ok(struct ltt_session *session, uid_t uid)
  *
  * Must be called with the session and session_list locks held.
  */
-int session_reset_rotation_state(struct ltt_session *session,
-               enum lttng_rotation_state result)
+int session_reset_rotation_state(ltt_session& session, enum lttng_rotation_state result)
 {
        int ret = 0;
 
        ASSERT_LOCKED(the_session_list.lock);
-       ASSERT_LOCKED(session->lock);
+       ASSERT_LOCKED(session.lock);
 
-       session->rotation_state = result;
-       if (session->rotation_pending_check_timer_enabled) {
+       session.rotation_state = result;
+       if (session.rotation_pending_check_timer_enabled) {
                ret = timer_session_rotation_pending_check_stop(session);
        }
-       if (session->chunk_being_archived) {
+       if (session.chunk_being_archived) {
                uint64_t chunk_id;
                enum lttng_trace_chunk_status chunk_status;
 
-               chunk_status = lttng_trace_chunk_get_id(
-                               session->chunk_being_archived,
-                               &chunk_id);
+               chunk_status = lttng_trace_chunk_get_id(session.chunk_being_archived, &chunk_id);
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
-               LTTNG_OPTIONAL_SET(&session->last_archived_chunk_id,
-                               chunk_id);
-               lttng_trace_chunk_put(session->chunk_being_archived);
-               session->chunk_being_archived = NULL;
+               LTTNG_OPTIONAL_SET(&session.last_archived_chunk_id, chunk_id);
+               lttng_trace_chunk_put(session.chunk_being_archived);
+               session.chunk_being_archived = nullptr;
                /*
                 * Fire the clear reply notifiers if we are completing a clear
                 * rotation.
@@ -1442,7 +1404,7 @@ bool sample_session_id_by_name(const char *name, uint64_t *id)
        struct lttng_ht_iter iter;
        struct ltt_session *ls;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!ltt_sessions_ht_by_name) {
                found = false;
@@ -1451,7 +1413,7 @@ bool sample_session_id_by_name(const char *name, uint64_t *id)
 
        lttng_ht_lookup(ltt_sessions_ht_by_name, name, &iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                found = false;
                goto end;
        }
@@ -1462,12 +1424,15 @@ bool sample_session_id_by_name(const char *name, uint64_t *id)
 
        DBG3("Session id `%" PRIu64 "` sampled for session `%s", *id, name);
 end:
-       rcu_read_unlock();
        return found;
 }
 
 void ls::details::locked_session_release(ltt_session *session)
 {
+       if (!session) {
+               return;
+       }
+
        session_unlock(session);
        session_put(session);
 }
@@ -1498,5 +1463,5 @@ ltt_session::sptr ls::find_session_by_id(ltt_session::id_t id)
                return nullptr;
        }
 
-       return {session, session_put};
+       return { session, session_put };
 }
index 12ac3eb73f78e39afc3a982df278b869a88bc081..8993f94681a27c9b900c93c12a39f542d5f31a5d 100644 (file)
@@ -8,30 +8,29 @@
 #ifndef _LTT_SESSION_H
 #define _LTT_SESSION_H
 
-#include <limits.h>
-#include <stdbool.h>
-#include <urcu/list.h>
+#include "consumer.hpp"
+#include "snapshot.hpp"
+#include "trace-kernel.hpp"
 
-#include <common/hashtable/hashtable.hpp>
 #include <common/dynamic-array.hpp>
+#include <common/hashtable/hashtable.hpp>
 #include <common/make-unique-wrapper.hpp>
 #include <common/pthread-lock.hpp>
-#include <lttng/rotation.h>
+
 #include <lttng/location.h>
 #include <lttng/lttng-error.h>
+#include <lttng/rotation.h>
 
-#include "snapshot.hpp"
-#include "trace-kernel.hpp"
-#include "consumer.hpp"
+#include <limits.h>
+#include <stdbool.h>
+#include <urcu/list.h>
 
 #define ASSERT_SESSION_LIST_LOCKED() LTTNG_ASSERT(session_trylock_list())
 
 struct ltt_ust_session;
 
-typedef void (*ltt_session_destroy_notifier)(const struct ltt_session *session,
-               void *user_data);
-typedef void (*ltt_session_clear_notifier)(const struct ltt_session *session,
-               void *user_data);
+using ltt_session_destroy_notifier = void (*)(const struct ltt_session *, void *);
+using ltt_session_clear_notifier = void (*)(const struct ltt_session *, void *);
 
 namespace lttng {
 namespace sessiond {
@@ -78,8 +77,10 @@ struct ltt_session_list {
  */
 struct ltt_session {
        using id_t = uint64_t;
-       using locked_ptr = std::unique_ptr<ltt_session,
-                       lttng::details::create_unique_class<ltt_session,
+       using locked_ptr =
+               std::unique_ptr<ltt_session,
+                               lttng::memory::create_deleter_class<
+                                       ltt_session,
                                        lttng::sessiond::details::locked_session_release>::deleter>;
        using sptr = std::shared_ptr<ltt_session>;
 
@@ -127,12 +128,9 @@ struct ltt_session {
         */
        bool has_user_specified_directory;
        /* Did at least ONE start command has been triggered?. */
-       unsigned int has_been_started:1;
-       /*
-        * Is the session active? Start trace command sets this to 1 and the stop
-        * command reset it to 0.
-        */
-       unsigned int active:1;
+       bool has_been_started;
+       /* Is the session active? */
+       bool active;
 
        /* Snapshot representation in a session. */
        struct snapshot snapshot;
@@ -217,8 +215,8 @@ struct ltt_session {
        char *base_path;
 };
 
-enum lttng_error_code session_create(const char *name, uid_t uid, gid_t gid,
-               struct ltt_session **out_session);
+enum lttng_error_code
+session_create(const char *name, uid_t uid, gid_t gid, struct ltt_session **out_session);
 void session_lock(struct ltt_session *session);
 void session_unlock(struct ltt_session *session);
 
@@ -231,48 +229,47 @@ void session_unlock(struct ltt_session *session);
  * In other words, it prevents tracer configurations from changing while they
  * are being transmitted to the various applications.
  */
-void session_lock_list(void);
-int session_trylock_list(void);
-void session_unlock_list(void);
+void session_lock_list() noexcept;
+int session_trylock_list() noexcept;
+void session_unlock_list() noexcept;
 
 void session_destroy(struct ltt_session *session);
 int session_add_destroy_notifier(struct ltt_session *session,
-               ltt_session_destroy_notifier notifier, void *user_data);
+                                ltt_session_destroy_notifier notifier,
+                                void *user_data);
 
 int session_add_clear_notifier(struct ltt_session *session,
-               ltt_session_clear_notifier notifier, void *user_data);
-void session_notify_clear(struct ltt_session *session);
+                              ltt_session_clear_notifier notifier,
+                              void *user_data);
+void session_notify_clear(ltt_session& session);
 
 bool session_get(struct ltt_session *session);
 void session_put(struct ltt_session *session);
 
-enum consumer_dst_type session_get_consumer_destination_type(
-               const struct ltt_session *session);
-const char *session_get_net_consumer_hostname(
-               const struct ltt_session *session);
-void session_get_net_consumer_ports(
-               const struct ltt_session *session,
-               uint16_t *control_port, uint16_t *data_port);
-struct lttng_trace_archive_location *session_get_trace_archive_location(
-               const struct ltt_session *session);
+enum consumer_dst_type session_get_consumer_destination_type(const struct ltt_session *session);
+const char *session_get_net_consumer_hostname(const struct ltt_session *session);
+void session_get_net_consumer_ports(const struct ltt_session *session,
+                                   uint16_t *control_port,
+                                   uint16_t *data_port);
+struct lttng_trace_archive_location *
+session_get_trace_archive_location(const struct ltt_session *session);
 
 struct ltt_session *session_find_by_name(const char *name);
 struct ltt_session *session_find_by_id(ltt_session::id_t id);
 
-struct ltt_session_list *session_get_list(void);
-void session_list_wait_empty(void);
+struct ltt_session_list *session_get_list();
+void session_list_wait_empty();
 
 bool session_access_ok(struct ltt_session *session, uid_t uid);
 
-int session_reset_rotation_state(struct ltt_session *session,
-               enum lttng_rotation_state result);
+int session_reset_rotation_state(ltt_session& session, enum lttng_rotation_state result);
 
 /* Create a new trace chunk object from the session's configuration. */
-struct lttng_trace_chunk *session_create_new_trace_chunk(
-               const struct ltt_session *session,
-               const struct consumer_output *consumer_output_override,
-               const char *session_base_path_override,
-               const char *chunk_name_override);
+struct lttng_trace_chunk *
+session_create_new_trace_chunk(const struct ltt_session *session,
+                              const struct consumer_output *consumer_output_override,
+                              const char *session_base_path_override,
+                              const char *chunk_name_override);
 
 /*
  * Set `new_trace_chunk` as the session's current trace chunk. A reference
@@ -283,17 +280,17 @@ struct lttng_trace_chunk *session_create_new_trace_chunk(
  * `current_session_trace_chunk` on success.
  */
 int session_set_trace_chunk(struct ltt_session *session,
-               struct lttng_trace_chunk *new_trace_chunk,
-               struct lttng_trace_chunk **current_session_trace_chunk);
+                           struct lttng_trace_chunk *new_trace_chunk,
+                           struct lttng_trace_chunk **current_session_trace_chunk);
 
 /*
  * Close a chunk on the remote peers of a session. Has no effect on the
  * ltt_session itself.
  */
 int session_close_trace_chunk(struct ltt_session *session,
-               struct lttng_trace_chunk *trace_chunk,
-               enum lttng_trace_chunk_command_type close_command,
-               char *path);
+                             struct lttng_trace_chunk *trace_chunk,
+                             enum lttng_trace_chunk_command_type close_command,
+                             char *path);
 
 /* Open a packet in all channels of a given session. */
 enum lttng_error_code session_open_packets(struct ltt_session *session);
index 8ebb2a07c3c674dc6c9d0436a9b6382d8244d87c..e8aeae8efbddb4e805f8ed90fa2a9b9b9ff80b20 100644 (file)
@@ -5,35 +5,36 @@
  *
  */
 
-#include "version.hpp"
-#include "sessiond-config.hpp"
 #include "lttng-ust-ctl.hpp"
+#include "sessiond-config.hpp"
+#include "version.hpp"
+
+#include <common/compat/errno.hpp>
+#include <common/compat/getenv.hpp>
 #include <common/defaults.hpp>
-#include <limits.h>
-#include <ctype.h>
 #include <common/error.hpp>
-#include <common/utils.hpp>
 #include <common/path.hpp>
-#include <common/compat/errno.hpp>
-#include <common/compat/getenv.hpp>
+#include <common/utils.hpp>
 
-static
-struct sessiond_config sessiond_config_build_defaults = {
-       .verbose =                              0,
-       .verbose_consumer =                     0,
-       .agent_tcp_port =                       { .begin = DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN, .end = DEFAULT_AGENT_TCP_PORT_RANGE_END },
+#include <ctype.h>
+#include <limits.h>
 
-       .event_notifier_buffer_size_kernel =    DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE,
-       .event_notifier_buffer_size_userspace = DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE,
-       .app_socket_timeout =                   DEFAULT_APP_SOCKET_RW_TIMEOUT,
+static struct sessiond_config sessiond_config_build_defaults = {
+       .verbose = 0,
+       .verbose_consumer = 0,
+       .agent_tcp_port = { .begin = DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN,
+                           .end = DEFAULT_AGENT_TCP_PORT_RANGE_END },
 
-       .quiet =                                false,
+       .event_notifier_buffer_size_kernel = DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE,
+       .event_notifier_buffer_size_userspace = DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE,
+       .app_socket_timeout = DEFAULT_APP_SOCKET_RW_TIMEOUT,
 
+       .quiet = false,
 
-       .no_kernel =                            false,
-       .background =                           false,
-       .daemonize =                            false,
-       .sig_parent =                           false,
+       .no_kernel = false,
+       .background = false,
+       .daemonize = false,
+       .sig_parent = false,
 
        .tracing_group_name = { (char *) DEFAULT_TRACING_GROUP, false },
 
@@ -69,15 +70,12 @@ struct sessiond_config sessiond_config_build_defaults = {
        .kconsumerd_cmd_unix_sock_path = { nullptr, false },
 };
 
-static
-void config_string_fini(struct config_string *str)
+static void config_string_fini(struct config_string *str)
 {
-       config_string_set(str, NULL);
+       config_string_set(str, nullptr);
 }
 
-static
-void config_string_set_static(struct config_string *config_str,
-               const char *value)
+static void config_string_set_static(struct config_string *config_str, const char *value)
 {
        config_string_set(config_str, (char *) value);
        config_str->should_free = false;
@@ -108,10 +106,10 @@ int sessiond_config_apply_env_config(struct sessiond_config *config)
 
                errno = 0;
                int_val = strtoul(env_value, &endptr, 0);
-               if (errno != 0 || int_val > INT_MAX ||
-                               (int_val < 0 && int_val != -1)) {
+               if (errno != 0 || int_val > INT_MAX || (int_val < 0 && int_val != -1)) {
                        ERR("Invalid value \"%s\" used for \"%s\" environment variable",
-                                       env_value, DEFAULT_APP_SOCKET_TIMEOUT_ENV);
+                           env_value,
+                           DEFAULT_APP_SOCKET_TIMEOUT_ENV);
                        ret = -1;
                        goto end;
                }
@@ -121,49 +119,41 @@ int sessiond_config_apply_env_config(struct sessiond_config *config)
 
        env_value = lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
        if (env_value) {
-               config_string_set_static(&config->consumerd32_bin_path,
-                               env_value);
+               config_string_set_static(&config->consumerd32_bin_path, env_value);
        }
        env_value = lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
        if (env_value) {
-               config_string_set_static(&config->consumerd64_bin_path,
-                               env_value);
+               config_string_set_static(&config->consumerd64_bin_path, env_value);
        }
 
        env_value = lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
        if (env_value) {
-               config_string_set_static(&config->consumerd32_lib_dir,
-                               env_value);
+               config_string_set_static(&config->consumerd32_lib_dir, env_value);
        }
        env_value = lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
        if (env_value) {
-               config_string_set_static(&config->consumerd64_lib_dir,
-                               env_value);
+               config_string_set_static(&config->consumerd64_lib_dir, env_value);
        }
 
        env_value = lttng_secure_getenv("LTTNG_UST_CLOCK_PLUGIN");
        if (env_value) {
-               config_string_set_static(&config->lttng_ust_clock_plugin,
-                               env_value);
+               config_string_set_static(&config->lttng_ust_clock_plugin, env_value);
        }
 
        env_value = lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES);
        if (env_value) {
-               config_string_set_static(&config->kmod_probes_list,
-                               env_value);
+               config_string_set_static(&config->kmod_probes_list, env_value);
        }
 
        env_value = lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES);
        if (env_value) {
-               config_string_set_static(&config->kmod_extra_probes_list,
-                               env_value);
+               config_string_set_static(&config->kmod_extra_probes_list, env_value);
        }
 end:
        return ret;
 }
 
-static
-int config_set_paths_root(struct sessiond_config *config)
+static int config_set_paths_root(struct sessiond_config *config)
 {
        int ret = 0;
 
@@ -174,26 +164,21 @@ int config_set_paths_root(struct sessiond_config *config)
                goto end;
        }
 
-       config_string_set_static(&config->apps_unix_sock_path,
-                       DEFAULT_GLOBAL_APPS_UNIX_SOCK);
-       config_string_set_static(&config->client_unix_sock_path,
-                       DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
-       config_string_set_static(&config->wait_shm_path,
-                       DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
-       config_string_set_static(&config->health_unix_sock_path,
-                       DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
+       config_string_set_static(&config->apps_unix_sock_path, DEFAULT_GLOBAL_APPS_UNIX_SOCK);
+       config_string_set_static(&config->client_unix_sock_path, DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
+       config_string_set_static(&config->wait_shm_path, DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
+       config_string_set_static(&config->health_unix_sock_path, DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
 end:
        return ret;
 }
 
-static
-int config_set_paths_non_root(struct sessiond_config *config)
+static int config_set_paths_non_root(struct sessiond_config *config)
 {
        int ret = 0;
        const char *home_path = utils_get_home_dir();
        char *str;
 
-       if (home_path == NULL) {
+       if (home_path == nullptr) {
                ERR("Can't get HOME directory for sockets creation.");
                ret = -1;
                goto end;
@@ -209,7 +194,7 @@ int config_set_paths_non_root(struct sessiond_config *config)
                goto end;
        }
        config_string_set(&config->rundir, str);
-       str = NULL;
+       str = nullptr;
 
        ret = asprintf(&str, DEFAULT_HOME_APPS_UNIX_SOCK, home_path);
        if (ret < 0) {
@@ -217,7 +202,7 @@ int config_set_paths_non_root(struct sessiond_config *config)
                goto end;
        }
        config_string_set(&config->apps_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
        ret = asprintf(&str, DEFAULT_HOME_CLIENT_UNIX_SOCK, home_path);
        if (ret < 0) {
@@ -225,7 +210,7 @@ int config_set_paths_non_root(struct sessiond_config *config)
                goto end;
        }
        config_string_set(&config->client_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
        ret = asprintf(&str, DEFAULT_HOME_APPS_WAIT_SHM_PATH, getuid());
        if (ret < 0) {
@@ -233,7 +218,7 @@ int config_set_paths_non_root(struct sessiond_config *config)
                goto end;
        }
        config_string_set(&config->wait_shm_path, str);
-       str = NULL;
+       str = nullptr;
 
        ret = asprintf(&str, DEFAULT_HOME_HEALTH_UNIX_SOCK, home_path);
        if (ret < 0) {
@@ -241,7 +226,7 @@ int config_set_paths_non_root(struct sessiond_config *config)
                goto end;
        }
        config_string_set(&config->health_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
        ret = 0;
 end:
@@ -267,115 +252,103 @@ int sessiond_config_init(struct sessiond_config *config)
        }
 
        /* 32 bits consumerd path setup */
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 32-bit consumer path");
                goto error;
        }
        config_string_set(&config->consumerd32_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 32-bit consumer error socket path");
                goto error;
        }
        config_string_set(&config->consumerd32_err_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 32-bit consumer command socket path");
                goto error;
        }
        config_string_set(&config->consumerd32_cmd_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
        /* 64 bits consumerd path setup */
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 64-bit consumer path");
                goto error;
        }
        config_string_set(&config->consumerd64_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 64-bit consumer error socket path");
                goto error;
        }
        config_string_set(&config->consumerd64_err_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set 64-bit consumer command socket path");
                goto error;
        }
        config_string_set(&config->consumerd64_cmd_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
        /* kconsumerd consumerd path setup */
-       ret = asprintf(&str, DEFAULT_KCONSUMERD_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_KCONSUMERD_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set kernel consumer path");
                goto error;
        }
        config_string_set(&config->kconsumerd_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_KCONSUMERD_ERR_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set kernel consumer error socket path");
                goto error;
        }
        config_string_set(&config->kconsumerd_err_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
-                       config->rundir.value);
+       ret = asprintf(&str, DEFAULT_KCONSUMERD_CMD_SOCK_PATH, config->rundir.value);
        if (ret < 0) {
                ERR("Failed to set kernel consumer command socket path");
                goto error;
        }
        config_string_set(&config->kconsumerd_cmd_unix_sock_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, "%s/%s", config->rundir.value,
-                       DEFAULT_LTTNG_SESSIOND_PIDFILE);
+       ret = asprintf(&str, "%s/%s", config->rundir.value, DEFAULT_LTTNG_SESSIOND_PIDFILE);
        if (ret < 0) {
                ERR("Failed to set PID file path");
                goto error;
        }
        config_string_set(&config->pid_file_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, "%s/%s", config->rundir.value,
-                       DEFAULT_LTTNG_SESSIOND_LOCKFILE);
+       ret = asprintf(&str, "%s/%s", config->rundir.value, DEFAULT_LTTNG_SESSIOND_LOCKFILE);
        if (ret < 0) {
                ERR("Failed to set lock file path");
                goto error;
        }
        config_string_set(&config->lock_file_path, str);
-       str = NULL;
+       str = nullptr;
 
-       ret = asprintf(&str, "%s/%s", config->rundir.value,
-                       DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE);
+       ret = asprintf(&str, "%s/%s", config->rundir.value, DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE);
        if (ret < 0) {
                ERR("Failed to set agent port file path");
                goto error;
        }
        config_string_set(&config->agent_port_file_path, str);
-       str = NULL;
+       str = nullptr;
 
        /*
         * Allow INSTALL_BIN_PATH to be used as a target path for the
@@ -384,14 +357,12 @@ int sessiond_config_init(struct sessiond_config *config)
         */
 #if (CAA_BITS_PER_LONG == 32)
        config_string_set_static(&config->consumerd32_bin_path,
-                       INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE);
-       config_string_set_static(&config->consumerd32_lib_dir,
-                       INSTALL_LIB_PATH);
+                                INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE);
+       config_string_set_static(&config->consumerd32_lib_dir, INSTALL_LIB_PATH);
 #elif (CAA_BITS_PER_LONG == 64)
        config_string_set_static(&config->consumerd64_bin_path,
-                       INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE);
-       config_string_set_static(&config->consumerd64_lib_dir,
-                       INSTALL_LIB_PATH);
+                                INSTALL_BIN_PATH "/" DEFAULT_CONSUMERD_FILE);
+       config_string_set_static(&config->consumerd64_lib_dir, INSTALL_LIB_PATH);
 #else
 #error "Unknown bitness"
 #endif
@@ -432,8 +403,7 @@ void sessiond_config_fini(struct sessiond_config *config)
        config_string_fini(&config->kconsumerd_cmd_unix_sock_path);
 }
 
-static
-int resolve_path(struct config_string *path)
+static int resolve_path(struct config_string *path)
 {
        int ret = 0;
        char *absolute_path;
@@ -453,9 +423,9 @@ end:
        return ret;
 }
 
-#define RESOLVE_CHECK(path_config_str)         \
-       if (resolve_path(path_config_str))      \
-               return -1
+#define RESOLVE_CHECK(path_config_str)     \
+       if (resolve_path(path_config_str)) \
+       return -1
 
 int sessiond_config_resolve_paths(struct sessiond_config *config)
 {
@@ -507,38 +477,60 @@ void sessiond_config_log(struct sessiond_config *config)
                DBG_NO_LOC("\tagent_tcp_port:                %i", config->agent_tcp_port.begin);
        } else {
                DBG_NO_LOC("\tagent_tcp_port:                [%i, %i]",
-                               config->agent_tcp_port.begin,
-                               config->agent_tcp_port.end);
+                          config->agent_tcp_port.begin,
+                          config->agent_tcp_port.end);
        }
        DBG_NO_LOC("\tapplication socket timeout:    %i", config->app_socket_timeout);
        DBG_NO_LOC("\tno-kernel:                     %s", config->no_kernel ? "True" : "False");
        DBG_NO_LOC("\tbackground:                    %s", config->background ? "True" : "False");
        DBG_NO_LOC("\tdaemonize:                     %s", config->daemonize ? "True" : "False");
        DBG_NO_LOC("\tsignal parent on start:        %s", config->sig_parent ? "True" : "False");
-       DBG_NO_LOC("\ttracing group name:            %s", config->tracing_group_name.value ? : "Unknown");
-       DBG_NO_LOC("\tkmod_probe_list:               %s", config->kmod_probes_list.value ? : "None");
-       DBG_NO_LOC("\tkmod_extra_probe_list:         %s", config->kmod_extra_probes_list.value ? : "None");
-       DBG_NO_LOC("\trundir:                        %s", config->rundir.value ? : "Unknown");
-       DBG_NO_LOC("\tapplication socket path:       %s", config->apps_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tclient socket path:            %s", config->client_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\twait shm path:                 %s", config->wait_shm_path.value ? : "Unknown");
-       DBG_NO_LOC("\thealth socket path:            %s", config->health_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tLTTNG_UST_CLOCK_PLUGIN:        %s", config->lttng_ust_clock_plugin.value ? : "None");
-       DBG_NO_LOC("\tpid file path:                 %s", config->pid_file_path.value ? : "Unknown");
-       DBG_NO_LOC("\tlock file path:                %s", config->lock_file_path.value ? : "Unknown");
-       DBG_NO_LOC("\tsession load path:             %s", config->load_session_path.value ? : "None");
-       DBG_NO_LOC("\tagent port file path:          %s", config->agent_port_file_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd32 path:              %s", config->consumerd32_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd32 bin path:          %s", config->consumerd32_bin_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd32 lib dir:           %s", config->consumerd32_lib_dir.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd32 err unix sock path:%s", config->consumerd32_err_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd32 cmd unix sock path:%s", config->consumerd32_cmd_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd64 path:              %s", config->consumerd64_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd64 bin path:          %s", config->consumerd64_bin_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd64 lib dir:           %s", config->consumerd64_lib_dir.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd64 err unix sock path:%s", config->consumerd64_err_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tconsumerd64 cmd unix sock path:%s", config->consumerd64_cmd_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tkconsumerd path:               %s", config->kconsumerd_path.value ? : "Unknown");
-       DBG_NO_LOC("\tkconsumerd err unix sock path: %s", config->kconsumerd_err_unix_sock_path.value ? : "Unknown");
-       DBG_NO_LOC("\tkconsumerd cmd unix sock path: %s", config->kconsumerd_cmd_unix_sock_path.value ? : "Unknown");
+       DBG_NO_LOC("\ttracing group name:            %s",
+                  config->tracing_group_name.value ?: "Unknown");
+       DBG_NO_LOC("\tkmod_probe_list:               %s", config->kmod_probes_list.value ?: "None");
+       DBG_NO_LOC("\tkmod_extra_probe_list:         %s",
+                  config->kmod_extra_probes_list.value ?: "None");
+       DBG_NO_LOC("\trundir:                        %s", config->rundir.value ?: "Unknown");
+       DBG_NO_LOC("\tapplication socket path:       %s",
+                  config->apps_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tclient socket path:            %s",
+                  config->client_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\twait shm path:                 %s", config->wait_shm_path.value ?: "Unknown");
+       DBG_NO_LOC("\thealth socket path:            %s",
+                  config->health_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tLTTNG_UST_CLOCK_PLUGIN:        %s",
+                  config->lttng_ust_clock_plugin.value ?: "None");
+       DBG_NO_LOC("\tpid file path:                 %s", config->pid_file_path.value ?: "Unknown");
+       DBG_NO_LOC("\tlock file path:                %s",
+                  config->lock_file_path.value ?: "Unknown");
+       DBG_NO_LOC("\tsession load path:             %s",
+                  config->load_session_path.value ?: "None");
+       DBG_NO_LOC("\tagent port file path:          %s",
+                  config->agent_port_file_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd32 path:              %s",
+                  config->consumerd32_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd32 bin path:          %s",
+                  config->consumerd32_bin_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd32 lib dir:           %s",
+                  config->consumerd32_lib_dir.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd32 err unix sock path:%s",
+                  config->consumerd32_err_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd32 cmd unix sock path:%s",
+                  config->consumerd32_cmd_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd64 path:              %s",
+                  config->consumerd64_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd64 bin path:          %s",
+                  config->consumerd64_bin_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd64 lib dir:           %s",
+                  config->consumerd64_lib_dir.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd64 err unix sock path:%s",
+                  config->consumerd64_err_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tconsumerd64 cmd unix sock path:%s",
+                  config->consumerd64_cmd_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tkconsumerd path:               %s",
+                  config->kconsumerd_path.value ?: "Unknown");
+       DBG_NO_LOC("\tkconsumerd err unix sock path: %s",
+                  config->kconsumerd_err_unix_sock_path.value ?: "Unknown");
+       DBG_NO_LOC("\tkconsumerd cmd unix sock path: %s",
+                  config->kconsumerd_cmd_unix_sock_path.value ?: "Unknown");
 }
index fa0bfeb8216b2161661de73be4a7e944a585b9d4..6b98a59a7fb56a53b7d6435e66c234f9939eb48d 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_SESSIOND_CONFIG_H
 
 #include <common/macros.hpp>
+
 #include <stdbool.h>
 
 struct config_string {
index e0ffe69c0b1a5303cebfe908ab99cee7eb2220d1..e7a0033541a5d07d5cdafd77d5f4306e462e2662 100644 (file)
@@ -6,14 +6,15 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <string.h>
-#include <urcu/uatomic.h>
+#include "snapshot.hpp"
+#include "utils.hpp"
 
 #include <common/defaults.hpp>
+#include <common/urcu.hpp>
 
-#include "snapshot.hpp"
-#include "utils.hpp"
+#include <inttypes.h>
+#include <string.h>
+#include <urcu/uatomic.h>
 
 /*
  * Return the atomically incremented value of next_output_id.
@@ -29,10 +30,13 @@ static inline unsigned long get_next_output_id(struct snapshot *snapshot)
  * Return 0 on success or else a negative value.
  */
 static int output_init(const struct ltt_session *session,
-               uint64_t max_size, const char *name,
-               struct lttng_uri *uris, size_t nb_uri,
-               struct consumer_output *consumer, struct snapshot_output *output,
-               struct snapshot *snapshot)
+                      uint64_t max_size,
+                      const char *name,
+                      struct lttng_uri *uris,
+                      size_t nb_uri,
+                      struct consumer_output *consumer,
+                      struct snapshot_output *output,
+                      struct snapshot *snapshot)
 {
        int ret = 0, i;
 
@@ -58,8 +62,11 @@ static int output_init(const struct ltt_session *session,
                }
        } else {
                /* Set default name. */
-               ret = snprintf(output->name, sizeof(output->name), "%s-%" PRIu32,
-                               DEFAULT_SNAPSHOT_NAME, output->id);
+               ret = snprintf(output->name,
+                              sizeof(output->name),
+                              "%s-%" PRIu32,
+                              DEFAULT_SNAPSHOT_NAME,
+                              output->id);
                if (ret < 0) {
                        ret = -ENOMEM;
                        goto error;
@@ -84,11 +91,12 @@ static int output_init(const struct ltt_session *session,
        }
 
        if (uris[0].dtype == LTTNG_DST_PATH) {
-               memset(output->consumer->dst.session_root_path, 0,
-                               sizeof(output->consumer->dst.session_root_path));
+               memset(output->consumer->dst.session_root_path,
+                      0,
+                      sizeof(output->consumer->dst.session_root_path));
                if (lttng_strncpy(output->consumer->dst.session_root_path,
-                               uris[0].dst.path,
-                               sizeof(output->consumer->dst.session_root_path))) {
+                                 uris[0].dst.path,
+                                 sizeof(output->consumer->dst.session_root_path))) {
                        ret = -LTTNG_ERR_INVALID;
                        goto error;
                }
@@ -103,10 +111,9 @@ static int output_init(const struct ltt_session *session,
                goto error;
        }
 
-       for (i = 0; i < nb_uri; i ++) {
+       for (i = 0; i < nb_uri; i++) {
                /* Network URIs */
-               ret = consumer_set_network_uri(session, output->consumer,
-                               &uris[i]);
+               ret = consumer_set_network_uri(session, output->consumer, &uris[i]);
                if (ret < 0) {
                        goto error;
                }
@@ -124,13 +131,15 @@ end:
  * Return 0 on success or else a negative value.
  */
 int snapshot_output_init_with_uri(const struct ltt_session *session,
-               uint64_t max_size, const char *name,
-               struct lttng_uri *uris, size_t nb_uri,
-               struct consumer_output *consumer, struct snapshot_output *output,
-               struct snapshot *snapshot)
+                                 uint64_t max_size,
+                                 const char *name,
+                                 struct lttng_uri *uris,
+                                 size_t nb_uri,
+                                 struct consumer_output *consumer,
+                                 struct snapshot_output *output,
+                                 struct snapshot *snapshot)
 {
-       return output_init(session, max_size, name, uris, nb_uri, consumer,
-                       output, snapshot);
+       return output_init(session, max_size, name, uris, nb_uri, consumer, output, snapshot);
 }
 
 /*
@@ -140,13 +149,16 @@ int snapshot_output_init_with_uri(const struct ltt_session *session,
  * Return 0 on success or else a negative value.
  */
 int snapshot_output_init(const struct ltt_session *session,
-               uint64_t max_size, const char *name,
-               const char *ctrl_url, const char *data_url,
-               struct consumer_output *consumer, struct snapshot_output *output,
-               struct snapshot *snapshot)
+                        uint64_t max_size,
+                        const char *name,
+                        const char *ctrl_url,
+                        const char *data_url,
+                        struct consumer_output *consumer,
+                        struct snapshot_output *output,
+                        struct snapshot *snapshot)
 {
        int ret = 0, nb_uri;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
 
        /* Create an array of URIs from URLs. */
        nb_uri = uri_parse_str_urls(ctrl_url, data_url, &uris);
@@ -155,15 +167,14 @@ int snapshot_output_init(const struct ltt_session *session,
                goto error;
        }
 
-       ret = output_init(session, max_size, name, uris, nb_uri, consumer,
-                       output, snapshot);
+       ret = output_init(session, max_size, name, uris, nb_uri, consumer, output, snapshot);
 
 error:
        free(uris);
        return ret;
 }
 
-struct snapshot_output *snapshot_output_alloc(void)
+struct snapshot_output *snapshot_output_alloc()
 {
        return zmalloc<snapshot_output>();
 }
@@ -171,8 +182,7 @@ struct snapshot_output *snapshot_output_alloc(void)
 /*
  * Delete output from the snapshot object.
  */
-void snapshot_delete_output(struct snapshot *snapshot,
-               struct snapshot_output *output)
+void snapshot_delete_output(struct snapshot *snapshot, struct snapshot_output *output)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -182,9 +192,8 @@ void snapshot_delete_output(struct snapshot *snapshot,
        LTTNG_ASSERT(output);
 
        iter.iter.node = &output->node.node;
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        ret = lttng_ht_del(snapshot->output_ht, &iter);
-       rcu_read_unlock();
        LTTNG_ASSERT(!ret);
        /*
         * This is safe because the ownership of a snapshot object is in a session
@@ -196,16 +205,14 @@ void snapshot_delete_output(struct snapshot *snapshot,
 /*
  * Add output object to the snapshot.
  */
-void snapshot_add_output(struct snapshot *snapshot,
-               struct snapshot_output *output)
+void snapshot_add_output(struct snapshot *snapshot, struct snapshot_output *output)
 {
        LTTNG_ASSERT(snapshot);
        LTTNG_ASSERT(snapshot->output_ht);
        LTTNG_ASSERT(output);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_add_unique_ulong(snapshot->output_ht, &output->node);
-       rcu_read_unlock();
        /*
         * This is safe because the ownership of a snapshot object is in a session
         * for which the session lock need to be acquired to read and modify it.
@@ -233,25 +240,23 @@ void snapshot_output_destroy(struct snapshot_output *obj)
  *
  * Return the reference on success or else NULL.
  */
-struct snapshot_output *snapshot_find_output_by_name(const char *name,
-               struct snapshot *snapshot)
+struct snapshot_output *snapshot_find_output_by_name(const char *name, struct snapshot *snapshot)
 {
        struct lttng_ht_iter iter;
-       struct snapshot_output *output = NULL;
+       struct snapshot_output *output = nullptr;
 
        LTTNG_ASSERT(snapshot);
        LTTNG_ASSERT(name);
        ASSERT_RCU_READ_LOCKED();
 
-       cds_lfht_for_each_entry(snapshot->output_ht->ht, &iter.iter, output,
-               node.node) {
+       cds_lfht_for_each_entry (snapshot->output_ht->ht, &iter.iter, output, node.node) {
                if (!strncmp(output->name, name, strlen(name))) {
                        return output;
                }
        }
 
        /* Not found */
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -260,17 +265,16 @@ struct snapshot_output *snapshot_find_output_by_name(const char *name,
  *
  * Return the reference on success or else NULL.
  */
-struct snapshot_output *snapshot_find_output_by_id(uint32_t id,
-               struct snapshot *snapshot)
+struct snapshot_output *snapshot_find_output_by_id(uint32_t id, struct snapshot *snapshot)
 {
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
-       struct snapshot_output *output = NULL;
+       struct snapshot_output *output = nullptr;
 
        LTTNG_ASSERT(snapshot);
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(snapshot->output_ht, (void *)((unsigned long) id), &iter);
+       lttng_ht_lookup(snapshot->output_ht, (void *) ((unsigned long) id), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
        if (!node) {
                DBG3("Snapshot output not found with id %" PRId32, id);
@@ -320,12 +324,14 @@ void snapshot_destroy(struct snapshot *obj)
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(obj->output_ht->ht, &iter.iter, output,
-                       node.node) {
-               snapshot_delete_output(obj, output);
-               snapshot_output_destroy(output);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (obj->output_ht->ht, &iter.iter, output, node.node) {
+                       snapshot_delete_output(obj, output);
+                       snapshot_output_destroy(output);
+               }
        }
-       rcu_read_unlock();
+
        lttng_ht_destroy(obj->output_ht);
 }
index 6aa06ddc6fb02e6c34afa7ff6c16e92ca0b5162f..726b89f80c23fbea59ea73452a29a6c692159f66 100644 (file)
@@ -8,14 +8,14 @@
 #ifndef SNAPSHOT_H
 #define SNAPSHOT_H
 
-#include <limits.h>
-#include <stdint.h>
+#include "consumer.hpp"
 
 #include <common/common.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/uri.hpp>
 
-#include "consumer.hpp"
+#include <limits.h>
+#include <stdint.h>
 
 struct consumer_output;
 struct ltt_session;
@@ -52,30 +52,32 @@ struct snapshot {
 };
 
 /* Snapshot object. */
-struct snapshot *snapshot_alloc(void);
+struct snapshot *snapshot_alloc();
 void snapshot_destroy(struct snapshot *obj);
 int snapshot_init(struct snapshot *obj);
-void snapshot_delete_output(struct snapshot *snapshot,
-               struct snapshot_output *output);
-void snapshot_add_output(struct snapshot *snapshot,
-               struct snapshot_output *output);
+void snapshot_delete_output(struct snapshot *snapshot, struct snapshot_output *output);
+void snapshot_add_output(struct snapshot *snapshot, struct snapshot_output *output);
 
 /* Snapshot output object. */
-struct snapshot_output *snapshot_output_alloc(void);
+struct snapshot_output *snapshot_output_alloc();
 void snapshot_output_destroy(struct snapshot_output *obj);
 int snapshot_output_init(const struct ltt_session *session,
-               uint64_t max_size, const char *name,
-               const char *ctrl_url, const char *data_url,
-               struct consumer_output *consumer, struct snapshot_output *output,
-               struct snapshot *snapshot);
+                        uint64_t max_size,
+                        const char *name,
+                        const char *ctrl_url,
+                        const char *data_url,
+                        struct consumer_output *consumer,
+                        struct snapshot_output *output,
+                        struct snapshot *snapshot);
 int snapshot_output_init_with_uri(const struct ltt_session *session,
-               uint64_t max_size, const char *name,
-               struct lttng_uri *uris, size_t nb_uri,
-               struct consumer_output *consumer, struct snapshot_output *output,
-               struct snapshot *snapshot);
-struct snapshot_output *snapshot_find_output_by_id(uint32_t id,
-               struct snapshot *snapshot);
-struct snapshot_output *snapshot_find_output_by_name(const char *name,
-               struct snapshot *snapshot);
+                                 uint64_t max_size,
+                                 const char *name,
+                                 struct lttng_uri *uris,
+                                 size_t nb_uri,
+                                 struct consumer_output *consumer,
+                                 struct snapshot_output *output,
+                                 struct snapshot *snapshot);
+struct snapshot_output *snapshot_find_output_by_id(uint32_t id, struct snapshot *snapshot);
+struct snapshot_output *snapshot_find_output_by_name(const char *name, struct snapshot *snapshot);
 
 #endif /* SNAPSHOT_H */
index c087facbaa8cc1c4f820be892d38929caf010f2f..856b98e8ad77c1de6b58c24036ae65ae627068a7 100644 (file)
 namespace lst = lttng::sessiond::trace;
 
 lttng::sessiond::trace::stream_class::stream_class(
-               unsigned int in_id, enum header_type in_header_type) :
-       id{in_id}, header_type_{in_header_type}
+       unsigned int in_id,
+       enum header_type in_header_type,
+       nonstd::optional<std::string> in_default_clock_class_name) :
+       id{ in_id },
+       header_type_{ in_header_type },
+       default_clock_class_name{ std::move(in_default_clock_class_name) }
 {
 }
 
@@ -22,8 +26,17 @@ void lst::stream_class::accept(trace_class_visitor& visitor) const
        _accept_on_event_classes(visitor);
 }
 
-const lttng::sessiond::trace::type& lst::stream_class::get_context() const
+const lttng::sessiond::trace::type *lst::stream_class::packet_context() const
 {
-       LTTNG_ASSERT(_context);
-       return *_context;
+       return _packet_context.get();
+}
+
+const lttng::sessiond::trace::type *lst::stream_class::event_header() const
+{
+       return _event_header.get();
+}
+
+const lttng::sessiond::trace::type *lst::stream_class::event_context() const
+{
+       return _event_context.get();
 }
index 08555f3071e55362f1ce4f20fae3d4ca7ab59a12..5faecd5e1eb41c3fd824eec132afe652c17fa997 100644 (file)
@@ -10,6 +10,8 @@
 
 #include "field.hpp"
 
+#include <vendor/optional.hpp>
+
 #include <vector>
 
 namespace lttng {
@@ -28,8 +30,14 @@ public:
         */
        void accept(trace_class_visitor& visitor) const;
        virtual ~stream_class() = default;
+       stream_class(const stream_class&) = delete;
+       stream_class(stream_class&&) = delete;
+       stream_class& operator=(stream_class&&) = delete;
+       stream_class& operator=(const stream_class&) = delete;
 
-       virtual const lttng::sessiond::trace::type& get_context() const;
+       virtual const type *packet_context() const;
+       virtual const type *event_header() const;
+       virtual const type *event_context() const;
 
        const unsigned int id;
        /*
@@ -38,12 +46,17 @@ public:
         * nested-name-specifiers.
         */
        const header_type header_type_;
+       const nonstd::optional<std::string> default_clock_class_name;
 
 protected:
-       stream_class(unsigned int id, enum header_type header_type);
+       stream_class(unsigned int id,
+                    enum header_type header_type,
+                    nonstd::optional<std::string> default_clock_class_name = nonstd::nullopt);
        virtual void _accept_on_event_classes(trace_class_visitor& trace_class_visitor) const = 0;
 
-       lttng::sessiond::trace::type::cuptr _context;
+       lttng::sessiond::trace::type::cuptr _packet_context;
+       lttng::sessiond::trace::type::cuptr _event_header;
+       lttng::sessiond::trace::type::cuptr _event_context;
 };
 
 } /* namespace trace */
index e28106e785d99aa52a4d5f8d4dc3a40d95524c53..c861e0f52e65bd76e5962742475e81f64003681f 100644 (file)
@@ -9,34 +9,38 @@
 
 #include "lttng-sessiond.hpp"
 #include "utils.hpp"
+
 #include <common/utils.hpp>
+
+#include <fcntl.h>
 #include <pthread.h>
 
 /*
- * Quit pipe for all threads. This permits a single cancellation point
- * for all threads when receiving an event on the pipe.
+ * Quit pipe for the main thread. This is used by signal handlers to start the
+ * shutdown sequence of the main thread which will tear down the other threads
+ * in the appropriate order.
  */
-static int thread_quit_pipe[2] = { -1, -1 };
+static int main_quit_pipe[2] = { -1, -1 };
 
 /*
- * Init thread quit pipe.
+ * Init main quit pipe.
  *
  * Return -1 on error or 0 if all pipes are created.
  */
-static int __init_thread_quit_pipe(int *a_pipe)
+int sessiond_init_main_quit_pipe()
 {
        int ret, i;
 
-       ret = pipe(a_pipe);
+       ret = pipe(main_quit_pipe);
        if (ret < 0) {
-               PERROR("thread quit pipe");
+               PERROR("main quit pipe");
                goto error;
        }
 
        for (i = 0; i < 2; i++) {
-               ret = fcntl(a_pipe[i], F_SETFD, FD_CLOEXEC);
+               ret = fcntl(main_quit_pipe[i], F_SETFD, FD_CLOEXEC);
                if (ret < 0) {
-                       PERROR("fcntl");
+                       PERROR("fcntl main_quit_pipe");
                        goto error;
                }
        }
@@ -45,25 +49,15 @@ error:
        return ret;
 }
 
-int sessiond_init_thread_quit_pipe(void)
-{
-       return __init_thread_quit_pipe(thread_quit_pipe);
-}
-
-int sessiond_check_thread_quit_pipe(int fd, uint32_t events)
-{
-       return (fd == thread_quit_pipe[0] && (events & LPOLLIN));
-}
-
 /*
- * Wait for a notification on the quit pipe (with a timeout).
+ * Wait for a notification on the main quit pipe (with a timeout).
  *
  * A timeout value of -1U means no timeout.
  *
  * Returns 1 if the caller should quit, 0 if the timeout was reached, and
  * -1 if an error was encountered.
  */
-int sessiond_wait_for_quit_pipe(int timeout_ms)
+int sessiond_wait_for_main_quit_pipe(int timeout_ms)
 {
        int ret;
        struct lttng_poll_event events;
@@ -74,7 +68,7 @@ int sessiond_wait_for_quit_pipe(int timeout_ms)
                ret = -1;
                goto end;
        }
-       ret = lttng_poll_add(&events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, main_quit_pipe[0], LPOLLIN);
        if (ret < 0) {
                PERROR("Failed to add file descriptor to poll/epoll set");
                ret = -1;
@@ -86,7 +80,7 @@ int sessiond_wait_for_quit_pipe(int timeout_ms)
                ret = 1;
        } else if (ret < 0 && errno != EINTR) {
                /* Unknown error. */
-               PERROR("Failed to epoll()/poll() thread quit pipe");
+               PERROR("Failed to epoll()/poll() main quit pipe");
                ret = -1;
        } else {
                /* Timeout reached. */
@@ -98,19 +92,20 @@ end:
        return ret;
 }
 
-int sessiond_notify_quit_pipe(void)
+int sessiond_notify_main_quit_pipe()
 {
-       return notify_thread_pipe(thread_quit_pipe[1]);
+       return notify_thread_pipe(main_quit_pipe[1]);
 }
 
-void sessiond_close_quit_pipe(void)
+void sessiond_close_main_quit_pipe()
 {
-       utils_close_pipe(thread_quit_pipe);
+       utils_close_pipe(main_quit_pipe);
 }
 
-static
-int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
-               int *a_pipe)
+/*
+ * Create a poll set with O_CLOEXEC and add the main quit pipe to the set.
+ */
+int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
 {
        int ret;
 
@@ -121,8 +116,8 @@ int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
                goto error;
        }
 
-       /* Add quit pipe */
-       ret = lttng_poll_add(events, a_pipe[0], LPOLLIN | LPOLLERR);
+       /* Add main quit pipe */
+       ret = lttng_poll_add(events, main_quit_pipe[0], LPOLLIN);
        if (ret < 0) {
                goto error;
        }
@@ -132,11 +127,3 @@ int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
 error:
        return ret;
 }
-
-/*
- * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
- */
-int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
-{
-       return __sessiond_set_thread_pollset(events, size, thread_quit_pipe);
-}
index fd9136fe5562b4e5acee6a70bef36061572b38c0..4077f460ef4c11dc31c5ce10b26ca2ed75348f06 100644 (file)
@@ -6,12 +6,14 @@
  */
 
 #include "thread.hpp"
+
+#include <common/defaults.hpp>
+#include <common/error.hpp>
+#include <common/macros.hpp>
+
+#include <pthread.h>
 #include <urcu/list.h>
 #include <urcu/ref.h>
-#include <pthread.h>
-#include <common/macros.hpp>
-#include <common/error.hpp>
-#include <common/defaults.hpp>
 
 namespace {
 struct thread_list {
@@ -42,8 +44,7 @@ struct lttng_thread {
        void *data;
 };
 
-static
-void lttng_thread_destroy(struct lttng_thread *thread)
+static void lttng_thread_destroy(struct lttng_thread *thread)
 {
        if (thread->cleanup) {
                thread->cleanup(thread->data);
@@ -51,14 +52,12 @@ void lttng_thread_destroy(struct lttng_thread *thread)
        free(thread);
 }
 
-static
-void lttng_thread_release(struct urcu_ref *ref)
+static void lttng_thread_release(struct urcu_ref *ref)
 {
        lttng_thread_destroy(lttng::utils::container_of(ref, &lttng_thread::ref));
 }
 
-static
-void *launch_thread(void *data)
+static void *launch_thread(void *data)
 {
        void *ret;
        struct lttng_thread *thread = (struct lttng_thread *) data;
@@ -71,10 +70,10 @@ void *launch_thread(void *data)
 }
 
 struct lttng_thread *lttng_thread_create(const char *name,
-               lttng_thread_entry_point entry,
-               lttng_thread_shutdown_cb shutdown,
-               lttng_thread_cleanup_cb cleanup,
-               void *thread_data)
+                                        lttng_thread_entry_point entry,
+                                        lttng_thread_shutdown_cb shutdown,
+                                        lttng_thread_cleanup_cb cleanup,
+                                        void *thread_data)
 {
        int ret;
        struct lttng_thread *thread;
@@ -105,8 +104,7 @@ struct lttng_thread *lttng_thread_create(const char *name,
        cds_list_add(&thread->node, &thread_list.head);
        (void) lttng_thread_get(thread);
 
-       ret = pthread_create(&thread->thread, default_pthread_attr(),
-                       launch_thread, thread);
+       ret = pthread_create(&thread->thread, default_pthread_attr(), launch_thread, thread);
        if (ret) {
                PERROR("Failed to create \"%s\" thread", thread->name);
                goto error_pthread_create;
@@ -123,7 +121,7 @@ error_pthread_create:
        /* Release initial reference. */
        lttng_thread_put(thread);
 error_alloc:
-       return NULL;
+       return nullptr;
 }
 
 bool lttng_thread_get(struct lttng_thread *thread)
@@ -145,8 +143,7 @@ const char *lttng_thread_get_name(const struct lttng_thread *thread)
        return thread->name;
 }
 
-static
-bool _lttng_thread_shutdown(struct lttng_thread *thread)
+static bool _lttng_thread_shutdown(struct lttng_thread *thread)
 {
        int ret;
        void *status;
@@ -186,12 +183,12 @@ bool lttng_thread_shutdown(struct lttng_thread *thread)
        return result;
 }
 
-void lttng_thread_list_shutdown_orphans(void)
+void lttng_thread_list_shutdown_orphans()
 {
        struct lttng_thread *thread, *tmp;
 
        pthread_mutex_lock(&thread_list.lock);
-       cds_list_for_each_entry_safe(thread, tmp, &thread_list.head, node) {
+       cds_list_for_each_entry_safe (thread, tmp, &thread_list.head, node) {
                bool result;
                const long ref = uatomic_read(&thread->ref.refcount);
 
index 530f72a8e446e3a9c1a2b188ccaaf415129b7625..a1e390a09b085ee2c56ce1f90d513349b1f30123 100644 (file)
 struct lttng_thread;
 
 /* Main function of the new thread. */
-typedef void *(*lttng_thread_entry_point)(void *);
+using lttng_thread_entry_point = void *(*) (void *);
 
 /* Callback invoked to initiate the shutdown a thread. */
-typedef bool (*lttng_thread_shutdown_cb)(void *);
+using lttng_thread_shutdown_cb = bool (*)(void *);
 
 /*
  * Callback invoked to clean-up the thread data.
@@ -24,17 +24,17 @@ typedef bool (*lttng_thread_shutdown_cb)(void *);
  * race between a use by the "thread shutdown callback" and
  * a use by the thread itself.
  */
-typedef void (*lttng_thread_cleanup_cb)(void *);
+using lttng_thread_cleanup_cb = void (*)(void *);
 
 /*
  * Returns a reference to the newly-created thread.
  * The shutdown and cleanup callbacks are optional.
  */
 struct lttng_thread *lttng_thread_create(const char *name,
-               lttng_thread_entry_point entry,
-               lttng_thread_shutdown_cb shutdown,
-               lttng_thread_cleanup_cb cleanup,
-               void *thread_data);
+                                        lttng_thread_entry_point entry,
+                                        lttng_thread_shutdown_cb shutdown,
+                                        lttng_thread_cleanup_cb cleanup,
+                                        void *thread_data);
 
 bool lttng_thread_get(struct lttng_thread *thread);
 void lttng_thread_put(struct lttng_thread *thread);
@@ -57,6 +57,6 @@ bool lttng_thread_shutdown(struct lttng_thread *thread);
  *
  * Returns once all orphaned threads have been joined.
  */
-void lttng_thread_list_shutdown_orphans(void);
+void lttng_thread_list_shutdown_orphans();
 
 #endif /* THREAD_H */
index 30eb13446e3badb44e1e278e5f8ad5c636490e7c..838983e3baa2d26a5b8c554a0a05e9d4ffe4449f 100644 (file)
@@ -7,25 +7,25 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <signal.h>
-
-#include "timer.hpp"
 #include "health-sessiond.hpp"
 #include "rotation-thread.hpp"
 #include "thread.hpp"
+#include "timer.hpp"
 
-#define LTTNG_SESSIOND_SIG_QS                          SIGRTMIN + 10
-#define LTTNG_SESSIOND_SIG_EXIT                                SIGRTMIN + 11
-#define LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK      SIGRTMIN + 12
-#define LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION          SIGRTMIN + 13
+#include <inttypes.h>
+#include <signal.h>
+
+#define LTTNG_SESSIOND_SIG_QS                    (SIGRTMIN + 10)
+#define LTTNG_SESSIOND_SIG_EXIT                          (SIGRTMIN + 11)
+#define LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK (SIGRTMIN + 12)
+#define LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION    (SIGRTMIN + 13)
 
-#define UINT_TO_PTR(value)                             \
-       ({                                              \
-               LTTNG_ASSERT(value <= UINTPTR_MAX);             \
-               (void *) (uintptr_t) value;             \
+#define UINT_TO_PTR(value)                            \
+       ({                                            \
+               LTTNG_ASSERT((value) <= UINTPTR_MAX); \
+               (void *) (uintptr_t) (value);         \
        })
-#define PTR_TO_UINT(ptr) ((uintptr_t) ptr)
+#define PTR_TO_UINT(ptr) ((uintptr_t) (ptr))
 
 namespace {
 /*
@@ -49,8 +49,7 @@ struct timer_signal_data {
 /*
  * Set custom signal mask to current thread.
  */
-static
-void setmask(sigset_t *mask)
+static void setmask(sigset_t *mask)
 {
        int ret;
 
@@ -81,8 +80,7 @@ void setmask(sigset_t *mask)
  * returns, it means that no timer signr is currently pending or being handled
  * by the timer thread. This cannot be called from the timer thread.
  */
-static
-void timer_signal_thread_qs(unsigned int signr)
+static void timer_signal_thread_qs(unsigned int signr)
 {
        sigset_t pending_set;
        int ret;
@@ -139,9 +137,11 @@ void timer_signal_thread_qs(unsigned int signr)
  * Returns a negative value on error, 0 if a timer was created, and
  * a positive value if no timer was created (not an error).
  */
-static
-int timer_start(timer_t *timer_id, struct ltt_session *session,
-               unsigned int timer_interval_us, int signal, bool one_shot)
+static int timer_start(timer_t *timer_id,
+                      struct ltt_session *session,
+                      unsigned int timer_interval_us,
+                      int signal,
+                      bool one_shot)
 {
        int ret = 0, delete_ret;
        struct sigevent sev = {};
@@ -166,7 +166,7 @@ int timer_start(timer_t *timer_id, struct ltt_session *session,
                its.it_interval.tv_nsec = its.it_value.tv_nsec;
        }
 
-       ret = timer_settime(*timer_id, 0, &its, NULL);
+       ret = timer_settime(*timer_id, 0, &its, nullptr);
        if (ret == -1) {
                PERROR("timer_settime");
                goto error_destroy_timer;
@@ -183,8 +183,7 @@ end:
        return ret;
 }
 
-static
-int timer_stop(timer_t *timer_id, int signal)
+static int timer_stop(timer_t *timer_id, int signal)
 {
        int ret = 0;
 
@@ -195,13 +194,13 @@ int timer_stop(timer_t *timer_id, int signal)
        }
 
        timer_signal_thread_qs(signal);
-       *timer_id = 0;
+       *timer_id = nullptr;
 end:
        return ret;
 }
 
 int timer_session_rotation_pending_check_start(struct ltt_session *session,
-               unsigned int interval_us)
+                                              unsigned int interval_us)
 {
        int ret;
 
@@ -209,8 +208,7 @@ int timer_session_rotation_pending_check_start(struct ltt_session *session,
                ret = -1;
                goto end;
        }
-       DBG("Enabling session rotation pending check timer on session %" PRIu64,
-                       session->id);
+       DBG("Enabling session rotation pending check timer on session %" PRIu64, session->id);
        /*
         * We arm this timer in a one-shot mode so we don't have to disable it
         * explicitly (which could deadlock if the timer thread is blocked
@@ -221,9 +219,10 @@ int timer_session_rotation_pending_check_start(struct ltt_session *session,
         * no need to go through the whole signal teardown scheme everytime.
         */
        ret = timer_start(&session->rotation_pending_check_timer,
-                       session, interval_us,
-                       LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK,
-                       /* one-shot */ true);
+                         session,
+                         interval_us,
+                         LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK,
+                         /* one-shot */ true);
        if (ret == 0) {
                session->rotation_pending_check_timer_enabled = true;
        }
@@ -234,26 +233,25 @@ end:
 /*
  * Call with session and session_list locks held.
  */
-int timer_session_rotation_pending_check_stop(struct ltt_session *session)
+int timer_session_rotation_pending_check_stop(ltt_session& session)
 {
        int ret;
 
-       LTTNG_ASSERT(session);
-       LTTNG_ASSERT(session->rotation_pending_check_timer_enabled);
+       LTTNG_ASSERT(session.rotation_pending_check_timer_enabled);
 
-       DBG("Disabling session rotation pending check timer on session %" PRIu64,
-                       session->id);
-       ret = timer_stop(&session->rotation_pending_check_timer,
-                       LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK);
+       DBG("Disabling session rotation pending check timer on session %" PRIu64, session.id);
+       ret = timer_stop(&session.rotation_pending_check_timer,
+                        LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK);
        if (ret == -1) {
                ERR("Failed to stop rotate_pending_check timer");
        } else {
-               session->rotation_pending_check_timer_enabled = false;
+               session.rotation_pending_check_timer_enabled = false;
                /*
                 * The timer's reference to the session can be released safely.
                 */
-               session_put(session);
+               session_put(&session);
        }
+
        return ret;
 }
 
@@ -261,7 +259,7 @@ int timer_session_rotation_pending_check_stop(struct ltt_session *session)
  * Call with session and session_list locks held.
  */
 int timer_session_rotation_schedule_timer_start(struct ltt_session *session,
-               unsigned int interval_us)
+                                               unsigned int interval_us)
 {
        int ret;
 
@@ -269,11 +267,15 @@ int timer_session_rotation_schedule_timer_start(struct ltt_session *session,
                ret = -1;
                goto end;
        }
-       DBG("Enabling scheduled rotation timer on session \"%s\" (%ui %s)", session->name,
-                       interval_us, USEC_UNIT);
-       ret = timer_start(&session->rotation_schedule_timer, session,
-                       interval_us, LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION,
-                       /* one-shot */ false);
+       DBG("Enabling scheduled rotation timer on session \"%s\" (%ui %s)",
+           session->name,
+           interval_us,
+           USEC_UNIT);
+       ret = timer_start(&session->rotation_schedule_timer,
+                         session,
+                         interval_us,
+                         LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION,
+                         /* one-shot */ false);
        if (ret < 0) {
                goto end;
        }
@@ -296,11 +298,9 @@ int timer_session_rotation_schedule_timer_stop(struct ltt_session *session)
        }
 
        DBG("Disabling scheduled rotation timer on session %s", session->name);
-       ret = timer_stop(&session->rotation_schedule_timer,
-                       LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION);
+       ret = timer_stop(&session->rotation_schedule_timer, LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION);
        if (ret < 0) {
-               ERR("Failed to stop scheduled rotation timer of session \"%s\"",
-                               session->name);
+               ERR("Failed to stop scheduled rotation timer of session \"%s\"", session->name);
                goto end;
        }
 
@@ -316,14 +316,14 @@ end:
  * Block the RT signals for the entire process. It must be called from the
  * sessiond main before creating the threads
  */
-int timer_signal_init(void)
+int timer_signal_init()
 {
        int ret;
        sigset_t mask;
 
        /* Block signal for entire process, so only our thread processes it. */
        setmask(&mask);
-       ret = pthread_sigmask(SIG_BLOCK, &mask, NULL);
+       ret = pthread_sigmask(SIG_BLOCK, &mask, nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_sigmask");
@@ -335,8 +335,7 @@ int timer_signal_init(void)
 /*
  * This thread is the sighandler for the timer signals.
  */
-static
-void *thread_timer(void *data)
+static void *thread_timer(void *data)
 {
        int signr;
        sigset_t mask;
@@ -353,7 +352,7 @@ void *thread_timer(void *data)
        setmask(&mask);
        CMM_STORE_SHARED(timer_signal.tid, pthread_self());
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                health_poll_entry();
@@ -378,15 +377,17 @@ void *thread_timer(void *data)
                        goto end;
                } else if (signr == LTTNG_SESSIOND_SIG_PENDING_ROTATION_CHECK) {
                        struct ltt_session *session =
-                                       (struct ltt_session *) info.si_value.sival_ptr;
+                               (struct ltt_session *) info.si_value.sival_ptr;
 
-                       rotation_thread_enqueue_job(ctx->rotation_thread_job_queue,
-                                       ROTATION_THREAD_JOB_TYPE_CHECK_PENDING_ROTATION,
-                                       session);
+                       rotation_thread_enqueue_job(
+                               ctx->rotation_thread_job_queue,
+                               lttng::sessiond::rotation_thread_job_type::CHECK_PENDING_ROTATION,
+                               session);
                } else if (signr == LTTNG_SESSIOND_SIG_SCHEDULED_ROTATION) {
-                       rotation_thread_enqueue_job(ctx->rotation_thread_job_queue,
-                                       ROTATION_THREAD_JOB_TYPE_SCHEDULED_ROTATION,
-                                       (struct ltt_session *) info.si_value.sival_ptr);
+                       rotation_thread_enqueue_job(
+                               ctx->rotation_thread_job_queue,
+                               lttng::sessiond::rotation_thread_job_type::SCHEDULED_ROTATION,
+                               (struct ltt_session *) info.si_value.sival_ptr);
                        /*
                         * The scheduled periodic rotation timer is not in
                         * "one-shot" mode. The reference to the session is not
@@ -403,25 +404,20 @@ end:
        health_unregister(the_health_sessiond);
        rcu_thread_offline();
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
-static
-bool shutdown_timer_thread(void *data __attribute__((unused)))
+static bool shutdown_timer_thread(void *data __attribute__((unused)))
 {
        return kill(getpid(), LTTNG_SESSIOND_SIG_EXIT) == 0;
 }
 
-bool launch_timer_thread(
-               struct timer_thread_parameters *timer_thread_parameters)
+bool launch_timer_thread(struct timer_thread_parameters *timer_thread_parameters)
 {
        struct lttng_thread *thread;
 
-       thread = lttng_thread_create("Timer",
-                       thread_timer,
-                       shutdown_timer_thread,
-                       NULL,
-                       timer_thread_parameters);
+       thread = lttng_thread_create(
+               "Timer", thread_timer, shutdown_timer_thread, nullptr, timer_thread_parameters);
        if (!thread) {
                goto error;
        }
index f746f0ed9c6fba3689894cfcb0eb49b1a921eff9..c291ae6d250db28adf56ae21b079391b683f7a95 100644 (file)
@@ -9,30 +9,30 @@
 #ifndef SESSIOND_TIMER_H
 #define SESSIOND_TIMER_H
 
+#include "rotation-thread.hpp"
+#include "session.hpp"
+
 #include <pthread.h>
 #include <stdbool.h>
 
-#include "session.hpp"
-
 struct timer_thread_parameters {
-       struct rotation_thread_timer_queue *rotation_thread_job_queue;
+       lttng::sessiond::rotation_thread_timer_queue *rotation_thread_job_queue;
 };
 
-int timer_signal_init(void);
+int timer_signal_init();
 
 /* Start a session's rotation pending check timer (one-shot mode). */
 int timer_session_rotation_pending_check_start(struct ltt_session *session,
-               unsigned int interval_us);
+                                              unsigned int interval_us);
 /* Stop a session's rotation pending check timer. */
-int timer_session_rotation_pending_check_stop(struct ltt_session *session);
+int timer_session_rotation_pending_check_stop(ltt_session& session);
 
 /* Start a session's rotation schedule timer. */
 int timer_session_rotation_schedule_timer_start(struct ltt_session *session,
-               unsigned int interval_us);
+                                               unsigned int interval_us);
 /* Stop a session's rotation schedule timer. */
 int timer_session_rotation_schedule_timer_stop(struct ltt_session *session);
 
-bool launch_timer_thread(
-               struct timer_thread_parameters *timer_thread_parameters);
+bool launch_timer_thread(struct timer_thread_parameters *timer_thread_parameters);
 
 #endif /* SESSIOND_TIMER_H */
index 21a0c52dca0f2a8ea4480886cefe4d1432e6985b..e5d4b54054b53b6a91e31c43308c0b2196ce494b 100644 (file)
@@ -9,11 +9,9 @@
 
 namespace lst = lttng::sessiond::trace;
 
-lttng::sessiond::trace::trace_class::trace_class(
-               const struct abi& in_abi,
-               const lttng_uuid& in_trace_uuid) :
-       abi{in_abi},
-       uuid{in_trace_uuid}
+lttng::sessiond::trace::trace_class::trace_class(const struct abi& in_abi,
+                                                const lttng_uuid& in_trace_uuid) :
+       abi(in_abi), uuid(in_trace_uuid)
 {
 }
 
@@ -21,15 +19,10 @@ void lttng::sessiond::trace::trace_class::accept(trace_class_visitor& trace_clas
 {
        trace_class_visitor.visit(*this);
        _accept_on_clock_classes(trace_class_visitor);
-
-       trace_class_visitor.environment_begin();
-       _visit_environment(trace_class_visitor);
-       trace_class_visitor.environment_end();
-
        _accept_on_stream_classes(trace_class_visitor);
 }
 
-void lst::trace_class_visitor::visit(const environment_field<std::string>& field)
+void lst::trace_class_environment_visitor::visit(const environment_field<std::string>& field)
 {
        visit(environment_field<const char *>(field.name, field.value.c_str()));
 }
index 087499866e097775dfc0bf4f2b2a564e1a4e3df8..afd99ffb7dfa67541f7ca327337e760ed93704bd 100644 (file)
@@ -8,6 +8,8 @@
 #ifndef LTTNG_TRACE_CLASS_H
 #define LTTNG_TRACE_CLASS_H
 
+#include "field.hpp"
+
 #include <common/uuid.hpp>
 
 namespace lttng {
@@ -18,11 +20,7 @@ class clock_class;
 class stream_class;
 class event_class;
 class trace_class_visitor;
-
-enum class byte_order {
-       BIG_ENDIAN_,
-       LITTLE_ENDIAN_,
-};
+class trace_class_environment_visitor;
 
 struct abi {
        unsigned int bits_per_long;
@@ -42,19 +40,25 @@ public:
        {
        }
 
-       const char * const name;
+       const char *const name;
        const ValueType& value;
 };
 
 class trace_class {
 public:
+       virtual ~trace_class() = default;
+       trace_class(const trace_class&) = delete;
+       trace_class(trace_class&&) = delete;
+       trace_class& operator=(trace_class&&) = delete;
+       trace_class& operator=(const trace_class&) = delete;
+
        /*
         * Derived classes must implement the _accept_on_*()
         * to continue the traversal to the trace class' children.
         */
        virtual void accept(trace_class_visitor& trace_class_visitor) const;
-
-       virtual ~trace_class() = default;
+       virtual void accept(trace_class_environment_visitor& environment_visitor) const = 0;
+       virtual const lttng::sessiond::trace::type *packet_header() const noexcept = 0;
 
        const struct abi abi;
        const lttng_uuid uuid;
@@ -62,33 +66,37 @@ public:
 protected:
        trace_class(const struct abi& abi, const lttng_uuid& trace_uuid);
        virtual void _accept_on_clock_classes(trace_class_visitor& trace_class_visitor) const = 0;
-       virtual void _visit_environment(trace_class_visitor& trace_class_visitor) const = 0;
        virtual void _accept_on_stream_classes(trace_class_visitor& trace_class_visitor) const = 0;
 };
 
+class trace_class_environment_visitor {
+public:
+       trace_class_environment_visitor() = default;
+       virtual ~trace_class_environment_visitor() = default;
+       trace_class_environment_visitor(const trace_class_environment_visitor&) = delete;
+       trace_class_environment_visitor(trace_class_environment_visitor&&) = delete;
+       trace_class_environment_visitor& operator=(trace_class_environment_visitor&&) = delete;
+       trace_class_environment_visitor& operator=(const trace_class_environment_visitor&) = delete;
+
+       virtual void visit(const environment_field<int64_t>& field) = 0;
+       virtual void visit(const environment_field<const char *>& field) = 0;
+       virtual void visit(const environment_field<std::string>& field);
+};
+
 class trace_class_visitor {
 public:
        using cuptr = std::unique_ptr<trace_class_visitor>;
 
+       trace_class_visitor() = default;
        virtual ~trace_class_visitor() = default;
+       trace_class_visitor(const trace_class_visitor&) = delete;
+       trace_class_visitor(trace_class_visitor&&) = delete;
+       trace_class_visitor& operator=(trace_class_visitor&&) = delete;
+       trace_class_visitor& operator=(const trace_class_visitor&) = delete;
 
-       /* trace class visitor interface. */
        virtual void visit(const lttng::sessiond::trace::trace_class& trace_class) = 0;
-
-       /* clock class visitor interface. */
        virtual void visit(const lttng::sessiond::trace::clock_class& clock_class) = 0;
-
-       /* environment visitor interface. */
-       virtual void environment_begin() = 0;
-       virtual void visit(const environment_field<int64_t>& field) = 0;
-       virtual void visit(const environment_field<const char *>& field) = 0;
-       void visit(const environment_field<std::string>& field);
-       virtual void environment_end() = 0;
-
-       /* stream class visitor interface. */
        virtual void visit(const lttng::sessiond::trace::stream_class& stream_class) = 0;
-
-       /* event class visitor interface. */
        virtual void visit(const lttng::sessiond::trace::event_class& event_class) = 0;
 };
 
index 23d808ce8852f155e82bcbf7dc6cd65f41f48703..e5d185223b53107c02b42b91b9cfb82e5f1f4219 100644 (file)
@@ -6,41 +6,42 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
+#include "consumer.hpp"
+#include "lttng-sessiond.hpp"
+#include "notification-thread-commands.hpp"
+#include "trace-kernel.hpp"
+
+#include <common/common.hpp>
+#include <common/defaults.hpp>
+#include <common/macros.hpp>
+#include <common/trace-chunk.hpp>
 
-#include <lttng/event.h>
-#include <lttng/lttng-error.h>
-#include <lttng/kernel-probe.h>
-#include <lttng/userspace-probe.h>
-#include <lttng/userspace-probe-internal.hpp>
-#include <lttng/event-rule/event-rule.h>
 #include <lttng/event-rule/event-rule-internal.hpp>
-#include <lttng/event-rule/kernel-kprobe.h>
+#include <lttng/event-rule/event-rule.h>
 #include <lttng/event-rule/kernel-kprobe-internal.hpp>
-#include <lttng/event-rule/kernel-syscall.h>
+#include <lttng/event-rule/kernel-kprobe.h>
 #include <lttng/event-rule/kernel-syscall-internal.hpp>
-#include <lttng/event-rule/kernel-tracepoint.h>
+#include <lttng/event-rule/kernel-syscall.h>
 #include <lttng/event-rule/kernel-tracepoint-internal.hpp>
-#include <lttng/event-rule/kernel-uprobe.h>
+#include <lttng/event-rule/kernel-tracepoint.h>
 #include <lttng/event-rule/kernel-uprobe-internal.hpp>
-#include <common/common.hpp>
-#include <common/defaults.hpp>
-#include <common/trace-chunk.hpp>
-#include <common/macros.hpp>
+#include <lttng/event-rule/kernel-uprobe.h>
+#include <lttng/event.h>
+#include <lttng/kernel-probe.h>
+#include <lttng/lttng-error.h>
+#include <lttng/userspace-probe-internal.hpp>
+#include <lttng/userspace-probe.h>
 
-#include "consumer.hpp"
-#include "trace-kernel.hpp"
-#include "lttng-sessiond.hpp"
-#include "notification-thread-commands.hpp"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
 /*
  * Find the channel name for the given kernel session.
  */
-struct ltt_kernel_channel *trace_kernel_get_channel_by_name(
-               const char *name, struct ltt_kernel_session *session)
+struct ltt_kernel_channel *trace_kernel_get_channel_by_name(const char *name,
+                                                           struct ltt_kernel_session *session)
 {
        struct ltt_kernel_channel *chan;
 
@@ -56,35 +57,35 @@ struct ltt_kernel_channel *trace_kernel_get_channel_by_name(
 
        DBG("Trying to find channel %s", name);
 
-       cds_list_for_each_entry(chan, &session->channel_list.head, list) {
+       cds_list_for_each_entry (chan, &session->channel_list.head, list) {
                if (strcmp(name, chan->channel->name) == 0) {
                        DBG("Found channel by name %s", name);
                        return chan;
                }
        }
 
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Find the event for the given channel.
  */
-struct ltt_kernel_event *trace_kernel_find_event(
-               char *name, struct ltt_kernel_channel *channel,
-               enum lttng_event_type type,
-               struct lttng_bytecode *filter)
+struct ltt_kernel_event *trace_kernel_find_event(char *name,
+                                                struct ltt_kernel_channel *channel,
+                                                enum lttng_event_type type,
+                                                struct lttng_bytecode *filter)
 {
        struct ltt_kernel_event *ev;
-       int found = 0;
+       bool found = false;
 
        LTTNG_ASSERT(name);
        LTTNG_ASSERT(channel);
 
-       cds_list_for_each_entry(ev, &channel->events_list.head, list) {
+       cds_list_for_each_entry (ev, &channel->events_list.head, list) {
                if (type != LTTNG_EVENT_ALL && ev->type != type) {
                        continue;
                }
-               if (strcmp(name, ev->event->name)) {
+               if (strcmp(name, ev->event->name) != 0) {
                        continue;
                }
                if ((ev->filter && !filter) || (!ev->filter && filter)) {
@@ -92,52 +93,53 @@ struct ltt_kernel_event *trace_kernel_find_event(
                }
                if (ev->filter && filter) {
                        if (ev->filter->len != filter->len ||
-                                       memcmp(ev->filter->data, filter->data,
-                                               filter->len) != 0) {
+                           memcmp(ev->filter->data, filter->data, filter->len) != 0) {
                                continue;
                        }
                }
-               found = 1;
+
+               found = true;
                break;
        }
+
        if (found) {
-               DBG("Found event %s for channel %s", name,
-                       channel->channel->name);
+               DBG("Found event %s for channel %s", name, channel->channel->name);
                return ev;
        } else {
-               return NULL;
+               return nullptr;
        }
 }
 
 /*
  * Find the event name for the given channel.
  */
-struct ltt_kernel_event *trace_kernel_get_event_by_name(
-               char *name, struct ltt_kernel_channel *channel,
-               enum lttng_event_type type)
+struct ltt_kernel_event *trace_kernel_get_event_by_name(char *name,
+                                                       struct ltt_kernel_channel *channel,
+                                                       enum lttng_event_type type)
 {
        struct ltt_kernel_event *ev;
-       int found = 0;
+       bool found = false;
 
        LTTNG_ASSERT(name);
        LTTNG_ASSERT(channel);
 
-       cds_list_for_each_entry(ev, &channel->events_list.head, list) {
+       cds_list_for_each_entry (ev, &channel->events_list.head, list) {
                if (type != LTTNG_EVENT_ALL && ev->type != type) {
                        continue;
                }
-               if (strcmp(name, ev->event->name)) {
+               if (strcmp(name, ev->event->name) != 0) {
                        continue;
                }
-               found = 1;
+
+               found = true;
                break;
        }
+
        if (found) {
-               DBG("Found event %s for channel %s", name,
-                       channel->channel->name);
+               DBG("Found event %s for channel %s", name, channel->channel->name);
                return ev;
        } else {
-               return NULL;
+               return nullptr;
        }
 }
 
@@ -146,13 +148,13 @@ struct ltt_kernel_event *trace_kernel_get_event_by_name(
  *
  * Return pointer to structure or NULL.
  */
-struct ltt_kernel_session *trace_kernel_create_session(void)
+struct ltt_kernel_session *trace_kernel_create_session()
 {
-       struct ltt_kernel_session *lks = NULL;
+       struct ltt_kernel_session *lks = nullptr;
 
        /* Allocate a new ltt kernel session */
        lks = zmalloc<ltt_kernel_session>();
-       if (lks == NULL) {
+       if (lks == nullptr) {
                PERROR("create kernel session zmalloc");
                goto alloc_error;
        }
@@ -162,7 +164,7 @@ struct ltt_kernel_session *trace_kernel_create_session(void)
        lks->metadata_stream_fd = -1;
        lks->channel_count = 0;
        lks->stream_count_global = 0;
-       lks->metadata = NULL;
+       lks->metadata = nullptr;
        CDS_INIT_LIST_HEAD(&lks->channel_list.head);
 
        lks->tracker_pid = process_attr_tracker_create();
@@ -190,7 +192,7 @@ struct ltt_kernel_session *trace_kernel_create_session(void)
                goto error;
        }
        lks->consumer = consumer_create_output(CONSUMER_DST_LOCAL);
-       if (lks->consumer == NULL) {
+       if (lks->consumer == nullptr) {
                goto error;
        }
 
@@ -206,7 +208,7 @@ error:
        free(lks);
 
 alloc_error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -214,22 +216,21 @@ alloc_error:
  *
  * Return pointer to structure or NULL.
  */
-struct ltt_kernel_channel *trace_kernel_create_channel(
-               struct lttng_channel *chan)
+struct ltt_kernel_channel *trace_kernel_create_channel(struct lttng_channel *chan)
 {
        struct ltt_kernel_channel *lkc;
-       struct lttng_channel_extended *extended = NULL;
+       struct lttng_channel_extended *extended = nullptr;
 
        LTTNG_ASSERT(chan);
 
        lkc = zmalloc<ltt_kernel_channel>();
-       if (lkc == NULL) {
+       if (lkc == nullptr) {
                PERROR("ltt_kernel_channel zmalloc");
                goto error;
        }
 
        lkc->channel = zmalloc<lttng_channel>();
-       if (lkc->channel == NULL) {
+       if (lkc->channel == nullptr) {
                PERROR("lttng_channel zmalloc");
                goto error;
        }
@@ -242,22 +243,21 @@ struct ltt_kernel_channel *trace_kernel_create_channel(
        memcpy(lkc->channel, chan, sizeof(struct lttng_channel));
        memcpy(extended, chan->attr.extended.ptr, sizeof(struct lttng_channel_extended));
        lkc->channel->attr.extended.ptr = extended;
-       extended = NULL;
+       extended = nullptr;
 
        /*
         * If we receive an empty string for channel name, it means the
         * default channel name is requested.
         */
        if (chan->name[0] == '\0') {
-               strncpy(lkc->channel->name, DEFAULT_CHANNEL_NAME,
-                       sizeof(lkc->channel->name));
+               strncpy(lkc->channel->name, DEFAULT_CHANNEL_NAME, sizeof(lkc->channel->name));
        }
        lkc->channel->name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
 
        lkc->fd = -1;
        lkc->stream_count = 0;
        lkc->event_count = 0;
-       lkc->enabled = 1;
+       lkc->enabled = true;
        lkc->published_to_notification_thread = false;
        /* Init linked list */
        CDS_INIT_LIST_HEAD(&lkc->events_list.head);
@@ -272,7 +272,7 @@ error:
        }
        free(extended);
        free(lkc);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -280,8 +280,7 @@ error:
  *
  * Return the allocated object or NULL on error.
  */
-struct ltt_kernel_context *trace_kernel_create_context(
-               struct lttng_kernel_abi_context *ctx)
+struct ltt_kernel_context *trace_kernel_create_context(struct lttng_kernel_abi_context *ctx)
 {
        struct ltt_kernel_context *kctx;
 
@@ -304,8 +303,7 @@ error:
  *
  * Return the allocated object or NULL on error.
  */
-struct ltt_kernel_context *trace_kernel_copy_context(
-               struct ltt_kernel_context *kctx)
+struct ltt_kernel_context *trace_kernel_copy_context(struct ltt_kernel_context *kctx)
 {
        struct ltt_kernel_context *kctx_copy;
 
@@ -329,21 +327,21 @@ error:
  *
  * Return pointer to structure or NULL.
  */
-enum lttng_error_code trace_kernel_create_event(
-               struct lttng_event *ev, char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct ltt_kernel_event **kernel_event)
+enum lttng_error_code trace_kernel_create_event(struct lttng_event *ev,
+                                               char *filter_expression,
+                                               struct lttng_bytecode *filter,
+                                               struct ltt_kernel_event **kernel_event)
 {
        enum lttng_error_code ret;
        struct lttng_kernel_abi_event *attr;
        struct ltt_kernel_event *local_kernel_event;
-       struct lttng_userspace_probe_location *userspace_probe_location = NULL;
+       struct lttng_userspace_probe_location *userspace_probe_location = nullptr;
 
        LTTNG_ASSERT(ev);
 
        local_kernel_event = zmalloc<ltt_kernel_event>();
        attr = zmalloc<lttng_kernel_abi_event>();
-       if (local_kernel_event == NULL || attr == NULL) {
+       if (local_kernel_event == nullptr || attr == nullptr) {
                PERROR("kernel event zmalloc");
                ret = LTTNG_ERR_NOMEM;
                goto error;
@@ -355,13 +353,14 @@ enum lttng_error_code trace_kernel_create_event(
                attr->u.kprobe.addr = ev->attr.probe.addr;
                attr->u.kprobe.offset = ev->attr.probe.offset;
                strncpy(attr->u.kprobe.symbol_name,
-                               ev->attr.probe.symbol_name, LTTNG_KERNEL_ABI_SYM_NAME_LEN);
+                       ev->attr.probe.symbol_name,
+                       LTTNG_KERNEL_ABI_SYM_NAME_LEN);
                attr->u.kprobe.symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
                break;
        case LTTNG_EVENT_USERSPACE_PROBE:
        {
-               const struct lttng_userspace_probe_location* location = NULL;
-               const struct lttng_userspace_probe_location_lookup_method *lookup = NULL;
+               const struct lttng_userspace_probe_location *location = nullptr;
+               const struct lttng_userspace_probe_location_lookup_method *lookup = nullptr;
 
                location = lttng_event_get_userspace_probe_location(ev);
                if (!location) {
@@ -379,8 +378,7 @@ enum lttng_error_code trace_kernel_create_event(
                 */
                attr->instrumentation = LTTNG_KERNEL_ABI_UPROBE;
 
-               lookup = lttng_userspace_probe_location_get_lookup_method(
-                               location);
+               lookup = lttng_userspace_probe_location_get_lookup_method(location);
                if (!lookup) {
                        ret = LTTNG_ERR_PROBE_LOCATION_INVAL;
                        goto error;
@@ -394,26 +392,24 @@ enum lttng_error_code trace_kernel_create_event(
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
                        /* Get the file descriptor on the target binary. */
                        attr->u.uprobe.fd =
-                                       lttng_userspace_probe_location_function_get_binary_fd(location);
+                               lttng_userspace_probe_location_function_get_binary_fd(location);
 
                        /*
                         * Save a reference to the probe location used during
                         * the listing of events.
                         */
-                       userspace_probe_location =
-                                       lttng_userspace_probe_location_copy(location);
+                       userspace_probe_location = lttng_userspace_probe_location_copy(location);
                        break;
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                        /* Get the file descriptor on the target binary. */
                        attr->u.uprobe.fd =
-                                       lttng_userspace_probe_location_tracepoint_get_binary_fd(location);
+                               lttng_userspace_probe_location_tracepoint_get_binary_fd(location);
 
                        /*
                         * Save a reference to the probe location used during the listing of
                         * events.
                         */
-                       userspace_probe_location =
-                                       lttng_userspace_probe_location_copy(location);
+                       userspace_probe_location = lttng_userspace_probe_location_copy(location);
                        break;
                default:
                        DBG("Unsupported lookup method type");
@@ -427,13 +423,15 @@ enum lttng_error_code trace_kernel_create_event(
                attr->u.kretprobe.addr = ev->attr.probe.addr;
                attr->u.kretprobe.offset = ev->attr.probe.offset;
                strncpy(attr->u.kretprobe.symbol_name,
-                               ev->attr.probe.symbol_name, LTTNG_KERNEL_ABI_SYM_NAME_LEN);
+                       ev->attr.probe.symbol_name,
+                       LTTNG_KERNEL_ABI_SYM_NAME_LEN);
                attr->u.kretprobe.symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
                break;
        case LTTNG_EVENT_FUNCTION_ENTRY:
                attr->instrumentation = LTTNG_KERNEL_ABI_FUNCTION;
                strncpy(attr->u.ftrace.symbol_name,
-                               ev->attr.ftrace.symbol_name, LTTNG_KERNEL_ABI_SYM_NAME_LEN);
+                       ev->attr.ftrace.symbol_name,
+                       LTTNG_KERNEL_ABI_SYM_NAME_LEN);
                attr->u.ftrace.symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
                break;
        case LTTNG_EVENT_TRACEPOINT:
@@ -461,7 +459,7 @@ enum lttng_error_code trace_kernel_create_event(
        /* Setting up a kernel event */
        local_kernel_event->fd = -1;
        local_kernel_event->event = attr;
-       local_kernel_event->enabled = 1;
+       local_kernel_event->enabled = true;
        local_kernel_event->filter_expression = filter_expression;
        local_kernel_event->filter = filter;
        local_kernel_event->userspace_probe_location = userspace_probe_location;
@@ -483,19 +481,19 @@ error:
  *
  * Return pointer to structure or NULL.
  */
-enum lttng_error_code trace_kernel_create_event_notifier_rule(
-               struct lttng_trigger *trigger,
-               uint64_t token,
-               uint64_t error_counter_index,
-               struct ltt_kernel_event_notifier_rule **event_notifier_rule)
+enum lttng_error_code
+trace_kernel_create_event_notifier_rule(struct lttng_trigger *trigger,
+                                       uint64_t token,
+                                       uint64_t error_counter_index,
+                                       struct ltt_kernel_event_notifier_rule **event_notifier_rule)
 {
        enum lttng_error_code ret = LTTNG_OK;
        enum lttng_condition_type condition_type;
        enum lttng_event_rule_type event_rule_type;
        enum lttng_condition_status condition_status;
        struct ltt_kernel_event_notifier_rule *local_kernel_token_event_rule;
-       const struct lttng_condition *condition = NULL;
-       const struct lttng_event_rule *event_rule = NULL;
+       const struct lttng_condition *condition = nullptr;
+       const struct lttng_event_rule *event_rule = nullptr;
 
        LTTNG_ASSERT(event_notifier_rule);
 
@@ -505,24 +503,22 @@ enum lttng_error_code trace_kernel_create_event_notifier_rule(
        condition_type = lttng_condition_get_type(condition);
        LTTNG_ASSERT(condition_type == LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(event_rule);
 
        event_rule_type = lttng_event_rule_get_type(event_rule);
        LTTNG_ASSERT(event_rule_type != LTTNG_EVENT_RULE_TYPE_UNKNOWN);
 
-       local_kernel_token_event_rule =
-                       zmalloc<ltt_kernel_event_notifier_rule>();
-       if (local_kernel_token_event_rule == NULL) {
+       local_kernel_token_event_rule = zmalloc<ltt_kernel_event_notifier_rule>();
+       if (local_kernel_token_event_rule == nullptr) {
                PERROR("Failed to allocate ltt_kernel_token_event_rule structure");
                ret = LTTNG_ERR_NOMEM;
                goto error;
        }
 
        local_kernel_token_event_rule->fd = -1;
-       local_kernel_token_event_rule->enabled = 1;
+       local_kernel_token_event_rule->enabled = true;
        local_kernel_token_event_rule->token = token;
        local_kernel_token_event_rule->error_counter_index = error_counter_index;
 
@@ -531,11 +527,10 @@ enum lttng_error_code trace_kernel_create_event_notifier_rule(
 
        local_kernel_token_event_rule->trigger = trigger;
        /* The event rule still owns the filter and bytecode. */
-       local_kernel_token_event_rule->filter =
-                       lttng_event_rule_get_filter_bytecode(event_rule);
+       local_kernel_token_event_rule->filter = lttng_event_rule_get_filter_bytecode(event_rule);
 
        DBG3("Created kernel event notifier rule: token =  %" PRIu64,
-                       local_kernel_token_event_rule->token);
+            local_kernel_token_event_rule->token);
 error:
        *event_notifier_rule = local_kernel_token_event_rule;
        return ret;
@@ -545,8 +540,8 @@ error:
  * Initialize a kernel trigger from an event rule.
  */
 enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
-               const struct lttng_event_rule *rule,
-               struct lttng_kernel_abi_event_notifier *kernel_event_notifier)
+       const struct lttng_event_rule *rule,
+       struct lttng_kernel_abi_event_notifier *kernel_event_notifier)
 {
        enum lttng_error_code ret_code;
        const char *name;
@@ -556,8 +551,8 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
        case LTTNG_EVENT_RULE_TYPE_KERNEL_KPROBE:
        {
                uint64_t address = 0, offset = 0;
-               const char *symbol_name = NULL;
-               const struct lttng_kernel_probe_location *location = NULL;
+               const char *symbol_name = nullptr;
+               const struct lttng_kernel_probe_location *location = nullptr;
                enum lttng_kernel_probe_location_status k_status;
                enum lttng_event_rule_status status;
 
@@ -570,18 +565,16 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                switch (lttng_kernel_probe_location_get_type(location)) {
                case LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS:
                {
-                       k_status = lttng_kernel_probe_location_address_get_address(
-                                       location, &address);
+                       k_status =
+                               lttng_kernel_probe_location_address_get_address(location, &address);
                        LTTNG_ASSERT(k_status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK);
                        break;
                }
                case LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET:
                {
-                       k_status = lttng_kernel_probe_location_symbol_get_offset(
-                                       location, &offset);
+                       k_status = lttng_kernel_probe_location_symbol_get_offset(location, &offset);
                        LTTNG_ASSERT(k_status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK);
-                       symbol_name = lttng_kernel_probe_location_symbol_get_name(
-                                       location);
+                       symbol_name = lttng_kernel_probe_location_symbol_get_name(location);
                        break;
                }
                default:
@@ -593,9 +586,9 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                kernel_event_notifier->event.u.kprobe.offset = offset;
                if (symbol_name) {
                        strncpy_ret = lttng_strncpy(
-                                       kernel_event_notifier->event.u.kprobe.symbol_name,
-                                       symbol_name,
-                                       sizeof(kernel_event_notifier->event.u.kprobe.symbol_name));
+                               kernel_event_notifier->event.u.kprobe.symbol_name,
+                               symbol_name,
+                               sizeof(kernel_event_notifier->event.u.kprobe.symbol_name));
 
                        if (strncpy_ret) {
                                ret_code = LTTNG_ERR_INVALID;
@@ -603,7 +596,8 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                        }
                }
 
-               kernel_event_notifier->event.u.kprobe.symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
+               kernel_event_notifier->event.u.kprobe
+                       .symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN - 1] = '\0';
 
                status = lttng_event_rule_kernel_kprobe_get_event_name(rule, &name);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
@@ -612,8 +606,8 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
        }
        case LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE:
        {
-               const struct lttng_userspace_probe_location* location = NULL;
-               const struct lttng_userspace_probe_location_lookup_method *lookup = NULL;
+               const struct lttng_userspace_probe_location *location = nullptr;
+               const struct lttng_userspace_probe_location_lookup_method *lookup = nullptr;
                enum lttng_event_rule_status status;
 
                status = lttng_event_rule_kernel_uprobe_get_location(rule, &location);
@@ -624,8 +618,7 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
 
                kernel_event_notifier->event.instrumentation = LTTNG_KERNEL_ABI_UPROBE;
 
-               lookup = lttng_userspace_probe_location_get_lookup_method(
-                               location);
+               lookup = lttng_userspace_probe_location_get_lookup_method(location);
                if (!lookup) {
                        ret_code = LTTNG_ERR_PROBE_LOCATION_INVAL;
                        goto error;
@@ -639,20 +632,19 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
                        /* Get the file descriptor on the target binary. */
                        kernel_event_notifier->event.u.uprobe.fd =
-                                       lttng_userspace_probe_location_function_get_binary_fd(location);
+                               lttng_userspace_probe_location_function_get_binary_fd(location);
 
                        break;
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                        /* Get the file descriptor on the target binary. */
                        kernel_event_notifier->event.u.uprobe.fd =
-                                       lttng_userspace_probe_location_tracepoint_get_binary_fd(location);
+                               lttng_userspace_probe_location_tracepoint_get_binary_fd(location);
                        break;
                default:
                        abort();
                }
 
-               status = lttng_event_rule_kernel_uprobe_get_event_name(
-                               rule, &name);
+               status = lttng_event_rule_kernel_uprobe_get_event_name(rule, &name);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
                ret_code = LTTNG_OK;
                break;
@@ -660,12 +652,10 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
        case LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT:
        {
                const enum lttng_event_rule_status status =
-                               lttng_event_rule_kernel_tracepoint_get_name_pattern(
-                                               rule, &name);
+                       lttng_event_rule_kernel_tracepoint_get_name_pattern(rule, &name);
 
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
-               kernel_event_notifier->event.instrumentation =
-                               LTTNG_KERNEL_ABI_TRACEPOINT;
+               kernel_event_notifier->event.instrumentation = LTTNG_KERNEL_ABI_TRACEPOINT;
 
                ret_code = LTTNG_OK;
                break;
@@ -673,17 +663,16 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
        case LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL:
        {
                const enum lttng_event_rule_status status =
-                               lttng_event_rule_kernel_syscall_get_name_pattern(
-                                               rule, &name);
-               const enum lttng_event_rule_kernel_syscall_emission_site
-                       emission_site =
+                       lttng_event_rule_kernel_syscall_get_name_pattern(rule, &name);
+               const enum lttng_event_rule_kernel_syscall_emission_site emission_site =
                        lttng_event_rule_kernel_syscall_get_emission_site(rule);
                enum lttng_kernel_abi_syscall_entryexit entryexit;
 
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
-               LTTNG_ASSERT(emission_site != LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_UNKNOWN);
+               LTTNG_ASSERT(emission_site !=
+                            LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_UNKNOWN);
 
-               switch(emission_site) {
+               switch (emission_site) {
                case LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY:
                        entryexit = LTTNG_KERNEL_ABI_SYSCALL_ENTRY;
                        break;
@@ -698,14 +687,10 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                        break;
                }
 
-               kernel_event_notifier->event.instrumentation =
-                               LTTNG_KERNEL_ABI_SYSCALL;
-               kernel_event_notifier->event.u.syscall.abi =
-                               LTTNG_KERNEL_ABI_SYSCALL_ABI_ALL;
-               kernel_event_notifier->event.u.syscall.entryexit =
-                               entryexit;
-               kernel_event_notifier->event.u.syscall.match =
-                               LTTNG_KERNEL_ABI_SYSCALL_MATCH_NAME;
+               kernel_event_notifier->event.instrumentation = LTTNG_KERNEL_ABI_SYSCALL;
+               kernel_event_notifier->event.u.syscall.abi = LTTNG_KERNEL_ABI_SYSCALL_ABI_ALL;
+               kernel_event_notifier->event.u.syscall.entryexit = entryexit;
+               kernel_event_notifier->event.u.syscall.match = LTTNG_KERNEL_ABI_SYSCALL_MATCH_NAME;
                ret_code = LTTNG_OK;
                break;
        }
@@ -714,8 +699,8 @@ enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
                break;
        }
 
-       strncpy_ret = lttng_strncpy(kernel_event_notifier->event.name, name,
-                       LTTNG_KERNEL_ABI_SYM_NAME_LEN);
+       strncpy_ret = lttng_strncpy(
+               kernel_event_notifier->event.name, name, LTTNG_KERNEL_ABI_SYM_NAME_LEN);
        if (strncpy_ret) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
@@ -729,7 +714,7 @@ error:
  *
  * Return pointer to structure or NULL.
  */
-struct ltt_kernel_metadata *trace_kernel_create_metadata(void)
+struct ltt_kernel_metadata *trace_kernel_create_metadata()
 {
        int ret;
        struct ltt_kernel_metadata *lkm;
@@ -737,16 +722,14 @@ struct ltt_kernel_metadata *trace_kernel_create_metadata(void)
 
        lkm = zmalloc<ltt_kernel_metadata>();
        chan = zmalloc<lttng_channel>();
-       if (lkm == NULL || chan == NULL) {
+       if (lkm == nullptr || chan == nullptr) {
                PERROR("kernel metadata zmalloc");
                goto error;
        }
 
-       ret = lttng_strncpy(
-                       chan->name, DEFAULT_METADATA_NAME, sizeof(chan->name));
+       ret = lttng_strncpy(chan->name, DEFAULT_METADATA_NAME, sizeof(chan->name));
        if (ret) {
-               ERR("Failed to initialize metadata channel name to `%s`",
-                               DEFAULT_METADATA_NAME);
+               ERR("Failed to initialize metadata channel name to `%s`", DEFAULT_METADATA_NAME);
                goto error;
        }
 
@@ -755,8 +738,8 @@ struct ltt_kernel_metadata *trace_kernel_create_metadata(void)
        chan->attr.subbuf_size = default_get_metadata_subbuf_size();
        chan->attr.num_subbuf = DEFAULT_METADATA_SUBBUF_NUM;
        chan->attr.switch_timer_interval = DEFAULT_METADATA_SWITCH_TIMER;
-       chan->attr.read_timer_interval = DEFAULT_METADATA_READ_TIMER;;
-
+       chan->attr.read_timer_interval = DEFAULT_METADATA_READ_TIMER;
+       ;
 
        /*
         * The metadata channel of kernel sessions must use the "mmap"
@@ -784,7 +767,7 @@ struct ltt_kernel_metadata *trace_kernel_create_metadata(void)
 error:
        free(lkm);
        free(chan);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -793,8 +776,7 @@ error:
  *
  * Return pointer to structure or NULL.
  */
-struct ltt_kernel_stream *trace_kernel_create_stream(const char *name,
-               unsigned int count)
+struct ltt_kernel_stream *trace_kernel_create_stream(const char *name, unsigned int count)
 {
        int ret;
        struct ltt_kernel_stream *lks;
@@ -802,7 +784,7 @@ struct ltt_kernel_stream *trace_kernel_create_stream(const char *name,
        LTTNG_ASSERT(name);
 
        lks = zmalloc<ltt_kernel_stream>();
-       if (lks == NULL) {
+       if (lks == nullptr) {
                PERROR("kernel stream zmalloc");
                goto error;
        }
@@ -823,7 +805,7 @@ struct ltt_kernel_stream *trace_kernel_create_stream(const char *name,
        return lks;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -884,25 +866,23 @@ void trace_kernel_destroy_event(struct ltt_kernel_event *event)
  */
 static void free_token_event_rule_rcu(struct rcu_head *rcu_node)
 {
-       struct ltt_kernel_event_notifier_rule *rule = caa_container_of(rcu_node,
-                       struct ltt_kernel_event_notifier_rule, rcu_node);
+       struct ltt_kernel_event_notifier_rule *rule =
+               caa_container_of(rcu_node, struct ltt_kernel_event_notifier_rule, rcu_node);
 
        free(rule);
 }
 
-void trace_kernel_destroy_event_notifier_rule(
-               struct ltt_kernel_event_notifier_rule *event)
+void trace_kernel_destroy_event_notifier_rule(struct ltt_kernel_event_notifier_rule *event)
 {
        LTTNG_ASSERT(event);
 
        if (event->fd >= 0) {
                const int ret = close(event->fd);
 
-               DBG("Closing kernel event notifier rule file descriptor: fd = %d",
-                               event->fd);
+               DBG("Closing kernel event notifier rule file descriptor: fd = %d", event->fd);
                if (ret) {
                        PERROR("Failed to close kernel event notifier file descriptor: fd = %d",
-                                       event->fd);
+                              event->fd);
                }
        } else {
                DBG("Destroying kernel event notifier rule (no associated file descriptor)");
@@ -947,28 +927,26 @@ void trace_kernel_destroy_channel(struct ltt_kernel_channel *channel)
        }
 
        /* For each stream in the channel list */
-       cds_list_for_each_entry_safe(stream, stmp, &channel->stream_list.head, list) {
+       cds_list_for_each_entry_safe (stream, stmp, &channel->stream_list.head, list) {
                trace_kernel_destroy_stream(stream);
        }
 
        /* For each event in the channel list */
-       cds_list_for_each_entry_safe(event, etmp, &channel->events_list.head, list) {
+       cds_list_for_each_entry_safe (event, etmp, &channel->events_list.head, list) {
                trace_kernel_destroy_event(event);
        }
 
        /* For each context in the channel list */
-       cds_list_for_each_entry_safe(ctx, ctmp, &channel->ctx_list, list) {
+       cds_list_for_each_entry_safe (ctx, ctmp, &channel->ctx_list, list) {
                trace_kernel_destroy_context(ctx);
        }
 
        /* Remove from channel list */
        cds_list_del(&channel->list);
 
-       if (the_notification_thread_handle &&
-                       channel->published_to_notification_thread) {
+       if (the_notification_thread_handle && channel->published_to_notification_thread) {
                status = notification_thread_command_remove_channel(
-                               the_notification_thread_handle, channel->key,
-                               LTTNG_DOMAIN_KERNEL);
+                       the_notification_thread_handle, channel->key, LTTNG_DOMAIN_KERNEL);
                LTTNG_ASSERT(status == LTTNG_OK);
        }
        free(channel->channel->attr.extended.ptr);
@@ -1025,11 +1003,11 @@ void trace_kernel_destroy_session(struct ltt_kernel_session *session)
                }
        }
 
-       if (session->metadata != NULL) {
+       if (session->metadata != nullptr) {
                trace_kernel_destroy_metadata(session->metadata);
        }
 
-       cds_list_for_each_entry_safe(channel, ctmp, &session->channel_list.head, list) {
+       cds_list_for_each_entry_safe (channel, ctmp, &session->channel_list.head, list) {
                trace_kernel_destroy_channel(channel);
        }
 }
index 50a58667ed88a7ad3f06f05aa6db51ebf96a62b7..265613ba81292caabcd59cc051a8764e15ebb459 100644 (file)
@@ -8,15 +8,16 @@
 #ifndef _LTT_TRACE_KERNEL_H
 #define _LTT_TRACE_KERNEL_H
 
-#include <urcu/list.h>
+#include "consumer.hpp"
+#include "tracker.hpp"
 
-#include <lttng/lttng.h>
-#include <common/lttng-kernel.hpp>
-#include <common/lttng-kernel-old.hpp>
 #include <common/defaults.hpp>
+#include <common/lttng-kernel-old.hpp>
+#include <common/lttng-kernel.hpp>
 
-#include "consumer.hpp"
-#include "tracker.hpp"
+#include <lttng/lttng.h>
+
+#include <urcu/list.h>
 
 /* Kernel event list */
 struct ltt_kernel_event_list {
@@ -43,7 +44,7 @@ struct ltt_kernel_context {
 /* Kernel event */
 struct ltt_kernel_event {
        int fd;
-       int enabled;
+       bool enabled;
        enum lttng_event_type type;
        struct lttng_kernel_abi_event *event;
        struct cds_list_head list;
@@ -56,7 +57,7 @@ struct ltt_kernel_event {
 struct ltt_kernel_event_notifier_rule {
        int fd;
        uint64_t error_counter_index;
-       int enabled;
+       bool enabled;
        enum lttng_event_type type;
        struct lttng_trigger *trigger;
        uint64_t token;
@@ -71,7 +72,7 @@ struct ltt_kernel_event_notifier_rule {
 struct ltt_kernel_channel {
        int fd;
        uint64_t key; /* Key to reference this channel with the consumer. */
-       int enabled;
+       bool enabled;
        unsigned int stream_count;
        unsigned int event_count;
        bool published_to_notification_thread;
@@ -121,7 +122,7 @@ struct ltt_kernel_session {
        /* Tracing session id */
        uint64_t id;
        /* Session is active or not meaning it has been started or stopped. */
-       unsigned int active:1;
+       bool active;
        /* Tell or not if the session has to output the traces. */
        unsigned int output_traces;
        unsigned int snapshot_mode;
@@ -141,41 +142,38 @@ struct ltt_kernel_session {
 /*
  * Lookup functions. NULL is returned if not found.
  */
-struct ltt_kernel_event *trace_kernel_get_event_by_name(
-               char *name, struct ltt_kernel_channel *channel,
-               enum lttng_event_type type);
-struct ltt_kernel_event *trace_kernel_find_event(
-               char *name, struct ltt_kernel_channel *channel,
-               enum lttng_event_type type,
-               struct lttng_bytecode *filter);
-struct ltt_kernel_channel *trace_kernel_get_channel_by_name(
-               const char *name, struct ltt_kernel_session *session);
+struct ltt_kernel_event *trace_kernel_get_event_by_name(char *name,
+                                                       struct ltt_kernel_channel *channel,
+                                                       enum lttng_event_type type);
+struct ltt_kernel_event *trace_kernel_find_event(char *name,
+                                                struct ltt_kernel_channel *channel,
+                                                enum lttng_event_type type,
+                                                struct lttng_bytecode *filter);
+struct ltt_kernel_channel *trace_kernel_get_channel_by_name(const char *name,
+                                                           struct ltt_kernel_session *session);
 
 /*
  * Create functions malloc() the data structure.
  */
-struct ltt_kernel_session *trace_kernel_create_session(void);
-struct ltt_kernel_channel *trace_kernel_create_channel(
-               struct lttng_channel *chan);
+struct ltt_kernel_session *trace_kernel_create_session();
+struct ltt_kernel_channel *trace_kernel_create_channel(struct lttng_channel *chan);
 enum lttng_error_code trace_kernel_create_event(struct lttng_event *ev,
-               char *filter_expression, struct lttng_bytecode *filter,
-               struct ltt_kernel_event **kernel_event);
-struct ltt_kernel_metadata *trace_kernel_create_metadata(void);
-struct ltt_kernel_stream *trace_kernel_create_stream(const char *name,
-               unsigned int count);
-struct ltt_kernel_context *trace_kernel_create_context(
-               struct lttng_kernel_abi_context *ctx);
+                                               char *filter_expression,
+                                               struct lttng_bytecode *filter,
+                                               struct ltt_kernel_event **kernel_event);
+struct ltt_kernel_metadata *trace_kernel_create_metadata();
+struct ltt_kernel_stream *trace_kernel_create_stream(const char *name, unsigned int count);
+struct ltt_kernel_context *trace_kernel_create_context(struct lttng_kernel_abi_context *ctx);
 /* Trigger is only non-const to acquire a reference. */
 enum lttng_error_code trace_kernel_create_event_notifier_rule(
-               struct lttng_trigger *trigger,
-               uint64_t token,
-               uint64_t error_counter_index,
-               struct ltt_kernel_event_notifier_rule **event_notifier_rule);
-struct ltt_kernel_context *trace_kernel_copy_context(
-               struct ltt_kernel_context *ctx);
+       struct lttng_trigger *trigger,
+       uint64_t token,
+       uint64_t error_counter_index,
+       struct ltt_kernel_event_notifier_rule **event_notifier_rule);
+struct ltt_kernel_context *trace_kernel_copy_context(struct ltt_kernel_context *ctx);
 enum lttng_error_code trace_kernel_init_event_notifier_from_event_rule(
-               const struct lttng_event_rule *rule,
-               struct lttng_kernel_abi_event_notifier *kernel_event_notifier);
+       const struct lttng_event_rule *rule,
+       struct lttng_kernel_abi_event_notifier *kernel_event_notifier);
 
 /*
  * Destroy functions free() the data structure and remove from linked list if
index 4a3e74de7792b8bc0b195b98f8bc15d9db9e5a10..e4fdef9ad159d686b1f3bd4f84fa453e7438c8ce 100644 (file)
@@ -7,22 +7,23 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <inttypes.h>
+#include "agent.hpp"
+#include "buffer-registry.hpp"
+#include "trace-ust.hpp"
+#include "ust-app.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/defaults.hpp>
 #include <common/trace-chunk.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
 
-#include "buffer-registry.hpp"
-#include "trace-ust.hpp"
-#include "utils.hpp"
-#include "ust-app.hpp"
-#include "agent.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
 namespace lsu = lttng::sessiond::ust;
 
@@ -31,8 +32,7 @@ namespace lsu = lttng::sessiond::ust;
  *
  * Matches by name only. Used by the disable command.
  */
-int trace_ust_ht_match_event_by_name(struct cds_lfht_node *node,
-               const void *_key)
+int trace_ust_ht_match_event_by_name(struct cds_lfht_node *node, const void *_key)
 {
        struct ltt_ust_event *event;
        const char *name;
@@ -84,8 +84,10 @@ int trace_ust_ht_match_event(struct cds_lfht_node *node, const void *_key)
 
        /* Event loglevel value and type. */
        ll_match = loglevels_match(event->attr.loglevel_type,
-               ev_loglevel_value, key->loglevel_type,
-               key->loglevel_value, LTTNG_UST_ABI_LOGLEVEL_ALL);
+                                  ev_loglevel_value,
+                                  key->loglevel_type,
+                                  key->loglevel_value,
+                                  LTTNG_UST_ABI_LOGLEVEL_ALL);
 
        if (!ll_match) {
                goto no_match;
@@ -99,8 +101,7 @@ int trace_ust_ht_match_event(struct cds_lfht_node *node, const void *_key)
        if (key->filter && event->filter) {
                /* Both filters exists, check length followed by the bytecode. */
                if (event->filter->len != key->filter->len ||
-                               memcmp(event->filter->data, key->filter->data,
-                                       event->filter->len) != 0) {
+                   memcmp(event->filter->data, key->filter->data, event->filter->len) != 0) {
                        goto no_match;
                }
        }
@@ -121,10 +122,8 @@ int trace_ust_ht_match_event(struct cds_lfht_node *node, const void *_key)
                /* Compare names individually. */
                for (i = 0; i < event->exclusion->count; ++i) {
                        size_t j;
-                       bool found = false;
-                       const char *name_ev =
-                               LTTNG_EVENT_EXCLUSION_NAME_AT(
-                                       event->exclusion, i);
+                       bool found = false;
+                       const char *name_ev = LTTNG_EVENT_EXCLUSION_NAME_AT(event->exclusion, i);
 
                        /*
                         * Compare this exclusion name to all the key's
@@ -132,11 +131,9 @@ int trace_ust_ht_match_event(struct cds_lfht_node *node, const void *_key)
                         */
                        for (j = 0; j < key->exclusion->count; ++j) {
                                const char *name_key =
-                                       LTTNG_EVENT_EXCLUSION_NAME_AT(
-                                               key->exclusion, j);
+                                       LTTNG_EVENT_EXCLUSION_NAME_AT(key->exclusion, j);
 
-                               if (!strncmp(name_ev, name_key,
-                                               LTTNG_SYMBOL_NAME_LEN)) {
+                               if (!strncmp(name_ev, name_key, LTTNG_SYMBOL_NAME_LEN)) {
                                        /* Names match! */
                                        found = true;
                                        break;
@@ -163,8 +160,7 @@ no_match:
  * Find the channel in the hashtable and return channel pointer. RCU read side
  * lock MUST be acquired before calling this.
  */
-struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht,
-               const char *name)
+struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht, const char *name)
 {
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
@@ -177,9 +173,9 @@ struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht,
        if (name[0] == '\0')
                name = DEFAULT_CHANNEL_NAME;
 
-       lttng_ht_lookup(ht, (void *)name, &iter);
+       lttng_ht_lookup(ht, (void *) name, &iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto error;
        }
 
@@ -189,7 +185,7 @@ struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht,
 
 error:
        DBG2("Trace UST channel %s not found by name", name);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -197,9 +193,11 @@ error:
  * MUST be acquired before calling this.
  */
 struct ltt_ust_event *trace_ust_find_event(struct lttng_ht *ht,
-               char *name, struct lttng_bytecode *filter,
-               enum lttng_ust_abi_loglevel_type loglevel_type, int loglevel_value,
-               struct lttng_event_exclusion *exclusion)
+                                          char *name,
+                                          struct lttng_bytecode *filter,
+                                          enum lttng_ust_abi_loglevel_type loglevel_type,
+                                          int loglevel_value,
+                                          struct lttng_event_exclusion *exclusion)
 {
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
@@ -215,10 +213,13 @@ struct ltt_ust_event *trace_ust_find_event(struct lttng_ht *ht,
        key.loglevel_value = loglevel_value;
        key.exclusion = exclusion;
 
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) name, lttng_ht_seed),
-                       trace_ust_ht_match_event, &key, &iter.iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) name, lttng_ht_seed),
+                       trace_ust_ht_match_event,
+                       &key,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto error;
        }
 
@@ -228,7 +229,7 @@ struct ltt_ust_event *trace_ust_find_event(struct lttng_ht *ht,
 
 error:
        DBG2("Trace UST event %s NOT found", key.name);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -239,9 +240,9 @@ error:
  * once the agent is no longer in scope or being used.
  */
 struct agent *trace_ust_find_agent(struct ltt_ust_session *session,
-               enum lttng_domain_type domain_type)
+                                  enum lttng_domain_type domain_type)
 {
-       struct agent *agt = NULL;
+       struct agent *agt = nullptr;
        struct lttng_ht_node_u64 *node;
        struct lttng_ht_iter iter;
        uint64_t key;
@@ -274,7 +275,7 @@ struct ltt_ust_session *trace_ust_create_session(uint64_t session_id)
 
        /* Allocate a new ltt ust session */
        lus = zmalloc<ltt_ust_session>();
-       if (lus == NULL) {
+       if (lus == nullptr) {
                PERROR("create ust session zmalloc");
                goto error_alloc;
        }
@@ -321,7 +322,7 @@ struct ltt_ust_session *trace_ust_create_session(uint64_t session_id)
                goto error;
        }
        lus->consumer = consumer_create_output(CONSUMER_DST_LOCAL);
-       if (lus->consumer == NULL) {
+       if (lus->consumer == nullptr) {
                goto error;
        }
 
@@ -337,7 +338,7 @@ error:
        lttng_ht_destroy(lus->agents);
        free(lus);
 error_alloc:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -346,14 +347,14 @@ error_alloc:
  * Return pointer to structure or NULL.
  */
 struct ltt_ust_channel *trace_ust_create_channel(struct lttng_channel *chan,
-               enum lttng_domain_type domain)
+                                                enum lttng_domain_type domain)
 {
        struct ltt_ust_channel *luc;
 
        LTTNG_ASSERT(chan);
 
        luc = zmalloc<ltt_ust_channel>();
-       if (luc == NULL) {
+       if (luc == nullptr) {
                PERROR("ltt_ust_channel zmalloc");
                goto error;
        }
@@ -367,10 +368,10 @@ struct ltt_ust_channel *trace_ust_create_channel(struct lttng_channel *chan,
        luc->attr.switch_timer_interval = chan->attr.switch_timer_interval;
        luc->attr.read_timer_interval = chan->attr.read_timer_interval;
        luc->attr.output = (enum lttng_ust_abi_output) chan->attr.output;
-       luc->monitor_timer_interval = ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->monitor_timer_interval;
-       luc->attr.u.s.blocking_timeout = ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->blocking_timeout;
+       luc->monitor_timer_interval =
+               ((struct lttng_channel_extended *) chan->attr.extended.ptr)->monitor_timer_interval;
+       luc->attr.u.s.blocking_timeout =
+               ((struct lttng_channel_extended *) chan->attr.extended.ptr)->blocking_timeout;
 
        /* Translate to UST output enum */
        switch (luc->attr.output) {
@@ -423,12 +424,10 @@ static int validate_exclusion(struct lttng_event_exclusion *exclusion)
 
        for (i = 0; i < exclusion->count; ++i) {
                size_t j;
-               const char *name_a =
-                       LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, i);
+               const char *name_a = LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, i);
 
                for (j = 0; j < i; ++j) {
-                       const char *name_b =
-                               LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, j);
+                       const char *name_b = LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, j);
 
                        if (!strncmp(name_a, name_b, LTTNG_SYMBOL_NAME_LEN)) {
                                /* Match! */
@@ -449,11 +448,11 @@ end:
  * Return an lttng_error_code
  */
 enum lttng_error_code trace_ust_create_event(struct lttng_event *ev,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               bool internal_event,
-               struct ltt_ust_event **ust_event)
+                                            char *filter_expression,
+                                            struct lttng_bytecode *filter,
+                                            struct lttng_event_exclusion *exclusion,
+                                            bool internal_event,
+                                            struct ltt_ust_event **ust_event)
 {
        struct ltt_ust_event *local_ust_event;
        enum lttng_error_code ret = LTTNG_OK;
@@ -466,7 +465,7 @@ enum lttng_error_code trace_ust_create_event(struct lttng_event *ev,
        }
 
        local_ust_event = zmalloc<ltt_ust_event>();
-       if (local_ust_event == NULL) {
+       if (local_ust_event == nullptr) {
                PERROR("ust event zmalloc");
                ret = LTTNG_ERR_NOMEM;
                goto error;
@@ -500,7 +499,7 @@ enum lttng_error_code trace_ust_create_event(struct lttng_event *ev,
        switch (ev->loglevel_type) {
        case LTTNG_EVENT_LOGLEVEL_ALL:
                local_ust_event->attr.loglevel_type = LTTNG_UST_ABI_LOGLEVEL_ALL;
-               local_ust_event->attr.loglevel = -1;    /* Force to -1 */
+               local_ust_event->attr.loglevel = -1; /* Force to -1 */
                break;
        case LTTNG_EVENT_LOGLEVEL_RANGE:
                local_ust_event->attr.loglevel_type = LTTNG_UST_ABI_LOGLEVEL_RANGE;
@@ -525,8 +524,9 @@ enum lttng_error_code trace_ust_create_event(struct lttng_event *ev,
        lttng_ht_node_init_str(&local_ust_event->node, local_ust_event->attr.name);
 
        DBG2("Trace UST event %s, loglevel (%d,%d) created",
-               local_ust_event->attr.name, local_ust_event->attr.loglevel_type,
-               local_ust_event->attr.loglevel);
+            local_ust_event->attr.name,
+            local_ust_event->attr.loglevel_type,
+            local_ust_event->attr.loglevel);
 
        *ust_event = local_ust_event;
 
@@ -541,9 +541,7 @@ error:
        return ret;
 }
 
-static
-int trace_ust_context_type_event_to_ust(
-               enum lttng_event_context_type type)
+static int trace_ust_context_type_event_to_ust(enum lttng_event_context_type type)
 {
        int utype;
 
@@ -627,7 +625,7 @@ int trace_ust_context_type_event_to_ust(
  * Return 1 if contexts match, 0 otherwise.
  */
 int trace_ust_match_context(const struct ltt_ust_context *uctx,
-               const struct lttng_event_context *ctx)
+                           const struct lttng_event_context *ctx)
 {
        int utype;
 
@@ -640,32 +638,27 @@ int trace_ust_match_context(const struct ltt_ust_context *uctx,
        }
        switch (utype) {
        case LTTNG_UST_ABI_CONTEXT_PERF_THREAD_COUNTER:
-               if (uctx->ctx.u.perf_counter.type
-                               != ctx->u.perf_counter.type) {
+               if (uctx->ctx.u.perf_counter.type != ctx->u.perf_counter.type) {
                        return 0;
                }
-               if (uctx->ctx.u.perf_counter.config
-                               != ctx->u.perf_counter.config) {
+               if (uctx->ctx.u.perf_counter.config != ctx->u.perf_counter.config) {
                        return 0;
                }
                if (strncmp(uctx->ctx.u.perf_counter.name,
-                               ctx->u.perf_counter.name,
-                               LTTNG_UST_ABI_SYM_NAME_LEN)) {
+                           ctx->u.perf_counter.name,
+                           LTTNG_UST_ABI_SYM_NAME_LEN) != 0) {
                        return 0;
                }
                break;
        case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT:
                LTTNG_ASSERT(uctx->ctx.u.app_ctx.provider_name);
                LTTNG_ASSERT(uctx->ctx.u.app_ctx.ctx_name);
-               if (strcmp(uctx->ctx.u.app_ctx.provider_name,
-                               ctx->u.app_ctx.provider_name) ||
-                               strcmp(uctx->ctx.u.app_ctx.ctx_name,
-                               ctx->u.app_ctx.ctx_name)) {
+               if (strcmp(uctx->ctx.u.app_ctx.provider_name, ctx->u.app_ctx.provider_name) != 0 ||
+                   strcmp(uctx->ctx.u.app_ctx.ctx_name, ctx->u.app_ctx.ctx_name) != 0) {
                        return 0;
                }
        default:
                break;
-
        }
        return 1;
 }
@@ -675,10 +668,9 @@ int trace_ust_match_context(const struct ltt_ust_context *uctx,
  *
  * Return pointer to structure or NULL.
  */
-struct ltt_ust_context *trace_ust_create_context(
-               const struct lttng_event_context *ctx)
+struct ltt_ust_context *trace_ust_create_context(const struct lttng_event_context *ctx)
 {
-       struct ltt_ust_context *uctx = NULL;
+       struct ltt_ust_context *uctx = nullptr;
        int utype;
 
        LTTNG_ASSERT(ctx);
@@ -700,13 +692,14 @@ struct ltt_ust_context *trace_ust_create_context(
        case LTTNG_UST_ABI_CONTEXT_PERF_THREAD_COUNTER:
                uctx->ctx.u.perf_counter.type = ctx->u.perf_counter.type;
                uctx->ctx.u.perf_counter.config = ctx->u.perf_counter.config;
-               strncpy(uctx->ctx.u.perf_counter.name, ctx->u.perf_counter.name,
-                               LTTNG_UST_ABI_SYM_NAME_LEN);
+               strncpy(uctx->ctx.u.perf_counter.name,
+                       ctx->u.perf_counter.name,
+                       LTTNG_UST_ABI_SYM_NAME_LEN);
                uctx->ctx.u.perf_counter.name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] = '\0';
                break;
        case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT:
        {
-               char *provider_name = NULL, *ctx_name = NULL;
+               char *provider_name = nullptr, *ctx_name = nullptr;
 
                provider_name = strdup(ctx->u.app_ctx.provider_name);
                if (!provider_name) {
@@ -729,13 +722,13 @@ end:
        return uctx;
 error:
        trace_ust_destroy_context(uctx);
-       return NULL;
+       return nullptr;
 }
 
 static void destroy_id_tracker_node_rcu(struct rcu_head *head)
 {
-       struct ust_id_tracker_node *tracker_node = caa_container_of(
-                       head, struct ust_id_tracker_node, node.head);
+       struct ust_id_tracker_node *tracker_node =
+               caa_container_of(head, struct ust_id_tracker_node, node.head);
        free(tracker_node);
 }
 
@@ -769,23 +762,24 @@ static void fini_id_tracker(struct ust_id_tracker *id_tracker)
        if (!id_tracker->ht) {
                return;
        }
-       rcu_read_lock();
-       cds_lfht_for_each_entry (id_tracker->ht->ht, &iter.iter, tracker_node,
-                       node.node) {
-               int ret = lttng_ht_del(id_tracker->ht, &iter);
 
-               LTTNG_ASSERT(!ret);
-               destroy_id_tracker_node(tracker_node);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (id_tracker->ht->ht, &iter.iter, tracker_node, node.node) {
+                       int ret = lttng_ht_del(id_tracker->ht, &iter);
+
+                       LTTNG_ASSERT(!ret);
+                       destroy_id_tracker_node(tracker_node);
+               }
        }
-       rcu_read_unlock();
+
        lttng_ht_destroy(id_tracker->ht);
-       id_tracker->ht = NULL;
+       id_tracker->ht = nullptr;
 }
 
-static struct ust_id_tracker_node *id_tracker_lookup(
-               struct ust_id_tracker *id_tracker,
-               int id,
-               struct lttng_ht_iter *iter)
+static struct ust_id_tracker_node *
+id_tracker_lookup(struct ust_id_tracker *id_tracker, int id, struct lttng_ht_iter *iter)
 {
        unsigned long _id = (unsigned long) id;
        struct lttng_ht_node_ulong *node;
@@ -795,7 +789,7 @@ static struct ust_id_tracker_node *id_tracker_lookup(
        if (node) {
                return lttng::utils::container_of(node, &ust_id_tracker_node::node);
        } else {
-               return NULL;
+               return nullptr;
        }
 }
 
@@ -851,7 +845,7 @@ end:
 }
 
 static struct ust_id_tracker *get_id_tracker(struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr)
+                                            enum lttng_process_attr process_attr)
 {
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
@@ -861,13 +855,13 @@ static struct ust_id_tracker *get_id_tracker(struct ltt_ust_session *session,
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                return &session->vgid_tracker;
        default:
-               return NULL;
+               return nullptr;
        }
 }
 
-static struct process_attr_tracker *_trace_ust_get_process_attr_tracker(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr)
+static struct process_attr_tracker *
+_trace_ust_get_process_attr_tracker(struct ltt_ust_session *session,
+                                   enum lttng_process_attr process_attr)
 {
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
@@ -877,25 +871,24 @@ static struct process_attr_tracker *_trace_ust_get_process_attr_tracker(
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                return session->tracker_vgid;
        default:
-               return NULL;
+               return nullptr;
        }
 }
 
-const struct process_attr_tracker *trace_ust_get_process_attr_tracker(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr)
+const struct process_attr_tracker *
+trace_ust_get_process_attr_tracker(struct ltt_ust_session *session,
+                                  enum lttng_process_attr process_attr)
 {
-       return (const struct process_attr_tracker *)
-                       _trace_ust_get_process_attr_tracker(
-                                       session, process_attr);
+       return (const struct process_attr_tracker *) _trace_ust_get_process_attr_tracker(
+               session, process_attr);
 }
 
 /*
  * The session lock is held when calling this function.
  */
 int trace_ust_id_tracker_lookup(enum lttng_process_attr process_attr,
-               struct ltt_ust_session *session,
-               int id)
+                               struct ltt_ust_session *session,
+                               int id)
 {
        struct lttng_ht_iter iter;
        struct ust_id_tracker *id_tracker;
@@ -916,18 +909,16 @@ int trace_ust_id_tracker_lookup(enum lttng_process_attr process_attr,
 /*
  * Called with the session lock held.
  */
-enum lttng_error_code trace_ust_process_attr_tracker_set_tracking_policy(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy)
+enum lttng_error_code
+trace_ust_process_attr_tracker_set_tracking_policy(struct ltt_ust_session *session,
+                                                  enum lttng_process_attr process_attr,
+                                                  enum lttng_tracking_policy policy)
 {
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
-       struct ust_id_tracker *id_tracker =
-                       get_id_tracker(session, process_attr);
+       struct ust_id_tracker *id_tracker = get_id_tracker(session, process_attr);
        struct process_attr_tracker *tracker =
-                       _trace_ust_get_process_attr_tracker(
-                                       session, process_attr);
+               _trace_ust_get_process_attr_tracker(session, process_attr);
        bool should_update_apps = false;
        enum lttng_tracking_policy previous_policy;
 
@@ -979,15 +970,14 @@ end:
 }
 
 /* Called with the session lock held. */
-enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+trace_ust_process_attr_tracker_inclusion_set_add_value(struct ltt_ust_session *session,
+                                                      enum lttng_process_attr process_attr,
+                                                      const struct process_attr_value *value)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
        bool should_update_apps = false;
-       struct ust_id_tracker *id_tracker =
-                       get_id_tracker(session, process_attr);
+       struct ust_id_tracker *id_tracker = get_id_tracker(session, process_attr);
        struct process_attr_tracker *tracker;
        int integral_value;
        enum process_attr_tracker_status status;
@@ -1007,8 +997,7 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME) {
                        uid_t uid;
 
-                       ret_code = utils_user_id_from_name(
-                                       value->value.user_name, &uid);
+                       ret_code = utils_user_id_from_name(value->value.user_name, &uid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1022,8 +1011,7 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME) {
                        gid_t gid;
 
-                       ret_code = utils_group_id_from_name(
-                                       value->value.group_name, &gid);
+                       ret_code = utils_group_id_from_name(value->value.group_name, &gid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1061,8 +1049,9 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
        }
 
        DBG("User space track %s %d for session id %" PRIu64,
-                       lttng_process_attr_to_string(process_attr),
-                       integral_value, session->id);
+           lttng_process_attr_to_string(process_attr),
+           integral_value,
+           session->id);
 
        ret_code = (lttng_error_code) id_tracker_add_id(id_tracker, integral_value);
        if (ret_code != LTTNG_OK) {
@@ -1088,15 +1077,14 @@ end:
 }
 
 /* Called with the session lock held. */
-enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value)
+enum lttng_error_code
+trace_ust_process_attr_tracker_inclusion_set_remove_value(struct ltt_ust_session *session,
+                                                         enum lttng_process_attr process_attr,
+                                                         const struct process_attr_value *value)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
        bool should_update_apps = false;
-       struct ust_id_tracker *id_tracker =
-                       get_id_tracker(session, process_attr);
+       struct ust_id_tracker *id_tracker = get_id_tracker(session, process_attr);
        struct process_attr_tracker *tracker;
        int integral_value;
        enum process_attr_tracker_status status;
@@ -1116,8 +1104,7 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME) {
                        uid_t uid;
 
-                       ret_code = utils_user_id_from_name(
-                                       value->value.user_name, &uid);
+                       ret_code = utils_user_id_from_name(value->value.user_name, &uid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1131,8 +1118,7 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
                if (value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME) {
                        gid_t gid;
 
-                       ret_code = utils_group_id_from_name(
-                                       value->value.group_name, &gid);
+                       ret_code = utils_group_id_from_name(value->value.group_name, &gid);
                        if (ret_code != LTTNG_OK) {
                                goto end;
                        }
@@ -1152,8 +1138,7 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
                goto end;
        }
 
-       status = process_attr_tracker_inclusion_set_remove_value(
-                       tracker, value);
+       status = process_attr_tracker_inclusion_set_remove_value(tracker, value);
        if (status != PROCESS_ATTR_TRACKER_STATUS_OK) {
                switch (status) {
                case PROCESS_ATTR_TRACKER_STATUS_MISSING:
@@ -1171,8 +1156,9 @@ enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
        }
 
        DBG("User space untrack %s %d for session id %" PRIu64,
-                       lttng_process_attr_to_string(process_attr),
-                       integral_value, session->id);
+           lttng_process_attr_to_string(process_attr),
+           integral_value,
+           session->id);
 
        ret_code = (lttng_error_code) id_tracker_del_id(id_tracker, integral_value);
        if (ret_code != LTTNG_OK) {
@@ -1204,8 +1190,7 @@ static void destroy_context_rcu(struct rcu_head *head)
 {
        struct lttng_ht_node_ulong *node =
                lttng::utils::container_of(head, &lttng_ht_node_ulong::head);
-       struct ltt_ust_context *ctx =
-               lttng::utils::container_of(node, &ltt_ust_context::node);
+       struct ltt_ust_context *ctx = lttng::utils::container_of(node, &ltt_ust_context::node);
 
        trace_ust_destroy_context(ctx);
 }
@@ -1222,18 +1207,20 @@ static void destroy_contexts(struct lttng_ht *ht)
 
        LTTNG_ASSERT(ht);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, node, node) {
-               /* Remove from ordered list. */
-               ctx = lttng::utils::container_of(node, &ltt_ust_context::node);
-               cds_list_del(&ctx->list);
-               /* Remove from channel's hash table. */
-               ret = lttng_ht_del(ht, &iter);
-               if (!ret) {
-                       call_rcu(&node->head, destroy_context_rcu);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, node, node) {
+                       /* Remove from ordered list. */
+                       ctx = lttng::utils::container_of(node, &ltt_ust_context::node);
+                       cds_list_del(&ctx->list);
+                       /* Remove from channel's hash table. */
+                       ret = lttng_ht_del(ht, &iter);
+                       if (!ret) {
+                               call_rcu(&node->head, destroy_context_rcu);
+                       }
                }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(ht);
 }
@@ -1271,10 +1258,8 @@ void trace_ust_destroy_context(struct ltt_ust_context *ctx)
  */
 static void destroy_event_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_str *node =
-               lttng::utils::container_of(head, &lttng_ht_node_str::head);
-       struct ltt_ust_event *event =
-               lttng::utils::container_of(node, &ltt_ust_event::node);
+       struct lttng_ht_node_str *node = lttng::utils::container_of(head, &lttng_ht_node_str::head);
+       struct ltt_ust_event *event = lttng::utils::container_of(node, &ltt_ust_event::node);
 
        trace_ust_destroy_event(event);
 }
@@ -1290,13 +1275,15 @@ static void destroy_events(struct lttng_ht *events)
 
        LTTNG_ASSERT(events);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(events->ht, &iter.iter, node, node) {
-               ret = lttng_ht_del(events, &iter);
-               LTTNG_ASSERT(!ret);
-               call_rcu(&node->head, destroy_event_rcu);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (events->ht, &iter.iter, node, node) {
+                       ret = lttng_ht_del(events, &iter);
+                       LTTNG_ASSERT(!ret);
+                       call_rcu(&node->head, destroy_event_rcu);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(events);
 }
@@ -1320,10 +1307,8 @@ static void _trace_ust_destroy_channel(struct ltt_ust_channel *channel)
  */
 static void destroy_channel_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_str *node =
-               lttng::utils::container_of(head, &lttng_ht_node_str::head);
-       struct ltt_ust_channel *channel =
-               lttng::utils::container_of(node, &ltt_ust_channel::node);
+       struct lttng_ht_node_str *node = lttng::utils::container_of(head, &lttng_ht_node_str::head);
+       struct ltt_ust_channel *channel = lttng::utils::container_of(node, &ltt_ust_channel::node);
 
        _trace_ust_destroy_channel(channel);
 }
@@ -1341,8 +1326,7 @@ void trace_ust_destroy_channel(struct ltt_ust_channel *channel)
 /*
  * Remove an UST channel from a channel HT.
  */
-void trace_ust_delete_channel(struct lttng_ht *ht,
-               struct ltt_ust_channel *channel)
+void trace_ust_delete_channel(struct lttng_ht *ht, struct ltt_ust_channel *channel)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -1358,11 +1342,11 @@ void trace_ust_delete_channel(struct lttng_ht *ht,
 int trace_ust_regenerate_metadata(struct ltt_ust_session *usess)
 {
        int ret = 0;
-       struct buffer_reg_uid *uid_reg = NULL;
-       struct buffer_reg_session *session_reg = NULL;
+       struct buffer_reg_uid *uid_reg = nullptr;
+       struct buffer_reg_session *session_reg = nullptr;
 
-       rcu_read_lock();
-       cds_list_for_each_entry(uid_reg, &usess->buffer_reg_uid_list, lnode) {
+       lttng::urcu::read_lock_guard read_lock;
+       cds_list_for_each_entry (uid_reg, &usess->buffer_reg_uid_list, lnode) {
                lsu::registry_session *registry;
 
                session_reg = uid_reg->registry;
@@ -1378,7 +1362,6 @@ int trace_ust_regenerate_metadata(struct ltt_ust_session *usess)
        }
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -1392,15 +1375,17 @@ static void destroy_channels(struct lttng_ht *channels)
 
        LTTNG_ASSERT(channels);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(channels->ht, &iter.iter, node, node) {
-               struct ltt_ust_channel *chan =
-                       lttng::utils::container_of(node, &ltt_ust_channel::node);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (channels->ht, &iter.iter, node, node) {
+                       struct ltt_ust_channel *chan =
+                               lttng::utils::container_of(node, &ltt_ust_channel::node);
 
-               trace_ust_delete_channel(channels, chan);
-               trace_ust_destroy_channel(chan);
+                       trace_ust_delete_channel(channels, chan);
+                       trace_ust_destroy_channel(chan);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(channels);
 }
@@ -1432,20 +1417,21 @@ void trace_ust_destroy_session(struct ltt_ust_session *session)
        /* Cleaning up UST domain */
        destroy_domain_global(&session->domain_global);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(session->agents->ht, &iter.iter, agt, node.node) {
-               int ret = lttng_ht_del(session->agents, &iter);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (session->agents->ht, &iter.iter, agt, node.node) {
+                       int ret = lttng_ht_del(session->agents, &iter);
 
-               LTTNG_ASSERT(!ret);
-               agent_destroy(agt);
+                       LTTNG_ASSERT(!ret);
+                       agent_destroy(agt);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(session->agents);
 
        /* Cleanup UID buffer registry object(s). */
-       cds_list_for_each_entry_safe(reg, sreg, &session->buffer_reg_uid_list,
-                       lnode) {
+       cds_list_for_each_entry_safe (reg, sreg, &session->buffer_reg_uid_list, lnode) {
                cds_list_del(&reg->lnode);
                buffer_reg_uid_remove(reg);
                buffer_reg_uid_destroy(reg, session->consumer);
index 38662ec5888de3fc8d6381fe5afea1c9716de25d..ea84722f1dbe407ff0777c1335bd8e1670de9330 100644 (file)
@@ -9,16 +9,17 @@
 #ifndef _LTT_TRACE_UST_H
 #define _LTT_TRACE_UST_H
 
-#include <limits.h>
-#include <urcu/list.h>
+#include "consumer.hpp"
+#include "lttng-ust-ctl.hpp"
 
 #include <common/defaults.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/tracker.hpp>
+
 #include <lttng/lttng.h>
 
-#include "consumer.hpp"
-#include "lttng-ust-ctl.hpp"
+#include <limits.h>
+#include <urcu/list.h>
 
 struct agent;
 
@@ -39,7 +40,7 @@ struct ltt_ust_context {
 
 /* UST event */
 struct ltt_ust_event {
-       unsigned int enabled;
+       bool enabled;
        struct lttng_ust_abi_event attr;
        struct lttng_ht_node_str node;
        char *filter_expression;
@@ -56,8 +57,8 @@ struct ltt_ust_event {
 
 /* UST channel */
 struct ltt_ust_channel {
-       uint64_t id;    /* unique id per session. */
-       unsigned int enabled;
+       uint64_t id; /* unique id per session. */
+       bool enabled;
        /*
         * A UST channel can be part of a userspace sub-domain such as JUL,
         * Log4j, Python.
@@ -92,7 +93,7 @@ struct ust_id_tracker {
 
 /* UST session */
 struct ltt_ust_session {
-       uint64_t id;    /* Unique identifier of session */
+       uint64_t id; /* Unique identifier of session */
        struct ltt_ust_domain_global domain_global;
        /* Hash table of agent indexed by agent domain. */
        struct lttng_ht *agents;
@@ -100,7 +101,7 @@ struct ltt_ust_session {
        uid_t uid;
        gid_t gid;
        /* Is the session active meaning has is been started or stopped. */
-       unsigned int active:1;
+       bool active;
        struct consumer_output *consumer;
        /* Sequence number for filters so the tracer knows the ordering. */
        uint64_t filter_seq_num;
@@ -111,14 +112,14 @@ struct ltt_ust_session {
        /* For per UID buffer, every buffer reg object is kept of this session */
        struct cds_list_head buffer_reg_uid_list;
        /* Next channel ID available for a newly registered channel. */
-       uint64_t next_channel_id;
-       /* Once this value reaches UINT32_MAX, no more id can be allocated. */
-       uint64_t used_channel_id;
+       uint64_t next_event_container_id;
+       /* Once this value reaches UINT64_MAX, no more id can be allocated. */
+       uint64_t used_event_container_id;
        /* Tell or not if the session has to output the traces. */
        unsigned int output_traces;
        unsigned int snapshot_mode;
        unsigned int has_non_default_channel;
-       unsigned int live_timer_interval;       /* usec */
+       unsigned int live_timer_interval; /* usec */
 
        /* Metadata channel attributes. */
        struct lttng_ust_abi_channel_attr metadata_attr;
@@ -159,55 +160,54 @@ static inline int trace_ust_is_max_id(uint64_t id)
  * the maximum number of IDs have been reached. If not, it is safe to call this
  * function.
  *
- * Return a unique channel ID. If max is reached, the used_channel_id counter
+ * Return a unique channel ID. If max is reached, the used_event_container_id counter
  * is returned.
  */
-static inline uint64_t trace_ust_get_next_chan_id(struct ltt_ust_session *s)
+static inline uint64_t trace_ust_get_next_event_container_id(struct ltt_ust_session *s)
 {
-       if (trace_ust_is_max_id(s->used_channel_id)) {
-               return s->used_channel_id;
+       if (trace_ust_is_max_id(s->used_event_container_id)) {
+               return s->used_event_container_id;
        }
 
-       s->used_channel_id++;
-       return s->next_channel_id++;
+       s->used_event_container_id++;
+       return s->next_event_container_id++;
 }
 
 #ifdef HAVE_LIBLTTNG_UST_CTL
 
 int trace_ust_ht_match_event(struct cds_lfht_node *node, const void *_key);
-int trace_ust_ht_match_event_by_name(struct cds_lfht_node *node,
-               const void *_key);
+int trace_ust_ht_match_event_by_name(struct cds_lfht_node *node, const void *_key);
 
 /*
  * Lookup functions. NULL is returned if not found.
  */
 struct ltt_ust_event *trace_ust_find_event(struct lttng_ht *ht,
-               char *name, struct lttng_bytecode *filter,
-               enum lttng_ust_abi_loglevel_type loglevel_type, int loglevel_value,
-               struct lttng_event_exclusion *exclusion);
-struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht,
-               const char *name);
+                                          char *name,
+                                          struct lttng_bytecode *filter,
+                                          enum lttng_ust_abi_loglevel_type loglevel_type,
+                                          int loglevel_value,
+                                          struct lttng_event_exclusion *exclusion);
+struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht, const char *name);
 struct agent *trace_ust_find_agent(struct ltt_ust_session *session,
-               enum lttng_domain_type domain_type);
+                                  enum lttng_domain_type domain_type);
 
 /*
  * Create functions malloc() the data structure.
  */
 struct ltt_ust_session *trace_ust_create_session(uint64_t session_id);
 struct ltt_ust_channel *trace_ust_create_channel(struct lttng_channel *attr,
-               enum lttng_domain_type domain);
+                                                enum lttng_domain_type domain);
 
 enum lttng_error_code trace_ust_create_event(struct lttng_event *ev,
-               char *filter_expression,
-               struct lttng_bytecode *filter,
-               struct lttng_event_exclusion *exclusion,
-               bool internal_event, struct ltt_ust_event **ust_event);
-struct ltt_ust_context *trace_ust_create_context(
-               const struct lttng_event_context *ctx);
+                                            char *filter_expression,
+                                            struct lttng_bytecode *filter,
+                                            struct lttng_event_exclusion *exclusion,
+                                            bool internal_event,
+                                            struct ltt_ust_event **ust_event);
+struct ltt_ust_context *trace_ust_create_context(const struct lttng_event_context *ctx);
 int trace_ust_match_context(const struct ltt_ust_context *uctx,
-               const struct lttng_event_context *ctx);
-void trace_ust_delete_channel(struct lttng_ht *ht,
-               struct ltt_ust_channel *channel);
+                           const struct lttng_event_context *ctx);
+void trace_ust_delete_channel(struct lttng_ht *ht, struct ltt_ust_channel *channel);
 
 int trace_ust_regenerate_metadata(struct ltt_ust_session *usess);
 
@@ -222,187 +222,171 @@ void trace_ust_destroy_context(struct ltt_ust_context *ctx);
 void trace_ust_free_session(struct ltt_ust_session *session);
 
 int trace_ust_id_tracker_lookup(enum lttng_process_attr process_attr,
-               struct ltt_ust_session *session,
-               int id);
-enum lttng_error_code trace_ust_process_attr_tracker_set_tracking_policy(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               enum lttng_tracking_policy policy);
-enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr,
-               const struct process_attr_value *value);
-const struct process_attr_tracker *trace_ust_get_process_attr_tracker(
-               struct ltt_ust_session *session,
-               enum lttng_process_attr process_attr);
+                               struct ltt_ust_session *session,
+                               int id);
+enum lttng_error_code
+trace_ust_process_attr_tracker_set_tracking_policy(struct ltt_ust_session *session,
+                                                  enum lttng_process_attr process_attr,
+                                                  enum lttng_tracking_policy policy);
+enum lttng_error_code
+trace_ust_process_attr_tracker_inclusion_set_add_value(struct ltt_ust_session *session,
+                                                      enum lttng_process_attr process_attr,
+                                                      const struct process_attr_value *value);
+enum lttng_error_code
+trace_ust_process_attr_tracker_inclusion_set_remove_value(struct ltt_ust_session *session,
+                                                         enum lttng_process_attr process_attr,
+                                                         const struct process_attr_value *value);
+const struct process_attr_tracker *
+trace_ust_get_process_attr_tracker(struct ltt_ust_session *session,
+                                  enum lttng_process_attr process_attr);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline int trace_ust_ht_match_event(
-               struct cds_lfht_node *node __attribute__((unused)),
-               const void *_key __attribute__((unused)))
+static inline int trace_ust_ht_match_event(struct cds_lfht_node *node __attribute__((unused)),
+                                          const void *_key __attribute__((unused)))
 {
        return 0;
 }
 
-static inline int trace_ust_ht_match_event_by_name(
-               struct cds_lfht_node *node __attribute__((unused)),
-               const void *_key __attribute__((unused)))
+static inline int trace_ust_ht_match_event_by_name(struct cds_lfht_node *node
+                                                  __attribute__((unused)),
+                                                  const void *_key __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-struct ltt_ust_channel *trace_ust_find_channel_by_name(
-               struct lttng_ht *ht __attribute__((unused)),
-               const char *name __attribute__((unused)))
+static inline struct ltt_ust_channel *trace_ust_find_channel_by_name(struct lttng_ht *ht
+                                                                    __attribute__((unused)),
+                                                                    const char *name
+                                                                    __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-struct ltt_ust_session *trace_ust_create_session(
-               unsigned int session_id __attribute__((unused)))
+static inline struct ltt_ust_session *trace_ust_create_session(unsigned int session_id
+                                                              __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-struct ltt_ust_channel *trace_ust_create_channel(
-               struct lttng_channel *attr __attribute__((unused)),
-               enum lttng_domain_type domain __attribute__((unused)))
+static inline struct ltt_ust_channel *trace_ust_create_channel(struct lttng_channel *attr
+                                                              __attribute__((unused)),
+                                                              enum lttng_domain_type domain
+                                                              __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-enum lttng_error_code trace_ust_create_event(
-               struct lttng_event *ev __attribute__((unused)),
-               const char *filter_expression __attribute__((unused)),
-               struct lttng_bytecode *filter __attribute__((unused)),
-               struct lttng_event_exclusion *exclusion __attribute__((unused)),
-               bool internal_event __attribute__((unused)),
-               struct ltt_ust_event **ust_event __attribute__((unused)))
+static inline enum lttng_error_code
+trace_ust_create_event(struct lttng_event *ev __attribute__((unused)),
+                      const char *filter_expression __attribute__((unused)),
+                      struct lttng_bytecode *filter __attribute__((unused)),
+                      struct lttng_event_exclusion *exclusion __attribute__((unused)),
+                      bool internal_event __attribute__((unused)),
+                      struct ltt_ust_event **ust_event __attribute__((unused)))
 {
        return LTTNG_ERR_NO_UST;
 }
 
-static inline
-void trace_ust_destroy_session(
-               struct ltt_ust_session *session __attribute__((unused)))
+static inline void trace_ust_destroy_session(struct ltt_ust_session *session
+                                            __attribute__((unused)))
 {
 }
 
-static inline
-void trace_ust_destroy_channel(
-               struct ltt_ust_channel *channel __attribute__((unused)))
+static inline void trace_ust_destroy_channel(struct ltt_ust_channel *channel
+                                            __attribute__((unused)))
 {
 }
 
-static inline
-void trace_ust_destroy_event(
-               struct ltt_ust_event *event __attribute__((unused)))
+static inline void trace_ust_destroy_event(struct ltt_ust_event *event __attribute__((unused)))
 {
 }
 
-static inline
-void trace_ust_free_session(
-               struct ltt_ust_session *session __attribute__((unused)))
+static inline void trace_ust_free_session(struct ltt_ust_session *session __attribute__((unused)))
 {
 }
 
-static inline
-struct ltt_ust_context *trace_ust_create_context(
-               const struct lttng_event_context *ctx __attribute__((unused)))
+static inline struct ltt_ust_context *trace_ust_create_context(const struct lttng_event_context *ctx
+                                                              __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-int trace_ust_match_context(
-               const struct ltt_ust_context *uctx __attribute__((unused)),
-               const struct lttng_event_context *ctx __attribute__((unused)))
+static inline int trace_ust_match_context(const struct ltt_ust_context *uctx
+                                         __attribute__((unused)),
+                                         const struct lttng_event_context *ctx
+                                         __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-struct ltt_ust_event *trace_ust_find_event(
-               struct lttng_ht *ht __attribute__((unused)),
-               char *name __attribute__((unused)),
-               struct lttng_bytecode *filter __attribute__((unused)),
-               enum lttng_ust_abi_loglevel_type loglevel_type __attribute__((unused)),
-               int loglevel_value __attribute__((unused)),
-               struct lttng_event_exclusion *exclusion __attribute__((unused)))
+static inline struct ltt_ust_event *
+trace_ust_find_event(struct lttng_ht *ht __attribute__((unused)),
+                    char *name __attribute__((unused)),
+                    struct lttng_bytecode *filter __attribute__((unused)),
+                    enum lttng_ust_abi_loglevel_type loglevel_type __attribute__((unused)),
+                    int loglevel_value __attribute__((unused)),
+                    struct lttng_event_exclusion *exclusion __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-void trace_ust_delete_channel(
-               struct lttng_ht *ht __attribute__((unused)),
-               struct ltt_ust_channel *channel __attribute__((unused)))
+static inline void trace_ust_delete_channel(struct lttng_ht *ht __attribute__((unused)),
+                                           struct ltt_ust_channel *channel __attribute__((unused)))
 {
        return;
 }
 
-static inline int trace_ust_regenerate_metadata(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline int trace_ust_regenerate_metadata(struct ltt_ust_session *usess
+                                               __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-struct agent *trace_ust_find_agent(
-               struct ltt_ust_session *session __attribute__((unused)),
-               enum lttng_domain_type domain_type __attribute__((unused)))
+static inline struct agent *trace_ust_find_agent(struct ltt_ust_session *session
+                                                __attribute__((unused)),
+                                                enum lttng_domain_type domain_type
+                                                __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline int trace_ust_id_tracker_lookup(
-               enum lttng_process_attr process_attr __attribute__((unused)),
-               struct ltt_ust_session *session __attribute__((unused)),
-               int id __attribute__((unused)))
+static inline int trace_ust_id_tracker_lookup(enum lttng_process_attr process_attr
+                                             __attribute__((unused)),
+                                             struct ltt_ust_session *session
+                                             __attribute__((unused)),
+                                             int id __attribute__((unused)))
 {
        return 0;
 }
 
-static inline enum lttng_error_code
-trace_ust_process_attr_tracker_set_tracking_policy(
-               struct ltt_ust_session *session __attribute__((unused)),
-               enum lttng_process_attr process_attr __attribute__((unused)),
-               enum lttng_tracking_policy policy __attribute__((unused)))
+static inline enum lttng_error_code trace_ust_process_attr_tracker_set_tracking_policy(
+       struct ltt_ust_session *session __attribute__((unused)),
+       enum lttng_process_attr process_attr __attribute__((unused)),
+       enum lttng_tracking_policy policy __attribute__((unused)))
 {
        return LTTNG_OK;
 }
 
-static inline enum lttng_error_code
-trace_ust_process_attr_tracker_inclusion_set_add_value(
-               struct ltt_ust_session *session __attribute__((unused)),
-               enum lttng_process_attr process_attr __attribute__((unused)),
-               const struct process_attr_value *value __attribute__((unused)))
+static inline enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_add_value(
+       struct ltt_ust_session *session __attribute__((unused)),
+       enum lttng_process_attr process_attr __attribute__((unused)),
+       const struct process_attr_value *value __attribute__((unused)))
 {
        return LTTNG_OK;
 }
 
-static inline enum lttng_error_code
-trace_ust_process_attr_tracker_inclusion_set_remove_value(
-               struct ltt_ust_session *session __attribute__((unused)),
-               enum lttng_process_attr process_attr __attribute__((unused)),
-               const struct process_attr_value *value __attribute__((unused)))
+static inline enum lttng_error_code trace_ust_process_attr_tracker_inclusion_set_remove_value(
+       struct ltt_ust_session *session __attribute__((unused)),
+       enum lttng_process_attr process_attr __attribute__((unused)),
+       const struct process_attr_value *value __attribute__((unused)))
 {
        return LTTNG_OK;
 }
 
 static inline const struct process_attr_tracker *
-trace_ust_get_process_attr_tracker(
-               struct ltt_ust_session *session __attribute__((unused)),
-               enum lttng_process_attr process_attr __attribute__((unused)))
+trace_ust_get_process_attr_tracker(struct ltt_ust_session *session __attribute__((unused)),
+                                  enum lttng_process_attr process_attr __attribute__((unused)))
 {
        return NULL;
 }
index 10f8dd59811a4e99f51d6c5fba025e347c4d7df8..526e51b6bc847ad47f7b4ceec872f95c975cbba7 100644 (file)
@@ -6,26 +6,29 @@
  *
  */
 
-#include "lttng/tracker.h"
 #include "common/dynamic-array.hpp"
 #include "common/macros.hpp"
+#include "lttng/tracker.h"
 #define _LGPL_SOURCE
-#include <grp.h>
-#include <pwd.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <urcu.h>
-#include <urcu/list.h>
-#include <urcu/rculfhash.h>
-
 #include "tracker.hpp"
+
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/tracker.hpp>
+#include <common/urcu.hpp>
+
 #include <lttng/lttng-error.h>
 
+#include <grp.h>
+#include <pwd.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <urcu.h>
+#include <urcu/list.h>
+#include <urcu/rculfhash.h>
+
 struct process_attr_tracker {
        enum lttng_tracking_policy policy;
        struct cds_lfht *inclusion_set_ht;
@@ -41,26 +44,25 @@ struct process_attr_tracker_value_node {
 
 static void process_attr_tracker_value_node_rcu_free(struct rcu_head *rcu_head)
 {
-       struct process_attr_tracker_value_node *node = lttng::utils::container_of(
-                       rcu_head, &process_attr_tracker_value_node::rcu_head);
+       struct process_attr_tracker_value_node *node =
+               lttng::utils::container_of(rcu_head, &process_attr_tracker_value_node::rcu_head);
 
        free(node);
 }
 
-struct process_attr_tracker *process_attr_tracker_create(void)
+struct process_attr_tracker *process_attr_tracker_create()
 {
        struct process_attr_tracker *tracker;
 
        tracker = zmalloc<process_attr_tracker>();
        if (!tracker) {
-               return NULL;
+               return nullptr;
        }
 
-       (void) process_attr_tracker_set_tracking_policy(
-                       tracker, LTTNG_TRACKING_POLICY_INCLUDE_ALL);
+       (void) process_attr_tracker_set_tracking_policy(tracker, LTTNG_TRACKING_POLICY_INCLUDE_ALL);
 
-       tracker->inclusion_set_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       tracker->inclusion_set_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!tracker->inclusion_set_ht) {
                goto error;
        }
@@ -68,22 +70,19 @@ struct process_attr_tracker *process_attr_tracker_create(void)
        return tracker;
 error:
        process_attr_tracker_destroy(tracker);
-       return NULL;
+       return nullptr;
 }
 
-static void process_attr_tracker_remove_value_node(
-               struct process_attr_tracker *tracker,
-               struct process_attr_tracker_value_node *value_node)
+static void
+process_attr_tracker_remove_value_node(struct process_attr_tracker *tracker,
+                                      struct process_attr_tracker_value_node *value_node)
 {
-       cds_lfht_del(tracker->inclusion_set_ht,
-                       &value_node->inclusion_set_ht_node);
+       cds_lfht_del(tracker->inclusion_set_ht, &value_node->inclusion_set_ht_node);
        process_attr_value_destroy(value_node->value);
-       call_rcu(&value_node->rcu_head,
-                       process_attr_tracker_value_node_rcu_free);
+       call_rcu(&value_node->rcu_head, process_attr_tracker_value_node_rcu_free);
 }
 
-static void process_attr_tracker_clear_inclusion_set(
-               struct process_attr_tracker *tracker)
+static void process_attr_tracker_clear_inclusion_set(struct process_attr_tracker *tracker)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -93,23 +92,25 @@ static void process_attr_tracker_clear_inclusion_set(
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry (tracker->inclusion_set_ht, &iter.iter,
-                       value_node, inclusion_set_ht_node) {
-               process_attr_tracker_remove_value_node(tracker, value_node);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       tracker->inclusion_set_ht, &iter.iter, value_node, inclusion_set_ht_node) {
+                       process_attr_tracker_remove_value_node(tracker, value_node);
+               }
        }
-       rcu_read_unlock();
-       ret = cds_lfht_destroy(tracker->inclusion_set_ht, NULL);
+
+       ret = cds_lfht_destroy(tracker->inclusion_set_ht, nullptr);
        LTTNG_ASSERT(ret == 0);
-       tracker->inclusion_set_ht = NULL;
+       tracker->inclusion_set_ht = nullptr;
 }
 
-static int process_attr_tracker_create_inclusion_set(
-               struct process_attr_tracker *tracker)
+static int process_attr_tracker_create_inclusion_set(struct process_attr_tracker *tracker)
 {
        LTTNG_ASSERT(!tracker->inclusion_set_ht);
-       tracker->inclusion_set_ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       tracker->inclusion_set_ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        return tracker->inclusion_set_ht ? 0 : -1;
 }
 
@@ -123,15 +124,14 @@ void process_attr_tracker_destroy(struct process_attr_tracker *tracker)
        free(tracker);
 }
 
-enum lttng_tracking_policy process_attr_tracker_get_tracking_policy(
-               const struct process_attr_tracker *tracker)
+enum lttng_tracking_policy
+process_attr_tracker_get_tracking_policy(const struct process_attr_tracker *tracker)
 {
        return tracker->policy;
 }
 
-int process_attr_tracker_set_tracking_policy(
-               struct process_attr_tracker *tracker,
-               enum lttng_tracking_policy tracking_policy)
+int process_attr_tracker_set_tracking_policy(struct process_attr_tracker *tracker,
+                                            enum lttng_tracking_policy tracking_policy)
 {
        int ret = 0;
 
@@ -149,50 +149,47 @@ end:
        return ret;
 }
 
-static int match_inclusion_set_value(
-               struct cds_lfht_node *node, const void *key)
+static int match_inclusion_set_value(struct cds_lfht_node *node, const void *key)
 {
        const struct process_attr_value *value_key = (process_attr_value *) key;
-       const struct process_attr_tracker_value_node *value_node =
-                       caa_container_of(node,
-                                       struct process_attr_tracker_value_node,
-                                       inclusion_set_ht_node);
+       const struct process_attr_tracker_value_node *value_node = caa_container_of(
+               node, struct process_attr_tracker_value_node, inclusion_set_ht_node);
 
        return process_attr_tracker_value_equal(value_node->value, value_key);
 }
 
-static struct process_attr_tracker_value_node *process_attr_tracker_lookup(
-               const struct process_attr_tracker *tracker,
-               const struct process_attr_value *value)
+static struct process_attr_tracker_value_node *
+process_attr_tracker_lookup(const struct process_attr_tracker *tracker,
+                           const struct process_attr_value *value)
 {
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
 
        LTTNG_ASSERT(tracker->policy == LTTNG_TRACKING_POLICY_INCLUDE_SET);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(tracker->inclusion_set_ht,
                        process_attr_value_hash(value),
-                       match_inclusion_set_value, value, &iter);
+                       match_inclusion_set_value,
+                       value,
+                       &iter);
        node = cds_lfht_iter_get_node(&iter);
-       rcu_read_unlock();
 
-       return node ? lttng::utils::container_of(node,
-                                     &process_attr_tracker_value_node::inclusion_set_ht_node) :
-                           NULL;
+       return node ? lttng::utils::container_of(
+                             node, &process_attr_tracker_value_node::inclusion_set_ht_node) :
+                     nullptr;
 }
 
 /* Protected by session mutex held by caller. */
-enum process_attr_tracker_status process_attr_tracker_inclusion_set_add_value(
-               struct process_attr_tracker *tracker,
-               const struct process_attr_value *value)
+enum process_attr_tracker_status
+process_attr_tracker_inclusion_set_add_value(struct process_attr_tracker *tracker,
+                                            const struct process_attr_value *value)
 {
-       enum process_attr_tracker_status status =
-                       PROCESS_ATTR_TRACKER_STATUS_OK;
-       struct process_attr_value *value_copy = NULL;
-       struct process_attr_tracker_value_node *value_node = NULL;
+       enum process_attr_tracker_status status = PROCESS_ATTR_TRACKER_STATUS_OK;
+       struct process_attr_value *value_copy = nullptr;
+       struct process_attr_tracker_value_node *value_node = nullptr;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        if (tracker->policy != LTTNG_TRACKING_POLICY_INCLUDE_SET) {
                status = PROCESS_ATTR_TRACKER_STATUS_INVALID_TRACKING_POLICY;
                goto end;
@@ -217,10 +214,10 @@ enum process_attr_tracker_status process_attr_tracker_inclusion_set_add_value(
 
        value_node->value = value_copy;
        cds_lfht_add(tracker->inclusion_set_ht,
-                       process_attr_value_hash(value_copy),
-                       &value_node->inclusion_set_ht_node);
-       value_copy = NULL;
-       value_node = NULL;
+                    process_attr_value_hash(value_copy),
+                    &value_node->inclusion_set_ht_node);
+       value_copy = nullptr;
+       value_node = nullptr;
 end:
        if (value_copy) {
                process_attr_value_destroy(value_copy);
@@ -228,21 +225,18 @@ end:
        if (value_node) {
                free(value_node);
        }
-       rcu_read_unlock();
        return status;
 }
 
 /* Protected by session mutex held by caller. */
 enum process_attr_tracker_status
-process_attr_tracker_inclusion_set_remove_value(
-               struct process_attr_tracker *tracker,
-               const struct process_attr_value *value)
+process_attr_tracker_inclusion_set_remove_value(struct process_attr_tracker *tracker,
+                                               const struct process_attr_value *value)
 {
        struct process_attr_tracker_value_node *value_node;
-       enum process_attr_tracker_status status =
-                       PROCESS_ATTR_TRACKER_STATUS_OK;
+       enum process_attr_tracker_status status = PROCESS_ATTR_TRACKER_STATUS_OK;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        if (tracker->policy != LTTNG_TRACKING_POLICY_INCLUDE_SET) {
                status = PROCESS_ATTR_TRACKER_STATUS_INVALID_TRACKING_POLICY;
                goto end;
@@ -256,20 +250,18 @@ process_attr_tracker_inclusion_set_remove_value(
 
        process_attr_tracker_remove_value_node(tracker, value_node);
 end:
-       rcu_read_unlock();
        return status;
 }
 
-enum process_attr_tracker_status process_attr_tracker_get_inclusion_set(
-               const struct process_attr_tracker *tracker,
-               struct lttng_process_attr_values **_values)
+enum process_attr_tracker_status
+process_attr_tracker_get_inclusion_set(const struct process_attr_tracker *tracker,
+                                      struct lttng_process_attr_values **_values)
 {
        struct lttng_ht_iter iter;
        struct process_attr_tracker_value_node *value_node;
-       enum process_attr_tracker_status status =
-                       PROCESS_ATTR_TRACKER_STATUS_OK;
+       enum process_attr_tracker_status status = PROCESS_ATTR_TRACKER_STATUS_OK;
        struct lttng_process_attr_values *values;
-       struct process_attr_value *new_value = NULL;
+       struct process_attr_value *new_value = nullptr;
 
        values = lttng_process_attr_values_create();
        if (!values) {
@@ -282,31 +274,32 @@ enum process_attr_tracker_status process_attr_tracker_get_inclusion_set(
                goto error;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry (tracker->inclusion_set_ht, &iter.iter,
-                       value_node, inclusion_set_ht_node) {
-               int ret;
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               new_value = process_attr_value_copy(value_node->value);
-               if (!new_value) {
-                       status = PROCESS_ATTR_TRACKER_STATUS_ERROR;
-                       goto error_unlock;
-               }
+               cds_lfht_for_each_entry (
+                       tracker->inclusion_set_ht, &iter.iter, value_node, inclusion_set_ht_node) {
+                       int ret;
 
-               ret = lttng_dynamic_pointer_array_add_pointer(
-                               &values->array, new_value);
-               if (ret) {
-                       status = PROCESS_ATTR_TRACKER_STATUS_ERROR;
-                       goto error_unlock;
-               }
+                       new_value = process_attr_value_copy(value_node->value);
+                       if (!new_value) {
+                               status = PROCESS_ATTR_TRACKER_STATUS_ERROR;
+                               goto error_unlock;
+                       }
 
-               new_value = NULL;
+                       ret = lttng_dynamic_pointer_array_add_pointer(&values->array, new_value);
+                       if (ret) {
+                               status = PROCESS_ATTR_TRACKER_STATUS_ERROR;
+                               goto error_unlock;
+                       }
+
+                       new_value = nullptr;
+               }
        }
-       rcu_read_unlock();
+
        *_values = values;
        return status;
 error_unlock:
-       rcu_read_unlock();
 error:
        lttng_process_attr_values_destroy(values);
        process_attr_value_destroy(new_value);
index c3f6b9694061ce3dad1c94d7187f9b419820b80e..2996113c53be140c1b0f92d6f42ace5af9d5b2ce 100644 (file)
@@ -10,6 +10,7 @@
 #define _LTT_TRACKER_H
 
 #include <common/tracker.hpp>
+
 #include <lttng/tracker.h>
 
 struct process_attr_tracker;
@@ -22,25 +23,23 @@ enum process_attr_tracker_status {
        PROCESS_ATTR_TRACKER_STATUS_INVALID_TRACKING_POLICY,
 };
 
-struct process_attr_tracker *process_attr_tracker_create(void);
+struct process_attr_tracker *process_attr_tracker_create();
 void process_attr_tracker_destroy(struct process_attr_tracker *tracker);
 
-enum lttng_tracking_policy process_attr_tracker_get_tracking_policy(
-               const struct process_attr_tracker *tracker);
-int process_attr_tracker_set_tracking_policy(
-               struct process_attr_tracker *tracker,
-               enum lttng_tracking_policy tracking_policy);
+enum lttng_tracking_policy
+process_attr_tracker_get_tracking_policy(const struct process_attr_tracker *tracker);
+int process_attr_tracker_set_tracking_policy(struct process_attr_tracker *tracker,
+                                            enum lttng_tracking_policy tracking_policy);
 
-enum process_attr_tracker_status process_attr_tracker_inclusion_set_add_value(
-               struct process_attr_tracker *tracker,
-               const struct process_attr_value *value);
 enum process_attr_tracker_status
-process_attr_tracker_inclusion_set_remove_value(
-               struct process_attr_tracker *tracker,
-               const struct process_attr_value *value);
+process_attr_tracker_inclusion_set_add_value(struct process_attr_tracker *tracker,
+                                            const struct process_attr_value *value);
+enum process_attr_tracker_status
+process_attr_tracker_inclusion_set_remove_value(struct process_attr_tracker *tracker,
+                                               const struct process_attr_value *value);
 
-enum process_attr_tracker_status process_attr_tracker_get_inclusion_set(
-               const struct process_attr_tracker *tracker,
-               struct lttng_process_attr_values **values);
+enum process_attr_tracker_status
+process_attr_tracker_get_inclusion_set(const struct process_attr_tracker *tracker,
+                                      struct lttng_process_attr_values **values);
 
 #endif /* _LTT_TRACKER_H */
index 63941a8abe05d71018c40c26aa4fdec996a44d3a..a50951f7bb4bfb2bbba4bba7dbbc07db8561b3dd 100644 (file)
@@ -6,33 +6,33 @@
  */
 
 #include "event-notifier-error-accounting.hpp"
+
+#include <lttng/action/action-internal.hpp>
 #include <lttng/error-query-internal.hpp>
 #include <lttng/trigger/trigger-internal.hpp>
-#include <lttng/action/action-internal.hpp>
 
-enum lttng_trigger_status lttng_trigger_add_error_results(
-               const struct lttng_trigger *trigger __attribute__((unused)),
-               struct lttng_error_query_results *results __attribute__((unused)))
+enum lttng_trigger_status lttng_trigger_add_error_results(const struct lttng_trigger *trigger
+                                                         __attribute__((unused)),
+                                                         struct lttng_error_query_results *results
+                                                         __attribute__((unused)))
 {
        return LTTNG_TRIGGER_STATUS_OK;
 }
 
-enum lttng_trigger_status lttng_trigger_condition_add_error_results(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results *results)
+enum lttng_trigger_status
+lttng_trigger_condition_add_error_results(const struct lttng_trigger *trigger,
+                                         struct lttng_error_query_results *results)
 {
        enum lttng_trigger_status status;
        uint64_t discarded_tracer_messages_count;
        enum event_notifier_error_accounting_status error_accounting_status;
-       struct lttng_error_query_result *discarded_tracer_messages_counter = NULL;
+       struct lttng_error_query_result *discarded_tracer_messages_counter = nullptr;
        const char *trigger_name;
        uid_t trigger_owner;
 
        status = lttng_trigger_get_name(trigger, &trigger_name);
-       trigger_name = status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
-       status = lttng_trigger_get_owner_uid(trigger,
-                       &trigger_owner);
+       trigger_name = status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
+       status = lttng_trigger_get_owner_uid(trigger, &trigger_owner);
        LTTNG_ASSERT(status == LTTNG_TRIGGER_STATUS_OK);
 
        /*
@@ -47,31 +47,31 @@ enum lttng_trigger_status lttng_trigger_condition_add_error_results(
        }
 
        error_accounting_status = event_notifier_error_accounting_get_count(
-                       trigger, &discarded_tracer_messages_count);
+               trigger, &discarded_tracer_messages_count);
        if (error_accounting_status != EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK) {
                ERR("Failed to retrieve tracer discarded messages count for trigger: trigger name = '%s', trigger owner uid = %d",
-                               trigger_name, (int) trigger_owner);
+                   trigger_name,
+                   (int) trigger_owner);
                status = LTTNG_TRIGGER_STATUS_ERROR;
                goto end;
        }
 
        discarded_tracer_messages_counter = lttng_error_query_result_counter_create(
-                       "discarded tracer messages",
-                       "Count of messages discarded by the tracer due to a communication error with the session daemon",
-                       discarded_tracer_messages_count);
+               "discarded tracer messages",
+               "Count of messages discarded by the tracer due to a communication error with the session daemon",
+               discarded_tracer_messages_count);
        if (!discarded_tracer_messages_counter) {
                status = LTTNG_TRIGGER_STATUS_ERROR;
                goto end;
        }
 
-       if (lttng_error_query_results_add_result(
-                           results, discarded_tracer_messages_counter)) {
+       if (lttng_error_query_results_add_result(results, discarded_tracer_messages_counter)) {
                status = LTTNG_TRIGGER_STATUS_ERROR;
                goto end;
        }
 
        /* Ownership transferred to the results. */
-       discarded_tracer_messages_counter = NULL;
+       discarded_tracer_messages_counter = nullptr;
 
        status = LTTNG_TRIGGER_STATUS_OK;
 end:
@@ -79,9 +79,9 @@ end:
        return status;
 }
 
-enum lttng_trigger_status lttng_trigger_add_action_error_query_results(
-               struct lttng_trigger *trigger,
-               struct lttng_error_query_results *results)
+enum lttng_trigger_status
+lttng_trigger_add_action_error_query_results(struct lttng_trigger *trigger,
+                                            struct lttng_error_query_results *results)
 {
        enum lttng_trigger_status status;
        const char *trigger_name;
@@ -89,14 +89,12 @@ enum lttng_trigger_status lttng_trigger_add_action_error_query_results(
        enum lttng_action_status action_status;
 
        status = lttng_trigger_get_name(trigger, &trigger_name);
-       trigger_name = status == LTTNG_TRIGGER_STATUS_OK ?
-                       trigger_name : "(anonymous)";
-       status = lttng_trigger_get_owner_uid(trigger,
-                       &trigger_owner);
+       trigger_name = status == LTTNG_TRIGGER_STATUS_OK ? trigger_name : "(anonymous)";
+       status = lttng_trigger_get_owner_uid(trigger, &trigger_owner);
        LTTNG_ASSERT(status == LTTNG_TRIGGER_STATUS_OK);
 
-       action_status = lttng_action_add_error_query_results(
-                       lttng_trigger_get_action(trigger), results);
+       action_status =
+               lttng_action_add_error_query_results(lttng_trigger_get_action(trigger), results);
        switch (action_status) {
        case LTTNG_ACTION_STATUS_OK:
                break;
index 115d579763ff355330eef93379484a04fbc6c730..83f4a24274fc84cd47799bd2327be35713b2702d 100644 (file)
 #include <common/exception.hpp>
 #include <common/format.hpp>
 #include <common/make-unique.hpp>
+#include <common/scope-exit.hpp>
 #include <common/uuid.hpp>
 
+#include <vendor/optional.hpp>
+
+#include <algorithm>
 #include <array>
-#include <queue>
 #include <locale>
+#include <queue>
+#include <set>
+#include <stack>
+#include <unordered_set>
+#include <utility>
 
 namespace lst = lttng::sessiond::trace;
 namespace tsdl = lttng::sessiond::tsdl;
@@ -24,6 +32,25 @@ namespace {
 const auto ctf_spec_major = 1;
 const auto ctf_spec_minor = 8;
 
+/*
+ * Although the CTF v1.8 specification recommends ignoring any leading underscore, Some readers,
+ * such as Babeltrace 1.x, expect special identifiers without a prepended underscore.
+ */
+const std::unordered_set<std::string> safe_tsdl_identifiers = { "stream_id",
+                                                               "packet_size",
+                                                               "content_size",
+                                                               "id",
+                                                               "v",
+                                                               "timestamp",
+                                                               "events_discarded",
+                                                               "packet_seq_num",
+                                                               "timestamp_begin",
+                                                               "timestamp_end",
+                                                               "cpu_id",
+                                                               "magic",
+                                                               "uuid",
+                                                               "stream_instance_id" };
+
 /*
  * A previous implementation always prepended '_' to the identifiers in order to
  * side-step the problem of escaping TSDL keywords and ensuring identifiers
@@ -38,13 +65,17 @@ std::string escape_tsdl_identifier(const std::string& original_identifier)
                LTTNG_THROW_ERROR("Invalid 0-length identifier used in trace description");
        }
 
+       if (safe_tsdl_identifiers.find(original_identifier) != safe_tsdl_identifiers.end()) {
+               return original_identifier;
+       }
+
        std::string new_identifier;
        /* Optimisticly assume most identifiers are valid and allocate the same length. */
        new_identifier.reserve(original_identifier.size());
        new_identifier = "_";
 
        /* Replace illegal characters by '_'. */
-       std::locale c_locale{"C"};
+       std::locale c_locale{ "C" };
        for (const auto current_char : original_identifier) {
                if (!std::isalnum(current_char, c_locale) && current_char != '_') {
                        new_identifier += '_';
@@ -82,21 +113,279 @@ std::string escape_tsdl_env_string_value(const std::string& original_string)
        return escaped_string;
 }
 
+/*
+ * Variants produced by LTTng-UST contain TSDL-unsafe names. A variant/selector
+ * sanitization pass is performed before serializing a trace class hierarchy to
+ * TSDL.
+ *
+ * The variant_tsdl_keyword_sanitizer visitor is used to visit field before it
+ * is handed-over to the actual TSDL-producing visitor.
+ *
+ * As it visits fields, the variant_tsdl_keyword_sanitizer populates a
+ * "type_overrider" with TSDL-safe replacements for any variant or enumeration
+ * that uses TSDL-unsafe identifiers (reserved keywords).
+ *
+ * The type_overrider, in turn, is used by the rest of the TSDL serialization
+ * visitor (tsdl_field_visitor) to swap any TSDL-unsafe types with their
+ * sanitized version.
+ *
+ * The tsdl_field_visitor owns the type_overrider and only briefly shares it
+ * with the variant_tsdl_keyword_sanitizer which takes a reference to it.
+ */
+class variant_tsdl_keyword_sanitizer : public lttng::sessiond::trace::field_visitor,
+                                      public lttng::sessiond::trace::type_visitor {
+public:
+       using type_lookup_function = std::function<const lst::type&(const lst::field_location&)>;
+
+       variant_tsdl_keyword_sanitizer(tsdl::details::type_overrider& type_overrides,
+                                      type_lookup_function lookup_type) :
+               _type_overrides(type_overrides), _lookup_type(std::move(lookup_type))
+       {
+       }
+
+private:
+       class _c_string_comparator {
+       public:
+               int operator()(const char *lhs, const char *rhs) const
+               {
+                       return std::strcmp(lhs, rhs) < 0;
+               }
+       };
+       using unsafe_names = std::set<const char *, _c_string_comparator>;
+
+       void visit(const lst::field& field) final
+       {
+               _type_overrides.type(field.get_type()).accept(*this);
+       }
+
+       void visit(const lst::integer_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::floating_point_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::signed_enumeration_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::unsigned_enumeration_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::static_length_array_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::dynamic_length_array_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::static_length_blob_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::dynamic_length_blob_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::null_terminated_string_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::structure_type& type) final
+       {
+               /* Recurse into structure attributes. */
+               for (const auto& field : type.fields_) {
+                       field->accept(*this);
+               }
+       }
+
+       /*
+        * Create a new enumeration type replacing any mapping that match, by name, the elements in
+        * `unsafe_names_found` with a TSDL-safe version. Currently, unsafe identifiers are made
+        * safe by adding a leading underscore.
+        */
+       template <typename MappingIntegerType>
+       lst::type::cuptr _create_sanitized_selector(
+               const lst::typed_enumeration_type<MappingIntegerType>& original_selector,
+               const unsafe_names& unsafe_names_found)
+       {
+               auto new_mappings = std::make_shared<
+                       typename lst::typed_enumeration_type<MappingIntegerType>::mappings>();
+
+               for (const auto& mapping : *original_selector.mappings_) {
+                       if (unsafe_names_found.find(mapping.name.c_str()) ==
+                           unsafe_names_found.end()) {
+                               /* Mapping is safe, simply copy it. */
+                               new_mappings->emplace_back(mapping);
+                       } else {
+                               /* Unsafe mapping, rename it and keep the rest of its attributes. */
+                               new_mappings->emplace_back(lttng::format("_{}", mapping.name),
+                                                          mapping.range);
+                       }
+               }
+
+               return lttng::make_unique<lst::typed_enumeration_type<MappingIntegerType>>(
+                       original_selector.alignment,
+                       original_selector.byte_order,
+                       original_selector.size,
+                       original_selector.base_,
+                       new_mappings);
+       }
+
+       template <typename MappingIntegerType>
+       const typename lst::typed_enumeration_type<MappingIntegerType>::mapping&
+       _find_enumeration_mapping_by_range(
+               const typename lst::typed_enumeration_type<MappingIntegerType>& enumeration_type,
+               const typename lst::typed_enumeration_type<MappingIntegerType>::mapping::range_t&
+                       target_mapping_range)
+       {
+               for (const auto& mapping : *enumeration_type.mappings_) {
+                       if (mapping.range == target_mapping_range) {
+                               return mapping;
+                       }
+               }
+
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Failed to find mapping by range in enumeration while sanitizing a variant: target_mapping_range={}",
+                       target_mapping_range));
+       }
+
+       /*
+        * Copy `original_variant`, but use the mappings of a previously-published sanitized tag
+        * to produce a TSDL-safe version of the variant.
+        */
+       template <typename MappingIntegerType>
+       lst::type::cuptr
+       _create_sanitized_variant(const lst::variant_type<MappingIntegerType>& original_variant)
+       {
+               typename lst::variant_type<MappingIntegerType>::choices new_choices;
+               const auto& sanitized_selector =
+                       static_cast<const lst::typed_enumeration_type<MappingIntegerType>&>(
+                               _type_overrides.type(
+                                       _lookup_type(original_variant.selector_field_location)));
+
+               /* Visit variant choices to sanitize them as needed. */
+               for (const auto& choice : original_variant.choices_) {
+                       choice.second->accept(*this);
+               }
+
+               for (const auto& choice : original_variant.choices_) {
+                       const auto& sanitized_choice_type = _type_overrides.type(*choice.second);
+
+                       new_choices.emplace_back(_find_enumeration_mapping_by_range(
+                                                        sanitized_selector, choice.first.range),
+                                                sanitized_choice_type.copy());
+               }
+
+               return lttng::make_unique<lst::variant_type<MappingIntegerType>>(
+                       original_variant.alignment,
+                       original_variant.selector_field_location,
+                       std::move(new_choices));
+       }
+
+       template <typename MappingIntegerType>
+       void visit_variant(const lst::variant_type<MappingIntegerType>& type)
+       {
+               unsafe_names unsafe_names_found;
+               static const std::unordered_set<std::string> tsdl_protected_keywords = {
+                       "align",  "callsite", "const",     "char",           "clock",    "double",
+                       "enum",   "env",      "event",     "floating_point", "float",    "integer",
+                       "int",    "long",     "short",     "signed",         "stream",   "string",
+                       "struct", "trace",    "typealias", "typedef",        "unsigned", "variant",
+                       "void",   "_Bool",    "_Complex",  "_Imaginary",
+               };
+
+               for (const auto& choice : type.choices_) {
+                       if (tsdl_protected_keywords.find(choice.first.name) !=
+                           tsdl_protected_keywords.cend()) {
+                               /* Choice name is illegal, we have to rename it and its matching
+                                * mapping. */
+                               unsafe_names_found.insert(choice.first.name.c_str());
+                       }
+               }
+
+               if (unsafe_names_found.empty()) {
+                       return;
+               }
+
+               /*
+                * Look-up selector field type.
+                *
+                * Since it may have been overriden previously, keep the original and overriden
+                * selector field types (which may be the same, if the original was not overriden).
+                *
+                * We work from the "overriden" selector field type to preserve any existing
+                * modifications. However, the original field type will be used to publish the new
+                * version of the type leaving only the most recent overriden type in the type
+                * overrides.
+                */
+               const auto& original_selector_type = _lookup_type(type.selector_field_location);
+               const auto& overriden_selector_type = _type_overrides.type(original_selector_type);
+
+               auto sanitized_selector_type = _create_sanitized_selector(
+                       static_cast<const lst::typed_enumeration_type<MappingIntegerType>&>(
+                               overriden_selector_type),
+                       unsafe_names_found);
+               _type_overrides.publish(original_selector_type, std::move(sanitized_selector_type));
+
+               auto sanitized_variant_type = _create_sanitized_variant(
+                       static_cast<const lst::variant_type<MappingIntegerType>&>(type));
+               _type_overrides.publish(type, std::move(sanitized_variant_type));
+       }
+
+       void visit(const lst::variant_type<
+                  lst::signed_enumeration_type::mapping::range_t::range_integer_t>& type) final
+       {
+               visit_variant(type);
+       }
+
+       void visit(const lst::variant_type<
+                  lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>& type) final
+       {
+               visit_variant(type);
+       }
+
+       void visit(const lst::static_length_string_type& type __attribute__((unused))) final
+       {
+       }
+
+       void visit(const lst::dynamic_length_string_type& type __attribute__((unused))) final
+       {
+       }
+
+       tsdl::details::type_overrider& _type_overrides;
+       const type_lookup_function _lookup_type;
+};
+
 class tsdl_field_visitor : public lttng::sessiond::trace::field_visitor,
                           public lttng::sessiond::trace::type_visitor {
 public:
-       tsdl_field_visitor(const lst::abi& abi, unsigned int indentation_level) :
-               _indentation_level{indentation_level}, _trace_abi{abi}
+       tsdl_field_visitor(const lst::abi& abi,
+                          unsigned int indentation_level,
+                          const tsdl::details::type_overrider& type_overrides,
+                          const nonstd::optional<std::string>& in_default_clock_class_name =
+                                  nonstd::nullopt) :
+               _indentation_level(indentation_level),
+               _trace_abi(abi),
+
+               _default_clock_class_name(in_default_clock_class_name ?
+                                                 in_default_clock_class_name->c_str() :
+                                                 nullptr),
+               _type_overrides(type_overrides)
        {
        }
 
-       std::string& get_description()
+       /* Only call once. */
+       std::string move_description()
        {
-               return _description;
+               return std::move(_description);
        }
 
 private:
-       virtual void visit(const lst::field& field) override final
+       void visit(const lst::field& field) final
        {
                /*
                 * Hack: keep the name of the field being visited since
@@ -105,11 +394,13 @@ private:
                 * empty structure declaration is inserted when needed to express the aligment
                 * constraint. The name of this structure is generated using the field's name.
                 */
-               _escaped_current_field_name = escape_tsdl_identifier(field.name);
-
-               field._type->accept(*this);
+               _current_field_name.push(_bypass_identifier_escape ?
+                                                field.name :
+                                                escape_tsdl_identifier(field.name));
+               _type_overrides.type(field.get_type()).accept(*this);
                _description += " ";
-               _description += _escaped_current_field_name;
+               _description += _current_field_name.top();
+               _current_field_name.pop();
 
                /*
                 * Some types requires suffixes to be appended (e.g. the length of arrays
@@ -121,17 +412,16 @@ private:
                }
 
                _description += ";";
-               _escaped_current_field_name.clear();
        }
 
-       virtual void visit(const lst::integer_type& type) override final
+       void visit(const lst::integer_type& type) final
        {
                _description += "integer { ";
 
                /* Mandatory properties (no defaults). */
-               _description += fmt::format("size = {size}; align = {alignment};",
-                               fmt::arg("size", type.size),
-                               fmt::arg("alignment", type.alignment));
+               _description += lttng::format("size = {size}; align = {alignment};",
+                                             fmt::arg("size", type.size),
+                                             fmt::arg("alignment", type.alignment));
 
                /* Defaults to unsigned. */
                if (type.signedness_ == lst::integer_type::signedness::SIGNED) {
@@ -153,19 +443,20 @@ private:
                                base = 16;
                                break;
                        default:
-                               LTTNG_THROW_ERROR(fmt::format(
-                                               "Unexpected base encountered while serializing integer type to TSDL: base = {}",
-                                               (int) type.base_));
+                               LTTNG_THROW_ERROR(lttng::format(
+                                       "Unexpected base encountered while serializing integer type to TSDL: base = {}",
+                                       (int) type.base_));
                        }
 
-                       _description += fmt::format(" base = {};", base);
+                       _description += lttng::format(" base = {};", base);
                }
 
                /* Defaults to the trace's native byte order. */
                if (type.byte_order != _trace_abi.byte_order) {
-                       const auto byte_order_str = type.byte_order == lst::byte_order::BIG_ENDIAN_ ? "be" : "le";
+                       const auto byte_order_str =
+                               type.byte_order == lst::byte_order::BIG_ENDIAN_ ? "be" : "le";
 
-                       _description += fmt::format(" byte_order = {};", byte_order_str);
+                       _description += lttng::format(" byte_order = {};", byte_order_str);
                }
 
                if (_current_integer_encoding_override) {
@@ -179,31 +470,45 @@ private:
                                encoding_str = "UTF8";
                                break;
                        default:
-                               LTTNG_THROW_ERROR(fmt::format(
-                                               "Unexpected encoding encountered while serializing integer type to TSDL: encoding = {}",
-                                               (int) *_current_integer_encoding_override));
+                               LTTNG_THROW_ERROR(lttng::format(
+                                       "Unexpected encoding encountered while serializing integer type to TSDL: encoding = {}",
+                                       (int) *_current_integer_encoding_override));
                        }
 
-                       _description += fmt::format(" encoding = {};", encoding_str);
+                       _description += lttng::format(" encoding = {};", encoding_str);
                        _current_integer_encoding_override.reset();
                }
 
+               if (std::find(type.roles_.begin(),
+                             type.roles_.end(),
+                             lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP) !=
+                           type.roles_.end() ||
+                   std::find(type.roles_.begin(),
+                             type.roles_.end(),
+                             lst::integer_type::role::PACKET_END_DEFAULT_CLOCK_TIMESTAMP) !=
+                           type.roles_.end()) {
+                       LTTNG_ASSERT(_default_clock_class_name);
+                       _description +=
+                               lttng::format(" map = clock.{}.value;", _default_clock_class_name);
+               }
+
                _description += " }";
        }
 
-       virtual void visit(const lst::floating_point_type& type) override final
+       void visit(const lst::floating_point_type& type) final
        {
-               _description += fmt::format(
-                               "floating_point {{ align = {alignment}; mant_dig = {mantissa_digits}; exp_dig = {exponent_digits};",
-                               fmt::arg("alignment", type.alignment),
-                               fmt::arg("mantissa_digits", type.mantissa_digits),
-                               fmt::arg("exponent_digits", type.exponent_digits));
+               _description += lttng::format(
+                       "floating_point {{ align = {alignment}; mant_dig = {mantissa_digits}; exp_dig = {exponent_digits};",
+                       fmt::arg("alignment", type.alignment),
+                       fmt::arg("mantissa_digits", type.mantissa_digits),
+                       fmt::arg("exponent_digits", type.exponent_digits));
 
                /* Defaults to the trace's native byte order. */
                if (type.byte_order != _trace_abi.byte_order) {
-                       const auto byte_order_str = type.byte_order == lst::byte_order::BIG_ENDIAN_ ? "be" : "le";
+                       const auto byte_order_str =
+                               type.byte_order == lst::byte_order::BIG_ENDIAN_ ? "be" : "le";
 
-                       _description += fmt::format(" byte_order = {};", byte_order_str);
+                       _description += lttng::format(" byte_order = {};", byte_order_str);
                }
 
                _description += " }";
@@ -215,34 +520,29 @@ private:
                /* name follows, when applicable. */
                _description += "enum : ";
 
-               tsdl_field_visitor integer_visitor{_trace_abi, _indentation_level};
-
-               integer_visitor.visit(static_cast<const lst::integer_type&>(type));
-               _description += integer_visitor.get_description() + " {\n";
+               visit(static_cast<const lst::integer_type&>(type));
+               _description += " {\n";
 
                const auto mappings_indentation_level = _indentation_level + 1;
 
                bool first_mapping = true;
-               for (const auto& mapping : *type._mappings) {
+               for (const auto& mapping : *type.mappings_) {
                        if (!first_mapping) {
                                _description += ",\n";
                        }
 
                        _description.resize(_description.size() + mappings_indentation_level, '\t');
-                       if (!mapping.range) {
-                               _description += fmt::format("\"{}\"", mapping.name);
-                       } else if (mapping.range->begin == mapping.range->end) {
-                               _description += fmt::format(
-                                               "\"{mapping_name}\" = {mapping_value}",
-                                               fmt::arg("mapping_name", mapping.name),
-                                               fmt::arg("mapping_value", mapping.range->begin));
+                       if (mapping.range.begin == mapping.range.end) {
+                               _description += lttng::format(
+                                       "\"{mapping_name}\" = {mapping_value}",
+                                       fmt::arg("mapping_name", mapping.name),
+                                       fmt::arg("mapping_value", mapping.range.begin));
                        } else {
-                               _description += fmt::format(
-                                               "\"{mapping_name}\" = {mapping_range_begin} ... {mapping_range_end}",
-                                               fmt::arg("mapping_name", mapping.name),
-                                               fmt::arg("mapping_range_begin",
-                                                               mapping.range->begin),
-                                               fmt::arg("mapping_range_end", mapping.range->end));
+                               _description += lttng::format(
+                                       "\"{mapping_name}\" = {mapping_range_begin} ... {mapping_range_end}",
+                                       fmt::arg("mapping_name", mapping.name),
+                                       fmt::arg("mapping_range_begin", mapping.range.begin),
+                                       fmt::arg("mapping_range_end", mapping.range.end));
                        }
 
                        first_mapping = false;
@@ -253,32 +553,32 @@ private:
                _description += "}";
        }
 
-       virtual void visit(const lst::signed_enumeration_type& type) override final
+       void visit(const lst::signed_enumeration_type& type) final
        {
                visit_enumeration(type);
        }
 
-       virtual void visit(const lst::unsigned_enumeration_type& type) override final
+       void visit(const lst::unsigned_enumeration_type& type) final
        {
                visit_enumeration(type);
        }
 
-       virtual void visit(const lst::static_length_array_type& type) override final
+       void visit(const lst::static_length_array_type& type) final
        {
                if (type.alignment != 0) {
-                       LTTNG_ASSERT(_escaped_current_field_name.size() > 0);
-                       _description += fmt::format(
-                                       "struct {{ }} align({alignment}) {field_name}_padding;\n",
-                                       fmt::arg("alignment", type.alignment),
-                                       fmt::arg("field_name", _escaped_current_field_name));
+                       LTTNG_ASSERT(!_current_field_name.empty());
+                       _description += lttng::format(
+                               "struct {{ }} align({alignment}) {field_name}_padding;\n",
+                               fmt::arg("alignment", type.alignment),
+                               fmt::arg("field_name", _current_field_name.top()));
                        _description.resize(_description.size() + _indentation_level, '\t');
                }
 
                type.element_type->accept(*this);
-               _type_suffixes.emplace(fmt::format("[{}]", type.length));
+               _type_suffixes.emplace(lttng::format("[{}]", type.length));
        }
 
-       virtual void visit(const lst::dynamic_length_array_type& type) override final
+       void visit(const lst::dynamic_length_array_type& type) final
        {
                if (type.alignment != 0) {
                        /*
@@ -287,22 +587,60 @@ private:
                         * could wrap nested sequences in structures, which
                         * would allow us to express alignment constraints.
                         */
-                       LTTNG_ASSERT(_escaped_current_field_name.size() > 0);
-                       _description += fmt::format(
-                                       "struct {{ }} align({alignment}) {field_name}_padding;\n",
-                                       fmt::arg("alignment", type.alignment),
-                                       fmt::arg("field_name", _escaped_current_field_name));
+                       LTTNG_ASSERT(!_current_field_name.empty());
+                       _description += lttng::format(
+                               "struct {{ }} align({alignment}) {field_name}_padding;\n",
+                               fmt::arg("alignment", type.alignment),
+                               fmt::arg("field_name", _current_field_name.top()));
                        _description.resize(_description.size() + _indentation_level, '\t');
                }
 
                type.element_type->accept(*this);
-               _type_suffixes.emplace(fmt::format(
-                               "[{}]", escape_tsdl_identifier(type.length_field_name)));
+               _type_suffixes.emplace(lttng::format(
+                       "[{}]",
+                       _bypass_identifier_escape ?
+                               *(type.length_field_location.elements_.end() - 1) :
+                               escape_tsdl_identifier(
+                                       *(type.length_field_location.elements_.end() - 1))));
+       }
+
+       void visit(const lst::static_length_blob_type& type) final
+       {
+               /* This type doesn't exist in CTF 1.x, express it as a static length array of
+                * uint8_t. */
+               std::unique_ptr<const lst::type> uint8_element =
+                       lttng::make_unique<lst::integer_type>(
+                               8,
+                               _trace_abi.byte_order,
+                               8,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::HEXADECIMAL);
+               const auto array = lttng::make_unique<lst::static_length_array_type>(
+                       type.alignment, std::move(uint8_element), type.length_bytes);
+
+               visit(*array);
        }
 
-       virtual void visit(const lst::null_terminated_string_type& type) override final
+       void visit(const lst::dynamic_length_blob_type& type) final
        {
-               /* Defaults to UTF-8.  */
+               /* This type doesn't exist in CTF 1.x, express it as a dynamic length array of
+                * uint8_t. */
+               std::unique_ptr<const lst::type> uint8_element =
+                       lttng::make_unique<lst::integer_type>(
+                               0,
+                               _trace_abi.byte_order,
+                               8,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::HEXADECIMAL);
+               const auto array = lttng::make_unique<lst::dynamic_length_array_type>(
+                       type.alignment, std::move(uint8_element), type.length_field_location);
+
+               visit(*array);
+       }
+
+       void visit(const lst::null_terminated_string_type& type) final
+       {
+               /* Defaults to UTF-8. */
                if (type.encoding_ == lst::null_terminated_string_type::encoding::ASCII) {
                        _description += "string { encoding = ASCII }";
                } else {
@@ -310,91 +648,121 @@ private:
                }
        }
 
-       virtual void visit(const lst::structure_type& type) override final
+       void visit(const lst::structure_type& type) final
        {
                _indentation_level++;
                _description += "struct {";
 
-               for (const auto& field : type._fields) {
+               const auto previous_bypass_identifier_escape = _bypass_identifier_escape;
+               _bypass_identifier_escape = false;
+               for (const auto& field : type.fields_) {
                        _description += "\n";
                        _description.resize(_description.size() + _indentation_level, '\t');
                        field->accept(*this);
                }
 
+               _bypass_identifier_escape = previous_bypass_identifier_escape;
+
                _indentation_level--;
-               if (type._fields.size() != 0) {
+               if (type.fields_.size() != 0) {
                        _description += "\n";
                        _description.resize(_description.size() + _indentation_level, '\t');
                }
 
-               _description += "};";
+               _description += "}";
        }
 
-       virtual void visit(const lst::variant_type& type) override final
+       template <class MappingIntegerType>
+       void visit_variant(const lst::variant_type<MappingIntegerType>& type)
        {
                if (type.alignment != 0) {
-                       LTTNG_ASSERT(_escaped_current_field_name.size() > 0);
-                       _description += fmt::format(
-                                       "struct {{ }} align({alignment}) {field_name}_padding;\n",
-                                       fmt::arg("alignment", type.alignment),
-                                       fmt::arg("field_name", _escaped_current_field_name));
+                       LTTNG_ASSERT(!_current_field_name.empty());
+                       _description += lttng::format(
+                               "struct {{ }} align({alignment}) {field_name}_padding;\n",
+                               fmt::arg("alignment", type.alignment),
+                               fmt::arg("field_name", _current_field_name.top()));
                        _description.resize(_description.size() + _indentation_level, '\t');
                }
 
                _indentation_level++;
-               _description += fmt::format("variant <{}> {\n", escape_tsdl_identifier(type.tag_name));
-
-               bool first_field = true;
-               for (const auto& field : type._choices) {
-                       if (!first_field) {
-                               _description += ",\n";
-                       }
+               _description += lttng::format(
+                       "variant <{}> {{\n",
+                       _bypass_identifier_escape ?
+                               *(type.selector_field_location.elements_.end() - 1) :
+                               escape_tsdl_identifier(
+                                       *(type.selector_field_location.elements_.end() - 1)));
 
+               /*
+                * The CTF 1.8 specification only recommends that implementations ignore
+                * leading underscores in field names. Both babeltrace 1 and 2 expect the
+                * variant choice and enumeration mapping name to match perfectly. Given that we
+                * don't have access to the tag in this context, we have to assume they match.
+                */
+               const auto previous_bypass_identifier_escape = _bypass_identifier_escape;
+               _bypass_identifier_escape = true;
+               for (const auto& field : type.choices_) {
                        _description.resize(_description.size() + _indentation_level, '\t');
-                       field->accept(*this);
-                       first_field = false;
+                       field.second->accept(*this);
+                       _description += lttng::format(" {};\n", field.first.name);
                }
 
-               _description += "\n";
-               _description.resize(_description.size() + _indentation_level, '\t');
-               _description += "};";
+               _bypass_identifier_escape = previous_bypass_identifier_escape;
+
                _indentation_level--;
+               _description.resize(_description.size() + _indentation_level, '\t');
+               _description += "}";
+       }
+
+       void visit(const lst::variant_type<
+                  lst::signed_enumeration_type::mapping::range_t::range_integer_t>& type) final
+       {
+               visit_variant(type);
+       }
+
+       void visit(const lst::variant_type<
+                  lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>& type) final
+       {
+               visit_variant(type);
        }
 
        lst::type::cuptr create_character_type(enum lst::string_type::encoding encoding)
        {
                _current_integer_encoding_override = encoding;
-               return lttng::make_unique<lst::integer_type>(8, _trace_abi.byte_order, 8,
-                               lst::integer_type::signedness::UNSIGNED,
-                               lst::integer_type::base::DECIMAL);
+               return lttng::make_unique<lst::integer_type>(
+                       8,
+                       _trace_abi.byte_order,
+                       8,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL);
        }
 
-       virtual void visit(const lst::static_length_string_type& type) override final
+       void visit(const lst::static_length_string_type& type) final
        {
                /*
                 * TSDL expresses static-length strings as arrays of 8-bit integer with
                 * an encoding specified.
                 */
                const auto char_array = lttng::make_unique<lst::static_length_array_type>(
-                               type.alignment, create_character_type(type.encoding_), type.length);
+                       type.alignment, create_character_type(type.encoding_), type.length);
 
                visit(*char_array);
        }
 
-       virtual void visit(const lst::dynamic_length_string_type& type) override final
+       void visit(const lst::dynamic_length_string_type& type) final
        {
                /*
                 * TSDL expresses dynamic-length strings as arrays of 8-bit integer with
                 * an encoding specified.
                 */
                const auto char_sequence = lttng::make_unique<lst::dynamic_length_array_type>(
-                               type.alignment, create_character_type(type.encoding_),
-                               type.length_field_name);
+                       type.alignment,
+                       create_character_type(type.encoding_),
+                       type.length_field_location);
 
                visit(*char_sequence);
        }
 
-       std::string _escaped_current_field_name;
+       std::stack<std::string> _current_field_name;
        /*
         * Encoding to specify for the next serialized integer type.
         * Since the integer_type does not allow an encoding to be specified (it is a TSDL-specific
@@ -410,12 +778,49 @@ private:
 
        /* Description in TSDL format. */
        std::string _description;
+
+       bool _bypass_identifier_escape{ false };
+       const char *_default_clock_class_name;
+       const tsdl::details::type_overrider& _type_overrides;
+};
+
+class tsdl_trace_environment_visitor : public lst::trace_class_environment_visitor {
+public:
+       tsdl_trace_environment_visitor() = default;
+
+       void visit(const lst::environment_field<int64_t>& field) override
+       {
+               _environment += lttng::format(" {} = {};\n", field.name, field.value);
+       }
+
+       void visit(const lst::environment_field<const char *>& field) override
+       {
+               /*
+                * clang-format 14 oscillates between two formatting for this
+                * line, disable it locally.
+                */
+               /* clang-format off */
+               _environment += lttng::format(
+                       "       {} = \"{}\";\n", field.name, escape_tsdl_env_string_value(field.value));
+               /* clang-format on */
+       }
+
+       /* Only call once. */
+       std::string move_description()
+       {
+               _environment += "};\n\n";
+               return std::move(_environment);
+       }
+
+private:
+       std::string _environment{ "env {\n" };
 };
 } /* namespace */
 
-tsdl::trace_class_visitor::trace_class_visitor(const lst::abi& trace_abi,
-               tsdl::append_metadata_fragment_function append_metadata_fragment) :
-       _trace_abi{trace_abi}, _append_metadata_fragment(append_metadata_fragment)
+tsdl::trace_class_visitor::trace_class_visitor(
+       const lst::abi& trace_abi,
+       tsdl::append_metadata_fragment_function append_metadata_fragment) :
+       _trace_abi(trace_abi), _append_metadata_fragment(std::move(append_metadata_fragment))
 {
 }
 
@@ -426,198 +831,298 @@ void tsdl::trace_class_visitor::append_metadata_fragment(const std::string& frag
 
 void tsdl::trace_class_visitor::visit(const lttng::sessiond::trace::trace_class& trace_class)
 {
+       /* Ensure this instance is not used against multiple trace classes. */
+       LTTNG_ASSERT(!_current_trace_class || _current_trace_class == &trace_class);
+       _current_trace_class = &trace_class;
+
+       tsdl_field_visitor packet_header_visitor{ trace_class.abi, 1, _sanitized_types_overrides };
+
+       trace_class.packet_header()->accept(packet_header_visitor);
+
        /* Declare type aliases, trace class, and packet header. */
-       auto trace_class_tsdl = fmt::format(
-                       "/* CTF {ctf_major}.{ctf_minor} */\n\n"
-                       "typealias integer {{ size = 8; align = {uint8_t_alignment}; signed = false; }} := uint8_t;\n"
-                       "typealias integer {{ size = 16; align = {uint16_t_alignment}; signed = false; }} := uint16_t;\n"
-                       "typealias integer {{ size = 32; align = {uint32_t_alignment}; signed = false; }} := uint32_t;\n"
-                       "typealias integer {{ size = 64; align = {uint64_t_alignment}; signed = false; }} := uint64_t;\n"
-                       "typealias integer {{ size = {bits_per_long}; align = {long_alignment}; signed = false; }} := unsigned long;\n"
-                       "typealias integer {{ size = 5; align = 1; signed = false; }} := uint5_t;\n"
-                       "typealias integer {{ size = 27; align = 1; signed = false; }} := uint27_t;\n"
-                       "\n"
-                       "trace {{\n"
-                       "       major = {ctf_major};\n"
-                       "       minor = {ctf_minor};\n"
-                       "       uuid = \"{uuid}\";\n"
-                       "       byte_order = {byte_order};\n"
-                       "       packet.header := struct {{\n"
-                       "               uint32_t magic;\n"
-                       "               uint8_t  uuid[16];\n"
-                       "               uint32_t stream_id;\n"
-                       "               uint64_t stream_instance_id;\n"
-                       "       }};\n"
-                       "}};\n\n",
-                       fmt::arg("ctf_major", ctf_spec_major),
-                       fmt::arg("ctf_minor", ctf_spec_minor),
-                       fmt::arg("uint8_t_alignment", trace_class.abi.uint8_t_alignment),
-                       fmt::arg("uint16_t_alignment", trace_class.abi.uint16_t_alignment),
-                       fmt::arg("uint32_t_alignment", trace_class.abi.uint32_t_alignment),
-                       fmt::arg("uint64_t_alignment", trace_class.abi.uint64_t_alignment),
-                       fmt::arg("long_alignment", trace_class.abi.long_alignment),
-                       fmt::arg("long_size", trace_class.abi.long_alignment),
-                       fmt::arg("bits_per_long", trace_class.abi.bits_per_long),
-                       fmt::arg("uuid", lttng::utils::uuid_to_str(trace_class.uuid)),
-                       fmt::arg("byte_order",
-                                       trace_class.abi.byte_order == lst::byte_order::BIG_ENDIAN_ ?
-                                                       "be" :
-                                                             "le"));
+       auto trace_class_tsdl = lttng::format(
+               "/* CTF {ctf_major}.{ctf_minor} */\n\n"
+               "trace {{\n"
+               "       major = {ctf_major};\n"
+               "       minor = {ctf_minor};\n"
+               "       uuid = \"{uuid}\";\n"
+               "       byte_order = {byte_order};\n"
+               "       packet.header := {packet_header_layout};\n"
+               "}};\n\n",
+               fmt::arg("ctf_major", ctf_spec_major),
+               fmt::arg("ctf_minor", ctf_spec_minor),
+               fmt::arg("uint8_t_alignment", trace_class.abi.uint8_t_alignment),
+               fmt::arg("uint16_t_alignment", trace_class.abi.uint16_t_alignment),
+               fmt::arg("uint32_t_alignment", trace_class.abi.uint32_t_alignment),
+               fmt::arg("uint64_t_alignment", trace_class.abi.uint64_t_alignment),
+               fmt::arg("long_alignment", trace_class.abi.long_alignment),
+               fmt::arg("long_size", trace_class.abi.long_alignment),
+               fmt::arg("bits_per_long", trace_class.abi.bits_per_long),
+               fmt::arg("uuid", lttng::utils::uuid_to_str(trace_class.uuid)),
+               fmt::arg("byte_order",
+                        trace_class.abi.byte_order == lst::byte_order::BIG_ENDIAN_ ? "be" : "le"),
+               fmt::arg("packet_header_layout", packet_header_visitor.move_description()));
 
        /* Declare trace scope and type aliases. */
-       append_metadata_fragment(std::move(trace_class_tsdl));
+       append_metadata_fragment(trace_class_tsdl);
+
+       tsdl_trace_environment_visitor environment_visitor;
+       trace_class.accept(environment_visitor);
+       append_metadata_fragment(environment_visitor.move_description());
 }
 
 void tsdl::trace_class_visitor::visit(const lttng::sessiond::trace::clock_class& clock_class)
 {
        auto uuid_str = clock_class.uuid ?
-                       fmt::format("   uuid = \"{}\";\n",
-                                       lttng::utils::uuid_to_str(*clock_class.uuid)) :
-                             "";
+               lttng::format(" uuid = \"{}\";\n", lttng::utils::uuid_to_str(*clock_class.uuid)) :
+               "";
 
        /* Assumes a single clock that maps to specific stream class fields/roles. */
-       auto clock_class_str = fmt::format(
-                       "clock {{\n"
-                       "       name = \"{name}\";\n"
-                       /* Optional uuid. */
-                       "{uuid}"
-                       "       description = \"{description}\";\n"
-                       "       freq = {frequency};\n"
-                       "       offset = {offset};\n"
-                       "}};\n"
-                       "\n"
-                       "typealias integer {{\n"
-                       "       size = 27; align = 1; signed = false;\n"
-                       "       map = clock.{name}.value;\n"
-                       "}} := uint27_clock_{name}_t;\n"
-                       "\n"
-                       "typealias integer {{\n"
-                       "       size = 32; align = {uint32_t_alignment}; signed = false;\n"
-                       "       map = clock.{name}.value;\n"
-                       "}} := uint32_clock_{name}_t;\n"
-                       "\n"
-                       "typealias integer {{\n"
-                       "       size = 64; align = {uint64_t_alignment}; signed = false;\n"
-                       "       map = clock.{name}.value;\n"
-                       "}} := uint64_clock_{name}_t;\n"
-                       "\n"
-                       "struct packet_context {{\n"
-                       "       uint64_clock_{name}_t timestamp_begin;\n"
-                       "       uint64_clock_{name}_t timestamp_end;\n"
-                       "       uint64_t content_size;\n"
-                       "       uint64_t packet_size;\n"
-                       "       uint64_t packet_seq_num;\n"
-                       "       unsigned long events_discarded;\n"
-                       "       uint32_t cpu_id;\n"
-                       "}};\n"
-                       "\n"
-                       "struct event_header_compact {{\n"
-                       "       enum : uint5_t {{ compact = 0 ... 30, extended = 31 }} id;\n"
-                       "       variant <id> {{\n"
-                       "               struct {{\n"
-                       "                       uint27_clock_{name}_t timestamp;\n"
-                       "               }} compact;\n"
-                       "               struct {{\n"
-                       "                       uint32_t id;\n"
-                       "                       uint64_clock_{name}_t timestamp;\n"
-                       "               }} extended;\n"
-                       "       }} v;\n"
-                       "}} align({uint32_t_alignment});\n"
-                       "\n"
-                       "struct event_header_large {{\n"
-                       "       enum : uint16_t {{ compact = 0 ... 65534, extended = 65535 }} id;\n"
-                       "       variant <id> {{\n"
-                       "               struct {{\n"
-                       "                       uint32_clock_{name}_t timestamp;\n"
-                       "               }} compact;\n"
-                       "               struct {{\n"
-                       "                       uint32_t id;\n"
-                       "                       uint64_clock_{name}_t timestamp;\n"
-                       "               }} extended;\n"
-                       "       }} v;\n"
-                       "}} align({uint16_t_alignment});\n\n",
-                       fmt::arg("name", clock_class.name),
-                       fmt::arg("uuid", uuid_str),
-                       fmt::arg("description", clock_class.description),
-                       fmt::arg("frequency", clock_class.frequency),
-                       fmt::arg("offset", clock_class.offset),
-                       fmt::arg("uint16_t_alignment", _trace_abi.uint16_t_alignment),
-                       fmt::arg("uint32_t_alignment", _trace_abi.uint32_t_alignment),
-                       fmt::arg("uint64_t_alignment", _trace_abi.uint64_t_alignment));
-
-       append_metadata_fragment(std::move(clock_class_str));
+       auto clock_class_str = lttng::format("clock {{\n"
+                                            "  name = \"{name}\";\n"
+                                            /* Optional uuid. */
+                                            "{uuid}"
+                                            "  description = \"{description}\";\n"
+                                            "  freq = {frequency};\n"
+                                            "  offset = {offset};\n"
+                                            "}};\n"
+                                            "\n",
+                                            fmt::arg("name", clock_class.name),
+                                            fmt::arg("uuid", uuid_str),
+                                            fmt::arg("description", clock_class.description),
+                                            fmt::arg("frequency", clock_class.frequency),
+                                            fmt::arg("offset", clock_class.offset));
+
+       append_metadata_fragment(clock_class_str);
 }
 
 void tsdl::trace_class_visitor::visit(const lttng::sessiond::trace::stream_class& stream_class)
 {
-       /* Declare stream. */
-       auto stream_class_str = fmt::format("stream {{\n"
-                                           "   id = {id};\n"
-                                           "   event.header := {header_type};\n"
-                                           "   packet.context := struct packet_context;\n",
-                       fmt::arg("id", stream_class.id),
-                       fmt::arg("header_type", stream_class.header_type_ == lst::stream_class::header_type::COMPACT ?
-                                                       "struct event_header_compact" :
-                                                             "struct event_header_large"));
+       _current_stream_class = &stream_class;
+       const auto clear_stream_class_on_exit =
+               lttng::make_scope_exit([this]() noexcept { _current_stream_class = nullptr; });
+
+       auto stream_class_str = lttng::format("stream {{\n"
+                                             " id = {};\n",
+                                             stream_class.id);
+       variant_tsdl_keyword_sanitizer variant_sanitizer(
+               _sanitized_types_overrides,
+               [this](const lttng::sessiond::trace::field_location& location) -> const lst::type& {
+                       return _lookup_field_type(location);
+               });
+
+       const auto *event_header = stream_class.event_header();
+       if (event_header) {
+               tsdl_field_visitor event_header_visitor{ _trace_abi,
+                                                        1,
+                                                        _sanitized_types_overrides,
+                                                        stream_class.default_clock_class_name };
+
+               event_header->accept(variant_sanitizer);
+               event_header->accept(event_header_visitor);
+               stream_class_str += lttng::format("     event.header := {};\n",
+                                                 event_header_visitor.move_description());
+       }
 
-       auto context_field_visitor = tsdl_field_visitor(_trace_abi, 1);
+       const auto *packet_context = stream_class.packet_context();
+       if (packet_context) {
+               tsdl_field_visitor packet_context_visitor{ _trace_abi,
+                                                          1,
+                                                          _sanitized_types_overrides,
+                                                          stream_class.default_clock_class_name };
+
+               packet_context->accept(variant_sanitizer);
+               packet_context->accept(packet_context_visitor);
+               stream_class_str += lttng::format("     packet.context := {};\n",
+                                                 packet_context_visitor.move_description());
+       }
+
+       const auto *event_context = stream_class.event_context();
+       if (event_context) {
+               tsdl_field_visitor event_context_visitor{ _trace_abi,
+                                                         1,
+                                                         _sanitized_types_overrides };
 
-       stream_class.get_context().accept(static_cast<lst::type_visitor&>(context_field_visitor));
+               event_context->accept(variant_sanitizer);
+               event_context->accept(event_context_visitor);
+               stream_class_str += lttng::format("     event.context := {};\n",
+                                                 event_context_visitor.move_description());
+       }
 
-       stream_class_str += fmt::format("       event.context := {}\n}};\n\n",
-                       context_field_visitor.get_description());
+       stream_class_str += "};\n\n";
 
        append_metadata_fragment(stream_class_str);
 }
 
 void tsdl::trace_class_visitor::visit(const lttng::sessiond::trace::event_class& event_class)
 {
-       auto event_class_str = fmt::format("event {{\n"
-                                          "    name = \"{name}\";\n"
-                                          "    id = {id};\n"
-                                          "    stream_id = {stream_class_id};\n"
-                                          "    loglevel = {log_level};\n",
-                       fmt::arg("name", event_class.name),
-                       fmt::arg("id", event_class.id),
-                       fmt::arg("stream_class_id", event_class.stream_class_id),
-                       fmt::arg("log_level", event_class.log_level));
+       _current_event_class = &event_class;
+       const auto clear_event_class_on_exit =
+               lttng::make_scope_exit([this]() noexcept { _current_event_class = nullptr; });
+
+       auto event_class_str =
+               lttng::format("event {{\n"
+                             " name = \"{name}\";\n"
+                             " id = {id};\n"
+                             " stream_id = {stream_class_id};\n"
+                             " loglevel = {log_level};\n",
+                             fmt::arg("name", event_class.name),
+                             fmt::arg("id", event_class.id),
+                             fmt::arg("stream_class_id", event_class.stream_class_id),
+                             fmt::arg("log_level", event_class.log_level));
 
        if (event_class.model_emf_uri) {
-               event_class_str += fmt::format(
-                               "       model.emf.uri = \"{}\";\n", *event_class.model_emf_uri);
+               event_class_str +=
+                       lttng::format(" model.emf.uri = \"{}\";\n", *event_class.model_emf_uri);
        }
 
-       auto payload_visitor = tsdl_field_visitor(_trace_abi, 1);
+       tsdl_field_visitor payload_visitor{ _trace_abi, 1, _sanitized_types_overrides };
+       variant_tsdl_keyword_sanitizer variant_sanitizer(
+               _sanitized_types_overrides,
+               [this](const lttng::sessiond::trace::field_location& location) -> const lst::type& {
+                       return _lookup_field_type(location);
+               });
 
-       event_class.payload->accept(static_cast<lst::type_visitor&>(payload_visitor));
+       event_class.payload->accept(variant_sanitizer);
+       event_class.payload->accept(payload_visitor);
 
-       event_class_str += fmt::format(
-                       "       fields := {}\n}};\n\n", payload_visitor.get_description());
+       event_class_str +=
+               lttng::format(" fields := {};\n}};\n\n", payload_visitor.move_description());
 
        append_metadata_fragment(event_class_str);
 }
 
-void tsdl::trace_class_visitor::environment_begin()
+void tsdl::details::type_overrider::publish(const lttng::sessiond::trace::type& original_type,
+                                           lttng::sessiond::trace::type::cuptr new_type_override)
 {
-       _environment += "env {\n";
+       auto current_override = _overriden_types.find(&original_type);
+
+       if (current_override != _overriden_types.end()) {
+               current_override->second = std::move(new_type_override);
+       } else {
+               _overriden_types.insert(
+                       std::make_pair(&original_type, std::move(new_type_override)));
+       }
 }
 
-void tsdl::trace_class_visitor::visit(
-               const lttng::sessiond::trace::environment_field<int64_t>& field)
+const lst::type&
+tsdl::details::type_overrider::type(const lttng::sessiond::trace::type& original) const noexcept
 {
-       _environment += fmt::format("   {} = {};\n", field.name, field.value);
+       const auto result = _overriden_types.find(&original);
+
+       if (result != _overriden_types.end()) {
+               /* Provide the overriden type. */
+               return *result->second;
+       }
+
+       /* Pass the original type through. */
+       return original;
 }
 
-void tsdl::trace_class_visitor::visit(
-               const lttng::sessiond::trace::environment_field<const char *>& field)
+namespace {
+const lttng::sessiond::trace::type&
+lookup_type_from_root_type(const lttng::sessiond::trace::type& root_type,
+                          const lttng::sessiond::trace::field_location& field_location)
 {
-       _environment += fmt::format(
-                       "       {} = \"{}\";\n", field.name, escape_tsdl_env_string_value(field.value));
+       const auto *type = &root_type;
+
+       for (const auto& location_element : field_location.elements_) {
+               /* Only structures can be traversed. */
+               const auto *struct_type = dynamic_cast<const lst::structure_type *>(type);
+
+               /*
+                * Traverse the type by following the field location path.
+                *
+                * While field paths are assumed to have been validated before-hand,
+                * a dynamic cast is performed here as an additional precaution
+                * since none of this is performance-critical; it can be removed
+                * safely.
+                */
+               if (!struct_type) {
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Encountered a type that is not a structure while traversing field location: field-location=`{}`",
+                               field_location));
+               }
+
+               const auto field_found_it =
+                       std::find_if(struct_type->fields_.cbegin(),
+                                    struct_type->fields_.cend(),
+                                    [&location_element](const lst::field::cuptr& struct_field) {
+                                            return struct_field->name == location_element;
+                                    });
+
+               if (field_found_it == struct_type->fields_.cend()) {
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Failed to find field using field location: field-name:=`{field_name}`, field-location=`{field_location}`",
+                               fmt::arg("field_location", field_location),
+                               fmt::arg("field_name", location_element)));
+               }
+
+               type = &(*field_found_it)->get_type();
+       }
+
+       return *type;
 }
+} /* anonymous namespace. */
 
-void tsdl::trace_class_visitor::environment_end()
+/*
+ * The trace hierarchy is assumed to have been validated on creation.
+ * This function can only fail due to a validation error, hence
+ * why it throws on any unexpected/invalid field location.
+ *
+ * Does not return an overriden field type; it returns the original field type
+ * as found in the trace hierarchy.
+ */
+const lttng::sessiond::trace::type& lttng::sessiond::tsdl::trace_class_visitor::_lookup_field_type(
+       const lttng::sessiond::trace::field_location& location) const
 {
-       _environment += "};\n\n";
-       append_metadata_fragment(_environment);
-       _environment.clear();
+       /* Validate the look-up is happening in a valid visit context. */
+       switch (location.root_) {
+       case lst::field_location::root::EVENT_RECORD_HEADER:
+       case lst::field_location::root::EVENT_RECORD_PAYLOAD:
+               if (!_current_event_class) {
+                       LTTNG_THROW_ERROR(
+                               "Field type look-up failure: no current event class in visitor's context");
+               }
+               /* fall through. */
+       case lst::field_location::root::EVENT_RECORD_COMMON_CONTEXT:
+       case lst::field_location::root::PACKET_CONTEXT:
+               if (!_current_stream_class) {
+                       LTTNG_THROW_ERROR(
+                               "Field type look-up failure: no current stream class in visitor's context");
+               }
+               /* fall through. */
+       case lst::field_location::root::PACKET_HEADER:
+               if (!_current_trace_class) {
+                       LTTNG_THROW_ERROR(
+                               "Field type look-up failure: no current trace class in visitor's context");
+               }
+
+               break;
+       case lst::field_location::root::EVENT_RECORD_SPECIFIC_CONTEXT:
+               LTTNG_THROW_UNSUPPORTED_ERROR(
+                       "Field type look-up failure: event-record specific contexts are not supported");
+       default:
+               LTTNG_THROW_UNSUPPORTED_ERROR(
+                       "Field type look-up failure: unknown field location root");
+       }
+
+       switch (location.root_) {
+       case lst::field_location::root::PACKET_HEADER:
+               return lookup_type_from_root_type(*_current_trace_class->packet_header(), location);
+       case lst::field_location::root::PACKET_CONTEXT:
+               return lookup_type_from_root_type(*_current_stream_class->packet_context(),
+                                                 location);
+       case lst::field_location::root::EVENT_RECORD_HEADER:
+               return lookup_type_from_root_type(*_current_stream_class->event_header(), location);
+       case lst::field_location::root::EVENT_RECORD_COMMON_CONTEXT:
+               return lookup_type_from_root_type(*_current_stream_class->event_context(),
+                                                 location);
+       case lst::field_location::root::EVENT_RECORD_PAYLOAD:
+               return lookup_type_from_root_type(*_current_event_class->payload, location);
+       case lst::field_location::root::EVENT_RECORD_SPECIFIC_CONTEXT:
+       default:
+               /* Unreachable as it was checked before. */
+               abort();
+       }
 }
index 6d629e2beff51dbe35268ca8b8f4721bf7e4031b..c15ee8f4586c24250219c1c7ffddcf48d7587e4c 100644 (file)
@@ -8,13 +8,14 @@
 #ifndef LTTNG_TSDL_TRACE_CLASS_VISITOR_H
 #define LTTNG_TSDL_TRACE_CLASS_VISITOR_H
 
-#include "trace-class.hpp"
-#include "stream-class.hpp"
 #include "event-class.hpp"
+#include "stream-class.hpp"
+#include "trace-class.hpp"
 
 #include <vendor/optional.hpp>
 
 #include <functional>
+#include <unordered_map>
 
 namespace lttng {
 namespace sessiond {
@@ -22,36 +23,73 @@ namespace tsdl {
 
 using append_metadata_fragment_function = std::function<void(const std::string& fragment)>;
 
-class trace_class_visitor : public lttng::sessiond::trace::trace_class_visitor {
+namespace details {
+/*
+ * Register types to be overriden. For example, a TSDL-safe copy of a type can
+ * be added to be overriden whenever the original type is encountered.
+ *
+ * Note that this class assumes no ownership of the original types. It assumes
+ * that the original types live as long as the original trace.
+ */
+class type_overrider {
 public:
-       trace_class_visitor(const lttng::sessiond::trace::abi& trace_abi,
-                       append_metadata_fragment_function append_metadata);
+       type_overrider() = default;
 
-       /* trace class visitor interface. */
-       virtual void visit(const lttng::sessiond::trace::trace_class& trace_class) override final;
+       void publish(const lttng::sessiond::trace::type& original,
+                    lttng::sessiond::trace::type::cuptr new_type_override);
+       const lttng::sessiond::trace::type&
+       type(const lttng::sessiond::trace::type& original) const noexcept;
 
-       /* clock class visitor interface. */
-       virtual void visit(const lttng::sessiond::trace::clock_class& clock_class) override final;
-
-       /* environment visitor interface. */
-       virtual void environment_begin() override final;
-       virtual void visit(const lttng::sessiond::trace::environment_field<int64_t>& field) override final;
-       virtual void visit(const lttng::sessiond::trace::environment_field<const char *>& field) override final;
-       virtual void environment_end() override final;
+private:
+       std::unordered_map<const lttng::sessiond::trace::type *, lttng::sessiond::trace::type::cuptr>
+               _overriden_types;
+};
+} /* namespace details. */
 
-       /* stream class visitor interface. */
-       virtual void visit(const lttng::sessiond::trace::stream_class& stream_class) override final;
+/*
+ * TSDL-producing trace class visitor.
+ *
+ * An instance of this class must not be used on multiple trace class instances.
+ * The `append_metadata` callback is automatically invoked when a coherent
+ * fragment of TSDL is available.
+ */
+class trace_class_visitor : public lttng::sessiond::trace::trace_class_visitor {
+public:
+       trace_class_visitor(const lttng::sessiond::trace::abi& trace_abi,
+                           append_metadata_fragment_function append_metadata);
 
-       /* event class visitor interface. */
-       virtual void visit(const lttng::sessiond::trace::event_class& event_class) override final;
+       void visit(const lttng::sessiond::trace::trace_class& trace_class) final;
+       void visit(const lttng::sessiond::trace::clock_class& clock_class) final;
+       void visit(const lttng::sessiond::trace::stream_class& stream_class) final;
+       void visit(const lttng::sessiond::trace::event_class& event_class) final;
 
 private:
        /* Coherent (parseable) fragments must be appended. */
        void append_metadata_fragment(const std::string& fragment) const;
+       const lttng::sessiond::trace::type&
+       _lookup_field_type(const lttng::sessiond::trace::field_location& field_location) const;
 
        const lttng::sessiond::trace::abi& _trace_abi;
        const append_metadata_fragment_function _append_metadata_fragment;
-       std::string _environment;
+       details::type_overrider _sanitized_types_overrides;
+
+       /*
+        * Current visit context.
+        *
+        * The members of a trace class hierarchy do not provide back-references
+        * up the hierarchy (e.g. stream class to its parent trace class).
+        *
+        * This context allows the visitor to evaluate a "field location".
+        *
+        * _current_trace_class is set the first time a trace class is visited and
+        * remains valid until the destruction of this object.
+        *
+        * _current_stream_class and _current_event_class are set only in the
+        * context of the visit of a stream class and of its event class(es).
+        */
+       const lttng::sessiond::trace::trace_class *_current_trace_class = nullptr;
+       const lttng::sessiond::trace::stream_class *_current_stream_class = nullptr;
+       const lttng::sessiond::trace::event_class *_current_event_class = nullptr;
 };
 
 } /* namespace tsdl */
index 343be56b97ccbc3ba9c4e16644a01b3ded1ec06d..a2a0dcabb3c883756c6d521116a9d05a586febae 100644 (file)
 #ifndef LTTNG_UST_ABI_INTERNAL_H
 #define LTTNG_UST_ABI_INTERNAL_H
 
-#include <stdint.h>
 #include <common/macros.hpp>
 
+#include <stdint.h>
+
 #ifndef LTTNG_PACKED
 #error "LTTNG_PACKED should be defined"
 #endif
 
 #ifndef __ust_stringify
-#define __ust_stringify1(x)    #x
-#define __ust_stringify(x)     __ust_stringify1(x)
+#define __ust_stringify1(x) #x
+#define __ust_stringify(x)  __ust_stringify1(x)
 #endif /* __ust_stringify */
 
-#define LTTNG_UST_ABI_SYM_NAME_LEN             256
-#define LTTNG_UST_ABI_PROCNAME_LEN             16
+#define LTTNG_UST_ABI_SYM_NAME_LEN 256
+#define LTTNG_UST_ABI_PROCNAME_LEN 16
 
 /* UST comm magic number, used to validate protocol and endianness. */
-#define LTTNG_UST_ABI_COMM_MAGIC                       0xC57C57C5
+#define LTTNG_UST_ABI_COMM_MAGIC 0xC57C57C5
 
 /* Version for ABI between liblttng-ust, sessiond, consumerd */
-#define LTTNG_UST_ABI_MAJOR_VERSION                    9
-#define LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE  8
-#define LTTNG_UST_ABI_MINOR_VERSION            0
+#define LTTNG_UST_ABI_MAJOR_VERSION                  9
+#define LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE 8
+#define LTTNG_UST_ABI_MINOR_VERSION                  0
 
 enum lttng_ust_abi_instrumentation {
-       LTTNG_UST_ABI_TRACEPOINT        = 0,
-       LTTNG_UST_ABI_PROBE             = 1,
-       LTTNG_UST_ABI_FUNCTION          = 2,
+       LTTNG_UST_ABI_TRACEPOINT = 0,
+       LTTNG_UST_ABI_PROBE = 1,
+       LTTNG_UST_ABI_FUNCTION = 2,
 };
 
 enum lttng_ust_abi_loglevel_type {
-       LTTNG_UST_ABI_LOGLEVEL_ALL      = 0,
-       LTTNG_UST_ABI_LOGLEVEL_RANGE    = 1,
-       LTTNG_UST_ABI_LOGLEVEL_SINGLE   = 2,
+       LTTNG_UST_ABI_LOGLEVEL_ALL = 0,
+       LTTNG_UST_ABI_LOGLEVEL_RANGE = 1,
+       LTTNG_UST_ABI_LOGLEVEL_SINGLE = 2,
 };
 
 enum lttng_ust_abi_output {
-       LTTNG_UST_ABI_MMAP              = 0,
+       LTTNG_UST_ABI_MMAP = 0,
 };
 
 enum lttng_ust_abi_chan_type {
@@ -62,25 +63,25 @@ struct lttng_ust_abi_tracer_version {
        uint32_t patchlevel;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_CHANNEL_PADDING  (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_CHANNEL_PADDING (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 /*
  * Given that the consumerd is limited to 64k file descriptors, we
  * cannot expect much more than 1MB channel structure size. This size is
  * depends on the number of streams within a channel, which depends on
  * the number of possible CPUs on the system.
  */
-#define LTTNG_UST_ABI_CHANNEL_DATA_MAX_LEN     1048576U
+#define LTTNG_UST_ABI_CHANNEL_DATA_MAX_LEN 1048576U
 struct lttng_ust_abi_channel {
        uint64_t len;
-       int32_t type;   /* enum lttng_ust_abi_chan_type */
+       int32_t type; /* enum lttng_ust_abi_chan_type */
        char padding[LTTNG_UST_ABI_CHANNEL_PADDING];
-       char data[];    /* variable sized data */
+       char data[]; /* variable sized data */
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_STREAM_PADDING1  (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_STREAM_PADDING1 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_stream {
-       uint64_t len;           /* shm len */
-       uint32_t stream_nr;     /* stream number */
+       uint64_t len; /* shm len */
+       uint32_t stream_nr; /* stream number */
        char padding[LTTNG_UST_ABI_STREAM_PADDING1];
        /*
         * shm_fd and wakeup_fd are send over unix socket as file
@@ -110,8 +111,8 @@ struct lttng_ust_abi_counter_dimension {
 
 #define LTTNG_UST_ABI_COUNTER_CONF_PADDING1 67
 struct lttng_ust_abi_counter_conf {
-       uint32_t arithmetic;    /* enum lttng_ust_abi_counter_arithmetic */
-       uint32_t bitness;       /* enum lttng_ust_abi_counter_bitness */
+       uint32_t arithmetic; /* enum lttng_ust_abi_counter_arithmetic */
+       uint32_t bitness; /* enum lttng_ust_abi_counter_bitness */
        uint32_t number_dimensions;
        int64_t global_sum_step;
        struct lttng_ust_abi_counter_dimension dimensions[LTTNG_UST_ABI_COUNTER_DIMENSION_MAX];
@@ -125,15 +126,15 @@ struct lttng_ust_abi_counter_value {
        int64_t value;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_EVENT_PADDING1   8
-#define LTTNG_UST_ABI_EVENT_PADDING2   (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_EVENT_PADDING1 8
+#define LTTNG_UST_ABI_EVENT_PADDING2 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_event {
-       int32_t instrumentation;                /* enum lttng_ust_abi_instrumentation */
-       char name[LTTNG_UST_ABI_SYM_NAME_LEN];  /* event name */
+       int32_t instrumentation; /* enum lttng_ust_abi_instrumentation */
+       char name[LTTNG_UST_ABI_SYM_NAME_LEN]; /* event name */
 
-       int32_t loglevel_type;                  /* enum lttng_ust_abi_loglevel_type */
-       int32_t loglevel;                       /* value, -1: all */
-       uint64_t token;                         /* User-provided token */
+       int32_t loglevel_type; /* enum lttng_ust_abi_loglevel_type */
+       int32_t loglevel; /* value, -1: all */
+       uint64_t token; /* User-provided token */
        char padding[LTTNG_UST_ABI_EVENT_PADDING1];
 
        /* Per instrumentation type configuration */
@@ -142,7 +143,7 @@ struct lttng_ust_abi_event {
        } u;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_EVENT_NOTIFIER_PADDING   32
+#define LTTNG_UST_ABI_EVENT_NOTIFIER_PADDING 32
 struct lttng_ust_abi_event_notifier {
        struct lttng_ust_abi_event event;
        uint64_t error_counter_index;
@@ -156,68 +157,68 @@ struct lttng_ust_abi_event_notifier_notification {
        char padding[LTTNG_UST_ABI_EVENT_NOTIFIER_NOTIFICATION_PADDING];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_COUNTER_PADDING1         (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
-#define LTTNG_UST_ABI_COUNTER_DATA_MAX_LEN     4096U
+#define LTTNG_UST_ABI_COUNTER_PADDING1    (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_COUNTER_DATA_MAX_LEN 4096U
 struct lttng_ust_abi_counter {
        uint64_t len;
        char padding[LTTNG_UST_ABI_COUNTER_PADDING1];
-       char data[];    /* variable sized data */
+       char data[]; /* variable sized data */
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_COUNTER_GLOBAL_PADDING1  (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_COUNTER_GLOBAL_PADDING1 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_counter_global {
-       uint64_t len;           /* shm len */
+       uint64_t len; /* shm len */
        char padding[LTTNG_UST_ABI_COUNTER_GLOBAL_PADDING1];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_COUNTER_CPU_PADDING1     (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_COUNTER_CPU_PADDING1 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_counter_cpu {
-       uint64_t len;           /* shm len */
+       uint64_t len; /* shm len */
        uint32_t cpu_nr;
        char padding[LTTNG_UST_ABI_COUNTER_CPU_PADDING1];
 } LTTNG_PACKED;
 
 enum lttng_ust_abi_field_type {
-       LTTNG_UST_ABI_FIELD_OTHER                       = 0,
-       LTTNG_UST_ABI_FIELD_INTEGER                     = 1,
-       LTTNG_UST_ABI_FIELD_ENUM                        = 2,
-       LTTNG_UST_ABI_FIELD_FLOAT                       = 3,
-       LTTNG_UST_ABI_FIELD_STRING                      = 4,
+       LTTNG_UST_ABI_FIELD_OTHER = 0,
+       LTTNG_UST_ABI_FIELD_INTEGER = 1,
+       LTTNG_UST_ABI_FIELD_ENUM = 2,
+       LTTNG_UST_ABI_FIELD_FLOAT = 3,
+       LTTNG_UST_ABI_FIELD_STRING = 4,
 };
 
-#define LTTNG_UST_ABI_FIELD_ITER_PADDING       (LTTNG_UST_ABI_SYM_NAME_LEN + 28)
+#define LTTNG_UST_ABI_FIELD_ITER_PADDING (LTTNG_UST_ABI_SYM_NAME_LEN + 28)
 struct lttng_ust_abi_field_iter {
        char event_name[LTTNG_UST_ABI_SYM_NAME_LEN];
        char field_name[LTTNG_UST_ABI_SYM_NAME_LEN];
-       int32_t type;                           /* enum lttng_ust_abi_field_type */
-       int loglevel;                           /* event loglevel */
+       int32_t type; /* enum lttng_ust_abi_field_type */
+       int loglevel; /* event loglevel */
        int nowrite;
        char padding[LTTNG_UST_ABI_FIELD_ITER_PADDING];
 } LTTNG_PACKED;
 
 enum lttng_ust_abi_context_type {
-       LTTNG_UST_ABI_CONTEXT_VTID                      = 0,
-       LTTNG_UST_ABI_CONTEXT_VPID                      = 1,
-       LTTNG_UST_ABI_CONTEXT_PTHREAD_ID                = 2,
-       LTTNG_UST_ABI_CONTEXT_PROCNAME                  = 3,
-       LTTNG_UST_ABI_CONTEXT_IP                        = 4,
-       LTTNG_UST_ABI_CONTEXT_PERF_THREAD_COUNTER       = 5,
-       LTTNG_UST_ABI_CONTEXT_CPU_ID                    = 6,
-       LTTNG_UST_ABI_CONTEXT_APP_CONTEXT               = 7,
-       LTTNG_UST_ABI_CONTEXT_CGROUP_NS                 = 8,
-       LTTNG_UST_ABI_CONTEXT_IPC_NS                    = 9,
-       LTTNG_UST_ABI_CONTEXT_MNT_NS                    = 10,
-       LTTNG_UST_ABI_CONTEXT_NET_NS                    = 11,
-       LTTNG_UST_ABI_CONTEXT_PID_NS                    = 12,
-       LTTNG_UST_ABI_CONTEXT_USER_NS                   = 13,
-       LTTNG_UST_ABI_CONTEXT_UTS_NS                    = 14,
-       LTTNG_UST_ABI_CONTEXT_VUID                      = 15,
-       LTTNG_UST_ABI_CONTEXT_VEUID                     = 16,
-       LTTNG_UST_ABI_CONTEXT_VSUID                     = 17,
-       LTTNG_UST_ABI_CONTEXT_VGID                      = 18,
-       LTTNG_UST_ABI_CONTEXT_VEGID                     = 19,
-       LTTNG_UST_ABI_CONTEXT_VSGID                     = 20,
-       LTTNG_UST_ABI_CONTEXT_TIME_NS                   = 21,
+       LTTNG_UST_ABI_CONTEXT_VTID = 0,
+       LTTNG_UST_ABI_CONTEXT_VPID = 1,
+       LTTNG_UST_ABI_CONTEXT_PTHREAD_ID = 2,
+       LTTNG_UST_ABI_CONTEXT_PROCNAME = 3,
+       LTTNG_UST_ABI_CONTEXT_IP = 4,
+       LTTNG_UST_ABI_CONTEXT_PERF_THREAD_COUNTER = 5,
+       LTTNG_UST_ABI_CONTEXT_CPU_ID = 6,
+       LTTNG_UST_ABI_CONTEXT_APP_CONTEXT = 7,
+       LTTNG_UST_ABI_CONTEXT_CGROUP_NS = 8,
+       LTTNG_UST_ABI_CONTEXT_IPC_NS = 9,
+       LTTNG_UST_ABI_CONTEXT_MNT_NS = 10,
+       LTTNG_UST_ABI_CONTEXT_NET_NS = 11,
+       LTTNG_UST_ABI_CONTEXT_PID_NS = 12,
+       LTTNG_UST_ABI_CONTEXT_USER_NS = 13,
+       LTTNG_UST_ABI_CONTEXT_UTS_NS = 14,
+       LTTNG_UST_ABI_CONTEXT_VUID = 15,
+       LTTNG_UST_ABI_CONTEXT_VEUID = 16,
+       LTTNG_UST_ABI_CONTEXT_VSUID = 17,
+       LTTNG_UST_ABI_CONTEXT_VGID = 18,
+       LTTNG_UST_ABI_CONTEXT_VEGID = 19,
+       LTTNG_UST_ABI_CONTEXT_VSGID = 20,
+       LTTNG_UST_ABI_CONTEXT_TIME_NS = 21,
 };
 
 struct lttng_ust_abi_perf_counter_ctx {
@@ -226,10 +227,10 @@ struct lttng_ust_abi_perf_counter_ctx {
        char name[LTTNG_UST_ABI_SYM_NAME_LEN];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_CONTEXT_PADDING1 16
-#define LTTNG_UST_ABI_CONTEXT_PADDING2 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_CONTEXT_PADDING1 16
+#define LTTNG_UST_ABI_CONTEXT_PADDING2 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_context {
-       int32_t ctx;     /* enum lttng_ust_abi_context_type */
+       int32_t ctx; /* enum lttng_ust_abi_context_type */
        char padding[LTTNG_UST_ABI_CONTEXT_PADDING1];
 
        union {
@@ -246,25 +247,25 @@ struct lttng_ust_abi_context {
 /*
  * Tracer channel attributes.
  */
-#define LTTNG_UST_ABI_CHANNEL_ATTR_PADDING     (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_CHANNEL_ATTR_PADDING (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_channel_attr {
-       uint64_t subbuf_size;                   /* bytes */
-       uint64_t num_subbuf;                    /* power of 2 */
-       int overwrite;                          /* 1: overwrite, 0: discard */
-       unsigned int switch_timer_interval;     /* usec */
-       unsigned int read_timer_interval;       /* usec */
-       int32_t output;                         /* enum lttng_ust_abi_output */
+       uint64_t subbuf_size; /* bytes */
+       uint64_t num_subbuf; /* power of 2 */
+       int overwrite; /* 1: overwrite, 0: discard */
+       unsigned int switch_timer_interval; /* usec */
+       unsigned int read_timer_interval; /* usec */
+       int32_t output; /* enum lttng_ust_abi_output */
        union {
                struct {
-                       int64_t blocking_timeout;       /* Blocking timeout (usec) */
+                       int64_t blocking_timeout; /* Blocking timeout (usec) */
                } s;
                char padding[LTTNG_UST_ABI_CHANNEL_ATTR_PADDING];
        } u;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_TRACEPOINT_ITER_PADDING  16
+#define LTTNG_UST_ABI_TRACEPOINT_ITER_PADDING 16
 struct lttng_ust_abi_tracepoint_iter {
-       char name[LTTNG_UST_ABI_SYM_NAME_LEN];  /* provider:name */
+       char name[LTTNG_UST_ABI_SYM_NAME_LEN]; /* provider:name */
        int loglevel;
        char padding[LTTNG_UST_ABI_TRACEPOINT_ITER_PADDING];
 } LTTNG_PACKED;
@@ -282,18 +283,18 @@ enum lttng_ust_abi_object_type {
        LTTNG_UST_ABI_OBJECT_TYPE_COUNTER_CPU = 8,
 };
 
-#define LTTNG_UST_ABI_OBJECT_DATA_PADDING1     32
-#define LTTNG_UST_ABI_OBJECT_DATA_PADDING2     (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_OBJECT_DATA_PADDING1 32
+#define LTTNG_UST_ABI_OBJECT_DATA_PADDING2 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 
 struct lttng_ust_abi_object_data {
-       int32_t type;   /* enum lttng_ust_abi_object_type */
+       int32_t type; /* enum lttng_ust_abi_object_type */
        int handle;
        uint64_t size;
        char padding1[LTTNG_UST_ABI_OBJECT_DATA_PADDING1];
        union {
                struct {
                        void *data;
-                       int32_t type;   /* enum lttng_ust_abi_chan_type */
+                       int32_t type; /* enum lttng_ust_abi_chan_type */
                        int wakeup_fd;
                } channel;
                struct {
@@ -319,10 +320,10 @@ enum lttng_ust_abi_calibrate_type {
        LTTNG_UST_ABI_CALIBRATE_TRACEPOINT,
 };
 
-#define LTTNG_UST_ABI_CALIBRATE_PADDING1       16
-#define LTTNG_UST_ABI_CALIBRATE_PADDING2       (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
+#define LTTNG_UST_ABI_CALIBRATE_PADDING1 16
+#define LTTNG_UST_ABI_CALIBRATE_PADDING2 (LTTNG_UST_ABI_SYM_NAME_LEN + 32)
 struct lttng_ust_abi_calibrate {
-       enum lttng_ust_abi_calibrate_type type;         /* type (input) */
+       enum lttng_ust_abi_calibrate_type type; /* type (input) */
        char padding[LTTNG_UST_ABI_CALIBRATE_PADDING1];
 
        union {
@@ -330,8 +331,8 @@ struct lttng_ust_abi_calibrate {
        } u;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN  65536
-#define LTTNG_UST_ABI_FILTER_PADDING           32
+#define LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN 65536
+#define LTTNG_UST_ABI_FILTER_PADDING         32
 struct lttng_ust_abi_filter_bytecode {
        uint32_t len;
        uint32_t reloc_offset;
@@ -340,8 +341,8 @@ struct lttng_ust_abi_filter_bytecode {
        char data[0];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN 65536
-#define LTTNG_UST_ABI_CAPTURE_PADDING          32
+#define LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN 65536
+#define LTTNG_UST_ABI_CAPTURE_PADDING         32
 struct lttng_ust_abi_capture_bytecode {
        uint32_t len;
        uint32_t reloc_offset;
@@ -350,80 +351,71 @@ struct lttng_ust_abi_capture_bytecode {
        char data[0];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_EXCLUSION_PADDING        32
+#define LTTNG_UST_ABI_EXCLUSION_PADDING 32
 struct lttng_ust_abi_event_exclusion {
        uint32_t count;
        char padding[LTTNG_UST_ABI_EXCLUSION_PADDING];
        char names[LTTNG_UST_ABI_SYM_NAME_LEN][0];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_ABI_CMD(minor)               (minor)
-#define LTTNG_UST_ABI_CMDR(minor, type)                (minor)
-#define LTTNG_UST_ABI_CMDW(minor, type)                (minor)
+#define LTTNG_UST_ABI_CMD(minor)       (minor)
+#define LTTNG_UST_ABI_CMDR(minor, type) (minor)
+#define LTTNG_UST_ABI_CMDW(minor, type) (minor)
 
 /* Handled by object descriptor */
-#define LTTNG_UST_ABI_RELEASE                  LTTNG_UST_ABI_CMD(0x1)
+#define LTTNG_UST_ABI_RELEASE LTTNG_UST_ABI_CMD(0x1)
 
 /* Handled by object cmd */
 
 /* LTTng-UST commands */
-#define LTTNG_UST_ABI_SESSION                  LTTNG_UST_ABI_CMD(0x40)
-#define LTTNG_UST_ABI_TRACER_VERSION           \
-       LTTNG_UST_ABI_CMDR(0x41, struct lttng_ust_abi_tracer_version)
-#define LTTNG_UST_ABI_TRACEPOINT_LIST          LTTNG_UST_ABI_CMD(0x42)
-#define LTTNG_UST_ABI_WAIT_QUIESCENT           LTTNG_UST_ABI_CMD(0x43)
-#define LTTNG_UST_ABI_REGISTER_DONE            LTTNG_UST_ABI_CMD(0x44)
-#define LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST    LTTNG_UST_ABI_CMD(0x45)
-#define LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE \
-       LTTNG_UST_ABI_CMD(0x46)
+#define LTTNG_UST_ABI_SESSION                    LTTNG_UST_ABI_CMD(0x40)
+#define LTTNG_UST_ABI_TRACER_VERSION             LTTNG_UST_ABI_CMDR(0x41, struct lttng_ust_abi_tracer_version)
+#define LTTNG_UST_ABI_TRACEPOINT_LIST            LTTNG_UST_ABI_CMD(0x42)
+#define LTTNG_UST_ABI_WAIT_QUIESCENT             LTTNG_UST_ABI_CMD(0x43)
+#define LTTNG_UST_ABI_REGISTER_DONE              LTTNG_UST_ABI_CMD(0x44)
+#define LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST      LTTNG_UST_ABI_CMD(0x45)
+#define LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE LTTNG_UST_ABI_CMD(0x46)
 
 /* Session commands */
-#define LTTNG_UST_ABI_CHANNEL                  \
-       LTTNG_UST_ABI_CMDW(0x51, struct lttng_ust_abi_channel)
-#define LTTNG_UST_ABI_SESSION_START            LTTNG_UST_ABI_CMD(0x52)
-#define LTTNG_UST_ABI_SESSION_STOP             LTTNG_UST_ABI_CMD(0x53)
-#define LTTNG_UST_ABI_SESSION_STATEDUMP                LTTNG_UST_ABI_CMD(0x54)
+#define LTTNG_UST_ABI_CHANNEL          LTTNG_UST_ABI_CMDW(0x51, struct lttng_ust_abi_channel)
+#define LTTNG_UST_ABI_SESSION_START    LTTNG_UST_ABI_CMD(0x52)
+#define LTTNG_UST_ABI_SESSION_STOP     LTTNG_UST_ABI_CMD(0x53)
+#define LTTNG_UST_ABI_SESSION_STATEDUMP LTTNG_UST_ABI_CMD(0x54)
 
 /* Channel commands */
-#define LTTNG_UST_ABI_STREAM                   LTTNG_UST_ABI_CMD(0x60)
-#define LTTNG_UST_ABI_EVENT                    \
-       LTTNG_UST_ABI_CMDW(0x61, struct lttng_ust_abi_event)
+#define LTTNG_UST_ABI_STREAM LTTNG_UST_ABI_CMD(0x60)
+#define LTTNG_UST_ABI_EVENT  LTTNG_UST_ABI_CMDW(0x61, struct lttng_ust_abi_event)
 
 /* Event and channel commands */
-#define LTTNG_UST_ABI_CONTEXT                  \
-       LTTNG_UST_ABI_CMDW(0x70, struct lttng_ust_abi_context)
-#define LTTNG_UST_ABI_FLUSH_BUFFER             \
-       LTTNG_UST_ABI_CMD(0x71)
+#define LTTNG_UST_ABI_CONTEXT     LTTNG_UST_ABI_CMDW(0x70, struct lttng_ust_abi_context)
+#define LTTNG_UST_ABI_FLUSH_BUFFER LTTNG_UST_ABI_CMD(0x71)
 
 /* Event, event notifier, channel and session commands */
-#define LTTNG_UST_ABI_ENABLE                   LTTNG_UST_ABI_CMD(0x80)
-#define LTTNG_UST_ABI_DISABLE                  LTTNG_UST_ABI_CMD(0x81)
+#define LTTNG_UST_ABI_ENABLE  LTTNG_UST_ABI_CMD(0x80)
+#define LTTNG_UST_ABI_DISABLE LTTNG_UST_ABI_CMD(0x81)
 
 /* Tracepoint list commands */
 #define LTTNG_UST_ABI_TRACEPOINT_LIST_GET      LTTNG_UST_ABI_CMD(0x90)
-#define LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET        LTTNG_UST_ABI_CMD(0x91)
+#define LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET LTTNG_UST_ABI_CMD(0x91)
 
 /* Event and event notifier commands */
-#define LTTNG_UST_ABI_FILTER                   LTTNG_UST_ABI_CMD(0xA0)
-#define LTTNG_UST_ABI_EXCLUSION                        LTTNG_UST_ABI_CMD(0xA1)
+#define LTTNG_UST_ABI_FILTER   LTTNG_UST_ABI_CMD(0xA0)
+#define LTTNG_UST_ABI_EXCLUSION LTTNG_UST_ABI_CMD(0xA1)
 
 /* Event notifier group commands */
-#define LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE    \
+#define LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE \
        LTTNG_UST_ABI_CMDW(0xB0, struct lttng_ust_abi_event_notifier)
 
 /* Event notifier commands */
-#define LTTNG_UST_ABI_CAPTURE                  LTTNG_UST_ABI_CMD(0xB6)
+#define LTTNG_UST_ABI_CAPTURE LTTNG_UST_ABI_CMD(0xB6)
 
 /* Session and event notifier group commands */
-#define LTTNG_UST_ABI_COUNTER                  \
-       LTTNG_UST_ABI_CMDW(0xC0, struct lttng_ust_abi_counter)
+#define LTTNG_UST_ABI_COUNTER LTTNG_UST_ABI_CMDW(0xC0, struct lttng_ust_abi_counter)
 
 /* Counter commands */
-#define LTTNG_UST_ABI_COUNTER_GLOBAL           \
-       LTTNG_UST_ABI_CMDW(0xD0, struct lttng_ust_abi_counter_global)
-#define LTTNG_UST_ABI_COUNTER_CPU              \
-       LTTNG_UST_ABI_CMDW(0xD1, struct lttng_ust_abi_counter_cpu)
+#define LTTNG_UST_ABI_COUNTER_GLOBAL LTTNG_UST_ABI_CMDW(0xD0, struct lttng_ust_abi_counter_global)
+#define LTTNG_UST_ABI_COUNTER_CPU    LTTNG_UST_ABI_CMDW(0xD1, struct lttng_ust_abi_counter_cpu)
 
-#define LTTNG_UST_ABI_ROOT_HANDLE      0
+#define LTTNG_UST_ABI_ROOT_HANDLE 0
 
 #endif /* LTTNG_UST_ABI_INTERNAL_H */
index 88db75f8f4d7da8f1f2ae5cc3d7978cae26fafdd..12250edfdaefb1341736ba5b78c62a53ceba1c8e 100644 (file)
@@ -19,7 +19,6 @@
 #include "lttng-ust-ctl.hpp"
 #include "lttng-ust-error.hpp"
 #include "notification-thread-commands.hpp"
-#include "rotate.hpp"
 #include "session.hpp"
 #include "ust-app.hpp"
 #include "ust-consumer.hpp"
@@ -33,6 +32,7 @@
 #include <common/format.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/make-unique.hpp>
+#include <common/pthread-lock.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/urcu.hpp>
 
@@ -66,8 +66,7 @@ struct lttng_ht *ust_app_ht;
 struct lttng_ht *ust_app_ht_by_sock;
 struct lttng_ht *ust_app_ht_by_notify_sock;
 
-static
-int ust_app_flush_app_session(struct ust_app *app, struct ust_app_session *ua_sess);
+static int ust_app_flush_app_session(ust_app& app, ust_app_session& ua_sess);
 
 /* Next available channel key. Access under next_channel_key_lock. */
 static uint64_t _next_channel_key;
@@ -86,10 +85,9 @@ namespace {
  * A registry per UID object MUST exists before calling this function or else
  * it LTTNG_ASSERT() if not found. RCU read side lock must be acquired.
  */
-static lsu::registry_session *get_session_registry(
-               const struct ust_app_session *ua_sess)
+static lsu::registry_session *get_session_registry(const struct ust_app_session *ua_sess)
 {
-       lsu::registry_session *registry = NULL;
+       lsu::registry_session *registry = nullptr;
 
        LTTNG_ASSERT(ua_sess);
 
@@ -105,9 +103,10 @@ static lsu::registry_session *get_session_registry(
        }
        case LTTNG_BUFFER_PER_UID:
        {
-               struct buffer_reg_uid *reg_uid = buffer_reg_uid_find(
-                               ua_sess->tracing_id, ua_sess->bits_per_long,
-                               lttng_credentials_get_uid(&ua_sess->real_credentials));
+               struct buffer_reg_uid *reg_uid =
+                       buffer_reg_uid_find(ua_sess->tracing_id,
+                                           ua_sess->bits_per_long,
+                                           lttng_credentials_get_uid(&ua_sess->real_credentials));
                if (!reg_uid) {
                        goto error;
                }
@@ -122,22 +121,21 @@ error:
        return registry;
 }
 
-lsu::registry_session::locked_ptr
-get_locked_session_registry(const struct ust_app_session *ua_sess)
+lsu::registry_session::locked_ptr get_locked_session_registry(const struct ust_app_session *ua_sess)
 {
        auto session = get_session_registry(ua_sess);
        if (session) {
                pthread_mutex_lock(&session->_lock);
        }
 
-       return lsu::registry_session::locked_ptr{session};
+       return lsu::registry_session::locked_ptr{ session };
 }
 } /* namespace */
 
 /*
  * Return the incremented value of next_channel_key.
  */
-static uint64_t get_next_channel_key(void)
+static uint64_t get_next_channel_key()
 {
        uint64_t ret;
 
@@ -150,7 +148,7 @@ static uint64_t get_next_channel_key(void)
 /*
  * Return the atomically incremented value of next_session_id.
  */
-static uint64_t get_next_session_id(void)
+static uint64_t get_next_session_id()
 {
        uint64_t ret;
 
@@ -160,9 +158,8 @@ static uint64_t get_next_session_id(void)
        return ret;
 }
 
-static void copy_channel_attr_to_ustctl(
-               struct lttng_ust_ctl_consumer_channel_attr *attr,
-               struct lttng_ust_abi_channel_attr *uattr)
+static void copy_channel_attr_to_ustctl(struct lttng_ust_ctl_consumer_channel_attr *attr,
+                                       struct lttng_ust_abi_channel_attr *uattr)
 {
        /* Copy event attributes since the layout is different. */
        attr->subbuf_size = uattr->subbuf_size;
@@ -184,14 +181,12 @@ static int ht_match_ust_app_event(struct cds_lfht_node *node, const void *_key)
 {
        struct ust_app_event *event;
        const struct ust_app_ht_key *key;
-       int ev_loglevel_value;
 
        LTTNG_ASSERT(node);
        LTTNG_ASSERT(_key);
 
        event = caa_container_of(node, struct ust_app_event, node.node);
        key = (ust_app_ht_key *) _key;
-       ev_loglevel_value = event->attr.loglevel;
 
        /* Match the 4 elements of the key: name, filter, loglevel, exclusions */
 
@@ -201,19 +196,12 @@ static int ht_match_ust_app_event(struct cds_lfht_node *node, const void *_key)
        }
 
        /* Event loglevel. */
-       if (ev_loglevel_value != key->loglevel_type) {
-               if (event->attr.loglevel_type == LTTNG_UST_ABI_LOGLEVEL_ALL
-                               && key->loglevel_type == 0 &&
-                               ev_loglevel_value == -1) {
-                       /*
-                        * Match is accepted. This is because on event creation, the
-                        * loglevel is set to -1 if the event loglevel type is ALL so 0 and
-                        * -1 are accepted for this loglevel type since 0 is the one set by
-                        * the API when receiving an enable event.
-                        */
-               } else {
-                       goto no_match;
-               }
+       if (!loglevels_match(event->attr.loglevel_type,
+                            event->attr.loglevel,
+                            key->loglevel_type,
+                            key->loglevel_value,
+                            LTTNG_UST_ABI_LOGLEVEL_ALL)) {
+               goto no_match;
        }
 
        /* One of the filters is NULL, fail. */
@@ -224,8 +212,7 @@ static int ht_match_ust_app_event(struct cds_lfht_node *node, const void *_key)
        if (key->filter && event->filter) {
                /* Both filters exists, check length followed by the bytecode. */
                if (event->filter->len != key->filter->len ||
-                               memcmp(event->filter->data, key->filter->data,
-                                       event->filter->len) != 0) {
+                   memcmp(event->filter->data, key->filter->data, event->filter->len) != 0) {
                        goto no_match;
                }
        }
@@ -238,13 +225,13 @@ static int ht_match_ust_app_event(struct cds_lfht_node *node, const void *_key)
        if (key->exclusion && event->exclusion) {
                /* Both exclusions exists, check count followed by the names. */
                if (event->exclusion->count != key->exclusion->count ||
-                               memcmp(event->exclusion->names, key->exclusion->names,
-                                       event->exclusion->count * LTTNG_UST_ABI_SYM_NAME_LEN) != 0) {
+                   memcmp(event->exclusion->names,
+                          key->exclusion->names,
+                          event->exclusion->count * LTTNG_UST_ABI_SYM_NAME_LEN) != 0) {
                        goto no_match;
                }
        }
 
-
        /* Match. */
        return 1;
 
@@ -256,8 +243,7 @@ no_match:
  * Unique add of an ust app event in the given ht. This uses the custom
  * ht_match_ust_app_event match function and the event name as hash.
  */
-static void add_unique_ust_app_event(struct ust_app_channel *ua_chan,
-               struct ust_app_event *event)
+static void add_unique_ust_app_event(struct ust_app_channel *ua_chan, struct ust_app_event *event)
 {
        struct cds_lfht_node *node_ptr;
        struct ust_app_ht_key key;
@@ -270,12 +256,15 @@ static void add_unique_ust_app_event(struct ust_app_channel *ua_chan,
        ht = ua_chan->events;
        key.name = event->attr.name;
        key.filter = event->filter;
-       key.loglevel_type = (lttng_ust_abi_loglevel_type) event->attr.loglevel;
+       key.loglevel_type = (lttng_ust_abi_loglevel_type) event->attr.loglevel_type;
+       key.loglevel_value = event->attr.loglevel;
        key.exclusion = event->exclusion;
 
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct(event->node.key, lttng_ht_seed),
-                       ht_match_ust_app_event, &key, &event->node.node);
+                                      ht->hash_fct(event->node.key, lttng_ht_seed),
+                                      ht_match_ust_app_event,
+                                      &key,
+                                      &event->node.node);
        LTTNG_ASSERT(node_ptr == &event->node.node);
 }
 
@@ -305,9 +294,7 @@ static void close_notify_sock_rcu(struct rcu_head *head)
  * Delete ust context safely. RCU read lock must be held before calling
  * this function.
  */
-static
-void delete_ust_app_ctx(int sock, struct ust_app_ctx *ua_ctx,
-               struct ust_app *app)
+static void delete_ust_app_ctx(int sock, struct ust_app_ctx *ua_ctx, struct ust_app *app)
 {
        int ret;
 
@@ -321,18 +308,28 @@ void delete_ust_app_ctx(int sock, struct ust_app_ctx *ua_ctx,
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app release ctx failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app release ctx failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app release ctx obj handle %d failed with ret %d: pid = %d, sock = %d",
-                                               ua_ctx->obj->handle, ret,
-                                               app->pid, app->sock);
+                                   ua_ctx->obj->handle,
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
                free(ua_ctx->obj);
        }
+
+       if (ua_ctx->ctx.ctx == LTTNG_UST_ABI_CONTEXT_APP_CONTEXT) {
+               free(ua_ctx->ctx.u.app_ctx.provider_name);
+               free(ua_ctx->ctx.u.app_ctx.ctx_name);
+       }
+
        free(ua_ctx);
 }
 
@@ -340,9 +337,7 @@ void delete_ust_app_ctx(int sock, struct ust_app_ctx *ua_ctx,
  * Delete ust app event safely. RCU read lock must be held before calling
  * this function.
  */
-static
-void delete_ust_app_event(int sock, struct ust_app_event *ua_event,
-               struct ust_app *app)
+static void delete_ust_app_event(int sock, struct ust_app_event *ua_event, struct ust_app *app)
 {
        int ret;
 
@@ -350,22 +345,26 @@ void delete_ust_app_event(int sock, struct ust_app_event *ua_event,
        ASSERT_RCU_READ_LOCKED();
 
        free(ua_event->filter);
-       if (ua_event->exclusion != NULL)
+       if (ua_event->exclusion != nullptr)
                free(ua_event->exclusion);
-       if (ua_event->obj != NULL) {
+       if (ua_event->obj != nullptr) {
                pthread_mutex_lock(&app->sock_lock);
                ret = lttng_ust_ctl_release_object(sock, ua_event->obj);
                pthread_mutex_unlock(&app->sock_lock);
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app release event failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app release event failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app release event obj failed with ret %d: pid = %d, sock = %d",
-                                               ret, app->pid, app->sock);
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
                free(ua_event->obj);
@@ -377,11 +376,10 @@ void delete_ust_app_event(int sock, struct ust_app_event *ua_event,
  * Delayed reclaim of a ust_app_event_notifier_rule object. This MUST be called
  * through a call_rcu().
  */
-static
-void free_ust_app_event_notifier_rule_rcu(struct rcu_head *head)
+static void free_ust_app_event_notifier_rule_rcu(struct rcu_head *head)
 {
-       struct ust_app_event_notifier_rule *obj = lttng::utils::container_of(
-                       head, &ust_app_event_notifier_rule::rcu_head);
+       struct ust_app_event_notifier_rule *obj =
+               lttng::utils::container_of(head, &ust_app_event_notifier_rule::rcu_head);
 
        free(obj);
 }
@@ -389,32 +387,35 @@ void free_ust_app_event_notifier_rule_rcu(struct rcu_head *head)
 /*
  * Delete ust app event notifier rule safely.
  */
-static void delete_ust_app_event_notifier_rule(int sock,
-               struct ust_app_event_notifier_rule *ua_event_notifier_rule,
-               struct ust_app *app)
+static void delete_ust_app_event_notifier_rule(
+       int sock, struct ust_app_event_notifier_rule *ua_event_notifier_rule, struct ust_app *app)
 {
        int ret;
 
        LTTNG_ASSERT(ua_event_notifier_rule);
 
-       if (ua_event_notifier_rule->exclusion != NULL) {
+       if (ua_event_notifier_rule->exclusion != nullptr) {
                free(ua_event_notifier_rule->exclusion);
        }
 
-       if (ua_event_notifier_rule->obj != NULL) {
+       if (ua_event_notifier_rule->obj != nullptr) {
                pthread_mutex_lock(&app->sock_lock);
                ret = lttng_ust_ctl_release_object(sock, ua_event_notifier_rule->obj);
                pthread_mutex_unlock(&app->sock_lock);
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app release event notifier failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app release event notifier failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app release event notifier failed with ret %d: pid = %d, sock = %d",
-                                               ret, app->pid, app->sock);
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
 
@@ -422,8 +423,7 @@ static void delete_ust_app_event_notifier_rule(int sock,
        }
 
        lttng_trigger_put(ua_event_notifier_rule->trigger);
-       call_rcu(&ua_event_notifier_rule->rcu_head,
-                       free_ust_app_event_notifier_rule_rcu);
+       call_rcu(&ua_event_notifier_rule->rcu_head, free_ust_app_event_notifier_rule_rcu);
 }
 
 /*
@@ -431,8 +431,7 @@ static void delete_ust_app_event_notifier_rule(int sock,
  *
  * Return 0 on success or else a negative value.
  */
-static int release_ust_app_stream(int sock, struct ust_app_stream *stream,
-               struct ust_app *app)
+static int release_ust_app_stream(int sock, struct ust_app_stream *stream, struct ust_app *app)
 {
        int ret = 0;
 
@@ -445,13 +444,17 @@ static int release_ust_app_stream(int sock, struct ust_app_stream *stream,
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app release stream failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app release stream failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app release stream obj failed with ret %d: pid = %d, sock = %d",
-                                               ret, app->pid, app->sock);
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
                lttng_fd_put(LTTNG_FD_APPS, 2);
@@ -465,9 +468,7 @@ static int release_ust_app_stream(int sock, struct ust_app_stream *stream,
  * Delete ust app stream safely. RCU read lock must be held before calling
  * this function.
  */
-static
-void delete_ust_app_stream(int sock, struct ust_app_stream *stream,
-               struct ust_app *app)
+static void delete_ust_app_stream(int sock, struct ust_app_stream *stream, struct ust_app *app)
 {
        LTTNG_ASSERT(stream);
        ASSERT_RCU_READ_LOCKED();
@@ -476,8 +477,7 @@ void delete_ust_app_stream(int sock, struct ust_app_stream *stream,
        free(stream);
 }
 
-static
-void delete_ust_app_channel_rcu(struct rcu_head *head)
+static void delete_ust_app_channel_rcu(struct rcu_head *head)
 {
        struct ust_app_channel *ua_chan =
                lttng::utils::container_of(head, &ust_app_channel::rcu_head);
@@ -494,8 +494,7 @@ void delete_ust_app_channel_rcu(struct rcu_head *head)
  *
  * The session list lock must be held by the caller.
  */
-static
-void save_per_pid_lost_discarded_counters(struct ust_app_channel *ua_chan)
+static void save_per_pid_lost_discarded_counters(struct ust_app_channel *ua_chan)
 {
        uint64_t discarded = 0, lost = 0;
        struct ltt_session *session;
@@ -505,7 +504,7 @@ void save_per_pid_lost_discarded_counters(struct ust_app_channel *ua_chan)
                return;
        }
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        session = session_find_by_id(ua_chan->session->tracing_id);
        if (!session || !session->ust_session) {
                /*
@@ -528,16 +527,17 @@ void save_per_pid_lost_discarded_counters(struct ust_app_channel *ua_chan)
 
        if (ua_chan->attr.overwrite) {
                consumer_get_lost_packets(ua_chan->session->tracing_id,
-                               ua_chan->key, session->ust_session->consumer,
-                               &lost);
+                                         ua_chan->key,
+                                         session->ust_session->consumer,
+                                         &lost);
        } else {
                consumer_get_discarded_events(ua_chan->session->tracing_id,
-                               ua_chan->key, session->ust_session->consumer,
-                               &discarded);
+                                             ua_chan->key,
+                                             session->ust_session->consumer,
+                                             &discarded);
        }
-       uchan = trace_ust_find_channel_by_name(
-                       session->ust_session->domain_global.channels,
-                       ua_chan->name);
+       uchan = trace_ust_find_channel_by_name(session->ust_session->domain_global.channels,
+                                              ua_chan->name);
        if (!uchan) {
                ERR("Missing UST channel to store discarded counters");
                goto end;
@@ -547,7 +547,6 @@ void save_per_pid_lost_discarded_counters(struct ust_app_channel *ua_chan)
        uchan->per_pid_closed_app_lost += lost;
 
 end:
-       rcu_read_unlock();
        if (session) {
                session_put(session);
        }
@@ -560,9 +559,9 @@ end:
  * The session list lock must be held by the caller.
  */
 static void delete_ust_app_channel(int sock,
-               struct ust_app_channel *ua_chan,
-               struct ust_app *app,
-               const lsu::registry_session::locked_ptr& locked_registry)
+                                  struct ust_app_channel *ua_chan,
+                                  struct ust_app *app,
+                                  const lsu::registry_session::locked_ptr& locked_registry)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -576,13 +575,13 @@ static void delete_ust_app_channel(int sock,
        DBG3("UST app deleting channel %s", ua_chan->name);
 
        /* Wipe stream */
-       cds_list_for_each_entry_safe(stream, stmp, &ua_chan->streams.head, list) {
+       cds_list_for_each_entry_safe (stream, stmp, &ua_chan->streams.head, list) {
                cds_list_del(&stream->list);
                delete_ust_app_stream(sock, stream, app);
        }
 
        /* Wipe context */
-       cds_lfht_for_each_entry(ua_chan->ctx->ht, &iter.iter, ua_ctx, node.node) {
+       cds_lfht_for_each_entry (ua_chan->ctx->ht, &iter.iter, ua_ctx, node.node) {
                cds_list_del(&ua_ctx->list);
                ret = lttng_ht_del(ua_chan->ctx, &iter);
                LTTNG_ASSERT(!ret);
@@ -590,8 +589,7 @@ static void delete_ust_app_channel(int sock,
        }
 
        /* Wipe events */
-       cds_lfht_for_each_entry(ua_chan->events->ht, &iter.iter, ua_event,
-                       node.node) {
+       cds_lfht_for_each_entry (ua_chan->events->ht, &iter.iter, ua_event, node.node) {
                ret = lttng_ht_del(ua_chan->events, &iter);
                LTTNG_ASSERT(!ret);
                delete_ust_app_event(sock, ua_event, app);
@@ -602,7 +600,7 @@ static void delete_ust_app_channel(int sock,
                if (locked_registry) {
                        try {
                                locked_registry->remove_channel(ua_chan->key, sock >= 0);
-                       } catch (const std::exception &ex) {
+                       } catch (const std::exceptionex) {
                                DBG("Could not find channel for removal: %s", ex.what());
                        }
                }
@@ -617,7 +615,7 @@ static void delete_ust_app_channel(int sock,
                }
        }
 
-       if (ua_chan->obj != NULL) {
+       if (ua_chan->obj != nullptr) {
                /* Remove channel from application UST object descriptor. */
                iter.iter.node = &ua_chan->ust_objd_node.node;
                ret = lttng_ht_del(app->ust_objd, &iter);
@@ -628,16 +626,20 @@ static void delete_ust_app_channel(int sock,
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app channel %s release failed. Application is dead: pid = %d, sock = %d",
-                                               ua_chan->name, app->pid,
-                                               app->sock);
+                                    ua_chan->name,
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app channel %s release failed. Communication time out: pid = %d, sock = %d",
-                                               ua_chan->name, app->pid,
-                                               app->sock);
+                                    ua_chan->name,
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app channel %s release failed with ret %d: pid = %d, sock = %d",
-                                               ua_chan->name, ret, app->pid,
-                                               app->sock);
+                                   ua_chan->name,
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
                lttng_fd_put(LTTNG_FD_APPS, 1);
@@ -686,11 +688,11 @@ int ust_app_release_object(struct ust_app *app, struct lttng_ust_abi_object_data
  * terminated concurrently).
  */
 ssize_t ust_app_push_metadata(const lsu::registry_session::locked_ptr& locked_registry,
-               struct consumer_socket *socket,
-               int send_zero_data)
+                             struct consumer_socket *socket,
+                             int send_zero_data)
 {
        int ret;
-       char *metadata_str = NULL;
+       char *metadata_str = nullptr;
        size_t len, offset, new_metadata_len_sent;
        ssize_t ret_val;
        uint64_t metadata_key, metadata_version;
@@ -715,7 +717,7 @@ ssize_t ust_app_push_metadata(const lsu::registry_session::locked_ptr& locked_re
        metadata_version = locked_registry->_metadata_version;
        if (len == 0) {
                DBG3("No metadata to push for metadata key %" PRIu64,
-                               locked_registry->_metadata_key);
+                    locked_registry->_metadata_key);
                ret_val = len;
                if (send_zero_data) {
                        DBG("No metadata to push");
@@ -748,8 +750,8 @@ push_data:
         * daemon. Those push and pull schemes are performed on two
         * different bidirectionnal communication sockets.
         */
-       ret = consumer_push_metadata(socket, metadata_key,
-                       metadata_str, len, offset, metadata_version);
+       ret = consumer_push_metadata(
+               socket, metadata_key, metadata_str, len, offset, metadata_version);
        pthread_mutex_lock(&locked_registry->_lock);
        if (ret < 0) {
                /*
@@ -788,8 +790,7 @@ push_data:
                 * send.
                 */
                locked_registry->_metadata_len_sent =
-                       std::max(locked_registry->_metadata_len_sent,
-                               new_metadata_len_sent);
+                       std::max(locked_registry->_metadata_len_sent, new_metadata_len_sent);
        }
        free(metadata_str);
        return len;
@@ -826,7 +827,7 @@ error_push:
  * terminated concurrently).
  */
 static int push_metadata(const lsu::registry_session::locked_ptr& locked_registry,
-               struct consumer_output *consumer)
+                        struct consumer_output *consumer)
 {
        int ret_val;
        ssize_t ret;
@@ -842,8 +843,7 @@ static int push_metadata(const lsu::registry_session::locked_ptr& locked_registr
        }
 
        /* Get consumer socket to use to push the metadata.*/
-       socket = consumer_find_socket_by_bitness(locked_registry->abi.bits_per_long,
-                       consumer);
+       socket = consumer_find_socket_by_bitness(locked_registry->abi.bits_per_long, consumer);
        if (!socket) {
                ret_val = -1;
                goto error;
@@ -872,8 +872,9 @@ error:
  *
  * Return 0 on success else a negative value.
  */
-static int close_metadata(uint64_t metadata_key, unsigned int consumer_bitness,
-               struct consumer_output *consumer)
+static int close_metadata(uint64_t metadata_key,
+                         unsigned int consumer_bitness,
+                         struct consumer_output *consumer)
 {
        int ret;
        struct consumer_socket *socket;
@@ -882,8 +883,7 @@ static int close_metadata(uint64_t metadata_key, unsigned int consumer_bitness,
        LTTNG_ASSERT(consumer);
 
        /* Get consumer socket to use to push the metadata. */
-       socket = consumer_find_socket_by_bitness(consumer_bitness,
-                       consumer);
+       socket = consumer_find_socket_by_bitness(consumer_bitness, consumer);
        if (!socket) {
                ret = -1;
                goto end;
@@ -898,8 +898,7 @@ end:
        return ret;
 }
 
-static
-void delete_ust_app_session_rcu(struct rcu_head *head)
+static void delete_ust_app_session_rcu(struct rcu_head *head)
 {
        struct ust_app_session *ua_sess =
                lttng::utils::container_of(head, &ust_app_session::rcu_head);
@@ -914,9 +913,7 @@ void delete_ust_app_session_rcu(struct rcu_head *head)
  *
  * The session list lock must be held by the caller.
  */
-static
-void delete_ust_app_session(int sock, struct ust_app_session *ua_sess,
-               struct ust_app *app)
+static void delete_ust_app_session(int sock, struct ust_app_session *ua_sess, struct ust_app *app)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -937,8 +934,7 @@ void delete_ust_app_session(int sock, struct ust_app_session *ua_sess,
                (void) push_metadata(locked_registry, ua_sess->consumer);
        }
 
-       cds_lfht_for_each_entry(ua_sess->channels->ht, &iter.iter, ua_chan,
-                       node.node) {
+       cds_lfht_for_each_entry (ua_sess->channels->ht, &iter.iter, ua_chan, node.node) {
                ret = lttng_ht_del(ua_sess->channels, &iter);
                LTTNG_ASSERT(!ret);
                delete_ust_app_channel(sock, ua_chan, app, locked_registry);
@@ -985,13 +981,17 @@ void delete_ust_app_session(int sock, struct ust_app_session *ua_sess,
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app release session handle failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app release session handle failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                    app->pid,
+                                    app->sock);
                        } else {
                                ERR("UST app release session handle failed with ret %d: pid = %d, sock = %d",
-                                               ret, app->pid, app->sock);
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                }
 
@@ -1012,8 +1012,7 @@ void delete_ust_app_session(int sock, struct ust_app_session *ua_sess,
  * Delete a traceable application structure from the global list. Never call
  * this function outside of a call_rcu call.
  */
-static
-void delete_ust_app(struct ust_app *app)
+static void delete_ust_app(struct ust_app *app)
 {
        int ret, sock;
        struct ust_app_session *ua_sess, *tmp_ua_sess;
@@ -1031,26 +1030,26 @@ void delete_ust_app(struct ust_app *app)
        app->sock = -1;
 
        /* Wipe sessions */
-       cds_list_for_each_entry_safe(ua_sess, tmp_ua_sess, &app->teardown_head,
-                       teardown_node) {
+       cds_list_for_each_entry_safe (ua_sess, tmp_ua_sess, &app->teardown_head, teardown_node) {
                /* Free every object in the session and the session. */
-               rcu_read_lock();
+               lttng::urcu::read_lock_guard read_lock;
                delete_ust_app_session(sock, ua_sess, app);
-               rcu_read_unlock();
        }
 
        /* Remove the event notifier rules associated with this app. */
-       rcu_read_lock();
-       cds_lfht_for_each_entry (app->token_to_event_notifier_rule_ht->ht,
-                       &iter.iter, event_notifier_rule, node.node) {
-               ret = lttng_ht_del(app->token_to_event_notifier_rule_ht, &iter);
-               LTTNG_ASSERT(!ret);
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               delete_ust_app_event_notifier_rule(
-                               app->sock, event_notifier_rule, app);
-       }
+               cds_lfht_for_each_entry (app->token_to_event_notifier_rule_ht->ht,
+                                        &iter.iter,
+                                        event_notifier_rule,
+                                        node.node) {
+                       ret = lttng_ht_del(app->token_to_event_notifier_rule_ht, &iter);
+                       LTTNG_ASSERT(!ret);
 
-       rcu_read_unlock();
+                       delete_ust_app_event_notifier_rule(app->sock, event_notifier_rule, app);
+               }
+       }
 
        lttng_ht_destroy(app->sessions);
        lttng_ht_destroy(app->ust_sessions_objd);
@@ -1065,12 +1064,11 @@ void delete_ust_app(struct ust_app *app)
                enum lttng_error_code ret_code;
                enum event_notifier_error_accounting_status status;
 
-               const int event_notifier_read_fd = lttng_pipe_get_readfd(
-                               app->event_notifier_group.event_pipe);
+               const int event_notifier_read_fd =
+                       lttng_pipe_get_readfd(app->event_notifier_group.event_pipe);
 
                ret_code = notification_thread_command_remove_tracer_event_source(
-                               the_notification_thread_handle,
-                               event_notifier_read_fd);
+                       the_notification_thread_handle, event_notifier_read_fd);
                if (ret_code != LTTNG_OK) {
                        ERR("Failed to remove application tracer event source from notification thread");
                }
@@ -1084,8 +1082,8 @@ void delete_ust_app(struct ust_app *app)
                free(app->event_notifier_group.object);
        }
 
-       event_notifier_write_fd_is_open = lttng_pipe_is_write_open(
-                       app->event_notifier_group.event_pipe);
+       event_notifier_write_fd_is_open =
+               lttng_pipe_is_write_open(app->event_notifier_group.event_pipe);
        lttng_pipe_destroy(app->event_notifier_group.event_pipe);
        /*
         * Release the file descriptors reserved for the event notifier pipe.
@@ -1122,13 +1120,11 @@ void delete_ust_app(struct ust_app *app)
 /*
  * URCU intermediate call to delete an UST app.
  */
-static
-void delete_ust_app_rcu(struct rcu_head *head)
+static void delete_ust_app_rcu(struct rcu_head *head)
 {
        struct lttng_ht_node_ulong *node =
                lttng::utils::container_of(head, &lttng_ht_node_ulong::head);
-       struct ust_app *app =
-               lttng::utils::container_of(node, &ust_app::pid_n);
+       struct ust_app *app = lttng::utils::container_of(node, &ust_app::pid_n);
 
        DBG3("Call RCU deleting app PID %d", app->pid);
        delete_ust_app(app);
@@ -1140,8 +1136,7 @@ void delete_ust_app_rcu(struct rcu_head *head)
  *
  * The session list lock must be held by the caller.
  */
-static void destroy_app_session(struct ust_app *app,
-               struct ust_app_session *ua_sess)
+static void destroy_app_session(struct ust_app *app, struct ust_app_session *ua_sess)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -1166,14 +1161,13 @@ end:
 /*
  * Alloc new UST app session.
  */
-static
-struct ust_app_session *alloc_ust_app_session(void)
+static struct ust_app_session *alloc_ust_app_session()
 {
        struct ust_app_session *ua_sess;
 
        /* Init most of the default value by allocating and zeroing */
        ua_sess = zmalloc<ust_app_session>();
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                PERROR("malloc");
                goto error_free;
        }
@@ -1181,27 +1175,26 @@ struct ust_app_session *alloc_ust_app_session(void)
        ua_sess->handle = -1;
        ua_sess->channels = lttng_ht_new(0, LTTNG_HT_TYPE_STRING);
        ua_sess->metadata_attr.type = LTTNG_UST_ABI_CHAN_METADATA;
-       pthread_mutex_init(&ua_sess->lock, NULL);
+       pthread_mutex_init(&ua_sess->lock, nullptr);
 
        return ua_sess;
 
 error_free:
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Alloc new UST app channel.
  */
-static
-struct ust_app_channel *alloc_ust_app_channel(const char *name,
-               struct ust_app_session *ua_sess,
-               struct lttng_ust_abi_channel_attr *attr)
+static struct ust_app_channel *alloc_ust_app_channel(const char *name,
+                                                    struct ust_app_session *ua_sess,
+                                                    struct lttng_ust_abi_channel_attr *attr)
 {
        struct ust_app_channel *ua_chan;
 
        /* Init most of the default value by allocating and zeroing */
        ua_chan = zmalloc<ust_app_channel>();
-       if (ua_chan == NULL) {
+       if (ua_chan == nullptr) {
                PERROR("malloc");
                goto error;
        }
@@ -1210,7 +1203,7 @@ struct ust_app_channel *alloc_ust_app_channel(const char *name,
        strncpy(ua_chan->name, name, sizeof(ua_chan->name));
        ua_chan->name[sizeof(ua_chan->name) - 1] = '\0';
 
-       ua_chan->enabled = 1;
+       ua_chan->enabled = true;
        ua_chan->handle = -1;
        ua_chan->session = ua_sess;
        ua_chan->key = get_next_channel_key();
@@ -1240,7 +1233,7 @@ struct ust_app_channel *alloc_ust_app_channel(const char *name,
        return ua_chan;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1248,12 +1241,12 @@ error:
  *
  * Return newly allocated stream pointer or NULL on error.
  */
-struct ust_app_stream *ust_app_alloc_stream(void)
+struct ust_app_stream *ust_app_alloc_stream()
 {
-       struct ust_app_stream *stream = NULL;
+       struct ust_app_stream *stream = nullptr;
 
        stream = zmalloc<ust_app_stream>();
-       if (stream == NULL) {
+       if (stream == nullptr) {
                PERROR("zmalloc ust app stream");
                goto error;
        }
@@ -1268,20 +1261,18 @@ error:
 /*
  * Alloc new UST app event.
  */
-static
-struct ust_app_event *alloc_ust_app_event(char *name,
-               struct lttng_ust_abi_event *attr)
+static struct ust_app_event *alloc_ust_app_event(char *name, struct lttng_ust_abi_event *attr)
 {
        struct ust_app_event *ua_event;
 
        /* Init most of the default value by allocating and zeroing */
        ua_event = zmalloc<ust_app_event>();
-       if (ua_event == NULL) {
+       if (ua_event == nullptr) {
                PERROR("Failed to allocate ust_app_event structure");
                goto error;
        }
 
-       ua_event->enabled = 1;
+       ua_event->enabled = true;
        strncpy(ua_event->name, name, sizeof(ua_event->name));
        ua_event->name[sizeof(ua_event->name) - 1] = '\0';
        lttng_ht_node_init_str(&ua_event->node, ua_event->name);
@@ -1296,52 +1287,49 @@ struct ust_app_event *alloc_ust_app_event(char *name,
        return ua_event;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Allocate a new UST app event notifier rule.
  */
-static struct ust_app_event_notifier_rule *alloc_ust_app_event_notifier_rule(
-               struct lttng_trigger *trigger)
+static struct ust_app_event_notifier_rule *
+alloc_ust_app_event_notifier_rule(struct lttng_trigger *trigger)
 {
-       enum lttng_event_rule_generate_exclusions_status
-                       generate_exclusion_status;
+       enum lttng_event_rule_generate_exclusions_status generate_exclusion_status;
        enum lttng_condition_status cond_status;
        struct ust_app_event_notifier_rule *ua_event_notifier_rule;
-       struct lttng_condition *condition = NULL;
-       const struct lttng_event_rule *event_rule = NULL;
+       struct lttng_condition *condition = nullptr;
+       const struct lttng_event_rule *event_rule = nullptr;
 
        ua_event_notifier_rule = zmalloc<ust_app_event_notifier_rule>();
-       if (ua_event_notifier_rule == NULL) {
+       if (ua_event_notifier_rule == nullptr) {
                PERROR("Failed to allocate ust_app_event_notifier_rule structure");
                goto error;
        }
 
-       ua_event_notifier_rule->enabled = 1;
+       ua_event_notifier_rule->enabled = true;
        ua_event_notifier_rule->token = lttng_trigger_get_tracer_token(trigger);
-       lttng_ht_node_init_u64(&ua_event_notifier_rule->node,
-                       ua_event_notifier_rule->token);
+       lttng_ht_node_init_u64(&ua_event_notifier_rule->node, ua_event_notifier_rule->token);
 
        condition = lttng_trigger_get_condition(trigger);
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       cond_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       cond_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(cond_status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(event_rule);
 
        ua_event_notifier_rule->error_counter_index =
-                       lttng_condition_event_rule_matches_get_error_counter_index(condition);
+               lttng_condition_event_rule_matches_get_error_counter_index(condition);
        /* Acquire the event notifier's reference to the trigger. */
        lttng_trigger_get(trigger);
 
        ua_event_notifier_rule->trigger = trigger;
        ua_event_notifier_rule->filter = lttng_event_rule_get_filter_bytecode(event_rule);
        generate_exclusion_status = lttng_event_rule_generate_exclusions(
-                       event_rule, &ua_event_notifier_rule->exclusion);
+               event_rule, &ua_event_notifier_rule->exclusion);
        switch (generate_exclusion_status) {
        case LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_OK:
        case LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE:
@@ -1353,7 +1341,7 @@ static struct ust_app_event_notifier_rule *alloc_ust_app_event_notifier_rule(
        }
 
        DBG3("UST app event notifier rule allocated: token = %" PRIu64,
-                       ua_event_notifier_rule->token);
+            ua_event_notifier_rule->token);
 
        return ua_event_notifier_rule;
 
@@ -1361,19 +1349,18 @@ error_put_trigger:
        lttng_trigger_put(trigger);
 error:
        free(ua_event_notifier_rule);
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Alloc new UST app context.
  */
-static
-struct ust_app_ctx *alloc_ust_app_ctx(struct lttng_ust_context_attr *uctx)
+static struct ust_app_ctx *alloc_ust_app_ctx(struct lttng_ust_context_attr *uctx)
 {
        struct ust_app_ctx *ua_ctx;
 
        ua_ctx = zmalloc<ust_app_ctx>();
-       if (ua_ctx == NULL) {
+       if (ua_ctx == nullptr) {
                goto error;
        }
 
@@ -1382,7 +1369,7 @@ struct ust_app_ctx *alloc_ust_app_ctx(struct lttng_ust_context_attr *uctx)
        if (uctx) {
                memcpy(&ua_ctx->ctx, uctx, sizeof(ua_ctx->ctx));
                if (uctx->ctx == LTTNG_UST_ABI_CONTEXT_APP_CONTEXT) {
-                       char *provider_name = NULL, *ctx_name = NULL;
+                       char *provider_name = nullptr, *ctx_name = nullptr;
 
                        provider_name = strdup(uctx->u.app_ctx.provider_name);
                        ctx_name = strdup(uctx->u.app_ctx.ctx_name);
@@ -1401,7 +1388,7 @@ struct ust_app_ctx *alloc_ust_app_ctx(struct lttng_ust_context_attr *uctx)
        return ua_ctx;
 error:
        free(ua_ctx);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1409,20 +1396,21 @@ error:
  *
  * Return allocated filter or NULL on error.
  */
-static struct lttng_ust_abi_filter_bytecode *create_ust_filter_bytecode_from_bytecode(
-               const struct lttng_bytecode *orig_f)
+static struct lttng_ust_abi_filter_bytecode *
+create_ust_filter_bytecode_from_bytecode(const struct lttng_bytecode *orig_f)
 {
-       struct lttng_ust_abi_filter_bytecode *filter = NULL;
+       struct lttng_ust_abi_filter_bytecode *filter = nullptr;
 
        /* Copy filter bytecode. */
        filter = zmalloc<lttng_ust_abi_filter_bytecode>(sizeof(*filter) + orig_f->len);
        if (!filter) {
-               PERROR("Failed to allocate lttng_ust_filter_bytecode: bytecode len = %" PRIu32 " bytes", orig_f->len);
+               PERROR("Failed to allocate lttng_ust_filter_bytecode: bytecode len = %" PRIu32
+                      " bytes",
+                      orig_f->len);
                goto error;
        }
 
-       LTTNG_ASSERT(sizeof(struct lttng_bytecode) ==
-                       sizeof(struct lttng_ust_abi_filter_bytecode));
+       LTTNG_ASSERT(sizeof(struct lttng_bytecode) == sizeof(struct lttng_ust_abi_filter_bytecode));
        memcpy(filter, orig_f, sizeof(*filter) + orig_f->len);
 error:
        return filter;
@@ -1436,17 +1424,19 @@ error:
 static struct lttng_ust_abi_capture_bytecode *
 create_ust_capture_bytecode_from_bytecode(const struct lttng_bytecode *orig_f)
 {
-       struct lttng_ust_abi_capture_bytecode *capture = NULL;
+       struct lttng_ust_abi_capture_bytecode *capture = nullptr;
 
        /* Copy capture bytecode. */
        capture = zmalloc<lttng_ust_abi_capture_bytecode>(sizeof(*capture) + orig_f->len);
        if (!capture) {
-               PERROR("Failed to allocate lttng_ust_abi_capture_bytecode: bytecode len = %" PRIu32 " bytes", orig_f->len);
+               PERROR("Failed to allocate lttng_ust_abi_capture_bytecode: bytecode len = %" PRIu32
+                      " bytes",
+                      orig_f->len);
                goto error;
        }
 
        LTTNG_ASSERT(sizeof(struct lttng_bytecode) ==
-                       sizeof(struct lttng_ust_abi_capture_bytecode));
+                    sizeof(struct lttng_ust_abi_capture_bytecode));
        memcpy(capture, orig_f, sizeof(*capture) + orig_f->len);
 error:
        return capture;
@@ -1463,9 +1453,9 @@ struct ust_app *ust_app_find_by_sock(int sock)
 
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(ust_app_ht_by_sock, (void *)((unsigned long) sock), &iter);
+       lttng_ht_lookup(ust_app_ht_by_sock, (void *) ((unsigned long) sock), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("UST app find by sock %d not found", sock);
                goto error;
        }
@@ -1473,7 +1463,7 @@ struct ust_app *ust_app_find_by_sock(int sock)
        return lttng::utils::container_of(node, &ust_app::sock_n);
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1487,10 +1477,9 @@ static struct ust_app *find_app_by_notify_sock(int sock)
 
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(ust_app_ht_by_notify_sock, (void *)((unsigned long) sock),
-                       &iter);
+       lttng_ht_lookup(ust_app_ht_by_notify_sock, (void *) ((unsigned long) sock), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("UST app find by notify sock %d not found", sock);
                goto error;
        }
@@ -1498,7 +1487,7 @@ static struct ust_app *find_app_by_notify_sock(int sock)
        return lttng::utils::container_of(node, &ust_app::notify_sock_n);
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1508,13 +1497,15 @@ error:
  * Return an ust_app_event object or NULL on error.
  */
 static struct ust_app_event *find_ust_app_event(struct lttng_ht *ht,
-               const char *name, const struct lttng_bytecode *filter,
-               int loglevel_value,
-               const struct lttng_event_exclusion *exclusion)
+                                               const char *name,
+                                               const struct lttng_bytecode *filter,
+                                               lttng_ust_abi_loglevel_type loglevel_type,
+                                               int loglevel_value,
+                                               const struct lttng_event_exclusion *exclusion)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_str *node;
-       struct ust_app_event *event = NULL;
+       struct ust_app_event *event = nullptr;
        struct ust_app_ht_key key;
 
        LTTNG_ASSERT(name);
@@ -1523,15 +1514,19 @@ static struct ust_app_event *find_ust_app_event(struct lttng_ht *ht,
        /* Setup key for event lookup. */
        key.name = name;
        key.filter = filter;
-       key.loglevel_type = (lttng_ust_abi_loglevel_type) loglevel_value;
+       key.loglevel_type = loglevel_type;
+       key.loglevel_value = loglevel_value;
        /* lttng_event_exclusion and lttng_ust_event_exclusion structures are similar */
        key.exclusion = exclusion;
 
        /* Lookup using the event name as hash and a custom match fct. */
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) name, lttng_ht_seed),
-                       ht_match_ust_app_event, &key, &iter.iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) name, lttng_ht_seed),
+                       ht_match_ust_app_event,
+                       &key,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto end;
        }
 
@@ -1547,26 +1542,24 @@ end:
  * Must be called with the RCU read lock held.
  * Return an ust_app_event_notifier_rule object or NULL on error.
  */
-static struct ust_app_event_notifier_rule *find_ust_app_event_notifier_rule(
-               struct lttng_ht *ht, uint64_t token)
+static struct ust_app_event_notifier_rule *find_ust_app_event_notifier_rule(struct lttng_ht *ht,
+                                                                           uint64_t token)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
-       struct ust_app_event_notifier_rule *event_notifier_rule = NULL;
+       struct ust_app_event_notifier_rule *event_notifier_rule = nullptr;
 
        LTTNG_ASSERT(ht);
        ASSERT_RCU_READ_LOCKED();
 
        lttng_ht_lookup(ht, &token, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node == NULL) {
-               DBG2("UST app event notifier rule token not found: token = %" PRIu64,
-                               token);
+       if (node == nullptr) {
+               DBG2("UST app event notifier rule token not found: token = %" PRIu64, token);
                goto end;
        }
 
-       event_notifier_rule = lttng::utils::container_of(
-                       node, &ust_app_event_notifier_rule::node);
+       event_notifier_rule = lttng::utils::container_of(node, &ust_app_event_notifier_rule::node);
 end:
        return event_notifier_rule;
 }
@@ -1576,30 +1569,33 @@ end:
  *
  * Called with UST app session lock held.
  */
-static
-int create_ust_channel_context(struct ust_app_channel *ua_chan,
-               struct ust_app_ctx *ua_ctx, struct ust_app *app)
+static int create_ust_channel_context(struct ust_app_channel *ua_chan,
+                                     struct ust_app_ctx *ua_ctx,
+                                     struct ust_app *app)
 {
        int ret;
 
        health_code_update();
 
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_add_context(app->sock, &ua_ctx->ctx,
-                       ua_chan->obj, &ua_ctx->obj);
+       ret = lttng_ust_ctl_add_context(app->sock, &ua_ctx->ctx, ua_chan->obj, &ua_ctx->obj);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app create channel context failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app create channel context failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app create channel context failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
@@ -1607,7 +1603,8 @@ int create_ust_channel_context(struct ust_app_channel *ua_chan,
        ua_ctx->handle = ua_ctx->obj->handle;
 
        DBG2("UST app context handle %d created successfully for channel %s",
-                       ua_ctx->handle, ua_chan->name);
+            ua_ctx->handle,
+            ua_chan->name);
 
 error:
        health_code_update();
@@ -1618,11 +1615,11 @@ error:
  * Set the filter on the tracer.
  */
 static int set_ust_object_filter(struct ust_app *app,
-               const struct lttng_bytecode *bytecode,
-               struct lttng_ust_abi_object_data *ust_object)
+                                const struct lttng_bytecode *bytecode,
+                                struct lttng_ust_abi_object_data *ust_object)
 {
        int ret;
-       struct lttng_ust_abi_filter_bytecode *ust_bytecode = NULL;
+       struct lttng_ust_abi_filter_bytecode *ust_bytecode = nullptr;
 
        health_code_update();
 
@@ -1632,21 +1629,25 @@ static int set_ust_object_filter(struct ust_app *app,
                goto error;
        }
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_set_filter(app->sock, ust_bytecode,
-                       ust_object);
+       ret = lttng_ust_ctl_set_filter(app->sock, ust_bytecode, ust_object);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app  set filter failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app  set filter failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app  set filter failed with ret %d: pid = %d, sock = %d, object = %p",
-                                       ret, app->pid, app->sock, ust_object);
+                           ret,
+                           app->pid,
+                           app->sock,
+                           ust_object);
                }
                goto error;
        }
@@ -1665,12 +1666,12 @@ error:
  * the captured payloads.
  */
 static int set_ust_capture(struct ust_app *app,
-               const struct lttng_bytecode *bytecode,
-               unsigned int capture_seqnum,
-               struct lttng_ust_abi_object_data *ust_object)
+                          const struct lttng_bytecode *bytecode,
+                          unsigned int capture_seqnum,
+                          struct lttng_ust_abi_object_data *ust_object)
 {
        int ret;
-       struct lttng_ust_abi_capture_bytecode *ust_bytecode = NULL;
+       struct lttng_ust_abi_capture_bytecode *ust_bytecode = nullptr;
 
        health_code_update();
 
@@ -1686,22 +1687,24 @@ static int set_ust_capture(struct ust_app *app,
        ust_bytecode->seqnum = capture_seqnum;
 
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_set_capture(app->sock, ust_bytecode,
-                       ust_object);
+       ret = lttng_ust_ctl_set_capture(app->sock, ust_bytecode, ust_object);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app set capture failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        DBG3("UST app set capture failed. Communication timeout: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app event set capture failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid,
-                                       app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
 
                goto error;
@@ -1715,11 +1718,10 @@ error:
        return ret;
 }
 
-static
-struct lttng_ust_abi_event_exclusion *create_ust_exclusion_from_exclusion(
-               const struct lttng_event_exclusion *exclusion)
+static struct lttng_ust_abi_event_exclusion *
+create_ust_exclusion_from_exclusion(const struct lttng_event_exclusion *exclusion)
 {
-       struct lttng_ust_abi_event_exclusion *ust_exclusion = NULL;
+       struct lttng_ust_abi_event_exclusion *ust_exclusion = nullptr;
        size_t exclusion_alloc_size = sizeof(struct lttng_ust_abi_event_exclusion) +
                LTTNG_UST_ABI_SYM_NAME_LEN * exclusion->count;
 
@@ -1730,7 +1732,7 @@ struct lttng_ust_abi_event_exclusion *create_ust_exclusion_from_exclusion(
        }
 
        LTTNG_ASSERT(sizeof(struct lttng_event_exclusion) ==
-                       sizeof(struct lttng_ust_abi_event_exclusion));
+                    sizeof(struct lttng_ust_abi_event_exclusion));
        memcpy(ust_exclusion, exclusion, exclusion_alloc_size);
 end:
        return ust_exclusion;
@@ -1740,18 +1742,17 @@ end:
  * Set event exclusions on the tracer.
  */
 static int set_ust_object_exclusions(struct ust_app *app,
-               const struct lttng_event_exclusion *exclusions,
-               struct lttng_ust_abi_object_data *ust_object)
+                                    const struct lttng_event_exclusion *exclusions,
+                                    struct lttng_ust_abi_object_data *ust_object)
 {
        int ret;
-       struct lttng_ust_abi_event_exclusion *ust_exclusions = NULL;
+       struct lttng_ust_abi_event_exclusion *ust_exclusions = nullptr;
 
        LTTNG_ASSERT(exclusions && exclusions->count > 0);
 
        health_code_update();
 
-       ust_exclusions = create_ust_exclusion_from_exclusion(
-                       exclusions);
+       ust_exclusions = create_ust_exclusion_from_exclusion(exclusions);
        if (!ust_exclusions) {
                ret = -LTTNG_ERR_NOMEM;
                goto error;
@@ -1763,14 +1764,19 @@ static int set_ust_object_exclusions(struct ust_app *app,
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app event exclusion failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app event exclusion failed. Communication time out(pid: %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app event exclusions failed with ret %d: pid = %d, sock = %d, object = %p",
-                                       ret, app->pid, app->sock, ust_object);
+                           ret,
+                           app->pid,
+                           app->sock,
+                           ust_object);
                }
                goto error;
        }
@@ -1786,8 +1792,7 @@ error:
 /*
  * Disable the specified event on to UST tracer for the UST session.
  */
-static int disable_ust_object(struct ust_app *app,
-               struct lttng_ust_abi_object_data *object)
+static int disable_ust_object(struct ust_app *app, struct lttng_ust_abi_object_data *object)
 {
        int ret;
 
@@ -1800,20 +1805,24 @@ static int disable_ust_object(struct ust_app *app,
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app disable object failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app disable object failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app disable object failed with ret %d: pid = %d, sock = %d, object = %p",
-                                       ret, app->pid, app->sock, object);
+                           ret,
+                           app->pid,
+                           app->sock,
+                           object);
                }
                goto error;
        }
 
-       DBG2("UST app object %p disabled successfully for app: pid = %d",
-                       object, app->pid);
+       DBG2("UST app object %p disabled successfully for app: pid = %d", object, app->pid);
 
 error:
        health_code_update();
@@ -1824,7 +1833,8 @@ error:
  * Disable the specified channel on to UST tracer for the UST session.
  */
 static int disable_ust_channel(struct ust_app *app,
-               struct ust_app_session *ua_sess, struct ust_app_channel *ua_chan)
+                              struct ust_app_session *ua_sess,
+                              struct ust_app_channel *ua_chan)
 {
        int ret;
 
@@ -1837,21 +1847,25 @@ static int disable_ust_channel(struct ust_app *app,
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app disable channel failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app disable channel failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app channel %s disable failed, session handle %d, with ret %d: pid = %d, sock = %d",
-                                       ua_chan->name, ua_sess->handle, ret,
-                                       app->pid, app->sock);
+                           ua_chan->name,
+                           ua_sess->handle,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
 
-       DBG2("UST app channel %s disabled successfully for app: pid = %d",
-                       ua_chan->name, app->pid);
+       DBG2("UST app channel %s disabled successfully for app: pid = %d", ua_chan->name, app->pid);
 
 error:
        health_code_update();
@@ -1862,7 +1876,8 @@ error:
  * Enable the specified channel on to UST tracer for the UST session.
  */
 static int enable_ust_channel(struct ust_app *app,
-               struct ust_app_session *ua_sess, struct ust_app_channel *ua_chan)
+                             struct ust_app_session *ua_sess,
+                             struct ust_app_channel *ua_chan)
 {
        int ret;
 
@@ -1875,23 +1890,29 @@ static int enable_ust_channel(struct ust_app *app,
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app channel %s enable failed. Application is dead: pid = %d, sock = %d",
-                                       ua_chan->name, app->pid, app->sock);
+                            ua_chan->name,
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app channel %s enable failed. Communication time out: pid = %d, sock = %d",
-                                       ua_chan->name, app->pid, app->sock);
+                            ua_chan->name,
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app channel %s enable failed, session handle %d, with ret %d: pid = %d, sock = %d",
-                                       ua_chan->name, ua_sess->handle, ret,
-                                       app->pid, app->sock);
+                           ua_chan->name,
+                           ua_sess->handle,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
 
-       ua_chan->enabled = 1;
+       ua_chan->enabled = true;
 
-       DBG2("UST app channel %s enabled successfully for app: pid = %d",
-                       ua_chan->name, app->pid);
+       DBG2("UST app channel %s enabled successfully for app: pid = %d", ua_chan->name, app->pid);
 
 error:
        health_code_update();
@@ -1901,8 +1922,7 @@ error:
 /*
  * Enable the specified event on to UST tracer for the UST session.
  */
-static int enable_ust_object(
-               struct ust_app *app, struct lttng_ust_abi_object_data *ust_object)
+static int enable_ust_object(struct ust_app *app, struct lttng_ust_abi_object_data *ust_object)
 {
        int ret;
 
@@ -1915,20 +1935,24 @@ static int enable_ust_object(
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app enable object failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app enable object failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app enable object failed with ret %d: pid = %d, sock = %d, object = %p",
-                                       ret, app->pid, app->sock, ust_object);
+                           ret,
+                           app->pid,
+                           app->sock,
+                           ust_object);
                }
                goto error;
        }
 
-       DBG2("UST app object %p enabled successfully for app: pid = %d",
-                       ust_object, app->pid);
+       DBG2("UST app object %p enabled successfully for app: pid = %d", ust_object, app->pid);
 
 error:
        health_code_update();
@@ -1941,7 +1965,8 @@ error:
  * Return 0 on success. On error, a negative value is returned.
  */
 static int send_channel_pid_to_ust(struct ust_app *app,
-               struct ust_app_session *ua_sess, struct ust_app_channel *ua_chan)
+                                  struct ust_app_session *ua_sess,
+                                  struct ust_app_channel *ua_chan)
 {
        int ret;
        struct ust_app_stream *stream, *stmp;
@@ -1952,18 +1977,20 @@ static int send_channel_pid_to_ust(struct ust_app *app,
 
        health_code_update();
 
-       DBG("UST app sending channel %s to UST app sock %d", ua_chan->name,
-                       app->sock);
+       DBG("UST app sending channel %s to UST app sock %d", ua_chan->name, app->sock);
 
        /* Send channel to the application. */
        ret = ust_consumer_send_channel_to_ust(app, ua_sess, ua_chan);
        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
-               ret = -ENOTCONN;        /* Caused by app exiting. */
+               ret = -ENOTCONN; /* Caused by app exiting. */
                goto error;
        } else if (ret == -EAGAIN) {
                /* Caused by timeout. */
-               WARN("Communication with application %d timed out on send_channel for channel \"%s\" of session \"%" PRIu64 "\".",
-                               app->pid, ua_chan->name, ua_sess->tracing_id);
+               WARN("Communication with application %d timed out on send_channel for channel \"%s\" of session \"%" PRIu64
+                    "\".",
+                    app->pid,
+                    ua_chan->name,
+                    ua_sess->tracing_id);
                /* Treat this the same way as an application that is exiting. */
                ret = -ENOTCONN;
                goto error;
@@ -1974,16 +2001,19 @@ static int send_channel_pid_to_ust(struct ust_app *app,
        health_code_update();
 
        /* Send all streams to application. */
-       cds_list_for_each_entry_safe(stream, stmp, &ua_chan->streams.head, list) {
+       cds_list_for_each_entry_safe (stream, stmp, &ua_chan->streams.head, list) {
                ret = ust_consumer_send_stream_to_ust(app, ua_chan, stream);
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = -ENOTCONN; /* Caused by app exiting. */
                        goto error;
                } else if (ret == -EAGAIN) {
                        /* Caused by timeout. */
-                       WARN("Communication with application %d timed out on send_stream for stream \"%s\" of channel \"%s\" of session \"%" PRIu64 "\".",
-                                       app->pid, stream->name, ua_chan->name,
-                                       ua_sess->tracing_id);
+                       WARN("Communication with application %d timed out on send_stream for stream \"%s\" of channel \"%s\" of session \"%" PRIu64
+                            "\".",
+                            app->pid,
+                            stream->name,
+                            ua_chan->name,
+                            ua_sess->tracing_id);
                        /*
                         * Treat this the same way as an application that is
                         * exiting.
@@ -2007,9 +2037,9 @@ error:
  *
  * Should be called with session mutex held.
  */
-static
-int create_ust_event(struct ust_app *app,
-               struct ust_app_channel *ua_chan, struct ust_app_event *ua_event)
+static int create_ust_event(struct ust_app *app,
+                           struct ust_app_channel *ua_chan,
+                           struct ust_app_event *ua_event)
 {
        int ret = 0;
 
@@ -2017,22 +2047,25 @@ int create_ust_event(struct ust_app *app,
 
        /* Create UST event on tracer */
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_create_event(app->sock, &ua_event->attr, ua_chan->obj,
-                       &ua_event->obj);
+       ret = lttng_ust_ctl_create_event(app->sock, &ua_event->attr, ua_chan->obj, &ua_event->obj);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app create event failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app create event failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app create event '%s' failed with ret %d: pid = %d, sock = %d",
-                                       ua_event->attr.name, ret, app->pid,
-                                       app->sock);
+                           ua_event->attr.name,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
@@ -2040,7 +2073,9 @@ int create_ust_event(struct ust_app *app,
        ua_event->handle = ua_event->obj->handle;
 
        DBG2("UST app event %s created successfully for pid:%d object = %p",
-                       ua_event->attr.name, app->pid, ua_event->obj);
+            ua_event->attr.name,
+            app->pid,
+            ua_event->obj);
 
        health_code_update();
 
@@ -2093,16 +2128,15 @@ error:
        return ret;
 }
 
-static int init_ust_event_notifier_from_event_rule(
-               const struct lttng_event_rule *rule,
-               struct lttng_ust_abi_event_notifier *event_notifier)
+static int
+init_ust_event_notifier_from_event_rule(const struct lttng_event_rule *rule,
+                                       struct lttng_ust_abi_event_notifier *event_notifier)
 {
        enum lttng_event_rule_status status;
        enum lttng_ust_abi_loglevel_type ust_loglevel_type = LTTNG_UST_ABI_LOGLEVEL_ALL;
        int loglevel = -1, ret = 0;
        const char *pattern;
 
-
        memset(event_notifier, 0, sizeof(*event_notifier));
 
        if (lttng_event_rule_targets_agent_domain(rule)) {
@@ -2112,15 +2146,14 @@ static int init_ust_event_notifier_from_event_rule(
                 * attached later on.
                 * Set the default values for the agent event.
                 */
-               pattern = event_get_default_agent_ust_name(
-                               lttng_event_rule_get_domain_type(rule));
+               pattern = event_get_default_agent_ust_name(lttng_event_rule_get_domain_type(rule));
                loglevel = 0;
                ust_loglevel_type = LTTNG_UST_ABI_LOGLEVEL_ALL;
        } else {
                const struct lttng_log_level_rule *log_level_rule;
 
                LTTNG_ASSERT(lttng_event_rule_get_type(rule) ==
-                               LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT);
+                            LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT);
 
                status = lttng_event_rule_user_tracepoint_get_name_pattern(rule, &pattern);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
@@ -2128,8 +2161,7 @@ static int init_ust_event_notifier_from_event_rule(
                        abort();
                }
 
-               status = lttng_event_rule_user_tracepoint_get_log_level_rule(
-                               rule, &log_level_rule);
+               status = lttng_event_rule_user_tracepoint_get_log_level_rule(rule, &log_level_rule);
                if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
                        ust_loglevel_type = LTTNG_UST_ABI_LOGLEVEL_ALL;
                } else if (status == LTTNG_EVENT_RULE_STATUS_OK) {
@@ -2138,13 +2170,13 @@ static int init_ust_event_notifier_from_event_rule(
                        switch (lttng_log_level_rule_get_type(log_level_rule)) {
                        case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
                                ust_loglevel_type = LTTNG_UST_ABI_LOGLEVEL_SINGLE;
-                               llr_status = lttng_log_level_rule_exactly_get_level(
-                                               log_level_rule, &loglevel);
+                               llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule,
+                                                                                   &loglevel);
                                break;
                        case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                                ust_loglevel_type = LTTNG_UST_ABI_LOGLEVEL_RANGE;
                                llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                               log_level_rule, &loglevel);
+                                       log_level_rule, &loglevel);
                                break;
                        default:
                                abort();
@@ -2158,11 +2190,10 @@ static int init_ust_event_notifier_from_event_rule(
        }
 
        event_notifier->event.instrumentation = LTTNG_UST_ABI_TRACEPOINT;
-       ret = lttng_strncpy(event_notifier->event.name, pattern,
-                       sizeof(event_notifier->event.name));
+       ret = lttng_strncpy(
+               event_notifier->event.name, pattern, sizeof(event_notifier->event.name));
        if (ret) {
-               ERR("Failed to copy event rule pattern to notifier: pattern = '%s' ",
-                               pattern);
+               ERR("Failed to copy event rule pattern to notifier: pattern = '%s' ", pattern);
                goto end;
        }
 
@@ -2177,13 +2208,13 @@ end:
  * given application.
  */
 static int create_ust_event_notifier(struct ust_app *app,
-               struct ust_app_event_notifier_rule *ua_event_notifier_rule)
+                                    struct ust_app_event_notifier_rule *ua_event_notifier_rule)
 {
        int ret = 0;
        enum lttng_condition_status condition_status;
-       const struct lttng_condition *condition = NULL;
+       const struct lttng_condition *condition = nullptr;
        struct lttng_ust_abi_event_notifier event_notifier;
-       const struct lttng_event_rule *event_rule = NULL;
+       const struct lttng_event_rule *event_rule = nullptr;
        unsigned int capture_bytecode_count = 0, i;
        enum lttng_condition_status cond_status;
        enum lttng_event_rule_type event_rule_type;
@@ -2191,25 +2222,21 @@ static int create_ust_event_notifier(struct ust_app *app,
        health_code_update();
        LTTNG_ASSERT(app->event_notifier_group.object);
 
-       condition = lttng_trigger_get_const_condition(
-                       ua_event_notifier_rule->trigger);
+       condition = lttng_trigger_get_const_condition(ua_event_notifier_rule->trigger);
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(lttng_condition_get_type(condition) ==
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+                    LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
 
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        LTTNG_ASSERT(event_rule);
 
        event_rule_type = lttng_event_rule_get_type(event_rule);
        LTTNG_ASSERT(event_rule_type == LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT ||
-                       event_rule_type == LTTNG_EVENT_RULE_TYPE_JUL_LOGGING ||
-                       event_rule_type ==
-                                       LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING ||
-                       event_rule_type ==
-                                       LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING);
+                    event_rule_type == LTTNG_EVENT_RULE_TYPE_JUL_LOGGING ||
+                    event_rule_type == LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING ||
+                    event_rule_type == LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING);
 
        init_ust_event_notifier_from_event_rule(event_rule, &event_notifier);
        event_notifier.event.token = ua_event_notifier_rule->token;
@@ -2217,23 +2244,28 @@ static int create_ust_event_notifier(struct ust_app *app,
 
        /* Create UST event notifier against the tracer. */
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_create_event_notifier(app->sock, &event_notifier,
-                       app->event_notifier_group.object,
-                       &ua_event_notifier_rule->obj);
+       ret = lttng_ust_ctl_create_event_notifier(app->sock,
+                                                 &event_notifier,
+                                                 app->event_notifier_group.object,
+                                                 &ua_event_notifier_rule->obj);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app create event notifier failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app create event notifier failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app create event notifier '%s' failed with ret %d: pid = %d, sock = %d",
-                                       event_notifier.event.name, ret, app->pid,
-                                       app->sock);
+                           event_notifier.event.name,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
@@ -2241,15 +2273,17 @@ static int create_ust_event_notifier(struct ust_app *app,
        ua_event_notifier_rule->handle = ua_event_notifier_rule->obj->handle;
 
        DBG2("UST app event notifier %s created successfully: app = '%s': pid = %d, object = %p",
-                       event_notifier.event.name, app->name, app->pid,
-                       ua_event_notifier_rule->obj);
+            event_notifier.event.name,
+            app->name,
+            app->pid,
+            ua_event_notifier_rule->obj);
 
        health_code_update();
 
        /* Set filter if one is present. */
        if (ua_event_notifier_rule->filter) {
-               ret = set_ust_object_filter(app, ua_event_notifier_rule->filter,
-                               ua_event_notifier_rule->obj);
+               ret = set_ust_object_filter(
+                       app, ua_event_notifier_rule->filter, ua_event_notifier_rule->obj);
                if (ret < 0) {
                        goto error;
                }
@@ -2257,9 +2291,8 @@ static int create_ust_event_notifier(struct ust_app *app,
 
        /* Set exclusions for the event. */
        if (ua_event_notifier_rule->exclusion) {
-               ret = set_ust_object_exclusions(app,
-                               ua_event_notifier_rule->exclusion,
-                               ua_event_notifier_rule->obj);
+               ret = set_ust_object_exclusions(
+                       app, ua_event_notifier_rule->exclusion, ua_event_notifier_rule->obj);
                if (ret < 0) {
                        goto error;
                }
@@ -2267,16 +2300,15 @@ static int create_ust_event_notifier(struct ust_app *app,
 
        /* Set the capture bytecodes. */
        cond_status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &capture_bytecode_count);
+               condition, &capture_bytecode_count);
        LTTNG_ASSERT(cond_status == LTTNG_CONDITION_STATUS_OK);
 
        for (i = 0; i < capture_bytecode_count; i++) {
                const struct lttng_bytecode *capture_bytecode =
-                               lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
-                                               condition, i);
+                       lttng_condition_event_rule_matches_get_capture_bytecode_at_index(condition,
+                                                                                        i);
 
-               ret = set_ust_capture(app, capture_bytecode, i,
-                               ua_event_notifier_rule->obj);
+               ret = set_ust_capture(app, capture_bytecode, i, ua_event_notifier_rule->obj);
                if (ret < 0) {
                        goto error;
                }
@@ -2318,8 +2350,7 @@ error:
 /*
  * Copy data between an UST app event and a LTT event.
  */
-static void shadow_copy_event(struct ust_app_event *ua_event,
-               struct ltt_ust_event *uevent)
+static void shadow_copy_event(struct ust_app_event *ua_event, struct ltt_ust_event *uevent)
 {
        size_t exclusion_alloc_size;
 
@@ -2340,13 +2371,12 @@ static void shadow_copy_event(struct ust_app_event *ua_event,
        /* Copy exclusion data */
        if (uevent->exclusion) {
                exclusion_alloc_size = sizeof(struct lttng_event_exclusion) +
-                               LTTNG_UST_ABI_SYM_NAME_LEN * uevent->exclusion->count;
+                       LTTNG_UST_ABI_SYM_NAME_LEN * uevent->exclusion->count;
                ua_event->exclusion = zmalloc<lttng_event_exclusion>(exclusion_alloc_size);
-               if (ua_event->exclusion == NULL) {
+               if (ua_event->exclusion == nullptr) {
                        PERROR("malloc");
                } else {
-                       memcpy(ua_event->exclusion, uevent->exclusion,
-                                       exclusion_alloc_size);
+                       memcpy(ua_event->exclusion, uevent->exclusion, exclusion_alloc_size);
                }
        }
 }
@@ -2354,8 +2384,7 @@ static void shadow_copy_event(struct ust_app_event *ua_event,
 /*
  * Copy data between an UST app channel and a LTT channel.
  */
-static void shadow_copy_channel(struct ust_app_channel *ua_chan,
-               struct ltt_ust_channel *uchan)
+static void shadow_copy_channel(struct ust_app_channel *ua_chan, struct ltt_ust_channel *uchan)
 {
        DBG2("UST app shadow copy of channel %s started", ua_chan->name);
 
@@ -2390,7 +2419,8 @@ static void shadow_copy_channel(struct ust_app_channel *ua_chan,
  * Copy data between a UST app session and a regular LTT session.
  */
 static void shadow_copy_session(struct ust_app_session *ua_sess,
-               struct ltt_ust_session *usess, struct ust_app *app)
+                               struct ltt_ust_session *usess,
+                               struct ust_app *app)
 {
        struct tm *timeinfo;
        char datetime[16];
@@ -2417,20 +2447,23 @@ static void shadow_copy_session(struct ust_app_session *ua_sess,
 
        ua_sess->output_traces = usess->output_traces;
        ua_sess->live_timer_interval = usess->live_timer_interval;
-       copy_channel_attr_to_ustctl(&ua_sess->metadata_attr,
-                       &usess->metadata_attr);
+       copy_channel_attr_to_ustctl(&ua_sess->metadata_attr, &usess->metadata_attr);
 
        switch (ua_sess->buffer_type) {
        case LTTNG_BUFFER_PER_PID:
-               ret = snprintf(ua_sess->path, sizeof(ua_sess->path),
-                               DEFAULT_UST_TRACE_PID_PATH "/%s-%d-%s", app->name, app->pid,
-                               datetime);
+               ret = snprintf(ua_sess->path,
+                              sizeof(ua_sess->path),
+                              DEFAULT_UST_TRACE_PID_PATH "/%s-%d-%s",
+                              app->name,
+                              app->pid,
+                              datetime);
                break;
        case LTTNG_BUFFER_PER_UID:
-               ret = snprintf(ua_sess->path, sizeof(ua_sess->path),
-                               DEFAULT_UST_TRACE_UID_PATH,
-                               lttng_credentials_get_uid(&ua_sess->real_credentials),
-                               app->abi.bits_per_long);
+               ret = snprintf(ua_sess->path,
+                              sizeof(ua_sess->path),
+                              DEFAULT_UST_TRACE_UID_PATH,
+                              lttng_credentials_get_uid(&ua_sess->real_credentials),
+                              app->abi.bits_per_long);
                break;
        default:
                abort();
@@ -2442,23 +2475,26 @@ static void shadow_copy_session(struct ust_app_session *ua_sess,
                goto error;
        }
 
-       strncpy(ua_sess->root_shm_path, usess->root_shm_path,
-               sizeof(ua_sess->root_shm_path));
+       strncpy(ua_sess->root_shm_path, usess->root_shm_path, sizeof(ua_sess->root_shm_path));
        ua_sess->root_shm_path[sizeof(ua_sess->root_shm_path) - 1] = '\0';
-       strncpy(ua_sess->shm_path, usess->shm_path,
-               sizeof(ua_sess->shm_path));
+       strncpy(ua_sess->shm_path, usess->shm_path, sizeof(ua_sess->shm_path));
        ua_sess->shm_path[sizeof(ua_sess->shm_path) - 1] = '\0';
        if (ua_sess->shm_path[0]) {
                switch (ua_sess->buffer_type) {
                case LTTNG_BUFFER_PER_PID:
-                       ret = snprintf(tmp_shm_path, sizeof(tmp_shm_path),
-                                       "/" DEFAULT_UST_TRACE_PID_PATH "/%s-%d-%s",
-                                       app->name, app->pid, datetime);
+                       ret = snprintf(tmp_shm_path,
+                                      sizeof(tmp_shm_path),
+                                      "/" DEFAULT_UST_TRACE_PID_PATH "/%s-%d-%s",
+                                      app->name,
+                                      app->pid,
+                                      datetime);
                        break;
                case LTTNG_BUFFER_PER_UID:
-                       ret = snprintf(tmp_shm_path, sizeof(tmp_shm_path),
-                                       "/" DEFAULT_UST_TRACE_UID_PATH,
-                                       app->uid, app->abi.bits_per_long);
+                       ret = snprintf(tmp_shm_path,
+                                      sizeof(tmp_shm_path),
+                                      "/" DEFAULT_UST_TRACE_UID_PATH,
+                                      app->uid,
+                                      app->abi.bits_per_long);
                        break;
                default:
                        abort();
@@ -2469,7 +2505,8 @@ static void shadow_copy_session(struct ust_app_session *ua_sess,
                        abort();
                        goto error;
                }
-               strncat(ua_sess->shm_path, tmp_shm_path,
+               strncat(ua_sess->shm_path,
+                       tmp_shm_path,
                        sizeof(ua_sess->shm_path) - strlen(ua_sess->shm_path) - 1);
                ua_sess->shm_path[sizeof(ua_sess->shm_path) - 1] = '\0';
        }
@@ -2482,9 +2519,9 @@ error:
 /*
  * Lookup sesison wrapper.
  */
-static
-void __lookup_session_by_app(const struct ltt_ust_session *usess,
-                       struct ust_app *app, struct lttng_ht_iter *iter)
+static void __lookup_session_by_app(const struct ltt_ust_session *usess,
+                                   struct ust_app *app,
+                                   struct lttng_ht_iter *iter)
 {
        /* Get right UST app session from app */
        lttng_ht_lookup(app->sessions, &usess->id, iter);
@@ -2494,22 +2531,22 @@ void __lookup_session_by_app(const struct ltt_ust_session *usess,
  * Return ust app session from the app session hashtable using the UST session
  * id.
  */
-static struct ust_app_session *lookup_session_by_app(
-               const struct ltt_ust_session *usess, struct ust_app *app)
+static struct ust_app_session *lookup_session_by_app(const struct ltt_ust_session *usess,
+                                                    struct ust_app *app)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
 
        __lookup_session_by_app(usess, app, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                goto error;
        }
 
        return lttng::utils::container_of(node, &ust_app_session::node);
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -2520,7 +2557,8 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int setup_buffer_reg_pid(struct ust_app_session *ua_sess,
-               struct ust_app *app, struct buffer_reg_pid **regp)
+                               struct ust_app *app,
+                               struct buffer_reg_pid **regp)
 {
        int ret = 0;
        struct buffer_reg_pid *reg_pid;
@@ -2528,7 +2566,7 @@ static int setup_buffer_reg_pid(struct ust_app_session *ua_sess,
        LTTNG_ASSERT(ua_sess);
        LTTNG_ASSERT(app);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        reg_pid = buffer_reg_pid_find(ua_sess->id);
        if (!reg_pid) {
@@ -2536,8 +2574,8 @@ static int setup_buffer_reg_pid(struct ust_app_session *ua_sess,
                 * This is the create channel path meaning that if there is NO
                 * registry available, we have to create one for this session.
                 */
-               ret = buffer_reg_pid_create(ua_sess->id, &reg_pid,
-                       ua_sess->root_shm_path, ua_sess->shm_path);
+               ret = buffer_reg_pid_create(
+                       ua_sess->id, &reg_pid, ua_sess->root_shm_path, ua_sess->shm_path);
                if (ret < 0) {
                        goto error;
                }
@@ -2546,12 +2584,16 @@ static int setup_buffer_reg_pid(struct ust_app_session *ua_sess,
        }
 
        /* Initialize registry. */
-       reg_pid->registry->reg.ust = ust_registry_session_per_pid_create(app, app->abi,
-                       app->version.major, app->version.minor, reg_pid->root_shm_path,
-                       reg_pid->shm_path,
-                       lttng_credentials_get_uid(&ua_sess->effective_credentials),
-                       lttng_credentials_get_gid(&ua_sess->effective_credentials),
-                       ua_sess->tracing_id);
+       reg_pid->registry->reg.ust = ust_registry_session_per_pid_create(
+               app,
+               app->abi,
+               app->version.major,
+               app->version.minor,
+               reg_pid->root_shm_path,
+               reg_pid->shm_path,
+               lttng_credentials_get_uid(&ua_sess->effective_credentials),
+               lttng_credentials_get_gid(&ua_sess->effective_credentials),
+               ua_sess->tracing_id);
        if (!reg_pid->registry->reg.ust) {
                /*
                 * reg_pid->registry->reg.ust is NULL upon error, so we need to
@@ -2572,7 +2614,6 @@ end:
                *regp = reg_pid;
        }
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -2584,8 +2625,9 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int setup_buffer_reg_uid(struct ltt_ust_session *usess,
-               struct ust_app_session *ua_sess,
-               struct ust_app *app, struct buffer_reg_uid **regp)
+                               struct ust_app_session *ua_sess,
+                               struct ust_app *app,
+                               struct buffer_reg_uid **regp)
 {
        int ret = 0;
        struct buffer_reg_uid *reg_uid;
@@ -2593,7 +2635,7 @@ static int setup_buffer_reg_uid(struct ltt_ust_session *usess,
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(app);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        reg_uid = buffer_reg_uid_find(usess->id, app->abi.bits_per_long, app->uid);
        if (!reg_uid) {
@@ -2601,9 +2643,13 @@ static int setup_buffer_reg_uid(struct ltt_ust_session *usess,
                 * This is the create channel path meaning that if there is NO
                 * registry available, we have to create one for this session.
                 */
-               ret = buffer_reg_uid_create(usess->id, app->abi.bits_per_long, app->uid,
-                               LTTNG_DOMAIN_UST, &reg_uid, ua_sess->root_shm_path,
-                               ua_sess->shm_path);
+               ret = buffer_reg_uid_create(usess->id,
+                                           app->abi.bits_per_long,
+                                           app->uid,
+                                           LTTNG_DOMAIN_UST,
+                                           &reg_uid,
+                                           ua_sess->root_shm_path,
+                                           ua_sess->shm_path);
                if (ret < 0) {
                        goto error;
                }
@@ -2613,8 +2659,14 @@ static int setup_buffer_reg_uid(struct ltt_ust_session *usess,
 
        /* Initialize registry. */
        reg_uid->registry->reg.ust = ust_registry_session_per_uid_create(app->abi,
-                       app->version.major, app->version.minor, reg_uid->root_shm_path,
-                       reg_uid->shm_path, usess->uid, usess->gid, ua_sess->tracing_id, app->uid);
+                                                                        app->version.major,
+                                                                        app->version.minor,
+                                                                        reg_uid->root_shm_path,
+                                                                        reg_uid->shm_path,
+                                                                        usess->uid,
+                                                                        usess->gid,
+                                                                        ua_sess->tracing_id,
+                                                                        app->uid);
        if (!reg_uid->registry->reg.ust) {
                /*
                 * reg_uid->registry->reg.ust is NULL upon error, so we need to
@@ -2622,7 +2674,7 @@ static int setup_buffer_reg_uid(struct ltt_ust_session *usess,
                 * that if the buffer registry can be found, its ust registry is
                 * non-NULL.
                 */
-               buffer_reg_uid_destroy(reg_uid, NULL);
+               buffer_reg_uid_destroy(reg_uid, nullptr);
                goto error;
        }
 
@@ -2637,7 +2689,6 @@ end:
                *regp = reg_uid;
        }
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -2653,8 +2704,9 @@ error:
  * -ENOTCONN which is the default code if the lttng_ust_ctl_create_session fails.
  */
 static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
-               struct ust_app *app, struct ust_app_session **ua_sess_ptr,
-               int *is_created)
+                                         struct ust_app *app,
+                                         struct ust_app_session **ua_sess_ptr,
+                                         int *is_created)
 {
        int ret, created = 0;
        struct ust_app_session *ua_sess;
@@ -2666,11 +2718,12 @@ static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
        health_code_update();
 
        ua_sess = lookup_session_by_app(usess, app);
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                DBG2("UST app pid: %d session id %" PRIu64 " not found, creating it",
-                               app->pid, usess->id);
+                    app->pid,
+                    usess->id);
                ua_sess = alloc_ust_app_session();
-               if (ua_sess == NULL) {
+               if (ua_sess == nullptr) {
                        /* Only malloc can failed so something is really wrong */
                        ret = -ENOMEM;
                        goto error;
@@ -2682,7 +2735,7 @@ static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_PID:
                /* Init local registry. */
-               ret = setup_buffer_reg_pid(ua_sess, app, NULL);
+               ret = setup_buffer_reg_pid(ua_sess, app, nullptr);
                if (ret < 0) {
                        delete_ust_app_session(-1, ua_sess, app);
                        goto error;
@@ -2690,7 +2743,7 @@ static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
                break;
        case LTTNG_BUFFER_PER_UID:
                /* Look for a global registry. If none exists, create one. */
-               ret = setup_buffer_reg_uid(usess, ua_sess, app, NULL);
+               ret = setup_buffer_reg_uid(usess, ua_sess, app, nullptr);
                if (ret < 0) {
                        delete_ust_app_session(-1, ua_sess, app);
                        goto error;
@@ -2711,15 +2764,19 @@ static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG("UST app creating session failed. Application is dead: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                   app->pid,
+                                   app->sock);
                                ret = 0;
                        } else if (ret == -EAGAIN) {
                                DBG("UST app creating session failed. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
+                                   app->pid,
+                                   app->sock);
                                ret = 0;
                        } else {
                                ERR("UST app creating session failed with ret %d: pid = %d, sock =%d",
-                                               ret, app->pid, app->sock);
+                                   ret,
+                                   app->pid,
+                                   app->sock);
                        }
                        delete_ust_app_session(-1, ua_sess, app);
                        if (ret != -ENOMEM) {
@@ -2735,12 +2792,10 @@ static int find_or_create_ust_app_session(struct ltt_ust_session *usess,
                ua_sess->handle = ret;
 
                /* Add ust app session to app's HT */
-               lttng_ht_node_init_u64(&ua_sess->node,
-                               ua_sess->tracing_id);
+               lttng_ht_node_init_u64(&ua_sess->node, ua_sess->tracing_id);
                lttng_ht_add_unique_u64(app->sessions, &ua_sess->node);
                lttng_ht_node_init_ulong(&ua_sess->ust_objd_node, ua_sess->handle);
-               lttng_ht_add_unique_ulong(app->ust_sessions_objd,
-                               &ua_sess->ust_objd_node);
+               lttng_ht_add_unique_ulong(app->ust_sessions_objd, &ua_sess->ust_objd_node);
 
                DBG2("UST app session created successfully with handle %d", ret);
        }
@@ -2780,19 +2835,17 @@ static int ht_match_ust_app_ctx(struct cds_lfht_node *node, const void *_key)
                goto no_match;
        }
 
-       switch(key->ctx) {
+       switch (key->ctx) {
        case LTTNG_UST_ABI_CONTEXT_PERF_THREAD_COUNTER:
                if (strncmp(key->u.perf_counter.name,
-                               ctx->ctx.u.perf_counter.name,
-                               sizeof(key->u.perf_counter.name))) {
+                           ctx->ctx.u.perf_counter.name,
+                           sizeof(key->u.perf_counter.name)) != 0) {
                        goto no_match;
                }
                break;
        case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT:
-               if (strcmp(key->u.app_ctx.provider_name,
-                               ctx->ctx.u.app_ctx.provider_name) ||
-                               strcmp(key->u.app_ctx.ctx_name,
-                               ctx->ctx.u.app_ctx.ctx_name)) {
+               if (strcmp(key->u.app_ctx.provider_name, ctx->ctx.u.app_ctx.provider_name) != 0 ||
+                   strcmp(key->u.app_ctx.ctx_name, ctx->ctx.u.app_ctx.ctx_name) != 0) {
                        goto no_match;
                }
                break;
@@ -2813,21 +2866,23 @@ no_match:
  * Must be called while holding RCU read side lock.
  * Return an ust_app_ctx object or NULL on error.
  */
-static
-struct ust_app_ctx *find_ust_app_context(struct lttng_ht *ht,
-               struct lttng_ust_context_attr *uctx)
+static struct ust_app_ctx *find_ust_app_context(struct lttng_ht *ht,
+                                               struct lttng_ust_context_attr *uctx)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_ulong *node;
-       struct ust_app_ctx *app_ctx = NULL;
+       struct ust_app_ctx *app_ctx = nullptr;
 
        LTTNG_ASSERT(uctx);
        LTTNG_ASSERT(ht);
        ASSERT_RCU_READ_LOCKED();
 
        /* Lookup using the lttng_ust_context_type and a custom match fct. */
-       cds_lfht_lookup(ht->ht, ht->hash_fct((void *) uctx->ctx, lttng_ht_seed),
-                       ht_match_ust_app_ctx, uctx, &iter.iter);
+       cds_lfht_lookup(ht->ht,
+                       ht->hash_fct((void *) uctx->ctx, lttng_ht_seed),
+                       ht_match_ust_app_ctx,
+                       uctx,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
        if (!node) {
                goto end;
@@ -2844,10 +2899,9 @@ end:
  *
  * Called with UST app session lock held and a RCU read side lock.
  */
-static
-int create_ust_app_channel_context(struct ust_app_channel *ua_chan,
-               struct lttng_ust_context_attr *uctx,
-               struct ust_app *app)
+static int create_ust_app_channel_context(struct ust_app_channel *ua_chan,
+                                         struct lttng_ust_context_attr *uctx,
+                                         struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_ctx *ua_ctx;
@@ -2863,7 +2917,7 @@ int create_ust_app_channel_context(struct ust_app_channel *ua_chan,
        }
 
        ua_ctx = alloc_ust_app_ctx(uctx);
-       if (ua_ctx == NULL) {
+       if (ua_ctx == nullptr) {
                /* malloc failed */
                ret = -ENOMEM;
                goto error;
@@ -2887,9 +2941,7 @@ error:
  *
  * Called with UST app session lock held.
  */
-static
-int enable_ust_app_event(struct ust_app_event *ua_event,
-               struct ust_app *app)
+static int enable_ust_app_event(struct ust_app_event *ua_event, struct ust_app *app)
 {
        int ret;
 
@@ -2898,7 +2950,7 @@ int enable_ust_app_event(struct ust_app_event *ua_event,
                goto error;
        }
 
-       ua_event->enabled = 1;
+       ua_event->enabled = true;
 
 error:
        return ret;
@@ -2907,8 +2959,7 @@ error:
 /*
  * Disable on the tracer side a ust app event for the session and channel.
  */
-static int disable_ust_app_event(struct ust_app_event *ua_event,
-               struct ust_app *app)
+static int disable_ust_app_event(struct ust_app_event *ua_event, struct ust_app *app)
 {
        int ret;
 
@@ -2917,7 +2968,7 @@ static int disable_ust_app_event(struct ust_app_event *ua_event,
                goto error;
        }
 
-       ua_event->enabled = 0;
+       ua_event->enabled = false;
 
 error:
        return ret;
@@ -2926,9 +2977,9 @@ error:
 /*
  * Lookup ust app channel for session and disable it on the tracer side.
  */
-static
-int disable_ust_app_channel(struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan, struct ust_app *app)
+static int disable_ust_app_channel(struct ust_app_session *ua_sess,
+                                  struct ust_app_channel *ua_chan,
+                                  struct ust_app *app)
 {
        int ret;
 
@@ -2937,7 +2988,7 @@ int disable_ust_app_channel(struct ust_app_session *ua_sess,
                goto error;
        }
 
-       ua_chan->enabled = 0;
+       ua_chan->enabled = false;
 
 error:
        return ret;
@@ -2948,7 +2999,8 @@ error:
  * MUST be called with a RCU read side lock acquired.
  */
 static int enable_ust_app_channel(struct ust_app_session *ua_sess,
-               struct ltt_ust_channel *uchan, struct ust_app *app)
+                                 struct ltt_ust_channel *uchan,
+                                 struct ust_app *app)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -2957,11 +3009,12 @@ static int enable_ust_app_channel(struct ust_app_session *ua_sess,
 
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &iter);
+       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &iter);
        ua_chan_node = lttng_ht_iter_get_node_str(&iter);
-       if (ua_chan_node == NULL) {
+       if (ua_chan_node == nullptr) {
                DBG2("Unable to find channel %s in ust session id %" PRIu64,
-                               uchan->name, ua_sess->tracing_id);
+                    uchan->name,
+                    ua_sess->tracing_id);
                goto error;
        }
 
@@ -2984,8 +3037,10 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int do_consumer_create_channel(struct ltt_ust_session *usess,
-               struct ust_app_session *ua_sess, struct ust_app_channel *ua_chan,
-               int bitness, lsu::registry_session *registry)
+                                     struct ust_app_session *ua_sess,
+                                     struct ust_app_channel *ua_chan,
+                                     int bitness,
+                                     lsu::registry_session *registry)
 {
        int ret;
        unsigned int nb_fd = 0;
@@ -2996,7 +3051,7 @@ static int do_consumer_create_channel(struct ltt_ust_session *usess,
        LTTNG_ASSERT(ua_chan);
        LTTNG_ASSERT(registry);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        health_code_update();
 
        /* Get the right consumer socket for the application. */
@@ -3019,8 +3074,8 @@ static int do_consumer_create_channel(struct ltt_ust_session *usess,
         * Ask consumer to create channel. The consumer will return the number of
         * stream we have to expect.
         */
-       ret = ust_consumer_ask_channel(ua_sess, ua_chan, usess->consumer, socket,
-                       registry, usess->current_trace_chunk);
+       ret = ust_consumer_ask_channel(
+               ua_sess, ua_chan, usess->consumer, socket, registry, usess->current_trace_chunk);
        if (ret < 0) {
                goto error_ask;
        }
@@ -3051,7 +3106,6 @@ static int do_consumer_create_channel(struct ltt_ust_session *usess,
                }
        }
 
-       rcu_read_unlock();
        return 0;
 
 error_destroy:
@@ -3068,7 +3122,6 @@ error_ask:
        lttng_fd_put(LTTNG_FD_APPS, 1);
 error:
        health_code_update();
-       rcu_read_unlock();
        return ret;
 }
 
@@ -3079,7 +3132,7 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int duplicate_stream_object(struct buffer_reg_stream *reg_stream,
-               struct ust_app_stream *stream)
+                                  struct ust_app_stream *stream)
 {
        int ret;
 
@@ -3094,11 +3147,12 @@ static int duplicate_stream_object(struct buffer_reg_stream *reg_stream,
        }
 
        /* Duplicate object for stream once the original is in the registry. */
-       ret = lttng_ust_ctl_duplicate_ust_object_data(&stream->obj,
-                       reg_stream->obj.ust);
+       ret = lttng_ust_ctl_duplicate_ust_object_data(&stream->obj, reg_stream->obj.ust);
        if (ret < 0) {
                ERR("Duplicate stream obj from %p to %p failed with ret %d",
-                               reg_stream->obj.ust, stream->obj, ret);
+                   reg_stream->obj.ust,
+                   stream->obj,
+                   ret);
                lttng_fd_put(LTTNG_FD_APPS, 2);
                goto error;
        }
@@ -3115,7 +3169,7 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int duplicate_channel_object(struct buffer_reg_channel *buf_reg_chan,
-               struct ust_app_channel *ua_chan)
+                                   struct ust_app_channel *ua_chan)
 {
        int ret;
 
@@ -3133,7 +3187,9 @@ static int duplicate_channel_object(struct buffer_reg_channel *buf_reg_chan,
        ret = lttng_ust_ctl_duplicate_ust_object_data(&ua_chan->obj, buf_reg_chan->obj.ust);
        if (ret < 0) {
                ERR("Duplicate channel obj from %p to %p failed with ret: %d",
-                               buf_reg_chan->obj.ust, ua_chan->obj, ret);
+                   buf_reg_chan->obj.ust,
+                   ua_chan->obj,
+                   ret);
                goto error;
        }
        ua_chan->handle = ua_chan->obj->handle;
@@ -3153,8 +3209,8 @@ error_fd_get:
  * Return 0 on success or else a negative value.
  */
 static int setup_buffer_reg_streams(struct buffer_reg_channel *buf_reg_chan,
-               struct ust_app_channel *ua_chan,
-               struct ust_app *app)
+                                   struct ust_app_channel *ua_chan,
+                                   struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_stream *stream, *stmp;
@@ -3165,7 +3221,7 @@ static int setup_buffer_reg_streams(struct buffer_reg_channel *buf_reg_chan,
        DBG2("UST app setup buffer registry stream");
 
        /* Send all streams to application. */
-       cds_list_for_each_entry_safe(stream, stmp, &ua_chan->streams.head, list) {
+       cds_list_for_each_entry_safe (stream, stmp, &ua_chan->streams.head, list) {
                struct buffer_reg_stream *reg_stream;
 
                ret = buffer_reg_stream_create(&reg_stream);
@@ -3178,7 +3234,7 @@ static int setup_buffer_reg_streams(struct buffer_reg_channel *buf_reg_chan,
                 * stream call does not release the object.
                 */
                reg_stream->obj.ust = stream->obj;
-               stream->obj = NULL;
+               stream->obj = nullptr;
                buffer_reg_stream_add(reg_stream, buf_reg_chan);
 
                /* We don't need the streams anymore. */
@@ -3199,10 +3255,11 @@ error:
  * Return 0 on success else a negative value.
  */
 static int create_buffer_reg_channel(struct buffer_reg_session *reg_sess,
-               struct ust_app_channel *ua_chan, struct buffer_reg_channel **regp)
+                                    struct ust_app_channel *ua_chan,
+                                    struct buffer_reg_channel **regp)
 {
        int ret;
-       struct buffer_reg_channel *buf_reg_chan = NULL;
+       struct buffer_reg_channel *buf_reg_chan = nullptr;
 
        LTTNG_ASSERT(reg_sess);
        LTTNG_ASSERT(ua_chan);
@@ -3223,7 +3280,8 @@ static int create_buffer_reg_channel(struct buffer_reg_session *reg_sess,
        try {
                reg_sess->reg.ust->add_channel(ua_chan->tracing_channel_id);
        } catch (const std::exception& ex) {
-               ERR("Failed to add a channel registry to userspace registry session: %s", ex.what());
+               ERR("Failed to add a channel registry to userspace registry session: %s",
+                   ex.what());
                ret = -1;
                goto error;
        }
@@ -3250,8 +3308,9 @@ error_create:
  * Return 0 on success else a negative value.
  */
 static int setup_buffer_reg_channel(struct buffer_reg_session *reg_sess,
-               struct ust_app_channel *ua_chan, struct buffer_reg_channel *buf_reg_chan,
-               struct ust_app *app)
+                                   struct ust_app_channel *ua_chan,
+                                   struct buffer_reg_channel *buf_reg_chan,
+                                   struct ust_app *app)
 {
        int ret;
 
@@ -3269,7 +3328,7 @@ static int setup_buffer_reg_channel(struct buffer_reg_session *reg_sess,
        }
 
        buf_reg_chan->obj.ust = ua_chan->obj;
-       ua_chan->obj = NULL;
+       ua_chan->obj = nullptr;
 
        return 0;
 
@@ -3285,8 +3344,9 @@ error:
  * Return 0 on success else a negative value.
  */
 static int send_channel_uid_to_ust(struct buffer_reg_channel *buf_reg_chan,
-               struct ust_app *app, struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan)
+                                  struct ust_app *app,
+                                  struct ust_app_session *ua_sess,
+                                  struct ust_app_channel *ua_chan)
 {
        int ret;
        struct buffer_reg_stream *reg_stream;
@@ -3306,12 +3366,15 @@ static int send_channel_uid_to_ust(struct buffer_reg_channel *buf_reg_chan,
        /* Send channel to the application. */
        ret = ust_consumer_send_channel_to_ust(app, ua_sess, ua_chan);
        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
-               ret = -ENOTCONN;        /* Caused by app exiting. */
+               ret = -ENOTCONN; /* Caused by app exiting. */
                goto error;
        } else if (ret == -EAGAIN) {
                /* Caused by timeout. */
-               WARN("Communication with application %d timed out on send_channel for channel \"%s\" of session \"%" PRIu64 "\".",
-                               app->pid, ua_chan->name, ua_sess->tracing_id);
+               WARN("Communication with application %d timed out on send_channel for channel \"%s\" of session \"%" PRIu64
+                    "\".",
+                    app->pid,
+                    ua_chan->name,
+                    ua_sess->tracing_id);
                /* Treat this the same way as an application that is exiting. */
                ret = -ENOTCONN;
                goto error;
@@ -3323,7 +3386,7 @@ static int send_channel_uid_to_ust(struct buffer_reg_channel *buf_reg_chan,
 
        /* Send all streams to application. */
        pthread_mutex_lock(&buf_reg_chan->stream_list_lock);
-       cds_list_for_each_entry(reg_stream, &buf_reg_chan->streams, lnode) {
+       cds_list_for_each_entry (reg_stream, &buf_reg_chan->streams, lnode) {
                struct ust_app_stream stream = {};
 
                ret = duplicate_stream_object(reg_stream, &stream);
@@ -3341,10 +3404,11 @@ static int send_channel_uid_to_ust(struct buffer_reg_channel *buf_reg_chan,
                                 * Treat this the same way as an application
                                 * that is exiting.
                                 */
-                               WARN("Communication with application %d timed out on send_stream for stream of channel \"%s\" of session \"%" PRIu64 "\".",
-                                               app->pid,
-                                               ua_chan->name,
-                                               ua_sess->tracing_id);
+                               WARN("Communication with application %d timed out on send_stream for stream of channel \"%s\" of session \"%" PRIu64
+                                    "\".",
+                                    app->pid,
+                                    ua_chan->name,
+                                    ua_sess->tracing_id);
                                ret = -ENOTCONN;
                        }
                        (void) release_ust_app_stream(-1, &stream, app);
@@ -3373,13 +3437,14 @@ error:
  * Return 0 on success else a negative value.
  */
 static int create_channel_per_uid(struct ust_app *app,
-               struct ltt_ust_session *usess, struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan)
+                                 struct ltt_ust_session *usess,
+                                 struct ust_app_session *ua_sess,
+                                 struct ust_app_channel *ua_chan)
 {
        int ret;
        struct buffer_reg_uid *reg_uid;
        struct buffer_reg_channel *buf_reg_chan;
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
        enum lttng_error_code notification_ret;
 
        LTTNG_ASSERT(app);
@@ -3398,8 +3463,7 @@ static int create_channel_per_uid(struct ust_app *app,
         */
        LTTNG_ASSERT(reg_uid);
 
-       buf_reg_chan = buffer_reg_channel_find(ua_chan->tracing_channel_id,
-                       reg_uid);
+       buf_reg_chan = buffer_reg_channel_find(ua_chan->tracing_channel_id, reg_uid);
        if (buf_reg_chan) {
                goto send_channel;
        }
@@ -3407,8 +3471,7 @@ static int create_channel_per_uid(struct ust_app *app,
        /* Create the buffer registry channel object. */
        ret = create_buffer_reg_channel(reg_uid->registry, ua_chan, &buf_reg_chan);
        if (ret < 0) {
-               ERR("Error creating the UST channel \"%s\" registry instance",
-                               ua_chan->name);
+               ERR("Error creating the UST channel \"%s\" registry instance", ua_chan->name);
                goto error;
        }
 
@@ -3421,11 +3484,10 @@ static int create_channel_per_uid(struct ust_app *app,
         * Create the buffers on the consumer side. This call populates the
         * ust app channel object with all streams and data object.
         */
-       ret = do_consumer_create_channel(usess, ua_sess, ua_chan,
-                       app->abi.bits_per_long, reg_uid->registry->reg.ust);
+       ret = do_consumer_create_channel(
+               usess, ua_sess, ua_chan, app->abi.bits_per_long, reg_uid->registry->reg.ust);
        if (ret < 0) {
-               ERR("Error creating UST channel \"%s\" on the consumer daemon",
-                               ua_chan->name);
+               ERR("Error creating UST channel \"%s\" on the consumer daemon", ua_chan->name);
 
                /*
                 * Let's remove the previously created buffer registry channel so
@@ -3434,7 +3496,7 @@ static int create_channel_per_uid(struct ust_app *app,
                auto locked_registry = reg_uid->registry->reg.ust->lock();
                try {
                        locked_registry->remove_channel(ua_chan->tracing_channel_id, false);
-               } catch (const std::exception &ex) {
+               } catch (const std::exceptionex) {
                        DBG("Could not find channel for removal: %s", ex.what());
                }
                buffer_reg_channel_remove(reg_uid->registry, buf_reg_chan);
@@ -3445,8 +3507,7 @@ static int create_channel_per_uid(struct ust_app *app,
        /*
         * Setup the streams and add it to the session registry.
         */
-       ret = setup_buffer_reg_channel(reg_uid->registry,
-                       ua_chan, buf_reg_chan, app);
+       ret = setup_buffer_reg_channel(reg_uid->registry, ua_chan, buf_reg_chan, app);
        if (ret < 0) {
                ERR("Error setting up UST channel \"%s\"", ua_chan->name);
                goto error;
@@ -3454,18 +3515,21 @@ static int create_channel_per_uid(struct ust_app *app,
 
        {
                auto locked_registry = reg_uid->registry->reg.ust->lock();
-               auto& ust_reg_chan = locked_registry->get_channel(ua_chan->tracing_channel_id);
+               auto& ust_reg_chan = locked_registry->channel(ua_chan->tracing_channel_id);
 
                ust_reg_chan._consumer_key = ua_chan->key;
        }
 
        /* Notify the notification subsystem of the channel's creation. */
        notification_ret = notification_thread_command_add_channel(
-                       the_notification_thread_handle, session->id,
-                       ua_chan->name, ua_chan->key, LTTNG_DOMAIN_UST,
-                       ua_chan->attr.subbuf_size * ua_chan->attr.num_subbuf);
+               the_notification_thread_handle,
+               session->id,
+               ua_chan->name,
+               ua_chan->key,
+               LTTNG_DOMAIN_UST,
+               ua_chan->attr.subbuf_size * ua_chan->attr.num_subbuf);
        if (notification_ret != LTTNG_OK) {
-               ret = - (int) notification_ret;
+               ret = -(int) notification_ret;
                ERR("Failed to add channel to notification thread");
                goto error;
        }
@@ -3496,13 +3560,14 @@ error:
  * Return 0 on success else a negative value.
  */
 static int create_channel_per_pid(struct ust_app *app,
-               struct ltt_ust_session *usess, struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan)
+                                 struct ltt_ust_session *usess,
+                                 struct ust_app_session *ua_sess,
+                                 struct ust_app_channel *ua_chan)
 {
        int ret;
        lsu::registry_session *registry;
        enum lttng_error_code cmd_ret;
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
        uint64_t chan_reg_key;
 
        LTTNG_ASSERT(app);
@@ -3512,7 +3577,7 @@ static int create_channel_per_pid(struct ust_app *app,
 
        DBG("UST app creating channel %s with per PID buffers", ua_chan->name);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        registry = get_session_registry(ua_sess);
        /* The UST app session lock is held, registry shall not be null. */
@@ -3522,8 +3587,9 @@ static int create_channel_per_pid(struct ust_app *app,
        try {
                registry->add_channel(ua_chan->key);
        } catch (const std::exception& ex) {
-               ERR("Error creating the UST channel \"%s\" registry instance: %s", ua_chan->name,
-                               ex.what());
+               ERR("Error creating the UST channel \"%s\" registry instance: %s",
+                   ua_chan->name,
+                   ex.what());
                ret = -1;
                goto error;
        }
@@ -3534,11 +3600,9 @@ static int create_channel_per_pid(struct ust_app *app,
        ASSERT_SESSION_LIST_LOCKED();
 
        /* Create and get channel on the consumer side. */
-       ret = do_consumer_create_channel(usess, ua_sess, ua_chan,
-                       app->abi.bits_per_long, registry);
+       ret = do_consumer_create_channel(usess, ua_sess, ua_chan, app->abi.bits_per_long, registry);
        if (ret < 0) {
-               ERR("Error creating UST channel \"%s\" on the consumer daemon",
-                       ua_chan->name);
+               ERR("Error creating UST channel \"%s\" on the consumer daemon", ua_chan->name);
                goto error_remove_from_registry;
        }
 
@@ -3554,16 +3618,19 @@ static int create_channel_per_pid(struct ust_app *app,
        {
                auto locked_registry = registry->lock();
 
-               auto& ust_reg_chan = locked_registry->get_channel(chan_reg_key);
+               auto& ust_reg_chan = locked_registry->channel(chan_reg_key);
                ust_reg_chan._consumer_key = ua_chan->key;
        }
 
-       cmd_ret = notification_thread_command_add_channel(
-                       the_notification_thread_handle, session->id,
-                       ua_chan->name, ua_chan->key, LTTNG_DOMAIN_UST,
-                       ua_chan->attr.subbuf_size * ua_chan->attr.num_subbuf);
+       cmd_ret = notification_thread_command_add_channel(the_notification_thread_handle,
+                                                         session->id,
+                                                         ua_chan->name,
+                                                         ua_chan->key,
+                                                         LTTNG_DOMAIN_UST,
+                                                         ua_chan->attr.subbuf_size *
+                                                                 ua_chan->attr.num_subbuf);
        if (cmd_ret != LTTNG_OK) {
-               ret = - (int) cmd_ret;
+               ret = -(int) cmd_ret;
                ERR("Failed to add channel to notification thread");
                goto error_remove_from_registry;
        }
@@ -3578,7 +3645,6 @@ error_remove_from_registry:
                }
        }
 error:
-       rcu_read_unlock();
        if (session) {
                session_put(session);
        }
@@ -3596,8 +3662,9 @@ error:
  * the application exited concurrently.
  */
 static int ust_app_channel_send(struct ust_app *app,
-               struct ltt_ust_session *usess, struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan)
+                               struct ltt_ust_session *usess,
+                               struct ust_app_session *ua_sess,
+                               struct ust_app_channel *ua_chan)
 {
        int ret;
 
@@ -3656,10 +3723,10 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int ust_app_channel_allocate(struct ust_app_session *ua_sess,
-               struct ltt_ust_channel *uchan,
-               enum lttng_ust_abi_chan_type type,
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ust_app_channel **ua_chanp)
+                                   struct ltt_ust_channel *uchan,
+                                   enum lttng_ust_abi_chan_type type,
+                                   struct ltt_ust_session *usess __attribute__((unused)),
+                                   struct ust_app_channel **ua_chanp)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -3669,15 +3736,15 @@ static int ust_app_channel_allocate(struct ust_app_session *ua_sess,
        ASSERT_RCU_READ_LOCKED();
 
        /* Lookup channel in the ust app session */
-       lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &iter);
+       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &iter);
        ua_chan_node = lttng_ht_iter_get_node_str(&iter);
-       if (ua_chan_node != NULL) {
+       if (ua_chan_node != nullptr) {
                ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
                goto end;
        }
 
        ua_chan = alloc_ust_app_channel(uchan->name, ua_sess, &uchan->attr);
-       if (ua_chan == NULL) {
+       if (ua_chan == nullptr) {
                /* Only malloc can fail here */
                ret = -ENOMEM;
                goto error;
@@ -3707,10 +3774,9 @@ error:
  * Must be called with the RCU read side lock held.
  * Called with ust app session mutex held.
  */
-static
-int create_ust_app_event(struct ust_app_channel *ua_chan,
-               struct ltt_ust_event *uevent,
-               struct ust_app *app)
+static int create_ust_app_event(struct ust_app_channel *ua_chan,
+                               struct ltt_ust_event *uevent,
+                               struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_event *ua_event;
@@ -3718,7 +3784,7 @@ int create_ust_app_event(struct ust_app_channel *ua_chan,
        ASSERT_RCU_READ_LOCKED();
 
        ua_event = alloc_ust_app_event(uevent->attr.name, &uevent->attr);
-       if (ua_event == NULL) {
+       if (ua_event == nullptr) {
                /* Only failure mode of alloc_ust_app_event(). */
                ret = -ENOMEM;
                goto end;
@@ -3736,18 +3802,19 @@ int create_ust_app_event(struct ust_app_channel *ua_chan,
                 */
                if (ret == -LTTNG_UST_ERR_EXIST) {
                        ERR("Tracer for application reported that an event being created already existed: "
-                                       "event_name = \"%s\", pid = %d, ppid = %d, uid = %d, gid = %d",
-                                       uevent->attr.name,
-                                       app->pid, app->ppid, app->uid,
-                                       app->gid);
+                           "event_name = \"%s\", pid = %d, ppid = %d, uid = %d, gid = %d",
+                           uevent->attr.name,
+                           app->pid,
+                           app->ppid,
+                           app->uid,
+                           app->gid);
                }
                goto error;
        }
 
        add_unique_ust_app_event(ua_chan, ua_event);
 
-       DBG2("UST app create event completed: app = '%s' pid = %d",
-                       app->name, app->pid);
+       DBG2("UST app create event completed: app = '%s' pid = %d", app->name, app->pid);
 
 end:
        return ret;
@@ -3764,9 +3831,7 @@ error:
  * Must be called with the RCU read side lock held.
  * Called with ust app session mutex held.
  */
-static
-int create_ust_app_event_notifier_rule(struct lttng_trigger *trigger,
-               struct ust_app *app)
+static int create_ust_app_event_notifier_rule(struct lttng_trigger *trigger, struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_event_notifier_rule *ua_event_notifier_rule;
@@ -3774,7 +3839,7 @@ int create_ust_app_event_notifier_rule(struct lttng_trigger *trigger,
        ASSERT_RCU_READ_LOCKED();
 
        ua_event_notifier_rule = alloc_ust_app_event_notifier_rule(trigger);
-       if (ua_event_notifier_rule == NULL) {
+       if (ua_event_notifier_rule == nullptr) {
                ret = -ENOMEM;
                goto end;
        }
@@ -3790,19 +3855,23 @@ int create_ust_app_event_notifier_rule(struct lttng_trigger *trigger,
                 */
                if (ret == -LTTNG_UST_ERR_EXIST) {
                        ERR("Tracer for application reported that an event notifier being created already exists: "
-                                       "token = \"%" PRIu64 "\", pid = %d, ppid = %d, uid = %d, gid = %d",
-                                       lttng_trigger_get_tracer_token(trigger),
-                                       app->pid, app->ppid, app->uid,
-                                       app->gid);
+                           "token = \"%" PRIu64 "\", pid = %d, ppid = %d, uid = %d, gid = %d",
+                           lttng_trigger_get_tracer_token(trigger),
+                           app->pid,
+                           app->ppid,
+                           app->uid,
+                           app->gid);
                }
                goto error;
        }
 
        lttng_ht_add_unique_u64(app->token_to_event_notifier_rule_ht,
-                       &ua_event_notifier_rule->node);
+                               &ua_event_notifier_rule->node);
 
        DBG2("UST app create token event rule completed: app = '%s', pid = %d, token = %" PRIu64,
-                       app->name, app->pid, lttng_trigger_get_tracer_token(trigger));
+            app->name,
+            app->pid,
+            lttng_trigger_get_tracer_token(trigger));
 
        goto end;
 
@@ -3819,12 +3888,13 @@ end:
  * Called with UST app session lock held and RCU read side lock.
  */
 static int create_ust_app_metadata(struct ust_app_session *ua_sess,
-               struct ust_app *app, struct consumer_output *consumer)
+                                  struct ust_app *app,
+                                  struct consumer_output *consumer)
 {
        int ret = 0;
        struct ust_app_channel *metadata;
        struct consumer_socket *socket;
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
 
        LTTNG_ASSERT(ua_sess);
        LTTNG_ASSERT(app);
@@ -3842,7 +3912,7 @@ static int create_ust_app_metadata(struct ust_app_session *ua_sess,
        }
 
        /* Allocate UST metadata */
-       metadata = alloc_ust_app_channel(DEFAULT_METADATA_NAME, ua_sess, NULL);
+       metadata = alloc_ust_app_channel(DEFAULT_METADATA_NAME, ua_sess, nullptr);
        if (!metadata) {
                /* malloc() failed */
                ret = -ENOMEM;
@@ -3884,8 +3954,12 @@ static int create_ust_app_metadata(struct ust_app_session *ua_sess,
         * never added or monitored until we do a first push metadata to the
         * consumer.
         */
-       ret = ust_consumer_ask_channel(ua_sess, metadata, consumer, socket,
-                       locked_registry.get(), session->current_trace_chunk);
+       ret = ust_consumer_ask_channel(ua_sess,
+                                      metadata,
+                                      consumer,
+                                      socket,
+                                      locked_registry.get(),
+                                      session->current_trace_chunk);
        if (ret < 0) {
                /* Nullify the metadata key so we don't try to close it later on. */
                locked_registry->_metadata_key = 0;
@@ -3905,8 +3979,7 @@ static int create_ust_app_metadata(struct ust_app_session *ua_sess,
                goto error_consumer;
        }
 
-       DBG2("UST metadata with key %" PRIu64 " created for app pid %d",
-                       metadata->key, app->pid);
+       DBG2("UST metadata with key %" PRIu64 " created for app pid %d", metadata->key, app->pid);
 
 error_consumer:
        lttng_fd_put(LTTNG_FD_APPS, 1);
@@ -3924,13 +3997,13 @@ error:
  */
 struct ust_app *ust_app_find_by_pid(pid_t pid)
 {
-       struct ust_app *app = NULL;
+       struct ust_app *app = nullptr;
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
 
-       lttng_ht_lookup(ust_app_ht, (void *)((unsigned long) pid), &iter);
+       lttng_ht_lookup(ust_app_ht, (void *) ((unsigned long) pid), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("UST app no found with pid %d", pid);
                goto error;
        }
@@ -3953,23 +4026,21 @@ error:
 struct ust_app *ust_app_create(struct ust_register_msg *msg, int sock)
 {
        int ret;
-       struct ust_app *lta = NULL;
-       struct lttng_pipe *event_notifier_event_source_pipe = NULL;
+       struct ust_app *lta = nullptr;
+       struct lttng_pipe *event_notifier_event_source_pipe = nullptr;
 
        LTTNG_ASSERT(msg);
        LTTNG_ASSERT(sock >= 0);
 
        DBG3("UST app creating application for socket %d", sock);
 
-       if ((msg->bits_per_long == 64 &&
-                           (uatomic_read(&the_ust_consumerd64_fd) ==
-                                           -EINVAL)) ||
-                       (msg->bits_per_long == 32 &&
-                                       (uatomic_read(&the_ust_consumerd32_fd) ==
-                                                       -EINVAL))) {
+       if ((msg->bits_per_long == 64 && (uatomic_read(&the_ust_consumerd64_fd) == -EINVAL)) ||
+           (msg->bits_per_long == 32 && (uatomic_read(&the_ust_consumerd32_fd) == -EINVAL))) {
                ERR("Registration failed: application \"%s\" (pid: %d) has "
-                               "%d-bit long, but no consumerd for this size is available.\n",
-                               msg->name, msg->pid, msg->bits_per_long);
+                   "%d-bit long, but no consumerd for this size is available.\n",
+                   msg->name,
+                   msg->pid,
+                   msg->bits_per_long);
                goto error;
        }
 
@@ -3981,23 +4052,27 @@ struct ust_app *ust_app_create(struct ust_register_msg *msg, int sock)
        ret = lttng_fd_get(LTTNG_FD_APPS, 2);
        if (ret) {
                ERR("Failed to reserve two file descriptors for the event source pipe while creating a new application instance: app = '%s', pid = %d",
-                               msg->name, (int) msg->pid);
+                   msg->name,
+                   (int) msg->pid);
                goto error;
        }
 
        event_notifier_event_source_pipe = lttng_pipe_open(FD_CLOEXEC);
        if (!event_notifier_event_source_pipe) {
                PERROR("Failed to open application event source pipe: '%s' (pid = %d)",
-                               msg->name, msg->pid);
+                      msg->name,
+                      msg->pid);
                goto error;
        }
 
        lta = zmalloc<ust_app>();
-       if (lta == NULL) {
+       if (lta == nullptr) {
                PERROR("malloc");
                goto error_free_pipe;
        }
 
+       urcu_ref_init(&lta->ref);
+
        lta->event_notifier_group.event_pipe = event_notifier_event_source_pipe;
 
        lta->ppid = msg->ppid;
@@ -4012,8 +4087,8 @@ struct ust_app *ust_app_create(struct ust_register_msg *msg, int sock)
                .uint32_t_alignment = msg->uint32_t_alignment,
                .uint64_t_alignment = msg->uint64_t_alignment,
                .byte_order = msg->byte_order == LITTLE_ENDIAN ?
-                               lttng::sessiond::trace::byte_order::LITTLE_ENDIAN_ :
-                                       lttng::sessiond::trace::byte_order::BIG_ENDIAN_,
+                       lttng::sessiond::trace::byte_order::LITTLE_ENDIAN_ :
+                       lttng::sessiond::trace::byte_order::BIG_ENDIAN_,
        };
 
        lta->v_major = msg->major;
@@ -4038,7 +4113,7 @@ struct ust_app *ust_app_create(struct ust_register_msg *msg, int sock)
        lta->pid = msg->pid;
        lttng_ht_node_init_ulong(&lta->pid_n, (unsigned long) lta->pid);
        lta->sock = sock;
-       pthread_mutex_init(&lta->sock_lock, NULL);
+       pthread_mutex_init(&lta->sock_lock, nullptr);
        lttng_ht_node_init_ulong(&lta->sock_n, (unsigned long) lta->sock);
 
        CDS_INIT_LIST_HEAD(&lta->teardown_head);
@@ -4048,7 +4123,7 @@ error_free_pipe:
        lttng_pipe_destroy(event_notifier_event_source_pipe);
        lttng_fd_put(LTTNG_FD_APPS, 2);
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -4059,9 +4134,9 @@ void ust_app_add(struct ust_app *app)
        LTTNG_ASSERT(app);
        LTTNG_ASSERT(app->notify_sock >= 0);
 
-       app->registration_time = time(NULL);
+       app->registration_time = time(nullptr);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * On a re-registration, we want to kick out the previous registration of
@@ -4081,11 +4156,16 @@ void ust_app_add(struct ust_app *app)
        lttng_ht_add_unique_ulong(ust_app_ht_by_notify_sock, &app->notify_sock_n);
 
        DBG("App registered with pid:%d ppid:%d uid:%d gid:%d sock =%d name:%s "
-                       "notify_sock =%d (version %d.%d)", app->pid, app->ppid, app->uid,
-                       app->gid, app->sock, app->name, app->notify_sock, app->v_major,
-                       app->v_minor);
-
-       rcu_read_unlock();
+           "notify_sock =%d (version %d.%d)",
+           app->pid,
+           app->ppid,
+           app->uid,
+           app->gid,
+           app->sock,
+           app->name,
+           app->notify_sock,
+           app->v_major,
+           app->v_minor);
 }
 
 /*
@@ -4106,13 +4186,17 @@ int ust_app_version(struct ust_app *app)
        if (ret < 0) {
                if (ret == -LTTNG_UST_ERR_EXITING || ret == -EPIPE) {
                        DBG3("UST app version failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app version failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app version failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
        }
 
@@ -4139,7 +4223,7 @@ int ust_app_setup_event_notifier_group(struct ust_app *app)
 {
        int ret;
        int event_pipe_write_fd;
-       struct lttng_ust_abi_object_data *event_notifier_group = NULL;
+       struct lttng_ust_abi_object_data *event_notifier_group = nullptr;
        enum lttng_error_code lttng_ret;
        enum event_notifier_error_accounting_status event_notifier_error_accounting_status;
 
@@ -4151,25 +4235,29 @@ int ust_app_setup_event_notifier_group(struct ust_app *app)
        }
 
        /* Get the write side of the pipe. */
-       event_pipe_write_fd = lttng_pipe_get_writefd(
-                       app->event_notifier_group.event_pipe);
+       event_pipe_write_fd = lttng_pipe_get_writefd(app->event_notifier_group.event_pipe);
 
        pthread_mutex_lock(&app->sock_lock);
-       ret = lttng_ust_ctl_create_event_notifier_group(app->sock,
-                       event_pipe_write_fd, &event_notifier_group);
+       ret = lttng_ust_ctl_create_event_notifier_group(
+               app->sock, event_pipe_write_fd, &event_notifier_group);
        pthread_mutex_unlock(&app->sock_lock);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        ret = 0;
                        DBG3("UST app create event notifier group failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        ret = 0;
                        WARN("UST app create event notifier group failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app create event notifier group failed with ret %d: pid = %d, sock = %d, event_pipe_write_fd: %d",
-                                       ret, app->pid, app->sock, event_pipe_write_fd);
+                           ret,
+                           app->pid,
+                           app->sock,
+                           event_pipe_write_fd);
                }
                goto error;
        }
@@ -4177,7 +4265,8 @@ int ust_app_setup_event_notifier_group(struct ust_app *app)
        ret = lttng_pipe_write_close(app->event_notifier_group.event_pipe);
        if (ret) {
                ERR("Failed to close write end of the application's event source pipe: app = '%s' (pid = %d)",
-                               app->name, app->pid);
+                   app->name,
+                   app->pid);
                goto error;
        }
 
@@ -4188,32 +4277,34 @@ int ust_app_setup_event_notifier_group(struct ust_app *app)
        lttng_fd_put(LTTNG_FD_APPS, 1);
 
        lttng_ret = notification_thread_command_add_tracer_event_source(
-                       the_notification_thread_handle,
-                       lttng_pipe_get_readfd(
-                                       app->event_notifier_group.event_pipe),
-                       LTTNG_DOMAIN_UST);
+               the_notification_thread_handle,
+               lttng_pipe_get_readfd(app->event_notifier_group.event_pipe),
+               LTTNG_DOMAIN_UST);
        if (lttng_ret != LTTNG_OK) {
                ERR("Failed to add tracer event source to notification thread");
-               ret = - 1;
+               ret = -1;
                goto error;
        }
 
        /* Assign handle only when the complete setup is valid. */
        app->event_notifier_group.object = event_notifier_group;
 
-       event_notifier_error_accounting_status =
-                       event_notifier_error_accounting_register_app(app);
+       event_notifier_error_accounting_status = event_notifier_error_accounting_register_app(app);
        switch (event_notifier_error_accounting_status) {
        case EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_OK:
                break;
        case EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_UNSUPPORTED:
                DBG3("Failed to setup event notifier error accounting (application does not support notifier error accounting): app socket fd = %d, app name = '%s', app pid = %d",
-                               app->sock, app->name, (int) app->pid);
+                    app->sock,
+                    app->name,
+                    (int) app->pid);
                ret = 0;
                goto error_accounting;
        case EVENT_NOTIFIER_ERROR_ACCOUNTING_STATUS_APP_DEAD:
                DBG3("Failed to setup event notifier error accounting (application is dead): app socket fd = %d, app name = '%s', app pid = %d",
-                               app->sock, app->name, (int) app->pid);
+                    app->sock,
+                    app->name,
+                    (int) app->pid);
                ret = 0;
                goto error_accounting;
        default:
@@ -4226,9 +4317,8 @@ int ust_app_setup_event_notifier_group(struct ust_app *app)
 
 error_accounting:
        lttng_ret = notification_thread_command_remove_tracer_event_source(
-                       the_notification_thread_handle,
-                       lttng_pipe_get_readfd(
-                                       app->event_notifier_group.event_pipe));
+               the_notification_thread_handle,
+               lttng_pipe_get_readfd(app->event_notifier_group.event_pipe));
        if (lttng_ret != LTTNG_OK) {
                ERR("Failed to remove application tracer event source from notification thread");
        }
@@ -4236,34 +4326,16 @@ error_accounting:
 error:
        lttng_ust_ctl_release_object(app->sock, app->event_notifier_group.object);
        free(app->event_notifier_group.object);
-       app->event_notifier_group.object = NULL;
+       app->event_notifier_group.object = nullptr;
        return ret;
 }
 
-/*
- * Unregister app by removing it from the global traceable app list and freeing
- * the data struct.
- *
- * The socket is already closed at this point so no close to sock.
- */
-void ust_app_unregister(int sock)
+static void ust_app_unregister(ust_app& app)
 {
-       struct ust_app *lta;
-       struct lttng_ht_node_ulong *node;
-       struct lttng_ht_iter ust_app_sock_iter;
        struct lttng_ht_iter iter;
        struct ust_app_session *ua_sess;
-       int ret;
-
-       rcu_read_lock();
-
-       /* Get the node reference for a call_rcu */
-       lttng_ht_lookup(ust_app_ht_by_sock, (void *)((unsigned long) sock), &ust_app_sock_iter);
-       node = lttng_ht_iter_get_node_ulong(&ust_app_sock_iter);
-       LTTNG_ASSERT(node);
 
-       lta = lttng::utils::container_of(node, &ust_app::sock_n);
-       DBG("PID %d unregistering with sock %d", lta->pid, sock);
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * For per-PID buffers, perform "push metadata" and flush all
@@ -4271,26 +4343,24 @@ void ust_app_unregister(int sock)
         * ensuring proper behavior of data_pending check.
         * Remove sessions so they are not visible during deletion.
         */
-       cds_lfht_for_each_entry(lta->sessions->ht, &iter.iter, ua_sess,
-                       node.node) {
-               ret = lttng_ht_del(lta->sessions, &iter);
-               if (ret) {
+       cds_lfht_for_each_entry (app.sessions->ht, &iter.iter, ua_sess, node.node) {
+               const auto del_ret = lttng_ht_del(app.sessions, &iter);
+               if (del_ret) {
                        /* The session was already removed so scheduled for teardown. */
                        continue;
                }
 
                if (ua_sess->buffer_type == LTTNG_BUFFER_PER_PID) {
-                       (void) ust_app_flush_app_session(lta, ua_sess);
+                       (void) ust_app_flush_app_session(app, *ua_sess);
                }
 
                /*
                 * Add session to list for teardown. This is safe since at this point we
                 * are the only one using this list.
                 */
-               pthread_mutex_lock(&ua_sess->lock);
+               lttng::pthread::lock_guard ust_app_session_lock(ua_sess->lock);
 
                if (ua_sess->deleted) {
-                       pthread_mutex_unlock(&ua_sess->lock);
                        continue;
                }
 
@@ -4324,29 +4394,26 @@ void ust_app_unregister(int sock)
                                        locked_registry->_metadata_closed = true;
                                }
 
-                               /* Release lock before communication, see comments in close_metadata(). */
+                               /* Release lock before communication, see comments in
+                                * close_metadata(). */
                                locked_registry.reset();
-                               (void) close_metadata(metadata_key, consumer_bitness, ua_sess->consumer);
+                               (void) close_metadata(
+                                       metadata_key, consumer_bitness, ua_sess->consumer);
                        } else {
                                locked_registry.reset();
                        }
                }
-               cds_list_add(&ua_sess->teardown_node, &lta->teardown_head);
 
-               pthread_mutex_unlock(&ua_sess->lock);
+               cds_list_add(&ua_sess->teardown_node, &app.teardown_head);
        }
 
-       /* Remove application from PID hash table */
-       ret = lttng_ht_del(ust_app_ht_by_sock, &ust_app_sock_iter);
-       LTTNG_ASSERT(!ret);
-
        /*
         * Remove application from notify hash table. The thread handling the
         * notify socket could have deleted the node so ignore on error because
         * either way it's valid. The close of that socket is handled by the
         * apps_notify_thread.
         */
-       iter.iter.node = &lta->notify_sock_n.node;
+       iter.iter.node = &app.notify_sock_n.node;
        (void) lttng_ht_del(ust_app_ht_by_notify_sock, &iter);
 
        /*
@@ -4354,18 +4421,47 @@ void ust_app_unregister(int sock)
         * add replace during app registration because the PID can be reassigned by
         * the OS.
         */
-       iter.iter.node = &lta->pid_n.node;
-       ret = lttng_ht_del(ust_app_ht, &iter);
-       if (ret) {
-               DBG3("Unregister app by PID %d failed. This can happen on pid reuse",
-                               lta->pid);
+       iter.iter.node = &app.pid_n.node;
+       if (lttng_ht_del(ust_app_ht, &iter)) {
+               DBG3("Unregister app by PID %d failed. This can happen on pid reuse", app.pid);
        }
+}
 
-       /* Free memory */
-       call_rcu(&lta->pid_n.head, delete_ust_app_rcu);
+/*
+ * Unregister app by removing it from the global traceable app list and freeing
+ * the data struct.
+ *
+ * The socket is already closed at this point, so there is no need to close it.
+ */
+void ust_app_unregister_by_socket(int sock_fd)
+{
+       struct ust_app *app;
+       struct lttng_ht_node_ulong *node;
+       struct lttng_ht_iter ust_app_sock_iter;
+       int ret;
 
-       rcu_read_unlock();
-       return;
+       lttng::urcu::read_lock_guard read_lock;
+
+       /* Get the node reference for a call_rcu */
+       lttng_ht_lookup(ust_app_ht_by_sock, (void *) ((unsigned long) sock_fd), &ust_app_sock_iter);
+       node = lttng_ht_iter_get_node_ulong(&ust_app_sock_iter);
+       assert(node);
+
+       app = caa_container_of(node, struct ust_app, sock_n);
+
+       DBG_FMT("Application unregistering after socket activity: pid={}, socket_fd={}",
+               app->pid,
+               sock_fd);
+
+       /* Remove application from socket hash table */
+       ret = lttng_ht_del(ust_app_ht_by_sock, &ust_app_sock_iter);
+       assert(!ret);
+
+       /*
+        * The socket is closed: release its reference to the application
+        * to trigger its eventual teardown.
+        */
+       ust_app_put(app);
 }
 
 /*
@@ -4381,112 +4477,136 @@ int ust_app_list_events(struct lttng_event **events)
 
        nbmem = UST_APP_EVENT_LIST_SIZE;
        tmp_event = calloc<lttng_event>(nbmem);
-       if (tmp_event == NULL) {
+       if (tmp_event == nullptr) {
                PERROR("zmalloc ust app events");
                ret = -ENOMEM;
                goto error;
        }
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               struct lttng_ust_abi_tracepoint_iter uiter;
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       struct lttng_ust_abi_tracepoint_iter uiter;
 
-               health_code_update();
+                       health_code_update();
 
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               pthread_mutex_lock(&app->sock_lock);
-               handle = lttng_ust_ctl_tracepoint_list(app->sock);
-               if (handle < 0) {
-                       if (handle != -EPIPE && handle != -LTTNG_UST_ERR_EXITING) {
-                               ERR("UST app list events getting handle failed for app pid %d",
-                                               app->pid);
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
                        }
-                       pthread_mutex_unlock(&app->sock_lock);
-                       continue;
-               }
 
-               while ((ret = lttng_ust_ctl_tracepoint_list_get(app->sock, handle,
-                                       &uiter)) != -LTTNG_UST_ERR_NOENT) {
-                       /* Handle ustctl error. */
-                       if (ret < 0) {
-                               int release_ret;
-
-                               if (ret != -LTTNG_UST_ERR_EXITING && ret != -EPIPE) {
-                                       ERR("UST app tp list get failed for app %d with ret %d",
-                                                       app->sock, ret);
-                               } else {
-                                       DBG3("UST app tp list get failed. Application is dead");
-                                       break;
-                               }
-                               free(tmp_event);
-                               release_ret = lttng_ust_ctl_release_handle(app->sock, handle);
-                               if (release_ret < 0 &&
-                                               release_ret != -LTTNG_UST_ERR_EXITING &&
-                                               release_ret != -EPIPE) {
-                                       ERR("Error releasing app handle for app %d with ret %d", app->sock, release_ret);
+                       pthread_mutex_lock(&app->sock_lock);
+                       handle = lttng_ust_ctl_tracepoint_list(app->sock);
+                       if (handle < 0) {
+                               if (handle != -EPIPE && handle != -LTTNG_UST_ERR_EXITING) {
+                                       ERR("UST app list events getting handle failed for app pid %d",
+                                           app->pid);
                                }
                                pthread_mutex_unlock(&app->sock_lock);
-                               goto rcu_error;
+                               continue;
                        }
 
-                       health_code_update();
-                       if (count >= nbmem) {
-                               /* In case the realloc fails, we free the memory */
-                               struct lttng_event *new_tmp_event;
-                               size_t new_nbmem;
-
-                               new_nbmem = nbmem << 1;
-                               DBG2("Reallocating event list from %zu to %zu entries",
-                                               nbmem, new_nbmem);
-                               new_tmp_event = (lttng_event *) realloc(tmp_event,
-                                       new_nbmem * sizeof(struct lttng_event));
-                               if (new_tmp_event == NULL) {
+                       while ((ret = lttng_ust_ctl_tracepoint_list_get(
+                                       app->sock, handle, &uiter)) != -LTTNG_UST_ERR_NOENT) {
+                               /* Handle ustctl error. */
+                               if (ret < 0) {
                                        int release_ret;
 
-                                       PERROR("realloc ust app events");
+                                       if (ret != -LTTNG_UST_ERR_EXITING && ret != -EPIPE) {
+                                               ERR("UST app tp list get failed for app %d with ret %d",
+                                                   app->sock,
+                                                   ret);
+                                       } else {
+                                               DBG3("UST app tp list get failed. Application is dead");
+                                               break;
+                                       }
+
                                        free(tmp_event);
-                                       ret = -ENOMEM;
-                                       release_ret = lttng_ust_ctl_release_handle(app->sock, handle);
+                                       release_ret =
+                                               lttng_ust_ctl_release_handle(app->sock, handle);
                                        if (release_ret < 0 &&
-                                                       release_ret != -LTTNG_UST_ERR_EXITING &&
-                                                       release_ret != -EPIPE) {
-                                               ERR("Error releasing app handle for app %d with ret %d", app->sock, release_ret);
+                                           release_ret != -LTTNG_UST_ERR_EXITING &&
+                                           release_ret != -EPIPE) {
+                                               ERR("Error releasing app handle for app %d with ret %d",
+                                                   app->sock,
+                                                   release_ret);
                                        }
+
                                        pthread_mutex_unlock(&app->sock_lock);
                                        goto rcu_error;
                                }
-                               /* Zero the new memory */
-                               memset(new_tmp_event + nbmem, 0,
-                                       (new_nbmem - nbmem) * sizeof(struct lttng_event));
-                               nbmem = new_nbmem;
-                               tmp_event = new_tmp_event;
+
+                               health_code_update();
+                               if (count >= nbmem) {
+                                       /* In case the realloc fails, we free the memory */
+                                       struct lttng_event *new_tmp_event;
+                                       size_t new_nbmem;
+
+                                       new_nbmem = nbmem << 1;
+                                       DBG2("Reallocating event list from %zu to %zu entries",
+                                            nbmem,
+                                            new_nbmem);
+                                       new_tmp_event = (lttng_event *) realloc(
+                                               tmp_event, new_nbmem * sizeof(struct lttng_event));
+                                       if (new_tmp_event == nullptr) {
+                                               int release_ret;
+
+                                               PERROR("realloc ust app events");
+                                               free(tmp_event);
+                                               ret = -ENOMEM;
+                                               release_ret = lttng_ust_ctl_release_handle(
+                                                       app->sock, handle);
+                                               if (release_ret < 0 &&
+                                                   release_ret != -LTTNG_UST_ERR_EXITING &&
+                                                   release_ret != -EPIPE) {
+                                                       ERR("Error releasing app handle for app %d with ret %d",
+                                                           app->sock,
+                                                           release_ret);
+                                               }
+
+                                               pthread_mutex_unlock(&app->sock_lock);
+                                               goto rcu_error;
+                                       }
+                                       /* Zero the new memory */
+                                       memset(new_tmp_event + nbmem,
+                                              0,
+                                              (new_nbmem - nbmem) * sizeof(struct lttng_event));
+                                       nbmem = new_nbmem;
+                                       tmp_event = new_tmp_event;
+                               }
+
+                               memcpy(tmp_event[count].name,
+                                      uiter.name,
+                                      LTTNG_UST_ABI_SYM_NAME_LEN);
+                               tmp_event[count].loglevel = uiter.loglevel;
+                               tmp_event[count].type =
+                                       (enum lttng_event_type) LTTNG_UST_ABI_TRACEPOINT;
+                               tmp_event[count].pid = app->pid;
+                               tmp_event[count].enabled = -1;
+                               count++;
                        }
-                       memcpy(tmp_event[count].name, uiter.name, LTTNG_UST_ABI_SYM_NAME_LEN);
-                       tmp_event[count].loglevel = uiter.loglevel;
-                       tmp_event[count].type = (enum lttng_event_type) LTTNG_UST_ABI_TRACEPOINT;
-                       tmp_event[count].pid = app->pid;
-                       tmp_event[count].enabled = -1;
-                       count++;
-               }
-               ret = lttng_ust_ctl_release_handle(app->sock, handle);
-               pthread_mutex_unlock(&app->sock_lock);
-               if (ret < 0) {
-                       if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
-                               DBG3("Error releasing app handle. Application died: pid = %d, sock = %d",
-                                               app->pid, app->sock);
-                       } else if (ret == -EAGAIN) {
-                               WARN("Error releasing app handle. Communication time out: pid = %d, sock = %d",
-                                               app->pid, app->sock);
-                       } else {
-                               ERR("Error releasing app handle with ret %d: pid = %d, sock = %d",
-                                               ret, app->pid, app->sock);
+
+                       ret = lttng_ust_ctl_release_handle(app->sock, handle);
+                       pthread_mutex_unlock(&app->sock_lock);
+                       if (ret < 0) {
+                               if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
+                                       DBG3("Error releasing app handle. Application died: pid = %d, sock = %d",
+                                            app->pid,
+                                            app->sock);
+                               } else if (ret == -EAGAIN) {
+                                       WARN("Error releasing app handle. Communication time out: pid = %d, sock = %d",
+                                            app->pid,
+                                            app->sock);
+                               } else {
+                                       ERR("Error releasing app handle with ret %d: pid = %d, sock = %d",
+                                           ret,
+                                           app->pid,
+                                           app->sock);
+                               }
                        }
                }
        }
@@ -4497,7 +4617,6 @@ int ust_app_list_events(struct lttng_event **events)
        DBG2("UST app list events done (%zu events)", count);
 
 rcu_error:
-       rcu_read_unlock();
 error:
        health_code_update();
        return ret;
@@ -4516,112 +4635,135 @@ int ust_app_list_event_fields(struct lttng_event_field **fields)
 
        nbmem = UST_APP_EVENT_LIST_SIZE;
        tmp_event = calloc<lttng_event_field>(nbmem);
-       if (tmp_event == NULL) {
+       if (tmp_event == nullptr) {
                PERROR("zmalloc ust app event fields");
                ret = -ENOMEM;
                goto error;
        }
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               struct lttng_ust_abi_field_iter uiter;
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       struct lttng_ust_abi_field_iter uiter;
 
-               health_code_update();
+                       health_code_update();
 
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               pthread_mutex_lock(&app->sock_lock);
-               handle = lttng_ust_ctl_tracepoint_field_list(app->sock);
-               if (handle < 0) {
-                       if (handle != -EPIPE && handle != -LTTNG_UST_ERR_EXITING) {
-                               ERR("UST app list field getting handle failed for app pid %d",
-                                               app->pid);
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
                        }
-                       pthread_mutex_unlock(&app->sock_lock);
-                       continue;
-               }
 
-               while ((ret = lttng_ust_ctl_tracepoint_field_list_get(app->sock, handle,
-                                       &uiter)) != -LTTNG_UST_ERR_NOENT) {
-                       /* Handle ustctl error. */
-                       if (ret < 0) {
-                               int release_ret;
-
-                               if (ret != -LTTNG_UST_ERR_EXITING && ret != -EPIPE) {
-                                       ERR("UST app tp list field failed for app %d with ret %d",
-                                                       app->sock, ret);
-                               } else {
-                                       DBG3("UST app tp list field failed. Application is dead");
-                                       break;
+                       pthread_mutex_lock(&app->sock_lock);
+                       handle = lttng_ust_ctl_tracepoint_field_list(app->sock);
+                       if (handle < 0) {
+                               if (handle != -EPIPE && handle != -LTTNG_UST_ERR_EXITING) {
+                                       ERR("UST app list field getting handle failed for app pid %d",
+                                           app->pid);
                                }
-                               free(tmp_event);
-                               release_ret = lttng_ust_ctl_release_handle(app->sock, handle);
                                pthread_mutex_unlock(&app->sock_lock);
-                               if (release_ret < 0 &&
-                                               release_ret != -LTTNG_UST_ERR_EXITING &&
-                                               release_ret != -EPIPE) {
-                                       ERR("Error releasing app handle for app %d with ret %d", app->sock, release_ret);
-                               }
-                               goto rcu_error;
+                               continue;
                        }
 
-                       health_code_update();
-                       if (count >= nbmem) {
-                               /* In case the realloc fails, we free the memory */
-                               struct lttng_event_field *new_tmp_event;
-                               size_t new_nbmem;
-
-                               new_nbmem = nbmem << 1;
-                               DBG2("Reallocating event field list from %zu to %zu entries",
-                                               nbmem, new_nbmem);
-                               new_tmp_event = (lttng_event_field *) realloc(tmp_event,
-                                       new_nbmem * sizeof(struct lttng_event_field));
-                               if (new_tmp_event == NULL) {
+                       while ((ret = lttng_ust_ctl_tracepoint_field_list_get(
+                                       app->sock, handle, &uiter)) != -LTTNG_UST_ERR_NOENT) {
+                               /* Handle ustctl error. */
+                               if (ret < 0) {
                                        int release_ret;
 
-                                       PERROR("realloc ust app event fields");
+                                       if (ret != -LTTNG_UST_ERR_EXITING && ret != -EPIPE) {
+                                               ERR("UST app tp list field failed for app %d with ret %d",
+                                                   app->sock,
+                                                   ret);
+                                       } else {
+                                               DBG3("UST app tp list field failed. Application is dead");
+                                               break;
+                                       }
+
                                        free(tmp_event);
-                                       ret = -ENOMEM;
-                                       release_ret = lttng_ust_ctl_release_handle(app->sock, handle);
+                                       release_ret =
+                                               lttng_ust_ctl_release_handle(app->sock, handle);
                                        pthread_mutex_unlock(&app->sock_lock);
-                                       if (release_ret &&
-                                                       release_ret != -LTTNG_UST_ERR_EXITING &&
-                                                       release_ret != -EPIPE) {
-                                               ERR("Error releasing app handle for app %d with ret %d", app->sock, release_ret);
+                                       if (release_ret < 0 &&
+                                           release_ret != -LTTNG_UST_ERR_EXITING &&
+                                           release_ret != -EPIPE) {
+                                               ERR("Error releasing app handle for app %d with ret %d",
+                                                   app->sock,
+                                                   release_ret);
                                        }
+
                                        goto rcu_error;
                                }
-                               /* Zero the new memory */
-                               memset(new_tmp_event + nbmem, 0,
-                                       (new_nbmem - nbmem) * sizeof(struct lttng_event_field));
-                               nbmem = new_nbmem;
-                               tmp_event = new_tmp_event;
-                       }
 
-                       memcpy(tmp_event[count].field_name, uiter.field_name, LTTNG_UST_ABI_SYM_NAME_LEN);
-                       /* Mapping between these enums matches 1 to 1. */
-                       tmp_event[count].type = (enum lttng_event_field_type) uiter.type;
-                       tmp_event[count].nowrite = uiter.nowrite;
+                               health_code_update();
+                               if (count >= nbmem) {
+                                       /* In case the realloc fails, we free the memory */
+                                       struct lttng_event_field *new_tmp_event;
+                                       size_t new_nbmem;
+
+                                       new_nbmem = nbmem << 1;
+                                       DBG2("Reallocating event field list from %zu to %zu entries",
+                                            nbmem,
+                                            new_nbmem);
+                                       new_tmp_event = (lttng_event_field *) realloc(
+                                               tmp_event,
+                                               new_nbmem * sizeof(struct lttng_event_field));
+                                       if (new_tmp_event == nullptr) {
+                                               int release_ret;
+
+                                               PERROR("realloc ust app event fields");
+                                               free(tmp_event);
+                                               ret = -ENOMEM;
+                                               release_ret = lttng_ust_ctl_release_handle(
+                                                       app->sock, handle);
+                                               pthread_mutex_unlock(&app->sock_lock);
+                                               if (release_ret &&
+                                                   release_ret != -LTTNG_UST_ERR_EXITING &&
+                                                   release_ret != -EPIPE) {
+                                                       ERR("Error releasing app handle for app %d with ret %d",
+                                                           app->sock,
+                                                           release_ret);
+                                               }
+
+                                               goto rcu_error;
+                                       }
 
-                       memcpy(tmp_event[count].event.name, uiter.event_name, LTTNG_UST_ABI_SYM_NAME_LEN);
-                       tmp_event[count].event.loglevel = uiter.loglevel;
-                       tmp_event[count].event.type = LTTNG_EVENT_TRACEPOINT;
-                       tmp_event[count].event.pid = app->pid;
-                       tmp_event[count].event.enabled = -1;
-                       count++;
-               }
-               ret = lttng_ust_ctl_release_handle(app->sock, handle);
-               pthread_mutex_unlock(&app->sock_lock);
-               if (ret < 0 &&
-                               ret != -LTTNG_UST_ERR_EXITING &&
-                               ret != -EPIPE) {
-                       ERR("Error releasing app handle for app %d with ret %d", app->sock, ret);
+                                       /* Zero the new memory */
+                                       memset(new_tmp_event + nbmem,
+                                              0,
+                                              (new_nbmem - nbmem) *
+                                                      sizeof(struct lttng_event_field));
+                                       nbmem = new_nbmem;
+                                       tmp_event = new_tmp_event;
+                               }
+
+                               memcpy(tmp_event[count].field_name,
+                                      uiter.field_name,
+                                      LTTNG_UST_ABI_SYM_NAME_LEN);
+                               /* Mapping between these enums matches 1 to 1. */
+                               tmp_event[count].type = (enum lttng_event_field_type) uiter.type;
+                               tmp_event[count].nowrite = uiter.nowrite;
+
+                               memcpy(tmp_event[count].event.name,
+                                      uiter.event_name,
+                                      LTTNG_UST_ABI_SYM_NAME_LEN);
+                               tmp_event[count].event.loglevel = uiter.loglevel;
+                               tmp_event[count].event.type = LTTNG_EVENT_TRACEPOINT;
+                               tmp_event[count].event.pid = app->pid;
+                               tmp_event[count].event.enabled = -1;
+                               count++;
+                       }
+
+                       ret = lttng_ust_ctl_release_handle(app->sock, handle);
+                       pthread_mutex_unlock(&app->sock_lock);
+                       if (ret < 0 && ret != -LTTNG_UST_ERR_EXITING && ret != -EPIPE) {
+                               ERR("Error releasing app handle for app %d with ret %d",
+                                   app->sock,
+                                   ret);
+                       }
                }
        }
 
@@ -4631,7 +4773,6 @@ int ust_app_list_event_fields(struct lttng_event_field **fields)
        DBG2("UST app list event fields done (%zu events)", count);
 
 rcu_error:
-       rcu_read_unlock();
 error:
        health_code_update();
        return ret;
@@ -4640,7 +4781,7 @@ error:
 /*
  * Free and clean all traceable apps of the global list.
  */
-void ust_app_clean_list(void)
+void ust_app_clean_list()
 {
        int ret;
        struct ust_app *app;
@@ -4648,41 +4789,32 @@ void ust_app_clean_list(void)
 
        DBG2("UST app cleaning registered apps hash table");
 
-       rcu_read_lock();
-
        /* Cleanup notify socket hash table */
        if (ust_app_ht_by_notify_sock) {
-               cds_lfht_for_each_entry(ust_app_ht_by_notify_sock->ht, &iter.iter, app,
-                               notify_sock_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       ust_app_ht_by_notify_sock->ht, &iter.iter, app, notify_sock_n.node) {
                        /*
                         * Assert that all notifiers are gone as all triggers
                         * are unregistered prior to this clean-up.
                         */
                        LTTNG_ASSERT(lttng_ht_get_count(app->token_to_event_notifier_rule_ht) == 0);
-
                        ust_app_notify_sock_unregister(app->notify_sock);
                }
        }
 
-       if (ust_app_ht) {
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-                       ret = lttng_ht_del(ust_app_ht, &iter);
-                       LTTNG_ASSERT(!ret);
-                       call_rcu(&app->pid_n.head, delete_ust_app_rcu);
-               }
-       }
-
        /* Cleanup socket hash table */
        if (ust_app_ht_by_sock) {
-               cds_lfht_for_each_entry(ust_app_ht_by_sock->ht, &iter.iter, app,
-                               sock_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ust_app_ht_by_sock->ht, &iter.iter, app, sock_n.node) {
                        ret = lttng_ht_del(ust_app_ht_by_sock, &iter);
                        LTTNG_ASSERT(!ret);
+                       ust_app_put(app);
                }
        }
 
-       rcu_read_unlock();
-
        /* Destroy is done only when the ht is empty */
        if (ust_app_ht) {
                lttng_ht_destroy(ust_app_ht);
@@ -4698,7 +4830,7 @@ void ust_app_clean_list(void)
 /*
  * Init UST app hash table.
  */
-int ust_app_ht_alloc(void)
+int ust_app_ht_alloc()
 {
        ust_app_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
        if (!ust_app_ht) {
@@ -4718,8 +4850,7 @@ int ust_app_ht_alloc(void)
 /*
  * For a specific UST session, disable the channel for all registered apps.
  */
-int ust_app_disable_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan)
+int ust_app_disable_channel_glb(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -4730,52 +4861,53 @@ int ust_app_disable_channel_glb(struct ltt_ust_session *usess,
 
        LTTNG_ASSERT(usess->active);
        DBG2("UST app disabling channel %s from global domain for session id %" PRIu64,
-                       uchan->name, usess->id);
+            uchan->name,
+            usess->id);
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       /* For every registered applications */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               struct lttng_ht_iter uiter;
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (ua_sess == NULL) {
-                       continue;
-               }
+               /* For every registered applications */
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       struct lttng_ht_iter uiter;
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (ua_sess == nullptr) {
+                               continue;
+                       }
 
-               /* Get channel */
-               lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &uiter);
-               ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
-               /* If the session if found for the app, the channel must be there */
-               LTTNG_ASSERT(ua_chan_node);
+                       /* Get channel */
+                       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &uiter);
+                       ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
+                       /* If the session if found for the app, the channel must be there */
+                       LTTNG_ASSERT(ua_chan_node);
 
-               ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
-               /* The channel must not be already disabled */
-               LTTNG_ASSERT(ua_chan->enabled == 1);
+                       ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+                       /* The channel must not be already disabled */
+                       LTTNG_ASSERT(ua_chan->enabled);
 
-               /* Disable channel onto application */
-               ret = disable_ust_app_channel(ua_sess, ua_chan, app);
-               if (ret < 0) {
-                       /* XXX: We might want to report this error at some point... */
-                       continue;
+                       /* Disable channel onto application */
+                       ret = disable_ust_app_channel(ua_sess, ua_chan, app);
+                       if (ret < 0) {
+                               /* XXX: We might want to report this error at some point... */
+                               continue;
+                       }
                }
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
 /*
  * For a specific UST session, enable the channel for all registered apps.
  */
-int ust_app_enable_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan)
+int ust_app_enable_channel_glb(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -4784,33 +4916,35 @@ int ust_app_enable_channel_glb(struct ltt_ust_session *usess,
 
        LTTNG_ASSERT(usess->active);
        DBG2("UST app enabling channel %s to global domain for session id %" PRIu64,
-                       uchan->name, usess->id);
+            uchan->name,
+            usess->id);
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       /* For every registered applications */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (ua_sess == NULL) {
-                       continue;
-               }
+               /* For every registered applications */
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (ua_sess == nullptr) {
+                               continue;
+                       }
 
-               /* Enable channel onto application */
-               ret = enable_ust_app_channel(ua_sess, uchan, app);
-               if (ret < 0) {
-                       /* XXX: We might want to report this error at some point... */
-                       continue;
+                       /* Enable channel onto application */
+                       ret = enable_ust_app_channel(ua_sess, uchan, app);
+                       if (ret < 0) {
+                               /* XXX: We might want to report this error at some point... */
+                               continue;
+                       }
                }
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
@@ -4818,7 +4952,8 @@ int ust_app_enable_channel_glb(struct ltt_ust_session *usess,
  * Disable an event in a channel and for a specific session.
  */
 int ust_app_disable_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent)
+                             struct ltt_ust_channel *uchan,
+                             struct ltt_ust_event *uevent)
 {
        int ret = 0;
        struct lttng_ht_iter iter, uiter;
@@ -4830,98 +4965,107 @@ int ust_app_disable_event_glb(struct ltt_ust_session *usess,
 
        LTTNG_ASSERT(usess->active);
        DBG("UST app disabling event %s for all apps in channel "
-                       "%s for session id %" PRIu64,
-                       uevent->attr.name, uchan->name, usess->id);
-
-       rcu_read_lock();
+           "%s for session id %" PRIu64,
+           uevent->attr.name,
+           uchan->name,
+           usess->id);
 
-       /* For all registered applications */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (ua_sess == NULL) {
-                       /* Next app */
-                       continue;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               /* Lookup channel in the ust app session */
-               lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &uiter);
-               ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
-               if (ua_chan_node == NULL) {
-                       DBG2("Channel %s not found in session id %" PRIu64 " for app pid %d."
-                                       "Skipping", uchan->name, usess->id, app->pid);
-                       continue;
-               }
-               ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+               /* For all registered applications */
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (ua_sess == nullptr) {
+                               /* Next app */
+                               continue;
+                       }
 
-               ua_event = find_ust_app_event(ua_chan->events, uevent->attr.name,
-                               uevent->filter, uevent->attr.loglevel,
+                       /* Lookup channel in the ust app session */
+                       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &uiter);
+                       ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
+                       if (ua_chan_node == nullptr) {
+                               DBG2("Channel %s not found in session id %" PRIu64
+                                    " for app pid %d."
+                                    "Skipping",
+                                    uchan->name,
+                                    usess->id,
+                                    app->pid);
+                               continue;
+                       }
+                       ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+
+                       ua_event = find_ust_app_event(
+                               ua_chan->events,
+                               uevent->attr.name,
+                               uevent->filter,
+                               (enum lttng_ust_abi_loglevel_type) uevent->attr.loglevel_type,
+                               uevent->attr.loglevel,
                                uevent->exclusion);
-               if (ua_event == NULL) {
-                       DBG2("Event %s not found in channel %s for app pid %d."
-                                       "Skipping", uevent->attr.name, uchan->name, app->pid);
-                       continue;
-               }
+                       if (ua_event == nullptr) {
+                               DBG2("Event %s not found in channel %s for app pid %d."
+                                    "Skipping",
+                                    uevent->attr.name,
+                                    uchan->name,
+                                    app->pid);
+                               continue;
+                       }
 
-               ret = disable_ust_app_event(ua_event, app);
-               if (ret < 0) {
-                       /* XXX: Report error someday... */
-                       continue;
+                       ret = disable_ust_app_event(ua_event, app);
+                       if (ret < 0) {
+                               /* XXX: Report error someday... */
+                               continue;
+                       }
                }
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
 /* The ua_sess lock must be held by the caller.  */
-static
-int ust_app_channel_create(struct ltt_ust_session *usess,
-               struct ust_app_session *ua_sess,
-               struct ltt_ust_channel *uchan, struct ust_app *app,
-               struct ust_app_channel **_ua_chan)
+static int ust_app_channel_create(struct ltt_ust_session *usess,
+                                 struct ust_app_session *ua_sess,
+                                 struct ltt_ust_channel *uchan,
+                                 struct ust_app *app,
+                                 struct ust_app_channel **_ua_chan)
 {
        int ret = 0;
-       struct ust_app_channel *ua_chan = NULL;
+       struct ust_app_channel *ua_chan = nullptr;
 
        LTTNG_ASSERT(ua_sess);
        ASSERT_LOCKED(ua_sess->lock);
 
-       if (!strncmp(uchan->name, DEFAULT_METADATA_NAME,
-                    sizeof(uchan->name))) {
-               copy_channel_attr_to_ustctl(&ua_sess->metadata_attr,
-                       &uchan->attr);
+       if (!strncmp(uchan->name, DEFAULT_METADATA_NAME, sizeof(uchan->name))) {
+               copy_channel_attr_to_ustctl(&ua_sess->metadata_attr, &uchan->attr);
                ret = 0;
        } else {
-               struct ltt_ust_context *uctx = NULL;
+               struct ltt_ust_context *uctx = nullptr;
 
                /*
                 * Create channel onto application and synchronize its
                 * configuration.
                 */
-               ret = ust_app_channel_allocate(ua_sess, uchan,
-                       LTTNG_UST_ABI_CHAN_PER_CPU, usess,
-                       &ua_chan);
+               ret = ust_app_channel_allocate(
+                       ua_sess, uchan, LTTNG_UST_ABI_CHAN_PER_CPU, usess, &ua_chan);
                if (ret < 0) {
                        goto error;
                }
 
-               ret = ust_app_channel_send(app, usess,
-                       ua_sess, ua_chan);
+               ret = ust_app_channel_send(app, usess, ua_sess, ua_chan);
                if (ret) {
                        goto error;
                }
 
                /* Add contexts. */
-               cds_list_for_each_entry(uctx, &uchan->ctx_list, list) {
-                       ret = create_ust_app_channel_context(ua_chan,
-                               &uctx->ctx, app);
+               cds_list_for_each_entry (uctx, &uchan->ctx_list, list) {
+                       ret = create_ust_app_channel_context(ua_chan, &uctx->ctx, app);
                        if (ret) {
                                goto error;
                        }
@@ -4937,7 +5081,7 @@ error:
                         * or a timeout on it. We can't inform the caller that for a
                         * specific app, the session failed so lets continue here.
                         */
-                       ret = 0;        /* Not an error. */
+                       ret = 0; /* Not an error. */
                        break;
                case -ENOMEM:
                default:
@@ -4960,7 +5104,8 @@ error:
  * Enable event for a specific session and channel on the tracer.
  */
 int ust_app_enable_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent)
+                            struct ltt_ust_channel *uchan,
+                            struct ltt_ust_event *uevent)
 {
        int ret = 0;
        struct lttng_ht_iter iter, uiter;
@@ -4972,7 +5117,8 @@ int ust_app_enable_event_glb(struct ltt_ust_session *usess,
 
        LTTNG_ASSERT(usess->active);
        DBG("UST app enabling event %s for all apps for session id %" PRIu64,
-                       uevent->attr.name, usess->id);
+           uevent->attr.name,
+           usess->id);
 
        /*
         * NOTE: At this point, this function is called only if the session and
@@ -4980,65 +5126,72 @@ int ust_app_enable_event_glb(struct ltt_ust_session *usess,
         * tracer also.
         */
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       /* For all registered applications */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (!ua_sess) {
-                       /* The application has problem or is probably dead. */
-                       continue;
-               }
+               /* For all registered applications */
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (!ua_sess) {
+                               /* The application has problem or is probably dead. */
+                               continue;
+                       }
 
-               pthread_mutex_lock(&ua_sess->lock);
+                       pthread_mutex_lock(&ua_sess->lock);
 
-               if (ua_sess->deleted) {
-                       pthread_mutex_unlock(&ua_sess->lock);
-                       continue;
-               }
+                       if (ua_sess->deleted) {
+                               pthread_mutex_unlock(&ua_sess->lock);
+                               continue;
+                       }
 
-               /* Lookup channel in the ust app session */
-               lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &uiter);
-               ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
-               /*
-                * It is possible that the channel cannot be found is
-                * the channel/event creation occurs concurrently with
-                * an application exit.
-                */
-               if (!ua_chan_node) {
-                       pthread_mutex_unlock(&ua_sess->lock);
-                       continue;
-               }
+                       /* Lookup channel in the ust app session */
+                       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &uiter);
+                       ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
+                       /*
+                        * It is possible that the channel cannot be found is
+                        * the channel/event creation occurs concurrently with
+                        * an application exit.
+                        */
+                       if (!ua_chan_node) {
+                               pthread_mutex_unlock(&ua_sess->lock);
+                               continue;
+                       }
 
-               ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+                       ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
 
-               /* Get event node */
-               ua_event = find_ust_app_event(ua_chan->events, uevent->attr.name,
-                               uevent->filter, uevent->attr.loglevel, uevent->exclusion);
-               if (ua_event == NULL) {
-                       DBG3("UST app enable event %s not found for app PID %d."
-                                       "Skipping app", uevent->attr.name, app->pid);
-                       goto next_app;
-               }
+                       /* Get event node */
+                       ua_event = find_ust_app_event(
+                               ua_chan->events,
+                               uevent->attr.name,
+                               uevent->filter,
+                               (enum lttng_ust_abi_loglevel_type) uevent->attr.loglevel_type,
+                               uevent->attr.loglevel,
+                               uevent->exclusion);
+                       if (ua_event == nullptr) {
+                               DBG3("UST app enable event %s not found for app PID %d."
+                                    "Skipping app",
+                                    uevent->attr.name,
+                                    app->pid);
+                               goto next_app;
+                       }
 
-               ret = enable_ust_app_event(ua_event, app);
-               if (ret < 0) {
+                       ret = enable_ust_app_event(ua_event, app);
+                       if (ret < 0) {
+                               pthread_mutex_unlock(&ua_sess->lock);
+                               goto error;
+                       }
+               next_app:
                        pthread_mutex_unlock(&ua_sess->lock);
-                       goto error;
                }
-       next_app:
-               pthread_mutex_unlock(&ua_sess->lock);
        }
-
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -5047,7 +5200,8 @@ error:
  * all registered apps.
  */
 int ust_app_create_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent)
+                            struct ltt_ust_channel *uchan,
+                            struct ltt_ust_event *uevent)
 {
        int ret = 0;
        struct lttng_ht_iter iter, uiter;
@@ -5058,54 +5212,59 @@ int ust_app_create_event_glb(struct ltt_ust_session *usess,
 
        LTTNG_ASSERT(usess->active);
        DBG("UST app creating event %s for all apps for session id %" PRIu64,
-                       uevent->attr.name, usess->id);
+           uevent->attr.name,
+           usess->id);
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       /* For all registered applications */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (!ua_sess) {
-                       /* The application has problem or is probably dead. */
-                       continue;
-               }
+               /* For all registered applications */
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
 
-               pthread_mutex_lock(&ua_sess->lock);
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (!ua_sess) {
+                               /* The application has problem or is probably dead. */
+                               continue;
+                       }
 
-               if (ua_sess->deleted) {
-                       pthread_mutex_unlock(&ua_sess->lock);
-                       continue;
-               }
+                       pthread_mutex_lock(&ua_sess->lock);
 
-               /* Lookup channel in the ust app session */
-               lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &uiter);
-               ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
-               /* If the channel is not found, there is a code flow error */
-               LTTNG_ASSERT(ua_chan_node);
+                       if (ua_sess->deleted) {
+                               pthread_mutex_unlock(&ua_sess->lock);
+                               continue;
+                       }
 
-               ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+                       /* Lookup channel in the ust app session */
+                       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &uiter);
+                       ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
+                       /* If the channel is not found, there is a code flow error */
+                       LTTNG_ASSERT(ua_chan_node);
 
-               ret = create_ust_app_event(ua_chan, uevent, app);
-               pthread_mutex_unlock(&ua_sess->lock);
-               if (ret < 0) {
-                       if (ret != -LTTNG_UST_ERR_EXIST) {
-                               /* Possible value at this point: -ENOMEM. If so, we stop! */
-                               break;
+                       ua_chan = lttng::utils::container_of(ua_chan_node, &ust_app_channel::node);
+
+                       ret = create_ust_app_event(ua_chan, uevent, app);
+                       pthread_mutex_unlock(&ua_sess->lock);
+                       if (ret < 0) {
+                               if (ret != -LTTNG_UST_ERR_EXIST) {
+                                       /* Possible value at this point: -ENOMEM. If so, we stop! */
+                                       break;
+                               }
+
+                               DBG2("UST app event %s already exist on app PID %d",
+                                    uevent->attr.name,
+                                    app->pid);
+                               continue;
                        }
-                       DBG2("UST app event %s already exist on app PID %d",
-                                       uevent->attr.name, app->pid);
-                       continue;
                }
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
@@ -5115,22 +5274,21 @@ int ust_app_create_event_glb(struct ltt_ust_session *usess,
  * Called with UST app session lock held.
  *
  */
-static
-int ust_app_start_trace(struct ltt_ust_session *usess, struct ust_app *app)
+static int ust_app_start_trace(struct ltt_ust_session *usess, struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_session *ua_sess;
 
        DBG("Starting tracing for ust app pid %d", app->pid);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!app->compatible) {
                goto end;
        }
 
        ua_sess = lookup_session_by_app(usess, app);
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                /* The session is in teardown process. Ignore and continue. */
                goto end;
        }
@@ -5162,25 +5320,29 @@ skip_setup:
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app start session failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                        pthread_mutex_unlock(&ua_sess->lock);
                        goto end;
                } else if (ret == -EAGAIN) {
                        WARN("UST app start session failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                        pthread_mutex_unlock(&ua_sess->lock);
                        goto end;
 
                } else {
                        ERR("UST app start session failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error_unlock;
        }
 
        /* Indicate that the session has been started once */
-       ua_sess->started = 1;
-       ua_sess->enabled = 1;
+       ua_sess->started = true;
+       ua_sess->enabled = true;
 
        pthread_mutex_unlock(&ua_sess->lock);
 
@@ -5193,24 +5355,26 @@ skip_setup:
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app wait quiescent failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app wait quiescent failed. Communication time out: pid =  %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app wait quiescent failed with ret %d: pid %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
        }
 
 end:
-       rcu_read_unlock();
        health_code_update();
        return 0;
 
 error_unlock:
        pthread_mutex_unlock(&ua_sess->lock);
-       rcu_read_unlock();
        health_code_update();
        return -1;
 }
@@ -5218,22 +5382,21 @@ error_unlock:
 /*
  * Stop tracing for a specific UST session and app.
  */
-static
-int ust_app_stop_trace(struct ltt_ust_session *usess, struct ust_app *app)
+static int ust_app_stop_trace(struct ltt_ust_session *usess, struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_session *ua_sess;
 
        DBG("Stopping tracing for ust app pid %d", app->pid);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!app->compatible) {
                goto end_no_session;
        }
 
        ua_sess = lookup_session_by_app(usess, app);
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                goto end_no_session;
        }
 
@@ -5263,22 +5426,26 @@ int ust_app_stop_trace(struct ltt_ust_session *usess, struct ust_app *app)
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app stop session failed. Application is dead: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                        goto end_unlock;
                } else if (ret == -EAGAIN) {
                        WARN("UST app stop session failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                        goto end_unlock;
 
                } else {
                        ERR("UST app stop session failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error_rcu_unlock;
        }
 
        health_code_update();
-       ua_sess->enabled = 0;
+       ua_sess->enabled = false;
 
        /* Quiescent wait after stopping trace */
        pthread_mutex_lock(&app->sock_lock);
@@ -5287,13 +5454,17 @@ int ust_app_stop_trace(struct ltt_ust_session *usess, struct ust_app *app)
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app wait quiescent failed. Application is dead: pid= %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app wait quiescent failed. Communication time out: pid= %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app wait quiescent failed with ret %d: pid= %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
        }
 
@@ -5312,51 +5483,46 @@ int ust_app_stop_trace(struct ltt_ust_session *usess, struct ust_app *app)
 end_unlock:
        pthread_mutex_unlock(&ua_sess->lock);
 end_no_session:
-       rcu_read_unlock();
        health_code_update();
        return 0;
 
 error_rcu_unlock:
        pthread_mutex_unlock(&ua_sess->lock);
-       rcu_read_unlock();
        health_code_update();
        return -1;
 }
 
-static
-int ust_app_flush_app_session(struct ust_app *app,
-               struct ust_app_session *ua_sess)
+static int ust_app_flush_app_session(ust_app& app, ust_app_session& ua_sess)
 {
        int ret, retval = 0;
        struct lttng_ht_iter iter;
        struct ust_app_channel *ua_chan;
        struct consumer_socket *socket;
 
-       DBG("Flushing app session buffers for ust app pid %d", app->pid);
+       DBG("Flushing app session buffers for ust app pid %d", app.pid);
 
-       rcu_read_lock();
-
-       if (!app->compatible) {
+       if (!app.compatible) {
                goto end_not_compatible;
        }
 
-       pthread_mutex_lock(&ua_sess->lock);
+       pthread_mutex_lock(&ua_sess.lock);
 
-       if (ua_sess->deleted) {
+       if (ua_sess.deleted) {
                goto end_deleted;
        }
 
        health_code_update();
 
        /* Flushing buffers */
-       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
-                       ua_sess->consumer);
+       socket = consumer_find_socket_by_bitness(app.abi.bits_per_long, ua_sess.consumer);
 
        /* Flush buffers and push metadata. */
-       switch (ua_sess->buffer_type) {
+       switch (ua_sess.buffer_type) {
        case LTTNG_BUFFER_PER_PID:
-               cds_lfht_for_each_entry(ua_sess->channels->ht, &iter.iter, ua_chan,
-                               node.node) {
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ua_sess.channels->ht, &iter.iter, ua_chan, node.node) {
                        health_code_update();
                        ret = consumer_flush_channel(socket, ua_chan->key);
                        if (ret) {
@@ -5365,7 +5531,9 @@ int ust_app_flush_app_session(struct ust_app *app,
                                continue;
                        }
                }
+
                break;
+       }
        case LTTNG_BUFFER_PER_UID:
        default:
                abort();
@@ -5375,10 +5543,9 @@ int ust_app_flush_app_session(struct ust_app *app,
        health_code_update();
 
 end_deleted:
-       pthread_mutex_unlock(&ua_sess->lock);
+       pthread_mutex_unlock(&ua_sess.lock);
 
 end_not_compatible:
-       rcu_read_unlock();
        health_code_update();
        return retval;
 }
@@ -5387,16 +5554,13 @@ end_not_compatible:
  * Flush buffers for all applications for a specific UST session.
  * Called with UST session lock held.
  */
-static
-int ust_app_flush_session(struct ltt_ust_session *usess)
+static int ust_app_flush_session(struct ltt_ust_session *usess)
 
 {
        int ret = 0;
 
        DBG("Flushing session buffers for all ust apps");
 
-       rcu_read_lock();
-
        /* Flush buffers and push metadata. */
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
@@ -5405,21 +5569,22 @@ int ust_app_flush_session(struct ltt_ust_session *usess)
                struct lttng_ht_iter iter;
 
                /* Flush all per UID buffers associated to that session. */
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
+                       lttng::urcu::read_lock_guard read_lock;
                        lsu::registry_session *ust_session_reg;
                        struct buffer_reg_channel *buf_reg_chan;
                        struct consumer_socket *socket;
 
                        /* Get consumer socket to use to push the metadata.*/
                        socket = consumer_find_socket_by_bitness(reg->bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                /* Ignore request if no consumer is found for the session. */
                                continue;
                        }
 
-                       cds_lfht_for_each_entry(reg->registry->channels->ht, &iter.iter,
-                                       buf_reg_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
                                /*
                                 * The following call will print error values so the return
                                 * code is of little importance because whatever happens, we
@@ -5433,6 +5598,7 @@ int ust_app_flush_session(struct ltt_ust_session *usess)
                        auto locked_registry = ust_session_reg->lock();
                        (void) push_metadata(locked_registry, usess->consumer);
                }
+
                break;
        }
        case LTTNG_BUFFER_PER_PID:
@@ -5440,14 +5606,17 @@ int ust_app_flush_session(struct ltt_ust_session *usess)
                struct ust_app_session *ua_sess;
                struct lttng_ht_iter iter;
                struct ust_app *app;
+               lttng::urcu::read_lock_guard read_lock;
 
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        ua_sess = lookup_session_by_app(usess, app);
-                       if (ua_sess == NULL) {
+                       if (ua_sess == nullptr) {
                                continue;
                        }
-                       (void) ust_app_flush_app_session(app, ua_sess);
+
+                       (void) ust_app_flush_app_session(*app, *ua_sess);
                }
+
                break;
        }
        default:
@@ -5456,14 +5625,11 @@ int ust_app_flush_session(struct ltt_ust_session *usess)
                break;
        }
 
-       rcu_read_unlock();
        health_code_update();
        return ret;
 }
 
-static
-int ust_app_clear_quiescent_app_session(struct ust_app *app,
-               struct ust_app_session *ua_sess)
+static int ust_app_clear_quiescent_app_session(struct ust_app *app, struct ust_app_session *ua_sess)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -5472,7 +5638,7 @@ int ust_app_clear_quiescent_app_session(struct ust_app *app,
 
        DBG("Clearing stream quiescent state for ust app pid %d", app->pid);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!app->compatible) {
                goto end_not_compatible;
@@ -5486,11 +5652,9 @@ int ust_app_clear_quiescent_app_session(struct ust_app *app,
 
        health_code_update();
 
-       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
-                       ua_sess->consumer);
+       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long, ua_sess->consumer);
        if (!socket) {
-               ERR("Failed to find consumer (%" PRIu32 ") socket",
-                               app->abi.bits_per_long);
+               ERR("Failed to find consumer (%" PRIu32 ") socket", app->abi.bits_per_long);
                ret = -1;
                goto end_unlock;
        }
@@ -5498,11 +5662,9 @@ int ust_app_clear_quiescent_app_session(struct ust_app *app,
        /* Clear quiescent state. */
        switch (ua_sess->buffer_type) {
        case LTTNG_BUFFER_PER_PID:
-               cds_lfht_for_each_entry(ua_sess->channels->ht, &iter.iter,
-                               ua_chan, node.node) {
+               cds_lfht_for_each_entry (ua_sess->channels->ht, &iter.iter, ua_chan, node.node) {
                        health_code_update();
-                       ret = consumer_clear_quiescent_channel(socket,
-                                       ua_chan->key);
+                       ret = consumer_clear_quiescent_channel(socket, ua_chan->key);
                        if (ret) {
                                ERR("Error clearing quiescent state for consumer channel");
                                ret = -1;
@@ -5523,7 +5685,6 @@ end_unlock:
        pthread_mutex_unlock(&ua_sess->lock);
 
 end_not_compatible:
-       rcu_read_unlock();
        health_code_update();
        return ret;
 }
@@ -5533,16 +5694,13 @@ end_not_compatible:
  * specific UST session.
  * Called with UST session lock held.
  */
-static
-int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
+static int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
 
 {
        int ret = 0;
 
        DBG("Clearing stream quiescent state for all ust apps");
 
-       rcu_read_lock();
-
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
        {
@@ -5553,13 +5711,14 @@ int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
                 * Clear quiescent for all per UID buffers associated to
                 * that session.
                 */
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct consumer_socket *socket;
                        struct buffer_reg_channel *buf_reg_chan;
+                       lttng::urcu::read_lock_guard read_lock;
 
                        /* Get associated consumer socket.*/
-                       socket = consumer_find_socket_by_bitness(
-                                       reg->bits_per_long, usess->consumer);
+                       socket = consumer_find_socket_by_bitness(reg->bits_per_long,
+                                                                usess->consumer);
                        if (!socket) {
                                /*
                                 * Ignore request if no consumer is found for
@@ -5568,8 +5727,8 @@ int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
                                continue;
                        }
 
-                       cds_lfht_for_each_entry(reg->registry->channels->ht,
-                                       &iter.iter, buf_reg_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
                                /*
                                 * The following call will print error values so
                                 * the return code is of little importance
@@ -5577,9 +5736,10 @@ int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
                                 * all.
                                 */
                                (void) consumer_clear_quiescent_channel(socket,
-                                               buf_reg_chan->consumer_key);
+                                                                       buf_reg_chan->consumer_key);
                        }
                }
+
                break;
        }
        case LTTNG_BUFFER_PER_PID:
@@ -5587,16 +5747,16 @@ int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
                struct ust_app_session *ua_sess;
                struct lttng_ht_iter iter;
                struct ust_app *app;
+               lttng::urcu::read_lock_guard read_lock;
 
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app,
-                               pid_n.node) {
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        ua_sess = lookup_session_by_app(usess, app);
-                       if (ua_sess == NULL) {
+                       if (ua_sess == nullptr) {
                                continue;
                        }
-                       (void) ust_app_clear_quiescent_app_session(app,
-                                       ua_sess);
+                       (void) ust_app_clear_quiescent_app_session(app, ua_sess);
                }
+
                break;
        }
        default:
@@ -5605,7 +5765,6 @@ int ust_app_clear_quiescent_session(struct ltt_ust_session *usess)
                break;
        }
 
-       rcu_read_unlock();
        health_code_update();
        return ret;
 }
@@ -5622,7 +5781,7 @@ static int destroy_trace(struct ltt_ust_session *usess, struct ust_app *app)
 
        DBG("Destroy tracing for ust app pid %d", app->pid);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (!app->compatible) {
                goto end;
@@ -5630,7 +5789,7 @@ static int destroy_trace(struct ltt_ust_session *usess, struct ust_app *app)
 
        __lookup_session_by_app(usess, app, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                /* Session is being or is deleted. */
                goto end;
        }
@@ -5648,17 +5807,20 @@ static int destroy_trace(struct ltt_ust_session *usess, struct ust_app *app)
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app wait quiescent failed. Application is dead: pid= %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app wait quiescent failed. Communication time out: pid= %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app wait quiescent failed with ret %d: pid= %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
        }
 end:
-       rcu_read_unlock();
        health_code_update();
        return 0;
 }
@@ -5677,9 +5839,7 @@ int ust_app_start_trace_all(struct ltt_ust_session *usess)
         * Even though the start trace might fail, flag this session active so
         * other application coming in are started by default.
         */
-       usess->active = 1;
-
-       rcu_read_lock();
+       usess->active = true;
 
        /*
         * In a start-stop-start use-case, we need to clear the quiescent state
@@ -5689,11 +5849,13 @@ int ust_app_start_trace_all(struct ltt_ust_session *usess)
         */
        (void) ust_app_clear_quiescent_session(usess);
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               ust_app_global_update(usess, app);
-       }
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       rcu_read_unlock();
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       ust_app_global_update(usess, app);
+               }
+       }
 
        return 0;
 }
@@ -5714,22 +5876,22 @@ int ust_app_stop_trace_all(struct ltt_ust_session *usess)
         * Even though the stop trace might fail, flag this session inactive so
         * other application coming in are not started by default.
         */
-       usess->active = 0;
+       usess->active = false;
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               ret = ust_app_stop_trace(usess, app);
-               if (ret < 0) {
-                       /* Continue to next apps even on error */
-                       continue;
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       ret = ust_app_stop_trace(usess, app);
+                       if (ret < 0) {
+                               /* Continue to next apps even on error */
+                               continue;
+                       }
                }
        }
 
        (void) ust_app_flush_session(usess);
 
-       rcu_read_unlock();
-
        return 0;
 }
 
@@ -5744,29 +5906,27 @@ int ust_app_destroy_trace_all(struct ltt_ust_session *usess)
 
        DBG("Destroy all UST traces");
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               ret = destroy_trace(usess, app);
-               if (ret < 0) {
-                       /* Continue to next apps even on error */
-                       continue;
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       ret = destroy_trace(usess, app);
+                       if (ret < 0) {
+                               /* Continue to next apps even on error */
+                               continue;
+                       }
                }
        }
 
-       rcu_read_unlock();
-
        return 0;
 }
 
 /* The ua_sess lock must be held by the caller. */
-static
-int find_or_create_ust_app_channel(
-               struct ltt_ust_session *usess,
-               struct ust_app_session *ua_sess,
-               struct ust_app *app,
-               struct ltt_ust_channel *uchan,
-               struct ust_app_channel **ua_chan)
+static int find_or_create_ust_app_channel(struct ltt_ust_session *usess,
+                                         struct ust_app_session *ua_sess,
+                                         struct ust_app *app,
+                                         struct ltt_ust_channel *uchan,
+                                         struct ust_app_channel **ua_chan)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -5775,8 +5935,7 @@ int find_or_create_ust_app_channel(
        lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &iter);
        ua_chan_node = lttng_ht_iter_get_node_str(&iter);
        if (ua_chan_node) {
-               *ua_chan = caa_container_of(ua_chan_node,
-                       struct ust_app_channel, node);
+               *ua_chan = caa_container_of(ua_chan_node, struct ust_app_channel, node);
                goto end;
        }
 
@@ -5788,16 +5947,19 @@ end:
        return ret;
 }
 
-static
-int ust_app_channel_synchronize_event(struct ust_app_channel *ua_chan,
-               struct ltt_ust_event *uevent,
-               struct ust_app *app)
+static int ust_app_channel_synchronize_event(struct ust_app_channel *ua_chan,
+                                            struct ltt_ust_event *uevent,
+                                            struct ust_app *app)
 {
        int ret = 0;
-       struct ust_app_event *ua_event = NULL;
-
-       ua_event = find_ust_app_event(ua_chan->events, uevent->attr.name,
-               uevent->filter, uevent->attr.loglevel, uevent->exclusion);
+       struct ust_app_event *ua_event = nullptr;
+
+       ua_event = find_ust_app_event(ua_chan->events,
+                                     uevent->attr.name,
+                                     uevent->filter,
+                                     (enum lttng_ust_abi_loglevel_type) uevent->attr.loglevel_type,
+                                     uevent->attr.loglevel,
+                                     uevent->exclusion);
        if (!ua_event) {
                ret = create_ust_app_event(ua_chan, uevent, app);
                if (ret < 0) {
@@ -5805,9 +5967,8 @@ int ust_app_channel_synchronize_event(struct ust_app_channel *ua_chan,
                }
        } else {
                if (ua_event->enabled != uevent->enabled) {
-                       ret = uevent->enabled ?
-                               enable_ust_app_event(ua_event, app) :
-                               disable_ust_app_event(ua_event, app);
+                       ret = uevent->enabled ? enable_ust_app_event(ua_event, app) :
+                                               disable_ust_app_event(ua_event, app);
                }
        }
 
@@ -5816,14 +5977,13 @@ end:
 }
 
 /* Called with RCU read-side lock held. */
-static
-void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
+static void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
 {
        int ret = 0;
        enum lttng_error_code ret_code;
        enum lttng_trigger_status t_status;
        struct lttng_ht_iter app_trigger_iter;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        struct ust_app_event_notifier_rule *event_notifier_rule;
        unsigned int count, i;
 
@@ -5852,7 +6012,7 @@ void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
 
        /* Get all triggers using uid 0 (root) */
        ret_code = notification_thread_command_list_triggers(
-                       the_notification_thread_handle, 0, &triggers);
+               the_notification_thread_handle, 0, &triggers);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
@@ -5879,14 +6039,13 @@ void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
                condition = lttng_trigger_get_condition(trigger);
 
                if (lttng_condition_get_type(condition) !=
-                               LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES) {
+                   LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES) {
                        /* Does not apply */
                        continue;
                }
 
-               condition_status =
-                               lttng_condition_event_rule_matches_borrow_rule_mutable(
-                                               condition, &event_rule);
+               condition_status = lttng_condition_event_rule_matches_borrow_rule_mutable(
+                       condition, &event_rule);
                LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
                if (lttng_event_rule_get_domain_type(event_rule) == LTTNG_DOMAIN_KERNEL) {
@@ -5900,7 +6059,7 @@ void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
                 * explicitly acquiring it here.
                 */
                looked_up_event_notifier_rule = find_ust_app_event_notifier_rule(
-                               app->token_to_event_notifier_rule_ht, token);
+                       app->token_to_event_notifier_rule_ht, token);
                if (!looked_up_event_notifier_rule) {
                        ret = create_ust_app_event_notifier_rule(trigger, app);
                        if (ret < 0) {
@@ -5909,57 +6068,55 @@ void ust_app_synchronize_event_notifier_rules(struct ust_app *app)
                }
        }
 
-       rcu_read_lock();
-       /* Remove all unknown event sources from the app. */
-       cds_lfht_for_each_entry (app->token_to_event_notifier_rule_ht->ht,
-                       &app_trigger_iter.iter, event_notifier_rule,
-                       node.node) {
-               const uint64_t app_token = event_notifier_rule->token;
-               bool found = false;
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               /*
-                * Check if the app event trigger still exists on the
-                * notification side.
-                */
-               for (i = 0; i < count; i++) {
-                       uint64_t notification_thread_token;
-                       const struct lttng_trigger *trigger =
-                                       lttng_triggers_get_at_index(
-                                                       triggers, i);
+               /* Remove all unknown event sources from the app. */
+               cds_lfht_for_each_entry (app->token_to_event_notifier_rule_ht->ht,
+                                        &app_trigger_iter.iter,
+                                        event_notifier_rule,
+                                        node.node) {
+                       const uint64_t app_token = event_notifier_rule->token;
+                       bool found = false;
 
-                       LTTNG_ASSERT(trigger);
+                       /*
+                        * Check if the app event trigger still exists on the
+                        * notification side.
+                        */
+                       for (i = 0; i < count; i++) {
+                               uint64_t notification_thread_token;
+                               const struct lttng_trigger *trigger =
+                                       lttng_triggers_get_at_index(triggers, i);
 
-                       notification_thread_token =
-                                       lttng_trigger_get_tracer_token(trigger);
+                               LTTNG_ASSERT(trigger);
 
-                       if (notification_thread_token == app_token) {
-                               found = true;
-                               break;
+                               notification_thread_token = lttng_trigger_get_tracer_token(trigger);
+
+                               if (notification_thread_token == app_token) {
+                                       found = true;
+                                       break;
+                               }
                        }
-               }
 
-               if (found) {
-                       /* Still valid. */
-                       continue;
-               }
+                       if (found) {
+                               /* Still valid. */
+                               continue;
+                       }
 
-               /*
-                * This trigger was unregistered, disable it on the tracer's
-                * side.
-                */
-               ret = lttng_ht_del(app->token_to_event_notifier_rule_ht,
-                               &app_trigger_iter);
-               LTTNG_ASSERT(ret == 0);
+                       /*
+                        * This trigger was unregistered, disable it on the tracer's
+                        * side.
+                        */
+                       ret = lttng_ht_del(app->token_to_event_notifier_rule_ht, &app_trigger_iter);
+                       LTTNG_ASSERT(ret == 0);
 
-               /* Callee logs errors. */
-               (void) disable_ust_object(app, event_notifier_rule->obj);
+                       /* Callee logs errors. */
+                       (void) disable_ust_object(app, event_notifier_rule->obj);
 
-               delete_ust_app_event_notifier_rule(
-                               app->sock, event_notifier_rule, app);
+                       delete_ust_app_event_notifier_rule(app->sock, event_notifier_rule, app);
+               }
        }
 
-       rcu_read_unlock();
-
 end:
        lttng_triggers_destroy(triggers);
        return;
@@ -5968,10 +6125,9 @@ end:
 /*
  * RCU read lock must be held by the caller.
  */
-static
-void ust_app_synchronize_all_channels(struct ltt_ust_session *usess,
-               struct ust_app_session *ua_sess,
-               struct ust_app *app)
+static void ust_app_synchronize_all_channels(struct ltt_ust_session *usess,
+                                            struct ust_app_session *ua_sess,
+                                            struct ust_app *app)
 {
        int ret = 0;
        struct cds_lfht_iter uchan_iter;
@@ -5982,8 +6138,7 @@ void ust_app_synchronize_all_channels(struct ltt_ust_session *usess,
        LTTNG_ASSERT(app);
        ASSERT_RCU_READ_LOCKED();
 
-       cds_lfht_for_each_entry(usess->domain_global.channels->ht, &uchan_iter,
-                       uchan, node.node) {
+       cds_lfht_for_each_entry (usess->domain_global.channels->ht, &uchan_iter, uchan, node.node) {
                struct ust_app_channel *ua_chan;
                struct cds_lfht_iter uevent_iter;
                struct ltt_ust_event *uevent;
@@ -5995,8 +6150,7 @@ void ust_app_synchronize_all_channels(struct ltt_ust_session *usess,
                 * allocated (if necessary) and sent to the application, and
                 * all enabled contexts will be added to the channel.
                 */
-               ret = find_or_create_ust_app_channel(usess, ua_sess,
-                       app, uchan, &ua_chan);
+               ret = find_or_create_ust_app_channel(usess, ua_sess, app, uchan, &ua_chan);
                if (ret) {
                        /* Tracer is probably gone or ENOMEM. */
                        goto end;
@@ -6007,19 +6161,16 @@ void ust_app_synchronize_all_channels(struct ltt_ust_session *usess,
                        continue;
                }
 
-               cds_lfht_for_each_entry(uchan->events->ht, &uevent_iter, uevent,
-                               node.node) {
-                       ret = ust_app_channel_synchronize_event(ua_chan,
-                               uevent, app);
+               cds_lfht_for_each_entry (uchan->events->ht, &uevent_iter, uevent, node.node) {
+                       ret = ust_app_channel_synchronize_event(ua_chan, uevent, app);
                        if (ret) {
                                goto end;
                        }
                }
 
                if (ua_chan->enabled != uchan->enabled) {
-                       ret = uchan->enabled ?
-                               enable_ust_app_channel(ua_sess, uchan, app) :
-                               disable_ust_app_channel(ua_sess, ua_chan, app);
+                       ret = uchan->enabled ? enable_ust_app_channel(ua_sess, uchan, app) :
+                                              disable_ust_app_channel(ua_sess, ua_chan, app);
                        if (ret) {
                                goto end;
                        }
@@ -6033,12 +6184,10 @@ end:
  * The caller must ensure that the application is compatible and is tracked
  * by the process attribute trackers.
  */
-static
-void ust_app_synchronize(struct ltt_ust_session *usess,
-               struct ust_app *app)
+static void ust_app_synchronize(struct ltt_ust_session *usess, struct ust_app *app)
 {
        int ret = 0;
-       struct ust_app_session *ua_sess = NULL;
+       struct ust_app_session *ua_sess = nullptr;
 
        /*
         * The application's configuration should only be synchronized for
@@ -6046,14 +6195,12 @@ void ust_app_synchronize(struct ltt_ust_session *usess,
         */
        LTTNG_ASSERT(usess->active);
 
-       ret = find_or_create_ust_app_session(usess, app, &ua_sess, NULL);
+       ret = find_or_create_ust_app_session(usess, app, &ua_sess, nullptr);
        if (ret < 0) {
                /* Tracer is probably gone or ENOMEM. */
-               if (ua_sess) {
-                       destroy_app_session(app, ua_sess);
-               }
                goto end;
        }
+
        LTTNG_ASSERT(ua_sess);
 
        pthread_mutex_lock(&ua_sess->lock);
@@ -6061,40 +6208,40 @@ void ust_app_synchronize(struct ltt_ust_session *usess,
                goto deleted_session;
        }
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       ust_app_synchronize_all_channels(usess, ua_sess, app);
+               ust_app_synchronize_all_channels(usess, ua_sess, app);
 
-       /*
-        * Create the metadata for the application. This returns gracefully if a
-        * metadata was already set for the session.
-        *
-        * The metadata channel must be created after the data channels as the
-        * consumer daemon assumes this ordering. When interacting with a relay
-        * daemon, the consumer will use this assumption to send the
-        * "STREAMS_SENT" message to the relay daemon.
-        */
-       ret = create_ust_app_metadata(ua_sess, app, usess->consumer);
-       if (ret < 0) {
-               ERR("Metadata creation failed for app sock %d for session id %" PRIu64,
-                               app->sock, usess->id);
+               /*
+                * Create the metadata for the application. This returns gracefully if a
+                * metadata was already set for the session.
+                *
+                * The metadata channel must be created after the data channels as the
+                * consumer daemon assumes this ordering. When interacting with a relay
+                * daemon, the consumer will use this assumption to send the
+                * "STREAMS_SENT" message to the relay daemon.
+                */
+               ret = create_ust_app_metadata(ua_sess, app, usess->consumer);
+               if (ret < 0) {
+                       ERR("Metadata creation failed for app sock %d for session id %" PRIu64,
+                           app->sock,
+                           usess->id);
+               }
        }
 
-       rcu_read_unlock();
-
 deleted_session:
        pthread_mutex_unlock(&ua_sess->lock);
 end:
        return;
 }
 
-static
-void ust_app_global_destroy(struct ltt_ust_session *usess, struct ust_app *app)
+static void ust_app_global_destroy(struct ltt_ust_session *usess, struct ust_app *app)
 {
        struct ust_app_session *ua_sess;
 
        ua_sess = lookup_session_by_app(usess, app);
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                return;
        }
        destroy_app_session(app, ua_sess);
@@ -6112,20 +6259,14 @@ void ust_app_global_update(struct ltt_ust_session *usess, struct ust_app *app)
        LTTNG_ASSERT(usess->active);
        ASSERT_RCU_READ_LOCKED();
 
-       DBG2("UST app global update for app sock %d for session id %" PRIu64,
-                       app->sock, usess->id);
+       DBG2("UST app global update for app sock %d for session id %" PRIu64, app->sock, usess->id);
 
        if (!app->compatible) {
                return;
        }
-       if (trace_ust_id_tracker_lookup(LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID,
-                           usess, app->pid) &&
-                       trace_ust_id_tracker_lookup(
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID,
-                                       usess, app->uid) &&
-                       trace_ust_id_tracker_lookup(
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID,
-                                       usess, app->gid)) {
+       if (trace_ust_id_tracker_lookup(LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID, usess, app->pid) &&
+           trace_ust_id_tracker_lookup(LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID, usess, app->uid) &&
+           trace_ust_id_tracker_lookup(LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID, usess, app->gid)) {
                /*
                 * Synchronize the application's internal tracing configuration
                 * and start tracing.
@@ -6148,15 +6289,17 @@ void ust_app_global_update_event_notifier_rules(struct ust_app *app)
        ASSERT_RCU_READ_LOCKED();
 
        DBG2("UST application global event notifier rules update: app = '%s', pid = %d",
-                       app->name, app->pid);
+            app->name,
+            app->pid);
 
        if (!app->compatible || !ust_app_supports_notifiers(app)) {
                return;
        }
 
-       if (app->event_notifier_group.object == NULL) {
+       if (app->event_notifier_group.object == nullptr) {
                WARN("UST app global update of event notifiers for app skipped since communication handle is null: app = '%s', pid = %d",
-                               app->name, app->pid);
+                    app->name,
+                    app->pid);
                return;
        }
 
@@ -6171,79 +6314,80 @@ void ust_app_global_update_all(struct ltt_ust_session *usess)
        struct lttng_ht_iter iter;
        struct ust_app *app;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               ust_app_global_update(usess, app);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       ust_app_global_update(usess, app);
+               }
        }
-       rcu_read_unlock();
 }
 
-void ust_app_global_update_all_event_notifier_rules(void)
+void ust_app_global_update_all_event_notifier_rules()
 {
        struct lttng_ht_iter iter;
        struct ust_app *app;
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                ust_app_global_update_event_notifier_rules(app);
        }
-
-       rcu_read_unlock();
 }
 
 /*
  * Add context to a specific channel for global UST domain.
  */
 int ust_app_add_ctx_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_context *uctx)
+                               struct ltt_ust_channel *uchan,
+                               struct ltt_ust_context *uctx)
 {
        int ret = 0;
        struct lttng_ht_node_str *ua_chan_node;
        struct lttng_ht_iter iter, uiter;
-       struct ust_app_channel *ua_chan = NULL;
+       struct ust_app_channel *ua_chan = nullptr;
        struct ust_app_session *ua_sess;
        struct ust_app *app;
 
        LTTNG_ASSERT(usess->active);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
-               if (!app->compatible) {
-                       /*
-                        * TODO: In time, we should notice the caller of this error by
-                        * telling him that this is a version error.
-                        */
-                       continue;
-               }
-               ua_sess = lookup_session_by_app(usess, app);
-               if (ua_sess == NULL) {
-                       continue;
-               }
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+                       if (!app->compatible) {
+                               /*
+                                * TODO: In time, we should notice the caller of this error by
+                                * telling him that this is a version error.
+                                */
+                               continue;
+                       }
+                       ua_sess = lookup_session_by_app(usess, app);
+                       if (ua_sess == nullptr) {
+                               continue;
+                       }
 
-               pthread_mutex_lock(&ua_sess->lock);
+                       pthread_mutex_lock(&ua_sess->lock);
 
-               if (ua_sess->deleted) {
-                       pthread_mutex_unlock(&ua_sess->lock);
-                       continue;
-               }
+                       if (ua_sess->deleted) {
+                               pthread_mutex_unlock(&ua_sess->lock);
+                               continue;
+                       }
 
-               /* Lookup channel in the ust app session */
-               lttng_ht_lookup(ua_sess->channels, (void *)uchan->name, &uiter);
-               ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
-               if (ua_chan_node == NULL) {
-                       goto next_app;
-               }
-               ua_chan = caa_container_of(ua_chan_node, struct ust_app_channel,
-                               node);
-               ret = create_ust_app_channel_context(ua_chan, &uctx->ctx, app);
-               if (ret < 0) {
-                       goto next_app;
+                       /* Lookup channel in the ust app session */
+                       lttng_ht_lookup(ua_sess->channels, (void *) uchan->name, &uiter);
+                       ua_chan_node = lttng_ht_iter_get_node_str(&uiter);
+                       if (ua_chan_node == nullptr) {
+                               goto next_app;
+                       }
+                       ua_chan = caa_container_of(ua_chan_node, struct ust_app_channel, node);
+                       ret = create_ust_app_channel_context(ua_chan, &uctx->ctx, app);
+                       if (ret < 0) {
+                               goto next_app;
+                       }
+               next_app:
+                       pthread_mutex_unlock(&ua_sess->lock);
                }
-       next_app:
-               pthread_mutex_unlock(&ua_sess->lock);
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
@@ -6259,16 +6403,22 @@ int ust_app_recv_registration(int sock, struct ust_register_msg *msg)
 
        LTTNG_ASSERT(msg);
 
-       ret = lttng_ust_ctl_recv_reg_msg(sock, &msg->type, &msg->major, &msg->minor,
-                       &pid, &ppid, &uid, &gid,
-                       &msg->bits_per_long,
-                       &msg->uint8_t_alignment,
-                       &msg->uint16_t_alignment,
-                       &msg->uint32_t_alignment,
-                       &msg->uint64_t_alignment,
-                       &msg->long_alignment,
-                       &msg->byte_order,
-                       msg->name);
+       ret = lttng_ust_ctl_recv_reg_msg(sock,
+                                        &msg->type,
+                                        &msg->major,
+                                        &msg->minor,
+                                        &pid,
+                                        &ppid,
+                                        &uid,
+                                        &gid,
+                                        &msg->bits_per_long,
+                                        &msg->uint8_t_alignment,
+                                        &msg->uint16_t_alignment,
+                                        &msg->uint32_t_alignment,
+                                        &msg->uint64_t_alignment,
+                                        &msg->long_alignment,
+                                        &msg->byte_order,
+                                        msg->name);
        if (ret < 0) {
                switch (-ret) {
                case EPIPE:
@@ -6278,8 +6428,10 @@ int ust_app_recv_registration(int sock, struct ust_register_msg *msg)
                        break;
                case LTTNG_UST_ERR_UNSUP_MAJOR:
                        ERR("UST app recv reg unsupported version %d.%d. Supporting %d.%d",
-                                       msg->major, msg->minor, LTTNG_UST_ABI_MAJOR_VERSION,
-                                       LTTNG_UST_ABI_MINOR_VERSION);
+                           msg->major,
+                           msg->minor,
+                           LTTNG_UST_ABI_MAJOR_VERSION,
+                           LTTNG_UST_ABI_MINOR_VERSION);
                        break;
                default:
                        ERR("UST app recv reg message failed with ret %d", ret);
@@ -6300,20 +6452,19 @@ error:
  * Return a ust app session object using the application object and the
  * session object descriptor has a key. If not found, NULL is returned.
  * A RCU read side lock MUST be acquired when calling this function.
-*/
-static struct ust_app_session *find_session_by_objd(struct ust_app *app,
-               int objd)
+ */
+static struct ust_app_session *find_session_by_objd(struct ust_app *app, int objd)
 {
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
-       struct ust_app_session *ua_sess = NULL;
+       struct ust_app_session *ua_sess = nullptr;
 
        LTTNG_ASSERT(app);
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(app->ust_sessions_objd, (void *)((unsigned long) objd), &iter);
+       lttng_ht_lookup(app->ust_sessions_objd, (void *) ((unsigned long) objd), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("UST app session find by objd %d not found", objd);
                goto error;
        }
@@ -6329,19 +6480,18 @@ error:
  * object descriptor has a key. If not found, NULL is returned. A RCU read side
  * lock MUST be acquired before calling this function.
  */
-static struct ust_app_channel *find_channel_by_objd(struct ust_app *app,
-               int objd)
+static struct ust_app_channel *find_channel_by_objd(struct ust_app *app, int objd)
 {
        struct lttng_ht_node_ulong *node;
        struct lttng_ht_iter iter;
-       struct ust_app_channel *ua_chan = NULL;
+       struct ust_app_channel *ua_chan = nullptr;
 
        LTTNG_ASSERT(app);
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(app->ust_objd, (void *)((unsigned long) objd), &iter);
+       lttng_ht_lookup(app->ust_objd, (void *) ((unsigned long) objd), &iter);
        node = lttng_ht_iter_get_node_ulong(&iter);
-       if (node == NULL) {
+       if (node == nullptr) {
                DBG2("UST app channel find by objd %d not found", objd);
                goto error;
        }
@@ -6361,9 +6511,9 @@ error:
  * On success 0 is returned else a negative value.
  */
 static int handle_app_register_channel_notification(int sock,
-               int cobjd,
-               struct lttng_ust_ctl_field *raw_context_fields,
-               size_t context_field_count)
+                                                   int cobjd,
+                                                   struct lttng_ust_ctl_field *raw_context_fields,
+                                                   size_t context_field_count)
 {
        int ret, ret_code = 0;
        uint32_t chan_id;
@@ -6371,7 +6521,8 @@ static int handle_app_register_channel_notification(int sock,
        struct ust_app *app;
        struct ust_app_channel *ua_chan;
        struct ust_app_session *ua_sess;
-       auto ust_ctl_context_fields = lttng::make_unique_wrapper<lttng_ust_ctl_field, lttng::free>(
+       auto ust_ctl_context_fields =
+               lttng::make_unique_wrapper<lttng_ust_ctl_field, lttng::memory::free>(
                        raw_context_fields);
 
        lttng::urcu::read_lock_guard read_lock_guard;
@@ -6379,8 +6530,7 @@ static int handle_app_register_channel_notification(int sock,
        /* Lookup application. If not found, there is a code flow error. */
        app = find_app_by_notify_sock(sock);
        if (!app) {
-               DBG("Application socket %d is being torn down. Abort event notify",
-                               sock);
+               DBG("Application socket %d is being torn down. Abort event notify", sock);
                return -1;
        }
 
@@ -6408,7 +6558,7 @@ static int handle_app_register_channel_notification(int sock,
                chan_reg_key = ua_chan->key;
        }
 
-       auto& ust_reg_chan = locked_registry_session->get_channel(chan_reg_key);
+       auto& ust_reg_chan = locked_registry_session->channel(chan_reg_key);
 
        /* Channel id is set during the object creation. */
        chan_id = ust_reg_chan.id;
@@ -6426,45 +6576,80 @@ static int handle_app_register_channel_notification(int sock,
         * that all apps provide the same typing for the context fields as a
         * sanity check.
         */
-       lst::type::cuptr context_fields = lttng::make_unique<lst::structure_type>(0,
-                       lsu::create_trace_fields_from_ust_ctl_fields(*locked_registry_session,
-                                       ust_ctl_context_fields.get(), context_field_count));
+       try {
+               auto app_context_fields = lsu::create_trace_fields_from_ust_ctl_fields(
+                       *locked_registry_session,
+                       ust_ctl_context_fields.get(),
+                       context_field_count,
+                       lst::field_location::root::EVENT_RECORD_COMMON_CONTEXT,
+                       lsu::ctl_field_quirks::UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS);
+
+               if (!ust_reg_chan.is_registered()) {
+                       lst::type::cuptr event_context = app_context_fields.size() ?
+                               lttng::make_unique<lst::structure_type>(
+                                       0, std::move(app_context_fields)) :
+                               nullptr;
+
+                       ust_reg_chan.event_context(std::move(event_context));
+               } else {
+                       /*
+                        * Validate that the context fields match between
+                        * registry and newcoming application.
+                        */
+                       bool context_fields_match;
+                       const auto *previous_event_context = ust_reg_chan.event_context();
 
-       if (!ust_reg_chan.is_registered()) {
-               ust_reg_chan.set_context(std::move(context_fields));
-       } else {
-               /*
-                * Validate that the context fields match between
-                * registry and newcoming application.
-                */
-               if (ust_reg_chan.get_context() != *context_fields) {
-                       ERR("Registering application channel due to context field mismatch: pid = %d, sock = %d",
-                               app->pid, app->sock);
-                       ret_code = -EINVAL;
-                       goto reply;
+                       if (!previous_event_context) {
+                               context_fields_match = app_context_fields.size() == 0;
+                       } else {
+                               const lst::structure_type app_event_context_struct(
+                                       0, std::move(app_context_fields));
+
+                               context_fields_match = *previous_event_context ==
+                                       app_event_context_struct;
+                       }
+
+                       if (!context_fields_match) {
+                               ERR("Registering application channel due to context field mismatch: pid = %d, sock = %d",
+                                   app->pid,
+                                   app->sock);
+                               ret_code = -EINVAL;
+                               goto reply;
+                       }
                }
+       } catch (const std::exception& ex) {
+               ERR("Failed to handle application context: %s", ex.what());
+               ret_code = -EINVAL;
+               goto reply;
        }
 
 reply:
-       DBG3("UST app replying to register channel key %" PRIu64
-                       " with id %u, ret = %d", chan_reg_key, chan_id,
-                       ret_code);
-
-       ret = lttng_ust_ctl_reply_register_channel(sock, chan_id,
-                       ust_reg_chan.header_type_ == lst::stream_class::header_type::COMPACT ?
-                                       LTTNG_UST_CTL_CHANNEL_HEADER_COMPACT :
-                                             LTTNG_UST_CTL_CHANNEL_HEADER_LARGE,
-                       ret_code);
+       DBG3("UST app replying to register channel key %" PRIu64 " with id %u, ret = %d",
+            chan_reg_key,
+            chan_id,
+            ret_code);
+
+       ret = lttng_ust_ctl_reply_register_channel(
+               sock,
+               chan_id,
+               ust_reg_chan.header_type_ == lst::stream_class::header_type::COMPACT ?
+                       LTTNG_UST_CTL_CHANNEL_HEADER_COMPACT :
+                       LTTNG_UST_CTL_CHANNEL_HEADER_LARGE,
+               ret_code);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app reply channel failed. Application died: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app reply channel failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app reply channel failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
 
                return ret;
@@ -6485,9 +6670,15 @@ reply:
  *
  * On success 0 is returned else a negative value.
  */
-static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *name,
-               char *raw_signature, size_t nr_fields, struct lttng_ust_ctl_field *raw_fields,
-               int loglevel_value, char *raw_model_emf_uri)
+static int add_event_ust_registry(int sock,
+                                 int sobjd,
+                                 int cobjd,
+                                 const char *name,
+                                 char *raw_signature,
+                                 size_t nr_fields,
+                                 struct lttng_ust_ctl_field *raw_fields,
+                                 int loglevel_value,
+                                 char *raw_model_emf_uri)
 {
        int ret, ret_code;
        uint32_t event_id = 0;
@@ -6496,15 +6687,16 @@ static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *na
        struct ust_app_channel *ua_chan;
        struct ust_app_session *ua_sess;
        lttng::urcu::read_lock_guard rcu_lock;
-       auto signature = lttng::make_unique_wrapper<char, lttng::free>(raw_signature);
-       auto fields = lttng::make_unique_wrapper<lttng_ust_ctl_field, lttng::free>(raw_fields);
-       auto model_emf_uri = lttng::make_unique_wrapper<char, lttng::free>(raw_model_emf_uri);
+       auto signature = lttng::make_unique_wrapper<char, lttng::memory::free>(raw_signature);
+       auto fields =
+               lttng::make_unique_wrapper<lttng_ust_ctl_field, lttng::memory::free>(raw_fields);
+       auto model_emf_uri =
+               lttng::make_unique_wrapper<char, lttng::memory::free>(raw_model_emf_uri);
 
        /* Lookup application. If not found, there is a code flow error. */
        app = find_app_by_notify_sock(sock);
        if (!app) {
-               DBG("Application socket %d is being torn down. Abort event notify",
-                               sock);
+               DBG("Application socket %d is being torn down. Abort event notify", sock);
                return -1;
        }
 
@@ -6533,23 +6725,33 @@ static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *na
                         * These three variables MUST NOT be read/write after this.
                         */
                        try {
-                               auto& channel = locked_registry->get_channel(chan_reg_key);
+                               auto& channel = locked_registry->channel(chan_reg_key);
 
                                /* event_id is set on success. */
-                               channel.add_event(sobjd, cobjd, name, signature.get(),
-                                               lsu::create_trace_fields_from_ust_ctl_fields(
-                                                               *locked_registry, fields.get(),
-                                                               nr_fields),
-                                               loglevel_value,
-                                               model_emf_uri.get() ?
-                                                               nonstd::optional<std::string>(
-                                                                               model_emf_uri.get()) :
-                                                                     nonstd::nullopt,
-                                               ua_sess->buffer_type, *app, event_id);
+                               channel.add_event(
+                                       sobjd,
+                                       cobjd,
+                                       name,
+                                       signature.get(),
+                                       lsu::create_trace_fields_from_ust_ctl_fields(
+                                               *locked_registry,
+                                               fields.get(),
+                                               nr_fields,
+                                               lst::field_location::root::EVENT_RECORD_PAYLOAD,
+                                               lsu::ctl_field_quirks::
+                                                       UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS),
+                                       loglevel_value,
+                                       model_emf_uri.get() ?
+                                               nonstd::optional<std::string>(model_emf_uri.get()) :
+                                               nonstd::nullopt,
+                                       ua_sess->buffer_type,
+                                       *app,
+                                       event_id);
                                ret_code = 0;
                        } catch (const std::exception& ex) {
-                               ERR("Failed to add event `%s` to registry session: %s", name,
-                                               ex.what());
+                               ERR("Failed to add event `%s` to registry session: %s",
+                                   name,
+                                   ex.what());
                                /* Inform the application of the error; don't return directly. */
                                ret_code = -EINVAL;
                        }
@@ -6568,13 +6770,17 @@ static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *na
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app reply event failed. Application died: pid = %d, sock = %d.",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app reply event failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app reply event failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                /*
                 * No need to wipe the create event since the application socket will
@@ -6583,8 +6789,7 @@ static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *na
                return ret;
        }
 
-       DBG3("UST registry event %s with id %" PRId32 " added successfully",
-                       name, event_id);
+       DBG3("UST registry event %s with id %" PRId32 " added successfully", name, event_id);
        return ret;
 }
 
@@ -6596,23 +6801,26 @@ static int add_event_ust_registry(int sock, int sobjd, int cobjd, const char *na
  *
  * On success 0 is returned else a negative value.
  */
-static int add_enum_ust_registry(int sock, int sobjd, const char *name,
-               struct lttng_ust_ctl_enum_entry *raw_entries, size_t nr_entries)
+static int add_enum_ust_registry(int sock,
+                                int sobjd,
+                                const char *name,
+                                struct lttng_ust_ctl_enum_entry *raw_entries,
+                                size_t nr_entries)
 {
        int ret = 0;
        struct ust_app *app;
        struct ust_app_session *ua_sess;
        uint64_t enum_id = -1ULL;
        lttng::urcu::read_lock_guard read_lock_guard;
-       auto entries = lttng::make_unique_wrapper<struct lttng_ust_ctl_enum_entry, lttng::free>(
+       auto entries =
+               lttng::make_unique_wrapper<struct lttng_ust_ctl_enum_entry, lttng::memory::free>(
                        raw_entries);
 
        /* Lookup application. If not found, there is a code flow error. */
        app = find_app_by_notify_sock(sock);
        if (!app) {
                /* Return an error since this is not an error */
-               DBG("Application socket %d is being torn down. Aborting enum registration",
-                               sock);
+               DBG("Application socket %d is being torn down. Aborting enum registration", sock);
                return -1;
        }
 
@@ -6638,11 +6846,16 @@ static int add_enum_ust_registry(int sock, int sobjd, const char *name,
        int application_reply_code;
        try {
                locked_registry->create_or_find_enum(
-                               sobjd, name, entries.release(), nr_entries, &enum_id);
+                       sobjd, name, entries.release(), nr_entries, &enum_id);
                application_reply_code = 0;
        } catch (const std::exception& ex) {
-               ERR("%s: %s", fmt::format("Failed to create or find enumeration provided by application: app = {}, enumeration name = {}",
-                               *app, name).c_str(), ex.what());
+               ERR("%s: %s",
+                   lttng::format(
+                           "Failed to create or find enumeration provided by application: app = {}, enumeration name = {}",
+                           *app,
+                           name)
+                           .c_str(),
+                   ex.what());
                application_reply_code = -1;
        }
 
@@ -6655,13 +6868,17 @@ static int add_enum_ust_registry(int sock, int sobjd, const char *name,
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app reply enum failed. Application died: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app reply enum failed. Communication time out: pid = %d, sock = %d",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app reply enum failed with ret %d: pid = %d, sock = %d",
-                                       ret, app->pid, app->sock);
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                /*
                 * No need to wipe the create enum since the application socket will
@@ -6689,14 +6906,11 @@ int ust_app_recv_notify(int sock)
        ret = lttng_ust_ctl_recv_notify(sock, &cmd);
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
-                       DBG3("UST app recv notify failed. Application died: sock = %d",
-                                       sock);
+                       DBG3("UST app recv notify failed. Application died: sock = %d", sock);
                } else if (ret == -EAGAIN) {
-                       WARN("UST app recv notify failed. Communication time out: sock = %d",
-                                       sock);
+                       WARN("UST app recv notify failed. Communication time out: sock = %d", sock);
                } else {
-                       ERR("UST app recv notify failed with ret %d: sock = %d",
-                                       ret, sock);
+                       ERR("UST app recv notify failed with ret %d: sock = %d", ret, sock);
                }
                goto error;
        }
@@ -6711,18 +6925,24 @@ int ust_app_recv_notify(int sock)
 
                DBG2("UST app ustctl register event received");
 
-               ret = lttng_ust_ctl_recv_register_event(sock, &sobjd, &cobjd, name, &loglevel_value,
-                               &sig, &nr_fields, &fields, &model_emf_uri);
+               ret = lttng_ust_ctl_recv_register_event(sock,
+                                                       &sobjd,
+                                                       &cobjd,
+                                                       name,
+                                                       &loglevel_value,
+                                                       &sig,
+                                                       &nr_fields,
+                                                       &fields,
+                                                       &model_emf_uri);
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app recv event failed. Application died: sock = %d",
-                                               sock);
+                                    sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app recv event failed. Communication time out: sock = %d",
-                                               sock);
+                                    sock);
                        } else {
-                               ERR("UST app recv event failed with ret %d: sock = %d",
-                                               ret, sock);
+                               ERR("UST app recv event failed with ret %d: sock = %d", ret, sock);
                        }
                        goto error;
                }
@@ -6731,7 +6951,8 @@ int ust_app_recv_notify(int sock)
                        lttng::urcu::read_lock_guard rcu_lock;
                        const struct ust_app *app = find_app_by_notify_sock(sock);
                        if (!app) {
-                               DBG("Application socket %d is being torn down. Abort event notify", sock);
+                               DBG("Application socket %d is being torn down. Abort event notify",
+                                   sock);
                                ret = -1;
                                goto error;
                        }
@@ -6739,7 +6960,8 @@ int ust_app_recv_notify(int sock)
 
                if ((!fields && nr_fields > 0) || (fields && nr_fields == 0)) {
                        ERR("Invalid return value from lttng_ust_ctl_recv_register_event: fields = %p, nr_fields = %zu",
-                                       fields, nr_fields);
+                           fields,
+                           nr_fields);
                        ret = -1;
                        free(fields);
                        goto error;
@@ -6751,8 +6973,15 @@ int ust_app_recv_notify(int sock)
                 * code path loses the ownsership of these variables and transfer them
                 * to the this function.
                 */
-               ret = add_event_ust_registry(sock, sobjd, cobjd, name, sig, nr_fields,
-                               fields, loglevel_value, model_emf_uri);
+               ret = add_event_ust_registry(sock,
+                                            sobjd,
+                                            cobjd,
+                                            name,
+                                            sig,
+                                            nr_fields,
+                                            fields,
+                                            loglevel_value,
+                                            model_emf_uri);
                if (ret < 0) {
                        goto error;
                }
@@ -6768,17 +6997,18 @@ int ust_app_recv_notify(int sock)
                DBG2("UST app ustctl register channel received");
 
                ret = lttng_ust_ctl_recv_register_channel(
-                               sock, &sobjd, &cobjd, &field_count, &context_fields);
+                       sock, &sobjd, &cobjd, &field_count, &context_fields);
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                                DBG3("UST app recv channel failed. Application died: sock = %d",
-                                               sock);
+                                    sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app recv channel failed. Communication time out: sock = %d",
-                                               sock);
+                                    sock);
                        } else {
-                               ERR("UST app recv channel failed with ret %d: sock = %d", ret,
-                                               sock);
+                               ERR("UST app recv channel failed with ret %d: sock = %d",
+                                   ret,
+                                   sock);
                        }
                        goto error;
                }
@@ -6788,7 +7018,8 @@ int ust_app_recv_notify(int sock)
                 * that if needed it will be freed. After this, it's invalid to access
                 * fields or clean them up.
                 */
-               ret = handle_app_register_channel_notification(sock, cobjd, context_fields, field_count);
+               ret = handle_app_register_channel_notification(
+                       sock, cobjd, context_fields, field_count);
                if (ret < 0) {
                        goto error;
                }
@@ -6804,25 +7035,21 @@ int ust_app_recv_notify(int sock)
 
                DBG2("UST app ustctl register enum received");
 
-               ret = lttng_ust_ctl_recv_register_enum(sock, &sobjd, name,
-                               &entries, &nr_entries);
+               ret = lttng_ust_ctl_recv_register_enum(sock, &sobjd, name, &entries, &nr_entries);
                if (ret < 0) {
                        if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
-                               DBG3("UST app recv enum failed. Application died: sock = %d",
-                                               sock);
+                               DBG3("UST app recv enum failed. Application died: sock = %d", sock);
                        } else if (ret == -EAGAIN) {
                                WARN("UST app recv enum failed. Communication time out: sock = %d",
-                                               sock);
+                                    sock);
                        } else {
-                               ERR("UST app recv enum failed with ret %d: sock = %d",
-                                               ret, sock);
+                               ERR("UST app recv enum failed with ret %d: sock = %d", ret, sock);
                        }
                        goto error;
                }
 
                /* Callee assumes ownership of entries. */
-               ret = add_enum_ust_registry(sock, sobjd, name,
-                               entries, nr_entries);
+               ret = add_enum_ust_registry(sock, sobjd, name, entries, nr_entries);
                if (ret < 0) {
                        goto error;
                }
@@ -6856,7 +7083,7 @@ void ust_app_notify_sock_unregister(int sock)
 
        LTTNG_ASSERT(sock >= 0);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        obj = zmalloc<ust_app_notify_sock_obj>();
        if (!obj) {
@@ -6903,7 +7130,6 @@ void ust_app_notify_sock_unregister(int sock)
        (void) lttng_ht_del(ust_app_ht_by_notify_sock, &iter);
 
 close_socket:
-       rcu_read_unlock();
 
        /*
         * Close socket after a grace period to avoid for the socket to be reused
@@ -6918,13 +7144,9 @@ close_socket:
 /*
  * Destroy a ust app data structure and free its memory.
  */
-void ust_app_destroy(struct ust_app *app)
+static void ust_app_destroy(ust_app& app)
 {
-       if (!app) {
-               return;
-       }
-
-       call_rcu(&app->pid_n.head, delete_ust_app_rcu);
+       call_rcu(&app.pid_n.head, delete_ust_app_rcu);
 }
 
 /*
@@ -6933,28 +7155,27 @@ void ust_app_destroy(struct ust_app *app)
  *
  * Returns LTTNG_OK on success or a LTTNG_ERR error code.
  */
-enum lttng_error_code ust_app_snapshot_record(
-               const struct ltt_ust_session *usess,
-               const struct consumer_output *output,
-               uint64_t nb_packets_per_stream)
+enum lttng_error_code ust_app_snapshot_record(const struct ltt_ust_session *usess,
+                                             const struct consumer_output *output,
+                                             uint64_t nb_packets_per_stream)
 {
        int ret = 0;
        enum lttng_error_code status = LTTNG_OK;
        struct lttng_ht_iter iter;
        struct ust_app *app;
-       char *trace_path = NULL;
+       char *trace_path = nullptr;
 
        LTTNG_ASSERT(usess);
        LTTNG_ASSERT(output);
 
-       rcu_read_lock();
-
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
        {
                struct buffer_reg_uid *reg;
 
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct buffer_reg_channel *buf_reg_chan;
                        struct consumer_socket *socket;
                        char pathname[PATH_MAX];
@@ -6967,16 +7188,18 @@ enum lttng_error_code ust_app_snapshot_record(
 
                        /* Get consumer socket to use to push the metadata.*/
                        socket = consumer_find_socket_by_bitness(reg->bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                status = LTTNG_ERR_INVALID;
                                goto error;
                        }
 
                        memset(pathname, 0, sizeof(pathname));
-                       ret = snprintf(pathname, sizeof(pathname),
-                                       DEFAULT_UST_TRACE_UID_PATH,
-                                       reg->uid, reg->bits_per_long);
+                       ret = snprintf(pathname,
+                                      sizeof(pathname),
+                                      DEFAULT_UST_TRACE_UID_PATH,
+                                      reg->uid,
+                                      reg->bits_per_long);
                        if (ret < 0) {
                                PERROR("snprintf snapshot path");
                                status = LTTNG_ERR_INVALID;
@@ -6984,35 +7207,44 @@ enum lttng_error_code ust_app_snapshot_record(
                        }
                        /* Free path allowed on previous iteration. */
                        free(trace_path);
-                       trace_path = setup_channel_trace_path(usess->consumer, pathname,
-                                               &consumer_path_offset);
+                       trace_path = setup_channel_trace_path(
+                               usess->consumer, pathname, &consumer_path_offset);
                        if (!trace_path) {
                                status = LTTNG_ERR_INVALID;
                                goto error;
                        }
                        /* Add the UST default trace dir to path. */
-                       cds_lfht_for_each_entry(reg->registry->channels->ht, &iter.iter,
-                                       buf_reg_chan, node.node) {
-                               status = consumer_snapshot_channel(socket,
-                                               buf_reg_chan->consumer_key,
-                                               output, 0, &trace_path[consumer_path_offset],
-                                               nb_packets_per_stream);
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
+                               status =
+                                       consumer_snapshot_channel(socket,
+                                                                 buf_reg_chan->consumer_key,
+                                                                 output,
+                                                                 0,
+                                                                 &trace_path[consumer_path_offset],
+                                                                 nb_packets_per_stream);
                                if (status != LTTNG_OK) {
                                        goto error;
                                }
                        }
                        status = consumer_snapshot_channel(socket,
-                                       reg->registry->reg.ust->_metadata_key, output, 1,
-                                       &trace_path[consumer_path_offset], 0);
+                                                          reg->registry->reg.ust->_metadata_key,
+                                                          output,
+                                                          1,
+                                                          &trace_path[consumer_path_offset],
+                                                          0);
                        if (status != LTTNG_OK) {
                                goto error;
                        }
                }
+
                break;
        }
        case LTTNG_BUFFER_PER_PID:
        {
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        struct consumer_socket *socket;
                        struct lttng_ht_iter chan_iter;
                        struct ust_app_channel *ua_chan;
@@ -7028,8 +7260,7 @@ enum lttng_error_code ust_app_snapshot_record(
                        }
 
                        /* Get the right consumer socket for the application. */
-                       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
-                                       output);
+                       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long, output);
                        if (!socket) {
                                status = LTTNG_ERR_INVALID;
                                goto error;
@@ -7037,8 +7268,7 @@ enum lttng_error_code ust_app_snapshot_record(
 
                        /* Add the UST default trace dir to path. */
                        memset(pathname, 0, sizeof(pathname));
-                       ret = snprintf(pathname, sizeof(pathname), "%s",
-                                       ua_sess->path);
+                       ret = snprintf(pathname, sizeof(pathname), "%s", ua_sess->path);
                        if (ret < 0) {
                                status = LTTNG_ERR_INVALID;
                                PERROR("snprintf snapshot path");
@@ -7046,18 +7276,21 @@ enum lttng_error_code ust_app_snapshot_record(
                        }
                        /* Free path allowed on previous iteration. */
                        free(trace_path);
-                       trace_path = setup_channel_trace_path(usess->consumer, pathname,
-                                       &consumer_path_offset);
+                       trace_path = setup_channel_trace_path(
+                               usess->consumer, pathname, &consumer_path_offset);
                        if (!trace_path) {
                                status = LTTNG_ERR_INVALID;
                                goto error;
                        }
-                       cds_lfht_for_each_entry(ua_sess->channels->ht, &chan_iter.iter,
-                                       ua_chan, node.node) {
-                               status = consumer_snapshot_channel(socket,
-                                               ua_chan->key, output, 0,
-                                               &trace_path[consumer_path_offset],
-                                               nb_packets_per_stream);
+                       cds_lfht_for_each_entry (
+                               ua_sess->channels->ht, &chan_iter.iter, ua_chan, node.node) {
+                               status =
+                                       consumer_snapshot_channel(socket,
+                                                                 ua_chan->key,
+                                                                 output,
+                                                                 0,
+                                                                 &trace_path[consumer_path_offset],
+                                                                 nb_packets_per_stream);
                                switch (status) {
                                case LTTNG_OK:
                                        break;
@@ -7074,8 +7307,11 @@ enum lttng_error_code ust_app_snapshot_record(
                                continue;
                        }
                        status = consumer_snapshot_channel(socket,
-                                       registry->_metadata_key, output, 1,
-                                       &trace_path[consumer_path_offset], 0);
+                                                          registry->_metadata_key,
+                                                          output,
+                                                          1,
+                                                          &trace_path[consumer_path_offset],
+                                                          0);
                        switch (status) {
                        case LTTNG_OK:
                                break;
@@ -7094,15 +7330,14 @@ enum lttng_error_code ust_app_snapshot_record(
 
 error:
        free(trace_path);
-       rcu_read_unlock();
        return status;
 }
 
 /*
  * Return the size taken by one more packet per stream.
  */
-uint64_t ust_app_get_size_one_more_packet_per_stream(
-               const struct ltt_ust_session *usess, uint64_t cur_nr_packets)
+uint64_t ust_app_get_size_one_more_packet_per_stream(const struct ltt_ust_session *usess,
+                                                    uint64_t cur_nr_packets)
 {
        uint64_t tot_size = 0;
        struct ust_app *app;
@@ -7115,12 +7350,13 @@ uint64_t ust_app_get_size_one_more_packet_per_stream(
        {
                struct buffer_reg_uid *reg;
 
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct buffer_reg_channel *buf_reg_chan;
 
-                       rcu_read_lock();
-                       cds_lfht_for_each_entry(reg->registry->channels->ht, &iter.iter,
-                                       buf_reg_chan, node.node) {
+                       lttng::urcu::read_lock_guard read_lock;
+
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
                                if (cur_nr_packets >= buf_reg_chan->num_subbuf) {
                                        /*
                                         * Don't take channel into account if we
@@ -7130,14 +7366,14 @@ uint64_t ust_app_get_size_one_more_packet_per_stream(
                                }
                                tot_size += buf_reg_chan->subbuf_size * buf_reg_chan->stream_count;
                        }
-                       rcu_read_unlock();
                }
                break;
        }
        case LTTNG_BUFFER_PER_PID:
        {
-               rcu_read_lock();
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        struct ust_app_channel *ua_chan;
                        struct ust_app_session *ua_sess;
                        struct lttng_ht_iter chan_iter;
@@ -7148,8 +7384,8 @@ uint64_t ust_app_get_size_one_more_packet_per_stream(
                                continue;
                        }
 
-                       cds_lfht_for_each_entry(ua_sess->channels->ht, &chan_iter.iter,
-                                       ua_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               ua_sess->channels->ht, &chan_iter.iter, ua_chan, node.node) {
                                if (cur_nr_packets >= ua_chan->attr.num_subbuf) {
                                        /*
                                         * Don't take channel into account if we
@@ -7160,7 +7396,6 @@ uint64_t ust_app_get_size_one_more_packet_per_stream(
                                tot_size += ua_chan->attr.subbuf_size * ua_chan->streams.count;
                        }
                }
-               rcu_read_unlock();
                break;
        }
        default:
@@ -7172,9 +7407,12 @@ uint64_t ust_app_get_size_one_more_packet_per_stream(
 }
 
 int ust_app_uid_get_channel_runtime_stats(uint64_t ust_session_id,
-               struct cds_list_head *buffer_reg_uid_list,
-               struct consumer_output *consumer, uint64_t uchan_id,
-               int overwrite, uint64_t *discarded, uint64_t *lost)
+                                         struct cds_list_head *buffer_reg_uid_list,
+                                         struct consumer_output *consumer,
+                                         uint64_t uchan_id,
+                                         int overwrite,
+                                         uint64_t *discarded,
+                                         uint64_t *lost)
 {
        int ret;
        uint64_t consumer_chan_key;
@@ -7183,7 +7421,7 @@ int ust_app_uid_get_channel_runtime_stats(uint64_t ust_session_id,
        *lost = 0;
 
        ret = buffer_reg_uid_consumer_channel_key(
-                       buffer_reg_uid_list, uchan_id, &consumer_chan_key);
+               buffer_reg_uid_list, uchan_id, &consumer_chan_key);
        if (ret < 0) {
                /* Not found */
                ret = 0;
@@ -7191,11 +7429,10 @@ int ust_app_uid_get_channel_runtime_stats(uint64_t ust_session_id,
        }
 
        if (overwrite) {
-               ret = consumer_get_lost_packets(ust_session_id,
-                               consumer_chan_key, consumer, lost);
+               ret = consumer_get_lost_packets(ust_session_id, consumer_chan_key, consumer, lost);
        } else {
-               ret = consumer_get_discarded_events(ust_session_id,
-                               consumer_chan_key, consumer, discarded);
+               ret = consumer_get_discarded_events(
+                       ust_session_id, consumer_chan_key, consumer, discarded);
        }
 
 end:
@@ -7203,9 +7440,11 @@ end:
 }
 
 int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan,
-               struct consumer_output *consumer, int overwrite,
-               uint64_t *discarded, uint64_t *lost)
+                                         struct ltt_ust_channel *uchan,
+                                         struct consumer_output *consumer,
+                                         int overwrite,
+                                         uint64_t *discarded,
+                                         uint64_t *lost)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -7217,16 +7456,17 @@ int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
        *discarded = 0;
        *lost = 0;
 
-       rcu_read_lock();
        /*
         * Iterate over every registered applications. Sum counters for
         * all applications containing requested session and channel.
         */
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+       lttng::urcu::read_lock_guard read_lock;
+
+       cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                struct lttng_ht_iter uiter;
 
                ua_sess = lookup_session_by_app(usess, app);
-               if (ua_sess == NULL) {
+               if (ua_sess == nullptr) {
                        continue;
                }
 
@@ -7241,8 +7481,7 @@ int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
                if (overwrite) {
                        uint64_t _lost;
 
-                       ret = consumer_get_lost_packets(usess->id, ua_chan->key,
-                                       consumer, &_lost);
+                       ret = consumer_get_lost_packets(usess->id, ua_chan->key, consumer, &_lost);
                        if (ret < 0) {
                                break;
                        }
@@ -7250,8 +7489,8 @@ int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
                } else {
                        uint64_t _discarded;
 
-                       ret = consumer_get_discarded_events(usess->id,
-                                       ua_chan->key, consumer, &_discarded);
+                       ret = consumer_get_discarded_events(
+                               usess->id, ua_chan->key, consumer, &_discarded);
                        if (ret < 0) {
                                break;
                        }
@@ -7259,23 +7498,20 @@ int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
                }
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
-static
-int ust_app_regenerate_statedump(struct ltt_ust_session *usess,
-               struct ust_app *app)
+static int ust_app_regenerate_statedump(struct ltt_ust_session *usess, struct ust_app *app)
 {
        int ret = 0;
        struct ust_app_session *ua_sess;
 
        DBG("Regenerating the metadata for ust app pid %d", app->pid);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        ua_sess = lookup_session_by_app(usess, app);
-       if (ua_sess == NULL) {
+       if (ua_sess == nullptr) {
                /* The session is in teardown process. Ignore and continue. */
                goto end;
        }
@@ -7294,7 +7530,6 @@ end_unlock:
        pthread_mutex_unlock(&ua_sess->lock);
 
 end:
-       rcu_read_unlock();
        health_code_update();
        return ret;
 }
@@ -7310,9 +7545,9 @@ int ust_app_regenerate_statedump_all(struct ltt_ust_session *usess)
 
        DBG("Regenerating the metadata for all UST apps");
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+       cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                if (!app->compatible) {
                        continue;
                }
@@ -7324,8 +7559,6 @@ int ust_app_regenerate_statedump_all(struct ltt_ust_session *usess)
                }
        }
 
-       rcu_read_unlock();
-
        return 0;
 }
 
@@ -7339,37 +7572,35 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
        int ret;
        enum lttng_error_code cmd_ret = LTTNG_OK;
        struct lttng_ht_iter iter;
-       struct ust_app *app;
        struct ltt_ust_session *usess = session->ust_session;
 
        LTTNG_ASSERT(usess);
 
-       rcu_read_lock();
-
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
        {
                struct buffer_reg_uid *reg;
 
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct buffer_reg_channel *buf_reg_chan;
                        struct consumer_socket *socket;
+                       lttng::urcu::read_lock_guard read_lock;
 
                        /* Get consumer socket to use to push the metadata.*/
                        socket = consumer_find_socket_by_bitness(reg->bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                cmd_ret = LTTNG_ERR_INVALID;
                                goto error;
                        }
 
                        /* Rotate the data channels. */
-                       cds_lfht_for_each_entry(reg->registry->channels->ht, &iter.iter,
-                                       buf_reg_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
                                ret = consumer_rotate_channel(socket,
-                                               buf_reg_chan->consumer_key,
-                                               usess->consumer,
-                                               /* is_metadata_channel */ false);
+                                                             buf_reg_chan->consumer_key,
+                                                             usess->consumer,
+                                                             /* is_metadata_channel */ false);
                                if (ret < 0) {
                                        cmd_ret = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
                                        goto error;
@@ -7395,9 +7626,9 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
                        }
 
                        ret = consumer_rotate_channel(socket,
-                                       reg->registry->reg.ust->_metadata_key,
-                                       usess->consumer,
-                                       /* is_metadata_channel */ true);
+                                                     reg->registry->reg.ust->_metadata_key,
+                                                     usess->consumer,
+                                                     /* is_metadata_channel */ true);
                        if (ret < 0) {
                                cmd_ret = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
                                goto error;
@@ -7407,14 +7638,28 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
        }
        case LTTNG_BUFFER_PER_PID:
        {
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+               ust_app *raw_app;
+
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, raw_app, pid_n.node) {
                        struct consumer_socket *socket;
                        struct lttng_ht_iter chan_iter;
                        struct ust_app_channel *ua_chan;
                        struct ust_app_session *ua_sess;
                        lsu::registry_session *registry;
+                       bool app_reference_taken;
 
-                       ua_sess = lookup_session_by_app(usess, app);
+                       app_reference_taken = ust_app_get(*raw_app);
+                       if (!app_reference_taken) {
+                               /* Application unregistered concurrently, skip it. */
+                               DBG("Could not get application reference as it is being torn down; skipping application");
+                               continue;
+                       }
+
+                       ust_app_reference app(raw_app);
+                       raw_app = nullptr;
+
+                       ua_sess = lookup_session_by_app(usess, app.get());
                        if (!ua_sess) {
                                /* Session not associated with this app. */
                                continue;
@@ -7422,29 +7667,23 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
 
                        /* Get the right consumer socket for the application. */
                        socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                cmd_ret = LTTNG_ERR_INVALID;
                                goto error;
                        }
 
                        registry = get_session_registry(ua_sess);
-                       if (!registry) {
-                               DBG("Application session is being torn down. Skip application.");
-                               continue;
-                       }
+                       LTTNG_ASSERT(registry);
 
                        /* Rotate the data channels. */
-                       cds_lfht_for_each_entry(ua_sess->channels->ht, &chan_iter.iter,
-                                       ua_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               ua_sess->channels->ht, &chan_iter.iter, ua_chan, node.node) {
                                ret = consumer_rotate_channel(socket,
-                                               ua_chan->key,
-                                               ua_sess->consumer,
-                                               /* is_metadata_channel */ false);
+                                                             ua_chan->key,
+                                                             ua_sess->consumer,
+                                                             /* is_metadata_channel */ false);
                                if (ret < 0) {
-                                       /* Per-PID buffer and application going away. */
-                                       if (ret == -LTTNG_ERR_CHAN_NOT_FOUND)
-                                               continue;
                                        cmd_ret = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
                                        goto error;
                                }
@@ -7456,18 +7695,17 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
 
                                (void) push_metadata(locked_registry, usess->consumer);
                        }
+
                        ret = consumer_rotate_channel(socket,
-                                       registry->_metadata_key,
-                                       ua_sess->consumer,
-                                       /* is_metadata_channel */ true);
+                                                     registry->_metadata_key,
+                                                     ua_sess->consumer,
+                                                     /* is_metadata_channel */ true);
                        if (ret < 0) {
-                               /* Per-PID buffer and application going away. */
-                               if (ret == -LTTNG_ERR_CHAN_NOT_FOUND)
-                                       continue;
                                cmd_ret = LTTNG_ERR_ROTATION_FAIL_CONSUMER;
                                goto error;
                        }
                }
+
                break;
        }
        default:
@@ -7478,12 +7716,10 @@ enum lttng_error_code ust_app_rotate_session(struct ltt_session *session)
        cmd_ret = LTTNG_OK;
 
 error:
-       rcu_read_unlock();
        return cmd_ret;
 }
 
-enum lttng_error_code ust_app_create_channel_subdirectories(
-               const struct ltt_ust_session *usess)
+enum lttng_error_code ust_app_create_channel_subdirectories(const struct ltt_ust_session *usess)
 {
        enum lttng_error_code ret = LTTNG_OK;
        struct lttng_ht_iter iter;
@@ -7492,17 +7728,19 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
        int fmt_ret;
 
        LTTNG_ASSERT(usess->current_trace_chunk);
-       rcu_read_lock();
 
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
        {
                struct buffer_reg_uid *reg;
+               lttng::urcu::read_lock_guard read_lock;
 
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        fmt_ret = asprintf(&pathname_index,
-                                      DEFAULT_UST_TRACE_DIR "/" DEFAULT_UST_TRACE_UID_PATH "/" DEFAULT_INDEX_DIR,
-                                      reg->uid, reg->bits_per_long);
+                                          DEFAULT_UST_TRACE_DIR "/" DEFAULT_UST_TRACE_UID_PATH
+                                                                "/" DEFAULT_INDEX_DIR,
+                                          reg->uid,
+                                          reg->bits_per_long);
                        if (fmt_ret < 0) {
                                ERR("Failed to format channel index directory");
                                ret = LTTNG_ERR_CREATE_DIR_FAIL;
@@ -7514,8 +7752,7 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
                         * of implicitly creating the channel's path.
                         */
                        chunk_status = lttng_trace_chunk_create_subdirectory(
-                                       usess->current_trace_chunk,
-                                       pathname_index);
+                               usess->current_trace_chunk, pathname_index);
                        free(pathname_index);
                        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                                ret = LTTNG_ERR_CREATE_DIR_FAIL;
@@ -7527,20 +7764,19 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
        case LTTNG_BUFFER_PER_PID:
        {
                struct ust_app *app;
+               lttng::urcu::read_lock_guard read_lock;
 
                /*
                 * Create the toplevel ust/ directory in case no apps are running.
                 */
-               chunk_status = lttng_trace_chunk_create_subdirectory(
-                               usess->current_trace_chunk,
-                               DEFAULT_UST_TRACE_DIR);
+               chunk_status = lttng_trace_chunk_create_subdirectory(usess->current_trace_chunk,
+                                                                    DEFAULT_UST_TRACE_DIR);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = LTTNG_ERR_CREATE_DIR_FAIL;
                        goto error;
                }
 
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app,
-                               pid_n.node) {
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        struct ust_app_session *ua_sess;
                        lsu::registry_session *registry;
 
@@ -7557,8 +7793,8 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
                        }
 
                        fmt_ret = asprintf(&pathname_index,
-                                       DEFAULT_UST_TRACE_DIR "/%s/" DEFAULT_INDEX_DIR,
-                                       ua_sess->path);
+                                          DEFAULT_UST_TRACE_DIR "/%s/" DEFAULT_INDEX_DIR,
+                                          ua_sess->path);
                        if (fmt_ret < 0) {
                                ERR("Failed to format channel index directory");
                                ret = LTTNG_ERR_CREATE_DIR_FAIL;
@@ -7569,8 +7805,7 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
                         * of implicitly creating the channel's path.
                         */
                        chunk_status = lttng_trace_chunk_create_subdirectory(
-                                       usess->current_trace_chunk,
-                                       pathname_index);
+                               usess->current_trace_chunk, pathname_index);
                        free(pathname_index);
                        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                                ret = LTTNG_ERR_CREATE_DIR_FAIL;
@@ -7585,7 +7820,6 @@ enum lttng_error_code ust_app_create_channel_subdirectories(
 
        ret = LTTNG_OK;
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -7604,8 +7838,6 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
 
        LTTNG_ASSERT(usess);
 
-       rcu_read_lock();
-
        if (usess->active) {
                ERR("Expecting inactive session %s (%" PRIu64 ")", session->name, session->id);
                cmd_ret = LTTNG_ERR_FATAL;
@@ -7616,24 +7848,24 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
        case LTTNG_BUFFER_PER_UID:
        {
                struct buffer_reg_uid *reg;
+               lttng::urcu::read_lock_guard read_lock;
 
-               cds_list_for_each_entry(reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct buffer_reg_channel *buf_reg_chan;
                        struct consumer_socket *socket;
 
                        /* Get consumer socket to use to push the metadata.*/
                        socket = consumer_find_socket_by_bitness(reg->bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                cmd_ret = LTTNG_ERR_INVALID;
                                goto error_socket;
                        }
 
                        /* Clear the data channels. */
-                       cds_lfht_for_each_entry(reg->registry->channels->ht, &iter.iter,
-                                       buf_reg_chan, node.node) {
-                               ret = consumer_clear_channel(socket,
-                                               buf_reg_chan->consumer_key);
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
+                               ret = consumer_clear_channel(socket, buf_reg_chan->consumer_key);
                                if (ret < 0) {
                                        goto error;
                                }
@@ -7649,8 +7881,7 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
                         * Metadata channel is not cleared per se but we still need to
                         * perform a rotation operation on it behind the scene.
                         */
-                       ret = consumer_clear_channel(socket,
-                                       reg->registry->reg.ust->_metadata_key);
+                       ret = consumer_clear_channel(socket, reg->registry->reg.ust->_metadata_key);
                        if (ret < 0) {
                                goto error;
                        }
@@ -7659,7 +7890,9 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
        }
        case LTTNG_BUFFER_PER_PID:
        {
-               cds_lfht_for_each_entry(ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        struct consumer_socket *socket;
                        struct lttng_ht_iter chan_iter;
                        struct ust_app_channel *ua_chan;
@@ -7674,7 +7907,7 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
 
                        /* Get the right consumer socket for the application. */
                        socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
-                                       usess->consumer);
+                                                                usess->consumer);
                        if (!socket) {
                                cmd_ret = LTTNG_ERR_INVALID;
                                goto error_socket;
@@ -7687,8 +7920,8 @@ enum lttng_error_code ust_app_clear_session(struct ltt_session *session)
                        }
 
                        /* Clear the data channels. */
-                       cds_lfht_for_each_entry(ua_sess->channels->ht, &chan_iter.iter,
-                                       ua_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               ua_sess->channels->ht, &chan_iter.iter, ua_chan, node.node) {
                                ret = consumer_clear_channel(socket, ua_chan->key);
                                if (ret < 0) {
                                        /* Per-PID buffer and application going away. */
@@ -7739,7 +7972,6 @@ error:
 
 error_socket:
 end:
-       rcu_read_unlock();
        return cmd_ret;
 }
 
@@ -7767,31 +7999,27 @@ enum lttng_error_code ust_app_open_packets(struct ltt_session *session)
 
        LTTNG_ASSERT(usess);
 
-       rcu_read_lock();
-
        switch (usess->buffer_type) {
        case LTTNG_BUFFER_PER_UID:
        {
                struct buffer_reg_uid *reg;
 
-               cds_list_for_each_entry (
-                               reg, &usess->buffer_reg_uid_list, lnode) {
+               cds_list_for_each_entry (reg, &usess->buffer_reg_uid_list, lnode) {
                        struct buffer_reg_channel *buf_reg_chan;
                        struct consumer_socket *socket;
+                       lttng::urcu::read_lock_guard read_lock;
 
-                       socket = consumer_find_socket_by_bitness(
-                                       reg->bits_per_long, usess->consumer);
+                       socket = consumer_find_socket_by_bitness(reg->bits_per_long,
+                                                                usess->consumer);
                        if (!socket) {
                                ret = LTTNG_ERR_FATAL;
                                goto error;
                        }
 
-                       cds_lfht_for_each_entry(reg->registry->channels->ht,
-                                       &iter.iter, buf_reg_chan, node.node) {
-                               const int open_ret =
-                                               consumer_open_channel_packets(
-                                                       socket,
-                                                       buf_reg_chan->consumer_key);
+                       cds_lfht_for_each_entry (
+                               reg->registry->channels->ht, &iter.iter, buf_reg_chan, node.node) {
+                               const int open_ret = consumer_open_channel_packets(
+                                       socket, buf_reg_chan->consumer_key);
 
                                if (open_ret < 0) {
                                        ret = LTTNG_ERR_UNK;
@@ -7804,9 +8032,9 @@ enum lttng_error_code ust_app_open_packets(struct ltt_session *session)
        case LTTNG_BUFFER_PER_PID:
        {
                struct ust_app *app;
+               lttng::urcu::read_lock_guard read_lock;
 
-               cds_lfht_for_each_entry (
-                               ust_app_ht->ht, &iter.iter, app, pid_n.node) {
+               cds_lfht_for_each_entry (ust_app_ht->ht, &iter.iter, app, pid_n.node) {
                        struct consumer_socket *socket;
                        struct lttng_ht_iter chan_iter;
                        struct ust_app_channel *ua_chan;
@@ -7820,8 +8048,8 @@ enum lttng_error_code ust_app_open_packets(struct ltt_session *session)
                        }
 
                        /* Get the right consumer socket for the application. */
-                       socket = consumer_find_socket_by_bitness(
-                                       app->abi.bits_per_long, usess->consumer);
+                       socket = consumer_find_socket_by_bitness(app->abi.bits_per_long,
+                                                                usess->consumer);
                        if (!socket) {
                                ret = LTTNG_ERR_FATAL;
                                goto error;
@@ -7833,12 +8061,10 @@ enum lttng_error_code ust_app_open_packets(struct ltt_session *session)
                                continue;
                        }
 
-                       cds_lfht_for_each_entry(ua_sess->channels->ht,
-                                       &chan_iter.iter, ua_chan, node.node) {
+                       cds_lfht_for_each_entry (
+                               ua_sess->channels->ht, &chan_iter.iter, ua_chan, node.node) {
                                const int open_ret =
-                                               consumer_open_channel_packets(
-                                                       socket,
-                                                       ua_chan->key);
+                                       consumer_open_channel_packets(socket, ua_chan->key);
 
                                if (open_ret < 0) {
                                        /*
@@ -7862,6 +8088,54 @@ enum lttng_error_code ust_app_open_packets(struct ltt_session *session)
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
+
+lsu::ctl_field_quirks ust_app::ctl_field_quirks() const
+{
+       /*
+        * Application contexts are expressed as variants. LTTng-UST announces
+        * those by registering an enumeration named `..._tag`. It then registers a
+        * variant as part of the event context that contains the various possible
+        * types.
+        *
+        * Unfortunately, the names used in the enumeration and variant don't
+        * match: the enumeration names are all prefixed with an underscore while
+        * the variant type tag fields aren't.
+        *
+        * While the CTF 1.8.3 specification mentions that
+        * underscores *should* (not *must*) be removed by CTF readers. Babeltrace
+        * 1.x (and possibly others) expect a perfect match between the names used
+        * by tags and variants.
+        *
+        * When the UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS quirk is enabled,
+        * the variant's fields are modified to match the mappings of its tag.
+        *
+        * From ABI version >= 10.x, the variant fields and tag mapping names
+        * correctly match, making this quirk unnecessary.
+        */
+       return v_major <= 9 ? lsu::ctl_field_quirks::UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS :
+                             lsu::ctl_field_quirks::NONE;
+}
+
+static void ust_app_release(urcu_ref *ref)
+{
+       auto& app = *lttng::utils::container_of(ref, &ust_app::ref);
+
+       ust_app_unregister(app);
+       ust_app_destroy(app);
+}
+
+bool ust_app_get(ust_app& app)
+{
+       return urcu_ref_get_unless_zero(&app.ref);
+}
+
+void ust_app_put(struct ust_app *app)
+{
+       if (!app) {
+               return;
+       }
+
+       urcu_ref_put(&app->ref, ust_app_release);
+}
index c48e2b9e25b97f95e745b4cbd47d667583c0eb26..64df1c2955abf4ca2b02ffd8136879c8bcd68923 100644 (file)
@@ -9,21 +9,22 @@
 #ifndef _LTT_UST_APP_H
 #define _LTT_UST_APP_H
 
-#include <stdint.h>
+#include "session.hpp"
+#include "trace-ust.hpp"
+#include "ust-field-convert.hpp"
+#include "ust-registry-session.hpp"
+#include "ust-registry.hpp"
 
-#include <common/index-allocator.hpp>
 #include <common/format.hpp>
+#include <common/index-allocator.hpp>
 #include <common/uuid.hpp>
 
-#include "trace-ust.hpp"
-#include "ust-registry.hpp"
-#include "ust-registry-session.hpp"
-#include "session.hpp"
+#include <stdint.h>
 
 #define UST_APP_EVENT_LIST_SIZE 32
 
 /* Process name (short). */
-#define UST_APP_PROCNAME_LEN   16
+#define UST_APP_PROCNAME_LEN 16
 
 struct lttng_bytecode;
 struct lttng_ust_filter_bytecode;
@@ -44,6 +45,7 @@ struct ust_app_ht_key {
        const char *name;
        const struct lttng_bytecode *filter;
        enum lttng_ust_abi_loglevel_type loglevel_type;
+       int loglevel_value;
        const struct lttng_event_exclusion *exclusion;
 };
 
@@ -66,7 +68,7 @@ struct ust_register_msg {
        uint32_t uint32_t_alignment;
        uint32_t uint64_t_alignment;
        uint32_t long_alignment;
-       int byte_order;         /* BIG_ENDIAN or LITTLE_ENDIAN */
+       int byte_order; /* BIG_ENDIAN or LITTLE_ENDIAN */
        char name[LTTNG_UST_ABI_PROCNAME_LEN];
 };
 
@@ -105,7 +107,7 @@ struct ust_app_ctx {
 };
 
 struct ust_app_event {
-       int enabled;
+       bool enabled;
        int handle;
        struct lttng_ust_abi_object_data *obj;
        struct lttng_ust_abi_event attr;
@@ -116,7 +118,7 @@ struct ust_app_event {
 };
 
 struct ust_app_event_notifier_rule {
-       int enabled;
+       bool enabled;
        uint64_t error_counter_index;
        int handle;
        struct lttng_ust_abi_object_data *obj;
@@ -144,7 +146,7 @@ struct ust_app_stream {
 };
 
 struct ust_app_channel {
-       int enabled;
+       bool enabled;
        int handle;
        /*
         * Unique key used to identify the channel on the consumer side.
@@ -195,19 +197,19 @@ struct ust_app_session {
         */
        pthread_mutex_t lock;
 
-       int enabled;
+       bool enabled;
        /* started: has the session been in started state at any time ? */
-       int started;  /* allows detection of start vs restart. */
-       int handle;   /* used has unique identifier for app session */
+       bool started; /* allows detection of start vs restart. */
+       int handle; /* used has unique identifier for app session */
 
-       bool deleted;   /* Session deleted flag. Check with lock held. */
+       bool deleted; /* Session deleted flag. Check with lock held. */
 
        /*
         * Tracing session ID. Multiple ust app session can have the same tracing
         * session id making this value NOT unique to the object.
         */
        uint64_t tracing_id;
-       uint64_t id;    /* Unique session identifier */
+       uint64_t id; /* Unique session identifier */
        struct lttng_ht *channels; /* Registered channels */
        struct lttng_ht_node_u64 node;
        /*
@@ -234,7 +236,7 @@ struct ust_app_session {
        struct rcu_head rcu_head;
        /* If the channel's streams have to be outputed or not. */
        unsigned int output_traces;
-       unsigned int live_timer_interval;       /* usec */
+       unsigned int live_timer_interval; /* usec */
 
        /* Metadata channel attributes. */
        struct lttng_ust_ctl_consumer_channel_attr metadata_attr;
@@ -248,14 +250,23 @@ struct ust_app_session {
  * and a linked list is kept of all running traceable app.
  */
 struct ust_app {
+       /*
+        * The lifetime of 'sock' holds a reference to the application; the
+        * application management thread will release a reference to the
+        * application if the application dies.
+        */
+       urcu_ref ref;
+
+       /* Traffic initiated from the session daemon to the application. */
        int sock;
-       pthread_mutex_t sock_lock;      /* Protects sock protocol. */
+       pthread_mutex_t sock_lock; /* Protects sock protocol. */
 
+       /* Traffic initiated from the application to the session daemon. */
        int notify_sock;
        pid_t pid;
        pid_t ppid;
-       uid_t uid;           /* User ID that owns the apps */
-       gid_t gid;           /* Group ID that owns the apps */
+       uid_t uid; /* User ID that owns the apps */
+       gid_t gid; /* Group ID that owns the apps */
 
        /* App ABI. */
        lttng::sessiond::trace::abi abi;
@@ -264,8 +275,8 @@ struct ust_app {
                                           supported version of the session daemon, this flag is
                                           set to 0 (NOT compatible) else 1. */
        struct lttng_ust_abi_tracer_version version;
-       uint32_t v_major;    /* Version major number */
-       uint32_t v_minor;    /* Version minor number */
+       uint32_t v_major; /* Version major number */
+       uint32_t v_minor; /* Version minor number */
        /* Extra for the NULL byte. */
        char name[UST_APP_PROCNAME_LEN + 1];
        /* Type of buffer this application uses. */
@@ -324,6 +335,8 @@ struct ust_app {
         * (ust_app_event_notifier_rule) by their token's value.
         */
        struct lttng_ht *token_to_event_notifier_rule_ht;
+
+       lttng::sessiond::ust::ctl_field_quirks ctl_field_quirks() const;
 };
 
 /*
@@ -333,14 +346,20 @@ struct ust_app {
 namespace fmt {
 template <>
 struct formatter<ust_app> : formatter<std::string> {
-       template <typename FormatCtx>
-       typename FormatCtx::iterator format(const ust_app& app, FormatCtx& ctx)
+       template <typename FormatContextType>
+       typename FormatContextType::iterator format(const ust_app& app, FormatContextType& ctx)
        {
-               return format_to(ctx.out(),
-                               "{{ procname = `{}`, ppid = {}, pid = {}, uid = {}, gid = {}, version = {}.{}, registration time = {} }}",
-                               app.name, app.ppid, app.pid, app.uid, app.gid, app.v_major,
-                               app.v_minor,
-                               lttng::utils::time_to_iso8601_str(app.registration_time));
+               return format_to(
+                       ctx.out(),
+                       "{{ procname = `{}`, ppid = {}, pid = {}, uid = {}, gid = {}, version = {}.{}, registration time = {} }}",
+                       app.name,
+                       app.ppid,
+                       app.pid,
+                       app.uid,
+                       app.gid,
+                       app.v_major,
+                       app.v_minor,
+                       lttng::utils::time_to_iso8601_str(app.registration_time));
        }
 };
 } /* namespace fmt */
@@ -350,70 +369,72 @@ struct formatter<ust_app> : formatter<std::string> {
 int ust_app_register(struct ust_register_msg *msg, int sock);
 int ust_app_register_done(struct ust_app *app);
 int ust_app_version(struct ust_app *app);
-void ust_app_unregister(int sock);
+void ust_app_unregister_by_socket(int sock);
 int ust_app_start_trace_all(struct ltt_ust_session *usess);
 int ust_app_stop_trace_all(struct ltt_ust_session *usess);
 int ust_app_destroy_trace_all(struct ltt_ust_session *usess);
 int ust_app_list_events(struct lttng_event **events);
 int ust_app_list_event_fields(struct lttng_event_field **fields);
 int ust_app_create_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent);
-int ust_app_disable_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan);
-int ust_app_enable_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan);
+                            struct ltt_ust_channel *uchan,
+                            struct ltt_ust_event *uevent);
+int ust_app_disable_channel_glb(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan);
+int ust_app_enable_channel_glb(struct ltt_ust_session *usess, struct ltt_ust_channel *uchan);
 int ust_app_enable_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent);
+                            struct ltt_ust_channel *uchan,
+                            struct ltt_ust_event *uevent);
 int ust_app_disable_event_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_event *uevent);
+                             struct ltt_ust_channel *uchan,
+                             struct ltt_ust_event *uevent);
 int ust_app_add_ctx_channel_glb(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan, struct ltt_ust_context *uctx);
+                               struct ltt_ust_channel *uchan,
+                               struct ltt_ust_context *uctx);
 void ust_app_global_update(struct ltt_ust_session *usess, struct ust_app *app);
 void ust_app_global_update_all(struct ltt_ust_session *usess);
 void ust_app_global_update_event_notifier_rules(struct ust_app *app);
-void ust_app_global_update_all_event_notifier_rules(void);
+void ust_app_global_update_all_event_notifier_rules();
 
-void ust_app_clean_list(void);
-int ust_app_ht_alloc(void);
+void ust_app_clean_list();
+int ust_app_ht_alloc();
 struct ust_app *ust_app_find_by_pid(pid_t pid);
-struct ust_app_stream *ust_app_alloc_stream(void);
+struct ust_app_stream *ust_app_alloc_stream();
 int ust_app_recv_registration(int sock, struct ust_register_msg *msg);
 int ust_app_recv_notify(int sock);
 void ust_app_add(struct ust_app *app);
 struct ust_app *ust_app_create(struct ust_register_msg *msg, int sock);
 void ust_app_notify_sock_unregister(int sock);
 ssize_t ust_app_push_metadata(const lttng::sessiond::ust::registry_session::locked_ptr& registry,
-               struct consumer_socket *socket,
-               int send_zero_data);
-void ust_app_destroy(struct ust_app *app);
-enum lttng_error_code ust_app_snapshot_record(
-               const struct ltt_ust_session *usess,
-               const struct consumer_output *output,
-               uint64_t nb_packets_per_stream);
-uint64_t ust_app_get_size_one_more_packet_per_stream(
-               const struct ltt_ust_session *usess, uint64_t cur_nr_packets);
+                             struct consumer_socket *socket,
+                             int send_zero_data);
+enum lttng_error_code ust_app_snapshot_record(const struct ltt_ust_session *usess,
+                                             const struct consumer_output *output,
+                                             uint64_t nb_packets_per_stream);
+uint64_t ust_app_get_size_one_more_packet_per_stream(const struct ltt_ust_session *usess,
+                                                    uint64_t cur_nr_packets);
 struct ust_app *ust_app_find_by_sock(int sock);
 int ust_app_uid_get_channel_runtime_stats(uint64_t ust_session_id,
-               struct cds_list_head *buffer_reg_uid_list,
-               struct consumer_output *consumer, uint64_t uchan_id,
-               int overwrite, uint64_t *discarded, uint64_t *lost);
+                                         struct cds_list_head *buffer_reg_uid_list,
+                                         struct consumer_output *consumer,
+                                         uint64_t uchan_id,
+                                         int overwrite,
+                                         uint64_t *discarded,
+                                         uint64_t *lost);
 int ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess,
-               struct ltt_ust_channel *uchan,
-               struct consumer_output *consumer,
-               int overwrite, uint64_t *discarded, uint64_t *lost);
+                                         struct ltt_ust_channel *uchan,
+                                         struct consumer_output *consumer,
+                                         int overwrite,
+                                         uint64_t *discarded,
+                                         uint64_t *lost);
 int ust_app_regenerate_statedump_all(struct ltt_ust_session *usess);
 enum lttng_error_code ust_app_rotate_session(struct ltt_session *session);
-enum lttng_error_code ust_app_create_channel_subdirectories(
-               const struct ltt_ust_session *session);
-int ust_app_release_object(struct ust_app *app,
-               struct lttng_ust_abi_object_data *data);
+enum lttng_error_code ust_app_create_channel_subdirectories(const struct ltt_ust_session *session);
+int ust_app_release_object(struct ust_app *app, struct lttng_ust_abi_object_data *data);
 enum lttng_error_code ust_app_clear_session(struct ltt_session *session);
 enum lttng_error_code ust_app_open_packets(struct ltt_session *session);
 
 int ust_app_setup_event_notifier_group(struct ust_app *app);
 
-static inline
-int ust_app_supported(void)
+static inline int ust_app_supported()
 {
        return 1;
 }
@@ -421,359 +442,308 @@ int ust_app_supported(void)
 bool ust_app_supports_notifiers(const struct ust_app *app);
 bool ust_app_supports_counters(const struct ust_app *app);
 
+bool ust_app_get(ust_app& app);
+void ust_app_put(ust_app *app);
+
+using ust_app_reference =
+       std::unique_ptr<ust_app, lttng::memory::create_deleter_class<ust_app, ust_app_put>::deleter>;
+
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-int ust_app_destroy_trace_all(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline int ust_app_destroy_trace_all(struct ltt_ust_session *usess __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_start_trace(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ust_app *app __attribute__((unused)))
+static inline int ust_app_start_trace(struct ltt_ust_session *usess __attribute__((unused)),
+                                     struct ust_app *app __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_start_trace_all(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline int ust_app_start_trace_all(struct ltt_ust_session *usess __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_stop_trace_all(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline int ust_app_stop_trace_all(struct ltt_ust_session *usess __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_list_events(
-               struct lttng_event **events __attribute__((unused)))
+static inline int ust_app_list_events(struct lttng_event **events __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int ust_app_list_event_fields(
-               struct lttng_event_field **fields __attribute__((unused)))
+static inline int ust_app_list_event_fields(struct lttng_event_field **fields
+                                           __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int ust_app_register(
-               struct ust_register_msg *msg __attribute__((unused)),
-               int sock __attribute__((unused)))
+static inline int ust_app_register(struct ust_register_msg *msg __attribute__((unused)),
+                                  int sock __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int ust_app_register_done(struct ust_app *app __attribute__((unused)))
+static inline int ust_app_register_done(struct ust_app *app __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int ust_app_version(struct ust_app *app __attribute__((unused)))
+static inline int ust_app_version(struct ust_app *app __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void ust_app_unregister(int sock __attribute__((unused)))
+static inline void ust_app_unregister_by_socket(int sock __attribute__((unused)))
 {
 }
 
-static inline
-void ust_app_clean_list(void)
+static inline void ust_app_clean_list(void)
 {
 }
 
-static inline
-struct ust_app_list *ust_app_get_list(void)
+static inline struct ust_app_list *ust_app_get_list(void)
 {
        return NULL;
 }
 
-static inline
-struct ust_app *ust_app_get_by_pid(pid_t pid __attribute__((unused)))
+static inline struct ust_app *ust_app_get_by_pid(pid_t pid __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-int ust_app_ht_alloc(void)
+static inline int ust_app_ht_alloc(void)
 {
        return 0;
 }
 
-static inline
-void ust_app_global_update(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ust_app *app __attribute__((unused)))
-{}
+static inline void ust_app_global_update(struct ltt_ust_session *usess __attribute__((unused)),
+                                        struct ust_app *app __attribute__((unused)))
+{
+}
 
-static inline
-void ust_app_global_update_event_notifier_rules(
-               struct ust_app *app __attribute__((unused)))
-{}
+static inline void ust_app_global_update_event_notifier_rules(struct ust_app *app
+                                                             __attribute__((unused)))
+{
+}
 
-static inline
-void ust_app_global_update_all_event_notifier_rules(void)
-{}
+static inline void ust_app_global_update_all_event_notifier_rules(void)
+{
+}
 
-static inline
-int ust_app_setup_event_notifier_group(
-               struct ust_app *app __attribute__((unused)))
+static inline int ust_app_setup_event_notifier_group(struct ust_app *app __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_disable_channel_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)))
+static inline int ust_app_disable_channel_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                             struct ltt_ust_channel *uchan __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_enable_channel_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)))
+static inline int ust_app_enable_channel_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                            struct ltt_ust_channel *uchan __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_create_event_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct ltt_ust_event *uevent __attribute__((unused)))
+static inline int ust_app_create_event_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                          struct ltt_ust_channel *uchan __attribute__((unused)),
+                                          struct ltt_ust_event *uevent __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_disable_event_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct ltt_ust_event *uevent __attribute__((unused)))
+static inline int ust_app_disable_event_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                           struct ltt_ust_channel *uchan __attribute__((unused)),
+                                           struct ltt_ust_event *uevent __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_enable_event_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct ltt_ust_event *uevent __attribute__((unused)))
+static inline int ust_app_enable_event_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                          struct ltt_ust_channel *uchan __attribute__((unused)),
+                                          struct ltt_ust_event *uevent __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_add_ctx_channel_glb(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct ltt_ust_context *uctx __attribute__((unused)))
+static inline int ust_app_add_ctx_channel_glb(struct ltt_ust_session *usess __attribute__((unused)),
+                                             struct ltt_ust_channel *uchan __attribute__((unused)),
+                                             struct ltt_ust_context *uctx __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_enable_event_pid(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct ltt_ust_event *uevent __attribute__((unused)),
-               pid_t pid __attribute__((unused)))
+static inline int ust_app_enable_event_pid(struct ltt_ust_session *usess __attribute__((unused)),
+                                          struct ltt_ust_channel *uchan __attribute__((unused)),
+                                          struct ltt_ust_event *uevent __attribute__((unused)),
+                                          pid_t pid __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_recv_registration(
-               int sock __attribute__((unused)),
-               struct ust_register_msg *msg __attribute__((unused)))
+static inline int ust_app_recv_registration(int sock __attribute__((unused)),
+                                           struct ust_register_msg *msg __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_recv_notify(int sock __attribute__((unused)))
+static inline int ust_app_recv_notify(int sock __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-struct ust_app *ust_app_create(
-               struct ust_register_msg *msg __attribute__((unused)),
-               int sock __attribute__((unused)))
+static inline struct ust_app *ust_app_create(struct ust_register_msg *msg __attribute__((unused)),
+                                            int sock __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-void ust_app_add(struct ust_app *app __attribute__((unused)))
+static inline void ust_app_add(struct ust_app *app __attribute__((unused)))
 {
 }
 
-static inline
-void ust_app_notify_sock_unregister(int sock __attribute__((unused)))
+static inline void ust_app_notify_sock_unregister(int sock __attribute__((unused)))
 {
 }
 
-static inline
-ssize_t ust_app_push_metadata(
-               lttng::sessiond::ust::registry_session *registry __attribute__((unused)),
-               struct consumer_socket *socket __attribute__((unused)),
-               int send_zero_data __attribute__((unused)))
+static inline ssize_t ust_app_push_metadata(lttng::sessiond::ust::registry_session *registry
+                                           __attribute__((unused)),
+                                           struct consumer_socket *socket __attribute__((unused)),
+                                           int send_zero_data __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-void ust_app_destroy(struct ust_app *app __attribute__((unused)))
-{
-       return;
-}
-
-static inline
-enum lttng_error_code ust_app_snapshot_record(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               const struct consumer_output *output __attribute__((unused)),
-               uint64_t max_stream_size __attribute__((unused)))
+static inline enum lttng_error_code
+ust_app_snapshot_record(struct ltt_ust_session *usess __attribute__((unused)),
+                       const struct consumer_output *output __attribute__((unused)),
+                       uint64_t max_stream_size __attribute__((unused)))
 {
        return LTTNG_ERR_UNK;
 }
 
-static inline
-unsigned int ust_app_get_nb_stream(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline unsigned int ust_app_get_nb_stream(struct ltt_ust_session *usess
+                                                __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-void ust_app_update_event_notifier_error_count(
-               struct lttng_trigger *lttng_trigger __attribute__((unused)))
+static inline void ust_app_update_event_notifier_error_count(struct lttng_trigger *lttng_trigger
+                                                            __attribute__((unused)))
 {
        return;
 }
 
-static inline
-int ust_app_supported(void)
+static inline int ust_app_supported(void)
 {
        return 0;
 }
 
-static inline
-bool ust_app_supports_notifiers(
-               const struct ust_app *app __attribute__((unused)))
+static inline bool ust_app_supports_notifiers(const struct ust_app *app __attribute__((unused)))
 {
        return false;
 }
 
-static inline
-bool ust_app_supports_counters(
-               const struct ust_app *app __attribute__((unused)))
+static inline bool ust_app_supports_counters(const struct ust_app *app __attribute__((unused)))
 {
        return false;
 }
 
-static inline
-struct ust_app *ust_app_find_by_sock(int sock __attribute__((unused)))
+static inline struct ust_app *ust_app_find_by_sock(int sock __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-struct ust_app *ust_app_find_by_pid(pid_t pid __attribute__((unused)))
+static inline struct ust_app *ust_app_find_by_pid(pid_t pid __attribute__((unused)))
 {
        return NULL;
 }
 
-static inline
-uint64_t ust_app_get_size_one_more_packet_per_stream(
-               const struct ltt_ust_session *usess __attribute__((unused)),
-               uint64_t cur_nr_packets __attribute__((unused))) {
+static inline uint64_t
+ust_app_get_size_one_more_packet_per_stream(const struct ltt_ust_session *usess
+                                           __attribute__((unused)),
+                                           uint64_t cur_nr_packets __attribute__((unused)))
+{
        return 0;
 }
 
-static inline
-int ust_app_uid_get_channel_runtime_stats(
-               uint64_t ust_session_id __attribute__((unused)),
-               struct cds_list_head *buffer_reg_uid_list __attribute__((unused)),
-               struct consumer_output *consumer __attribute__((unused)),
-               int overwrite __attribute__((unused)),
-               uint64_t uchan_id __attribute__((unused)),
-               uint64_t *discarded __attribute__((unused)),
-               uint64_t *lost __attribute__((unused)))
+static inline int ust_app_uid_get_channel_runtime_stats(uint64_t ust_session_id
+                                                       __attribute__((unused)),
+                                                       struct cds_list_head *buffer_reg_uid_list
+                                                       __attribute__((unused)),
+                                                       struct consumer_output *consumer
+                                                       __attribute__((unused)),
+                                                       int overwrite __attribute__((unused)),
+                                                       uint64_t uchan_id __attribute__((unused)),
+                                                       uint64_t *discarded __attribute__((unused)),
+                                                       uint64_t *lost __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_pid_get_channel_runtime_stats(
-               struct ltt_ust_session *usess __attribute__((unused)),
-               struct ltt_ust_channel *uchan __attribute__((unused)),
-               struct consumer_output *consumer __attribute__((unused)),
-               int overwrite __attribute__((unused)),
-               uint64_t *discarded __attribute__((unused)),
-               uint64_t *lost __attribute__((unused)))
+static inline int
+ust_app_pid_get_channel_runtime_stats(struct ltt_ust_session *usess __attribute__((unused)),
+                                     struct ltt_ust_channel *uchan __attribute__((unused)),
+                                     struct consumer_output *consumer __attribute__((unused)),
+                                     int overwrite __attribute__((unused)),
+                                     uint64_t *discarded __attribute__((unused)),
+                                     uint64_t *lost __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_app_regenerate_statedump_all(
-               struct ltt_ust_session *usess __attribute__((unused)))
+static inline int ust_app_regenerate_statedump_all(struct ltt_ust_session *usess
+                                                  __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-enum lttng_error_code ust_app_rotate_session(
-               struct ltt_session *session __attribute__((unused)))
+static inline enum lttng_error_code ust_app_rotate_session(struct ltt_session *session
+                                                          __attribute__((unused)))
 {
        return LTTNG_ERR_UNK;
 }
 
-static inline
-enum lttng_error_code ust_app_create_channel_subdirectories(
-               const struct ltt_ust_session *session __attribute__((unused)))
+static inline enum lttng_error_code
+ust_app_create_channel_subdirectories(const struct ltt_ust_session *session __attribute__((unused)))
 {
        return LTTNG_ERR_UNK;
 }
 
-static inline
-int ust_app_release_object(struct ust_app *app __attribute__((unused)),
-               struct lttng_ust_abi_object_data *data __attribute__((unused)))
+static inline int ust_app_release_object(struct ust_app *app __attribute__((unused)),
+                                        struct lttng_ust_abi_object_data *data
+                                        __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-enum lttng_error_code ust_app_clear_session(
-               struct ltt_session *session __attribute__((unused)))
+static inline enum lttng_error_code ust_app_clear_session(struct ltt_session *session
+                                                         __attribute__((unused)))
 {
        return LTTNG_ERR_UNK;
 }
 
-static inline
-enum lttng_error_code ust_app_open_packets(
-               struct ltt_session *session __attribute__((unused)))
+static inline enum lttng_error_code ust_app_open_packets(struct ltt_session *session
+                                                        __attribute__((unused)))
 {
        return LTTNG_ERR_UNK;
 }
 
+static inline void ust_app_get(ust_app& app __attribute__((unused)))
+{
+}
+
+static inline void ust_app_put(ust_app *app __attribute__((unused)))
+{
+}
+
 #endif /* HAVE_LIBLTTNG_UST_CTL */
 
 #endif /* _LTT_UST_APP_H */
index 34b466f0a849332ee8fc89cd84fef16693d55bab..cdb3b50a5fe5154c57322eed7f4db975ae0b8f9d 100644 (file)
@@ -9,12 +9,12 @@
 
 #include "ust-clock-class.hpp"
 
-#include <common/time.hpp>
 #include <common/exception.hpp>
+#include <common/time.hpp>
 
 #include <lttng/ust-clock.h>
 
-#define CLOCK_OFFSET_SAMPLE_COUNT              10
+#define CLOCK_OFFSET_SAMPLE_COUNT 10
 
 namespace lst = lttng::sessiond::trace;
 
@@ -66,7 +66,7 @@ nonstd::optional<lttng_uuid> sample_clock_uuid()
                LTTNG_THROW_ERROR("Failed to parse UUID from string");
        }
 
-       return nonstd::optional<lttng_uuid>{uuid};
+       return nonstd::optional<lttng_uuid>{ uuid };
 }
 
 const char *sample_clock_name()
@@ -79,7 +79,8 @@ const char *sample_clock_name()
 
        const auto name = get_name_cb();
        if (!name) {
-               LTTNG_THROW_ERROR("Invalid clock name returned by LTTng-UST `lttng_ust_clock_name_function`");
+               LTTNG_THROW_ERROR(
+                       "Invalid clock name returned by LTTng-UST `lttng_ust_clock_name_function`");
        }
 
        return name;
@@ -95,7 +96,8 @@ const char *sample_clock_description()
 
        const auto description = get_description_cb();
        if (!description) {
-               LTTNG_THROW_ERROR("Invalid clock description returned by LTTng-UST `lttng_ust_clock_description_function`");
+               LTTNG_THROW_ERROR(
+                       "Invalid clock description returned by LTTng-UST `lttng_ust_clock_description_function`");
        }
 
        return description;
@@ -107,8 +109,7 @@ const char *sample_clock_description()
  */
 void measure_single_clock_offset(struct offset_sample *sample)
 {
-       lst::clock_class::cycles_t monotonic_avg, monotonic[2], measure_delta,
-                       realtime;
+       lst::clock_class::cycles_t monotonic_avg, monotonic[2], measure_delta, realtime;
        const auto tcf = sample_clock_frequency();
        struct timespec rts = { 0, 0 };
 
@@ -132,8 +133,7 @@ void measure_single_clock_offset(struct offset_sample *sample)
        if (tcf == NSEC_PER_SEC) {
                realtime += rts.tv_nsec;
        } else {
-               realtime += (lst::clock_class::cycles_t) rts.tv_nsec * tcf /
-                               NSEC_PER_SEC;
+               realtime += (lst::clock_class::cycles_t) rts.tv_nsec * tcf / NSEC_PER_SEC;
        }
 
        sample->offset = (lst::clock_class::scycles_t) realtime - monotonic_avg;
@@ -146,7 +146,7 @@ void measure_single_clock_offset(struct offset_sample *sample)
  * to complete, thus removing imprecision caused by preemption.
  * May return a negative offset.
  */
-lst::clock_class::scycles_t measure_clock_offset(void)
+lst::clock_class::scycles_t measure_clock_offset()
 {
        struct offset_sample offset_best_sample = {
                .offset = 0,
@@ -163,9 +163,9 @@ lst::clock_class::scycles_t measure_clock_offset(void)
 
 lttng::sessiond::ust::clock_class::clock_class() :
        lst::clock_class(sample_clock_name(),
-                       sample_clock_description(),
-                       sample_clock_uuid(),
-                       measure_clock_offset(),
-                       sample_clock_frequency())
+                        sample_clock_description(),
+                        sample_clock_uuid(),
+                        measure_clock_offset(),
+                        sample_clock_frequency())
 {
 }
index df4689920eb0b90ffff3eb45c368b42be8727c28..8bcc246121346b239c651ac66c8a23b8aab926a3 100644 (file)
@@ -6,24 +6,24 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <inttypes.h>
+#include "buffer-registry.hpp"
+#include "consumer.hpp"
+#include "health-sessiond.hpp"
+#include "lttng-sessiond.hpp"
+#include "lttng-ust-error.hpp"
+#include "session.hpp"
+#include "ust-consumer.hpp"
 
-#include <common/compat/errno.hpp>
 #include <common/common.hpp>
+#include <common/compat/errno.hpp>
 #include <common/consumer/consumer.hpp>
 #include <common/defaults.hpp>
 
-#include "consumer.hpp"
-#include "health-sessiond.hpp"
-#include "ust-consumer.hpp"
-#include "lttng-ust-error.hpp"
-#include "buffer-registry.hpp"
-#include "session.hpp"
-#include "lttng-sessiond.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
 namespace lsu = lttng::sessiond::ust;
 
@@ -33,16 +33,16 @@ namespace lsu = lttng::sessiond::ust;
  * Consumer socket lock MUST be acquired before calling this.
  */
 static int ask_channel_creation(struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan,
-               struct consumer_output *consumer,
-               struct consumer_socket *socket,
-               lsu::registry_session *registry,
-               struct lttng_trace_chunk *trace_chunk)
+                               struct ust_app_channel *ua_chan,
+                               struct consumer_output *consumer,
+                               struct consumer_socket *socket,
+                               lsu::registry_session *registry,
+                               struct lttng_trace_chunk *trace_chunk)
 {
        int ret, output;
        uint32_t chan_id;
        uint64_t key, chan_reg_key;
-       char *pathname = NULL;
+       char *pathname = nullptr;
        struct lttcomm_consumer_msg msg;
        char shm_path[PATH_MAX] = "";
        char root_shm_path[PATH_MAX] = "";
@@ -59,8 +59,7 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
 
        is_local_trace = consumer->net_seq_index == -1ULL;
        /* Format the channel's path (relative to the current trace chunk). */
-       pathname = setup_channel_trace_path(consumer, ua_sess->path,
-                       &consumer_path_offset);
+       pathname = setup_channel_trace_path(consumer, ua_sess->path, &consumer_path_offset);
        if (!pathname) {
                ret = -1;
                goto error;
@@ -70,8 +69,7 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
                enum lttng_trace_chunk_status chunk_status;
                char *pathname_index;
 
-               ret = asprintf(&pathname_index, "%s/" DEFAULT_INDEX_DIR,
-                               pathname);
+               ret = asprintf(&pathname_index, "%s/" DEFAULT_INDEX_DIR, pathname);
                if (ret < 0) {
                        ERR("Failed to format channel index directory");
                        ret = -1;
@@ -82,8 +80,7 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
                 * Create the index subdirectory which will take care
                 * of implicitly creating the channel's path.
                 */
-               chunk_status = lttng_trace_chunk_create_subdirectory(
-                               trace_chunk, pathname_index);
+               chunk_status = lttng_trace_chunk_create_subdirectory(trace_chunk, pathname_index);
                free(pathname_index);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
@@ -108,7 +105,7 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
        } else {
                {
                        auto locked_registry = registry->lock();
-                       auto& ust_reg_chan = registry->get_channel(chan_reg_key);
+                       auto& ust_reg_chan = registry->channel(chan_reg_key);
 
                        chan_id = ust_reg_chan.id;
                }
@@ -116,12 +113,9 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
                if (ua_sess->shm_path[0]) {
                        strncpy(shm_path, ua_sess->shm_path, sizeof(shm_path));
                        shm_path[sizeof(shm_path) - 1] = '\0';
-                       strncat(shm_path, "/",
-                               sizeof(shm_path) - strlen(shm_path) - 1);
-                       strncat(shm_path, ua_chan->name,
-                                       sizeof(shm_path) - strlen(shm_path) - 1);
-                               strncat(shm_path, "_",
-                                       sizeof(shm_path) - strlen(shm_path) - 1);
+                       strncat(shm_path, "/", sizeof(shm_path) - strlen(shm_path) - 1);
+                       strncat(shm_path, ua_chan->name, sizeof(shm_path) - strlen(shm_path) - 1);
+                       strncat(shm_path, "_", sizeof(shm_path) - strlen(shm_path) - 1);
                }
                strncpy(root_shm_path, ua_sess->root_shm_path, sizeof(root_shm_path));
                root_shm_path[sizeof(root_shm_path) - 1] = '\0';
@@ -135,32 +129,33 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
        }
 
        consumer_init_ask_channel_comm_msg(&msg,
-                       ua_chan->attr.subbuf_size,
-                       ua_chan->attr.num_subbuf,
-                       ua_chan->attr.overwrite,
-                       ua_chan->attr.switch_timer_interval,
-                       ua_chan->attr.read_timer_interval,
-                       ua_sess->live_timer_interval,
-                       ua_sess->live_timer_interval != 0,
-                       ua_chan->monitor_timer_interval,
-                       output,
-                       (int) ua_chan->attr.type,
-                       ua_sess->tracing_id,
-                       &pathname[consumer_path_offset],
-                       ua_chan->name,
-                       consumer->net_seq_index,
-                       ua_chan->key,
-                       registry->uuid,
-                       chan_id,
-                       ua_chan->tracefile_size,
-                       ua_chan->tracefile_count,
-                       ua_sess->id,
-                       ua_sess->output_traces,
-                       lttng_credentials_get_uid(&ua_sess->real_credentials),
-                       ua_chan->attr.blocking_timeout,
-                       root_shm_path, shm_path,
-                       trace_chunk,
-                       &ua_sess->effective_credentials);
+                                          ua_chan->attr.subbuf_size,
+                                          ua_chan->attr.num_subbuf,
+                                          ua_chan->attr.overwrite,
+                                          ua_chan->attr.switch_timer_interval,
+                                          ua_chan->attr.read_timer_interval,
+                                          ua_sess->live_timer_interval,
+                                          ua_sess->live_timer_interval != 0,
+                                          ua_chan->monitor_timer_interval,
+                                          output,
+                                          (int) ua_chan->attr.type,
+                                          ua_sess->tracing_id,
+                                          &pathname[consumer_path_offset],
+                                          ua_chan->name,
+                                          consumer->net_seq_index,
+                                          ua_chan->key,
+                                          registry->uuid,
+                                          chan_id,
+                                          ua_chan->tracefile_size,
+                                          ua_chan->tracefile_count,
+                                          ua_sess->id,
+                                          ua_sess->output_traces,
+                                          lttng_credentials_get_uid(&ua_sess->real_credentials),
+                                          ua_chan->attr.blocking_timeout,
+                                          root_shm_path,
+                                          shm_path,
+                                          trace_chunk,
+                                          &ua_sess->effective_credentials);
 
        health_code_update();
 
@@ -169,8 +164,7 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
                goto error;
        }
 
-       ret = consumer_recv_status_channel(socket, &key,
-                       &ua_chan->expected_stream_count);
+       ret = consumer_recv_status_channel(socket, &key, &ua_chan->expected_stream_count);
        if (ret < 0) {
                goto error;
        }
@@ -181,8 +175,9 @@ static int ask_channel_creation(struct ust_app_session *ua_sess,
                LTTNG_ASSERT(ua_chan->expected_stream_count > 0);
        }
 
-       DBG2("UST ask channel %" PRIu64 " successfully done with %u stream(s)", key,
-                       ua_chan->expected_stream_count);
+       DBG2("UST ask channel %" PRIu64 " successfully done with %u stream(s)",
+            key,
+            ua_chan->expected_stream_count);
 
 error:
        free(pathname);
@@ -198,11 +193,11 @@ error:
  * Returns 0 on success else a negative value.
  */
 int ust_consumer_ask_channel(struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan,
-               struct consumer_output *consumer,
-               struct consumer_socket *socket,
-               lsu::registry_session *registry,
-               struct lttng_trace_chunk * trace_chunk)
+                            struct ust_app_channel *ua_chan,
+                            struct consumer_output *consumer,
+                            struct consumer_socket *socket,
+                            lsu::registry_session *registry,
+                            struct lttng_trace_chunk *trace_chunk)
 {
        int ret;
 
@@ -219,8 +214,7 @@ int ust_consumer_ask_channel(struct ust_app_session *ua_sess,
        }
 
        pthread_mutex_lock(socket->lock);
-       ret = ask_channel_creation(ua_sess, ua_chan, consumer, socket, registry,
-                       trace_chunk);
+       ret = ask_channel_creation(ua_sess, ua_chan, consumer, socket, registry, trace_chunk);
        pthread_mutex_unlock(socket->lock);
        if (ret < 0) {
                ERR("ask_channel_creation consumer command failed");
@@ -237,8 +231,7 @@ error:
  *
  * Return 0 on success else a negative value.
  */
-int ust_consumer_get_channel(struct consumer_socket *socket,
-               struct ust_app_channel *ua_chan)
+int ust_consumer_get_channel(struct consumer_socket *socket, struct ust_app_channel *ua_chan)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -264,7 +257,8 @@ int ust_consumer_get_channel(struct consumer_socket *socket,
        if (ret < 0) {
                if (ret != -EPIPE) {
                        ERR("Error recv channel from consumer %d with ret %d",
-                                       *socket->fd_ptr, ret);
+                           *socket->fd_ptr,
+                           ret);
                } else {
                        DBG3("UST app recv channel from consumer. Consumer is dead.");
                }
@@ -272,12 +266,12 @@ int ust_consumer_get_channel(struct consumer_socket *socket,
        }
 
        /* Next, get all streams. */
-       while (1) {
+       while (true) {
                struct ust_app_stream *stream;
 
                /* Create UST stream */
                stream = ust_app_alloc_stream();
-               if (stream == NULL) {
+               if (stream == nullptr) {
                        ret = -ENOMEM;
                        goto error;
                }
@@ -292,7 +286,8 @@ int ust_consumer_get_channel(struct consumer_socket *socket,
                        }
                        if (ret != -EPIPE) {
                                ERR("Recv stream from consumer %d with ret %d",
-                                               *socket->fd_ptr, ret);
+                                   *socket->fd_ptr,
+                                   ret);
                        } else {
                                DBG3("UST app recv stream from consumer. Consumer is dead.");
                        }
@@ -331,8 +326,7 @@ error:
  *
  * Return 0 on success else a negative value.
  */
-int ust_consumer_destroy_channel(struct consumer_socket *socket,
-               struct ust_app_channel *ua_chan)
+int ust_consumer_destroy_channel(struct consumer_socket *socket, struct ust_app_channel *ua_chan)
 {
        int ret;
        struct lttcomm_consumer_msg msg;
@@ -364,7 +358,8 @@ error:
  * On success return 0 else a negative value.
  */
 int ust_consumer_send_stream_to_ust(struct ust_app *app,
-               struct ust_app_channel *channel, struct ust_app_stream *stream)
+                                   struct ust_app_channel *channel,
+                                   struct ust_app_stream *stream)
 {
        int ret;
 
@@ -381,14 +376,18 @@ int ust_consumer_send_stream_to_ust(struct ust_app *app,
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app send stream to ust failed. Application is dead. (pid: %d, sock: %d).",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app send stream to ust failed. Communication time out (pid: %d, sock: %d).",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app send stream, handle %d, to ust failed with ret %d (pid: %d, sock: %d).",
-                                       stream->obj->handle, ret, app->pid,
-                                       app->sock);
+                           stream->obj->handle,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
@@ -404,7 +403,8 @@ error:
  * On success return 0 else a negative value.
  */
 int ust_consumer_send_channel_to_ust(struct ust_app *app,
-               struct ust_app_session *ua_sess, struct ust_app_channel *channel)
+                                    struct ust_app_session *ua_sess,
+                                    struct ust_app_channel *channel)
 {
        int ret;
 
@@ -414,7 +414,10 @@ int ust_consumer_send_channel_to_ust(struct ust_app *app,
        LTTNG_ASSERT(channel->obj);
 
        DBG2("UST app send channel to sock %d pid %d (name: %s, key: %" PRIu64 ")",
-                       app->sock, app->pid, channel->name, channel->tracing_channel_id);
+            app->sock,
+            app->pid,
+            channel->name,
+            channel->tracing_channel_id);
 
        /* Send stream to application. */
        pthread_mutex_lock(&app->sock_lock);
@@ -423,14 +426,18 @@ int ust_consumer_send_channel_to_ust(struct ust_app *app,
        if (ret < 0) {
                if (ret == -EPIPE || ret == -LTTNG_UST_ERR_EXITING) {
                        DBG3("UST app send channel to ust failed. Application is dead (pid: %d, sock: %d).",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else if (ret == -EAGAIN) {
                        WARN("UST app send channel to ust failed. Communication timeout (pid: %d, sock: %d).",
-                                       app->pid, app->sock);
+                            app->pid,
+                            app->sock);
                } else {
                        ERR("UST app send channel %s, to ust failed with ret %d (pid: %d, sock: %d).",
-                                       channel->name, ret, app->pid,
-                                       app->sock);
+                           channel->name,
+                           ret,
+                           app->pid,
+                           app->sock);
                }
                goto error;
        }
@@ -455,7 +462,7 @@ int ust_consumer_metadata_request(struct consumer_socket *socket)
 
        LTTNG_ASSERT(socket);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        health_code_update();
 
        /* Wait for a metadata request */
@@ -467,18 +474,17 @@ int ust_consumer_metadata_request(struct consumer_socket *socket)
        }
 
        DBG("Metadata request received for session %" PRIu64 ", key %" PRIu64,
-                       request.session_id, request.key);
+           request.session_id,
+           request.key);
 
-       reg_uid = buffer_reg_uid_find(request.session_id,
-                       request.bits_per_long, request.uid);
+       reg_uid = buffer_reg_uid_find(request.session_id, request.bits_per_long, request.uid);
        if (reg_uid) {
                ust_reg = reg_uid->registry->reg.ust;
        } else {
-               struct buffer_reg_pid *reg_pid =
-                       buffer_reg_pid_find(request.session_id_per_pid);
+               struct buffer_reg_pid *reg_pid = buffer_reg_pid_find(request.session_id_per_pid);
                if (!reg_pid) {
                        DBG("PID registry not found for session id %" PRIu64,
-                                       request.session_id_per_pid);
+                           request.session_id_per_pid);
 
                        memset(&msg, 0, sizeof(msg));
                        msg.cmd_type = LTTNG_ERR_UND;
@@ -514,6 +520,5 @@ int ust_consumer_metadata_request(struct consumer_socket *socket)
        ret = 0;
 
 end:
-       rcu_read_unlock();
        return ret;
 }
index f752131b63b6e28fbe54b93e5561c477cfb44bf9..9fc83e6abf790458f3f989e351dcd7924de8de41 100644 (file)
 
 #include "consumer.hpp"
 #include "ust-app.hpp"
-#include <stdint.h>
+
 #include <common/trace-chunk.hpp>
 
+#include <stdint.h>
+
 int ust_consumer_ask_channel(struct ust_app_session *ua_sess,
-               struct ust_app_channel *ua_chan,
-               struct consumer_output *consumer,
-               struct consumer_socket *socket,
-               lttng::sessiond::ust::registry_session *registry,
-               struct lttng_trace_chunk *trace_chunk);
+                            struct ust_app_channel *ua_chan,
+                            struct consumer_output *consumer,
+                            struct consumer_socket *socket,
+                            lttng::sessiond::ust::registry_session *registry,
+                            struct lttng_trace_chunk *trace_chunk);
 
-int ust_consumer_get_channel(struct consumer_socket *socket,
-               struct ust_app_channel *ua_chan);
+int ust_consumer_get_channel(struct consumer_socket *socket, struct ust_app_channel *ua_chan);
 
-int ust_consumer_destroy_channel(struct consumer_socket *socket,
-               struct ust_app_channel *ua_chan);
+int ust_consumer_destroy_channel(struct consumer_socket *socket, struct ust_app_channel *ua_chan);
 
 int ust_consumer_send_stream_to_ust(struct ust_app *app,
-               struct ust_app_channel *channel, struct ust_app_stream *stream);
+                                   struct ust_app_channel *channel,
+                                   struct ust_app_stream *stream);
 
 int ust_consumer_send_channel_to_ust(struct ust_app *app,
-               struct ust_app_session *ua_sess, struct ust_app_channel *channel);
+                                    struct ust_app_session *ua_sess,
+                                    struct ust_app_channel *channel);
 
 #ifdef HAVE_LIBLTTNG_UST_CTL
 int ust_consumer_metadata_request(struct consumer_socket *sock);
 #else
-static inline
-int ust_consumer_metadata_request(
-               struct consumer_socket *sock __attribute__((unused)))
+static inline int ust_consumer_metadata_request(struct consumer_socket *sock
+                                               __attribute__((unused)))
 {
        return -ENOSYS;
 }
index aee3cd580adeeca45e328c0242c010b72db0cf61..79b863ce2f7f36f089e713f049d186c5ce986f71 100644 (file)
@@ -9,42 +9,40 @@
 #ifndef LTTNG_UST_CTL_INTERNAL_H
 #define LTTNG_UST_CTL_INTERNAL_H
 
-#include <sys/types.h>
-#include <limits.h>
-
 #include "lttng-ust-abi.hpp"
 
+#include <limits.h>
+#include <sys/types.h>
+
 #ifndef LTTNG_UST_UUID_LEN
-#define LTTNG_UST_UUID_LEN     16
+#define LTTNG_UST_UUID_LEN 16
 #endif
 
 /* Default unix socket path */
-#define LTTNG_UST_SOCK_FILENAME                                        \
-       "lttng-ust-sock-"                                       \
-       __ust_stringify(LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE)
+#define LTTNG_UST_SOCK_FILENAME \
+       "lttng-ust-sock-" __ust_stringify(LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE)
 
 /*
  * Shared memory files path are automatically related to shm root, e.g.
  * /dev/shm under linux.
  */
-#define LTTNG_UST_WAIT_FILENAME                                        \
-       "lttng-ust-wait-"                                       \
-       __ust_stringify(LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE)
+#define LTTNG_UST_WAIT_FILENAME \
+       "lttng-ust-wait-" __ust_stringify(LTTNG_UST_ABI_MAJOR_VERSION_OLDEST_COMPATIBLE)
 
 struct lttng_ust_shm_handle;
 struct lttng_ust_lib_ring_buffer;
 
 struct lttng_ust_ctl_consumer_channel_attr {
        enum lttng_ust_abi_chan_type type;
-       uint64_t subbuf_size;                   /* bytes */
-       uint64_t num_subbuf;                    /* power of 2 */
-       int overwrite;                          /* 1: overwrite, 0: discard */
-       unsigned int switch_timer_interval;     /* usec */
-       unsigned int read_timer_interval;       /* usec */
-       enum lttng_ust_abi_output output;       /* splice, mmap */
-       uint32_t chan_id;                       /* channel ID */
+       uint64_t subbuf_size; /* bytes */
+       uint64_t num_subbuf; /* power of 2 */
+       int overwrite; /* 1: overwrite, 0: discard */
+       unsigned int switch_timer_interval; /* usec */
+       unsigned int read_timer_interval; /* usec */
+       enum lttng_ust_abi_output output; /* splice, mmap */
+       uint32_t chan_id; /* channel ID */
        unsigned char uuid[LTTNG_UST_UUID_LEN]; /* Trace session unique ID */
-       int64_t blocking_timeout;                       /* Blocking timeout (usec) */
+       int64_t blocking_timeout; /* Blocking timeout (usec) */
 } LTTNG_PACKED;
 
 /*
@@ -69,18 +67,23 @@ struct lttng_ust_context_attr {
  */
 int lttng_ust_ctl_register_done(int sock);
 int lttng_ust_ctl_create_session(int sock);
-int lttng_ust_ctl_create_event(int sock, struct lttng_ust_abi_event *ev,
-               struct lttng_ust_abi_object_data *channel_data,
-               struct lttng_ust_abi_object_data **event_data);
-int lttng_ust_ctl_add_context(int sock, struct lttng_ust_context_attr *ctx,
-               struct lttng_ust_abi_object_data *obj_data,
-               struct lttng_ust_abi_object_data **context_data);
-int lttng_ust_ctl_set_filter(int sock, struct lttng_ust_abi_filter_bytecode *bytecode,
-               struct lttng_ust_abi_object_data *obj_data);
-int lttng_ust_ctl_set_capture(int sock, struct lttng_ust_abi_capture_bytecode *bytecode,
-               struct lttng_ust_abi_object_data *obj_data);
-int lttng_ust_ctl_set_exclusion(int sock, struct lttng_ust_abi_event_exclusion *exclusion,
-               struct lttng_ust_abi_object_data *obj_data);
+int lttng_ust_ctl_create_event(int sock,
+                              struct lttng_ust_abi_event *ev,
+                              struct lttng_ust_abi_object_data *channel_data,
+                              struct lttng_ust_abi_object_data **event_data);
+int lttng_ust_ctl_add_context(int sock,
+                             struct lttng_ust_context_attr *ctx,
+                             struct lttng_ust_abi_object_data *obj_data,
+                             struct lttng_ust_abi_object_data **context_data);
+int lttng_ust_ctl_set_filter(int sock,
+                            struct lttng_ust_abi_filter_bytecode *bytecode,
+                            struct lttng_ust_abi_object_data *obj_data);
+int lttng_ust_ctl_set_capture(int sock,
+                             struct lttng_ust_abi_capture_bytecode *bytecode,
+                             struct lttng_ust_abi_object_data *obj_data);
+int lttng_ust_ctl_set_exclusion(int sock,
+                               struct lttng_ust_abi_event_exclusion *exclusion,
+                               struct lttng_ust_abi_object_data *obj_data);
 
 int lttng_ust_ctl_enable(int sock, struct lttng_ust_abi_object_data *object);
 int lttng_ust_ctl_disable(int sock, struct lttng_ust_abi_object_data *object);
@@ -94,8 +97,8 @@ int lttng_ust_ctl_stop_session(int sock, int handle);
  * of that group is fired. It returns a handle to be used when creating event
  * notifier in that group.
  */
-int lttng_ust_ctl_create_event_notifier_group(int sock, int pipe_fd,
-               struct lttng_ust_abi_object_data **event_notifier_group);
+int lttng_ust_ctl_create_event_notifier_group(
+       int sock, int pipe_fd, struct lttng_ust_abi_object_data **event_notifier_group);
 
 /*
  * lttng_ust_ctl_create_event notifier creates a event notifier in a event notifier
@@ -105,9 +108,9 @@ int lttng_ust_ctl_create_event_notifier_group(int sock, int pipe_fd,
  * notifier.
  */
 int lttng_ust_ctl_create_event_notifier(int sock,
-               struct lttng_ust_abi_event_notifier *event_notifier,
-               struct lttng_ust_abi_object_data *event_notifier_group,
-               struct lttng_ust_abi_object_data **event_notifier_data);
+                                       struct lttng_ust_abi_event_notifier *event_notifier,
+                                       struct lttng_ust_abi_object_data *event_notifier_group,
+                                       struct lttng_ust_abi_object_data **event_notifier_data);
 
 /*
  * lttng_ust_ctl_tracepoint_list returns a tracepoint list handle, or negative
@@ -120,8 +123,9 @@ int lttng_ust_ctl_tracepoint_list(int sock);
  * handle. End is iteration is reached when -LTTNG_UST_ERR_NOENT is
  * returned.
  */
-int lttng_ust_ctl_tracepoint_list_get(int sock, int tp_list_handle,
-               struct lttng_ust_abi_tracepoint_iter *iter);
+int lttng_ust_ctl_tracepoint_list_get(int sock,
+                                     int tp_list_handle,
+                                     struct lttng_ust_abi_tracepoint_iter *iter);
 
 /*
  * lttng_ust_ctl_tracepoint_field_list returns a tracepoint field list handle,
@@ -134,8 +138,9 @@ int lttng_ust_ctl_tracepoint_field_list(int sock);
  * list handle. End is iteration is reached when -LTTNG_UST_ERR_NOENT is
  * returned.
  */
-int lttng_ust_ctl_tracepoint_field_list_get(int sock, int tp_field_list_handle,
-               struct lttng_ust_abi_field_iter *iter);
+int lttng_ust_ctl_tracepoint_field_list_get(int sock,
+                                           int tp_field_list_handle,
+                                           struct lttng_ust_abi_field_iter *iter);
 
 int lttng_ust_ctl_tracer_version(int sock, struct lttng_ust_abi_tracer_version *v);
 int lttng_ust_ctl_wait_quiescent(int sock);
@@ -150,14 +155,15 @@ int lttng_ust_ctl_release_object(int sock, struct lttng_ust_abi_object_data *dat
 int lttng_ust_ctl_release_handle(int sock, int handle);
 
 int lttng_ust_ctl_recv_channel_from_consumer(int sock,
-               struct lttng_ust_abi_object_data **channel_data);
+                                            struct lttng_ust_abi_object_data **channel_data);
 int lttng_ust_ctl_recv_stream_from_consumer(int sock,
-               struct lttng_ust_abi_object_data **stream_data);
-int lttng_ust_ctl_send_channel_to_ust(int sock, int session_handle,
-               struct lttng_ust_abi_object_data *channel_data);
+                                           struct lttng_ust_abi_object_data **stream_data);
+int lttng_ust_ctl_send_channel_to_ust(int sock,
+                                     int session_handle,
+                                     struct lttng_ust_abi_object_data *channel_data);
 int lttng_ust_ctl_send_stream_to_ust(int sock,
-               struct lttng_ust_abi_object_data *channel_data,
-               struct lttng_ust_abi_object_data *stream_data);
+                                    struct lttng_ust_abi_object_data *channel_data,
+                                    struct lttng_ust_abi_object_data *stream_data);
 
 /*
  * lttng_ust_ctl_duplicate_ust_object_data allocated a new object in "dest" if
@@ -165,7 +171,7 @@ int lttng_ust_ctl_send_stream_to_ust(int sock,
  * lttng_ust_ctl_release_object() and then freed with free().
  */
 int lttng_ust_ctl_duplicate_ust_object_data(struct lttng_ust_abi_object_data **dest,
-               struct lttng_ust_abi_object_data *src);
+                                           struct lttng_ust_abi_object_data *src);
 
 /*
  * API used by consumer.
@@ -175,11 +181,10 @@ struct lttng_ust_ctl_consumer_channel;
 struct lttng_ust_ctl_consumer_stream;
 struct lttng_ust_ctl_consumer_channel_attr;
 
-int lttng_ust_ctl_get_nr_stream_per_channel(void);
+int lttng_ust_ctl_get_nr_stream_per_channel();
 
-struct lttng_ust_ctl_consumer_channel *
-       lttng_ust_ctl_create_channel(struct lttng_ust_ctl_consumer_channel_attr *attr,
-               const int *stream_fds, int nr_stream_fds);
+struct lttng_ust_ctl_consumer_channel *lttng_ust_ctl_create_channel(
+       struct lttng_ust_ctl_consumer_channel_attr *attr, const int *stream_fds, int nr_stream_fds);
 /*
  * Each stream created needs to be destroyed before calling
  * lttng_ust_ctl_destroy_channel().
@@ -187,27 +192,25 @@ struct lttng_ust_ctl_consumer_channel *
 void lttng_ust_ctl_destroy_channel(struct lttng_ust_ctl_consumer_channel *chan);
 
 int lttng_ust_ctl_send_channel_to_sessiond(int sock,
-               struct lttng_ust_ctl_consumer_channel *channel);
+                                          struct lttng_ust_ctl_consumer_channel *channel);
 int lttng_ust_ctl_channel_close_wait_fd(struct lttng_ust_ctl_consumer_channel *consumer_chan);
 int lttng_ust_ctl_channel_close_wakeup_fd(struct lttng_ust_ctl_consumer_channel *consumer_chan);
 int lttng_ust_ctl_channel_get_wait_fd(struct lttng_ust_ctl_consumer_channel *consumer_chan);
 int lttng_ust_ctl_channel_get_wakeup_fd(struct lttng_ust_ctl_consumer_channel *consumer_chan);
 
-int lttng_ust_ctl_write_metadata_to_channel(
-               struct lttng_ust_ctl_consumer_channel *channel,
-               const char *metadata_str,       /* NOT null-terminated */
-               size_t len);                    /* metadata length */
-ssize_t lttng_ust_ctl_write_one_packet_to_channel(
-               struct lttng_ust_ctl_consumer_channel *channel,
-               const char *metadata_str,       /* NOT null-terminated */
-               size_t len);                    /* metadata length */
+int lttng_ust_ctl_write_metadata_to_channel(struct lttng_ust_ctl_consumer_channel *channel,
+                                           const char *metadata_str, /* NOT null-terminated */
+                                           size_t len); /* metadata length */
+ssize_t lttng_ust_ctl_write_one_packet_to_channel(struct lttng_ust_ctl_consumer_channel *channel,
+                                                 const char *metadata_str, /* NOT null-terminated
+                                                                            */
+                                                 size_t len); /* metadata length */
 
 /*
  * Send a NULL stream to finish iteration over all streams of a given
  * channel.
  */
-int lttng_ust_ctl_send_stream_to_sessiond(int sock,
-               struct lttng_ust_ctl_consumer_stream *stream);
+int lttng_ust_ctl_send_stream_to_sessiond(int sock, struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_stream_close_wait_fd(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_stream_close_wakeup_fd(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_stream_get_wait_fd(struct lttng_ust_ctl_consumer_stream *stream);
@@ -215,15 +218,13 @@ int lttng_ust_ctl_stream_get_wakeup_fd(struct lttng_ust_ctl_consumer_stream *str
 
 /* Create/destroy stream buffers for read */
 struct lttng_ust_ctl_consumer_stream *
-       lttng_ust_ctl_create_stream(struct lttng_ust_ctl_consumer_channel *channel,
-                       int cpu);
+lttng_ust_ctl_create_stream(struct lttng_ust_ctl_consumer_channel *channel, int cpu);
 void lttng_ust_ctl_destroy_stream(struct lttng_ust_ctl_consumer_stream *stream);
 
 /* For mmap mode, readable without "get" operation */
-int lttng_ust_ctl_get_mmap_len(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *len);
+int lttng_ust_ctl_get_mmap_len(struct lttng_ust_ctl_consumer_stream *stream, unsigned long *len);
 int lttng_ust_ctl_get_max_subbuf_size(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *len);
+                                     unsigned long *len);
 
 /*
  * For mmap mode, operate on the current packet (between get/put or
@@ -231,11 +232,10 @@ int lttng_ust_ctl_get_max_subbuf_size(struct lttng_ust_ctl_consumer_stream *stre
  */
 void *lttng_ust_ctl_get_mmap_base(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_get_mmap_read_offset(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *off);
-int lttng_ust_ctl_get_subbuf_size(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *len);
+                                      unsigned long *off);
+int lttng_ust_ctl_get_subbuf_size(struct lttng_ust_ctl_consumer_stream *stream, unsigned long *len);
 int lttng_ust_ctl_get_padded_subbuf_size(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *len);
+                                        unsigned long *len);
 int lttng_ust_ctl_get_next_subbuf(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_put_next_subbuf(struct lttng_ust_ctl_consumer_stream *stream);
 
@@ -244,15 +244,13 @@ int lttng_ust_ctl_put_next_subbuf(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_snapshot(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_snapshot_sample_positions(struct lttng_ust_ctl_consumer_stream *stream);
 int lttng_ust_ctl_snapshot_get_consumed(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *pos);
+                                       unsigned long *pos);
 int lttng_ust_ctl_snapshot_get_produced(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *pos);
-int lttng_ust_ctl_get_subbuf(struct lttng_ust_ctl_consumer_stream *stream,
-               unsigned long *pos);
+                                       unsigned long *pos);
+int lttng_ust_ctl_get_subbuf(struct lttng_ust_ctl_consumer_stream *stream, unsigned long *pos);
 int lttng_ust_ctl_put_subbuf(struct lttng_ust_ctl_consumer_stream *stream);
 
-int lttng_ust_ctl_flush_buffer(struct lttng_ust_ctl_consumer_stream *stream,
-               int producer_active);
+int lttng_ust_ctl_flush_buffer(struct lttng_ust_ctl_consumer_stream *stream, int producer_active);
 int lttng_ust_ctl_clear_buffer(struct lttng_ust_ctl_consumer_stream *stream);
 
 /* index */
@@ -263,37 +261,33 @@ int lttng_ust_ctl_clear_buffer(struct lttng_ust_ctl_consumer_stream *stream);
  */
 
 int lttng_ust_ctl_get_timestamp_begin(struct lttng_ust_ctl_consumer_stream *stream,
-               uint64_t *timestamp_begin);
+                                     uint64_t *timestamp_begin);
 int lttng_ust_ctl_get_timestamp_end(struct lttng_ust_ctl_consumer_stream *stream,
-       uint64_t *timestamp_end);
+                                   uint64_t *timestamp_end);
 int lttng_ust_ctl_get_events_discarded(struct lttng_ust_ctl_consumer_stream *stream,
-       uint64_t *events_discarded);
+                                      uint64_t *events_discarded);
 int lttng_ust_ctl_get_content_size(struct lttng_ust_ctl_consumer_stream *stream,
-       uint64_t *content_size);
+                                  uint64_t *content_size);
 int lttng_ust_ctl_get_packet_size(struct lttng_ust_ctl_consumer_stream *stream,
-       uint64_t *packet_size);
-int lttng_ust_ctl_get_sequence_number(struct lttng_ust_ctl_consumer_stream *stream,
-               uint64_t *seq);
+                                 uint64_t *packet_size);
+int lttng_ust_ctl_get_sequence_number(struct lttng_ust_ctl_consumer_stream *stream, uint64_t *seq);
 
 /*
  * Getter returning state invariant for the stream, which can be used
  * without "get" operation.
  */
 
-int lttng_ust_ctl_get_stream_id(struct lttng_ust_ctl_consumer_stream *stream,
-               uint64_t *stream_id);
-int lttng_ust_ctl_get_instance_id(struct lttng_ust_ctl_consumer_stream *stream,
-               uint64_t *id);
+int lttng_ust_ctl_get_stream_id(struct lttng_ust_ctl_consumer_stream *stream, uint64_t *stream_id);
+int lttng_ust_ctl_get_instance_id(struct lttng_ust_ctl_consumer_stream *stream, uint64_t *id);
 
 /*
  * Getter returning the current timestamp as perceived from the
  * tracer.
  */
-int lttng_ust_ctl_get_current_timestamp(struct lttng_ust_ctl_consumer_stream *stream,
-               uint64_t *ts);
+int lttng_ust_ctl_get_current_timestamp(struct lttng_ust_ctl_consumer_stream *stream, uint64_t *ts);
 
 /* returns whether UST has perf counters support. */
-int lttng_ust_ctl_has_perf_counters(void);
+int lttng_ust_ctl_has_perf_counters();
 
 /* Regenerate the statedump. */
 int lttng_ust_ctl_regenerate_statedump(int sock, int handle);
@@ -321,13 +315,13 @@ enum lttng_ust_ctl_channel_header {
 
 enum lttng_ust_ctl_abstract_types {
        lttng_ust_ctl_atype_integer,
-       lttng_ust_ctl_atype_enum,       /* legacy */
-       lttng_ust_ctl_atype_array,      /* legacy */
-       lttng_ust_ctl_atype_sequence,   /* legacy */
+       lttng_ust_ctl_atype_enum, /* legacy */
+       lttng_ust_ctl_atype_array, /* legacy */
+       lttng_ust_ctl_atype_sequence, /* legacy */
        lttng_ust_ctl_atype_string,
        lttng_ust_ctl_atype_float,
-       lttng_ust_ctl_atype_variant,    /* legacy */
-       lttng_ust_ctl_atype_struct,     /* legacy */
+       lttng_ust_ctl_atype_variant, /* legacy */
+       lttng_ust_ctl_atype_struct, /* legacy */
        lttng_ust_ctl_atype_enum_nestable,
        lttng_ust_ctl_atype_array_nestable,
        lttng_ust_ctl_atype_sequence_nestable,
@@ -343,27 +337,27 @@ enum lttng_ust_ctl_string_encodings {
        NR_LTTNG_UST_CTL_STRING_ENCODINGS,
 };
 
-#define LTTNG_UST_CTL_UST_INTEGER_TYPE_PADDING 24
+#define LTTNG_UST_CTL_UST_INTEGER_TYPE_PADDING 24
 struct lttng_ust_ctl_integer_type {
-       uint32_t size;          /* in bits */
+       uint32_t size; /* in bits */
        uint32_t signedness;
        uint32_t reverse_byte_order;
-       uint32_t base;          /* 2, 8, 10, 16, for pretty print */
-       int32_t encoding;       /* enum lttng_ust_ctl_string_encodings */
-       uint16_t alignment;     /* in bits */
+       uint32_t base; /* 2, 8, 10, 16, for pretty print */
+       int32_t encoding; /* enum lttng_ust_ctl_string_encodings */
+       uint16_t alignment; /* in bits */
        char padding[LTTNG_UST_CTL_UST_INTEGER_TYPE_PADDING];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_CTL_UST_FLOAT_TYPE_PADDING   24
+#define LTTNG_UST_CTL_UST_FLOAT_TYPE_PADDING 24
 struct lttng_ust_ctl_float_type {
-       uint32_t exp_dig;               /* exponent digits, in bits */
-       uint32_t mant_dig;              /* mantissa digits, in bits */
+       uint32_t exp_dig; /* exponent digits, in bits */
+       uint32_t mant_dig; /* mantissa digits, in bits */
        uint32_t reverse_byte_order;
-       uint16_t alignment;     /* in bits */
+       uint16_t alignment; /* in bits */
        char padding[LTTNG_UST_CTL_UST_FLOAT_TYPE_PADDING];
 } LTTNG_PACKED;
 
-#define LTTNG_UST_CTL_UST_ENUM_VALUE_PADDING   15
+#define LTTNG_UST_CTL_UST_ENUM_VALUE_PADDING 15
 struct lttng_ust_ctl_enum_value {
        uint64_t value;
        uint8_t signedness;
@@ -374,7 +368,7 @@ enum lttng_ust_ctl_ust_enum_entry_options {
        LTTNG_UST_CTL_UST_ENUM_ENTRY_OPTION_IS_AUTO = 1U << 0,
 };
 
-#define LTTNG_UST_CTL_UST_ENUM_ENTRY_PADDING   32
+#define LTTNG_UST_CTL_UST_ENUM_ENTRY_PADDING 32
 struct lttng_ust_ctl_enum_entry {
        struct lttng_ust_ctl_enum_value start, end; /* start and end are inclusive */
        char string[LTTNG_UST_ABI_SYM_NAME_LEN];
@@ -387,16 +381,16 @@ struct lttng_ust_ctl_enum_entry {
 } LTTNG_PACKED;
 
 /* legacy */
-#define LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING   296
+#define LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING 296
 union _lttng_ust_ctl_basic_type {
        struct lttng_ust_ctl_integer_type integer;
        struct {
                char name[LTTNG_UST_ABI_SYM_NAME_LEN];
                struct lttng_ust_ctl_integer_type container_type;
-               uint64_t id;    /* enum ID in sessiond. */
+               uint64_t id; /* enum ID in sessiond. */
        } enumeration;
        struct {
-               int32_t encoding;       /* enum lttng_ust_ctl_string_encodings */
+               int32_t encoding; /* enum lttng_ust_ctl_string_encodings */
        } string;
        struct lttng_ust_ctl_float_type _float;
        char padding[LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING];
@@ -414,28 +408,28 @@ struct lttng_ust_ctl_basic_type {
  * Padding is derived from largest member: u.legacy.sequence which
  * contains two basic types, each with LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING.
  */
-#define LTTNG_UST_CTL_UST_TYPE_PADDING (2 * LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING)
+#define LTTNG_UST_CTL_UST_TYPE_PADDING (2 * LTTNG_UST_CTL_UST_BASIC_TYPE_PADDING)
 struct lttng_ust_ctl_type {
        enum lttng_ust_ctl_abstract_types atype;
        union {
                struct lttng_ust_ctl_integer_type integer;
                struct lttng_ust_ctl_float_type _float;
                struct {
-                       int32_t encoding;       /* enum lttng_ust_ctl_string_encodings */
+                       int32_t encoding; /* enum lttng_ust_ctl_string_encodings */
                } string;
                struct {
                        char name[LTTNG_UST_ABI_SYM_NAME_LEN];
-                       uint64_t id;    /* enum ID in sessiond. */
+                       uint64_t id; /* enum ID in sessiond. */
                        /* container_type follows after this struct lttng_ust_ctl_field. */
                } enum_nestable;
                struct {
-                       uint32_t length;                /* num. elems. */
+                       uint32_t length; /* num. elems. */
                        uint32_t alignment;
                        /* elem_type follows after this struct lttng_ust_ctl_field. */
                } array_nestable;
                struct {
                        char length_name[LTTNG_UST_ABI_SYM_NAME_LEN];
-                       uint32_t alignment;             /* Alignment before elements. */
+                       uint32_t alignment; /* Alignment before elements. */
                        /* elem_type follows after the length_type. */
                } sequence_nestable;
                struct {
@@ -455,7 +449,7 @@ struct lttng_ust_ctl_type {
                        union _lttng_ust_ctl_basic_type basic;
                        struct {
                                struct lttng_ust_ctl_basic_type elem_type;
-                               uint32_t length;                /* num. elems. */
+                               uint32_t length; /* num. elems. */
                        } array;
                        struct {
                                struct lttng_ust_ctl_basic_type length_type;
@@ -475,7 +469,7 @@ struct lttng_ust_ctl_type {
        } u;
 } LTTNG_PACKED;
 
-#define LTTNG_UST_CTL_UST_FIELD_PADDING        28
+#define LTTNG_UST_CTL_UST_FIELD_PADDING 28
 struct lttng_ust_ctl_field {
        char name[LTTNG_UST_ABI_SYM_NAME_LEN];
        struct lttng_ust_ctl_type type;
@@ -488,21 +482,21 @@ struct lttng_ust_ctl_field {
  * the output fields are not populated.
  */
 int lttng_ust_ctl_recv_reg_msg(int sock,
-       enum lttng_ust_ctl_socket_type *type,
-       uint32_t *major,
-       uint32_t *minor,
-       uint32_t *pid,
-       uint32_t *ppid,
-       uint32_t *uid,
-       uint32_t *gid,
-       uint32_t *bits_per_long,
-       uint32_t *uint8_t_alignment,
-       uint32_t *uint16_t_alignment,
-       uint32_t *uint32_t_alignment,
-       uint32_t *uint64_t_alignment,
-       uint32_t *long_alignment,
-       int *byte_order,
-       char *name);    /* size LTTNG_UST_ABI_PROCNAME_LEN */
+                              enum lttng_ust_ctl_socket_type *type,
+                              uint32_t *major,
+                              uint32_t *minor,
+                              uint32_t *pid,
+                              uint32_t *ppid,
+                              uint32_t *uid,
+                              uint32_t *gid,
+                              uint32_t *bits_per_long,
+                              uint32_t *uint8_t_alignment,
+                              uint32_t *uint16_t_alignment,
+                              uint32_t *uint32_t_alignment,
+                              uint32_t *uint64_t_alignment,
+                              uint32_t *long_alignment,
+                              int *byte_order,
+                              char *name); /* size LTTNG_UST_ABI_PROCNAME_LEN */
 
 /*
  * Returns 0 on success, negative UST or system error value on error.
@@ -517,63 +511,63 @@ int lttng_ust_ctl_recv_notify(int sock, enum lttng_ust_ctl_notify_cmd *notify_cm
  * Returns 0 on success, negative UST or system error value on error.
  */
 int lttng_ust_ctl_recv_register_event(int sock,
-       int *session_objd,              /* session descriptor (output) */
-       int *channel_objd,              /* channel descriptor (output) */
-       char *event_name,               /*
-                                        * event name (output,
-                                        * size LTTNG_UST_ABI_SYM_NAME_LEN)
-                                        */
-       int *loglevel,
-       char **signature,               /*
-                                        * event signature
-                                        * (output, dynamically
-                                        * allocated, must be free(3)'d
-                                        * by the caller if function
-                                        * returns success.)
-                                        */
-       size_t *nr_fields,
-       struct lttng_ust_ctl_field **fields,
-       char **model_emf_uri);
+                                     int *session_objd, /* session descriptor (output) */
+                                     int *channel_objd, /* channel descriptor (output) */
+                                     char *event_name, /*
+                                                        * event name (output,
+                                                        * size LTTNG_UST_ABI_SYM_NAME_LEN)
+                                                        */
+                                     int *loglevel,
+                                     char **signature, /*
+                                                        * event signature
+                                                        * (output, dynamically
+                                                        * allocated, must be free(3)'d
+                                                        * by the caller if function
+                                                        * returns success.)
+                                                        */
+                                     size_t *nr_fields,
+                                     struct lttng_ust_ctl_field **fields,
+                                     char **model_emf_uri);
 
 /*
  * Returns 0 on success, negative error value on error.
  */
 int lttng_ust_ctl_reply_register_event(int sock,
-       uint32_t id,                    /* event id (input) */
-       int ret_code);                  /* return code. 0 ok, negative error */
+                                      uint32_t id, /* event id (input) */
+                                      int ret_code); /* return code. 0 ok, negative error */
 
 /*
  * Returns 0 on success, negative UST or system error value on error.
  */
 int lttng_ust_ctl_recv_register_enum(int sock,
-       int *session_objd,
-       char *enum_name,
-       struct lttng_ust_ctl_enum_entry **entries,
-       size_t *nr_entries);
+                                    int *session_objd,
+                                    char *enum_name,
+                                    struct lttng_ust_ctl_enum_entry **entries,
+                                    size_t *nr_entries);
 
 /*
  * Returns 0 on success, negative error value on error.
  */
 int lttng_ust_ctl_reply_register_enum(int sock,
-       uint64_t id,                    /* enum id (input) */
-       int ret_code);
+                                     uint64_t id, /* enum id (input) */
+                                     int ret_code);
 
 /*
  * Returns 0 on success, negative UST or system error value on error.
  */
 int lttng_ust_ctl_recv_register_channel(int sock,
-       int *session_objd,              /* session descriptor (output) */
-       int *channel_objd,              /* channel descriptor (output) */
-       size_t *nr_fields,              /* context fields */
-       struct lttng_ust_ctl_field **fields);
+                                       int *session_objd, /* session descriptor (output) */
+                                       int *channel_objd, /* channel descriptor (output) */
+                                       size_t *nr_fields, /* context fields */
+                                       struct lttng_ust_ctl_field **fields);
 
 /*
  * Returns 0 on success, negative error value on error.
  */
 int lttng_ust_ctl_reply_register_channel(int sock,
-       uint32_t chan_id,
-       enum lttng_ust_ctl_channel_header header_type,
-       int ret_code);                  /* return code. 0 ok, negative error */
+                                        uint32_t chan_id,
+                                        enum lttng_ust_ctl_channel_header header_type,
+                                        int ret_code); /* return code. 0 ok, negative error */
 
 /*
  * Counter API.
@@ -585,8 +579,8 @@ enum lttng_ust_ctl_counter_bitness {
 };
 
 enum lttng_ust_ctl_counter_arithmetic {
-       LTTNG_UST_CTL_COUNTER_ARITHMETIC_MODULAR        = 0,
-       LTTNG_UST_CTL_COUNTER_ARITHMETIC_SATURATION     = 1,
+       LTTNG_UST_CTL_COUNTER_ARITHMETIC_MODULAR = 0,
+       LTTNG_UST_CTL_COUNTER_ARITHMETIC_SATURATION = 1,
 };
 
 /* Used as alloc flags. */
@@ -597,7 +591,7 @@ enum lttng_ust_ctl_counter_alloc {
 
 struct lttng_ust_ctl_daemon_counter;
 
-int lttng_ust_ctl_get_nr_cpu_per_counter(void);
+int lttng_ust_ctl_get_nr_cpu_per_counter();
 
 struct lttng_ust_ctl_counter_dimension {
        uint64_t size;
@@ -608,24 +602,25 @@ struct lttng_ust_ctl_counter_dimension {
 };
 
 struct lttng_ust_ctl_daemon_counter *
-       lttng_ust_ctl_create_counter(size_t nr_dimensions,
-               const struct lttng_ust_ctl_counter_dimension *dimensions,
-               int64_t global_sum_step,
-               int global_counter_fd,
-               int nr_counter_cpu_fds,
-               const int *counter_cpu_fds,
-               enum lttng_ust_ctl_counter_bitness bitness,
-               enum lttng_ust_ctl_counter_arithmetic arithmetic,
-               uint32_t alloc_flags,
-               bool coalesce_hits);
+lttng_ust_ctl_create_counter(size_t nr_dimensions,
+                            const struct lttng_ust_ctl_counter_dimension *dimensions,
+                            int64_t global_sum_step,
+                            int global_counter_fd,
+                            int nr_counter_cpu_fds,
+                            const int *counter_cpu_fds,
+                            enum lttng_ust_ctl_counter_bitness bitness,
+                            enum lttng_ust_ctl_counter_arithmetic arithmetic,
+                            uint32_t alloc_flags,
+                            bool coalesce_hits);
 
 int lttng_ust_ctl_create_counter_data(struct lttng_ust_ctl_daemon_counter *counter,
-               struct lttng_ust_abi_object_data **counter_data);
+                                     struct lttng_ust_abi_object_data **counter_data);
 
 int lttng_ust_ctl_create_counter_global_data(struct lttng_ust_ctl_daemon_counter *counter,
-               struct lttng_ust_abi_object_data **counter_global_data);
-int lttng_ust_ctl_create_counter_cpu_data(struct lttng_ust_ctl_daemon_counter *counter, int cpu,
-               struct lttng_ust_abi_object_data **counter_cpu_data);
+                                            struct lttng_ust_abi_object_data **counter_global_data);
+int lttng_ust_ctl_create_counter_cpu_data(struct lttng_ust_ctl_daemon_counter *counter,
+                                         int cpu,
+                                         struct lttng_ust_abi_object_data **counter_cpu_data);
 
 /*
  * Each counter data and counter cpu data created need to be destroyed
@@ -633,25 +628,30 @@ int lttng_ust_ctl_create_counter_cpu_data(struct lttng_ust_ctl_daemon_counter *c
  */
 void lttng_ust_ctl_destroy_counter(struct lttng_ust_ctl_daemon_counter *counter);
 
-int lttng_ust_ctl_send_counter_data_to_ust(int sock, int parent_handle,
-               struct lttng_ust_abi_object_data *counter_data);
-int lttng_ust_ctl_send_counter_global_data_to_ust(int sock,
-               struct lttng_ust_abi_object_data *counter_data,
-               struct lttng_ust_abi_object_data *counter_global_data);
+int lttng_ust_ctl_send_counter_data_to_ust(int sock,
+                                          int parent_handle,
+                                          struct lttng_ust_abi_object_data *counter_data);
+int lttng_ust_ctl_send_counter_global_data_to_ust(
+       int sock,
+       struct lttng_ust_abi_object_data *counter_data,
+       struct lttng_ust_abi_object_data *counter_global_data);
 int lttng_ust_ctl_send_counter_cpu_data_to_ust(int sock,
-               struct lttng_ust_abi_object_data *counter_data,
-               struct lttng_ust_abi_object_data *counter_cpu_data);
+                                              struct lttng_ust_abi_object_data *counter_data,
+                                              struct lttng_ust_abi_object_data *counter_cpu_data);
 
 int lttng_ust_ctl_counter_read(struct lttng_ust_ctl_daemon_counter *counter,
-               const size_t *dimension_indexes,
-               int cpu, int64_t *value,
-               bool *overflow, bool *underflow);
+                              const size_t *dimension_indexes,
+                              int cpu,
+                              int64_t *value,
+                              bool *overflow,
+                              bool *underflow);
 int lttng_ust_ctl_counter_aggregate(struct lttng_ust_ctl_daemon_counter *counter,
-               const size_t *dimension_indexes,
-               int64_t *value,
-               bool *overflow, bool *underflow);
+                                   const size_t *dimension_indexes,
+                                   int64_t *value,
+                                   bool *overflow,
+                                   bool *underflow);
 int lttng_ust_ctl_counter_clear(struct lttng_ust_ctl_daemon_counter *counter,
-               const size_t *dimension_indexes);
+                               const size_t *dimension_indexes);
 
 void lttng_ust_ctl_sigbus_handle(void *addr);
 
index 1cf05f2e32f303307136c052ad2e564e9398c2a0..7e59d07542121b26a25efb28a70cf3ed511d0739 100644 (file)
  * These declarations should NOT be considered stable API.
  */
 
+#include "lttng-ust-abi.hpp"
+
 #include <limits.h>
 #include <unistd.h>
 
-#include "lttng-ust-abi.hpp"
-
 /*
  * ustcomm error code.
  */
 enum lttng_ust_error_code {
-       LTTNG_UST_OK = 0,                       /* Ok */
-       LTTNG_UST_ERR = 1024,                   /* Unknown Error */
-       LTTNG_UST_ERR_NOENT = 1025,             /* No entry */
-       LTTNG_UST_ERR_EXIST = 1026,             /* Object exists */
-       LTTNG_UST_ERR_INVAL = 1027,             /* Invalid argument */
-       LTTNG_UST_ERR_PERM  = 1028,             /* Permission denied */
-       LTTNG_UST_ERR_NOSYS = 1029,             /* Not implemented */
-       LTTNG_UST_ERR_EXITING = 1030,           /* Process is exiting */
-
-       LTTNG_UST_ERR_INVAL_MAGIC = 1031,       /* Invalid magic number */
-       LTTNG_UST_ERR_INVAL_SOCKET_TYPE = 1032, /* Invalid socket type */
-       LTTNG_UST_ERR_UNSUP_MAJOR = 1033,       /* Unsupported major version */
+       LTTNG_UST_OK = 0, /* Ok */
+       LTTNG_UST_ERR = 1024, /* Unknown Error */
+       LTTNG_UST_ERR_NOENT = 1025, /* No entry */
+       LTTNG_UST_ERR_EXIST = 1026, /* Object exists */
+       LTTNG_UST_ERR_INVAL = 1027, /* Invalid argument */
+       LTTNG_UST_ERR_PERM = 1028, /* Permission denied */
+       LTTNG_UST_ERR_NOSYS = 1029, /* Not implemented */
+       LTTNG_UST_ERR_EXITING = 1030, /* Process is exiting */
+
+       LTTNG_UST_ERR_INVAL_MAGIC = 1031, /* Invalid magic number */
+       LTTNG_UST_ERR_INVAL_SOCKET_TYPE = 1032, /* Invalid socket type */
+       LTTNG_UST_ERR_UNSUP_MAJOR = 1033, /* Unsupported major version */
 
        /* MUST be last element */
-       LTTNG_UST_ERR_NR,                       /* Last element */
+       LTTNG_UST_ERR_NR, /* Last element */
 };
 
 /*
@@ -46,4 +46,4 @@ enum lttng_ust_error_code {
  */
 extern const char *lttng_ust_strerror(int code);
 
-#endif /* _LTTNG_UST_ERROR_H */
+#endif /* _LTTNG_UST_ERROR_H */
index 89f000128214e6720e4ebe1e027d5348cb42bc11..b51ba7bfc2c7e55ea4749b0e2d41807a7a33deed 100644 (file)
@@ -7,14 +7,25 @@
 
 #include "ust-field-convert.hpp"
 
+#include <common/exception.hpp>
 #include <common/make-unique.hpp>
 
 #include <unordered_map>
+#include <utility>
 
 namespace lst = lttng::sessiond::trace;
 namespace lsu = lttng::sessiond::ust;
-namespace {
 
+/*
+ * fmtlib helper that must be under the same namespace as lttng_ust_ctl_abstract_types
+ * (global).
+ */
+static int format_as(lttng_ust_ctl_abstract_types type)
+{
+       return fmt::underlying(type);
+}
+
+namespace {
 /*
  * Type enclosing the session information that may be required during the decoding
  * of the lttng_ust_ctl_field array provided by applications on registration of
@@ -23,12 +34,13 @@ namespace {
 class session_attributes {
 public:
        using registry_enum_getter_fn =
-                       std::function<lsu::registry_enum::const_rcu_protected_reference(
-                                       const char *name, uint64_t id)>;
+               std::function<lsu::registry_enum::const_rcu_protected_reference(const char *name,
+                                                                               uint64_t id)>;
 
        session_attributes(registry_enum_getter_fn reg_enum_getter,
-                       lst::byte_order native_trace_byte_order) :
-               get_registry_enum{reg_enum_getter}, _native_trace_byte_order{native_trace_byte_order}
+                          lst::byte_order native_trace_byte_order) :
+               get_registry_enum{ std::move(reg_enum_getter) },
+               _native_trace_byte_order{ native_trace_byte_order }
        {
        }
 
@@ -37,36 +49,50 @@ public:
 };
 
 /* Used to publish fields on which a field being decoded has an implicit dependency. */
-using publish_field_fn = std::function<void(lst::field::cuptr)>;
-
-lst::type::cuptr create_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field);
+using publish_field_fn = std::function<void(lst::field::uptr)>;
+
+/* Look-up field from a field location. */
+using lookup_field_fn = std::function<const lst::field&(const lst::field_location&)>;
+
+lst::type::cuptr
+create_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                               const lttng_ust_ctl_field *end,
+                               const session_attributes& session_attributes,
+                               const lttng_ust_ctl_field **next_ust_ctl_field,
+                               const publish_field_fn& publish_field,
+                               const lookup_field_fn& lookup_field,
+                               lst::field_location::root lookup_root,
+                               lst::field_location::elements& current_field_location_elements,
+                               lsu::ctl_field_quirks quirks);
 
 void create_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field);
+                                     const lttng_ust_ctl_field *end,
+                                     const session_attributes& session_attributes,
+                                     const lttng_ust_ctl_field **next_ust_ctl_field,
+                                     const publish_field_fn& publish_field,
+                                     const lookup_field_fn& lookup_field,
+                                     lst::field_location::root lookup_root,
+                                     lst::field_location::elements& current_field_location_elements,
+                                     lsu::ctl_field_quirks quirks);
 
 template <class UstCtlEncodingType>
-enum lst::null_terminated_string_type::encoding ust_ctl_encoding_to_string_field_encoding(UstCtlEncodingType encoding)
+enum lst::null_terminated_string_type::encoding
+ust_ctl_encoding_to_string_field_encoding(UstCtlEncodingType encoding)
 {
-       static const std::unordered_map<UstCtlEncodingType, enum lst::null_terminated_string_type::encoding>
-                       encoding_conversion_map = {
-                                       {(UstCtlEncodingType) lttng_ust_ctl_encode_ASCII,
-                                                       lst::null_terminated_string_type::encoding::ASCII},
-                                       {(UstCtlEncodingType) lttng_ust_ctl_encode_UTF8,
-                                                       lst::null_terminated_string_type::encoding::UTF8},
-                       };
+       static const std::unordered_map<UstCtlEncodingType,
+                                       enum lst::null_terminated_string_type::encoding>
+               encoding_conversion_map = {
+                       { (UstCtlEncodingType) lttng_ust_ctl_encode_ASCII,
+                         lst::null_terminated_string_type::encoding::ASCII },
+                       { (UstCtlEncodingType) lttng_ust_ctl_encode_UTF8,
+                         lst::null_terminated_string_type::encoding::UTF8 },
+               };
 
        const auto encoding_it = encoding_conversion_map.find(encoding);
        if (encoding_it == encoding_conversion_map.end()) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unknown lttng_ust_ctl_string_encodings value `{}` encountered when decoding integer field",
-                               encoding));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unknown lttng_ust_ctl_string_encodings value `{}` encountered when decoding integer field",
+                       encoding));
        }
 
        return encoding_it->second;
@@ -76,103 +102,111 @@ template <class UstCtlBaseType>
 enum lst::integer_type::base ust_ctl_base_to_integer_field_base(UstCtlBaseType base)
 {
        static const std::unordered_map<UstCtlBaseType, enum lst::integer_type::base>
-                       base_conversion_map = {{2, lst::integer_type::base::BINARY},
-                                       {8, lst::integer_type::base::OCTAL},
-                                       {10, lst::integer_type::base::DECIMAL},
-                                       {16, lst::integer_type::base::HEXADECIMAL}};
+               base_conversion_map = { { 2, lst::integer_type::base::BINARY },
+                                       { 8, lst::integer_type::base::OCTAL },
+                                       { 10, lst::integer_type::base::DECIMAL },
+                                       { 16, lst::integer_type::base::HEXADECIMAL } };
 
        const auto base_it = base_conversion_map.find(base);
        if (base_it == base_conversion_map.end()) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unknown integer base value `{}` encountered when decoding integer field",
-                               base));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unknown integer base value `{}` encountered when decoding integer field",
+                       base));
        }
 
        return base_it->second;
 }
 
-lst::type::cuptr create_integer_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_integer_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                       const lttng_ust_ctl_field *end,
+                                       const session_attributes& session_attributes,
+                                       const lttng_ust_ctl_field **next_ust_ctl_field,
+                                       lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto base = ust_ctl_base_to_integer_field_base(current->type.u.integer.base);
        const auto signedness = current->type.u.integer.signedness ?
-                       lst::integer_type::signedness::SIGNED :
-                             lst::integer_type::signedness::UNSIGNED;
+               lst::integer_type::signedness::SIGNED :
+               lst::integer_type::signedness::UNSIGNED;
        const auto byte_order = current->type.u.integer.reverse_byte_order ?
-                       lst::type::reverse_byte_order(session_attributes._native_trace_byte_order) :
-                             session_attributes._native_trace_byte_order;
+               lst::type::reverse_byte_order(session_attributes._native_trace_byte_order) :
+               session_attributes._native_trace_byte_order;
 
        *next_ust_ctl_field = current + 1;
 
        return lttng::make_unique<const lst::integer_type>(current->type.u.integer.alignment,
-                       byte_order, current->type.u.integer.size, signedness, base);
+                                                          byte_order,
+                                                          current->type.u.integer.size,
+                                                          signedness,
+                                                          base);
 }
 
-lst::type::cuptr create_floating_point_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_floating_point_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                              const lttng_ust_ctl_field *end,
+                                              const session_attributes& session_attributes,
+                                              const lttng_ust_ctl_field **next_ust_ctl_field,
+                                              lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        *next_ust_ctl_field = current + 1;
 
        const auto byte_order = current->type.u._float.reverse_byte_order ?
-                       lst::type::reverse_byte_order(session_attributes._native_trace_byte_order) :
-                             session_attributes._native_trace_byte_order;
+               lst::type::reverse_byte_order(session_attributes._native_trace_byte_order) :
+               session_attributes._native_trace_byte_order;
 
        try {
                return lttng::make_unique<const lst::floating_point_type>(
-                               current->type.u._float.alignment, byte_order,
-                               current->type.u._float.exp_dig, current->type.u._float.mant_dig);
+                       current->type.u._float.alignment,
+                       byte_order,
+                       current->type.u._float.exp_dig,
+                       current->type.u._float.mant_dig);
        } catch (lttng::invalid_argument_error& ex) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format("Invalid floating point attribute in {}: {}",
-                               typeid(*current), ex.what()));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Invalid floating point attribute in {}: {}", typeid(*current), ex.what()));
        }
 }
 
-lst::type::cuptr create_enumeration_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_enumeration_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                           const lttng_ust_ctl_field *end,
+                                           const session_attributes& session_attributes,
+                                           const lttng_ust_ctl_field **next_ust_ctl_field,
+                                           lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        uint64_t enumeration_id;
        const auto& enum_uctl_field = *current;
        const char *enumeration_name;
        const auto *enum_container_uctl_type =
-                       &current->type.u.legacy.basic.enumeration.container_type;
+               &current->type.u.legacy.basic.enumeration.container_type;
 
        if (enum_uctl_field.type.atype == lttng_ust_ctl_atype_enum_nestable) {
                /* Nestable enumeration fields are followed by their container type. */
                ++current;
                if (current >= end) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Array of {} is too short to contain nestable enumeration's container",
-                                       typeid(*current)));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Array of {} is too short to contain nestable enumeration's container",
+                               typeid(*current)));
                }
 
                if (current->type.atype != lttng_ust_ctl_atype_integer) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Invalid type of nestable enum container: type id = {}",
-                                       current->type.atype));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Invalid type of nestable enum container: type id = {}",
+                               current->type.atype));
                }
 
                enum_container_uctl_type = &current->type.u.integer;
@@ -187,84 +221,88 @@ lst::type::cuptr create_enumeration_type_from_ust_ctl_fields(const lttng_ust_ctl
 
        const auto base = ust_ctl_base_to_integer_field_base(enum_container_uctl_type->base);
        const auto byte_order = enum_container_uctl_type->reverse_byte_order ?
-                       lst::integer_type::reverse_byte_order(
-                                       session_attributes._native_trace_byte_order) :
-                             session_attributes._native_trace_byte_order;
+               lst::integer_type::reverse_byte_order(session_attributes._native_trace_byte_order) :
+               session_attributes._native_trace_byte_order;
        const auto signedness = enum_container_uctl_type->signedness ?
-                       lst::integer_type::signedness::SIGNED :
-                             lst::integer_type::signedness::UNSIGNED;
+               lst::integer_type::signedness::SIGNED :
+               lst::integer_type::signedness::UNSIGNED;
 
-       if (enum_container_uctl_type->signedness) {
+       if (signedness == lst::integer_type::signedness::SIGNED) {
                const auto& enum_registry = static_cast<const lsu::registry_signed_enum&>(
-                               *session_attributes.get_registry_enum(
-                                               enumeration_name, enumeration_id));
+                       *session_attributes.get_registry_enum(enumeration_name, enumeration_id));
 
                return lttng::make_unique<const lst::signed_enumeration_type>(
-                               enum_container_uctl_type->alignment, byte_order,
-                               enum_container_uctl_type->size, signedness, base,
-                               enum_registry._mappings);
+                       enum_container_uctl_type->alignment,
+                       byte_order,
+                       enum_container_uctl_type->size,
+                       base,
+                       enum_registry._mappings);
        } else {
                const auto& enum_registry = static_cast<const lsu::registry_unsigned_enum&>(
-                               *session_attributes.get_registry_enum(
-                                               enumeration_name, enumeration_id));
+                       *session_attributes.get_registry_enum(enumeration_name, enumeration_id));
 
                return lttng::make_unique<const lst::unsigned_enumeration_type>(
-                               enum_container_uctl_type->alignment, byte_order,
-                               enum_container_uctl_type->size, signedness, base,
-                               enum_registry._mappings);
+                       enum_container_uctl_type->alignment,
+                       byte_order,
+                       enum_container_uctl_type->size,
+                       base,
+                       enum_registry._mappings);
        }
 }
 
-lst::type::cuptr create_string_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes __attribute__((unused)),
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_string_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                      const lttng_ust_ctl_field *end,
+                                      const session_attributes& session_attributes
+                                      __attribute__((unused)),
+                                      const lttng_ust_ctl_field **next_ust_ctl_field,
+                                      lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& string_uctl_field = *current;
        *next_ust_ctl_field = current + 1;
 
-       const auto encoding = ust_ctl_encoding_to_string_field_encoding(
-                       string_uctl_field.type.u.string.encoding);
+       const auto encoding =
+               ust_ctl_encoding_to_string_field_encoding(string_uctl_field.type.u.string.encoding);
 
        return lttng::make_unique<const lst::null_terminated_string_type>(1, encoding);
 }
 
-lst::type::cuptr create_integer_type_from_ust_ctl_basic_type(
-               const lttng_ust_ctl_basic_type& type, const session_attributes& session_attributes)
+lst::type::cuptr
+create_integer_type_from_ust_ctl_basic_type(const lttng_ust_ctl_basic_type& type,
+                                           const session_attributes& session_attributes)
 {
        /* Checked by caller. */
        LTTNG_ASSERT(type.atype == lttng_ust_ctl_atype_integer);
 
        const auto byte_order = type.u.basic.integer.reverse_byte_order ?
-                       lst::integer_type::reverse_byte_order(
-                                       session_attributes._native_trace_byte_order) :
-                             session_attributes._native_trace_byte_order;
+               lst::integer_type::reverse_byte_order(session_attributes._native_trace_byte_order) :
+               session_attributes._native_trace_byte_order;
        const auto signedness = type.u.basic.integer.signedness ?
-                       lst::integer_type::signedness::SIGNED :
-                             lst::integer_type::signedness::UNSIGNED;
+               lst::integer_type::signedness::SIGNED :
+               lst::integer_type::signedness::UNSIGNED;
        const auto base = ust_ctl_base_to_integer_field_base(type.u.basic.integer.base);
        const auto size = type.u.basic.integer.size;
        const auto alignment = type.u.basic.integer.alignment;
 
        return lttng::make_unique<const lst::integer_type>(
-                       alignment, byte_order, size, signedness, base);
+               alignment, byte_order, size, signedness, base);
 }
 
-lst::type::cuptr create_array_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_array_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                     const lttng_ust_ctl_field *end,
+                                     const session_attributes& session_attributes,
+                                     const lttng_ust_ctl_field **next_ust_ctl_field,
+                                     lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& array_uctl_field = *current;
@@ -277,51 +315,56 @@ lst::type::cuptr create_array_type_from_ust_ctl_fields(const lttng_ust_ctl_field
 
        const auto& element_uctl_type = array_uctl_field.type.u.legacy.array.elem_type;
        if (element_uctl_type.atype != lttng_ust_ctl_atype_integer) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unexpected legacy array element type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
-                               element_uctl_type.atype, lttng_ust_ctl_atype_integer));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unexpected legacy array element type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
+                       element_uctl_type.atype,
+                       lttng_ust_ctl_atype_integer));
        }
 
-       element_type = create_integer_type_from_ust_ctl_basic_type(
-                       element_uctl_type, session_attributes);
+       element_type =
+               create_integer_type_from_ust_ctl_basic_type(element_uctl_type, session_attributes);
        if (element_uctl_type.atype == lttng_ust_ctl_atype_integer &&
-                       element_uctl_type.u.basic.integer.encoding != lttng_ust_ctl_encode_none) {
+           element_uctl_type.u.basic.integer.encoding != lttng_ust_ctl_encode_none) {
                /* Element represents a text character. */
                element_encoding = ust_ctl_encoding_to_string_field_encoding(
-                               element_uctl_type.u.basic.integer.encoding);
+                       element_uctl_type.u.basic.integer.encoding);
        }
 
        *next_ust_ctl_field = current + 1;
 
        if (element_encoding) {
                const auto integer_element_size =
-                               static_cast<const lst::integer_type&>(*element_type).size;
+                       static_cast<const lst::integer_type&>(*element_type).size;
 
                if (integer_element_size != 8) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Unexpected legacy array element type: integer has encoding but size is not 8: size = {}",
-                                       integer_element_size));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Unexpected legacy array element type: integer has encoding but size is not 8: size = {}",
+                               integer_element_size));
                }
 
                /* Array is a static-length string. */
                return lttng::make_unique<lst::static_length_string_type>(
-                               array_alignment, *element_encoding, array_length);
+                       array_alignment, *element_encoding, array_length);
        }
 
        return lttng::make_unique<lst::static_length_array_type>(
-                       array_alignment, std::move(element_type), array_length);
+               array_alignment, std::move(element_type), array_length);
 }
 
-lst::type::cuptr create_array_nestable_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field)
+lst::type::cuptr create_array_nestable_type_from_ust_ctl_fields(
+       const lttng_ust_ctl_field *current,
+       const lttng_ust_ctl_field *end,
+       const session_attributes& session_attributes,
+       const lttng_ust_ctl_field **next_ust_ctl_field,
+       const publish_field_fn& publish_field,
+       const lookup_field_fn& lookup_field,
+       lst::field_location::root lookup_root,
+       lst::field_location::elements& current_field_location_elements,
+       lsu::ctl_field_quirks quirks)
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& array_uctl_field = *current;
@@ -336,48 +379,58 @@ lst::type::cuptr create_array_nestable_type_from_ust_ctl_fields(const lttng_ust_
        const auto& element_uctl_field = *(current + 1);
 
        /* next_ust_ctl_field is updated as needed. */
-       element_type = create_type_from_ust_ctl_fields(&element_uctl_field, end, session_attributes,
-                       next_ust_ctl_field, publish_field);
+       element_type = create_type_from_ust_ctl_fields(&element_uctl_field,
+                                                      end,
+                                                      session_attributes,
+                                                      next_ust_ctl_field,
+                                                      publish_field,
+                                                      lookup_field,
+                                                      lookup_root,
+                                                      current_field_location_elements,
+                                                      quirks);
        if (element_uctl_field.type.atype == lttng_ust_ctl_atype_integer &&
-                       element_uctl_field.type.u.integer.encoding != lttng_ust_ctl_encode_none) {
+           element_uctl_field.type.u.integer.encoding != lttng_ust_ctl_encode_none) {
                /* Element represents a text character. */
                element_encoding = ust_ctl_encoding_to_string_field_encoding(
-                               element_uctl_field.type.u.integer.encoding);
+                       element_uctl_field.type.u.integer.encoding);
        }
 
        if (element_encoding) {
                const auto integer_element_size =
-                               static_cast<const lst::integer_type&>(*element_type).size;
+                       static_cast<const lst::integer_type&>(*element_type).size;
 
                if (integer_element_size != 8) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Unexpected array element type: integer has encoding but size is not 8: size = {}",
-                                       integer_element_size));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Unexpected array element type: integer has encoding but size is not 8: size = {}",
+                               integer_element_size));
                }
 
                /* Array is a static-length string. */
                return lttng::make_unique<lst::static_length_string_type>(
-                               array_alignment, *element_encoding, array_length);
+                       array_alignment, *element_encoding, array_length);
        }
 
        return lttng::make_unique<lst::static_length_array_type>(
-                       array_alignment, std::move(element_type), array_length);
+               array_alignment, std::move(element_type), array_length);
 }
 
 /*
  * For legacy sequence types, LTTng-UST expresses both the sequence and sequence
  * length as part of the same lttng_ust_ctl_field entry.
  */
-lst::type::cuptr create_sequence_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field)
+lst::type::cuptr create_sequence_type_from_ust_ctl_fields(
+       const lttng_ust_ctl_field *current,
+       const lttng_ust_ctl_field *end,
+       const session_attributes& session_attributes,
+       const lttng_ust_ctl_field **next_ust_ctl_field,
+       const publish_field_fn& publish_field,
+       lst::field_location::root lookup_root,
+       lst::field_location::elements& current_field_location_elements,
+       lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& sequence_uctl_field = *current;
@@ -386,66 +439,79 @@ lst::type::cuptr create_sequence_type_from_ust_ctl_fields(const lttng_ust_ctl_fi
        const auto sequence_alignment = 0U;
 
        if (element_uctl_type.atype != lttng_ust_ctl_atype_integer) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unexpected legacy sequence element type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
-                               element_uctl_type.atype, lttng_ust_ctl_atype_integer));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unexpected legacy sequence element type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
+                       element_uctl_type.atype,
+                       lttng_ust_ctl_atype_integer));
        }
 
        if (length_uctl_type.atype != lttng_ust_ctl_atype_integer) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unexpected legacy sequence length field type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
-                               length_uctl_type.atype, lttng_ust_ctl_atype_integer));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unexpected legacy sequence length field type: atype = {}, expected atype = lttng_ust_ctl_atype_integer ({})",
+                       length_uctl_type.atype,
+                       lttng_ust_ctl_atype_integer));
        }
 
        nonstd::optional<enum lst::string_type::encoding> element_encoding;
        if (element_uctl_type.atype == lttng_ust_ctl_atype_integer &&
-                       element_uctl_type.u.basic.integer.encoding != lttng_ust_ctl_encode_none) {
+           element_uctl_type.u.basic.integer.encoding != lttng_ust_ctl_encode_none) {
                /* Element represents a text character. */
                element_encoding = ust_ctl_encoding_to_string_field_encoding(
-                               element_uctl_type.u.basic.integer.encoding);
+                       element_uctl_type.u.basic.integer.encoding);
        }
 
-       const auto length_field_name = fmt::format("_{}_length", sequence_uctl_field.name);
-       auto element_type = create_integer_type_from_ust_ctl_basic_type(
-                       element_uctl_type, session_attributes);
-       auto length_type = create_integer_type_from_ust_ctl_basic_type(
-                       length_uctl_type, session_attributes);
+       auto length_field_name = lttng::format("_{}_length", sequence_uctl_field.name);
+       auto element_type =
+               create_integer_type_from_ust_ctl_basic_type(element_uctl_type, session_attributes);
+       auto length_type =
+               create_integer_type_from_ust_ctl_basic_type(length_uctl_type, session_attributes);
+
+       lst::field_location::elements length_field_location_elements =
+               current_field_location_elements;
+       length_field_location_elements.emplace_back(length_field_name);
+
+       lst::field_location length_field_location{ lookup_root,
+                                                  std::move(length_field_location_elements) };
 
        /* Publish an implicit length field _before_ the sequence field. */
-       publish_field(lttng::make_unique<lst::field>(length_field_name, std::move(length_type)));
+       publish_field(lttng::make_unique<lst::field>(std::move(length_field_name),
+                                                    std::move(length_type)));
 
        *next_ust_ctl_field = current + 1;
 
        if (element_encoding) {
                const auto integer_element_size =
-                               static_cast<const lst::integer_type&>(*element_type).size;
+                       static_cast<const lst::integer_type&>(*element_type).size;
 
                if (integer_element_size != 8) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Unexpected legacy array element type: integer has encoding but size is not 8: size = {}",
-                                       integer_element_size));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Unexpected legacy array element type: integer has encoding but size is not 8: size = {}",
+                               integer_element_size));
                }
 
                /* Sequence is a dynamic-length string. */
-               return lttng::make_unique<lst::dynamic_length_string_type>(sequence_alignment,
-                               *element_encoding, std::move(length_field_name));
+               return lttng::make_unique<lst::dynamic_length_string_type>(
+                       sequence_alignment, *element_encoding, std::move(length_field_location));
        }
 
        return lttng::make_unique<lst::dynamic_length_array_type>(
-                       sequence_alignment, std::move(element_type), std::move(length_field_name));
+               sequence_alignment, std::move(element_type), std::move(length_field_location));
 }
 
 lst::type::cuptr create_sequence_nestable_type_from_ust_ctl_fields(
-               const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field)
+       const lttng_ust_ctl_field *current,
+       const lttng_ust_ctl_field *end,
+       const session_attributes& session_attributes,
+       const lttng_ust_ctl_field **next_ust_ctl_field,
+       const publish_field_fn& publish_field,
+       const lookup_field_fn& lookup_field,
+       lst::field_location::root lookup_root,
+       lst::field_location::elements& current_field_location_elements,
+       lsu::ctl_field_quirks quirks)
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& sequence_uctl_field = *current;
@@ -457,50 +523,75 @@ lst::type::cuptr create_sequence_nestable_type_from_ust_ctl_fields(
 
        nonstd::optional<enum lst::string_type::encoding> element_encoding;
        if (element_uctl_field.type.atype == lttng_ust_ctl_atype_integer &&
-                       element_uctl_field.type.u.integer.encoding != lttng_ust_ctl_encode_none) {
+           element_uctl_field.type.u.integer.encoding != lttng_ust_ctl_encode_none) {
                /* Element represents a text character. */
                element_encoding = ust_ctl_encoding_to_string_field_encoding(
-                               element_uctl_field.type.u.integer.encoding);
+                       element_uctl_field.type.u.integer.encoding);
        }
 
        /* next_ust_ctl_field is updated as needed. */
-       auto element_type = create_type_from_ust_ctl_fields(&element_uctl_field, end,
-                       session_attributes, next_ust_ctl_field, publish_field);
+       auto element_type = create_type_from_ust_ctl_fields(&element_uctl_field,
+                                                           end,
+                                                           session_attributes,
+                                                           next_ust_ctl_field,
+                                                           publish_field,
+                                                           lookup_field,
+                                                           lookup_root,
+                                                           current_field_location_elements,
+                                                           quirks);
 
        if (lttng_strnlen(sequence_uctl_field.type.u.sequence_nestable.length_name,
-                           sizeof(sequence_uctl_field.type.u.sequence_nestable.length_name)) ==
-                       sizeof(sequence_uctl_field.type.u.sequence_nestable.length_name)) {
+                         sizeof(sequence_uctl_field.type.u.sequence_nestable.length_name)) ==
+           sizeof(sequence_uctl_field.type.u.sequence_nestable.length_name)) {
                LTTNG_THROW_PROTOCOL_ERROR("Sequence length field name is not null terminated");
        }
 
+       lst::field_location::elements length_field_location_elements =
+               current_field_location_elements;
+       length_field_location_elements.emplace_back(length_field_name);
+
+       lst::field_location length_field_location{ lookup_root,
+                                                  std::move(length_field_location_elements) };
+
+       /* Validate existence of length field (throws if not found). */
+       const auto& length_field = lookup_field(length_field_location);
+       const auto *integer_selector_field =
+               dynamic_cast<const lst::integer_type *>(&length_field.get_type());
+       if (!integer_selector_field) {
+               LTTNG_THROW_PROTOCOL_ERROR(
+                       "Invalid selector field type referenced from sequence: expected integer or enumeration");
+       }
+
        if (element_encoding) {
                const auto integer_element_size =
-                               static_cast<const lst::integer_type&>(*element_type).size;
+                       static_cast<const lst::integer_type&>(*element_type).size;
 
                if (integer_element_size != 8) {
-                       LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                                       "Unexpected array element type: integer has encoding but size is not 8: size = {}",
-                                       integer_element_size));
+                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                               "Unexpected array element type: integer has encoding but size is not 8: size = {}",
+                               integer_element_size));
                }
 
                /* Sqeuence is a dynamic-length string. */
-               return lttng::make_unique<lst::dynamic_length_string_type>(sequence_alignment,
-                               *element_encoding, std::move(length_field_name));
+               return lttng::make_unique<lst::dynamic_length_string_type>(
+                       sequence_alignment, *element_encoding, std::move(length_field_location));
        }
 
        return lttng::make_unique<lst::dynamic_length_array_type>(
-                       sequence_alignment, std::move(element_type), std::move(length_field_name));
+               sequence_alignment, std::move(element_type), std::move(length_field_location));
 }
 
-lst::type::cuptr create_structure_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes __attribute__((unused)),
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+lst::type::cuptr
+create_structure_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                                          const lttng_ust_ctl_field *end,
+                                          const session_attributes& session_attributes
+                                          __attribute__((unused)),
+                                          const lttng_ust_ctl_field **next_ust_ctl_field,
+                                          lsu::ctl_field_quirks quirks __attribute__((unused)))
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        uint32_t field_count;
@@ -516,24 +607,104 @@ lst::type::cuptr create_structure_field_from_ust_ctl_fields(const lttng_ust_ctl_
        }
 
        if (field_count != 0) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Only empty structures are supported by LTTng-UST: nr_fields = {}",
-                               field_count));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Only empty structures are supported by LTTng-UST: nr_fields = {}",
+                       field_count));
        }
 
        *next_ust_ctl_field = current + 1;
        return lttng::make_unique<lst::structure_type>(alignment, lst::structure_type::fields());
 }
 
-lst::type::cuptr create_variant_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field)
+template <class VariantSelectorMappingIntegerType>
+typename lst::variant_type<VariantSelectorMappingIntegerType>::choices
+create_typed_variant_choices(const lttng_ust_ctl_field *current,
+                            const lttng_ust_ctl_field *end,
+                            const session_attributes& session_attributes,
+                            const lttng_ust_ctl_field **next_ust_ctl_field,
+                            lookup_field_fn lookup_field,
+                            lst::field_location::root lookup_root,
+                            lst::field_location::elements& current_field_location_elements,
+                            unsigned int choice_count,
+                            const lst::field& selector_field,
+                            lsu::ctl_field_quirks quirks)
+{
+       typename lst::variant_type<VariantSelectorMappingIntegerType>::choices choices;
+       const auto& typed_enumeration =
+               static_cast<const lst::typed_enumeration_type<VariantSelectorMappingIntegerType>&>(
+                       selector_field.get_type());
+
+       for (unsigned int i = 0; i < choice_count; i++) {
+               create_field_from_ust_ctl_fields(
+                       current,
+                       end,
+                       session_attributes,
+                       next_ust_ctl_field,
+                       [&choices, &typed_enumeration, &selector_field, quirks](
+                               lst::field::uptr field) {
+                               /*
+                                * Find the enumeration mapping that matches the
+                                * field's name.
+                                */
+                               const auto mapping_it = std::find_if(
+                                       typed_enumeration.mappings_->begin(),
+                                       typed_enumeration.mappings_->end(),
+                                       [&field,
+                                        quirks](const typename std::remove_reference<
+                                                decltype(typed_enumeration)>::type::mapping&
+                                                        mapping) {
+                                               if (static_cast<bool>(
+                                                           quirks &
+                                                           lsu::ctl_field_quirks::
+                                                                   UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS)) {
+                                                       /*
+                                                        * Check if they match with
+                                                        * a prepended underscore
+                                                        * and, if not, perform the
+                                                        * regular check.
+                                                        */
+                                                       if ((std::string("_") + field->name) ==
+                                                           mapping.name) {
+                                                               return true;
+                                                       }
+                                               }
+
+                                               return mapping.name == field->name;
+                                       });
+
+                               if (mapping_it == typed_enumeration.mappings_->end()) {
+                                       LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                                               "Invalid variant choice: `{}` does not match any mapping in `{}` enumeration",
+                                               field->name,
+                                               selector_field.name));
+                               }
+
+                               choices.emplace_back(*mapping_it, field->move_type());
+                       },
+                       lookup_field,
+                       lookup_root,
+                       current_field_location_elements,
+                       quirks);
+
+               current = *next_ust_ctl_field;
+       }
+
+       return choices;
+}
+
+lst::type::cuptr create_variant_field_from_ust_ctl_fields(
+       const lttng_ust_ctl_field *current,
+       const lttng_ust_ctl_field *end,
+       const session_attributes& session_attributes,
+       const lttng_ust_ctl_field **next_ust_ctl_field,
+       const lookup_field_fn& lookup_field,
+       lst::field_location::root lookup_root,
+       lst::field_location::elements& current_field_location_elements,
+       lsu::ctl_field_quirks quirks)
 {
        if (current >= end) {
-               LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("End of {} array reached unexpectedly during decoding",
-                                               typeid(*current)));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "End of {} array reached unexpectedly during decoding", typeid(*current)));
        }
 
        const auto& variant_uctl_field = *current;
@@ -553,84 +724,202 @@ lst::type::cuptr create_variant_field_from_ust_ctl_fields(const lttng_ust_ctl_fi
                tag_name = variant_uctl_field.type.u.variant_nestable.tag_name;
        }
 
-       /* Choices follow. next_ust_ctl_field is updated as needed. */
-       lst::variant_type::choices choices;
-       for (unsigned int i = 0; i < choice_count; i++) {
-               create_field_from_ust_ctl_fields(current, end, session_attributes,
-                               next_ust_ctl_field, [&choices](lst::field::cuptr field) {
-                                       choices.emplace_back(std::move(field));
-                               });
+       lst::field_location::elements selector_field_location_elements =
+               current_field_location_elements;
+       selector_field_location_elements.emplace_back(tag_name);
 
-               current = *next_ust_ctl_field;
+       lst::field_location selector_field_location{ lookup_root,
+                                                    std::move(selector_field_location_elements) };
+
+       /* Validate existence of selector field (throws if not found). */
+       const auto& selector_field = lookup_field(selector_field_location);
+       const auto *enumeration_selector_type =
+               dynamic_cast<const lst::enumeration_type *>(&selector_field.get_type());
+       if (!enumeration_selector_type) {
+               LTTNG_THROW_PROTOCOL_ERROR(
+                       "Invalid selector field type referenced from variant: expected enumeration");
        }
 
-       return lttng::make_unique<lst::variant_type>(alignment, tag_name, std::move(choices));
+       const bool selector_is_signed = enumeration_selector_type->signedness_ ==
+               lst::integer_type::signedness::SIGNED;
+
+       /* Choices follow. next_ust_ctl_field is updated as needed. */
+       if (selector_is_signed) {
+               lst::variant_type<lst::signed_enumeration_type::mapping::range_t::range_integer_t>::
+                       choices choices = create_typed_variant_choices<int64_t>(
+                               current,
+                               end,
+                               session_attributes,
+                               next_ust_ctl_field,
+                               lookup_field,
+                               lookup_root,
+                               current_field_location_elements,
+                               choice_count,
+                               selector_field,
+                               quirks);
+
+               return lttng::make_unique<lst::variant_type<int64_t>>(
+                       alignment, std::move(selector_field_location), std::move(choices));
+       } else {
+               lst::variant_type<
+                       lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>::choices
+                       choices = create_typed_variant_choices<uint64_t>(
+                               current,
+                               end,
+                               session_attributes,
+                               next_ust_ctl_field,
+                               lookup_field,
+                               lookup_root,
+                               current_field_location_elements,
+                               choice_count,
+                               selector_field,
+                               quirks);
+
+               return lttng::make_unique<lst::variant_type<uint64_t>>(
+                       alignment, std::move(selector_field_location), std::move(choices));
+       }
 }
 
-lst::type::cuptr create_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field)
+lst::type::cuptr
+create_type_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
+                               const lttng_ust_ctl_field *end,
+                               const session_attributes& session_attributes,
+                               const lttng_ust_ctl_field **next_ust_ctl_field,
+                               const publish_field_fn& publish_field,
+                               const lookup_field_fn& lookup_field,
+                               lst::field_location::root lookup_root,
+                               lst::field_location::elements& current_field_location_elements,
+                               lsu::ctl_field_quirks quirks)
 {
        switch (current->type.atype) {
        case lttng_ust_ctl_atype_integer:
                return create_integer_type_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_enum:
        case lttng_ust_ctl_atype_enum_nestable:
                return create_enumeration_type_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_float:
                return create_floating_point_type_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_string:
                return create_string_type_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_array:
-               return create_array_type_from_ust_ctl_fields(current, end, session_attributes,
-                               next_ust_ctl_field);
+               return create_array_type_from_ust_ctl_fields(
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_array_nestable:
-               return create_array_nestable_type_from_ust_ctl_fields(current, end,
-                               session_attributes, next_ust_ctl_field, publish_field);
+               return create_array_nestable_type_from_ust_ctl_fields(
+                       current,
+                       end,
+                       session_attributes,
+                       next_ust_ctl_field,
+                       publish_field,
+                       lookup_field,
+                       lookup_root,
+                       current_field_location_elements,
+                       quirks);
        case lttng_ust_ctl_atype_sequence:
-               return create_sequence_type_from_ust_ctl_fields(current, end, session_attributes,
-                               next_ust_ctl_field, publish_field);
+               return create_sequence_type_from_ust_ctl_fields(current,
+                                                               end,
+                                                               session_attributes,
+                                                               next_ust_ctl_field,
+                                                               publish_field,
+                                                               lookup_root,
+                                                               current_field_location_elements,
+                                                               quirks);
        case lttng_ust_ctl_atype_sequence_nestable:
-               return create_sequence_nestable_type_from_ust_ctl_fields(current, end,
-                               session_attributes, next_ust_ctl_field, publish_field);
+               return create_sequence_nestable_type_from_ust_ctl_fields(
+                       current,
+                       end,
+                       session_attributes,
+                       next_ust_ctl_field,
+                       publish_field,
+                       lookup_field,
+                       lookup_root,
+                       current_field_location_elements,
+                       quirks);
        case lttng_ust_ctl_atype_struct:
        case lttng_ust_ctl_atype_struct_nestable:
                return create_structure_field_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+                       current, end, session_attributes, next_ust_ctl_field, quirks);
        case lttng_ust_ctl_atype_variant:
        case lttng_ust_ctl_atype_variant_nestable:
-               return create_variant_field_from_ust_ctl_fields(
-                               current, end, session_attributes, next_ust_ctl_field);
+               return create_variant_field_from_ust_ctl_fields(current,
+                                                               end,
+                                                               session_attributes,
+                                                               next_ust_ctl_field,
+                                                               lookup_field,
+                                                               lookup_root,
+                                                               current_field_location_elements,
+                                                               quirks);
        default:
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unknown {} value `{}` encountered while converting {} to {}",
-                               typeid(current->type.atype), current->type.atype, typeid(*current),
-                               typeid(lst::type::cuptr::element_type)));
+               LTTNG_THROW_PROTOCOL_ERROR(
+                       lttng::format("Unknown {} value `{}` encountered while converting {} to {}",
+                                     typeid(current->type.atype),
+                                     current->type.atype,
+                                     typeid(*current),
+                                     typeid(lst::type::cuptr::element_type)));
        }
 }
 
 void create_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end,
-               const session_attributes& session_attributes,
-               const lttng_ust_ctl_field **next_ust_ctl_field,
-               publish_field_fn publish_field)
+                                     const lttng_ust_ctl_field *end,
+                                     const session_attributes& session_attributes,
+                                     const lttng_ust_ctl_field **next_ust_ctl_field,
+                                     const publish_field_fn& publish_field,
+                                     const lookup_field_fn& lookup_field,
+                                     lst::field_location::root lookup_root,
+                                     lst::field_location::elements& current_field_location_elements,
+                                     lsu::ctl_field_quirks quirks)
 {
        LTTNG_ASSERT(current < end);
 
        if (lttng_strnlen(current->name, sizeof(current->name)) == sizeof(current->name)) {
                LTTNG_THROW_PROTOCOL_ERROR(
-                               fmt::format("Name of {} is not null-terminated", typeid(*current)));
+                       lttng::format("Name of {} is not null-terminated", typeid(*current)));
+       }
+
+       publish_field(lttng::make_unique<lst::field>(
+               current->name,
+               create_type_from_ust_ctl_fields(current,
+                                               end,
+                                               session_attributes,
+                                               next_ust_ctl_field,
+                                               publish_field,
+                                               lookup_field,
+                                               lookup_root,
+                                               current_field_location_elements,
+                                               quirks)));
+}
+
+std::vector<lst::field::cuptr>::iterator
+lookup_field_in_vector(std::vector<lst::field::cuptr>& fields, const lst::field_location& location)
+{
+       if (location.elements_.size() != 1) {
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Unexpected field location received during field look-up: location = {}",
+                       location));
+       }
+
+       /*
+        * In the context of fields received from LTTng-UST, field
+        * look-up is extremely naive as the protocol can only
+        * express empty structures. It is safe to assume that
+        * location has a depth of 1 and directly refers to a field
+        * in the 'fields' vector.
+        */
+       const auto field_it =
+               std::find_if(fields.begin(), fields.end(), [location](lst::field::cuptr& field) {
+                       return field->name == location.elements_[0];
+               });
+
+       if (field_it == fields.end()) {
+               LTTNG_THROW_PROTOCOL_ERROR(
+                       lttng::format("Failed to look-up field: location = {}", location));
        }
 
-       publish_field(lttng::make_unique<lst::field>(current->name,
-                       create_type_from_ust_ctl_fields(current, end, session_attributes,
-                                       next_ust_ctl_field, publish_field)));
+       return field_it;
 }
 
 /*
@@ -641,18 +930,23 @@ void create_field_from_ust_ctl_fields(const lttng_ust_ctl_field *current,
  *
  * Always returns a new field, throws on error.
  */
-std::vector<lst::field::cuptr> create_fields_from_ust_ctl_fields(
-               const lsu::registry_session& session,
-               const lttng_ust_ctl_field *current,
-               const lttng_ust_ctl_field *end)
+std::vector<lst::field::cuptr>
+create_fields_from_ust_ctl_fields(const lsu::registry_session& session,
+                                 const lttng_ust_ctl_field *current,
+                                 const lttng_ust_ctl_field *end,
+                                 lst::field_location::root lookup_root,
+                                 lsu::ctl_field_quirks quirks)
 {
        std::vector<lst::field::cuptr> fields;
        const auto trace_native_byte_order = session.abi.byte_order;
        const session_attributes session_attributes{
-                       [&session](const char *enum_name, uint64_t enum_id) {
-                               return session.get_enumeration(enum_name, enum_id);
-                       },
-                       trace_native_byte_order};
+               [&session](const char *enum_name, uint64_t enum_id) {
+                       return session.enumeration(enum_name, enum_id);
+               },
+               trace_native_byte_order
+       };
+       /* Location of field being created. */
+       lst::field_location::elements current_field_location_elements;
 
        while (current < end) {
                auto *next_field = current;
@@ -666,10 +960,24 @@ std::vector<lst::field::cuptr> create_fields_from_ust_ctl_fields(
                 * The lambda allows the factory functions to push as many fields as
                 * needed depending on the decoded field's type.
                 */
-               create_field_from_ust_ctl_fields(current, end, session_attributes, &next_field,
-                               [&fields](lst::field::cuptr field) {
-                                       fields.emplace_back(std::move(field));
-                               });
+               create_field_from_ust_ctl_fields(
+                       current,
+                       end,
+                       session_attributes,
+                       &next_field,
+                       [&fields](lst::field::cuptr field) {
+                               /* Publishing a field simply adds it to the converted
+                                * fields. */
+                               fields.emplace_back(std::move(field));
+                       },
+                       [&fields](const lst::field_location& location)
+                               -> lookup_field_fn::result_type {
+                               /* Resolve location to a previously-constructed field. */
+                               return **lookup_field_in_vector(fields, location);
+                       },
+                       lookup_root,
+                       current_field_location_elements,
+                       quirks);
 
                current = next_field;
        }
@@ -678,10 +986,13 @@ std::vector<lst::field::cuptr> create_fields_from_ust_ctl_fields(
 }
 } /* namespace */
 
-std::vector<lst::field::cuptr> lsu::create_trace_fields_from_ust_ctl_fields(
-               const lsu::registry_session& session,
-               const lttng_ust_ctl_field *fields,
-               std::size_t field_count)
+std::vector<lst::field::cuptr>
+lsu::create_trace_fields_from_ust_ctl_fields(const lsu::registry_session& session,
+                                            const lttng_ust_ctl_field *fields,
+                                            std::size_t field_count,
+                                            lst::field_location::root lookup_root,
+                                            lsu::ctl_field_quirks quirks)
 {
-       return create_fields_from_ust_ctl_fields(session, fields, fields + field_count);
+       return create_fields_from_ust_ctl_fields(
+               session, fields, fields + field_count, lookup_root, quirks);
 }
index 0faf65db1b87d42f9d7b24c99df9ffb15be8f6ed..063abcd6808f9eae972e819dedebb16d2b91237a 100644 (file)
@@ -9,20 +9,45 @@
 #define LTTNG_UST_FIELD_CONVERT_H
 
 #include "field.hpp"
-#include "ust-registry.hpp"
 #include "ust-registry-session.hpp"
+#include "ust-registry.hpp"
 
 #include <cstddef>
+#include <type_traits>
 #include <vector>
 
 namespace lttng {
 namespace sessiond {
 namespace ust {
 
-std::vector<trace::field::cuptr> create_trace_fields_from_ust_ctl_fields(
-               const lttng::sessiond::ust::registry_session& session,
-               const lttng_ust_ctl_field *fields,
-               std::size_t field_count);
+enum class ctl_field_quirks : unsigned int {
+       NONE = 0,
+       /*
+        * LTTng-UST with ABI major version <= 9 express variants with a tag
+        * enumeration that doesn't match the fields of the variant. The
+        * tag's mapping names are systematically prefixed with an underscore.
+        */
+       UNDERSCORE_PREFIXED_VARIANT_TAG_MAPPINGS = 1 << 0,
+};
+
+inline ctl_field_quirks operator&(ctl_field_quirks lhs, ctl_field_quirks rhs)
+{
+       using enum_type = std::underlying_type<ctl_field_quirks>::type;
+       return ctl_field_quirks(static_cast<enum_type>(lhs) & static_cast<enum_type>(rhs));
+}
+
+inline ctl_field_quirks operator|(ctl_field_quirks lhs, ctl_field_quirks rhs)
+{
+       using enum_type = std::underlying_type<ctl_field_quirks>::type;
+       return ctl_field_quirks(static_cast<enum_type>(lhs) | static_cast<enum_type>(rhs));
+}
+
+std::vector<trace::field::cuptr>
+create_trace_fields_from_ust_ctl_fields(const lttng::sessiond::ust::registry_session& session,
+                                       const lttng_ust_ctl_field *fields,
+                                       std::size_t field_count,
+                                       trace::field_location::root lookup_root,
+                                       ctl_field_quirks quirks = ctl_field_quirks::NONE);
 
 } /* namespace ust */
 } /* namespace sessiond */
diff --git a/src/bin/lttng-sessiond/ust-metadata.cpp b/src/bin/lttng-sessiond/ust-metadata.cpp
deleted file mode 100644 (file)
index 6a5d5ff..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2010-2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
- *
- * SPDX-License-Identifier: GPL-2.0-only
- *
- */
-
-#define _LGPL_SOURCE
-#include <inttypes.h>
-#include <limits.h>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <vector>
-
-#include <common/common.hpp>
-#include <common/exception.hpp>
-#include <common/format.hpp>
-#include <common/time.hpp>
-#include <common/uuid.hpp>
-
-#include "ust-app.hpp"
-#include "ust-clock-class.hpp"
-#include "ust-registry.hpp"
-#include "tsdl-environment-visitor.hpp"
-
-namespace ls = lttng::sessiond;
-namespace lsu = lttng::sessiond::ust;
index 85448b7032626024c116837aa392643bb8ed4d92..f4c8f226e09f104b33b7142a16d1b59fe8878425 100644 (file)
@@ -5,16 +5,19 @@
  *
  */
 
-#include "ust-registry-channel.hpp"
 #include "ust-app.hpp"
+#include "ust-registry-channel.hpp"
 #include "ust-registry-event.hpp"
 
 #include <common/error.hpp>
 #include <common/exception.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/make-unique-wrapper.hpp>
+#include <common/make-unique.hpp>
 #include <common/urcu.hpp>
 
+#include <utility>
+
 namespace lst = lttng::sessiond::trace;
 namespace lsu = lttng::sessiond::ust;
 
@@ -28,7 +31,7 @@ unsigned long ht_hash_event(const void *_key, unsigned long seed)
 {
        uint64_t hashed_key;
        const lttng::sessiond::ust::registry_event *key =
-                       (lttng::sessiond::ust::registry_event *) _key;
+               (lttng::sessiond::ust::registry_event *) _key;
 
        LTTNG_ASSERT(key);
 
@@ -77,18 +80,273 @@ int ht_match_event(struct cds_lfht_node *node, const void *_key)
 no_match:
        return 0;
 }
+
+lst::type::cuptr create_event_header(const lst::abi& trace_abi,
+                                    lst::stream_class::header_type header_type)
+{
+       lst::structure_type::fields event_header_fields;
+
+       if (header_type == lst::stream_class::header_type::COMPACT) {
+               auto enum_mappings = std::make_shared<lst::unsigned_enumeration_type::mappings>();
+               lst::unsigned_enumeration_type::mapping compact_mapping{
+                       "compact", lst::unsigned_enumeration_type::mapping::range_t(0, 30)
+               };
+               lst::unsigned_enumeration_type::mapping extended_mapping{ "extended", 31 };
+
+               enum_mappings->emplace_back(compact_mapping);
+               enum_mappings->emplace_back(extended_mapping);
+
+               lst::type::cuptr choice_enum = lttng::make_unique<lst::unsigned_enumeration_type>(
+                       1,
+                       trace_abi.byte_order,
+                       5,
+                       lst::integer_type::base::DECIMAL,
+                       std::move(enum_mappings),
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::EVENT_RECORD_CLASS_ID }));
+
+               lst::variant_type<
+                       lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>::choices
+                       variant_choices;
+
+               lst::structure_type::fields compact_fields;
+               compact_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "timestamp",
+                       lttng::make_unique<lst::integer_type>(
+                               1,
+                               trace_abi.byte_order,
+                               27,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP }))));
+
+               auto compact_type =
+                       lttng::make_unique<lst::structure_type>(0, std::move(compact_fields));
+               variant_choices.emplace_back(std::move(compact_mapping), std::move(compact_type));
+
+               lst::structure_type::fields extended_fields;
+               extended_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "id",
+                       lttng::make_unique<lst::integer_type>(
+                               trace_abi.uint32_t_alignment,
+                               trace_abi.byte_order,
+                               32,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::EVENT_RECORD_CLASS_ID }))));
+               extended_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "timestamp",
+                       lttng::make_unique<lst::integer_type>(
+                               trace_abi.uint64_t_alignment,
+                               trace_abi.byte_order,
+                               64,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP }))));
+
+               lst::type::cuptr extended_type =
+                       lttng::make_unique<lst::structure_type>(0, std::move(extended_fields));
+               variant_choices.emplace_back(std::move(extended_mapping), std::move(extended_type));
+
+               auto variant = lttng::make_unique<lst::variant_type<
+                       lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>>(
+                       0,
+                       lst::field_location(lst::field_location::root::EVENT_RECORD_HEADER,
+                                           { "id" }),
+                       std::move(variant_choices));
+
+               event_header_fields.emplace_back(
+                       lttng::make_unique<lst::field>("id", std::move(choice_enum)));
+               event_header_fields.emplace_back(
+                       lttng::make_unique<lst::field>("v", std::move(variant)));
+       } else {
+               auto enum_mappings = std::make_shared<lst::unsigned_enumeration_type::mappings>();
+               lst::unsigned_enumeration_type::mapping compact_mapping{
+                       "compact", lst::unsigned_enumeration_type::mapping::range_t(0, 65534)
+               };
+               lst::unsigned_enumeration_type::mapping extended_mapping{ "extended", 65535 };
+               enum_mappings->emplace_back(compact_mapping);
+               enum_mappings->emplace_back(extended_mapping);
+
+               auto choice_enum = lttng::make_unique<lst::unsigned_enumeration_type>(
+                       trace_abi.uint16_t_alignment,
+                       trace_abi.byte_order,
+                       16,
+                       lst::integer_type::base::DECIMAL,
+                       std::move(enum_mappings),
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::EVENT_RECORD_CLASS_ID }));
+
+               lst::variant_type<
+                       lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>::choices
+                       variant_choices;
+
+               lst::structure_type::fields compact_fields;
+               compact_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "timestamp",
+                       lttng::make_unique<lst::integer_type>(
+                               trace_abi.uint32_t_alignment,
+                               trace_abi.byte_order,
+                               32,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP }))));
+
+               lst::type::cuptr compact_type =
+                       lttng::make_unique<lst::structure_type>(0, std::move(compact_fields));
+               variant_choices.emplace_back(std::move(compact_mapping), std::move(compact_type));
+
+               lst::structure_type::fields extended_fields;
+               extended_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "id",
+                       lttng::make_unique<lst::integer_type>(
+                               trace_abi.uint32_t_alignment,
+                               trace_abi.byte_order,
+                               32,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::EVENT_RECORD_CLASS_ID }))));
+               extended_fields.emplace_back(lttng::make_unique<lst::field>(
+                       "timestamp",
+                       lttng::make_unique<lst::integer_type>(
+                               trace_abi.uint64_t_alignment,
+                               trace_abi.byte_order,
+                               64,
+                               lst::integer_type::signedness::UNSIGNED,
+                               lst::integer_type::base::DECIMAL,
+                               std::initializer_list<lst::integer_type::role>(
+                                       { lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP }))));
+
+               auto extended_type =
+                       lttng::make_unique<lst::structure_type>(0, std::move(extended_fields));
+               variant_choices.emplace_back(std::move(extended_mapping), std::move(extended_type));
+
+               auto variant = lttng::make_unique<lst::variant_type<
+                       lst::unsigned_enumeration_type::mapping::range_t::range_integer_t>>(
+                       0,
+                       lst::field_location(lst::field_location::root::EVENT_RECORD_HEADER,
+                                           { "id" }),
+                       std::move(variant_choices));
+
+               event_header_fields.emplace_back(
+                       lttng::make_unique<lst::field>("id", std::move(choice_enum)));
+               event_header_fields.emplace_back(
+                       lttng::make_unique<lst::field>("v", std::move(variant)));
+       }
+
+       return lttng::make_unique<lst::structure_type>(0, std::move(event_header_fields));
+}
+
+lst::type::cuptr create_packet_context(const lst::abi& trace_abi)
+{
+       lst::structure_type::fields packet_context_fields;
+
+       /* uint64_t timestamp_begin */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "timestamp_begin",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.uint64_t_alignment,
+                       trace_abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::DEFAULT_CLOCK_TIMESTAMP }))));
+
+       /* uint64_t timestamp_end */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "timestamp_end",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.uint64_t_alignment,
+                       trace_abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::PACKET_END_DEFAULT_CLOCK_TIMESTAMP }))));
+
+       /* uint64_t content_size */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "content_size",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.uint64_t_alignment,
+                       trace_abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::PACKET_CONTENT_LENGTH }))));
+
+       /* uint64_t packet_size */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "packet_size",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.uint64_t_alignment,
+                       trace_abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::PACKET_TOTAL_LENGTH }))));
+
+       /* uint64_t packet_seq_num */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "packet_seq_num",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.uint64_t_alignment,
+                       trace_abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::PACKET_SEQUENCE_NUMBER }))));
+
+       /* unsigned long events_discarded */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "events_discarded",
+               lttng::make_unique<lst::integer_type>(
+                       trace_abi.long_alignment,
+                       trace_abi.byte_order,
+                       trace_abi.bits_per_long,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::
+                                         DISCARDED_EVENT_RECORD_COUNTER_SNAPSHOT }))));
+
+       /* uint32_t cpu_id */
+       packet_context_fields.emplace_back(lttng::make_unique<lst::field>(
+               "cpu_id",
+               lttng::make_unique<lst::integer_type>(trace_abi.uint32_t_alignment,
+                                                     trace_abi.byte_order,
+                                                     32,
+                                                     lst::integer_type::signedness::UNSIGNED,
+                                                     lst::integer_type::base::DECIMAL)));
+
+       return lttng::make_unique<lst::structure_type>(0, std::move(packet_context_fields));
+}
 }; /* namespace */
 
-lsu::registry_channel::registry_channel(unsigned int channel_id,
-               lsu::registry_channel::registered_listener_fn channel_registered_listener,
-               lsu::registry_channel::event_added_listener_fn event_added_listener) :
-       lst::stream_class(channel_id, lst::stream_class::header_type::LARGE),
-       _key{-1ULL},
-       _consumer_key{-1ULL},
-       _next_event_id{0},
-       _is_registered_listener{channel_registered_listener},
-       _event_added_listener{event_added_listener},
-       _is_registered{false}
+lsu::registry_channel::registry_channel(
+       unsigned int channel_id,
+       const lst::abi& trace_abi,
+       std::string in_default_clock_class_name,
+       lsu::registry_channel::registered_listener_fn channel_registered_listener,
+       lsu::registry_channel::event_added_listener_fn event_added_listener) :
+       lst::stream_class(channel_id,
+                         lst::stream_class::header_type::LARGE,
+                         std::move(in_default_clock_class_name)),
+       _key{ -1ULL },
+       _consumer_key{ -1ULL },
+       _next_event_id{ 0 },
+       _is_registered_listener{ std::move(channel_registered_listener) },
+       _event_added_listener{ std::move(event_added_listener) },
+       _is_registered{ false }
 {
        _events = lttng_ht_new(0, LTTNG_HT_TYPE_STRING);
        if (!_events) {
@@ -105,19 +363,21 @@ lsu::registry_channel::registry_channel(unsigned int channel_id,
         * channel object itself.
         */
        _node = {};
+
+       _packet_context = create_packet_context(trace_abi);
+       _event_header = create_event_header(trace_abi, header_type_);
 }
 
-void lsu::registry_channel::add_event(
-               int session_objd,
-               int channel_objd,
-               std::string name,
-               std::string signature,
-               std::vector<lst::field::cuptr> event_fields,
-               int loglevel_value,
-               nonstd::optional<std::string> model_emf_uri,
-               lttng_buffer_type buffer_type,
-               const ust_app& app,
-               uint32_t& out_event_id)
+void lsu::registry_channel::add_event(int session_objd,
+                                     int channel_objd,
+                                     std::string name,
+                                     std::string signature,
+                                     std::vector<lst::field::cuptr> event_fields,
+                                     int loglevel_value,
+                                     nonstd::optional<std::string> model_emf_uri,
+                                     lttng_buffer_type buffer_type,
+                                     const ust_app& app,
+                                     uint32_t& out_event_id)
 {
        uint32_t event_id;
        struct cds_lfht_node *nptr;
@@ -128,38 +388,47 @@ void lsu::registry_channel::add_event(
         * external party, don't assert and simply validate values.
         */
        if (session_objd < 0) {
-               LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                               "Invalid session object descriptor provided by application: session descriptor = {}, app = {}",
-                               session_objd, app));
+               LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                       "Invalid session object descriptor provided by application: session descriptor = {}, app = {}",
+                       session_objd,
+                       app));
        }
 
        if (channel_objd < 0) {
-               LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                               "Invalid channel object descriptor provided by application: channel descriptor = {}, app = {}",
-                               channel_objd, app));
+               LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                       "Invalid channel object descriptor provided by application: channel descriptor = {}, app = {}",
+                       channel_objd,
+                       app));
        }
 
        /* Check if we've reached the maximum possible id. */
        if (is_max_event_id(_next_event_id)) {
-               LTTNG_THROW_ERROR(fmt::format(
-                               "Failed to allocate new event id (id would overflow): app = {}",
-                               app));
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Failed to allocate new event id (id would overflow): app = {}", app));
        }
 
        auto event = lttng::make_unique_wrapper<lsu::registry_event, registry_event_destroy>(
-                       new lsu::registry_event(_next_event_id, id, session_objd, channel_objd,
-                                       std::move(name), std::move(signature),
-                                       std::move(event_fields), loglevel_value,
+               new lsu::registry_event(_next_event_id,
+                                       id,
+                                       session_objd,
+                                       channel_objd,
+                                       std::move(name),
+                                       std::move(signature),
+                                       std::move(event_fields),
+                                       loglevel_value,
                                        std::move(model_emf_uri)));
 
-       DBG3("%s", fmt::format("UST registry creating event: event = {}", *event).c_str());
+       DBG3("%s", lttng::format("UST registry creating event: event = {}", *event).c_str());
 
        /*
         * This is an add unique with a custom match function for event. The node
         * are matched using the event name and signature.
         */
-       nptr = cds_lfht_add_unique(_events->ht, _events->hash_fct(event.get(), lttng_ht_seed),
-                       _events->match_fct, event.get(), &event->_node);
+       nptr = cds_lfht_add_unique(_events->ht,
+                                  _events->hash_fct(event.get(), lttng_ht_seed),
+                                  _events->match_fct,
+                                  event.get(),
+                                  &event->_node);
        if (nptr != &event->_node) {
                if (buffer_type == LTTNG_BUFFER_PER_UID) {
                        /*
@@ -167,18 +436,18 @@ void lsu::registry_channel::add_event(
                         * returned node.
                         */
                        const auto existing_event = lttng::utils::container_of(
-                                       nptr, &lttng::sessiond::ust::registry_event::_node);
+                               nptr, &lttng::sessiond::ust::registry_event::_node);
                        event_id = existing_event->id;
                } else {
-                       LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                                       "UST registry create event add unique failed for event: event = {}",
-                                       *event));
+                       LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                               "UST registry create event add unique failed for event: event = {}",
+                               *event));
                }
        } else {
                const auto& event_ref = *event;
 
                /* Ownership transferred to _events hash table. */
-               event.release();
+               (void) event.release();
 
                /* Request next event id if the node was successfully added. */
                event_id = event_ref.id;
@@ -199,17 +468,17 @@ lsu::registry_channel::~registry_channel()
        lttng_ht_destroy(_events);
 }
 
-const lttng::sessiond::trace::type& lsu::registry_channel::get_context() const
+const lttng::sessiond::trace::type *lsu::registry_channel::event_context() const
 {
        LTTNG_ASSERT(_is_registered);
-       return lst::stream_class::get_context();
+       return lst::stream_class::event_context();
 }
 
-void lsu::registry_channel::set_context(lttng::sessiond::trace::type::cuptr context)
+void lsu::registry_channel::event_context(lttng::sessiond::trace::type::cuptr context)
 {
        /* Must only be set once, on the first channel registration provided by an application. */
-       LTTNG_ASSERT(!_context);
-       _context = std::move(context);
+       LTTNG_ASSERT(!_event_context);
+       _event_context = std::move(context);
 }
 
 bool lsu::registry_channel::is_registered() const
@@ -226,7 +495,7 @@ void lsu::registry_channel::set_as_registered()
 }
 
 void lsu::registry_channel::_accept_on_event_classes(
-               lttng::sessiond::trace::trace_class_visitor& visitor) const
+       lttng::sessiond::trace::trace_class_visitor& visitor) const
 {
        std::vector<const lttng::sessiond::ust::registry_event *> sorted_event_classes;
 
@@ -237,17 +506,16 @@ void lsu::registry_channel::_accept_on_event_classes(
 
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-               cds_lfht_for_each_entry(_events->ht, &iter.iter, event, _node) {
+               cds_lfht_for_each_entry (_events->ht, &iter.iter, event, _node) {
                        sorted_event_classes.emplace_back(event);
                }
                DIAGNOSTIC_POP
        }
 
-       std::sort(sorted_event_classes.begin(), sorted_event_classes.end(),
-                       [](const lttng::sessiond::ust::registry_event *a,
-                                       const lttng::sessiond::ust::registry_event *b) {
-                               return a->id < b->id;
-                       });
+       std::sort(sorted_event_classes.begin(),
+                 sorted_event_classes.end(),
+                 [](const lttng::sessiond::ust::registry_event *a,
+                    const lttng::sessiond::ust::registry_event *b) { return a->id < b->id; });
 
        for (const auto event : sorted_event_classes) {
                event->accept(visitor);
index 1e5745aedcfe2fdc4b980315c84414dbfbf4b2cb..636de94aa9979ebfbf8a23e8d95a5a1c7a32e046 100644 (file)
@@ -9,13 +9,14 @@
 #define LTTNG_UST_REGISTRY_CHANNEL_H
 
 #include "stream-class.hpp"
+#include "trace-class.hpp"
 
 #include <common/hashtable/hashtable.hpp>
 
 #include <lttng/lttng.h>
 
-#include <urcu.h>
 #include <functional>
+#include <urcu.h>
 
 struct ust_app;
 
@@ -28,25 +29,32 @@ class registry_event;
 class registry_channel : public lttng::sessiond::trace::stream_class {
 public:
        using registered_listener_fn = std::function<void(const registry_channel&)>;
-       using event_added_listener_fn = std::function<void(const registry_channel&, const registry_event &)>;
+       using event_added_listener_fn =
+               std::function<void(const registry_channel&, const registry_event&)>;
 
        registry_channel(uint32_t channel_id,
-                       registered_listener_fn channel_registered_listener,
-                       event_added_listener_fn new_event_listener);
+                        const lttng::sessiond::trace::abi& trace_abi,
+                        std::string default_clock_class_name,
+                        registered_listener_fn channel_registered_listener,
+                        event_added_listener_fn new_event_listener);
        void add_event(int session_objd,
-                       int channel_objd,
-                       std::string name,
-                       std::string signature,
-                       std::vector<lttng::sessiond::trace::field::cuptr> event_fields,
-                       int loglevel_value,
-                       nonstd::optional<std::string> model_emf_uri,
-                       lttng_buffer_type buffer_type,
-                       const ust_app& app,
-                       uint32_t& out_event_id);
-       virtual ~registry_channel();
-
-       virtual const lttng::sessiond::trace::type& get_context() const override final;
-       void set_context(lttng::sessiond::trace::type::cuptr context);
+                      int channel_objd,
+                      std::string name,
+                      std::string signature,
+                      std::vector<lttng::sessiond::trace::field::cuptr> event_fields,
+                      int loglevel_value,
+                      nonstd::optional<std::string> model_emf_uri,
+                      lttng_buffer_type buffer_type,
+                      const ust_app& app,
+                      uint32_t& out_event_id);
+       ~registry_channel() override;
+       registry_channel(const registry_channel&) = delete;
+       registry_channel(registry_channel&&) = delete;
+       registry_channel& operator=(registry_channel&&) = delete;
+       registry_channel& operator=(const registry_channel&) = delete;
+
+       const lttng::sessiond::trace::type *event_context() const final;
+       void event_context(lttng::sessiond::trace::type::cuptr context);
 
        /* Channel was registered to at least one application. */
        bool is_registered() const;
@@ -67,8 +75,8 @@ public:
        uint32_t _next_event_id;
 
 private:
-       virtual void _accept_on_event_classes(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor) const override final;
+       void _accept_on_event_classes(
+               lttng::sessiond::trace::trace_class_visitor& trace_class_visitor) const final;
 
        registered_listener_fn _is_registered_listener;
        event_added_listener_fn _event_added_listener;
index 543da2f6670b36bf19088f0fc20a285ed7adf07e..fec7fb54815339cf39cb75a7aeb3918eb729579e 100644 (file)
@@ -15,24 +15,24 @@ namespace lst = lttng::sessiond::trace;
 namespace lsu = lttng::sessiond::ust;
 
 lsu::registry_event::registry_event(unsigned int in_id,
-               unsigned int in_stream_class_id,
-               int in_session_objd,
-               int in_channel_objd,
-               std::string in_name,
-               std::string in_signature,
-               std::vector<lttng::sessiond::trace::field::cuptr> in_fields,
-               int in_loglevel_value,
-               nonstd::optional<std::string> in_model_emf_uri) :
+                                   unsigned int in_stream_class_id,
+                                   int in_session_objd,
+                                   int in_channel_objd,
+                                   std::string in_name,
+                                   std::string in_signature,
+                                   std::vector<lttng::sessiond::trace::field::cuptr> in_fields,
+                                   int in_loglevel_value,
+                                   nonstd::optional<std::string> in_model_emf_uri) :
        lst::event_class(in_id,
-                       in_stream_class_id,
-                       in_loglevel_value,
-                       std::move(in_name),
-                       std::move(in_model_emf_uri),
-                       lttng::make_unique<lst::structure_type>(0, std::move(in_fields))),
-       session_objd{in_session_objd},
-       channel_objd{in_channel_objd},
-       signature{std::move(in_signature)},
-       _metadata_dumped{false}
+                        in_stream_class_id,
+                        in_loglevel_value,
+                        std::move(in_name),
+                        std::move(in_model_emf_uri),
+                        lttng::make_unique<lst::structure_type>(0, std::move(in_fields))),
+       session_objd{ in_session_objd },
+       channel_objd{ in_channel_objd },
+       signature{ std::move(in_signature) },
+       _metadata_dumped{ false }
 {
        cds_lfht_node_init(&_node);
        _head = {};
index 5dc98032a2900d58f650bdbdbfa213b90c22164f..38d96eb8fbd179b9a6982bac0377b1ce68cb7d4c 100644 (file)
@@ -13,6 +13,7 @@
 
 #include <common/format.hpp>
 #include <common/hashtable/hashtable.hpp>
+
 #include <vendor/optional.hpp>
 
 #include <typeinfo>
@@ -28,15 +29,19 @@ namespace ust {
 class registry_event : public lttng::sessiond::trace::event_class {
 public:
        registry_event(unsigned int id,
-                       unsigned int stream_class_id,
-                       int session_objd,
-                       int channel_objd,
-                       std::string name,
-                       std::string signature,
-                       std::vector<lttng::sessiond::trace::field::cuptr> fields,
-                       int loglevel_value,
-                       nonstd::optional<std::string> model_emf_uri);
-       virtual ~registry_event() = default;
+                      unsigned int stream_class_id,
+                      int session_objd,
+                      int channel_objd,
+                      std::string name,
+                      std::string signature,
+                      std::vector<lttng::sessiond::trace::field::cuptr> fields,
+                      int loglevel_value,
+                      nonstd::optional<std::string> model_emf_uri);
+       ~registry_event() override = default;
+       registry_event(const registry_event&) = delete;
+       registry_event(registry_event&&) = delete;
+       registry_event& operator=(registry_event&&) = delete;
+       registry_event& operator=(const registry_event&) = delete;
 
        /* Both objd are set by the tracer. */
        const int session_objd;
@@ -70,14 +75,18 @@ void registry_event_destroy(registry_event *event);
 namespace fmt {
 template <>
 struct formatter<lttng::sessiond::ust::registry_event> : formatter<std::string> {
-       template <typename FormatCtx>
-       typename FormatCtx::iterator format(
-                       const lttng::sessiond::ust::registry_event& event, FormatCtx& ctx)
+       template <typename FormatContextType>
+       typename FormatContextType::iterator
+       format(const lttng::sessiond::ust::registry_event& event, FormatContextType& ctx)
        {
-               return format_to(ctx.out(),
-                               "{{ name = `{}`, signature = `{}`, id = {}, session objd = {}, channel objd = {} }}",
-                               event.name, event.signature, event.id, event.session_objd,
-                               event.channel_objd);
+               return format_to(
+                       ctx.out(),
+                       "{{ name = `{}`, signature = `{}`, id = {}, session objd = {}, channel objd = {} }}",
+                       event.name,
+                       event.signature,
+                       event.id,
+                       event.session_objd,
+                       event.channel_objd);
        }
 };
 } /* namespace fmt */
index 7e091fdac7abff133e4138f9814bf582befce597..49dc60d5232090048c781d9f587a25fc79670925 100644 (file)
@@ -14,37 +14,37 @@ namespace lst = lttng::sessiond::trace;
 namespace lsu = lttng::sessiond::ust;
 
 lsu::registry_session_per_pid::registry_session_per_pid(const struct ust_app& app,
-               const struct lst::abi& in_abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id) :
-       registry_session{in_abi, major, minor, root_shm_path, shm_path, euid, egid, tracing_id},
-       _tracer_patch_level_version{app.version.patchlevel},
-       _vpid{app.pid},
-       _procname{app.name},
-       _app_creation_time{app.registration_time}
+                                                       const struct lst::abi& in_abi,
+                                                       uint32_t major,
+                                                       uint32_t minor,
+                                                       const char *root_shm_path,
+                                                       const char *shm_path,
+                                                       uid_t euid,
+                                                       gid_t egid,
+                                                       uint64_t tracing_id) :
+       registry_session{ in_abi, major, minor, root_shm_path, shm_path, euid, egid, tracing_id },
+       _tracer_patch_level_version{ app.version.patchlevel },
+       _vpid{ app.pid },
+       _procname{ app.name },
+       _app_creation_time{ app.registration_time }
 {
        lttng::pthread::lock_guard registry_lock(_lock);
        _generate_metadata();
 }
 
-lttng_buffer_type lsu::registry_session_per_pid::get_buffering_scheme() const noexcept
+lttng_buffer_type lsu::registry_session_per_pid::buffering_scheme() const noexcept
 {
        return LTTNG_BUFFER_PER_PID;
 }
 
-void lsu::registry_session_per_pid::_visit_environment(lst::trace_class_visitor& visitor) const
+void lsu::registry_session_per_pid::accept(lst::trace_class_environment_visitor& visitor) const
 {
-       registry_session::_visit_environment(visitor);
+       registry_session::accept(visitor);
        visitor.visit(lst::environment_field<int64_t>("tracer_buffering_id", _vpid));
-       visitor.visit(lst::environment_field<int64_t>(
-                       "tracer_patchlevel", _tracer_patch_level_version));
+       visitor.visit(
+               lst::environment_field<int64_t>("tracer_patchlevel", _tracer_patch_level_version));
        visitor.visit(lst::environment_field<int64_t>("vpid", _vpid));
        visitor.visit(lst::environment_field<std::string>("procname", _procname));
        visitor.visit(lst::environment_field<std::string>(
-                       "vpid_datetime", lttng::utils::time_to_iso8601_str(_app_creation_time)));
+               "vpid_datetime", lttng::utils::time_to_iso8601_str(_app_creation_time)));
 }
index aa6cfb91b99e0f74b80de327a41bb079a614434a..4bdbe4a738c7a5738aa4ba0a4c2b202d354ac26f 100644 (file)
 #include "trace-class.hpp"
 #include "ust-registry-session.hpp"
 
+#include <lttng/lttng.h>
+
 #include <cstdint>
 #include <ctime>
-#include <lttng/lttng.h>
 #include <string>
 #include <unistd.h>
 
@@ -24,22 +25,20 @@ namespace ust {
 class registry_session_per_pid : public registry_session {
 public:
        registry_session_per_pid(const struct ust_app& app,
-                       const struct lttng::sessiond::trace::abi& trace_abi,
-                       uint32_t major,
-                       uint32_t minor,
-                       const char *root_shm_path,
-                       const char *shm_path,
-                       uid_t euid,
-                       gid_t egid,
-                       uint64_t tracing_id);
-
-       virtual lttng_buffer_type get_buffering_scheme() const noexcept override final;
+                                const struct lttng::sessiond::trace::abi& trace_abi,
+                                uint32_t major,
+                                uint32_t minor,
+                                const char *root_shm_path,
+                                const char *shm_path,
+                                uid_t euid,
+                                gid_t egid,
+                                uint64_t tracing_id);
+
+       lttng_buffer_type buffering_scheme() const noexcept final;
+       void accept(lttng::sessiond::trace::trace_class_environment_visitor& environment_visitor)
+               const final;
 
 private:
-       virtual void _visit_environment(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor)
-                       const override final;
-
        const unsigned int _tracer_patch_level_version;
        const pid_t _vpid;
        const std::string _procname;
index 8aa79dd7b5bb54bbfb0f5f353bd75c3a7a72fa4d..f5e1a93c2630d02bd9c59bea1256b85a3b8af42b 100644 (file)
 namespace lst = lttng::sessiond::trace;
 namespace lsu = lttng::sessiond::ust;
 
-lsu::registry_session_per_uid::registry_session_per_uid(
-               const struct lst::abi& in_abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id,
-               uid_t tracing_uid) :
-       registry_session{in_abi, major, minor, root_shm_path, shm_path, euid, egid, tracing_id},
-       _tracing_uid{tracing_uid}
+lsu::registry_session_per_uid::registry_session_per_uid(const struct lst::abi& in_abi,
+                                                       uint32_t major,
+                                                       uint32_t minor,
+                                                       const char *root_shm_path,
+                                                       const char *shm_path,
+                                                       uid_t euid,
+                                                       gid_t egid,
+                                                       uint64_t tracing_id,
+                                                       uid_t tracing_uid) :
+       registry_session{ in_abi, major, minor, root_shm_path, shm_path, euid, egid, tracing_id },
+       _tracing_uid{ tracing_uid }
 {
        lttng::pthread::lock_guard registry_lock(_lock);
        _generate_metadata();
 }
 
-lttng_buffer_type lsu::registry_session_per_uid::get_buffering_scheme() const noexcept
+lttng_buffer_type lsu::registry_session_per_uid::buffering_scheme() const noexcept
 {
        return LTTNG_BUFFER_PER_UID;
 }
 
-void lsu::registry_session_per_uid::_visit_environment(lst::trace_class_visitor& visitor) const
+void lsu::registry_session_per_uid::accept(lst::trace_class_environment_visitor& visitor) const
 {
-       registry_session::_visit_environment(visitor);
+       registry_session::accept(visitor);
        visitor.visit(lst::environment_field<int64_t>("tracer_buffering_id", _tracing_uid));
 }
index 665bfa5d014bcd81217a4bf0655ebd28d4f906f6..d7de5ebfb9c7da0e60e0b6f08d746babe79d4a63 100644 (file)
@@ -11,8 +11,9 @@
 #include "trace-class.hpp"
 #include "ust-registry-session.hpp"
 
-#include <cstdint>
 #include <lttng/lttng.h>
+
+#include <cstdint>
 #include <unistd.h>
 
 namespace lttng {
@@ -22,22 +23,20 @@ namespace ust {
 class registry_session_per_uid : public registry_session {
 public:
        registry_session_per_uid(const struct lttng::sessiond::trace::abi& trace_abi,
-                       uint32_t major,
-                       uint32_t minor,
-                       const char *root_shm_path,
-                       const char *shm_path,
-                       uid_t euid,
-                       gid_t egid,
-                       uint64_t tracing_id,
-                       uid_t tracing_uid);
-
-       virtual lttng_buffer_type get_buffering_scheme() const noexcept override final;
+                                uint32_t major,
+                                uint32_t minor,
+                                const char *root_shm_path,
+                                const char *shm_path,
+                                uid_t euid,
+                                gid_t egid,
+                                uint64_t tracing_id,
+                                uid_t tracing_uid);
+
+       lttng_buffer_type buffering_scheme() const noexcept final;
+       void accept(lttng::sessiond::trace::trace_class_environment_visitor& environment_visitor)
+               const final;
 
 private:
-       virtual void _visit_environment(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor)
-                       const override final;
-
        const uid_t _tracing_uid;
 };
 
index eced786e0446836f54ffbadf47a0607f5eb04775..d0891fe9a87325a3d245e52cbe001c5a2c401c41 100644 (file)
@@ -5,6 +5,7 @@
  *
  */
 
+#include "ctf2-trace-class-visitor.hpp"
 #include "field.hpp"
 #include "lttng-sessiond.hpp"
 #include "notification-thread-commands.hpp"
@@ -29,6 +30,7 @@
 
 #include <fcntl.h>
 #include <functional>
+#include <initializer_list>
 #include <mutex>
 #include <sstream>
 #include <string>
@@ -66,7 +68,9 @@ void clear_metadata_file(int fd)
 {
        const auto lseek_ret = lseek(fd, 0, SEEK_SET);
        if (lseek_ret < 0) {
-               LTTNG_THROW_POSIX("Failed to seek to the beginning of the metadata file while clearing it", errno);
+               LTTNG_THROW_POSIX(
+                       "Failed to seek to the beginning of the metadata file while clearing it",
+                       errno);
        }
 
        const auto ret = ftruncate(fd, 0);
@@ -111,8 +115,7 @@ void destroy_channel(lsu::registry_channel *chan, bool notify) noexcept
 
        if (notify) {
                cmd_ret = notification_thread_command_remove_channel(
-                               the_notification_thread_handle,
-                               chan->_consumer_key, LTTNG_DOMAIN_UST);
+                       the_notification_thread_handle, chan->_consumer_key, LTTNG_DOMAIN_UST);
                if (cmd_ret != LTTNG_OK) {
                        ERR("Failed to remove channel from notification thread");
                }
@@ -124,8 +127,7 @@ void destroy_channel(lsu::registry_channel *chan, bool notify) noexcept
                /* Destroy all event associated with this registry. */
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-               cds_lfht_for_each_entry(
-                               chan->_events->ht, &iter.iter, event, _node) {
+               cds_lfht_for_each_entry (chan->_events->ht, &iter.iter, event, _node) {
                        /* Delete the node from the ht and free it. */
                        ust_registry_channel_destroy_event(chan, event);
                }
@@ -170,8 +172,7 @@ int ht_match_enum(struct cds_lfht_node *node, const void *_key)
 
        DIAGNOSTIC_PUSH
        DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-       _enum = caa_container_of(node, lsu::registry_enum,
-                       node.node);
+       _enum = caa_container_of(node, lsu::registry_enum, node.node);
        DIAGNOSTIC_POP
 
        LTTNG_ASSERT(_enum);
@@ -221,7 +222,6 @@ unsigned long ht_hash_enum(void *_key, unsigned long seed)
        LTTNG_ASSERT(key);
        return hash_key_str(key->name.c_str(), seed);
 }
-
 } /* namespace */
 
 void lsu::details::locked_registry_session_release(lsu::registry_session *session)
@@ -230,29 +230,29 @@ void lsu::details::locked_registry_session_release(lsu::registry_session *sessio
 }
 
 lsu::registry_session::registry_session(const struct lst::abi& in_abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id) :
+                                       uint32_t major,
+                                       uint32_t minor,
+                                       const char *root_shm_path,
+                                       const char *shm_path,
+                                       uid_t euid,
+                                       gid_t egid,
+                                       uint64_t tracing_id) :
        lst::trace_class(in_abi, generate_uuid_or_throw()),
-       _root_shm_path{root_shm_path ? root_shm_path : ""},
-       _shm_path{shm_path ? shm_path : ""},
-       _metadata_path{_shm_path.size() > 0 ?
-                       fmt::format("{}/metadata", _shm_path) : std::string("")},
-       _uid{euid},
-       _gid{egid},
-       _app_tracer_version{.major = major, .minor = minor},
-       _tracing_id{tracing_id},
-       _clock{lttng::make_unique<lsu::clock_class>()},
-       _metadata_generating_visitor{lttng::make_unique<ls::tsdl::trace_class_visitor>(abi,
-                       [this](const std::string& fragment) {
-                               _append_metadata_fragment(fragment);
-                       })}
-{
-       pthread_mutex_init(&_lock, NULL);
+       _root_shm_path{ root_shm_path ? root_shm_path : "" },
+       _shm_path{ shm_path ? shm_path : "" },
+       _metadata_path{ _shm_path.size() > 0 ? lttng::format("{}/metadata", _shm_path) :
+                                              std::string("") },
+       _uid{ euid },
+       _gid{ egid },
+       _app_tracer_version{ .major = major, .minor = minor },
+       _tracing_id{ tracing_id },
+       _clock{ lttng::make_unique<lsu::clock_class>() },
+       _metadata_generating_visitor{ lttng::make_unique<ls::tsdl::trace_class_visitor>(
+               abi,
+               [this](const std::string& fragment) { _append_metadata_fragment(fragment); }) },
+       _packet_header{ _create_packet_header() }
+{
+       pthread_mutex_init(&_lock, nullptr);
        if (_shm_path.size() > 0) {
                if (run_as_mkdir_recursive(_shm_path.c_str(), S_IRWXU | S_IRWXG, euid, egid)) {
                        LTTNG_THROW_POSIX("run_as_mkdir_recursive", errno);
@@ -261,11 +261,17 @@ lsu::registry_session::registry_session(const struct lst::abi& in_abi,
 
        if (_metadata_path.size() > 0) {
                /* Create metadata file. */
-               const int ret = run_as_open(_metadata_path.c_str(), O_WRONLY | O_CREAT | O_EXCL,
-                               S_IRUSR | S_IWUSR, euid, egid);
+               const int ret = run_as_open(_metadata_path.c_str(),
+                                           O_WRONLY | O_CREAT | O_EXCL,
+                                           S_IRUSR | S_IWUSR,
+                                           euid,
+                                           egid);
                if (ret < 0) {
-                       LTTNG_THROW_POSIX(fmt::format("Failed to open metadata file during registry session creation: path = {}",
-                                       _metadata_path), errno);
+                       LTTNG_THROW_POSIX(
+                               lttng::format(
+                                       "Failed to open metadata file during registry session creation: path = {}",
+                                       _metadata_path),
+                               errno);
                }
 
                _metadata_fd = ret;
@@ -277,8 +283,8 @@ lsu::registry_session::registry_session(const struct lst::abi& in_abi,
        }
 
        /* hash/match functions are specified at call site. */
-       _enums->match_fct = NULL;
-       _enums->hash_fct = NULL;
+       _enums->match_fct = nullptr;
+       _enums->hash_fct = nullptr;
 
        _channels.reset(lttng_ht_new(0, LTTNG_HT_TYPE_U64));
        if (!_channels) {
@@ -286,6 +292,63 @@ lsu::registry_session::registry_session(const struct lst::abi& in_abi,
        }
 }
 
+lst::type::cuptr lsu::registry_session::_create_packet_header() const
+{
+       lst::structure_type::fields packet_header_fields;
+
+       /* uint32_t magic */
+       packet_header_fields.emplace_back(lttng::make_unique<lst::field>(
+               "magic",
+               lttng::make_unique<lst::integer_type>(
+                       abi.uint32_t_alignment,
+                       abi.byte_order,
+                       32,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::HEXADECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::PACKET_MAGIC_NUMBER }))));
+
+       /* uuid */
+       packet_header_fields.emplace_back(lttng::make_unique<lst::field>(
+               "uuid",
+               lttng::make_unique<lst::static_length_blob_type>(
+                       0,
+                       16,
+                       std::initializer_list<lst::static_length_blob_type::role>(
+                               { lst::static_length_blob_type::role::METADATA_STREAM_UUID }))));
+
+       /* uint32_t stream_id */
+       packet_header_fields.emplace_back(lttng::make_unique<lst::field>(
+               "stream_id",
+               lttng::make_unique<lst::integer_type>(
+                       abi.uint32_t_alignment,
+                       abi.byte_order,
+                       32,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::DATA_STREAM_CLASS_ID }))));
+
+       /* uint64_t stream_instance_id */
+       packet_header_fields.emplace_back(lttng::make_unique<lst::field>(
+               "stream_instance_id",
+               lttng::make_unique<lst::integer_type>(
+                       abi.uint64_t_alignment,
+                       abi.byte_order,
+                       64,
+                       lst::integer_type::signedness::UNSIGNED,
+                       lst::integer_type::base::DECIMAL,
+                       std::initializer_list<lst::integer_type::role>(
+                               { lst::integer_type::role::DATA_STREAM_ID }))));
+
+       return lttng::make_unique<lst::structure_type>(0, std::move(packet_header_fields));
+}
+
+const lst::type *lsu::registry_session::packet_header() const noexcept
+{
+       return _packet_header.get();
+}
+
 /*
  * For a given enumeration in a registry, delete the entry and destroy
  * the enumeration.
@@ -325,7 +388,7 @@ lsu::registry_session::~registry_session()
                /* Destroy all event associated with this registry. */
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-               cds_lfht_for_each_entry(_channels->ht, &iter.iter, chan, _node.node) {
+               cds_lfht_for_each_entry (_channels->ht, &iter.iter, chan, _node.node) {
                        /* Delete the node from the ht and free it. */
                        ret = lttng_ht_del(_channels.get(), &iter);
                        LTTNG_ASSERT(!ret);
@@ -349,8 +412,10 @@ lsu::registry_session::~registry_session()
 
        if (_root_shm_path[0]) {
                /* Try to delete the directory hierarchy. */
-               (void) run_as_rmdir_recursive(_root_shm_path.c_str(), _uid, _gid,
-                               LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+               (void) run_as_rmdir_recursive(_root_shm_path.c_str(),
+                                             _uid,
+                                             _gid,
+                                             LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
        }
 
        /* Destroy the enum hash table */
@@ -386,39 +451,41 @@ void lsu::registry_session::add_channel(uint64_t key)
         * the metadata can be dumped for that event.
         */
        if (is_max_channel_id(_used_channel_id)) {
-               LTTNG_THROW_ERROR(fmt::format("Failed to allocate unique id for channel under session while adding channel"));
+               LTTNG_THROW_ERROR(lttng::format(
+                       "Failed to allocate unique id for channel under session while adding channel"));
        }
 
        auto chan = new lsu::registry_channel(
-                       _get_next_channel_id(),
-                       /* Registered channel listener. */
-                       [this](const lsu::registry_channel& registered_channel) {
-                               /*
-                                * Channel registration completed, serialize it's layout's
-                                * description.
-                                */
-                               registered_channel.accept(*_metadata_generating_visitor);
-                       },
-                       /* Added event listener. */
-                       [this](const lsu::registry_channel& channel,
-                                       const lsu::registry_event& added_event) {
-                               /*
-                                * The channel and its event classes will be dumped at once when
-                                * it is registered. This check prevents event classes from being
-                                * declared before their stream class.
-                                */
-                               if (channel.is_registered()) {
-                                       added_event.accept(*_metadata_generating_visitor);
-                               }
-                       });
+               _get_next_channel_id(),
+               abi,
+               _clock->name,
+               /* Registered channel listener. */
+               [this](const lsu::registry_channel& registered_channel) {
+                       /*
+                        * Channel registration completed, serialize it's layout's
+                        * description.
+                        */
+                       registered_channel.accept(*_metadata_generating_visitor);
+               },
+               /* Added event listener. */
+               [this](const lsu::registry_channel& channel,
+                      const lsu::registry_event& added_event) {
+                       /*
+                        * The channel and its event classes will be dumped at once when
+                        * it is registered. This check prevents event classes from being
+                        * declared before their stream class.
+                        */
+                       if (channel.is_registered()) {
+                               added_event.accept(*_metadata_generating_visitor);
+                       }
+               });
 
        lttng::urcu::read_lock_guard rcu_read_lock_guard;
        lttng_ht_node_init_u64(&chan->_node, key);
        lttng_ht_add_unique_u64(_channels.get(), &chan->_node);
 }
 
-lttng::sessiond::ust::registry_channel& lsu::registry_session::get_channel(
-               uint64_t channel_key) const
+lttng::sessiond::ust::registry_channel& lsu::registry_session::channel(uint64_t channel_key) const
 {
        lttng::urcu::read_lock_guard read_lock_guard;
        struct lttng_ht_node_u64 *node;
@@ -429,8 +496,8 @@ lttng::sessiond::ust::registry_channel& lsu::registry_session::get_channel(
        lttng_ht_lookup(_channels.get(), &channel_key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
        if (!node) {
-               LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                               "Invalid channel key provided: channel key = {}", channel_key));
+               LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                       "Invalid channel key provided: channel key = {}", channel_key));
        }
 
        DIAGNOSTIC_PUSH
@@ -447,16 +514,16 @@ void lsu::registry_session::remove_channel(uint64_t channel_key, bool notify)
        lttng::urcu::read_lock_guard read_lock_guard;
 
        ASSERT_LOCKED(_lock);
-       auto& channel = get_channel(channel_key);
+       auto& channel_to_remove = channel(channel_key);
 
-       iter.iter.node = &channel._node.node;
+       iter.iter.node = &channel_to_remove._node.node;
        ret = lttng_ht_del(_channels.get(), &iter);
        LTTNG_ASSERT(!ret);
-       destroy_channel(&channel, notify);
+       destroy_channel(&channel_to_remove, notify);
 }
 
-void lsu::registry_session::_visit_environment(
-               lttng::sessiond::trace::trace_class_visitor& visitor) const
+void lsu::registry_session::accept(
+       lttng::sessiond::trace::trace_class_environment_visitor& visitor) const
 {
        ASSERT_LOCKED(_lock);
 
@@ -464,8 +531,9 @@ void lsu::registry_session::_visit_environment(
        visitor.visit(lst::environment_field<const char *>("tracer_name", "lttng-ust"));
        visitor.visit(lst::environment_field<int64_t>("tracer_major", _app_tracer_version.major));
        visitor.visit(lst::environment_field<int64_t>("tracer_minor", _app_tracer_version.minor));
-       visitor.visit(lst::environment_field<const char *>("tracer_buffering_scheme",
-                       get_buffering_scheme() == LTTNG_BUFFER_PER_PID ? "pid" : "uid"));
+       visitor.visit(lst::environment_field<const char *>(
+               "tracer_buffering_scheme",
+               buffering_scheme() == LTTNG_BUFFER_PER_PID ? "pid" : "uid"));
        visitor.visit(lst::environment_field<int64_t>("architecture_bit_width", abi.bits_per_long));
 
        {
@@ -476,11 +544,12 @@ void lsu::registry_session::_visit_environment(
                LTTNG_ASSERT(session);
                ASSERT_LOCKED(session->lock);
 
-               visitor.visit(lst::environment_field<const char *>("trace_name",
-                               session->has_auto_generated_name ? DEFAULT_SESSION_NAME :
-                                                                        session->name));
-               visitor.visit(lst::environment_field<std::string>("trace_creation_datetime",
-                               lttng::utils::time_to_iso8601_str(session->creation_time)));
+               visitor.visit(lst::environment_field<const char *>(
+                       "trace_name",
+                       session->has_auto_generated_name ? DEFAULT_SESSION_NAME : session->name));
+               visitor.visit(lst::environment_field<std::string>(
+                       "trace_creation_datetime",
+                       lttng::utils::time_to_iso8601_str(session->creation_time)));
                visitor.visit(lst::environment_field<const char *>("hostname", session->hostname));
        }
 }
@@ -504,17 +573,16 @@ void lsu::registry_session::_accept_on_stream_classes(lst::trace_class_visitor&
 
                DIAGNOSTIC_PUSH
                DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-               cds_lfht_for_each_entry(_channels->ht, &channel_it.iter, channel, _node.node) {
+               cds_lfht_for_each_entry (_channels->ht, &channel_it.iter, channel, _node.node) {
                        sorted_stream_classes.emplace_back(channel);
                }
                DIAGNOSTIC_POP
        }
 
-       std::sort(sorted_stream_classes.begin(), sorted_stream_classes.end(),
-                       [](const lttng::sessiond::ust::registry_channel *a,
-                                       const lttng::sessiond::ust::registry_channel *b) {
-                               return a->id < b->id;
-                       });
+       std::sort(sorted_stream_classes.begin(),
+                 sorted_stream_classes.end(),
+                 [](const lttng::sessiond::ust::registry_channel *a,
+                    const lttng::sessiond::ust::registry_channel *b) { return a->id < b->id; });
 
        for (const auto stream_class : sorted_stream_classes) {
                stream_class->accept(visitor);
@@ -548,17 +616,19 @@ void lsu::registry_session::_increase_metadata_size(size_t reservation_length)
 
        /* Rounding the new allocation length to the next power of 2 would overflow. */
        if (new_alloc_len > (UINT32_MAX >> 1)) {
-               LTTNG_THROW_ERROR("Failed to reserve trace metadata storage as the new size would overflow");
+               LTTNG_THROW_ERROR(
+                       "Failed to reserve trace metadata storage as the new size would overflow");
        }
 
        /* The current allocation length is already the largest we can afford. */
        if ((old_alloc_len << 1) > (UINT32_MAX >> 1)) {
-               LTTNG_THROW_ERROR("Failed to reserve trace metadata storage as the max size was already reached");
+               LTTNG_THROW_ERROR(
+                       "Failed to reserve trace metadata storage as the max size was already reached");
        }
 
        if (new_alloc_len > old_alloc_len) {
-               new_alloc_len = std::max<size_t>(
-                               1U << get_count_order(new_alloc_len), old_alloc_len << 1);
+               new_alloc_len =
+                       std::max<size_t>(1U << get_count_order(new_alloc_len), old_alloc_len << 1);
 
                auto newptr = (char *) realloc(_metadata, new_alloc_len);
                if (!newptr) {
@@ -584,11 +654,10 @@ void lsu::registry_session::_append_metadata_fragment(const std::string& fragmen
 
        if (_metadata_fd >= 0) {
                const auto bytes_written =
-                               lttng_write(_metadata_fd, fragment.c_str(), fragment.size());
+                       lttng_write(_metadata_fd, fragment.c_str(), fragment.size());
 
                if (bytes_written != fragment.size()) {
-                       LTTNG_THROW_POSIX("Failed to write trace metadata fragment to file",
-                                       errno);
+                       LTTNG_THROW_POSIX("Failed to write trace metadata fragment to file", errno);
                }
        }
 }
@@ -607,7 +676,7 @@ void lsu::registry_session::_reset_metadata()
 
 void lsu::registry_session::_generate_metadata()
 {
-       accept(*_metadata_generating_visitor);
+       trace_class::accept(*_metadata_generating_visitor);
 }
 
 void lsu::registry_session::regenerate_metadata()
@@ -631,9 +700,9 @@ void lsu::registry_session::regenerate_metadata()
  * disposes of the object.
  */
 lsu::registry_enum::const_rcu_protected_reference
-lsu::registry_session::get_enumeration(const char *enum_name, uint64_t enum_id) const
+lsu::registry_session::enumeration(const char *enum_name, uint64_t enum_id) const
 {
-       lsu::registry_enum *reg_enum = NULL;
+       lsu::registry_enum *reg_enum = nullptr;
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
        lttng::urcu::unique_read_lock rcu_lock;
@@ -648,12 +717,15 @@ lsu::registry_session::get_enumeration(const char *enum_name, uint64_t enum_id)
        reg_enum_lookup.id = enum_id;
        cds_lfht_lookup(_enums->ht,
                        ht_hash_enum((void *) &reg_enum_lookup, lttng_ht_seed),
-                       ht_match_enum_id, &reg_enum_lookup, &iter.iter);
+                       ht_match_enum_id,
+                       &reg_enum_lookup,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
        if (!node) {
-               LTTNG_THROW_PROTOCOL_ERROR(fmt::format(
-                               "Unknown enumeration referenced by application event field: enum name = `{}`, enum id = {}",
-                               enum_name, enum_id));
+               LTTNG_THROW_PROTOCOL_ERROR(lttng::format(
+                       "Unknown enumeration referenced by application event field: enum name = `{}`, enum id = {}",
+                       enum_name,
+                       enum_id));
        }
 
        DIAGNOSTIC_PUSH
@@ -661,24 +733,27 @@ lsu::registry_session::get_enumeration(const char *enum_name, uint64_t enum_id)
        reg_enum = lttng::utils::container_of(node, &lsu::registry_enum::node);
        DIAGNOSTIC_POP
 
-       return lsu::registry_enum::const_rcu_protected_reference{*reg_enum, std::move(rcu_lock)};
+       return lsu::registry_enum::const_rcu_protected_reference{ *reg_enum, std::move(rcu_lock) };
 }
 
 /*
  * Lookup enumeration by name and comparing enumeration entries.
  * Needs to be called from RCU read-side critical section.
  */
-lsu::registry_enum *lsu::registry_session::_lookup_enum(
-               const lsu::registry_enum *reg_enum_lookup) const
+lsu::registry_enum *
+lsu::registry_session::_lookup_enum(const lsu::registry_enum *reg_enum_lookup) const
 {
-       lsu::registry_enum *reg_enum = NULL;
+       lsu::registry_enum *reg_enum = nullptr;
        struct lttng_ht_node_str *node;
        struct lttng_ht_iter iter;
 
        ASSERT_RCU_READ_LOCKED();
 
-       cds_lfht_lookup(_enums->ht, ht_hash_enum((void *) reg_enum_lookup, lttng_ht_seed),
-                       ht_match_enum, reg_enum_lookup, &iter.iter);
+       cds_lfht_lookup(_enums->ht,
+                       ht_hash_enum((void *) reg_enum_lookup, lttng_ht_seed),
+                       ht_match_enum,
+                       reg_enum_lookup,
+                       &iter.iter);
        node = lttng_ht_iter_get_node_str(&iter);
        if (!node) {
                goto end;
@@ -701,15 +776,17 @@ end:
  *
  * We receive ownership of entries.
  */
-void lsu::registry_session::create_or_find_enum(
-               int session_objd, const char *enum_name,
-               struct lttng_ust_ctl_enum_entry *raw_entries, size_t nr_entries,
-               uint64_t *enum_id)
+void lsu::registry_session::create_or_find_enum(int session_objd,
+                                               const char *enum_name,
+                                               struct lttng_ust_ctl_enum_entry *raw_entries,
+                                               size_t nr_entries,
+                                               uint64_t *enum_id)
 {
        struct cds_lfht_node *nodep;
-       lsu::registry_enum *reg_enum = NULL, *old_reg_enum;
+       lsu::registry_enum *reg_enum = nullptr, *old_reg_enum;
        lttng::urcu::read_lock_guard read_lock_guard;
-       auto entries = lttng::make_unique_wrapper<lttng_ust_ctl_enum_entry, lttng::free>(raw_entries);
+       auto entries = lttng::make_unique_wrapper<lttng_ust_ctl_enum_entry, lttng::memory::free>(
+               raw_entries);
 
        LTTNG_ASSERT(enum_name);
 
@@ -718,27 +795,24 @@ void lsu::registry_session::create_or_find_enum(
         * external party, don't assert and simply validate values.
         */
        if (session_objd < 0) {
-               LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                               "Invalid parameters used to create or look-up enumeration from registry session: session_objd = {}",
-                               session_objd));
+               LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                       "Invalid parameters used to create or look-up enumeration from registry session: session_objd = {}",
+                       session_objd));
        }
        if (nr_entries == 0) {
-               LTTNG_THROW_INVALID_ARGUMENT_ERROR(fmt::format(
-                               "Invalid parameters used to create or look-up enumeration from registry session: nr_entries = {}",
-                               nr_entries));
+               LTTNG_THROW_INVALID_ARGUMENT_ERROR(lttng::format(
+                       "Invalid parameters used to create or look-up enumeration from registry session: nr_entries = {}",
+                       nr_entries));
        }
-       if (lttng_strnlen(enum_name, LTTNG_UST_ABI_SYM_NAME_LEN) ==
-                                       LTTNG_UST_ABI_SYM_NAME_LEN) {
+       if (lttng_strnlen(enum_name, LTTNG_UST_ABI_SYM_NAME_LEN) == LTTNG_UST_ABI_SYM_NAME_LEN) {
                LTTNG_THROW_INVALID_ARGUMENT_ERROR(
-                               "Invalid parameters used to create or look-up enumeration from registry session: enumeration name is not null terminated");
+                       "Invalid parameters used to create or look-up enumeration from registry session: enumeration name is not null terminated");
        }
 
        if (entries->start.signedness) {
-               reg_enum = new lsu::registry_signed_enum(
-                               enum_name, entries.get(), nr_entries);
+               reg_enum = new lsu::registry_signed_enum(enum_name, entries.get(), nr_entries);
        } else {
-               reg_enum = new lsu::registry_unsigned_enum(
-                               enum_name, entries.get(), nr_entries);
+               reg_enum = new lsu::registry_unsigned_enum(enum_name, entries.get(), nr_entries);
        }
 
        old_reg_enum = _lookup_enum(reg_enum);
@@ -748,22 +822,25 @@ void lsu::registry_session::create_or_find_enum(
                destroy_enum(reg_enum);
                reg_enum = old_reg_enum;
        } else {
-               DBG("UST registry creating enum: %s, sess_objd: %u",
-                               enum_name, session_objd);
+               DBG("UST registry creating enum: %s, sess_objd: %u", enum_name, session_objd);
                if (_next_enum_id == -1ULL) {
                        destroy_enum(reg_enum);
-                       LTTNG_THROW_ERROR("Failed to allocate unique enumeration ID as it would overflow");
+                       LTTNG_THROW_ERROR(
+                               "Failed to allocate unique enumeration ID as it would overflow");
                }
 
                reg_enum->id = _next_enum_id++;
                nodep = cds_lfht_add_unique(_enums->ht,
-                               ht_hash_enum(reg_enum, lttng_ht_seed),
-                               ht_match_enum_id, reg_enum,
-                               &reg_enum->node.node);
+                                           ht_hash_enum(reg_enum, lttng_ht_seed),
+                                           ht_match_enum_id,
+                                           reg_enum,
+                                           &reg_enum->node.node);
                LTTNG_ASSERT(nodep == &reg_enum->node.node);
        }
 
        DBG("UST registry reply with enum %s with id %" PRIu64 " in sess_objd: %u",
-                       enum_name, reg_enum->id, session_objd);
+           enum_name,
+           reg_enum->id,
+           session_objd);
        *enum_id = reg_enum->id;
 }
index 316703769fe57e92d2391fa36cb3159a28972bae..7f407e13ae6edcab0bbb0fba594589fa5edcdb03 100644 (file)
 
 #include <common/make-unique-wrapper.hpp>
 
+#include <lttng/lttng.h>
+
 #include <cstdint>
 #include <ctime>
-#include <lttng/lttng.h>
 #include <string>
 #include <unistd.h>
 
@@ -36,31 +37,39 @@ void locked_registry_session_release(registry_session *session);
 
 class registry_session : public lttng::sessiond::trace::trace_class {
 public:
-       using locked_ptr = std::unique_ptr<registry_session,
-                       lttng::details::create_unique_class<registry_session,
-                                       details::locked_registry_session_release>::
-                                       deleter>;
+       using locked_ptr =
+               std::unique_ptr<registry_session,
+                               lttng::memory::create_deleter_class<
+                                       registry_session,
+                                       details::locked_registry_session_release>::deleter>;
 
-       virtual lttng_buffer_type get_buffering_scheme() const noexcept = 0;
+       virtual lttng_buffer_type buffering_scheme() const noexcept = 0;
        locked_ptr lock() noexcept;
 
        void add_channel(uint64_t channel_key);
 
        /* A channel is protected by its parent registry session's lock. */
-       lttng::sessiond::ust::registry_channel& get_channel(uint64_t channel_key) const;
+       lttng::sessiond::ust::registry_channel& channel(uint64_t channel_key) const;
 
        void remove_channel(uint64_t channel_key, bool notify);
 
        void create_or_find_enum(int session_objd,
-                       const char *enum_name,
-                       struct lttng_ust_ctl_enum_entry *raw_entries,
-                       size_t nr_entries,
-                       uint64_t *enum_id);
-       registry_enum::const_rcu_protected_reference get_enumeration(
-                       const char *enum_name, uint64_t enum_id) const;
+                                const char *enum_name,
+                                struct lttng_ust_ctl_enum_entry *raw_entries,
+                                size_t nr_entries,
+                                uint64_t *enum_id);
+       registry_enum::const_rcu_protected_reference enumeration(const char *enum_name,
+                                                                uint64_t enum_id) const;
 
        void regenerate_metadata();
-       virtual ~registry_session();
+
+       ~registry_session() override;
+       registry_session(const registry_session&) = delete;
+       registry_session(registry_session&&) = delete;
+       registry_session& operator=(registry_session&&) = delete;
+       registry_session& operator=(const registry_session&) = delete;
+
+       const lttng::sessiond::trace::type *packet_header() const noexcept override;
 
        /*
         * With multiple writers and readers, use this lock to access
@@ -95,16 +104,14 @@ public:
 protected:
        /* Prevent instanciation of this base class. */
        registry_session(const struct lttng::sessiond::trace::abi& abi,
-                       unsigned int app_tracer_version_major,
-                       unsigned int app_tracer_version_minor,
-                       const char *root_shm_path,
-                       const char *shm_path,
-                       uid_t euid,
-                       gid_t egid,
-                       uint64_t tracing_id);
-       virtual void _visit_environment(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor)
-                       const override;
+                        unsigned int app_tracer_version_major,
+                        unsigned int app_tracer_version_minor,
+                        const char *root_shm_path,
+                        const char *shm_path,
+                        uid_t euid,
+                        gid_t egid,
+                        uint64_t tracing_id);
+       void accept(trace::trace_class_environment_visitor& environment_visitor) const override;
        void _generate_metadata();
 
 private:
@@ -114,13 +121,12 @@ private:
        void _reset_metadata();
        void _destroy_enum(registry_enum *reg_enum) noexcept;
        registry_enum *_lookup_enum(const registry_enum *target_enum) const;
+       lttng::sessiond::trace::type::cuptr _create_packet_header() const;
 
-       virtual void _accept_on_clock_classes(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor)
-                       const override final;
-       virtual void _accept_on_stream_classes(
-                       lttng::sessiond::trace::trace_class_visitor& trace_class_visitor)
-                       const override final;
+       void _accept_on_clock_classes(
+               lttng::sessiond::trace::trace_class_visitor& trace_class_visitor) const final;
+       void _accept_on_stream_classes(
+               lttng::sessiond::trace::trace_class_visitor& trace_class_visitor) const final;
 
        /* Next channel ID available for a newly registered channel. */
        uint32_t _next_channel_id = 0;
@@ -193,6 +199,7 @@ private:
 
        lttng::sessiond::ust::clock_class::cuptr _clock;
        const lttng::sessiond::trace::trace_class_visitor::cuptr _metadata_generating_visitor;
+       lttng::sessiond::trace::type::cuptr _packet_header;
 };
 
 } /* namespace ust */
index a6ceece9882dad64dfd20606eb2148446bad05e4..57aa2236fcbe08d7a26710462c038000dc462c98 100644 (file)
@@ -7,12 +7,12 @@
 
 #define _LGPL_SOURCE
 
-#include "ust-registry.hpp"
 #include "lttng-sessiond.hpp"
 #include "notification-thread-commands.hpp"
 #include "ust-app.hpp"
 #include "ust-registry-session-pid.hpp"
 #include "ust-registry-session-uid.hpp"
+#include "ust-registry.hpp"
 #include "utils.hpp"
 
 #include <common/common.hpp>
@@ -20,6 +20,7 @@
 #include <common/format.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/make-unique-wrapper.hpp>
+
 #include <lttng/lttng.h>
 
 #include <inttypes.h>
@@ -36,7 +37,7 @@ static void ust_registry_event_destroy_rcu(struct rcu_head *head)
        DIAGNOSTIC_PUSH
        DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
        lttng::sessiond::ust::registry_event *event =
-                       lttng::utils::container_of(head, &lttng::sessiond::ust::registry_event::_head);
+               lttng::utils::container_of(head, &lttng::sessiond::ust::registry_event::_head);
        DIAGNOSTIC_POP
 
        lttng::sessiond::ust::registry_event_destroy(event);
@@ -47,7 +48,7 @@ static void ust_registry_event_destroy_rcu(struct rcu_head *head)
  * This MUST be called within a RCU read side lock section.
  */
 void ust_registry_channel_destroy_event(lsu::registry_channel *chan,
-               lttng::sessiond::ust::registry_event *event)
+                                       lttng::sessiond::ust::registry_event *event)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -67,18 +68,25 @@ void ust_registry_channel_destroy_event(lsu::registry_channel *chan,
 }
 
 lsu::registry_session *ust_registry_session_per_uid_create(const lttng::sessiond::trace::abi& abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id,
-               uid_t tracing_uid)
+                                                          uint32_t major,
+                                                          uint32_t minor,
+                                                          const char *root_shm_path,
+                                                          const char *shm_path,
+                                                          uid_t euid,
+                                                          gid_t egid,
+                                                          uint64_t tracing_id,
+                                                          uid_t tracing_uid)
 {
        try {
-               return new lsu::registry_session_per_uid(abi, major, minor, root_shm_path, shm_path,
-                               euid, egid, tracing_id, tracing_uid);
+               return new lsu::registry_session_per_uid(abi,
+                                                        major,
+                                                        minor,
+                                                        root_shm_path,
+                                                        shm_path,
+                                                        euid,
+                                                        egid,
+                                                        tracing_id,
+                                                        tracing_uid);
        } catch (const std::exception& ex) {
                ERR("Failed to create per-uid registry session: %s", ex.what());
                return nullptr;
@@ -86,18 +94,18 @@ lsu::registry_session *ust_registry_session_per_uid_create(const lttng::sessiond
 }
 
 lsu::registry_session *ust_registry_session_per_pid_create(struct ust_app *app,
-               const lttng::sessiond::trace::abi& abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id)
+                                                          const lttng::sessiond::trace::abi& abi,
+                                                          uint32_t major,
+                                                          uint32_t minor,
+                                                          const char *root_shm_path,
+                                                          const char *shm_path,
+                                                          uid_t euid,
+                                                          gid_t egid,
+                                                          uint64_t tracing_id)
 {
        try {
-               return new lsu::registry_session_per_pid(*app, abi, major, minor, root_shm_path,
-                               shm_path, euid, egid, tracing_id);
+               return new lsu::registry_session_per_pid(
+                       *app, abi, major, minor, root_shm_path, shm_path, euid, egid, tracing_id);
        } catch (const std::exception& ex) {
                ERR("Failed to create per-pid registry session: %s", ex.what());
                return nullptr;
@@ -113,9 +121,9 @@ void ust_registry_session_destroy(lsu::registry_session *reg)
        delete reg;
 }
 
-lsu::registry_enum::registry_enum(
-               std::string in_name, enum lst::integer_type::signedness in_signedness) :
-       name{std::move(in_name)}, signedness{in_signedness}
+lsu::registry_enum::registry_enum(std::string in_name,
+                                 enum lst::integer_type::signedness in_signedness) :
+       name{ std::move(in_name) }, signedness{ in_signedness }
 {
        cds_lfht_node_init(&this->node.node);
        this->rcu_head = {};
index c438211005bbe9dd78c48ba0410cf0fb2f975075..4bb14be6fcc7d3a1f6c76ffa674bc847927c3650 100644 (file)
@@ -34,8 +34,8 @@
 #include <string>
 #include <type_traits>
 
-#define CTF_SPEC_MAJOR 1
-#define CTF_SPEC_MINOR 8
+#define CTF_SPEC_MAJOR 1
+#define CTF_SPEC_MINOR 8
 
 struct ust_app;
 
@@ -48,29 +48,28 @@ class registry_session;
 namespace details {
 
 template <class MappingIntegerType>
-typename trace::typed_enumeration_type<MappingIntegerType>::mapping mapping_from_ust_ctl_entry(
-               const lttng_ust_ctl_enum_entry& entry)
-{
-       if (entry.u.extra.options & LTTNG_UST_CTL_UST_ENUM_ENTRY_OPTION_IS_AUTO) {
-               return {entry.string};
-
-       } else {
-               return {entry.string,
-                               {(MappingIntegerType) entry.start.value,
-                                               (MappingIntegerType) entry.end.value}};
-       }
-}
-
-template <class MappingIntegerType>
-typename trace::typed_enumeration_type<MappingIntegerType>::mappings mappings_from_ust_ctl_entries(
-               const lttng_ust_ctl_enum_entry *in_entries, size_t in_entry_count)
+typename trace::typed_enumeration_type<MappingIntegerType>::mappings
+mappings_from_ust_ctl_entries(const lttng_ust_ctl_enum_entry *in_entries, size_t in_entry_count)
 {
        typename trace::typed_enumeration_type<MappingIntegerType>::mappings mappings;
 
+       MappingIntegerType next_range_begin = 0;
        for (size_t entry_idx = 0; entry_idx < in_entry_count; entry_idx++) {
                const auto& entry = in_entries[entry_idx];
-
-               mappings.emplace_back(mapping_from_ust_ctl_entry<MappingIntegerType>(entry));
+               MappingIntegerType range_begin, range_end;
+
+               if (entry.u.extra.options & LTTNG_UST_CTL_UST_ENUM_ENTRY_OPTION_IS_AUTO) {
+                       range_begin = range_end = next_range_begin;
+               } else {
+                       range_begin = (MappingIntegerType) entry.start.value;
+                       range_end = (MappingIntegerType) entry.end.value;
+               }
+
+               next_range_begin = range_end + 1;
+               mappings.emplace_back(
+                       entry.string,
+                       typename trace::typed_enumeration_type<MappingIntegerType>::mapping::range_t{
+                               range_begin, range_end });
        }
 
        return mappings;
@@ -79,10 +78,16 @@ typename trace::typed_enumeration_type<MappingIntegerType>::mappings mappings_fr
 
 class registry_enum {
 public:
-       using const_rcu_protected_reference = lttng::locked_reference<const registry_enum, lttng::urcu::unique_read_lock>;
+       using const_rcu_protected_reference =
+               lttng::locked_reference<const registry_enum, lttng::urcu::unique_read_lock>;
 
-       registry_enum(std::string name, enum lttng::sessiond::trace::integer_type::signedness signedness);
+       registry_enum(std::string name,
+                     enum lttng::sessiond::trace::integer_type::signedness signedness);
        virtual ~registry_enum() = default;
+       registry_enum(const registry_enum&) = delete;
+       registry_enum(registry_enum&&) = delete;
+       registry_enum& operator=(registry_enum&&) = delete;
+       registry_enum& operator=(const registry_enum&) = delete;
 
        std::string name;
        enum lttng::sessiond::trace::integer_type::signedness signedness;
@@ -94,6 +99,7 @@ public:
        struct rcu_head rcu_head;
 
        friend bool operator==(const registry_enum& lhs, const registry_enum& rhs) noexcept;
+
 protected:
        virtual bool _is_equal(const registry_enum& other) const noexcept = 0;
 };
@@ -104,27 +110,27 @@ template <class MappingIntegerType>
 class registry_typed_enum : public registry_enum {
 public:
        registry_typed_enum(const char *in_name,
-                       const lttng_ust_ctl_enum_entry *entries,
-                       size_t entry_count) :
+                           const lttng_ust_ctl_enum_entry *entries,
+                           size_t entry_count) :
                registry_enum(in_name,
-                               std::is_signed<MappingIntegerType>::value ?
-                                               lttng::sessiond::trace::integer_type::signedness::SIGNED :
-                                                     lttng::sessiond::trace::integer_type::signedness::UNSIGNED),
-               _mappings{std::make_shared<
-                               typename trace::typed_enumeration_type<MappingIntegerType>::mappings>(
-                               details::mappings_from_ust_ctl_entries<MappingIntegerType>(
-                                               entries, entry_count))}
+                             std::is_signed<MappingIntegerType>::value ?
+                                     lttng::sessiond::trace::integer_type::signedness::SIGNED :
+                                     lttng::sessiond::trace::integer_type::signedness::UNSIGNED),
+               _mappings{ std::make_shared<
+                       typename trace::typed_enumeration_type<MappingIntegerType>::mappings>(
+                       details::mappings_from_ust_ctl_entries<MappingIntegerType>(entries,
+                                                                                  entry_count)) }
        {
        }
 
        const typename std::shared_ptr<const typename lttng::sessiond::trace::typed_enumeration_type<
-                       MappingIntegerType>::mappings>
-                       _mappings;
+               MappingIntegerType>::mappings>
+               _mappings;
 
 protected:
-       virtual bool _is_equal(const registry_enum& base_other) const noexcept
+       bool _is_equal(const registry_enum& base_other) const noexcept override
        {
-               const auto &other = static_cast<decltype(*this)&>(base_other);
+               const autoother = static_cast<decltype(*this)&>(base_other);
 
                /* Don't compare IDs as some comparisons are performed before an id is assigned. */
                return this->name == other.name && *this->_mappings == *other._mappings;
@@ -145,112 +151,112 @@ using registry_unsigned_enum = registry_typed_enum<uint64_t>;
  *
  * Return new instance on success, nullptr on error.
  */
-lttng::sessiond::ust::registry_session *ust_registry_session_per_uid_create(
-               const lttng::sessiond::trace::abi& abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id,
-               uid_t tracing_uid);
+lttng::sessiond::ust::registry_session *
+ust_registry_session_per_uid_create(const lttng::sessiond::trace::abi& abi,
+                                   uint32_t major,
+                                   uint32_t minor,
+                                   const char *root_shm_path,
+                                   const char *shm_path,
+                                   uid_t euid,
+                                   gid_t egid,
+                                   uint64_t tracing_id,
+                                   uid_t tracing_uid);
 
 /*
  * Create per-pid registry with default values.
  *
  * Return new instance on success, nullptr on error.
  */
-lttng::sessiond::ust::registry_session *ust_registry_session_per_pid_create(struct ust_app *app,
-               const lttng::sessiond::trace::abi& abi,
-               uint32_t major,
-               uint32_t minor,
-               const char *root_shm_path,
-               const char *shm_path,
-               uid_t euid,
-               gid_t egid,
-               uint64_t tracing_id);
+lttng::sessiond::ust::registry_session *
+ust_registry_session_per_pid_create(struct ust_app *app,
+                                   const lttng::sessiond::trace::abi& abi,
+                                   uint32_t major,
+                                   uint32_t minor,
+                                   const char *root_shm_path,
+                                   const char *shm_path,
+                                   uid_t euid,
+                                   gid_t egid,
+                                   uint64_t tracing_id);
 void ust_registry_session_destroy(lttng::sessiond::ust::registry_session *session);
 
 void ust_registry_channel_destroy_event(lttng::sessiond::ust::registry_channel *chan,
-               lttng::sessiond::ust::registry_event *event);
+                                       lttng::sessiond::ust::registry_event *event);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-lttng::sessiond::ust::registry_session *ust_registry_session_per_uid_create(
-               uint32_t bits_per_long __attribute__((unused)),
-               uint32_t uint8_t_alignment __attribute__((unused)),
-               uint32_t uint16_t_alignment __attribute__((unused)),
-               uint32_t uint32_t_alignment __attribute__((unused)),
-               uint32_t uint64_t_alignment __attribute__((unused)),
-               uint32_t long_alignment __attribute__((unused)),
-               int byte_order __attribute__((unused)),
-               uint32_t major __attribute__((unused)),
-               uint32_t minor __attribute__((unused)),
-               const char *root_shm_path __attribute__((unused)),
-               const char *shm_path __attribute__((unused)),
-               uid_t euid __attribute__((unused)),
-               gid_t egid __attribute__((unused)),
-               uint64_t tracing_id __attribute__((unused)),
-               uid_t tracing_uid __attribute__((unused)))
+static inline lttng::sessiond::ust::registry_session *
+ust_registry_session_per_uid_create(uint32_t bits_per_long __attribute__((unused)),
+                                   uint32_t uint8_t_alignment __attribute__((unused)),
+                                   uint32_t uint16_t_alignment __attribute__((unused)),
+                                   uint32_t uint32_t_alignment __attribute__((unused)),
+                                   uint32_t uint64_t_alignment __attribute__((unused)),
+                                   uint32_t long_alignment __attribute__((unused)),
+                                   int byte_order __attribute__((unused)),
+                                   uint32_t major __attribute__((unused)),
+                                   uint32_t minor __attribute__((unused)),
+                                   const char *root_shm_path __attribute__((unused)),
+                                   const char *shm_path __attribute__((unused)),
+                                   uid_t euid __attribute__((unused)),
+                                   gid_t egid __attribute__((unused)),
+                                   uint64_t tracing_id __attribute__((unused)),
+                                   uid_t tracing_uid __attribute__((unused)))
 {
        return nullptr;
 }
 
-static inline
-lttng::sessiond::ust::registry_session *ust_registry_session_per_pid_create(
-               struct ust_app *app __attribute__((unused)),
-               uint32_t bits_per_long __attribute__((unused)),
-               uint32_t uint8_t_alignment __attribute__((unused)),
-               uint32_t uint16_t_alignment __attribute__((unused)),
-               uint32_t uint32_t_alignment __attribute__((unused)),
-               uint32_t uint64_t_alignment __attribute__((unused)),
-               uint32_t long_alignment __attribute__((unused)),
-               int byte_order __attribute__((unused)),
-               uint32_t major __attribute__((unused)),
-               uint32_t minor __attribute__((unused)),
-               const char *root_shm_path __attribute__((unused)),
-               const char *shm_path __attribute__((unused)),
-               uid_t euid __attribute__((unused)),
-               gid_t egid __attribute__((unused)),
-               uint64_t tracing_id __attribute__((unused)))
+static inline lttng::sessiond::ust::registry_session *
+ust_registry_session_per_pid_create(struct ust_app *app __attribute__((unused)),
+                                   uint32_t bits_per_long __attribute__((unused)),
+                                   uint32_t uint8_t_alignment __attribute__((unused)),
+                                   uint32_t uint16_t_alignment __attribute__((unused)),
+                                   uint32_t uint32_t_alignment __attribute__((unused)),
+                                   uint32_t uint64_t_alignment __attribute__((unused)),
+                                   uint32_t long_alignment __attribute__((unused)),
+                                   int byte_order __attribute__((unused)),
+                                   uint32_t major __attribute__((unused)),
+                                   uint32_t minor __attribute__((unused)),
+                                   const char *root_shm_path __attribute__((unused)),
+                                   const char *shm_path __attribute__((unused)),
+                                   uid_t euid __attribute__((unused)),
+                                   gid_t egid __attribute__((unused)),
+                                   uint64_t tracing_id __attribute__((unused)))
 {
        return nullptr;
 }
 
-static inline
-void ust_registry_session_destroy(
-               lttng::sessiond::ust::registry_session *session __attribute__((unused)))
-{}
+static inline void ust_registry_session_destroy(lttng::sessiond::ust::registry_session *session
+                                               __attribute__((unused)))
+{
+}
 
-static inline
-void ust_registry_destroy_event(
-               lttng::sessiond::ust::registry_channel *chan __attribute__((unused)),
-               lttng::sessiond::ust::registry_event *event __attribute__((unused)))
-{}
+static inline void ust_registry_destroy_event(lttng::sessiond::ust::registry_channel *chan
+                                             __attribute__((unused)),
+                                             lttng::sessiond::ust::registry_event *event
+                                             __attribute__((unused)))
+{
+}
 
 /* The app object can be NULL for registry shared across applications. */
-static inline
-int ust_metadata_session_statedump(
-               lttng::sessiond::ust::registry_session *session __attribute__((unused)))
+static inline int ust_metadata_session_statedump(lttng::sessiond::ust::registry_session *session
+                                                __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_metadata_channel_statedump(
-               lttng::sessiond::ust::registry_session *session __attribute__((unused)),
-               lttng::sessiond::ust::registry_channel *chan __attribute__((unused)))
+static inline int ust_metadata_channel_statedump(lttng::sessiond::ust::registry_session *session
+                                                __attribute__((unused)),
+                                                lttng::sessiond::ust::registry_channel *chan
+                                                __attribute__((unused)))
 {
        return 0;
 }
 
-static inline
-int ust_metadata_event_statedump(
-               lttng::sessiond::ust::registry_session *session __attribute__((unused)),
-               lttng::sessiond::ust::registry_channel *chan __attribute__((unused)),
-               lttng::sessiond::ust::registry_event *event __attribute__((unused)))
+static inline int ust_metadata_event_statedump(lttng::sessiond::ust::registry_session *session
+                                              __attribute__((unused)),
+                                              lttng::sessiond::ust::registry_channel *chan
+                                              __attribute__((unused)),
+                                              lttng::sessiond::ust::registry_event *event
+                                              __attribute__((unused)))
 {
        return 0;
 }
index cecaf4d584d244a5a54c2123dc9ce88e0d62c281..988c786572232df41f4a1ef06989c4211c722aca 100644 (file)
@@ -5,14 +5,15 @@
  *
  */
 
-#include <lttng/ust-sigbus.h>
-#include <lttng/ust-ctl.h>
-#include <lttng/lttng-export.h>
 #include "ust-sigbus.hpp"
 
+#include <lttng/lttng-export.h>
+#include <lttng/ust-ctl.h>
+#include <lttng/ust-sigbus.h>
+
 LTTNG_EXPORT DEFINE_LTTNG_UST_SIGBUS_STATE();
 
 void lttng_ust_handle_sigbus(void *address)
 {
-        lttng_ust_ctl_sigbus_handle(address);
+       lttng_ust_ctl_sigbus_handle(address);
 }
index 5c1ff2e7335be1202337c53468b167a50b0a0e25..f87a4aced738f17a40019fc82dc4601c6fea0ed5 100644 (file)
@@ -14,8 +14,7 @@ void lttng_ust_handle_sigbus(void *address);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-void lttng_ust_handle_sigbus(void *address __attribute__((unused)))
+static inline void lttng_ust_handle_sigbus(void *address __attribute__((unused)))
 {
 }
 
index f3446bc26c5b660a18e2611617f6c2fb4e7ce17b..b4d3c00a498b2644d34c7b7bccdf9a26d1ee2938 100644 (file)
@@ -7,14 +7,14 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdlib.h>
-#include <unistd.h>
+#include "lttng-sessiond.hpp"
+#include "snapshot.hpp"
+#include "utils.hpp"
 
 #include <common/error.hpp>
 
-#include "utils.hpp"
-#include "snapshot.hpp"
-#include "lttng-sessiond.hpp"
+#include <stdlib.h>
+#include <unistd.h>
 
 /*
  * Write to writable pipe used to notify a thread.
@@ -30,14 +30,18 @@ int notify_thread_pipe(int wpipe)
 
        ret = lttng_write(wpipe, "!", 1);
        if (ret < 1) {
-               PERROR("write poll pipe");
+               ret = -1;
+               PERROR("Failed to write to thread pipe");
        }
 
        return (int) ret;
 }
 
-int loglevels_match(int a_loglevel_type, int a_loglevel_value,
-       int b_loglevel_type, int b_loglevel_value, int loglevel_all_type)
+int loglevels_match(int a_loglevel_type,
+                   int a_loglevel_value,
+                   int b_loglevel_type,
+                   int b_loglevel_value,
+                   int loglevel_all_type)
 {
        int match = 1;
 
@@ -67,7 +71,6 @@ const char *session_get_base_path(const struct ltt_session *session)
 
 const char *consumer_output_get_base_path(const struct consumer_output *output)
 {
-       return output->type == CONSUMER_DST_LOCAL ?
-                       output->dst.session_root_path :
-                       output->dst.net.base_dir;
+       return output->type == CONSUMER_DST_LOCAL ? output->dst.session_root_path :
+                                                   output->dst.net.base_dir;
 }
index 5cbf7487ff5abb7a1b7e3cbbdcdfab550e754b5b..83117f426f46dff1b606e2bf7ef12c5876a98553 100644 (file)
@@ -12,10 +12,13 @@ struct lttng_ht;
 struct ltt_session;
 struct consumer_output;
 
-const char *get_home_dir(void);
+const char *get_home_dir();
 int notify_thread_pipe(int wpipe);
-int loglevels_match(int a_loglevel_type, int a_loglevel_value,
-       int b_loglevel_type, int b_loglevel_value, int loglevel_all_type);
+int loglevels_match(int a_loglevel_type,
+                   int a_loglevel_value,
+                   int b_loglevel_type,
+                   int b_loglevel_value,
+                   int loglevel_all_type);
 const char *session_get_base_path(const struct ltt_session *session);
 const char *consumer_output_get_base_path(const struct consumer_output *output);
 
index 09c5171d8f99f7b055b4bf7c7f25a1d57426c3fa..e3718374637deda24acccd4bc1ccc5c0cd7443ae 100644 (file)
@@ -34,7 +34,8 @@ lttng_SOURCES = command.hpp conf.cpp conf.hpp commands/start.cpp \
                                commands/list_triggers.cpp \
                                commands/remove_trigger.cpp \
                                utils.cpp utils.hpp lttng.cpp \
-                               uprobe.cpp uprobe.hpp
+                               uprobe.cpp uprobe.hpp \
+                               exception.hpp exception.cpp
 
 lttng_CXXFLAGS = $(AM_CXXFLAGS) $(POPT_CFLAGS)
 
index c707267cdbbed622d5b2d8685f8249dddf697657..2545104ed582e2dac77791da0a98d75661d1e4fc 100644 (file)
@@ -8,32 +8,32 @@
 #ifndef _LTTNG_CMD_H
 #define _LTTNG_CMD_H
 
-#include <lttng/lttng.h>
+#include "conf.hpp"
+#include "utils.hpp"
+
 #include <common/common.hpp>
 #include <common/defaults.hpp>
 
-#include "conf.hpp"
-#include "utils.hpp"
+#include <lttng/lttng.h>
 
-#define DECL_COMMAND(_name) \
-       extern int cmd_##_name(int, const char **)
+#define DECL_COMMAND(_name) extern int cmd_##_name(int, const char **)
 
 #ifdef LTTNG_EMBED_HELP
-# define HELP_MSG_NAME         help_msg
-# define SHOW_HELP_ERROR_LINE  ERR("Cannot show --help for `lttng-%s`", argv[0]);
+#define HELP_MSG_NAME       help_msg
+#define SHOW_HELP_ERROR_LINE ERR("Cannot show --help for `lttng-%s`", argv[0]);
 #else
-# define HELP_MSG_NAME         NULL
-# define SHOW_HELP_ERROR_LINE  ;
+#define HELP_MSG_NAME       NULL
+#define SHOW_HELP_ERROR_LINE ;
 #endif
 
-#define SHOW_HELP()                                                    \
-       do {                                                            \
-               ret = show_cmd_help(argv[0], HELP_MSG_NAME);            \
-                                                                       \
-               if (ret) {                                              \
-                       SHOW_HELP_ERROR_LINE                            \
-                       ret = CMD_ERROR;                                \
-               }                                                       \
+#define SHOW_HELP()                                          \
+       do {                                                 \
+               ret = show_cmd_help(argv[0], HELP_MSG_NAME); \
+                                                             \
+               if (ret) {                                   \
+                       SHOW_HELP_ERROR_LINE                 \
+                       ret = CMD_ERROR;                     \
+               }                                            \
        } while (0)
 
 enum cmd_error_code {
@@ -81,7 +81,6 @@ DECL_COMMAND(add_trigger);
 DECL_COMMAND(list_triggers);
 DECL_COMMAND(remove_trigger);
 
-extern int cmd_help(int argc, const char **argv,
-               const struct cmd_struct commands[]);
+extern int cmd_help(int argc, const char **argv, const struct cmd_struct commands[]);
 
 #endif /* _LTTNG_CMD_H */
index 5db0c5664888193d1b943558faf2ae4d3556a4aa..3a0613bd00d6f55c1d40fb5973035c6d90b4213e 100644 (file)
@@ -7,6 +7,12 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
+#include <lttng/domain-internal.hpp>
+
 #include <ctype.h>
 #include <popt.h>
 #include <stdio.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-
 #include <urcu/list.h>
 
-#include <lttng/domain-internal.hpp>
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-
 static char *opt_channel_name;
 static char *opt_session_name;
 static int opt_kernel;
@@ -34,7 +34,7 @@ static char *opt_type;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-add-context.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -54,49 +54,49 @@ static struct mi_writer *writer;
  * Taken from the LTTng ABI except for "UNKNOWN".
  */
 enum context_type {
-       CONTEXT_UNKNOWN      = -1,
-       CONTEXT_PID          = 0,
-       CONTEXT_PERF_COUNTER = 1,       /* Backward compat. */
-       CONTEXT_PROCNAME     = 2,
-       CONTEXT_PRIO         = 3,
-       CONTEXT_NICE         = 4,
-       CONTEXT_VPID         = 5,
-       CONTEXT_TID          = 6,
-       CONTEXT_VTID         = 7,
-       CONTEXT_PPID         = 8,
-       CONTEXT_VPPID        = 9,
-       CONTEXT_PTHREAD_ID   = 10,
-       CONTEXT_HOSTNAME     = 11,
-       CONTEXT_IP           = 12,
+       CONTEXT_UNKNOWN = -1,
+       CONTEXT_PID = 0,
+       CONTEXT_PERF_COUNTER = 1, /* Backward compat. */
+       CONTEXT_PROCNAME = 2,
+       CONTEXT_PRIO = 3,
+       CONTEXT_NICE = 4,
+       CONTEXT_VPID = 5,
+       CONTEXT_TID = 6,
+       CONTEXT_VTID = 7,
+       CONTEXT_PPID = 8,
+       CONTEXT_VPPID = 9,
+       CONTEXT_PTHREAD_ID = 10,
+       CONTEXT_HOSTNAME = 11,
+       CONTEXT_IP = 12,
        CONTEXT_PERF_CPU_COUNTER = 13,
        CONTEXT_PERF_THREAD_COUNTER = 14,
-       CONTEXT_APP_CONTEXT  = 15,
+       CONTEXT_APP_CONTEXT = 15,
        CONTEXT_INTERRUPTIBLE = 16,
-       CONTEXT_PREEMPTIBLE  = 17,
+       CONTEXT_PREEMPTIBLE = 17,
        CONTEXT_NEED_RESCHEDULE = 18,
-       CONTEXT_MIGRATABLE   = 19,
+       CONTEXT_MIGRATABLE = 19,
        CONTEXT_CALLSTACK_KERNEL = 20,
        CONTEXT_CALLSTACK_USER = 21,
-       CONTEXT_CGROUP_NS    = 22,
-       CONTEXT_IPC_NS       = 23,
-       CONTEXT_MNT_NS       = 24,
-       CONTEXT_NET_NS       = 25,
-       CONTEXT_PID_NS       = 26,
-       CONTEXT_USER_NS      = 27,
-       CONTEXT_UTS_NS       = 28,
-       CONTEXT_UID          = 29,
-       CONTEXT_EUID         = 30,
-       CONTEXT_SUID         = 31,
-       CONTEXT_GID          = 32,
-       CONTEXT_EGID         = 33,
-       CONTEXT_SGID         = 34,
-       CONTEXT_VUID         = 35,
-       CONTEXT_VEUID        = 36,
-       CONTEXT_VSUID        = 37,
-       CONTEXT_VGID         = 38,
-       CONTEXT_VEGID        = 39,
-       CONTEXT_VSGID        = 40,
-       CONTEXT_TIME_NS      = 41,
+       CONTEXT_CGROUP_NS = 22,
+       CONTEXT_IPC_NS = 23,
+       CONTEXT_MNT_NS = 24,
+       CONTEXT_NET_NS = 25,
+       CONTEXT_PID_NS = 26,
+       CONTEXT_USER_NS = 27,
+       CONTEXT_UTS_NS = 28,
+       CONTEXT_UID = 29,
+       CONTEXT_EUID = 30,
+       CONTEXT_SUID = 31,
+       CONTEXT_GID = 32,
+       CONTEXT_EGID = 33,
+       CONTEXT_SGID = 34,
+       CONTEXT_VUID = 35,
+       CONTEXT_VEUID = 36,
+       CONTEXT_VSUID = 37,
+       CONTEXT_VGID = 38,
+       CONTEXT_VEGID = 39,
+       CONTEXT_VSGID = 40,
+       CONTEXT_TIME_NS = 41,
 };
 
 /*
@@ -110,25 +110,25 @@ enum perf_type {
 };
 
 enum perf_count_hard {
-       PERF_COUNT_HW_CPU_CYCLES                = 0,
-       PERF_COUNT_HW_INSTRUCTIONS              = 1,
-       PERF_COUNT_HW_CACHE_REFERENCES          = 2,
-       PERF_COUNT_HW_CACHE_MISSES              = 3,
-       PERF_COUNT_HW_BRANCH_INSTRUCTIONS       = 4,
-       PERF_COUNT_HW_BRANCH_MISSES             = 5,
-       PERF_COUNT_HW_BUS_CYCLES                = 6,
-       PERF_COUNT_HW_STALLED_CYCLES_FRONTEND   = 7,
-       PERF_COUNT_HW_STALLED_CYCLES_BACKEND    = 8,
+       PERF_COUNT_HW_CPU_CYCLES = 0,
+       PERF_COUNT_HW_INSTRUCTIONS = 1,
+       PERF_COUNT_HW_CACHE_REFERENCES = 2,
+       PERF_COUNT_HW_CACHE_MISSES = 3,
+       PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4,
+       PERF_COUNT_HW_BRANCH_MISSES = 5,
+       PERF_COUNT_HW_BUS_CYCLES = 6,
+       PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7,
+       PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8,
 };
 
 enum perf_count_soft {
-       PERF_COUNT_SW_CPU_CLOCK        = 0,
-       PERF_COUNT_SW_TASK_CLOCK       = 1,
-       PERF_COUNT_SW_PAGE_FAULTS      = 2,
+       PERF_COUNT_SW_CPU_CLOCK = 0,
+       PERF_COUNT_SW_TASK_CLOCK = 1,
+       PERF_COUNT_SW_PAGE_FAULTS = 2,
        PERF_COUNT_SW_CONTEXT_SWITCHES = 3,
-       PERF_COUNT_SW_CPU_MIGRATIONS   = 4,
-       PERF_COUNT_SW_PAGE_FAULTS_MIN  = 5,
-       PERF_COUNT_SW_PAGE_FAULTS_MAJ  = 6,
+       PERF_COUNT_SW_CPU_MIGRATIONS = 4,
+       PERF_COUNT_SW_PAGE_FAULTS_MIN = 5,
+       PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6,
        PERF_COUNT_SW_ALIGNMENT_FAULTS = 7,
        PERF_COUNT_SW_EMULATION_FAULTS = 8,
 };
@@ -141,121 +141,121 @@ enum perf_count_soft {
  *       { accesses, misses }
  */
 enum perf_hw_cache_id {
-       PERF_COUNT_HW_CACHE_L1D                 = 0,
-       PERF_COUNT_HW_CACHE_L1I                 = 1,
-       PERF_COUNT_HW_CACHE_LL                  = 2,
-       PERF_COUNT_HW_CACHE_DTLB                = 3,
-       PERF_COUNT_HW_CACHE_ITLB                = 4,
-       PERF_COUNT_HW_CACHE_BPU                 = 5,
-
-       PERF_COUNT_HW_CACHE_MAX,                /* non-ABI */
+       PERF_COUNT_HW_CACHE_L1D = 0,
+       PERF_COUNT_HW_CACHE_L1I = 1,
+       PERF_COUNT_HW_CACHE_LL = 2,
+       PERF_COUNT_HW_CACHE_DTLB = 3,
+       PERF_COUNT_HW_CACHE_ITLB = 4,
+       PERF_COUNT_HW_CACHE_BPU = 5,
+
+       PERF_COUNT_HW_CACHE_MAX, /* non-ABI */
 };
 
 enum perf_hw_cache_op_id {
-       PERF_COUNT_HW_CACHE_OP_READ             = 0,
-       PERF_COUNT_HW_CACHE_OP_WRITE            = 1,
-       PERF_COUNT_HW_CACHE_OP_PREFETCH         = 2,
+       PERF_COUNT_HW_CACHE_OP_READ = 0,
+       PERF_COUNT_HW_CACHE_OP_WRITE = 1,
+       PERF_COUNT_HW_CACHE_OP_PREFETCH = 2,
 
-       PERF_COUNT_HW_CACHE_OP_MAX,             /* non-ABI */
+       PERF_COUNT_HW_CACHE_OP_MAX, /* non-ABI */
 };
 
 enum perf_hw_cache_op_result_id {
-       PERF_COUNT_HW_CACHE_RESULT_ACCESS       = 0,
-       PERF_COUNT_HW_CACHE_RESULT_MISS         = 1,
+       PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0,
+       PERF_COUNT_HW_CACHE_RESULT_MISS = 1,
 
-       PERF_COUNT_HW_CACHE_RESULT_MAX,         /* non-ABI */
+       PERF_COUNT_HW_CACHE_RESULT_MAX, /* non-ABI */
 };
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",        's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"channel",        'c', POPT_ARG_STRING, &opt_channel_name, 0, 0, 0},
-       {"kernel",         'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"userspace",      'u', POPT_ARG_NONE, 0, OPT_USERSPACE, 0, 0},
-       {"jul",            'j', POPT_ARG_NONE, 0, OPT_JUL, 0, 0},
-       {"log4j",          'l', POPT_ARG_NONE, 0, OPT_LOG4J, 0, 0},
-       {"type",           't', POPT_ARG_STRING, &opt_type, OPT_TYPE, 0, 0},
-       {"list",           0, POPT_ARG_NONE, NULL, OPT_LIST, NULL, NULL},
-       {"list-options",   0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "channel", 'c', POPT_ARG_STRING, &opt_channel_name, 0, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_NONE, nullptr, OPT_USERSPACE, nullptr, nullptr },
+       { "jul", 'j', POPT_ARG_NONE, nullptr, OPT_JUL, nullptr, nullptr },
+       { "log4j", 'l', POPT_ARG_NONE, nullptr, OPT_LOG4J, nullptr, nullptr },
+       { "type", 't', POPT_ARG_STRING, &opt_type, OPT_TYPE, nullptr, nullptr },
+       { "list", 0, POPT_ARG_NONE, nullptr, OPT_LIST, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
  * Context options
  */
-#define PERF_HW(optstr, name, type, hide)                              \
-       {                                                               \
-               optstr, type, PERF_COUNT_HW_##name, hide                \
+#define PERF_HW(optstr, name, type, hide)                \
+       {                                                \
+               optstr, type, PERF_COUNT_HW_##name, hide \
        }
 
-#define PERF_SW(optstr, name, type, hide)                              \
-       {                                                               \
-               optstr, type, PERF_COUNT_SW_##name, hide                \
+#define PERF_SW(optstr, name, type, hide)                \
+       {                                                \
+               optstr, type, PERF_COUNT_SW_##name, hide \
        }
 
-#define _PERF_HW_CACHE(optstr, name, type, op, result, hide)           \
-       {                                                               \
-               optstr, type,                                           \
-               PERF_COUNT_HW_CACHE_##name,                             \
-               PERF_COUNT_HW_CACHE_OP_##op,                            \
-               PERF_COUNT_HW_CACHE_RESULT_##result,                    \
-               hide,                                                   \
+#define _PERF_HW_CACHE(optstr, name, type, op, result, hide)                           \
+       {                                                                              \
+               optstr, type, PERF_COUNT_HW_CACHE_##name, PERF_COUNT_HW_CACHE_OP_##op, \
+                       PERF_COUNT_HW_CACHE_RESULT_##result, hide,                     \
        }
 
-#define PERF_HW_CACHE(optstr, name, type, hide)                                \
-       _PERF_HW_CACHE(optstr "-loads", name, type,                     \
-               READ, ACCESS, hide),                                    \
-       _PERF_HW_CACHE(optstr "-load-misses", name, type,               \
-               READ, MISS, hide),                                      \
-       _PERF_HW_CACHE(optstr "-stores", name, type,                    \
-               WRITE, ACCESS, hide),                                   \
-       _PERF_HW_CACHE(optstr "-store-misses", name, type,              \
-               WRITE, MISS, hide),                                     \
-       _PERF_HW_CACHE(optstr "-prefetches", name, type,                \
-               PREFETCH, ACCESS, hide),                                \
-       _PERF_HW_CACHE(optstr "-prefetch-misses", name, type,           \
-               PREFETCH, MISS, hide)
+#define PERF_HW_CACHE(optstr, name, type, hide)                                           \
+       _PERF_HW_CACHE(optstr "-loads", name, type, READ, ACCESS, hide),                  \
+               _PERF_HW_CACHE(optstr "-load-misses", name, type, READ, MISS, hide),      \
+               _PERF_HW_CACHE(optstr "-stores", name, type, WRITE, ACCESS, hide),        \
+               _PERF_HW_CACHE(optstr "-store-misses", name, type, WRITE, MISS, hide),    \
+               _PERF_HW_CACHE(optstr "-prefetches", name, type, PREFETCH, ACCESS, hide), \
+               _PERF_HW_CACHE(optstr "-prefetch-misses", name, type, PREFETCH, MISS, hide)
 
 namespace {
 const struct ctx_opts {
        /* Needed for end-of-list item. */
-       ctx_opts()
-               : ctx_opts(nullptr, CONTEXT_UNKNOWN)
-       {}
+       ctx_opts() : ctx_opts(nullptr, CONTEXT_UNKNOWN)
+       {
+       }
 
-       ctx_opts(const char *symbol_, context_type ctx_type_, bool hide_help_ = false)
-               : symbol((char *) symbol_), ctx_type(ctx_type_), hide_help(hide_help_)
-       {}
+       ctx_opts(const char *symbol_, context_type ctx_type_, bool hide_help_ = false) :
+               symbol((char *) symbol_), ctx_type(ctx_type_), hide_help(hide_help_)
+       {
+       }
 
-       ctx_opts(const char *symbol_, context_type ctx_type_, perf_count_hard perf_count_hard, bool hide_help_)
-               : ctx_opts(symbol_, ctx_type_, hide_help_)
+       ctx_opts(const char *symbol_,
+                context_type ctx_type_,
+                perf_count_hard perf_count_hard,
+                bool hide_help_) :
+               ctx_opts(symbol_, ctx_type_, hide_help_)
        {
                u.perf.type = PERF_TYPE_HARDWARE;
                u.perf.config = perf_count_hard;
        }
 
-       ctx_opts(const char *symbol_, context_type ctx_type_, perf_count_soft perf_count_soft, bool hide_help_)
-               : ctx_opts(symbol_, ctx_type_, hide_help_)
+       ctx_opts(const char *symbol_,
+                context_type ctx_type_,
+                perf_count_soft perf_count_soft,
+                bool hide_help_) :
+               ctx_opts(symbol_, ctx_type_, hide_help_)
        {
                u.perf.type = PERF_TYPE_SOFTWARE;
                u.perf.config = perf_count_soft;
        }
 
-       ctx_opts(const char *symbol_, context_type ctx_type_,
-                       perf_hw_cache_id perf_hw_cache_id,
-                       perf_hw_cache_op_id perf_hw_cache_op_id,
-                       perf_hw_cache_op_result_id perf_hw_cache_op_result_id,
-                       bool hide_help_)
-               : ctx_opts(symbol_, ctx_type_, hide_help_)
+       ctx_opts(const char *symbol_,
+                context_type ctx_type_,
+                perf_hw_cache_id perf_hw_cache_id,
+                perf_hw_cache_op_id perf_hw_cache_op_id,
+                perf_hw_cache_op_result_id perf_hw_cache_op_result_id,
+                bool hide_help_) :
+               ctx_opts(symbol_, ctx_type_, hide_help_)
        {
                u.perf.type = PERF_TYPE_HW_CACHE;
-               u.perf.config = perf_hw_cache_id | perf_hw_cache_op_id << 8 | perf_hw_cache_op_result_id << 16;
+               u.perf.config = perf_hw_cache_id | perf_hw_cache_op_id << 8 |
+                       perf_hw_cache_op_result_id << 16;
        }
 
        char *symbol;
        enum context_type ctx_type;
-       bool hide_help; /* Hide from --help */
+       bool hide_help; /* Hide from --help */
        union {
                struct {
                        uint32_t type;
@@ -315,219 +315,147 @@ const struct ctx_opts {
        /* Perf options */
 
        /* Perf per-CPU counters */
-       PERF_HW("perf:cpu:cpu-cycles", CPU_CYCLES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:cycles", CPU_CYCLES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:stalled-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:idle-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:stalled-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:idle-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:instructions", INSTRUCTIONS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:cache-references", CACHE_REFERENCES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:cache-misses", CACHE_MISSES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:branch-instructions", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:branches", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:branch-misses", BRANCH_MISSES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW("perf:cpu:bus-cycles", BUS_CYCLES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-
-       PERF_HW_CACHE("perf:cpu:L1-dcache", L1D,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW_CACHE("perf:cpu:L1-icache", L1I,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW_CACHE("perf:cpu:LLC", LL,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_HW_CACHE("perf:cpu:dTLB", DTLB,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       _PERF_HW_CACHE("perf:cpu:iTLB-loads", ITLB,
-               CONTEXT_PERF_CPU_COUNTER, READ, ACCESS, 0),
-       _PERF_HW_CACHE("perf:cpu:iTLB-load-misses", ITLB,
-               CONTEXT_PERF_CPU_COUNTER, READ, MISS, 0),
-       _PERF_HW_CACHE("perf:cpu:branch-loads", BPU,
-               CONTEXT_PERF_CPU_COUNTER, READ, ACCESS, 0),
-       _PERF_HW_CACHE("perf:cpu:branch-load-misses", BPU,
-               CONTEXT_PERF_CPU_COUNTER, READ, MISS, 0),
-
-       PERF_SW("perf:cpu:cpu-clock", CPU_CLOCK,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:task-clock", TASK_CLOCK,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:page-fault", PAGE_FAULTS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:faults", PAGE_FAULTS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:major-faults", PAGE_FAULTS_MAJ,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:minor-faults", PAGE_FAULTS_MIN,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:context-switches", CONTEXT_SWITCHES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:cs", CONTEXT_SWITCHES,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:cpu-migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:alignment-faults", ALIGNMENT_FAULTS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
-       PERF_SW("perf:cpu:emulation-faults", EMULATION_FAULTS,
-               CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:cpu-cycles", CPU_CYCLES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:cycles", CPU_CYCLES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:stalled-cycles-frontend",
+               STALLED_CYCLES_FRONTEND,
+               CONTEXT_PERF_CPU_COUNTER,
+               0),
+       PERF_HW("perf:cpu:idle-cycles-frontend",
+               STALLED_CYCLES_FRONTEND,
+               CONTEXT_PERF_CPU_COUNTER,
+               0),
+       PERF_HW("perf:cpu:stalled-cycles-backend",
+               STALLED_CYCLES_BACKEND,
+               CONTEXT_PERF_CPU_COUNTER,
+               0),
+       PERF_HW("perf:cpu:idle-cycles-backend", STALLED_CYCLES_BACKEND, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:instructions", INSTRUCTIONS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:cache-references", CACHE_REFERENCES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:cache-misses", CACHE_MISSES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:branch-instructions", BRANCH_INSTRUCTIONS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:branches", BRANCH_INSTRUCTIONS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:branch-misses", BRANCH_MISSES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW("perf:cpu:bus-cycles", BUS_CYCLES, CONTEXT_PERF_CPU_COUNTER, 0),
+
+       PERF_HW_CACHE("perf:cpu:L1-dcache", L1D, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW_CACHE("perf:cpu:L1-icache", L1I, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW_CACHE("perf:cpu:LLC", LL, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_HW_CACHE("perf:cpu:dTLB", DTLB, CONTEXT_PERF_CPU_COUNTER, 0),
+       _PERF_HW_CACHE("perf:cpu:iTLB-loads", ITLB, CONTEXT_PERF_CPU_COUNTER, READ, ACCESS, 0),
+       _PERF_HW_CACHE("perf:cpu:iTLB-load-misses", ITLB, CONTEXT_PERF_CPU_COUNTER, READ, MISS, 0),
+       _PERF_HW_CACHE("perf:cpu:branch-loads", BPU, CONTEXT_PERF_CPU_COUNTER, READ, ACCESS, 0),
+       _PERF_HW_CACHE("perf:cpu:branch-load-misses", BPU, CONTEXT_PERF_CPU_COUNTER, READ, MISS, 0),
+
+       PERF_SW("perf:cpu:cpu-clock", CPU_CLOCK, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:task-clock", TASK_CLOCK, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:page-fault", PAGE_FAULTS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:faults", PAGE_FAULTS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:major-faults", PAGE_FAULTS_MAJ, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:minor-faults", PAGE_FAULTS_MIN, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:context-switches", CONTEXT_SWITCHES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:cs", CONTEXT_SWITCHES, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:cpu-migrations", CPU_MIGRATIONS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:migrations", CPU_MIGRATIONS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:alignment-faults", ALIGNMENT_FAULTS, CONTEXT_PERF_CPU_COUNTER, 0),
+       PERF_SW("perf:cpu:emulation-faults", EMULATION_FAULTS, CONTEXT_PERF_CPU_COUNTER, 0),
 
        /* Perf per-thread counters */
-       PERF_HW("perf:thread:cpu-cycles", CPU_CYCLES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:cycles", CPU_CYCLES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:stalled-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:idle-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:stalled-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:idle-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:instructions", INSTRUCTIONS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:cache-references", CACHE_REFERENCES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:cache-misses", CACHE_MISSES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:branch-instructions", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:branches", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:branch-misses", BRANCH_MISSES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW("perf:thread:bus-cycles", BUS_CYCLES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-
-       PERF_HW_CACHE("perf:thread:L1-dcache", L1D,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW_CACHE("perf:thread:L1-icache", L1I,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW_CACHE("perf:thread:LLC", LL,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_HW_CACHE("perf:thread:dTLB", DTLB,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       _PERF_HW_CACHE("perf:thread:iTLB-loads", ITLB,
-               CONTEXT_PERF_THREAD_COUNTER, READ, ACCESS, 0),
-       _PERF_HW_CACHE("perf:thread:iTLB-load-misses", ITLB,
-               CONTEXT_PERF_THREAD_COUNTER, READ, MISS, 0),
-       _PERF_HW_CACHE("perf:thread:branch-loads", BPU,
-               CONTEXT_PERF_THREAD_COUNTER, READ, ACCESS, 0),
-       _PERF_HW_CACHE("perf:thread:branch-load-misses", BPU,
-               CONTEXT_PERF_THREAD_COUNTER, READ, MISS, 0),
-
-       PERF_SW("perf:thread:cpu-clock", CPU_CLOCK,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:task-clock", TASK_CLOCK,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:page-fault", PAGE_FAULTS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:faults", PAGE_FAULTS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:major-faults", PAGE_FAULTS_MAJ,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:minor-faults", PAGE_FAULTS_MIN,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:context-switches", CONTEXT_SWITCHES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:cs", CONTEXT_SWITCHES,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:cpu-migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:alignment-faults", ALIGNMENT_FAULTS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
-       PERF_SW("perf:thread:emulation-faults", EMULATION_FAULTS,
-               CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:cpu-cycles", CPU_CYCLES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:cycles", CPU_CYCLES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:stalled-cycles-frontend",
+               STALLED_CYCLES_FRONTEND,
+               CONTEXT_PERF_THREAD_COUNTER,
+               0),
+       PERF_HW("perf:thread:idle-cycles-frontend",
+               STALLED_CYCLES_FRONTEND,
+               CONTEXT_PERF_THREAD_COUNTER,
+               0),
+       PERF_HW("perf:thread:stalled-cycles-backend",
+               STALLED_CYCLES_BACKEND,
+               CONTEXT_PERF_THREAD_COUNTER,
+               0),
+       PERF_HW("perf:thread:idle-cycles-backend",
+               STALLED_CYCLES_BACKEND,
+               CONTEXT_PERF_THREAD_COUNTER,
+               0),
+       PERF_HW("perf:thread:instructions", INSTRUCTIONS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:cache-references", CACHE_REFERENCES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:cache-misses", CACHE_MISSES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:branch-instructions",
+               BRANCH_INSTRUCTIONS,
+               CONTEXT_PERF_THREAD_COUNTER,
+               0),
+       PERF_HW("perf:thread:branches", BRANCH_INSTRUCTIONS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:branch-misses", BRANCH_MISSES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW("perf:thread:bus-cycles", BUS_CYCLES, CONTEXT_PERF_THREAD_COUNTER, 0),
+
+       PERF_HW_CACHE("perf:thread:L1-dcache", L1D, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW_CACHE("perf:thread:L1-icache", L1I, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW_CACHE("perf:thread:LLC", LL, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_HW_CACHE("perf:thread:dTLB", DTLB, CONTEXT_PERF_THREAD_COUNTER, 0),
+       _PERF_HW_CACHE("perf:thread:iTLB-loads", ITLB, CONTEXT_PERF_THREAD_COUNTER, READ, ACCESS, 0),
+       _PERF_HW_CACHE(
+               "perf:thread:iTLB-load-misses", ITLB, CONTEXT_PERF_THREAD_COUNTER, READ, MISS, 0),
+       _PERF_HW_CACHE(
+               "perf:thread:branch-loads", BPU, CONTEXT_PERF_THREAD_COUNTER, READ, ACCESS, 0),
+       _PERF_HW_CACHE(
+               "perf:thread:branch-load-misses", BPU, CONTEXT_PERF_THREAD_COUNTER, READ, MISS, 0),
+
+       PERF_SW("perf:thread:cpu-clock", CPU_CLOCK, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:task-clock", TASK_CLOCK, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:page-fault", PAGE_FAULTS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:faults", PAGE_FAULTS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:major-faults", PAGE_FAULTS_MAJ, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:minor-faults", PAGE_FAULTS_MIN, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:context-switches", CONTEXT_SWITCHES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:cs", CONTEXT_SWITCHES, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:cpu-migrations", CPU_MIGRATIONS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:migrations", CPU_MIGRATIONS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:alignment-faults", ALIGNMENT_FAULTS, CONTEXT_PERF_THREAD_COUNTER, 0),
+       PERF_SW("perf:thread:emulation-faults", EMULATION_FAULTS, CONTEXT_PERF_THREAD_COUNTER, 0),
 
        /*
         * Perf per-CPU counters, backward compatibilty for names.
         * Hidden from help listing.
         */
-       PERF_HW("perf:cpu-cycles", CPU_CYCLES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:cycles", CPU_CYCLES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:stalled-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:idle-cycles-frontend", STALLED_CYCLES_FRONTEND,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:stalled-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:idle-cycles-backend", STALLED_CYCLES_BACKEND,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:instructions", INSTRUCTIONS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:cache-references", CACHE_REFERENCES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:cache-misses", CACHE_MISSES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:branch-instructions", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:branches", BRANCH_INSTRUCTIONS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:branch-misses", BRANCH_MISSES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW("perf:bus-cycles", BUS_CYCLES,
-               CONTEXT_PERF_COUNTER, 1),
-
-       PERF_HW_CACHE("perf:L1-dcache", L1D,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW_CACHE("perf:L1-icache", L1I,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW_CACHE("perf:LLC", LL,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_HW_CACHE("perf:dTLB", DTLB,
-               CONTEXT_PERF_COUNTER, 1),
-       _PERF_HW_CACHE("perf:iTLB-loads", ITLB,
-               CONTEXT_PERF_COUNTER, READ, ACCESS, 1),
-       _PERF_HW_CACHE("perf:iTLB-load-misses", ITLB,
-               CONTEXT_PERF_COUNTER, READ, MISS, 1),
-       _PERF_HW_CACHE("perf:branch-loads", BPU,
-               CONTEXT_PERF_COUNTER, READ, ACCESS, 1),
-       _PERF_HW_CACHE("perf:branch-load-misses", BPU,
-               CONTEXT_PERF_COUNTER, READ, MISS, 1),
-
-       PERF_SW("perf:cpu-clock", CPU_CLOCK,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:task-clock", TASK_CLOCK,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:page-fault", PAGE_FAULTS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:faults", PAGE_FAULTS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:major-faults", PAGE_FAULTS_MAJ,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:minor-faults", PAGE_FAULTS_MIN,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:context-switches", CONTEXT_SWITCHES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:cs", CONTEXT_SWITCHES,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:cpu-migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:migrations", CPU_MIGRATIONS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:alignment-faults", ALIGNMENT_FAULTS,
-               CONTEXT_PERF_COUNTER, 1),
-       PERF_SW("perf:emulation-faults", EMULATION_FAULTS,
-               CONTEXT_PERF_COUNTER, 1),
-
-       {},             /* Closure */
+       PERF_HW("perf:cpu-cycles", CPU_CYCLES, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:cycles", CPU_CYCLES, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:stalled-cycles-frontend", STALLED_CYCLES_FRONTEND, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:idle-cycles-frontend", STALLED_CYCLES_FRONTEND, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:stalled-cycles-backend", STALLED_CYCLES_BACKEND, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:idle-cycles-backend", STALLED_CYCLES_BACKEND, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:instructions", INSTRUCTIONS, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:cache-references", CACHE_REFERENCES, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:cache-misses", CACHE_MISSES, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:branch-instructions", BRANCH_INSTRUCTIONS, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:branches", BRANCH_INSTRUCTIONS, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:branch-misses", BRANCH_MISSES, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW("perf:bus-cycles", BUS_CYCLES, CONTEXT_PERF_COUNTER, 1),
+
+       PERF_HW_CACHE("perf:L1-dcache", L1D, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW_CACHE("perf:L1-icache", L1I, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW_CACHE("perf:LLC", LL, CONTEXT_PERF_COUNTER, 1),
+       PERF_HW_CACHE("perf:dTLB", DTLB, CONTEXT_PERF_COUNTER, 1),
+       _PERF_HW_CACHE("perf:iTLB-loads", ITLB, CONTEXT_PERF_COUNTER, READ, ACCESS, 1),
+       _PERF_HW_CACHE("perf:iTLB-load-misses", ITLB, CONTEXT_PERF_COUNTER, READ, MISS, 1),
+       _PERF_HW_CACHE("perf:branch-loads", BPU, CONTEXT_PERF_COUNTER, READ, ACCESS, 1),
+       _PERF_HW_CACHE("perf:branch-load-misses", BPU, CONTEXT_PERF_COUNTER, READ, MISS, 1),
+
+       PERF_SW("perf:cpu-clock", CPU_CLOCK, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:task-clock", TASK_CLOCK, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:page-fault", PAGE_FAULTS, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:faults", PAGE_FAULTS, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:major-faults", PAGE_FAULTS_MAJ, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:minor-faults", PAGE_FAULTS_MIN, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:context-switches", CONTEXT_SWITCHES, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:cs", CONTEXT_SWITCHES, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:cpu-migrations", CPU_MIGRATIONS, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:migrations", CPU_MIGRATIONS, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:alignment-faults", ALIGNMENT_FAULTS, CONTEXT_PERF_COUNTER, 1),
+       PERF_SW("perf:emulation-faults", EMULATION_FAULTS, CONTEXT_PERF_COUNTER, 1),
+
+       {}, /* Closure */
 };
 
 #undef PERF_HW_CACHE
@@ -563,7 +491,7 @@ static int find_ctx_type_idx(const char *opt)
 {
        int ret, i = 0;
 
-       while (ctx_opts[i].symbol != NULL) {
+       while (ctx_opts[i].symbol != nullptr) {
                if (strcmp(opt, ctx_opts[i].symbol) == 0) {
                        ret = i;
                        goto end;
@@ -576,8 +504,7 @@ end:
        return ret;
 }
 
-static
-enum lttng_domain_type get_domain(void)
+static enum lttng_domain_type get_domain()
 {
        if (opt_kernel) {
                return LTTNG_DOMAIN_KERNEL;
@@ -592,8 +519,7 @@ enum lttng_domain_type get_domain(void)
        }
 }
 
-static
-int mi_open(void)
+static int mi_open()
 {
        int ret;
 
@@ -617,16 +543,14 @@ int mi_open(void)
        }
 
        /* Open command element */
-       ret = mi_lttng_writer_command_open(writer,
-                       mi_lttng_element_command_add_context);
+       ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_add_context);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
        }
 
        /* Open output element */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_output);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
@@ -635,8 +559,7 @@ end:
        return ret;
 }
 
-static
-int mi_close(enum cmd_error_code success)
+static int mi_close(enum cmd_error_code success)
 {
        int ret;
 
@@ -653,8 +576,8 @@ int mi_close(enum cmd_error_code success)
        }
 
        /* Success ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       mi_lttng_element_command_success, !success);
+       ret = mi_lttng_writer_write_element_bool(
+               writer, mi_lttng_element_command_success, !success);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
@@ -670,9 +593,7 @@ end:
        return ret;
 }
 
-static
-void populate_context(struct lttng_event_context *context,
-               const struct ctx_opts *opt)
+static void populate_context(struct lttng_event_context *context, const struct ctx_opts *opt)
 {
        char *ptr;
 
@@ -683,22 +604,19 @@ void populate_context(struct lttng_event_context *context,
        case LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER:
                context->u.perf_counter.type = opt->u.perf.type;
                context->u.perf_counter.config = opt->u.perf.config;
-               strncpy(context->u.perf_counter.name, opt->symbol,
-                               LTTNG_SYMBOL_NAME_LEN);
+               strncpy(context->u.perf_counter.name, opt->symbol, LTTNG_SYMBOL_NAME_LEN);
                context->u.perf_counter.name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
                /* Replace : and - by _ */
-               while ((ptr = strchr(context->u.perf_counter.name, '-')) != NULL) {
+               while ((ptr = strchr(context->u.perf_counter.name, '-')) != nullptr) {
                        *ptr = '_';
                }
-               while ((ptr = strchr(context->u.perf_counter.name, ':')) != NULL) {
+               while ((ptr = strchr(context->u.perf_counter.name, ':')) != nullptr) {
                        *ptr = '_';
                }
                break;
        case LTTNG_EVENT_CONTEXT_APP_CONTEXT:
-               context->u.app_ctx.provider_name =
-                       opt->u.app_ctx.provider_name;
-               context->u.app_ctx.ctx_name =
-                       opt->u.app_ctx.ctx_name;
+               context->u.app_ctx.provider_name = opt->u.app_ctx.provider_name;
+               context->u.app_ctx.ctx_name = opt->u.app_ctx.ctx_name;
                break;
        default:
                break;
@@ -708,10 +626,8 @@ void populate_context(struct lttng_event_context *context,
 /*
  * Pretty print context type.
  */
-static
-int print_ctx_type(void)
+static int print_ctx_type()
 {
-
        FILE *ofp = stdout;
        int i = 0;
        int ret;
@@ -734,7 +650,7 @@ int print_ctx_type(void)
                }
        }
 
-       while (ctx_opts[i].symbol != NULL) {
+       while (ctx_opts[i].symbol != nullptr) {
                if (!ctx_opts[i].hide_help) {
                        if (lttng_opt_mi) {
                                populate_context(&context, &ctx_opts[i]);
@@ -745,9 +661,9 @@ int print_ctx_type(void)
                                }
 
                                ret = mi_lttng_writer_write_element_string(
-                                               writer,
-                                               mi_lttng_element_context_symbol,
-                                               ctx_opts[i].symbol);
+                                       writer,
+                                       mi_lttng_element_context_symbol,
+                                       ctx_opts[i].symbol);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
@@ -796,7 +712,7 @@ static int add_context(char *session_name)
 
        dom.type = get_domain();
        handle = lttng_create_handle(session_name, &dom);
-       if (handle == NULL) {
+       if (handle == nullptr) {
                ret = CMD_ERROR;
                goto error;
        }
@@ -810,7 +726,7 @@ static int add_context(char *session_name)
        }
 
        /* Iterate over all the context types given */
-       cds_list_for_each_entry(type, &ctx_type_list.head, list) {
+       cds_list_for_each_entry (type, &ctx_type_list.head, list) {
                DBG("Adding context...");
 
                populate_context(&context, type->opt);
@@ -823,16 +739,15 @@ static int add_context(char *session_name)
                                goto error;
                        }
 
-                       ret = mi_lttng_writer_write_element_string(writer,
-                                       mi_lttng_element_context_symbol,
-                                       type->opt->symbol);
+                       ret = mi_lttng_writer_write_element_string(
+                               writer, mi_lttng_element_context_symbol, type->opt->symbol);
                        if (ret) {
                                ret = CMD_ERROR;
                                goto error;
                        }
                }
 
-               ret = lttng_add_context(handle, &context, NULL, opt_channel_name);
+               ret = lttng_add_context(handle, &context, nullptr, opt_channel_name);
                if (ret < 0) {
                        ERR("%s: %s", type->opt->symbol, lttng_strerror(ret));
                        warn = 1;
@@ -840,21 +755,21 @@ static int add_context(char *session_name)
                } else {
                        if (opt_channel_name) {
                                MSG("%s context %s added to channel %s",
-                                               lttng_domain_type_str(dom.type),
-                                               type->opt->symbol,
-                                               opt_channel_name);
+                                   lttng_domain_type_str(dom.type),
+                                   type->opt->symbol,
+                                   opt_channel_name);
                        } else {
                                MSG("%s context %s added to all channels",
-                                               lttng_domain_type_str(dom.type),
-                                               type->opt->symbol);
+                                   lttng_domain_type_str(dom.type),
+                                   type->opt->symbol);
                        }
                        success = 1;
                }
 
                if (lttng_opt_mi) {
                        /* Is the single operation a success ? */
-                       ret = mi_lttng_writer_write_element_bool(writer,
-                                       mi_lttng_element_success, success);
+                       ret = mi_lttng_writer_write_element_bool(
+                               writer, mi_lttng_element_success, success);
                        if (ret) {
                                ret = CMD_ERROR;
                                goto error;
@@ -892,21 +807,26 @@ error:
        return ret;
 }
 
-static
-void destroy_ctx_type(struct ctx_type *type)
+static void destroy_ctx_type(struct ctx_type *type)
 {
        if (!type) {
                return;
        }
+
        if (type->opt) {
                free(type->opt->symbol);
+
+               if (type->opt->ctx_type == CONTEXT_APP_CONTEXT) {
+                       free(type->opt->u.app_ctx.ctx_name);
+                       free(type->opt->u.app_ctx.provider_name);
+               }
        }
+
        delete type->opt;
        free(type);
 }
 
-static
-struct ctx_type *create_ctx_type(void)
+static struct ctx_type *create_ctx_type()
 {
        struct ctx_type *type = zmalloc<ctx_type>();
 
@@ -919,15 +839,14 @@ struct ctx_type *create_ctx_type(void)
        if (!type->opt) {
                PERROR("malloc ctx_type options");
                destroy_ctx_type(type);
-               type = NULL;
+               type = nullptr;
                goto end;
        }
 end:
        return type;
 }
 
-static
-int find_ctx_type_perf_raw(const char *ctx, struct ctx_type *type)
+static int find_ctx_type_perf_raw(const char *ctx, struct ctx_type *type)
 {
        int ret;
        int field_pos = 0;
@@ -948,7 +867,7 @@ int find_ctx_type_perf_raw(const char *ctx, struct ctx_type *type)
                if (!next) {
                        break;
                }
-               cur_list = NULL;
+               cur_list = nullptr;
                switch (field_pos) {
                case 0:
                        if (strncmp(next, "perf", 4) != 0) {
@@ -982,7 +901,7 @@ int find_ctx_type_perf_raw(const char *ctx, struct ctx_type *type)
                                goto end;
                        }
                        errno = 0;
-                       type->opt->u.perf.config = strtoll(next +  1, &endptr, 16);
+                       type->opt->u.perf.config = strtoll(next + 1, &endptr, 16);
                        if (errno != 0 || !endptr || *endptr) {
                                ERR("Wrong perf raw mask format: expected rNNN");
                                ret = -1;
@@ -1003,8 +922,8 @@ int find_ctx_type_perf_raw(const char *ctx, struct ctx_type *type)
 
        if (field_pos < 5) {
                ERR("Invalid perf counter specifier, expected a specifier of "
-                       "the form perf:cpu:raw:rNNN:<name> or "
-                       "perf:thread:raw:rNNN:<name>");
+                   "the form perf:cpu:raw:rNNN:<name> or "
+                   "perf:thread:raw:rNNN:<name>");
                ret = -1;
                goto end;
        }
@@ -1017,13 +936,12 @@ end:
        return ret;
 }
 
-static
-struct ctx_type *get_context_type(const char *ctx)
+static struct ctx_type *get_context_type(const char *ctx)
 {
        int opt_index, ret;
-       struct ctx_type *type = NULL;
+       struct ctx_type *type = nullptr;
        const char app_ctx_prefix[] = "$app.";
-       char *provider_name = NULL, *ctx_name = NULL;
+       char *provider_name = nullptr, *ctx_name = nullptr;
        size_t i, len, colon_pos = 0, provider_name_len, ctx_name_len;
 
        if (!ctx) {
@@ -1065,7 +983,7 @@ struct ctx_type *get_context_type(const char *ctx)
        }
 
        /* String starts with $app. */
-       if (strncmp(ctx, app_ctx_prefix, sizeof(app_ctx_prefix) - 1)) {
+       if (strncmp(ctx, app_ctx_prefix, sizeof(app_ctx_prefix) - 1) != 0) {
                goto not_found;
        }
 
@@ -1083,8 +1001,7 @@ struct ctx_type *get_context_type(const char *ctx)
         * No colon found or no ctx name ("$app.provider:") or no provider name
         * given ("$app.:..."), which is invalid.
         */
-       if (!colon_pos || colon_pos == len ||
-                       colon_pos == sizeof(app_ctx_prefix)) {
+       if (!colon_pos || colon_pos == len || colon_pos == sizeof(app_ctx_prefix)) {
                ERR("Invalid application context provided: no provider or context name provided.");
                goto not_found;
        }
@@ -1095,8 +1012,7 @@ struct ctx_type *get_context_type(const char *ctx)
                PERROR("malloc provider_name");
                goto not_found;
        }
-       strncpy(provider_name, ctx + sizeof(app_ctx_prefix) - 1,
-                       provider_name_len - 1);
+       strncpy(provider_name, ctx + sizeof(app_ctx_prefix) - 1, provider_name_len - 1);
        type->opt->u.app_ctx.provider_name = provider_name;
 
        ctx_name_len = len - colon_pos;
@@ -1115,7 +1031,7 @@ not_found:
        free(provider_name);
        free(ctx_name);
        destroy_ctx_type(type);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1126,15 +1042,15 @@ int cmd_add_context(int argc, const char **argv)
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS;
        static poptContext pc;
        struct ctx_type *type, *tmptype;
-       char *session_name = NULL;
-       const char *leftover = NULL;
+       char *session_name = nullptr;
+       const char *leftover = nullptr;
 
        if (argc < 2) {
                ret = CMD_ERROR;
                goto end;
        }
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -1181,8 +1097,8 @@ int cmd_add_context(int argc, const char **argv)
                goto end;
        }
 
-       ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace + opt_jul + opt_log4j, true);
+       ret = print_missing_or_multiple_domains(opt_kernel + opt_userspace + opt_jul + opt_log4j,
+                                               true);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
@@ -1196,7 +1112,7 @@ int cmd_add_context(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -1227,7 +1143,7 @@ end:
        }
 
        /* Cleanup allocated memory */
-       cds_list_for_each_entry_safe(type, tmptype, &ctx_type_list.head, list) {
+       cds_list_for_each_entry_safe (type, tmptype, &ctx_type_list.head, list) {
                destroy_ctx_type(type);
        }
 
index 8619a822161eda44fbe2f61aceb7dedae8c07781..54f41f28bd0344fd29c5ad69b5be7e024a8d42cd 100644 (file)
@@ -5,28 +5,29 @@
  *
  */
 
-#include <ctype.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-
 #include "../command.hpp"
 #include "../loglevel.hpp"
 #include "../uprobe.hpp"
-
-#include "common/argpar/argpar.h"
 #include "common/argpar-utils/argpar-utils.hpp"
+#include "common/argpar/argpar.h"
 #include "common/dynamic-array.hpp"
 #include "common/mi-lttng.hpp"
 #include "common/string-utils/string-utils.hpp"
 #include "common/utils.hpp"
+
 #include <lttng/domain-internal.hpp>
+
+#include <ctype.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
 /* For lttng_event_rule_type_str(). */
-#include <lttng/event-rule/event-rule-internal.hpp>
-#include <lttng/lttng.h>
+#include "common/dynamic-array.hpp"
 #include "common/filter/filter-ast.hpp"
 #include "common/filter/filter-ir.hpp"
-#include "common/dynamic-array.hpp"
+
+#include <lttng/event-rule/event-rule-internal.hpp>
+#include <lttng/lttng.h>
 
 #if (LTTNG_SYMBOL_NAME_LEN == 256)
 #define LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "255"
@@ -35,7 +36,7 @@
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-add-trigger.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -82,22 +83,20 @@ static const struct argpar_opt_descr event_rule_opt_descrs[] = {
        ARGPAR_OPT_DESCR_SENTINEL
 };
 
-static
-bool has_syscall_prefix(const char *arg)
+static bool has_syscall_prefix(const char *arg)
 {
        bool matches = false;
        const char kernel_syscall_type_opt_prefix[] = "kernel:syscall";
        const size_t kernel_syscall_type_opt_prefix_len =
-                       sizeof(kernel_syscall_type_opt_prefix) - 1;
+               sizeof(kernel_syscall_type_opt_prefix) - 1;
        const char syscall_type_opt_prefix[] = "syscall";
-       const size_t syscall_type_opt_prefix_len =
-                       sizeof(syscall_type_opt_prefix) - 1;
+       const size_t syscall_type_opt_prefix_len = sizeof(syscall_type_opt_prefix) - 1;
 
-       if (strncmp(arg, syscall_type_opt_prefix,
-                           syscall_type_opt_prefix_len) == 0) {
+       if (strncmp(arg, syscall_type_opt_prefix, syscall_type_opt_prefix_len) == 0) {
                matches = true;
-       } else if (strncmp(arg, kernel_syscall_type_opt_prefix,
-                                  kernel_syscall_type_opt_prefix_len) == 0) {
+       } else if (strncmp(arg,
+                          kernel_syscall_type_opt_prefix,
+                          kernel_syscall_type_opt_prefix_len) == 0) {
                matches = true;
        } else {
                matches = false;
@@ -106,8 +105,7 @@ bool has_syscall_prefix(const char *arg)
        return matches;
 }
 
-static
-bool assign_event_rule_type(enum lttng_event_rule_type *dest, const char *arg)
+static bool assign_event_rule_type(enum lttng_event_rule_type *dest, const char *arg)
 {
        bool ret;
 
@@ -118,19 +116,15 @@ bool assign_event_rule_type(enum lttng_event_rule_type *dest, const char *arg)
 
        if (strcmp(arg, "user") == 0 || strcmp(arg, "user:tracepoint") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT;
-       } else if (strcmp(arg, "kernel") == 0 ||
-                       strcmp(arg, "kernel:tracepoint") == 0) {
+       } else if (strcmp(arg, "kernel") == 0 || strcmp(arg, "kernel:tracepoint") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT;
        } else if (strcmp(arg, "jul") == 0 || strcmp(arg, "jul:logging") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_JUL_LOGGING;
-       } else if (strcmp(arg, "log4j") == 0 ||
-                       strcmp(arg, "log4j:logging") == 0) {
+       } else if (strcmp(arg, "log4j") == 0 || strcmp(arg, "log4j:logging") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING;
-       } else if (strcmp(arg, "python") == 0 ||
-                       strcmp(arg, "python:logging") == 0) {
+       } else if (strcmp(arg, "python") == 0 || strcmp(arg, "python:logging") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING;
-       } else if (strcmp(arg, "kprobe") == 0 ||
-                       strcmp(arg, "kernel:kprobe") == 0) {
+       } else if (strcmp(arg, "kprobe") == 0 || strcmp(arg, "kernel:kprobe") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_KERNEL_KPROBE;
        } else if (strcmp(arg, "kernel:uprobe") == 0) {
                *dest = LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE;
@@ -166,8 +160,7 @@ end:
        return ret;
 }
 
-static
-bool assign_string(char **dest, const char *src, const char *opt_name)
+static bool assign_string(char **dest, const char *src, const char *opt_name)
 {
        bool ret;
 
@@ -192,8 +185,9 @@ end:
        return ret;
 }
 
-static bool parse_syscall_emission_site_from_type(const char *str,
-               enum lttng_event_rule_kernel_syscall_emission_site *type)
+static bool
+parse_syscall_emission_site_from_type(const char *str,
+                                     enum lttng_event_rule_kernel_syscall_emission_site *type)
 {
        bool ret = false;
        const char kernel_prefix[] = "kernel:";
@@ -207,8 +201,7 @@ static bool parse_syscall_emission_site_from_type(const char *str,
                str = &str[kernel_prefix_len];
        }
 
-       if (strcmp(str, "syscall") == 0 ||
-                       strcmp(str, "syscall:entry+exit") == 0) {
+       if (strcmp(str, "syscall") == 0 || strcmp(str, "syscall:entry+exit") == 0) {
                *type = LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY_EXIT;
        } else if (strcmp(str, "syscall:entry") == 0) {
                *type = LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY;
@@ -234,9 +227,9 @@ error:
  * Return true if the string was successfully parsed as a log level string.
  */
 static bool parse_log_level_string(const char *str,
-               enum lttng_event_rule_type event_rule_type,
-               int *log_level,
-               bool *log_level_only)
+                                  enum lttng_event_rule_type event_rule_type,
+                                  int *log_level,
+                                  bool *log_level_only)
 {
        bool ret;
 
@@ -244,14 +237,12 @@ static bool parse_log_level_string(const char *str,
        case LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT:
        {
                enum lttng_loglevel log_level_min, log_level_max;
-               if (!loglevel_parse_range_string(
-                                   str, &log_level_min, &log_level_max)) {
+               if (!loglevel_parse_range_string(str, &log_level_min, &log_level_max)) {
                        goto error;
                }
 
                /* Only support VAL and VAL.. for now. */
-               if (log_level_min != log_level_max &&
-                               log_level_max != LTTNG_LOGLEVEL_EMERG) {
+               if (log_level_min != log_level_max && log_level_max != LTTNG_LOGLEVEL_EMERG) {
                        goto error;
                }
 
@@ -262,14 +253,12 @@ static bool parse_log_level_string(const char *str,
        case LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING:
        {
                enum lttng_loglevel_log4j log_level_min, log_level_max;
-               if (!loglevel_log4j_parse_range_string(
-                                   str, &log_level_min, &log_level_max)) {
+               if (!loglevel_log4j_parse_range_string(str, &log_level_min, &log_level_max)) {
                        goto error;
                }
 
                /* Only support VAL and VAL.. for now. */
-               if (log_level_min != log_level_max &&
-                               log_level_max != LTTNG_LOGLEVEL_LOG4J_FATAL) {
+               if (log_level_min != log_level_max && log_level_max != LTTNG_LOGLEVEL_LOG4J_FATAL) {
                        goto error;
                }
 
@@ -280,14 +269,12 @@ static bool parse_log_level_string(const char *str,
        case LTTNG_EVENT_RULE_TYPE_JUL_LOGGING:
        {
                enum lttng_loglevel_jul log_level_min, log_level_max;
-               if (!loglevel_jul_parse_range_string(
-                                   str, &log_level_min, &log_level_max)) {
+               if (!loglevel_jul_parse_range_string(str, &log_level_min, &log_level_max)) {
                        goto error;
                }
 
                /* Only support VAL and VAL.. for now. */
-               if (log_level_min != log_level_max &&
-                               log_level_max != LTTNG_LOGLEVEL_JUL_SEVERE) {
+               if (log_level_min != log_level_max && log_level_max != LTTNG_LOGLEVEL_JUL_SEVERE) {
                        goto error;
                }
 
@@ -298,15 +285,13 @@ static bool parse_log_level_string(const char *str,
        case LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING:
        {
                enum lttng_loglevel_python log_level_min, log_level_max;
-               if (!loglevel_python_parse_range_string(
-                                   str, &log_level_min, &log_level_max)) {
+               if (!loglevel_python_parse_range_string(str, &log_level_min, &log_level_max)) {
                        goto error;
                }
 
                /* Only support VAL and VAL.. for now. */
                if (log_level_min != log_level_max &&
-                               log_level_max !=
-                                               LTTNG_LOGLEVEL_PYTHON_CRITICAL) {
+                   log_level_max != LTTNG_LOGLEVEL_PYTHON_CRITICAL) {
                        goto error;
                }
 
@@ -330,20 +315,18 @@ end:
 }
 
 static int parse_kernel_probe_opts(const char *source,
-               struct lttng_kernel_probe_location **location)
+                                  struct lttng_kernel_probe_location **location)
 {
        int ret = 0;
        int match;
        char s_hex[19];
        char name[LTTNG_SYMBOL_NAME_LEN];
-       char *symbol_name = NULL;
+       char *symbol_name = nullptr;
        uint64_t offset;
 
        /* Check for symbol+offset. */
-       match = sscanf(source,
-                       "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API
-                       "[^'+']+%18s",
-                       name, s_hex);
+       match = sscanf(
+               source, "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "[^'+']+%18s", name, s_hex);
        if (match == 2) {
                if (*s_hex == '\0') {
                        ERR("Kernel probe symbol offset is missing.");
@@ -355,10 +338,9 @@ static int parse_kernel_probe_opts(const char *source,
                        PERROR("Failed to copy kernel probe location symbol name.");
                        goto error;
                }
-               offset = strtoull(s_hex, NULL, 0);
+               offset = strtoull(s_hex, nullptr, 0);
 
-               *location = lttng_kernel_probe_location_symbol_create(
-                               symbol_name, offset);
+               *location = lttng_kernel_probe_location_symbol_create(symbol_name, offset);
                if (!*location) {
                        ERR("Failed to create symbol kernel probe location.");
                        goto error;
@@ -369,10 +351,7 @@ static int parse_kernel_probe_opts(const char *source,
 
        /* Check for symbol. */
        if (isalpha(name[0]) || name[0] == '_') {
-               match = sscanf(source,
-                               "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API
-                               "s",
-                               name);
+               match = sscanf(source, "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "s", name);
                if (match == 1) {
                        symbol_name = strndup(name, LTTNG_SYMBOL_NAME_LEN);
                        if (!symbol_name) {
@@ -380,8 +359,7 @@ static int parse_kernel_probe_opts(const char *source,
                                goto error;
                        }
 
-                       *location = lttng_kernel_probe_location_symbol_create(
-                                       symbol_name, 0);
+                       *location = lttng_kernel_probe_location_symbol_create(symbol_name, 0);
                        if (!*location) {
                                ERR("Failed to create symbol kernel probe location.");
                                goto error;
@@ -401,7 +379,7 @@ static int parse_kernel_probe_opts(const char *source,
                        goto error;
                }
 
-               address = strtoull(s_hex, NULL, 0);
+               address = strtoull(s_hex, nullptr, 0);
                *location = lttng_kernel_probe_location_address_create(address);
                if (!*location) {
                        ERR("Failed to create symbol kernel probe location.");
@@ -414,23 +392,20 @@ static int parse_kernel_probe_opts(const char *source,
 error:
        /* No match */
        ret = -1;
-       *location = NULL;
+       *location = nullptr;
 
 end:
        free(symbol_name);
        return ret;
 }
 
-static
-struct lttng_event_expr *ir_op_load_expr_to_event_expr(
-               const struct ir_load_expression *load_expr,
-               const char *capture_str)
+static struct lttng_event_expr *
+ir_op_load_expr_to_event_expr(const struct ir_load_expression *load_expr, const char *capture_str)
 {
-       char *provider_name = NULL;
-       struct lttng_event_expr *event_expr = NULL;
+       char *provider_name = nullptr;
+       struct lttng_event_expr *event_expr = nullptr;
        const struct ir_load_expression_op *load_expr_op = load_expr->child;
-       const enum ir_load_expression_type load_expr_child_type =
-                       load_expr_op->type;
+       const enum ir_load_expression_type load_expr_child_type = load_expr_op->type;
 
        switch (load_expr_child_type) {
        case IR_LOAD_EXPRESSION_GET_PAYLOAD_ROOT:
@@ -445,13 +420,14 @@ struct lttng_event_expr *ir_op_load_expr_to_event_expr(
                LTTNG_ASSERT(field_name);
 
                event_expr = load_expr_child_type == IR_LOAD_EXPRESSION_GET_PAYLOAD_ROOT ?
-                               lttng_event_expr_event_payload_field_create(field_name) :
-                               lttng_event_expr_channel_context_field_create(field_name);
+                       lttng_event_expr_event_payload_field_create(field_name) :
+                       lttng_event_expr_channel_context_field_create(field_name);
                if (!event_expr) {
                        ERR("Failed to create %s event expression: field name = `%s`.",
-                                       load_expr_child_type == IR_LOAD_EXPRESSION_GET_PAYLOAD_ROOT ?
-                                                       "payload field" : "channel context",
-                                                       field_name);
+                           load_expr_child_type == IR_LOAD_EXPRESSION_GET_PAYLOAD_ROOT ?
+                                   "payload field" :
+                                   "channel context",
+                           field_name);
                        goto error;
                }
 
@@ -476,14 +452,14 @@ struct lttng_event_expr *ir_op_load_expr_to_event_expr(
                colon = strchr(field_name, ':');
                if (!colon) {
                        ERR("Invalid app-specific context field name: missing colon in `%s`.",
-                                       field_name);
+                           field_name);
                        goto error;
                }
 
                type_name = colon + 1;
                if (*type_name == '\0') {
                        ERR("Invalid app-specific context field name: missing type name after colon in `%s`.",
-                                       field_name);
+                           field_name);
                        goto error;
                }
 
@@ -493,19 +469,19 @@ struct lttng_event_expr *ir_op_load_expr_to_event_expr(
                        goto error;
                }
 
-               event_expr = lttng_event_expr_app_specific_context_field_create(
-                               provider_name, type_name);
+               event_expr = lttng_event_expr_app_specific_context_field_create(provider_name,
+                                                                               type_name);
                if (!event_expr) {
                        ERR("Failed to create app-specific context field event expression: provider name = `%s`, type name = `%s`",
-                                       provider_name, type_name);
+                           provider_name,
+                           type_name);
                        goto error;
                }
 
                break;
        }
        default:
-               ERR("%s: unexpected load expr type %d.", __func__,
-                               load_expr_op->type);
+               ERR("%s: unexpected load expr type %d.", __func__, load_expr_op->type);
                abort();
        }
 
@@ -535,12 +511,13 @@ struct lttng_event_expr *ir_op_load_expr_to_event_expr(
                break;
        case IR_LOAD_EXPRESSION_GET_SYMBOL:
                ERR("While parsing expression `%s`: Capturing subfields is not supported.",
-                               capture_str);
+                   capture_str);
                goto error;
 
        default:
-               ERR("%s: unexpected load expression operator %s.", __func__,
-                               ir_load_expression_type_str(load_expr_op->type));
+               ERR("%s: unexpected load expression operator %s.",
+                   __func__,
+                   ir_load_expression_type_str(load_expr_op->type));
                abort();
        }
 
@@ -548,7 +525,7 @@ struct lttng_event_expr *ir_op_load_expr_to_event_expr(
 
 error:
        lttng_event_expr_destroy(event_expr);
-       event_expr = NULL;
+       event_expr = nullptr;
 
 end:
        free(provider_name);
@@ -556,35 +533,30 @@ end:
        return event_expr;
 }
 
-static
-struct lttng_event_expr *ir_op_load_to_event_expr(
-               const struct ir_op *ir, const char *capture_str)
+static struct lttng_event_expr *ir_op_load_to_event_expr(const struct ir_op *ir,
+                                                        const char *capture_str)
 {
-       struct lttng_event_expr *event_expr = NULL;
+       struct lttng_event_expr *event_expr = nullptr;
 
        LTTNG_ASSERT(ir->op == IR_OP_LOAD);
 
        switch (ir->data_type) {
        case IR_DATA_EXPRESSION:
        {
-               const struct ir_load_expression *ir_load_expr =
-                               ir->u.load.u.expression;
+               const struct ir_load_expression *ir_load_expr = ir->u.load.u.expression;
 
-               event_expr = ir_op_load_expr_to_event_expr(
-                               ir_load_expr, capture_str);
+               event_expr = ir_op_load_expr_to_event_expr(ir_load_expr, capture_str);
                break;
        }
        default:
-               ERR("%s: unexpected data type: %s.", __func__,
-                               ir_data_type_str(ir->data_type));
+               ERR("%s: unexpected data type: %s.", __func__, ir_data_type_str(ir->data_type));
                abort();
        }
 
        return event_expr;
 }
 
-static
-const char *ir_operator_type_human_str(enum ir_op_type op)
+static const char *ir_operator_type_human_str(enum ir_op_type op)
 {
        const char *name;
 
@@ -605,11 +577,10 @@ const char *ir_operator_type_human_str(enum ir_op_type op)
        return name;
 }
 
-static
-struct lttng_event_expr *ir_op_root_to_event_expr(const struct ir_op *ir,
-               const char *capture_str)
+static struct lttng_event_expr *ir_op_root_to_event_expr(const struct ir_op *ir,
+                                                        const char *capture_str)
 {
-       struct lttng_event_expr *event_expr = NULL;
+       struct lttng_event_expr *event_expr = nullptr;
 
        LTTNG_ASSERT(ir->op == IR_OP_ROOT);
        ir = ir->u.root.child;
@@ -622,20 +593,18 @@ struct lttng_event_expr *ir_op_root_to_event_expr(const struct ir_op *ir,
        case IR_OP_UNARY:
        case IR_OP_LOGICAL:
                ERR("While parsing expression `%s`: %s operators are not allowed in capture expressions.",
-                               capture_str,
-                               ir_operator_type_human_str(ir->op));
+                   capture_str,
+                   ir_operator_type_human_str(ir->op));
                break;
        default:
-               ERR("%s: unexpected IR op type: %s.", __func__,
-                               ir_op_type_str(ir->op));
+               ERR("%s: unexpected IR op type: %s.", __func__, ir_op_type_str(ir->op));
                abort();
        }
 
        return event_expr;
 }
 
-static
-void destroy_event_expr(void *ptr)
+static void destroy_event_expr(void *ptr)
 {
        lttng_event_expr_destroy((lttng_event_expr *) ptr);
 }
@@ -650,42 +619,38 @@ struct parse_event_rule_res {
 };
 } /* namespace */
 
-static
-struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
-               int argc_offset)
+static struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv, int argc_offset)
 {
-       enum lttng_event_rule_type event_rule_type =
-                       LTTNG_EVENT_RULE_TYPE_UNKNOWN;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
+       enum lttng_event_rule_type event_rule_type = LTTNG_EVENT_RULE_TYPE_UNKNOWN;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
        int consumed_args = -1;
-       struct lttng_kernel_probe_location *kernel_probe_location = NULL;
-       struct lttng_userspace_probe_location *userspace_probe_location = NULL;
+       struct lttng_kernel_probe_location *kernel_probe_location = nullptr;
+       struct lttng_userspace_probe_location *userspace_probe_location = nullptr;
        struct parse_event_rule_res res = {};
-       struct lttng_event_expr *event_expr = NULL;
-       struct filter_parser_ctx *parser_ctx = NULL;
-       struct lttng_log_level_rule *log_level_rule = NULL;
+       struct lttng_event_expr *event_expr = nullptr;
+       struct filter_parser_ctx *parser_ctx = nullptr;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
 
        /* Event rule type option */
-       char *event_rule_type_str = NULL;
+       char *event_rule_type_str = nullptr;
 
        /* Tracepoint and syscall options. */
-       char *name = NULL;
+       char *name = nullptr;
        /* Array of strings. */
        struct lttng_dynamic_pointer_array exclude_names;
 
        /* For userspace / kernel probe and function. */
-       char *location = NULL;
-       char *event_name = NULL;
+       char *location = nullptr;
+       char *event_name = nullptr;
 
        /* Filter. */
-       char *filter = NULL;
+       char *filter = nullptr;
 
        /* Log level. */
-       char *log_level_str = NULL;
+       char *log_level_str = nullptr;
 
-       lttng_dynamic_pointer_array_init(&res.capture_descriptors,
-                               destroy_event_expr);
+       lttng_dynamic_pointer_array_init(&res.capture_descriptors, destroy_event_expr);
 
        lttng_dynamic_pointer_array_init(&exclude_names, free);
 
@@ -698,10 +663,10 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item,
-                       argc_offset, *argv, false, NULL, NULL);
+               status = parse_next_item(
+                       argpar_iter, &argpar_item, argc_offset, *argv, false, nullptr, nullptr);
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -710,8 +675,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                LTTNG_ASSERT(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
                        const char *arg = argpar_item_opt_arg(argpar_item);
 
                        switch (descr->id) {
@@ -721,36 +685,31 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                                }
 
                                /* Save the string for later use. */
-                               if (!assign_string(&event_rule_type_str, arg,
-                                               "--type/-t")) {
+                               if (!assign_string(&event_rule_type_str, arg, "--type/-t")) {
                                        goto error;
                                }
 
                                break;
                        case OPT_LOCATION:
-                               if (!assign_string(&location, arg,
-                                               "--location/-L")) {
+                               if (!assign_string(&location, arg, "--location/-L")) {
                                        goto error;
                                }
 
                                break;
                        case OPT_EVENT_NAME:
-                               if (!assign_string(&event_name, arg,
-                                               "--event-name/-E")) {
+                               if (!assign_string(&event_name, arg, "--event-name/-E")) {
                                        goto error;
                                }
 
                                break;
                        case OPT_FILTER:
-                               if (!assign_string(&filter, arg,
-                                               "--filter/-f")) {
+                               if (!assign_string(&filter, arg, "--filter/-f")) {
                                        goto error;
                                }
 
                                break;
                        case OPT_NAME:
-                               if (!assign_string(&name, arg,
-                                               "--name/-n")) {
+                               if (!assign_string(&name, arg, "--name/-n")) {
                                        goto error;
                                }
 
@@ -759,9 +718,8 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                        {
                                int ret;
 
-                               ret = lttng_dynamic_pointer_array_add_pointer(
-                                               &exclude_names,
-                                               strdup(arg));
+                               ret = lttng_dynamic_pointer_array_add_pointer(&exclude_names,
+                                                                             strdup(arg));
                                if (ret != 0) {
                                        ERR("Failed to add pointer to dynamic pointer array.");
                                        goto error;
@@ -770,8 +728,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                                break;
                        }
                        case OPT_LOG_LEVEL:
-                               if (!assign_string(&log_level_str, arg,
-                                               "--log-level/-l")) {
+                               if (!assign_string(&log_level_str, arg, "--log-level/-l")) {
                                        goto error;
                                }
 
@@ -780,15 +737,14 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                        {
                                int ret;
 
-                               ret = filter_parser_ctx_create_from_filter_expression(
-                                               arg, &parser_ctx);
+                               ret = filter_parser_ctx_create_from_filter_expression(arg,
+                                                                                     &parser_ctx);
                                if (ret) {
                                        ERR("Failed to parse capture expression `%s`.", arg);
                                        goto error;
                                }
 
-                               event_expr = ir_op_root_to_event_expr(
-                                               parser_ctx->ir_root, arg);
+                               event_expr = ir_op_root_to_event_expr(parser_ctx->ir_root, arg);
                                filter_parser_ctx_free(parser_ctx);
                                parser_ctx = nullptr;
                                if (!event_expr) {
@@ -800,8 +756,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                                }
 
                                ret = lttng_dynamic_pointer_array_add_pointer(
-                                               &res.capture_descriptors,
-                                               event_expr);
+                                       &res.capture_descriptors, event_expr);
                                if (ret) {
                                        goto error;
                                }
@@ -810,7 +765,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                                 * The ownership of event expression was
                                 * transferred to the dynamic array.
                                 */
-                               event_expr = NULL;
+                               event_expr = nullptr;
 
                                break;
                        }
@@ -851,15 +806,13 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
        default:
                if (name) {
                        ERR("Can't use --name with %s event rules.",
-                                       lttng_event_rule_type_str(
-                                                       event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
 
                if (lttng_dynamic_pointer_array_get_count(&exclude_names) > 0) {
                        ERR("Can't use --exclude-name/-x with %s event rules.",
-                                       lttng_event_rule_type_str(
-                                                       event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
        }
@@ -876,7 +829,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
        case LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE:
                if (!location) {
                        ERR("Event rule of type %s requires a --location.",
-                       lttng_event_rule_type_str(event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
 
@@ -889,14 +842,13 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
        default:
                if (location) {
                        ERR("Can't use --location with %s event rules.",
-                       lttng_event_rule_type_str(event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
 
                if (event_name) {
                        ERR("Can't use --event-name with %s event rules.",
-                                       lttng_event_rule_type_str(
-                                                       event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
        }
@@ -925,7 +877,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                        break;
                default:
                        ERR("Filter expressions are not supported for %s event rules.",
-                                       lttng_event_rule_type_str(event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
        }
@@ -938,7 +890,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
        if (lttng_dynamic_pointer_array_get_count(&exclude_names) > 0) {
                if (event_rule_type != LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT) {
                        ERR("Event name exclusions are not yet implemented for %s event rules.",
-                                       lttng_event_rule_type_str(event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
 
@@ -969,20 +921,20 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                                break;
                        }
 
-                       if (!parse_log_level_string(log_level_str, event_rule_type,
-                                           &log_level, &log_level_only)) {
-                               ERR("Failed to parse log level string `%s`.",
-                                               log_level_str);
+                       if (!parse_log_level_string(
+                                   log_level_str, event_rule_type, &log_level, &log_level_only)) {
+                               ERR("Failed to parse log level string `%s`.", log_level_str);
                                goto error;
                        }
 
                        if (log_level_only) {
                                log_level_rule = lttng_log_level_rule_exactly_create(log_level);
                        } else {
-                               log_level_rule = lttng_log_level_rule_at_least_as_severe_as_create(log_level);
+                               log_level_rule = lttng_log_level_rule_at_least_as_severe_as_create(
+                                       log_level);
                        }
 
-                       if (log_level_rule == NULL) {
+                       if (log_level_rule == nullptr) {
                                ERR("Failed to create log level rule object.");
                                goto error;
                        }
@@ -990,7 +942,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
                default:
                        ERR("Log levels are not supported for %s event rules.",
-                                       lttng_event_rule_type_str(event_rule_type));
+                           lttng_event_rule_type_str(event_rule_type));
                        goto error;
                }
        }
@@ -1008,21 +960,19 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                /* Set pattern. */
-               event_rule_status = lttng_event_rule_user_tracepoint_set_name_pattern(
-                               res.er, name);
+               event_rule_status = lttng_event_rule_user_tracepoint_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set user_tracepoint event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set user_tracepoint event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                /* Set filter. */
                if (filter) {
-                       event_rule_status = lttng_event_rule_user_tracepoint_set_filter(
-                                       res.er, filter);
+                       event_rule_status =
+                               lttng_event_rule_user_tracepoint_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set user_tracepoint event rule's filter to '%s'.",
-                                               filter);
+                                   filter);
                                goto error;
                        }
                }
@@ -1030,32 +980,27 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                /* Set exclusion list. */
                if (lttng_dynamic_pointer_array_get_count(&exclude_names) > 0) {
                        int n;
-                       int count = lttng_dynamic_pointer_array_get_count(
-                                       &exclude_names);
+                       int count = lttng_dynamic_pointer_array_get_count(&exclude_names);
 
                        for (n = 0; n < count; n++) {
                                const char *exclude_name =
-                                               (const char *) lttng_dynamic_pointer_array_get_pointer(
-                                                               &exclude_names,
-                                                               n);
+                                       (const char *) lttng_dynamic_pointer_array_get_pointer(
+                                               &exclude_names, n);
 
                                event_rule_status =
-                                               lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
-                                                               res.er,
-                                                               exclude_name);
-                               if (event_rule_status !=
-                                               LTTNG_EVENT_RULE_STATUS_OK) {
+                                       lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
+                                               res.er, exclude_name);
+                               if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                        ERR("Failed to set user_tracepoint exclusion list element '%s'",
-                                                       exclude_name);
+                                           exclude_name);
                                        goto error;
                                }
                        }
                }
 
                if (log_level_rule) {
-                       event_rule_status =
-                                       lttng_event_rule_user_tracepoint_set_log_level_rule(
-                                                       res.er, log_level_rule);
+                       event_rule_status = lttng_event_rule_user_tracepoint_set_log_level_rule(
+                               res.er, log_level_rule);
 
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set log level on event fule.");
@@ -1076,21 +1021,20 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                /* Set pattern. */
-               event_rule_status = lttng_event_rule_kernel_tracepoint_set_name_pattern(
-                               res.er, name);
+               event_rule_status =
+                       lttng_event_rule_kernel_tracepoint_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set kernel_tracepoint event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set kernel_tracepoint event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                /* Set filter. */
                if (filter) {
-                       event_rule_status = lttng_event_rule_kernel_tracepoint_set_filter(
-                                       res.er, filter);
+                       event_rule_status =
+                               lttng_event_rule_kernel_tracepoint_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set kernel_tracepoint event rule's filter to '%s'.",
-                                               filter);
+                                   filter);
                                goto error;
                        }
                }
@@ -1107,29 +1051,25 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                /* Set pattern. */
-               event_rule_status = lttng_event_rule_jul_logging_set_name_pattern(
-                               res.er, name);
+               event_rule_status = lttng_event_rule_jul_logging_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set jul_logging event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set jul_logging event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                /* Set filter. */
                if (filter) {
-                       event_rule_status = lttng_event_rule_jul_logging_set_filter(
-                                       res.er, filter);
+                       event_rule_status = lttng_event_rule_jul_logging_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set jul_logging event rule's filter to '%s'.",
-                                               filter);
+                                   filter);
                                goto error;
                        }
                }
 
                if (log_level_rule) {
-                       event_rule_status =
-                                       lttng_event_rule_jul_logging_set_log_level_rule(
-                                                       res.er, log_level_rule);
+                       event_rule_status = lttng_event_rule_jul_logging_set_log_level_rule(
+                               res.er, log_level_rule);
 
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set log level on event fule.");
@@ -1149,29 +1089,26 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                /* Set pattern. */
-               event_rule_status = lttng_event_rule_log4j_logging_set_name_pattern(
-                               res.er, name);
+               event_rule_status = lttng_event_rule_log4j_logging_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set jul_logging event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set jul_logging event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                /* Set filter. */
                if (filter) {
-                       event_rule_status = lttng_event_rule_log4j_logging_set_filter(
-                                       res.er, filter);
+                       event_rule_status =
+                               lttng_event_rule_log4j_logging_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set jul_logging event rule's filter to '%s'.",
-                                               filter);
+                                   filter);
                                goto error;
                        }
                }
 
                if (log_level_rule) {
-                       event_rule_status =
-                                       lttng_event_rule_log4j_logging_set_log_level_rule(
-                                                       res.er, log_level_rule);
+                       event_rule_status = lttng_event_rule_log4j_logging_set_log_level_rule(
+                               res.er, log_level_rule);
 
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set log level on event fule.");
@@ -1191,29 +1128,26 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                /* Set pattern. */
-               event_rule_status = lttng_event_rule_python_logging_set_name_pattern(
-                               res.er, name);
+               event_rule_status = lttng_event_rule_python_logging_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set jul_logging event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set jul_logging event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                /* Set filter. */
                if (filter) {
-                       event_rule_status = lttng_event_rule_python_logging_set_filter(
-                                       res.er, filter);
+                       event_rule_status =
+                               lttng_event_rule_python_logging_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set jul_logging event rule's filter to '%s'.",
-                                               filter);
+                                   filter);
                                goto error;
                        }
                }
 
                if (log_level_rule) {
-                       event_rule_status =
-                                       lttng_event_rule_python_logging_set_log_level_rule(
-                                                       res.er, log_level_rule);
+                       event_rule_status = lttng_event_rule_python_logging_set_log_level_rule(
+                               res.er, log_level_rule);
 
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                ERR("Failed to set log level on event fule.");
@@ -1227,8 +1161,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                int ret;
                enum lttng_event_rule_status event_rule_status;
 
-               ret = parse_kernel_probe_opts(
-                               location, &kernel_probe_location);
+               ret = parse_kernel_probe_opts(location, &kernel_probe_location);
                if (ret) {
                        ERR("Failed to parse kernel probe location.");
                        goto error;
@@ -1242,11 +1175,9 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                event_rule_status =
-                               lttng_event_rule_kernel_kprobe_set_event_name(
-                                               res.er, event_name);
+                       lttng_event_rule_kernel_kprobe_set_event_name(res.er, event_name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set kprobe event rule's name to '%s'.",
-                                       event_name);
+                       ERR("Failed to set kprobe event rule's name to '%s'.", event_name);
                        goto error;
                }
 
@@ -1257,8 +1188,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                int ret;
                enum lttng_event_rule_status event_rule_status;
 
-               ret = parse_userspace_probe_opts(
-                               location, &userspace_probe_location);
+               ret = parse_userspace_probe_opts(location, &userspace_probe_location);
                if (ret) {
                        ERR("Failed to parse user space probe location.");
                        goto error;
@@ -1271,11 +1201,10 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                }
 
                event_rule_status =
-                               lttng_event_rule_kernel_uprobe_set_event_name(
-                                               res.er, event_name);
+                       lttng_event_rule_kernel_uprobe_set_event_name(res.er, event_name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set user space probe event rule's name to '%s'.",
-                                       event_name);
+                           event_name);
                        goto error;
                }
 
@@ -1286,8 +1215,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                enum lttng_event_rule_status event_rule_status;
                enum lttng_event_rule_kernel_syscall_emission_site emission_site;
 
-               if (!parse_syscall_emission_site_from_type(
-                                   event_rule_type_str, &emission_site)) {
+               if (!parse_syscall_emission_site_from_type(event_rule_type_str, &emission_site)) {
                        ERR("Failed to parse syscall type '%s'.", event_rule_type_str);
                        goto error;
                }
@@ -1298,20 +1226,17 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
                        goto error;
                }
 
-               event_rule_status = lttng_event_rule_kernel_syscall_set_name_pattern(
-                               res.er, name);
+               event_rule_status = lttng_event_rule_kernel_syscall_set_name_pattern(res.er, name);
                if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                       ERR("Failed to set syscall event rule's pattern to '%s'.",
-                                       name);
+                       ERR("Failed to set syscall event rule's pattern to '%s'.", name);
                        goto error;
                }
 
                if (filter) {
-                       event_rule_status = lttng_event_rule_kernel_syscall_set_filter(
-                                       res.er, filter);
+                       event_rule_status =
+                               lttng_event_rule_kernel_syscall_set_filter(res.er, filter);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
-                               ERR("Failed to set syscall event rule's filter to '%s'.",
-                                               filter);
+                               ERR("Failed to set syscall event rule's filter to '%s'.", filter);
                                goto error;
                        }
                }
@@ -1327,7 +1252,7 @@ struct parse_event_rule_res parse_event_rule(int *argc, const char ***argv,
 
 error:
        lttng_event_rule_destroy(res.er);
-       res.er = NULL;
+       res.er = nullptr;
        lttng_dynamic_pointer_array_reset(&res.capture_descriptors);
 
 end:
@@ -1352,9 +1277,8 @@ end:
        return res;
 }
 
-static
-struct lttng_condition *handle_condition_event(int *argc, const char ***argv,
-               int argc_offset)
+static struct lttng_condition *
+handle_condition_event(int *argc, const char ***argv, int argc_offset)
 {
        struct parse_event_rule_res res;
        struct lttng_condition *c;
@@ -1362,28 +1286,26 @@ struct lttng_condition *handle_condition_event(int *argc, const char ***argv,
 
        res = parse_event_rule(argc, argv, argc_offset);
        if (!res.er) {
-               c = NULL;
+               c = nullptr;
                goto error;
        }
 
        c = lttng_condition_event_rule_matches_create(res.er);
        lttng_event_rule_destroy(res.er);
-       res.er = NULL;
+       res.er = nullptr;
        if (!c) {
                goto error;
        }
 
-       for (i = 0; i < lttng_dynamic_pointer_array_get_count(&res.capture_descriptors);
-                       i++) {
+       for (i = 0; i < lttng_dynamic_pointer_array_get_count(&res.capture_descriptors); i++) {
                enum lttng_condition_status status;
                struct lttng_event_expr **expr =
-                               (lttng_event_expr **) lttng_dynamic_array_get_element(
-                                       &res.capture_descriptors.array, i);
+                       (lttng_event_expr **) lttng_dynamic_array_get_element(
+                               &res.capture_descriptors.array, i);
 
                LTTNG_ASSERT(expr);
                LTTNG_ASSERT(*expr);
-               status = lttng_condition_event_rule_matches_append_capture_descriptor(
-                               c, *expr);
+               status = lttng_condition_event_rule_matches_append_capture_descriptor(c, *expr);
                if (status != LTTNG_CONDITION_STATUS_OK) {
                        if (status == LTTNG_CONDITION_STATUS_UNSUPPORTED) {
                                ERR("The capture feature is unsupported by the event-rule condition type");
@@ -1393,14 +1315,14 @@ struct lttng_condition *handle_condition_event(int *argc, const char ***argv,
                }
 
                /* Ownership of event expression moved to `c` */
-               *expr = NULL;
+               *expr = nullptr;
        }
 
        goto end;
 
 error:
        lttng_condition_destroy(c);
-       c = NULL;
+       c = nullptr;
 
 end:
        lttng_dynamic_pointer_array_reset(&res.capture_descriptors);
@@ -1411,18 +1333,15 @@ end:
 namespace {
 struct condition_descr {
        const char *name;
-       struct lttng_condition *(*handler) (int *argc, const char ***argv,
-               int argc_offset);
+       struct lttng_condition *(*handler)(int *argc, const char ***argv, int argc_offset);
 };
 } /* namespace */
 
-static const
-struct condition_descr condition_descrs[] = {
+static const struct condition_descr condition_descrs[] = {
        { "event-rule-matches", handle_condition_event },
 };
 
-static
-void print_valid_condition_names(void)
+static void print_valid_condition_names()
 {
        unsigned int i;
 
@@ -1433,14 +1352,16 @@ void print_valid_condition_names(void)
        }
 }
 
-static
-struct lttng_condition *parse_condition(const char *condition_name, int *argc,
-               const char ***argv, int argc_offset, int orig_arg_index,
-               const char *orig_arg)
+static struct lttng_condition *parse_condition(const char *condition_name,
+                                              int *argc,
+                                              const char ***argv,
+                                              int argc_offset,
+                                              int orig_arg_index,
+                                              const char *orig_arg)
 {
        int i;
        struct lttng_condition *cond;
-       const struct condition_descr *descr = NULL;
+       const struct condition_descr *descr = nullptr;
 
        for (i = 0; i < ARRAY_SIZE(condition_descrs); i++) {
                if (strcmp(condition_name, condition_descrs[i].name) == 0) {
@@ -1451,7 +1372,9 @@ struct lttng_condition *parse_condition(const char *condition_name, int *argc,
 
        if (!descr) {
                ERR(WHILE_PARSING_ARG_N_ARG_FMT "Unknown condition name '%s'",
-                       orig_arg_index + 1, orig_arg, condition_name);
+                   orig_arg_index + 1,
+                   orig_arg,
+                   condition_name);
                print_valid_condition_names();
                goto error;
        }
@@ -1464,7 +1387,7 @@ struct lttng_condition *parse_condition(const char *condition_name, int *argc,
 
        goto end;
 error:
-       cond = NULL;
+       cond = nullptr;
 end:
        return cond;
 }
@@ -1474,17 +1397,17 @@ static struct lttng_rate_policy *parse_rate_policy(const char *policy_str)
        int ret;
        size_t num_token = 0;
        struct lttng_dynamic_pointer_array tokens;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
        enum lttng_rate_policy_type policy_type;
        unsigned long long value;
        char *policy_type_str;
        char *policy_value_str;
 
        LTTNG_ASSERT(policy_str);
-       lttng_dynamic_pointer_array_init(&tokens, NULL);
+       lttng_dynamic_pointer_array_init(&tokens, nullptr);
 
        /* Rate policy fields are separated by ':'. */
-       ret = strutils_split(policy_str, ':', 1, &tokens);
+       ret = strutils_split(policy_str, ':', true, &tokens);
        if (ret == 0) {
                num_token = lttng_dynamic_pointer_array_get_count(&tokens);
        }
@@ -1513,8 +1436,7 @@ static struct lttng_rate_policy *parse_rate_policy(const char *policy_str)
 
        /* Parse the value. */
        if (utils_parse_unsigned_long_long(policy_value_str, &value) != 0) {
-               ERR("Failed to parse rate policy value `%s` as an integer.",
-                               policy_value_str);
+               ERR("Failed to parse rate policy value `%s` as an integer.", policy_value_str);
                goto end;
        }
 
@@ -1534,7 +1456,7 @@ static struct lttng_rate_policy *parse_rate_policy(const char *policy_str)
                abort();
        }
 
-       if (policy == NULL) {
+       if (policy == nullptr) {
                ERR("Failed to create rate policy `%s`.", policy_str);
        }
 
@@ -1544,18 +1466,15 @@ end:
 }
 
 static const struct argpar_opt_descr notify_action_opt_descrs[] = {
-       { OPT_RATE_POLICY, '\0', "rate-policy", true },
-       ARGPAR_OPT_DESCR_SENTINEL
+       { OPT_RATE_POLICY, '\0', "rate-policy", true }, ARGPAR_OPT_DESCR_SENTINEL
 };
 
-static
-struct lttng_action *handle_action_notify(int *argc, const char ***argv,
-               int argc_offset)
+static struct lttng_action *handle_action_notify(int *argc, const char ***argv, int argc_offset)
 {
-       struct lttng_action *action = NULL;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_action *action = nullptr;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
 
        argpar_iter = argpar_iter_create(*argc, *argv, notify_action_opt_descrs);
        if (!argpar_iter) {
@@ -1566,11 +1485,15 @@ struct lttng_action *handle_action_notify(int *argc, const char ***argv,
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item,
-                       argc_offset, *argv, false, NULL,
-                       "While parsing `notify` action:");
+               status = parse_next_item(argpar_iter,
+                                        &argpar_item,
+                                        argc_offset,
+                                        *argv,
+                                        false,
+                                        nullptr,
+                                        "While parsing `notify` action:");
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -1579,8 +1502,7 @@ struct lttng_action *handle_action_notify(int *argc, const char ***argv,
                LTTNG_ASSERT(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
                        const char *arg = argpar_item_opt_arg(argpar_item);
 
                        switch (descr->id) {
@@ -1625,7 +1547,7 @@ struct lttng_action *handle_action_notify(int *argc, const char ***argv,
 
 error:
        lttng_action_destroy(action);
-       action = NULL;
+       action = nullptr;
 end:
        lttng_rate_policy_destroy(policy);
        argpar_item_destroy(argpar_item);
@@ -1638,30 +1560,28 @@ end:
  * optional rate policy.
  */
 
-static struct lttng_action *handle_action_simple_session_with_policy(int *argc,
-               const char ***argv,
-               int argc_offset,
-               struct lttng_action *(*create_action_cb)(void),
-               enum lttng_action_status (*set_session_name_cb)(
-                               struct lttng_action *, const char *),
-               enum lttng_action_status (*set_rate_policy_cb)(
-                               struct lttng_action *,
-                               const struct lttng_rate_policy *),
-               const char *action_name)
+static struct lttng_action *handle_action_simple_session_with_policy(
+       int *argc,
+       const char ***argv,
+       int argc_offset,
+       struct lttng_action *(*create_action_cb)(),
+       enum lttng_action_status (*set_session_name_cb)(struct lttng_action *, const char *),
+       enum lttng_action_status (*set_rate_policy_cb)(struct lttng_action *,
+                                                      const struct lttng_rate_policy *),
+       const char *action_name)
 {
-       struct lttng_action *action = NULL;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       const char *session_name_arg = NULL;
+       struct lttng_action *action = nullptr;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       const char *session_name_arg = nullptr;
        enum lttng_action_status action_status;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(set_session_name_cb);
        LTTNG_ASSERT(set_rate_policy_cb);
 
        const struct argpar_opt_descr rate_policy_opt_descrs[] = {
-               { OPT_RATE_POLICY, '\0', "rate-policy", true },
-               ARGPAR_OPT_DESCR_SENTINEL
+               { OPT_RATE_POLICY, '\0', "rate-policy", true }, ARGPAR_OPT_DESCR_SENTINEL
        };
 
        argpar_iter = argpar_iter_create(*argc, *argv, rate_policy_opt_descrs);
@@ -1673,11 +1593,16 @@ static struct lttng_action *handle_action_simple_session_with_policy(int *argc,
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item, argc_offset,
-                       *argv, false, NULL,
-                       "While parsing `%s` action:", action_name);
+               status = parse_next_item(argpar_iter,
+                                        &argpar_item,
+                                        argc_offset,
+                                        *argv,
+                                        false,
+                                        nullptr,
+                                        "While parsing `%s` action:",
+                                        action_name);
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -1686,8 +1611,7 @@ static struct lttng_action *handle_action_simple_session_with_policy(int *argc,
                LTTNG_ASSERT(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
                        const char *arg = argpar_item_opt_arg(argpar_item);
 
                        switch (descr->id) {
@@ -1734,7 +1658,8 @@ static struct lttng_action *handle_action_simple_session_with_policy(int *argc,
        action_status = set_session_name_cb(action, session_name_arg);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
                ERR("Failed to set action %s session's session name to '%s'.",
-                               action_name, session_name_arg);
+                   action_name,
+                   session_name_arg);
                goto error;
        }
 
@@ -1750,7 +1675,7 @@ static struct lttng_action *handle_action_simple_session_with_policy(int *argc,
 
 error:
        lttng_action_destroy(action);
-       action = NULL;
+       action = nullptr;
 
 end:
        lttng_rate_policy_destroy(policy);
@@ -1759,33 +1684,36 @@ end:
        return action;
 }
 
-static
-struct lttng_action *handle_action_start_session(int *argc,
-               const char ***argv, int argc_offset)
+static struct lttng_action *
+handle_action_start_session(int *argc, const char ***argv, int argc_offset)
 {
-       return handle_action_simple_session_with_policy(argc, argv,
-                       argc_offset,
-                       lttng_action_start_session_create,
-                       lttng_action_start_session_set_session_name,
-                       lttng_action_start_session_set_rate_policy, "start");
+       return handle_action_simple_session_with_policy(argc,
+                                                       argv,
+                                                       argc_offset,
+                                                       lttng_action_start_session_create,
+                                                       lttng_action_start_session_set_session_name,
+                                                       lttng_action_start_session_set_rate_policy,
+                                                       "start");
 }
 
-static
-struct lttng_action *handle_action_stop_session(int *argc,
-               const char ***argv, int argc_offset)
+static struct lttng_action *
+handle_action_stop_session(int *argc, const char ***argv, int argc_offset)
 {
-       return handle_action_simple_session_with_policy(argc, argv,
-                       argc_offset,
-                       lttng_action_stop_session_create,
-                       lttng_action_stop_session_set_session_name,
-                       lttng_action_stop_session_set_rate_policy, "stop");
+       return handle_action_simple_session_with_policy(argc,
+                                                       argv,
+                                                       argc_offset,
+                                                       lttng_action_stop_session_create,
+                                                       lttng_action_stop_session_set_session_name,
+                                                       lttng_action_stop_session_set_rate_policy,
+                                                       "stop");
 }
 
-static
-struct lttng_action *handle_action_rotate_session(int *argc,
-               const char ***argv, int argc_offset)
+static struct lttng_action *
+handle_action_rotate_session(int *argc, const char ***argv, int argc_offset)
 {
-       return handle_action_simple_session_with_policy(argc, argv,
+       return handle_action_simple_session_with_policy(
+               argc,
+               argv,
                argc_offset,
                lttng_action_rotate_session_create,
                lttng_action_rotate_session_set_session_name,
@@ -1804,24 +1732,23 @@ static const struct argpar_opt_descr snapshot_action_opt_descrs[] = {
        ARGPAR_OPT_DESCR_SENTINEL
 };
 
-static
-struct lttng_action *handle_action_snapshot_session(int *argc,
-               const char ***argv, int argc_offset)
+static struct lttng_action *
+handle_action_snapshot_session(int *argc, const char ***argv, int argc_offset)
 {
-       struct lttng_action *action = NULL;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       const char *session_name_arg = NULL;
-       char *snapshot_name_arg = NULL;
-       char *ctrl_url_arg = NULL;
-       char *data_url_arg = NULL;
-       char *max_size_arg = NULL;
-       char *url_arg = NULL;
-       char *path_arg = NULL;
-       char *error = NULL;
+       struct lttng_action *action = nullptr;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       const char *session_name_arg = nullptr;
+       char *snapshot_name_arg = nullptr;
+       char *ctrl_url_arg = nullptr;
+       char *data_url_arg = nullptr;
+       char *max_size_arg = nullptr;
+       char *url_arg = nullptr;
+       char *path_arg = nullptr;
+       char *error = nullptr;
        enum lttng_action_status action_status;
-       struct lttng_snapshot_output *snapshot_output = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_snapshot_output *snapshot_output = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        int ret;
        unsigned int locations_specified = 0;
 
@@ -1834,10 +1761,15 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item, argc_offset,
-                       *argv, false, NULL, "While parsing `snapshot` action:");
+               status = parse_next_item(argpar_iter,
+                                        &argpar_item,
+                                        argc_offset,
+                                        *argv,
+                                        false,
+                                        nullptr,
+                                        "While parsing `snapshot` action:");
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -1846,8 +1778,7 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                LTTNG_ASSERT(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
                        const char *arg = argpar_item_opt_arg(argpar_item);
 
                        switch (descr->id) {
@@ -1960,11 +1891,10 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                goto error;
        }
 
-       action_status = lttng_action_snapshot_session_set_session_name(
-                       action, session_name_arg);
+       action_status = lttng_action_snapshot_session_set_session_name(action, session_name_arg);
        if (action_status != LTTNG_ACTION_STATUS_OK) {
                ERR("Failed to set action snapshot session's session name to '%s'.",
-                               session_name_arg);
+                   session_name_arg);
                goto error;
        }
 
@@ -1974,8 +1904,7 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                        goto error;
                }
 
-               ret = lttng_snapshot_output_set_name(
-                               snapshot_name_arg, snapshot_output);
+               ret = lttng_snapshot_output_set_name(snapshot_name_arg, snapshot_output);
                if (ret != 0) {
                        ERR("Failed to set name of snapshot output.");
                        goto error;
@@ -1999,7 +1928,7 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                ret = lttng_snapshot_output_set_size(max_size, snapshot_output);
                if (ret != 0) {
                        ERR("Failed to set snapshot output's max size to %" PRIu64 " bytes.",
-                                       max_size);
+                           max_size);
                        goto error;
                }
        }
@@ -2013,36 +1942,32 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                        goto error;
                }
 
-               num_uris = uri_parse_str_urls(url_arg, NULL, &uris);
+               num_uris = uri_parse_str_urls(url_arg, nullptr, &uris);
                if (num_uris < 1) {
                        ERR("Failed to parse '%s' as an URL.", url_arg);
                        goto error;
                }
 
                if (uris[0].dtype == LTTNG_DST_PATH) {
-                       ret = lttng_snapshot_output_set_local_path(
-                                       uris[0].dst.path, snapshot_output);
+                       ret = lttng_snapshot_output_set_local_path(uris[0].dst.path,
+                                                                  snapshot_output);
                        free(uris);
                        if (ret != 0) {
-                               ERR("Failed to assign '%s' as a local destination.",
-                                               url_arg);
+                               ERR("Failed to assign '%s' as a local destination.", url_arg);
                                goto error;
                        }
                } else {
-                       ret = lttng_snapshot_output_set_network_url(
-                                       url_arg, snapshot_output);
+                       ret = lttng_snapshot_output_set_network_url(url_arg, snapshot_output);
                        free(uris);
                        if (ret != 0) {
-                               ERR("Failed to assign '%s' as a network URL.",
-                                               url_arg);
+                               ERR("Failed to assign '%s' as a network URL.", url_arg);
                                goto error;
                        }
                }
        }
 
        if (path_arg) {
-               ret = lttng_snapshot_output_set_local_path(
-                               path_arg, snapshot_output);
+               ret = lttng_snapshot_output_set_local_path(path_arg, snapshot_output);
                if (ret != 0) {
                        ERR("Failed to parse '%s' as a local path.", path_arg);
                        goto error;
@@ -2055,30 +1980,29 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
                 * data URLs.
                 */
                ret = lttng_snapshot_output_set_network_urls(
-                               ctrl_url_arg, data_url_arg, snapshot_output);
+                       ctrl_url_arg, data_url_arg, snapshot_output);
                if (ret != 0) {
                        ERR("Failed to parse `%s` and `%s` as control and data URLs.",
-                                       ctrl_url_arg, data_url_arg);
+                           ctrl_url_arg,
+                           data_url_arg);
                        goto error;
                }
        }
 
        if (snapshot_output) {
-               action_status = lttng_action_snapshot_session_set_output(
-                               action, snapshot_output);
+               action_status = lttng_action_snapshot_session_set_output(action, snapshot_output);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to set snapshot session action's output.");
                        goto error;
                }
 
                /* Ownership of `snapshot_output` has been transferred to the action. */
-               snapshot_output = NULL;
+               snapshot_output = nullptr;
        }
 
        if (policy) {
                enum lttng_action_status status;
-               status = lttng_action_snapshot_session_set_rate_policy(
-                               action, policy);
+               status = lttng_action_snapshot_session_set_rate_policy(action, policy);
                if (status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to set rate policy");
                        goto error;
@@ -2089,7 +2013,7 @@ struct lttng_action *handle_action_snapshot_session(int *argc,
 
 error:
        lttng_action_destroy(action);
-       action = NULL;
+       action = nullptr;
        free(error);
 end:
        free(snapshot_name_arg);
@@ -2108,13 +2032,11 @@ end:
 namespace {
 struct action_descr {
        const char *name;
-       struct lttng_action *(*handler) (int *argc, const char ***argv,
-               int argc_offset);
+       struct lttng_action *(*handler)(int *argc, const char ***argv, int argc_offset);
 };
 } /* namespace */
 
-static const
-struct action_descr action_descrs[] = {
+static const struct action_descr action_descrs[] = {
        { "notify", handle_action_notify },
        { "start-session", handle_action_start_session },
        { "stop-session", handle_action_stop_session },
@@ -2122,8 +2044,7 @@ struct action_descr action_descrs[] = {
        { "snapshot-session", handle_action_snapshot_session },
 };
 
-static
-void print_valid_action_names(void)
+static void print_valid_action_names()
 {
        unsigned int i;
 
@@ -2134,14 +2055,16 @@ void print_valid_action_names(void)
        }
 }
 
-static
-struct lttng_action *parse_action(const char *action_name, int *argc,
-               const char ***argv, int argc_offset, int orig_arg_index,
-               const char *orig_arg)
+static struct lttng_action *parse_action(const char *action_name,
+                                        int *argc,
+                                        const char ***argv,
+                                        int argc_offset,
+                                        int orig_arg_index,
+                                        const char *orig_arg)
 {
        int i;
        struct lttng_action *action;
-       const struct action_descr *descr = NULL;
+       const struct action_descr *descr = nullptr;
 
        for (i = 0; i < ARRAY_SIZE(action_descrs); i++) {
                if (strcmp(action_name, action_descrs[i].name) == 0) {
@@ -2152,7 +2075,9 @@ struct lttng_action *parse_action(const char *action_name, int *argc,
 
        if (!descr) {
                ERR(WHILE_PARSING_ARG_N_ARG_FMT "Unknown action name '%s'",
-                       orig_arg_index + 1, orig_arg, action_name);
+                   orig_arg_index + 1,
+                   orig_arg,
+                   action_name);
                print_valid_action_names();
                goto error;
        }
@@ -2165,13 +2090,12 @@ struct lttng_action *parse_action(const char *action_name, int *argc,
 
        goto end;
 error:
-       action = NULL;
+       action = nullptr;
 end:
        return action;
 }
 
-static const
-struct argpar_opt_descr add_trigger_options[] = {
+static const struct argpar_opt_descr add_trigger_options[] = {
        { OPT_HELP, 'h', "help", false },
        { OPT_LIST_OPTIONS, '\0', "list-options", false },
        { OPT_CONDITION, '\0', "condition", true },
@@ -2181,8 +2105,7 @@ struct argpar_opt_descr add_trigger_options[] = {
        ARGPAR_OPT_DESCR_SENTINEL,
 };
 
-static
-void lttng_actions_destructor(void *p)
+static void lttng_actions_destructor(void *p)
 {
        struct lttng_action *action = (lttng_action *) p;
 
@@ -2194,41 +2117,38 @@ int cmd_add_trigger(int argc, const char **argv)
        int ret;
        int my_argc = argc - 1;
        const char **my_argv = argv + 1;
-       struct lttng_condition *condition = NULL;
+       struct lttng_condition *condition = nullptr;
        struct lttng_dynamic_pointer_array actions;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       const struct argpar_error *argpar_error = NULL;
-       struct lttng_action *action_list = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
-       char *name = NULL;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       const struct argpar_error *argpar_error = nullptr;
+       struct lttng_action *action_list = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       char *name = nullptr;
        int i;
-       char *owner_uid = NULL;
+       char *owner_uid = nullptr;
        enum lttng_error_code ret_code;
-       struct mi_writer *mi_writer = NULL;
+       struct mi_writer *mi_writer = nullptr;
 
        lttng_dynamic_pointer_array_init(&actions, lttng_actions_destructor);
 
        if (lttng_opt_mi) {
-               mi_writer = mi_lttng_writer_create(
-                               fileno(stdout), lttng_opt_mi);
+               mi_writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!mi_writer) {
                        ret = CMD_ERROR;
                        goto error;
                }
 
                /* Open command element. */
-               ret = mi_lttng_writer_command_open(mi_writer,
-                               mi_lttng_element_command_add_trigger);
+               ret = mi_lttng_writer_command_open(mi_writer, mi_lttng_element_command_add_trigger);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
                }
 
                /* Open output element. */
-               ret = mi_lttng_writer_open_element(
-                               mi_writer, mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(mi_writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
@@ -2242,20 +2162,22 @@ int cmd_add_trigger(int argc, const char **argv)
                const char *arg;
 
                argpar_iter_destroy(argpar_iter);
-               argpar_iter = argpar_iter_create(my_argc, my_argv,
-                       add_trigger_options);
+               argpar_iter = argpar_iter_create(my_argc, my_argv, add_trigger_options);
                if (!argpar_iter) {
                        ERR("Failed to create argpar iter.");
                        goto error;
                }
 
-               status = parse_next_item(argpar_iter, &argpar_item,
-                       argc - my_argc, my_argv, true, &argpar_error, NULL);
+               status = parse_next_item(argpar_iter,
+                                        &argpar_item,
+                                        argc - my_argc,
+                                        my_argv,
+                                        true,
+                                        &argpar_error,
+                                        nullptr);
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR) {
-
-                       if (argpar_error_type(argpar_error) ==
-                                       ARGPAR_ERROR_TYPE_MISSING_OPT_ARG) {
-                               int opt_id = argpar_error_opt_descr(argpar_error, NULL)->id;
+                       if (argpar_error_type(argpar_error) == ARGPAR_ERROR_TYPE_MISSING_OPT_ARG) {
+                               int opt_id = argpar_error_opt_descr(argpar_error, nullptr)->id;
 
                                if (opt_id == OPT_CONDITION) {
                                        print_valid_condition_names();
@@ -2274,8 +2196,7 @@ int cmd_add_trigger(int argc, const char **argv)
                LTTNG_ASSERT(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_NON_OPT) {
-                       ERR("Unexpected argument `%s`.",
-                               argpar_item_non_opt_arg(argpar_item));
+                       ERR("Unexpected argument `%s`.", argpar_item_non_opt_arg(argpar_item));
                        goto error;
                }
 
@@ -2303,9 +2224,12 @@ int cmd_add_trigger(int argc, const char **argv)
                                goto error;
                        }
 
-                       condition = parse_condition(arg, &my_argc, &my_argv,
-                               argc - my_argc, argc - my_argc - ingested_args,
-                               my_argv[-ingested_args]);
+                       condition = parse_condition(arg,
+                                                   &my_argc,
+                                                   &my_argv,
+                                                   argc - my_argc,
+                                                   argc - my_argc - ingested_args,
+                                                   my_argv[-ingested_args]);
                        if (!condition) {
                                /*
                                 * An error message was already printed by
@@ -2318,9 +2242,12 @@ int cmd_add_trigger(int argc, const char **argv)
                }
                case OPT_ACTION:
                {
-                       action = parse_action(arg, &my_argc, &my_argv,
-                               argc - my_argc,  argc - my_argc - ingested_args,
-                               my_argv[-ingested_args]);
+                       action = parse_action(arg,
+                                             &my_argc,
+                                             &my_argv,
+                                             argc - my_argc,
+                                             argc - my_argc - ingested_args,
+                                             my_argv[-ingested_args]);
                        if (!action) {
                                /*
                                 * An error message was already printed by
@@ -2329,15 +2256,14 @@ int cmd_add_trigger(int argc, const char **argv)
                                goto error;
                        }
 
-                       ret = lttng_dynamic_pointer_array_add_pointer(
-                                       &actions, action);
+                       ret = lttng_dynamic_pointer_array_add_pointer(&actions, action);
                        if (ret) {
                                ERR("Failed to add pointer to pointer array.");
                                goto error;
                        }
 
                        /* Ownership of the action was transferred to the list. */
-                       action = NULL;
+                       action = nullptr;
 
                        break;
                }
@@ -2351,8 +2277,7 @@ int cmd_add_trigger(int argc, const char **argv)
                }
                case OPT_OWNER_UID:
                {
-                       if (!assign_string(&owner_uid, arg,
-                                       "--owner-uid")) {
+                       if (!assign_string(&owner_uid, arg, "--owner-uid")) {
                                goto error;
                        }
 
@@ -2393,7 +2318,7 @@ int cmd_add_trigger(int argc, const char **argv)
                 * the action. We can destroy ours.
                 */
                lttng_action_destroy(action);
-               action = NULL;
+               action = nullptr;
        }
 
        trigger = lttng_trigger_create(condition, action_list);
@@ -2427,21 +2352,19 @@ int cmd_add_trigger(int argc, const char **argv)
        }
 
        if (ret_code != LTTNG_OK) {
-               ERR("Failed to register trigger: %s.",
-                               lttng_strerror(-ret_code));
+               ERR("Failed to register trigger: %s.", lttng_strerror(-ret_code));
                goto error;
        }
 
        if (lttng_opt_mi) {
-               ret_code = lttng_trigger_mi_serialize(trigger, mi_writer, NULL);
+               ret_code = lttng_trigger_mi_serialize(trigger, mi_writer, nullptr);
                if (ret_code != LTTNG_OK) {
                        goto error;
                }
        } else {
                const char *returned_trigger_name;
                const enum lttng_trigger_status trigger_status =
-                               lttng_trigger_get_name(trigger,
-                                               &returned_trigger_name);
+                       lttng_trigger_get_name(trigger, &returned_trigger_name);
 
                if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
                        WARN("Failed to retrieve the added trigger's name.");
@@ -2469,8 +2392,8 @@ end:
                        goto cleanup;
                }
 
-               mi_ret = mi_lttng_writer_write_element_bool(mi_writer,
-                               mi_lttng_element_command_success, ret ? 0 : 1);
+               mi_ret = mi_lttng_writer_write_element_bool(
+                       mi_writer, mi_lttng_element_command_success, ret ? 0 : 1);
                if (mi_ret) {
                        ret = 1;
                        goto cleanup;
index 6c2399181105cae25aa366ccf3d71f7a8de11082..1637cf240360da58c3a66f0de0291523631fc78b 100644 (file)
@@ -6,28 +6,29 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
 #include <popt.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <stdbool.h>
-#include <lttng/lttng.h>
-
-#include "../command.hpp"
-
-#include <common/mi-lttng.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
 
 static int opt_clear_all;
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-clear.1.h>
-;
+       ;
 #endif
 
 /* Mi writer */
@@ -40,10 +41,10 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"all",       'a', POPT_ARG_VAL, &opt_clear_all, 1, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_VAL, &opt_clear_all, 1, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -51,12 +52,10 @@ static struct poptOption long_options[] = {
  */
 static int clear_session(struct lttng_session *session)
 {
-       enum lttng_clear_handle_status status =
-                       LTTNG_CLEAR_HANDLE_STATUS_OK;
-       struct lttng_clear_handle *handle = NULL;
+       enum lttng_clear_handle_status status = LTTNG_CLEAR_HANDLE_STATUS_OK;
+       struct lttng_clear_handle *handle = nullptr;
        enum lttng_error_code ret_code;
        bool printed_wait_msg = false;
-       char *session_name = NULL;
        int ret;
 
        ret = lttng_clear_session(session->name, &handle);
@@ -66,13 +65,12 @@ static int clear_session(struct lttng_session *session)
        }
 
        do {
-               status = lttng_clear_handle_wait_for_completion(handle,
-                               DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US / USEC_PER_MSEC);
+               status = lttng_clear_handle_wait_for_completion(
+                       handle, DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US / USEC_PER_MSEC);
                switch (status) {
                case LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT:
                        if (!printed_wait_msg) {
-                               _MSG("Waiting for clear of session \"%s\"",
-                                               session->name);
+                               _MSG("Waiting for clear of session \"%s\"", session->name);
                                printed_wait_msg = true;
                        }
                        _MSG(".");
@@ -82,7 +80,7 @@ static int clear_session(struct lttng_session *session)
                        break;
                default:
                        ERR("Failed to wait for the completion of clear for session \"%s\"",
-                                       session->name);
+                           session->name);
                        ret = -1;
                        goto error;
                }
@@ -99,8 +97,7 @@ static int clear_session(struct lttng_session *session)
                goto error;
        }
 
-       MSG("%sSession \"%s\" cleared", printed_wait_msg ? "\n" : "",
-                       session->name);
+       MSG("%sSession \"%s\" cleared", printed_wait_msg ? "\n" : "", session->name);
        printed_wait_msg = false;
 
        if (lttng_opt_mi) {
@@ -117,7 +114,6 @@ error:
                MSG("");
        }
        lttng_clear_handle_destroy(handle);
-       free(session_name);
        return ret;
 }
 
@@ -153,16 +149,16 @@ error:
 int cmd_clear(int argc, const char **argv)
 {
        int opt;
-       int ret = CMD_SUCCESS , i, command_ret = CMD_SUCCESS, success = 1;
+       int ret = CMD_SUCCESS, i, command_ret = CMD_SUCCESS, success = 1;
        static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
-       bool free_session_name = false;
-       struct lttng_session *sessions = NULL;
+       char *session_name = nullptr;
+       const char *arg_session_name = nullptr;
+       const char *leftover = nullptr;
+       struct lttng_session *sessions = nullptr;
        int count;
-       int found;
+       bool found;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -189,16 +185,14 @@ int cmd_clear(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_clear);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_clear);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -213,19 +207,22 @@ int cmd_clear(int argc, const char **argv)
        }
 
        if (!opt_clear_all) {
-               session_name = (char *) poptGetArg(pc);
-               if (!session_name) {
+               arg_session_name = poptGetArg(pc);
+               if (!arg_session_name) {
                        /* No session name specified, lookup default */
                        session_name = get_session_name();
-                       if (session_name == NULL) {
-                               command_ret = CMD_ERROR;
-                               success = 0;
-                               goto mi_closing;
+               } else {
+                       session_name = strdup(arg_session_name);
+                       if (session_name == nullptr) {
+                               PERROR("Failed to copy session name");
                        }
-                       free_session_name = true;
                }
-       } else {
-               session_name = NULL;
+
+               if (session_name == nullptr) {
+                       command_ret = CMD_ERROR;
+                       success = 0;
+                       goto mi_closing;
+               }
        }
 
        leftover = poptGetArg(pc);
@@ -254,10 +251,10 @@ int cmd_clear(int argc, const char **argv)
                }
        } else {
                /* Find the corresponding lttng_session struct */
-               found = 0;
+               found = false;
                for (i = 0; i < count; i++) {
                        if (strncmp(sessions[i].name, session_name, NAME_MAX) == 0) {
-                               found = 1;
+                               found = true;
                                command_ret = clear_session(&sessions[i]);
                                if (command_ret) {
                                        ERR("%s", lttng_strerror(command_ret));
@@ -285,8 +282,8 @@ mi_closing:
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -307,9 +304,7 @@ end:
        }
 
        free(sessions);
-       if (free_session_name) {
-               free(session_name);
-       }
+       free(session_name);
 
        /* Overwrite ret if an error occurred during clear_session/all */
        ret = command_ret ? command_ret : ret;
index 64cf2b37ca37f46b70b5e5dc2bb0e699024ed779..dce13866f6dea7d2948149de093e49af65935bde 100644 (file)
@@ -7,32 +7,31 @@
  */
 
 #define _LGPL_SOURCE
-#include <ctype.h>
-#include <popt.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <common/compat/time.hpp>
-#include <unistd.h>
-#include <signal.h>
-#include <sys/wait.h>
-
-#include <common/mi-lttng.hpp>
-
 #include "../command.hpp"
 #include "../utils.hpp"
 
+#include <common/compat/time.hpp>
 #include <common/defaults.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/path.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/uri.hpp>
 #include <common/utils.hpp>
-#include <common/path.hpp>
+
 #include <lttng/lttng.h>
 
+#include <ctype.h>
+#include <popt.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
 static char *opt_output_path;
-static char *opt_session_name;
 static char *opt_url;
 static char *opt_ctrl_url;
 static char *opt_data_url;
@@ -45,7 +44,7 @@ static uint32_t opt_live_timer;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-create.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -64,18 +63,24 @@ enum output_type {
 static struct mi_writer *writer;
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help", 'h', POPT_ARG_NONE, NULL, OPT_HELP, NULL, NULL},
-       {"output", 'o', POPT_ARG_STRING, &opt_output_path, 0, NULL, NULL},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"set-url",        'U', POPT_ARG_STRING, &opt_url, 0, 0, 0},
-       {"ctrl-url",       'C', POPT_ARG_STRING, &opt_ctrl_url, 0, 0, 0},
-       {"data-url",       'D', POPT_ARG_STRING, &opt_data_url, 0, 0, 0},
-       {"no-output",       0, POPT_ARG_VAL, &opt_no_output, 1, 0, 0},
-       {"no-consumer",     0, POPT_ARG_VAL, &opt_no_consumer, 1, 0, 0},
-       {"snapshot",        0, POPT_ARG_VAL, &opt_snapshot, 1, 0, 0},
-       {"live",            0, POPT_ARG_INT | POPT_ARGFLAG_OPTIONAL, 0, OPT_LIVE_TIMER, 0, 0},
-       {"shm-path",        0, POPT_ARG_STRING, &opt_shm_path, 0, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "output", 'o', POPT_ARG_STRING, &opt_output_path, 0, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "set-url", 'U', POPT_ARG_STRING, &opt_url, 0, nullptr, nullptr },
+       { "ctrl-url", 'C', POPT_ARG_STRING, &opt_ctrl_url, 0, nullptr, nullptr },
+       { "data-url", 'D', POPT_ARG_STRING, &opt_data_url, 0, nullptr, nullptr },
+       { "no-output", 0, POPT_ARG_VAL, &opt_no_output, 1, nullptr, nullptr },
+       { "no-consumer", 0, POPT_ARG_VAL, &opt_no_consumer, 1, nullptr, nullptr },
+       { "snapshot", 0, POPT_ARG_VAL, &opt_snapshot, 1, nullptr, nullptr },
+       { "live",
+         0,
+         POPT_ARG_INT | POPT_ARGFLAG_OPTIONAL,
+         nullptr,
+         OPT_LIVE_TIMER,
+         nullptr,
+         nullptr },
+       { "shm-path", 0, POPT_ARG_STRING, &opt_shm_path, 0, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -129,14 +134,13 @@ end:
        return ret;
 }
 
-static
-struct lttng_session_descriptor *create_session_descriptor(void)
+static struct lttng_session_descriptor *create_session_descriptor(const char *session_name)
 {
        ssize_t uri_count;
        enum output_type output_type;
-       struct lttng_uri *uris = NULL;
-       struct lttng_session_descriptor *descriptor = NULL;
-       const char *uri_str1 = NULL, *uri_str2 = NULL;
+       struct lttng_uri *uris = nullptr;
+       struct lttng_session_descriptor *descriptor = nullptr;
+       const char *uri_str1 = nullptr, *uri_str2 = nullptr;
        char local_output_path[LTTNG_PATH_MAX] = {};
 
        if (opt_no_output) {
@@ -151,12 +155,12 @@ struct lttng_session_descriptor *create_session_descriptor(void)
                        ERR("Failed to expand output path.");
                        goto end;
                }
-               ret = lttng_strncpy(local_output_path, expanded_output_path,
-                               sizeof(local_output_path));
+               ret = lttng_strncpy(
+                       local_output_path, expanded_output_path, sizeof(local_output_path));
                free(expanded_output_path);
                if (ret) {
                        ERR("Output path exceeds the maximal supported length (%zu bytes)",
-                                       sizeof(local_output_path));
+                           sizeof(local_output_path));
                        goto end;
                }
        } else if (opt_url || opt_ctrl_url) {
@@ -178,11 +182,11 @@ struct lttng_session_descriptor *create_session_descriptor(void)
                                ERR("Unrecognized URL format.");
                                goto end;
                        }
-                       ret = lttng_strncpy(local_output_path, uris[0].dst.path,
-                                       sizeof(local_output_path));
+                       ret = lttng_strncpy(
+                               local_output_path, uris[0].dst.path, sizeof(local_output_path));
                        if (ret) {
                                ERR("Output path exceeds the maximal supported length (%zu bytes)",
-                                               sizeof(local_output_path));
+                                   sizeof(local_output_path));
                        }
                        break;
                case 2:
@@ -202,48 +206,42 @@ struct lttng_session_descriptor *create_session_descriptor(void)
                case OUTPUT_UNSPECIFIED:
                case OUTPUT_LOCAL:
                        descriptor = lttng_session_descriptor_snapshot_local_create(
-                                       opt_session_name,
-                                       output_type == OUTPUT_LOCAL ?
-                                               local_output_path : NULL);
+                               session_name,
+                               output_type == OUTPUT_LOCAL ? local_output_path : nullptr);
                        break;
                case OUTPUT_NONE:
-                       descriptor = lttng_session_descriptor_snapshot_create(
-                                       opt_session_name);
+                       descriptor = lttng_session_descriptor_snapshot_create(session_name);
                        break;
                case OUTPUT_NETWORK:
                        descriptor = lttng_session_descriptor_snapshot_network_create(
-                                       opt_session_name, uri_str1, uri_str2);
+                               session_name, uri_str1, uri_str2);
                        break;
                default:
                        abort();
                }
        } else if (opt_live_timer) {
                /* Live session. */
-               if (output_type != OUTPUT_UNSPECIFIED &&
-                               output_type != OUTPUT_NETWORK) {
+               if (output_type != OUTPUT_UNSPECIFIED && output_type != OUTPUT_NETWORK) {
                        ERR("Unsupported output type specified for live session.");
                        goto end;
                }
                descriptor = lttng_session_descriptor_live_network_create(
-                               opt_session_name, uri_str1, uri_str2,
-                               opt_live_timer);
+                       session_name, uri_str1, uri_str2, opt_live_timer);
        } else {
                /* Regular session. */
                switch (output_type) {
                case OUTPUT_UNSPECIFIED:
                case OUTPUT_LOCAL:
                        descriptor = lttng_session_descriptor_local_create(
-                                       opt_session_name,
-                                       output_type == OUTPUT_LOCAL ?
-                                               local_output_path : NULL);
+                               session_name,
+                               output_type == OUTPUT_LOCAL ? local_output_path : nullptr);
                        break;
                case OUTPUT_NONE:
-                       descriptor = lttng_session_descriptor_create(
-                                       opt_session_name);
+                       descriptor = lttng_session_descriptor_create(session_name);
                        break;
                case OUTPUT_NETWORK:
                        descriptor = lttng_session_descriptor_network_create(
-                                       opt_session_name, uri_str1, uri_str2);
+                               session_name, uri_str1, uri_str2);
                        break;
                default:
                        abort();
@@ -256,16 +254,15 @@ struct lttng_session_descriptor *create_session_descriptor(void)
                 * Auto-launch the relay daemon when a live session
                 * is created using default URLs.
                 */
-               if (!opt_url && !opt_ctrl_url && !opt_data_url &&
-                               opt_live_timer && !check_relayd()) {
+               if (!opt_url && !opt_ctrl_url && !opt_data_url && opt_live_timer &&
+                   !check_relayd()) {
                        int ret;
-                       const char *pathname = opt_relayd_path ? :
-                                       INSTALL_BIN_PATH "/lttng-relayd";
+                       const char *pathname = opt_relayd_path ?: INSTALL_BIN_PATH "/lttng-relayd";
 
                        ret = spawn_relayd(pathname, 0);
                        if (ret < 0) {
                                lttng_session_descriptor_destroy(descriptor);
-                               descriptor = NULL;
+                               descriptor = nullptr;
                        }
                }
        }
@@ -280,22 +277,21 @@ end:
  *
  *  Returns one of the CMD_* result constants.
  */
-static int create_session(void)
+static int create_session(const char *session_name)
 {
        int ret, i;
        char shm_path[LTTNG_PATH_MAX] = {};
-       struct lttng_session_descriptor *session_descriptor = NULL;
+       struct lttng_session_descriptor *session_descriptor = nullptr;
        enum lttng_session_descriptor_status descriptor_status;
        enum lttng_error_code ret_code;
-       struct lttng_session *sessions = NULL;
-       const struct lttng_session *created_session = NULL;
+       struct lttng_session *sessions = nullptr;
+       const struct lttng_session *created_session = nullptr;
        const char *created_session_name;
 
        /* Validate options. */
-       if (opt_session_name) {
-               if (strlen(opt_session_name) > NAME_MAX) {
-                       ERR("Session name too long. Length must be lower or equal to %d",
-                                       NAME_MAX);
+       if (session_name) {
+               if (strlen(session_name) > NAME_MAX) {
+                       ERR("Session name too long. Length must be lower or equal to %d", NAME_MAX);
                        ret = CMD_ERROR;
                        goto error;
                }
@@ -304,13 +300,14 @@ static int create_session(void)
                 * Both are reserved for the default session name. See bug #449 to
                 * understand why we need to check both here.
                 */
-               if ((strncmp(opt_session_name, DEFAULT_SESSION_NAME "-",
-                                       strlen(DEFAULT_SESSION_NAME) + 1) == 0) ||
-                               (strncmp(opt_session_name, DEFAULT_SESSION_NAME,
-                                       strlen(DEFAULT_SESSION_NAME)) == 0 &&
-                               strlen(opt_session_name) == strlen(DEFAULT_SESSION_NAME))) {
+               if ((strncmp(session_name,
+                            DEFAULT_SESSION_NAME "-",
+                            strlen(DEFAULT_SESSION_NAME) + 1) == 0) ||
+                   (strncmp(session_name, DEFAULT_SESSION_NAME, strlen(DEFAULT_SESSION_NAME)) ==
+                            0 &&
+                    strlen(session_name) == strlen(DEFAULT_SESSION_NAME))) {
                        ERR("%s is a reserved keyword for default session(s)",
-                                       DEFAULT_SESSION_NAME);
+                           DEFAULT_SESSION_NAME);
                        ret = CMD_ERROR;
                        goto error;
                }
@@ -328,7 +325,7 @@ static int create_session(void)
                goto error;
        }
 
-       session_descriptor = create_session_descriptor();
+       session_descriptor = create_session_descriptor(session_name);
        if (!session_descriptor) {
                ret = CMD_ERROR;
                goto error;
@@ -340,8 +337,8 @@ static int create_session(void)
                goto error;
        }
 
-       descriptor_status = lttng_session_descriptor_get_session_name(
-               session_descriptor, &created_session_name);
+       descriptor_status = lttng_session_descriptor_get_session_name(session_descriptor,
+                                                                     &created_session_name);
        if (descriptor_status != LTTNG_SESSION_DESCRIPTOR_STATUS_OK) {
                ERR("Failed to obtain created session name");
                ret = CMD_ERROR;
@@ -350,8 +347,7 @@ static int create_session(void)
 
        ret = lttng_list_sessions(&sessions);
        if (ret < 0) {
-               ERR("Failed to fetch properties of created session: %s",
-                               lttng_strerror(ret));
+               ERR("Failed to fetch properties of created session: %s", lttng_strerror(ret));
                ret = CMD_ERROR;
                goto error;
        }
@@ -374,15 +370,13 @@ static int create_session(void)
                 * An auto-generated session name already includes the creation
                 * timestamp.
                 */
-               if (opt_session_name) {
+               if (session_name) {
                        uint64_t creation_time;
                        struct tm *timeinfo;
                        time_t creation_time_t;
                        size_t strftime_ret;
 
-                       ret_code = lttng_session_get_creation_time(
-                                       created_session,
-                                       &creation_time);
+                       ret_code = lttng_session_get_creation_time(created_session, &creation_time);
                        if (ret_code != LTTNG_OK) {
                                ERR("%s", lttng_strerror(-ret_code));
                                ret = CMD_ERROR;
@@ -396,8 +390,9 @@ static int create_session(void)
                                goto error;
                        }
                        strftime_ret = strftime(datetime_suffix,
-                                       sizeof(datetime_suffix),
-                                       "-%Y%m%d-%H%M%S", timeinfo);
+                                               sizeof(datetime_suffix),
+                                               "-%Y%m%d-%H%M%S",
+                                               timeinfo);
                        if (strftime_ret == 0) {
                                ERR("Failed to format session creation time.");
                                ret = CMD_ERROR;
@@ -405,16 +400,18 @@ static int create_session(void)
                        }
                }
 
-               ret = snprintf(shm_path, sizeof(shm_path),
-                               "%s/%s%s", opt_shm_path, created_session_name,
-                               datetime_suffix);
+               ret = snprintf(shm_path,
+                              sizeof(shm_path),
+                              "%s/%s%s",
+                              opt_shm_path,
+                              created_session_name,
+                              datetime_suffix);
                if (ret < 0 || ret >= sizeof(shm_path)) {
                        ERR("Failed to format the shared memory path.");
                        ret = CMD_ERROR;
                        goto error;
                }
-               ret = lttng_set_session_shm_path(created_session_name,
-                               shm_path);
+               ret = lttng_set_session_shm_path(created_session_name, shm_path);
                if (ret < 0) {
                        lttng_destroy_session(created_session_name);
                        ret = CMD_ERROR;
@@ -434,8 +431,7 @@ static int create_session(void)
                MSG("Traces will be output to %s", created_session->path);
 
                if (opt_live_timer) {
-                       MSG("Live timer interval set to %u %s", opt_live_timer,
-                                       USEC_UNIT);
+                       MSG("Live timer interval set to %u %s", opt_live_timer, USEC_UNIT);
                }
        } else if (opt_snapshot) {
                struct lttng_snapshot_output_list *list;
@@ -450,12 +446,10 @@ static int create_session(void)
                }
 
                while ((iter = lttng_snapshot_output_list_get_next(list))) {
-                       const char *url = NULL;
+                       const char *url = nullptr;
 
-                       url = lttng_snapshot_output_get_ctrl_url(
-                                       iter);
-                       ret = lttng_strncpy(snapshot_url, url,
-                                       sizeof(snapshot_url));
+                       url = lttng_snapshot_output_get_ctrl_url(iter);
+                       ret = lttng_strncpy(snapshot_url, url, sizeof(snapshot_url));
                        if (ret) {
                                snapshot_url[0] = '\0';
                                ERR("Failed to retrieve snapshot output destination");
@@ -465,8 +459,7 @@ static int create_session(void)
                lttng_snapshot_output_list_destroy(list);
 
                if (*snapshot_url) {
-                       MSG("Default snapshot output set to %s",
-                                       snapshot_url);
+                       MSG("Default snapshot output set to %s", snapshot_url);
                }
                MSG("Every channel enabled for this session will be set to mmap output and default to overwrite mode.");
        }
@@ -513,15 +506,14 @@ static int spawn_sessiond(const char *pathname)
                /*
                 * Spawn session daemon in daemon mode.
                 */
-               execlp(pathname, "lttng-sessiond",
-                               "--daemonize", NULL);
+               execlp(pathname, "lttng-sessiond", "--daemonize", NULL);
                /* execlp only returns if error happened */
                if (errno == ENOENT) {
                        ERR("No session daemon found. Use --sessiond-path.");
                } else {
                        PERROR("execlp");
                }
-               kill(getppid(), SIGTERM);       /* wake parent */
+               kill(getppid(), SIGTERM); /* wake parent */
                exit(EXIT_FAILURE);
        } else if (pid > 0) {
                /*
@@ -542,19 +534,18 @@ static int spawn_sessiond(const char *pathname)
                        }
 
                        if (WIFSIGNALED(status)) {
-                               ERR("Session daemon was killed by signal %d",
-                                               WTERMSIG(status));
+                               ERR("Session daemon was killed by signal %d", WTERMSIG(status));
                                ret = -1;
-                               goto end;
+                               goto end;
                        } else if (WIFEXITED(status)) {
                                DBG("Session daemon terminated normally (exit status: %d)",
-                                               WEXITSTATUS(status));
+                                   WEXITSTATUS(status));
 
                                if (WEXITSTATUS(status) != 0) {
                                        ERR("Session daemon terminated with an error (exit status: %d)",
-                                                       WEXITSTATUS(status));
+                                           WEXITSTATUS(status));
                                        ret = -1;
-                                       goto end;
+                                       goto end;
                                }
                                break;
                        }
@@ -578,10 +569,10 @@ end:
  *  the liblttngctl API for the check. If not, try to
  *  spawn a daemon.
  */
-static int launch_sessiond(void)
+static int launch_sessiond()
 {
        int ret;
-       const char *pathname = NULL;
+       const char *pathname = nullptr;
 
        ret = lttng_session_daemon_alive();
        if (ret) {
@@ -594,19 +585,19 @@ static int launch_sessiond(void)
        pathname = opt_sessiond_path;
 
        /* Try LTTNG_SESSIOND_PATH env variable */
-       if (pathname == NULL) {
+       if (pathname == nullptr) {
                pathname = getenv(DEFAULT_SESSIOND_PATH_ENV);
        }
 
        /* Try with configured path */
-       if (pathname == NULL) {
+       if (pathname == nullptr) {
                if (CONFIG_SESSIOND_BIN[0] != '\0') {
                        pathname = CONFIG_SESSIOND_BIN;
                }
        }
 
        /* Try the default path */
-       if (pathname == NULL) {
+       if (pathname == nullptr) {
                pathname = INSTALL_BIN_PATH "/lttng-sessiond";
        }
 
@@ -622,14 +613,12 @@ static int launch_sessiond(void)
        ret = spawn_sessiond(pathname);
 end:
        if (ret) {
-               ERR("Problem occurred while launching session daemon (%s)",
-                               pathname);
+               ERR("Problem occurred while launching session daemon (%s)", pathname);
        }
        return ret;
 }
 
-static
-int validate_url_option_combination(void)
+static int validate_url_option_combination()
 {
        int ret = 0;
        int used_count = 0;
@@ -653,11 +642,12 @@ int validate_url_option_combination(void)
 int cmd_create(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
-       char *opt_arg = NULL;
-       const char *leftover = NULL;
+       char *opt_arg = nullptr;
+       const char *arg_session_name = nullptr;
+       const char *leftover = nullptr;
        static poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -683,7 +673,7 @@ int cmd_create(int argc, const char **argv)
                                /* Set up default values. */
                                opt_live_timer = (uint32_t) DEFAULT_LTTNG_LIVE_TIMER;
                                DBG("Session live timer interval set to default value %d",
-                                               opt_live_timer);
+                                   opt_live_timer);
                                break;
                        }
 
@@ -745,22 +735,22 @@ int cmd_create(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_create);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_create);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
-       opt_session_name = (char*) poptGetArg(pc);
+
+       /* Get the optional session name argument. */
+       arg_session_name = poptGetArg(pc);
 
        leftover = poptGetArg(pc);
        if (leftover) {
@@ -769,7 +759,7 @@ int cmd_create(int argc, const char **argv)
                goto end;
        }
 
-       command_ret = create_session();
+       command_ret = create_session(arg_session_name);
        if (command_ret) {
                success = 0;
        }
@@ -783,8 +773,8 @@ int cmd_create(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
index 3ab9b224849180052f9755036abd279ab794fe6b..ef4b914d38bd39f124debce1dfb31600ba572a50 100644 (file)
@@ -6,47 +6,54 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "../exception.hpp"
+
+#include <common/exception.hpp>
+#include <common/make-unique-wrapper.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/scope-exit.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
 #include <popt.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <stdbool.h>
-#include <lttng/lttng.h>
 
-#include "../command.hpp"
-
-#include <common/mi-lttng.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
-
-static char *opt_session_name;
-static int opt_destroy_all;
-static int opt_no_wait;
+enum {
+       OPT_HELP = 1,
+       OPT_LIST_OPTIONS,
+       OPT_ALL,
+       OPT_ENABLE_GLOB,
+};
 
+namespace {
 #ifdef LTTNG_EMBED_HELP
-static const char help_msg[] =
+const char help_msg[] =
 #include <lttng-destroy.1.h>
-;
+       ;
 #endif
 
-/* Mi writer */
-static struct mi_writer *writer;
+int opt_no_wait;
 
-enum {
-       OPT_HELP = 1,
-       OPT_LIST_OPTIONS,
-};
+/* Mi writer */
+struct mi_writer *writer;
 
-static struct poptOption long_options[] = {
+struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"all",       'a', POPT_ARG_VAL, &opt_destroy_all, 1, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"no-wait",   'n', POPT_ARG_VAL, &opt_no_wait, 1, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_NONE, nullptr, OPT_ALL, nullptr, nullptr },
+       { "glob", 'g', POPT_ARG_NONE, nullptr, OPT_ENABLE_GLOB, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "no-wait", 'n', POPT_ARG_VAL, &opt_no_wait, 1, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -55,30 +62,33 @@ static struct poptOption long_options[] = {
  * Unregister the provided session to the session daemon. On success, removes
  * the default configuration.
  */
-static int destroy_session(struct lttng_session *session)
+cmd_error_code destroy_session(const lttng_session& session)
 {
        int ret;
-       char *session_name = NULL;
-       bool session_was_already_stopped;
-       enum lttng_error_code ret_code;
-       struct lttng_destruction_handle *handle = NULL;
-       enum lttng_destruction_handle_status status;
        bool newline_needed = false, printed_destroy_msg = false;
-       enum lttng_rotation_state rotation_state;
-       char *stats_str = NULL;
 
-       ret = lttng_stop_tracing_no_wait(session->name);
+       const auto print_trailing_new_line = lttng::make_scope_exit([&newline_needed]() noexcept {
+               if (newline_needed) {
+                       MSG("");
+               }
+       });
+
+       ret = lttng_stop_tracing_no_wait(session.name);
        if (ret < 0 && ret != -LTTNG_ERR_TRACE_ALREADY_STOPPED) {
-               ERR("%s", lttng_strerror(ret));
+               LTTNG_THROW_CTL(lttng::format("Failed to stop session `{}`", session.name),
+                               static_cast<lttng_error_code>(-ret));
        }
 
-       session_was_already_stopped = ret == -LTTNG_ERR_TRACE_ALREADY_STOPPED;
+       const auto session_was_already_stopped = ret == -LTTNG_ERR_TRACE_ALREADY_STOPPED;
        if (!opt_no_wait) {
                do {
-                       ret = lttng_data_pending(session->name);
+                       ret = lttng_data_pending(session.name);
                        if (ret < 0) {
                                /* Return the data available call error. */
-                               goto error;
+                               ERR_FMT("Failed to check pending data for session `{}` ({})",
+                                       session.name,
+                                       lttng_strerror(ret));
+                               return CMD_ERROR;
                        }
 
                        /*
@@ -88,8 +98,7 @@ static int destroy_session(struct lttng_session *session)
                         */
                        if (ret) {
                                if (!printed_destroy_msg) {
-                                       _MSG("Destroying session %s",
-                                                       session->name);
+                                       _MSG("Destroying session `%s`", session.name);
                                        newline_needed = true;
                                        printed_destroy_msg = true;
                                        fflush(stdout);
@@ -102,164 +111,232 @@ static int destroy_session(struct lttng_session *session)
                } while (ret != 0);
        }
 
+       std::unique_ptr<char,
+                       lttng::memory::create_deleter_class<char, lttng::memory::free>::deleter>
+               stats_str;
        if (!session_was_already_stopped) {
+               char *raw_stats_str = nullptr;
+
                /*
                 * Don't print the event and packet loss warnings since the user
                 * already saw them when stopping the trace.
                 */
-               ret = get_session_stats_str(session->name, &stats_str);
+               ret = get_session_stats_str(session.name, &raw_stats_str);
                if (ret < 0) {
-                       goto error;
+                       return CMD_ERROR;
                }
-       }
 
-       ret_code = lttng_destroy_session_ext(session->name, &handle);
-       if (ret_code != LTTNG_OK) {
-               ret = -ret_code;
-               goto error;
+               /* May still be null if there are no stats to print. */
+               stats_str.reset(raw_stats_str);
        }
 
-       if (opt_no_wait) {
-               goto skip_wait_rotation;
-       }
+       const auto destruction_handle = [&session]() {
+               struct lttng_destruction_handle *raw_destruction_handle = nullptr;
 
-       do {
-               status = lttng_destruction_handle_wait_for_completion(
-                               handle, DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US /
-                                                       USEC_PER_MSEC);
-               switch (status) {
-               case LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT:
-                       if (!printed_destroy_msg) {
-                               _MSG("Destroying session %s", session->name);
-                               newline_needed = true;
-                               printed_destroy_msg = true;
-                       }
-                       _MSG(".");
-                       fflush(stdout);
-                       break;
-               case LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED:
-                       break;
-               default:
-                       ERR("%sFailed to wait for the completion of the destruction of session \"%s\"",
+               auto ctl_ret_code =
+                       lttng_destroy_session_ext(session.name, &raw_destruction_handle);
+               if (ctl_ret_code != LTTNG_OK) {
+                       LTTNG_THROW_CTL(lttng::format("Failed to destroy session `{}`",
+                                                     session.name),
+                                       ctl_ret_code);
+               }
+
+               return lttng::make_unique_wrapper<lttng_destruction_handle,
+                                                 lttng_destruction_handle_destroy>(
+                       raw_destruction_handle);
+       }();
+
+       if (!opt_no_wait) {
+               enum lttng_destruction_handle_status status;
+
+               do {
+                       status = lttng_destruction_handle_wait_for_completion(
+                               destruction_handle.get(),
+                               DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US / USEC_PER_MSEC);
+                       switch (status) {
+                       case LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT:
+                               if (!printed_destroy_msg) {
+                                       _MSG("Destroying session `%s`", session.name);
+                                       newline_needed = true;
+                                       printed_destroy_msg = true;
+                               }
+                               _MSG(".");
+                               fflush(stdout);
+                               break;
+                       case LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED:
+                               break;
+                       default:
+                               ERR_FMT("{}An error occurred during the destruction of session `{}`",
                                        newline_needed ? "\n" : "",
-                                       session->name);
+                                       session.name);
+                               newline_needed = false;
+                               return CMD_ERROR;
+                       }
+               } while (status == LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT);
+
+               enum lttng_error_code ctl_ret_code;
+               status = lttng_destruction_handle_get_result(destruction_handle.get(),
+                                                            &ctl_ret_code);
+               if (status != LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
+                       ERR_FMT("{}Failed to query the result of the destruction of session `{}`",
+                               newline_needed ? "\n" : "",
+                               session.name);
+
                        newline_needed = false;
-                       ret = -1;
-                       goto error;
+                       return CMD_ERROR;
                }
-       } while (status == LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT);
-
-       status = lttng_destruction_handle_get_result(handle, &ret_code);
-       if (status != LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
-               ERR("%sFailed to get the result of session destruction",
-                               newline_needed ? "\n" : "");
-               ret = -1;
-               newline_needed = false;
-               goto error;
-       }
-       if (ret_code != LTTNG_OK) {
-               ret = -ret_code;
-               goto error;
-       }
 
-       status = lttng_destruction_handle_get_rotation_state(
-                       handle, &rotation_state);
-       if (status != LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
-               ERR("%sFailed to get rotation state from destruction handle",
-                               newline_needed ? "\n" : "");
-               newline_needed = false;
-               goto skip_wait_rotation;
-       }
+               if (ctl_ret_code != LTTNG_OK) {
+                       LTTNG_THROW_CTL(lttng::format("Failed to destroy session `{}`",
+                                                     session.name),
+                                       ctl_ret_code);
+               }
 
-       switch (rotation_state) {
-       case LTTNG_ROTATION_STATE_NO_ROTATION:
-               break;
-       case LTTNG_ROTATION_STATE_COMPLETED:
-       {
-               const struct lttng_trace_archive_location *location;
-
-               status = lttng_destruction_handle_get_archive_location(
-                               handle, &location);
-               if (status == LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
-                       ret = print_trace_archive_location(
-                                       location, session->name);
-                       if (ret) {
-                               ERR("%sFailed to print the location of trace archive",
-                                               newline_needed ? "\n" : "");
+               enum lttng_rotation_state rotation_state;
+               status = lttng_destruction_handle_get_rotation_state(destruction_handle.get(),
+                                                                    &rotation_state);
+               if (status != LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
+                       ERR_FMT("{}Failed to query the rotation state from the destruction handle of session `{}`",
+                               newline_needed ? "\n" : "",
+                               session.name);
+                       newline_needed = false;
+               } else {
+                       switch (rotation_state) {
+                       case LTTNG_ROTATION_STATE_NO_ROTATION:
+                               break;
+                       case LTTNG_ROTATION_STATE_COMPLETED:
+                       {
+                               const struct lttng_trace_archive_location *location;
+
+                               status = lttng_destruction_handle_get_archive_location(
+                                       destruction_handle.get(), &location);
+                               if (status == LTTNG_DESTRUCTION_HANDLE_STATUS_OK) {
+                                       ret = print_trace_archive_location(location, session.name);
+                                       if (ret) {
+                                               ERR_FMT("{}Failed to print the location of the latest trace archive of session `{}`",
+                                                       newline_needed ? "\n" : "",
+                                                       session.name);
+                                               newline_needed = false;
+                                       }
+
+                                       break;
+                               }
+                       }
+                       /* fall-through. */
+                       default:
+                               ERR_FMT("{}Failed to get the location of the rotation performed during the destruction of `{}`",
+                                       newline_needed ? "\n" : "",
+                                       session.name);
                                newline_needed = false;
-                               goto skip_wait_rotation;
+                               break;
                        }
-                       break;
                }
        }
-       /* fall-through. */
-       default:
-               ERR("%sFailed to get the location of the rotation performed during the session's destruction",
-                               newline_needed ? "\n" : "");
-               newline_needed = false;
-               goto skip_wait_rotation;
-       }
-skip_wait_rotation:
-       MSG("%sSession %s destroyed", newline_needed ? "\n" : "",
-                       session->name);
+
+       MSG("%sSession `%s` destroyed", newline_needed ? "\n" : "", session.name);
        newline_needed = false;
        if (stats_str) {
-               MSG("%s", stats_str);
+               MSG("%s", stats_str.get());
        }
 
-       session_name = get_session_name_quiet();
-       if (session_name && !strncmp(session->name, session_name, NAME_MAX)) {
+       /*
+        * If the session being destroy is the "default" session as defined in the .lttngrc file,
+        * destroy the file.
+        */
+       const auto session_name =
+               lttng::make_unique_wrapper<char, lttng::memory::free>(get_session_name_quiet());
+       if (session_name && !strncmp(session.name, session_name.get(), NAME_MAX)) {
                config_destroy_default();
        }
 
        if (lttng_opt_mi) {
-               ret = mi_lttng_session(writer, session, 0);
+               ret = mi_lttng_session(writer, &session, 0);
                if (ret) {
-                       ret = CMD_ERROR;
-                       goto error;
+                       return CMD_ERROR;
                }
        }
 
-       ret = CMD_SUCCESS;
-error:
-       if (newline_needed) {
-               MSG("");
-       }
-       lttng_destruction_handle_destroy(handle);
-       free(session_name);
-       free(stats_str);
-       return ret;
+       return CMD_SUCCESS;
 }
 
-/*
- * destroy_all_sessions
- *
- * Call destroy_sessions for each registered sessions
- */
-static int destroy_all_sessions(struct lttng_session *sessions, int count)
+cmd_error_code destroy_sessions(const lttng::cli::session_spec& spec)
 {
-       int i;
-       bool error_occurred = false;
+       bool had_warning = false;
+       bool had_error = false;
+       bool listing_failed = false;
+
+       const auto sessions = [&listing_failed, &spec]() -> lttng::cli::session_list {
+               try {
+                       return list_sessions(spec);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       ERR_FMT("Failed to list sessions ({})",
+                               lttng_strerror(-ctl_exception.code()));
+                       listing_failed = true;
+                       return {};
+               } catch (const lttng::cli::no_default_session_error& cli_exception) {
+                       /*
+                        * The retrieval of the default session name already logs
+                        * an error when it fails. There is no value in printing
+                        * anything about this exception.
+                        */
+                       listing_failed = true;
+                       return {};
+               }
+       }();
 
-       LTTNG_ASSERT(count >= 0);
-       if (count == 0) {
-               MSG("No session found, nothing to do.");
+       if (!listing_failed && sessions.size() == 0 &&
+           spec.type_ == lttng::cli::session_spec::type::NAME) {
+               ERR_FMT("Session `{}` not found", spec.value);
+               return CMD_ERROR;
        }
 
-       for (i = 0; i < count; i++) {
-               int ret = destroy_session(&sessions[i]);
+       if (listing_failed) {
+               return CMD_FATAL;
+       }
 
-               if (ret < 0) {
-                       ERR("%s during the destruction of session \"%s\"",
-                                       lttng_strerror(ret),
-                                       sessions[i].name);
-                       /* Continue to next session. */
-                       error_occurred = true;
+       for (const auto& session : sessions) {
+               cmd_error_code sub_ret;
+
+               try {
+                       sub_ret = destroy_session(session);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       switch (ctl_exception.code()) {
+                       case LTTNG_ERR_NO_SESSION:
+                               if (spec.type_ != lttng::cli::session_spec::type::NAME) {
+                                       /* Session destroyed during command, ignore and carry-on. */
+                                       sub_ret = CMD_SUCCESS;
+                                       break;
+                               } else {
+                                       sub_ret = CMD_ERROR;
+                                       break;
+                               }
+                       case LTTNG_ERR_NO_SESSIOND:
+                               /* Don't keep going on a fatal error. */
+                               return CMD_FATAL;
+                       default:
+                               /* Generic error. */
+                               sub_ret = CMD_ERROR;
+                               ERR_FMT("Failed to destroy session `{}` ({})",
+                                       session.name,
+                                       lttng_strerror(-ctl_exception.code()));
+                               break;
+                       }
                }
+
+               /* Keep going, but report the most serious state. */
+               had_warning |= sub_ret == CMD_WARNING;
+               had_error |= sub_ret == CMD_ERROR;
        }
 
-       return error_occurred ? CMD_ERROR : CMD_SUCCESS;
+       if (had_error) {
+               return CMD_ERROR;
+       } else if (had_warning) {
+               return CMD_WARNING;
+       } else {
+               return CMD_SUCCESS;
+       }
 }
+} /* namespace */
 
 /*
  * The 'destroy <options>' first level command
@@ -267,167 +344,108 @@ static int destroy_all_sessions(struct lttng_session *sessions, int count)
 int cmd_destroy(int argc, const char **argv)
 {
        int opt;
-       int ret = CMD_SUCCESS , i, command_ret = CMD_SUCCESS, success = 1;
+       cmd_error_code command_ret = CMD_SUCCESS;
+       bool success;
        static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
-
-       struct lttng_session *sessions = NULL;
-       int count;
-       int found;
+       const char *leftover = nullptr;
+       lttng::cli::session_spec spec(lttng::cli::session_spec::type::NAME);
+       lttng::cli::session_list const sessions;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
                switch (opt) {
                case OPT_HELP:
+               {
+                       int ret;
+
                        SHOW_HELP();
-                       break;
+                       command_ret = static_cast<cmd_error_code>(ret);
+                       goto end;
+               }
                case OPT_LIST_OPTIONS:
                        list_cmd_options(stdout, long_options);
+                       goto end;
+               case OPT_ALL:
+                       spec.type_ = lttng::cli::session_spec::type::ALL;
                        break;
-               default:
-                       ret = CMD_UNDEFINED;
+               case OPT_ENABLE_GLOB:
+                       spec.type_ = lttng::cli::session_spec::type::GLOB_PATTERN;
                        break;
+               default:
+                       command_ret = CMD_UNDEFINED;
+                       goto end;
                }
-               goto end;
        }
 
        /* Mi preparation */
        if (lttng_opt_mi) {
                writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!writer) {
-                       ret = -LTTNG_ERR_NOMEM;
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_destroy);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_open(writer, mi_lttng_element_command_destroy)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_open_element(writer, mi_lttng_element_command_output)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* For validation and semantic purpose we open a sessions element */
-               ret = mi_lttng_sessions_open(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_sessions_open(writer)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       /* Recuperate all sessions for further operation */
-       count = lttng_list_sessions(&sessions);
-       if (count < 0) {
-               ERR("%s", lttng_strerror(count));
-               command_ret = CMD_ERROR;
-               success = 0;
-               goto mi_closing;
-       }
-
-       /* Ignore session name in case all sessions are to be destroyed */
-       if (opt_destroy_all) {
-               command_ret = destroy_all_sessions(sessions, count);
-               if (command_ret) {
-                       success = 0;
-               }
-       } else {
-               opt_session_name = (char *) poptGetArg(pc);
-
-               if (!opt_session_name) {
-                       /* No session name specified, lookup default */
-                       session_name = get_session_name();
-                       if (session_name == NULL) {
-                               command_ret = CMD_ERROR;
-                               success = 0;
-                               goto mi_closing;
-                       }
-               } else {
-                       session_name = opt_session_name;
-               }
+       spec.value = poptGetArg(pc);
 
-               /* Find the corresponding lttng_session struct */
-               found = 0;
-               for (i = 0; i < count; i++) {
-                       if (strncmp(sessions[i].name, session_name, NAME_MAX) == 0) {
-                               found = 1;
-                               command_ret = destroy_session(&sessions[i]);
-                               if (command_ret) {
-                                       success = 0;
-                                       ERR("%s during the destruction of session \"%s\"",
-                                                       lttng_strerror(command_ret),
-                                                       sessions[i].name);
-                               }
-                       }
-               }
+       command_ret = destroy_sessions(spec);
 
-               if (!found) {
-                       ERR("Session name %s not found", session_name);
-                       command_ret = LTTNG_ERR_SESS_NOT_FOUND;
-                       success = 0;
-                       goto mi_closing;
-               }
-       }
+       success = command_ret == CMD_SUCCESS;
 
        leftover = poptGetArg(pc);
        if (leftover) {
                ERR("Unknown argument: %s", leftover);
-               ret = CMD_ERROR;
-               success = 0;
-               goto mi_closing;
+               command_ret = CMD_ERROR;
+               success = false;
        }
 
-mi_closing:
        /* Mi closing */
        if (lttng_opt_mi) {
                /* Close sessions and output element element */
-               ret = mi_lttng_close_multi_element(writer, 2);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_close_multi_element(writer, 2)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_write_element_bool(
+                           writer, mi_lttng_element_command_success, success)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Command element close */
-               ret = mi_lttng_writer_command_close(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_close(writer)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
 end:
        /* Mi clean-up */
        if (writer && mi_lttng_writer_destroy(writer)) {
-               /* Preserve original error code */
-               ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
-       }
-
-       if (opt_session_name == NULL) {
-               free(session_name);
+               command_ret = CMD_ERROR;
        }
 
-       free(sessions);
-
-       /* Overwrite ret if an error occurred during destroy_session/all */
-       ret = command_ret ? command_ret : ret;
-
        poptFreeContext(pc);
-       return ret;
+       return command_ret;
 }
index df9eb13fac04a52f8334efbedab5ae2f38cd73b6..2c006552c7da5a4342ac5f31e0328e58681f2892 100644 (file)
@@ -6,6 +6,12 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
+#include <lttng/domain-internal.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-#include <lttng/domain-internal.hpp>
-
-#include "../command.hpp"
-
-static char *opt_channels;
 static int opt_kernel;
 static char *opt_session_name;
 static int opt_userspace;
@@ -27,7 +27,7 @@ static int opt_userspace;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-disable-channel.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -41,16 +41,15 @@ static struct mi_writer *writer;
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",        's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"kernel",         'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"userspace",      'u', POPT_ARG_NONE, 0, OPT_USERSPACE, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_NONE, nullptr, OPT_USERSPACE, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
-static int mi_partial_channel_print(char *channel_name, unsigned int enabled,
-               int success)
+static int mi_partial_channel_print(char *channel_name, unsigned int enabled, int success)
 {
        int ret;
 
@@ -64,22 +63,19 @@ static int mi_partial_channel_print(char *channel_name, unsigned int enabled,
        }
 
        /* Name */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       channel_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, channel_name);
        if (ret) {
                goto end;
        }
 
        /* Enabled ? */
-       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled,
-                       enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, enabled);
        if (ret) {
                goto end;
        }
 
        /* Success ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       mi_lttng_element_success, success);
+       ret = mi_lttng_writer_write_element_bool(writer, mi_lttng_element_success, success);
        if (ret) {
                goto end;
        }
@@ -94,12 +90,11 @@ end:
 /*
  * Disabling channel using the lttng API.
  */
-static int disable_channels(char *session_name)
+static int disable_channels(char *session_name, char *channel_list)
 {
-       int ret = CMD_SUCCESS, warn = 0, success;
-
-       /* Normal case for disable channed is enabled = 0 */
-       unsigned int enabled = 0;
+       int ret = CMD_SUCCESS;
+       /* Normal case for disable channed is enabled = false */
+       bool warn = false, success, enabled = false;
        char *channel_name;
        struct lttng_domain dom;
 
@@ -116,7 +111,7 @@ static int disable_channels(char *session_name)
        }
 
        handle = lttng_create_handle(session_name, &dom);
-       if (handle == NULL) {
+       if (handle == nullptr) {
                ret = -1;
                goto error;
        }
@@ -129,19 +124,20 @@ static int disable_channels(char *session_name)
                        ret = CMD_ERROR;
                        goto error;
                }
-
        }
 
        /* Strip channel list */
-       channel_name = strtok(opt_channels, ",");
-       while (channel_name != NULL) {
+       channel_name = strtok(channel_list, ",");
+       while (channel_name != nullptr) {
                DBG("Disabling channel %s", channel_name);
 
                ret = lttng_disable_channel(handle, channel_name);
                if (ret < 0) {
-                       ERR("Channel %s: %s (session %s)", channel_name,
-                                       lttng_strerror(ret), session_name);
-                       warn = 1;
+                       ERR("Channel %s: %s (session %s)",
+                           channel_name,
+                           lttng_strerror(ret),
+                           session_name);
+                       warn = true;
 
                        /*
                         * Mi:
@@ -150,15 +146,16 @@ static int disable_channels(char *session_name)
                         * The client should look at the stderr stream
                         * for more informations.
                         */
-                       enabled = 1;
-                       success = 0;
+                       enabled = true;
+                       success = false;
 
                } else {
                        MSG("%s channel %s disabled for session %s",
-                                       lttng_domain_type_str(dom.type),
-                                       channel_name, session_name);
-                       enabled = 0;
-                       success = 1;
+                           lttng_domain_type_str(dom.type),
+                           channel_name,
+                           session_name);
+                       enabled = false;
+                       success = true;
                }
 
                /* Print the channel */
@@ -171,7 +168,7 @@ static int disable_channels(char *session_name)
                }
 
                /* Next channel */
-               channel_name = strtok(NULL, ",");
+               channel_name = strtok(nullptr, ",");
        }
 
        ret = CMD_SUCCESS;
@@ -206,10 +203,12 @@ int cmd_disable_channels(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
        static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
+       char *session_name = nullptr;
+       char *channel_list = nullptr;
+       const char *arg_channel_list = nullptr;
+       const char *leftover = nullptr;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -229,16 +228,22 @@ int cmd_disable_channels(int argc, const char **argv)
                }
        }
 
-       ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace, false);
+       ret = print_missing_or_multiple_domains(opt_kernel + opt_userspace, false);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
        }
 
-       opt_channels = (char*) poptGetArg(pc);
-       if (opt_channels == NULL) {
-               ERR("Missing channel name(s).\n");
+       arg_channel_list = poptGetArg(pc);
+       if (arg_channel_list == nullptr) {
+               ERR("Missing channel name(s).");
+               ret = CMD_ERROR;
+               goto end;
+       }
+
+       channel_list = strdup(arg_channel_list);
+       if (channel_list == nullptr) {
+               PERROR("Failed to copy channel name");
                ret = CMD_ERROR;
                goto end;
        }
@@ -252,7 +257,7 @@ int cmd_disable_channels(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -270,22 +275,21 @@ int cmd_disable_channels(int argc, const char **argv)
 
                /* Open command element */
                ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_disable_channel);
+                                                  mi_lttng_element_command_disable_channel);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       command_ret = disable_channels(session_name);
+       command_ret = disable_channels(session_name, channel_list);
        if (command_ret) {
                success = 0;
        }
@@ -300,8 +304,7 @@ int cmd_disable_channels(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_success, success);
+               ret = mi_lttng_writer_write_element_bool(writer, mi_lttng_element_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -326,6 +329,8 @@ end:
                free(session_name);
        }
 
+       free(channel_list);
+
        /* Overwrite ret if an error occurred in disable_channels */
        ret = command_ret ? command_ret : ret;
 
index d2948ac041928814f51a7ebd0610b5811fcecfee..40e85e7c8afe6b447f1cacda25ba6d4d20ef0de9 100644 (file)
@@ -6,6 +6,12 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
+#include <lttng/domain-internal.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-#include <lttng/domain-internal.hpp>
-
-#include "../command.hpp"
-
-static char *opt_event_list;
 static int opt_kernel;
 static char *opt_channel_name;
 static char *opt_session_name;
@@ -33,7 +33,7 @@ static int opt_event_type;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-disable-event.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -51,38 +51,35 @@ static struct mi_writer *writer;
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",        's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"all-events",     'a', POPT_ARG_VAL, &opt_disable_all, 1, 0, 0},
-       {"channel",        'c', POPT_ARG_STRING, &opt_channel_name, 0, 0, 0},
-       {"jul",            'j', POPT_ARG_VAL, &opt_jul, 1, 0, 0},
-       {"log4j",          'l', POPT_ARG_VAL, &opt_log4j, 1, 0, 0},
-       {"python",         'p', POPT_ARG_VAL, &opt_python, 1, 0, 0},
-       {"kernel",         'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"userspace",      'u', POPT_ARG_VAL, &opt_userspace, 1, 0, 0},
-       {"syscall",          0, POPT_ARG_NONE, 0, OPT_TYPE_SYSCALL, 0, 0},
-       {"probe",            0, POPT_ARG_NONE, 0, OPT_TYPE_PROBE, 0, 0},
-       {"tracepoint",       0, POPT_ARG_NONE, 0, OPT_TYPE_TRACEPOINT, 0, 0},
-       {"function",         0, POPT_ARG_NONE, 0, OPT_TYPE_FUNCTION, 0, 0},
-       {"all",              0, POPT_ARG_NONE, 0, OPT_TYPE_ALL, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "all-events", 'a', POPT_ARG_VAL, &opt_disable_all, 1, nullptr, nullptr },
+       { "channel", 'c', POPT_ARG_STRING, &opt_channel_name, 0, nullptr, nullptr },
+       { "jul", 'j', POPT_ARG_VAL, &opt_jul, 1, nullptr, nullptr },
+       { "log4j", 'l', POPT_ARG_VAL, &opt_log4j, 1, nullptr, nullptr },
+       { "python", 'p', POPT_ARG_VAL, &opt_python, 1, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_VAL, &opt_userspace, 1, nullptr, nullptr },
+       { "syscall", 0, POPT_ARG_NONE, nullptr, OPT_TYPE_SYSCALL, nullptr, nullptr },
+       { "probe", 0, POPT_ARG_NONE, nullptr, OPT_TYPE_PROBE, nullptr, nullptr },
+       { "tracepoint", 0, POPT_ARG_NONE, nullptr, OPT_TYPE_TRACEPOINT, nullptr, nullptr },
+       { "function", 0, POPT_ARG_NONE, nullptr, OPT_TYPE_FUNCTION, nullptr, nullptr },
+       { "all", 0, POPT_ARG_NONE, nullptr, OPT_TYPE_ALL, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
-static
-const char *print_channel_name(const char *name)
+static const char *print_channel_name(const char *name)
 {
-       return name ? : DEFAULT_CHANNEL_NAME;
+       return name ?: DEFAULT_CHANNEL_NAME;
 }
 
-static
-const char *print_raw_channel_name(const char *name)
+static const char *print_raw_channel_name(const char *name)
 {
-       return name ? : "<default>";
+       return name ?: "<default>";
 }
 
-static
-const char *print_event_type(const enum lttng_event_type ev_type)
+static const char *print_event_type(const enum lttng_event_type ev_type)
 {
        switch (ev_type) {
        case LTTNG_EVENT_ALL:
@@ -120,22 +117,19 @@ static int mi_print_event(const char *event_name, int enabled, int success)
        }
 
        /* Print the name of event */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, event_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, event_name);
        if (ret) {
                goto end;
        }
 
        /* Print enabled ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       config_element_enabled, enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, enabled);
        if (ret) {
                goto end;
        }
 
        /* Success ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       mi_lttng_element_command_success, success);
+       ret = mi_lttng_writer_write_element_bool(writer, mi_lttng_element_command_success, success);
        if (ret) {
                goto end;
        }
@@ -151,11 +145,11 @@ end:
  *
  *  Disabling event using the lttng API.
  */
-static int disable_events(char *session_name)
+static int disable_events(char *session_name, char *event_list)
 {
-       int ret = CMD_SUCCESS, warn = 0, command_ret = CMD_SUCCESS;
-       int enabled = 1, success = 1;
-       char *event_name, *channel_name = NULL;
+       enum cmd_error_code ret = CMD_SUCCESS, command_ret = CMD_SUCCESS;
+       bool enabled = true, success = true, warn = false;
+       char *event_name, *channel_name = nullptr;
        struct lttng_domain dom;
        struct lttng_event event;
 
@@ -180,29 +174,29 @@ static int disable_events(char *session_name)
        channel_name = opt_channel_name;
 
        handle = lttng_create_handle(session_name, &dom);
-       if (handle == NULL) {
-               ret = -1;
+       if (handle == nullptr) {
+               ret = CMD_ERROR;
                goto error;
        }
 
        /* Mi print the channel and open the events element */
        if (lttng_opt_mi) {
-               ret = mi_lttng_writer_open_element(writer, config_element_channel);
-               if (ret) {
+               int mi_ret = mi_lttng_writer_open_element(writer, config_element_channel);
+               if (mi_ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_name, print_channel_name(channel_name));
-               if (ret) {
+               mi_ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_name, print_channel_name(channel_name));
+               if (mi_ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open events element */
-               ret = mi_lttng_writer_open_element(writer, config_element_events);
-               if (ret) {
+               mi_ret = mi_lttng_writer_open_element(writer, config_element_events);
+               if (mi_ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -216,82 +210,89 @@ static int disable_events(char *session_name)
        event.type = (lttng_event_type) opt_event_type;
 
        if (opt_disable_all) {
-               command_ret = lttng_disable_event_ext(handle, &event, channel_name, NULL);
-               if (command_ret < 0) {
-                       ERR("%s", lttng_strerror(command_ret));
-                       enabled = 1;
-                       success = 0;
+               const int disable_ret =
+                       lttng_disable_event_ext(handle, &event, channel_name, nullptr);
 
+               if (disable_ret < 0) {
+                       ERR("%s", lttng_strerror(command_ret));
+                       command_ret = CMD_ERROR;
+                       enabled = true;
+                       success = false;
                } else {
-                       enabled = 0;
-                       success = 1;
+                       enabled = false;
+                       success = true;
                        MSG("All %s events of type %s are disabled in channel %s",
-                                       lttng_domain_type_str(dom.type),
-                                       print_event_type((lttng_event_type) opt_event_type),
-                                       print_channel_name(channel_name));
+                           lttng_domain_type_str(dom.type),
+                           print_event_type((lttng_event_type) opt_event_type),
+                           print_channel_name(channel_name));
                }
 
                if (lttng_opt_mi) {
-                       ret = mi_print_event("*", enabled, success);
-                       if (ret) {
+                       const int mi_ret = mi_print_event("*", enabled, success);
+
+                       if (mi_ret) {
                                ret = CMD_ERROR;
                                goto error;
                        }
                }
        } else {
                /* Strip event list */
-               event_name = strtok(opt_event_list, ",");
-               while (event_name != NULL) {
+               event_name = strtok(event_list, ",");
+               while (event_name != nullptr) {
                        DBG("Disabling event %s", event_name);
 
                        strncpy(event.name, event_name, sizeof(event.name));
                        event.name[sizeof(event.name) - 1] = '\0';
-                       command_ret = lttng_disable_event_ext(handle, &event, channel_name, NULL);
-                       if (command_ret < 0) {
+                       const int disable_ret =
+                               lttng_disable_event_ext(handle, &event, channel_name, nullptr);
+                       if (disable_ret < 0) {
                                ERR("%s of type %s : %s (channel %s, session %s)",
-                                               event_name,
-                                               print_event_type((lttng_event_type) opt_event_type),
-                                               lttng_strerror(command_ret),
-                                               command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME
-                                                       ? print_raw_channel_name(channel_name)
-                                                       : print_channel_name(channel_name),
-                                               session_name);
-                               warn = 1;
-                               success = 0;
+                                   event_name,
+                                   print_event_type((lttng_event_type) opt_event_type),
+                                   lttng_strerror(disable_ret),
+                                   disable_ret == -LTTNG_ERR_NEED_CHANNEL_NAME ?
+                                           print_raw_channel_name(channel_name) :
+                                           print_channel_name(channel_name),
+                                   session_name);
+                               warn = true;
+                               success = false;
                                /*
                                 * If an error occurred we assume that the event is still
                                 * enabled.
                                 */
-                               enabled = 1;
+                               enabled = true;
+                               command_ret = CMD_ERROR;
                        } else {
                                MSG("%s %s of type %s disabled in channel %s for session %s",
-                                               lttng_domain_type_str(dom.type),
-                                               event_name,
-                                               print_event_type((lttng_event_type) opt_event_type),
-                                               print_channel_name(channel_name),
-                                               session_name);
-                               success = 1;
-                               enabled = 0;
+                                   lttng_domain_type_str(dom.type),
+                                   event_name,
+                                   print_event_type((lttng_event_type) opt_event_type),
+                                   print_channel_name(channel_name),
+                                   session_name);
+                               success = true;
+                               enabled = false;
                        }
 
                        if (lttng_opt_mi) {
-                               ret = mi_print_event(event_name, enabled, success);
-                               if (ret) {
+                               const int mi_ret = mi_print_event(event_name, enabled, success);
+
+                               if (mi_ret) {
                                        ret = CMD_ERROR;
                                        goto error;
                                }
                        }
 
                        /* Next event */
-                       event_name = strtok(NULL, ",");
+                       event_name = strtok(nullptr, ",");
                }
        }
 
 end:
        if (lttng_opt_mi) {
                /* Close events element and channel element */
-               ret = mi_lttng_close_multi_element(writer, 2);
-               if (ret) {
+               const int mi_ret = mi_lttng_close_multi_element(writer, 2);
+
+               if (mi_ret) {
                        ret = CMD_ERROR;
                }
        }
@@ -317,11 +318,13 @@ int cmd_disable_events(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
        static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
+       char *session_name = nullptr;
+       char *event_list = nullptr;
+       const char *arg_event_list = nullptr;
+       const char *leftover = nullptr;
        int event_type = -1;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        /* Default event type */
@@ -368,29 +371,36 @@ int cmd_disable_events(int argc, const char **argv)
        }
 
        ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace + opt_jul + opt_log4j +
-                                       opt_python,
-                       true);
+               opt_kernel + opt_userspace + opt_jul + opt_log4j + opt_python, true);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
        }
 
        /* Ust and agent only support ALL event type */
-       if ((opt_userspace || opt_jul || opt_log4j || opt_python)
-                       && opt_event_type != LTTNG_EVENT_ALL) {
+       if ((opt_userspace || opt_jul || opt_log4j || opt_python) &&
+           opt_event_type != LTTNG_EVENT_ALL) {
                ERR("Disabling userspace and agent (-j | -l | -p) event(s) based on instrumentation type is not supported.\n");
                ret = CMD_ERROR;
                goto end;
        }
 
-       opt_event_list = (char*) poptGetArg(pc);
-       if (opt_event_list == NULL && opt_disable_all == 0) {
+       arg_event_list = poptGetArg(pc);
+       if (arg_event_list == nullptr && opt_disable_all == 0) {
                ERR("Missing event name(s).\n");
                ret = CMD_ERROR;
                goto end;
        }
 
+       if (opt_disable_all == 0) {
+               event_list = strdup(arg_event_list);
+               if (event_list == nullptr) {
+                       PERROR("Failed to copy event name(s)");
+                       ret = CMD_ERROR;
+                       goto end;
+               }
+       }
+
        leftover = poptGetArg(pc);
        if (leftover) {
                ERR("Unknown argument: %s", leftover);
@@ -400,7 +410,7 @@ int cmd_disable_events(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -417,23 +427,21 @@ int cmd_disable_events(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_disable_event);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_disable_event);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       command_ret = disable_events(session_name);
+       command_ret = disable_events(session_name, event_list);
        if (command_ret) {
                success = 0;
        }
@@ -447,8 +455,8 @@ int cmd_disable_events(int argc, const char **argv)
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -467,6 +475,8 @@ end:
                free(session_name);
        }
 
+       free(event_list);
+
        /* Mi clean-up */
        if (writer && mi_lttng_writer_destroy(writer)) {
                /* Preserve original error code */
index c2b6728ae758f0da0117213d5027d7b3ed7a0a01..a75af66ba347026a359aa325d3a575207161fd3c 100644 (file)
@@ -6,6 +6,15 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
+#include <lttng/lttng.h>
+
+#include <ctype.h>
+#include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <ctype.h>
-
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-#include <lttng/lttng.h>
 
 static char *opt_session_name;
 static struct mi_writer *writer;
@@ -28,7 +29,7 @@ static struct mi_writer *writer;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-disable-rotation.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -40,12 +41,12 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h',  POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0,   POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"session",     's',  POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"timer",        0,   POPT_ARG_NONE, 0, OPT_TIMER, 0, 0},
-       {"size",         0,   POPT_ARG_NONE, 0, OPT_SIZE, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "timer", 0, POPT_ARG_NONE, nullptr, OPT_TIMER, nullptr, nullptr },
+       { "size", 0, POPT_ARG_NONE, nullptr, OPT_SIZE, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static const char *schedule_type_str[] = {
@@ -53,34 +54,32 @@ static const char *schedule_type_str[] = {
        "size-based",
 };
 
-static const struct lttng_rotation_schedule *get_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedules *schedules,
-               enum lttng_rotation_schedule_type schedule_type)
+static const struct lttng_rotation_schedule *
+get_schedule(const char *session_name,
+            const struct lttng_rotation_schedules *schedules,
+            enum lttng_rotation_schedule_type schedule_type)
 {
        unsigned int count, i;
        enum lttng_rotation_status status;
-       const struct lttng_rotation_schedule *ret = NULL;
+       const struct lttng_rotation_schedule *ret = nullptr;
 
        status = lttng_rotation_schedules_get_count(schedules, &count);
        if (status != LTTNG_ROTATION_STATUS_OK) {
                ERR("Unable to determine the number of rotation schedules of session %s",
-                               session_name);
+                   session_name);
                goto end;
        }
 
        for (i = 0; i < count; i++) {
-               const struct lttng_rotation_schedule *schedule = NULL;
+               const struct lttng_rotation_schedule *schedule = nullptr;
 
                schedule = lttng_rotation_schedules_get_at_index(schedules, i);
                if (!schedule) {
-                       ERR("Unable to retrieve rotation schedule at index %u",
-                                       i);
+                       ERR("Unable to retrieve rotation schedule at index %u", i);
                        goto end;
                }
 
-               if (lttng_rotation_schedule_get_type(schedule) ==
-                               schedule_type) {
+               if (lttng_rotation_schedule_get_type(schedule) == schedule_type) {
                        ret = schedule;
                        break;
                }
@@ -88,16 +87,16 @@ static const struct lttng_rotation_schedule *get_schedule(
 
        if (!ret) {
                ERR("No %s rotation schedule active on session %s",
-                               schedule_type_str[schedule_type], session_name);
+                   schedule_type_str[schedule_type],
+                   session_name);
        }
 end:
        return ret;
 }
 
-static struct lttng_rotation_schedule *create_empty_schedule(
-               enum lttng_rotation_schedule_type type)
+static struct lttng_rotation_schedule *create_empty_schedule(enum lttng_rotation_schedule_type type)
 {
-       struct lttng_rotation_schedule *schedule = NULL;
+       struct lttng_rotation_schedule *schedule = nullptr;
 
        switch (type) {
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
@@ -113,15 +112,15 @@ static struct lttng_rotation_schedule *create_empty_schedule(
 }
 
 static enum cmd_error_code remove_schedule(const char *session_name,
-               enum lttng_rotation_schedule_type schedule_type)
+                                          enum lttng_rotation_schedule_type schedule_type)
 {
        enum cmd_error_code cmd_ret;
        int ret;
-       const struct lttng_rotation_schedule *schedule = NULL;
-       struct lttng_rotation_schedules *schedules = NULL;
+       const struct lttng_rotation_schedule *schedule = nullptr;
+       struct lttng_rotation_schedules *schedules = nullptr;
        enum lttng_rotation_status status;
        const char *schedule_type_name;
-       struct lttng_rotation_schedule *empty_schedule = NULL;
+       struct lttng_rotation_schedule *empty_schedule = nullptr;
 
        switch (schedule_type) {
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
@@ -136,8 +135,7 @@ static enum cmd_error_code remove_schedule(const char *session_name,
 
        ret = lttng_session_list_rotation_schedules(session_name, &schedules);
        if (ret != LTTNG_OK) {
-               ERR("Failed to list rotation schedules of session %s",
-                               session_name);
+               ERR("Failed to list rotation schedules of session %s", session_name);
                goto error;
        }
 
@@ -160,30 +158,27 @@ static enum cmd_error_code remove_schedule(const char *session_name,
        status = lttng_session_remove_rotation_schedule(session_name, schedule);
        switch (status) {
        case LTTNG_ROTATION_STATUS_OK:
-               MSG("Disabled %s rotation on session %s",
-                               schedule_type_name, session_name);
+               MSG("Disabled %s rotation on session %s", schedule_type_name, session_name);
                cmd_ret = CMD_SUCCESS;
                break;
        case LTTNG_ROTATION_STATUS_SCHEDULE_NOT_SET:
-               ERR("No %s rotation schedule set on session %s",
-                               schedule_type_name,
-                               session_name);
+               ERR("No %s rotation schedule set on session %s", schedule_type_name, session_name);
                cmd_ret = CMD_ERROR;
                break;
        case LTTNG_ROTATION_STATUS_ERROR:
        case LTTNG_ROTATION_STATUS_INVALID:
        default:
                ERR("Failed to disable %s rotation schedule on session %s",
-                               schedule_type_name, session_name);
+                   schedule_type_name,
+                   session_name);
                cmd_ret = CMD_ERROR;
                break;
        }
 
 skip_removal:
        if (lttng_opt_mi) {
-               ret = mi_lttng_rotation_schedule_result(writer,
-                               schedule ? schedule : empty_schedule,
-                               cmd_ret == CMD_SUCCESS);
+               ret = mi_lttng_rotation_schedule_result(
+                       writer, schedule ? schedule : empty_schedule, cmd_ret == CMD_SUCCESS);
                if (ret < 0) {
                        goto error;
                }
@@ -208,11 +203,11 @@ int cmd_disable_rotation(int argc, const char **argv)
        int popt_ret, opt, ret = 0;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        static poptContext pc;
-       char *session_name = NULL;
+       char *session_name = nullptr;
        bool free_session_name = false;
        bool periodic_rotation = false, size_rotation = false;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        popt_ret = poptReadDefaultConfig(pc, 0);
        if (popt_ret) {
                cmd_ret = CMD_ERROR;
@@ -240,9 +235,9 @@ int cmd_disable_rotation(int argc, const char **argv)
                }
        }
 
-       if (opt_session_name == NULL) {
+       if (opt_session_name == nullptr) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        goto error;
                }
                free_session_name = true;
@@ -259,14 +254,13 @@ int cmd_disable_rotation(int argc, const char **argv)
 
                /* Open command element */
                ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_disable_rotation);
+                                                  mi_lttng_element_command_disable_rotation);
                if (ret) {
                        goto error;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        goto error;
                }
@@ -280,14 +274,13 @@ int cmd_disable_rotation(int argc, const char **argv)
 
        if (lttng_opt_mi) {
                ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_rotation_schedule_results);
+                                                  mi_lttng_element_rotation_schedule_results);
                if (ret) {
                        goto error;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_session_name,
-                               session_name);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_session_name, session_name);
                if (ret) {
                        goto error;
                }
@@ -298,16 +291,15 @@ int cmd_disable_rotation(int argc, const char **argv)
                 * Continue processing even on error as multiple schedules can
                 * be specified at once.
                 */
-               cmd_ret = remove_schedule(session_name,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC);
+               cmd_ret = remove_schedule(session_name, LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC);
        }
 
        if (size_rotation) {
                enum cmd_error_code tmp_ret;
 
                /* Don't overwrite cmd_ret if it already indicates an error. */
-               tmp_ret = remove_schedule(session_name,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD);
+               tmp_ret =
+                       remove_schedule(session_name, LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD);
                cmd_ret = cmd_ret ? cmd_ret : tmp_ret;
        }
 
@@ -329,9 +321,8 @@ close_command:
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success,
-                               cmd_ret == CMD_SUCCESS);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, cmd_ret == CMD_SUCCESS);
                if (ret) {
                        goto error;
                }
index a7fffbff1b155409f1f613bd2e29bdf47cda29fd..4e5f2eb15534147b28ea05233600862652d3408e 100644 (file)
@@ -6,6 +6,18 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "../utils.hpp"
+
+#include <common/lttng-kernel.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/domain-internal.hpp>
+
+#include <ctype.h>
+#include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <ctype.h>
-
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/utils.hpp>
-#include <common/mi-lttng.hpp>
-
-#include <lttng/domain-internal.hpp>
-
-#include "../command.hpp"
-#include "../utils.hpp"
-
 
 static struct lttng_channel chan_opts;
-static char *opt_channels;
 static int opt_kernel;
 static char *opt_session_name;
 static int opt_userspace;
@@ -49,7 +48,7 @@ static struct mi_writer *writer;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-enable-channel.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -75,26 +74,26 @@ const char *output_splice = "splice";
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",        's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"kernel",         'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"userspace",      'u', POPT_ARG_NONE, 0, OPT_USERSPACE, 0, 0},
-       {"discard",        0,   POPT_ARG_NONE, 0, OPT_DISCARD, 0, 0},
-       {"overwrite",      0,   POPT_ARG_NONE, 0, OPT_OVERWRITE, 0, 0},
-       {"subbuf-size",    0,   POPT_ARG_STRING, 0, OPT_SUBBUF_SIZE, 0, 0},
-       {"num-subbuf",     0,   POPT_ARG_INT, 0, OPT_NUM_SUBBUF, 0, 0},
-       {"switch-timer",   0,   POPT_ARG_INT, 0, OPT_SWITCH_TIMER, 0, 0},
-       {"monitor-timer",  0,   POPT_ARG_INT, 0, OPT_MONITOR_TIMER, 0, 0},
-       {"read-timer",     0,   POPT_ARG_INT, 0, OPT_READ_TIMER, 0, 0},
-       {"list-options",   0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"output",         0,   POPT_ARG_STRING, &opt_output, 0, 0, 0},
-       {"buffers-uid",    0,   POPT_ARG_VAL, &opt_buffer_uid, 1, 0, 0},
-       {"buffers-pid",    0,   POPT_ARG_VAL, &opt_buffer_pid, 1, 0, 0},
-       {"buffers-global", 0,   POPT_ARG_VAL, &opt_buffer_global, 1, 0, 0},
-       {"tracefile-size", 'C',   POPT_ARG_INT, 0, OPT_TRACEFILE_SIZE, 0, 0},
-       {"tracefile-count", 'W',   POPT_ARG_INT, 0, OPT_TRACEFILE_COUNT, 0, 0},
-       {"blocking-timeout",     0,   POPT_ARG_INT, 0, OPT_BLOCKING_TIMEOUT, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_NONE, nullptr, OPT_USERSPACE, nullptr, nullptr },
+       { "discard", 0, POPT_ARG_NONE, nullptr, OPT_DISCARD, nullptr, nullptr },
+       { "overwrite", 0, POPT_ARG_NONE, nullptr, OPT_OVERWRITE, nullptr, nullptr },
+       { "subbuf-size", 0, POPT_ARG_STRING, nullptr, OPT_SUBBUF_SIZE, nullptr, nullptr },
+       { "num-subbuf", 0, POPT_ARG_INT, nullptr, OPT_NUM_SUBBUF, nullptr, nullptr },
+       { "switch-timer", 0, POPT_ARG_INT, nullptr, OPT_SWITCH_TIMER, nullptr, nullptr },
+       { "monitor-timer", 0, POPT_ARG_INT, nullptr, OPT_MONITOR_TIMER, nullptr, nullptr },
+       { "read-timer", 0, POPT_ARG_INT, nullptr, OPT_READ_TIMER, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "output", 0, POPT_ARG_STRING, &opt_output, 0, nullptr, nullptr },
+       { "buffers-uid", 0, POPT_ARG_VAL, &opt_buffer_uid, 1, nullptr, nullptr },
+       { "buffers-pid", 0, POPT_ARG_VAL, &opt_buffer_pid, 1, nullptr, nullptr },
+       { "buffers-global", 0, POPT_ARG_VAL, &opt_buffer_global, 1, nullptr, nullptr },
+       { "tracefile-size", 'C', POPT_ARG_INT, nullptr, OPT_TRACEFILE_SIZE, nullptr, nullptr },
+       { "tracefile-count", 'W', POPT_ARG_INT, nullptr, OPT_TRACEFILE_COUNT, nullptr, nullptr },
+       { "blocking-timeout", 0, POPT_ARG_INT, nullptr, OPT_BLOCKING_TIMEOUT, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -139,9 +138,9 @@ static void set_default_attr(struct lttng_domain *dom)
 /*
  * Adding channel using the lttng API.
  */
-static int enable_channel(char *session_name)
+static int enable_channel(char *session_name, char *channel_list)
 {
-       struct lttng_channel *channel = NULL;
+       struct lttng_channel *channel = nullptr;
        int ret = CMD_SUCCESS, warn = 0, error = 0, success = 0;
        char *channel_name;
        struct lttng_domain dom;
@@ -187,15 +186,16 @@ static int enable_channel(char *session_name)
 
        if (chan_opts.attr.tracefile_size == 0 && chan_opts.attr.tracefile_count) {
                ERR("Missing option --tracefile-size. "
-                               "A file count without a size won't do anything.");
+                   "A file count without a size won't do anything.");
                ret = CMD_ERROR;
                goto error;
        }
 
        if ((chan_opts.attr.tracefile_size > 0) &&
-                       (chan_opts.attr.tracefile_size < chan_opts.attr.subbuf_size)) {
+           (chan_opts.attr.tracefile_size < chan_opts.attr.subbuf_size)) {
                WARN("Tracefile size rounded up from (%" PRIu64 ") to subbuffer size (%" PRIu64 ")",
-                               chan_opts.attr.tracefile_size, chan_opts.attr.subbuf_size);
+                    chan_opts.attr.tracefile_size,
+                    chan_opts.attr.subbuf_size);
                chan_opts.attr.tracefile_size = chan_opts.attr.subbuf_size;
        }
 
@@ -207,14 +207,16 @@ static int enable_channel(char *session_name)
                        chan_opts.attr.output = LTTNG_EVENT_SPLICE;
                } else {
                        ERR("Unknown output type %s. Possible values are: %s, %s\n",
-                                       opt_output, output_mmap, output_splice);
+                           opt_output,
+                           output_mmap,
+                           output_splice);
                        ret = CMD_ERROR;
                        goto error;
                }
        }
 
        handle = lttng_create_handle(session_name, &dom);
-       if (handle == NULL) {
+       if (handle == nullptr) {
                ret = -1;
                goto error;
        }
@@ -230,14 +232,14 @@ static int enable_channel(char *session_name)
        }
 
        /* Strip channel list (format: chan1,chan2,...) */
-       channel_name = strtok(opt_channels, ",");
-       while (channel_name != NULL) {
+       channel_name = strtok(channel_list, ",");
+       while (channel_name != nullptr) {
                void *extended_ptr;
 
                /* Validate channel name's length */
                if (strlen(channel_name) >= sizeof(chan_opts.name)) {
                        ERR("Channel name is too long (max. %zu characters)",
-                                       sizeof(chan_opts.name) - 1);
+                           sizeof(chan_opts.name) - 1);
                        error = 1;
                        goto skip_enable;
                }
@@ -261,7 +263,7 @@ static int enable_channel(char *session_name)
                channel->attr.extended.ptr = extended_ptr;
                if (opt_monitor_timer.set) {
                        ret = lttng_channel_set_monitor_timer_interval(channel,
-                                       opt_monitor_timer.interval);
+                                                                      opt_monitor_timer.interval);
                        if (ret) {
                                ERR("Failed to set the channel's monitor timer interval");
                                error = 1;
@@ -270,7 +272,7 @@ static int enable_channel(char *session_name)
                }
                if (opt_blocking_timeout.set) {
                        ret = lttng_channel_set_blocking_timeout(channel,
-                                       opt_blocking_timeout.value);
+                                                                opt_blocking_timeout.value);
                        if (ret) {
                                ERR("Failed to set the channel's blocking timeout");
                                error = 1;
@@ -282,35 +284,48 @@ static int enable_channel(char *session_name)
 
                ret = lttng_enable_channel(handle, channel);
                if (ret < 0) {
+                       bool msg_already_printed = false;
+
                        success = 0;
                        switch (-ret) {
                        case LTTNG_ERR_KERN_CHAN_EXIST:
                        case LTTNG_ERR_UST_CHAN_EXIST:
                        case LTTNG_ERR_CHAN_EXIST:
-                               WARN("Channel %s: %s (session %s)", channel_name,
-                                               lttng_strerror(ret), session_name);
                                warn = 1;
                                break;
                        case LTTNG_ERR_INVALID_CHANNEL_NAME:
                                ERR("Invalid channel name: \"%s\". "
                                    "Channel names may not start with '.', and "
-                                   "may not contain '/'.", channel_name);
+                                   "may not contain '/'.",
+                                   channel_name);
+                               msg_already_printed = true;
                                error = 1;
                                break;
                        default:
-                               ERR("Channel %s: %s (session %s)", channel_name,
-                                               lttng_strerror(ret), session_name);
                                error = 1;
                                break;
                        }
+
+                       if (!msg_already_printed) {
+                               LOG(error ? PRINT_ERR : PRINT_WARN,
+                                   "Failed to enable channel `%s` under session `%s`: %s",
+                                   channel_name,
+                                   session_name,
+                                   lttng_strerror(ret));
+                       }
+
+                       if (opt_kernel) {
+                               print_kernel_tracer_status_error();
+                       }
                } else {
-                       MSG("%s channel %s enabled for session %s",
-                                       lttng_domain_type_str(dom.type),
-                                       channel_name, session_name);
+                       MSG("%s channel `%s` enabled for session `%s`",
+                           lttng_domain_type_str(dom.type),
+                           channel_name,
+                           session_name);
                        success = 1;
                }
 
-skip_enable:
+       skip_enable:
                if (lttng_opt_mi) {
                        /* Mi print the channel element and leave it open */
                        ret = mi_lttng_channel(writer, channel, 1);
@@ -320,8 +335,8 @@ skip_enable:
                        }
 
                        /* Individual Success ? */
-                       ret = mi_lttng_writer_write_element_bool(writer,
-                                       mi_lttng_element_command_success, success);
+                       ret = mi_lttng_writer_write_element_bool(
+                               writer, mi_lttng_element_command_success, success);
                        if (ret) {
                                ret = CMD_ERROR;
                                goto error;
@@ -336,9 +351,9 @@ skip_enable:
                }
 
                /* Next channel */
-               channel_name = strtok(NULL, ",");
+               channel_name = strtok(nullptr, ",");
                lttng_channel_destroy(channel);
-               channel = NULL;
+               channel = nullptr;
        }
 
        if (lttng_opt_mi) {
@@ -373,14 +388,14 @@ error:
 /*
  * Default value for channel configuration.
  */
-static void init_channel_config(void)
+static void init_channel_config()
 {
        /*
         * Put -1 everywhere so we can identify those set by the command line and
         * those needed to be set by the default values.
         */
        memset(&chan_opts.attr, -1, sizeof(chan_opts.attr));
-       chan_opts.attr.extended.ptr = NULL;
+       chan_opts.attr.extended.ptr = nullptr;
 }
 
 /*
@@ -390,13 +405,15 @@ int cmd_enable_channels(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
        static poptContext pc;
-       char *session_name = NULL;
-       char *opt_arg = NULL;
-       const char *leftover = NULL;
+       char *session_name = nullptr;
+       char *channel_list = nullptr;
+       char *opt_arg = nullptr;
+       const char *arg_channel_list = nullptr;
+       const char *leftover = nullptr;
 
        init_channel_config();
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -419,7 +436,8 @@ int cmd_enable_channels(int argc, const char **argv)
 
                        /* Parse the size */
                        opt_arg = poptGetOptArg(pc);
-                       if (utils_parse_size_suffix(opt_arg, &chan_opts.attr.subbuf_size) < 0 || !chan_opts.attr.subbuf_size) {
+                       if (utils_parse_size_suffix(opt_arg, &chan_opts.attr.subbuf_size) < 0 ||
+                           !chan_opts.attr.subbuf_size) {
                                ERR("Wrong value in --subbuf-size parameter: %s", opt_arg);
                                ret = CMD_ERROR;
                                goto end;
@@ -430,19 +448,22 @@ int cmd_enable_channels(int argc, const char **argv)
                        rounded_size = 1ULL << order;
                        if (rounded_size < chan_opts.attr.subbuf_size) {
                                ERR("The subbuf size (%" PRIu64 ") is rounded and overflows!",
-                                               chan_opts.attr.subbuf_size);
+                                   chan_opts.attr.subbuf_size);
                                ret = CMD_ERROR;
                                goto end;
                        }
 
                        if (rounded_size != chan_opts.attr.subbuf_size) {
-                               WARN("The subbuf size (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
-                                               chan_opts.attr.subbuf_size, rounded_size);
+                               WARN("The subbuf size (%" PRIu64
+                                    ") is rounded to the next power of 2 (%" PRIu64 ")",
+                                    chan_opts.attr.subbuf_size,
+                                    rounded_size);
                                chan_opts.attr.subbuf_size = rounded_size;
                        }
 
                        /* Should now be power of 2 */
-                       LTTNG_ASSERT(!((chan_opts.attr.subbuf_size - 1) & chan_opts.attr.subbuf_size));
+                       LTTNG_ASSERT(
+                               !((chan_opts.attr.subbuf_size - 1) & chan_opts.attr.subbuf_size));
 
                        DBG("Channel subbuf size set to %" PRIu64, chan_opts.attr.subbuf_size);
                        break;
@@ -454,7 +475,7 @@ int cmd_enable_channels(int argc, const char **argv)
 
                        errno = 0;
                        opt_arg = poptGetOptArg(pc);
-                       chan_opts.attr.num_subbuf = strtoull(opt_arg, NULL, 0);
+                       chan_opts.attr.num_subbuf = strtoull(opt_arg, nullptr, 0);
                        if (errno != 0 || !chan_opts.attr.num_subbuf || !isdigit(opt_arg[0])) {
                                ERR("Wrong value in --num-subbuf parameter: %s", opt_arg);
                                ret = CMD_ERROR;
@@ -465,20 +486,24 @@ int cmd_enable_channels(int argc, const char **argv)
                        LTTNG_ASSERT(order >= 0);
                        rounded_size = 1ULL << order;
                        if (rounded_size < chan_opts.attr.num_subbuf) {
-                               ERR("The number of subbuffers (%" PRIu64 ") is rounded and overflows!",
-                                               chan_opts.attr.num_subbuf);
+                               ERR("The number of subbuffers (%" PRIu64
+                                   ") is rounded and overflows!",
+                                   chan_opts.attr.num_subbuf);
                                ret = CMD_ERROR;
                                goto end;
                        }
 
                        if (rounded_size != chan_opts.attr.num_subbuf) {
-                               WARN("The number of subbuffers (%" PRIu64 ") is rounded to the next power of 2 (%" PRIu64 ")",
-                                               chan_opts.attr.num_subbuf, rounded_size);
+                               WARN("The number of subbuffers (%" PRIu64
+                                    ") is rounded to the next power of 2 (%" PRIu64 ")",
+                                    chan_opts.attr.num_subbuf,
+                                    rounded_size);
                                chan_opts.attr.num_subbuf = rounded_size;
                        }
 
                        /* Should now be power of 2 */
-                       LTTNG_ASSERT(!((chan_opts.attr.num_subbuf - 1) & chan_opts.attr.num_subbuf));
+                       LTTNG_ASSERT(
+                               !((chan_opts.attr.num_subbuf - 1) & chan_opts.attr.num_subbuf));
 
                        DBG("Channel subbuf num set to %" PRIu64, chan_opts.attr.num_subbuf);
                        break;
@@ -503,8 +528,8 @@ int cmd_enable_channels(int argc, const char **argv)
                        }
                        chan_opts.attr.switch_timer_interval = (uint32_t) v;
                        DBG("Channel switch timer interval set to %d %s",
-                                       chan_opts.attr.switch_timer_interval,
-                                       USEC_UNIT);
+                           chan_opts.attr.switch_timer_interval,
+                           USEC_UNIT);
                        break;
                }
                case OPT_READ_TIMER:
@@ -527,8 +552,8 @@ int cmd_enable_channels(int argc, const char **argv)
                        }
                        chan_opts.attr.read_timer_interval = (uint32_t) v;
                        DBG("Channel read timer interval set to %d %s",
-                                       chan_opts.attr.read_timer_interval,
-                                       USEC_UNIT);
+                           chan_opts.attr.read_timer_interval,
+                           USEC_UNIT);
                        break;
                }
                case OPT_MONITOR_TIMER:
@@ -546,8 +571,8 @@ int cmd_enable_channels(int argc, const char **argv)
                        opt_monitor_timer.interval = (uint64_t) v;
                        opt_monitor_timer.set = true;
                        DBG("Channel monitor timer interval set to %" PRIu64 " %s",
-                                       opt_monitor_timer.interval,
-                                       USEC_UNIT);
+                           opt_monitor_timer.interval,
+                           USEC_UNIT);
                        break;
                }
                case OPT_BLOCKING_TIMEOUT:
@@ -588,7 +613,8 @@ int cmd_enable_channels(int argc, const char **argv)
                         */
                        v_msec = v / 1000;
                        if (v_msec != (int32_t) v_msec) {
-                               ERR("32-bit milliseconds overflow in --blocking-timeout parameter: %s", opt_arg);
+                               ERR("32-bit milliseconds overflow in --blocking-timeout parameter: %s",
+                                   opt_arg);
                                ret = CMD_ERROR;
                                goto end;
                        }
@@ -596,10 +622,9 @@ int cmd_enable_channels(int argc, const char **argv)
                        opt_blocking_timeout.value = (int64_t) v;
                        opt_blocking_timeout.set = true;
                        DBG("Channel blocking timeout set to %" PRId64 " %s%s",
-                                       opt_blocking_timeout.value,
-                                       USEC_UNIT,
-                                       opt_blocking_timeout.value == 0 ?
-                                               " (non-blocking)" : "");
+                           opt_blocking_timeout.value,
+                           USEC_UNIT,
+                           opt_blocking_timeout.value == 0 ? " (non-blocking)" : "");
                        break;
                }
                case OPT_USERSPACE:
@@ -613,7 +638,7 @@ int cmd_enable_channels(int argc, const char **argv)
                                goto end;
                        }
                        DBG("Maximum tracefile size set to %" PRIu64,
-                                       chan_opts.attr.tracefile_size);
+                           chan_opts.attr.tracefile_size);
                        break;
                case OPT_TRACEFILE_COUNT:
                {
@@ -621,7 +646,7 @@ int cmd_enable_channels(int argc, const char **argv)
 
                        errno = 0;
                        opt_arg = poptGetOptArg(pc);
-                       v = strtoul(opt_arg, NULL, 0);
+                       v = strtoul(opt_arg, nullptr, 0);
                        if (errno != 0 || !isdigit(opt_arg[0])) {
                                ERR("Wrong value in --tracefile-count parameter: %s", opt_arg);
                                ret = CMD_ERROR;
@@ -634,7 +659,7 @@ int cmd_enable_channels(int argc, const char **argv)
                        }
                        chan_opts.attr.tracefile_count = (uint32_t) v;
                        DBG("Maximum tracefile count set to %" PRIu64,
-                                       chan_opts.attr.tracefile_count);
+                           chan_opts.attr.tracefile_count);
                        break;
                }
                case OPT_LIST_OPTIONS:
@@ -651,17 +676,16 @@ int cmd_enable_channels(int argc, const char **argv)
                }
        }
 
-       ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace, false);
+       ret = print_missing_or_multiple_domains(opt_kernel + opt_userspace, false);
        if (ret) {
                ret = CMD_ERROR;
                goto end;
        }
 
        if (chan_opts.attr.overwrite == 1 && opt_blocking_timeout.set &&
-                       opt_blocking_timeout.value != 0) {
+           opt_blocking_timeout.value != 0) {
                ERR("You cannot specify --overwrite and --blocking-timeout=N, "
-                       "where N is different than 0");
+                   "where N is different than 0");
                ret = CMD_ERROR;
                goto end;
        }
@@ -676,24 +700,31 @@ int cmd_enable_channels(int argc, const char **argv)
 
                /* Open command element */
                ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_enable_channels);
+                                                  mi_lttng_element_command_enable_channels);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       opt_channels = (char*) poptGetArg(pc);
-       if (opt_channels == NULL) {
-               ERR("Missing channel name.\n");
+       arg_channel_list = poptGetArg(pc);
+       if (arg_channel_list == nullptr) {
+               ERR("Missing channel name.");
+               ret = CMD_ERROR;
+               success = 0;
+               goto mi_closing;
+       }
+
+       channel_list = strdup(arg_channel_list);
+       if (channel_list == nullptr) {
+               PERROR("Failed to copy channel name");
                ret = CMD_ERROR;
                success = 0;
                goto mi_closing;
@@ -709,7 +740,7 @@ int cmd_enable_channels(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        command_ret = CMD_ERROR;
                        success = 0;
                        goto mi_closing;
@@ -718,7 +749,7 @@ int cmd_enable_channels(int argc, const char **argv)
                session_name = opt_session_name;
        }
 
-       command_ret = enable_channel(session_name);
+       command_ret = enable_channel(session_name, channel_list);
        if (command_ret) {
                success = 0;
        }
@@ -733,8 +764,8 @@ mi_closing:
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        goto end;
                }
@@ -757,6 +788,8 @@ end:
                free(session_name);
        }
 
+       free(channel_list);
+
        /* Overwrite ret if an error occurred when enable_channel */
        ret = command_ret ? command_ret : ret;
        poptFreeContext(pc);
index 1d81143ae562bd6589ad09b8c1e07b0dc59b6575..b081adeeed7f3f68d7d97f57722002091c40bef0 100644 (file)
@@ -6,57 +6,77 @@
  */
 
 #define _LGPL_SOURCE
+#include <common/compat/getenv.hpp>
+#include <common/compat/string.hpp>
+#include <common/make-unique-wrapper.hpp>
+#include <common/scope-exit.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/string-utils/string-utils.hpp>
+#include <common/utils.hpp>
+
+#include <ctype.h>
+#include <inttypes.h>
 #include <popt.h>
+#include <sstream>
 #include <stdio.h>
 #include <stdlib.h>
+#include <string>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <ctype.h>
-
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/compat/string.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/string-utils/string-utils.hpp>
-#include <common/utils.hpp>
+#include <vector>
 
 /* Mi dependancy */
+#include "../command.hpp"
+#include "../loglevel.hpp"
+#include "../uprobe.hpp"
+
 #include <common/mi-lttng.hpp>
 
 #include <lttng/domain-internal.hpp>
 #include <lttng/event-internal.hpp>
 
-#include "../command.hpp"
-#include "../loglevel.hpp"
-#include "../uprobe.hpp"
-
 #if (LTTNG_SYMBOL_NAME_LEN == 256)
-#define LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API    "255"
+#define LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "255"
 #endif
 
-static char *opt_event_list;
-static int opt_event_type;
-static const char *opt_loglevel;
-static int opt_loglevel_type;
-static int opt_kernel;
-static char *opt_session_name;
-static int opt_userspace;
-static int opt_jul;
-static int opt_log4j;
-static int opt_python;
-static int opt_enable_all;
-static char *opt_probe;
-static char *opt_userspace_probe;
-static char *opt_function;
-static char *opt_channel_name;
-static char *opt_filter;
-static char *opt_exclude;
+namespace {
+void _mi_lttng_writer_deleter_func(mi_writer *writer)
+{
+       if (writer && mi_lttng_writer_destroy(writer)) {
+               LTTNG_THROW_ERROR("Failed to destroy mi_writer instance");
+       }
+}
+
+using mi_writer_uptr = std::unique_ptr<
+       mi_writer,
+       lttng::memory::create_deleter_class<mi_writer, _mi_lttng_writer_deleter_func>::deleter>;
+using event_rule_patterns = std::vector<std::string>;
+
+int opt_event_type;
+const char *opt_loglevel;
+int opt_loglevel_type;
+int opt_kernel;
+char *opt_session_name;
+int opt_userspace;
+int opt_jul;
+int opt_log4j;
+int opt_python;
+int opt_enable_all;
+char *opt_probe;
+char *opt_userspace_probe;
+char *opt_function;
+char *opt_channel_name;
+char *opt_filter;
+char *opt_exclude;
+
+struct lttng_handle *handle;
+mi_writer_uptr writer;
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-enable-event.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -74,52 +94,58 @@ enum {
        OPT_EXCLUDE,
 };
 
-static struct lttng_handle *handle;
-static struct mi_writer *writer;
-
-static struct poptOption long_options[] = {
+struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",        's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"all",            'a', POPT_ARG_VAL, &opt_enable_all, 1, 0, 0},
-       {"channel",        'c', POPT_ARG_STRING, &opt_channel_name, 0, 0, 0},
-       {"kernel",         'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"userspace",      'u', POPT_ARG_NONE, 0, OPT_USERSPACE, 0, 0},
-       {"jul",            'j', POPT_ARG_VAL, &opt_jul, 1, 0, 0},
-       {"log4j",          'l', POPT_ARG_VAL, &opt_log4j, 1, 0, 0},
-       {"python",         'p', POPT_ARG_VAL, &opt_python, 1, 0, 0},
-       {"tracepoint",     0,   POPT_ARG_NONE, 0, OPT_TRACEPOINT, 0, 0},
-       {"probe",          0,   POPT_ARG_STRING, &opt_probe, OPT_PROBE, 0, 0},
-       {"userspace-probe",0,   POPT_ARG_STRING, &opt_userspace_probe, OPT_USERSPACE_PROBE, 0, 0},
-       {"function",       0,   POPT_ARG_STRING, &opt_function, OPT_FUNCTION, 0, 0},
-       {"syscall",        0,   POPT_ARG_NONE, 0, OPT_SYSCALL, 0, 0},
-       {"loglevel",       0,     POPT_ARG_STRING, 0, OPT_LOGLEVEL, 0, 0},
-       {"loglevel-only",  0,     POPT_ARG_STRING, 0, OPT_LOGLEVEL_ONLY, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"filter",         'f', POPT_ARG_STRING, &opt_filter, OPT_FILTER, 0, 0},
-       {"exclude",        'x', POPT_ARG_STRING, &opt_exclude, OPT_EXCLUDE, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_VAL, &opt_enable_all, 1, nullptr, nullptr },
+       { "channel", 'c', POPT_ARG_STRING, &opt_channel_name, 0, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_NONE, nullptr, OPT_USERSPACE, nullptr, nullptr },
+       { "jul", 'j', POPT_ARG_VAL, &opt_jul, 1, nullptr, nullptr },
+       { "log4j", 'l', POPT_ARG_VAL, &opt_log4j, 1, nullptr, nullptr },
+       { "python", 'p', POPT_ARG_VAL, &opt_python, 1, nullptr, nullptr },
+       { "tracepoint", 0, POPT_ARG_NONE, nullptr, OPT_TRACEPOINT, nullptr, nullptr },
+       { "probe", 0, POPT_ARG_STRING, &opt_probe, OPT_PROBE, nullptr, nullptr },
+       { "userspace-probe",
+         0,
+         POPT_ARG_STRING,
+         &opt_userspace_probe,
+         OPT_USERSPACE_PROBE,
+         nullptr,
+         nullptr },
+       { "function", 0, POPT_ARG_STRING, &opt_function, OPT_FUNCTION, nullptr, nullptr },
+       { "syscall", 0, POPT_ARG_NONE, nullptr, OPT_SYSCALL, nullptr, nullptr },
+       { "loglevel", 0, POPT_ARG_STRING, nullptr, OPT_LOGLEVEL, nullptr, nullptr },
+       { "loglevel-only", 0, POPT_ARG_STRING, nullptr, OPT_LOGLEVEL_ONLY, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "filter", 'f', POPT_ARG_STRING, &opt_filter, OPT_FILTER, nullptr, nullptr },
+       { "exclude", 'x', POPT_ARG_STRING, &opt_exclude, OPT_EXCLUDE, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
  * Parse probe options.
  */
-static int parse_probe_opts(struct lttng_event *ev, char *opt)
+int parse_probe_opts(struct lttng_event *ev, char *opt)
 {
        int ret = CMD_SUCCESS;
        int match;
        char s_hex[19];
-#define S_HEX_LEN_SCANF_IS_A_BROKEN_API "18"   /* 18 is (19 - 1) (\0 is extra) */
+#define S_HEX_LEN_SCANF_IS_A_BROKEN_API "18" /* 18 is (19 - 1) (\0 is extra) */
        char name[LTTNG_SYMBOL_NAME_LEN];
 
-       if (opt == NULL) {
+       if (opt == nullptr) {
                ret = CMD_ERROR;
                goto end;
        }
 
        /* Check for symbol+offset */
-       match = sscanf(opt, "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API
-                       "[^'+']+%" S_HEX_LEN_SCANF_IS_A_BROKEN_API "s", name, s_hex);
+       match = sscanf(opt,
+                      "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API
+                      "[^'+']+%" S_HEX_LEN_SCANF_IS_A_BROKEN_API "s",
+                      name,
+                      s_hex);
        if (match == 2) {
                strncpy(ev->attr.probe.symbol_name, name, LTTNG_SYMBOL_NAME_LEN);
                ev->attr.probe.symbol_name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
@@ -129,7 +155,7 @@ static int parse_probe_opts(struct lttng_event *ev, char *opt)
                        ret = CMD_ERROR;
                        goto end;
                }
-               ev->attr.probe.offset = strtoull(s_hex, NULL, 0);
+               ev->attr.probe.offset = strtoull(s_hex, nullptr, 0);
                DBG("probe offset %" PRIu64, ev->attr.probe.offset);
                ev->attr.probe.addr = 0;
                goto end;
@@ -137,8 +163,7 @@ static int parse_probe_opts(struct lttng_event *ev, char *opt)
 
        /* Check for symbol */
        if (isalpha(name[0]) || name[0] == '_') {
-               match = sscanf(opt, "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "s",
-                       name);
+               match = sscanf(opt, "%" LTTNG_SYMBOL_NAME_LEN_SCANF_IS_A_BROKEN_API "s", name);
                if (match == 1) {
                        strncpy(ev->attr.probe.symbol_name, name, LTTNG_SYMBOL_NAME_LEN);
                        ev->attr.probe.symbol_name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
@@ -159,11 +184,11 @@ static int parse_probe_opts(struct lttng_event *ev, char *opt)
                 * is in hexadecimal and can be 1 to 9 if it's in decimal.
                 */
                if (*s_hex == '\0' || !isdigit(*s_hex)) {
-                       ERR("Invalid probe description %s", s_hex);
+                       ERR("Invalid probe description `%s`", s_hex);
                        ret = CMD_ERROR;
                        goto end;
                }
-               ev->attr.probe.addr = strtoull(s_hex, NULL, 0);
+               ev->attr.probe.addr = strtoull(s_hex, nullptr, 0);
                DBG("probe addr %" PRIu64, ev->attr.probe.addr);
                ev->attr.probe.offset = 0;
                memset(ev->attr.probe.symbol_name, 0, LTTNG_SYMBOL_NAME_LEN);
@@ -177,22 +202,19 @@ end:
        return ret;
 }
 
-static
 const char *print_channel_name(const char *name)
 {
-       return name ? : DEFAULT_CHANNEL_NAME;
+       return name ?: DEFAULT_CHANNEL_NAME;
 }
 
-static
 const char *print_raw_channel_name(const char *name)
 {
-       return name ? : "<default>";
+       return name ?: "<default>";
 }
 
 /*
  * Mi print exlcusion list
  */
-static
 int mi_print_exclusion(const struct lttng_dynamic_pointer_array *exclusions)
 {
        int ret;
@@ -206,24 +228,24 @@ int mi_print_exclusion(const struct lttng_dynamic_pointer_array *exclusions)
                goto end;
        }
 
-       ret = mi_lttng_writer_open_element(writer, config_element_exclusions);
+       ret = mi_lttng_writer_open_element(writer.get(), config_element_exclusions);
        if (ret) {
                goto end;
        }
 
        for (i = 0; i < count; i++) {
-               const char *exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               exclusions, i);
+               const char *exclusion =
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions, i);
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_exclusion, exclusion);
+               ret = mi_lttng_writer_write_element_string(
+                       writer.get(), config_element_exclusion, exclusion);
                if (ret) {
                        goto end;
                }
        }
 
        /* Close exclusions element */
-       ret = mi_lttng_writer_close_element(writer);
+       ret = mi_lttng_writer_close_element(writer.get());
 
 end:
        return ret;
@@ -232,7 +254,6 @@ end:
 /*
  * Return allocated string for pretty-printing exclusion names.
  */
-static
 char *print_exclusions(const struct lttng_dynamic_pointer_array *exclusions)
 {
        int length = 0;
@@ -247,8 +268,8 @@ char *print_exclusions(const struct lttng_dynamic_pointer_array *exclusions)
 
        /* Calculate total required length. */
        for (i = 0; i < count; i++) {
-               const char *exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               exclusions, i);
+               const char *exclusion =
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions, i);
 
                length += strlen(exclusion) + 4;
        }
@@ -256,17 +277,17 @@ char *print_exclusions(const struct lttng_dynamic_pointer_array *exclusions)
        length += sizeof(preamble);
        ret = calloc<char>(length);
        if (!ret) {
-               return NULL;
+               return nullptr;
        }
 
        strncpy(ret, preamble, length);
        for (i = 0; i < count; i++) {
-               const char *exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               exclusions, i);
+               const char *exclusion =
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions, i);
 
-               strcat(ret, "\"");
+               strcat(ret, "`");
                strcat(ret, exclusion);
-               strcat(ret, "\"");
+               strcat(ret, "`");
                if (i != count - 1) {
                        strcat(ret, ", ");
                }
@@ -275,12 +296,11 @@ char *print_exclusions(const struct lttng_dynamic_pointer_array *exclusions)
        return ret;
 }
 
-static
-int check_exclusion_subsets(const char *event_name, const char *exclusion)
+int check_exclusion_subsets(const char *pattern, const char *exclusion)
 {
        bool warn = false;
        int ret = 0;
-       const char *e = event_name;
+       const char *e = pattern;
        const char *x = exclusion;
 
        /* Scan both the excluder and the event letter by letter */
@@ -298,8 +318,9 @@ int check_exclusion_subsets(const char *event_name, const char *exclusion)
 
                if (*x == '*') {
                        /* Event is a subset of the excluder */
-                       ERR("Event %s: %s excludes all events from %s",
-                               event_name, exclusion, event_name);
+                       ERR("Exclusion pattern `%s` excludes all events from `%s`",
+                           exclusion,
+                           pattern);
                        goto error;
                }
 
@@ -311,7 +332,7 @@ int check_exclusion_subsets(const char *event_name, const char *exclusion)
                        goto end;
                }
 
-cmp_chars:
+       cmp_chars:
                if (*x != *e) {
                        warn = true;
                        break;
@@ -328,63 +349,17 @@ error:
 
 end:
        if (warn) {
-               WARN("Event %s: %s does not exclude any events from %s",
-                       event_name, exclusion, event_name);
+               WARN("Exclusion pattern `%s` does not exclude any event from `%s`",
+                    exclusion,
+                    pattern);
        }
 
        return ret;
 }
 
-int validate_exclusion_list(const char *event_name,
-               const struct lttng_dynamic_pointer_array *exclusions)
-{
-       int ret;
-
-       /* Event name must be a valid globbing pattern to allow exclusions. */
-       if (!strutils_is_star_glob_pattern(event_name)) {
-               ERR("Event %s: Exclusions can only be used with a globbing pattern",
-                       event_name);
-               goto error;
-       }
-
-       /*
-        * If the event name is a star-at-end only globbing pattern,
-        * then we can validate the individual exclusions. Otherwise
-        * all exclusions are passed to the session daemon.
-        */
-       if (strutils_is_star_at_the_end_only_glob_pattern(event_name)) {
-               size_t i, num_exclusions;
-
-               num_exclusions = lttng_dynamic_pointer_array_get_count(exclusions);
-
-               for (i = 0; i < num_exclusions; i++) {
-                       const char *exclusion =
-                                       (const char *) lttng_dynamic_pointer_array_get_pointer(
-                                                       exclusions, i);
-
-                       if (!strutils_is_star_glob_pattern(exclusion) ||
-                                       strutils_is_star_at_the_end_only_glob_pattern(exclusion)) {
-                               ret = check_exclusion_subsets(event_name, exclusion);
-                               if (ret) {
-                                       goto error;
-                               }
-                       }
-               }
-       }
-
-       ret = 0;
-       goto end;
-
-error:
-       ret = -1;
-
-end:
-       return ret;
-}
-
-static int create_exclusion_list_and_validate(const char *event_name,
-               const char *exclusions_arg,
-               struct lttng_dynamic_pointer_array *exclusions)
+int create_exclusion_list_and_validate(const char *pattern,
+                                      const char *exclusions_arg,
+                                      struct lttng_dynamic_pointer_array *exclusions)
 {
        int ret = 0;
 
@@ -394,8 +369,7 @@ static int create_exclusion_list_and_validate(const char *event_name,
                goto error;
        }
 
-       if (validate_exclusion_list(event_name, exclusions) !=
-                       0) {
+       if (validate_exclusion_list(pattern, exclusions) != 0) {
                goto error;
        }
 
@@ -409,18 +383,18 @@ end:
        return ret;
 }
 
-static void warn_on_truncated_exclusion_names(const struct lttng_dynamic_pointer_array *exclusions,
-       int *warn)
+void warn_on_truncated_exclusion_names(const struct lttng_dynamic_pointer_array *exclusions,
+                                      int *warn)
 {
        size_t i;
        const size_t num_exclusions = lttng_dynamic_pointer_array_get_count(exclusions);
 
        for (i = 0; i < num_exclusions; i++) {
-               const char * const exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions, i);
+               const char *const exclusion =
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions, i);
 
                if (strlen(exclusion) >= LTTNG_SYMBOL_NAME_LEN) {
-                       WARN("Event exclusion \"%s\" will be truncated",
-                                       exclusion);
+                       WARN("Event exclusion \"%s\" will be truncated", exclusion);
                        *warn = 1;
                }
        }
@@ -430,17 +404,17 @@ static void warn_on_truncated_exclusion_names(const struct lttng_dynamic_pointer
  * Enabling event using the lttng API.
  * Note: in case of error only the last error code will be return.
  */
-static int enable_events(char *session_name)
+int enable_events(const std::string& session_name, const event_rule_patterns& patterns)
 {
        int ret = CMD_SUCCESS, command_ret = CMD_SUCCESS;
        int error_holder = CMD_SUCCESS, warn = 0, error = 0, success = 1;
-       char *event_name, *channel_name = NULL;
+       char *channel_name = nullptr;
        struct lttng_event *ev;
        struct lttng_domain dom = {};
        struct lttng_dynamic_pointer_array exclusions;
-       struct lttng_userspace_probe_location *uprobe_loc = NULL;
+       struct lttng_userspace_probe_location *uprobe_loc = nullptr;
 
-       lttng_dynamic_pointer_array_init(&exclusions, NULL);
+       lttng_dynamic_pointer_array_init(&exclusions, nullptr);
 
        ev = lttng_event_create();
        if (!ev) {
@@ -450,7 +424,7 @@ static int enable_events(char *session_name)
 
        if (opt_kernel) {
                if (opt_loglevel) {
-                       WARN("Kernel loglevels are not supported.");
+                       WARN("Kernel log levels are not supported");
                }
        }
 
@@ -485,8 +459,8 @@ static int enable_events(char *session_name)
                case LTTNG_DOMAIN_JUL:
                case LTTNG_DOMAIN_LOG4J:
                case LTTNG_DOMAIN_PYTHON:
-                       ERR("Event name exclusions are not yet implemented for %s events",
-                                       lttng_domain_type_str(dom.type));
+                       ERR("Event name exclusions are not supported for %s event rules",
+                           lttng_domain_type_str(dom.type));
                        ret = CMD_ERROR;
                        goto error;
                case LTTNG_DOMAIN_UST:
@@ -511,8 +485,8 @@ static int enable_events(char *session_name)
                case LTTNG_EVENT_PROBE:
                case LTTNG_EVENT_USERSPACE_PROBE:
                case LTTNG_EVENT_FUNCTION:
-                       ERR("Filter expressions are not supported for %s events",
-                                       get_event_type_str((lttng_event_type) opt_event_type));
+                       ERR("Filter expressions are not supported for %s event rules",
+                           get_event_type_str((lttng_event_type) opt_event_type));
                        ret = CMD_ERROR;
                        goto error;
                default:
@@ -523,8 +497,8 @@ static int enable_events(char *session_name)
 
        channel_name = opt_channel_name;
 
-       handle = lttng_create_handle(session_name, &dom);
-       if (handle == NULL) {
+       handle = lttng_create_handle(session_name.c_str(), &dom);
+       if (handle == nullptr) {
                ret = -1;
                goto error;
        }
@@ -532,303 +506,29 @@ static int enable_events(char *session_name)
        /* Prepare Mi */
        if (lttng_opt_mi) {
                /* Open a events element */
-               ret = mi_lttng_writer_open_element(writer, config_element_events);
+               ret = mi_lttng_writer_open_element(writer.get(), config_element_events);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
                }
        }
 
-       if (opt_enable_all) {
-               /* Default setup for enable all */
-               if (opt_kernel) {
-                       ev->type = (lttng_event_type) opt_event_type;
-                       strcpy(ev->name, "*");
-                       /* kernel loglevels not implemented */
-                       ev->loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               } else {
-                       ev->type = LTTNG_EVENT_TRACEPOINT;
-                       strcpy(ev->name, "*");
-                       ev->loglevel_type = (lttng_loglevel_type) opt_loglevel_type;
-                       if (opt_loglevel) {
-                               int name_search_ret;
-
-                               LTTNG_ASSERT(opt_userspace || opt_jul || opt_log4j || opt_python);
-
-                               if (opt_userspace) {
-                                       enum lttng_loglevel loglevel;
-
-                                       name_search_ret = loglevel_name_to_value(opt_loglevel, &loglevel);
-                                       ev->loglevel = (int) loglevel;
-                               } else if (opt_jul) {
-                                       enum lttng_loglevel_jul loglevel;
-
-                                       name_search_ret = loglevel_jul_name_to_value(opt_loglevel, &loglevel);
-                                       ev->loglevel = (int) loglevel;
-                               } else if (opt_log4j) {
-                                       enum lttng_loglevel_log4j loglevel;
-
-                                       name_search_ret = loglevel_log4j_name_to_value(opt_loglevel, &loglevel);
-                                       ev->loglevel = (int) loglevel;
-                               } else {
-                                       /* python domain. */
-                                       enum lttng_loglevel_python loglevel;
-
-                                       name_search_ret = loglevel_python_name_to_value(opt_loglevel, &loglevel);
-                                       ev->loglevel = (int) loglevel;
-                               }
-
-                               if (name_search_ret == -1) {
-                                       ERR("Unknown loglevel %s", opt_loglevel);
-                                       ret = -LTTNG_ERR_INVALID;
-                                       goto error;
-                               }
-                       } else {
-                               LTTNG_ASSERT(opt_userspace || opt_jul || opt_log4j || opt_python);
-                               if (opt_userspace) {
-                                       ev->loglevel = -1;
-                               } else if (opt_jul) {
-                                       ev->loglevel = LTTNG_LOGLEVEL_JUL_ALL;
-                               } else if (opt_log4j) {
-                                       ev->loglevel = LTTNG_LOGLEVEL_LOG4J_ALL;
-                               } else if (opt_python) {
-                                       ev->loglevel = LTTNG_LOGLEVEL_PYTHON_DEBUG;
-                               }
-                       }
-               }
-
-               if (opt_exclude) {
-                       ret = create_exclusion_list_and_validate("*",
-                               opt_exclude, &exclusions);
-                       if (ret) {
-                               ret = CMD_ERROR;
-                               goto error;
-                       }
-
-                       ev->exclusion = 1;
-                       warn_on_truncated_exclusion_names(&exclusions,
-                               &warn);
-               }
-               if (!opt_filter) {
-                       ret = lttng_enable_event_with_exclusions(handle,
-                                       ev, channel_name,
-                                       NULL,
-                                       lttng_dynamic_pointer_array_get_count(&exclusions),
-                                       (char **) exclusions.array.buffer.data);
-                       if (ret < 0) {
-                               switch (-ret) {
-                               case LTTNG_ERR_KERN_EVENT_EXIST:
-                                       WARN("Kernel events already enabled (channel %s, session %s)",
-                                                       print_channel_name(channel_name), session_name);
-                                       warn = 1;
-                                       break;
-                               case LTTNG_ERR_TRACE_ALREADY_STARTED:
-                               {
-                                       const char *msg = "The command tried to enable an event in a new domain for a session that has already been started once.";
-                                       ERR("Events: %s (channel %s, session %s)",
-                                                       msg,
-                                                       print_channel_name(channel_name),
-                                                       session_name);
-                                       error = 1;
-                                       break;
-                               }
-                               default:
-                                       ERR("Events: %s (channel %s, session %s)",
-                                                       lttng_strerror(ret),
-                                                       ret == -LTTNG_ERR_NEED_CHANNEL_NAME
-                                                               ? print_raw_channel_name(channel_name)
-                                                               : print_channel_name(channel_name),
-                                                       session_name);
-                                       error = 1;
-                                       break;
-                               }
-                               goto end;
-                       }
-
-                       switch (opt_event_type) {
-                       case LTTNG_EVENT_TRACEPOINT:
-                               if (opt_loglevel && dom.type != LTTNG_DOMAIN_KERNEL) {
-                                       char *exclusion_string = print_exclusions(&exclusions);
-
-                                       if (!exclusion_string) {
-                                               PERROR("Cannot allocate exclusion_string");
-                                               error = 1;
-                                               goto end;
-                                       }
-                                       MSG("All %s tracepoints%s are enabled in channel %s for loglevel %s",
-                                                       lttng_domain_type_str(dom.type),
-                                                       exclusion_string,
-                                                       print_channel_name(channel_name),
-                                                       opt_loglevel);
-                                       free(exclusion_string);
-                               } else {
-                                       char *exclusion_string = print_exclusions(&exclusions);
-
-                                       if (!exclusion_string) {
-                                               PERROR("Cannot allocate exclusion_string");
-                                               error = 1;
-                                               goto end;
-                                       }
-                                       MSG("All %s tracepoints%s are enabled in channel %s",
-                                                       lttng_domain_type_str(dom.type),
-                                                       exclusion_string,
-                                                       print_channel_name(channel_name));
-                                       free(exclusion_string);
-                               }
-                               break;
-                       case LTTNG_EVENT_SYSCALL:
-                               if (opt_kernel) {
-                                       MSG("All %s system calls are enabled in channel %s",
-                                                       lttng_domain_type_str(dom.type),
-                                                       print_channel_name(channel_name));
-                               }
-                               break;
-                       case LTTNG_EVENT_ALL:
-                               if (opt_loglevel && dom.type != LTTNG_DOMAIN_KERNEL) {
-                                       char *exclusion_string = print_exclusions(&exclusions);
-
-                                       if (!exclusion_string) {
-                                               PERROR("Cannot allocate exclusion_string");
-                                               error = 1;
-                                               goto end;
-                                       }
-                                       MSG("All %s events%s are enabled in channel %s for loglevel %s",
-                                                       lttng_domain_type_str(dom.type),
-                                                       exclusion_string,
-                                                       print_channel_name(channel_name),
-                                                       opt_loglevel);
-                                       free(exclusion_string);
-                               } else {
-                                       char *exclusion_string = print_exclusions(&exclusions);
-
-                                       if (!exclusion_string) {
-                                               PERROR("Cannot allocate exclusion_string");
-                                               error = 1;
-                                               goto end;
-                                       }
-                                       MSG("All %s events%s are enabled in channel %s",
-                                                       lttng_domain_type_str(dom.type),
-                                                       exclusion_string,
-                                                       print_channel_name(channel_name));
-                                       free(exclusion_string);
-                               }
-                               break;
-                       default:
-                               /*
-                                * We should not be here since lttng_enable_event should have
-                                * failed on the event type.
-                                */
-                               goto error;
-                       }
-               }
-
-               if (opt_filter) {
-                       command_ret = lttng_enable_event_with_exclusions(handle, ev, channel_name,
-                                       opt_filter,
-                                       lttng_dynamic_pointer_array_get_count(&exclusions),
-                                       (char **) exclusions.array.buffer.data);
-                       if (command_ret < 0) {
-                               switch (-command_ret) {
-                               case LTTNG_ERR_FILTER_EXIST:
-                                       WARN("Filter on all events is already enabled"
-                                                       " (channel %s, session %s)",
-                                               print_channel_name(channel_name), session_name);
-                                       warn = 1;
-                                       break;
-                               case LTTNG_ERR_TRACE_ALREADY_STARTED:
-                               {
-                                       const char *msg = "The command tried to enable an event in a new domain for a session that has already been started once.";
-                                       ERR("All events: %s (channel %s, session %s, filter \'%s\')",
-                                                       msg,
-                                                       print_channel_name(channel_name),
-                                                       session_name, opt_filter);
-                                       error = 1;
-                                       break;
-                               }
-                               default:
-                                       ERR("All events: %s (channel %s, session %s, filter \'%s\')",
-                                                       lttng_strerror(command_ret),
-                                                       command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME
-                                                               ? print_raw_channel_name(channel_name)
-                                                               : print_channel_name(channel_name),
-                                                       session_name, opt_filter);
-                                       error = 1;
-                                       break;
-                               }
-                               error_holder = command_ret;
-                       } else {
-                               ev->filter = 1;
-                               MSG("Filter '%s' successfully set", opt_filter);
-                       }
-               }
-
-               if (lttng_opt_mi) {
-                       /* The wildcard * is used for kernel and ust domain to
-                        * represent ALL. We copy * in event name to force the wildcard use
-                        * for kernel domain
-                        *
-                        * Note: this is strictly for semantic and printing while in
-                        * machine interface mode.
-                        */
-                       strcpy(ev->name, "*");
-
-                       /* If we reach here the events are enabled */
-                       if (!error && !warn) {
-                               ev->enabled = 1;
-                       } else {
-                               ev->enabled = 0;
-                               success = 0;
-                       }
-                       ret = mi_lttng_event(writer, ev, 1, handle->domain.type);
-                       if (ret) {
-                               ret = CMD_ERROR;
-                               goto error;
-                       }
-
-                       /* print exclusion */
-                       ret = mi_print_exclusion(&exclusions);
-                       if (ret) {
-                               ret = CMD_ERROR;
-                               goto error;
-                       }
-
-                       /* Success ? */
-                       ret = mi_lttng_writer_write_element_bool(writer,
-                                       mi_lttng_element_command_success, success);
-                       if (ret) {
-                               ret = CMD_ERROR;
-                               goto error;
-                       }
-
-                       /* Close event element */
-                       ret = mi_lttng_writer_close_element(writer);
-                       if (ret) {
-                               ret = CMD_ERROR;
-                               goto error;
-                       }
-               }
-
-               goto end;
-       }
-
-       /* Strip event list */
-       event_name = strtok(opt_event_list, ",");
-       while (event_name != NULL) {
+       for (const auto& pattern : patterns) {
                /* Copy name and type of the event */
-               strncpy(ev->name, event_name, LTTNG_SYMBOL_NAME_LEN);
+               strncpy(ev->name, pattern.c_str(), LTTNG_SYMBOL_NAME_LEN);
                ev->name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
                ev->type = (lttng_event_type) opt_event_type;
 
                /* Kernel tracer action */
                if (opt_kernel) {
-                       DBG("Enabling kernel event %s for channel %s",
-                                       event_name,
-                                       print_channel_name(channel_name));
+                       DBG_FMT("Enabling kernel event rule: pattern=`{}`, channel_name=`{}`",
+                               pattern,
+                               print_channel_name(channel_name));
 
                        switch (opt_event_type) {
-                       case LTTNG_EVENT_ALL:   /* Enable tracepoints and syscalls */
+                       case LTTNG_EVENT_ALL: /* Enable tracepoints and syscalls */
                                /* If event name differs from *, select tracepoint. */
-                               if (strcmp(ev->name, "*")) {
+                               if (strcmp(ev->name, "*") != 0) {
                                        ev->type = LTTNG_EVENT_TRACEPOINT;
                                }
                                break;
@@ -857,7 +557,7 @@ static int enable_events(char *session_name)
                                                break;
                                        case CMD_ERROR:
                                        default:
-                                               ERR("Unable to parse userspace probe options");
+                                               ERR("Unable to parse user space probe options");
                                                break;
                                        }
                                        goto error;
@@ -871,7 +571,7 @@ static int enable_events(char *session_name)
                                }
 
                                /* Ownership of the uprobe location was transferred to the event. */
-                               uprobe_loc = NULL;
+                               uprobe_loc = nullptr;
                                break;
                        case LTTNG_EVENT_FUNCTION:
                                ret = parse_probe_opts(ev, opt_function);
@@ -891,17 +591,19 @@ static int enable_events(char *session_name)
 
                        /* kernel loglevels not implemented */
                        ev->loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               } else if (opt_userspace) {             /* User-space tracer action */
-                       DBG("Enabling UST event %s for channel %s, loglevel %s", event_name,
-                                       print_channel_name(channel_name), opt_loglevel ? : "<all>");
+               } else if (opt_userspace) { /* User-space tracer action */
+                       DBG_FMT("Enabling user space event rule: pattern=`{}`, channel_name=`{}`, log_level=`{}`",
+                               pattern.c_str(),
+                               print_channel_name(channel_name),
+                               opt_loglevel ?: "all");
 
                        switch (opt_event_type) {
-                       case LTTNG_EVENT_ALL:   /* Default behavior is tracepoint */
+                       case LTTNG_EVENT_ALL: /* Default behavior is tracepoint */
                                /* Fall-through */
                        case LTTNG_EVENT_TRACEPOINT:
                                /* Copy name and type of the event */
                                ev->type = LTTNG_EVENT_TRACEPOINT;
-                               strncpy(ev->name, event_name, LTTNG_SYMBOL_NAME_LEN);
+                               strncpy(ev->name, pattern.c_str(), LTTNG_SYMBOL_NAME_LEN);
                                ev->name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
                                break;
                        case LTTNG_EVENT_PROBE:
@@ -909,14 +611,16 @@ static int enable_events(char *session_name)
                        case LTTNG_EVENT_SYSCALL:
                        case LTTNG_EVENT_USERSPACE_PROBE:
                        default:
-                               ERR("Event type not available for user-space tracing");
+                               ERR("Instrumentation point type not supported for the %s domain",
+                                   lttng_domain_type_str(dom.type));
                                ret = CMD_UNSUPPORTED;
                                goto error;
                        }
 
                        if (opt_exclude) {
                                ev->exclusion = 1;
-                               if (opt_event_type != LTTNG_EVENT_ALL && opt_event_type != LTTNG_EVENT_TRACEPOINT) {
+                               if (opt_event_type != LTTNG_EVENT_ALL &&
+                                   opt_event_type != LTTNG_EVENT_TRACEPOINT) {
                                        ERR("Exclusion option can only be used with tracepoint events");
                                        ret = CMD_ERROR;
                                        goto error;
@@ -924,24 +628,23 @@ static int enable_events(char *session_name)
                                /* Free previously allocated items. */
                                lttng_dynamic_pointer_array_reset(&exclusions);
                                ret = create_exclusion_list_and_validate(
-                                       event_name, opt_exclude,
-                                       &exclusions);
+                                       pattern.c_str(), opt_exclude, &exclusions);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto error;
                                }
 
-                               warn_on_truncated_exclusion_names(
-                                       &exclusions, &warn);
+                               warn_on_truncated_exclusion_names(&exclusions, &warn);
                        }
 
                        ev->loglevel_type = (lttng_loglevel_type) opt_loglevel_type;
                        if (opt_loglevel) {
                                enum lttng_loglevel loglevel;
-                               const int name_search_ret = loglevel_name_to_value(opt_loglevel, &loglevel);
+                               const int name_search_ret =
+                                       loglevel_name_to_value(opt_loglevel, &loglevel);
 
                                if (name_search_ret == -1) {
-                                       ERR("Unknown loglevel %s", opt_loglevel);
+                                       ERR("Unknown log level `%s`", opt_loglevel);
                                        ret = -LTTNG_ERR_INVALID;
                                        goto error;
                                }
@@ -952,8 +655,9 @@ static int enable_events(char *session_name)
                        }
                } else if (opt_jul || opt_log4j || opt_python) {
                        if (opt_event_type != LTTNG_EVENT_ALL &&
-                                       opt_event_type != LTTNG_EVENT_TRACEPOINT) {
-                               ERR("Event type not supported for domain.");
+                           opt_event_type != LTTNG_EVENT_TRACEPOINT) {
+                               ERR("Instrumentation point type not supported for the %s domain",
+                                   lttng_domain_type_str(dom.type));
                                ret = CMD_UNSUPPORTED;
                                goto error;
                        }
@@ -965,23 +669,26 @@ static int enable_events(char *session_name)
                                if (opt_jul) {
                                        enum lttng_loglevel_jul loglevel;
 
-                                       name_search_ret = loglevel_jul_name_to_value(opt_loglevel, &loglevel);
+                                       name_search_ret =
+                                               loglevel_jul_name_to_value(opt_loglevel, &loglevel);
                                        ev->loglevel = (int) loglevel;
                                } else if (opt_log4j) {
                                        enum lttng_loglevel_log4j loglevel;
 
-                                       name_search_ret = loglevel_log4j_name_to_value(opt_loglevel, &loglevel);
+                                       name_search_ret = loglevel_log4j_name_to_value(opt_loglevel,
+                                                                                      &loglevel);
                                        ev->loglevel = (int) loglevel;
                                } else {
                                        /* python domain. */
                                        enum lttng_loglevel_python loglevel;
 
-                                       name_search_ret = loglevel_python_name_to_value(opt_loglevel, &loglevel);
+                                       name_search_ret = loglevel_python_name_to_value(
+                                               opt_loglevel, &loglevel);
                                        ev->loglevel = (int) loglevel;
                                }
 
                                if (name_search_ret) {
-                                       ERR("Unknown loglevel %s", opt_loglevel);
+                                       ERR("Unknown log level `%s`", opt_loglevel);
                                        ret = -LTTNG_ERR_INVALID;
                                        goto error;
                                }
@@ -995,61 +702,75 @@ static int enable_events(char *session_name)
                                }
                        }
                        ev->type = LTTNG_EVENT_TRACEPOINT;
-                       strncpy(ev->name, event_name, LTTNG_SYMBOL_NAME_LEN);
+                       strncpy(ev->name, pattern.c_str(), LTTNG_SYMBOL_NAME_LEN);
                        ev->name[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
                } else {
                        abort();
                }
 
                if (!opt_filter) {
-                       char *exclusion_string;
-
-                       command_ret = lttng_enable_event_with_exclusions(handle,
-                                       ev, channel_name,
-                                       NULL,
-                                       lttng_dynamic_pointer_array_get_count(&exclusions),
-                                       (char **) exclusions.array.buffer.data);
-                       exclusion_string = print_exclusions(&exclusions);
+                       command_ret = lttng_enable_event_with_exclusions(
+                               handle,
+                               ev,
+                               channel_name,
+                               nullptr,
+                               lttng_dynamic_pointer_array_get_count(&exclusions),
+                               (char **) exclusions.array.buffer.data);
+
+                       auto exclusion_string =
+                               lttng::make_unique_wrapper<char, lttng::memory::free>(
+                                       print_exclusions(&exclusions));
                        if (!exclusion_string) {
                                PERROR("Cannot allocate exclusion_string");
                                error = 1;
                                goto end;
                        }
+
                        if (command_ret < 0) {
                                /* Turn ret to positive value to handle the positive error code */
                                switch (-command_ret) {
                                case LTTNG_ERR_KERN_EVENT_EXIST:
-                                       WARN("Kernel event %s%s already enabled (channel %s, session %s)",
-                                                       event_name,
-                                                       exclusion_string,
-                                                       print_channel_name(channel_name), session_name);
+                                       WARN("Kernel event rule %s%s and attached to channel `%s` is already enabled (session `%s`)",
+                                            opt_enable_all ? "matching all events" :
+                                                             (std::string("with pattern `") +
+                                                              pattern + std::string("`"))
+                                                                     .c_str(),
+                                            exclusion_string.get(),
+                                            print_channel_name(channel_name),
+                                            session_name.c_str());
                                        warn = 1;
                                        break;
                                case LTTNG_ERR_TRACE_ALREADY_STARTED:
                                {
-                                       const char *msg = "The command tried to enable an event in a new domain for a session that has already been started once.";
-                                       ERR("Event %s%s: %s (channel %s, session %s)", event_name,
-                                                       exclusion_string,
-                                                       msg,
-                                                       print_channel_name(channel_name),
-                                                       session_name);
+                                       ERR("Can't enable an event in a new domain for a session that has already been started once (session `%s`)",
+                                           session_name.c_str());
                                        error = 1;
                                        break;
                                }
                                case LTTNG_ERR_SDT_PROBE_SEMAPHORE:
-                                       ERR("SDT probes %s guarded by semaphores are not supported (channel %s, session %s)",
-                                                       event_name, print_channel_name(channel_name),
-                                                       session_name);
+                                       ERR("Failed to enable event rule with pattern `%s` and attached to channel `%s` as SDT probes guarded by semaphores are not supported (session `%s`)",
+                                           pattern.c_str(),
+                                           print_channel_name(channel_name),
+                                           session_name.c_str());
                                        error = 1;
                                        break;
                                default:
-                                       ERR("Event %s%s: %s (channel %s, session %s)", event_name,
-                                                       exclusion_string,
-                                                       lttng_strerror(command_ret),
-                                                       command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME
-                                                               ? print_raw_channel_name(channel_name)
-                                                               : print_channel_name(channel_name),
-                                                       session_name);
+                                       ERR("Failed to enable event rule %s%s and attached to channel `%s`: %s (session `%s`)",
+                                           opt_enable_all ? "matching all events" :
+                                                            (std::string("with pattern `") +
+                                                             pattern + std::string("`"))
+                                                                    .c_str(),
+                                           exclusion_string.get(),
+                                           command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME ?
+                                                   print_raw_channel_name(channel_name) :
+                                                   print_channel_name(channel_name),
+                                           lttng_strerror(command_ret),
+                                           session_name.c_str());
+
+                                       if (opt_kernel) {
+                                               print_kernel_tracer_status_error();
+                                       }
+
                                        error = 1;
                                        break;
                                }
@@ -1058,12 +779,17 @@ static int enable_events(char *session_name)
                                switch (dom.type) {
                                case LTTNG_DOMAIN_KERNEL:
                                case LTTNG_DOMAIN_UST:
-                                       MSG("%s event %s%s created in channel %s",
-                                               lttng_domain_type_str(dom.type),
-                                               event_name,
-                                               exclusion_string,
-                                               print_channel_name(channel_name));
+                               {
+                                       MSG("Enabled %s event rule %s%s and attached to channel `%s`",
+                                           lttng_domain_type_str(dom.type),
+                                           opt_enable_all ? "matching all events" :
+                                                            (std::string("with pattern `") +
+                                                             pattern + std::string("`"))
+                                                                    .c_str(),
+                                           exclusion_string.get(),
+                                           print_channel_name(channel_name));
                                        break;
+                               }
                                case LTTNG_DOMAIN_JUL:
                                case LTTNG_DOMAIN_LOG4J:
                                case LTTNG_DOMAIN_PYTHON:
@@ -1071,74 +797,92 @@ static int enable_events(char *session_name)
                                         * Don't print the default channel
                                         * name for agent domains.
                                         */
-                                       MSG("%s event %s%s enabled",
-                                               lttng_domain_type_str(dom.type),
-                                               event_name,
-                                               exclusion_string);
+                                       MSG("Enabled %s event rule %s%s",
+                                           lttng_domain_type_str(dom.type),
+                                           opt_enable_all ? "matching all events" :
+                                                            (std::string("with pattern `") +
+                                                             pattern + std::string("`"))
+                                                                    .c_str(),
+                                           exclusion_string.get());
                                        break;
                                default:
                                        abort();
                                }
                        }
-                       free(exclusion_string);
-               }
-
-               if (opt_filter) {
-                       char *exclusion_string;
-
+               } else {
                        /* Filter present */
                        ev->filter = 1;
 
-                       command_ret = lttng_enable_event_with_exclusions(handle, ev, channel_name,
-                                       opt_filter,
-                                       lttng_dynamic_pointer_array_get_count(&exclusions),
-                                       (char **) exclusions.array.buffer.data);
-                       exclusion_string = print_exclusions(&exclusions);
+                       command_ret = lttng_enable_event_with_exclusions(
+                               handle,
+                               ev,
+                               channel_name,
+                               opt_filter,
+                               lttng_dynamic_pointer_array_get_count(&exclusions),
+                               (char **) exclusions.array.buffer.data);
+
+                       auto exclusion_string =
+                               lttng::make_unique_wrapper<char, lttng::memory::free>(
+                                       print_exclusions(&exclusions));
                        if (!exclusion_string) {
-                               PERROR("Cannot allocate exclusion_string");
+                               PERROR("Failed allocate exclusion string");
                                error = 1;
                                goto end;
                        }
                        if (command_ret < 0) {
                                switch (-command_ret) {
                                case LTTNG_ERR_FILTER_EXIST:
-                                       WARN("Filter on event %s%s is already enabled"
-                                                       " (channel %s, session %s)",
-                                               event_name,
-                                               exclusion_string,
-                                               print_channel_name(channel_name), session_name);
+                                       WARN("An event rule %s%s and filter expression `%s` is already attached to channel `%s`",
+                                            opt_enable_all ? "matching all events" :
+                                                             (std::string("with pattern `") +
+                                                              pattern + std::string("`"))
+                                                                     .c_str(),
+                                            exclusion_string.get(),
+                                            opt_filter,
+                                            print_channel_name(channel_name));
                                        warn = 1;
                                        break;
                                case LTTNG_ERR_TRACE_ALREADY_STARTED:
                                {
-                                       const char *msg = "The command tried to enable an event in a new domain for a session that has already been started once.";
-                                       ERR("Event %s%s: %s (channel %s, session %s, filter \'%s\')", ev->name,
-                                                       exclusion_string,
-                                                       msg,
-                                                       print_channel_name(channel_name),
-                                                       session_name, opt_filter);
+                                       ERR("Can't enable an event in a new domain for a session that has already been started once (session `%s`)",
+                                           session_name.c_str());
                                        error = 1;
                                        break;
                                }
                                default:
-                                       ERR("Event %s%s: %s (channel %s, session %s, filter \'%s\')", ev->name,
-                                                       exclusion_string,
-                                                       lttng_strerror(command_ret),
-                                                       command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME
-                                                               ? print_raw_channel_name(channel_name)
-                                                               : print_channel_name(channel_name),
-                                                       session_name, opt_filter);
+                                       ERR("Failed to enable event rule %s%s, with filter expression `%s`, and attached to channel `%s`: %s (session `%s`)",
+                                           opt_enable_all ? "matching all events" :
+                                                            (std::string("with pattern `") +
+                                                             pattern + std::string("`"))
+                                                                    .c_str(),
+                                           exclusion_string.get(),
+                                           opt_filter,
+                                           command_ret == -LTTNG_ERR_NEED_CHANNEL_NAME ?
+                                                   print_raw_channel_name(channel_name) :
+                                                   print_channel_name(channel_name),
+                                           lttng_strerror(command_ret),
+                                           session_name.c_str());
                                        error = 1;
+
+                                       if (opt_kernel) {
+                                               print_kernel_tracer_status_error();
+                                       }
+
                                        break;
                                }
-                               error_holder = command_ret;
 
+                               error_holder = command_ret;
                        } else {
-                               MSG("Event %s%s: Filter '%s' successfully set",
-                                               event_name, exclusion_string,
-                                               opt_filter);
+                               MSG("Enabled %s event rule %s%s and filter expression `%s`",
+                                   lttng_domain_type_str(dom.type),
+                                   opt_enable_all ? "matching all events" :
+                                                    (std::string("with pattern `") + pattern +
+                                                     std::string("`"))
+                                                            .c_str(),
+
+                                   exclusion_string.get(),
+                                   opt_filter);
                        }
-                       free(exclusion_string);
                }
 
                if (lttng_opt_mi) {
@@ -1149,7 +893,7 @@ static int enable_events(char *session_name)
                                ev->enabled = 1;
                        }
 
-                       ret = mi_lttng_event(writer, ev, 1, handle->domain.type);
+                       ret = mi_lttng_event(writer.get(), ev, 1, handle->domain.type);
                        if (ret) {
                                ret = CMD_ERROR;
                                goto error;
@@ -1163,23 +907,21 @@ static int enable_events(char *session_name)
                        }
 
                        /* Success ? */
-                       ret = mi_lttng_writer_write_element_bool(writer,
-                                       mi_lttng_element_command_success, success);
+                       ret = mi_lttng_writer_write_element_bool(
+                               writer.get(), mi_lttng_element_command_success, success);
                        if (ret) {
                                ret = CMD_ERROR;
                                goto end;
                        }
 
                        /* Close event element */
-                       ret = mi_lttng_writer_close_element(writer);
+                       ret = mi_lttng_writer_close_element(writer.get());
                        if (ret) {
                                ret = CMD_ERROR;
                                goto end;
                        }
                }
 
-               /* Next event */
-               event_name = strtok(NULL, ",");
                /* Reset warn, error and success */
                success = 1;
        }
@@ -1188,7 +930,7 @@ end:
        /* Close Mi */
        if (lttng_opt_mi) {
                /* Close events element */
-               ret = mi_lttng_writer_close_element(writer);
+               ret = mi_lttng_writer_close_element(writer.get());
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
@@ -1214,28 +956,83 @@ error:
        return ret;
 }
 
+void _poptContextFree_deleter_func(poptContext ctx)
+{
+       poptFreeContext(ctx);
+}
+
+} /* namespace */
+
+int validate_exclusion_list(const char *pattern,
+                           const struct lttng_dynamic_pointer_array *exclusions)
+{
+       int ret;
+
+       /* Event name pattern must be a valid globbing pattern to allow exclusions. */
+       if (!strutils_is_star_glob_pattern(pattern)) {
+               ERR("Event name pattern must contain wildcard characters to use exclusions");
+               goto error;
+       }
+
+       /*
+        * If the event name is a star-at-end only globbing pattern,
+        * then we can validate the individual exclusions. Otherwise
+        * all exclusions are passed to the session daemon.
+        */
+       if (strutils_is_star_at_the_end_only_glob_pattern(pattern)) {
+               size_t i, num_exclusions;
+
+               num_exclusions = lttng_dynamic_pointer_array_get_count(exclusions);
+
+               for (i = 0; i < num_exclusions; i++) {
+                       const char *exclusion =
+                               (const char *) lttng_dynamic_pointer_array_get_pointer(exclusions,
+                                                                                      i);
+
+                       if (!strutils_is_star_glob_pattern(exclusion) ||
+                           strutils_is_star_at_the_end_only_glob_pattern(exclusion)) {
+                               ret = check_exclusion_subsets(pattern, exclusion);
+                               if (ret) {
+                                       goto error;
+                               }
+                       }
+               }
+       }
+
+       ret = 0;
+       goto end;
+
+error:
+       ret = -1;
+
+end:
+       return ret;
+}
+
 /*
  * Add event to trace session
  */
 int cmd_enable_events(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
-       static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
+       std::string session_name;
+       const char *arg_event_list = nullptr;
+       const char *leftover = nullptr;
        int event_type = -1;
+       event_rule_patterns patterns;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
-       poptReadDefaultConfig(pc, 0);
+       auto pc = lttng::make_unique_wrapper<poptContext_s, _poptContextFree_deleter_func>(
+               poptGetContext(nullptr, argc, argv, long_options, 0));
+       poptReadDefaultConfig(pc.get(), 0);
 
        /* Default event type */
        opt_event_type = LTTNG_EVENT_ALL;
 
-       while ((opt = poptGetNextOpt(pc)) != -1) {
+       while ((opt = poptGetNextOpt(pc.get())) != -1) {
                switch (opt) {
                case OPT_HELP:
                        SHOW_HELP();
-                       goto end;
+                       return CMD_SUCCESS;
                case OPT_TRACEPOINT:
                        opt_event_type = LTTNG_EVENT_TRACEPOINT;
                        break;
@@ -1256,22 +1053,21 @@ int cmd_enable_events(int argc, const char **argv)
                        break;
                case OPT_LOGLEVEL:
                        opt_loglevel_type = LTTNG_EVENT_LOGLEVEL_RANGE;
-                       opt_loglevel = poptGetOptArg(pc);
+                       opt_loglevel = poptGetOptArg(pc.get());
                        break;
                case OPT_LOGLEVEL_ONLY:
                        opt_loglevel_type = LTTNG_EVENT_LOGLEVEL_SINGLE;
-                       opt_loglevel = poptGetOptArg(pc);
+                       opt_loglevel = poptGetOptArg(pc.get());
                        break;
                case OPT_LIST_OPTIONS:
                        list_cmd_options(stdout, long_options);
-                       goto end;
+                       return CMD_SUCCESS;
                case OPT_FILTER:
                        break;
                case OPT_EXCLUDE:
                        break;
                default:
-                       ret = CMD_UNDEFINED;
-                       goto end;
+                       return CMD_UNDEFINED;
                }
 
                /* Validate event type. Multiple event type are not supported. */
@@ -1279,118 +1075,110 @@ int cmd_enable_events(int argc, const char **argv)
                        event_type = opt_event_type;
                } else {
                        if (event_type != opt_event_type) {
-                               ERR("Multiple event type not supported.");
-                               ret = CMD_ERROR;
-                               goto end;
+                               ERR("Only one event type may be enabled at once");
+                               return CMD_ERROR;
                        }
                }
        }
 
        ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace + opt_jul + opt_log4j +
-                                       opt_python,
-                       true);
+               opt_kernel + opt_userspace + opt_jul + opt_log4j + opt_python, true);
        if (ret) {
-               ret = CMD_ERROR;
-               goto end;
+               return CMD_ERROR;
        }
 
        /* Mi check */
        if (lttng_opt_mi) {
-               writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
+               writer = mi_writer_uptr(mi_lttng_writer_create(fileno(stdout), lttng_opt_mi));
                if (!writer) {
-                       ret = -LTTNG_ERR_NOMEM;
-                       goto end;
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Failed to create MI writer: format_code={}", lttng_opt_mi));
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_enable_event);
+               ret = mi_lttng_writer_command_open(writer.get(),
+                                                  mi_lttng_element_command_enable_event);
                if (ret) {
-                       ret = CMD_ERROR;
-                       goto end;
+                       LTTNG_THROW_ERROR(lttng::format(
+                               "Failed to open MI command element: command_name=`{}`",
+                               mi_lttng_element_command_enable_event));
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer.get(), mi_lttng_element_command_output);
                if (ret) {
-                       ret = CMD_ERROR;
-                       goto end;
+                       LTTNG_THROW_ERROR(
+                               lttng::format("Failed to open MI element: element_name=`{}`",
+                                             mi_lttng_element_command_output));
                }
        }
 
-       opt_event_list = (char*) poptGetArg(pc);
-       if (opt_event_list == NULL && opt_enable_all == 0) {
-               ERR("Missing event name(s).\n");
-               ret = CMD_ERROR;
-               goto end;
-       }
-
-       leftover = poptGetArg(pc);
-       if (leftover) {
-               ERR("Unknown argument: %s", leftover);
-               ret = CMD_ERROR;
-               goto end;
-       }
-
-       if (!opt_session_name) {
-               session_name = get_session_name();
-               if (session_name == NULL) {
-                       command_ret = CMD_ERROR;
-                       success = 0;
-                       goto mi_closing;
+       /* Close the MI command context when leaving the function, no matter the result. */
+       const auto close_mi_on_exit = lttng::make_scope_exit([&success]() noexcept {
+               if (!lttng_opt_mi) {
+                       return;
                }
-       } else {
-               session_name = opt_session_name;
-       }
 
-       command_ret = enable_events(session_name);
-       if (command_ret) {
-               success = 0;
-               goto mi_closing;
-       }
+               /* Close output element. */
+               if (mi_lttng_writer_close_element(writer.get())) {
+                       ERR_FMT("Failed to close MI output element");
+                       return;
+               }
 
-mi_closing:
-       /* Mi closing */
-       if (lttng_opt_mi) {
-               /* Close  output element */
-               ret = mi_lttng_writer_close_element(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
-                       goto end;
+               if (mi_lttng_writer_write_element_bool(
+                           writer.get(), mi_lttng_element_command_success, success)) {
+                       ERR_FMT("Failed to write MI element: element_name=`{}`, value={}",
+                               mi_lttng_element_command_success,
+                               success);
+                       return;
                }
 
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
-               if (ret) {
-                       ret = CMD_ERROR;
-                       goto end;
+               /* Command element close. */
+               if (mi_lttng_writer_command_close(writer.get())) {
+                       ERR_FMT("Failed to close MI command element");
+                       return;
                }
+       });
 
-               /* Command element close */
-               ret = mi_lttng_writer_command_close(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
-                       goto end;
+       arg_event_list = poptGetArg(pc.get());
+       if (arg_event_list == nullptr && opt_enable_all == 0) {
+               ERR("Missing event name pattern(s)");
+               return CMD_ERROR;
+       }
+
+       if (opt_enable_all) {
+               patterns.emplace_back("*");
+       } else {
+               std::stringstream event_list_arg_stream(arg_event_list);
+
+               for (std::string line; std::getline(event_list_arg_stream, line, ',');) {
+                       patterns.emplace_back(std::move(line));
                }
        }
 
-end:
-       /* Mi clean-up */
-       if (writer && mi_lttng_writer_destroy(writer)) {
-               /* Preserve original error code */
-               ret = ret ? ret : LTTNG_ERR_MI_IO_FAIL;
+       leftover = poptGetArg(pc.get());
+       if (leftover) {
+               ERR("Unknown argument: %s", leftover);
+               return CMD_ERROR;
        }
 
-       if (opt_session_name == NULL) {
-               free(session_name);
+       if (!opt_session_name) {
+               const auto rc_file_session_name =
+                       lttng::make_unique_wrapper<char, lttng::memory::free>(get_session_name());
+
+               if (!rc_file_session_name) {
+                       return CMD_ERROR;
+               }
+
+               session_name = rc_file_session_name.get();
+       } else {
+               session_name = opt_session_name;
        }
 
-       /* Overwrite ret if an error occurred in enable_events */
-       ret = command_ret ? command_ret : ret;
+       command_ret = enable_events(session_name, patterns);
+       if (command_ret) {
+               return CMD_ERROR;
+       }
 
-       poptFreeContext(pc);
-       return ret;
+       return CMD_SUCCESS;
 }
-
index 1b79da148065b6f0ace1d3d9eaebb8676f8239b7..77879d0afb352ca9db42101ff38702b903f0d6d6 100644 (file)
@@ -6,6 +6,16 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
+#include <ctype.h>
+#include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <ctype.h>
-
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/mi-lttng.hpp>
-#include <common/utils.hpp>
-
-#include "../command.hpp"
-#include <lttng/lttng.h>
 
 static char *opt_session_name;
 static struct mi_writer *writer;
@@ -29,7 +30,7 @@ static struct mi_writer *writer;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-enable-rotation.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -41,12 +42,12 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"session",     's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"timer",        0,   POPT_ARG_INT, 0, OPT_TIMER, 0, 0},
-       {"size",         0,   POPT_ARG_INT, 0, OPT_SIZE, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "timer", 0, POPT_ARG_INT, nullptr, OPT_TIMER, nullptr, nullptr },
+       { "size", 0, POPT_ARG_INT, nullptr, OPT_SIZE, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static const char *schedule_type_str[] = {
@@ -55,10 +56,11 @@ static const char *schedule_type_str[] = {
 };
 
 static enum cmd_error_code add_schedule(const char *session_name,
-               enum lttng_rotation_schedule_type schedule_type, uint64_t value)
+                                       enum lttng_rotation_schedule_type schedule_type,
+                                       uint64_t value)
 {
        enum cmd_error_code ret = CMD_SUCCESS;
-       struct lttng_rotation_schedule *schedule = NULL;
+       struct lttng_rotation_schedule *schedule = nullptr;
        enum lttng_rotation_status status;
        const char *schedule_type_name;
 
@@ -69,8 +71,7 @@ static enum cmd_error_code add_schedule(const char *session_name,
                        ret = CMD_ERROR;
                        goto end;
                }
-               status = lttng_rotation_schedule_periodic_set_period(schedule,
-                               value);
+               status = lttng_rotation_schedule_periodic_set_period(schedule, value);
                break;
        case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
                schedule = lttng_rotation_schedule_size_threshold_create();
@@ -78,8 +79,7 @@ static enum cmd_error_code add_schedule(const char *session_name,
                        ret = CMD_ERROR;
                        goto end;
                }
-               status = lttng_rotation_schedule_size_threshold_set_threshold(
-                               schedule, value);
+               status = lttng_rotation_schedule_size_threshold_set_threshold(schedule, value);
                break;
        default:
                ERR("Unknown schedule type");
@@ -96,8 +96,7 @@ static enum cmd_error_code add_schedule(const char *session_name,
                ret = CMD_ERROR;
                goto end;
        default:
-               ERR("Unknown error occurred setting %s rotation schedule",
-                               schedule_type_name);
+               ERR("Unknown error occurred setting %s rotation schedule", schedule_type_name);
                ret = CMD_ERROR;
                goto end;
        }
@@ -109,32 +108,36 @@ static enum cmd_error_code add_schedule(const char *session_name,
                switch (schedule_type) {
                case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
                        MSG("Enabled %s rotations every %" PRIu64 " %s on session %s",
-                                       schedule_type_name, value, USEC_UNIT, session_name);
+                           schedule_type_name,
+                           value,
+                           USEC_UNIT,
+                           session_name);
                        break;
                case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
                        MSG("Enabled %s rotations every %" PRIu64 " bytes written on session %s",
-                                       schedule_type_name, value, session_name);
+                           schedule_type_name,
+                           value,
+                           session_name);
                        break;
                default:
                        abort();
                }
                break;
        case LTTNG_ROTATION_STATUS_INVALID:
-               ERR("Invalid parameter for %s rotation schedule",
-                               schedule_type_name);
+               ERR("Invalid parameter for %s rotation schedule", schedule_type_name);
                ret = CMD_ERROR;
                break;
        case LTTNG_ROTATION_STATUS_SCHEDULE_ALREADY_SET:
                ERR("A %s rotation schedule is already set on session %s",
-                               schedule_type_name,
-                               session_name);
+                   schedule_type_name,
+                   session_name);
                ret = CMD_ERROR;
                break;
        case LTTNG_ROTATION_STATUS_ERROR:
        default:
                ERR("Failed to enable %s rotation schedule on session %s",
-                               schedule_type_name,
-                               session_name);
+                   schedule_type_name,
+                   session_name);
                ret = CMD_ERROR;
                break;
        }
@@ -142,8 +145,7 @@ static enum cmd_error_code add_schedule(const char *session_name,
        if (lttng_opt_mi) {
                int mi_ret;
 
-               mi_ret = mi_lttng_rotation_schedule_result(writer,
-                               schedule, ret == CMD_SUCCESS);
+               mi_ret = mi_lttng_rotation_schedule_result(writer, schedule, ret == CMD_SUCCESS);
                if (mi_ret < 0) {
                        ret = CMD_ERROR;
                        goto end;
@@ -165,13 +167,13 @@ int cmd_enable_rotation(int argc, const char **argv)
        int popt_ret, opt, ret = 0;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        static poptContext pc;
-       char *session_name = NULL;
-       char *opt_arg = NULL;
+       char *session_name = nullptr;
+       char *opt_arg = nullptr;
        bool free_session_name = false;
        uint64_t timer_us = 0, size_bytes = 0;
        bool periodic_rotation = false, size_rotation = false;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        popt_ret = poptReadDefaultConfig(pc, 0);
        if (popt_ret) {
                ERR("poptReadDefaultConfig");
@@ -226,9 +228,9 @@ int cmd_enable_rotation(int argc, const char **argv)
                }
        }
 
-       if (opt_session_name == NULL) {
+       if (opt_session_name == nullptr) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        goto error;
                }
                free_session_name = true;
@@ -245,14 +247,13 @@ int cmd_enable_rotation(int argc, const char **argv)
 
                /* Open command element */
                ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_enable_rotation);
+                                                  mi_lttng_element_command_enable_rotation);
                if (ret) {
                        goto error;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        goto error;
                }
@@ -266,14 +267,13 @@ int cmd_enable_rotation(int argc, const char **argv)
 
        if (lttng_opt_mi) {
                ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_rotation_schedule_results);
+                                                  mi_lttng_element_rotation_schedule_results);
                if (ret) {
                        goto error;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_session_name,
-                               session_name);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_session_name, session_name);
                if (ret) {
                        goto error;
                }
@@ -284,18 +284,16 @@ int cmd_enable_rotation(int argc, const char **argv)
                 * Continue processing even on error as multiple schedules can
                 * be specified at once.
                 */
-               cmd_ret = add_schedule(session_name,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC,
-                               timer_us);
+               cmd_ret =
+                       add_schedule(session_name, LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC, timer_us);
        }
 
        if (size_rotation) {
                enum cmd_error_code tmp_ret;
 
                /* Don't overwrite cmd_ret if it already indicates an error. */
-               tmp_ret = add_schedule(session_name,
-                               LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD,
-                               size_bytes);
+               tmp_ret = add_schedule(
+                       session_name, LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD, size_bytes);
                cmd_ret = cmd_ret ? cmd_ret : tmp_ret;
        }
 
@@ -317,9 +315,8 @@ close_command:
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success,
-                               cmd_ret == CMD_SUCCESS);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, cmd_ret == CMD_SUCCESS);
                if (ret) {
                        goto error;
                }
index 74b64964443aa184eb8ac7762491f4cac2e37037..57b73a6b0a94198d90fdda62c68afb58ba4c8780 100644 (file)
@@ -6,27 +6,28 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/utils.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include "../command.hpp"
-#include <common/utils.hpp>
-
 #ifdef LTTNG_EMBED_HELP
 static const char *help_msg =
 #include <lttng-help.1.h>
-;
+       ;
 #endif
 
 static const char *lttng_help_msg =
 #ifdef LTTNG_EMBED_HELP
 #include <lttng.1.h>
 #else
-NULL
+       nullptr
 #endif
-;
+       ;
 
 enum {
        OPT_HELP = 1,
@@ -35,9 +36,9 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -46,13 +47,13 @@ static struct poptOption long_options[] = {
 int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
 {
        int opt, ret = CMD_SUCCESS;
-       char *cmd_name;
+       const char *arg_cmd_name;
        static poptContext pc;
        const struct cmd_struct *cmd;
-       int found = 0;
+       bool found = false;
        const char *cmd_argv[2];
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -70,9 +71,8 @@ int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
        }
 
        /* Get command name */
-       cmd_name = (char *) poptGetArg(pc);
-
-       if (cmd_name == NULL) {
+       arg_cmd_name = poptGetArg(pc);
+       if (arg_cmd_name == nullptr) {
                /* Fall back to lttng(1) */
                ret = utils_show_help(1, "lttng", lttng_help_msg);
                if (ret) {
@@ -85,7 +85,7 @@ int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
        }
 
        /* Help about help? */
-       if (strcmp(cmd_name, "help") == 0) {
+       if (strcmp(arg_cmd_name, "help") == 0) {
                SHOW_HELP();
                goto end;
        }
@@ -93,9 +93,9 @@ int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
        /* Make sure command name exists */
        cmd = &commands[0];
 
-       while (cmd->name != NULL) {
-               if (strcmp(cmd->name, cmd_name) == 0) {
-                       found = 1;
+       while (cmd->name != nullptr) {
+               if (strcmp(cmd->name, arg_cmd_name) == 0) {
+                       found = true;
                        break;
                }
 
@@ -103,7 +103,7 @@ int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
        }
 
        if (!found) {
-               ERR("Unknown command \"%s\"", cmd_name);
+               ERR("Unknown command \"%s\"", arg_cmd_name);
                ret = CMD_ERROR;
                goto end;
        }
index 8636cd101850d5557e489e2671add4ede354e4cc..c4e52b78fef879d9edf902bf25e4dc63c50d28af 100644 (file)
@@ -8,19 +8,20 @@
 
 #include <stdint.h>
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <popt.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include "../command.hpp"
 
 #include <common/mi-lttng.hpp>
 #include <common/time.hpp>
 #include <common/tracker.hpp>
+
 #include <lttng/domain-internal.hpp>
 #include <lttng/lttng.h>
 
-#include "../command.hpp"
+#include <inttypes.h>
+#include <popt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 static int opt_userspace;
 static int opt_kernel;
@@ -39,7 +40,7 @@ const char *indent8 = "        ";
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-list.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -56,18 +57,18 @@ static struct lttng_session the_listed_session;
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"kernel",      'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0},
-       {"jul", 'j', POPT_ARG_VAL, &opt_jul, 1, 0, 0},
-       {"log4j",       'l', POPT_ARG_VAL, &opt_log4j, 1, 0, 0},
-       {"python",      'p', POPT_ARG_VAL, &opt_python, 1, 0, 0},
-       {"userspace",   'u', POPT_ARG_NONE, 0, OPT_USERSPACE, 0, 0},
-       {"channel",     'c', POPT_ARG_STRING, &opt_channel, 0, 0, 0},
-       {"domain",      'd', POPT_ARG_VAL, &opt_domain, 1, 0, 0},
-       {"fields",      'f', POPT_ARG_VAL, &opt_fields, 1, 0, 0},
-       {"syscall",     'S', POPT_ARG_VAL, &opt_syscall, 1, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "kernel", 'k', POPT_ARG_VAL, &opt_kernel, 1, nullptr, nullptr },
+       { "jul", 'j', POPT_ARG_VAL, &opt_jul, 1, nullptr, nullptr },
+       { "log4j", 'l', POPT_ARG_VAL, &opt_log4j, 1, nullptr, nullptr },
+       { "python", 'p', POPT_ARG_VAL, &opt_python, 1, nullptr, nullptr },
+       { "userspace", 'u', POPT_ARG_NONE, nullptr, OPT_USERSPACE, nullptr, nullptr },
+       { "channel", 'c', POPT_ARG_STRING, &opt_channel, 0, nullptr, nullptr },
+       { "domain", 'd', POPT_ARG_VAL, &opt_domain, 1, nullptr, nullptr },
+       { "fields", 'f', POPT_ARG_VAL, &opt_fields, 1, nullptr, nullptr },
+       { "syscall", 'S', POPT_ARG_VAL, &opt_syscall, 1, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -79,14 +80,14 @@ static struct poptOption long_options[] = {
 static char *get_cmdline_by_pid(pid_t pid)
 {
        int ret;
-       FILE *fp = NULL;
-       char *cmdline = NULL;
+       FILE *fp = nullptr;
+       char *cmdline = nullptr;
        /* Can't go bigger than /proc/LTTNG_MAX_PID/cmdline */
        char path[sizeof("/proc//cmdline") + sizeof(LTTNG_MAX_PID_STR) - 1];
 
        snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
        fp = fopen(path, "r");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                goto end;
        }
 
@@ -109,14 +110,17 @@ end:
        return cmdline;
 }
 
-static
-const char *active_string(int value)
+static const char *active_string(int value)
 {
        switch (value) {
-       case 0: return "inactive";
-       case 1: return "active";
-       case -1: return "";
-       default: return NULL;
+       case 0:
+               return "inactive";
+       case 1:
+               return "active";
+       case -1:
+               return "";
+       default:
+               return nullptr;
        }
 }
 
@@ -130,19 +134,21 @@ static const char *snapshot_string(int value)
        }
 }
 
-static
-const char *enabled_string(int value)
+static const char *enabled_string(int value)
 {
        switch (value) {
-       case 0: return " [disabled]";
-       case 1: return " [enabled]";
-       case -1: return "";
-       default: return NULL;
+       case 0:
+               return " [disabled]";
+       case 1:
+               return " [enabled]";
+       case -1:
+               return "";
+       default:
+               return nullptr;
        }
 }
 
-static
-const char *safe_string(const char *str)
+static const char *safe_string(const char *str)
 {
        return str ? str : "";
 }
@@ -185,10 +191,10 @@ static char *get_exclusion_names_msg(struct lttng_event *event)
 {
        int ret;
        int exclusion_count;
-       char *exclusion_msg = NULL;
+       char *exclusion_msg = nullptr;
        char *at;
        size_t i;
-       const char * const exclusion_fmt = " [exclusions: ";
+       const char *const exclusion_fmt = " [exclusions: ";
        const size_t exclusion_fmt_len = strlen(exclusion_fmt);
 
        exclusion_count = lttng_event_get_exclusion_name_count(event);
@@ -208,9 +214,8 @@ static char *get_exclusion_names_msg(struct lttng_event *event)
         * a comma per entry, the entry count (fixed-size), a closing
         * bracket, and a trailing \0.
         */
-       exclusion_msg = (char *) malloc(exclusion_count +
-                       exclusion_count * LTTNG_SYMBOL_NAME_LEN +
-                       exclusion_fmt_len + 1);
+       exclusion_msg = (char *) malloc(exclusion_count + exclusion_count * LTTNG_SYMBOL_NAME_LEN +
+                                       exclusion_fmt_len + 1);
        if (!exclusion_msg) {
                goto end;
        }
@@ -277,7 +282,8 @@ static void print_userspace_probe_location(struct lttng_event *event)
 
                MSG("%sType: Function", indent8);
                function_name = lttng_userspace_probe_location_function_get_function_name(location);
-               binary_path = realpath(lttng_userspace_probe_location_function_get_binary_path(location), NULL);
+               binary_path = realpath(
+                       lttng_userspace_probe_location_function_get_binary_path(location), nullptr);
 
                MSG("%sBinary path:   %s", indent8, binary_path ? binary_path : "NULL");
                MSG("%sFunction:      %s()", indent8, function_name ? function_name : "NULL");
@@ -303,10 +309,16 @@ static void print_userspace_probe_location(struct lttng_event *event)
 
                MSG("%sType: Tracepoint", indent8);
                probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(location);
-               provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(location);
-               binary_path = realpath(lttng_userspace_probe_location_tracepoint_get_binary_path(location), NULL);
+               provider_name =
+                       lttng_userspace_probe_location_tracepoint_get_provider_name(location);
+               binary_path = realpath(
+                       lttng_userspace_probe_location_tracepoint_get_binary_path(location),
+                       nullptr);
                MSG("%sBinary path:   %s", indent8, binary_path ? binary_path : "NULL");
-               MSG("%sTracepoint:    %s:%s", indent8, provider_name ? provider_name : "NULL", probe_name ? probe_name : "NULL");
+               MSG("%sTracepoint:    %s:%s",
+                   indent8,
+                   provider_name ? provider_name : "NULL",
+                   probe_name ? probe_name : "NULL");
                switch (lookup_type) {
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                        MSG("%sLookup method: SDT", indent8);
@@ -331,8 +343,8 @@ static void print_events(struct lttng_event *event)
 {
        int ret;
        const char *filter_str;
-       char *filter_msg = NULL;
-       char *exclusion_msg = NULL;
+       char *filter_msg = nullptr;
+       char *exclusion_msg = nullptr;
 
        ret = lttng_event_get_filter_expression(event, &filter_str);
 
@@ -340,7 +352,7 @@ static void print_events(struct lttng_event *event)
                filter_msg = strdup(" [failed to retrieve filter]");
        } else if (filter_str) {
                if (asprintf(&filter_msg, " [filter: '%s']", filter_str) == -1) {
-                       filter_msg = NULL;
+                       filter_msg = nullptr;
                }
        }
 
@@ -354,30 +366,30 @@ static void print_events(struct lttng_event *event)
        {
                if (event->loglevel != -1) {
                        MSG("%s%s (loglevel%s %s (%d)) (type: tracepoint)%s%s%s",
-                                       indent6, event->name,
-                                       logleveltype_string(
-                                                       event->loglevel_type),
-                                       mi_lttng_loglevel_string(
-                                                       event->loglevel,
-                                                       the_handle->domain.type),
-                                       event->loglevel,
-                                       enabled_string(event->enabled),
-                                       safe_string(exclusion_msg),
-                                       safe_string(filter_msg));
+                           indent6,
+                           event->name,
+                           logleveltype_string(event->loglevel_type),
+                           mi_lttng_loglevel_string(event->loglevel, the_handle->domain.type),
+                           event->loglevel,
+                           enabled_string(event->enabled),
+                           safe_string(exclusion_msg),
+                           safe_string(filter_msg));
                } else {
                        MSG("%s%s (type: tracepoint)%s%s%s",
-                               indent6,
-                               event->name,
-                               enabled_string(event->enabled),
-                               safe_string(exclusion_msg),
-                               safe_string(filter_msg));
+                           indent6,
+                           event->name,
+                           enabled_string(event->enabled),
+                           safe_string(exclusion_msg),
+                           safe_string(filter_msg));
                }
                break;
        }
        case LTTNG_EVENT_FUNCTION:
-               MSG("%s%s (type: function)%s%s", indent6,
-                               event->name, enabled_string(event->enabled),
-                               safe_string(filter_msg));
+               MSG("%s%s (type: function)%s%s",
+                   indent6,
+                   event->name,
+                   enabled_string(event->enabled),
+                   safe_string(filter_msg));
                if (event->attr.probe.addr != 0) {
                        MSG("%saddr: 0x%" PRIx64, indent8, event->attr.probe.addr);
                } else {
@@ -386,9 +398,11 @@ static void print_events(struct lttng_event *event)
                }
                break;
        case LTTNG_EVENT_PROBE:
-               MSG("%s%s (type: probe)%s%s", indent6,
-                               event->name, enabled_string(event->enabled),
-                               safe_string(filter_msg));
+               MSG("%s%s (type: probe)%s%s",
+                   indent6,
+                   event->name,
+                   enabled_string(event->enabled),
+                   safe_string(filter_msg));
                if (event->attr.probe.addr != 0) {
                        MSG("%saddr: 0x%" PRIx64, indent8, event->attr.probe.addr);
                } else {
@@ -400,22 +414,27 @@ static void print_events(struct lttng_event *event)
                print_userspace_probe_location(event);
                break;
        case LTTNG_EVENT_FUNCTION_ENTRY:
-               MSG("%s%s (type: function)%s%s", indent6,
-                               event->name, enabled_string(event->enabled),
-                               safe_string(filter_msg));
+               MSG("%s%s (type: function)%s%s",
+                   indent6,
+                   event->name,
+                   enabled_string(event->enabled),
+                   safe_string(filter_msg));
                MSG("%ssymbol: \"%s\"", indent8, event->attr.ftrace.symbol_name);
                break;
        case LTTNG_EVENT_SYSCALL:
-               MSG("%s%s%s%s%s%s", indent6, event->name,
-                               (opt_syscall ? "" : " (type:syscall)"),
-                               enabled_string(event->enabled),
-                               bitness_event(event->flags),
-                               safe_string(filter_msg));
+               MSG("%s%s%s%s%s%s",
+                   indent6,
+                   event->name,
+                   (opt_syscall ? "" : " (type:syscall)"),
+                   enabled_string(event->enabled),
+                   bitness_event(event->flags),
+                   safe_string(filter_msg));
                break;
        case LTTNG_EVENT_NOOP:
-               MSG("%s (type: noop)%s%s", indent6,
-                               enabled_string(event->enabled),
-                               safe_string(filter_msg));
+               MSG("%s (type: noop)%s%s",
+                   indent6,
+                   enabled_string(event->enabled),
+                   safe_string(filter_msg));
                break;
        case LTTNG_EVENT_ALL:
                /* Fall-through. */
@@ -431,7 +450,7 @@ static void print_events(struct lttng_event *event)
 
 static const char *field_type(struct lttng_event_field *field)
 {
-       switch(field->type) {
+       switch (field->type) {
        case LTTNG_EVENT_FIELD_INTEGER:
                return "integer";
        case LTTNG_EVENT_FIELD_ENUM:
@@ -441,7 +460,7 @@ static const char *field_type(struct lttng_event_field *field)
        case LTTNG_EVENT_FIELD_STRING:
                return "string";
        case LTTNG_EVENT_FIELD_OTHER:
-       default:        /* fall-through */
+       default: /* fall-through */
                return "unknown";
        }
 }
@@ -454,20 +473,23 @@ static void print_event_field(struct lttng_event_field *field)
        if (!field->field_name[0]) {
                return;
        }
-       MSG("%sfield: %s (%s)%s", indent8, field->field_name,
-               field_type(field), field->nowrite ? " [no write]" : "");
+       MSG("%sfield: %s (%s)%s",
+           indent8,
+           field->field_name,
+           field_type(field),
+           field->nowrite ? " [no write]" : "");
 }
 
 /*
  * Machine interface
  * Jul and ust event listing
  */
-static int mi_list_agent_ust_events(struct lttng_event *events, int count,
-               struct lttng_domain *domain)
+static int
+mi_list_agent_ust_events(struct lttng_event *events, int count, struct lttng_domain *domain)
 {
        int ret, i;
        pid_t cur_pid = 0;
-       char *cmdline = NULL;
+       char *cmdline = nullptr;
        int pid_element_open = 0;
 
        /* Open domains element */
@@ -492,8 +514,7 @@ static int mi_list_agent_ust_events(struct lttng_event *events, int count,
                if (cur_pid != events[i].pid) {
                        if (pid_element_open) {
                                /* Close the previous events and pid element */
-                               ret = mi_lttng_close_multi_element(
-                                               the_writer, 2);
+                               ret = mi_lttng_close_multi_element(the_writer, 2);
                                if (ret) {
                                        goto end;
                                }
@@ -509,8 +530,7 @@ static int mi_list_agent_ust_events(struct lttng_event *events, int count,
 
                        if (!pid_element_open) {
                                /* Open and write a pid element */
-                               ret = mi_lttng_pid(the_writer, cur_pid, cmdline,
-                                               1);
+                               ret = mi_lttng_pid(the_writer, cur_pid, cmdline, 1);
                                if (ret) {
                                        goto error;
                                }
@@ -527,8 +547,7 @@ static int mi_list_agent_ust_events(struct lttng_event *events, int count,
                }
 
                /* Write an event */
-               ret = mi_lttng_event(the_writer, &events[i], 0,
-                               the_handle->domain.type);
+               ret = mi_lttng_event(the_writer, &events[i], 0, the_handle->domain.type);
                if (ret) {
                        goto end;
                }
@@ -549,14 +568,14 @@ error:
        return ret;
 }
 
-static int list_agent_events(void)
+static int list_agent_events()
 {
        int i, size, ret = CMD_SUCCESS;
        struct lttng_domain domain;
-       struct lttng_handle *handle = NULL;
-       struct lttng_event *event_list = NULL;
+       struct lttng_handle *handle = nullptr;
+       struct lttng_event *event_list = nullptr;
        pid_t cur_pid = 0;
-       char *cmdline = NULL;
+       char *cmdline = nullptr;
        const char *agent_domain_str;
 
        memset(&domain, 0, sizeof(domain));
@@ -576,16 +595,15 @@ static int list_agent_events(void)
 
        DBG("Getting %s tracing events", agent_domain_str);
 
-       handle = lttng_create_handle(NULL, &domain);
-       if (handle == NULL) {
+       handle = lttng_create_handle(nullptr, &domain);
+       if (handle == nullptr) {
                ret = CMD_ERROR;
                goto end;
        }
 
        size = lttng_list_tracepoints(handle, &event_list);
        if (size < 0) {
-               ERR("Unable to list %s events: %s", agent_domain_str,
-                               lttng_strerror(size));
+               ERR("Unable to list %s events: %s", agent_domain_str, lttng_strerror(size));
                ret = CMD_ERROR;
                goto end;
        }
@@ -599,8 +617,7 @@ static int list_agent_events(void)
                }
        } else {
                /* Pretty print */
-               MSG("%s events (Logger name):\n-------------------------",
-                               agent_domain_str);
+               MSG("%s events (Logger name):\n-------------------------", agent_domain_str);
 
                if (size == 0) {
                        MSG("None");
@@ -610,7 +627,7 @@ static int list_agent_events(void)
                        if (cur_pid != event_list[i].pid) {
                                cur_pid = event_list[i].pid;
                                cmdline = get_cmdline_by_pid(cur_pid);
-                               if (cmdline == NULL) {
+                               if (cmdline == nullptr) {
                                        ret = CMD_ERROR;
                                        goto error;
                                }
@@ -633,14 +650,14 @@ end:
 /*
  * Ask session daemon for all user space tracepoints available.
  */
-static int list_ust_events(void)
+static int list_ust_events()
 {
        int i, size, ret = CMD_SUCCESS;
        struct lttng_domain domain;
        struct lttng_handle *handle;
-       struct lttng_event *event_list = NULL;
+       struct lttng_event *event_list = nullptr;
        pid_t cur_pid = 0;
-       char *cmdline = NULL;
+       char *cmdline = nullptr;
 
        memset(&domain, 0, sizeof(domain));
 
@@ -648,8 +665,8 @@ static int list_ust_events(void)
 
        domain.type = LTTNG_DOMAIN_UST;
 
-       handle = lttng_create_handle(NULL, &domain);
-       if (handle == NULL) {
+       handle = lttng_create_handle(nullptr, &domain);
+       if (handle == nullptr) {
                ret = CMD_ERROR;
                goto end;
        }
@@ -676,7 +693,7 @@ static int list_ust_events(void)
                        if (cur_pid != event_list[i].pid) {
                                cur_pid = event_list[i].pid;
                                cmdline = get_cmdline_by_pid(cur_pid);
-                               if (cmdline == NULL) {
+                               if (cmdline == nullptr) {
                                        ret = CMD_ERROR;
                                        goto error;
                                }
@@ -700,12 +717,12 @@ end:
  * Machine interface
  * List all ust event with their fields
  */
-static int mi_list_ust_event_fields(struct lttng_event_field *fields, int count,
-               struct lttng_domain *domain)
+static int
+mi_list_ust_event_fields(struct lttng_event_field *fields, int count, struct lttng_domain *domain)
 {
        int ret, i;
        pid_t cur_pid = 0;
-       char *cmdline = NULL;
+       char *cmdline = nullptr;
        int pid_element_open = 0;
        int event_element_open = 0;
        struct lttng_event cur_event;
@@ -735,16 +752,14 @@ static int mi_list_ust_event_fields(struct lttng_event_field *fields, int count,
                        if (pid_element_open) {
                                if (event_element_open) {
                                        /* Close the previous field element and event. */
-                                       ret = mi_lttng_close_multi_element(
-                                                       the_writer, 2);
+                                       ret = mi_lttng_close_multi_element(the_writer, 2);
                                        if (ret) {
                                                goto end;
                                        }
                                        event_element_open = 0;
                                }
                                /* Close the previous events, pid element */
-                               ret = mi_lttng_close_multi_element(
-                                               the_writer, 2);
+                               ret = mi_lttng_close_multi_element(the_writer, 2);
                                if (ret) {
                                        goto end;
                                }
@@ -755,8 +770,7 @@ static int mi_list_ust_event_fields(struct lttng_event_field *fields, int count,
                        cmdline = get_cmdline_by_pid(cur_pid);
                        if (!pid_element_open) {
                                /* Open and write a pid element */
-                               ret = mi_lttng_pid(the_writer, cur_pid, cmdline,
-                                               1);
+                               ret = mi_lttng_pid(the_writer, cur_pid, cmdline, 1);
                                if (ret) {
                                        goto error;
                                }
@@ -776,21 +790,19 @@ static int mi_list_ust_event_fields(struct lttng_event_field *fields, int count,
                if (strcmp(cur_event.name, fields[i].event.name) != 0) {
                        if (event_element_open) {
                                /* Close the previous fields element and the previous event */
-                               ret = mi_lttng_close_multi_element(
-                                               the_writer, 2);
+                               ret = mi_lttng_close_multi_element(the_writer, 2);
                                if (ret) {
                                        goto end;
                                }
                                event_element_open = 0;
                        }
 
-                       memcpy(&cur_event, &fields[i].event,
-                                       sizeof(cur_event));
+                       memcpy(&cur_event, &fields[i].event, sizeof(cur_event));
 
                        if (!event_element_open) {
                                /* Open and write the event */
-                               ret = mi_lttng_event(the_writer, &cur_event, 1,
-                                               the_handle->domain.type);
+                               ret = mi_lttng_event(
+                                       the_writer, &cur_event, 1, the_handle->domain.type);
                                if (ret) {
                                        goto end;
                                }
@@ -823,14 +835,14 @@ error:
 /*
  * Ask session daemon for all user space tracepoint fields available.
  */
-static int list_ust_event_fields(void)
+static int list_ust_event_fields()
 {
        int i, size, ret = CMD_SUCCESS;
        struct lttng_domain domain;
        struct lttng_handle *handle;
        struct lttng_event_field *event_field_list;
        pid_t cur_pid = 0;
-       char *cmdline = NULL;
+       char *cmdline = nullptr;
 
        struct lttng_event cur_event;
 
@@ -841,8 +853,8 @@ static int list_ust_event_fields(void)
 
        domain.type = LTTNG_DOMAIN_UST;
 
-       handle = lttng_create_handle(NULL, &domain);
-       if (handle == NULL) {
+       handle = lttng_create_handle(nullptr, &domain);
+       if (handle == nullptr) {
                ret = CMD_ERROR;
                goto end;
        }
@@ -873,7 +885,7 @@ static int list_ust_event_fields(void)
                        if (cur_pid != event_field_list[i].event.pid) {
                                cur_pid = event_field_list[i].event.pid;
                                cmdline = get_cmdline_by_pid(cur_pid);
-                               if (cmdline == NULL) {
+                               if (cmdline == nullptr) {
                                        ret = CMD_ERROR;
                                        goto error;
                                }
@@ -884,8 +896,7 @@ static int list_ust_event_fields(void)
                        }
                        if (strcmp(cur_event.name, event_field_list[i].event.name) != 0) {
                                print_events(&event_field_list[i].event);
-                               memcpy(&cur_event, &event_field_list[i].event,
-                                               sizeof(cur_event));
+                               memcpy(&cur_event, &event_field_list[i].event, sizeof(cur_event));
                        }
                        print_event_field(&event_field_list[i]);
                }
@@ -904,8 +915,7 @@ end:
  * Machine interface
  * Print a list of kernel events
  */
-static int mi_list_kernel_events(struct lttng_event *events, int count,
-               struct lttng_domain *domain)
+static int mi_list_kernel_events(struct lttng_event *events, int count, struct lttng_domain *domain)
 {
        int ret, i;
 
@@ -928,8 +938,7 @@ static int mi_list_kernel_events(struct lttng_event *events, int count,
        }
 
        for (i = 0; i < count; i++) {
-               ret = mi_lttng_event(the_writer, &events[i], 0,
-                               the_handle->domain.type);
+               ret = mi_lttng_event(the_writer, &events[i], 0, the_handle->domain.type);
                if (ret) {
                        goto end;
                }
@@ -948,7 +957,7 @@ end:
 /*
  * Ask for all trace events in the kernel
  */
-static int list_kernel_events(void)
+static int list_kernel_events()
 {
        int i, size, ret = CMD_SUCCESS;
        struct lttng_domain domain;
@@ -961,8 +970,8 @@ static int list_kernel_events(void)
 
        domain.type = LTTNG_DOMAIN_KERNEL;
 
-       handle = lttng_create_handle(NULL, &domain);
-       if (handle == NULL) {
+       handle = lttng_create_handle(nullptr, &domain);
+       if (handle == nullptr) {
                ret = CMD_ERROR;
                goto error;
        }
@@ -1017,8 +1026,7 @@ static int mi_list_syscalls(struct lttng_event *events, int count)
        }
 
        for (i = 0; i < count; i++) {
-               ret = mi_lttng_event(the_writer, &events[i], 0,
-                               the_handle->domain.type);
+               ret = mi_lttng_event(the_writer, &events[i], 0, the_handle->domain.type);
                if (ret) {
                        goto end;
                }
@@ -1037,7 +1045,7 @@ end:
 /*
  * Ask for kernel system calls.
  */
-static int list_syscalls(void)
+static int list_syscalls()
 {
        int i, size, ret = CMD_SUCCESS;
        struct lttng_event *event_list;
@@ -1091,8 +1099,7 @@ static int mi_list_session_agent_events(struct lttng_event *events, int count)
        }
 
        for (i = 0; i < count; i++) {
-               ret = mi_lttng_event(the_writer, &events[i], 0,
-                               the_handle->domain.type);
+               ret = mi_lttng_event(the_writer, &events[i], 0, the_handle->domain.type);
                if (ret) {
                        goto end;
                }
@@ -1110,10 +1117,10 @@ end:
  *
  * Return CMD_SUCCESS on success else a negative value.
  */
-static int list_session_agent_events(void)
+static int list_session_agent_events()
 {
        int ret = CMD_SUCCESS, count, i;
-       struct lttng_event *events = NULL;
+       struct lttng_event *events = nullptr;
 
        count = lttng_list_events(the_handle, "", &events);
        if (count < 0) {
@@ -1139,35 +1146,33 @@ static int list_session_agent_events(void)
 
                for (i = 0; i < count; i++) {
                        const char *filter_str;
-                       char *filter_msg = NULL;
+                       char *filter_msg = nullptr;
                        struct lttng_event *event = &events[i];
 
-                       ret = lttng_event_get_filter_expression(event,
-                                       &filter_str);
+                       ret = lttng_event_get_filter_expression(event, &filter_str);
                        if (ret) {
                                filter_msg = strdup(" [failed to retrieve filter]");
                        } else if (filter_str) {
                                if (asprintf(&filter_msg, " [filter: '%s']", filter_str) == -1) {
-                                       filter_msg = NULL;
+                                       filter_msg = nullptr;
                                }
                        }
 
-                       if (event->loglevel_type !=
-                                       LTTNG_EVENT_LOGLEVEL_ALL) {
-                               MSG("%s- %s%s (loglevel%s %s)%s", indent4,
-                                               event->name,
-                                               enabled_string(event->enabled),
-                                               logleveltype_string(
-                                                               event->loglevel_type),
-                                               mi_lttng_loglevel_string(
-                                                               event->loglevel,
-                                                               the_handle->domain
-                                                                               .type),
-                                               safe_string(filter_msg));
+                       if (event->loglevel_type != LTTNG_EVENT_LOGLEVEL_ALL) {
+                               MSG("%s- %s%s (loglevel%s %s)%s",
+                                   indent4,
+                                   event->name,
+                                   enabled_string(event->enabled),
+                                   logleveltype_string(event->loglevel_type),
+                                   mi_lttng_loglevel_string(event->loglevel,
+                                                            the_handle->domain.type),
+                                   safe_string(filter_msg));
                        } else {
-                               MSG("%s- %s%s%s", indent4, event->name,
-                                               enabled_string(event->enabled),
-                                               safe_string(filter_msg));
+                               MSG("%s- %s%s%s",
+                                   indent4,
+                                   event->name,
+                                   enabled_string(event->enabled),
+                                   safe_string(filter_msg));
                        }
                        free(filter_msg);
                }
@@ -1196,8 +1201,7 @@ static int mi_list_events(struct lttng_event *events, int count)
        }
 
        for (i = 0; i < count; i++) {
-               ret = mi_lttng_event(the_writer, &events[i], 0,
-                               the_handle->domain.type);
+               ret = mi_lttng_event(the_writer, &events[i], 0, the_handle->domain.type);
                if (ret) {
                        goto end;
                }
@@ -1216,7 +1220,7 @@ end:
 static int list_events(const char *channel_name)
 {
        int ret = CMD_SUCCESS, count, i;
-       struct lttng_event *events = NULL;
+       struct lttng_event *events = nullptr;
 
        count = lttng_list_events(the_handle, channel_name, &events);
        if (count < 0) {
@@ -1252,8 +1256,7 @@ error:
        return ret;
 }
 
-static
-void print_timer(const char *timer_name, uint32_t space_count, int64_t value)
+static void print_timer(const char *timer_name, uint32_t space_count, int64_t value)
 {
        uint32_t i;
 
@@ -1278,29 +1281,25 @@ static void print_channel(struct lttng_channel *channel)
        uint64_t discarded_events, lost_packets, monitor_timer_interval;
        int64_t blocking_timeout;
 
-       ret = lttng_channel_get_discarded_event_count(channel,
-                       &discarded_events);
+       ret = lttng_channel_get_discarded_event_count(channel, &discarded_events);
        if (ret) {
                ERR("Failed to retrieve discarded event count of channel");
                return;
        }
 
-       ret = lttng_channel_get_lost_packet_count(channel,
-                       &lost_packets);
+       ret = lttng_channel_get_lost_packet_count(channel, &lost_packets);
        if (ret) {
                ERR("Failed to retrieve lost packet count of channel");
                return;
        }
 
-       ret = lttng_channel_get_monitor_timer_interval(channel,
-                       &monitor_timer_interval);
+       ret = lttng_channel_get_monitor_timer_interval(channel, &monitor_timer_interval);
        if (ret) {
                ERR("Failed to retrieve monitor interval of channel");
                return;
        }
 
-       ret = lttng_channel_get_blocking_timeout(channel,
-                       &blocking_timeout);
+       ret = lttng_channel_get_blocking_timeout(channel, &blocking_timeout);
        if (ret) {
                ERR("Failed to retrieve blocking timeout of channel");
                return;
@@ -1313,34 +1312,35 @@ static void print_channel(struct lttng_channel *channel)
        MSG("%sSub-buffer count: %" PRIu64, indent6, channel->attr.num_subbuf);
 
        print_timer("Switch timer", 5, channel->attr.switch_timer_interval);
-       print_timer("Read timer",  7, channel->attr.read_timer_interval);
+       print_timer("Read timer", 7, channel->attr.read_timer_interval);
        print_timer("Monitor timer", 4, monitor_timer_interval);
 
        if (!channel->attr.overwrite) {
                if (blocking_timeout == -1) {
                        MSG("%sBlocking timeout: infinite", indent6);
                } else {
-                       MSG("%sBlocking timeout: %" PRId64 " %s", indent6,
-                                       blocking_timeout, USEC_UNIT);
+                       MSG("%sBlocking timeout: %" PRId64 " %s",
+                           indent6,
+                           blocking_timeout,
+                           USEC_UNIT);
                }
        }
 
-       MSG("%sTrace file count: %" PRIu64 " per stream", indent6,
-                       channel->attr.tracefile_count == 0 ?
-                               1 : channel->attr.tracefile_count);
-       if (channel->attr.tracefile_size != 0 ) {
-               MSG("%sTrace file size:  %" PRIu64 " bytes", indent6,
-                               channel->attr.tracefile_size);
+       MSG("%sTrace file count: %" PRIu64 " per stream",
+           indent6,
+           channel->attr.tracefile_count == 0 ? 1 : channel->attr.tracefile_count);
+       if (channel->attr.tracefile_size != 0) {
+               MSG("%sTrace file size:  %" PRIu64 " bytes", indent6, channel->attr.tracefile_size);
        } else {
                MSG("%sTrace file size:  %s", indent6, "unlimited");
        }
        switch (channel->attr.output) {
-               case LTTNG_EVENT_SPLICE:
-                       MSG("%sOutput mode:      splice", indent6);
-                       break;
-               case LTTNG_EVENT_MMAP:
-                       MSG("%sOutput mode:      mmap", indent6);
-                       break;
+       case LTTNG_EVENT_SPLICE:
+               MSG("%sOutput mode:      splice", indent6);
+               break;
+       case LTTNG_EVENT_MMAP:
+               MSG("%sOutput mode:      mmap", indent6);
+               break;
        }
 
        MSG("\n%sStatistics:", indent4);
@@ -1376,8 +1376,7 @@ skip_stats_printing:
  * Print a list of channel
  *
  */
-static int mi_list_channels(struct lttng_channel *channels, int count,
-               const char *channel_name)
+static int mi_list_channels(struct lttng_channel *channels, int count, const char *channel_name)
 {
        int i, ret;
        unsigned int chan_found = 0;
@@ -1389,7 +1388,7 @@ static int mi_list_channels(struct lttng_channel *channels, int count,
        }
 
        for (i = 0; i < count; i++) {
-               if (channel_name != NULL) {
+               if (channel_name != nullptr) {
                        if (strncmp(channels[i].name, channel_name, NAME_MAX) == 0) {
                                chan_found = 1;
                        } else {
@@ -1439,9 +1438,9 @@ static int list_channels(const char *channel_name)
 {
        int count, i, ret = CMD_SUCCESS;
        unsigned int chan_found = 0;
-       struct lttng_channel *channels = NULL;
+       struct lttng_channel *channels = nullptr;
 
-       DBG("Listing channel(s) (%s)", channel_name ? : "<all>");
+       DBG("Listing channel(s) (%s)", channel_name ?: "<all>");
 
        count = lttng_list_channels(the_handle, &channels);
        if (count < 0) {
@@ -1479,7 +1478,7 @@ static int list_channels(const char *channel_name)
                }
 
                for (i = 0; i < count; i++) {
-                       if (channel_name != NULL) {
+                       if (channel_name != nullptr) {
                                if (strncmp(channels[i].name, channel_name, NAME_MAX) == 0) {
                                        chan_found = 1;
                                } else {
@@ -1499,7 +1498,7 @@ static int list_channels(const char *channel_name)
                        }
                }
 
-               if (!chan_found && channel_name != NULL) {
+               if (!chan_found && channel_name != nullptr) {
                        ret = CMD_ERROR;
                        ERR("Channel %s not found", channel_name);
                        goto error;
@@ -1530,11 +1529,11 @@ static const char *get_capitalized_process_attr_str(enum lttng_process_attr proc
        default:
                return "Unknown";
        }
-       return NULL;
+       return nullptr;
 }
 
 static int handle_process_attr_status(enum lttng_process_attr process_attr,
-               enum lttng_process_attr_tracker_handle_status status)
+                                     enum lttng_process_attr_tracker_handle_status status)
 {
        int ret = CMD_SUCCESS;
 
@@ -1545,18 +1544,18 @@ static int handle_process_attr_status(enum lttng_process_attr process_attr,
                break;
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_COMMUNICATION_ERROR:
                ERR("Communication occurred while fetching %s tracker",
-                               lttng_process_attr_to_string(process_attr));
+                   lttng_process_attr_to_string(process_attr));
                ret = CMD_ERROR;
                break;
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST:
                ERR("Failed to get the inclusion set of the %s tracker: session `%s` no longer exists",
-                               lttng_process_attr_to_string(process_attr),
-                               the_handle->session_name);
+                   lttng_process_attr_to_string(process_attr),
+                   the_handle->session_name);
                ret = CMD_ERROR;
                break;
        default:
                ERR("Unknown error occurred while fetching the inclusion set of the %s tracker",
-                               lttng_process_attr_to_string(process_attr));
+                   lttng_process_attr_to_string(process_attr));
                ret = CMD_ERROR;
                break;
        }
@@ -1578,11 +1577,10 @@ end:
        return ret;
 }
 
-static inline bool is_value_type_name(
-               enum lttng_process_attr_value_type value_type)
+static inline bool is_value_type_name(enum lttng_process_attr_value_type value_type)
 {
        return value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ||
-              value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME;
+               value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME;
 }
 
 /*
@@ -1597,26 +1595,25 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
        enum lttng_process_attr_tracker_handle_status handle_status;
        enum lttng_process_attr_values_status values_status;
        const struct lttng_process_attr_values *values;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
 
-       ret_code = lttng_session_get_tracker_handle(the_handle->session_name,
-                       the_handle->domain.type, process_attr, &tracker_handle);
+       ret_code = lttng_session_get_tracker_handle(
+               the_handle->session_name, the_handle->domain.type, process_attr, &tracker_handle);
        if (ret_code != LTTNG_OK) {
-               ERR("Failed to get process attribute tracker handle: %s",
-                               lttng_strerror(ret_code));
+               ERR("Failed to get process attribute tracker handle: %s", lttng_strerror(ret_code));
                ret = CMD_ERROR;
                goto end;
        }
 
-       handle_status = lttng_process_attr_tracker_handle_get_inclusion_set(
-                       tracker_handle, &values);
+       handle_status =
+               lttng_process_attr_tracker_handle_get_inclusion_set(tracker_handle, &values);
        ret = handle_process_attr_status(process_attr, handle_status);
        if (ret != CMD_SUCCESS) {
                goto end;
        }
 
-       handle_status = lttng_process_attr_tracker_handle_get_tracking_policy(
-                       tracker_handle, &policy);
+       handle_status =
+               lttng_process_attr_tracker_handle_get_tracking_policy(tracker_handle, &policy);
        ret = handle_process_attr_status(process_attr, handle_status);
        if (ret != CMD_SUCCESS) {
                goto end;
@@ -1624,8 +1621,8 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
 
        {
                char *process_attr_name;
-               const int print_ret = asprintf(&process_attr_name, "%ss:",
-                               get_capitalized_process_attr_str(process_attr));
+               const int print_ret = asprintf(
+                       &process_attr_name, "%ss:", get_capitalized_process_attr_str(process_attr));
 
                if (print_ret == -1) {
                        ret = CMD_FATAL;
@@ -1650,8 +1647,8 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
                goto end;
        default:
                ERR("Unknown tracking policy encoutered while listing the %s process attribute tracker of session `%s`",
-                               lttng_process_attr_to_string(process_attr),
-                               the_handle->session_name);
+                   lttng_process_attr_to_string(process_attr),
+                   the_handle->session_name);
                ret = CMD_FATAL;
                goto end;
        }
@@ -1659,8 +1656,8 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
        values_status = lttng_process_attr_values_get_count(values, &count);
        if (values_status != LTTNG_PROCESS_ATTR_VALUES_STATUS_OK) {
                ERR("Failed to get the count of values in the inclusion set of the %s process attribute tracker of session `%s`",
-                               lttng_process_attr_to_string(process_attr),
-                               the_handle->session_name);
+                   lttng_process_attr_to_string(process_attr),
+                   the_handle->session_name);
                ret = CMD_FATAL;
                goto end;
        }
@@ -1678,8 +1675,7 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
        /* Mi tracker_id element */
        if (the_writer) {
                /* Open tracker_id and targets elements */
-               ret = mi_lttng_process_attribute_tracker_open(
-                               the_writer, process_attr);
+               ret = mi_lttng_process_attribute_tracker_open(the_writer, process_attr);
                if (ret) {
                        goto end;
                }
@@ -1687,8 +1683,7 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
 
        for (i = 0; i < count; i++) {
                const enum lttng_process_attr_value_type value_type =
-                               lttng_process_attr_values_get_type_at_index(
-                                               values, i);
+                       lttng_process_attr_values_get_type_at_index(values, i);
                int64_t integral_value = INT64_MAX;
                const char *name = "error";
 
@@ -1700,8 +1695,7 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
                {
                        pid_t pid;
 
-                       values_status = lttng_process_attr_values_get_pid_at_index(
-                                       values, i, &pid);
+                       values_status = lttng_process_attr_values_get_pid_at_index(values, i, &pid);
                        integral_value = (int64_t) pid;
                        break;
                }
@@ -1709,8 +1703,7 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
                {
                        uid_t uid;
 
-                       values_status = lttng_process_attr_values_get_uid_at_index(
-                                       values, i, &uid);
+                       values_status = lttng_process_attr_values_get_uid_at_index(values, i, &uid);
                        integral_value = (int64_t) uid;
                        break;
                }
@@ -1718,18 +1711,17 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
                {
                        gid_t gid;
 
-                       values_status = lttng_process_attr_values_get_gid_at_index(
-                                       values, i, &gid);
+                       values_status = lttng_process_attr_values_get_gid_at_index(values, i, &gid);
                        integral_value = (int64_t) gid;
                        break;
                }
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME:
-                       values_status = lttng_process_attr_values_get_user_name_at_index(
-                                       values, i, &name);
+                       values_status =
+                               lttng_process_attr_values_get_user_name_at_index(values, i, &name);
                        break;
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME:
-                       values_status = lttng_process_attr_values_get_group_name_at_index(
-                                       values, i, &name);
+                       values_status =
+                               lttng_process_attr_values_get_group_name_at_index(values, i, &name);
                        break;
                default:
                        ret = CMD_ERROR;
@@ -1755,14 +1747,10 @@ static int list_process_attr_tracker(enum lttng_process_attr process_attr)
                /* Mi */
                if (the_writer) {
                        ret = is_value_type_name(value_type) ?
-                                             mi_lttng_string_process_attribute_value(
-                                                       the_writer,
-                                                       process_attr, name,
-                                                       false) :
-                                             mi_lttng_integral_process_attribute_value(
-                                                       the_writer,
-                                                       process_attr,
-                                                       integral_value, false);
+                               mi_lttng_string_process_attribute_value(
+                                       the_writer, process_attr, name, false) :
+                               mi_lttng_integral_process_attribute_value(
+                                       the_writer, process_attr, integral_value, false);
                        if (ret) {
                                goto end;
                        }
@@ -1806,8 +1794,7 @@ static int list_trackers(const struct lttng_domain *domain)
                        goto end;
                }
                /* vpid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
                if (ret) {
                        goto end;
                }
@@ -1817,8 +1804,7 @@ static int list_trackers(const struct lttng_domain *domain)
                        goto end;
                }
                /* vuid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
                if (ret) {
                        goto end;
                }
@@ -1828,28 +1814,24 @@ static int list_trackers(const struct lttng_domain *domain)
                        goto end;
                }
                /* vgid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
                if (ret) {
                        goto end;
                }
                break;
        case LTTNG_DOMAIN_UST:
                /* vpid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
                if (ret) {
                        goto end;
                }
                /* vuid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
                if (ret) {
                        goto end;
                }
                /* vgid tracker */
-               ret = list_process_attr_tracker(
-                               LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
+               ret = list_process_attr_tracker(LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
                if (ret) {
                        goto end;
                }
@@ -1870,50 +1852,47 @@ end:
        return ret;
 }
 
-static enum cmd_error_code print_periodic_rotation_schedule(
-               const struct lttng_rotation_schedule *schedule)
+static enum cmd_error_code
+print_periodic_rotation_schedule(const struct lttng_rotation_schedule *schedule)
 {
        enum cmd_error_code ret;
        enum lttng_rotation_status status;
        uint64_t value;
 
-       status = lttng_rotation_schedule_periodic_get_period(schedule,
-                       &value);
+       status = lttng_rotation_schedule_periodic_get_period(schedule, &value);
        if (status != LTTNG_ROTATION_STATUS_OK) {
                ERR("Failed to retrieve period parameter from periodic rotation schedule.");
                ret = CMD_ERROR;
                goto end;
        }
 
-       MSG("    timer period: %" PRIu64" %s", value, USEC_UNIT);
+       MSG("    timer period: %" PRIu64 " %s", value, USEC_UNIT);
        ret = CMD_SUCCESS;
 end:
        return ret;
 }
 
-static enum cmd_error_code print_size_threshold_rotation_schedule(
-               const struct lttng_rotation_schedule *schedule)
+static enum cmd_error_code
+print_size_threshold_rotation_schedule(const struct lttng_rotation_schedule *schedule)
 {
        enum cmd_error_code ret;
        enum lttng_rotation_status status;
        uint64_t value;
 
-       status = lttng_rotation_schedule_size_threshold_get_threshold(schedule,
-                       &value);
+       status = lttng_rotation_schedule_size_threshold_get_threshold(schedule, &value);
        if (status != LTTNG_ROTATION_STATUS_OK) {
                ERR("Failed to retrieve size parameter from size-based rotation schedule.");
                ret = CMD_ERROR;
                goto end;
        }
 
-       MSG("    size threshold: %" PRIu64" bytes", value);
+       MSG("    size threshold: %" PRIu64 " bytes", value);
        ret = CMD_SUCCESS;
 end:
        return ret;
 }
 
-static enum cmd_error_code print_rotation_schedule(
-               const struct lttng_rotation_schedule *schedule)
+static enum cmd_error_code print_rotation_schedule(const struct lttng_rotation_schedule *schedule)
 {
        enum cmd_error_code ret;
 
@@ -1938,7 +1917,7 @@ static enum cmd_error_code list_rotate_settings(const char *session_name)
        int ret;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        unsigned int count, i;
-       struct lttng_rotation_schedules *schedules = NULL;
+       struct lttng_rotation_schedules *schedules = nullptr;
        enum lttng_rotation_status status;
 
        ret = lttng_session_list_rotation_schedules(session_name, &schedules);
@@ -1962,8 +1941,7 @@ static enum cmd_error_code list_rotate_settings(const char *session_name)
 
        MSG("Automatic rotation schedules:");
        if (lttng_opt_mi) {
-               ret = mi_lttng_writer_open_element(the_writer,
-                               mi_lttng_element_rotation_schedules);
+               ret = mi_lttng_writer_open_element(the_writer, mi_lttng_element_rotation_schedules);
                if (ret) {
                        cmd_ret = CMD_ERROR;
                        goto end;
@@ -2016,13 +1994,12 @@ end:
  * Find the session with session_name as name
  * and print his informations.
  */
-static int mi_list_session(const char *session_name,
-               struct lttng_session *sessions, int count)
+static int mi_list_session(const char *session_name, struct lttng_session *sessions, int count)
 {
        int ret, i;
        unsigned int session_found = 0;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret = -LTTNG_ERR_SESS_NOT_FOUND;
                goto end;
        }
@@ -2092,7 +2069,7 @@ static int list_sessions(const char *session_name)
        int ret = CMD_SUCCESS;
        int count, i;
        unsigned int session_found = 0;
-       struct lttng_session *sessions = NULL;
+       struct lttng_session *sessions = nullptr;
 
        count = lttng_list_sessions(&sessions);
        DBG("Session count %d", count);
@@ -2104,7 +2081,7 @@ static int list_sessions(const char *session_name)
 
        if (lttng_opt_mi) {
                /* Mi */
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        /* List all sessions */
                        ret = mi_list_sessions(sessions, count);
                } else {
@@ -2122,49 +2099,54 @@ static int list_sessions(const char *session_name)
                        goto end;
                }
 
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        MSG("Available recording sessions:");
                }
 
                for (i = 0; i < count; i++) {
-                       if (session_name != NULL) {
+                       if (session_name != nullptr) {
                                if (strncmp(sessions[i].name, session_name, NAME_MAX) == 0) {
                                        session_found = 1;
-                                       MSG("Recording session %s: [%s%s]", session_name,
-                                                       active_string(sessions[i].enabled),
-                                                       snapshot_string(sessions[i].snapshot_mode));
+                                       MSG("Recording session %s: [%s%s]",
+                                           session_name,
+                                           active_string(sessions[i].enabled),
+                                           snapshot_string(sessions[i].snapshot_mode));
                                        if (*sessions[i].path) {
-                                               MSG("%sTrace output: %s\n", indent4, sessions[i].path);
+                                               MSG("%sTrace output: %s\n",
+                                                   indent4,
+                                                   sessions[i].path);
                                        }
                                        memcpy(&the_listed_session,
-                                                       &sessions[i],
-                                                       sizeof(the_listed_session));
+                                              &sessions[i],
+                                              sizeof(the_listed_session));
                                        break;
                                }
                        } else {
-                               MSG("  %d) %s [%s%s]", i + 1,
-                                               sessions[i].name,
-                                               active_string(sessions[i].enabled),
-                                               snapshot_string(sessions[i].snapshot_mode));
+                               MSG("  %d) %s [%s%s]",
+                                   i + 1,
+                                   sessions[i].name,
+                                   active_string(sessions[i].enabled),
+                                   snapshot_string(sessions[i].snapshot_mode));
                                if (*sessions[i].path) {
                                        MSG("%sTrace output: %s", indent4, sessions[i].path);
                                }
                                if (sessions[i].live_timer_interval != 0) {
-                                       MSG("%sLive timer interval: %u %s", indent4,
-                                                       sessions[i].live_timer_interval,
-                                                       USEC_UNIT);
+                                       MSG("%sLive timer interval: %u %s",
+                                           indent4,
+                                           sessions[i].live_timer_interval,
+                                           USEC_UNIT);
                                }
                                MSG("");
                        }
                }
 
-               if (!session_found && session_name != NULL) {
+               if (!session_found && session_name != nullptr) {
                        ERR("Session '%s' not found", session_name);
                        ret = CMD_ERROR;
                        goto end;
                }
 
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        MSG("\nUse lttng list <session_name> for more details");
                }
        }
@@ -2174,7 +2156,6 @@ end:
        return ret;
 }
 
-
 /*
  * Machine Interface
  * list available domain(s) for a session.
@@ -2210,8 +2191,7 @@ end:
 static int list_domains(const char *session_name)
 {
        int i, count, ret = CMD_SUCCESS;
-       struct lttng_domain *domains = NULL;
-
+       struct lttng_domain *domains = nullptr;
 
        count = lttng_list_domains(session_name, &domains);
        if (count < 0) {
@@ -2271,10 +2251,10 @@ end:
 int cmd_list(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS;
-       const char *session_name, *leftover = NULL;
+       const char *arg_session_name, *leftover = nullptr;
        static poptContext pc;
        struct lttng_domain domain;
-       struct lttng_domain *domains = NULL;
+       struct lttng_domain *domains = nullptr;
 
        memset(&domain, 0, sizeof(domain));
 
@@ -2283,7 +2263,7 @@ int cmd_list(int argc, const char **argv)
                goto end;
        }
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -2305,24 +2285,21 @@ int cmd_list(int argc, const char **argv)
 
        /* Mi check */
        if (lttng_opt_mi) {
-               the_writer = mi_lttng_writer_create(
-                               fileno(stdout), lttng_opt_mi);
+               the_writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!the_writer) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(
-                               the_writer, mi_lttng_element_command_list);
+               ret = mi_lttng_writer_command_open(the_writer, mi_lttng_element_command_list);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(
-                               the_writer, mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(the_writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -2330,8 +2307,8 @@ int cmd_list(int argc, const char **argv)
        }
 
        /* Get session name (trailing argument) */
-       session_name = poptGetArg(pc);
-       DBG2("Session name: %s", session_name);
+       arg_session_name = poptGetArg(pc);
+       DBG2("Session name: %s", arg_session_name);
 
        leftover = poptGetArg(pc);
        if (leftover) {
@@ -2361,17 +2338,16 @@ int cmd_list(int argc, const char **argv)
        }
 
        if (opt_kernel || opt_userspace || opt_jul || opt_log4j || opt_python) {
-               the_handle = lttng_create_handle(session_name, &domain);
-               if (the_handle == NULL) {
+               the_handle = lttng_create_handle(arg_session_name, &domain);
+               if (the_handle == nullptr) {
                        ret = CMD_FATAL;
                        goto end;
                }
        }
 
-       if (session_name == NULL) {
-               if (!opt_kernel && !opt_userspace && !opt_jul && !opt_log4j
-                               && !opt_python) {
-                       ret = list_sessions(NULL);
+       if (arg_session_name == nullptr) {
+               if (!opt_kernel && !opt_userspace && !opt_jul && !opt_log4j && !opt_python) {
+                       ret = list_sessions(nullptr);
                        if (ret) {
                                goto end;
                        }
@@ -2416,19 +2392,19 @@ int cmd_list(int argc, const char **argv)
                        }
                }
                /* MI: the ouptut of list_sessions is an unclosed session element */
-               ret = list_sessions(session_name);
+               ret = list_sessions(arg_session_name);
                if (ret) {
                        goto end;
                }
 
-               ret = list_rotate_settings(session_name);
+               ret = list_rotate_settings(arg_session_name);
                if (ret) {
                        goto end;
                }
 
                /* Domain listing */
                if (opt_domain) {
-                       ret = list_domains(session_name);
+                       ret = list_domains(arg_session_name);
                        goto end;
                }
 
@@ -2449,10 +2425,8 @@ int cmd_list(int argc, const char **argv)
                                if (ret) {
                                        goto end;
                                }
-
                        }
 
-
                        /* Trackers */
                        ret = list_trackers(&domain);
                        if (ret) {
@@ -2467,19 +2441,17 @@ int cmd_list(int argc, const char **argv)
 
                        if (lttng_opt_mi) {
                                /* Close domain and domain element */
-                               ret = mi_lttng_close_multi_element(
-                                               the_writer, 2);
+                               ret = mi_lttng_close_multi_element(the_writer, 2);
                        }
                        if (ret) {
                                goto end;
                        }
 
-
                } else {
                        int i, nb_domain;
 
                        /* We want all domain(s) */
-                       nb_domain = lttng_list_domains(session_name, &domains);
+                       nb_domain = lttng_list_domains(arg_session_name, &domains);
                        if (nb_domain < 0) {
                                ret = CMD_ERROR;
                                ERR("%s", lttng_strerror(nb_domain));
@@ -2502,8 +2474,9 @@ int cmd_list(int argc, const char **argv)
                                case LTTNG_DOMAIN_UST:
                                        MSG("=== Domain: User space ===\n");
                                        MSG("Buffering scheme: %s\n",
-                                                       domains[i].buf_type ==
-                                                       LTTNG_BUFFER_PER_PID ? "per-process" : "per-user");
+                                           domains[i].buf_type == LTTNG_BUFFER_PER_PID ?
+                                                   "per-process" :
+                                                   "per-user");
                                        break;
                                case LTTNG_DOMAIN_JUL:
                                        MSG("=== Domain: java.util.logging (JUL) ===\n");
@@ -2520,8 +2493,7 @@ int cmd_list(int argc, const char **argv)
                                }
 
                                if (lttng_opt_mi) {
-                                       ret = mi_lttng_domain(the_writer,
-                                                       &domains[i], 1);
+                                       ret = mi_lttng_domain(the_writer, &domains[i], 1);
                                        if (ret) {
                                                ret = CMD_ERROR;
                                                goto end;
@@ -2533,16 +2505,15 @@ int cmd_list(int argc, const char **argv)
                                        lttng_destroy_handle(the_handle);
                                }
 
-                               the_handle = lttng_create_handle(
-                                               session_name, &domains[i]);
-                               if (the_handle == NULL) {
+                               the_handle = lttng_create_handle(arg_session_name, &domains[i]);
+                               if (the_handle == nullptr) {
                                        ret = CMD_FATAL;
                                        goto end;
                                }
 
                                if (domains[i].type == LTTNG_DOMAIN_JUL ||
-                                               domains[i].type == LTTNG_DOMAIN_LOG4J ||
-                                               domains[i].type == LTTNG_DOMAIN_PYTHON) {
+                                   domains[i].type == LTTNG_DOMAIN_LOG4J ||
+                                   domains[i].type == LTTNG_DOMAIN_PYTHON) {
                                        ret = list_session_agent_events();
                                        if (ret) {
                                                goto end;
@@ -2568,22 +2539,19 @@ int cmd_list(int argc, const char **argv)
                                        goto end;
                                }
 
-next_domain:
+                       next_domain:
                                if (lttng_opt_mi) {
                                        /* Close domain element */
-                                       ret = mi_lttng_writer_close_element(
-                                                       the_writer);
+                                       ret = mi_lttng_writer_close_element(the_writer);
                                        if (ret) {
                                                ret = CMD_ERROR;
                                                goto end;
                                        }
                                }
-
                        }
                        if (lttng_opt_mi) {
                                /* Close the domains, session and sessions element */
-                               ret = mi_lttng_close_multi_element(
-                                               the_writer, 3);
+                               ret = mi_lttng_close_multi_element(the_writer, 3);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
index e7075844520eaeb7da3a90f086545e047969ac5c..03e567c86d449c317f91df4fd1dd67de04dc014a 100644 (file)
@@ -5,99 +5,91 @@
  *
  */
 
-#include <stdio.h>
-
 #include "../command.hpp"
-
-#include "common/argpar/argpar.h"
 #include "common/argpar-utils/argpar-utils.hpp"
+#include "common/argpar/argpar.h"
 #include "common/dynamic-array.hpp"
 #include "common/mi-lttng.hpp"
+#include "lttng/action/list-internal.hpp"
+
 /* For lttng_condition_type_str(). */
 #include "lttng/condition/condition-internal.hpp"
-#include "lttng/condition/event-rule-matches.h"
 #include "lttng/condition/event-rule-matches-internal.hpp"
+#include "lttng/condition/event-rule-matches.h"
+
 /* For lttng_domain_type_str(). */
 #include "lttng/domain-internal.hpp"
+
 /* For lttng_event_rule_kernel_syscall_emission_site_str() */
-#include "lttng/event-rule/kernel-syscall-internal.hpp"
 #include "../loglevel.hpp"
+#include "lttng/event-rule/kernel-syscall-internal.hpp"
+
 #include <lttng/lttng.h>
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-list-triggers.1.h>
-;
+       ;
 #endif
 
 #define INDENTATION_LEVEL_STR "  "
 
-typedef enum lttng_event_rule_status (*event_rule_logging_get_name_pattern)(
-               const struct lttng_event_rule *rule, const char **pattern);
-typedef enum lttng_event_rule_status (*event_rule_logging_get_filter)(
-               const struct lttng_event_rule *rule, const char **expression);
-typedef enum lttng_event_rule_status (*event_rule_logging_get_log_level_rule)(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule);
+using event_rule_logging_get_name_pattern =
+       enum lttng_event_rule_status (*)(const struct lttng_event_rule *, const char **);
+using event_rule_logging_get_filter =
+       enum lttng_event_rule_status (*)(const struct lttng_event_rule *, const char **);
+using event_rule_logging_get_log_level_rule = enum lttng_event_rule_status (*)(
+       const struct lttng_event_rule *, const struct lttng_log_level_rule **);
 
 enum {
        OPT_HELP,
        OPT_LIST_OPTIONS,
 };
 
-static const
-struct argpar_opt_descr list_trigger_options[] = {
+static const struct argpar_opt_descr list_trigger_options[] = {
        { OPT_HELP, 'h', "help", false },
        { OPT_LIST_OPTIONS, '\0', "list-options", false },
        ARGPAR_OPT_DESCR_SENTINEL,
 };
 
-static void print_condition_session_consumed_size(
-               const struct lttng_condition *condition)
+static void print_condition_session_consumed_size(const struct lttng_condition *condition)
 {
        enum lttng_condition_status condition_status;
        const char *session_name;
        uint64_t threshold;
 
        condition_status =
-                       lttng_condition_session_consumed_size_get_session_name(
-                                       condition, &session_name);
+               lttng_condition_session_consumed_size_get_session_name(condition, &session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
-       lttng_condition_session_consumed_size_get_threshold(
-                       condition, &threshold);
+       lttng_condition_session_consumed_size_get_threshold(condition, &threshold);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        MSG("    session name: %s", session_name);
        MSG("    threshold: %" PRIu64 " bytes", threshold);
 }
 
-static void print_condition_buffer_usage(
-               const struct lttng_condition *condition)
+static void print_condition_buffer_usage(const struct lttng_condition *condition)
 {
        enum lttng_condition_status condition_status;
        const char *session_name, *channel_name;
        enum lttng_domain_type domain_type;
        uint64_t threshold;
 
-       condition_status = lttng_condition_buffer_usage_get_session_name(
-                       condition, &session_name);
+       condition_status = lttng_condition_buffer_usage_get_session_name(condition, &session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
-       condition_status = lttng_condition_buffer_usage_get_channel_name(
-                       condition, &channel_name);
+       condition_status = lttng_condition_buffer_usage_get_channel_name(condition, &channel_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
-       condition_status = lttng_condition_buffer_usage_get_domain_type(
-                       condition, &domain_type);
+       condition_status = lttng_condition_buffer_usage_get_domain_type(condition, &domain_type);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        MSG("    session name: %s", session_name);
        MSG("    channel name: %s", channel_name);
        MSG("    domain: %s", lttng_domain_type_str(domain_type));
 
-       condition_status = lttng_condition_buffer_usage_get_threshold(
-                       condition, &threshold);
+       condition_status = lttng_condition_buffer_usage_get_threshold(condition, &threshold);
        if (condition_status == LTTNG_CONDITION_STATUS_OK) {
                MSG("    threshold (bytes): %" PRIu64, threshold);
        } else {
@@ -105,23 +97,21 @@ static void print_condition_buffer_usage(
 
                LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_UNSET);
 
-               condition_status =
-                               lttng_condition_buffer_usage_get_threshold_ratio(
-                                               condition, &threshold_ratio);
+               condition_status = lttng_condition_buffer_usage_get_threshold_ratio(
+                       condition, &threshold_ratio);
                LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
                MSG("    threshold (ratio): %.2f", threshold_ratio);
        }
 }
 
-static void print_condition_session_rotation(
-               const struct lttng_condition *condition)
+static void print_condition_session_rotation(const struct lttng_condition *condition)
 {
        enum lttng_condition_status condition_status;
        const char *session_name;
 
-       condition_status = lttng_condition_session_rotation_get_session_name(
-                       condition, &session_name);
+       condition_status =
+               lttng_condition_session_rotation_get_session_name(condition, &session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        MSG("    session name: %s", session_name);
@@ -133,10 +123,10 @@ static void print_condition_session_rotation(
  * values (a value can fall between two labels). In those cases, NULL is
  * returned.
  */
-static const char *get_pretty_loglevel_name(
-               enum lttng_event_rule_type event_rule_type, int loglevel)
+static const char *get_pretty_loglevel_name(enum lttng_event_rule_type event_rule_type,
+                                           int loglevel)
 {
-       const char *name = NULL;
+       const char *name = nullptr;
 
        switch (event_rule_type) {
        case LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT:
@@ -158,33 +148,30 @@ static const char *get_pretty_loglevel_name(
        return name;
 }
 
-static
-void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
+static void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
 {
        enum lttng_event_rule_status event_rule_status;
        const char *pattern;
        const char *filter;
        int log_level;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
        unsigned int exclusions_count;
        int i;
 
-       event_rule_status = lttng_event_rule_user_tracepoint_get_name_pattern(
-                       event_rule, &pattern);
+       event_rule_status = lttng_event_rule_user_tracepoint_get_name_pattern(event_rule, &pattern);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
        _MSG("    rule: %s (type: user tracepoint", pattern);
 
-       event_rule_status = lttng_event_rule_user_tracepoint_get_filter(
-                       event_rule, &filter);
+       event_rule_status = lttng_event_rule_user_tracepoint_get_filter(event_rule, &filter);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                _MSG(", filter: %s", filter);
        } else {
                LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_UNSET);
        }
 
-       event_rule_status = lttng_event_rule_user_tracepoint_get_log_level_rule(
-                       event_rule, &log_level_rule);
+       event_rule_status =
+               lttng_event_rule_user_tracepoint_get_log_level_rule(event_rule, &log_level_rule);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
                const char *log_level_op;
@@ -193,13 +180,13 @@ void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
                switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
                        log_level_op = "is";
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &log_level);
+                       llr_status =
+                               lttng_log_level_rule_exactly_get_level(log_level_rule, &log_level);
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        log_level_op = "at least";
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &log_level);
+                               log_level_rule, &log_level);
                        break;
                default:
                        abort();
@@ -207,11 +194,10 @@ void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
 
                LTTNG_ASSERT(llr_status == LTTNG_LOG_LEVEL_RULE_STATUS_OK);
 
-               pretty_loglevel_name = get_pretty_loglevel_name(
-                               LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT, log_level);
+               pretty_loglevel_name =
+                       get_pretty_loglevel_name(LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT, log_level);
                if (pretty_loglevel_name) {
-                       _MSG(", log level %s %s", log_level_op,
-                                       pretty_loglevel_name);
+                       _MSG(", log level %s %s", log_level_op, pretty_loglevel_name);
                } else {
                        _MSG(", log level %s %d", log_level_op, log_level);
                }
@@ -220,14 +206,15 @@ void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
        }
 
        event_rule_status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-                       event_rule, &exclusions_count);
+               event_rule, &exclusions_count);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
        if (exclusions_count > 0) {
                _MSG(", exclusions: ");
                for (i = 0; i < exclusions_count; i++) {
                        const char *exclusion;
 
-                       event_rule_status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
+                       event_rule_status =
+                               lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
                                        event_rule, i, &exclusion);
                        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
@@ -238,21 +225,19 @@ void print_event_rule_user_tracepoint(const struct lttng_event_rule *event_rule)
        MSG(")");
 }
 
-static
-void print_event_rule_kernel_tracepoint(const struct lttng_event_rule *event_rule)
+static void print_event_rule_kernel_tracepoint(const struct lttng_event_rule *event_rule)
 {
        enum lttng_event_rule_status event_rule_status;
        const char *pattern;
        const char *filter;
 
-       event_rule_status = lttng_event_rule_kernel_tracepoint_get_name_pattern(
-                       event_rule, &pattern);
+       event_rule_status =
+               lttng_event_rule_kernel_tracepoint_get_name_pattern(event_rule, &pattern);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
        _MSG("    rule: %s (type: kernel tracepoint", pattern);
 
-       event_rule_status = lttng_event_rule_kernel_tracepoint_get_filter(
-                       event_rule, &filter);
+       event_rule_status = lttng_event_rule_kernel_tracepoint_get_filter(event_rule, &filter);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                _MSG(", filter: %s", filter);
        } else {
@@ -262,16 +247,15 @@ void print_event_rule_kernel_tracepoint(const struct lttng_event_rule *event_rul
        MSG(")");
 }
 
-static
-void print_event_rule_logging(const struct lttng_event_rule *event_rule)
+static void print_event_rule_logging(const struct lttng_event_rule *event_rule)
 {
        enum lttng_event_rule_status event_rule_status;
        enum lttng_event_rule_type event_rule_type = lttng_event_rule_get_type(event_rule);
        const char *pattern;
        const char *filter;
        int log_level;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
-       const char *type_str = NULL;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
+       const char *type_str = nullptr;
 
        event_rule_logging_get_name_pattern logging_get_name_pattern;
        event_rule_logging_get_filter logging_get_filter;
@@ -279,27 +263,21 @@ void print_event_rule_logging(const struct lttng_event_rule *event_rule)
 
        switch (event_rule_type) {
        case LTTNG_EVENT_RULE_TYPE_JUL_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_jul_logging_get_name_pattern;
+               logging_get_name_pattern = lttng_event_rule_jul_logging_get_name_pattern;
                logging_get_filter = lttng_event_rule_jul_logging_get_filter;
-               logging_get_log_level_rule =
-                               lttng_event_rule_jul_logging_get_log_level_rule;
+               logging_get_log_level_rule = lttng_event_rule_jul_logging_get_log_level_rule;
                type_str = "jul";
                break;
        case LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_log4j_logging_get_name_pattern;
+               logging_get_name_pattern = lttng_event_rule_log4j_logging_get_name_pattern;
                logging_get_filter = lttng_event_rule_log4j_logging_get_filter;
-               logging_get_log_level_rule =
-                               lttng_event_rule_log4j_logging_get_log_level_rule;
+               logging_get_log_level_rule = lttng_event_rule_log4j_logging_get_log_level_rule;
                type_str = "log4j";
                break;
        case LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING:
-               logging_get_name_pattern =
-                               lttng_event_rule_python_logging_get_name_pattern;
+               logging_get_name_pattern = lttng_event_rule_python_logging_get_name_pattern;
                logging_get_filter = lttng_event_rule_python_logging_get_filter;
-               logging_get_log_level_rule =
-                               lttng_event_rule_python_logging_get_log_level_rule;
+               logging_get_log_level_rule = lttng_event_rule_python_logging_get_log_level_rule;
                type_str = "python";
                break;
        default:
@@ -307,22 +285,19 @@ void print_event_rule_logging(const struct lttng_event_rule *event_rule)
                break;
        }
 
-       event_rule_status = logging_get_name_pattern(
-                       event_rule, &pattern);
+       event_rule_status = logging_get_name_pattern(event_rule, &pattern);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
        _MSG("    rule: %s (type: %s:logging", pattern, type_str);
 
-       event_rule_status = logging_get_filter(
-                       event_rule, &filter);
+       event_rule_status = logging_get_filter(event_rule, &filter);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                _MSG(", filter: %s", filter);
        } else {
                LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_UNSET);
        }
 
-       event_rule_status = logging_get_log_level_rule(
-                       event_rule, &log_level_rule);
+       event_rule_status = logging_get_log_level_rule(event_rule, &log_level_rule);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
                const char *log_level_op;
@@ -331,13 +306,13 @@ void print_event_rule_logging(const struct lttng_event_rule *event_rule)
                switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
                        log_level_op = "is";
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &log_level);
+                       llr_status =
+                               lttng_log_level_rule_exactly_get_level(log_level_rule, &log_level);
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        log_level_op = "at least";
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &log_level);
+                               log_level_rule, &log_level);
                        break;
                default:
                        abort();
@@ -345,11 +320,9 @@ void print_event_rule_logging(const struct lttng_event_rule *event_rule)
 
                LTTNG_ASSERT(llr_status == LTTNG_LOG_LEVEL_RULE_STATUS_OK);
 
-               pretty_loglevel_name = get_pretty_loglevel_name(
-                               event_rule_type, log_level);
+               pretty_loglevel_name = get_pretty_loglevel_name(event_rule_type, log_level);
                if (pretty_loglevel_name) {
-                       _MSG(", log level %s %s", log_level_op,
-                                       pretty_loglevel_name);
+                       _MSG(", log level %s %s", log_level_op, pretty_loglevel_name);
                } else {
                        _MSG(", log level %s %d", log_level_op, log_level);
                }
@@ -360,8 +333,7 @@ void print_event_rule_logging(const struct lttng_event_rule *event_rule)
        MSG(")");
 }
 
-static void print_kernel_probe_location(
-               const struct lttng_kernel_probe_location *location)
+static void print_kernel_probe_location(const struct lttng_kernel_probe_location *location)
 {
        enum lttng_kernel_probe_location_status status;
        switch (lttng_kernel_probe_location_get_type(location)) {
@@ -369,8 +341,7 @@ static void print_kernel_probe_location(
        {
                uint64_t address;
 
-               status = lttng_kernel_probe_location_address_get_address(
-                               location, &address);
+               status = lttng_kernel_probe_location_address_get_address(location, &address);
                if (status != LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK) {
                        ERR("Getting kernel probe location address failed.");
                        goto end;
@@ -385,15 +356,13 @@ static void print_kernel_probe_location(
                uint64_t offset;
                const char *symbol_name;
 
-               symbol_name = lttng_kernel_probe_location_symbol_get_name(
-                               location);
+               symbol_name = lttng_kernel_probe_location_symbol_get_name(location);
                if (!symbol_name) {
                        ERR("Getting kernel probe location symbol name failed.");
                        goto end;
                }
 
-               status = lttng_kernel_probe_location_symbol_get_offset(
-                               location, &offset);
+               status = lttng_kernel_probe_location_symbol_get_offset(location, &offset);
                if (status != LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK) {
                        ERR("Getting kernel probe location address failed.");
                        goto end;
@@ -414,8 +383,7 @@ end:
        return;
 }
 
-static
-void print_event_rule_kernel_probe(const struct lttng_event_rule *event_rule)
+static void print_event_rule_kernel_probe(const struct lttng_event_rule *event_rule)
 {
        enum lttng_event_rule_status event_rule_status;
        const char *name;
@@ -429,8 +397,7 @@ void print_event_rule_kernel_probe(const struct lttng_event_rule *event_rule)
                goto end;
        }
 
-       event_rule_status = lttng_event_rule_kernel_kprobe_get_location(
-                       event_rule, &location);
+       event_rule_status = lttng_event_rule_kernel_kprobe_get_location(event_rule, &location);
        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                ERR("Failed to get kprobe event rule's location.");
                goto end;
@@ -446,8 +413,7 @@ end:
        return;
 }
 
-static
-void print_event_rule_userspace_probe(const struct lttng_event_rule *event_rule)
+static void print_event_rule_userspace_probe(const struct lttng_event_rule *event_rule)
 {
        enum lttng_event_rule_status event_rule_status;
        const char *name;
@@ -456,15 +422,13 @@ void print_event_rule_userspace_probe(const struct lttng_event_rule *event_rule)
 
        LTTNG_ASSERT(lttng_event_rule_get_type(event_rule) == LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE);
 
-       event_rule_status = lttng_event_rule_kernel_uprobe_get_event_name(
-                       event_rule, &name);
+       event_rule_status = lttng_event_rule_kernel_uprobe_get_event_name(event_rule, &name);
        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                ERR("Failed to get uprobe event rule's name.");
                goto end;
        }
 
-       event_rule_status = lttng_event_rule_kernel_uprobe_get_location(
-                       event_rule, &location);
+       event_rule_status = lttng_event_rule_kernel_uprobe_get_location(event_rule, &location);
        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                ERR("Failed to get uprobe event rule's location.");
                goto end;
@@ -472,18 +436,15 @@ void print_event_rule_userspace_probe(const struct lttng_event_rule *event_rule)
 
        _MSG("    rule: %s (type: kernel:uprobe, ", name);
 
-       userspace_probe_location_type =
-                       lttng_userspace_probe_location_get_type(location);
+       userspace_probe_location_type = lttng_userspace_probe_location_get_type(location);
 
        switch (userspace_probe_location_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
        {
                const char *binary_path, *function_name;
 
-               binary_path = lttng_userspace_probe_location_function_get_binary_path(
-                               location);
-               function_name = lttng_userspace_probe_location_function_get_function_name(
-                               location);
+               binary_path = lttng_userspace_probe_location_function_get_binary_path(location);
+               function_name = lttng_userspace_probe_location_function_get_function_name(location);
 
                _MSG("location type: ELF, location: %s:%s", binary_path, function_name);
                break;
@@ -492,13 +453,14 @@ void print_event_rule_userspace_probe(const struct lttng_event_rule *event_rule)
        {
                const char *binary_path, *provider_name, *probe_name;
 
-               binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(
-                               location);
-               provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(
-                               location);
-               probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(
-                               location);
-               _MSG("location type: SDT, location: %s:%s:%s", binary_path, provider_name, probe_name);
+               binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(location);
+               provider_name =
+                       lttng_userspace_probe_location_tracepoint_get_provider_name(location);
+               probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(location);
+               _MSG("location type: SDT, location: %s:%s:%s",
+                    binary_path,
+                    provider_name,
+                    probe_name);
                break;
        }
        default:
@@ -511,8 +473,7 @@ end:
        return;
 }
 
-static
-void print_event_rule_syscall(const struct lttng_event_rule *event_rule)
+static void print_event_rule_syscall(const struct lttng_event_rule *event_rule)
 {
        const char *pattern, *filter;
        enum lttng_event_rule_status event_rule_status;
@@ -520,19 +481,16 @@ void print_event_rule_syscall(const struct lttng_event_rule *event_rule)
 
        LTTNG_ASSERT(lttng_event_rule_get_type(event_rule) == LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL);
 
-       emission_site =
-               lttng_event_rule_kernel_syscall_get_emission_site(event_rule);
+       emission_site = lttng_event_rule_kernel_syscall_get_emission_site(event_rule);
 
-       event_rule_status = lttng_event_rule_kernel_syscall_get_name_pattern(
-                       event_rule, &pattern);
+       event_rule_status = lttng_event_rule_kernel_syscall_get_name_pattern(event_rule, &pattern);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
-       _MSG("    rule: %s (type: kernel:syscall:%s", pattern,
-                       lttng_event_rule_kernel_syscall_emission_site_str(
-                                       emission_site));
+       _MSG("    rule: %s (type: kernel:syscall:%s",
+            pattern,
+            lttng_event_rule_kernel_syscall_emission_site_str(emission_site));
 
-       event_rule_status = lttng_event_rule_kernel_syscall_get_filter(
-                       event_rule, &filter);
+       event_rule_status = lttng_event_rule_kernel_syscall_get_filter(event_rule, &filter);
        if (event_rule_status == LTTNG_EVENT_RULE_STATUS_OK) {
                _MSG(", filter: %s", filter);
        } else {
@@ -542,11 +500,9 @@ void print_event_rule_syscall(const struct lttng_event_rule *event_rule)
        MSG(")");
 }
 
-static
-void print_event_rule(const struct lttng_event_rule *event_rule)
+static void print_event_rule(const struct lttng_event_rule *event_rule)
 {
-       const enum lttng_event_rule_type event_rule_type =
-                       lttng_event_rule_get_type(event_rule);
+       const enum lttng_event_rule_type event_rule_type = lttng_event_rule_get_type(event_rule);
 
        switch (event_rule_type) {
        case LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT:
@@ -574,8 +530,7 @@ void print_event_rule(const struct lttng_event_rule *event_rule)
        }
 }
 
-static
-void print_one_event_expr(const struct lttng_event_expr *event_expr)
+static void print_one_event_expr(const struct lttng_event_expr *event_expr)
 {
        enum lttng_event_expr_type type;
 
@@ -586,8 +541,7 @@ void print_one_event_expr(const struct lttng_event_expr *event_expr)
        {
                const char *name;
 
-               name = lttng_event_expr_event_payload_field_get_name(
-                               event_expr);
+               name = lttng_event_expr_event_payload_field_get_name(event_expr);
                _MSG("%s", name);
 
                break;
@@ -596,8 +550,7 @@ void print_one_event_expr(const struct lttng_event_expr *event_expr)
        {
                const char *name;
 
-               name = lttng_event_expr_channel_context_field_get_name(
-                               event_expr);
+               name = lttng_event_expr_channel_context_field_get_name(event_expr);
                _MSG("$ctx.%s", name);
 
                break;
@@ -607,10 +560,9 @@ void print_one_event_expr(const struct lttng_event_expr *event_expr)
                const char *provider_name;
                const char *type_name;
 
-               provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(
-                               event_expr);
-               type_name = lttng_event_expr_app_specific_context_field_get_type_name(
-                               event_expr);
+               provider_name =
+                       lttng_event_expr_app_specific_context_field_get_provider_name(event_expr);
+               type_name = lttng_event_expr_app_specific_context_field_get_type_name(event_expr);
 
                _MSG("$app.%s:%s", provider_name, type_name);
 
@@ -622,14 +574,12 @@ void print_one_event_expr(const struct lttng_event_expr *event_expr)
                const struct lttng_event_expr *parent_expr;
                enum lttng_event_expr_status status;
 
-               parent_expr = lttng_event_expr_array_field_element_get_parent_expr(
-                               event_expr);
-               LTTNG_ASSERT(parent_expr != NULL);
+               parent_expr = lttng_event_expr_array_field_element_get_parent_expr(event_expr);
+               LTTNG_ASSERT(parent_expr != nullptr);
 
                print_one_event_expr(parent_expr);
 
-               status = lttng_event_expr_array_field_element_get_index(
-                               event_expr, &index);
+               status = lttng_event_expr_array_field_element_get_index(event_expr, &index);
                LTTNG_ASSERT(status == LTTNG_EVENT_EXPR_STATUS_OK);
 
                _MSG("[%u]", index);
@@ -641,8 +591,7 @@ void print_one_event_expr(const struct lttng_event_expr *event_expr)
        }
 }
 
-static
-void print_indentation(unsigned int indentation_level)
+static void print_indentation(unsigned int indentation_level)
 {
        unsigned int i;
 
@@ -651,9 +600,8 @@ void print_indentation(unsigned int indentation_level)
        }
 }
 
-static
-void print_error_query_results(struct lttng_error_query_results *results,
-               unsigned int base_indentation_level)
+static void print_error_query_results(struct lttng_error_query_results *results,
+                                     unsigned int base_indentation_level)
 {
        unsigned int i, count, printed_errors_count = 0;
        enum lttng_error_query_results_status results_status;
@@ -673,24 +621,20 @@ void print_error_query_results(struct lttng_error_query_results *results,
                const char *result_description;
                uint64_t result_value;
 
-               results_status = lttng_error_query_results_get_result(
-                               results, &result, i);
+               results_status = lttng_error_query_results_get_result(results, &result, i);
                LTTNG_ASSERT(results_status == LTTNG_ERROR_QUERY_RESULTS_STATUS_OK);
 
-               result_status = lttng_error_query_result_get_name(
-                               result, &result_name);
+               result_status = lttng_error_query_result_get_name(result, &result_name);
                LTTNG_ASSERT(result_status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
-               result_status = lttng_error_query_result_get_description(
-                               result, &result_description);
+               result_status =
+                       lttng_error_query_result_get_description(result, &result_description);
                LTTNG_ASSERT(result_status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
 
-
                if (lttng_error_query_result_get_type(result) ==
-                               LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER) {
-                       result_status = lttng_error_query_result_counter_get_value(
-                                       result, &result_value);
-                       LTTNG_ASSERT(result_status ==
-                                       LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
+                   LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER) {
+                       result_status =
+                               lttng_error_query_result_counter_get_value(result, &result_value);
+                       LTTNG_ASSERT(result_status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
                        if (result_value == 0) {
                                continue;
                        }
@@ -704,7 +648,8 @@ void print_error_query_results(struct lttng_error_query_results *results,
                        MSG("");
                        print_indentation(base_indentation_level + 1);
                        _MSG("Unknown error query result type for result '%s' (%s)",
-                                       result_name, result_description);
+                            result_name,
+                            result_description);
                        continue;
                }
        }
@@ -714,22 +659,19 @@ void print_error_query_results(struct lttng_error_query_results *results,
        }
 }
 
-static void print_condition_event_rule_matches(
-               const struct lttng_condition *condition)
+static void print_condition_event_rule_matches(const struct lttng_condition *condition)
 {
        const struct lttng_event_rule *event_rule;
        enum lttng_condition_status condition_status;
        unsigned int cap_desc_count, i;
 
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &event_rule);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &event_rule);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        print_event_rule(event_rule);
 
-       condition_status =
-                       lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                                       condition, &cap_desc_count);
+       condition_status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
+               condition, &cap_desc_count);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        if (cap_desc_count > 0) {
@@ -737,8 +679,8 @@ static void print_condition_event_rule_matches(
 
                for (i = 0; i < cap_desc_count; i++) {
                        const struct lttng_event_expr *cap_desc =
-                                       lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-                                                       condition, i);
+                               lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
+                                       condition, i);
 
                        _MSG("      - ");
                        print_one_event_expr(cap_desc);
@@ -748,17 +690,17 @@ static void print_condition_event_rule_matches(
 }
 
 static void print_action_errors(const struct lttng_trigger *trigger,
-               const uint64_t *action_path_indexes,
-               size_t action_path_length)
+                               const uint64_t *action_path_indexes,
+                               size_t action_path_length)
 {
        enum lttng_error_code error_query_ret;
-       struct lttng_error_query_results *results = NULL;
+       struct lttng_error_query_results *results = nullptr;
        const char *trigger_name;
        uid_t trigger_uid;
        enum lttng_trigger_status trigger_status;
        struct lttng_error_query *query;
-       struct lttng_action_path *action_path = lttng_action_path_create(
-                       action_path_indexes, action_path_length);
+       struct lttng_action_path *action_path =
+               lttng_action_path_create(action_path_indexes, action_path_length);
 
        LTTNG_ASSERT(action_path);
 
@@ -774,12 +716,13 @@ static void print_action_errors(const struct lttng_trigger *trigger,
        trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-       error_query_ret = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, &results);
+       error_query_ret =
+               lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, &results);
        if (error_query_ret != LTTNG_OK) {
                ERR("Failed to query errors of trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-error_query_ret));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-error_query_ret));
                goto end;
        }
 
@@ -792,15 +735,14 @@ end:
        lttng_action_path_destroy(action_path);
 }
 
-static
-void print_one_action(const struct lttng_trigger *trigger,
-               const struct lttng_action *action,
-               const uint64_t *action_path_indexes,
-               size_t action_path_length)
+static void print_one_action(const struct lttng_trigger *trigger,
+                            const struct lttng_action *action,
+                            const uint64_t *action_path_indexes,
+                            size_t action_path_length)
 {
        enum lttng_action_type action_type;
        enum lttng_action_status action_status;
-       const struct lttng_rate_policy *policy = NULL;
+       const struct lttng_rate_policy *policy = nullptr;
        const char *value;
 
        action_type = lttng_action_get_type(action);
@@ -810,47 +752,40 @@ void print_one_action(const struct lttng_trigger *trigger,
        case LTTNG_ACTION_TYPE_NOTIFY:
                _MSG("notify");
 
-               action_status = lttng_action_notify_get_rate_policy(
-                               action, &policy);
+               action_status = lttng_action_notify_get_rate_policy(action, &policy);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to retrieve rate policy.");
                        goto end;
                }
                break;
        case LTTNG_ACTION_TYPE_START_SESSION:
-               action_status = lttng_action_start_session_get_session_name(
-                               action, &value);
+               action_status = lttng_action_start_session_get_session_name(action, &value);
                LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
                _MSG("start session `%s`", value);
 
-               action_status = lttng_action_start_session_get_rate_policy(
-                               action, &policy);
+               action_status = lttng_action_start_session_get_rate_policy(action, &policy);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to retrieve rate policy.");
                        goto end;
                }
                break;
        case LTTNG_ACTION_TYPE_STOP_SESSION:
-               action_status = lttng_action_stop_session_get_session_name(
-                               action, &value);
+               action_status = lttng_action_stop_session_get_session_name(action, &value);
                LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
                _MSG("stop session `%s`", value);
 
-               action_status = lttng_action_stop_session_get_rate_policy(
-                               action, &policy);
+               action_status = lttng_action_stop_session_get_rate_policy(action, &policy);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to retrieve rate policy.");
                        goto end;
                }
                break;
        case LTTNG_ACTION_TYPE_ROTATE_SESSION:
-               action_status = lttng_action_rotate_session_get_session_name(
-                               action, &value);
+               action_status = lttng_action_rotate_session_get_session_name(action, &value);
                LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
                _MSG("rotate session `%s`", value);
 
-               action_status = lttng_action_rotate_session_get_rate_policy(
-                               action, &policy);
+               action_status = lttng_action_rotate_session_get_rate_policy(action, &policy);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to retrieve rate policy.");
                        goto end;
@@ -860,13 +795,11 @@ void print_one_action(const struct lttng_trigger *trigger,
        {
                const struct lttng_snapshot_output *output;
 
-               action_status = lttng_action_snapshot_session_get_session_name(
-                               action, &value);
+               action_status = lttng_action_snapshot_session_get_session_name(action, &value);
                LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
                _MSG("snapshot session `%s`", value);
 
-               action_status = lttng_action_snapshot_session_get_output(
-                               action, &output);
+               action_status = lttng_action_snapshot_session_get_output(action, &output);
                if (action_status == LTTNG_ACTION_STATUS_OK) {
                        const char *name;
                        uint64_t max_size;
@@ -909,8 +842,7 @@ void print_one_action(const struct lttng_trigger *trigger,
                        }
                }
 
-               action_status = lttng_action_snapshot_session_get_rate_policy(
-                               action, &policy);
+               action_status = lttng_action_snapshot_session_get_rate_policy(action, &policy);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        ERR("Failed to retrieve rate policy.");
                        goto end;
@@ -930,8 +862,8 @@ void print_one_action(const struct lttng_trigger *trigger,
 
                switch (policy_type) {
                case LTTNG_RATE_POLICY_TYPE_EVERY_N:
-                       policy_status = lttng_rate_policy_every_n_get_interval(
-                                       policy, &policy_value);
+                       policy_status =
+                               lttng_rate_policy_every_n_get_interval(policy, &policy_value);
                        if (policy_status != LTTNG_RATE_POLICY_STATUS_OK) {
                                ERR("Failed to get action rate policy interval");
                                goto end;
@@ -940,21 +872,17 @@ void print_one_action(const struct lttng_trigger *trigger,
                                /* The default is 1 so print only when it is a
                                 * special case.
                                 */
-                               _MSG(", rate policy: every %" PRIu64
-                                    " occurrences",
-                                               policy_value);
+                               _MSG(", rate policy: every %" PRIu64 " occurrences", policy_value);
                        }
                        break;
                case LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N:
-                       policy_status = lttng_rate_policy_once_after_n_get_threshold(
-                                       policy, &policy_value);
+                       policy_status =
+                               lttng_rate_policy_once_after_n_get_threshold(policy, &policy_value);
                        if (policy_status != LTTNG_RATE_POLICY_STATUS_OK) {
                                ERR("Failed to get action rate policy interval");
                                goto end;
                        }
-                       _MSG(", rate policy: once after %" PRIu64
-                            " occurrences",
-                                       policy_value);
+                       _MSG(", rate policy: once after %" PRIu64 " occurrences", policy_value);
                        break;
                default:
                        abort();
@@ -962,23 +890,20 @@ void print_one_action(const struct lttng_trigger *trigger,
        }
 
        MSG("");
-       print_action_errors(trigger, action_path_indexes,
-                       action_path_length);
+       print_action_errors(trigger, action_path_indexes, action_path_length);
 
 end:
        return;
 }
 
-static
-void print_trigger_errors(const struct lttng_trigger *trigger)
+static void print_trigger_errors(const struct lttng_trigger *trigger)
 {
        enum lttng_error_code error_query_ret;
-       struct lttng_error_query_results *results = NULL;
+       struct lttng_error_query_results *results = nullptr;
        enum lttng_trigger_status trigger_status;
        const char *trigger_name;
        uid_t trigger_uid;
-       struct lttng_error_query *query =
-                       lttng_error_query_trigger_create(trigger);
+       struct lttng_error_query *query = lttng_error_query_trigger_create(trigger);
 
        LTTNG_ASSERT(query);
        /*
@@ -990,12 +915,13 @@ void print_trigger_errors(const struct lttng_trigger *trigger)
        trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-       error_query_ret = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, &results);
+       error_query_ret =
+               lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, &results);
        if (error_query_ret != LTTNG_OK) {
                ERR("Failed to query errors of trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-error_query_ret));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-error_query_ret));
                goto end;
        }
 
@@ -1007,16 +933,14 @@ end:
        lttng_error_query_results_destroy(results);
 }
 
-static
-void print_condition_errors(const struct lttng_trigger *trigger)
+static void print_condition_errors(const struct lttng_trigger *trigger)
 {
        enum lttng_error_code error_query_ret;
-       struct lttng_error_query_results *results = NULL;
+       struct lttng_error_query_results *results = nullptr;
        enum lttng_trigger_status trigger_status;
        const char *trigger_name;
        uid_t trigger_uid;
-       struct lttng_error_query *query =
-                       lttng_error_query_condition_create(trigger);
+       struct lttng_error_query *query = lttng_error_query_condition_create(trigger);
 
        LTTNG_ASSERT(query);
        /*
@@ -1028,12 +952,13 @@ void print_condition_errors(const struct lttng_trigger *trigger)
        trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-       error_query_ret = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, &results);
+       error_query_ret =
+               lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, &results);
        if (error_query_ret != LTTNG_OK) {
                ERR("Failed to query errors of condition of trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-error_query_ret));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-error_query_ret));
                goto end;
        }
 
@@ -1045,8 +970,7 @@ end:
        lttng_error_query_results_destroy(results);
 }
 
-static
-void print_one_trigger(const struct lttng_trigger *trigger)
+static void print_one_trigger(const struct lttng_trigger *trigger)
 {
        const struct lttng_condition *condition;
        enum lttng_condition_type condition_type;
@@ -1100,27 +1024,17 @@ void print_one_trigger(const struct lttng_trigger *trigger)
        action = lttng_trigger_get_const_action(trigger);
        action_type = lttng_action_get_type(action);
        if (action_type == LTTNG_ACTION_TYPE_LIST) {
-               unsigned int count, i;
-               enum lttng_action_status action_status;
+               uint64_t action_path_index = 0;
 
                MSG("  actions:");
-
-               action_status = lttng_action_list_get_count(action, &count);
-               LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
-
-               for (i = 0; i < count; i++) {
-                       const uint64_t action_path_index = i;
-                       const struct lttng_action *subaction =
-                                       lttng_action_list_get_at_index(
-                                                       action, i);
-
+               for (auto subaction : lttng::ctl::const_action_list_view(action)) {
                        _MSG("    ");
-                       print_one_action(trigger, subaction, &action_path_index,
-                                       1);
+                       print_one_action(trigger, subaction, &action_path_index, 1);
+                       action_path_index++;
                }
        } else {
                _MSG(" action:");
-               print_one_action(trigger, action, NULL, 0);
+               print_one_action(trigger, action, nullptr, 0);
        }
 
        print_trigger_errors(trigger);
@@ -1128,8 +1042,7 @@ end:
        return;
 }
 
-static
-int compare_triggers_by_name(const void *a, const void *b)
+static int compare_triggers_by_name(const void *a, const void *b)
 {
        const struct lttng_trigger *trigger_a = *((const struct lttng_trigger **) a);
        const struct lttng_trigger *trigger_b = *((const struct lttng_trigger **) b);
@@ -1154,7 +1067,7 @@ static int print_sorted_triggers(const struct lttng_triggers *triggers)
        enum lttng_trigger_status trigger_status;
        unsigned int num_triggers;
 
-       lttng_dynamic_pointer_array_init(&sorted_triggers, NULL);
+       lttng_dynamic_pointer_array_init(&sorted_triggers, nullptr);
 
        trigger_status = lttng_triggers_get_count(triggers, &num_triggers);
        if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
@@ -1165,8 +1078,7 @@ static int print_sorted_triggers(const struct lttng_triggers *triggers)
        for (i = 0; i < num_triggers; i++) {
                int add_ret;
                const char *unused_name;
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
 
                trigger_status = lttng_trigger_get_name(trigger, &unused_name);
                switch (trigger_status) {
@@ -1179,24 +1091,23 @@ static int print_sorted_triggers(const struct lttng_triggers *triggers)
                        abort();
                }
 
-               add_ret = lttng_dynamic_pointer_array_add_pointer(
-                               &sorted_triggers, (void *) trigger);
+               add_ret =
+                       lttng_dynamic_pointer_array_add_pointer(&sorted_triggers, (void *) trigger);
                if (add_ret) {
                        ERR("Failed to allocate array of struct lttng_trigger *.");
                        goto error;
                }
        }
 
-       qsort(sorted_triggers.array.buffer.data, num_triggers,
-                       sizeof(struct lttng_trigger *),
-                       compare_triggers_by_name);
+       qsort(sorted_triggers.array.buffer.data,
+             num_triggers,
+             sizeof(struct lttng_trigger *),
+             compare_triggers_by_name);
 
-       for (i = 0; i < lttng_dynamic_pointer_array_get_count(&sorted_triggers);
-                       i++) {
-               const struct lttng_trigger *trigger_to_print = (const struct lttng_trigger
-                                               *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               &sorted_triggers, i);
+       for (i = 0; i < lttng_dynamic_pointer_array_get_count(&sorted_triggers); i++) {
+               const struct lttng_trigger *trigger_to_print =
+                       (const struct lttng_trigger *) lttng_dynamic_pointer_array_get_pointer(
+                               &sorted_triggers, i);
 
                print_one_trigger(trigger_to_print);
        }
@@ -1211,19 +1122,17 @@ end:
        return ret;
 }
 
-static enum lttng_error_code mi_error_query_trigger_callback(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results **results)
+static enum lttng_error_code
+mi_error_query_trigger_callback(const struct lttng_trigger *trigger,
+                               struct lttng_error_query_results **results)
 {
        enum lttng_error_code ret_code;
-       struct lttng_error_query *query =
-                       lttng_error_query_trigger_create(trigger);
+       struct lttng_error_query *query = lttng_error_query_trigger_create(trigger);
 
        LTTNG_ASSERT(results);
        LTTNG_ASSERT(query);
 
-       ret_code = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, results);
+       ret_code = lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, results);
        if (ret_code != LTTNG_OK) {
                enum lttng_trigger_status trigger_status;
                const char *trigger_name;
@@ -1232,33 +1141,31 @@ static enum lttng_error_code mi_error_query_trigger_callback(
                trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-               trigger_status = lttng_trigger_get_owner_uid(
-                               trigger, &trigger_uid);
+               trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
                ERR("Failed to query errors of trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-ret_code));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-ret_code));
        }
 
        lttng_error_query_destroy(query);
        return ret_code;
 }
 
-static enum lttng_error_code mi_error_query_action_callback(
-               const struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path,
-               struct lttng_error_query_results **results)
+static enum lttng_error_code
+mi_error_query_action_callback(const struct lttng_trigger *trigger,
+                              const struct lttng_action_path *action_path,
+                              struct lttng_error_query_results **results)
 {
        enum lttng_error_code ret_code;
-       struct lttng_error_query *query =
-                       lttng_error_query_action_create(trigger, action_path);
+       struct lttng_error_query *query = lttng_error_query_action_create(trigger, action_path);
 
        LTTNG_ASSERT(results);
        LTTNG_ASSERT(query);
 
-       ret_code = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, results);
+       ret_code = lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, results);
        if (ret_code != LTTNG_OK) {
                enum lttng_trigger_status trigger_status;
                const char *trigger_name;
@@ -1267,32 +1174,30 @@ static enum lttng_error_code mi_error_query_action_callback(
                trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-               trigger_status = lttng_trigger_get_owner_uid(
-                               trigger, &trigger_uid);
+               trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
                ERR("Failed to query errors of an action for trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-ret_code));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-ret_code));
        }
 
        lttng_error_query_destroy(query);
        return ret_code;
 }
 
-static enum lttng_error_code mi_error_query_condition_callback(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results **results)
+static enum lttng_error_code
+mi_error_query_condition_callback(const struct lttng_trigger *trigger,
+                                 struct lttng_error_query_results **results)
 {
        enum lttng_error_code ret_code;
-       struct lttng_error_query *query =
-                       lttng_error_query_condition_create(trigger);
+       struct lttng_error_query *query = lttng_error_query_condition_create(trigger);
 
        LTTNG_ASSERT(results);
        LTTNG_ASSERT(query);
 
-       ret_code = lttng_error_query_execute(
-                       query, lttng_session_daemon_command_endpoint, results);
+       ret_code = lttng_error_query_execute(query, lttng_session_daemon_command_endpoint, results);
        if (ret_code != LTTNG_OK) {
                enum lttng_trigger_status trigger_status;
                const char *trigger_name;
@@ -1301,13 +1206,13 @@ static enum lttng_error_code mi_error_query_condition_callback(
                trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
-               trigger_status = lttng_trigger_get_owner_uid(
-                               trigger, &trigger_uid);
+               trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
                ERR("Failed to query errors of of condition for condition of trigger '%s' (owner uid: %d): %s",
-                               trigger_name, (int) trigger_uid,
-                               lttng_strerror(-ret_code));
+                   trigger_name,
+                   (int) trigger_uid,
+                   lttng_strerror(-ret_code));
        }
 
        lttng_error_query_destroy(query);
@@ -1317,10 +1222,10 @@ static enum lttng_error_code mi_error_query_condition_callback(
 int cmd_list_triggers(int argc, const char **argv)
 {
        int ret;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       struct lttng_triggers *triggers = NULL;
-       struct mi_writer *mi_writer = NULL;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       struct lttng_triggers *triggers = nullptr;
+       struct mi_writer *mi_writer = nullptr;
 
        argc--;
        argv++;
@@ -1334,10 +1239,10 @@ int cmd_list_triggers(int argc, const char **argv)
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item, 1, argv,
-                       true, NULL, NULL);
+               status =
+                       parse_next_item(argpar_iter, &argpar_item, 1, argv, true, nullptr, nullptr);
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -1346,8 +1251,7 @@ int cmd_list_triggers(int argc, const char **argv)
                assert(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
 
                        switch (descr->id) {
                        case OPT_HELP:
@@ -1356,8 +1260,7 @@ int cmd_list_triggers(int argc, const char **argv)
                                goto end;
 
                        case OPT_LIST_OPTIONS:
-                               list_cmd_options_argpar(
-                                               stdout, list_trigger_options);
+                               list_cmd_options_argpar(stdout, list_trigger_options);
                                ret = 0;
                                goto end;
 
@@ -1366,8 +1269,7 @@ int cmd_list_triggers(int argc, const char **argv)
                        }
 
                } else {
-                       ERR("Unexpected argument: %s",
-                               argpar_item_non_opt_arg(argpar_item));
+                       ERR("Unexpected argument: %s", argpar_item_non_opt_arg(argpar_item));
                }
        }
 
@@ -1378,8 +1280,7 @@ int cmd_list_triggers(int argc, const char **argv)
        }
 
        if (lttng_opt_mi) {
-               mi_writer = mi_lttng_writer_create(
-                               fileno(stdout), lttng_opt_mi);
+               mi_writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!mi_writer) {
                        ret = CMD_ERROR;
                        goto end;
@@ -1387,15 +1288,14 @@ int cmd_list_triggers(int argc, const char **argv)
 
                /* Open command element. */
                ret = mi_lttng_writer_command_open(mi_writer,
-                               mi_lttng_element_command_list_trigger);
+                                                  mi_lttng_element_command_list_trigger);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element. */
-               ret = mi_lttng_writer_open_element(
-                               mi_writer, mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(mi_writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -1409,11 +1309,9 @@ int cmd_list_triggers(int argc, const char **argv)
                        .action_cb = mi_error_query_action_callback,
                };
 
-               ret = lttng_triggers_mi_serialize(
-                               triggers, mi_writer, &callbacks);
+               ret = lttng_triggers_mi_serialize(triggers, mi_writer, &callbacks);
                if (ret != LTTNG_OK) {
-                       ERR("Error printing MI triggers: %s.",
-                                       lttng_strerror(-ret));
+                       ERR("Error printing MI triggers: %s.", lttng_strerror(-ret));
                        goto error;
                }
        } else {
index 2ab005f2a3a029546a370e8141e0cf1af9c3531f..4a60db2d1134f7b0c854b5084ba3565c22bae2a3 100644 (file)
@@ -6,18 +6,19 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/config/session-config.hpp>
+#include <common/mi-lttng.hpp>
+
+#include <lttng/lttng.h>
+
 #include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include <common/mi-lttng.hpp>
-#include <common/config/session-config.hpp>
-#include <lttng/lttng.h>
-
-#include "../command.hpp"
-
 static char *the_opt_input_path;
 static char *the_opt_override_url;
 static char *the_opt_override_session_name;
@@ -29,7 +30,7 @@ static const char *the_session_name;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-load.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -43,14 +44,14 @@ static struct mi_writer *the_writer;
 
 static struct poptOption the_load_opts[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",          'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"all",           'a', POPT_ARG_NONE, 0, OPT_ALL, 0, 0},
-       {"input-path",    'i', POPT_ARG_STRING, &the_opt_input_path, 0, 0, 0},
-       {"force",         'f', POPT_ARG_NONE, 0, OPT_FORCE, 0, 0},
-       {"override-url",    0, POPT_ARG_STRING, &the_opt_override_url, 0, 0, 0},
-       {"override-name",   0, POPT_ARG_STRING, &the_opt_override_session_name, 0, 0, 0},
-       {"list-options",    0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_NONE, nullptr, OPT_ALL, nullptr, nullptr },
+       { "input-path", 'i', POPT_ARG_STRING, &the_opt_input_path, 0, nullptr, nullptr },
+       { "force", 'f', POPT_ARG_NONE, nullptr, OPT_FORCE, nullptr, nullptr },
+       { "override-url", 0, POPT_ARG_STRING, &the_opt_override_url, 0, nullptr, nullptr },
+       { "override-name", 0, POPT_ARG_STRING, &the_opt_override_session_name, 0, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static int mi_partial_session(const char *session_name)
@@ -65,8 +66,7 @@ static int mi_partial_session(const char *session_name)
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_string(the_writer, config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(the_writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
@@ -104,8 +104,8 @@ static int mi_load_print(const char *session_name)
 
        /* Path element */
        if (the_opt_input_path) {
-               ret = mi_lttng_writer_write_element_string(the_writer, config_element_path,
-                               the_opt_input_path);
+               ret = mi_lttng_writer_write_element_string(
+                       the_writer, config_element_path, the_opt_input_path);
                if (ret) {
                        goto end;
                }
@@ -119,8 +119,8 @@ static int mi_load_print(const char *session_name)
 
        /* Session name override element */
        if (the_opt_override_session_name) {
-               ret = mi_lttng_writer_write_element_string(the_writer,
-                               config_element_name, the_opt_override_session_name);
+               ret = mi_lttng_writer_write_element_string(
+                       the_writer, config_element_name, the_opt_override_session_name);
                if (ret) {
                        goto end;
                }
@@ -128,9 +128,8 @@ static int mi_load_print(const char *session_name)
 
        /* Session url override element */
        if (the_opt_override_url) {
-               ret = mi_lttng_writer_write_element_string(the_writer,
-                               mi_lttng_element_load_override_url,
-                               the_opt_override_url);
+               ret = mi_lttng_writer_write_element_string(
+                       the_writer, mi_lttng_element_load_override_url, the_opt_override_url);
                if (ret) {
                        goto end;
                }
@@ -150,11 +149,11 @@ int cmd_load(int argc, const char **argv)
        int ret, success;
        int opt;
        poptContext pc;
-       struct lttng_load_session_attr *session_attr = NULL;
-       char *input_path = NULL;
-       const char *leftover = NULL;
+       struct lttng_load_session_attr *session_attr = nullptr;
+       char *input_path = nullptr;
+       const char *leftover = nullptr;
 
-       pc = poptGetContext(NULL, argc, argv, the_load_opts, 0);
+       pc = poptGetContext(nullptr, argc, argv, the_load_opts, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -212,16 +211,14 @@ int cmd_load(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(the_writer,
-                               mi_lttng_element_command_load);
+               ret = mi_lttng_writer_command_open(the_writer, mi_lttng_element_command_load);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(the_writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(the_writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -242,18 +239,17 @@ int cmd_load(int argc, const char **argv)
         * Use realpath to resolve any relative path.
         * */
        if (the_opt_input_path) {
-               input_path = realpath(the_opt_input_path, NULL);
+               input_path = realpath(the_opt_input_path, nullptr);
                if (!input_path) {
                        PERROR("Invalid input path");
                        ret = CMD_ERROR;
                        goto end;
                }
        } else {
-               input_path = NULL;
+               input_path = nullptr;
        }
 
-       ret = lttng_load_session_attr_set_input_url(session_attr,
-                       input_path);
+       ret = lttng_load_session_attr_set_input_url(session_attr, input_path);
        if (ret) {
                ERR("Invalid input path");
                ret = CMD_ERROR;
@@ -261,8 +257,7 @@ int cmd_load(int argc, const char **argv)
        }
 
        /* Set the session name. NULL means all sessions should be loaded */
-       ret = lttng_load_session_attr_set_session_name(session_attr,
-                       the_session_name);
+       ret = lttng_load_session_attr_set_session_name(session_attr, the_session_name);
        if (ret) {
                ERR("Invalid session name");
                ret = CMD_ERROR;
@@ -279,8 +274,7 @@ int cmd_load(int argc, const char **argv)
 
        /* Set the overrides attributes if any */
        if (the_opt_override_url) {
-               ret = lttng_load_session_attr_set_override_url(session_attr,
-                               the_opt_override_url);
+               ret = lttng_load_session_attr_set_override_url(session_attr, the_opt_override_url);
                if (ret) {
                        ERR("Url override is invalid");
                        goto end;
@@ -293,8 +287,8 @@ int cmd_load(int argc, const char **argv)
                        ret = CMD_ERROR;
                        goto end;
                }
-               ret = lttng_load_session_attr_set_override_session_name(session_attr,
-                               the_opt_override_session_name);
+               ret = lttng_load_session_attr_set_override_session_name(
+                       session_attr, the_opt_override_session_name);
                if (ret) {
                        ERR("Failed to set session name override");
                        ret = CMD_ERROR;
@@ -313,8 +307,7 @@ int cmd_load(int argc, const char **argv)
                } else if (the_session_name) {
                        ret = config_init((char *) the_session_name);
                        if (ret < 0) {
-                               WARN("Could not set %s as the default session",
-                                               the_session_name);
+                               WARN("Could not set %s as the default session", the_session_name);
                        }
                        MSG("Session %s has been loaded successfully", the_session_name);
                } else {
@@ -322,8 +315,7 @@ int cmd_load(int argc, const char **argv)
                }
 
                if (the_opt_override_session_name) {
-                       MSG("Session name overridden with %s",
-                                       the_opt_override_session_name);
+                       MSG("Session name overridden with %s", the_opt_override_session_name);
                }
 
                if (the_opt_override_url) {
@@ -350,8 +342,8 @@ int cmd_load(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(the_writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       the_writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
index 38e99b4a408a2891298c729c6f28319732bdcd1b..d9b86f2ffef47cecca1bf08ab53a6292afcdbbf9 100644 (file)
@@ -6,6 +6,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
 #include <ctype.h>
 #include <popt.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-
 static char *opt_session_name;
-static char *session_name = NULL;
+static char *session_name = nullptr;
 
 static int metadata_regenerate(int argc, const char **argv);
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-metadata.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -38,16 +38,39 @@ static struct mi_writer *writer;
 
 static struct poptOption long_options[] = {
        /* { longName, shortName, argInfo, argPtr, value, descrip, argDesc, } */
-       { "help",               'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0, },
-       { "session",            's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       { "list-options",       0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, 0, 0, },
-       { "list-commands",      0, POPT_ARG_NONE, NULL, OPT_LIST_COMMANDS, NULL, NULL},
-       { 0, 0, 0, 0, 0, 0, 0, },
+       {
+               "help",
+               'h',
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_HELP,
+               nullptr,
+               nullptr,
+       },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       {
+               "list-options",
+               0,
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_LIST_OPTIONS,
+               nullptr,
+               nullptr,
+       },
+       { "list-commands", 0, POPT_ARG_NONE, nullptr, OPT_LIST_COMMANDS, nullptr, nullptr },
+       {
+               nullptr,
+               0,
+               0,
+               nullptr,
+               0,
+               nullptr,
+               nullptr,
+       },
 };
 
 static struct cmd_struct actions[] = {
-       { "regenerate", metadata_regenerate },
-       { NULL, NULL }  /* Array closure */
+       { "regenerate", metadata_regenerate }, { nullptr, nullptr } /* Array closure */
 };
 
 /*
@@ -59,15 +82,14 @@ static int count_arguments(const char **argv)
 
        LTTNG_ASSERT(argv);
 
-       while (argv[i] != NULL) {
+       while (argv[i] != nullptr) {
                i++;
        }
 
        return i;
 }
 
-static int metadata_regenerate(int argc,
-               const char **argv __attribute__((unused)))
+static int metadata_regenerate(int argc, const char **argv __attribute__((unused)))
 {
        int ret;
 
@@ -91,7 +113,7 @@ static int handle_command(const char **argv)
        struct cmd_struct *cmd;
        int ret = CMD_SUCCESS, i = 0, argc, command_ret = CMD_SUCCESS;
 
-       if (argv == NULL) {
+       if (argv == nullptr) {
                ERR("No action specified for metadata command.");
                ret = CMD_ERROR;
                goto end;
@@ -101,21 +123,21 @@ static int handle_command(const char **argv)
        LTTNG_ASSERT(argc >= 1);
 
        cmd = &actions[i];
-       while (cmd->func != NULL) {
+       while (cmd->func != nullptr) {
                /* Find command */
                if (strcmp(argv[0], cmd->name) == 0) {
                        if (lttng_opt_mi) {
                                /* Action element */
-                               ret = mi_lttng_writer_open_element(writer,
-                                               mi_lttng_element_command_metadata_action);
+                               ret = mi_lttng_writer_open_element(
+                                       writer, mi_lttng_element_command_metadata_action);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
                                }
 
                                /* Name of the action */
-                               ret = mi_lttng_writer_write_element_string(writer,
-                                               config_element_name, argv[0]);
+                               ret = mi_lttng_writer_write_element_string(
+                                       writer, config_element_name, argv[0]);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
@@ -158,7 +180,7 @@ int cmd_metadata(int argc, const char **argv)
                goto end;
        }
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        if (lttng_opt_mi) {
@@ -168,16 +190,14 @@ int cmd_metadata(int argc, const char **argv)
                        goto end;
                }
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_metadata);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_metadata);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -204,7 +224,7 @@ int cmd_metadata(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -226,8 +246,8 @@ int cmd_metadata(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
index 936b7d7ca3111247ece764c2ae981714151f1eff..fb415739387ab08a72466341527a10109cc02093 100644 (file)
@@ -6,6 +6,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
 #include <ctype.h>
 #include <popt.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-
 static char *opt_session_name;
-static char *session_name = NULL;
+static char *session_name = nullptr;
 
 static int regenerate_metadata(int argc, const char **argv);
 static int regenerate_statedump(int argc, const char **argv);
@@ -26,7 +26,7 @@ static int regenerate_statedump(int argc, const char **argv);
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-regenerate.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -39,17 +39,41 @@ static struct mi_writer *writer;
 
 static struct poptOption long_options[] = {
        /* { longName, shortName, argInfo, argPtr, value, descrip, argDesc, } */
-       { "help",               'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0, },
-       { "session",            's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       { "list-options",       0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, 0, 0, },
-       { "list-commands",      0, POPT_ARG_NONE, NULL, OPT_LIST_COMMANDS, NULL, NULL},
-       { 0, 0, 0, 0, 0, 0, 0, },
+       {
+               "help",
+               'h',
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_HELP,
+               nullptr,
+               nullptr,
+       },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       {
+               "list-options",
+               0,
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_LIST_OPTIONS,
+               nullptr,
+               nullptr,
+       },
+       { "list-commands", 0, POPT_ARG_NONE, nullptr, OPT_LIST_COMMANDS, nullptr, nullptr },
+       {
+               nullptr,
+               0,
+               0,
+               nullptr,
+               0,
+               nullptr,
+               nullptr,
+       },
 };
 
 static struct cmd_struct actions[] = {
        { "metadata", regenerate_metadata },
        { "statedump", regenerate_statedump },
-       { NULL, NULL }  /* Array closure */
+       { nullptr, nullptr } /* Array closure */
 };
 
 /*
@@ -61,15 +85,14 @@ static int count_arguments(const char **argv)
 
        LTTNG_ASSERT(argv);
 
-       while (argv[i] != NULL) {
+       while (argv[i] != nullptr) {
                i++;
        }
 
        return i;
 }
 
-static int regenerate_metadata(int argc,
-               const char **argv __attribute__((unused)))
+static int regenerate_metadata(int argc, const char **argv __attribute__((unused)))
 {
        int ret;
 
@@ -88,8 +111,7 @@ end:
        return ret;
 }
 
-static int regenerate_statedump(int argc,
-               const char **argv __attribute__((unused)))
+static int regenerate_statedump(int argc, const char **argv __attribute__((unused)))
 {
        int ret;
 
@@ -111,7 +133,7 @@ static int handle_command(const char **argv)
        struct cmd_struct *cmd;
        int ret = CMD_SUCCESS, i = 0, argc, command_ret = CMD_SUCCESS;
 
-       if (argv == NULL) {
+       if (argv == nullptr) {
                ERR("No object specified for regenerate command.");
                command_ret = CMD_ERROR;
                goto end;
@@ -121,21 +143,21 @@ static int handle_command(const char **argv)
        LTTNG_ASSERT(argc >= 1);
 
        cmd = &actions[i];
-       while (cmd->func != NULL) {
+       while (cmd->func != nullptr) {
                /* Find command */
                if (strcmp(argv[0], cmd->name) == 0) {
                        if (lttng_opt_mi) {
                                /* Action element */
-                               ret = mi_lttng_writer_open_element(writer,
-                                               mi_lttng_element_command_regenerate_action);
+                               ret = mi_lttng_writer_open_element(
+                                       writer, mi_lttng_element_command_regenerate_action);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
                                }
 
                                /* Name of the action */
-                               ret = mi_lttng_writer_write_element_string(writer,
-                                               config_element_name, argv[0]);
+                               ret = mi_lttng_writer_write_element_string(
+                                       writer, config_element_name, argv[0]);
                                if (ret) {
                                        ret = CMD_ERROR;
                                        goto end;
@@ -178,7 +200,7 @@ int cmd_regenerate(int argc, const char **argv)
                goto end;
        }
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        if (lttng_opt_mi) {
@@ -188,16 +210,14 @@ int cmd_regenerate(int argc, const char **argv)
                        goto end;
                }
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_regenerate);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_regenerate);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
@@ -224,7 +244,7 @@ int cmd_regenerate(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto end;
                }
@@ -246,8 +266,8 @@ int cmd_regenerate(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
index 65b5e79a9b4b18b562e536772b87bfd4f94e0a89..08d4873f08a4cb9b9b66611eaeb51331c773ea76 100644 (file)
@@ -6,16 +6,18 @@
  */
 
 #include "../command.hpp"
-#include "common/argpar/argpar.h"
 #include "common/argpar-utils/argpar-utils.hpp"
+#include "common/argpar/argpar.h"
 #include "common/mi-lttng.hpp"
+
 #include <lttng/lttng.h>
+
 #include <stdio.h>
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-remove-trigger.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -24,16 +26,14 @@ enum {
        OPT_OWNER_UID,
 };
 
-static const
-struct argpar_opt_descr remove_trigger_options[] = {
+static const struct argpar_opt_descr remove_trigger_options[] = {
        { OPT_HELP, 'h', "help", false },
        { OPT_LIST_OPTIONS, '\0', "list-options", false },
        { OPT_OWNER_UID, '\0', "owner-uid", true },
        ARGPAR_OPT_DESCR_SENTINEL,
 };
 
-static
-bool assign_string(char **dest, const char *src, const char *opt_name)
+static bool assign_string(char **dest, const char *src, const char *opt_name)
 {
        bool ret;
 
@@ -62,21 +62,21 @@ int cmd_remove_trigger(int argc, const char **argv)
 {
        enum lttng_error_code ret_code;
        int ret;
-       struct argpar_iter *argpar_iter = NULL;
-       const struct argpar_item *argpar_item = NULL;
-       const char *name = NULL;
+       struct argpar_iter *argpar_iter = nullptr;
+       const struct argpar_item *argpar_item = nullptr;
+       const char *name = nullptr;
        int i;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int triggers_count;
        enum lttng_trigger_status trigger_status;
-       const struct lttng_trigger *trigger_to_remove = NULL;
-       char *owner_uid = NULL;
+       const struct lttng_trigger *trigger_to_remove = nullptr;
+       char *owner_uid = nullptr;
        long long uid;
-       struct mi_writer *mi_writer = NULL;
+       struct mi_writer *mi_writer = nullptr;
+       const char **args;
 
        if (lttng_opt_mi) {
-               mi_writer = mi_lttng_writer_create(
-                               fileno(stdout), lttng_opt_mi);
+               mi_writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!mi_writer) {
                        ret = CMD_ERROR;
                        goto error;
@@ -84,25 +84,23 @@ int cmd_remove_trigger(int argc, const char **argv)
 
                /* Open command element. */
                ret = mi_lttng_writer_command_open(mi_writer,
-                               mi_lttng_element_command_remove_trigger);
+                                                  mi_lttng_element_command_remove_trigger);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
                }
 
                /* Open output element. */
-               ret = mi_lttng_writer_open_element(
-                               mi_writer, mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(mi_writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
                }
        }
 
-       argc--;
-       argv++;
+       args = argv + 1;
 
-       argpar_iter = argpar_iter_create(argc, argv, remove_trigger_options);
+       argpar_iter = argpar_iter_create(argc - 1, args, remove_trigger_options);
        if (!argpar_iter) {
                ERR("Failed to allocate an argpar iter.");
                goto error;
@@ -111,10 +109,10 @@ int cmd_remove_trigger(int argc, const char **argv)
        while (true) {
                enum parse_next_item_status status;
 
-               status = parse_next_item(argpar_iter, &argpar_item, 1, argv,
-                       true, NULL, NULL);
+               status =
+                       parse_next_item(argpar_iter, &argpar_item, 1, args, true, nullptr, nullptr);
                if (status == PARSE_NEXT_ITEM_STATUS_ERROR ||
-                               status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
+                   status == PARSE_NEXT_ITEM_STATUS_ERROR_MEMORY) {
                        goto error;
                } else if (status == PARSE_NEXT_ITEM_STATUS_END) {
                        break;
@@ -123,8 +121,7 @@ int cmd_remove_trigger(int argc, const char **argv)
                assert(status == PARSE_NEXT_ITEM_STATUS_OK);
 
                if (argpar_item_type(argpar_item) == ARGPAR_ITEM_TYPE_OPT) {
-                       const struct argpar_opt_descr *descr =
-                               argpar_item_opt_descr(argpar_item);
+                       const struct argpar_opt_descr *descr = argpar_item_opt_descr(argpar_item);
                        const char *arg = argpar_item_opt_arg(argpar_item);
 
                        switch (descr->id) {
@@ -133,14 +130,12 @@ int cmd_remove_trigger(int argc, const char **argv)
                                ret = 0;
                                goto end;
                        case OPT_LIST_OPTIONS:
-                               list_cmd_options_argpar(stdout,
-                                       remove_trigger_options);
+                               list_cmd_options_argpar(stdout, remove_trigger_options);
                                ret = 0;
                                goto end;
                        case OPT_OWNER_UID:
                        {
-                               if (!assign_string(&owner_uid, arg,
-                                               "--owner-uid")) {
+                               if (!assign_string(&owner_uid, arg, "--owner-uid")) {
                                        goto error;
                                }
                                break;
@@ -203,8 +198,7 @@ int cmd_remove_trigger(int argc, const char **argv)
                        abort();
                }
 
-               trigger_status = lttng_trigger_get_owner_uid(
-                               trigger, &trigger_uid);
+               trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_uid);
                LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
                if (trigger_uid == uid && strcmp(trigger_name, name) == 0) {
@@ -225,8 +219,7 @@ int cmd_remove_trigger(int argc, const char **argv)
        }
 
        if (lttng_opt_mi) {
-               ret_code = lttng_trigger_mi_serialize(
-                               trigger_to_remove, mi_writer, NULL);
+               ret_code = lttng_trigger_mi_serialize(trigger_to_remove, mi_writer, nullptr);
                if (ret_code != LTTNG_OK) {
                        goto error;
                }
@@ -249,8 +242,8 @@ end:
                        goto cleanup;
                }
 
-               mi_ret = mi_lttng_writer_write_element_bool(mi_writer,
-                               mi_lttng_element_command_success, ret ? 0 : 1);
+               mi_ret = mi_lttng_writer_write_element_bool(
+                       mi_writer, mi_lttng_element_command_success, ret ? 0 : 1);
                if (mi_ret) {
                        ret = 1;
                        goto cleanup;
index 339e39598891505d3b62eafffc123be901b445dd..9c4347e43191467e3de3b4ecd28b7576e1749dd9 100644 (file)
@@ -6,6 +6,15 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
+#include <lttng/lttng.h>
+
+#include <ctype.h>
+#include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-#include <ctype.h>
 
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-#include <lttng/lttng.h>
-
-static char *opt_session_name;
 static int opt_no_wait;
 static struct mi_writer *writer;
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-rotate.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -39,25 +39,25 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"no-wait",   'n', POPT_ARG_VAL, &opt_no_wait, 1, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "no-wait", 'n', POPT_ARG_VAL, &opt_no_wait, 1, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static int rotate_tracing(char *session_name)
 {
        int ret;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
-       struct lttng_rotation_handle *handle = NULL;
+       struct lttng_rotation_handle *handle = nullptr;
        enum lttng_rotation_status rotation_status;
        enum lttng_rotation_state rotation_state = LTTNG_ROTATION_STATE_ONGOING;
-       const struct lttng_trace_archive_location *location = NULL;
+       const struct lttng_trace_archive_location *location = nullptr;
        bool print_location = true;
 
        DBG("Rotating the output files of session %s", session_name);
 
-       ret = lttng_rotate_session(session_name, NULL, &handle);
+       ret = lttng_rotate_session(session_name, nullptr, &handle);
        if (ret < 0) {
                switch (-ret) {
                case LTTNG_ERR_SESSION_NOT_STARTED:
@@ -83,8 +83,7 @@ static int rotate_tracing(char *session_name)
        }
 
        do {
-               rotation_status = lttng_rotation_handle_get_state(handle,
-                               &rotation_state);
+               rotation_status = lttng_rotation_handle_get_state(handle, &rotation_state);
                if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
                        MSG("");
                        ERR("Failed to query the state of the rotation.");
@@ -111,8 +110,7 @@ static int rotate_tracing(char *session_name)
 skip_wait:
        switch (rotation_state) {
        case LTTNG_ROTATION_STATE_COMPLETED:
-               rotation_status = lttng_rotation_handle_get_archive_location(
-                               handle, &location);
+               rotation_status = lttng_rotation_handle_get_archive_location(handle, &location);
                if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
                        ERR("Failed to retrieve the rotation's completed chunk archive location.");
                        cmd_ret = CMD_ERROR;
@@ -133,11 +131,9 @@ skip_wait:
        }
 
        if (!lttng_opt_mi && print_location) {
-               ret = print_trace_archive_location(location,
-                               session_name);
+               ret = print_trace_archive_location(location, session_name);
        } else if (lttng_opt_mi) {
-               ret = mi_lttng_rotate(writer, session_name, rotation_state,
-                               location);
+               ret = mi_lttng_rotate(writer, session_name, rotation_state, location);
        }
 
        if (ret < 0) {
@@ -163,14 +159,15 @@ int cmd_rotate(int argc, const char **argv)
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        int popt_ret;
        static poptContext pc;
-       char *session_name = NULL;
-       bool free_session_name = false;
+       const char *arg_session_name = nullptr;
+       char *session_name = nullptr;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        popt_ret = poptReadDefaultConfig(pc, 0);
        if (popt_ret) {
                ERR("poptReadDefaultConfig");
-               goto error;
+               cmd_ret = CMD_ERROR;
+               goto end;
        }
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -187,37 +184,41 @@ int cmd_rotate(int argc, const char **argv)
                }
        }
 
-       opt_session_name = (char*) poptGetArg(pc);
-
-       if (!opt_session_name) {
+       arg_session_name = poptGetArg(pc);
+       if (arg_session_name == nullptr) {
                session_name = get_session_name();
-               if (!session_name) {
-                       goto error;
-               }
-               free_session_name = true;
        } else {
-               session_name = opt_session_name;
+               session_name = strdup(arg_session_name);
+               if (session_name == nullptr) {
+                       PERROR("Failed to copy session name");
+               }
+       }
+
+       if (session_name == nullptr) {
+               cmd_ret = CMD_ERROR;
+               goto end;
        }
 
        /* Mi check */
        if (lttng_opt_mi) {
                writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!writer) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
 
                /* Open rotate command */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_rotate);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_rotate);
                if (ret) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
        }
 
@@ -228,35 +229,33 @@ int cmd_rotate(int argc, const char **argv)
                /* Close output element */
                ret = mi_lttng_writer_close_element(writer);
                if (ret) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success,
-                               cmd_ret == CMD_SUCCESS);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, cmd_ret == CMD_SUCCESS);
                if (ret) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
 
                /* Command element close */
                ret = mi_lttng_writer_command_close(writer);
                if (ret) {
-                       goto error;
+                       cmd_ret = CMD_ERROR;
+                       goto end;
                }
        }
 
        /* Mi clean-up */
        if (writer && mi_lttng_writer_destroy(writer)) {
-               goto error;
+               cmd_ret = CMD_ERROR;
+               goto end;
        }
 end:
+       free(session_name);
        poptFreeContext(pc);
-       if (free_session_name) {
-               free(session_name);
-       }
 
        return cmd_ret;
-error:
-       cmd_ret = CMD_ERROR;
-       goto end;
 }
index 9b939102ccb8c8d8511c7cbefedd6c8c702645d6..3ee71c08845a84cd80c0a5511be2212ee92c8495 100644 (file)
@@ -6,17 +6,18 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
+#include <lttng/lttng.h>
+
 #include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-#include <lttng/lttng.h>
-
 static char *opt_output_path;
 static bool opt_force;
 static bool opt_save_all;
@@ -25,7 +26,7 @@ static struct mi_writer *writer;
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-save.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -37,12 +38,12 @@ enum {
 
 static struct poptOption save_opts[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h', POPT_ARG_NONE, NULL, OPT_HELP, NULL, NULL},
-       {"all",         'a', POPT_ARG_NONE, NULL, OPT_ALL, NULL, NULL},
-       {"output-path", 'o', POPT_ARG_STRING, &opt_output_path, 0, NULL, NULL},
-       {"force",       'f', POPT_ARG_NONE, NULL, OPT_FORCE, NULL, NULL},
-       {"list-options",  0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_NONE, nullptr, OPT_ALL, nullptr, nullptr },
+       { "output-path", 'o', POPT_ARG_STRING, &opt_output_path, 0, nullptr, nullptr },
+       { "force", 'f', POPT_ARG_NONE, nullptr, OPT_FORCE, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static int mi_partial_session(const char *session_name)
@@ -57,8 +58,7 @@ static int mi_partial_session(const char *session_name)
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
@@ -96,8 +96,8 @@ static int mi_save_print(const char *session_name)
 
        /* Path element */
        if (opt_output_path) {
-               ret = mi_lttng_writer_write_element_string(writer, config_element_path,
-                               opt_output_path);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_path, opt_output_path);
                if (ret) {
                        goto end;
                }
@@ -116,11 +116,11 @@ int cmd_save(int argc, const char **argv)
 {
        int ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success;
        int opt;
-       const char *session_name = NULL, *leftover = NULL;
+       const char *arg_session_name = nullptr, *leftover = nullptr;
        poptContext pc;
        struct lttng_save_session_attr *attr;
 
-       pc = poptGetContext(NULL, argc, argv, save_opts, 0);
+       pc = poptGetContext(nullptr, argc, argv, save_opts, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -144,9 +144,9 @@ int cmd_save(int argc, const char **argv)
        }
 
        if (!opt_save_all) {
-               session_name = poptGetArg(pc);
-               if (session_name) {
-                       DBG2("Session name: %s", session_name);
+               arg_session_name = poptGetArg(pc);
+               if (arg_session_name) {
+                       DBG2("Session name: %s", arg_session_name);
                } else {
                        /* default to opt_save_all */
                        opt_save_all = true;
@@ -166,7 +166,7 @@ int cmd_save(int argc, const char **argv)
                goto end_destroy;
        }
 
-       if (lttng_save_session_attr_set_session_name(attr, session_name)) {
+       if (lttng_save_session_attr_set_session_name(attr, arg_session_name)) {
                ret = CMD_ERROR;
                goto end_destroy;
        }
@@ -190,16 +190,14 @@ int cmd_save(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_save);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_save);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end_destroy;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end_destroy;
@@ -212,14 +210,14 @@ int cmd_save(int argc, const char **argv)
                success = 0;
        } else {
                /* Inform the user of what just happened on success. */
-               if (session_name && opt_output_path) {
-                       MSG("Session %s saved successfully in %s.", session_name,
-                                       opt_output_path);
-               } else if (session_name && !opt_output_path) {
-                       MSG("Session %s saved successfully.", session_name);
-               } else if (!session_name && opt_output_path) {
-                       MSG("All sessions have been saved successfully in %s.",
-                                       opt_output_path);
+               if (arg_session_name && opt_output_path) {
+                       MSG("Session %s saved successfully in %s.",
+                           arg_session_name,
+                           opt_output_path);
+               } else if (arg_session_name && !opt_output_path) {
+                       MSG("Session %s saved successfully.", arg_session_name);
+               } else if (!arg_session_name && opt_output_path) {
+                       MSG("All sessions have been saved successfully in %s.", opt_output_path);
                } else {
                        MSG("All sessions have been saved successfully.");
                }
@@ -229,7 +227,7 @@ int cmd_save(int argc, const char **argv)
        /* Mi Printing and closing */
        if (lttng_opt_mi) {
                /* Mi print */
-               ret = mi_save_print(session_name);
+               ret = mi_save_print(arg_session_name);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end_destroy;
@@ -243,8 +241,8 @@ int cmd_save(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end_destroy;
index 770921292996ac1151584b95db361a1a8bc0901e..627ba3040819d5340abf22653f57675820a7620d 100644 (file)
@@ -6,6 +6,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-
-static char *opt_session_name;
-
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-set-session.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -35,15 +33,15 @@ static struct mi_writer *writer;
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",           'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options",   0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
  * Print the necessary mi for a session and name.
  */
-static int mi_print(char *session_name)
+static int mi_print(const char *session_name)
 {
        int ret;
 
@@ -66,8 +64,7 @@ static int mi_print(char *session_name)
        }
 
        /* Session name */
-       ret = mi_lttng_writer_write_element_string(writer , config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
@@ -84,16 +81,15 @@ end:
 /*
  *  set_session
  */
-static int set_session(void)
+static int set_session(const char *session_name)
 {
        int ret = CMD_SUCCESS;
        int count, i;
        unsigned int session_found = 0;
        struct lttng_session *sessions;
 
-       if (opt_session_name && strlen(opt_session_name) > NAME_MAX) {
-               ERR("Session name too long. Length must be lower or equal to %d",
-                       NAME_MAX);
+       if (session_name && strlen(session_name) > NAME_MAX) {
+               ERR("Session name too long. Length must be lower or equal to %d", NAME_MAX);
                ret = CMD_ERROR;
                goto end;
        }
@@ -106,28 +102,28 @@ static int set_session(void)
        }
 
        for (i = 0; i < count; i++) {
-               if (strncmp(sessions[i].name, opt_session_name, NAME_MAX) == 0) {
+               if (strncmp(sessions[i].name, session_name, NAME_MAX) == 0) {
                        session_found = 1;
                        break;
                }
        }
 
        if (!session_found) {
-               ERR("Session '%s' not found", opt_session_name);
+               ERR("Session '%s' not found", session_name);
                ret = CMD_ERROR;
                goto error;
        }
 
-       ret = config_init(opt_session_name);
+       ret = config_init(session_name);
        if (ret < 0) {
                ERR("Unable to set session name");
                ret = CMD_ERROR;
                goto error;
        }
 
-       MSG("Session set to %s", opt_session_name);
+       MSG("Session set to %s", session_name);
        if (lttng_opt_mi) {
-               ret = mi_print(opt_session_name);
+               ret = mi_print(session_name);
                if (ret) {
                        ret = CMD_ERROR;
                        goto error;
@@ -149,8 +145,9 @@ int cmd_set_session(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
        static poptContext pc;
+       const char *arg_session_name = nullptr;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -167,8 +164,8 @@ int cmd_set_session(int argc, const char **argv)
                }
        }
 
-       opt_session_name = (char *) poptGetArg(pc);
-       if (opt_session_name == NULL) {
+       arg_session_name = poptGetArg(pc);
+       if (arg_session_name == nullptr) {
                ERR("Missing session name");
                ret = CMD_ERROR;
                goto end;
@@ -183,23 +180,21 @@ int cmd_set_session(int argc, const char **argv)
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_set_session);
+               ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_set_session);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       command_ret = set_session();
+       command_ret = set_session(arg_session_name);
        if (command_ret) {
                success = 0;
        }
@@ -214,8 +209,8 @@ int cmd_set_session(int argc, const char **argv)
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, success);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
index 3cb66c5557406ed3585d80f1f4c4185cda51be9e..93307ca5eaeea8ca388c1d752040acaa380821a1 100644 (file)
@@ -6,6 +6,13 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/mi-lttng.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
 #include <inttypes.h>
 #include <popt.h>
 #include <stdio.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/utils.hpp>
-#include <common/mi-lttng.hpp>
-#include <lttng/lttng.h>
-
-#include "../command.hpp"
-
 static const char *opt_session_name;
 static const char *opt_output_name;
 static const char *opt_data_url;
@@ -39,7 +40,7 @@ static const char *indent4 = "    ";
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-snapshot.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -53,15 +54,15 @@ static struct mi_writer *writer;
 
 static struct poptOption snapshot_opts[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"session",      's', POPT_ARG_STRING, &opt_session_name, 0, 0, 0},
-       {"ctrl-url",     'C', POPT_ARG_STRING, &opt_ctrl_url, 0, 0, 0},
-       {"data-url",     'D', POPT_ARG_STRING, &opt_data_url, 0, 0, 0},
-       {"name",         'n', POPT_ARG_STRING, &opt_output_name, 0, 0, 0},
-       {"max-size",     'm', POPT_ARG_STRING, 0, OPT_MAX_SIZE, 0, 0},
-       {"list-options",   0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"list-commands",  0, POPT_ARG_NONE, NULL, OPT_LIST_COMMANDS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "session", 's', POPT_ARG_STRING, &opt_session_name, 0, nullptr, nullptr },
+       { "ctrl-url", 'C', POPT_ARG_STRING, &opt_ctrl_url, 0, nullptr, nullptr },
+       { "data-url", 'D', POPT_ARG_STRING, &opt_data_url, 0, nullptr, nullptr },
+       { "name", 'n', POPT_ARG_STRING, &opt_output_name, 0, nullptr, nullptr },
+       { "max-size", 'm', POPT_ARG_STRING, nullptr, OPT_MAX_SIZE, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "list-commands", 0, POPT_ARG_NONE, nullptr, OPT_LIST_COMMANDS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 static struct cmd_struct actions[] = {
@@ -69,7 +70,7 @@ static struct cmd_struct actions[] = {
        { "del-output", cmd_del_output },
        { "list-output", cmd_list_output },
        { "record", cmd_record },
-       { NULL, NULL }  /* Array closure */
+       { nullptr, nullptr } /* Array closure */
 };
 
 /*
@@ -81,7 +82,7 @@ static int count_arguments(const char **argv)
 
        LTTNG_ASSERT(argv);
 
-       while (argv[i] != NULL) {
+       while (argv[i] != nullptr) {
                i++;
        }
 
@@ -96,7 +97,7 @@ static int count_arguments(const char **argv)
 static struct lttng_snapshot_output *create_output_from_args(const char *url)
 {
        int ret = 0;
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
 
        output = lttng_snapshot_output_create();
        if (!output) {
@@ -141,10 +142,10 @@ static struct lttng_snapshot_output *create_output_from_args(const char *url)
 error:
        lttng_snapshot_output_destroy(output);
 error_create:
-       return NULL;
+       return nullptr;
 }
 
-static int list_output(void)
+static int list_output()
 {
        int ret, output_seen = 0;
        struct lttng_snapshot_output *s_iter;
@@ -158,26 +159,27 @@ static int list_output(void)
        MSG("Snapshot output list for session %s", current_session_name);
 
        if (lttng_opt_mi) {
-               ret = mi_lttng_snapshot_output_session_name(writer,
-                               current_session_name);
+               ret = mi_lttng_snapshot_output_session_name(writer, current_session_name);
                if (ret) {
                        ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       while ((s_iter = lttng_snapshot_output_list_get_next(list)) != NULL) {
+       while ((s_iter = lttng_snapshot_output_list_get_next(list)) != nullptr) {
                if (lttng_snapshot_output_get_maxsize(s_iter)) {
-                       MSG("%s[%" PRIu32 "] %s: %s (max size: %" PRIu64 " bytes)", indent4,
-                                       lttng_snapshot_output_get_id(s_iter),
-                                       lttng_snapshot_output_get_name(s_iter),
-                                       lttng_snapshot_output_get_ctrl_url(s_iter),
-                                       lttng_snapshot_output_get_maxsize(s_iter));
+                       MSG("%s[%" PRIu32 "] %s: %s (max size: %" PRIu64 " bytes)",
+                           indent4,
+                           lttng_snapshot_output_get_id(s_iter),
+                           lttng_snapshot_output_get_name(s_iter),
+                           lttng_snapshot_output_get_ctrl_url(s_iter),
+                           lttng_snapshot_output_get_maxsize(s_iter));
                } else {
-                       MSG("%s[%" PRIu32 "] %s: %s", indent4,
-                                       lttng_snapshot_output_get_id(s_iter),
-                                       lttng_snapshot_output_get_name(s_iter),
-                                       lttng_snapshot_output_get_ctrl_url(s_iter));
+                       MSG("%s[%" PRIu32 "] %s: %s",
+                           indent4,
+                           lttng_snapshot_output_get_id(s_iter),
+                           lttng_snapshot_output_get_name(s_iter),
+                           lttng_snapshot_output_get_ctrl_url(s_iter));
                }
                output_seen = 1;
                if (lttng_opt_mi) {
@@ -220,7 +222,7 @@ error:
 static int del_output(uint32_t id, const char *name)
 {
        int ret;
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
 
        output = lttng_snapshot_output_create();
        if (!output) {
@@ -248,15 +250,16 @@ static int del_output(uint32_t id, const char *name)
 
        if (id != UINT32_MAX) {
                MSG("Snapshot output id %" PRIu32 " successfully deleted for session %s",
-                               id, current_session_name);
+                   id,
+                   current_session_name);
        } else {
                MSG("Snapshot output %s successfully deleted for session %s",
-                               name, current_session_name);
+                   name,
+                   current_session_name);
        }
 
        if (lttng_opt_mi) {
-               ret = mi_lttng_snapshot_del_output(writer, id, name,
-                               current_session_name);
+               ret = mi_lttng_snapshot_del_output(writer, id, name, current_session_name);
                if (ret) {
                        ret = CMD_ERROR;
                }
@@ -273,7 +276,7 @@ error:
 static int add_output(const char *url)
 {
        int ret;
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
        char name[NAME_MAX];
        const char *n_ptr;
 
@@ -297,7 +300,9 @@ static int add_output(const char *url)
        n_ptr = lttng_snapshot_output_get_name(output);
        if (*n_ptr == '\0') {
                int pret;
-               pret = snprintf(name, sizeof(name), DEFAULT_SNAPSHOT_NAME "-%" PRIu32,
+               pret = snprintf(name,
+                               sizeof(name),
+                               DEFAULT_SNAPSHOT_NAME "-%" PRIu32,
                                lttng_snapshot_output_get_id(output));
                if (pret < 0) {
                        PERROR("snprintf add output name");
@@ -305,21 +310,21 @@ static int add_output(const char *url)
                n_ptr = name;
        }
 
-       MSG("Snapshot output successfully added for session %s",
-                       current_session_name);
+       MSG("Snapshot output successfully added for session %s", current_session_name);
        if (opt_max_size) {
                MSG("  [%" PRIu32 "] %s: %s (max size: %" PRIu64 " bytes)",
-                               lttng_snapshot_output_get_id(output), n_ptr,
-                               lttng_snapshot_output_get_ctrl_url(output),
-                               lttng_snapshot_output_get_maxsize(output));
+                   lttng_snapshot_output_get_id(output),
+                   n_ptr,
+                   lttng_snapshot_output_get_ctrl_url(output),
+                   lttng_snapshot_output_get_maxsize(output));
        } else {
                MSG("  [%" PRIu32 "] %s: %s",
-                               lttng_snapshot_output_get_id(output), n_ptr,
-                               lttng_snapshot_output_get_ctrl_url(output));
+                   lttng_snapshot_output_get_id(output),
+                   n_ptr,
+                   lttng_snapshot_output_get_ctrl_url(output));
        }
        if (lttng_opt_mi) {
-               ret = mi_lttng_snapshot_add_output(writer, current_session_name,
-                               n_ptr, output);
+               ret = mi_lttng_snapshot_add_output(writer, current_session_name, n_ptr, output);
                if (ret) {
                        ret = CMD_ERROR;
                }
@@ -344,7 +349,7 @@ static int cmd_add_output(int argc, const char **argv)
                switch (-ret) {
                case LTTNG_ERR_SNAPSHOT_UNSUPPORTED:
                        ERR("Session \"%s\" contains a channel that is incompatible with the snapshot functionality.\nMake sure all channels are configured in 'mmap' output mode.",
-                                       current_session_name);
+                           current_session_name);
                        ret = CMD_ERROR;
                        break;
                default:
@@ -373,7 +378,7 @@ static int cmd_del_output(int argc, const char **argv)
        if (id == 0 && (errno == 0 || errno == EINVAL)) {
                ret = del_output(UINT32_MAX, name);
        } else if (errno == 0 && *name == '\0') {
-               ret = del_output(id, NULL);
+               ret = del_output(id, nullptr);
        } else {
                ERR("Argument %s not recognized", argv[1]);
                ret = -1;
@@ -385,7 +390,7 @@ end:
 }
 
 static int cmd_list_output(int argc __attribute__((unused)),
-               const char **argv __attribute__((unused)))
+                          const char **argv __attribute__((unused)))
 {
        int ret;
 
@@ -400,7 +405,7 @@ static int cmd_list_output(int argc __attribute__((unused)),
 static int record(const char *url)
 {
        int ret;
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
 
        output = create_output_from_args(url);
        if (!output) {
@@ -421,13 +426,11 @@ static int record(const char *url)
        if (url) {
                MSG("Snapshot written at: %s", url);
        } else if (opt_ctrl_url) {
-               MSG("Snapshot written to ctrl: %s, data: %s", opt_ctrl_url,
-                               opt_data_url);
+               MSG("Snapshot written to ctrl: %s, data: %s", opt_ctrl_url, opt_data_url);
        }
 
        if (lttng_opt_mi) {
-               ret = mi_lttng_snapshot_record(writer, url, opt_ctrl_url,
-                               opt_data_url);
+               ret = mi_lttng_snapshot_record(writer, url, opt_ctrl_url, opt_data_url);
                if (ret) {
                        ret = CMD_ERROR;
                }
@@ -445,7 +448,7 @@ static int cmd_record(int argc, const char **argv)
        if (argc == 2) {
                ret = record(argv[1]);
        } else {
-               ret = record(NULL);
+               ret = record(nullptr);
        }
 
        return ret;
@@ -463,8 +466,7 @@ static enum cmd_error_code handle_command(const char **argv)
                goto end;
        }
 
-       if ((!opt_ctrl_url && opt_data_url) ||
-                       (opt_ctrl_url && !opt_data_url)) {
+       if ((!opt_ctrl_url && opt_data_url) || (opt_ctrl_url && !opt_data_url)) {
                ERR("URLs must be specified for both data and control");
                cmd_ret = CMD_ERROR;
                goto end;
@@ -475,31 +477,31 @@ static enum cmd_error_code handle_command(const char **argv)
        LTTNG_ASSERT(argc > 0);
 
        cmd = &actions[i];
-       while (cmd->func != NULL) {
+       while (cmd->func != nullptr) {
                /* Find command */
                if (strcmp(argv[0], cmd->name) == 0) {
                        int result;
 
                        if (lttng_opt_mi) {
                                /* Action element */
-                               mi_ret = mi_lttng_writer_open_element(writer,
-                                               mi_lttng_element_command_action);
+                               mi_ret = mi_lttng_writer_open_element(
+                                       writer, mi_lttng_element_command_action);
                                if (mi_ret) {
                                        cmd_ret = CMD_ERROR;
                                        goto end;
                                }
 
                                /* Name of the action */
-                               mi_ret = mi_lttng_writer_write_element_string(writer,
-                                               config_element_name, argv[0]);
+                               mi_ret = mi_lttng_writer_write_element_string(
+                                       writer, config_element_name, argv[0]);
                                if (mi_ret) {
                                        cmd_ret = CMD_ERROR;
                                        goto end;
                                }
 
                                /* Open output element */
-                               mi_ret = mi_lttng_writer_open_element(writer,
-                                               mi_lttng_element_command_output);
+                               mi_ret = mi_lttng_writer_open_element(
+                                       writer, mi_lttng_element_command_output);
                                if (mi_ret) {
                                        cmd_ret = CMD_ERROR;
                                        goto end;
@@ -544,7 +546,6 @@ static enum cmd_error_code handle_command(const char **argv)
                                cmd_ret = CMD_SUCCESS;
                        }
 
-
                        if (lttng_opt_mi) {
                                /* Close output and action element */
                                mi_ret = mi_lttng_close_multi_element(writer, 2);
@@ -572,10 +573,10 @@ int cmd_snapshot(int argc, const char **argv)
        int opt;
        int mi_ret;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
-       char *session_name = NULL;
+       char *session_name = nullptr;
        static poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, snapshot_opts, 0);
+       pc = poptGetContext(nullptr, argc, argv, snapshot_opts, 0);
        poptReadDefaultConfig(pc, 0);
 
        /* Mi check */
@@ -587,16 +588,14 @@ int cmd_snapshot(int argc, const char **argv)
                }
 
                /* Open command element */
-               mi_ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_snapshot);
+               mi_ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_snapshot);
                if (mi_ret) {
                        cmd_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               mi_ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               mi_ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (mi_ret) {
                        cmd_ret = CMD_ERROR;
                        goto end;
@@ -624,12 +623,10 @@ int cmd_snapshot(int argc, const char **argv)
                {
                        uint64_t val;
                        char *max_size_arg = poptGetOptArg(pc);
-                       const int parse_ret = utils_parse_size_suffix(
-                                       (char *) max_size_arg, &val);
+                       const int parse_ret = utils_parse_size_suffix((char *) max_size_arg, &val);
 
                        if (parse_ret < 0) {
-                               ERR("Unable to handle max-size value %s",
-                                               max_size_arg);
+                               ERR("Unable to handle max-size value %s", max_size_arg);
                                cmd_ret = CMD_ERROR;
                                free(max_size_arg);
                                goto end;
@@ -647,7 +644,7 @@ int cmd_snapshot(int argc, const char **argv)
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        cmd_ret = CMD_ERROR;
                        goto end;
                }
@@ -667,9 +664,8 @@ int cmd_snapshot(int argc, const char **argv)
                }
 
                /* Success ? */
-               mi_ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success,
-                               cmd_ret == CMD_SUCCESS);
+               mi_ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, cmd_ret == CMD_SUCCESS);
                if (mi_ret) {
                        cmd_ret = CMD_ERROR;
                        goto end;
index 4d2b40a5064f5977c900f6a9f014867801d97fff..f00ce973e39c59034dec8c3c270d7bd229ab496f 100644 (file)
@@ -6,6 +6,14 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "../exception.hpp"
+#include "../utils.hpp"
+
+#include <common/exception.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-
+enum {
+       OPT_HELP = 1,
+       OPT_LIST_OPTIONS,
+       OPT_ENABLE_GLOB,
+       OPT_ALL,
+};
 
-static char *opt_session_name;
-static struct mi_writer *writer;
+namespace {
+struct mi_writer *writer;
 
 #ifdef LTTNG_EMBED_HELP
-static const char help_msg[] =
+const char help_msg[] =
 #include <lttng-start.1.h>
-;
+       ;
 #endif
 
-enum {
-       OPT_HELP = 1,
-       OPT_LIST_OPTIONS,
-};
-
-static struct poptOption long_options[] = {
+struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "glob", 'g', POPT_ARG_NONE, nullptr, OPT_ENABLE_GLOB, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_NONE, nullptr, OPT_ALL, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
-static int mi_print_session(char *session_name, int enabled)
+int mi_print_session(const char *session_name, int enabled)
 {
        int ret;
 
@@ -52,14 +58,12 @@ static int mi_print_session(char *session_name, int enabled)
        }
 
        /* Print session name element */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled,
-                       enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, enabled);
        if (ret) {
                goto end;
        }
@@ -76,54 +80,112 @@ end:
  *
  *  Start tracing for all trace of the session.
  */
-static int start_tracing(void)
+cmd_error_code start_tracing(const char *session_name)
 {
-       int ret;
-       char *session_name;
+       if (session_name == nullptr) {
+               return CMD_ERROR;
+       }
+
+       DBG("Starting tracing for session `%s`", session_name);
 
-       if (opt_session_name == NULL) {
-               session_name = get_session_name();
-               if (session_name == NULL) {
-                       ret = CMD_ERROR;
-                       goto error;
+       const int ret = lttng_start_tracing(session_name);
+       if (ret < 0) {
+               LTTNG_THROW_CTL(lttng::format("Failed to start session `{}`", session_name),
+                               static_cast<lttng_error_code>(-ret));
+       }
+
+       MSG("Tracing started for session `%s`", session_name);
+       if (lttng_opt_mi) {
+               if (mi_print_session(session_name, 1)) {
+                       return CMD_ERROR;
                }
-       } else {
-               session_name = opt_session_name;
        }
 
-       DBG("Starting tracing for session %s", session_name);
+       return CMD_SUCCESS;
+}
 
-       ret = lttng_start_tracing(session_name);
-       if (ret < 0) {
-               switch (-ret) {
-               case LTTNG_ERR_TRACE_ALREADY_STARTED:
-                       WARN("Tracing already started for session %s", session_name);
-                       break;
-               default:
-                       ERR("%s", lttng_strerror(ret));
-                       break;
+cmd_error_code start_tracing(const lttng::cli::session_spec& spec)
+{
+       bool had_warning = false;
+       bool had_error = false;
+       bool listing_failed = false;
+
+       const auto sessions = [&listing_failed, &spec]() -> lttng::cli::session_list {
+               try {
+                       return list_sessions(spec);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       ERR_FMT("Failed to list sessions ({})",
+                               lttng_strerror(-ctl_exception.code()));
+                       listing_failed = true;
+                       return {};
+               } catch (const lttng::cli::no_default_session_error& cli_exception) {
+                       /*
+                        * The retrieval of the default session name already logs
+                        * an error when it fails. There is no value in printing
+                        * anything about this exception.
+                        */
+                       listing_failed = true;
+                       return {};
                }
-               goto free_name;
+       }();
+
+       if (!listing_failed && sessions.size() == 0 &&
+           spec.type_ == lttng::cli::session_spec::type::NAME) {
+               ERR_FMT("Session `{}` not found", spec.value);
+               return CMD_ERROR;
        }
 
-       ret = CMD_SUCCESS;
+       if (listing_failed) {
+               return CMD_FATAL;
+       }
 
-       MSG("Tracing started for session %s", session_name);
-       if (lttng_opt_mi) {
-               ret = mi_print_session(session_name, 1);
-               if (ret) {
-                       ret = CMD_ERROR;
-                       goto free_name;
+       for (const auto& session : sessions) {
+               cmd_error_code sub_ret;
+
+               try {
+                       sub_ret = start_tracing(session.name);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       switch (ctl_exception.code()) {
+                       case LTTNG_ERR_TRACE_ALREADY_STARTED:
+                               WARN_FMT("Tracing already started for session `{}`", session.name);
+                               sub_ret = CMD_SUCCESS;
+                               break;
+                       case LTTNG_ERR_NO_SESSION:
+                               if (spec.type_ != lttng::cli::session_spec::type::NAME) {
+                                       /* Session destroyed during command, ignore and carry-on. */
+                                       sub_ret = CMD_SUCCESS;
+                                       break;
+                               } else {
+                                       sub_ret = CMD_ERROR;
+                                       break;
+                               }
+                       case LTTNG_ERR_NO_SESSIOND:
+                               /* Don't keep going on a fatal error. */
+                               return CMD_FATAL;
+                       default:
+                               /* Generic error. */
+                               sub_ret = CMD_ERROR;
+                               ERR_FMT("Failed to start session `{}` ({})",
+                                       session.name,
+                                       lttng_strerror(-ctl_exception.code()));
+                               break;
+                       }
                }
+
+               /* Keep going, but report the most serious state. */
+               had_warning |= sub_ret == CMD_WARNING;
+               had_error |= sub_ret == CMD_ERROR;
        }
 
-free_name:
-       if (opt_session_name == NULL) {
-               free(session_name);
+       if (had_error) {
+               return CMD_ERROR;
+       } else if (had_warning) {
+               return CMD_WARNING;
+       } else {
+               return CMD_SUCCESS;
        }
-error:
-       return ret;
 }
+} /* namespace */
 
 /*
  *  cmd_start
@@ -132,33 +194,47 @@ error:
  */
 int cmd_start(int argc, const char **argv)
 {
-       int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
+       int opt;
+       cmd_error_code command_ret = CMD_SUCCESS;
+       bool success = true;
        static poptContext pc;
-       const char *leftover = NULL;
+       const char *leftover = nullptr;
+       lttng::cli::session_spec session_spec(lttng::cli::session_spec::type::NAME);
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
                switch (opt) {
                case OPT_HELP:
+               {
+                       int ret;
+
                        SHOW_HELP();
+                       command_ret = static_cast<cmd_error_code>(ret);
                        goto end;
+               }
                case OPT_LIST_OPTIONS:
                        list_cmd_options(stdout, long_options);
                        goto end;
+               case OPT_ENABLE_GLOB:
+                       session_spec.type_ = lttng::cli::session_spec::type::GLOB_PATTERN;
+                       break;
+               case OPT_ALL:
+                       session_spec.type_ = lttng::cli::session_spec::type::ALL;
+                       break;
                default:
-                       ret = CMD_UNDEFINED;
+                       command_ret = CMD_UNDEFINED;
                        goto end;
                }
        }
 
-       opt_session_name = (char*) poptGetArg(pc);
+       session_spec.value = poptGetArg(pc);
 
        leftover = poptGetArg(pc);
        if (leftover) {
                ERR("Unknown argument: %s", leftover);
-               ret = CMD_ERROR;
+               command_ret = CMD_ERROR;
                goto end;
        }
 
@@ -166,23 +242,19 @@ int cmd_start(int argc, const char **argv)
        if (lttng_opt_mi) {
                writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!writer) {
-                       ret = -LTTNG_ERR_NOMEM;
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_start);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_open(writer, mi_lttng_element_command_start)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_open_element(writer, mi_lttng_element_command_output)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
@@ -190,40 +262,35 @@ int cmd_start(int argc, const char **argv)
                 * Open sessions element
                 * For validation purpose
                 */
-               ret = mi_lttng_writer_open_element(writer,
-                       config_element_sessions);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_open_element(writer, config_element_sessions)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       command_ret = start_tracing();
-       if (command_ret) {
-               success = 0;
+       command_ret = start_tracing(session_spec);
+       if (command_ret != CMD_SUCCESS) {
+               success = false;
        }
 
        /* Mi closing */
        if (lttng_opt_mi) {
                /* Close  sessions and output element */
-               ret = mi_lttng_close_multi_element(writer, 2);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_close_multi_element(writer, 2)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_write_element_bool(
+                           writer, mi_lttng_element_command_success, success)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Command element close */
-               ret = mi_lttng_writer_command_close(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_close(writer)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
@@ -231,12 +298,9 @@ int cmd_start(int argc, const char **argv)
 end:
        /* Mi clean-up */
        if (writer && mi_lttng_writer_destroy(writer)) {
-               /* Preserve original error code */
-               ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
+               command_ret = CMD_ERROR;
        }
 
-       /* Overwrite ret if an error occurred with start_tracing */
-       ret = command_ret ? command_ret : ret;
        poptFreeContext(pc);
-       return ret;
+       return command_ret;
 }
index a77830ece028d002ba0cf97ac30019ff585d7267..82a26c5b2752c026fde647eb8184e65d3a4c6604 100644 (file)
@@ -6,6 +6,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "../utils.hpp"
+
+#include <config.h>
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include "../command.hpp"
-#include "../utils.hpp"
-#include <config.h>
-
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-status.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -31,16 +31,16 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h', POPT_ARG_NONE, NULL, OPT_HELP, NULL, NULL},
-       {"list-options", 0,  POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
-static int status(void)
+static int status()
 {
        const char *argv[2];
        int ret = CMD_SUCCESS;
-       char *session_name = NULL;
+       char *session_name = nullptr;
 
        session_name = get_session_name();
        if (!session_name) {
@@ -64,7 +64,7 @@ int cmd_status(int argc, const char **argv)
        int opt, ret = CMD_SUCCESS;
        static poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -81,7 +81,7 @@ int cmd_status(int argc, const char **argv)
                }
        }
 
-       if (poptPeekArg(pc) != NULL) {
+       if (poptPeekArg(pc) != nullptr) {
                ERR("This command does not accept positional arguments.\n");
                ret = CMD_UNDEFINED;
                goto end;
index 6107dc15808abd883c08c0de245e3a80ed2d18b3..9d5533a2175c361be78f159a56628517afed9c13 100644 (file)
@@ -6,6 +6,14 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "../exception.hpp"
+#include "../utils.hpp"
+
+#include <common/exception.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
+enum {
+       OPT_HELP = 1,
+       OPT_LIST_OPTIONS,
+       OPT_ENABLE_GLOB,
+       OPT_ALL,
+};
 
-static char *opt_session_name;
-static int opt_no_wait;
-static struct mi_writer *writer;
+namespace {
+int opt_no_wait;
+struct mi_writer *writer;
 
 #ifdef LTTNG_EMBED_HELP
-static const char help_msg[] =
+const char help_msg[] =
 #include <lttng-stop.1.h>
-;
+       ;
 #endif
 
-enum {
-       OPT_HELP = 1,
-       OPT_LIST_OPTIONS,
-};
-
-static struct poptOption long_options[] = {
+struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"no-wait",   'n', POPT_ARG_VAL, &opt_no_wait, 1, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "no-wait", 'n', POPT_ARG_VAL, &opt_no_wait, 1, nullptr, nullptr },
+       { "glob", 'g', POPT_ARG_NONE, nullptr, OPT_ENABLE_GLOB, nullptr, nullptr },
+       { "all", 'a', POPT_ARG_NONE, nullptr, OPT_ALL, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
  * Mi print of partial session
  */
-static int mi_print_session(char *session_name, int enabled)
+int mi_print_session(const char *session_name, int enabled)
 {
        int ret;
        LTTNG_ASSERT(writer);
@@ -58,15 +65,13 @@ static int mi_print_session(char *session_name, int enabled)
        }
 
        /* Print session name element */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
 
        /* Is enabled ? */
-       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled,
-                       enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, enabled);
        if (ret) {
                goto end;
        }
@@ -81,32 +86,14 @@ end:
 /*
  * Start tracing for all trace of the session.
  */
-static int stop_tracing(void)
+cmd_error_code stop_tracing(const char *session_name)
 {
        int ret;
-       char *session_name;
-
-       if (opt_session_name == NULL) {
-               session_name = get_session_name();
-               if (session_name == NULL) {
-                       ret = CMD_ERROR;
-                       goto error;
-               }
-       } else {
-               session_name = opt_session_name;
-       }
 
        ret = lttng_stop_tracing_no_wait(session_name);
        if (ret < 0) {
-               switch (-ret) {
-               case LTTNG_ERR_TRACE_ALREADY_STOPPED:
-                       WARN("Tracing already stopped for session %s", session_name);
-                       break;
-               default:
-                       ERR("%s", lttng_strerror(ret));
-                       break;
-               }
-               goto free_name;
+               LTTNG_THROW_CTL(lttng::format("Failed to start session `{}`", session_name),
+                               static_cast<lttng_error_code>(-ret));
        }
 
        if (!opt_no_wait) {
@@ -116,7 +103,10 @@ static int stop_tracing(void)
                        ret = lttng_data_pending(session_name);
                        if (ret < 0) {
                                /* Return the data available call error. */
-                               goto free_name;
+                               ERR_FMT("Failed to check pending data for session `{}` ({})",
+                                       session_name,
+                                       lttng_strerror(ret));
+                               return CMD_ERROR;
                        }
 
                        /*
@@ -132,25 +122,99 @@ static int stop_tracing(void)
                MSG("");
        }
 
-       ret = CMD_SUCCESS;
-
        print_session_stats(session_name);
-       MSG("Tracing stopped for session %s", session_name);
+       MSG("Tracing stopped for session `%s`", session_name);
        if (lttng_opt_mi) {
-               ret = mi_print_session(session_name, 0);
-               if (ret) {
-                       goto free_name;
+               if (mi_print_session(session_name, 0)) {
+                       return CMD_ERROR;
                }
        }
 
-free_name:
-       if (opt_session_name == NULL) {
-               free(session_name);
+       return CMD_SUCCESS;
+}
+
+cmd_error_code stop_tracing(const lttng::cli::session_spec& spec)
+{
+       bool had_warning = false;
+       bool had_error = false;
+       bool listing_failed = false;
+
+       const auto sessions = [&listing_failed, &spec]() -> lttng::cli::session_list {
+               try {
+                       return list_sessions(spec);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       ERR_FMT("Failed to list sessions ({})",
+                               lttng_strerror(-ctl_exception.code()));
+                       listing_failed = true;
+                       return {};
+               } catch (const lttng::cli::no_default_session_error& cli_exception) {
+                       /*
+                        * The retrieval of the default session name already logs
+                        * an error when it fails. There is no value in printing
+                        * anything about this exception.
+                        */
+                       listing_failed = true;
+                       return {};
+               }
+       }();
+
+       if (!listing_failed && sessions.size() == 0 &&
+           spec.type_ == lttng::cli::session_spec::type::NAME) {
+               ERR_FMT("Session `{}` not found", spec.value);
+               return CMD_ERROR;
        }
 
-error:
-       return ret;
+       if (listing_failed) {
+               return CMD_FATAL;
+       }
+
+       for (const auto& session : sessions) {
+               cmd_error_code sub_ret;
+
+               try {
+                       sub_ret = stop_tracing(session.name);
+               } catch (const lttng::ctl::error& ctl_exception) {
+                       switch (ctl_exception.code()) {
+                       case LTTNG_ERR_TRACE_ALREADY_STOPPED:
+                               WARN_FMT("Tracing already stopped for session `{}`", session.name);
+                               sub_ret = CMD_SUCCESS;
+                               break;
+                       case LTTNG_ERR_NO_SESSION:
+                               if (spec.type_ != lttng::cli::session_spec::type::NAME) {
+                                       /* Session destroyed during command, ignore and carry-on. */
+                                       sub_ret = CMD_SUCCESS;
+                                       break;
+                               } else {
+                                       sub_ret = CMD_ERROR;
+                                       break;
+                               }
+                       case LTTNG_ERR_NO_SESSIOND:
+                               /* Don't keep going on a fatal error. */
+                               return CMD_FATAL;
+                       default:
+                               /* Generic error. */
+                               sub_ret = CMD_ERROR;
+                               ERR_FMT("Failed to stop session `{}` ({})",
+                                       session.name,
+                                       lttng_strerror(-ctl_exception.code()));
+                               break;
+                       }
+               }
+
+               /* Keep going, but report the most serious state. */
+               had_warning |= sub_ret == CMD_WARNING;
+               had_error |= sub_ret == CMD_ERROR;
+       }
+
+       if (had_error) {
+               return CMD_ERROR;
+       } else if (had_warning) {
+               return CMD_WARNING;
+       } else {
+               return CMD_SUCCESS;
+       }
 }
+} /* namespace */
 
 /*
  *  cmd_stop
@@ -159,23 +223,37 @@ error:
  */
 int cmd_stop(int argc, const char **argv)
 {
-       int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
+       int opt;
+       cmd_error_code command_ret = CMD_SUCCESS;
+       bool success = true;
        static poptContext pc;
-       const char *leftover = NULL;
+       const char *leftover = nullptr;
+       lttng::cli::session_spec session_spec(lttng::cli::session_spec::type::NAME);
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
                switch (opt) {
                case OPT_HELP:
+               {
+                       int ret;
+
                        SHOW_HELP();
+                       command_ret = static_cast<cmd_error_code>(ret);
                        goto end;
+               }
                case OPT_LIST_OPTIONS:
                        list_cmd_options(stdout, long_options);
                        goto end;
+               case OPT_ENABLE_GLOB:
+                       session_spec.type_ = lttng::cli::session_spec::type::GLOB_PATTERN;
+                       break;
+               case OPT_ALL:
+                       session_spec.type_ = lttng::cli::session_spec::type::ALL;
+                       break;
                default:
-                       ret = CMD_UNDEFINED;
+                       command_ret = CMD_UNDEFINED;
                        goto end;
                }
        }
@@ -184,23 +262,19 @@ int cmd_stop(int argc, const char **argv)
        if (lttng_opt_mi) {
                writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
                if (!writer) {
-                       ret = -LTTNG_ERR_NOMEM;
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               mi_lttng_element_command_stop);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_open(writer, mi_lttng_element_command_stop)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_open_element(writer, mi_lttng_element_command_output)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
@@ -208,49 +282,44 @@ int cmd_stop(int argc, const char **argv)
                 * Open sessions element
                 * For validation
                 */
-               ret = mi_lttng_writer_open_element(writer,
-                               config_element_sessions);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_open_element(writer, config_element_sessions)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
 
-       opt_session_name = (char*) poptGetArg(pc);
+       session_spec.value = poptGetArg(pc);
 
        leftover = poptGetArg(pc);
        if (leftover) {
                ERR("Unknown argument: %s", leftover);
-               ret = CMD_ERROR;
+               command_ret = CMD_ERROR;
                goto end;
        }
 
-       command_ret = stop_tracing();
+       command_ret = stop_tracing(session_spec);
        if (command_ret) {
-               success = 0;
+               success = false;
        }
 
        /* Mi closing */
        if (lttng_opt_mi) {
                /* Close sessions and  output element */
-               ret = mi_lttng_close_multi_element(writer, 2);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_close_multi_element(writer, 2)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success, success);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_write_element_bool(
+                           writer, mi_lttng_element_command_success, success)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Command element close */
-               ret = mi_lttng_writer_command_close(writer);
-               if (ret) {
-                       ret = CMD_ERROR;
+               if (mi_lttng_writer_command_close(writer)) {
+                       command_ret = CMD_ERROR;
                        goto end;
                }
        }
@@ -258,13 +327,9 @@ int cmd_stop(int argc, const char **argv)
 end:
        /* Mi clean-up */
        if (writer && mi_lttng_writer_destroy(writer)) {
-               /* Preserve original error code */
-               ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
+               command_ret = CMD_ERROR;
        }
 
-       /* Overwrite ret if an error occurred in stop_tracing() */
-       ret = command_ret ? command_ret : ret;
-
        poptFreeContext(pc);
-       return ret;
+       return command_ret;
 }
index e311304f4aa40bf10a491dab12d2b6f41402ab56..99f411afbc49a722506215dc1c86d8c2c5876ddb 100644 (file)
@@ -8,6 +8,16 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/dynamic-array.hpp>
+#include <common/dynamic-buffer.hpp>
+#include <common/mi-lttng.hpp>
+#include <common/optional.hpp>
+#include <common/tracker.hpp>
+
+#include <lttng/lttng.h>
+
 #include <ctype.h>
 #include <popt.h>
 #include <stdbool.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-
 #include <urcu/list.h>
 
-#include <common/dynamic-array.hpp>
-#include <common/mi-lttng.hpp>
-#include <common/optional.hpp>
-#include <common/dynamic-buffer.hpp>
-#include <common/tracker.hpp>
-
-#include <lttng/lttng.h>
-
-#include "../command.hpp"
-
 namespace {
 struct process_attr_command_args {
        enum lttng_process_attr process_attr;
@@ -66,26 +65,130 @@ static char *opt_str_arg;
 
 static struct poptOption long_options[] = {
        /* { longName, shortName, argInfo, argPtr, value, descrip, argDesc, } */
-       { "help",               'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0, },
-       { "session",            's', POPT_ARG_STRING, &opt_session_name, OPT_SESSION, 0, 0, },
-       { "kernel",             'k', POPT_ARG_VAL, &opt_kernel, 1, 0, 0, },
-       { "userspace",          'u', POPT_ARG_VAL, &opt_userspace, 1, 0, 0, },
-       { "pid",                'p', POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_PID, 0, 0, },
-       { "vpid",               0, POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_VPID, 0, 0, },
-       { "uid",                0, POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_UID, 0, 0, },
-       { "vuid",               0, POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_VUID, 0, 0, },
-       { "gid",                0, POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_GID, 0, 0, },
-       { "vgid",               0, POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL, &opt_str_arg, OPT_VGID, 0, 0, },
-       { "all",                'a', POPT_ARG_NONE, 0, OPT_ALL, 0, 0, },
-       { "list-options",       0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, 0, 0, },
-       { 0, 0, 0, 0, 0, 0, 0, },
+       {
+               "help",
+               'h',
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_HELP,
+               nullptr,
+               nullptr,
+       },
+       {
+               "session",
+               's',
+               POPT_ARG_STRING,
+               &opt_session_name,
+               OPT_SESSION,
+               nullptr,
+               nullptr,
+       },
+       {
+               "kernel",
+               'k',
+               POPT_ARG_VAL,
+               &opt_kernel,
+               1,
+               nullptr,
+               nullptr,
+       },
+       {
+               "userspace",
+               'u',
+               POPT_ARG_VAL,
+               &opt_userspace,
+               1,
+               nullptr,
+               nullptr,
+       },
+       {
+               "pid",
+               'p',
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_PID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "vpid",
+               0,
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_VPID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "uid",
+               0,
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_UID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "vuid",
+               0,
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_VUID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "gid",
+               0,
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_GID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "vgid",
+               0,
+               POPT_ARG_STRING | POPT_ARGFLAG_OPTIONAL,
+               &opt_str_arg,
+               OPT_VGID,
+               nullptr,
+               nullptr,
+       },
+       {
+               "all",
+               'a',
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_ALL,
+               nullptr,
+               nullptr,
+       },
+       {
+               "list-options",
+               0,
+               POPT_ARG_NONE,
+               nullptr,
+               OPT_LIST_OPTIONS,
+               nullptr,
+               nullptr,
+       },
+       {
+               nullptr,
+               0,
+               0,
+               nullptr,
+               0,
+               nullptr,
+               nullptr,
+       },
 };
 
 static struct process_attr_command_args
-               process_attr_commands[LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID + 1];
+       process_attr_commands[LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID + 1];
 
 static void process_attr_command_init(struct process_attr_command_args *cmd,
-               enum lttng_process_attr process_attr)
+                                     enum lttng_process_attr process_attr)
 {
        cmd->process_attr = process_attr;
        cmd->all = false;
@@ -115,7 +218,7 @@ static const char *get_capitalized_process_attr_str(enum lttng_process_attr proc
        default:
                return "Unknown";
        }
-       return NULL;
+       return nullptr;
 }
 
 static bool ust_process_attr_supported(enum lttng_process_attr *process_attr)
@@ -133,7 +236,7 @@ static bool ust_process_attr_supported(enum lttng_process_attr *process_attr)
                break;
        default:
                ERR("The %s process attribute cannot be tracked in the user space domain.",
-                               lttng_process_attr_to_string(*process_attr));
+                   lttng_process_attr_to_string(*process_attr));
                supported = false;
                break;
        }
@@ -153,22 +256,19 @@ static const char *get_mi_element_command(enum cmd_type cmd_type)
 }
 
 static enum cmd_error_code run_command_all(enum cmd_type cmd_type,
-               const char *session_name,
-               enum lttng_domain_type domain_type,
-               enum lttng_process_attr process_attr,
-               struct mi_writer *writer)
+                                          const char *session_name,
+                                          enum lttng_domain_type domain_type,
+                                          enum lttng_process_attr process_attr,
+                                          struct mi_writer *writer)
 {
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
-       const enum lttng_error_code handle_ret_code =
-                       lttng_session_get_tracker_handle(session_name,
-                                       domain_type, process_attr,
-                                       &tracker_handle);
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
+       const enum lttng_error_code handle_ret_code = lttng_session_get_tracker_handle(
+               session_name, domain_type, process_attr, &tracker_handle);
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        enum lttng_process_attr_tracker_handle_status status;
 
        if (writer) {
-               const int ret = mi_lttng_all_process_attribute_value(
-                               writer, process_attr, true);
+               const int ret = mi_lttng_all_process_attribute_value(writer, process_attr, true);
                if (ret) {
                        cmd_ret = CMD_FATAL;
                        goto end;
@@ -182,18 +282,17 @@ static enum cmd_error_code run_command_all(enum cmd_type cmd_type,
        }
 
        status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                       tracker_handle,
-                       cmd_type == CMD_TRACK ?
-                                       LTTNG_TRACKING_POLICY_INCLUDE_ALL :
+               tracker_handle,
+               cmd_type == CMD_TRACK ? LTTNG_TRACKING_POLICY_INCLUDE_ALL :
                                        LTTNG_TRACKING_POLICY_EXCLUDE_ALL);
        switch (status) {
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK:
                if (cmd_type == CMD_TRACK) {
                        MSG("%s tracking policy set to `include all`",
-                                       get_capitalized_process_attr_str(process_attr));
+                           get_capitalized_process_attr_str(process_attr));
                } else {
                        MSG("%s tracking policy set to `exclude all`",
-                                       get_capitalized_process_attr_str(process_attr));
+                           get_capitalized_process_attr_str(process_attr));
                }
                break;
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST:
@@ -201,17 +300,15 @@ static enum cmd_error_code run_command_all(enum cmd_type cmd_type,
                break;
        default:
                ERR("Unknown error encountered while setting tracking policy of %s tracker to `%s`",
-                               lttng_process_attr_to_string(process_attr),
-                               cmd_type == CMD_TRACK ? "include all" :
-                                                       "exclude all");
+                   lttng_process_attr_to_string(process_attr),
+                   cmd_type == CMD_TRACK ? "include all" : "exclude all");
                cmd_ret = CMD_FATAL;
                break;
        }
 end:
        if (writer) {
-               int ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_success,
-                               cmd_ret == CMD_SUCCESS);
+               int ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_success, cmd_ret == CMD_SUCCESS);
 
                if (ret) {
                        cmd_ret = CMD_FATAL;
@@ -225,17 +322,15 @@ end:
 }
 
 static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
-               const char *session_name,
-               enum lttng_domain_type domain_type,
-               enum lttng_process_attr process_attr,
-               const char *_args,
-               struct mi_writer *writer)
+                                             const char *session_name,
+                                             enum lttng_domain_type domain_type,
+                                             enum lttng_process_attr process_attr,
+                                             const char *_args,
+                                             struct mi_writer *writer)
 {
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
-       const enum lttng_error_code handle_ret_code =
-                       lttng_session_get_tracker_handle(session_name,
-                                       domain_type, process_attr,
-                                       &tracker_handle);
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
+       const enum lttng_error_code handle_ret_code = lttng_session_get_tracker_handle(
+               session_name, domain_type, process_attr, &tracker_handle);
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        const char *one_value_str;
        char *args = strdup(_args);
@@ -254,7 +349,7 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                goto end;
        }
 
-       while ((one_value_str = strtok_r(iter, ",", &iter)) != NULL) {
+       while ((one_value_str = strtok_r(iter, ",", &iter)) != nullptr) {
                const bool is_numerical_argument = isdigit(one_value_str[0]);
                enum lttng_process_attr_tracker_handle_status status;
                enum lttng_tracking_policy policy;
@@ -263,15 +358,14 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
 
                if (!policy_set) {
                        status = lttng_process_attr_tracker_handle_get_tracking_policy(
-                                       tracker_handle, &policy);
+                               tracker_handle, &policy);
                        if (status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                                break;
                        }
 
                        if (policy != LTTNG_TRACKING_POLICY_INCLUDE_SET) {
                                status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                                               tracker_handle,
-                                               LTTNG_TRACKING_POLICY_INCLUDE_SET);
+                                       tracker_handle, LTTNG_TRACKING_POLICY_INCLUDE_SET);
                                if (status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                                        break;
                                }
@@ -280,13 +374,11 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                }
 
                if (is_numerical_argument) {
-                       const unsigned long one_value_int =
-                                       strtoul(one_value_str, NULL, 10);
+                       const unsigned long one_value_int = strtoul(one_value_str, nullptr, 10);
 
                        if (writer) {
                                ret = mi_lttng_integral_process_attribute_value(
-                                               writer, process_attr,
-                                               (int64_t) one_value_int, true);
+                                       writer, process_attr, (int64_t) one_value_int, true);
                                if (ret) {
                                        cmd_ret = CMD_FATAL;
                                        goto end;
@@ -296,57 +388,45 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                        switch (process_attr) {
                        case LTTNG_PROCESS_ATTR_PROCESS_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_process_id_tracker_handle_add_pid(
-                                                                        tracker_handle,
-                                                                        (pid_t) one_value_int) :
-                                                        lttng_process_attr_process_id_tracker_handle_remove_pid(
-                                                                        tracker_handle,
-                                                                        (pid_t) one_value_int);
+                                       lttng_process_attr_process_id_tracker_handle_add_pid(
+                                               tracker_handle, (pid_t) one_value_int) :
+                                       lttng_process_attr_process_id_tracker_handle_remove_pid(
+                                               tracker_handle, (pid_t) one_value_int);
                                break;
                        case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
-                                                                        tracker_handle,
-                                                                        (pid_t) one_value_int) :
-                                                        lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(
-                                                                        tracker_handle,
-                                                                        (pid_t) one_value_int);
+                                       lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
+                                               tracker_handle, (pid_t) one_value_int) :
+                                       lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(
+                                               tracker_handle, (pid_t) one_value_int);
                                break;
                        case LTTNG_PROCESS_ATTR_USER_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_user_id_tracker_handle_add_uid(
-                                                                        tracker_handle,
-                                                                        (uid_t) one_value_int) :
-                                                        lttng_process_attr_user_id_tracker_handle_remove_uid(
-                                                                        tracker_handle,
-                                                                        (uid_t) one_value_int);
+                                       lttng_process_attr_user_id_tracker_handle_add_uid(
+                                               tracker_handle, (uid_t) one_value_int) :
+                                       lttng_process_attr_user_id_tracker_handle_remove_uid(
+                                               tracker_handle, (uid_t) one_value_int);
                                break;
                        case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
-                                                                        tracker_handle,
-                                                                        (uid_t) one_value_int) :
-                                                        lttng_process_attr_virtual_user_id_tracker_handle_remove_uid(
-                                                                        tracker_handle,
-                                                                        (uid_t) one_value_int);
+                                       lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
+                                               tracker_handle, (uid_t) one_value_int) :
+                                       lttng_process_attr_virtual_user_id_tracker_handle_remove_uid(
+                                               tracker_handle, (uid_t) one_value_int);
                                break;
                        case LTTNG_PROCESS_ATTR_GROUP_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_group_id_tracker_handle_add_gid(
-                                                                        tracker_handle,
-                                                                        (gid_t) one_value_int) :
-                                                        lttng_process_attr_group_id_tracker_handle_remove_gid(
-                                                                        tracker_handle,
-                                                                        (gid_t) one_value_int);
+                                       lttng_process_attr_group_id_tracker_handle_add_gid(
+                                               tracker_handle, (gid_t) one_value_int) :
+                                       lttng_process_attr_group_id_tracker_handle_remove_gid(
+                                               tracker_handle, (gid_t) one_value_int);
                                break;
                        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
-                                                                        tracker_handle,
-                                                                        (gid_t) one_value_int) :
-                                                        lttng_process_attr_virtual_group_id_tracker_handle_remove_gid(
-                                                                        tracker_handle,
-                                                                        (gid_t) one_value_int);
+                                       lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
+                                               tracker_handle, (gid_t) one_value_int) :
+                                       lttng_process_attr_virtual_group_id_tracker_handle_remove_gid(
+                                               tracker_handle, (gid_t) one_value_int);
                                break;
                        default:
                                abort();
@@ -355,8 +435,7 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                } else {
                        if (writer) {
                                ret = mi_lttng_string_process_attribute_value(
-                                               writer, process_attr,
-                                               one_value_str, true);
+                                       writer, process_attr, one_value_str, true);
                                if (ret) {
                                        cmd_ret = CMD_FATAL;
                                        goto end;
@@ -366,53 +445,43 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                        switch (process_attr) {
                        case LTTNG_PROCESS_ATTR_USER_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_user_id_tracker_handle_add_user_name(
-                                                                        tracker_handle,
-                                                                        one_value_str) :
-                                                        lttng_process_attr_user_id_tracker_handle_remove_user_name(
-                                                                        tracker_handle,
-                                                                        one_value_str);
+                                       lttng_process_attr_user_id_tracker_handle_add_user_name(
+                                               tracker_handle, one_value_str) :
+                                       lttng_process_attr_user_id_tracker_handle_remove_user_name(
+                                               tracker_handle, one_value_str);
                                break;
                        case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
-                                                                        tracker_handle,
-                                                                        one_value_str) :
-                                                        lttng_process_attr_virtual_user_id_tracker_handle_remove_user_name(
-                                                                        tracker_handle,
-                                                                        one_value_str);
+                                       lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
+                                               tracker_handle, one_value_str) :
+                                       lttng_process_attr_virtual_user_id_tracker_handle_remove_user_name(
+                                               tracker_handle, one_value_str);
                                break;
                        case LTTNG_PROCESS_ATTR_GROUP_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_group_id_tracker_handle_add_group_name(
-                                                                        tracker_handle,
-                                                                        one_value_str) :
-                                                        lttng_process_attr_group_id_tracker_handle_remove_group_name(
-                                                                        tracker_handle,
-                                                                        one_value_str);
+                                       lttng_process_attr_group_id_tracker_handle_add_group_name(
+                                               tracker_handle, one_value_str) :
+                                       lttng_process_attr_group_id_tracker_handle_remove_group_name(
+                                               tracker_handle, one_value_str);
                                break;
                        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                                status = cmd_type == CMD_TRACK ?
-                                                        lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
-                                                                        tracker_handle,
-                                                                        one_value_str) :
-                                                        lttng_process_attr_virtual_group_id_tracker_handle_remove_group_name(
-                                                                        tracker_handle,
-                                                                        one_value_str);
+                                       lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
+                                               tracker_handle, one_value_str) :
+                                       lttng_process_attr_virtual_group_id_tracker_handle_remove_group_name(
+                                               tracker_handle, one_value_str);
                                break;
                        default:
                                ERR("%s is not a valid %s value; expected an integer",
-                                               one_value_str,
-                                               lttng_process_attr_to_string(
-                                                               process_attr));
+                                   one_value_str,
+                                   lttng_process_attr_to_string(process_attr));
                                cmd_ret = CMD_FATAL;
                                goto end;
                        }
                }
 
-               ret = asprintf(&prettified_arg,
-                               is_numerical_argument ? "%s" : "`%s`",
-                               one_value_str);
+               ret = asprintf(
+                       &prettified_arg, is_numerical_argument ? "%s" : "`%s`", one_value_str);
                if (ret < 0) {
                        PERROR("Failed to format argument `%s`", one_value_str);
                        cmd_ret = CMD_FATAL;
@@ -423,14 +492,12 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK:
                        if (cmd_type == CMD_TRACK) {
                                MSG("Added %s to the %s tracker inclusion set",
-                                               one_value_str,
-                                               lttng_process_attr_to_string(
-                                                               process_attr));
+                                   one_value_str,
+                                   lttng_process_attr_to_string(process_attr));
                        } else {
                                MSG("Removed %s from the %s tracker inclusion set",
-                                               one_value_str,
-                                               lttng_process_attr_to_string(
-                                                               process_attr));
+                                   one_value_str,
+                                   lttng_process_attr_to_string(process_attr));
                        }
                        break;
                case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST:
@@ -438,15 +505,13 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                        break;
                case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_EXISTS:
                        WARN("%s is already in the %s inclusion set",
-                                       prettified_arg,
-                                       lttng_process_attr_to_string(
-                                                       process_attr));
+                            prettified_arg,
+                            lttng_process_attr_to_string(process_attr));
                        break;
                case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_MISSING:
                        WARN("%s is not in the %s the inclusion set",
-                                       prettified_arg,
-                                       lttng_process_attr_to_string(
-                                                       process_attr));
+                            prettified_arg,
+                            lttng_process_attr_to_string(process_attr));
                        break;
                case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_USER_NOT_FOUND:
                        ERR("User %s was not found", prettified_arg);
@@ -458,21 +523,18 @@ static enum cmd_error_code run_command_string(enum cmd_type cmd_type,
                        break;
                default:
                        ERR("Unknown error encountered while %s %s %s %s tracker's inclusion set",
-                                       cmd_type == CMD_TRACK ? "adding" :
-                                                               "removing",
-                                       lttng_process_attr_to_string(
-                                                       process_attr),
-                                       prettified_arg,
-                                       cmd_type == CMD_TRACK ? "to" : "from");
+                           cmd_type == CMD_TRACK ? "adding" : "removing",
+                           lttng_process_attr_to_string(process_attr),
+                           prettified_arg,
+                           cmd_type == CMD_TRACK ? "to" : "from");
                        cmd_ret = CMD_FATAL;
                        break;
                }
                free(prettified_arg);
 
                if (writer) {
-                       ret = mi_lttng_writer_write_element_bool(writer,
-                                       mi_lttng_element_success,
-                                       cmd_ret == CMD_SUCCESS);
+                       ret = mi_lttng_writer_write_element_bool(
+                               writer, mi_lttng_element_success, cmd_ret == CMD_SUCCESS);
 
                        if (ret) {
                                cmd_ret = CMD_FATAL;
@@ -489,17 +551,16 @@ end:
 }
 
 static enum cmd_error_code run_command(enum cmd_type cmd_type,
-               const char *session_name,
-               const struct process_attr_command_args *command_args,
-               struct mi_writer *writer)
+                                      const char *session_name,
+                                      const struct process_attr_command_args *command_args,
+                                      struct mi_writer *writer)
 {
-       const enum lttng_domain_type domain_type =
-                       opt_kernel ? LTTNG_DOMAIN_KERNEL : LTTNG_DOMAIN_UST;
+       const enum lttng_domain_type domain_type = opt_kernel ? LTTNG_DOMAIN_KERNEL :
+                                                               LTTNG_DOMAIN_UST;
        enum cmd_error_code cmd_ret = CMD_SUCCESS;
        unsigned int i;
        const unsigned int string_arg_count =
-                       lttng_dynamic_pointer_array_get_count(
-                                       &command_args->string_args);
+               lttng_dynamic_pointer_array_get_count(&command_args->string_args);
        enum lttng_process_attr process_attr = command_args->process_attr;
 
        if (opt_userspace) {
@@ -516,8 +577,7 @@ static enum cmd_error_code run_command(enum cmd_type cmd_type,
 
        if (writer) {
                /* Open tracker and trackers elements */
-               const int ret = mi_lttng_process_attribute_tracker_open(
-                               writer, process_attr);
+               const int ret = mi_lttng_process_attribute_tracker_open(writer, process_attr);
                if (ret) {
                        cmd_ret = CMD_FATAL;
                        goto end;
@@ -525,17 +585,17 @@ static enum cmd_error_code run_command(enum cmd_type cmd_type,
        }
 
        if (command_args->all) {
-               cmd_ret = run_command_all(cmd_type, session_name, domain_type,
-                               process_attr, writer);
+               cmd_ret =
+                       run_command_all(cmd_type, session_name, domain_type, process_attr, writer);
        } else {
                bool error_occurred = false;
 
                for (i = 0; i < string_arg_count; i++) {
                        const char *arg = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                                       &command_args->string_args, i);
+                               &command_args->string_args, i);
 
-                       cmd_ret = run_command_string(cmd_type, session_name,
-                                       domain_type, process_attr, arg, writer);
+                       cmd_ret = run_command_string(
+                               cmd_type, session_name, domain_type, process_attr, arg, writer);
                        if (cmd_ret != CMD_SUCCESS) {
                                error_occurred = true;
                                if (cmd_ret == CMD_FATAL) {
@@ -551,8 +611,7 @@ static enum cmd_error_code run_command(enum cmd_type cmd_type,
 
        if (writer) {
                /* Close tracker and trackers elements */
-               const int ret = mi_lttng_close_multi_element(
-                               writer, 2);
+               const int ret = mi_lttng_close_multi_element(writer, 2);
                if (ret) {
                        cmd_ret = CMD_FATAL;
                        goto end;
@@ -566,22 +625,21 @@ end:
  * Add/remove tracker to/from session.
  */
 static int cmd_track_untrack(enum cmd_type cmd_type,
-               int argc,
-               const char **argv,
-               const char *help_msg __attribute__((unused)))
+                            int argc,
+                            const char **argv,
+                            const char *help_msg __attribute__((unused)))
 {
        int opt, ret = 0;
        bool sub_command_failed = false;
        bool opt_all = false;
        unsigned int selected_process_attr_tracker_count = 0;
        const unsigned int command_count =
-                       sizeof(process_attr_commands) /
-                       sizeof(struct process_attr_command_args);
+               sizeof(process_attr_commands) / sizeof(struct process_attr_command_args);
        enum cmd_error_code command_ret = CMD_SUCCESS;
        static poptContext pc;
-       char *session_name = NULL;
-       const char *leftover = NULL;
-       struct mi_writer *writer = NULL;
+       char *session_name = nullptr;
+       const char *leftover = nullptr;
+       struct mi_writer *writer = nullptr;
        size_t i;
 
        for (i = 0; i < command_count; i++) {
@@ -593,7 +651,7 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                goto end;
        }
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -620,8 +678,7 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                                continue;
                        }
                        ret = lttng_dynamic_pointer_array_add_pointer(
-                                       &process_attr_commands[opt].string_args,
-                                       opt_str_arg);
+                               &process_attr_commands[opt].string_args, opt_str_arg);
                        if (ret) {
                                ERR("Allocation failed while parsing command arguments");
                                command_ret = CMD_ERROR;
@@ -637,8 +694,7 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                }
        }
 
-       ret = print_missing_or_multiple_domains(
-                       opt_kernel + opt_userspace, false);
+       ret = print_missing_or_multiple_domains(opt_kernel + opt_userspace, false);
        if (ret) {
                command_ret = CMD_ERROR;
                goto end;
@@ -660,8 +716,7 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                        }
                        process_attr_commands[i].all = true;
                        if (lttng_dynamic_pointer_array_get_count(
-                                           &process_attr_commands[i]
-                                                            .string_args)) {
+                                   &process_attr_commands[i].string_args)) {
                                ERR("The --all option cannot be used with a list of process attribute values");
                                command_ret = CMD_ERROR;
                                goto end;
@@ -673,12 +728,10 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                                continue;
                        }
                        if (lttng_dynamic_pointer_array_get_count(
-                                   &process_attr_commands[i]
-                                   .string_args) == 0) {
+                                   &process_attr_commands[i].string_args) == 0) {
                                ERR("No process attribute value specified for %s tracker",
-                                               get_capitalized_process_attr_str(
-                                                               process_attr_commands[i]
-                                                                               .process_attr));
+                                   get_capitalized_process_attr_str(
+                                           process_attr_commands[i].process_attr));
                                command_ret = CMD_ERROR;
                                goto end;
                        }
@@ -687,7 +740,7 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
 
        if (!opt_session_name) {
                session_name = get_session_name();
-               if (session_name == NULL) {
+               if (session_name == nullptr) {
                        command_ret = CMD_ERROR;
                        goto end;
                }
@@ -713,16 +766,14 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
 
        if (writer) {
                /* Open command element */
-               ret = mi_lttng_writer_command_open(writer,
-                               get_mi_element_command(cmd_type));
+               ret = mi_lttng_writer_command_open(writer, get_mi_element_command(cmd_type));
                if (ret) {
                        command_ret = CMD_ERROR;
                        goto end;
                }
 
                /* Open output element */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_command_output);
+               ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
                if (ret) {
                        command_ret = CMD_ERROR;
                        goto end;
@@ -739,8 +790,8 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                if (!process_attr_commands[i].requested) {
                        continue;
                }
-               command_ret = run_command(cmd_type, session_name,
-                               &process_attr_commands[i], writer);
+               command_ret =
+                       run_command(cmd_type, session_name, &process_attr_commands[i], writer);
                if (command_ret != CMD_SUCCESS) {
                        sub_command_failed = true;
                        if (command_ret == CMD_FATAL) {
@@ -759,9 +810,8 @@ static int cmd_track_untrack(enum cmd_type cmd_type,
                }
 
                /* Success ? */
-               ret = mi_lttng_writer_write_element_bool(writer,
-                               mi_lttng_element_command_success,
-                               !sub_command_failed);
+               ret = mi_lttng_writer_write_element_bool(
+                       writer, mi_lttng_element_command_success, !sub_command_failed);
                if (ret) {
                        command_ret = CMD_ERROR;
                        goto end;
@@ -800,9 +850,9 @@ int cmd_track(int argc, const char **argv)
 #ifdef LTTNG_EMBED_HELP
 #include <lttng-track.1.h>
 #else
-       NULL
+               nullptr
 #endif
-       ;
+               ;
 
        return cmd_track_untrack(CMD_TRACK, argc, argv, help_msg);
 }
@@ -813,9 +863,9 @@ int cmd_untrack(int argc, const char **argv)
 #ifdef LTTNG_EMBED_HELP
 #include <lttng-untrack.1.h>
 #else
-       NULL
+               nullptr
 #endif
-       ;
+               ;
 
        return cmd_track_untrack(CMD_UNTRACK, argc, argv, help_msg);
 }
index e4aed95ad8ac3ad442442240098598c9e05ffe95..836e8f489d194c3de9e82a94d871d91d9f05e388 100644 (file)
@@ -6,6 +6,11 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+#include "version.hpp"
+
+#include <common/mi-lttng.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/mi-lttng.hpp>
-
-#include "../command.hpp"
-#include "version.hpp"
-
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-version.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -34,9 +34,9 @@ static const char *lttng_license = "lttng is free software and under the GPL lic
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",      'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /*
@@ -56,10 +56,10 @@ static void create_version(struct mi_lttng_version_data *version)
 /*
  * Print the machine interface output of this command.
  */
-static int print_mi(void)
+static int print_mi()
 {
        int ret = CMD_SUCCESS;
-       struct mi_writer *writer = NULL;
+       struct mi_writer *writer = nullptr;
        struct mi_lttng_version_data version;
 
        create_version(&version);
@@ -71,24 +71,21 @@ static int print_mi(void)
        }
 
        /* Open the command element */
-       ret = mi_lttng_writer_command_open(writer,
-                       mi_lttng_element_command_version);
+       ret = mi_lttng_writer_command_open(writer, mi_lttng_element_command_version);
        if (ret) {
                ret = CMD_ERROR;
                goto error;
        }
 
        /* Beginning of output */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_output);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_output);
        if (ret) {
                ret = CMD_ERROR;
                goto error;
        }
 
        /* Print the machine interface of version */
-       ret = mi_lttng_version(writer, &version,
-                       VERSION_DESCRIPTION, lttng_license);
+       ret = mi_lttng_version(writer, &version, VERSION_DESCRIPTION, lttng_license);
        if (ret) {
                ret = CMD_ERROR;
                goto error;
@@ -126,7 +123,7 @@ int cmd_version(int argc, const char **argv)
        int opt, ret = CMD_SUCCESS;
        static poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        while ((opt = poptGetNextOpt(pc)) != -1) {
@@ -147,7 +144,7 @@ int cmd_version(int argc, const char **argv)
                ret = print_mi();
        } else {
                MSG("lttng version " VERSION " - " VERSION_NAME "%s",
-                       GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION);
+                   GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION);
                MSG("\n" VERSION_DESCRIPTION "\n");
                MSG("Web site: https://lttng.org");
                MSG("\n%s", lttng_license);
index 1bf2648714193fd9270c57ef30931224c759ed09..9a7557e40dbd07144c557bdd463e4ba537f637be 100644 (file)
@@ -6,6 +6,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "../command.hpp"
+
+#include <common/spawn-viewer.hpp>
+
 #include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/spawn-viewer.hpp>
-#include "../command.hpp"
-
-static char *opt_session_name;
 static char *opt_viewer;
 static char *opt_trace_path;
 
 #ifdef LTTNG_EMBED_HELP
 static const char help_msg[] =
 #include <lttng-view.1.h>
-;
+       ;
 #endif
 
 enum {
@@ -34,11 +34,11 @@ enum {
 
 static struct poptOption long_options[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       {"help",        'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
-       {"list-options", 0,  POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
-       {"viewer",      'e', POPT_ARG_STRING, &opt_viewer, 0, 0, 0},
-       {"trace-path",  't', POPT_ARG_STRING, &opt_trace_path, 0, 0, 0},
-       {0, 0, 0, 0, 0, 0, 0}
+       { "help", 'h', POPT_ARG_NONE, nullptr, OPT_HELP, nullptr, nullptr },
+       { "list-options", 0, POPT_ARG_NONE, nullptr, OPT_LIST_OPTIONS, nullptr, nullptr },
+       { "viewer", 'e', POPT_ARG_STRING, &opt_viewer, 0, nullptr, nullptr },
+       { "trace-path", 't', POPT_ARG_STRING, &opt_trace_path, 0, nullptr, nullptr },
+       { nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
 /* Is the session we are trying to view is in live mode. */
@@ -50,7 +50,7 @@ static int session_live_mode;
 static char *build_live_path(char *session_name)
 {
        int ret;
-       char *path = NULL;
+       char *path = nullptr;
        char hostname[LTTNG_HOST_NAME_MAX];
 
        ret = gethostname(hostname, sizeof(hostname));
@@ -59,8 +59,7 @@ static char *build_live_path(char *session_name)
                goto error;
        }
 
-       ret = asprintf(&path, "net://localhost/host/%s/%s", hostname,
-                       session_name);
+       ret = asprintf(&path, "net://localhost/host/%s/%s", hostname, session_name);
        if (ret < 0) {
                PERROR("asprintf live path");
                goto error;
@@ -73,11 +72,11 @@ error:
 /*
  * Exec viewer if found and use session name path.
  */
-static int view_trace(void)
+static int view_trace(const char *arg_session_name)
 {
        int ret;
-       char *session_name, *trace_path = NULL;
-       struct lttng_session *sessions = NULL;
+       char *session_name, *trace_path = nullptr;
+       struct lttng_session *sessions = nullptr;
        bool free_trace_path = false;
 
        /*
@@ -98,15 +97,21 @@ static int view_trace(void)
 
        /* User define trace path override the session name */
        if (opt_trace_path) {
-               session_name = NULL;
-       } else if(opt_session_name == NULL) {
-               session_name = get_session_name();
-               if (session_name == NULL) {
+               session_name = nullptr;
+       } else {
+               if (arg_session_name == nullptr) {
+                       session_name = get_session_name();
+               } else {
+                       session_name = strdup(arg_session_name);
+                       if (session_name == nullptr) {
+                               PERROR("Failed to copy session name");
+                       }
+               }
+
+               if (session_name == nullptr) {
                        ret = CMD_ERROR;
                        goto error;
                }
-       } else {
-               session_name = opt_session_name;
        }
 
        DBG("Viewing trace for session %s", session_name);
@@ -117,8 +122,7 @@ static int view_trace(void)
                /* Getting all sessions */
                count = lttng_list_sessions(&sessions);
                if (count < 0) {
-                       ERR("Unable to list sessions. Session name %s not found.",
-                                       session_name);
+                       ERR("Unable to list sessions. Session name %s not found.", session_name);
                        MSG("Is there a session daemon running?");
                        ret = CMD_ERROR;
                        goto free_error;
@@ -144,7 +148,7 @@ static int view_trace(void)
 
                if (sessions[i].enabled && !session_live_mode) {
                        WARN("Session %s is running. Please stop it before reading it.",
-                                       session_name);
+                            session_name);
                        ret = CMD_ERROR;
                        goto free_sessions;
                }
@@ -179,9 +183,7 @@ free_sessions:
        }
        free(sessions);
 free_error:
-       if (opt_session_name == NULL) {
-               free(session_name);
-       }
+       free(session_name);
 error:
        return ret;
 }
@@ -193,9 +195,10 @@ int cmd_view(int argc, const char **argv)
 {
        int opt, ret = CMD_SUCCESS;
        static poptContext pc;
-       const char *leftover = NULL;
+       const char *arg_session_name = nullptr;
+       const char *leftover = nullptr;
 
-       pc = poptGetContext(NULL, argc, argv, long_options, 0);
+       pc = poptGetContext(nullptr, argc, argv, long_options, 0);
        poptReadDefaultConfig(pc, 0);
 
        if (lttng_opt_mi) {
@@ -216,7 +219,7 @@ int cmd_view(int argc, const char **argv)
                }
        }
 
-       opt_session_name = (char*) poptGetArg(pc);
+       arg_session_name = poptGetArg(pc);
 
        leftover = poptGetArg(pc);
        if (leftover) {
@@ -225,7 +228,7 @@ int cmd_view(int argc, const char **argv)
                goto end;
        }
 
-       ret = view_trace();
+       ret = view_trace(arg_session_name);
 
 end:
        poptFreeContext(pc);
index 33550eb3778fe5fb636c0700618b153804f84057..65be35a158f70518dda1317f78900347ba67b117 100644 (file)
@@ -6,6 +6,12 @@
  */
 
 #define _LGPL_SOURCE
+#include "conf.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/utils.hpp>
+
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/compat/errno.hpp>
-#include <common/common.hpp>
-#include <common/utils.hpp>
-
-#include "conf.hpp"
-
 /*
  * Returns the path with '/CONFIG_FILENAME' added to it;
  * path will be NULL if an error occurs.
@@ -32,7 +32,7 @@ char *config_get_file_path(const char *path)
        ret = asprintf(&file_path, "%s/%s", path, CONFIG_FILENAME);
        if (ret < 0) {
                ERR("Fail allocating config file path");
-               file_path = NULL;
+               file_path = nullptr;
        }
 
        return file_path;
@@ -44,16 +44,16 @@ char *config_get_file_path(const char *path)
  */
 static FILE *open_config(const char *path, const char *mode)
 {
-       FILE *fp = NULL;
+       FILE *fp = nullptr;
        char *file_path;
 
        file_path = config_get_file_path(path);
-       if (file_path == NULL) {
+       if (file_path == nullptr) {
                goto error;
        }
 
        fp = fopen(file_path, mode);
-       if (fp == NULL) {
+       if (fp == nullptr) {
                goto error;
        }
 
@@ -73,7 +73,7 @@ static int create_config_file(const char *path)
        FILE *fp;
 
        fp = open_config(path, "w+");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                ERR("Unable to create config file");
                ret = -1;
                goto error;
@@ -97,7 +97,7 @@ static int write_config(const char *file_path, size_t size, char *data)
        int ret = 0;
 
        fp = open_config(file_path, "a");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                ret = -1;
                goto end;
        }
@@ -123,7 +123,7 @@ void config_destroy(const char *path)
        char *config_path;
 
        config_path = config_get_file_path(path);
-       if (config_path == NULL) {
+       if (config_path == nullptr) {
                return;
        }
 
@@ -143,10 +143,10 @@ end:
 /*
  * Destroys the default config
  */
-void config_destroy_default(void)
+void config_destroy_default()
 {
        const char *path = utils_get_home_dir();
-       if (path == NULL) {
+       if (path == nullptr) {
                return;
        }
        config_destroy(path);
@@ -167,34 +167,35 @@ int config_exists(const char *path)
        return S_ISREG(info.st_mode) || S_ISDIR(info.st_mode);
 }
 
-static
-int _config_read_session_name(const char *path, char **name)
+static int _config_read_session_name(const char *path, char **name)
 {
        int ret = 0;
        FILE *fp;
        char var[NAME_MAX], *session_name;
 
 #if (NAME_MAX == 255)
-#define NAME_MAX_SCANF_IS_A_BROKEN_API "254"
+#define NAME_MAX_SCANF_IS_A_BROKEN_API "254"
 #endif
 
        session_name = calloc<char>(NAME_MAX);
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret = -ENOMEM;
                ERR("Out of memory");
                goto error;
        }
 
        fp = open_config(path, "r");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                ret = -ENOENT;
                goto error;
        }
 
        while (!feof(fp)) {
-               if ((ret = fscanf(fp, "%" NAME_MAX_SCANF_IS_A_BROKEN_API
-                               "[^'=']=%" NAME_MAX_SCANF_IS_A_BROKEN_API "s\n",
-                               var, session_name)) != 2) {
+               if ((ret = fscanf(fp,
+                                 "%" NAME_MAX_SCANF_IS_A_BROKEN_API
+                                 "[^'=']=%" NAME_MAX_SCANF_IS_A_BROKEN_API "s\n",
+                                 var,
+                                 session_name)) != 2) {
                        if (ret == -1) {
                                ERR("Missing session=NAME in config file.");
                                goto error_close;
@@ -231,7 +232,7 @@ found:
 char *config_read_session_name(const char *path)
 {
        int ret;
-       char *name = NULL;
+       char *name = nullptr;
 
        ret = _config_read_session_name(path, &name);
        if (ret == -ENOENT) {
@@ -252,7 +253,7 @@ char *config_read_session_name(const char *path)
  */
 char *config_read_session_name_quiet(const char *path)
 {
-       char *name = NULL;
+       char *name = nullptr;
 
        (void) _config_read_session_name(path, &name);
        return name;
@@ -295,7 +296,7 @@ int config_init(const char *session_name)
        const char *path;
 
        path = utils_get_home_dir();
-       if (path == NULL) {
+       if (path == nullptr) {
                ret = -1;
                goto error;
        }
index e1260c772371f34910bc5fe3989ec467c41caff8..cda2763a3fa362f4882bb71a1ded820dd20b6f6e 100644 (file)
@@ -11,7 +11,7 @@
 #define CONFIG_FILENAME ".lttngrc"
 
 void config_destroy(const char *path);
-void config_destroy_default(void);
+void config_destroy_default();
 int config_exists(const char *path);
 int config_init(const char *path);
 int config_add_session_name(const char *path, const char *name);
diff --git a/src/bin/lttng/exception.cpp b/src/bin/lttng/exception.cpp
new file mode 100644 (file)
index 0000000..8995d5e
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "exception.hpp"
+
+#include <common/format.hpp>
+#include <common/utils.hpp>
+
+#include <sstream>
+
+lttng::cli::no_default_session_error::no_default_session_error(const char *file_name,
+                                                              const char *function_name,
+                                                              unsigned int line_number) :
+       runtime_error(lttng::format("No default session found in `{}/.lttngrc`",
+                                   utils_get_home_dir() ?: "LTTNG_HOME"),
+                     file_name,
+                     function_name,
+                     line_number)
+{
+}
diff --git a/src/bin/lttng/exception.hpp b/src/bin/lttng/exception.hpp
new file mode 100644 (file)
index 0000000..00448f9
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2024 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_CLI_EXCEPTION_H
+#define LTTNG_CLI_EXCEPTION_H
+
+#include <common/exception.hpp>
+
+#include <lttng/lttng-error.h>
+
+#include <stdexcept>
+#include <string>
+
+#define LTTNG_THROW_CLI_NO_DEFAULT_SESSION() \
+       throw lttng::cli::no_default_session_error(__FILE__, __func__, __LINE__)
+
+namespace lttng {
+namespace cli {
+class no_default_session_error : public runtime_error {
+public:
+       explicit no_default_session_error(const char *file_name,
+                                         const char *function_name,
+                                         unsigned int line_number);
+};
+} /* namespace cli */
+}; /* namespace lttng */
+
+#endif /* LTTNG_CLI_EXCEPTION_H */
index 6b9881a025bcd8004982b059fd4fd99e4f96657a..73940723628b18ba04b410496ddcfd46f04a73ba 100644 (file)
@@ -6,9 +6,10 @@
  */
 
 #include "loglevel.hpp"
+
+#include <ctype.h>
 #include <string.h>
 #include <strings.h>
-#include <ctype.h>
 
 namespace {
 struct loglevel_name_value {
@@ -17,8 +18,7 @@ struct loglevel_name_value {
 };
 } /* namespace */
 
-static
-const struct loglevel_name_value loglevel_values[] = {
+static const struct loglevel_name_value loglevel_values[] = {
        { .name = "EMERG", .value = LTTNG_LOGLEVEL_EMERG },
        { .name = "TRACE_EMERG", .value = LTTNG_LOGLEVEL_EMERG },
        { .name = "ALERT", .value = LTTNG_LOGLEVEL_ALERT },
@@ -58,8 +58,7 @@ const struct loglevel_name_value loglevel_values[] = {
        { .name = "TRACE_DEBUG", .value = LTTNG_LOGLEVEL_DEBUG },
 };
 
-static
-const struct loglevel_name_value loglevel_log4j_values[] = {
+static const struct loglevel_name_value loglevel_log4j_values[] = {
        { .name = "OFF", .value = LTTNG_LOGLEVEL_LOG4J_OFF },
        { .name = "LOG4J_OFF", .value = LTTNG_LOGLEVEL_LOG4J_OFF },
        { .name = "FATAL", .value = LTTNG_LOGLEVEL_LOG4J_FATAL },
@@ -78,8 +77,7 @@ const struct loglevel_name_value loglevel_log4j_values[] = {
        { .name = "LOG4J_ALL", .value = LTTNG_LOGLEVEL_LOG4J_ALL },
 };
 
-static
-const struct loglevel_name_value loglevel_jul_values[] = {
+static const struct loglevel_name_value loglevel_jul_values[] = {
        { .name = "OFF", .value = LTTNG_LOGLEVEL_JUL_OFF },
        { .name = "JUL_OFF", .value = LTTNG_LOGLEVEL_JUL_OFF },
        { .name = "SEVERE", .value = LTTNG_LOGLEVEL_JUL_SEVERE },
@@ -100,8 +98,7 @@ const struct loglevel_name_value loglevel_jul_values[] = {
        { .name = "JUL_ALL", .value = LTTNG_LOGLEVEL_JUL_ALL },
 };
 
-static
-const struct loglevel_name_value loglevel_python_values[] = {
+static const struct loglevel_name_value loglevel_python_values[] = {
        { .name = "CRITICAL", .value = LTTNG_LOGLEVEL_PYTHON_CRITICAL },
        { .name = "PYTHON_CRITICAL", .value = LTTNG_LOGLEVEL_PYTHON_CRITICAL },
        { .name = "ERROR", .value = LTTNG_LOGLEVEL_PYTHON_ERROR },
@@ -116,15 +113,14 @@ const struct loglevel_name_value loglevel_python_values[] = {
        { .name = "PYTHON_NOTSET", .value = LTTNG_LOGLEVEL_PYTHON_NOTSET },
 };
 
-static
-bool string_equal_insensitive(const char *a, const char *b)
+static bool string_equal_insensitive(const char *a, const char *b)
 {
        return strcasecmp(a, b) == 0;
 }
 
-static
-int lookup_value_from_name(const struct loglevel_name_value values[],
-               size_t values_count, const char *name)
+static int lookup_value_from_name(const struct loglevel_name_value values[],
+                                 size_t values_count,
+                                 const char *name)
 {
        size_t i;
        int ret = -1;
@@ -146,10 +142,10 @@ end:
 }
 
 static bool loglevel_parse_range_string_common(const char *str,
-               const struct loglevel_name_value *nvs,
-               size_t nvs_count,
-               int *min,
-               int *max)
+                                              const struct loglevel_name_value *nvs,
+                                              size_t nvs_count,
+                                              int *min,
+                                              int *max)
 {
        bool ret;
        int i;
@@ -214,8 +210,7 @@ end:
 
 int loglevel_name_to_value(const char *name, enum lttng_loglevel *loglevel)
 {
-       int ret = lookup_value_from_name(loglevel_values,
-                       ARRAY_SIZE(loglevel_values), name);
+       int ret = lookup_value_from_name(loglevel_values, ARRAY_SIZE(loglevel_values), name);
 
        if (ret >= 0) {
                *loglevel = (typeof(*loglevel)) ret;
@@ -226,12 +221,12 @@ int loglevel_name_to_value(const char *name, enum lttng_loglevel *loglevel)
 }
 
 bool loglevel_parse_range_string(const char *str,
-               enum lttng_loglevel *min,
-               enum lttng_loglevel *max)
+                                enum lttng_loglevel *min,
+                                enum lttng_loglevel *max)
 {
        int min_int, max_int;
-       bool ret = loglevel_parse_range_string_common(str, loglevel_values,
-                       ARRAY_SIZE(loglevel_values), &min_int, &max_int);
+       bool ret = loglevel_parse_range_string_common(
+               str, loglevel_values, ARRAY_SIZE(loglevel_values), &min_int, &max_int);
 
        *min = (lttng_loglevel) min_int;
        *max = (lttng_loglevel) max_int;
@@ -239,12 +234,10 @@ bool loglevel_parse_range_string(const char *str,
        return ret;
 }
 
-int loglevel_log4j_name_to_value(
-               const char *name, enum lttng_loglevel_log4j *loglevel)
+int loglevel_log4j_name_to_value(const char *name, enum lttng_loglevel_log4j *loglevel)
 {
-       int ret = lookup_value_from_name(loglevel_log4j_values,
-                       ARRAY_SIZE(loglevel_log4j_values),
-                       name);
+       int ret = lookup_value_from_name(
+               loglevel_log4j_values, ARRAY_SIZE(loglevel_log4j_values), name);
 
        if (ret >= 0) {
                *loglevel = (typeof(*loglevel)) ret;
@@ -255,13 +248,12 @@ int loglevel_log4j_name_to_value(
 }
 
 bool loglevel_log4j_parse_range_string(const char *str,
-               enum lttng_loglevel_log4j *min,
-               enum lttng_loglevel_log4j *max)
+                                      enum lttng_loglevel_log4j *min,
+                                      enum lttng_loglevel_log4j *max)
 {
        int min_int, max_int;
-       bool ret = loglevel_parse_range_string_common(str,
-                       loglevel_log4j_values,
-                       ARRAY_SIZE(loglevel_log4j_values), &min_int, &max_int);
+       bool ret = loglevel_parse_range_string_common(
+               str, loglevel_log4j_values, ARRAY_SIZE(loglevel_log4j_values), &min_int, &max_int);
 
        *min = (lttng_loglevel_log4j) min_int;
        *max = (lttng_loglevel_log4j) max_int;
@@ -269,12 +261,10 @@ bool loglevel_log4j_parse_range_string(const char *str,
        return ret;
 }
 
-int loglevel_jul_name_to_value(
-               const char *name, enum lttng_loglevel_jul *loglevel)
+int loglevel_jul_name_to_value(const char *name, enum lttng_loglevel_jul *loglevel)
 {
-       int ret = lookup_value_from_name(loglevel_jul_values,
-                       ARRAY_SIZE(loglevel_jul_values),
-                       name);
+       int ret =
+               lookup_value_from_name(loglevel_jul_values, ARRAY_SIZE(loglevel_jul_values), name);
 
        if (ret >= 0) {
                *loglevel = (typeof(*loglevel)) ret;
@@ -285,12 +275,12 @@ int loglevel_jul_name_to_value(
 }
 
 bool loglevel_jul_parse_range_string(const char *str,
-               enum lttng_loglevel_jul *min,
-               enum lttng_loglevel_jul *max)
+                                    enum lttng_loglevel_jul *min,
+                                    enum lttng_loglevel_jul *max)
 {
        int min_int, max_int;
-       bool ret = loglevel_parse_range_string_common(str, loglevel_jul_values,
-                       ARRAY_SIZE(loglevel_jul_values), &min_int, &max_int);
+       bool ret = loglevel_parse_range_string_common(
+               str, loglevel_jul_values, ARRAY_SIZE(loglevel_jul_values), &min_int, &max_int);
 
        *min = (lttng_loglevel_jul) min_int;
        *max = (lttng_loglevel_jul) max_int;
@@ -298,12 +288,10 @@ bool loglevel_jul_parse_range_string(const char *str,
        return ret;
 }
 
-int loglevel_python_name_to_value(
-               const char *name, enum lttng_loglevel_python *loglevel)
+int loglevel_python_name_to_value(const char *name, enum lttng_loglevel_python *loglevel)
 {
-       int ret = lookup_value_from_name(loglevel_python_values,
-                       ARRAY_SIZE(loglevel_python_values),
-                       name);
+       int ret = lookup_value_from_name(
+               loglevel_python_values, ARRAY_SIZE(loglevel_python_values), name);
 
        if (ret >= 0) {
                *loglevel = (typeof(*loglevel)) ret;
@@ -314,13 +302,15 @@ int loglevel_python_name_to_value(
 }
 
 bool loglevel_python_parse_range_string(const char *str,
-               enum lttng_loglevel_python *min,
-               enum lttng_loglevel_python *max)
+                                       enum lttng_loglevel_python *min,
+                                       enum lttng_loglevel_python *max)
 {
        int min_int, max_int;
        bool ret = loglevel_parse_range_string_common(str,
-                       loglevel_python_values,
-                       ARRAY_SIZE(loglevel_python_values), &min_int, &max_int);
+                                                     loglevel_python_values,
+                                                     ARRAY_SIZE(loglevel_python_values),
+                                                     &min_int,
+                                                     &max_int);
 
        *min = (lttng_loglevel_python) min_int;
        *max = (lttng_loglevel_python) max_int;
@@ -328,12 +318,11 @@ bool loglevel_python_parse_range_string(const char *str,
        return ret;
 }
 
-static
-const char *lookup_name_from_value(const struct loglevel_name_value values[],
-               size_t values_count, int loglevel)
+static const char *
+lookup_name_from_value(const struct loglevel_name_value values[], size_t values_count, int loglevel)
 {
        size_t i;
-       const char *name = NULL;
+       const char *name = nullptr;
 
        for (i = 0; i < values_count; i++) {
                if (values[i].value == loglevel) {
@@ -349,24 +338,23 @@ end:
 
 const char *loglevel_value_to_name(int loglevel)
 {
-       return lookup_name_from_value(
-                       loglevel_values, ARRAY_SIZE(loglevel_values), loglevel);
+       return lookup_name_from_value(loglevel_values, ARRAY_SIZE(loglevel_values), loglevel);
 }
 
 const char *loglevel_log4j_value_to_name(int loglevel)
 {
-       return lookup_name_from_value(loglevel_log4j_values,
-                       ARRAY_SIZE(loglevel_log4j_values), loglevel);
+       return lookup_name_from_value(
+               loglevel_log4j_values, ARRAY_SIZE(loglevel_log4j_values), loglevel);
 }
 
 const char *loglevel_jul_value_to_name(int loglevel)
 {
-       return lookup_name_from_value(loglevel_jul_values,
-                       ARRAY_SIZE(loglevel_jul_values), loglevel);
+       return lookup_name_from_value(
+               loglevel_jul_values, ARRAY_SIZE(loglevel_jul_values), loglevel);
 }
 
 const char *loglevel_python_value_to_name(int loglevel)
 {
-       return lookup_name_from_value(loglevel_python_values,
-                       ARRAY_SIZE(loglevel_python_values), loglevel);
+       return lookup_name_from_value(
+               loglevel_python_values, ARRAY_SIZE(loglevel_python_values), loglevel);
 }
index f2cc9139b3914bc10e9ff3d77c1bc78e5e685d2e..76c5ce021e2a26759ba8dfd3415ef9b40ac91fe1 100644 (file)
@@ -8,35 +8,33 @@
 #ifndef _LTTNG_LOGLEVEL_UTILS_H
 #define _LTTNG_LOGLEVEL_UTILS_H
 
-#include <lttng/lttng.h>
 #include <common/macros.hpp>
 
+#include <lttng/lttng.h>
+
 int loglevel_name_to_value(const char *name, enum lttng_loglevel *loglevel);
 
 bool loglevel_parse_range_string(const char *str,
-               enum lttng_loglevel *min,
-               enum lttng_loglevel *max);
+                                enum lttng_loglevel *min,
+                                enum lttng_loglevel *max);
 
-int loglevel_log4j_name_to_value(
-               const char *name, enum lttng_loglevel_log4j *loglevel);
+int loglevel_log4j_name_to_value(const char *name, enum lttng_loglevel_log4j *loglevel);
 
 bool loglevel_log4j_parse_range_string(const char *str,
-               enum lttng_loglevel_log4j *min,
-               enum lttng_loglevel_log4j *max);
+                                      enum lttng_loglevel_log4j *min,
+                                      enum lttng_loglevel_log4j *max);
 
-int loglevel_jul_name_to_value(
-               const char *name, enum lttng_loglevel_jul *loglevel);
+int loglevel_jul_name_to_value(const char *name, enum lttng_loglevel_jul *loglevel);
 
 bool loglevel_jul_parse_range_string(const char *str,
-               enum lttng_loglevel_jul *min,
-               enum lttng_loglevel_jul *max);
+                                    enum lttng_loglevel_jul *min,
+                                    enum lttng_loglevel_jul *max);
 
-int loglevel_python_name_to_value(
-               const char *name, enum lttng_loglevel_python *loglevel);
+int loglevel_python_name_to_value(const char *name, enum lttng_loglevel_python *loglevel);
 
 bool loglevel_python_parse_range_string(const char *str,
-               enum lttng_loglevel_python *min,
-               enum lttng_loglevel_python *max);
+                                       enum lttng_loglevel_python *min,
+                                       enum lttng_loglevel_python *max);
 
 const char *loglevel_value_to_name(int loglevel);
 
index 7e70c3afce4f9e22b03e628bdda0b6344635d6ae..48b02c6272687ed3d905ddc363c47d19d182e5b0 100644 (file)
@@ -6,6 +6,16 @@
  */
 
 #define _LGPL_SOURCE
+#include "command.hpp"
+#include "version.hpp"
+
+#include <common/compat/getenv.hpp>
+#include <common/error.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/lttng.h>
+
+#include <ctype.h>
 #include <getopt.h>
 #include <signal.h>
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <unistd.h>
-#include <ctype.h>
-
-#include <lttng/lttng.h>
-#include <common/error.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/utils.hpp>
-
-#include "command.hpp"
-#include "version.hpp"
 
 static const char *help_msg =
 #ifdef LTTNG_EMBED_HELP
 #include <lttng.1.h>
 #else
-NULL
+       nullptr
 #endif
-;
+       ;
 
 /* Variables */
 static const char *progname;
@@ -47,61 +48,60 @@ enum {
 };
 
 /* Getopt options. No first level command. */
-static struct option long_options[] = {
-       {"version",          0, NULL, 'V'},
-       {"help",             0, NULL, 'h'},
-       {"group",            1, NULL, 'g'},
-       {"verbose",          0, NULL, 'v'},
-       {"quiet",            0, NULL, 'q'},
-       {"mi",               1, NULL, 'm'},
-       {"no-sessiond",      0, NULL, 'n'},
-       {"sessiond-path",    1, NULL, OPT_SESSION_PATH},
-       {"relayd-path",      1, NULL, OPT_RELAYD_PATH},
-       {"list-options",     0, NULL, OPT_DUMP_OPTIONS},
-       {"list-commands",    0, NULL, OPT_DUMP_COMMANDS},
-       {NULL, 0, NULL, 0}
-};
+static struct option long_options[] = { { "version", 0, nullptr, 'V' },
+                                       { "help", 0, nullptr, 'h' },
+                                       { "group", 1, nullptr, 'g' },
+                                       { "verbose", 0, nullptr, 'v' },
+                                       { "quiet", 0, nullptr, 'q' },
+                                       { "mi", 1, nullptr, 'm' },
+                                       { "no-sessiond", 0, nullptr, 'n' },
+                                       { "sessiond-path", 1, nullptr, OPT_SESSION_PATH },
+                                       { "relayd-path", 1, nullptr, OPT_RELAYD_PATH },
+                                       { "list-options", 0, nullptr, OPT_DUMP_OPTIONS },
+                                       { "list-commands", 0, nullptr, OPT_DUMP_COMMANDS },
+                                       { nullptr, 0, nullptr, 0 } };
 
 /* First level command */
-static struct cmd_struct commands[] =  {
-       { "add-context", cmd_add_context},
-       { "add-trigger", cmd_add_trigger},
-       { "create", cmd_create},
-       { "clear", cmd_clear},
-       { "destroy", cmd_destroy},
-       { "disable-channel", cmd_disable_channels},
-       { "disable-event", cmd_disable_events},
-       { "enable-channel", cmd_enable_channels},
-       { "enable-event", cmd_enable_events},
-       { "help", NULL},
-       { "list", cmd_list},
-       { "list-triggers", cmd_list_triggers},
-       { "load", cmd_load},
-       { "metadata", cmd_metadata},
-       { "regenerate", cmd_regenerate},
-       { "remove-trigger", cmd_remove_trigger},
-       { "rotate", cmd_rotate},
-       { "enable-rotation", cmd_enable_rotation},
-       { "disable-rotation", cmd_disable_rotation},
-       { "save", cmd_save},
-       { "set-session", cmd_set_session},
-       { "snapshot", cmd_snapshot},
-       { "start", cmd_start},
-       { "status", cmd_status},
-       { "stop", cmd_stop},
-       { "track", cmd_track},
-       { "untrack", cmd_untrack},
-       { "version", cmd_version},
-       { "view", cmd_view},
-       { NULL, NULL}   /* Array closure */
+static struct cmd_struct commands[] = {
+       { "add-context", cmd_add_context },
+       { "add-trigger", cmd_add_trigger },
+       { "create", cmd_create },
+       { "clear", cmd_clear },
+       { "destroy", cmd_destroy },
+       { "disable-channel", cmd_disable_channels },
+       { "disable-event", cmd_disable_events },
+       { "enable-channel", cmd_enable_channels },
+       { "enable-event", cmd_enable_events },
+       { "help", nullptr },
+       { "list", cmd_list },
+       { "list-triggers", cmd_list_triggers },
+       { "load", cmd_load },
+       { "metadata", cmd_metadata },
+       { "regenerate", cmd_regenerate },
+       { "remove-trigger", cmd_remove_trigger },
+       { "rotate", cmd_rotate },
+       { "enable-rotation", cmd_enable_rotation },
+       { "disable-rotation", cmd_disable_rotation },
+       { "save", cmd_save },
+       { "set-session", cmd_set_session },
+       { "snapshot", cmd_snapshot },
+       { "start", cmd_start },
+       { "status", cmd_status },
+       { "stop", cmd_stop },
+       { "track", cmd_track },
+       { "untrack", cmd_untrack },
+       { "version", cmd_version },
+       { "view", cmd_view },
+       { nullptr, nullptr } /* Array closure */
 };
 
 static void version(FILE *ofp)
 {
-       fprintf(ofp, "%s (LTTng Trace Control) " VERSION" - " VERSION_NAME "%s%s\n",
-                       progname,
-                       GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
-                       EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
+       fprintf(ofp,
+               "%s (LTTng Trace Control) " VERSION " - " VERSION_NAME "%s%s\n",
+               progname,
+               GIT_VERSION[0] == '\0' ? "" : " - " GIT_VERSION,
+               EXTRA_VERSION_NAME[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME);
 }
 
 /*
@@ -132,10 +132,10 @@ static int mi_output_type(const char *output_type)
 static void list_options(FILE *ofp)
 {
        int i = 0;
-       struct option *option = NULL;
+       struct option *option = nullptr;
 
        option = &long_options[i];
-       while (option->name != NULL) {
+       while (option->name != nullptr) {
                fprintf(ofp, "--%s\n", option->name);
 
                if (isprint(option->val)) {
@@ -150,8 +150,7 @@ static void list_options(FILE *ofp)
 /*
  * clean_exit
  */
-__attribute__((noreturn))
-static void clean_exit(int code)
+__attribute__((noreturn)) static void clean_exit(int code)
 {
        DBG("Clean exit");
        exit(code);
@@ -165,13 +164,13 @@ static void clean_exit(int code)
 static void sighandler(int sig)
 {
        switch (sig) {
-               case SIGTERM:
-                       DBG("SIGTERM caught");
-                       clean_exit(EXIT_FAILURE);
-                       break;
-               default:
-                       DBG("Unknown signal %d caught", sig);
-                       break;
+       case SIGTERM:
+               DBG("SIGTERM caught");
+               clean_exit(EXIT_FAILURE);
+               break;
+       default:
+               DBG("Unknown signal %d caught", sig);
+               break;
        }
 
        return;
@@ -182,7 +181,7 @@ static void sighandler(int sig)
  *
  *  Setup signal handler for SIGCHLD and SIGTERM.
  */
-static int set_signal_handler(void)
+static int set_signal_handler()
 {
        int ret = 0;
        struct sigaction sa;
@@ -197,7 +196,7 @@ static int set_signal_handler(void)
        sa.sa_mask = sigset;
        sa.sa_flags = 0;
 
-       if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGTERM, &sa, nullptr)) < 0) {
                PERROR("sigaction");
                goto end;
        }
@@ -220,22 +219,28 @@ static int handle_command(int argc, char **argv)
        int i = 0, ret;
        struct cmd_struct *cmd;
 
-       if (*argv == NULL) {
+       if (*argv == nullptr) {
                ret = CMD_SUCCESS;
                goto end;
        }
 
        /* Special case for help command which needs the commands array */
        if (strcmp(argv[0], "help") == 0) {
-               ret = cmd_help(argc, (const char**) argv, commands);
+               ret = cmd_help(argc, (const char **) argv, commands);
                goto end;
        }
 
        cmd = &commands[i];
-       while (cmd->name != NULL) {
+       while (cmd->name != nullptr) {
                /* Find command */
                if (strcmp(argv[0], cmd->name) == 0) {
-                       ret = cmd->func(argc, (const char**) argv);
+                       try {
+                               ret = cmd->func(argc, (const char **) argv);
+                       } catch (const std::exception& e) {
+                               ERR_FMT("{}", e.what());
+                               ret = CMD_ERROR;
+                       }
+
                        goto end;
                }
                i++;
@@ -254,7 +259,7 @@ static bool command_exists(const char *command)
        const struct cmd_struct *cmd = commands;
        bool exists = false;
 
-       while (cmd->name != NULL) {
+       while (cmd->name != nullptr) {
                if (!strcmp(command, cmd->name)) {
                        exists = true;
                        goto end;
@@ -266,7 +271,7 @@ end:
        return exists;
 }
 
-static void show_basic_help(void)
+static void show_basic_help()
 {
        puts("Usage: lttng [--group=GROUP] [--mi=TYPE] [--no-sessiond | --sessiond-path=PATH]");
        puts("             [--quiet | -v | -vv | -vvv] COMMAND [COMMAND OPTIONS]");
@@ -335,7 +340,8 @@ static int parse_args(int argc, char **argv)
        int opt, ret;
 
        if (lttng_is_setuid_setgid()) {
-               ERR("'%s' is not allowed to be executed as a setuid/setgid binary for security reasons. Aborting.", argv[0]);
+               ERR("'%s' is not allowed to be executed as a setuid/setgid binary for security reasons. Aborting.",
+                   argv[0]);
                clean_exit(EXIT_FAILURE);
        }
 
@@ -344,7 +350,7 @@ static int parse_args(int argc, char **argv)
                clean_exit(EXIT_FAILURE);
        }
 
-       while ((opt = getopt_long(argc, argv, "+Vhnvqg:m:", long_options, NULL)) != -1) {
+       while ((opt = getopt_long(argc, argv, "+Vhnvqg:m:", long_options, nullptr)) != -1) {
                switch (opt) {
                case 'V':
                        version(stdout);
@@ -432,10 +438,9 @@ static int parse_args(int argc, char **argv)
        case CMD_UNDEFINED:
                if (!command_exists(*(argv + optind))) {
                        MSG("lttng: %s is not an lttng command. See 'lttng --help'.",
-                                       *(argv + optind));
+                           *(argv + optind));
                } else {
-                       ERR("Unrecognized argument used with \'%s\' command",
-                                       *(argv + optind));
+                       ERR("Unrecognized argument used with \'%s\' command", *(argv + optind));
                }
                break;
        case CMD_FATAL:
@@ -458,11 +463,10 @@ error:
        return ret;
 }
 
-
 /*
  *  main
  */
-int main(int argc, char *argv[])
+static int _main(int argc, char *argv[])
 {
        int ret;
 
@@ -480,3 +484,13 @@ int main(int argc, char *argv[])
 
        return 0;
 }
+
+int main(int argc, char **argv)
+{
+       try {
+               return _main(argc, argv);
+       } catch (const std::exception& e) {
+               ERR_FMT("Unhandled exception caught by client: {}", e.what());
+               abort();
+       }
+}
index c6a2d9429090f3ce2141f0fbdd66ecc51272ff75..60fd5f619580cc7c5b07aca89b6311275165fe8f 100644 (file)
@@ -5,19 +5,17 @@
  *
  */
 
-#include "uprobe.hpp"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
+#include "command.hpp"
 #include "common/compat/getenv.hpp"
+#include "common/path.hpp"
 #include "common/string-utils/string-utils.hpp"
 #include "common/utils.hpp"
-#include "common/path.hpp"
 #include "lttng/constant.h"
+#include "uprobe.hpp"
 
-#include "command.hpp"
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 /*
  * Walk the directories in the PATH environment variable to find the target
  * LTTNG_PATH_MAX bytes long.
  * On failure, returns -1;
  */
-static
-int walk_command_search_path(const char *binary, char *binary_full_path)
+static int walk_command_search_path(const char *binary, char *binary_full_path)
 {
-       char *tentative_binary_path = NULL;
-       char *command_search_path = NULL;
-       char *curr_search_dir_end = NULL;
-       char *curr_search_dir = NULL;
+       char *tentative_binary_path = nullptr;
+       char *command_search_path = nullptr;
+       char *curr_search_dir_end = nullptr;
+       char *curr_search_dir = nullptr;
        struct stat stat_output;
        int ret = 0;
 
@@ -71,7 +68,7 @@ int walk_command_search_path(const char *binary, char *binary_full_path)
                 * matching character.
                 */
                curr_search_dir_end = strchr(curr_search_dir, ':');
-               if (curr_search_dir_end != NULL) {
+               if (curr_search_dir_end != nullptr) {
                        /*
                         * Add a NULL byte to the end of the first token so it
                         * can be used as a string.
@@ -86,14 +83,14 @@ int walk_command_search_path(const char *binary, char *binary_full_path)
                 * Build the tentative path to the binary using the current
                 * search directory and the name of the binary.
                 */
-               ret = snprintf(tentative_binary_path, LTTNG_PATH_MAX, "%s/%s",
-                               curr_search_dir, binary);
+               ret = snprintf(
+                       tentative_binary_path, LTTNG_PATH_MAX, "%s/%s", curr_search_dir, binary);
                if (ret < 0) {
                        goto free_binary_path;
                }
                if (ret < LTTNG_PATH_MAX) {
-                        /*
-                         * Use STAT(2) to see if the file exists.
+                       /*
+                        * Use STAT(2) to see if the file exists.
                         */
                        ret = stat(tentative_binary_path, &stat_output);
                        if (ret == 0) {
@@ -102,18 +99,17 @@ int walk_command_search_path(const char *binary, char *binary_full_path)
                                 * symlink and not a special file (e.g.
                                 * device).
                                 */
-                               if (S_ISREG(stat_output.st_mode)
-                                               || S_ISLNK(stat_output.st_mode)) {
+                               if (S_ISREG(stat_output.st_mode) || S_ISLNK(stat_output.st_mode)) {
                                        /*
                                         * Found a match, set the out parameter
                                         * and return success.
                                         */
                                        ret = lttng_strncpy(binary_full_path,
-                                                       tentative_binary_path,
-                                                       LTTNG_PATH_MAX);
+                                                           tentative_binary_path,
+                                                           LTTNG_PATH_MAX);
                                        if (ret == -1) {
                                                ERR("Source path does not fit "
-                                                       "in destination buffer.");
+                                                   "in destination buffer.");
                                        }
                                        goto free_binary_path;
                                }
@@ -121,7 +117,7 @@ int walk_command_search_path(const char *binary, char *binary_full_path)
                }
                /* Go to the next entry in the $PATH variable. */
                curr_search_dir = curr_search_dir_end + 1;
-       } while (curr_search_dir_end != NULL);
+       } while (curr_search_dir_end != nullptr);
 
 free_binary_path:
        free(tentative_binary_path);
@@ -144,8 +140,7 @@ end:
  * elf:/path/to/binary:my_symbol+0x323
  * elf:/path/to/binary:my_symbol+43
  */
-static
-int warn_userspace_probe_syntax(const char *symbol)
+static int warn_userspace_probe_syntax(const char *symbol)
 {
        int ret;
 
@@ -197,16 +192,16 @@ error:
  * target_path to the path to the binary.
  */
 int parse_userspace_probe_opts(const char *opt,
-               struct lttng_userspace_probe_location **probe_location)
+                              struct lttng_userspace_probe_location **probe_location)
 {
        int ret = CMD_SUCCESS;
        size_t num_token = 0;
-       char *target_path = NULL;
-       char *unescaped_target_path = NULL;
-       char *real_target_path = NULL;
-       char *symbol_name = NULL, *probe_name = NULL, *provider_name = NULL;
-       struct lttng_userspace_probe_location *probe_location_local = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
+       char *target_path = nullptr;
+       char *unescaped_target_path = nullptr;
+       char *real_target_path = nullptr;
+       char *symbol_name = nullptr, *probe_name = nullptr, *provider_name = nullptr;
+       struct lttng_userspace_probe_location *probe_location_local = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
        struct lttng_dynamic_pointer_array tokens;
 
        LTTNG_ASSERT(opt);
@@ -239,7 +234,9 @@ int parse_userspace_probe_opts(const char *opt,
        case 2:
                /* When the probe type is omitted we assume ELF for now. */
        case 3:
-               if (num_token == 3 && strcmp((const char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 0), "elf") == 0) {
+               if (num_token == 3 &&
+                   strcmp((const char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 0),
+                          "elf") == 0) {
                        target_path = (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 1);
                        symbol_name = (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 2);
                } else if (num_token == 2) {
@@ -249,8 +246,7 @@ int parse_userspace_probe_opts(const char *opt,
                        ret = CMD_ERROR;
                        goto end;
                }
-               lookup_method =
-                       lttng_userspace_probe_location_lookup_method_function_elf_create();
+               lookup_method = lttng_userspace_probe_location_lookup_method_function_elf_create();
                if (!lookup_method) {
                        WARN("Failed to create ELF lookup method");
                        ret = CMD_ERROR;
@@ -258,9 +254,11 @@ int parse_userspace_probe_opts(const char *opt,
                }
                break;
        case 4:
-               if (strcmp((const char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 0), "sdt") == 0) {
+               if (strcmp((const char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 0),
+                          "sdt") == 0) {
                        target_path = (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 1);
-                       provider_name = (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 2);
+                       provider_name =
+                               (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 2);
                        probe_name = (char *) lttng_dynamic_pointer_array_get_pointer(&tokens, 3);
                } else {
                        ret = CMD_ERROR;
@@ -290,7 +288,7 @@ int parse_userspace_probe_opts(const char *opt,
         * If there is not forward slash in the path. Walk the $PATH else
         * expand.
         */
-       if (strchr(unescaped_target_path, '/') == NULL) {
+       if (strchr(unescaped_target_path, '/') == nullptr) {
                /* Walk the $PATH variable to find the targeted binary. */
                real_target_path = calloc<char>(LTTNG_PATH_MAX);
                if (!real_target_path) {
@@ -340,7 +338,7 @@ int parse_userspace_probe_opts(const char *opt,
                }
 
                probe_location_local = lttng_userspace_probe_location_function_create(
-                               real_target_path, symbol_name, lookup_method);
+                       real_target_path, symbol_name, lookup_method);
                if (!probe_location_local) {
                        WARN("Failed to create function probe location");
                        ret = CMD_ERROR;
@@ -348,11 +346,11 @@ int parse_userspace_probe_opts(const char *opt,
                }
 
                /* Ownership transferred to probe_location. */
-               lookup_method = NULL;
+               lookup_method = nullptr;
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                probe_location_local = lttng_userspace_probe_location_tracepoint_create(
-                               real_target_path, provider_name, probe_name, lookup_method);
+                       real_target_path, provider_name, probe_name, lookup_method);
                if (!probe_location_local) {
                        WARN("Failed to create function probe location");
                        ret = CMD_ERROR;
@@ -360,7 +358,7 @@ int parse_userspace_probe_opts(const char *opt,
                }
 
                /* Ownership transferred to probe_location. */
-               lookup_method = NULL;
+               lookup_method = nullptr;
                break;
        default:
                ret = CMD_ERROR;
@@ -372,7 +370,7 @@ int parse_userspace_probe_opts(const char *opt,
         * caller.
         */
        *probe_location = probe_location_local;
-       probe_location_local = NULL;
+       probe_location_local = nullptr;
 
 end:
        lttng_userspace_probe_location_destroy(probe_location_local);
index 83733129142fb1b2cd39b2148f9fb8c1b77e66da..413dd02ab0fc7fb66c362ea1f8613975a3386b2f 100644 (file)
@@ -12,7 +12,6 @@
 
 struct lttng_userspace_probe_location;
 
-int parse_userspace_probe_opts(const char *opt,
-               struct lttng_userspace_probe_location **uprobe_loc);
+int parse_userspace_probe_opts(const char *opt, struct lttng_userspace_probe_location **uprobe_loc);
 
 #endif /* SRC_BIN_LTTNG_UPROBE_H */
index 9a9f39bf2529b1cd6328f5052b73672715d12663..45fe256a579d092b4a1d92ddd81e26459b315a1e 100644 (file)
@@ -6,24 +6,29 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdlib.h>
-#include <ctype.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <signal.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <inttypes.h>
-#include <unistd.h>
+#include "command.hpp"
+#include "conf.hpp"
+#include "exception.hpp"
+#include "utils.hpp"
 
+#include <common/defaults.hpp>
 #include <common/error.hpp>
+#include <common/exception.hpp>
+#include <common/make-unique-wrapper.hpp>
 #include <common/utils.hpp>
-#include <common/defaults.hpp>
 
-#include "conf.hpp"
-#include "utils.hpp"
-#include "command.hpp"
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <fnmatch.h>
+#include <inttypes.h>
+#include <iostream>
+#include <limits.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 static const char *str_all = "ALL";
 static const char *str_tracepoint = "Tracepoint";
@@ -32,22 +37,21 @@ static const char *str_probe = "Probe";
 static const char *str_userspace_probe = "Userspace Probe";
 static const char *str_function = "Function";
 
-static
-char *_get_session_name(int quiet)
+static char *_get_session_name(int quiet)
 {
        const char *path;
-       char *session_name = NULL;
+       char *session_name = nullptr;
 
        /* Get path to config file */
        path = utils_get_home_dir();
-       if (path == NULL) {
+       if (path == nullptr) {
                goto error;
        }
 
        /* Get session name from config */
        session_name = quiet ? config_read_session_name_quiet(path) :
-               config_read_session_name(path);
-       if (session_name == NULL) {
+                              config_read_session_name(path);
+       if (session_name == nullptr) {
                goto error;
        }
 
@@ -56,7 +60,7 @@ char *_get_session_name(int quiet)
        return session_name;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -65,7 +69,7 @@ error:
  *  Return allocated string with the session name found in the config
  *  directory.
  */
-char *get_session_name(void)
+char *get_session_name()
 {
        return _get_session_name(0);
 }
@@ -76,7 +80,7 @@ char *get_session_name(void)
  *  Return allocated string with the session name found in the config
  *  directory.
  */
-char *get_session_name_quiet(void)
+char *get_session_name_quiet()
 {
        return _get_session_name(1);
 }
@@ -90,10 +94,10 @@ char *get_session_name_quiet(void)
 void list_commands(struct cmd_struct *commands, FILE *ofp)
 {
        int i = 0;
-       struct cmd_struct *cmd = NULL;
+       struct cmd_struct *cmd = nullptr;
 
        cmd = &commands[i];
-       while (cmd->name != NULL) {
+       while (cmd->name != nullptr) {
                fprintf(ofp, "%s\n", cmd->name);
                i++;
                cmd = &commands[i];
@@ -109,9 +113,9 @@ void list_commands(struct cmd_struct *commands, FILE *ofp)
 void list_cmd_options(FILE *ofp, struct poptOption *options)
 {
        int i;
-       struct poptOption *option = NULL;
+       struct poptOption *option = nullptr;
 
-       for (i = 0; options[i].longName != NULL; i++) {
+       for (i = 0; options[i].longName != nullptr; i++) {
                option = &options[i];
 
                fprintf(ofp, "--%s\n", option->longName);
@@ -129,7 +133,7 @@ void list_cmd_options_argpar(FILE *ofp, const struct argpar_opt_descr *options)
 {
        int i;
 
-       for (i = 0; options[i].long_name != NULL; i++) {
+       for (i = 0; options[i].long_name != nullptr; i++) {
                const struct argpar_opt_descr *option = &options[i];
 
                fprintf(ofp, "--%s\n", option->long_name);
@@ -146,8 +150,7 @@ void list_cmd_options_argpar(FILE *ofp, const struct argpar_opt_descr *options)
  * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
  */
 #if defined(__i386) || defined(__x86_64)
-static inline
-unsigned int fls_u32(uint32_t x)
+static inline unsigned int fls_u32(uint32_t x)
 {
        int r;
 
@@ -155,15 +158,15 @@ unsigned int fls_u32(uint32_t x)
            "jnz 1f\n\t"
            "movl $-1,%0\n\t"
            "1:\n\t"
-           : "=r" (r) : "rm" (x));
+           : "=r"(r)
+           : "rm"(x));
        return r + 1;
 }
 #define HAS_FLS_U32
 #endif
 
 #if defined(__x86_64) && defined(__LP64__)
-static inline
-unsigned int fls_u64(uint64_t x)
+static inline unsigned int fls_u64(uint64_t x)
 {
        long r;
 
@@ -171,15 +174,15 @@ unsigned int fls_u64(uint64_t x)
            "jnz 1f\n\t"
            "movq $-1,%0\n\t"
            "1:\n\t"
-           : "=r" (r) : "rm" (x));
+           : "=r"(r)
+           : "rm"(x));
        return r + 1;
 }
 #define HAS_FLS_U64
 #endif
 
 #ifndef HAS_FLS_U64
-static __attribute__((unused))
-unsigned int fls_u64(uint64_t x)
+static __attribute__((unused)) unsigned int fls_u64(uint64_t x)
 {
        unsigned int r = 64;
 
@@ -215,8 +218,7 @@ unsigned int fls_u64(uint64_t x)
 #endif
 
 #ifndef HAS_FLS_U32
-static __attribute__((unused))
-unsigned int fls_u32(uint32_t x)
+static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
 {
        unsigned int r = 32;
 
@@ -246,8 +248,7 @@ unsigned int fls_u32(uint32_t x)
 }
 #endif
 
-static
-unsigned int fls_ulong(unsigned long x)
+static unsigned int fls_ulong(unsigned long x)
 {
 #if (CAA_BITS_PER_LONG == 32)
        return fls_u32(x);
@@ -355,7 +356,7 @@ int spawn_relayd(const char *pathname, int port)
                } else {
                        PERROR("execlp");
                }
-               kill(getppid(), SIGTERM);       /* wake parent */
+               kill(getppid(), SIGTERM); /* wake parent */
                exit(EXIT_FAILURE);
        } else if (pid > 0) {
                goto end;
@@ -374,7 +375,7 @@ end:
  *
  * Return 1 if found else 0 if NOT found. Negative value on error.
  */
-int check_relayd(void)
+int check_relayd()
 {
        int ret, fd;
        struct sockaddr_in sin;
@@ -416,16 +417,13 @@ error_socket:
        return ret;
 }
 
-int print_missing_or_multiple_domains(unsigned int domain_count,
-               bool include_agent_domains)
+int print_missing_or_multiple_domains(unsigned int domain_count, bool include_agent_domains)
 {
        int ret = 0;
 
        if (domain_count == 0) {
                ERR("Please specify a domain (--kernel/--userspace%s).",
-                               include_agent_domains ?
-                                               "/--jul/--log4j/--python" :
-                                               "");
+                   include_agent_domains ? "/--jul/--log4j/--python" : "");
                ret = -1;
        } else if (domain_count > 1) {
                ERR("Only one domain must be specified.");
@@ -452,12 +450,12 @@ void print_session_stats(const char *session_name)
 int get_session_stats_str(const char *session_name, char **out_str)
 {
        int count, nb_domains, domain_idx, channel_idx, session_idx, ret;
-       struct lttng_domain *domains = NULL;
-       struct lttng_channel *channels = NULL;
+       struct lttng_domain *domains = nullptr;
+       struct lttng_channel *channels = nullptr;
        uint64_t discarded_events_total = 0, lost_packets_total = 0;
-       struct lttng_session *sessions = NULL;
-       const struct lttng_session *selected_session = NULL;
-       char *stats_str = NULL;
+       struct lttng_session *sessions = nullptr;
+       const struct lttng_session *selected_session = nullptr;
+       char *stats_str = nullptr;
        bool print_discarded_events = false, print_lost_packets = false;
 
        count = lttng_list_sessions(&sessions);
@@ -475,7 +473,8 @@ int get_session_stats_str(const char *session_name, char **out_str)
                }
        }
        if (!selected_session) {
-               ERR("Failed to retrieve session \"%s\" description while printing session statistics.", session_name);
+               ERR("Failed to retrieve session \"%s\" description while printing session statistics.",
+                   session_name);
                ret = -1;
                goto end;
        }
@@ -486,8 +485,8 @@ int get_session_stats_str(const char *session_name, char **out_str)
                goto end;
        }
        for (domain_idx = 0; domain_idx < nb_domains; domain_idx++) {
-               struct lttng_handle *handle = lttng_create_handle(session_name,
-                               &domains[domain_idx]);
+               struct lttng_handle *handle =
+                       lttng_create_handle(session_name, &domains[domain_idx]);
 
                if (!handle) {
                        ERR("Failed to create session handle while printing session statistics.");
@@ -496,24 +495,22 @@ int get_session_stats_str(const char *session_name, char **out_str)
                }
 
                free(channels);
-               channels = NULL;
+               channels = nullptr;
                count = lttng_list_channels(handle, &channels);
                for (channel_idx = 0; channel_idx < count; channel_idx++) {
                        uint64_t discarded_events = 0, lost_packets = 0;
                        struct lttng_channel *channel = &channels[channel_idx];
 
-                       ret = lttng_channel_get_discarded_event_count(channel,
-                                       &discarded_events);
+                       ret = lttng_channel_get_discarded_event_count(channel, &discarded_events);
                        if (ret) {
                                ERR("Failed to retrieve discarded event count from channel %s",
-                                               channel->name);
+                                   channel->name);
                        }
 
-                       ret = lttng_channel_get_lost_packet_count(channel,
-                                       &lost_packets);
+                       ret = lttng_channel_get_lost_packet_count(channel, &lost_packets);
                        if (ret) {
                                ERR("Failed to retrieve lost packet count from channel %s",
-                                               channel->name);
+                                   channel->name);
                        }
 
                        discarded_events_total += discarded_events;
@@ -522,30 +519,26 @@ int get_session_stats_str(const char *session_name, char **out_str)
                lttng_destroy_handle(handle);
        }
 
-       print_discarded_events = discarded_events_total > 0 &&
-                                !selected_session->snapshot_mode;
-       print_lost_packets = lost_packets_total > 0 &&
-                            !selected_session->snapshot_mode;
+       print_discarded_events = discarded_events_total > 0 && !selected_session->snapshot_mode;
+       print_lost_packets = lost_packets_total > 0 && !selected_session->snapshot_mode;
 
        if (print_discarded_events && print_lost_packets) {
                ret = asprintf(&stats_str,
-                               "Warning: %" PRIu64
-                               " events were discarded and %" PRIu64
-                               " packets were lost, please refer to "
-                               "the documentation on channel configuration.",
-                               discarded_events_total, lost_packets_total);
+                              "Warning: %" PRIu64 " events were discarded and %" PRIu64
+                              " packets were lost, please refer to "
+                              "the documentation on channel configuration.",
+                              discarded_events_total,
+                              lost_packets_total);
        } else if (print_discarded_events) {
                ret = asprintf(&stats_str,
-                               "Warning: %" PRIu64
-                               " events were discarded, please refer to "
-                               "the documentation on channel configuration.",
-                               discarded_events_total);
+                              "Warning: %" PRIu64 " events were discarded, please refer to "
+                              "the documentation on channel configuration.",
+                              discarded_events_total);
        } else if (print_lost_packets) {
                ret = asprintf(&stats_str,
-                               "Warning: %" PRIu64
-                               " packets were lost, please refer to "
-                               "the documentation on channel configuration.",
-                               lost_packets_total);
+                              "Warning: %" PRIu64 " packets were lost, please refer to "
+                              "the documentation on channel configuration.",
+                              lost_packets_total);
        } else {
                ret = 0;
        }
@@ -579,9 +572,8 @@ int show_cmd_help(const char *cmd_name, const char *help_msg)
        return ret;
 }
 
-int print_trace_archive_location(
-               const struct lttng_trace_archive_location *location,
-               const char *session_name)
+int print_trace_archive_location(const struct lttng_trace_archive_location *location,
+                                const char *session_name)
 {
        int ret = 0;
        enum lttng_trace_archive_location_type location_type;
@@ -590,15 +582,14 @@ int print_trace_archive_location(
 
        location_type = lttng_trace_archive_location_get_type(location);
 
-       _MSG("Trace chunk archive for session %s is now readable",
-                       session_name);
+       _MSG("Trace chunk archive for session %s is now readable", session_name);
        switch (location_type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
        {
                const char *absolute_path;
 
-               status = lttng_trace_archive_location_local_get_absolute_path(
-                               location, &absolute_path);
+               status = lttng_trace_archive_location_local_get_absolute_path(location,
+                                                                             &absolute_path);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
@@ -614,36 +605,33 @@ int print_trace_archive_location(
                enum lttng_trace_archive_location_relay_protocol_type protocol;
 
                /* Fetch all relay location parameters. */
-               status = lttng_trace_archive_location_relay_get_protocol_type(
-                               location, &protocol);
+               status = lttng_trace_archive_location_relay_get_protocol_type(location, &protocol);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_host(
-                               location, &host);
+               status = lttng_trace_archive_location_relay_get_host(location, &host);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_control_port(
-                               location, &control_port);
+               status = lttng_trace_archive_location_relay_get_control_port(location,
+                                                                            &control_port);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_data_port(
-                               location, &data_port);
+               status = lttng_trace_archive_location_relay_get_data_port(location, &data_port);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_relative_path(
-                               location, &relative_path);
+               status = lttng_trace_archive_location_relay_get_relative_path(location,
+                                                                             &relative_path);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
@@ -658,9 +646,12 @@ int print_trace_archive_location(
                        break;
                }
 
-               MSG(" on relay %s://%s/%s [control port %" PRIu16 ", data port %"
-                               PRIu16 "]", protocol_str, host,
-                               relative_path, control_port, data_port);
+               MSG(" on relay %s://%s/%s [control port %" PRIu16 ", data port %" PRIu16 "]",
+                   protocol_str,
+                   host,
+                   relative_path,
+                   control_port,
+                   data_port);
                printed_location = true;
                break;
        }
@@ -673,3 +664,130 @@ end:
        }
        return ret;
 }
+
+namespace {
+template <typename FilterFunctionType>
+lttng::cli::session_list get_sessions(const FilterFunctionType& filter,
+                                     bool return_first_match_only = false)
+{
+       lttng::cli::session_list list = []() {
+               int list_ret;
+               struct lttng_session *psessions;
+
+               list_ret = lttng_list_sessions(&psessions);
+
+               if (list_ret < 0) {
+                       LTTNG_THROW_CTL("Failed to list sessions",
+                                       static_cast<lttng_error_code>(list_ret));
+               }
+
+               return lttng::cli::session_list(psessions, list_ret);
+       }();
+
+       std::size_t write_to = 0;
+       for (std::size_t read_from = 0; read_from < list.size(); ++read_from) {
+               if (!filter(list[read_from])) {
+                       continue;
+               }
+
+               if (read_from != write_to) {
+                       list[write_to] = list[read_from];
+               }
+
+               ++write_to;
+
+               if (return_first_match_only) {
+                       return lttng::cli::session_list(std::move(list), 1);
+               }
+       }
+
+       list.resize(write_to);
+
+       return list;
+}
+} /* namespace */
+
+lttng::cli::session_list lttng::cli::list_sessions(const struct session_spec& spec)
+{
+       switch (spec.type_) {
+       case lttng::cli::session_spec::type::NAME:
+               if (spec.value == nullptr) {
+                       const auto configured_name =
+                               lttng::make_unique_wrapper<char, lttng::memory::free>(
+                                       get_session_name());
+
+                       if (!configured_name) {
+                               LTTNG_THROW_CLI_NO_DEFAULT_SESSION();
+                       }
+
+                       const struct lttng::cli::session_spec new_spec(
+                               lttng::cli::session_spec::type::NAME, configured_name.get());
+
+                       return list_sessions(new_spec);
+               }
+
+               return get_sessions(
+                       [&spec](const lttng_session& session) {
+                               return strcmp(session.name, spec.value) == 0;
+                       },
+                       true);
+       case lttng::cli::session_spec::type::GLOB_PATTERN:
+               return get_sessions([&spec](const lttng_session& session) {
+                       return fnmatch(spec.value, session.name, 0) == 0;
+               });
+       case lttng::cli::session_spec::type::ALL:
+               return get_sessions([](const lttng_session&) { return true; });
+       }
+
+       return lttng::cli::session_list();
+}
+
+void print_kernel_tracer_status_error()
+{
+       if (lttng_opt_mi) {
+               return;
+       }
+
+       enum lttng_kernel_tracer_status kernel_tracer_status;
+       const auto ret = lttng_get_kernel_tracer_status(&kernel_tracer_status);
+
+       if (ret < 0) {
+               ERR("Failed to get kernel tracer status: %s", lttng_strerror(ret));
+       } else {
+               switch (kernel_tracer_status) {
+               case LTTNG_KERNEL_TRACER_STATUS_INITIALIZED:
+                       return;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_UNKNOWN:
+                       std::cerr << "\tKernel module loading failed" << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_MISSING:
+                       std::cerr << "\tMissing one or more required kernel modules" << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_MODULES_SIGNATURE:
+                       std::cerr
+                               << "\tKernel module signature error prevented loading of one or more required kernel modules"
+                               << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_NEED_ROOT:
+                       std::cerr << "\tlttng-sessiond isn't running as root" << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_NOTIFIER:
+                       std::cerr << "\tFailed to setup notifiers" << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_OPEN_PROC_LTTNG:
+                       std::cerr << "\tlttng-sessiond failed to open /proc/lttng" << std::endl;
+                       break;
+               case LTTNG_KERNEL_TRACER_STATUS_ERR_VERSION_MISMATCH:
+                       std::cerr << "\tVersion mismatch between kernel tracer and kernel tracer ABI"
+                                 << std::endl;
+                       break;
+               default:
+                       std::cerr << lttng::format("\t\tUnknown kernel tracer status (%d)",
+                                                  static_cast<int>(kernel_tracer_status))
+                                 << std::endl;
+                       break;
+               }
+
+               std::cerr << "\tConsult lttng-sessiond logs for more information" << std::endl;
+       }
+}
index bb1c2cdfbbbbeba767fec438a51d3d14c9750f17..7f398397a95a38ca585bcfcd000095497f913c6d 100644 (file)
 #ifndef _LTTNG_UTILS_H
 #define _LTTNG_UTILS_H
 
-#include <popt.h>
 #include <common/argpar/argpar.h>
+#include <common/container-wrapper.hpp>
 #include <common/dynamic-array.hpp>
+#include <common/make-unique-wrapper.hpp>
 
 #include <lttng/lttng.h>
+#include <lttng/session-internal.hpp>
+
+#include <iterator>
+#include <memory>
+#include <popt.h>
 
 extern char *opt_relayd_path;
 extern int opt_no_sessiond;
-extern char * opt_sessiond_path;
+extern char *opt_sessiond_path;
 extern pid_t sessiond_pid;
 
 struct cmd_struct;
 
-char *get_session_name(void);
-char *get_session_name_quiet(void);
+namespace lttng {
+namespace cli {
+
+struct session_spec {
+       enum class type {
+               NAME,
+               GLOB_PATTERN,
+               ALL,
+       };
+
+       explicit session_spec(type spec_type, const char *name_or_pattern = nullptr) noexcept :
+               type_(spec_type), value(name_or_pattern)
+       {
+       }
+
+       /* Disambiguate type enum from the member for buggy g++ versions. */
+       type type_;
+       const char *value;
+};
+
+class session_list;
+
+namespace details {
+class session_storage {
+public:
+       session_storage(lttng_session *raw_sessions, std::size_t sessions_count) :
+               _array(raw_sessions), _count(sessions_count)
+       {
+       }
+
+       session_storage(session_storage&& original) noexcept :
+               _array(std::move(original._array)), _count(original._count)
+       {
+       }
+
+       session_storage(session_storage&& original, std::size_t new_count) :
+               _array(std::move(original._array)), _count(new_count)
+       {
+       }
+
+       session_storage(session_storage&) = delete;
+       session_storage& operator=(const session_storage& other) = delete;
+       session_storage& operator=(session_storage&& other) = delete;
+       ~session_storage() = default;
+
+       lttng_session_uptr _array = nullptr;
+       std::size_t _count = 0;
+};
+
+class session_list_operations {
+public:
+       static lttng_session& get(const lttng::cli::details::session_storage& storage,
+                                 std::size_t index) noexcept
+       {
+               return storage._array[index];
+       }
+
+       static std::size_t size(const lttng::cli::details::session_storage& storage)
+       {
+               return storage._count;
+       }
+};
+} /* namespace details */
+
+/*
+ * We don't use a std::vector here because it would make a copy of the C array.
+ */
+class session_list
+       : public lttng::utils::random_access_container_wrapper<details::session_storage,
+                                                              lttng_session&,
+                                                              details::session_list_operations> {
+public:
+       friend details::session_list_operations;
+
+       session_list() :
+               lttng::utils::random_access_container_wrapper<details::session_storage,
+                                                             lttng_session&,
+                                                             details::session_list_operations>(
+                       { nullptr, 0 })
+       {
+       }
+
+       session_list(session_list&& original) noexcept :
+               lttng::utils::random_access_container_wrapper<details::session_storage,
+                                                             lttng_session&,
+                                                             details::session_list_operations>(
+                       std::move(original._container))
+       {
+       }
+
+       session_list(session_list&& original, std::size_t new_count) :
+               lttng::utils::random_access_container_wrapper<details::session_storage,
+                                                             lttng_session&,
+                                                             details::session_list_operations>(
+                       { std::move(original._container), new_count })
+       {
+       }
+
+       session_list(lttng_session *raw_sessions, std::size_t raw_sessions_count) :
+               lttng::utils::random_access_container_wrapper<details::session_storage,
+                                                             lttng_session&,
+                                                             details::session_list_operations>(
+                       { raw_sessions, raw_sessions_count })
+       {
+       }
+
+       session_list(session_list&) = delete;
+       session_list& operator=(const session_list& other) = delete;
+       session_list& operator=(session_list&& other) = delete;
+       ~session_list() = default;
+
+       void resize(std::size_t new_size) noexcept
+       {
+               _container._count = new_size;
+       }
+};
+
+lttng::cli::session_list list_sessions(const struct session_spec& spec);
+} /* namespace cli */
+} /* namespace lttng */
+
+char *get_session_name();
+char *get_session_name_quiet();
 void list_commands(struct cmd_struct *commands, FILE *ofp);
 void list_cmd_options(FILE *ofp, struct poptOption *options);
 void list_cmd_options_argpar(FILE *ofp, const struct argpar_opt_descr *options);
@@ -47,20 +174,24 @@ int get_count_order_ulong(unsigned long x);
 
 const char *get_event_type_str(enum lttng_event_type event_type);
 
-int print_missing_or_multiple_domains(unsigned int domain_count,
-               bool include_agent_domains);
+int print_missing_or_multiple_domains(unsigned int domain_count, bool include_agent_domains);
 
 int spawn_relayd(const char *pathname, int port);
-int check_relayd(void);
+int check_relayd();
 void print_session_stats(const char *session_name);
 int get_session_stats_str(const char *session_name, char **str);
 int show_cmd_help(const char *cmd_name, const char *help_msg);
 
-int print_trace_archive_location(
-               const struct lttng_trace_archive_location *location,
-               const char *session_name);
+int print_trace_archive_location(const struct lttng_trace_archive_location *location,
+                                const char *session_name);
 
 int validate_exclusion_list(const char *event_name,
-               const struct lttng_dynamic_pointer_array *exclusions);
+                           const struct lttng_dynamic_pointer_array *exclusions);
+
+/*
+ * Ask the sessiond for the more details on the status of the kernel tracer and
+ * print it to stderr.
+ */
+void print_kernel_tracer_status_error();
 
 #endif /* _LTTNG_UTILS_H */
index 66ab77d05d9cf825c61feb7c8edb49d77f85a6e1..34fd83452802f5b8caa21a347ce4264e693f1e88 100644 (file)
@@ -57,11 +57,13 @@ libcommon_lgpl_la_SOURCES = \
        actions/rate-policy.cpp \
        buffer-view.hpp buffer-view.cpp \
        channel.cpp \
+       compiler.hpp \
        conditions/buffer-usage.cpp \
        conditions/condition.cpp \
        conditions/event-rule-matches.cpp \
        conditions/session-consumed-size.cpp \
        conditions/session-rotation.cpp \
+       container-wrapper.hpp \
        credentials.cpp credentials.hpp \
        defaults.cpp \
        domain.cpp \
@@ -84,11 +86,16 @@ libcommon_lgpl_la_SOURCES = \
        event-rule/jul-logging.cpp \
        event-rule/python-logging.cpp \
        exception.cpp exception.hpp \
-       fd-handle.cpp fd-handle.hpp\
+       file-descriptor.hpp file-descriptor.cpp \
+       fd-handle.cpp fd-handle.hpp \
        format.hpp \
+       io-hint.cpp \
+       io-hint.hpp \
        kernel-probe.cpp \
        location.cpp \
+       lockfile.cpp lockfile.hpp \
        locked-reference.hpp \
+       logging-utils.hpp logging-utils.cpp \
        log-level-rule.cpp \
        make-unique.hpp \
        make-unique-wrapper.hpp \
@@ -97,8 +104,10 @@ libcommon_lgpl_la_SOURCES = \
        payload.cpp payload.hpp \
        payload-view.cpp payload-view.hpp \
        pthread-lock.hpp \
+       random.cpp random.hpp \
        readwrite.cpp readwrite.hpp \
        runas.cpp runas.hpp \
+       scope-exit.hpp \
        session-descriptor.cpp \
        snapshot.cpp snapshot.hpp \
        spawn-viewer.cpp spawn-viewer.hpp \
@@ -112,6 +121,10 @@ libcommon_lgpl_la_SOURCES = \
        urcu.hpp \
        utils.cpp utils.hpp
 
+if IS_LINUX
+libcommon_lgpl_la_SOURCES += eventfd.cpp eventfd.hpp
+endif
+
 if HAVE_ELF_H
 libcommon_lgpl_la_SOURCES += \
        lttng-elf.cpp lttng-elf.hpp
@@ -163,13 +176,11 @@ libcommon_gpl_la_LIBADD = \
 # libcompat
 noinst_LTLIBRARIES += libcompat.la
 libcompat_la_SOURCES = \
-        compat/compat-fcntl.cpp \
         compat/directory-handle.cpp \
         compat/directory-handle.hpp \
         compat/dirent.hpp \
         compat/endian.hpp \
         compat/errno.hpp \
-        compat/fcntl.hpp \
         compat/getenv.hpp \
         compat/mman.hpp \
         compat/netdb.hpp \
index bc9e3580a769632f6f09000eb05318d84501bc24..af277b3e207c29b9e0aa57c8fed156805314e259 100644 (file)
@@ -7,6 +7,7 @@
 
 #include <common/error.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/list-internal.hpp>
 #include <lttng/action/notify-internal.hpp>
@@ -45,14 +46,14 @@ enum lttng_action_type lttng_action_get_type(const struct lttng_action *action)
 }
 
 void lttng_action_init(struct lttng_action *action,
-               enum lttng_action_type type,
-               action_validate_cb validate,
-               action_serialize_cb serialize,
-               action_equal_cb equal,
-               action_destroy_cb destroy,
-               action_get_rate_policy_cb get_rate_policy,
-               action_add_error_query_results_cb add_error_query_results,
-               action_mi_serialize_cb mi)
+                      enum lttng_action_type type,
+                      action_validate_cb validate,
+                      action_serialize_cb serialize,
+                      action_equal_cb equal,
+                      action_destroy_cb destroy,
+                      action_get_rate_policy_cb get_rate_policy,
+                      action_add_error_query_results_cb add_error_query_results,
+                      action_mi_serialize_cb mi)
 {
        urcu_ref_init(&action->ref);
        action->type = type;
@@ -69,11 +70,9 @@ void lttng_action_init(struct lttng_action *action,
        action->execution_failure_counter = 0;
 }
 
-static
-void action_destroy_ref(struct urcu_ref *ref)
+static void action_destroy_ref(struct urcu_ref *ref)
 {
-       struct lttng_action *action =
-                       lttng::utils::container_of(ref, &lttng_action::ref);
+       struct lttng_action *action = lttng::utils::container_of(ref, &lttng_action::ref);
 
        action->destroy(action);
 }
@@ -118,16 +117,14 @@ end:
        return valid;
 }
 
-int lttng_action_serialize(struct lttng_action *action,
-               struct lttng_payload *payload)
+int lttng_action_serialize(struct lttng_action *action, struct lttng_payload *payload)
 {
        int ret;
        struct lttng_action_comm action_comm = {
                .action_type = (int8_t) action->type,
        };
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &action_comm,
-                       sizeof(action_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &action_comm, sizeof(action_comm));
        if (ret) {
                goto end;
        }
@@ -141,14 +138,13 @@ end:
 }
 
 ssize_t lttng_action_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_action **action)
+                                        struct lttng_action **action)
 {
        ssize_t consumed_len, specific_action_consumed_len;
        action_create_from_payload_cb create_from_payload_cb;
        const struct lttng_action_comm *action_comm;
        const struct lttng_payload_view action_comm_view =
-                       lttng_payload_view_from_view(
-                                       view, 0, sizeof(*action_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*action_comm));
 
        if (!view || !action) {
                consumed_len = -1;
@@ -164,36 +160,31 @@ ssize_t lttng_action_create_from_payload(struct lttng_payload_view *view,
        action_comm = (const struct lttng_action_comm *) action_comm_view.buffer.data;
 
        DBG("Create action from payload: action-type=%s",
-                       lttng_action_type_string((lttng_action_type) action_comm->action_type));
+           lttng_action_type_string((lttng_action_type) action_comm->action_type));
 
        switch (action_comm->action_type) {
        case LTTNG_ACTION_TYPE_NOTIFY:
                create_from_payload_cb = lttng_action_notify_create_from_payload;
                break;
        case LTTNG_ACTION_TYPE_ROTATE_SESSION:
-               create_from_payload_cb =
-                               lttng_action_rotate_session_create_from_payload;
+               create_from_payload_cb = lttng_action_rotate_session_create_from_payload;
                break;
        case LTTNG_ACTION_TYPE_SNAPSHOT_SESSION:
-               create_from_payload_cb =
-                               lttng_action_snapshot_session_create_from_payload;
+               create_from_payload_cb = lttng_action_snapshot_session_create_from_payload;
                break;
        case LTTNG_ACTION_TYPE_START_SESSION:
-               create_from_payload_cb =
-                               lttng_action_start_session_create_from_payload;
+               create_from_payload_cb = lttng_action_start_session_create_from_payload;
                break;
        case LTTNG_ACTION_TYPE_STOP_SESSION:
-               create_from_payload_cb =
-                               lttng_action_stop_session_create_from_payload;
+               create_from_payload_cb = lttng_action_stop_session_create_from_payload;
                break;
        case LTTNG_ACTION_TYPE_LIST:
                create_from_payload_cb = lttng_action_list_create_from_payload;
                break;
        default:
                ERR("Failed to create action from payload, unhandled action type: action-type=%u (%s)",
-                               action_comm->action_type,
-                               lttng_action_type_string(
-                                               (lttng_action_type) action_comm->action_type));
+                   action_comm->action_type,
+                   lttng_action_type_string((lttng_action_type) action_comm->action_type));
                consumed_len = -1;
                goto end;
        }
@@ -201,12 +192,10 @@ ssize_t lttng_action_create_from_payload(struct lttng_payload_view *view,
        {
                /* Create buffer view for the action-type-specific data. */
                struct lttng_payload_view specific_action_view =
-                               lttng_payload_view_from_view(view,
-                                               sizeof(struct lttng_action_comm),
-                                               -1);
+                       lttng_payload_view_from_view(view, sizeof(struct lttng_action_comm), -1);
 
-               specific_action_consumed_len = create_from_payload_cb(
-                               &specific_action_view, action);
+               specific_action_consumed_len =
+                       create_from_payload_cb(&specific_action_view, action);
        }
        if (specific_action_consumed_len < 0) {
                ERR("Failed to create specific action from buffer.");
@@ -216,15 +205,13 @@ ssize_t lttng_action_create_from_payload(struct lttng_payload_view *view,
 
        LTTNG_ASSERT(*action);
 
-       consumed_len = sizeof(struct lttng_action_comm) +
-                      specific_action_consumed_len;
+       consumed_len = sizeof(struct lttng_action_comm) + specific_action_consumed_len;
 
 end:
        return consumed_len;
 }
 
-bool lttng_action_is_equal(const struct lttng_action *a,
-               const struct lttng_action *b)
+bool lttng_action_is_equal(const struct lttng_action *a, const struct lttng_action *b)
 {
        bool is_equal = false;
 
@@ -264,76 +251,73 @@ void lttng_action_increase_execution_failure_count(struct lttng_action *action)
 
 bool lttng_action_should_execute(const struct lttng_action *action)
 {
-       const struct lttng_rate_policy *policy = NULL;
+       const struct lttng_rate_policy *policy = nullptr;
        bool execute = false;
 
-       if (action->get_rate_policy == NULL) {
+       if (action->get_rate_policy == nullptr) {
                execute = true;
                goto end;
        }
 
        policy = action->get_rate_policy(action);
-       if (policy == NULL) {
+       if (policy == nullptr) {
                execute = true;
                goto end;
        }
 
-       execute = lttng_rate_policy_should_execute(
-                       policy, action->execution_request_counter);
+       execute = lttng_rate_policy_should_execute(policy, action->execution_request_counter);
 end:
        return execute;
 }
 
-enum lttng_action_status lttng_action_add_error_query_results(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results)
+enum lttng_action_status
+lttng_action_add_error_query_results(const struct lttng_action *action,
+                                    struct lttng_error_query_results *results)
 {
        return action->add_error_query_results(action, results);
 }
 
-enum lttng_action_status lttng_action_generic_add_error_query_results(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results)
+enum lttng_action_status
+lttng_action_generic_add_error_query_results(const struct lttng_action *action,
+                                            struct lttng_error_query_results *results)
 {
        enum lttng_action_status action_status;
-       struct lttng_error_query_result *error_counter = NULL;
-       const uint64_t execution_failure_counter =
-                       uatomic_read(&action->execution_failure_counter);
+       struct lttng_error_query_result *error_counter = nullptr;
+       const uint64_t execution_failure_counter = uatomic_read(&action->execution_failure_counter);
 
        error_counter = lttng_error_query_result_counter_create(
-                       "total execution failures",
-                       "Aggregated count of errors encountered when executing the action",
-                       execution_failure_counter);
+               "total execution failures",
+               "Aggregated count of errors encountered when executing the action",
+               execution_failure_counter);
        if (!error_counter) {
                action_status = LTTNG_ACTION_STATUS_ERROR;
                goto end;
        }
 
-       if (lttng_error_query_results_add_result(
-                           results, error_counter)) {
+       if (lttng_error_query_results_add_result(results, error_counter)) {
                action_status = LTTNG_ACTION_STATUS_ERROR;
                goto end;
        }
 
        /* Ownership transferred to the results. */
-       error_counter = NULL;
+       error_counter = nullptr;
        action_status = LTTNG_ACTION_STATUS_OK;
 end:
        lttng_error_query_result_destroy(error_counter);
        return action_status;
 }
 
-enum lttng_error_code lttng_action_mi_serialize(const struct lttng_trigger *trigger,
-               const struct lttng_action *action,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks,
-               struct lttng_dynamic_array *action_path_indexes)
+enum lttng_error_code
+lttng_action_mi_serialize(const struct lttng_trigger *trigger,
+                         const struct lttng_action *action,
+                         struct mi_writer *writer,
+                         const struct mi_lttng_error_query_callbacks *error_query_callbacks,
+                         struct lttng_dynamic_array *action_path_indexes)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct lttng_action_path *action_path = NULL;
-       struct lttng_error_query_results *error_query_results = NULL;
+       struct lttng_action_path *action_path = nullptr;
+       struct lttng_error_query_results *error_query_results = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(writer);
@@ -349,8 +333,8 @@ enum lttng_error_code lttng_action_mi_serialize(const struct lttng_trigger *trig
                 * Recursion is safe since action lists can't be nested for
                 * the moment.
                 */
-               ret_code = lttng_action_list_mi_serialize(trigger, action, writer,
-                               error_query_callbacks, action_path_indexes);
+               ret_code = lttng_action_list_mi_serialize(
+                       trigger, action, writer, error_query_callbacks, action_path_indexes);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
@@ -367,31 +351,27 @@ enum lttng_error_code lttng_action_mi_serialize(const struct lttng_trigger *trig
 
        /* Error query for the action. */
        if (error_query_callbacks && error_query_callbacks->action_cb) {
-               const uint64_t *action_path_indexes_raw_pointer = NULL;
+               const uint64_t *action_path_indexes_raw_pointer = nullptr;
                const size_t action_path_indexes_size =
-                               lttng_dynamic_array_get_count(
-                                               action_path_indexes);
+                       lttng_dynamic_array_get_count(action_path_indexes);
 
                if (action_path_indexes_size != 0) {
                        action_path_indexes_raw_pointer =
-                                       (const uint64_t *) action_path_indexes
-                                                       ->buffer.data;
+                               (const uint64_t *) action_path_indexes->buffer.data;
                }
 
-               action_path = lttng_action_path_create(
-                               action_path_indexes_raw_pointer,
-                               action_path_indexes_size);
+               action_path = lttng_action_path_create(action_path_indexes_raw_pointer,
+                                                      action_path_indexes_size);
                LTTNG_ASSERT(action_path);
 
                ret_code = error_query_callbacks->action_cb(
-                               trigger, action_path, &error_query_results);
+                       trigger, action_path, &error_query_results);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
 
                /* Serialize the error query results. */
-               ret_code = lttng_error_query_results_mi_serialize(
-                               error_query_results, writer);
+               ret_code = lttng_error_query_results_mi_serialize(error_query_results, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
index 4de7d81e8a04eeed57210a5b7b08a87e2e6d78df..b56b8eda0025dfda36e528282ef76d1ce7d9b7f1 100644 (file)
 #include <common/mi-lttng.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/list-internal.hpp>
 #include <lttng/action/list.h>
 
-#define IS_LIST_ACTION(action) \
-       (lttng_action_get_type(action) == LTTNG_ACTION_TYPE_LIST)
+#define IS_LIST_ACTION(action) (lttng_action_get_type(action) == LTTNG_ACTION_TYPE_LIST)
 
 namespace {
 struct lttng_action_list {
@@ -43,16 +43,15 @@ static void destroy_lttng_action_list_element(void *ptr)
        lttng_action_destroy(element);
 }
 
-static struct lttng_action_list *action_list_from_action(
-               const struct lttng_action *action)
+static struct lttng_action_list *action_list_from_action(const struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
        return lttng::utils::container_of(action, &lttng_action_list::parent);
 }
 
-static const struct lttng_action_list *action_list_from_action_const(
-               const struct lttng_action *action)
+static const struct lttng_action_list *
+action_list_from_action_const(const struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
@@ -73,8 +72,8 @@ static bool lttng_action_list_validate(struct lttng_action *action)
 
        for (i = 0; i < count; i++) {
                struct lttng_action *child =
-                               (lttng_action *) lttng_dynamic_pointer_array_get_pointer(
-                                               &action_list->actions, i);
+                       (lttng_action *) lttng_dynamic_pointer_array_get_pointer(
+                               &action_list->actions, i);
 
                LTTNG_ASSERT(child);
 
@@ -90,20 +89,17 @@ end:
        return valid;
 }
 
-static bool lttng_action_list_is_equal(
-               const struct lttng_action *_a, const struct lttng_action *_b)
+static bool lttng_action_list_is_equal(const struct lttng_action *_a, const struct lttng_action *_b)
 {
        bool is_equal = false;
        unsigned int i;
        unsigned int a_count, b_count;
 
-       if (lttng_action_list_get_count(_a, &a_count) !=
-                       LTTNG_ACTION_STATUS_OK) {
+       if (lttng_action_list_get_count(_a, &a_count) != LTTNG_ACTION_STATUS_OK) {
                goto end;
        }
 
-       if (lttng_action_list_get_count(_b, &b_count) !=
-                       LTTNG_ACTION_STATUS_OK) {
+       if (lttng_action_list_get_count(_b, &b_count) != LTTNG_ACTION_STATUS_OK) {
                goto end;
        }
 
@@ -112,10 +108,8 @@ static bool lttng_action_list_is_equal(
        }
 
        for (i = 0; i < a_count; i++) {
-               const struct lttng_action *child_a =
-                       lttng_action_list_get_at_index(_a, i);
-               const struct lttng_action *child_b =
-                       lttng_action_list_get_at_index(_b, i);
+               const struct lttng_action *child_a = lttng_action_list_get_at_index(_a, i);
+               const struct lttng_action *child_b = lttng_action_list_get_at_index(_b, i);
 
                LTTNG_ASSERT(child_a);
                LTTNG_ASSERT(child_b);
@@ -130,8 +124,7 @@ end:
        return is_equal;
 }
 
-static int lttng_action_list_serialize(
-               struct lttng_action *action, struct lttng_payload *payload)
+static int lttng_action_list_serialize(struct lttng_action *action, struct lttng_payload *payload)
 {
        struct lttng_action_list *action_list;
        struct lttng_action_list_comm comm;
@@ -150,8 +143,7 @@ static int lttng_action_list_serialize(
 
        comm.action_count = count;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                ret = -1;
                goto end;
@@ -159,8 +151,8 @@ static int lttng_action_list_serialize(
 
        for (i = 0; i < count; i++) {
                struct lttng_action *child =
-                               (lttng_action *) lttng_dynamic_pointer_array_get_pointer(
-                                               &action_list->actions, i);
+                       (lttng_action *) lttng_dynamic_pointer_array_get_pointer(
+                               &action_list->actions, i);
 
                LTTNG_ASSERT(child);
 
@@ -192,14 +184,13 @@ end:
        return;
 }
 
-ssize_t lttng_action_list_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **p_action)
+ssize_t lttng_action_list_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_action **p_action)
 {
        ssize_t consumed_len;
        const struct lttng_action_list_comm *comm;
        struct lttng_action *list;
-       struct lttng_action *child_action = NULL;
+       struct lttng_action *child_action = nullptr;
        enum lttng_action_status status;
        size_t i;
 
@@ -215,17 +206,15 @@ ssize_t lttng_action_list_create_from_payload(
 
        for (i = 0; i < comm->action_count; i++) {
                ssize_t consumed_len_child;
-               struct lttng_payload_view child_view =
-                               lttng_payload_view_from_view(view, consumed_len,
-                                               view->buffer.size - consumed_len);
+               struct lttng_payload_view child_view = lttng_payload_view_from_view(
+                       view, consumed_len, view->buffer.size - consumed_len);
 
                if (!lttng_payload_view_is_valid(&child_view)) {
                        consumed_len = -1;
                        goto end;
                }
 
-               consumed_len_child = lttng_action_create_from_payload(
-                               &child_view, &child_action);
+               consumed_len_child = lttng_action_create_from_payload(&child_view, &child_action);
                if (consumed_len_child < 0) {
                        consumed_len = -1;
                        goto end;
@@ -239,22 +228,22 @@ ssize_t lttng_action_list_create_from_payload(
 
                /* Transfer ownership to the action list. */
                lttng_action_put(child_action);
-               child_action = NULL;
+               child_action = nullptr;
 
                consumed_len += consumed_len_child;
        }
 
        *p_action = list;
-       list = NULL;
+       list = nullptr;
 
 end:
        lttng_action_list_destroy(list);
        return consumed_len;
 }
 
-static enum lttng_action_status lttng_action_list_add_error_query_results(
-               const struct lttng_action *action,
-               struct lttng_error_query_results *results)
+static enum lttng_action_status
+lttng_action_list_add_error_query_results(const struct lttng_action *action,
+                                         struct lttng_error_query_results *results)
 {
        unsigned int i, count;
        enum lttng_action_status action_status;
@@ -266,10 +255,9 @@ static enum lttng_action_status lttng_action_list_add_error_query_results(
 
        for (i = 0; i < count; i++) {
                struct lttng_action *inner_action =
-                               lttng_action_list_borrow_mutable_at_index(action, i);
+                       lttng_action_list_borrow_mutable_at_index(action, i);
 
-               action_status = lttng_action_add_error_query_results(
-                               inner_action, results);
+               action_status = lttng_action_add_error_query_results(inner_action, results);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        goto end;
                }
@@ -278,13 +266,12 @@ end:
        return action_status;
 }
 
-enum lttng_error_code lttng_action_list_mi_serialize(
-               const struct lttng_trigger *trigger,
-               const struct lttng_action *action,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks,
-               struct lttng_dynamic_array *action_path_indexes)
+enum lttng_error_code
+lttng_action_list_mi_serialize(const struct lttng_trigger *trigger,
+                              const struct lttng_action *action,
+                              struct mi_writer *writer,
+                              const struct mi_lttng_error_query_callbacks *error_query_callbacks,
+                              struct lttng_dynamic_array *action_path_indexes)
 {
        int ret;
        struct lttng_action_list *action_list;
@@ -296,8 +283,7 @@ enum lttng_error_code lttng_action_list_mi_serialize(
        LTTNG_ASSERT(writer);
 
        /* Open action list. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_list);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_list);
        if (ret) {
                goto mi_error;
        }
@@ -306,8 +292,7 @@ enum lttng_error_code lttng_action_list_mi_serialize(
        action_list = action_list_from_action(action);
        count = lttng_dynamic_pointer_array_get_count(&action_list->actions);
        for (i = 0; i < count; i++) {
-               const struct lttng_action *child =
-                               lttng_action_list_get_at_index(action, i);
+               const struct lttng_action *child = lttng_action_list_get_at_index(action, i);
                const uint64_t index = (uint64_t) i;
 
                LTTNG_ASSERT(child);
@@ -319,23 +304,21 @@ enum lttng_error_code lttng_action_list_mi_serialize(
                 * tree in-order and to re-use the dynamic array instead of
                 * copying it at every level.
                 */
-               ret = lttng_dynamic_array_add_element(
-                               action_path_indexes, &index);
+               ret = lttng_dynamic_array_add_element(action_path_indexes, &index);
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
                }
 
-               ret_code = lttng_action_mi_serialize(trigger, child, writer,
-                               error_query_callbacks, action_path_indexes);
+               ret_code = lttng_action_mi_serialize(
+                       trigger, child, writer, error_query_callbacks, action_path_indexes);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
 
-               ret = lttng_dynamic_array_remove_element(action_path_indexes,
-                               lttng_dynamic_array_get_count(
-                                               action_path_indexes) -
-                                               1);
+               ret = lttng_dynamic_array_remove_element(
+                       action_path_indexes,
+                       lttng_dynamic_array_get_count(action_path_indexes) - 1);
                if (ret) {
                        ret_code = LTTNG_ERR_UNK;
                        goto end;
@@ -364,7 +347,7 @@ struct lttng_action *lttng_action_list_create(void)
 
        action_list = zmalloc<lttng_action_list>();
        if (!action_list) {
-               action = NULL;
+               action = nullptr;
                goto end;
        }
 
@@ -374,20 +357,24 @@ struct lttng_action *lttng_action_list_create(void)
         * The mi for the list is handled at the lttng_action_mi level to ease
         * action path management for error query.
         */
-       lttng_action_init(action, LTTNG_ACTION_TYPE_LIST,
-                       lttng_action_list_validate, lttng_action_list_serialize,
-                       lttng_action_list_is_equal, lttng_action_list_destroy,
-                       NULL, lttng_action_list_add_error_query_results, NULL);
-
-       lttng_dynamic_pointer_array_init(&action_list->actions,
-                       destroy_lttng_action_list_element);
+       lttng_action_init(action,
+                         LTTNG_ACTION_TYPE_LIST,
+                         lttng_action_list_validate,
+                         lttng_action_list_serialize,
+                         lttng_action_list_is_equal,
+                         lttng_action_list_destroy,
+                         nullptr,
+                         lttng_action_list_add_error_query_results,
+                         nullptr);
+
+       lttng_dynamic_pointer_array_init(&action_list->actions, destroy_lttng_action_list_element);
 
 end:
        return action;
 }
 
-enum lttng_action_status lttng_action_list_add_action(
-               struct lttng_action *list, struct lttng_action *action)
+enum lttng_action_status lttng_action_list_add_action(struct lttng_action *list,
+                                                     struct lttng_action *action)
 {
        struct lttng_action_list *action_list;
        enum lttng_action_status status;
@@ -409,8 +396,7 @@ enum lttng_action_status lttng_action_list_add_action(
 
        action_list = action_list_from_action(list);
 
-       ret = lttng_dynamic_pointer_array_add_pointer(&action_list->actions,
-                       action);
+       ret = lttng_dynamic_pointer_array_add_pointer(&action_list->actions, action);
        if (ret < 0) {
                status = LTTNG_ACTION_STATUS_ERROR;
                goto end;
@@ -423,8 +409,8 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_list_get_count(
-               const struct lttng_action *list, unsigned int *count)
+enum lttng_action_status lttng_action_list_get_count(const struct lttng_action *list,
+                                                    unsigned int *count)
 {
        const struct lttng_action_list *action_list;
        enum lttng_action_status status = LTTNG_ACTION_STATUS_OK;
@@ -441,21 +427,20 @@ end:
        return status;
 }
 
-const struct lttng_action *lttng_action_list_get_at_index(
-               const struct lttng_action *list, unsigned int index)
+const struct lttng_action *lttng_action_list_get_at_index(const struct lttng_action *list,
+                                                         unsigned int index)
 {
        return lttng_action_list_borrow_mutable_at_index(list, index);
 }
 
-struct lttng_action *lttng_action_list_borrow_mutable_at_index(
-               const struct lttng_action *list, unsigned int index)
+struct lttng_action *lttng_action_list_borrow_mutable_at_index(const struct lttng_action *list,
+                                                              unsigned int index)
 {
        unsigned int count;
        const struct lttng_action_list *action_list;
-       struct lttng_action *action = NULL;
+       struct lttng_action *action = nullptr;
 
-       if (lttng_action_list_get_count(list, &count) !=
-                       LTTNG_ACTION_STATUS_OK) {
+       if (lttng_action_list_get_count(list, &count) != LTTNG_ACTION_STATUS_OK) {
                goto end;
        }
 
@@ -465,7 +450,7 @@ struct lttng_action *lttng_action_list_borrow_mutable_at_index(
 
        action_list = action_list_from_action_const(list);
        action = (lttng_action *) lttng_dynamic_pointer_array_get_pointer(&action_list->actions,
-                       index);
+                                                                         index);
 end:
        return action;
 }
index d58dcbe3621b54e1dd139e91a90b743257637a34..cae5ecdc33a880964b1aa178eca9506646954f01 100644 (file)
@@ -8,32 +8,30 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/notify-internal.hpp>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/lttng-error.h>
 
-#define IS_NOTIFY_ACTION(action) \
-       (lttng_action_get_type(action) == LTTNG_ACTION_TYPE_NOTIFY)
+#define IS_NOTIFY_ACTION(action) (lttng_action_get_type(action) == LTTNG_ACTION_TYPE_NOTIFY)
 
-static struct lttng_action_notify *action_notify_from_action(
-               struct lttng_action *action)
+static struct lttng_action_notify *action_notify_from_action(struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
        return lttng::utils::container_of(action, &lttng_action_notify::parent);
 }
 
-static const struct lttng_action_notify *action_notify_from_action_const(
-               const struct lttng_action *action)
+static const struct lttng_action_notify *
+action_notify_from_action_const(const struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
        return lttng::utils::container_of(action, &lttng_action_notify::parent);
 }
 
-static
-void lttng_action_notify_destroy(struct lttng_action *action)
+static void lttng_action_notify_destroy(struct lttng_action *action)
 {
        struct lttng_action_notify *notify_action;
        notify_action = action_notify_from_action(action);
@@ -41,9 +39,7 @@ void lttng_action_notify_destroy(struct lttng_action *action)
        free(notify_action);
 }
 
-static
-int lttng_action_notify_serialize(struct lttng_action *action,
-               struct lttng_payload *payload)
+static int lttng_action_notify_serialize(struct lttng_action *action, struct lttng_payload *payload)
 {
        int ret;
        struct lttng_action_notify *notify_action;
@@ -63,9 +59,7 @@ end:
        return ret;
 }
 
-static
-bool lttng_action_notify_is_equal(const struct lttng_action *a,
-               const struct lttng_action *b)
+static bool lttng_action_notify_is_equal(const struct lttng_action *a, const struct lttng_action *b)
 {
        const struct lttng_action_notify *_a, *_b;
 
@@ -83,13 +77,13 @@ lttng_action_notify_internal_get_rate_policy(const struct lttng_action *action)
        return _action->policy;
 }
 
-static enum lttng_error_code lttng_action_notify_mi_serialize(
-               const struct lttng_action *action, struct mi_writer *writer)
+static enum lttng_error_code lttng_action_notify_mi_serialize(const struct lttng_action *action,
+                                                             struct mi_writer *writer)
 {
        int ret;
        enum lttng_action_status status;
        enum lttng_error_code ret_code;
-       const struct lttng_rate_policy *policy = NULL;
+       const struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(IS_NOTIFY_ACTION(action));
@@ -97,11 +91,10 @@ static enum lttng_error_code lttng_action_notify_mi_serialize(
 
        status = lttng_action_notify_get_rate_policy(action, &policy);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(policy != NULL);
+       LTTNG_ASSERT(policy != nullptr);
 
        /* Open action notify. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_notify);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_notify);
        if (ret) {
                goto mi_error;
        }
@@ -128,9 +121,9 @@ end:
 
 struct lttng_action *lttng_action_notify_create(void)
 {
-       struct lttng_rate_policy *policy = NULL;
-       struct lttng_action_notify *notify = NULL;
-       struct lttng_action *action = NULL;
+       struct lttng_rate_policy *policy = nullptr;
+       struct lttng_action_notify *notify = nullptr;
+       struct lttng_action *action = nullptr;
 
        notify = zmalloc<lttng_action_notify>();
        if (!notify) {
@@ -143,19 +136,21 @@ struct lttng_action *lttng_action_notify_create(void)
                goto end;
        }
 
-       lttng_action_init(&notify->parent, LTTNG_ACTION_TYPE_NOTIFY, NULL,
-                       lttng_action_notify_serialize,
-                       lttng_action_notify_is_equal,
-                       lttng_action_notify_destroy,
-                       lttng_action_notify_internal_get_rate_policy,
-                       lttng_action_generic_add_error_query_results,
-                       lttng_action_notify_mi_serialize);
+       lttng_action_init(&notify->parent,
+                         LTTNG_ACTION_TYPE_NOTIFY,
+                         nullptr,
+                         lttng_action_notify_serialize,
+                         lttng_action_notify_is_equal,
+                         lttng_action_notify_destroy,
+                         lttng_action_notify_internal_get_rate_policy,
+                         lttng_action_generic_add_error_query_results,
+                         lttng_action_notify_mi_serialize);
 
        notify->policy = policy;
-       policy = NULL;
+       policy = nullptr;
 
        action = &notify->parent;
-       notify = NULL;
+       notify = nullptr;
 
 end:
        free(notify);
@@ -163,17 +158,15 @@ end:
        return action;
 }
 
-ssize_t lttng_action_notify_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **action)
+ssize_t lttng_action_notify_create_from_payload(struct lttng_payload_view *view,
+                                               struct lttng_action **action)
 {
        enum lttng_action_status status;
        ssize_t consumed_length;
-       struct lttng_rate_policy *rate_policy = NULL;
-       struct lttng_action *_action = NULL;
+       struct lttng_rate_policy *rate_policy = nullptr;
+       struct lttng_action *_action = nullptr;
 
-       consumed_length = lttng_rate_policy_create_from_payload(
-                       view, &rate_policy);
+       consumed_length = lttng_rate_policy_create_from_payload(view, &rate_policy);
        if (!rate_policy) {
                consumed_length = -1;
                goto end;
@@ -192,7 +185,7 @@ ssize_t lttng_action_notify_create_from_payload(
        }
 
        *action = _action;
-       _action = NULL;
+       _action = nullptr;
 
 end:
        lttng_rate_policy_destroy(rate_policy);
@@ -200,13 +193,12 @@ end:
        return consumed_length;
 }
 
-enum lttng_action_status lttng_action_notify_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy)
+enum lttng_action_status lttng_action_notify_set_rate_policy(struct lttng_action *action,
+                                                            const struct lttng_rate_policy *policy)
 {
        enum lttng_action_status status;
        struct lttng_action_notify *notify_action;
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
 
        if (!action || !policy || !IS_NOTIFY_ACTION(action)) {
                status = LTTNG_ACTION_STATUS_INVALID;
@@ -227,16 +219,16 @@ enum lttng_action_status lttng_action_notify_set_rate_policy(
        /* Assign the policy. */
        notify_action->policy = copy;
        status = LTTNG_ACTION_STATUS_OK;
-       copy = NULL;
+       copy = nullptr;
 
 end:
        lttng_rate_policy_destroy(copy);
        return status;
 }
 
-enum lttng_action_status lttng_action_notify_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy)
+enum lttng_action_status
+lttng_action_notify_get_rate_policy(const struct lttng_action *action,
+                                   const struct lttng_rate_policy **policy)
 {
        enum lttng_action_status status;
        const struct lttng_action_notify *notify_action;
index 612ade8c31a69e7696312c9882c145b1700335e4..383c64839688b8913fdcd631ee5946c2b1139293 100644 (file)
@@ -14,12 +14,11 @@ struct lttng_action_path_comm {
 } LTTNG_PACKED;
 } /* namespace */
 
-struct lttng_action_path *lttng_action_path_create(
-               const uint64_t *indexes, size_t index_count)
+struct lttng_action_path *lttng_action_path_create(const uint64_t *indexes, size_t index_count)
 {
        int ret;
        size_t i;
-       struct lttng_action_path *path = NULL;
+       struct lttng_action_path *path = nullptr;
 
        if (!indexes && index_count > 0) {
                goto error;
@@ -30,11 +29,10 @@ struct lttng_action_path *lttng_action_path_create(
                goto error;
        }
 
-       lttng_dynamic_array_init(&path->indexes, sizeof(uint64_t), NULL);
+       lttng_dynamic_array_init(&path->indexes, sizeof(uint64_t), nullptr);
 
        for (i = 0; i < index_count; i++) {
-               ret = lttng_dynamic_array_add_element(
-                               &path->indexes, &indexes[i]);
+               ret = lttng_dynamic_array_add_element(&path->indexes, &indexes[i]);
                if (ret) {
                        goto error;
                }
@@ -43,13 +41,13 @@ struct lttng_action_path *lttng_action_path_create(
        goto end;
 error:
        lttng_action_path_destroy(path);
-       path = NULL;
+       path = nullptr;
 end:
        return path;
 }
 
-enum lttng_action_path_status lttng_action_path_get_index_count(
-               const struct lttng_action_path *path, size_t *index_count)
+enum lttng_action_path_status
+lttng_action_path_get_index_count(const struct lttng_action_path *path, size_t *index_count)
 {
        enum lttng_action_path_status status;
 
@@ -65,21 +63,17 @@ end:
 }
 
 enum lttng_action_path_status lttng_action_path_get_index_at_index(
-               const struct lttng_action_path *path,
-               size_t path_index,
-               uint64_t *out_index)
+       const struct lttng_action_path *path, size_t path_index, uint64_t *out_index)
 {
        enum lttng_action_path_status status;
 
-       if (!path || !out_index ||
-                       path_index >= lttng_dynamic_array_get_count(
-                               &path->indexes)) {
+       if (!path || !out_index || path_index >= lttng_dynamic_array_get_count(&path->indexes)) {
                status = LTTNG_ACTION_PATH_STATUS_INVALID;
                goto end;
        }
 
-       *out_index = *((typeof(out_index)) lttng_dynamic_array_get_element(
-                       &path->indexes, path_index));
+       *out_index =
+               *((typeof(out_index)) lttng_dynamic_array_get_element(&path->indexes, path_index));
        status = LTTNG_ACTION_PATH_STATUS_OK;
 end:
        return status;
@@ -97,8 +91,7 @@ end:
        return;
 }
 
-int lttng_action_path_copy(const struct lttng_action_path *src,
-               struct lttng_action_path **dst)
+int lttng_action_path_copy(const struct lttng_action_path *src, struct lttng_action_path **dst)
 {
        int ret;
        struct lttng_action_path *new_path;
@@ -107,9 +100,8 @@ int lttng_action_path_copy(const struct lttng_action_path *src,
        LTTNG_ASSERT(dst);
 
        new_path = lttng_action_path_create(
-                       (uint64_t *) lttng_dynamic_array_get_element(
-                               &src->indexes, 0), 
-                       lttng_dynamic_array_get_count(&src->indexes));
+               (uint64_t *) lttng_dynamic_array_get_element(&src->indexes, 0),
+               lttng_dynamic_array_get_count(&src->indexes));
        if (!new_path) {
                ret = -1;
        } else {
@@ -120,15 +112,14 @@ int lttng_action_path_copy(const struct lttng_action_path *src,
        return ret;
 }
 
-ssize_t lttng_action_path_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action_path **_action_path)
+ssize_t lttng_action_path_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_action_path **_action_path)
 {
        ssize_t consumed_size = 0, ret = -1;
        const struct lttng_action_path_comm *header;
-       struct lttng_action_path *action_path = NULL;
+       struct lttng_action_path *action_path = nullptr;
        const struct lttng_payload_view header_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*header));
+               lttng_payload_view_from_view(view, 0, sizeof(*header));
 
        if (!lttng_payload_view_is_valid(&header_view)) {
                goto end;
@@ -142,27 +133,22 @@ ssize_t lttng_action_path_create_from_payload(
         * single non-list action. Handle it differently since a payload view of
         * size 0 is considered invalid.
         */
-       if (header->index_count != 0)
-       {
-               const struct lttng_payload_view indexes_view =
-                               lttng_payload_view_from_view(view,
-                                               consumed_size,
-                                               header->index_count *
-                                                               sizeof(uint64_t));
+       if (header->index_count != 0) {
+               const struct lttng_payload_view indexes_view = lttng_payload_view_from_view(
+                       view, consumed_size, header->index_count * sizeof(uint64_t));
 
                if (!lttng_payload_view_is_valid(&indexes_view)) {
                        goto end;
                }
 
                consumed_size += indexes_view.buffer.size;
-               action_path = lttng_action_path_create(
-                               (const uint64_t *) indexes_view.buffer.data,
-                               header->index_count);
+               action_path = lttng_action_path_create((const uint64_t *) indexes_view.buffer.data,
+                                                      header->index_count);
                if (!action_path) {
                        goto end;
                }
        } else {
-               action_path = lttng_action_path_create(NULL, 0);
+               action_path = lttng_action_path_create(nullptr, 0);
                if (!action_path) {
                        goto end;
                }
@@ -175,7 +161,7 @@ end:
 }
 
 int lttng_action_path_serialize(const struct lttng_action_path *action_path,
-               struct lttng_payload *payload)
+                               struct lttng_payload *payload)
 {
        int ret;
        size_t index_count, i;
@@ -189,22 +175,20 @@ int lttng_action_path_serialize(const struct lttng_action_path *action_path,
        }
 
        comm.index_count = (uint32_t) index_count;
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       &comm,
-                       sizeof(struct lttng_action_path_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &comm, sizeof(struct lttng_action_path_comm));
 
        for (i = 0; i < index_count; i++) {
                uint64_t path_index;
 
-               status = lttng_action_path_get_index_at_index(
-                               action_path, i, &path_index);
+               status = lttng_action_path_get_index_at_index(action_path, i, &path_index);
                if (status != LTTNG_ACTION_PATH_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&payload->buffer, &path_index,
-                               sizeof(path_index));
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, &path_index, sizeof(path_index));
                if (ret) {
                        goto end;
                }
index 303b4a781765ab71f4a739073c0ac168b95b71c0..60def0d9d45231b45878890543f17447a120e271 100644 (file)
 #include <common/mi-lttng.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
-#include <limits.h>
+
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
+
+#include <limits.h>
 #include <stdbool.h>
 #include <sys/types.h>
 
 #define IS_EVERY_N_RATE_POLICY(policy) \
        (lttng_rate_policy_get_type(policy) == LTTNG_RATE_POLICY_TYPE_EVERY_N)
 
-#define IS_ONCE_AFTER_N_RATE_POLICY(policy)    \
-       (lttng_rate_policy_get_type(policy) == \
-                       LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N)
-
-typedef void (*rate_policy_destroy_cb)(struct lttng_rate_policy *rate_policy);
-typedef int (*rate_policy_serialize_cb)(struct lttng_rate_policy *rate_policy,
-               struct lttng_payload *payload);
-typedef bool (*rate_policy_equal_cb)(const struct lttng_rate_policy *a,
-               const struct lttng_rate_policy *b);
-typedef ssize_t (*rate_policy_create_from_payload_cb)(
-               struct lttng_payload_view *view,
-               struct lttng_rate_policy **rate_policy);
-typedef struct lttng_rate_policy *(*rate_policy_copy_cb)(
-               const struct lttng_rate_policy *source);
-typedef enum lttng_error_code (*rate_policy_mi_serialize_cb)(
-               const struct lttng_rate_policy *rate_policy,
-               struct mi_writer *writer);
+#define IS_ONCE_AFTER_N_RATE_POLICY(policy) \
+       (lttng_rate_policy_get_type(policy) == LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N)
+
+using rate_policy_destroy_cb = void (*)(struct lttng_rate_policy *);
+using rate_policy_serialize_cb = int (*)(struct lttng_rate_policy *, struct lttng_payload *);
+using rate_policy_equal_cb = bool (*)(const struct lttng_rate_policy *,
+                                     const struct lttng_rate_policy *);
+using rate_policy_create_from_payload_cb = ssize_t (*)(struct lttng_payload_view *,
+                                                      struct lttng_rate_policy **);
+using rate_policy_copy_cb = struct lttng_rate_policy *(*) (const struct lttng_rate_policy *);
+using rate_policy_mi_serialize_cb = enum lttng_error_code (*)(const struct lttng_rate_policy *,
+                                                             struct mi_writer *);
 
 struct lttng_rate_policy {
        enum lttng_rate_policy_type type;
@@ -75,23 +72,22 @@ struct lttng_rate_policy_every_n_comm {
 
 /* Forward declaration. */
 static void lttng_rate_policy_init(struct lttng_rate_policy *rate_policy,
-               enum lttng_rate_policy_type type,
-               rate_policy_serialize_cb serialize,
-               rate_policy_equal_cb equal,
-               rate_policy_destroy_cb destroy,
-               rate_policy_copy_cb copy,
-               rate_policy_mi_serialize_cb mi);
+                                  enum lttng_rate_policy_type type,
+                                  rate_policy_serialize_cb serialize,
+                                  rate_policy_equal_cb equal,
+                                  rate_policy_destroy_cb destroy,
+                                  rate_policy_copy_cb copy,
+                                  rate_policy_mi_serialize_cb mi);
 
 /* Forward declaration. Every n */
-static bool lttng_rate_policy_every_n_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter);
+static bool lttng_rate_policy_every_n_should_execute(const struct lttng_rate_policy *policy,
+                                                    uint64_t counter);
 
 /* Forward declaration. Once after N */
-static bool lttng_rate_policy_once_after_n_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter);
+static bool lttng_rate_policy_once_after_n_should_execute(const struct lttng_rate_policy *policy,
+                                                         uint64_t counter);
 
-const char *lttng_rate_policy_type_string(
-               enum lttng_rate_policy_type rate_policy_type)
+const char *lttng_rate_policy_type_string(enum lttng_rate_policy_type rate_policy_type)
 {
        switch (rate_policy_type) {
        case LTTNG_RATE_POLICY_TYPE_EVERY_N:
@@ -103,19 +99,18 @@ const char *lttng_rate_policy_type_string(
        }
 }
 
-enum lttng_rate_policy_type lttng_rate_policy_get_type(
-               const struct lttng_rate_policy *policy)
+enum lttng_rate_policy_type lttng_rate_policy_get_type(const struct lttng_rate_policy *policy)
 {
        return policy ? policy->type : LTTNG_RATE_POLICY_TYPE_UNKNOWN;
 }
 
 void lttng_rate_policy_init(struct lttng_rate_policy *rate_policy,
-               enum lttng_rate_policy_type type,
-               rate_policy_serialize_cb serialize,
-               rate_policy_equal_cb equal,
-               rate_policy_destroy_cb destroy,
-               rate_policy_copy_cb copy,
-               rate_policy_mi_serialize_cb mi)
+                           enum lttng_rate_policy_type type,
+                           rate_policy_serialize_cb serialize,
+                           rate_policy_equal_cb equal,
+                           rate_policy_destroy_cb destroy,
+                           rate_policy_copy_cb copy,
+                           rate_policy_mi_serialize_cb mi)
 {
        rate_policy->type = type;
        rate_policy->serialize = serialize;
@@ -135,15 +130,15 @@ void lttng_rate_policy_destroy(struct lttng_rate_policy *rate_policy)
 }
 
 int lttng_rate_policy_serialize(struct lttng_rate_policy *rate_policy,
-               struct lttng_payload *payload)
+                               struct lttng_payload *payload)
 {
        int ret;
        struct lttng_rate_policy_comm rate_policy_comm = {
-                       .rate_policy_type = (int8_t) rate_policy->type,
+               .rate_policy_type = (int8_t) rate_policy->type,
        };
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &rate_policy_comm,
-                       sizeof(rate_policy_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &rate_policy_comm, sizeof(rate_policy_comm));
        if (ret) {
                goto end;
        }
@@ -156,15 +151,15 @@ end:
        return ret;
 }
 
-static ssize_t lttng_rate_policy_once_after_n_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_rate_policy **rate_policy)
+static ssize_t
+lttng_rate_policy_once_after_n_create_from_payload(struct lttng_payload_view *view,
+                                                  struct lttng_rate_policy **rate_policy)
 {
        ssize_t consumed_len = -1;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
        const struct lttng_rate_policy_once_after_n_comm *comm;
        const struct lttng_payload_view comm_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*comm));
 
        if (!view || !rate_policy) {
                consumed_len = -1;
@@ -177,11 +172,10 @@ static ssize_t lttng_rate_policy_once_after_n_create_from_payload(
                goto end;
        }
 
-       comm = (const struct lttng_rate_policy_once_after_n_comm *)
-                              comm_view.buffer.data;
+       comm = (const struct lttng_rate_policy_once_after_n_comm *) comm_view.buffer.data;
 
        policy = lttng_rate_policy_once_after_n_create(comm->threshold);
-       if (policy == NULL) {
+       if (policy == nullptr) {
                consumed_len = -1;
                goto end;
        }
@@ -193,15 +187,14 @@ end:
        return consumed_len;
 }
 
-static ssize_t lttng_rate_policy_every_n_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_rate_policy **rate_policy)
+static ssize_t lttng_rate_policy_every_n_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_rate_policy **rate_policy)
 {
        ssize_t consumed_len = -1;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
        const struct lttng_rate_policy_every_n_comm *comm;
        const struct lttng_payload_view comm_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*comm));
 
        if (!view || !rate_policy) {
                consumed_len = -1;
@@ -214,11 +207,10 @@ static ssize_t lttng_rate_policy_every_n_create_from_payload(
                goto end;
        }
 
-       comm = (const struct lttng_rate_policy_every_n_comm *)
-                              comm_view.buffer.data;
+       comm = (const struct lttng_rate_policy_every_n_comm *) comm_view.buffer.data;
 
        policy = lttng_rate_policy_every_n_create(comm->interval);
-       if (policy == NULL) {
+       if (policy == nullptr) {
                consumed_len = -1;
                goto end;
        }
@@ -231,14 +223,13 @@ end:
 }
 
 ssize_t lttng_rate_policy_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_rate_policy **rate_policy)
+                                             struct lttng_rate_policy **rate_policy)
 {
        ssize_t consumed_len, specific_rate_policy_consumed_len;
        rate_policy_create_from_payload_cb create_from_payload_cb;
        const struct lttng_rate_policy_comm *rate_policy_comm;
        const struct lttng_payload_view rate_policy_comm_view =
-               lttng_payload_view_from_view(
-                       view, 0, sizeof(*rate_policy_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*rate_policy_comm));
 
        if (!view || !rate_policy) {
                consumed_len = -1;
@@ -251,27 +242,25 @@ ssize_t lttng_rate_policy_create_from_payload(struct lttng_payload_view *view,
                goto end;
        }
 
-       rate_policy_comm = (const struct lttng_rate_policy_comm *)
-                                          rate_policy_comm_view.buffer.data;
+       rate_policy_comm =
+               (const struct lttng_rate_policy_comm *) rate_policy_comm_view.buffer.data;
 
        DBG("Create rate_policy from payload: rate-policy-type=%s",
-               lttng_rate_policy_type_string(
-                       (lttng_rate_policy_type) rate_policy_comm->rate_policy_type));
+           lttng_rate_policy_type_string(
+                   (lttng_rate_policy_type) rate_policy_comm->rate_policy_type));
 
        switch (rate_policy_comm->rate_policy_type) {
        case LTTNG_RATE_POLICY_TYPE_EVERY_N:
-               create_from_payload_cb =
-                               lttng_rate_policy_every_n_create_from_payload;
+               create_from_payload_cb = lttng_rate_policy_every_n_create_from_payload;
                break;
        case LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N:
-               create_from_payload_cb =
-                               lttng_rate_policy_once_after_n_create_from_payload;
+               create_from_payload_cb = lttng_rate_policy_once_after_n_create_from_payload;
                break;
        default:
                ERR("Failed to create rate-policy from payload, unhandled rate-policy type: rate-policy-type=%u (%s)",
-                               rate_policy_comm->rate_policy_type,
-                               lttng_rate_policy_type_string(
-                                       (lttng_rate_policy_type) rate_policy_comm->rate_policy_type));
+                   rate_policy_comm->rate_policy_type,
+                   lttng_rate_policy_type_string(
+                           (lttng_rate_policy_type) rate_policy_comm->rate_policy_type));
                consumed_len = -1;
                goto end;
        }
@@ -279,13 +268,11 @@ ssize_t lttng_rate_policy_create_from_payload(struct lttng_payload_view *view,
        {
                /* Create buffer view for the rate_policy-type-specific data.
                 */
-               struct lttng_payload_view specific_rate_policy_view =
-                               lttng_payload_view_from_view(view,
-                                               sizeof(struct lttng_rate_policy_comm),
-                                               -1);
+               struct lttng_payload_view specific_rate_policy_view = lttng_payload_view_from_view(
+                       view, sizeof(struct lttng_rate_policy_comm), -1);
 
-               specific_rate_policy_consumed_len = create_from_payload_cb(
-                               &specific_rate_policy_view, rate_policy);
+               specific_rate_policy_consumed_len =
+                       create_from_payload_cb(&specific_rate_policy_view, rate_policy);
        }
        if (specific_rate_policy_consumed_len < 0) {
                ERR("Failed to create specific rate_policy from buffer.");
@@ -295,15 +282,14 @@ ssize_t lttng_rate_policy_create_from_payload(struct lttng_payload_view *view,
 
        LTTNG_ASSERT(*rate_policy);
 
-       consumed_len = sizeof(struct lttng_rate_policy_comm) +
-                       specific_rate_policy_consumed_len;
+       consumed_len = sizeof(struct lttng_rate_policy_comm) + specific_rate_policy_consumed_len;
 
 end:
        return consumed_len;
 }
 
 bool lttng_rate_policy_is_equal(const struct lttng_rate_policy *a,
-               const struct lttng_rate_policy *b)
+                               const struct lttng_rate_policy *b)
 {
        bool is_equal = false;
 
@@ -326,16 +312,13 @@ end:
        return is_equal;
 }
 
-bool lttng_rate_policy_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter)
+bool lttng_rate_policy_should_execute(const struct lttng_rate_policy *policy, uint64_t counter)
 {
        switch (policy->type) {
        case LTTNG_RATE_POLICY_TYPE_EVERY_N:
-               return lttng_rate_policy_every_n_should_execute(
-                               policy, counter);
+               return lttng_rate_policy_every_n_should_execute(policy, counter);
        case LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N:
-               return lttng_rate_policy_once_after_n_should_execute(
-                               policy, counter);
+               return lttng_rate_policy_once_after_n_should_execute(policy, counter);
        default:
                abort();
                break;
@@ -343,8 +326,8 @@ bool lttng_rate_policy_should_execute(
 }
 
 /* Every N */
-static struct lttng_rate_policy_every_n *rate_policy_every_n_from_rate_policy(
-               struct lttng_rate_policy *policy)
+static struct lttng_rate_policy_every_n *
+rate_policy_every_n_from_rate_policy(struct lttng_rate_policy *policy)
 {
        LTTNG_ASSERT(policy);
 
@@ -352,16 +335,15 @@ static struct lttng_rate_policy_every_n *rate_policy_every_n_from_rate_policy(
 }
 
 static const struct lttng_rate_policy_every_n *
-rate_policy_every_n_from_rate_policy_const(
-               const struct lttng_rate_policy *policy)
+rate_policy_every_n_from_rate_policy_const(const struct lttng_rate_policy *policy)
 {
        LTTNG_ASSERT(policy);
 
        return lttng::utils::container_of(policy, &lttng_rate_policy_every_n::parent);
 }
 
-static int lttng_rate_policy_every_n_serialize(
-               struct lttng_rate_policy *policy, struct lttng_payload *payload)
+static int lttng_rate_policy_every_n_serialize(struct lttng_rate_policy *policy,
+                                              struct lttng_payload *payload)
 {
        int ret;
 
@@ -374,14 +356,12 @@ static int lttng_rate_policy_every_n_serialize(
        every_n_policy = rate_policy_every_n_from_rate_policy(policy);
        comm.interval = every_n_policy->interval;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        return ret;
 }
 
-static bool lttng_rate_policy_every_n_is_equal(
-               const struct lttng_rate_policy *_a,
-               const struct lttng_rate_policy *_b)
+static bool lttng_rate_policy_every_n_is_equal(const struct lttng_rate_policy *_a,
+                                              const struct lttng_rate_policy *_b)
 {
        bool is_equal = false;
        const struct lttng_rate_policy_every_n *a, *b;
@@ -415,10 +395,10 @@ end:
        return;
 }
 
-static struct lttng_rate_policy *lttng_rate_policy_every_n_copy(
-               const struct lttng_rate_policy *source)
+static struct lttng_rate_policy *
+lttng_rate_policy_every_n_copy(const struct lttng_rate_policy *source)
 {
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
        const struct lttng_rate_policy_every_n *every_n_policy;
 
        if (!source) {
@@ -432,32 +412,29 @@ end:
        return copy;
 }
 
-static enum lttng_error_code lttng_rate_policy_every_n_mi_serialize(
-               const struct lttng_rate_policy *rate_policy,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_rate_policy_every_n_mi_serialize(const struct lttng_rate_policy *rate_policy,
+                                      struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const struct lttng_rate_policy_every_n *every_n_policy = NULL;
+       const struct lttng_rate_policy_every_n *every_n_policy = nullptr;
 
        LTTNG_ASSERT(rate_policy);
        LTTNG_ASSERT(IS_EVERY_N_RATE_POLICY(rate_policy));
        LTTNG_ASSERT(writer);
 
-       every_n_policy = rate_policy_every_n_from_rate_policy_const(
-                       rate_policy);
+       every_n_policy = rate_policy_every_n_from_rate_policy_const(rate_policy);
 
        /* Open rate_policy_every_n element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_rate_policy_every_n);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rate_policy_every_n);
        if (ret) {
                goto mi_error;
        }
 
        /* Interval. */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_rate_policy_every_n_interval,
-                       every_n_policy->interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_rate_policy_every_n_interval, every_n_policy->interval);
        if (ret) {
                goto mi_error;
        }
@@ -479,8 +456,8 @@ end:
 
 struct lttng_rate_policy *lttng_rate_policy_every_n_create(uint64_t interval)
 {
-       struct lttng_rate_policy_every_n *policy = NULL;
-       struct lttng_rate_policy *_policy = NULL;
+       struct lttng_rate_policy_every_n *policy = nullptr;
+       struct lttng_rate_policy *_policy = nullptr;
 
        if (interval == 0) {
                /*
@@ -494,25 +471,26 @@ struct lttng_rate_policy *lttng_rate_policy_every_n_create(uint64_t interval)
                goto end;
        }
 
-       lttng_rate_policy_init(&policy->parent, LTTNG_RATE_POLICY_TYPE_EVERY_N,
-                       lttng_rate_policy_every_n_serialize,
-                       lttng_rate_policy_every_n_is_equal,
-                       lttng_rate_policy_every_n_destroy,
-                       lttng_rate_policy_every_n_copy,
-                       lttng_rate_policy_every_n_mi_serialize);
+       lttng_rate_policy_init(&policy->parent,
+                              LTTNG_RATE_POLICY_TYPE_EVERY_N,
+                              lttng_rate_policy_every_n_serialize,
+                              lttng_rate_policy_every_n_is_equal,
+                              lttng_rate_policy_every_n_destroy,
+                              lttng_rate_policy_every_n_copy,
+                              lttng_rate_policy_every_n_mi_serialize);
 
        policy->interval = interval;
 
        _policy = &policy->parent;
-       policy = NULL;
+       policy = nullptr;
 
 end:
        free(policy);
        return _policy;
 }
 
-enum lttng_rate_policy_status lttng_rate_policy_every_n_get_interval(
-               const struct lttng_rate_policy *policy, uint64_t *interval)
+enum lttng_rate_policy_status
+lttng_rate_policy_every_n_get_interval(const struct lttng_rate_policy *policy, uint64_t *interval)
 {
        const struct lttng_rate_policy_every_n *every_n_policy;
        enum lttng_rate_policy_status status;
@@ -530,8 +508,8 @@ end:
        return status;
 }
 
-static bool lttng_rate_policy_every_n_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter)
+static bool lttng_rate_policy_every_n_should_execute(const struct lttng_rate_policy *policy,
+                                                    uint64_t counter)
 {
        const struct lttng_rate_policy_every_n *every_n_policy;
        LTTNG_ASSERT(policy);
@@ -545,10 +523,10 @@ static bool lttng_rate_policy_every_n_should_execute(
 
        execute = (counter % every_n_policy->interval) == 0;
 
-       DBG("Policy every N = %" PRIu64
-           ": execution %s. Execution count: %" PRIu64,
-                       every_n_policy->interval,
-                       execute ? "accepted" : "denied", counter);
+       DBG("Policy every N = %" PRIu64 ": execution %s. Execution count: %" PRIu64,
+           every_n_policy->interval,
+           execute ? "accepted" : "denied",
+           counter);
 
        return execute;
 }
@@ -560,21 +538,18 @@ rate_policy_once_after_n_from_rate_policy(struct lttng_rate_policy *policy)
 {
        LTTNG_ASSERT(policy);
 
-       return lttng::utils::container_of(
-                       policy, &lttng_rate_policy_once_after_n::parent);
+       return lttng::utils::container_of(policy, &lttng_rate_policy_once_after_n::parent);
 }
 
 static const struct lttng_rate_policy_once_after_n *
-rate_policy_once_after_n_from_rate_policy_const(
-               const struct lttng_rate_policy *policy)
+rate_policy_once_after_n_from_rate_policy_const(const struct lttng_rate_policy *policy)
 {
        LTTNG_ASSERT(policy);
 
-       return lttng::utils::container_of(
-                       policy, &lttng_rate_policy_once_after_n::parent);
+       return lttng::utils::container_of(policy, &lttng_rate_policy_once_after_n::parent);
 }
-static int lttng_rate_policy_once_after_n_serialize(
-               struct lttng_rate_policy *policy, struct lttng_payload *payload)
+static int lttng_rate_policy_once_after_n_serialize(struct lttng_rate_policy *policy,
+                                                   struct lttng_payload *payload)
 {
        int ret;
 
@@ -587,14 +562,12 @@ static int lttng_rate_policy_once_after_n_serialize(
        once_after_n_policy = rate_policy_once_after_n_from_rate_policy(policy);
        comm.threshold = once_after_n_policy->threshold;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        return ret;
 }
 
-static bool lttng_rate_policy_once_after_n_is_equal(
-               const struct lttng_rate_policy *_a,
-               const struct lttng_rate_policy *_b)
+static bool lttng_rate_policy_once_after_n_is_equal(const struct lttng_rate_policy *_a,
+                                                   const struct lttng_rate_policy *_b)
 {
        bool is_equal = false;
        const struct lttng_rate_policy_once_after_n *a, *b;
@@ -612,8 +585,7 @@ end:
        return is_equal;
 }
 
-static void lttng_rate_policy_once_after_n_destroy(
-               struct lttng_rate_policy *policy)
+static void lttng_rate_policy_once_after_n_destroy(struct lttng_rate_policy *policy)
 {
        struct lttng_rate_policy_once_after_n *once_after_n_policy;
 
@@ -629,51 +601,48 @@ end:
        return;
 }
 
-static struct lttng_rate_policy *lttng_rate_policy_once_after_n_copy(
-               const struct lttng_rate_policy *source)
+static struct lttng_rate_policy *
+lttng_rate_policy_once_after_n_copy(const struct lttng_rate_policy *source)
 {
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
        const struct lttng_rate_policy_once_after_n *once_after_n_policy;
 
        if (!source) {
                goto end;
        }
 
-       once_after_n_policy =
-                       rate_policy_once_after_n_from_rate_policy_const(source);
-       copy = lttng_rate_policy_once_after_n_create(
-                       once_after_n_policy->threshold);
+       once_after_n_policy = rate_policy_once_after_n_from_rate_policy_const(source);
+       copy = lttng_rate_policy_once_after_n_create(once_after_n_policy->threshold);
 
 end:
        return copy;
 }
 
-static enum lttng_error_code lttng_rate_policy_once_after_n_mi_serialize(
-               const struct lttng_rate_policy *rate_policy,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_rate_policy_once_after_n_mi_serialize(const struct lttng_rate_policy *rate_policy,
+                                           struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const struct lttng_rate_policy_once_after_n *once_after_n_policy = NULL;
+       const struct lttng_rate_policy_once_after_n *once_after_n_policy = nullptr;
 
        LTTNG_ASSERT(rate_policy);
        LTTNG_ASSERT(IS_ONCE_AFTER_N_RATE_POLICY(rate_policy));
        LTTNG_ASSERT(writer);
 
-       once_after_n_policy = rate_policy_once_after_n_from_rate_policy_const(
-                       rate_policy);
+       once_after_n_policy = rate_policy_once_after_n_from_rate_policy_const(rate_policy);
 
        /* Open rate_policy_once_after_n. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_rate_policy_once_after_n);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rate_policy_once_after_n);
        if (ret) {
                goto mi_error;
        }
 
        /* Threshold. */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_rate_policy_once_after_n_threshold,
-                       once_after_n_policy->threshold);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer,
+               mi_lttng_element_rate_policy_once_after_n_threshold,
+               once_after_n_policy->threshold);
        if (ret) {
                goto mi_error;
        }
@@ -693,11 +662,10 @@ end:
        return ret_code;
 }
 
-struct lttng_rate_policy *lttng_rate_policy_once_after_n_create(
-               uint64_t threshold)
+struct lttng_rate_policy *lttng_rate_policy_once_after_n_create(uint64_t threshold)
 {
-       struct lttng_rate_policy_once_after_n *policy = NULL;
-       struct lttng_rate_policy *_policy = NULL;
+       struct lttng_rate_policy_once_after_n *policy = nullptr;
+       struct lttng_rate_policy *_policy = nullptr;
 
        if (threshold == 0) {
                /* threshold is expected to be > 0 */
@@ -710,25 +678,26 @@ struct lttng_rate_policy *lttng_rate_policy_once_after_n_create(
        }
 
        lttng_rate_policy_init(&policy->parent,
-                       LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N,
-                       lttng_rate_policy_once_after_n_serialize,
-                       lttng_rate_policy_once_after_n_is_equal,
-                       lttng_rate_policy_once_after_n_destroy,
-                       lttng_rate_policy_once_after_n_copy,
-                       lttng_rate_policy_once_after_n_mi_serialize);
+                              LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N,
+                              lttng_rate_policy_once_after_n_serialize,
+                              lttng_rate_policy_once_after_n_is_equal,
+                              lttng_rate_policy_once_after_n_destroy,
+                              lttng_rate_policy_once_after_n_copy,
+                              lttng_rate_policy_once_after_n_mi_serialize);
 
        policy->threshold = threshold;
 
        _policy = &policy->parent;
-       policy = NULL;
+       policy = nullptr;
 
 end:
        free(policy);
        return _policy;
 }
 
-enum lttng_rate_policy_status lttng_rate_policy_once_after_n_get_threshold(
-               const struct lttng_rate_policy *policy, uint64_t *threshold)
+enum lttng_rate_policy_status
+lttng_rate_policy_once_after_n_get_threshold(const struct lttng_rate_policy *policy,
+                                            uint64_t *threshold)
 {
        const struct lttng_rate_policy_once_after_n *once_after_n_policy;
        enum lttng_rate_policy_status status;
@@ -738,8 +707,7 @@ enum lttng_rate_policy_status lttng_rate_policy_once_after_n_get_threshold(
                goto end;
        }
 
-       once_after_n_policy =
-                       rate_policy_once_after_n_from_rate_policy_const(policy);
+       once_after_n_policy = rate_policy_once_after_n_from_rate_policy_const(policy);
        *threshold = once_after_n_policy->threshold;
        status = LTTNG_RATE_POLICY_STATUS_OK;
 end:
@@ -747,36 +715,33 @@ end:
        return status;
 }
 
-struct lttng_rate_policy *lttng_rate_policy_copy(
-               const struct lttng_rate_policy *source)
+struct lttng_rate_policy *lttng_rate_policy_copy(const struct lttng_rate_policy *source)
 {
        LTTNG_ASSERT(source->copy);
        return source->copy(source);
 }
 
-static bool lttng_rate_policy_once_after_n_should_execute(
-               const struct lttng_rate_policy *policy, uint64_t counter)
+static bool lttng_rate_policy_once_after_n_should_execute(const struct lttng_rate_policy *policy,
+                                                         uint64_t counter)
 {
        const struct lttng_rate_policy_once_after_n *once_after_n_policy;
        bool execute = false;
        LTTNG_ASSERT(policy);
 
-       once_after_n_policy =
-                       rate_policy_once_after_n_from_rate_policy_const(policy);
+       once_after_n_policy = rate_policy_once_after_n_from_rate_policy_const(policy);
 
        execute = counter == once_after_n_policy->threshold;
 
-       DBG("Policy once after N = %" PRIu64
-           ": execution %s. Execution count: %" PRIu64,
-                       once_after_n_policy->threshold,
-                       execute ? "accepted" : "denied", counter);
+       DBG("Policy once after N = %" PRIu64 ": execution %s. Execution count: %" PRIu64,
+           once_after_n_policy->threshold,
+           execute ? "accepted" : "denied",
+           counter);
 
        return counter == once_after_n_policy->threshold;
 }
 
-enum lttng_error_code lttng_rate_policy_mi_serialize(
-               const struct lttng_rate_policy *rate_policy,
-               struct mi_writer *writer)
+enum lttng_error_code lttng_rate_policy_mi_serialize(const struct lttng_rate_policy *rate_policy,
+                                                    struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -786,8 +751,7 @@ enum lttng_error_code lttng_rate_policy_mi_serialize(
        LTTNG_ASSERT(rate_policy->mi_serialize);
 
        /* Open rate policy element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_rate_policy);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rate_policy);
        if (ret) {
                goto mi_error;
        }
index b25731484891788f64e34b804baf4882b25929b7..8997542e9358a91f074a821d5db3182af380b5e8 100644 (file)
@@ -8,6 +8,7 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
@@ -41,11 +42,10 @@ struct lttng_action_rotate_session_comm {
 } /* namespace */
 
 static const struct lttng_rate_policy *
-lttng_action_rotate_session_internal_get_rate_policy(
-               const struct lttng_action *action);
+lttng_action_rotate_session_internal_get_rate_policy(const struct lttng_action *action);
 
-static struct lttng_action_rotate_session *action_rotate_session_from_action(
-               struct lttng_action *action)
+static struct lttng_action_rotate_session *
+action_rotate_session_from_action(struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
@@ -74,7 +74,7 @@ static bool lttng_action_rotate_session_validate(struct lttng_action *action)
 
        /* A non-empty session name is mandatory. */
        if (!action_rotate_session->session_name ||
-                       strlen(action_rotate_session->session_name) == 0) {
+           strlen(action_rotate_session->session_name) == 0) {
                valid = false;
                goto end;
        }
@@ -84,8 +84,8 @@ end:
        return valid;
 }
 
-static bool lttng_action_rotate_session_is_equal(
-               const struct lttng_action *_a, const struct lttng_action *_b)
+static bool lttng_action_rotate_session_is_equal(const struct lttng_action *_a,
+                                                const struct lttng_action *_b)
 {
        bool is_equal = false;
        const struct lttng_action_rotate_session *a, *b;
@@ -96,7 +96,7 @@ static bool lttng_action_rotate_session_is_equal(
        /* Action is not valid if this is not true. */
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
@@ -104,8 +104,8 @@ static bool lttng_action_rotate_session_is_equal(
 end:
        return is_equal;
 }
-static int lttng_action_rotate_session_serialize(
-               struct lttng_action *action, struct lttng_payload *payload)
+static int lttng_action_rotate_session_serialize(struct lttng_action *action,
+                                                struct lttng_payload *payload)
 {
        struct lttng_action_rotate_session *action_rotate_session;
        struct lttng_action_rotate_session_comm comm;
@@ -120,27 +120,25 @@ static int lttng_action_rotate_session_serialize(
        LTTNG_ASSERT(action_rotate_session->session_name);
 
        DBG("Serializing rotate session action: session-name: %s",
-                       action_rotate_session->session_name);
+           action_rotate_session->session_name);
 
        session_name_len = strlen(action_rotate_session->session_name) + 1;
        comm.session_name_len = session_name_len;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       action_rotate_session->session_name, session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, action_rotate_session->session_name, session_name_len);
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_rate_policy_serialize(
-                       action_rotate_session->policy, payload);
+       ret = lttng_rate_policy_serialize(action_rotate_session->policy, payload);
        if (ret) {
                ret = -1;
                goto end;
@@ -167,16 +165,15 @@ end:
        return;
 }
 
-ssize_t lttng_action_rotate_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **p_action)
+ssize_t lttng_action_rotate_session_create_from_payload(struct lttng_payload_view *view,
+                                                       struct lttng_action **p_action)
 {
        ssize_t consumed_len, ret;
        const struct lttng_action_rotate_session_comm *comm;
        const char *session_name;
        struct lttng_action *action;
        enum lttng_action_status status;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
 
        action = lttng_action_rotate_session_create();
        if (!action) {
@@ -188,7 +185,7 @@ ssize_t lttng_action_rotate_session_create_from_payload(
        session_name = (const char *) &comm->data;
 
        if (!lttng_buffer_view_contains_string(
-                       &view->buffer, session_name, comm->session_name_len)) {
+                   &view->buffer, session_name, comm->session_name_len)) {
                consumed_len = -1;
                goto end;
        }
@@ -197,10 +194,8 @@ ssize_t lttng_action_rotate_session_create_from_payload(
        /* Rate policy. */
        {
                struct lttng_payload_view policy_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed_len, -1);
-               ret = lttng_rate_policy_create_from_payload(
-                               &policy_view, &policy);
+                       lttng_payload_view_from_view(view, consumed_len, -1);
+               ret = lttng_rate_policy_create_from_payload(&policy_view, &policy);
                if (ret < 0) {
                        consumed_len = -1;
                        goto end;
@@ -208,8 +203,7 @@ ssize_t lttng_action_rotate_session_create_from_payload(
                consumed_len += ret;
        }
 
-       status = lttng_action_rotate_session_set_session_name(
-                       action, session_name);
+       status = lttng_action_rotate_session_set_session_name(action, session_name);
        if (status != LTTNG_ACTION_STATUS_OK) {
                consumed_len = -1;
                goto end;
@@ -223,7 +217,7 @@ ssize_t lttng_action_rotate_session_create_from_payload(
        }
 
        *p_action = action;
-       action = NULL;
+       action = nullptr;
 
 end:
        lttng_rate_policy_destroy(policy);
@@ -232,37 +226,36 @@ end:
        return consumed_len;
 }
 
-static enum lttng_error_code lttng_action_rotate_session_mi_serialize(
-               const struct lttng_action *action, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_action_rotate_session_mi_serialize(const struct lttng_action *action,
+                                        struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_action_status status;
-       const char *session_name = NULL;
-       const struct lttng_rate_policy *policy = NULL;
+       const char *session_name = nullptr;
+       const struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(IS_ROTATE_SESSION_ACTION(action));
 
-       status = lttng_action_rotate_session_get_session_name(
-                       action, &session_name);
+       status = lttng_action_rotate_session_get_session_name(action, &session_name);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(session_name != NULL);
+       LTTNG_ASSERT(session_name != nullptr);
 
        status = lttng_action_notify_get_rate_policy(action, &policy);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(policy != NULL);
+       LTTNG_ASSERT(policy != nullptr);
 
        /* Open action rotate session element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_rotate_session);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_rotate_session);
        if (ret) {
                goto mi_error;
        }
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
@@ -290,8 +283,8 @@ end:
 
 struct lttng_action *lttng_action_rotate_session_create(void)
 {
-       struct lttng_action_rotate_session *action_rotate = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_action_rotate_session *action_rotate = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        enum lttng_action_status status;
 
        /* Create a every N = 1 rate policy. */
@@ -306,20 +299,19 @@ struct lttng_action *lttng_action_rotate_session_create(void)
        }
 
        lttng_action_init(&action_rotate->parent,
-                       LTTNG_ACTION_TYPE_ROTATE_SESSION,
-                       lttng_action_rotate_session_validate,
-                       lttng_action_rotate_session_serialize,
-                       lttng_action_rotate_session_is_equal,
-                       lttng_action_rotate_session_destroy,
-                       lttng_action_rotate_session_internal_get_rate_policy,
-                       lttng_action_generic_add_error_query_results,
-                       lttng_action_rotate_session_mi_serialize);
-
-       status = lttng_action_rotate_session_set_rate_policy(
-                       &action_rotate->parent, policy);
+                         LTTNG_ACTION_TYPE_ROTATE_SESSION,
+                         lttng_action_rotate_session_validate,
+                         lttng_action_rotate_session_serialize,
+                         lttng_action_rotate_session_is_equal,
+                         lttng_action_rotate_session_destroy,
+                         lttng_action_rotate_session_internal_get_rate_policy,
+                         lttng_action_generic_add_error_query_results,
+                         lttng_action_rotate_session_mi_serialize);
+
+       status = lttng_action_rotate_session_set_rate_policy(&action_rotate->parent, policy);
        if (status != LTTNG_ACTION_STATUS_OK) {
                lttng_action_destroy(&action_rotate->parent);
-               action_rotate = NULL;
+               action_rotate = nullptr;
                goto end;
        }
 
@@ -328,14 +320,14 @@ end:
        return action_rotate ? &action_rotate->parent : nullptr;
 }
 
-enum lttng_action_status lttng_action_rotate_session_set_session_name(
-               struct lttng_action *action, const char *session_name)
+enum lttng_action_status lttng_action_rotate_session_set_session_name(struct lttng_action *action,
+                                                                     const char *session_name)
 {
        struct lttng_action_rotate_session *action_rotate_session;
        enum lttng_action_status status;
 
        if (!action || !IS_ROTATE_SESSION_ACTION(action) || !session_name ||
-                       strlen(session_name) == 0) {
+           strlen(session_name) == 0) {
                status = LTTNG_ACTION_STATUS_INVALID;
                goto end;
        }
@@ -355,8 +347,9 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_rotate_session_get_session_name(
-               const struct lttng_action *action, const char **session_name)
+enum lttng_action_status
+lttng_action_rotate_session_get_session_name(const struct lttng_action *action,
+                                            const char **session_name)
 {
        const struct lttng_action_rotate_session *action_rotate_session;
        enum lttng_action_status status;
@@ -375,13 +368,13 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_rotate_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy)
+enum lttng_action_status
+lttng_action_rotate_session_set_rate_policy(struct lttng_action *action,
+                                           const struct lttng_rate_policy *policy)
 {
        enum lttng_action_status status;
        struct lttng_action_rotate_session *rotate_session_action;
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
 
        if (!action || !policy || !IS_ROTATE_SESSION_ACTION(action)) {
                status = LTTNG_ACTION_STATUS_INVALID;
@@ -402,16 +395,16 @@ enum lttng_action_status lttng_action_rotate_session_set_rate_policy(
        /* Assign the policy. */
        rotate_session_action->policy = copy;
        status = LTTNG_ACTION_STATUS_OK;
-       copy = NULL;
+       copy = nullptr;
 
 end:
        lttng_rate_policy_destroy(copy);
        return status;
 }
 
-enum lttng_action_status lttng_action_rotate_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy)
+enum lttng_action_status
+lttng_action_rotate_session_get_rate_policy(const struct lttng_action *action,
+                                           const struct lttng_rate_policy **policy)
 {
        enum lttng_action_status status;
        const struct lttng_action_rotate_session *rotate_session_action;
@@ -430,8 +423,7 @@ end:
 }
 
 static const struct lttng_rate_policy *
-lttng_action_rotate_session_internal_get_rate_policy(
-               const struct lttng_action *action)
+lttng_action_rotate_session_internal_get_rate_policy(const struct lttng_action *action)
 {
        const struct lttng_action_rotate_session *_action;
        _action = action_rotate_session_from_action_const(action);
index 6af260c93e35a3e7cb2659429cd0a6f0f849bf53..015a834ddfe52e468fe1ea359e3129fa8b946b12 100644 (file)
@@ -11,7 +11,7 @@
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
 #include <common/snapshot.hpp>
-#include <inttypes.h>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
@@ -20,6 +20,8 @@
 #include <lttng/snapshot-internal.hpp>
 #include <lttng/snapshot.h>
 
+#include <inttypes.h>
+
 #define IS_SNAPSHOT_SESSION_ACTION(action) \
        (lttng_action_get_type(action) == LTTNG_ACTION_TYPE_SNAPSHOT_SESSION)
 
@@ -58,16 +60,14 @@ struct lttng_action_snapshot_session_comm {
 } /* namespace */
 
 static const struct lttng_rate_policy *
-lttng_action_snapshot_session_internal_get_rate_policy(
-               const struct lttng_action *action);
+lttng_action_snapshot_session_internal_get_rate_policy(const struct lttng_action *action);
 
 static struct lttng_action_snapshot_session *
 action_snapshot_session_from_action(struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
-       return lttng::utils::container_of(
-                       action, &lttng_action_snapshot_session::parent);
+       return lttng::utils::container_of(action, &lttng_action_snapshot_session::parent);
 }
 
 static const struct lttng_action_snapshot_session *
@@ -75,8 +75,7 @@ action_snapshot_session_from_action_const(const struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
-       return lttng::utils::container_of(
-                       action, &lttng_action_snapshot_session::parent);
+       return lttng::utils::container_of(action, &lttng_action_snapshot_session::parent);
 }
 
 static bool lttng_action_snapshot_session_validate(struct lttng_action *action)
@@ -92,12 +91,12 @@ static bool lttng_action_snapshot_session_validate(struct lttng_action *action)
 
        /* A non-empty session name is mandatory. */
        if (!action_snapshot_session->session_name ||
-                       strlen(action_snapshot_session->session_name) == 0) {
+           strlen(action_snapshot_session->session_name) == 0) {
                goto end;
        }
 
        if (action_snapshot_session->output &&
-                       !lttng_snapshot_output_validate(action_snapshot_session->output)) {
+           !lttng_snapshot_output_validate(action_snapshot_session->output)) {
                goto end;
        }
 
@@ -106,8 +105,8 @@ end:
        return valid;
 }
 
-static bool lttng_action_snapshot_session_is_equal(
-               const struct lttng_action *_a, const struct lttng_action *_b)
+static bool lttng_action_snapshot_session_is_equal(const struct lttng_action *_a,
+                                                  const struct lttng_action *_b)
 {
        bool is_equal = false;
        const struct lttng_action_snapshot_session *a, *b;
@@ -118,12 +117,11 @@ static bool lttng_action_snapshot_session_is_equal(
        /* Action is not valid if this is not true. */
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
-       if (a->output && b->output &&
-                       !lttng_snapshot_output_is_equal(a->output, b->output)) {
+       if (a->output && b->output && !lttng_snapshot_output_is_equal(a->output, b->output)) {
                goto end;
        } else if (!!a->output != !!b->output) {
                goto end;
@@ -139,8 +137,8 @@ static size_t serialize_strlen(const char *str)
        return str ? strlen(str) + 1 : 0;
 }
 
-static int lttng_action_snapshot_session_serialize(
-               struct lttng_action *action, struct lttng_payload *payload)
+static int lttng_action_snapshot_session_serialize(struct lttng_action *action,
+                                                  struct lttng_payload *payload)
 {
        struct lttng_action_snapshot_session *action_snapshot_session;
        struct lttng_action_snapshot_session_comm comm = {};
@@ -153,24 +151,21 @@ static int lttng_action_snapshot_session_serialize(
        size_before_comm = payload->buffer.size;
 
        action_snapshot_session = action_snapshot_session_from_action(action);
-       comm.session_name_len =
-               serialize_strlen(action_snapshot_session->session_name);
+       comm.session_name_len = serialize_strlen(action_snapshot_session->session_name);
 
        /* Add header. */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                goto end;
        }
 
        LTTNG_ASSERT(action_snapshot_session->session_name);
        DBG("Serializing snapshot session action: session-name: %s",
-                       action_snapshot_session->session_name);
+           action_snapshot_session->session_name);
 
        /* Add session name. */
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       action_snapshot_session->session_name,
-                       comm.session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, action_snapshot_session->session_name, comm.session_name_len);
        if (ret) {
                goto end;
        }
@@ -180,18 +175,15 @@ static int lttng_action_snapshot_session_serialize(
                const size_t size_before_output = payload->buffer.size;
                struct lttng_action_snapshot_session_comm *comm_in_payload;
 
-               ret = lttng_snapshot_output_serialize(
-                               action_snapshot_session->output,
-                               payload);
+               ret = lttng_snapshot_output_serialize(action_snapshot_session->output, payload);
                if (ret) {
                        goto end;
                }
 
-               comm_in_payload = (typeof(comm_in_payload))(
-                               payload->buffer.data + size_before_comm);
+               comm_in_payload =
+                       (typeof(comm_in_payload)) (payload->buffer.data + size_before_comm);
                /* Adjust action length in header. */
-               comm_in_payload->snapshot_output_len =
-                               payload->buffer.size - size_before_output;
+               comm_in_payload->snapshot_output_len = payload->buffer.size - size_before_output;
        }
 
        /* Serialize the rate policy. */
@@ -199,18 +191,16 @@ static int lttng_action_snapshot_session_serialize(
                const size_t size_before_output = payload->buffer.size;
                struct lttng_action_snapshot_session_comm *comm_in_payload;
 
-               ret = lttng_rate_policy_serialize(
-                               action_snapshot_session->policy, payload);
+               ret = lttng_rate_policy_serialize(action_snapshot_session->policy, payload);
                if (ret) {
                        ret = -1;
                        goto end;
                }
 
-               comm_in_payload = (typeof(comm_in_payload))(
-                               payload->buffer.data + size_before_comm);
+               comm_in_payload =
+                       (typeof(comm_in_payload)) (payload->buffer.data + size_before_comm);
                /* Adjust rate policy length in header. */
-               comm_in_payload->rate_policy_len =
-                               payload->buffer.size - size_before_output;
+               comm_in_payload->rate_policy_len = payload->buffer.size - size_before_output;
        }
 
 end:
@@ -236,20 +226,18 @@ end:
        return;
 }
 
-ssize_t lttng_action_snapshot_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **p_action)
+ssize_t lttng_action_snapshot_session_create_from_payload(struct lttng_payload_view *view,
+                                                         struct lttng_action **p_action)
 {
        ssize_t consumed_len;
        const char *variable_data;
        struct lttng_action *action;
        enum lttng_action_status status;
-       struct lttng_snapshot_output *snapshot_output = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_snapshot_output *snapshot_output = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        const struct lttng_action_snapshot_session_comm *comm;
        const struct lttng_payload_view snapshot_session_comm_view =
-                       lttng_payload_view_from_view(
-                               view, 0, sizeof(*comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*comm));
 
        action = lttng_action_snapshot_session_create();
        if (!action) {
@@ -267,12 +255,11 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
        consumed_len = sizeof(struct lttng_action_snapshot_session_comm);
 
        if (!lttng_buffer_view_contains_string(
-                       &view->buffer, variable_data, comm->session_name_len)) {
+                   &view->buffer, variable_data, comm->session_name_len)) {
                goto error;
        }
 
-       status = lttng_action_snapshot_session_set_session_name(
-                       action, variable_data);
+       status = lttng_action_snapshot_session_set_session_name(action, variable_data);
        if (status != LTTNG_ACTION_STATUS_OK) {
                goto error;
        }
@@ -285,34 +272,30 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
                ssize_t snapshot_output_consumed_len;
                enum lttng_action_status action_status;
                struct lttng_payload_view snapshot_output_buffer_view =
-                       lttng_payload_view_from_view(view, consumed_len,
-                               comm->snapshot_output_len);
+                       lttng_payload_view_from_view(view, consumed_len, comm->snapshot_output_len);
 
                if (!lttng_payload_view_is_valid(&snapshot_output_buffer_view)) {
                        ERR("Failed to create buffer view for snapshot output.");
                        goto error;
                }
 
-               snapshot_output_consumed_len =
-                               lttng_snapshot_output_create_from_payload(
-                                               &snapshot_output_buffer_view,
-                                               &snapshot_output);
+               snapshot_output_consumed_len = lttng_snapshot_output_create_from_payload(
+                       &snapshot_output_buffer_view, &snapshot_output);
                if (snapshot_output_consumed_len != comm->snapshot_output_len) {
                        ERR("Failed to deserialize snapshot output object: "
-                                       "consumed-len: %zd, expected-len: %" PRIu32,
-                                       snapshot_output_consumed_len,
-                                       comm->snapshot_output_len);
+                           "consumed-len: %zd, expected-len: %" PRIu32,
+                           snapshot_output_consumed_len,
+                           comm->snapshot_output_len);
                        goto error;
                }
 
-               action_status = lttng_action_snapshot_session_set_output(
-                       action, snapshot_output);
+               action_status = lttng_action_snapshot_session_set_output(action, snapshot_output);
                if (action_status != LTTNG_ACTION_STATUS_OK) {
                        goto error;
                }
 
                /* Ownership has been transferred to the action. */
-               snapshot_output = NULL;
+               snapshot_output = nullptr;
        }
 
        variable_data += comm->snapshot_output_len;
@@ -326,8 +309,7 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
        {
                ssize_t rate_policy_consumed_len;
                struct lttng_payload_view policy_view =
-                               lttng_payload_view_from_view(view, consumed_len,
-                                               comm->rate_policy_len);
+                       lttng_payload_view_from_view(view, consumed_len, comm->rate_policy_len);
 
                if (!lttng_payload_view_is_valid(&policy_view)) {
                        ERR("Failed to create buffer view for rate policy.");
@@ -335,8 +317,7 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
                }
 
                rate_policy_consumed_len =
-                               lttng_rate_policy_create_from_payload(
-                                               &policy_view, &policy);
+                       lttng_rate_policy_create_from_payload(&policy_view, &policy);
                if (rate_policy_consumed_len < 0) {
                        goto error;
                }
@@ -344,13 +325,12 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
                if (rate_policy_consumed_len != comm->rate_policy_len) {
                        ERR("Failed to deserialize rate policy object: "
                            "consumed-len: %zd, expected-len: %" PRIu32,
-                                       rate_policy_consumed_len,
-                                       comm->rate_policy_len);
+                           rate_policy_consumed_len,
+                           comm->rate_policy_len);
                        goto error;
                }
 
-               status = lttng_action_snapshot_session_set_rate_policy(
-                               action, policy);
+               status = lttng_action_snapshot_session_set_rate_policy(action, policy);
                if (status != LTTNG_ACTION_STATUS_OK) {
                        goto error;
                }
@@ -360,7 +340,7 @@ ssize_t lttng_action_snapshot_session_create_from_payload(
        consumed_len += comm->rate_policy_len;
 
        *p_action = action;
-       action = NULL;
+       action = nullptr;
 
        goto end;
 
@@ -375,38 +355,37 @@ end:
        return consumed_len;
 }
 
-static enum lttng_error_code lttng_action_snapshot_session_mi_serialize(
-               const struct lttng_action *action, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_action_snapshot_session_mi_serialize(const struct lttng_action *action,
+                                          struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_action_status status;
-       const char *session_name = NULL;
-       const struct lttng_snapshot_output *output = NULL;
-       const struct lttng_rate_policy *policy = NULL;
+       const char *session_name = nullptr;
+       const struct lttng_snapshot_output *output = nullptr;
+       const struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(IS_SNAPSHOT_SESSION_ACTION(action));
 
-       status = lttng_action_snapshot_session_get_session_name(
-                       action, &session_name);
+       status = lttng_action_snapshot_session_get_session_name(action, &session_name);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(session_name != NULL);
+       LTTNG_ASSERT(session_name != nullptr);
 
        status = lttng_action_snapshot_session_get_rate_policy(action, &policy);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(policy != NULL);
+       LTTNG_ASSERT(policy != nullptr);
 
        /* Open action snapshot session element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_snapshot_session);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_snapshot_session);
        if (ret) {
                goto mi_error;
        }
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
@@ -414,7 +393,7 @@ static enum lttng_error_code lttng_action_snapshot_session_mi_serialize(
        /* Output if any. */
        status = lttng_action_snapshot_session_get_output(action, &output);
        if (status == LTTNG_ACTION_STATUS_OK) {
-               LTTNG_ASSERT(output != NULL);
+               LTTNG_ASSERT(output != nullptr);
                ret_code = lttng_snapshot_output_mi_serialize(output, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
@@ -447,8 +426,8 @@ end:
 
 struct lttng_action *lttng_action_snapshot_session_create(void)
 {
-       struct lttng_action_snapshot_session *action_snapshot = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_action_snapshot_session *action_snapshot = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        enum lttng_action_status status;
 
        /* Create a every N = 1 rate policy. */
@@ -463,20 +442,19 @@ struct lttng_action *lttng_action_snapshot_session_create(void)
        }
 
        lttng_action_init(&action_snapshot->parent,
-                       LTTNG_ACTION_TYPE_SNAPSHOT_SESSION,
-                       lttng_action_snapshot_session_validate,
-                       lttng_action_snapshot_session_serialize,
-                       lttng_action_snapshot_session_is_equal,
-                       lttng_action_snapshot_session_destroy,
-                       lttng_action_snapshot_session_internal_get_rate_policy,
-                       lttng_action_generic_add_error_query_results,
-                       lttng_action_snapshot_session_mi_serialize);
-
-       status = lttng_action_snapshot_session_set_rate_policy(
-                       &action_snapshot->parent, policy);
+                         LTTNG_ACTION_TYPE_SNAPSHOT_SESSION,
+                         lttng_action_snapshot_session_validate,
+                         lttng_action_snapshot_session_serialize,
+                         lttng_action_snapshot_session_is_equal,
+                         lttng_action_snapshot_session_destroy,
+                         lttng_action_snapshot_session_internal_get_rate_policy,
+                         lttng_action_generic_add_error_query_results,
+                         lttng_action_snapshot_session_mi_serialize);
+
+       status = lttng_action_snapshot_session_set_rate_policy(&action_snapshot->parent, policy);
        if (status != LTTNG_ACTION_STATUS_OK) {
                lttng_action_destroy(&action_snapshot->parent);
-               action_snapshot = NULL;
+               action_snapshot = nullptr;
                goto end;
        }
 
@@ -485,14 +463,14 @@ end:
        return action_snapshot ? &action_snapshot->parent : nullptr;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_set_session_name(
-               struct lttng_action *action, const char *session_name)
+enum lttng_action_status lttng_action_snapshot_session_set_session_name(struct lttng_action *action,
+                                                                       const char *session_name)
 {
        struct lttng_action_snapshot_session *action_snapshot_session;
        enum lttng_action_status status;
 
        if (!action || !IS_SNAPSHOT_SESSION_ACTION(action) || !session_name ||
-                       strlen(session_name) == 0) {
+           strlen(session_name) == 0) {
                status = LTTNG_ACTION_STATUS_INVALID;
                goto end;
        }
@@ -512,8 +490,9 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_get_session_name(
-               const struct lttng_action *action, const char **session_name)
+enum lttng_action_status
+lttng_action_snapshot_session_get_session_name(const struct lttng_action *action,
+                                              const char **session_name)
 {
        const struct lttng_action_snapshot_session *action_snapshot_session;
        enum lttng_action_status status;
@@ -537,9 +516,9 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_set_output(
-               struct lttng_action *action,
-               struct lttng_snapshot_output *output)
+enum lttng_action_status
+lttng_action_snapshot_session_set_output(struct lttng_action *action,
+                                        struct lttng_snapshot_output *output)
 {
        struct lttng_action_snapshot_session *action_snapshot_session;
        enum lttng_action_status status;
@@ -560,14 +539,14 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_get_output(
-               const struct lttng_action *action,
-               const struct lttng_snapshot_output **output)
+enum lttng_action_status
+lttng_action_snapshot_session_get_output(const struct lttng_action *action,
+                                        const struct lttng_snapshot_output **output)
 {
        const struct lttng_action_snapshot_session *action_snapshot_session;
        enum lttng_action_status status;
 
-       if (!action || !IS_SNAPSHOT_SESSION_ACTION(action)|| !output) {
+       if (!action || !IS_SNAPSHOT_SESSION_ACTION(action) || !output) {
                status = LTTNG_ACTION_STATUS_INVALID;
                goto end;
        }
@@ -585,13 +564,13 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy)
+enum lttng_action_status
+lttng_action_snapshot_session_set_rate_policy(struct lttng_action *action,
+                                             const struct lttng_rate_policy *policy)
 {
        enum lttng_action_status status;
        struct lttng_action_snapshot_session *snapshot_session_action;
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
 
        if (!action || !policy || !IS_SNAPSHOT_SESSION_ACTION(action)) {
                status = LTTNG_ACTION_STATUS_INVALID;
@@ -612,16 +591,16 @@ enum lttng_action_status lttng_action_snapshot_session_set_rate_policy(
        /* Assign the policy. */
        snapshot_session_action->policy = copy;
        status = LTTNG_ACTION_STATUS_OK;
-       copy = NULL;
+       copy = nullptr;
 
 end:
        lttng_rate_policy_destroy(copy);
        return status;
 }
 
-enum lttng_action_status lttng_action_snapshot_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy)
+enum lttng_action_status
+lttng_action_snapshot_session_get_rate_policy(const struct lttng_action *action,
+                                             const struct lttng_rate_policy **policy)
 {
        enum lttng_action_status status;
        const struct lttng_action_snapshot_session *snapshot_session_action;
@@ -631,8 +610,7 @@ enum lttng_action_status lttng_action_snapshot_session_get_rate_policy(
                goto end;
        }
 
-       snapshot_session_action =
-                       action_snapshot_session_from_action_const(action);
+       snapshot_session_action = action_snapshot_session_from_action_const(action);
 
        *policy = snapshot_session_action->policy;
        status = LTTNG_ACTION_STATUS_OK;
@@ -641,8 +619,7 @@ end:
 }
 
 static const struct lttng_rate_policy *
-lttng_action_snapshot_session_internal_get_rate_policy(
-               const struct lttng_action *action)
+lttng_action_snapshot_session_internal_get_rate_policy(const struct lttng_action *action)
 {
        const struct lttng_action_snapshot_session *_action;
        _action = action_snapshot_session_from_action_const(action);
index 2c9f799727e43ad454ab32610c16fe14000b68a6..1004290fe9a94020b84934070637e9e3b9484233 100644 (file)
@@ -8,6 +8,7 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
@@ -41,11 +42,10 @@ struct lttng_action_start_session_comm {
 } /* namespace */
 
 static const struct lttng_rate_policy *
-lttng_action_start_session_internal_get_rate_policy(
-               const struct lttng_action *action);
+lttng_action_start_session_internal_get_rate_policy(const struct lttng_action *action);
 
-static struct lttng_action_start_session *action_start_session_from_action(
-               struct lttng_action *action)
+static struct lttng_action_start_session *
+action_start_session_from_action(struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
@@ -74,7 +74,7 @@ static bool lttng_action_start_session_validate(struct lttng_action *action)
 
        /* A non-empty session name is mandatory. */
        if (!action_start_session->session_name ||
-                       strlen(action_start_session->session_name) == 0) {
+           strlen(action_start_session->session_name) == 0) {
                valid = false;
                goto end;
        }
@@ -84,8 +84,8 @@ end:
        return valid;
 }
 
-static bool lttng_action_start_session_is_equal(
-               const struct lttng_action *_a, const struct lttng_action *_b)
+static bool lttng_action_start_session_is_equal(const struct lttng_action *_a,
+                                               const struct lttng_action *_b)
 {
        bool is_equal = false;
        struct lttng_action_start_session *a, *b;
@@ -96,7 +96,7 @@ static bool lttng_action_start_session_is_equal(
        /* Action is not valid if this is not true. */
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
@@ -105,8 +105,8 @@ end:
        return is_equal;
 }
 
-static int lttng_action_start_session_serialize(
-               struct lttng_action *action, struct lttng_payload *payload)
+static int lttng_action_start_session_serialize(struct lttng_action *action,
+                                               struct lttng_payload *payload)
 {
        struct lttng_action_start_session *action_start_session;
        struct lttng_action_start_session_comm comm;
@@ -121,7 +121,7 @@ static int lttng_action_start_session_serialize(
        LTTNG_ASSERT(action_start_session->session_name);
 
        DBG("Serializing start session action: session-name: %s",
-                       action_start_session->session_name);
+           action_start_session->session_name);
 
        session_name_len = strlen(action_start_session->session_name) + 1;
        comm.session_name_len = session_name_len;
@@ -132,15 +132,14 @@ static int lttng_action_start_session_serialize(
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       action_start_session->session_name, session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, action_start_session->session_name, session_name_len);
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_rate_policy_serialize(
-                       action_start_session->policy, payload);
+       ret = lttng_rate_policy_serialize(action_start_session->policy, payload);
        if (ret) {
                ret = -1;
                goto end;
@@ -169,23 +168,22 @@ end:
        return;
 }
 
-ssize_t lttng_action_start_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **p_action)
+ssize_t lttng_action_start_session_create_from_payload(struct lttng_payload_view *view,
+                                                      struct lttng_action **p_action)
 {
        ssize_t consumed_len, ret;
        const struct lttng_action_start_session_comm *comm;
        const char *session_name;
-       struct lttng_action *action = NULL;
+       struct lttng_action *action = nullptr;
        enum lttng_action_status status;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
 
        comm = (typeof(comm)) view->buffer.data;
        session_name = (const char *) &comm->data;
 
        /* Session name */
-       if (!lttng_buffer_view_contains_string(&view->buffer, session_name,
-                           comm->session_name_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, session_name, comm->session_name_len)) {
                consumed_len = -1;
                goto end;
        }
@@ -194,10 +192,8 @@ ssize_t lttng_action_start_session_create_from_payload(
        /* Rate policy. */
        {
                struct lttng_payload_view policy_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed_len, -1);
-               ret = lttng_rate_policy_create_from_payload(
-                               &policy_view, &policy);
+                       lttng_payload_view_from_view(view, consumed_len, -1);
+               ret = lttng_rate_policy_create_from_payload(&policy_view, &policy);
                if (ret < 0) {
                        consumed_len = -1;
                        goto end;
@@ -211,8 +207,7 @@ ssize_t lttng_action_start_session_create_from_payload(
                goto end;
        }
 
-       status = lttng_action_start_session_set_session_name(
-                       action, session_name);
+       status = lttng_action_start_session_set_session_name(action, session_name);
        if (status != LTTNG_ACTION_STATUS_OK) {
                consumed_len = -1;
                goto end;
@@ -226,7 +221,7 @@ ssize_t lttng_action_start_session_create_from_payload(
        }
 
        *p_action = action;
-       action = NULL;
+       action = nullptr;
 
 end:
        lttng_rate_policy_destroy(policy);
@@ -235,37 +230,35 @@ end:
        return consumed_len;
 }
 
-static enum lttng_error_code lttng_action_start_session_mi_serialize(
-               const struct lttng_action *action, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_action_start_session_mi_serialize(const struct lttng_action *action, struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_action_status status;
-       const char *session_name = NULL;
-       const struct lttng_rate_policy *policy = NULL;
+       const char *session_name = nullptr;
+       const struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(IS_START_SESSION_ACTION(action));
 
-       status = lttng_action_start_session_get_session_name(
-                       action, &session_name);
+       status = lttng_action_start_session_get_session_name(action, &session_name);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(session_name != NULL);
+       LTTNG_ASSERT(session_name != nullptr);
 
        status = lttng_action_start_session_get_rate_policy(action, &policy);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(policy != NULL);
+       LTTNG_ASSERT(policy != nullptr);
 
        /* Open action start session element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_start_session);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_start_session);
        if (ret) {
                goto mi_error;
        }
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
@@ -293,8 +286,8 @@ end:
 
 struct lttng_action *lttng_action_start_session_create(void)
 {
-       struct lttng_action_start_session *action_start = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_action_start_session *action_start = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        enum lttng_action_status status;
 
        /* Create a every N = 1 rate policy. */
@@ -309,20 +302,19 @@ struct lttng_action *lttng_action_start_session_create(void)
        }
 
        lttng_action_init(&action_start->parent,
-                       LTTNG_ACTION_TYPE_START_SESSION,
-                       lttng_action_start_session_validate,
-                       lttng_action_start_session_serialize,
-                       lttng_action_start_session_is_equal,
-                       lttng_action_start_session_destroy,
-                       lttng_action_start_session_internal_get_rate_policy,
-                       lttng_action_generic_add_error_query_results,
-                       lttng_action_start_session_mi_serialize);
-
-       status = lttng_action_start_session_set_rate_policy(
-                       &action_start->parent, policy);
+                         LTTNG_ACTION_TYPE_START_SESSION,
+                         lttng_action_start_session_validate,
+                         lttng_action_start_session_serialize,
+                         lttng_action_start_session_is_equal,
+                         lttng_action_start_session_destroy,
+                         lttng_action_start_session_internal_get_rate_policy,
+                         lttng_action_generic_add_error_query_results,
+                         lttng_action_start_session_mi_serialize);
+
+       status = lttng_action_start_session_set_rate_policy(&action_start->parent, policy);
        if (status != LTTNG_ACTION_STATUS_OK) {
                lttng_action_destroy(&action_start->parent);
-               action_start = NULL;
+               action_start = nullptr;
                goto end;
        }
 
@@ -331,14 +323,14 @@ end:
        return &action_start->parent;
 }
 
-enum lttng_action_status lttng_action_start_session_set_session_name(
-               struct lttng_action *action, const char *session_name)
+enum lttng_action_status lttng_action_start_session_set_session_name(struct lttng_action *action,
+                                                                    const char *session_name)
 {
        struct lttng_action_start_session *action_start_session;
        enum lttng_action_status status;
 
        if (!action || !IS_START_SESSION_ACTION(action) || !session_name ||
-                       strlen(session_name) == 0) {
+           strlen(session_name) == 0) {
                status = LTTNG_ACTION_STATUS_INVALID;
                goto end;
        }
@@ -358,8 +350,9 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_start_session_get_session_name(
-               const struct lttng_action *action, const char **session_name)
+enum lttng_action_status
+lttng_action_start_session_get_session_name(const struct lttng_action *action,
+                                           const char **session_name)
 {
        const struct lttng_action_start_session *action_start_session;
        enum lttng_action_status status;
@@ -378,13 +371,13 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_start_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy)
+enum lttng_action_status
+lttng_action_start_session_set_rate_policy(struct lttng_action *action,
+                                          const struct lttng_rate_policy *policy)
 {
        enum lttng_action_status status;
        struct lttng_action_start_session *start_session_action;
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
 
        if (!action || !policy || !IS_START_SESSION_ACTION(action)) {
                status = LTTNG_ACTION_STATUS_INVALID;
@@ -405,16 +398,16 @@ enum lttng_action_status lttng_action_start_session_set_rate_policy(
        /* Assign the policy. */
        start_session_action->policy = copy;
        status = LTTNG_ACTION_STATUS_OK;
-       copy = NULL;
+       copy = nullptr;
 
 end:
        lttng_rate_policy_destroy(copy);
        return status;
 }
 
-enum lttng_action_status lttng_action_start_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy)
+enum lttng_action_status
+lttng_action_start_session_get_rate_policy(const struct lttng_action *action,
+                                          const struct lttng_rate_policy **policy)
 {
        enum lttng_action_status status;
        const struct lttng_action_start_session *start_session_action;
@@ -433,8 +426,7 @@ end:
 }
 
 static const struct lttng_rate_policy *
-lttng_action_start_session_internal_get_rate_policy(
-               const struct lttng_action *action)
+lttng_action_start_session_internal_get_rate_policy(const struct lttng_action *action)
 {
        const struct lttng_action_start_session *_action;
        _action = action_start_session_from_action_const(action);
index 08a6665dd0c196b63dbe3ee255f8037cf872027c..be8fd0aaec92cf489eb0b5109f4b8f3178dcd259 100644 (file)
@@ -8,6 +8,7 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
@@ -41,11 +42,10 @@ struct lttng_action_stop_session_comm {
 } /* namespace */
 
 static const struct lttng_rate_policy *
-lttng_action_stop_session_internal_get_rate_policy(
-               const struct lttng_action *action);
+lttng_action_stop_session_internal_get_rate_policy(const struct lttng_action *action);
 
-static struct lttng_action_stop_session *action_stop_session_from_action(
-               struct lttng_action *action)
+static struct lttng_action_stop_session *
+action_stop_session_from_action(struct lttng_action *action)
 {
        LTTNG_ASSERT(action);
 
@@ -73,8 +73,7 @@ static bool lttng_action_stop_session_validate(struct lttng_action *action)
        action_stop_session = action_stop_session_from_action(action);
 
        /* A non-empty session name is mandatory. */
-       if (!action_stop_session->session_name ||
-                       strlen(action_stop_session->session_name) == 0) {
+       if (!action_stop_session->session_name || strlen(action_stop_session->session_name) == 0) {
                valid = false;
                goto end;
        }
@@ -84,8 +83,8 @@ end:
        return valid;
 }
 
-static bool lttng_action_stop_session_is_equal(
-               const struct lttng_action *_a, const struct lttng_action *_b)
+static bool lttng_action_stop_session_is_equal(const struct lttng_action *_a,
+                                              const struct lttng_action *_b)
 {
        bool is_equal = false;
        const struct lttng_action_stop_session *a, *b;
@@ -96,7 +95,7 @@ static bool lttng_action_stop_session_is_equal(
        /* Action is not valid if this is not true. */
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
@@ -105,8 +104,8 @@ end:
        return is_equal;
 }
 
-static int lttng_action_stop_session_serialize(
-               struct lttng_action *action, struct lttng_payload *payload)
+static int lttng_action_stop_session_serialize(struct lttng_action *action,
+                                              struct lttng_payload *payload)
 {
        struct lttng_action_stop_session *action_stop_session;
        struct lttng_action_stop_session_comm comm;
@@ -120,21 +119,19 @@ static int lttng_action_stop_session_serialize(
 
        LTTNG_ASSERT(action_stop_session->session_name);
 
-       DBG("Serializing stop session action: session-name: %s",
-                       action_stop_session->session_name);
+       DBG("Serializing stop session action: session-name: %s", action_stop_session->session_name);
 
        session_name_len = strlen(action_stop_session->session_name) + 1;
        comm.session_name_len = session_name_len;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       action_stop_session->session_name, session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, action_stop_session->session_name, session_name_len);
        if (ret) {
                ret = -1;
                goto end;
@@ -169,23 +166,22 @@ end:
        return;
 }
 
-ssize_t lttng_action_stop_session_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_action **p_action)
+ssize_t lttng_action_stop_session_create_from_payload(struct lttng_payload_view *view,
+                                                     struct lttng_action **p_action)
 {
        ssize_t consumed_len, ret;
        const struct lttng_action_stop_session_comm *comm;
        const char *session_name;
-       struct lttng_action *action = NULL;
+       struct lttng_action *action = nullptr;
        enum lttng_action_status status;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_rate_policy *policy = nullptr;
 
        comm = (typeof(comm)) view->buffer.data;
        session_name = (const char *) &comm->data;
 
        /* Session name. */
        if (!lttng_buffer_view_contains_string(
-                       &view->buffer, session_name, comm->session_name_len)) {
+                   &view->buffer, session_name, comm->session_name_len)) {
                consumed_len = -1;
                goto end;
        }
@@ -194,10 +190,8 @@ ssize_t lttng_action_stop_session_create_from_payload(
        /* Rate policy. */
        {
                struct lttng_payload_view policy_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed_len, -1);
-               ret = lttng_rate_policy_create_from_payload(
-                               &policy_view, &policy);
+                       lttng_payload_view_from_view(view, consumed_len, -1);
+               ret = lttng_rate_policy_create_from_payload(&policy_view, &policy);
                if (ret < 0) {
                        consumed_len = -1;
                        goto end;
@@ -211,8 +205,7 @@ ssize_t lttng_action_stop_session_create_from_payload(
                goto end;
        }
 
-       status = lttng_action_stop_session_set_session_name(
-                       action, session_name);
+       status = lttng_action_stop_session_set_session_name(action, session_name);
        if (status != LTTNG_ACTION_STATUS_OK) {
                consumed_len = -1;
                goto end;
@@ -226,7 +219,7 @@ ssize_t lttng_action_stop_session_create_from_payload(
        }
 
        *p_action = action;
-       action = NULL;
+       action = nullptr;
 
 end:
        lttng_rate_policy_destroy(policy);
@@ -235,37 +228,35 @@ end:
        return consumed_len;
 }
 
-static enum lttng_error_code lttng_action_stop_session_mi_serialize(
-               const struct lttng_action *action, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_action_stop_session_mi_serialize(const struct lttng_action *action, struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_action_status status;
-       const char *session_name = NULL;
-       const struct lttng_rate_policy *policy = NULL;
+       const char *session_name = nullptr;
+       const struct lttng_rate_policy *policy = nullptr;
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(IS_STOP_SESSION_ACTION(action));
 
-       status = lttng_action_stop_session_get_session_name(
-                       action, &session_name);
+       status = lttng_action_stop_session_get_session_name(action, &session_name);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(session_name != NULL);
+       LTTNG_ASSERT(session_name != nullptr);
 
        status = lttng_action_stop_session_get_rate_policy(action, &policy);
        LTTNG_ASSERT(status == LTTNG_ACTION_STATUS_OK);
-       LTTNG_ASSERT(policy != NULL);
+       LTTNG_ASSERT(policy != nullptr);
 
        /* Open action stop session. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_action_start_session);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_start_session);
        if (ret) {
                goto mi_error;
        }
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
@@ -293,8 +284,8 @@ end:
 
 struct lttng_action *lttng_action_stop_session_create(void)
 {
-       struct lttng_action_stop_session *action_stop = NULL;
-       struct lttng_rate_policy *policy = NULL;
+       struct lttng_action_stop_session *action_stop = nullptr;
+       struct lttng_rate_policy *policy = nullptr;
        enum lttng_action_status status;
 
        /* Create a every N = 1 rate policy. */
@@ -308,20 +299,20 @@ struct lttng_action *lttng_action_stop_session_create(void)
                goto end;
        }
 
-       lttng_action_init(&action_stop->parent, LTTNG_ACTION_TYPE_STOP_SESSION,
-                       lttng_action_stop_session_validate,
-                       lttng_action_stop_session_serialize,
-                       lttng_action_stop_session_is_equal,
-                       lttng_action_stop_session_destroy,
-                       lttng_action_stop_session_internal_get_rate_policy,
-                       lttng_action_generic_add_error_query_results,
-                       lttng_action_stop_session_mi_serialize);
-
-       status = lttng_action_stop_session_set_rate_policy(
-                       &action_stop->parent, policy);
+       lttng_action_init(&action_stop->parent,
+                         LTTNG_ACTION_TYPE_STOP_SESSION,
+                         lttng_action_stop_session_validate,
+                         lttng_action_stop_session_serialize,
+                         lttng_action_stop_session_is_equal,
+                         lttng_action_stop_session_destroy,
+                         lttng_action_stop_session_internal_get_rate_policy,
+                         lttng_action_generic_add_error_query_results,
+                         lttng_action_stop_session_mi_serialize);
+
+       status = lttng_action_stop_session_set_rate_policy(&action_stop->parent, policy);
        if (status != LTTNG_ACTION_STATUS_OK) {
                lttng_action_destroy(&action_stop->parent);
-               action_stop = NULL;
+               action_stop = nullptr;
                goto end;
        }
 
@@ -330,14 +321,14 @@ end:
        return &action_stop->parent;
 }
 
-enum lttng_action_status lttng_action_stop_session_set_session_name(
-               struct lttng_action *action, const char *session_name)
+enum lttng_action_status lttng_action_stop_session_set_session_name(struct lttng_action *action,
+                                                                   const char *session_name)
 {
        struct lttng_action_stop_session *action_stop_session;
        enum lttng_action_status status;
 
        if (!action || !IS_STOP_SESSION_ACTION(action) || !session_name ||
-                       strlen(session_name) == 0) {
+           strlen(session_name) == 0) {
                status = LTTNG_ACTION_STATUS_INVALID;
                goto end;
        }
@@ -357,8 +348,9 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_stop_session_get_session_name(
-               const struct lttng_action *action, const char **session_name)
+enum lttng_action_status
+lttng_action_stop_session_get_session_name(const struct lttng_action *action,
+                                          const char **session_name)
 {
        const struct lttng_action_stop_session *action_stop_session;
        enum lttng_action_status status;
@@ -377,13 +369,13 @@ end:
        return status;
 }
 
-enum lttng_action_status lttng_action_stop_session_set_rate_policy(
-               struct lttng_action *action,
-               const struct lttng_rate_policy *policy)
+enum lttng_action_status
+lttng_action_stop_session_set_rate_policy(struct lttng_action *action,
+                                         const struct lttng_rate_policy *policy)
 {
        enum lttng_action_status status;
        struct lttng_action_stop_session *stop_session_action;
-       struct lttng_rate_policy *copy = NULL;
+       struct lttng_rate_policy *copy = nullptr;
 
        if (!action || !policy || !IS_STOP_SESSION_ACTION(action)) {
                status = LTTNG_ACTION_STATUS_INVALID;
@@ -402,16 +394,16 @@ enum lttng_action_status lttng_action_stop_session_set_rate_policy(
 
        stop_session_action->policy = copy;
        status = LTTNG_ACTION_STATUS_OK;
-       copy = NULL;
+       copy = nullptr;
 
 end:
        lttng_rate_policy_destroy(copy);
        return status;
 }
 
-enum lttng_action_status lttng_action_stop_session_get_rate_policy(
-               const struct lttng_action *action,
-               const struct lttng_rate_policy **policy)
+enum lttng_action_status
+lttng_action_stop_session_get_rate_policy(const struct lttng_action *action,
+                                         const struct lttng_rate_policy **policy)
 {
        enum lttng_action_status status;
        const struct lttng_action_stop_session *stop_session_action;
@@ -430,8 +422,7 @@ end:
 }
 
 static const struct lttng_rate_policy *
-lttng_action_stop_session_internal_get_rate_policy(
-               const struct lttng_action *action)
+lttng_action_stop_session_internal_get_rate_policy(const struct lttng_action *action)
 {
        const struct lttng_action_stop_session *_action;
        _action = action_stop_session_from_action_const(action);
index c957824af72d265800a1bd2ab0cd5e3179d3c051..fab15af8c77619c5b68a79e9c7d7c70b69911637 100644 (file)
  * Align value to the next multiple of align. Returns val if it already is a
  * multiple of align. Align must be a power of two.
  */
-#define __lttng_align_ceil_mask(v, mask)       (((v) + (mask)) & ~(mask))
+#define __lttng_align_ceil_mask(v, mask) (((v) + (mask)) & ~(mask))
 
-#define lttng_align_ceil(v, align) \
-       __lttng_align_ceil_mask(v, (__typeof__(v)) (align) - 1)
+#define lttng_align_ceil(v, align) __lttng_align_ceil_mask(v, (__typeof__(v)) (align) -1)
 
 /*
  * Align value to the previous multiple of align. Returns val if it already is a
  * multiple of align. Align must be a power of two.
  */
-#define __lttng_align_floor_mask(v, mask)      ((v) & ~(mask))
+#define __lttng_align_floor_mask(v, mask) ((v) & ~(mask))
 
-#define lttng_align_floor(v, align) \
-       __lttng_align_floor_mask(v, (__typeof__(v)) (align) - 1)
+#define lttng_align_floor(v, align) __lttng_align_floor_mask(v, (__typeof__(v)) (align) -1)
 
 /**
  * lttng_offset_align - Calculate the offset needed to align an object on its natural
  * Returns the offset that must be added to align towards higher
  * addresses.
  */
-#define lttng_offset_align(align_drift, alignment)                                    \
-       ({                                                                     \
-               LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0                    \
-                                  || ((alignment) & ((alignment) - 1)));      \
-               (((alignment) - (align_drift)) & ((alignment) - 1));           \
+#define lttng_offset_align(align_drift, alignment)                                                \
+       ({                                                                                        \
+               LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0 || ((alignment) & ((alignment) -1))); \
+               (((alignment) - (align_drift)) & ((alignment) -1));                               \
        })
 
 /**
  *
  * Returns the offset that must be substracted to align towards lower addresses.
  */
-#define lttng_offset_align_floor(align_drift, alignment)                              \
-       ({                                                                     \
-               LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0                    \
-                                  || ((alignment) & ((alignment) - 1)));      \
-               (((align_drift) - (alignment)) & ((alignment) - 1));           \
+#define lttng_offset_align_floor(align_drift, alignment)                                          \
+       ({                                                                                        \
+               LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0 || ((alignment) & ((alignment) -1))); \
+               (((align_drift) - (alignment)) & ((alignment) -1));                               \
        })
 
 #endif /* _LTTNG_ALIGN_H */
index 0beff92adfc7598bb02cc2389a406e517a84ae52..7c8934778a5b478ac1252d937a61f44151e577ea 100644 (file)
@@ -7,11 +7,11 @@
 
 #include "argpar-utils.hpp"
 
-#include <stdio.h>
-
 #include <common/error.hpp>
 #include <common/string-utils/string-utils.hpp>
 
+#include <stdio.h>
+
 /*
  * Given argpar error status `status` and error `error`, return a formatted
  * error message describing the error.
  *
  * The returned string must be freed by the caller.
  */
-static ATTR_FORMAT_PRINTF(4, 0)
-char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
-               const char **argv, const char *context_fmt, va_list args)
+static ATTR_FORMAT_PRINTF(4, 0) char *format_arg_error_v(const struct argpar_error *error,
+                                                        int argc_offset,
+                                                        const char **argv,
+                                                        const char *context_fmt,
+                                                        va_list args)
 {
-       char *str = NULL;
-       char *str_ret = NULL;
+       char *str = nullptr;
+       char *str_ret = nullptr;
        int ret;
 
        if (context_fmt) {
@@ -40,7 +42,7 @@ char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
                         * If vasprintf fails, the content of str is undefined,
                         * and we shouldn't try to free it.
                         */
-                       str = NULL;
+                       str = nullptr;
                        goto end;
                }
 
@@ -50,16 +52,18 @@ char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
                }
        }
 
-       switch (argpar_error_type(error))
-       {
+       switch (argpar_error_type(error)) {
        case ARGPAR_ERROR_TYPE_MISSING_OPT_ARG:
        {
                const int orig_index = argpar_error_orig_index(error);
                const char *arg = argv[orig_index];
 
                ret = strutils_appendf(&str,
-                       WHILE_PARSING_ARG_N_ARG_FMT "Missing required argument for option `%s`",
-                       orig_index + 1 + argc_offset, argv[orig_index], arg);
+                                      WHILE_PARSING_ARG_N_ARG_FMT
+                                      "Missing required argument for option `%s`",
+                                      orig_index + 1 + argc_offset,
+                                      argv[orig_index],
+                                      arg);
                if (ret < 0) {
                        goto end;
                }
@@ -69,19 +73,24 @@ char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
        case ARGPAR_ERROR_TYPE_UNEXPECTED_OPT_ARG:
        {
                bool is_short;
-               const struct argpar_opt_descr *descr =
-                       argpar_error_opt_descr(error, &is_short);
+               const struct argpar_opt_descr *descr = argpar_error_opt_descr(error, &is_short);
                int orig_index = argpar_error_orig_index(error);
                const char *arg = argv[orig_index];
 
                if (is_short) {
                        ret = strutils_appendf(&str,
-                               WHILE_PARSING_ARG_N_ARG_FMT "Unexpected argument for option `-%c`",
-                               orig_index + 1 + argc_offset, arg, descr->short_name);
+                                              WHILE_PARSING_ARG_N_ARG_FMT
+                                              "Unexpected argument for option `-%c`",
+                                              orig_index + 1 + argc_offset,
+                                              arg,
+                                              descr->short_name);
                } else {
                        ret = strutils_appendf(&str,
-                               WHILE_PARSING_ARG_N_ARG_FMT "Unexpected argument for option `--%s`",
-                               orig_index + 1 + argc_offset, arg, descr->long_name);
+                                              WHILE_PARSING_ARG_N_ARG_FMT
+                                              "Unexpected argument for option `--%s`",
+                                              orig_index + 1 + argc_offset,
+                                              arg,
+                                              descr->long_name);
                }
 
                if (ret < 0) {
@@ -96,8 +105,10 @@ char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
                const char *unknown_opt = argpar_error_unknown_opt_name(error);
 
                ret = strutils_appendf(&str,
-                       WHILE_PARSING_ARG_N_ARG_FMT "Unknown option `%s`",
-                       orig_index + 1 + argc_offset, argv[orig_index], unknown_opt);
+                                      WHILE_PARSING_ARG_N_ARG_FMT "Unknown option `%s`",
+                                      orig_index + 1 + argc_offset,
+                                      argv[orig_index],
+                                      unknown_opt);
 
                if (ret < 0) {
                        goto end;
@@ -106,11 +117,11 @@ char *format_arg_error_v(const struct argpar_error *error, int argc_offset,
                break;
        }
        default:
-               abort ();
+               abort();
        }
 
        str_ret = str;
-       str = NULL;
+       str = nullptr;
 
 end:
        free(str);
@@ -118,13 +129,16 @@ end:
 }
 
 enum parse_next_item_status parse_next_item(struct argpar_iter *iter,
-               const struct argpar_item **item, int argc_offset,
-               const char **argv, bool unknown_opt_is_error,
-               const struct argpar_error **error_out,
-               const char *context_fmt, ...)
+                                           const struct argpar_item **item,
+                                           int argc_offset,
+                                           const char **argv,
+                                           bool unknown_opt_is_error,
+                                           const struct argpar_error **error_out,
+                                           const char *context_fmt,
+                                           ...)
 {
        enum argpar_iter_next_status status;
-       const struct argpar_error *error = NULL;
+       const struct argpar_error *error = nullptr;
        enum parse_next_item_status ret;
 
        ARGPAR_ITEM_DESTROY_AND_RESET(*item);
@@ -141,14 +155,13 @@ enum parse_next_item_status parse_next_item(struct argpar_iter *iter,
                char *err_str;
 
                if (argpar_error_type(error) == ARGPAR_ERROR_TYPE_UNKNOWN_OPT &&
-                               !unknown_opt_is_error) {
+                   !unknown_opt_is_error) {
                        ret = PARSE_NEXT_ITEM_STATUS_END;
                        break;
                }
 
                va_start(args, context_fmt);
-               err_str = format_arg_error_v(error, argc_offset, argv,
-                       context_fmt, args);
+               err_str = format_arg_error_v(error, argc_offset, argv, context_fmt, args);
                va_end(args);
 
                if (err_str) {
@@ -174,7 +187,7 @@ enum parse_next_item_status parse_next_item(struct argpar_iter *iter,
        if (error_out) {
                argpar_error_destroy(*error_out);
                *error_out = error;
-               error = NULL;
+               error = nullptr;
        }
 
        argpar_error_destroy(error);
index b77609edd5b53f35ea08da0b9e8f38c052c97d88..4d25b3a705ad13c3fbffeb764036a4c1d612d8fb 100644 (file)
@@ -8,20 +8,19 @@
 #ifndef COMMON_ARGPAR_UTILS_H
 #define COMMON_ARGPAR_UTILS_H
 
-#include <stdarg.h>
-
-#include <common/macros.hpp>
 #include <common/argpar/argpar.h>
+#include <common/macros.hpp>
 #include <common/string-utils/format.hpp>
 
+#include <stdarg.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 #define WHILE_PARSING_ARG_N_ARG_FMT "While parsing argument #%d (`%s`): "
 
-enum parse_next_item_status
-{
+enum parse_next_item_status {
        PARSE_NEXT_ITEM_STATUS_OK = 0,
        PARSE_NEXT_ITEM_STATUS_END = 1,
        PARSE_NEXT_ITEM_STATUS_ERROR = -1,
@@ -53,10 +52,13 @@ enum parse_next_item_status
  */
 ATTR_FORMAT_PRINTF(7, 8)
 enum parse_next_item_status parse_next_item(struct argpar_iter *iter,
-               const struct argpar_item **item, int argc_offset,
-               const char **argv, bool unknown_opt_is_error,
-               const struct argpar_error **error_out,
-               const char *context_fmt, ...);
+                                           const struct argpar_item **item,
+                                           int argc_offset,
+                                           const char **argv,
+                                           bool unknown_opt_is_error,
+                                           const struct argpar_error **error_out,
+                                           const char *context_fmt,
+                                           ...);
 
 #ifdef __cplusplus
 }
index 82b561ceaae707002f36754c55e828d35b882206..f8280ce1423a5c609fd34e5451bab875c4e186eb 100644 (file)
@@ -5,19 +5,17 @@
  * Copyright (c) 2020-2021 Simon Marchi <simon.marchi@efficios.com>
  */
 
+#include "argpar.h"
+
 #include <stdarg.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include "argpar.h"
-
-#define ARGPAR_REALLOC(_ptr, _type, _nmemb)                            \
-       ((_type *) realloc(_ptr, (_nmemb) * sizeof(_type)))
+#define ARGPAR_REALLOC(_ptr, _type, _nmemb) ((_type *) realloc(_ptr, (_nmemb) * sizeof(_type)))
 
-#define ARGPAR_CALLOC(_type, _nmemb)                                   \
-       ((_type *) calloc((_nmemb), sizeof(_type)))
+#define ARGPAR_CALLOC(_type, _nmemb) ((_type *) calloc((_nmemb), sizeof(_type)))
 
 #define ARGPAR_ZALLOC(_type) ARGPAR_CALLOC(_type, 1)
 
  * Force usage of the assertion condition to prevent unused variable warnings
  * when `assert()` are disabled by the `NDEBUG` definition.
  */
-# define ARGPAR_ASSERT(_cond) ((void) sizeof((void) (_cond), 0))
+#define ARGPAR_ASSERT(_cond) ((void) sizeof((void) (_cond), 0))
 #else
-# include <assert.h>
-# define ARGPAR_ASSERT(_cond) assert(_cond)
+#include <assert.h>
+#define ARGPAR_ASSERT(_cond) assert(_cond)
 #endif
 
 /*
@@ -45,7 +43,7 @@ struct argpar_iter {
         */
        struct {
                unsigned int argc;
-               const char * const *argv;
+               const char *const *argv;
                const struct argpar_opt_descr *descrs;
        } user;
 
@@ -128,15 +126,14 @@ struct argpar_error {
 };
 
 ARGPAR_HIDDEN
-enum argpar_item_type argpar_item_type(const struct argpar_item * const item)
+enum argpar_item_type argpar_item_type(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        return item->type;
 }
 
 ARGPAR_HIDDEN
-const struct argpar_opt_descr *argpar_item_opt_descr(
-               const struct argpar_item * const item)
+const struct argpar_opt_descr *argpar_item_opt_descr(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
@@ -144,7 +141,7 @@ const struct argpar_opt_descr *argpar_item_opt_descr(
 }
 
 ARGPAR_HIDDEN
-const char *argpar_item_opt_arg(const struct argpar_item * const item)
+const char *argpar_item_opt_arg(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_OPT);
@@ -152,7 +149,7 @@ const char *argpar_item_opt_arg(const struct argpar_item * const item)
 }
 
 ARGPAR_HIDDEN
-const char *argpar_item_non_opt_arg(const struct argpar_item * const item)
+const char *argpar_item_non_opt_arg(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
@@ -160,8 +157,7 @@ const char *argpar_item_non_opt_arg(const struct argpar_item * const item)
 }
 
 ARGPAR_HIDDEN
-unsigned int argpar_item_non_opt_orig_index(
-               const struct argpar_item * const item)
+unsigned int argpar_item_non_opt_orig_index(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
@@ -169,8 +165,7 @@ unsigned int argpar_item_non_opt_orig_index(
 }
 
 ARGPAR_HIDDEN
-unsigned int argpar_item_non_opt_non_opt_index(
-               const struct argpar_item * const item)
+unsigned int argpar_item_non_opt_non_opt_index(const struct argpar_item *const item)
 {
        ARGPAR_ASSERT(item);
        ARGPAR_ASSERT(item->type == ARGPAR_ITEM_TYPE_NON_OPT);
@@ -178,15 +173,14 @@ unsigned int argpar_item_non_opt_non_opt_index(
 }
 
 ARGPAR_HIDDEN
-void argpar_item_destroy(const struct argpar_item * const item)
+void argpar_item_destroy(const struct argpar_item *const item)
 {
        if (!item) {
                goto end;
        }
 
        if (item->type == ARGPAR_ITEM_TYPE_OPT) {
-               struct argpar_item_opt * const opt_item =
-                       (struct argpar_item_opt *) item;
+               struct argpar_item_opt *const opt_item = (struct argpar_item_opt *) item;
 
                free(opt_item->arg);
        }
@@ -203,13 +197,10 @@ end:
  *
  * Returns `NULL` on memory error.
  */
-static
-struct argpar_item_opt *create_opt_item(
-               const struct argpar_opt_descr * const descr,
-               const char * const arg)
+static struct argpar_item_opt *create_opt_item(const struct argpar_opt_descr *const descr,
+                                              const char *const arg)
 {
-       struct argpar_item_opt *opt_item =
-               ARGPAR_ZALLOC(struct argpar_item_opt);
+       struct argpar_item_opt *opt_item = ARGPAR_ZALLOC(struct argpar_item_opt);
 
        if (!opt_item) {
                goto end;
@@ -242,13 +233,11 @@ end:
  *
  * Returns `NULL` on memory error.
  */
-static
-struct argpar_item_non_opt *create_non_opt_item(const char * const arg,
-               const unsigned int orig_index,
-               const unsigned int non_opt_index)
+static struct argpar_item_non_opt *create_non_opt_item(const char *const arg,
+                                                      const unsigned int orig_index,
+                                                      const unsigned int non_opt_index)
 {
-       struct argpar_item_non_opt * const non_opt_item =
-               ARGPAR_ZALLOC(struct argpar_item_non_opt);
+       struct argpar_item_non_opt *const non_opt_item = ARGPAR_ZALLOC(struct argpar_item_non_opt);
 
        if (!non_opt_item) {
                goto end;
@@ -274,12 +263,11 @@ end:
  * Returns 0 on success (including if `error` is `NULL`) or -1 on memory
  * error.
  */
-static
-int set_error(struct argpar_error ** const error,
-               enum argpar_error_type type,
-               const char * const unknown_opt_name,
-               const struct argpar_opt_descr * const opt_descr,
-               const bool is_short)
+static int set_error(struct argpar_error **const error,
+                    enum argpar_error_type type,
+                    const char *const unknown_opt_name,
+                    const struct argpar_opt_descr *const opt_descr,
+                    const bool is_short)
 {
        int ret = 0;
 
@@ -295,8 +283,8 @@ int set_error(struct argpar_error ** const error,
        (*error)->type = type;
 
        if (unknown_opt_name) {
-               (*error)->unknown_opt_name = ARGPAR_CALLOC(char,
-                       strlen(unknown_opt_name) + 1 + (is_short ? 1 : 2));
+               (*error)->unknown_opt_name =
+                       ARGPAR_CALLOC(char, strlen(unknown_opt_name) + 1 + (is_short ? 1 : 2));
                if (!(*error)->unknown_opt_name) {
                        goto error;
                }
@@ -323,23 +311,21 @@ end:
 }
 
 ARGPAR_HIDDEN
-enum argpar_error_type argpar_error_type(
-               const struct argpar_error * const error)
+enum argpar_error_type argpar_error_type(const struct argpar_error *const error)
 {
        ARGPAR_ASSERT(error);
        return error->type;
 }
 
 ARGPAR_HIDDEN
-unsigned int argpar_error_orig_index(const struct argpar_error * const error)
+unsigned int argpar_error_orig_index(const struct argpar_error *const error)
 {
        ARGPAR_ASSERT(error);
        return error->orig_index;
 }
 
 ARGPAR_HIDDEN
-const char *argpar_error_unknown_opt_name(
-               const struct argpar_error * const error)
+const char *argpar_error_unknown_opt_name(const struct argpar_error *const error)
 {
        ARGPAR_ASSERT(error);
        ARGPAR_ASSERT(error->type == ARGPAR_ERROR_TYPE_UNKNOWN_OPT);
@@ -348,12 +334,12 @@ const char *argpar_error_unknown_opt_name(
 }
 
 ARGPAR_HIDDEN
-const struct argpar_opt_descr *argpar_error_opt_descr(
-               const struct argpar_error * const error, bool * const is_short)
+const struct argpar_opt_descr *argpar_error_opt_descr(const struct argpar_error *const error,
+                                                     bool *const is_short)
 {
        ARGPAR_ASSERT(error);
        ARGPAR_ASSERT(error->type == ARGPAR_ERROR_TYPE_MISSING_OPT_ARG ||
-               error->type == ARGPAR_ERROR_TYPE_UNEXPECTED_OPT_ARG);
+                     error->type == ARGPAR_ERROR_TYPE_UNEXPECTED_OPT_ARG);
        ARGPAR_ASSERT(error->opt_descr);
 
        if (is_short) {
@@ -364,7 +350,7 @@ const struct argpar_opt_descr *argpar_error_opt_descr(
 }
 
 ARGPAR_HIDDEN
-void argpar_error_destroy(const struct argpar_error * const error)
+void argpar_error_destroy(const struct argpar_error *const error)
 {
        if (error) {
                free(error->unknown_opt_name);
@@ -383,21 +369,18 @@ void argpar_error_destroy(const struct argpar_error * const error)
  *
  * Returns `NULL` if no descriptor is found.
  */
-static
-const struct argpar_opt_descr *find_descr(
-               const struct argpar_opt_descr * const descrs,
-               const char short_name, const char * const long_name)
+static const struct argpar_opt_descr *find_descr(const struct argpar_opt_descr *const descrs,
+                                                const char short_name,
+                                                const char *const long_name)
 {
        const struct argpar_opt_descr *descr;
 
        for (descr = descrs; descr->short_name || descr->long_name; descr++) {
-               if (short_name && descr->short_name &&
-                               short_name == descr->short_name) {
+               if (short_name && descr->short_name && short_name == descr->short_name) {
                        goto end;
                }
 
-               if (long_name && descr->long_name &&
-                               strcmp(long_name, descr->long_name) == 0) {
+               if (long_name && descr->long_name && strcmp(long_name, descr->long_name) == 0) {
                        goto end;
                }
        }
@@ -422,14 +405,13 @@ enum parse_orig_arg_opt_ret {
  * On error (except for `PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY`), sets
  * `*error`.
  */
-static
-enum parse_orig_arg_opt_ret parse_short_opt_group(
-               const char * const short_opt_group,
-               const char * const next_orig_arg,
-               const struct argpar_opt_descr * const descrs,
-               struct argpar_iter * const iter,
-               struct argpar_error ** const error,
-               struct argpar_item ** const item)
+static enum parse_orig_arg_opt_ret
+parse_short_opt_group(const char *const short_opt_group,
+                     const char *const next_orig_arg,
+                     const struct argpar_opt_descr *const descrs,
+                     struct argpar_iter *const iter,
+                     struct argpar_error **const error,
+                     struct argpar_item **const item)
 {
        enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
        bool used_next_orig_arg = false;
@@ -446,13 +428,11 @@ enum parse_orig_arg_opt_ret parse_short_opt_group(
        /* Find corresponding option descriptor */
        descr = find_descr(descrs, *iter->short_opt_group_ch, NULL);
        if (!descr) {
-               const char unknown_opt_name[] =
-                       {*iter->short_opt_group_ch, '\0'};
+               const char unknown_opt_name[] = { *iter->short_opt_group_ch, '\0' };
 
                ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
 
-               if (set_error(error, ARGPAR_ERROR_TYPE_UNKNOWN_OPT,
-                               unknown_opt_name, NULL, true)) {
+               if (set_error(error, ARGPAR_ERROR_TYPE_UNKNOWN_OPT, unknown_opt_name, NULL, true)) {
                        ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                }
 
@@ -473,12 +453,10 @@ enum parse_orig_arg_opt_ret parse_short_opt_group(
                 * We accept `-o ''` (empty option argument), but not
                 * `-o` alone if an option argument is expected.
                 */
-               if (!opt_arg || (iter->short_opt_group_ch[1] &&
-                               strlen(opt_arg) == 0)) {
+               if (!opt_arg || (iter->short_opt_group_ch[1] && strlen(opt_arg) == 0)) {
                        ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
 
-                       if (set_error(error, ARGPAR_ERROR_TYPE_MISSING_OPT_ARG,
-                                       NULL, descr, true)) {
+                       if (set_error(error, ARGPAR_ERROR_TYPE_MISSING_OPT_ARG, NULL, descr, true)) {
                                ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                        }
 
@@ -524,13 +502,12 @@ end:
  * On error (except for `PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY`), sets
  * `*error`.
  */
-static
-enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
-               const char * const next_orig_arg,
-               const struct argpar_opt_descr * const descrs,
-               struct argpar_iter * const iter,
-               struct argpar_error ** const error,
-               struct argpar_item ** const item)
+static enum parse_orig_arg_opt_ret parse_long_opt(const char *const long_opt_arg,
+                                                 const char *const next_orig_arg,
+                                                 const struct argpar_opt_descr *const descrs,
+                                                 struct argpar_iter *const iter,
+                                                 struct argpar_error **const error,
+                                                 struct argpar_item **const item)
 {
        enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
        const struct argpar_opt_descr *descr;
@@ -556,8 +533,8 @@ enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
                /* Isolate the option name */
                while (long_opt_name_size > iter->tmp_buf.size - 1) {
                        iter->tmp_buf.size *= 2;
-                       iter->tmp_buf.data = ARGPAR_REALLOC(iter->tmp_buf.data,
-                               char, iter->tmp_buf.size);
+                       iter->tmp_buf.data =
+                               ARGPAR_REALLOC(iter->tmp_buf.data, char, iter->tmp_buf.size);
                        if (!iter->tmp_buf.data) {
                                ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                                goto error;
@@ -574,8 +551,7 @@ enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
        if (!descr) {
                ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
 
-               if (set_error(error, ARGPAR_ERROR_TYPE_UNKNOWN_OPT,
-                               long_opt_name, NULL, false)) {
+               if (set_error(error, ARGPAR_ERROR_TYPE_UNKNOWN_OPT, long_opt_name, NULL, false)) {
                        ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                }
 
@@ -592,8 +568,11 @@ enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
                        if (!next_orig_arg) {
                                ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
 
-                               if (set_error(error, ARGPAR_ERROR_TYPE_MISSING_OPT_ARG,
-                                               NULL, descr, false)) {
+                               if (set_error(error,
+                                             ARGPAR_ERROR_TYPE_MISSING_OPT_ARG,
+                                             NULL,
+                                             descr,
+                                             false)) {
                                        ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                                }
 
@@ -610,8 +589,7 @@ enum parse_orig_arg_opt_ret parse_long_opt(const char * const long_opt_arg,
                 */
                ret = PARSE_ORIG_ARG_OPT_RET_ERROR;
 
-               if (set_error(error, ARGPAR_ERROR_TYPE_UNEXPECTED_OPT_ARG,
-                               NULL, descr, false)) {
+               if (set_error(error, ARGPAR_ERROR_TYPE_UNEXPECTED_OPT_ARG, NULL, descr, false)) {
                        ret = PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY;
                }
 
@@ -648,13 +626,12 @@ end:
  * On error (except for `PARSE_ORIG_ARG_OPT_RET_ERROR_MEMORY`), sets
  * `*error`.
  */
-static
-enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char * const orig_arg,
-               const char * const next_orig_arg,
-               const struct argpar_opt_descr * const descrs,
-               struct argpar_iter * const iter,
-               struct argpar_error ** const error,
-               struct argpar_item ** const item)
+static enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char *const orig_arg,
+                                                     const char *const next_orig_arg,
+                                                     const struct argpar_opt_descr *const descrs,
+                                                     struct argpar_iter *const iter,
+                                                     struct argpar_error **const error,
+                                                     struct argpar_item **const item)
 {
        enum parse_orig_arg_opt_ret ret = PARSE_ORIG_ARG_OPT_RET_OK;
 
@@ -662,12 +639,10 @@ enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char * const orig_arg,
 
        if (orig_arg[1] == '-') {
                /* Long option */
-               ret = parse_long_opt(&orig_arg[2],
-                       next_orig_arg, descrs, iter, error, item);
+               ret = parse_long_opt(&orig_arg[2], next_orig_arg, descrs, iter, error, item);
        } else {
                /* Short option */
-               ret = parse_short_opt_group(&orig_arg[1],
-                       next_orig_arg, descrs, iter, error, item);
+               ret = parse_short_opt_group(&orig_arg[1], next_orig_arg, descrs, iter, error, item);
        }
 
        return ret;
@@ -675,8 +650,8 @@ enum parse_orig_arg_opt_ret parse_orig_arg_opt(const char * const orig_arg,
 
 ARGPAR_HIDDEN
 struct argpar_iter *argpar_iter_create(const unsigned int argc,
-               const char * const * const argv,
-               const struct argpar_opt_descr * const descrs)
+                                      const char *const *const argv,
+                                      const struct argpar_opt_descr *const descrs)
 {
        struct argpar_iter *iter = ARGPAR_ZALLOC(struct argpar_iter);
 
@@ -700,7 +675,7 @@ end:
 }
 
 ARGPAR_HIDDEN
-void argpar_iter_destroy(struct argpar_iter * const iter)
+void argpar_iter_destroy(struct argpar_iter *const iter)
 {
        if (iter) {
                free(iter->tmp_buf.data);
@@ -709,16 +684,15 @@ void argpar_iter_destroy(struct argpar_iter * const iter)
 }
 
 ARGPAR_HIDDEN
-enum argpar_iter_next_status argpar_iter_next(
-               struct argpar_iter * const iter,
-               const struct argpar_item ** const item,
-               const struct argpar_error ** const error)
+enum argpar_iter_next_status argpar_iter_next(struct argpar_iter *const iter,
+                                             const struct argpar_item **const item,
+                                             const struct argpar_error **const error)
 {
        enum argpar_iter_next_status status;
        enum parse_orig_arg_opt_ret parse_orig_arg_opt_ret;
        const char *orig_arg;
        const char *next_orig_arg;
-       struct argpar_error ** const nc_error = (struct argpar_error **) error;
+       struct argpar_error **const nc_error = (struct argpar_error **) error;
 
        ARGPAR_ASSERT(iter->i <= iter->user.argc);
 
@@ -732,16 +706,12 @@ enum argpar_iter_next_status argpar_iter_next(
        }
 
        orig_arg = iter->user.argv[iter->i];
-       next_orig_arg =
-               iter->i < (iter->user.argc - 1) ?
-                       iter->user.argv[iter->i + 1] : NULL;
+       next_orig_arg = iter->i < (iter->user.argc - 1) ? iter->user.argv[iter->i + 1] : NULL;
 
-       if (strcmp(orig_arg, "-") == 0 || strcmp(orig_arg, "--") == 0 ||
-                       orig_arg[0] != '-') {
+       if (strcmp(orig_arg, "-") == 0 || strcmp(orig_arg, "--") == 0 || orig_arg[0] != '-') {
                /* Non-option argument */
-               const struct argpar_item_non_opt * const non_opt_item =
-                       create_non_opt_item(orig_arg, iter->i,
-                               iter->non_opt_index);
+               const struct argpar_item_non_opt *const non_opt_item =
+                       create_non_opt_item(orig_arg, iter->i, iter->non_opt_index);
 
                if (!non_opt_item) {
                        status = ARGPAR_ITER_NEXT_STATUS_ERROR_MEMORY;
@@ -757,8 +727,11 @@ enum argpar_iter_next_status argpar_iter_next(
 
        /* Option argument */
        parse_orig_arg_opt_ret = parse_orig_arg_opt(orig_arg,
-               next_orig_arg, iter->user.descrs, iter, nc_error,
-               (struct argpar_item **) item);
+                                                   next_orig_arg,
+                                                   iter->user.descrs,
+                                                   iter,
+                                                   nc_error,
+                                                   (struct argpar_item **) item);
        switch (parse_orig_arg_opt_ret) {
        case PARSE_ORIG_ARG_OPT_RET_OK:
                status = ARGPAR_ITER_NEXT_STATUS_OK;
@@ -782,8 +755,7 @@ end:
 }
 
 ARGPAR_HIDDEN
-unsigned int argpar_iter_ingested_orig_args(
-               const struct argpar_iter * const iter)
+unsigned int argpar_iter_ingested_orig_args(const struct argpar_iter *const iter)
 {
        return iter->i;
 }
index c528cc4412272700990a0a61a480b6859ce57c18..909da9cb3cce4ae3ff15633be0090271f058e985 100644 (file)
@@ -119,9 +119,9 @@ argpar_iter_next() produces the following items, in this order:
  * <https://gcc.gnu.org/wiki/Visibility>.
  */
 #if defined(_WIN32) || defined(__CYGWIN__)
-# define ARGPAR_HIDDEN
+#define ARGPAR_HIDDEN
 #else
-# define ARGPAR_HIDDEN __attribute__((visibility("hidden")))
+#define ARGPAR_HIDDEN __attribute__((visibility("hidden")))
 #endif
 
 struct argpar_opt_descr;
@@ -190,8 +190,7 @@ enum argpar_item_type argpar_item_type(const struct argpar_item *item);
 /// @cond hidden_macro
 ARGPAR_HIDDEN
 /// @endcond
-const struct argpar_opt_descr *argpar_item_opt_descr(
-               const struct argpar_item *item);
+const struct argpar_opt_descr *argpar_item_opt_descr(const struct argpar_item *item);
 
 /*!
 @brief
@@ -331,10 +330,10 @@ void argpar_item_destroy(const struct argpar_item *item);
     Item to destroy and variable to reset
     (<code>const struct argpar_item *</code> type).
 */
-#define ARGPAR_ITEM_DESTROY_AND_RESET(_item)                           \
-       {                                                               \
-               argpar_item_destroy(_item);                             \
-               _item = NULL;                                           \
+#define ARGPAR_ITEM_DESTROY_AND_RESET(_item) \
+       {                                    \
+               argpar_item_destroy(_item);  \
+               ((_item)) = NULL;            \
        }
 
 /// @}
@@ -468,8 +467,8 @@ const char *argpar_error_unknown_opt_name(const struct argpar_error *error);
 /// @cond hidden_macro
 ARGPAR_HIDDEN
 /// @endcond
-const struct argpar_opt_descr *argpar_error_opt_descr(
-               const struct argpar_error *error, bool *is_short);
+const struct argpar_opt_descr *argpar_error_opt_descr(const struct argpar_error *error,
+                                                     bool *is_short);
 
 /*!
 @brief
@@ -516,7 +515,7 @@ struct argpar_opt_descr {
        const char short_name;
 
        /// Long option name (without the <code>\--</code> prefix), or \c NULL
-       const char * const long_name;
+       const char *const long_name;
 
        /// \c true if this option has an argument
        const bool with_arg;
@@ -537,7 +536,10 @@ const struct argpar_opt_descr descrs[] = {
 };
 @endcode
 */
-#define ARGPAR_OPT_DESCR_SENTINEL      { -1, '\0', NULL, false }
+#define ARGPAR_OPT_DESCR_SENTINEL     \
+       {                             \
+               -1, '\0', NULL, false \
+       }
 
 /*!
 @struct argpar_iter
@@ -607,8 +609,8 @@ argpar_iter_next().
 ARGPAR_HIDDEN
 /// @endcond
 struct argpar_iter *argpar_iter_create(unsigned int argc,
-               const char * const *argv,
-               const struct argpar_opt_descr *descrs);
+                                      const char *const *argv,
+                                      const struct argpar_opt_descr *descrs);
 
 /*!
 @brief
@@ -681,9 +683,9 @@ If there are no more original arguments to parse, this function returns
 /// @cond hidden_macro
 ARGPAR_HIDDEN
 /// @endcond
-enum argpar_iter_next_status argpar_iter_next(
-               struct argpar_iter *iter, const struct argpar_item **item,
-               const struct argpar_error **error);
+enum argpar_iter_next_status argpar_iter_next(struct argpar_iter *iter,
+                                             const struct argpar_item **item,
+                                             const struct argpar_error **error);
 
 /*
  * Returns the number of ingested elements from `argv`, as passed to
index 9498423cae64efb38d1b5e55fbccd1db879bdd82..0b3de73b0345911831b9eeefd8537ce87c9e7a19 100644 (file)
@@ -9,8 +9,7 @@
 #include <common/dynamic-buffer.hpp>
 #include <common/error.hpp>
 
-struct lttng_buffer_view lttng_buffer_view_init(
-               const char *src, size_t offset, ptrdiff_t len)
+struct lttng_buffer_view lttng_buffer_view_init(const char *src, size_t offset, ptrdiff_t len)
 {
        struct lttng_buffer_view view = { .data = src + offset, .size = (size_t) len };
        return view;
@@ -21,23 +20,26 @@ bool lttng_buffer_view_is_valid(const struct lttng_buffer_view *view)
        return view && view->data && view->size > 0;
 }
 
-struct lttng_buffer_view lttng_buffer_view_from_view(
-               const struct lttng_buffer_view *src, size_t offset,
-               ptrdiff_t len)
+struct lttng_buffer_view
+lttng_buffer_view_from_view(const struct lttng_buffer_view *src, size_t offset, ptrdiff_t len)
 {
-       struct lttng_buffer_view view = { .data = NULL, .size = 0 };
+       struct lttng_buffer_view view = { .data = nullptr, .size = 0 };
 
        LTTNG_ASSERT(src);
 
        if (offset > src->size) {
                ERR("Attempt to create buffer view from another view with invalid offset (offset > source size): source size = %zu, offset in source = %zu, length = %zd",
-                               src->size, offset, len);
+                   src->size,
+                   offset,
+                   len);
                goto end;
        }
 
        if (len != -1 && len > (src->size - offset)) {
                ERR("Attempt to create buffer view from another view with invalid length (length > space left after offset in source): source size = %zu, offset in source = %zu, length = %zd",
-                               src->size, offset, len);
+                   src->size,
+                   offset,
+                   len);
                goto end;
        }
 
@@ -48,22 +50,25 @@ end:
 }
 
 struct lttng_buffer_view lttng_buffer_view_from_dynamic_buffer(
-               const struct lttng_dynamic_buffer *src, size_t offset,
-               ptrdiff_t len)
+       const struct lttng_dynamic_buffer *src, size_t offset, ptrdiff_t len)
 {
-       struct lttng_buffer_view view = { .data = NULL, .size = 0 };
+       struct lttng_buffer_view view = { .data = nullptr, .size = 0 };
 
        LTTNG_ASSERT(src);
 
        if (offset > src->size) {
                ERR("Attempt to create buffer view from a dynamic buffer with invalid offset (offset > source size): source size = %zu, offset in source = %zu, length = %zd",
-                               src->size, offset, len);
+                   src->size,
+                   offset,
+                   len);
                goto end;
        }
 
        if (len != -1 && len > (src->size - offset)) {
                ERR("Attempt to create buffer view from a dynamic buffer with invalid length (length > space left after offset in source): source size = %zu, offset in source = %zu, length = %zd",
-                               src->size, offset, len);
+                   src->size,
+                   offset,
+                   len);
                goto end;
        }
 
@@ -74,8 +79,8 @@ end:
 }
 
 bool lttng_buffer_view_contains_string(const struct lttng_buffer_view *buf,
-               const char *str,
-               size_t len_with_null_terminator)
+                                      const char *str,
+                                      size_t len_with_null_terminator)
 {
        const char *past_buf_end;
        size_t max_str_len_with_null_terminator;
index 7e638c05eca0837bed50c2d7e17b17f0f2d60f20..131275af2805e3279ed55c18edb270dc1a53a9ff 100644 (file)
@@ -9,6 +9,7 @@
 #define LTTNG_BUFFER_VIEW_H
 
 #include <common/macros.hpp>
+
 #include <stdbool.h>
 #include <stddef.h>
 #include <stdint.h>
@@ -31,8 +32,7 @@ struct lttng_buffer_view {
  * Note that a buffer view never assumes the ownership of the memory it
  * references.
  */
-struct lttng_buffer_view lttng_buffer_view_init(
-               const char *src, size_t offset, ptrdiff_t len);
+struct lttng_buffer_view lttng_buffer_view_init(const char *src, size_t offset, ptrdiff_t len);
 
 /**
  * Checks if a buffer view is safe to access.
@@ -58,9 +58,8 @@ bool lttng_buffer_view_is_valid(const struct lttng_buffer_view *view);
  * Note that a buffer view never assumes the ownership of the memory it
  * references.
  */
-struct lttng_buffer_view lttng_buffer_view_from_view(
-               const struct lttng_buffer_view *src, size_t offset,
-               ptrdiff_t len);
+struct lttng_buffer_view
+lttng_buffer_view_from_view(const struct lttng_buffer_view *src, size_t offset, ptrdiff_t len);
 
 /**
  * Return a buffer view referencing a subset of the memory referenced by a
@@ -76,8 +75,7 @@ struct lttng_buffer_view lttng_buffer_view_from_view(
  * references.
  */
 struct lttng_buffer_view lttng_buffer_view_from_dynamic_buffer(
-               const struct lttng_dynamic_buffer *src, size_t offset,
-               ptrdiff_t len);
+       const struct lttng_dynamic_buffer *src, size_t offset, ptrdiff_t len);
 
 /**
  * Verify that `buf` contains a string starting at `str` of length
@@ -89,7 +87,7 @@ struct lttng_buffer_view lttng_buffer_view_from_dynamic_buffer(
  *                             NULL terminator.
  */
 bool lttng_buffer_view_contains_string(const struct lttng_buffer_view *buf,
-               const char *str,
-               size_t len_with_null_terminator);
+                                      const char *str,
+                                      size_t len_with_null_terminator);
 
 #endif /* LTTNG_BUFFER_VIEW_H */
index f77c775a7ff23a190ad36808ff429645e77f9dc3..758fcf70c5be9d176ac6f5e97ad1963dde1b7d20 100644 (file)
@@ -8,22 +8,19 @@
 #ifndef _LTTNG_BUG_H
 #define _LTTNG_BUG_H
 
-#include <urcu/compiler.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <urcu/compiler.h>
 
-#define LTTNG_BUG_ON(condition)                                                \
-       do {                                                            \
-               if (caa_unlikely(condition)) {                          \
-                       fprintf(stderr,                                 \
-                               "LTTng BUG in file %s, line %d.\n",     \
-                               __FILE__, __LINE__);                    \
-                       exit(EXIT_FAILURE);                             \
-               }                                                       \
+#define LTTNG_BUG_ON(condition)                                                                  \
+       do {                                                                                     \
+               if (caa_unlikely(condition)) {                                                   \
+                       fprintf(stderr, "LTTng BUG in file %s, line %d.\n", __FILE__, __LINE__); \
+                       exit(EXIT_FAILURE);                                                      \
+               }                                                                                \
        } while (0)
 
-#define LTTNG_BUILD_BUG_ON(condition)                                  \
-       ((void) sizeof(char[-!!(condition)]))
+#define LTTNG_BUILD_BUG_ON(condition) ((void) sizeof(char[-!!(condition)]))
 
 /**
  * LTTNG_BUILD_RUNTIME_BUG_ON - check condition at build (if constant) or runtime
  * if the condition is ever true. If the condition is constant and false, no
  * code is emitted.
  */
-#define LTTNG_BUILD_RUNTIME_BUG_ON(condition)                  \
-       do {                                                    \
-               if (__builtin_constant_p(condition))            \
-                       LTTNG_BUILD_BUG_ON(condition);          \
-               else                                            \
-                       LTTNG_BUG_ON(condition);                \
+#define LTTNG_BUILD_RUNTIME_BUG_ON(condition)          \
+       do {                                           \
+               if (__builtin_constant_p(condition))   \
+                       LTTNG_BUILD_BUG_ON(condition); \
+               else                                   \
+                       LTTNG_BUG_ON(condition);       \
        } while (0)
 
 #endif
index c32f3900b8d4332d32e0a9eb5b771dc40b82fe85..00b4f5e7bca300cb6d513b38a7c640b016978cc1 100644 (file)
@@ -6,16 +6,14 @@
  */
 
 #include "bytecode.hpp"
+#include "common/align.hpp"
 
-#include <errno.h>
 #include <algorithm>
-
-#include "common/align.hpp"
+#include <errno.h>
 
 #define INIT_ALLOC_SIZE 4
 
-static inline
-int get_count_order(unsigned int count)
+static inline int get_count_order(unsigned int count)
 {
        int order;
 
@@ -39,8 +37,7 @@ int bytecode_init(struct lttng_bytecode_alloc **fb)
        }
 }
 
-static
-int32_t bytecode_reserve(struct lttng_bytecode_alloc **fb, uint32_t align, uint32_t len)
+static int32_t bytecode_reserve(struct lttng_bytecode_alloc **fb, uint32_t align, uint32_t len)
 {
        int32_t ret;
        uint32_t padding = lttng_offset_align((*fb)->b.len, align);
@@ -54,8 +51,7 @@ int32_t bytecode_reserve(struct lttng_bytecode_alloc **fb, uint32_t align, uint3
        if (new_alloc_len > old_alloc_len) {
                struct lttng_bytecode_alloc *newptr;
 
-               new_alloc_len =
-                       std::max(1U << get_count_order(new_alloc_len), old_alloc_len << 1);
+               new_alloc_len = std::max(1U << get_count_order(new_alloc_len), old_alloc_len << 1);
                newptr = (lttng_bytecode_alloc *) realloc(*fb, new_alloc_len);
                if (!newptr)
                        return -ENOMEM;
@@ -70,8 +66,7 @@ int32_t bytecode_reserve(struct lttng_bytecode_alloc **fb, uint32_t align, uint3
        return ret;
 }
 
-int bytecode_push(struct lttng_bytecode_alloc **fb, const void *data,
-               uint32_t align, uint32_t len)
+int bytecode_push(struct lttng_bytecode_alloc **fb, const void *data, uint32_t align, uint32_t len)
 {
        int32_t offset;
 
@@ -83,9 +78,10 @@ int bytecode_push(struct lttng_bytecode_alloc **fb, const void *data,
 }
 
 int bytecode_push_logical(struct lttng_bytecode_alloc **fb,
-               struct logical_op *data,
-               uint32_t align, uint32_t len,
-               uint16_t *skip_offset)
+                         struct logical_op *data,
+                         uint32_t align,
+                         uint32_t len,
+                         uint16_t *skip_offset)
 {
        int32_t offset;
 
@@ -93,9 +89,8 @@ int bytecode_push_logical(struct lttng_bytecode_alloc **fb,
        if (offset < 0)
                return offset;
        memcpy(&(*fb)->b.data[offset], data, len);
-       *skip_offset =
-               (char *) &((struct logical_op *) &(*fb)->b.data[offset])->skip_offset
-                       - (char *) &(*fb)->b.data[0];
+       *skip_offset = (char *) &((struct logical_op *) &(*fb)->b.data[offset])->skip_offset -
+               (char *) &(*fb)->b.data[0];
        return 0;
 }
 
@@ -156,14 +151,12 @@ end:
        return ret;
 }
 
-int bytecode_push_get_index_u64(struct lttng_bytecode_alloc **bytecode,
-               uint64_t index)
+int bytecode_push_get_index_u64(struct lttng_bytecode_alloc **bytecode, uint64_t index)
 {
        int ret;
        struct load_op *insn;
        struct get_index_u64 index_op_data;
-       const uint32_t insn_len =
-                       sizeof(struct load_op) + sizeof(struct get_index_u64);
+       const uint32_t insn_len = sizeof(struct load_op) + sizeof(struct get_index_u64);
 
        insn = (load_op *) calloc(insn_len, 1);
        if (!insn) {
@@ -182,8 +175,8 @@ end:
 }
 
 int bytecode_push_get_symbol(struct lttng_bytecode_alloc **bytecode,
-               struct lttng_bytecode_alloc **bytecode_reloc,
-               const char *symbol)
+                            struct lttng_bytecode_alloc **bytecode_reloc,
+                            const char *symbol)
 {
        int ret;
        struct load_op *insn;
@@ -191,8 +184,7 @@ int bytecode_push_get_symbol(struct lttng_bytecode_alloc **bytecode,
        uint32_t reloc_offset_u32;
        uint16_t reloc_offset;
        uint32_t bytecode_reloc_offset_u32;
-       const uint32_t insn_len =
-                       sizeof(struct load_op) + sizeof(struct get_symbol);
+       const uint32_t insn_len = sizeof(struct load_op) + sizeof(struct get_symbol);
 
        insn = (load_op *) calloc(insn_len, 1);
        if (!insn) {
@@ -206,8 +198,7 @@ int bytecode_push_get_symbol(struct lttng_bytecode_alloc **bytecode,
         * Get offset in the reloc portion at which the symbol name
         * will end up at (GET_SYMBOL's operand points there).
         */
-       bytecode_reloc_offset_u32 = bytecode_get_len(&(*bytecode_reloc)->b) +
-                       sizeof(reloc_offset);
+       bytecode_reloc_offset_u32 = bytecode_get_len(&(*bytecode_reloc)->b) + sizeof(reloc_offset);
        symbol_offset.offset = (uint16_t) bytecode_reloc_offset_u32;
        memcpy(insn->data, &symbol_offset, sizeof(symbol_offset));
 
@@ -229,8 +220,7 @@ int bytecode_push_get_symbol(struct lttng_bytecode_alloc **bytecode,
        }
 
        /* Append reloc offset. */
-       ret = bytecode_push(bytecode_reloc, &reloc_offset,
-                       1, sizeof(reloc_offset));
+       ret = bytecode_push(bytecode_reloc, &reloc_offset, 1, sizeof(reloc_offset));
        if (ret) {
                goto end;
        }
@@ -248,11 +238,9 @@ end:
  *
  * Return allocated bytecode or NULL on error.
  */
-struct lttng_bytecode *lttng_bytecode_copy(
-               const struct lttng_bytecode *orig_f)
+struct lttng_bytecode *lttng_bytecode_copy(const struct lttng_bytecode *orig_f)
 {
-       lttng_bytecode *bytecode
-               = zmalloc<lttng_bytecode>(sizeof(*bytecode) + orig_f->len);
+       lttng_bytecode *bytecode = zmalloc<lttng_bytecode>(sizeof(*bytecode) + orig_f->len);
        if (!bytecode) {
                goto error;
        }
index 4ed51dcfe14ec14ad0a782c0cdfa251d819f9142..306a7ff767d4b0b484408561ee2396f053b22148 100644 (file)
@@ -8,11 +8,11 @@
 #ifndef LTTNG_COMMON_BYTECODE_H
 #define LTTNG_COMMON_BYTECODE_H
 
-#include <stdint.h>
-
 #include "common/macros.hpp"
 #include "common/sessiond-comm/sessiond-comm.hpp"
 
+#include <stdint.h>
+
 /*
  * offsets are absolute from start of bytecode.
  */
@@ -44,154 +44,154 @@ struct literal_double {
 } LTTNG_PACKED;
 
 enum bytecode_op {
-       BYTECODE_OP_UNKNOWN                             = 0,
+       BYTECODE_OP_UNKNOWN = 0,
 
-       BYTECODE_OP_RETURN                              = 1,
+       BYTECODE_OP_RETURN = 1,
 
        /* binary */
-       BYTECODE_OP_MUL                                 = 2,
-       BYTECODE_OP_DIV                                 = 3,
-       BYTECODE_OP_MOD                                 = 4,
-       BYTECODE_OP_PLUS                                = 5,
-       BYTECODE_OP_MINUS                               = 6,
-       BYTECODE_OP_BIT_RSHIFT                          = 7,
-       BYTECODE_OP_BIT_LSHIFT                          = 8,
-       BYTECODE_OP_BIT_AND                             = 9,
-       BYTECODE_OP_BIT_OR                              = 10,
-       BYTECODE_OP_BIT_XOR                             = 11,
+       BYTECODE_OP_MUL = 2,
+       BYTECODE_OP_DIV = 3,
+       BYTECODE_OP_MOD = 4,
+       BYTECODE_OP_PLUS = 5,
+       BYTECODE_OP_MINUS = 6,
+       BYTECODE_OP_BIT_RSHIFT = 7,
+       BYTECODE_OP_BIT_LSHIFT = 8,
+       BYTECODE_OP_BIT_AND = 9,
+       BYTECODE_OP_BIT_OR = 10,
+       BYTECODE_OP_BIT_XOR = 11,
 
        /* binary comparators */
-       BYTECODE_OP_EQ                                  = 12,
-       BYTECODE_OP_NE                                  = 13,
-       BYTECODE_OP_GT                                  = 14,
-       BYTECODE_OP_LT                                  = 15,
-       BYTECODE_OP_GE                                  = 16,
-       BYTECODE_OP_LE                                  = 17,
+       BYTECODE_OP_EQ = 12,
+       BYTECODE_OP_NE = 13,
+       BYTECODE_OP_GT = 14,
+       BYTECODE_OP_LT = 15,
+       BYTECODE_OP_GE = 16,
+       BYTECODE_OP_LE = 17,
 
        /* string binary comparator: apply to  */
-       BYTECODE_OP_EQ_STRING                           = 18,
-       BYTECODE_OP_NE_STRING                           = 19,
-       BYTECODE_OP_GT_STRING                           = 20,
-       BYTECODE_OP_LT_STRING                           = 21,
-       BYTECODE_OP_GE_STRING                           = 22,
-       BYTECODE_OP_LE_STRING                           = 23,
+       BYTECODE_OP_EQ_STRING = 18,
+       BYTECODE_OP_NE_STRING = 19,
+       BYTECODE_OP_GT_STRING = 20,
+       BYTECODE_OP_LT_STRING = 21,
+       BYTECODE_OP_GE_STRING = 22,
+       BYTECODE_OP_LE_STRING = 23,
 
        /* s64 binary comparator */
-       BYTECODE_OP_EQ_S64                              = 24,
-       BYTECODE_OP_NE_S64                              = 25,
-       BYTECODE_OP_GT_S64                              = 26,
-       BYTECODE_OP_LT_S64                              = 27,
-       BYTECODE_OP_GE_S64                              = 28,
-       BYTECODE_OP_LE_S64                              = 29,
+       BYTECODE_OP_EQ_S64 = 24,
+       BYTECODE_OP_NE_S64 = 25,
+       BYTECODE_OP_GT_S64 = 26,
+       BYTECODE_OP_LT_S64 = 27,
+       BYTECODE_OP_GE_S64 = 28,
+       BYTECODE_OP_LE_S64 = 29,
 
        /* double binary comparator */
-       BYTECODE_OP_EQ_DOUBLE                           = 30,
-       BYTECODE_OP_NE_DOUBLE                           = 31,
-       BYTECODE_OP_GT_DOUBLE                           = 32,
-       BYTECODE_OP_LT_DOUBLE                           = 33,
-       BYTECODE_OP_GE_DOUBLE                           = 34,
-       BYTECODE_OP_LE_DOUBLE                           = 35,
+       BYTECODE_OP_EQ_DOUBLE = 30,
+       BYTECODE_OP_NE_DOUBLE = 31,
+       BYTECODE_OP_GT_DOUBLE = 32,
+       BYTECODE_OP_LT_DOUBLE = 33,
+       BYTECODE_OP_GE_DOUBLE = 34,
+       BYTECODE_OP_LE_DOUBLE = 35,
 
        /* Mixed S64-double binary comparators */
-       BYTECODE_OP_EQ_DOUBLE_S64                       = 36,
-       BYTECODE_OP_NE_DOUBLE_S64                       = 37,
-       BYTECODE_OP_GT_DOUBLE_S64                       = 38,
-       BYTECODE_OP_LT_DOUBLE_S64                       = 39,
-       BYTECODE_OP_GE_DOUBLE_S64                       = 40,
-       BYTECODE_OP_LE_DOUBLE_S64                       = 41,
-
-       BYTECODE_OP_EQ_S64_DOUBLE                       = 42,
-       BYTECODE_OP_NE_S64_DOUBLE                       = 43,
-       BYTECODE_OP_GT_S64_DOUBLE                       = 44,
-       BYTECODE_OP_LT_S64_DOUBLE                       = 45,
-       BYTECODE_OP_GE_S64_DOUBLE                       = 46,
-       BYTECODE_OP_LE_S64_DOUBLE                       = 47,
+       BYTECODE_OP_EQ_DOUBLE_S64 = 36,
+       BYTECODE_OP_NE_DOUBLE_S64 = 37,
+       BYTECODE_OP_GT_DOUBLE_S64 = 38,
+       BYTECODE_OP_LT_DOUBLE_S64 = 39,
+       BYTECODE_OP_GE_DOUBLE_S64 = 40,
+       BYTECODE_OP_LE_DOUBLE_S64 = 41,
+
+       BYTECODE_OP_EQ_S64_DOUBLE = 42,
+       BYTECODE_OP_NE_S64_DOUBLE = 43,
+       BYTECODE_OP_GT_S64_DOUBLE = 44,
+       BYTECODE_OP_LT_S64_DOUBLE = 45,
+       BYTECODE_OP_GE_S64_DOUBLE = 46,
+       BYTECODE_OP_LE_S64_DOUBLE = 47,
 
        /* unary */
-       BYTECODE_OP_UNARY_PLUS                          = 48,
-       BYTECODE_OP_UNARY_MINUS                         = 49,
-       BYTECODE_OP_UNARY_NOT                           = 50,
-       BYTECODE_OP_UNARY_PLUS_S64                      = 51,
-       BYTECODE_OP_UNARY_MINUS_S64                     = 52,
-       BYTECODE_OP_UNARY_NOT_S64                       = 53,
-       BYTECODE_OP_UNARY_PLUS_DOUBLE                   = 54,
-       BYTECODE_OP_UNARY_MINUS_DOUBLE                  = 55,
-       BYTECODE_OP_UNARY_NOT_DOUBLE                    = 56,
+       BYTECODE_OP_UNARY_PLUS = 48,
+       BYTECODE_OP_UNARY_MINUS = 49,
+       BYTECODE_OP_UNARY_NOT = 50,
+       BYTECODE_OP_UNARY_PLUS_S64 = 51,
+       BYTECODE_OP_UNARY_MINUS_S64 = 52,
+       BYTECODE_OP_UNARY_NOT_S64 = 53,
+       BYTECODE_OP_UNARY_PLUS_DOUBLE = 54,
+       BYTECODE_OP_UNARY_MINUS_DOUBLE = 55,
+       BYTECODE_OP_UNARY_NOT_DOUBLE = 56,
 
        /* logical */
-       BYTECODE_OP_AND                                 = 57,
-       BYTECODE_OP_OR                                  = 58,
+       BYTECODE_OP_AND = 57,
+       BYTECODE_OP_OR = 58,
 
        /* load field ref */
-       BYTECODE_OP_LOAD_FIELD_REF                      = 59,
-       BYTECODE_OP_LOAD_FIELD_REF_STRING               = 60,
-       BYTECODE_OP_LOAD_FIELD_REF_SEQUENCE             = 61,
-       BYTECODE_OP_LOAD_FIELD_REF_S64                  = 62,
-       BYTECODE_OP_LOAD_FIELD_REF_DOUBLE               = 63,
+       BYTECODE_OP_LOAD_FIELD_REF = 59,
+       BYTECODE_OP_LOAD_FIELD_REF_STRING = 60,
+       BYTECODE_OP_LOAD_FIELD_REF_SEQUENCE = 61,
+       BYTECODE_OP_LOAD_FIELD_REF_S64 = 62,
+       BYTECODE_OP_LOAD_FIELD_REF_DOUBLE = 63,
 
        /* load immediate from operand */
-       BYTECODE_OP_LOAD_STRING                         = 64,
-       BYTECODE_OP_LOAD_S64                            = 65,
-       BYTECODE_OP_LOAD_DOUBLE                         = 66,
+       BYTECODE_OP_LOAD_STRING = 64,
+       BYTECODE_OP_LOAD_S64 = 65,
+       BYTECODE_OP_LOAD_DOUBLE = 66,
 
        /* cast */
-       BYTECODE_OP_CAST_TO_S64                         = 67,
-       BYTECODE_OP_CAST_DOUBLE_TO_S64                  = 68,
-       BYTECODE_OP_CAST_NOP                            = 69,
+       BYTECODE_OP_CAST_TO_S64 = 67,
+       BYTECODE_OP_CAST_DOUBLE_TO_S64 = 68,
+       BYTECODE_OP_CAST_NOP = 69,
 
        /* get context ref */
-       BYTECODE_OP_GET_CONTEXT_REF                     = 70,
-       BYTECODE_OP_GET_CONTEXT_REF_STRING              = 71,
-       BYTECODE_OP_GET_CONTEXT_REF_S64                 = 72,
-       BYTECODE_OP_GET_CONTEXT_REF_DOUBLE              = 73,
+       BYTECODE_OP_GET_CONTEXT_REF = 70,
+       BYTECODE_OP_GET_CONTEXT_REF_STRING = 71,
+       BYTECODE_OP_GET_CONTEXT_REF_S64 = 72,
+       BYTECODE_OP_GET_CONTEXT_REF_DOUBLE = 73,
 
        /* load userspace field ref */
-       BYTECODE_OP_LOAD_FIELD_REF_USER_STRING          = 74,
-       BYTECODE_OP_LOAD_FIELD_REF_USER_SEQUENCE        = 75,
+       BYTECODE_OP_LOAD_FIELD_REF_USER_STRING = 74,
+       BYTECODE_OP_LOAD_FIELD_REF_USER_SEQUENCE = 75,
 
        /*
         * load immediate star globbing pattern (literal string)
         * from immediate
         */
-       BYTECODE_OP_LOAD_STAR_GLOB_STRING               = 76,
+       BYTECODE_OP_LOAD_STAR_GLOB_STRING = 76,
 
        /* globbing pattern binary operator: apply to */
-       BYTECODE_OP_EQ_STAR_GLOB_STRING                 = 77,
-       BYTECODE_OP_NE_STAR_GLOB_STRING                 = 78,
+       BYTECODE_OP_EQ_STAR_GLOB_STRING = 77,
+       BYTECODE_OP_NE_STAR_GLOB_STRING = 78,
 
        /*
         * Instructions for recursive traversal through composed types.
         */
-       BYTECODE_OP_GET_CONTEXT_ROOT                    = 79,
-       BYTECODE_OP_GET_APP_CONTEXT_ROOT                = 80,
-       BYTECODE_OP_GET_PAYLOAD_ROOT                    = 81,
-
-       BYTECODE_OP_GET_SYMBOL                          = 82,
-       BYTECODE_OP_GET_SYMBOL_FIELD                    = 83,
-       BYTECODE_OP_GET_INDEX_U16                       = 84,
-       BYTECODE_OP_GET_INDEX_U64                       = 85,
-
-       BYTECODE_OP_LOAD_FIELD                          = 86,
-       BYTECODE_OP_LOAD_FIELD_S8                       = 87,
-       BYTECODE_OP_LOAD_FIELD_S16                      = 88,
-       BYTECODE_OP_LOAD_FIELD_S32                      = 89,
-       BYTECODE_OP_LOAD_FIELD_S64                      = 90,
-       BYTECODE_OP_LOAD_FIELD_U8                       = 91,
-       BYTECODE_OP_LOAD_FIELD_U16                      = 92,
-       BYTECODE_OP_LOAD_FIELD_U32                      = 93,
-       BYTECODE_OP_LOAD_FIELD_U64                      = 94,
-       BYTECODE_OP_LOAD_FIELD_STRING                   = 95,
-       BYTECODE_OP_LOAD_FIELD_SEQUENCE                 = 96,
-       BYTECODE_OP_LOAD_FIELD_DOUBLE                   = 97,
-
-       BYTECODE_OP_UNARY_BIT_NOT                       = 98,
-
-       BYTECODE_OP_RETURN_S64                          = 99,
+       BYTECODE_OP_GET_CONTEXT_ROOT = 79,
+       BYTECODE_OP_GET_APP_CONTEXT_ROOT = 80,
+       BYTECODE_OP_GET_PAYLOAD_ROOT = 81,
+
+       BYTECODE_OP_GET_SYMBOL = 82,
+       BYTECODE_OP_GET_SYMBOL_FIELD = 83,
+       BYTECODE_OP_GET_INDEX_U16 = 84,
+       BYTECODE_OP_GET_INDEX_U64 = 85,
+
+       BYTECODE_OP_LOAD_FIELD = 86,
+       BYTECODE_OP_LOAD_FIELD_S8 = 87,
+       BYTECODE_OP_LOAD_FIELD_S16 = 88,
+       BYTECODE_OP_LOAD_FIELD_S32 = 89,
+       BYTECODE_OP_LOAD_FIELD_S64 = 90,
+       BYTECODE_OP_LOAD_FIELD_U8 = 91,
+       BYTECODE_OP_LOAD_FIELD_U16 = 92,
+       BYTECODE_OP_LOAD_FIELD_U32 = 93,
+       BYTECODE_OP_LOAD_FIELD_U64 = 94,
+       BYTECODE_OP_LOAD_FIELD_STRING = 95,
+       BYTECODE_OP_LOAD_FIELD_SEQUENCE = 96,
+       BYTECODE_OP_LOAD_FIELD_DOUBLE = 97,
+
+       BYTECODE_OP_UNARY_BIT_NOT = 98,
+
+       BYTECODE_OP_RETURN_S64 = 99,
 
        NR_BYTECODE_OPS,
 };
 
-typedef uint8_t bytecode_opcode_t;
+using bytecode_opcode_t = uint8_t;
 
 struct load_op {
        bytecode_opcode_t op;
@@ -214,7 +214,7 @@ struct unary_op {
 /* skip_offset is absolute from start of bytecode */
 struct logical_op {
        bytecode_opcode_t op;
-       uint16_t skip_offset;   /* bytecode insn, if skip second test */
+       uint16_t skip_offset; /* bytecode insn, if skip second test */
 } LTTNG_PACKED;
 
 struct cast_op {
@@ -231,29 +231,23 @@ struct lttng_bytecode_alloc {
 };
 
 int bytecode_init(struct lttng_bytecode_alloc **fb);
-int bytecode_push(struct lttng_bytecode_alloc **fb,
-               const void *data, uint32_t align, uint32_t len);
+int bytecode_push(struct lttng_bytecode_alloc **fb, const void *data, uint32_t align, uint32_t len);
 int bytecode_push_logical(struct lttng_bytecode_alloc **fb,
-               struct logical_op *data, uint32_t align, uint32_t len,
-               uint16_t *skip_offset);
-struct lttng_bytecode *lttng_bytecode_copy(
-               const struct lttng_bytecode *orig_f);
-
-int bytecode_push_get_payload_root(
-               struct lttng_bytecode_alloc **bytecode);
-int bytecode_push_get_context_root(
-               struct lttng_bytecode_alloc **bytecode);
-int bytecode_push_get_app_context_root(
-               struct lttng_bytecode_alloc **bytecode);
-int bytecode_push_get_index_u64(
-               struct lttng_bytecode_alloc **bytecode, uint64_t index);
-int bytecode_push_get_symbol(
-               struct lttng_bytecode_alloc **bytecode,
-               struct lttng_bytecode_alloc **bytecode_reloc,
-               const char *symbol);
-
-static inline
-unsigned int bytecode_get_len(struct lttng_bytecode *bytecode)
+                         struct logical_op *data,
+                         uint32_t align,
+                         uint32_t len,
+                         uint16_t *skip_offset);
+struct lttng_bytecode *lttng_bytecode_copy(const struct lttng_bytecode *orig_f);
+
+int bytecode_push_get_payload_root(struct lttng_bytecode_alloc **bytecode);
+int bytecode_push_get_context_root(struct lttng_bytecode_alloc **bytecode);
+int bytecode_push_get_app_context_root(struct lttng_bytecode_alloc **bytecode);
+int bytecode_push_get_index_u64(struct lttng_bytecode_alloc **bytecode, uint64_t index);
+int bytecode_push_get_symbol(struct lttng_bytecode_alloc **bytecode,
+                            struct lttng_bytecode_alloc **bytecode_reloc,
+                            const char *symbol);
+
+static inline unsigned int bytecode_get_len(struct lttng_bytecode *bytecode)
 {
        return bytecode->len;
 }
index 5bef795589d75c4349cdf05fe31b65a77369698f..efdc38dcc35ced97148d12857d767c013f242666 100644 (file)
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
+
 #include <lttng/channel-internal.hpp>
 #include <lttng/channel.h>
 #include <lttng/constant.h>
 #include <lttng/userspace-probe-internal.hpp>
 
-static enum lttng_error_code flatten_lttng_channels(
-               struct lttng_dynamic_pointer_array *channels,
-               struct lttng_channel **flattened_channels);
+static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer_array *channels,
+                                                   struct lttng_channel **flattened_channels);
 
-static enum lttng_error_code channel_list_create_from_buffer(
-               const struct lttng_buffer_view *buffer,
-               uint32_t count,
-               struct lttng_dynamic_pointer_array *channel_list);
+static enum lttng_error_code
+channel_list_create_from_buffer(const struct lttng_buffer_view *buffer,
+                               uint32_t count,
+                               struct lttng_dynamic_pointer_array *channel_list);
 
 static void channel_list_destructor(void *ptr)
 {
@@ -65,7 +66,7 @@ end:
 /*
  * The channel object is NOT populated.
  */
-struct lttng_channel *lttng_channel_create_internal(void)
+struct lttng_channel *lttng_channel_create_internal()
 {
        struct lttng_channel *local_channel = nullptr, *ret = nullptr;
        struct lttng_channel_extended *extended = nullptr;
@@ -93,7 +94,7 @@ end:
 }
 
 ssize_t lttng_channel_create_from_buffer(const struct lttng_buffer_view *view,
-               struct lttng_channel **channel)
+                                        struct lttng_channel **channel)
 {
        ssize_t ret, offset = 0;
        struct lttng_channel *local_channel = nullptr;
@@ -122,34 +123,29 @@ ssize_t lttng_channel_create_from_buffer(const struct lttng_buffer_view *view,
        /* lttng_trigger_comm header */
        {
                const struct lttng_buffer_view comm_view =
-                               lttng_buffer_view_from_view(view, offset,
-                                               sizeof(*channel_comm));
+                       lttng_buffer_view_from_view(view, offset, sizeof(*channel_comm));
 
                if (!lttng_buffer_view_is_valid(&comm_view)) {
                        ret = -1;
                        goto end;
                }
 
-               channel_comm = (const struct lttng_channel_comm *)
-                                              comm_view.data;
+               channel_comm = (const struct lttng_channel_comm *) comm_view.data;
                offset += sizeof(*channel_comm);
        }
 
        {
                const char *name;
                const struct lttng_buffer_view name_view =
-                               lttng_buffer_view_from_view(view, offset,
-                                               channel_comm->name_len);
+                       lttng_buffer_view_from_view(view, offset, channel_comm->name_len);
 
                name = name_view.data;
-               if (!lttng_buffer_view_contains_string(
-                                   &name_view, name, channel_comm->name_len)) {
+               if (!lttng_buffer_view_contains_string(&name_view, name, channel_comm->name_len)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(local_channel->name, name,
-                               sizeof(local_channel->name));
+               ret = lttng_strncpy(local_channel->name, name, sizeof(local_channel->name));
                if (ret) {
                        goto end;
                }
@@ -164,15 +160,12 @@ ssize_t lttng_channel_create_from_buffer(const struct lttng_buffer_view *view,
        local_channel->attr.overwrite = channel_comm->overwrite;
        local_channel->attr.subbuf_size = channel_comm->subbuf_size;
        local_channel->attr.num_subbuf = channel_comm->num_subbuf;
-       local_channel->attr.switch_timer_interval =
-                       channel_comm->switch_timer_interval;
-       local_channel->attr.read_timer_interval =
-                       channel_comm->read_timer_interval;
+       local_channel->attr.switch_timer_interval = channel_comm->switch_timer_interval;
+       local_channel->attr.read_timer_interval = channel_comm->read_timer_interval;
        local_channel->attr.output = (enum lttng_event_output) channel_comm->output;
        local_channel->attr.tracefile_size = channel_comm->tracefile_size;
        local_channel->attr.tracefile_count = channel_comm->tracefile_count;
-       local_channel->attr.live_timer_interval =
-                       channel_comm->live_timer_interval;
+       local_channel->attr.live_timer_interval = channel_comm->live_timer_interval;
 
        extended->discarded_events = channel_comm->discarded_events;
        extended->lost_packets = channel_comm->lost_packets;
@@ -188,8 +181,7 @@ end:
        return ret;
 }
 
-int lttng_channel_serialize(
-               struct lttng_channel *channel, struct lttng_dynamic_buffer *buf)
+int lttng_channel_serialize(struct lttng_channel *channel, struct lttng_dynamic_buffer *buf)
 {
        int ret;
        size_t name_len;
@@ -219,8 +211,7 @@ int lttng_channel_serialize(
        channel_comm.overwrite = channel->attr.overwrite;
        channel_comm.subbuf_size = channel->attr.subbuf_size;
        channel_comm.num_subbuf = channel->attr.num_subbuf;
-       channel_comm.switch_timer_interval =
-                       channel->attr.switch_timer_interval;
+       channel_comm.switch_timer_interval = channel->attr.switch_timer_interval;
        channel_comm.read_timer_interval = channel->attr.read_timer_interval;
        channel_comm.output = channel->attr.output;
        channel_comm.tracefile_size = channel->attr.tracefile_size;
@@ -234,8 +225,7 @@ int lttng_channel_serialize(
        channel_comm.blocking_timeout = extended->blocking_timeout;
 
        /* Header */
-       ret = lttng_dynamic_buffer_append(
-                       buf, &channel_comm, sizeof(channel_comm));
+       ret = lttng_dynamic_buffer_append(buf, &channel_comm, sizeof(channel_comm));
        if (ret) {
                goto end;
        }
@@ -250,7 +240,7 @@ end:
 }
 
 void lttng_channel_set_default_extended_attr(struct lttng_domain *domain,
-               struct lttng_channel_extended *extended_attr)
+                                            struct lttng_channel_extended *extended_attr)
 {
        assert(domain);
        assert(extended_attr);
@@ -259,26 +249,23 @@ void lttng_channel_set_default_extended_attr(struct lttng_domain *domain,
 
        switch (domain->type) {
        case LTTNG_DOMAIN_KERNEL:
-               extended_attr->monitor_timer_interval =
-                               DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER;
-               extended_attr->blocking_timeout =
-                               DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT;
+               extended_attr->monitor_timer_interval = DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER;
+               extended_attr->blocking_timeout = DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT;
                break;
        case LTTNG_DOMAIN_UST:
                switch (domain->buf_type) {
                case LTTNG_BUFFER_PER_UID:
                        extended_attr->monitor_timer_interval =
-                                       DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER;
-                       extended_attr->blocking_timeout =
-                                       DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT;
+                               DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER;
+                       extended_attr->blocking_timeout = DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT;
                        break;
                case LTTNG_BUFFER_PER_PID:
                default:
                        if (extended_attr) {
                                extended_attr->monitor_timer_interval =
-                                               DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER;
+                                       DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER;
                                extended_attr->blocking_timeout =
-                                               DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT;
+                                       DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT;
                        }
                        break;
                }
@@ -288,10 +275,10 @@ void lttng_channel_set_default_extended_attr(struct lttng_domain *domain,
        }
 }
 
-static enum lttng_error_code channel_list_create_from_buffer(
-               const struct lttng_buffer_view *view,
-               unsigned int count,
-               struct lttng_dynamic_pointer_array *channel_list)
+static enum lttng_error_code
+channel_list_create_from_buffer(const struct lttng_buffer_view *view,
+                               unsigned int count,
+                               struct lttng_dynamic_pointer_array *channel_list)
 {
        enum lttng_error_code ret_code;
        int ret, i;
@@ -304,10 +291,9 @@ static enum lttng_error_code channel_list_create_from_buffer(
                ssize_t channel_size;
                struct lttng_channel *channel = nullptr;
                const struct lttng_buffer_view channel_view =
-                               lttng_buffer_view_from_view(view, offset, -1);
+                       lttng_buffer_view_from_view(view, offset, -1);
 
-               channel_size = lttng_channel_create_from_buffer(
-                               &channel_view, &channel);
+               channel_size = lttng_channel_create_from_buffer(&channel_view, &channel);
                if (channel_size < 0) {
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
@@ -335,7 +321,7 @@ end:
 }
 
 static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer_array *channels,
-               struct lttng_channel **flattened_channels)
+                                                   struct lttng_channel **flattened_channels)
 {
        enum lttng_error_code ret_code;
        int ret, i;
@@ -356,8 +342,7 @@ static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer
         * We must ensure that "local_flattened_channels" is never resized so as
         * to preserve the validity of the flattened objects.
         */
-       ret = lttng_dynamic_buffer_set_capacity(
-                       &local_flattened_channels, storage_req);
+       ret = lttng_dynamic_buffer_set_capacity(&local_flattened_channels, storage_req);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -365,17 +350,17 @@ static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer
 
        /* Start by laying the struct lttng_channel */
        for (i = 0; i < nb_channels; i++) {
-               const auto *element = (const struct lttng_channel *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               channels, i);
+               const auto *element =
+                       (const struct lttng_channel *) lttng_dynamic_pointer_array_get_pointer(
+                               channels, i);
 
                if (!element) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&local_flattened_channels,
-                               element, sizeof(struct lttng_channel));
+               ret = lttng_dynamic_buffer_append(
+                       &local_flattened_channels, element, sizeof(struct lttng_channel));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -384,21 +369,22 @@ static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer
 
        /* Flatten the extended data */
        for (i = 0; i < nb_channels; i++) {
-               const auto *element = (const struct lttng_channel *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               channels, i);
+               const auto *element =
+                       (const struct lttng_channel *) lttng_dynamic_pointer_array_get_pointer(
+                               channels, i);
                /*
                 * Sample the location of the flattened channel we are about
                 * to modify.
                 */
-               auto *channel = (struct lttng_channel *)
-                               (local_flattened_channels.data + (sizeof(struct lttng_channel) * i));
+               auto *channel = (struct lttng_channel *) (local_flattened_channels.data +
+                                                         (sizeof(struct lttng_channel) * i));
                /*
                 * Sample the location of the extended attributes we are about
                 * to add.
                 */
-               const auto *channel_extended = (struct lttng_channel_extended *)
-                               (local_flattened_channels.data + local_flattened_channels.size);
+               const auto *channel_extended =
+                       (struct lttng_channel_extended *) (local_flattened_channels.data +
+                                                          local_flattened_channels.size);
 
                if (!element) {
                        ret_code = LTTNG_ERR_FATAL;
@@ -406,8 +392,8 @@ static enum lttng_error_code flatten_lttng_channels(struct lttng_dynamic_pointer
                }
 
                ret = lttng_dynamic_buffer_append(&local_flattened_channels,
-                               element->attr.extended.ptr,
-                               sizeof(struct lttng_channel_extended));
+                                                 element->attr.extended.ptr,
+                                                 sizeof(struct lttng_channel_extended));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -430,9 +416,7 @@ end:
 }
 
 enum lttng_error_code lttng_channels_create_and_flatten_from_buffer(
-               const struct lttng_buffer_view *view,
-               uint32_t count,
-               struct lttng_channel **channels)
+       const struct lttng_buffer_view *view, uint32_t count, struct lttng_channel **channels)
 {
        enum lttng_error_code ret_code;
        struct lttng_dynamic_pointer_array local_channels;
@@ -442,10 +426,9 @@ enum lttng_error_code lttng_channels_create_and_flatten_from_buffer(
        /* Deserialize the channels */
        {
                const struct lttng_buffer_view channels_view =
-                               lttng_buffer_view_from_view(view, 0, -1);
+                       lttng_buffer_view_from_view(view, 0, -1);
 
-               ret_code = channel_list_create_from_buffer(
-                               &channels_view, count, &local_channels);
+               ret_code = channel_list_create_from_buffer(&channels_view, count, &local_channels);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
index 926ebf36dc75a6a1a5f5c9ff4a98251c64617b68..b784e5c0cd798b2f7bf8cafd0fd5bacf23dafdf3 100644 (file)
@@ -11,8 +11,8 @@
 
 #include "error.hpp"
 #include "macros.hpp"
-#include "runas.hpp"
 #include "readwrite.hpp"
+#include "runas.hpp"
 #include "time.hpp"
 
 #endif /* _COMMON_H */
diff --git a/src/common/compat/compat-fcntl.cpp b/src/common/compat/compat-fcntl.cpp
deleted file mode 100644 (file)
index 13ba512..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2011 David Goulet <dgoulet@efficios.com>
- *
- * SPDX-License-Identifier: LGPL-2.1-only
- *
- */
-
-#define _LGPL_SOURCE
-#include <common/compat/fcntl.hpp>
-#include <common/macros.hpp>
-#include <unistd.h>
-
-#ifdef __linux__
-
-int compat_sync_file_range(int fd, off64_t offset, off64_t nbytes,
-               unsigned int flags)
-{
-#ifdef HAVE_SYNC_FILE_RANGE
-       return sync_file_range(fd, offset, nbytes, flags);
-#else
-       return fdatasync(fd);
-#endif
-}
-
-#endif /* __linux__ */
index cd4bf1769a739c189576716096304dea956aa70a..157e9d4c24e0abd0b656d564d9623a2bad9f2f7f 100644 (file)
@@ -6,76 +6,77 @@
  */
 
 #include <common/compat/directory-handle.hpp>
+#include <common/credentials.hpp>
+#include <common/dynamic-array.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/runas.hpp>
-#include <common/credentials.hpp>
+
 #include <lttng/constant.h>
-#include <common/dynamic-array.hpp>
 
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <dirent.h>
 #include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 #include <unistd.h>
-#include <dirent.h>
 
 /*
  * This compatibility layer shares a common "base" that is implemented
  * in terms of an internal API. This file contains two implementations
  * of the internal API below.
  */
-static
-int lttng_directory_handle_mkdir(
-               const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode);
-static
-int _run_as_mkdir(const struct lttng_directory_handle *handle, const char *path,
-               mode_t mode, uid_t uid, gid_t gid);
-static
-int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode, uid_t uid, gid_t gid);
-static
-int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
-               const char *filename, int flags, mode_t mode);
-static
-int _run_as_open(const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode, uid_t uid, gid_t gid);
-static
-int lttng_directory_handle_unlink(
-               const struct lttng_directory_handle *handle,
-               const char *filename);
-static
-int _run_as_unlink(const struct lttng_directory_handle *handle,
-               const char *filename, uid_t uid, gid_t gid);
-static
-int _lttng_directory_handle_rename(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name);
-static
-int _run_as_rename(const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name, uid_t uid, gid_t gid);
-static
-DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
-               const char *path);
-static
-int lttng_directory_handle_rmdir(
-               const struct lttng_directory_handle *handle, const char *name);
-static
-int _run_as_rmdir(const struct lttng_directory_handle *handle,
-               const char *name, uid_t uid, gid_t gid);
-static
-int _run_as_rmdir_recursive(
-               const struct lttng_directory_handle *handle, const char *name,
-               uid_t uid, gid_t gid, int flags);
-static
-void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle);
-static
-void lttng_directory_handle_release(struct urcu_ref *ref);
+static int lttng_directory_handle_mkdir(const struct lttng_directory_handle *handle,
+                                       const char *path,
+                                       mode_t mode);
+static int _run_as_mkdir(const struct lttng_directory_handle *handle,
+                        const char *path,
+                        mode_t mode,
+                        uid_t uid,
+                        gid_t gid);
+static int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *path,
+                                  mode_t mode,
+                                  uid_t uid,
+                                  gid_t gid);
+static int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
+                                      const char *filename,
+                                      int flags,
+                                      mode_t mode);
+static int _run_as_open(const struct lttng_directory_handle *handle,
+                       const char *filename,
+                       int flags,
+                       mode_t mode,
+                       uid_t uid,
+                       gid_t gid);
+static int lttng_directory_handle_unlink(const struct lttng_directory_handle *handle,
+                                        const char *filename);
+static int _run_as_unlink(const struct lttng_directory_handle *handle,
+                         const char *filename,
+                         uid_t uid,
+                         gid_t gid);
+static int _lttng_directory_handle_rename(const struct lttng_directory_handle *old_handle,
+                                         const char *old_name,
+                                         const struct lttng_directory_handle *new_handle,
+                                         const char *new_name);
+static int _run_as_rename(const struct lttng_directory_handle *old_handle,
+                         const char *old_name,
+                         const struct lttng_directory_handle *new_handle,
+                         const char *new_name,
+                         uid_t uid,
+                         gid_t gid);
+static DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
+                                          const char *path);
+static int lttng_directory_handle_rmdir(const struct lttng_directory_handle *handle,
+                                       const char *name);
+static int
+_run_as_rmdir(const struct lttng_directory_handle *handle, const char *name, uid_t uid, gid_t gid);
+static int _run_as_rmdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *name,
+                                  uid_t uid,
+                                  gid_t gid,
+                                  int flags);
+static void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle);
+static void lttng_directory_handle_release(struct urcu_ref *ref);
 
 #ifdef HAVE_DIRFD
 
@@ -101,19 +102,19 @@ void lttng_directory_handle_release(struct urcu_ref *ref);
 
 struct lttng_directory_handle *lttng_directory_handle_create(const char *path)
 {
-       lttng_directory_handle cwd_handle {};
+       lttng_directory_handle cwd_handle{};
        cwd_handle.dirfd = AT_FDCWD;
 
        /* Open a handle to the CWD if NULL is passed. */
        return lttng_directory_handle_create_from_handle(path, &cwd_handle);
 }
 
-struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
-               const char *path,
-               const struct lttng_directory_handle *ref_handle)
+struct lttng_directory_handle *
+lttng_directory_handle_create_from_handle(const char *path,
+                                         const struct lttng_directory_handle *ref_handle)
 {
        int dirfd;
-       struct lttng_directory_handle *handle = NULL;
+       struct lttng_directory_handle *handle = nullptr;
 
        if (!path) {
                handle = lttng_directory_handle_copy(ref_handle);
@@ -140,11 +141,10 @@ error_close:
        if (close(dirfd)) {
                PERROR("Failed to close directory file descriptor");
        }
-       return NULL;
+       return nullptr;
 }
 
-struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(
-               int dirfd)
+struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(int dirfd)
 {
        int ret;
        struct lttng_directory_handle *handle = zmalloc<lttng_directory_handle>();
@@ -159,7 +159,7 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(
                if (ret) {
                        PERROR("Failed to fstat directory file descriptor %i", dirfd);
                        lttng_directory_handle_release(&handle->ref);
-                       handle = NULL;
+                       handle = nullptr;
                        goto end;
                }
        } else {
@@ -171,12 +171,11 @@ end:
        return handle;
 }
 
-static
-void lttng_directory_handle_release(struct urcu_ref *ref)
+static void lttng_directory_handle_release(struct urcu_ref *ref)
 {
        int ret;
        struct lttng_directory_handle *handle =
-                       lttng::utils::container_of(ref, &lttng_directory_handle::ref);
+               lttng::utils::container_of(ref, &lttng_directory_handle::ref);
 
        if (handle->destroy_cb) {
                handle->destroy_cb(handle, handle->destroy_cb_data);
@@ -194,10 +193,10 @@ end:
        free(handle);
 }
 
-struct lttng_directory_handle *lttng_directory_handle_copy(
-               const struct lttng_directory_handle *handle)
+struct lttng_directory_handle *
+lttng_directory_handle_copy(const struct lttng_directory_handle *handle)
 {
-       struct lttng_directory_handle *new_handle = NULL;
+       struct lttng_directory_handle *new_handle = nullptr;
 
        if (handle->dirfd == AT_FDCWD) {
                new_handle = lttng_directory_handle_create_from_dirfd(AT_FDCWD);
@@ -208,8 +207,7 @@ struct lttng_directory_handle *lttng_directory_handle_copy(
                        PERROR("Failed to duplicate directory file descriptor of directory handle");
                        goto end;
                }
-               new_handle = lttng_directory_handle_create_from_dirfd(
-                               new_dirfd);
+               new_handle = lttng_directory_handle_create_from_dirfd(new_dirfd);
                if (!new_handle && close(new_dirfd)) {
                        PERROR("Failed to close directory file descriptor of directory handle");
                }
@@ -219,107 +217,107 @@ end:
 }
 
 bool lttng_directory_handle_equals(const struct lttng_directory_handle *lhs,
-               const struct lttng_directory_handle *rhs)
+                                  const struct lttng_directory_handle *rhs)
 {
        return lhs->directory_inode == rhs->directory_inode;
 }
 
-static
-void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle)
+static void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle)
 {
        handle->dirfd = -1;
 }
 
 int lttng_directory_handle_stat(const struct lttng_directory_handle *handle,
-               const char *path, struct stat *st)
+                               const char *path,
+                               struct stat *st)
 {
        return fstatat(handle->dirfd, path, st, 0);
 }
 
-bool lttng_directory_handle_uses_fd(
-               const struct lttng_directory_handle *handle)
+bool lttng_directory_handle_uses_fd(const struct lttng_directory_handle *handle)
 {
        return handle->dirfd != AT_FDCWD;
 }
 
-static
-int lttng_directory_handle_mkdir(
-               const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode)
+static int lttng_directory_handle_mkdir(const struct lttng_directory_handle *handle,
+                                       const char *path,
+                                       mode_t mode)
 {
        return mkdirat(handle->dirfd, path, mode);
 }
 
-static
-int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
-               const char *filename, int flags, mode_t mode)
+static int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
+                                      const char *filename,
+                                      int flags,
+                                      mode_t mode)
 {
        return openat(handle->dirfd, filename, flags, mode);
 }
 
-static
-int _run_as_open(const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_open(const struct lttng_directory_handle *handle,
+                       const char *filename,
+                       int flags,
+                       mode_t mode,
+                       uid_t uid,
+                       gid_t gid)
 {
        return run_as_openat(handle->dirfd, filename, flags, mode, uid, gid);
 }
 
-static
-int _run_as_unlink(const struct lttng_directory_handle *handle,
-               const char *filename, uid_t uid, gid_t gid)
+static int _run_as_unlink(const struct lttng_directory_handle *handle,
+                         const char *filename,
+                         uid_t uid,
+                         gid_t gid)
 {
        return run_as_unlinkat(handle->dirfd, filename, uid, gid);
 }
 
-static
-int lttng_directory_handle_unlink(
-               const struct lttng_directory_handle *handle,
-               const char *filename)
+static int lttng_directory_handle_unlink(const struct lttng_directory_handle *handle,
+                                        const char *filename)
 {
        return unlinkat(handle->dirfd, filename, 0);
 }
 
-static
-int _run_as_mkdir(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_mkdir(const struct lttng_directory_handle *handle,
+                        const char *path,
+                        mode_t mode,
+                        uid_t uid,
+                        gid_t gid)
 {
        return run_as_mkdirat(handle->dirfd, path, mode, uid, gid);
 }
 
-static
-int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *path,
+                                  mode_t mode,
+                                  uid_t uid,
+                                  gid_t gid)
 {
        return run_as_mkdirat_recursive(handle->dirfd, path, mode, uid, gid);
 }
 
-static
-int _lttng_directory_handle_rename(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name)
+static int _lttng_directory_handle_rename(const struct lttng_directory_handle *old_handle,
+                                         const char *old_name,
+                                         const struct lttng_directory_handle *new_handle,
+                                         const char *new_name)
 {
-       return renameat(old_handle->dirfd, old_name,
-                       new_handle->dirfd, new_name);
+       return renameat(old_handle->dirfd, old_name, new_handle->dirfd, new_name);
 }
 
-static
-int _run_as_rename(const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name, uid_t uid, gid_t gid)
+static int _run_as_rename(const struct lttng_directory_handle *old_handle,
+                         const char *old_name,
+                         const struct lttng_directory_handle *new_handle,
+                         const char *new_name,
+                         uid_t uid,
+                         gid_t gid)
 {
-       return run_as_renameat(old_handle->dirfd, old_name, new_handle->dirfd,
-                       new_name, uid, gid);
+       return run_as_renameat(old_handle->dirfd, old_name, new_handle->dirfd, new_name, uid, gid);
 }
 
-static
-DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
-               const char *path)
+static DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
+                                          const char *path)
 {
-       DIR *dir_stream = NULL;
+       DIR *dir_stream = nullptr;
        int fd = openat(handle->dirfd, path, O_RDONLY);
 
        if (fd < 0) {
@@ -342,9 +340,8 @@ end:
        return dir_stream;
 }
 
-static
-int lttng_directory_handle_rmdir(
-               const struct lttng_directory_handle *handle, const char *name)
+static int lttng_directory_handle_rmdir(const struct lttng_directory_handle *handle,
+                                       const char *name)
 {
        int ret = unlinkat(handle->dirfd, name, AT_REMOVEDIR);
        if (ret) {
@@ -354,44 +351,44 @@ int lttng_directory_handle_rmdir(
        return ret;
 }
 
-static
-int _run_as_rmdir(const struct lttng_directory_handle *handle,
-               const char *name, uid_t uid, gid_t gid)
+static int
+_run_as_rmdir(const struct lttng_directory_handle *handle, const char *name, uid_t uid, gid_t gid)
 {
        return run_as_rmdirat(handle->dirfd, name, uid, gid);
 }
 
-static
-int _run_as_rmdir_recursive(
-               const struct lttng_directory_handle *handle, const char *name,
-               uid_t uid, gid_t gid, int flags)
+static int _run_as_rmdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *name,
+                                  uid_t uid,
+                                  gid_t gid,
+                                  int flags)
 {
        return run_as_rmdirat_recursive(handle->dirfd, name, uid, gid, flags);
 }
 
 #else /* HAVE_DIRFD */
 
-static
-int get_full_path(const struct lttng_directory_handle *handle,
-               const char *subdirectory, char *fullpath, size_t size)
+static int get_full_path(const struct lttng_directory_handle *handle,
+                        const char *subdirectory,
+                        char *fullpath,
+                        size_t size)
 {
        int ret;
-       const bool subdirectory_is_absolute =
-                       subdirectory && *subdirectory == '/';
-       const char * const base = subdirectory_is_absolute ?
-                       subdirectory : handle->base_path;
-       const char * const end = subdirectory && !subdirectory_is_absolute ?
-                       subdirectory : NULL;
+       const bool subdirectory_is_absolute = subdirectory && *subdirectory == '/';
+       const char *const base = subdirectory_is_absolute ? subdirectory : handle->base_path;
+       const char *const end = subdirectory && !subdirectory_is_absolute ? subdirectory : NULL;
        const size_t base_len = strlen(base);
        const size_t end_len = end ? strlen(end) : 0;
        const bool add_separator_slash = end && base[base_len - 1] != '/';
        const bool add_trailing_slash = end && end[end_len - 1] != '/';
 
-       ret = snprintf(fullpath, size, "%s%s%s%s",
-                       base,
-                       add_separator_slash ? "/" : "",
-                       end ? end : "",
-                       add_trailing_slash ? "/" : "");
+       ret = snprintf(fullpath,
+                      size,
+                      "%s%s%s%s",
+                      base,
+                      add_separator_slash ? "/" : "",
+                      end ? end : "",
+                      add_trailing_slash ? "/" : "");
        if (ret == -1 || ret >= size) {
                ERR("Failed to format subdirectory from directory handle");
                ret = -1;
@@ -402,8 +399,7 @@ end:
        return ret;
 }
 
-static
-struct lttng_directory_handle *_lttng_directory_handle_create(char *path)
+static struct lttng_directory_handle *_lttng_directory_handle_create(char *path)
 {
        struct lttng_directory_handle *handle = zmalloc<lttng_directory_handle>();
 
@@ -416,8 +412,7 @@ end:
        return handle;
 }
 
-struct lttng_directory_handle *lttng_directory_handle_create(
-               const char *path)
+struct lttng_directory_handle *lttng_directory_handle_create(const char *path)
 {
        int ret;
        const char *cwd = "";
@@ -448,11 +443,13 @@ struct lttng_directory_handle *lttng_directory_handle_create(
                add_cwd_slash = cwd[cwd_len - 1] != '/';
        }
 
-       ret = snprintf(handle_buf, sizeof(handle_buf), "%s%s%s%s",
-                       cwd,
-                       add_cwd_slash ? "/" : "",
-                       path ? : "",
-                       add_trailing_slash ? "/" : "");
+       ret = snprintf(handle_buf,
+                      sizeof(handle_buf),
+                      "%s%s%s%s",
+                      cwd,
+                      add_cwd_slash ? "/" : "",
+                      path ?: "",
+                      add_trailing_slash ? "/" : "");
        if (ret == -1 || ret >= LTTNG_PATH_MAX) {
                ERR("Failed to initialize directory handle, failed to format directory path");
                goto end;
@@ -463,9 +460,9 @@ end:
        return new_handle;
 }
 
-struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
-               const char *path,
-               const struct lttng_directory_handle *ref_handle)
+struct lttng_directory_handle *
+lttng_directory_handle_create_from_handle(const char *path,
+                                         const struct lttng_directory_handle *ref_handle)
 {
        int ret;
        size_t path_len, handle_path_len;
@@ -484,14 +481,12 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
                char full_path[LTTNG_PATH_MAX];
 
                /* Best effort for logging purposes. */
-               ret = get_full_path(ref_handle, path, full_path,
-                               sizeof(full_path));
+               ret = get_full_path(ref_handle, path, full_path, sizeof(full_path));
                if (ret) {
                        full_path[0] = '\0';
                }
 
-               ERR("Failed to initialize directory handle to \"%s\": not a directory",
-                               full_path);
+               ERR("Failed to initialize directory handle to \"%s\": not a directory", full_path);
                goto end;
        }
        if (!path) {
@@ -518,11 +513,11 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
 
        add_trailing_slash = path[path_len - 1] != '/';
 
-       handle_path_len = strlen(ref_handle->base_path) + path_len +
-                       !!add_trailing_slash;
+       handle_path_len = strlen(ref_handle->base_path) + path_len + !!add_trailing_slash;
        if (handle_path_len >= LTTNG_PATH_MAX) {
                ERR("Failed to initialize directory handle as the resulting path's length (%zu bytes) exceeds the maximal allowed length (%d bytes)",
-                               handle_path_len, LTTNG_PATH_MAX);
+                   handle_path_len,
+                   LTTNG_PATH_MAX);
                goto end;
        }
        new_path = zmalloc<char>(handle_path_len);
@@ -531,10 +526,11 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
                goto end;
        }
 
-       ret = sprintf(new_handle->base_path, "%s%s%s",
-                       ref_handle->base_path,
-                       path,
-                       add_trailing_slash ? "/" : "");
+       ret = sprintf(new_handle->base_path,
+                     "%s%s%s",
+                     ref_handle->base_path,
+                     path,
+                     add_trailing_slash ? "/" : "");
        if (ret == -1 || ret >= handle_path_len) {
                ERR("Failed to initialize directory handle: path formatting failed");
                goto end;
@@ -546,26 +542,24 @@ end:
        return new_handle;
 }
 
-struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(
-               int dirfd)
+struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(int dirfd)
 {
        LTTNG_ASSERT(dirfd == AT_FDCWD);
        return lttng_directory_handle_create(NULL);
 }
 
-static
-void lttng_directory_handle_release(struct urcu_ref *ref)
+static void lttng_directory_handle_release(struct urcu_ref *ref)
 {
        struct lttng_directory_handle *handle =
-                       lttng::utils::container_of(ref, &lttng_directory_handle::ref);
+               lttng::utils::container_of(ref, &lttng_directory_handle::ref);
 
        free(handle->base_path);
        lttng_directory_handle_invalidate(handle);
        free(handle);
 }
 
-struct lttng_directory_handle *lttng_directory_handle_copy(
-               const struct lttng_directory_handle *handle)
+struct lttng_directory_handle *
+lttng_directory_handle_copy(const struct lttng_directory_handle *handle)
 {
        struct lttng_directory_handle *new_handle = NULL;
        char *new_path = NULL;
@@ -582,19 +576,19 @@ end:
 }
 
 bool lttng_directory_handle_equals(const struct lttng_directory_handle *lhs,
-               const struct lttng_directory_handle *rhs)
+                                  const struct lttng_directory_handle *rhs)
 {
        return strcmp(lhs->base_path, rhs->base_path) == 0;
 }
 
-static
-void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle)
+static void lttng_directory_handle_invalidate(struct lttng_directory_handle *handle)
 {
        handle->base_path = NULL;
 }
 
 int lttng_directory_handle_stat(const struct lttng_directory_handle *handle,
-               const char *subdirectory, struct stat *st)
+                               const char *subdirectory,
+                               struct stat *st)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -610,15 +604,14 @@ end:
        return ret;
 }
 
-bool lttng_directory_handle_uses_fd(
-               const struct lttng_directory_handle *handle)
+bool lttng_directory_handle_uses_fd(const struct lttng_directory_handle *handle)
 {
        return false;
 }
 
-static
-int lttng_directory_handle_mkdir(const struct lttng_directory_handle *handle,
-               const char *subdirectory, mode_t mode)
+static int lttng_directory_handle_mkdir(const struct lttng_directory_handle *handle,
+                                       const char *subdirectory,
+                                       mode_t mode)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -634,9 +627,10 @@ end:
        return ret;
 }
 
-static
-int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
-               const char *filename, int flags, mode_t mode)
+static int lttng_directory_handle_open(const struct lttng_directory_handle *handle,
+                                      const char *filename,
+                                      int flags,
+                                      mode_t mode)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -652,10 +646,8 @@ end:
        return ret;
 }
 
-static
-int lttng_directory_handle_unlink(
-               const struct lttng_directory_handle *handle,
-               const char *filename)
+static int lttng_directory_handle_unlink(const struct lttng_directory_handle *handle,
+                                        const char *filename)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -671,9 +663,11 @@ end:
        return ret;
 }
 
-static
-int _run_as_mkdir(const struct lttng_directory_handle *handle, const char *path,
-               mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_mkdir(const struct lttng_directory_handle *handle,
+                        const char *path,
+                        mode_t mode,
+                        uid_t uid,
+                        gid_t gid)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -689,10 +683,12 @@ end:
        return ret;
 }
 
-static
-int _run_as_open(const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_open(const struct lttng_directory_handle *handle,
+                       const char *filename,
+                       int flags,
+                       mode_t mode,
+                       uid_t uid,
+                       gid_t gid)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -708,9 +704,10 @@ end:
        return ret;
 }
 
-static
-int _run_as_unlink(const struct lttng_directory_handle *handle,
-               const char *filename, uid_t uid, gid_t gid)
+static int _run_as_unlink(const struct lttng_directory_handle *handle,
+                         const char *filename,
+                         uid_t uid,
+                         gid_t gid)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -726,9 +723,11 @@ end:
        return ret;
 }
 
-static
-int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode, uid_t uid, gid_t gid)
+static int _run_as_mkdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *path,
+                                  mode_t mode,
+                                  uid_t uid,
+                                  gid_t gid)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -744,25 +743,21 @@ end:
        return ret;
 }
 
-static
-int _lttng_directory_handle_rename(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name)
+static int _lttng_directory_handle_rename(const struct lttng_directory_handle *old_handle,
+                                         const char *old_name,
+                                         const struct lttng_directory_handle *new_handle,
+                                         const char *new_name)
 {
        int ret;
        char old_fullpath[LTTNG_PATH_MAX];
        char new_fullpath[LTTNG_PATH_MAX];
 
-       ret = get_full_path(old_handle, old_name, old_fullpath,
-                       sizeof(old_fullpath));
+       ret = get_full_path(old_handle, old_name, old_fullpath, sizeof(old_fullpath));
        if (ret) {
                errno = ENOMEM;
                goto end;
        }
-       ret = get_full_path(new_handle, new_name, new_fullpath,
-                       sizeof(new_fullpath));
+       ret = get_full_path(new_handle, new_name, new_fullpath, sizeof(new_fullpath));
        if (ret) {
                errno = ENOMEM;
                goto end;
@@ -773,24 +768,23 @@ end:
        return ret;
 }
 
-static
-int _run_as_rename(const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name, uid_t uid, gid_t gid)
+static int _run_as_rename(const struct lttng_directory_handle *old_handle,
+                         const char *old_name,
+                         const struct lttng_directory_handle *new_handle,
+                         const char *new_name,
+                         uid_t uid,
+                         gid_t gid)
 {
        int ret;
        char old_fullpath[LTTNG_PATH_MAX];
        char new_fullpath[LTTNG_PATH_MAX];
 
-       ret = get_full_path(old_handle, old_name, old_fullpath,
-                       sizeof(old_fullpath));
+       ret = get_full_path(old_handle, old_name, old_fullpath, sizeof(old_fullpath));
        if (ret) {
                errno = ENOMEM;
                goto end;
        }
-       ret = get_full_path(new_handle, new_name, new_fullpath,
-                       sizeof(new_fullpath));
+       ret = get_full_path(new_handle, new_name, new_fullpath, sizeof(new_fullpath));
        if (ret) {
                errno = ENOMEM;
                goto end;
@@ -801,9 +795,8 @@ end:
        return ret;
 }
 
-static
-DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
-               const char *path)
+static DIR *lttng_directory_handle_opendir(const struct lttng_directory_handle *handle,
+                                          const char *path)
 {
        int ret;
        DIR *dir_stream = NULL;
@@ -820,9 +813,8 @@ end:
        return dir_stream;
 }
 
-static
-int lttng_directory_handle_rmdir(
-               const struct lttng_directory_handle *handle, const char *name)
+static int lttng_directory_handle_rmdir(const struct lttng_directory_handle *handle,
+                                       const char *name)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -838,9 +830,8 @@ end:
        return ret;
 }
 
-static
-int _run_as_rmdir(const struct lttng_directory_handle *handle,
-               const char *name, uid_t uid, gid_t gid)
+static int
+_run_as_rmdir(const struct lttng_directory_handle *handle, const char *name, uid_t uid, gid_t gid)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -856,10 +847,11 @@ end:
        return ret;
 }
 
-static
-int _run_as_rmdir_recursive(
-               const struct lttng_directory_handle *handle, const char *name,
-               uid_t uid, gid_t gid, int flags)
+static int _run_as_rmdir_recursive(const struct lttng_directory_handle *handle,
+                                  const char *name,
+                                  uid_t uid,
+                                  gid_t gid,
+                                  int flags)
 {
        int ret;
        char fullpath[LTTNG_PATH_MAX];
@@ -888,9 +880,9 @@ end:
  *
  * Checking the path for existence allows us to work around this behaviour.
  */
-static
-int create_directory_check_exists(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode)
+static int create_directory_check_exists(const struct lttng_directory_handle *handle,
+                                        const char *path,
+                                        mode_t mode)
 {
        int ret = 0;
        struct stat st;
@@ -919,9 +911,9 @@ end:
        return ret;
 }
 
-static
-int create_directory_recursive(const struct lttng_directory_handle *handle,
-               const char *path, mode_t mode)
+static int create_directory_recursive(const struct lttng_directory_handle *handle,
+                                     const char *path,
+                                     mode_t mode)
 {
        char *p, tmp[LTTNG_PATH_MAX];
        size_t len;
@@ -932,7 +924,8 @@ int create_directory_recursive(const struct lttng_directory_handle *handle,
        ret = lttng_strncpy(tmp, path, sizeof(tmp));
        if (ret) {
                ERR("Failed to create directory: provided path's length (%zu bytes) exceeds the maximal allowed length (%zu bytes)",
-                               strlen(path) + 1, sizeof(tmp));
+                   strlen(path) + 1,
+                   sizeof(tmp));
                goto error;
        }
 
@@ -944,19 +937,16 @@ int create_directory_recursive(const struct lttng_directory_handle *handle,
        for (p = tmp + 1; *p; p++) {
                if (*p == '/') {
                        *p = 0;
-                       if (tmp[strlen(tmp) - 1] == '.' &&
-                                       tmp[strlen(tmp) - 2] == '.' &&
-                                       tmp[strlen(tmp) - 3] == '/') {
-                               ERR("Using '/../' is not permitted in the trace path (%s)",
-                                               tmp);
+                       if (tmp[strlen(tmp) - 1] == '.' && tmp[strlen(tmp) - 2] == '.' &&
+                           tmp[strlen(tmp) - 3] == '/') {
+                               ERR("Using '/../' is not permitted in the trace path (%s)", tmp);
                                ret = -1;
                                goto error;
                        }
                        ret = create_directory_check_exists(handle, tmp, mode);
                        if (ret < 0) {
                                if (errno != EACCES) {
-                                       PERROR("Failed to create directory \"%s\"",
-                                                       path);
+                                       PERROR("Failed to create directory \"%s\"", path);
                                        ret = -errno;
                                        goto error;
                                }
@@ -988,95 +978,97 @@ void lttng_directory_handle_put(struct lttng_directory_handle *handle)
        urcu_ref_put(&handle->ref, lttng_directory_handle_release);
 }
 
-int lttng_directory_handle_create_subdirectory_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory,
-               mode_t mode, const struct lttng_credentials *creds)
+int lttng_directory_handle_create_subdirectory_as_user(const struct lttng_directory_handle *handle,
+                                                      const char *subdirectory,
+                                                      mode_t mode,
+                                                      const struct lttng_credentials *creds)
 {
        int ret;
 
        if (!creds) {
                /* Run as current user. */
-               ret = create_directory_check_exists(handle,
-                               subdirectory, mode);
+               ret = create_directory_check_exists(handle, subdirectory, mode);
        } else {
-               ret = _run_as_mkdir(handle, subdirectory, mode,
-                               lttng_credentials_get_uid(creds),
-                               lttng_credentials_get_gid(creds));
+               ret = _run_as_mkdir(handle,
+                                   subdirectory,
+                                   mode,
+                                   lttng_credentials_get_uid(creds),
+                                   lttng_credentials_get_gid(creds));
        }
 
        return ret;
 }
 
 int lttng_directory_handle_create_subdirectory_recursive_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory_path,
-               mode_t mode, const struct lttng_credentials *creds)
+       const struct lttng_directory_handle *handle,
+       const char *subdirectory_path,
+       mode_t mode,
+       const struct lttng_credentials *creds)
 {
        int ret;
 
        if (!creds) {
                /* Run as current user. */
-               ret = create_directory_recursive(handle,
-                               subdirectory_path, mode);
+               ret = create_directory_recursive(handle, subdirectory_path, mode);
        } else {
-               ret = _run_as_mkdir_recursive(handle, subdirectory_path,
-                               mode, lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds));
+               ret = _run_as_mkdir_recursive(handle,
+                                             subdirectory_path,
+                                             mode,
+                                             lttng_credentials_get_uid(creds),
+                                             lttng_credentials_get_gid(creds));
        }
 
        return ret;
 }
 
-int lttng_directory_handle_create_subdirectory(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory,
-               mode_t mode)
+int lttng_directory_handle_create_subdirectory(const struct lttng_directory_handle *handle,
+                                              const char *subdirectory,
+                                              mode_t mode)
 {
        return lttng_directory_handle_create_subdirectory_as_user(
-                       handle, subdirectory, mode, NULL);
+               handle, subdirectory, mode, nullptr);
 }
 
 int lttng_directory_handle_create_subdirectory_recursive(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory_path,
-               mode_t mode)
+       const struct lttng_directory_handle *handle, const char *subdirectory_path, mode_t mode)
 {
        return lttng_directory_handle_create_subdirectory_recursive_as_user(
-                       handle, subdirectory_path, mode, NULL);
+               handle, subdirectory_path, mode, nullptr);
 }
 
-int lttng_directory_handle_open_file_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode,
-               const struct lttng_credentials *creds)
+int lttng_directory_handle_open_file_as_user(const struct lttng_directory_handle *handle,
+                                            const char *filename,
+                                            int flags,
+                                            mode_t mode,
+                                            const struct lttng_credentials *creds)
 {
        int ret;
 
        if (!creds) {
                /* Run as current user. */
-               ret = lttng_directory_handle_open(handle, filename, flags,
-                               mode);
+               ret = lttng_directory_handle_open(handle, filename, flags, mode);
        } else {
-               ret = _run_as_open(handle, filename, flags, mode,
-                               lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds));
+               ret = _run_as_open(handle,
+                                  filename,
+                                  flags,
+                                  mode,
+                                  lttng_credentials_get_uid(creds),
+                                  lttng_credentials_get_gid(creds));
        }
        return ret;
 }
 
-int lttng_directory_handle_open_file(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode)
+int lttng_directory_handle_open_file(const struct lttng_directory_handle *handle,
+                                    const char *filename,
+                                    int flags,
+                                    mode_t mode)
 {
-       return lttng_directory_handle_open_file_as_user(handle, filename, flags,
-                       mode, NULL);
+       return lttng_directory_handle_open_file_as_user(handle, filename, flags, mode, nullptr);
 }
 
-int lttng_directory_handle_unlink_file_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               const struct lttng_credentials *creds)
+int lttng_directory_handle_unlink_file_as_user(const struct lttng_directory_handle *handle,
+                                              const char *filename,
+                                              const struct lttng_credentials *creds)
 {
        int ret;
 
@@ -1084,61 +1076,60 @@ int lttng_directory_handle_unlink_file_as_user(
                /* Run as current user. */
                ret = lttng_directory_handle_unlink(handle, filename);
        } else {
-               ret = _run_as_unlink(handle, filename, lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds));
+               ret = _run_as_unlink(handle,
+                                    filename,
+                                    lttng_credentials_get_uid(creds),
+                                    lttng_credentials_get_gid(creds));
        }
        return ret;
 }
 
-int lttng_directory_handle_unlink_file(
-               const struct lttng_directory_handle *handle,
-               const char *filename)
+int lttng_directory_handle_unlink_file(const struct lttng_directory_handle *handle,
+                                      const char *filename)
 {
-       return lttng_directory_handle_unlink_file_as_user(handle,
-                       filename, NULL);
+       return lttng_directory_handle_unlink_file_as_user(handle, filename, nullptr);
 }
 
-int lttng_directory_handle_rename(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name)
+int lttng_directory_handle_rename(const struct lttng_directory_handle *old_handle,
+                                 const char *old_name,
+                                 const struct lttng_directory_handle *new_handle,
+                                 const char *new_name)
 {
-       return lttng_directory_handle_rename_as_user(old_handle, old_name,
-                       new_handle, new_name, NULL);
+       return lttng_directory_handle_rename_as_user(
+               old_handle, old_name, new_handle, new_name, nullptr);
 }
 
-int lttng_directory_handle_rename_as_user(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name,
-               const struct lttng_credentials *creds)
+int lttng_directory_handle_rename_as_user(const struct lttng_directory_handle *old_handle,
+                                         const char *old_name,
+                                         const struct lttng_directory_handle *new_handle,
+                                         const char *new_name,
+                                         const struct lttng_credentials *creds)
 {
        int ret;
 
        if (!creds) {
                /* Run as current user. */
-               ret = _lttng_directory_handle_rename(old_handle,
-                               old_name, new_handle, new_name);
+               ret = _lttng_directory_handle_rename(old_handle, old_name, new_handle, new_name);
        } else {
-               ret = _run_as_rename(old_handle, old_name, new_handle,
-                               new_name, lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds));
+               ret = _run_as_rename(old_handle,
+                                    old_name,
+                                    new_handle,
+                                    new_name,
+                                    lttng_credentials_get_uid(creds),
+                                    lttng_credentials_get_gid(creds));
        }
        return ret;
 }
 
-int lttng_directory_handle_remove_subdirectory(
-               const struct lttng_directory_handle *handle,
-               const char *name)
+int lttng_directory_handle_remove_subdirectory(const struct lttng_directory_handle *handle,
+                                              const char *name)
 {
-       return lttng_directory_handle_remove_subdirectory_as_user(handle, name,
-                       NULL);
+       return lttng_directory_handle_remove_subdirectory_as_user(handle, name, nullptr);
 }
 
-int lttng_directory_handle_remove_subdirectory_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               const struct lttng_credentials *creds)
+int lttng_directory_handle_remove_subdirectory_as_user(const struct lttng_directory_handle *handle,
+                                                      const char *name,
+                                                      const struct lttng_credentials *creds)
 {
        int ret;
 
@@ -1146,7 +1137,10 @@ int lttng_directory_handle_remove_subdirectory_as_user(
                /* Run as current user. */
                ret = lttng_directory_handle_rmdir(handle, name);
        } else {
-               ret = _run_as_rmdir(handle, name, lttng_credentials_get_uid(creds), lttng_credentials_get_gid(creds));
+               ret = _run_as_rmdir(handle,
+                                   name,
+                                   lttng_credentials_get_uid(creds),
+                                   lttng_credentials_get_gid(creds));
        }
        return ret;
 }
@@ -1161,8 +1155,7 @@ struct rmdir_frame {
 };
 } /* namespace */
 
-static
-void rmdir_frame_fini(void *data)
+static void rmdir_frame_fini(void *data)
 {
        int ret;
        struct rmdir_frame *frame = (rmdir_frame *) data;
@@ -1173,9 +1166,8 @@ void rmdir_frame_fini(void *data)
        }
 }
 
-static
-int remove_directory_recursive(const struct lttng_directory_handle *handle,
-               const char *path, int flags)
+static int
+remove_directory_recursive(const struct lttng_directory_handle *handle, const char *path, int flags)
 {
        int ret;
        struct lttng_dynamic_array frames;
@@ -1190,19 +1182,18 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
        const char separator = '/';
 
        lttng_dynamic_buffer_init(&current_path);
-       lttng_dynamic_array_init(&frames, sizeof(struct rmdir_frame),
-                       rmdir_frame_fini);
+       lttng_dynamic_array_init(&frames, sizeof(struct rmdir_frame), rmdir_frame_fini);
 
-       if (flags & ~(LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG |
-                                   LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG)) {
+       if (flags &
+           ~(LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG |
+             LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG)) {
                ERR("Unknown flags %d", flags);
                ret = -1;
                goto end;
        }
 
        if (!initial_frame.dir) {
-               if (flags & LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG &&
-                               errno == ENOENT) {
+               if (flags & LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG && errno == ENOENT) {
                        DBG("Cannot rmdir \"%s\": root does not exist", path);
                        ret = 0;
                        goto end;
@@ -1220,8 +1211,7 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &current_path, path, initial_frame.path_size);
+       ret = lttng_dynamic_buffer_append(&current_path, path, initial_frame.path_size);
        if (ret) {
                ERR("Failed to set initial path during recursive directory removal");
                ret = -1;
@@ -1231,47 +1221,40 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
        while (lttng_dynamic_array_get_count(&frames) > 0) {
                struct dirent *entry;
                struct rmdir_frame *current_frame =
-                               (rmdir_frame *) lttng_dynamic_array_get_element(
-                                               &frames, current_frame_idx);
+                       (rmdir_frame *) lttng_dynamic_array_get_element(&frames, current_frame_idx);
 
                LTTNG_ASSERT(current_frame->dir);
-               ret = lttng_dynamic_buffer_set_size(
-                               &current_path, current_frame->path_size);
+               ret = lttng_dynamic_buffer_set_size(&current_path, current_frame->path_size);
                LTTNG_ASSERT(!ret);
                current_path.data[current_path.size - 1] = '\0';
 
                while ((entry = readdir(current_frame->dir))) {
                        struct stat st;
 
-                       if (!strcmp(entry->d_name, ".") ||
-                                       !strcmp(entry->d_name, "..")) {
+                       if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
                                continue;
                        }
 
                        /* Set current_path to the entry's path. */
-                       ret = lttng_dynamic_buffer_set_size(
-                                       &current_path, current_path.size - 1);
+                       ret = lttng_dynamic_buffer_set_size(&current_path, current_path.size - 1);
                        LTTNG_ASSERT(!ret);
-                       ret = lttng_dynamic_buffer_append(&current_path,
-                                       &separator, sizeof(separator));
+                       ret = lttng_dynamic_buffer_append(
+                               &current_path, &separator, sizeof(separator));
                        if (ret) {
                                goto end;
                        }
-                       ret = lttng_dynamic_buffer_append(&current_path,
-                                       entry->d_name,
-                                       strlen(entry->d_name) + 1);
+                       ret = lttng_dynamic_buffer_append(
+                               &current_path, entry->d_name, strlen(entry->d_name) + 1);
                        if (ret) {
                                goto end;
                        }
 
-                       if (lttng_directory_handle_stat(
-                                           handle, current_path.data, &st)) {
+                       if (lttng_directory_handle_stat(handle, current_path.data, &st)) {
                                if ((flags & LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG) &&
-                                               errno == ENOENT) {
+                                   errno == ENOENT) {
                                        break;
                                }
-                               PERROR("Failed to stat \"%s\"",
-                                               current_path.data);
+                               PERROR("Failed to stat \"%s\"", current_path.data);
                                ret = -1;
                                goto end;
                        }
@@ -1283,23 +1266,22 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
                                } else {
                                        /* Not empty, abort. */
                                        DBG("Directory \"%s\" is not empty; refusing to remove directory",
-                                                       current_path.data);
+                                           current_path.data);
                                        ret = -1;
                                        goto end;
                                }
                        } else {
                                struct rmdir_frame new_frame = {
                                        .parent_frame_idx = (ssize_t) current_frame_idx,
-                                       .dir = lttng_directory_handle_opendir(
-                                                       handle,
-                                                       current_path.data),
+                                       .dir = lttng_directory_handle_opendir(handle,
+                                                                             current_path.data),
                                        .empty = true,
                                        .path_size = current_path.size,
                                };
 
                                if (!new_frame.dir) {
                                        if (flags & LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG &&
-                                                       errno == ENOENT) {
+                                           errno == ENOENT) {
                                                DBG("Non-existing directory stream during recursive directory removal");
                                                break;
                                        } else {
@@ -1308,8 +1290,7 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
                                                goto end;
                                        }
                                }
-                               ret = lttng_dynamic_array_add_element(
-                                               &frames, &new_frame);
+                               ret = lttng_dynamic_array_add_element(&frames, &new_frame);
                                if (ret) {
                                        ERR("Failed to push context frame during recursive directory removal");
                                        rmdir_frame_fini(&new_frame);
@@ -1326,13 +1307,12 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
 
                /* Pop rmdir frame. */
                if (current_frame->empty) {
-                       ret = lttng_directory_handle_rmdir(
-                                       handle, current_path.data);
+                       ret = lttng_directory_handle_rmdir(handle, current_path.data);
                        if (ret) {
                                if ((flags & LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG) ||
-                                               errno != ENOENT) {
+                                   errno != ENOENT) {
                                        PERROR("Failed to remove \"%s\" during recursive directory removal",
-                                                       current_path.data);
+                                              current_path.data);
                                        goto end;
                                }
                                DBG("Non-existing directory stream during recursive directory removal");
@@ -1340,13 +1320,12 @@ int remove_directory_recursive(const struct lttng_directory_handle *handle,
                } else if (current_frame->parent_frame_idx >= 0) {
                        struct rmdir_frame *parent_frame;
 
-                       parent_frame = (rmdir_frame *) lttng_dynamic_array_get_element(&frames,
-                                       current_frame->parent_frame_idx);
+                       parent_frame = (rmdir_frame *) lttng_dynamic_array_get_element(
+                               &frames, current_frame->parent_frame_idx);
                        LTTNG_ASSERT(parent_frame);
                        parent_frame->empty = false;
                }
-               ret = lttng_dynamic_array_remove_element(
-                               &frames, current_frame_idx);
+               ret = lttng_dynamic_array_remove_element(&frames, current_frame_idx);
                if (ret) {
                        ERR("Failed to pop context frame during recursive directory removal");
                        goto end;
@@ -1360,19 +1339,17 @@ end:
 }
 
 int lttng_directory_handle_remove_subdirectory_recursive(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               int flags)
+       const struct lttng_directory_handle *handle, const char *name, int flags)
 {
        return lttng_directory_handle_remove_subdirectory_recursive_as_user(
-                       handle, name, NULL, flags);
+               handle, name, nullptr, flags);
 }
 
 int lttng_directory_handle_remove_subdirectory_recursive_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               const struct lttng_credentials *creds,
-               int flags)
+       const struct lttng_directory_handle *handle,
+       const char *name,
+       const struct lttng_credentials *creds,
+       int flags)
 {
        int ret;
 
@@ -1380,8 +1357,11 @@ int lttng_directory_handle_remove_subdirectory_recursive_as_user(
                /* Run as current user. */
                ret = remove_directory_recursive(handle, name, flags);
        } else {
-               ret = _run_as_rmdir_recursive(handle, name, lttng_credentials_get_uid(creds),
-                               lttng_credentials_get_gid(creds), flags);
+               ret = _run_as_rmdir_recursive(handle,
+                                             name,
+                                             lttng_credentials_get_uid(creds),
+                                             lttng_credentials_get_gid(creds),
+                                             flags);
        }
        return ret;
 }
index 0f969554d79ae774bd03be16d177a9399919eef7..108ec4c862d0479280837d62b875361dc0afff45 100644 (file)
@@ -10,6 +10,7 @@
 
 #include <common/credentials.hpp>
 #include <common/macros.hpp>
+
 #include <sys/stat.h>
 #include <urcu/ref.h>
 
@@ -29,8 +30,7 @@ enum lttng_directory_handle_rmdir_recursive_flags {
 
 struct lttng_directory_handle;
 
-typedef void (*lttng_directory_handle_destroy_cb)(
-               struct lttng_directory_handle *handle, void *data);
+using lttng_directory_handle_destroy_cb = void (*)(struct lttng_directory_handle *, void *);
 
 struct lttng_directory_handle {
        struct urcu_ref ref;
@@ -40,9 +40,7 @@ struct lttng_directory_handle {
        void *destroy_cb_data;
 };
 
-static inline
-int lttng_directory_handle_get_dirfd(
-               const struct lttng_directory_handle *handle)
+static inline int lttng_directory_handle_get_dirfd(const struct lttng_directory_handle *handle)
 {
        return handle->dirfd;
 }
@@ -61,8 +59,7 @@ struct lttng_directory_handle {
  * The reference to the directory handle must be released using
  * lttng_directory_handle_put().
  */
-struct lttng_directory_handle *lttng_directory_handle_create(
-               const char *path);
+struct lttng_directory_handle *lttng_directory_handle_create(const char *path);
 
 /*
  * Create a new directory handle to a path relative to an existing handle.
@@ -77,9 +74,9 @@ struct lttng_directory_handle *lttng_directory_handle_create(
  * The reference to the directory handle must be released using
  * lttng_directory_handle_put().
  */
-struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
-               const char *path,
-               const struct lttng_directory_handle *ref_handle);
+struct lttng_directory_handle *
+lttng_directory_handle_create_from_handle(const char *path,
+                                         const struct lttng_directory_handle *ref_handle);
 
 /*
  * Create a new directory handle from an existing directory fd.
@@ -91,8 +88,7 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_handle(
  * The reference to the directory handle must be released using
  * lttng_directory_handle_put().
  */
-struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(
-               int dirfd);
+struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(int dirfd);
 
 /*
  * Copy a directory handle.
@@ -100,8 +96,8 @@ struct lttng_directory_handle *lttng_directory_handle_create_from_dirfd(
  * The reference to the directory handle must be released using
  * lttng_directory_handle_put().
  */
-struct lttng_directory_handle *lttng_directory_handle_copy(
-               const struct lttng_directory_handle *handle);
+struct lttng_directory_handle *
+lttng_directory_handle_copy(const struct lttng_directory_handle *handle);
 
 /*
  * Acquire a reference to a directory handle.
@@ -116,105 +112,97 @@ void lttng_directory_handle_put(struct lttng_directory_handle *handle);
 /*
  * Create a subdirectory relative to a directory handle.
  */
-int lttng_directory_handle_create_subdirectory(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory,
-               mode_t mode);
+int lttng_directory_handle_create_subdirectory(const struct lttng_directory_handle *handle,
+                                              const char *subdirectory,
+                                              mode_t mode);
 
 /*
  * Create a subdirectory relative to a directory handle
  * as a given user.
  */
-int lttng_directory_handle_create_subdirectory_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory,
-               mode_t mode, const struct lttng_credentials *creds);
+int lttng_directory_handle_create_subdirectory_as_user(const struct lttng_directory_handle *handle,
+                                                      const char *subdirectory,
+                                                      mode_t mode,
+                                                      const struct lttng_credentials *creds);
 
 /*
  * Recursively create a directory relative to a directory handle.
  */
 int lttng_directory_handle_create_subdirectory_recursive(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory_path,
-               mode_t mode);
+       const struct lttng_directory_handle *handle, const char *subdirectory_path, mode_t mode);
 
 /*
  * Recursively create a directory relative to a directory handle
  * as a given user.
  */
 int lttng_directory_handle_create_subdirectory_recursive_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *subdirectory_path,
-               mode_t mode, const struct lttng_credentials *creds);
+       const struct lttng_directory_handle *handle,
+       const char *subdirectory_path,
+       mode_t mode,
+       const struct lttng_credentials *creds);
 
 /*
  * Open a file descriptor to a path relative to a directory handle.
  */
-int lttng_directory_handle_open_file(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode);
+int lttng_directory_handle_open_file(const struct lttng_directory_handle *handle,
+                                    const char *filename,
+                                    int flags,
+                                    mode_t mode);
 
 /*
  * Open a file descriptor to a path relative to a directory handle
  * as a given user.
  */
-int lttng_directory_handle_open_file_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               int flags, mode_t mode,
-               const struct lttng_credentials *creds);
+int lttng_directory_handle_open_file_as_user(const struct lttng_directory_handle *handle,
+                                            const char *filename,
+                                            int flags,
+                                            mode_t mode,
+                                            const struct lttng_credentials *creds);
 
 /*
  * Unlink a file to a path relative to a directory handle.
  */
-int lttng_directory_handle_unlink_file(
-               const struct lttng_directory_handle *handle,
-               const char *filename);
+int lttng_directory_handle_unlink_file(const struct lttng_directory_handle *handle,
+                                      const char *filename);
 
 /*
  * Unlink a file to a path relative to a directory handle as a given user.
  */
-int lttng_directory_handle_unlink_file_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *filename,
-               const struct lttng_credentials *creds);
+int lttng_directory_handle_unlink_file_as_user(const struct lttng_directory_handle *handle,
+                                              const char *filename,
+                                              const struct lttng_credentials *creds);
 
 /*
  * Rename a file from a path relative to a directory handle to a new
  * name relative to another directory handle.
  */
-int lttng_directory_handle_rename(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name);
+int lttng_directory_handle_rename(const struct lttng_directory_handle *old_handle,
+                                 const char *old_name,
+                                 const struct lttng_directory_handle *new_handle,
+                                 const char *new_name);
 
 /*
  * Rename a file from a path relative to a directory handle to a new
  * name relative to another directory handle as a given user.
  */
-int lttng_directory_handle_rename_as_user(
-               const struct lttng_directory_handle *old_handle,
-               const char *old_name,
-               const struct lttng_directory_handle *new_handle,
-               const char *new_name,
-               const struct lttng_credentials *creds);
+int lttng_directory_handle_rename_as_user(const struct lttng_directory_handle *old_handle,
+                                         const char *old_name,
+                                         const struct lttng_directory_handle *new_handle,
+                                         const char *new_name,
+                                         const struct lttng_credentials *creds);
 
 /*
  * Remove a subdirectory relative to a directory handle.
  */
-int lttng_directory_handle_remove_subdirectory(
-               const struct lttng_directory_handle *handle,
-               const char *name);
+int lttng_directory_handle_remove_subdirectory(const struct lttng_directory_handle *handle,
+                                              const char *name);
 
 /*
  * Remove a subdirectory relative to a directory handle as a given user.
  */
-int lttng_directory_handle_remove_subdirectory_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               const struct lttng_credentials *creds);
+int lttng_directory_handle_remove_subdirectory_as_user(const struct lttng_directory_handle *handle,
+                                                      const char *name,
+                                                      const struct lttng_credentials *creds);
 
 /*
  * Remove a subdirectory and remove its contents if it only
@@ -222,8 +210,7 @@ int lttng_directory_handle_remove_subdirectory_as_user(
  * @flags: enum lttng_directory_handle_rmdir_recursive_flags
  */
 int lttng_directory_handle_remove_subdirectory_recursive(
-               const struct lttng_directory_handle *handle,
-               const char *name, int flags);
+       const struct lttng_directory_handle *handle, const char *name, int flags);
 
 /*
  * Remove a subdirectory and remove its contents if it only
@@ -231,25 +218,23 @@ int lttng_directory_handle_remove_subdirectory_recursive(
  * @flags: enum lttng_directory_handle_rmdir_recursive_flags
  */
 int lttng_directory_handle_remove_subdirectory_recursive_as_user(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               const struct lttng_credentials *creds,
-               int flags);
+       const struct lttng_directory_handle *handle,
+       const char *name,
+       const struct lttng_credentials *creds,
+       int flags);
 
 /*
  * stat() a file relative to a directory handle.
  */
-int lttng_directory_handle_stat(
-               const struct lttng_directory_handle *handle,
-               const char *name,
-               struct stat *stat_buf);
+int lttng_directory_handle_stat(const struct lttng_directory_handle *handle,
+                               const char *name,
+                               struct stat *stat_buf);
 
 /*
  * Returns true if this directory handle is backed by a file
  * descriptor, false otherwise.
  */
-bool lttng_directory_handle_uses_fd(
-               const struct lttng_directory_handle *handle);
+bool lttng_directory_handle_uses_fd(const struct lttng_directory_handle *handle);
 
 /*
  * Compare two directory handles.
@@ -257,7 +242,6 @@ bool lttng_directory_handle_uses_fd(
  * Returns true if the two directory handles are equal, false otherwise.
  */
 bool lttng_directory_handle_equals(const struct lttng_directory_handle *lhs,
-               const struct lttng_directory_handle *rhs);
-
+                                  const struct lttng_directory_handle *rhs);
 
 #endif /* _COMPAT_PATH_HANDLE_H */
index b760ed2db7d3f245e051e8c8de7585dcfd87c054..d2dc5ed60819f07d21f58213c43b8f6c0d0a6c8e 100644 (file)
 #include <dirent.h>
 
 #ifdef HAVE_DIRFD
-static inline
-int lttng_dirfd(DIR *dir) {
+static inline int lttng_dirfd(DIR *dir)
+{
        return dirfd(dir);
 }
 #else
-# ifndef __XOPEN_OR_POSIX
-static inline
-int lttng_dirfd(DIR *dir) {
+#ifndef __XOPEN_OR_POSIX
+static inline int lttng_dirfd(DIR *dir)
+{
        return dir->dd_fd;
 }
-# else
-static inline
-int lttng_dirfd(DIR *dir) {
+#else
+static inline int lttng_dirfd(DIR *dir)
+{
        return dir->d_fd;
 }
-# endif
+#endif
 #endif
 
 #endif /* _COMPAT_DIRENT_H */
index ff383763461f19e32d76439275755f27524ea5a3..642e23b0c433cd7bd0765c961e7a97fdd2b6cb98 100644 (file)
@@ -38,8 +38,8 @@
 #define _COMPAT_ENDIAN_H
 
 #if defined(__linux__) || defined(__CYGWIN__)
-#include <endian.h>
 #include <byteswap.h>
+#include <endian.h>
 
 /*
  * htobe/betoh are not defined for glibc <2.9, so add them
  */
 #ifdef __USE_BSD
 /* Conversion interfaces. */
-# include <byteswap.h>
-
-# if __BYTE_ORDER == __LITTLE_ENDIAN
-#  ifndef htobe16
-#   define htobe16(x) __bswap_16(x)
-#  endif
-#  ifndef htole16
-#   define htole16(x) (x)
-#  endif
-#  ifndef be16toh
-#   define be16toh(x) __bswap_16(x)
-#  endif
-#  ifndef le16toh
-#   define le16toh(x) (x)
-#  endif
-
-#  ifndef htobe32
-#   define htobe32(x) __bswap_32(x)
-#  endif
-#  ifndef htole32
-#   define htole32(x) (x)
-#  endif
-#  ifndef be32toh
-#   define be32toh(x) __bswap_32(x)
-#  endif
-#  ifndef le32toh
-#   define le32toh(x) (x)
-#  endif
-
-#  ifndef htobe64
-#   define htobe64(x) __bswap_64(x)
-#  endif
-#  ifndef htole64
-#   define htole64(x) (x)
-#  endif
-#  ifndef be64toh
-#   define be64toh(x) __bswap_64(x)
-#  endif
-#  ifndef le64toh
-#   define le64toh(x) (x)
-#  endif
-
-# else /* __BYTE_ORDER == __LITTLE_ENDIAN */
-#  ifndef htobe16
-#   define htobe16(x) (x)
-#  endif
-#  ifndef htole16
-#   define htole16(x) __bswap_16(x)
-#  endif
-#  ifndef be16toh
-#   define be16toh(x) (x)
-#  endif
-#  ifndef le16toh
-#   define le16toh(x) __bswap_16(x)
-#  endif
-
-#  ifndef htobe32
-#   define htobe32(x) (x)
-#  endif
-#  ifndef htole32
-#   define htole32(x) __bswap_32(x)
-#  endif
-#  ifndef be32toh
-#   define be32toh(x) (x)
-#  endif
-#  ifndef le32toh
-#   define le32toh(x) __bswap_32(x)
-#  endif
-
-#  ifndef htobe64
-#   define htobe64(x) (x)
-#  endif
-#  ifndef htole64
-#   define htole64(x) __bswap_64(x)
-#  endif
-#  ifndef be64toh
-#   define be64toh(x) (x)
-#  endif
-#  ifndef le64toh
-#   define le64toh(x) __bswap_64(x)
-#  endif
-
-# endif /* __BYTE_ORDER == __LITTLE_ENDIAN */
+#include <byteswap.h>
+
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#ifndef htobe16
+#define htobe16(x) __bswap_16(x)
+#endif
+#ifndef htole16
+#define htole16(x) (x)
+#endif
+#ifndef be16toh
+#define be16toh(x) __bswap_16(x)
+#endif
+#ifndef le16toh
+#define le16toh(x) (x)
+#endif
+
+#ifndef htobe32
+#define htobe32(x) __bswap_32(x)
+#endif
+#ifndef htole32
+#define htole32(x) (x)
+#endif
+#ifndef be32toh
+#define be32toh(x) __bswap_32(x)
+#endif
+#ifndef le32toh
+#define le32toh(x) (x)
+#endif
+
+#ifndef htobe64
+#define htobe64(x) __bswap_64(x)
+#endif
+#ifndef htole64
+#define htole64(x) (x)
+#endif
+#ifndef be64toh
+#define be64toh(x) __bswap_64(x)
+#endif
+#ifndef le64toh
+#define le64toh(x) (x)
+#endif
+
+#else /* __BYTE_ORDER == __LITTLE_ENDIAN */
+#ifndef htobe16
+#define htobe16(x) (x)
+#endif
+#ifndef htole16
+#define htole16(x) __bswap_16(x)
+#endif
+#ifndef be16toh
+#define be16toh(x) (x)
+#endif
+#ifndef le16toh
+#define le16toh(x) __bswap_16(x)
+#endif
+
+#ifndef htobe32
+#define htobe32(x) (x)
+#endif
+#ifndef htole32
+#define htole32(x) __bswap_32(x)
+#endif
+#ifndef be32toh
+#define be32toh(x) (x)
+#endif
+#ifndef le32toh
+#define le32toh(x) __bswap_32(x)
+#endif
+
+#ifndef htobe64
+#define htobe64(x) (x)
+#endif
+#ifndef htole64
+#define htole64(x) __bswap_64(x)
+#endif
+#ifndef be64toh
+#define be64toh(x) (x)
+#endif
+#ifndef le64toh
+#define le64toh(x) __bswap_64(x)
+#endif
+
+#endif /* __BYTE_ORDER == __LITTLE_ENDIAN */
 #endif /* __USE_BSD */
 
 #elif defined(__FreeBSD__)
 #include <sys/endian.h>
 
-#define bswap_16(x)    bswap16(x)
-#define bswap_32(x)    bswap32(x)
-#define bswap_64(x)    bswap64(x)
+#define bswap_16(x) bswap16(x)
+#define bswap_32(x) bswap32(x)
+#define bswap_64(x) bswap64(x)
 
 #elif defined(__sun__)
 #include <sys/byteorder.h>
 #define __BYTE_ORDER __BIG_ENDIAN
 #endif /* _BIG_ENDIAN */
 
-#define LITTLE_ENDIAN  __LITTLE_ENDIAN
-#define BIG_ENDIAN     __BIG_ENDIAN
-#define BYTE_ORDER     __BYTE_ORDER
+#define LITTLE_ENDIAN __LITTLE_ENDIAN
+#define BIG_ENDIAN    __BIG_ENDIAN
+#define BYTE_ORDER    __BYTE_ORDER
 
 #define betoh16(x) BE_16(x)
 #define letoh16(x) LE_16(x)
 #define be64toh(x) BE_64(x)
 
 #elif defined(__APPLE__)
-# include <machine/endian.h>
-# include <libkern/OSByteOrder.h>
-
-# if BYTE_ORDER == LITTLE_ENDIAN
-#  define htobe16(x) OSSwapConstInt16(x)
-#  define htole16(x) (x)
-#  define be16toh(x) OSSwapConstInt16(x)
-#  define le16toh(x) (x)
-
-#  define htobe32(x) OSSwapConstInt32(x)
-#  define htole32(x) (x)
-#  define be32toh(x) OSSwapConstInt32(x)
-#  define le32toh(x) (x)
-
-#  define htobe64(x) OSSwapConstInt64(x)
-#  define htole64(x) (x)
-#  define be64toh(x) OSSwapConstInt64(x)
-#  define le64toh(x) (x)
-
-# else /* BYTE_ORDER == LITTLE_ENDIAN */
-#  define htobe16(x) (x)
-#  define htole16(x) OSSwapConstInt16(x)
-#  define be16toh(x) (x)
-#  define le16toh(x) OSSwapConstInt16(x)
-
-#  define htobe32(x) (x)
-#  define htole32(x) OSSwapConstInt32(x)
-#  define be32toh(x) (x)
-#  define le32toh(x) OSSwapConstInt32(x)
-
-#  define htobe64(x) (x)
-#  define htole64(x) OSSwapConstInt64(x)
-#  define be64toh(x) (x)
-#  define le64toh(x) OSSwapConstInt64(x)
-# endif
+#include <libkern/OSByteOrder.h>
+#include <machine/endian.h>
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+#define htobe16(x) OSSwapConstInt16(x)
+#define htole16(x) (x)
+#define be16toh(x) OSSwapConstInt16(x)
+#define le16toh(x) (x)
+
+#define htobe32(x) OSSwapConstInt32(x)
+#define htole32(x) (x)
+#define be32toh(x) OSSwapConstInt32(x)
+#define le32toh(x) (x)
+
+#define htobe64(x) OSSwapConstInt64(x)
+#define htole64(x) (x)
+#define be64toh(x) OSSwapConstInt64(x)
+#define le64toh(x) (x)
+
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+#define htobe16(x) (x)
+#define htole16(x) OSSwapConstInt16(x)
+#define be16toh(x) (x)
+#define le16toh(x) OSSwapConstInt16(x)
+
+#define htobe32(x) (x)
+#define htole32(x) OSSwapConstInt32(x)
+#define be32toh(x) (x)
+#define le32toh(x) OSSwapConstInt32(x)
+
+#define htobe64(x) (x)
+#define htole64(x) OSSwapConstInt64(x)
+#define be64toh(x) (x)
+#define le64toh(x) OSSwapConstInt64(x)
+#endif
 
 #else
 #error "Please add support for your OS."
diff --git a/src/common/compat/fcntl.hpp b/src/common/compat/fcntl.hpp
deleted file mode 100644 (file)
index a526ca5..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2011 David Goulet <dgoulet@efficios.com>
- *
- * SPDX-License-Identifier: LGPL-2.1-only
- *
- */
-
-#ifndef _COMPAT_FCNTL_H
-#define _COMPAT_FCNTL_H
-
-#include <fcntl.h>
-#include <sys/types.h>
-
-#include <common/compat/errno.hpp>
-
-#if (defined(__CYGWIN__))
-typedef long long off64_t;
-#endif
-
-#if (defined(__FreeBSD__) || defined(__sun__))
-typedef off64_t loff_t;
-#endif
-
-#ifdef __linux__
-extern int compat_sync_file_range(int fd, off64_t offset, off64_t nbytes,
-               unsigned int flags);
-#define lttng_sync_file_range(fd, offset, nbytes, flags) \
-       compat_sync_file_range(fd, offset, nbytes, flags)
-
-#endif /* __linux__ */
-
-#if (defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__sun__))
-/*
- * Possible flags under Linux. Simply nullify them and avoid wrapper.
- */
-#define SYNC_FILE_RANGE_WAIT_AFTER    0
-#define SYNC_FILE_RANGE_WAIT_BEFORE   0
-#define SYNC_FILE_RANGE_WRITE         0
-
-static inline int lttng_sync_file_range(
-               int fd __attribute__((unused)),
-               off64_t offset __attribute__((unused)),
-               off64_t nbytes __attribute__((unused)),
-               unsigned int flags __attribute__((unused)))
-{
-       return -ENOSYS;
-}
-#endif
-
-#if (defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__sun__))
-/*
- * Possible flags under Linux. Simply nullify them and avoid wrappers.
- */
-#define SPLICE_F_MOVE       0
-#define SPLICE_F_NONBLOCK   0
-#define SPLICE_F_MORE       0
-#define SPLICE_F_GIFT       0
-
-static inline ssize_t splice(
-               int fd_in __attribute__((unused)),
-               loff_t *off_in __attribute__((unused)),
-               int fd_out __attribute__((unused)),
-               loff_t *off_out __attribute__((unused)),
-               size_t len __attribute__((unused)),
-               unsigned int flags __attribute__((unused)))
-{
-       return -ENOSYS;
-}
-#endif
-
-#if !(defined(__linux__) || defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__sun__) || defined(__APPLE__))
-#error "Please add support for your OS."
-#endif /* __linux__ , __FreeBSD__, __CYGWIN__, __sun__, __APPLE__ */
-
-#endif /* _COMPAT_FCNTL_H */
index 7a31fef9e0c2614481c52e1f5df11349d7fc4f9c..d37db05fc72ba53f8e8fcd65244666213876484d 100644 (file)
@@ -8,24 +8,23 @@
  *
  */
 
+#include <common/error.hpp>
+
 #include <stdlib.h>
-#include <unistd.h>
 #include <sys/types.h>
-#include <common/error.hpp>
+#include <unistd.h>
 
-static inline
-int lttng_is_setuid_setgid(void)
+static inline int lttng_is_setuid_setgid()
 {
        return geteuid() != getuid() || getegid() != getgid();
 }
 
-static inline
-char *lttng_secure_getenv(const char *name)
+static inline char *lttng_secure_getenv(const char *name)
 {
        if (lttng_is_setuid_setgid()) {
                WARN("Getting environment variable '%s' from setuid/setgid binary refused for security reasons.",
-                       name);
-               return NULL;
+                    name);
+               return nullptr;
        }
        return getenv(name);
 }
index a8bf7e2d08d8efc3a34fdccad7260d210ce974aa..4d5f4f98f9dccf31b16d78649846ddcf69e34a06 100644 (file)
 #include <netdb.h>
 
 #ifdef HAVE_GETHOSTBYNAME2
-static inline
-struct hostent *lttng_gethostbyname2(const char *name, int af) {
+static inline struct hostent *lttng_gethostbyname2(const char *name, int af)
+{
        return gethostbyname2(name, af);
 }
-#elif HAVE_GETIPNODEBYNAME
-static inline
-struct hostent *lttng_gethostbyname2(const char *name, int af) {
+#elif defined(HAVE_GETIPNODEBYNAME)
+static inline struct hostent *lttng_gethostbyname2(const char *name, int af)
+{
        int unused;
 
        return getipnodebyname(name, af, AI_DEFAULT, &unused);
 }
 #else
-# error "Missing compat for gethostbyname2()"
+#error "Missing compat for gethostbyname2()"
 #endif
 
 #endif /* _COMPAT_NETDB_H */
index 0203ae80db0074d3893f97c0d15558fcf1910e21..235538b42df88da7e1f8f9a9449ab2ace5d4edb6 100644 (file)
@@ -11,7 +11,7 @@
 #ifdef HAVE_PATHS_H
 #include <paths.h>
 #else
-# define _PATH_DEVNULL "/dev/null"
+#define _PATH_DEVNULL "/dev/null"
 #endif
 
 #endif /* _COMPAT_PATHS_H */
index dfe05d59eec70afd3aaf6e9daffe83f733ac5132..52ff0467681e45c416c028715c379b3397084ee9 100644 (file)
@@ -7,22 +7,22 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdlib.h>
-#include <stdbool.h>
+#include "poll.hpp"
 
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/utils.hpp>
 
-#include "poll.hpp"
+#include <stdbool.h>
+#include <stdlib.h>
 
 #ifdef HAVE_EPOLL
 
 #include <fcntl.h>
 #include <limits.h>
-#include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/types.h>
 #include <unistd.h>
 
 /*
@@ -42,22 +42,20 @@ static unsigned int poll_max_size;
  *
  * Return 0 on success or else -1 with the current events pointer untouched.
  */
-static int resize_poll_event(struct lttng_poll_event *events,
-               uint32_t new_size)
+static int resize_poll_event(struct lttng_poll_event *events, uint32_t new_size)
 {
        struct epoll_event *ptr;
 
        LTTNG_ASSERT(events);
 
        ptr = (epoll_event *) realloc(events->events, new_size * sizeof(*ptr));
-       if (ptr == NULL) {
+       if (ptr == nullptr) {
                PERROR("realloc epoll add");
                goto error;
        }
        if (new_size > events->alloc_size) {
                /* Zero newly allocated memory */
-               memset(ptr + events->alloc_size, 0,
-                       (new_size - events->alloc_size) * sizeof(*ptr));
+               memset(ptr + events->alloc_size, 0, (new_size - events->alloc_size) * sizeof(*ptr));
        }
        events->events = ptr;
        events->alloc_size = new_size;
@@ -75,7 +73,7 @@ int compat_epoll_create(struct lttng_poll_event *events, int count, int flags)
 {
        int ret;
 
-       if (events == NULL || count <= 0) {
+       if (events == nullptr || count <= 0) {
                goto error;
        }
 
@@ -101,7 +99,7 @@ int compat_epoll_create(struct lttng_poll_event *events, int count, int flags)
 
        /* This *must* be freed by using lttng_poll_free() */
        events->events = calloc<epoll_event>(count);
-       if (events->events == NULL) {
+       if (events->events == nullptr) {
                PERROR("zmalloc epoll set");
                goto error_close;
        }
@@ -128,7 +126,7 @@ int compat_epoll_add(struct lttng_poll_event *events, int fd, uint32_t req_event
        int ret;
        struct epoll_event ev;
 
-       if (events == NULL || events->events == NULL || fd < 0) {
+       if (events == nullptr || events->events == nullptr || fd < 0) {
                ERR("Bad compat epoll add arguments");
                goto error;
        }
@@ -174,11 +172,11 @@ int compat_epoll_del(struct lttng_poll_event *events, int fd)
 {
        int ret;
 
-       if (events == NULL || fd < 0 || events->nb_fd == 0) {
+       if (events == nullptr || fd < 0 || events->nb_fd == 0) {
                goto error;
        }
 
-       ret = epoll_ctl(events->epfd, EPOLL_CTL_DEL, fd, NULL);
+       ret = epoll_ctl(events->epfd, EPOLL_CTL_DEL, fd, nullptr);
        if (ret < 0) {
                switch (errno) {
                case ENOENT:
@@ -209,7 +207,7 @@ int compat_epoll_mod(struct lttng_poll_event *events, int fd, uint32_t req_event
        int ret;
        struct epoll_event ev;
 
-       if (events == NULL || fd < 0 || events->nb_fd == 0) {
+       if (events == nullptr || fd < 0 || events->nb_fd == 0) {
                goto error;
        }
 
@@ -245,13 +243,12 @@ error:
 /*
  * Wait on epoll set. This is a blocking call of timeout value.
  */
-int compat_epoll_wait(struct lttng_poll_event *events, int timeout,
-               bool interruptible)
+int compat_epoll_wait(struct lttng_poll_event *events, int timeout, bool interruptible)
 {
        int ret;
        uint32_t new_size;
 
-       if (events == NULL || events->events == NULL) {
+       if (events == nullptr || events->events == nullptr) {
                ERR("Wrong arguments in compat_epoll_wait");
                goto error;
        }
@@ -299,7 +296,7 @@ error:
 /*
  * Setup poll set maximum size.
  */
-int compat_epoll_set_max_size(void)
+int compat_epoll_set_max_size()
 {
        int ret, fd, retval = 0;
        ssize_t size_ret;
@@ -362,8 +359,7 @@ static unsigned int poll_max_size;
  *
  * Return 0 on success or else -1 with the current events pointer untouched.
  */
-static int resize_poll_event(struct compat_poll_event_array *array,
-               uint32_t new_size)
+static int resize_poll_event(struct compat_poll_event_array *array, uint32_t new_size)
 {
        struct pollfd *ptr;
 
@@ -381,8 +377,7 @@ static int resize_poll_event(struct compat_poll_event_array *array,
        }
        if (new_size > array->alloc_size) {
                /* Zero newly allocated memory */
-               memset(ptr + array->alloc_size, 0,
-                       (new_size - array->alloc_size) * sizeof(*ptr));
+               memset(ptr + array->alloc_size, 0, (new_size - array->alloc_size) * sizeof(*ptr));
        }
        array->events = ptr;
        array->alloc_size = new_size;
@@ -413,8 +408,7 @@ static int update_current_events(struct lttng_poll_event *events)
                        goto error;
                }
        }
-       memcpy(wait->events, current->events,
-                       current->nb_fd * sizeof(*current->events));
+       memcpy(wait->events, current->events, current->nb_fd * sizeof(*current->events));
 
        /* Update is done. */
        events->need_update = 0;
@@ -480,8 +474,7 @@ error:
 /*
  * Add fd to pollfd data structure with requested events.
  */
-int compat_poll_add(struct lttng_poll_event *events, int fd,
-               uint32_t req_events)
+int compat_poll_add(struct lttng_poll_event *events, int fd, uint32_t req_events)
 {
        int new_size, ret, i;
        struct compat_poll_event_array *current;
@@ -526,14 +519,13 @@ error:
 /*
  * Modify an fd's events..
  */
-int compat_poll_mod(struct lttng_poll_event *events, int fd,
-               uint32_t req_events)
+int compat_poll_mod(struct lttng_poll_event *events, int fd, uint32_t req_events)
 {
        int i;
        struct compat_poll_event_array *current;
 
-       if (events == NULL || events->current.nb_fd == 0 ||
-                       events->current.events == NULL || fd < 0) {
+       if (events == NULL || events->current.nb_fd == 0 || events->current.events == NULL ||
+           fd < 0) {
                ERR("Bad compat poll mod arguments");
                goto error;
        }
@@ -568,8 +560,8 @@ int compat_poll_del(struct lttng_poll_event *events, int fd)
        uint32_t new_size;
        struct compat_poll_event_array *current;
 
-       if (events == NULL || events->current.nb_fd == 0 ||
-                       events->current.events == NULL || fd < 0) {
+       if (events == NULL || events->current.nb_fd == 0 || events->current.events == NULL ||
+           fd < 0) {
                goto error;
        }
 
@@ -596,8 +588,8 @@ int compat_poll_del(struct lttng_poll_event *events, int fd)
 
        /* Resize array if needed. */
        new_size = 1U << utils_get_count_order_u32(current->nb_fd);
-       if (new_size != current->alloc_size && new_size >= current->init_size
-                       && current->nb_fd != 0) {
+       if (new_size != current->alloc_size && new_size >= current->init_size &&
+           current->nb_fd != 0) {
                ret = resize_poll_event(current, new_size);
                if (ret < 0) {
                        goto error;
@@ -616,8 +608,7 @@ error:
 /*
  * Wait on poll() with timeout. Blocking call.
  */
-int compat_poll_wait(struct lttng_poll_event *events, int timeout,
-               bool interruptible)
+int compat_poll_wait(struct lttng_poll_event *events, int timeout, bool interruptible)
 {
        int ret, active_fd_count;
        size_t pos = 0, consecutive_entries = 0, non_idle_pos;
@@ -675,7 +666,8 @@ int compat_poll_wait(struct lttng_poll_event *events, int timeout,
                non_idle_pos = pos;
 
                /* Look for next non-idle entry. */
-               while (events->wait.events[++non_idle_pos].revents == 0);
+               while (events->wait.events[++non_idle_pos].revents == 0)
+                       ;
 
                /* Swap idle and non-idle entries. */
                idle_entry = *current;
index 3cb07bf9375200ee51ca6da444175898a4a34d35..da339110622bca7a1f1c1f56271121ea105f5ad3 100644 (file)
@@ -8,11 +8,11 @@
 #ifndef _LTT_POLL_H
 #define _LTT_POLL_H
 
+#include <common/common.hpp>
+
 #include <string.h>
 #include <unistd.h>
 
-#include <common/common.hpp>
-
 /*
  * Used by lttng_poll_clean to free the events structure in a lttng_poll_event.
  */
@@ -25,10 +25,10 @@ static inline void __lttng_poll_free(void *events)
  * epoll(7) implementation.
  */
 #ifdef HAVE_EPOLL
-#include <sys/epoll.h>
-#include <stdio.h>
+
 #include <features.h>
-#include <common/compat/fcntl.hpp>
+#include <stdio.h>
+#include <sys/epoll.h>
 
 /* See man epoll(7) for this define path */
 #define COMPAT_EPOLL_PROC_PATH "/proc/sys/fs/epoll/max_user_watches"
@@ -47,7 +47,7 @@ enum {
        LPOLLHUP = EPOLLHUP,
        LPOLLNVAL = EPOLLHUP,
        LPOLLRDHUP = EPOLLRDHUP,
-       /* Close on exec feature of epoll */
+/* Close on exec feature of epoll */
 #if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC)
        LTTNG_CLOEXEC = EPOLL_CLOEXEC,
 #else
@@ -63,15 +63,15 @@ enum {
 
 struct compat_epoll_event {
        int epfd;
-       uint32_t nb_fd;       /* Current number of fd in events */
+       uint32_t nb_fd; /* Current number of fd in events */
        uint32_t alloc_size; /* Size of events array */
-       uint32_t init_size;     /* Initial size of events array */
+       uint32_t init_size; /* Initial size of events array */
        struct epoll_event *events;
 };
 #define lttng_poll_event compat_epoll_event
 
-static inline int __lttng_epoll_get_prev_fd(struct lttng_poll_event *events,
-               int index, uint32_t nb_fd)
+static inline int
+__lttng_epoll_get_prev_fd(struct lttng_poll_event *events, int index, uint32_t nb_fd)
 {
        LTTNG_ASSERT(events);
        LTTNG_ASSERT(index != nb_fd);
@@ -87,22 +87,18 @@ static inline int __lttng_epoll_get_prev_fd(struct lttng_poll_event *events,
  * For the following calls, consider 'e' to be a lttng_poll_event pointer and i
  * being the index of the events array.
  */
-#define LTTNG_POLL_GETFD(e, i) LTTNG_REF(e)->events[i].data.fd
-#define LTTNG_POLL_GETEV(e, i) LTTNG_REF(e)->events[i].events
-#define LTTNG_POLL_GETNB(e) LTTNG_REF(e)->nb_fd
-#define LTTNG_POLL_GETSZ(e) LTTNG_REF(e)->events_size
-#define LTTNG_POLL_GET_PREV_FD(e, i, nb_fd) \
-       __lttng_epoll_get_prev_fd(LTTNG_REF(e), i, nb_fd)
+#define LTTNG_POLL_GETFD(e, i)             LTTNG_REF(e)->events[i].data.fd
+#define LTTNG_POLL_GETEV(e, i)             LTTNG_REF(e)->events[i].events
+#define LTTNG_POLL_GETNB(e)                LTTNG_REF(e)->nb_fd
+#define LTTNG_POLL_GETSZ(e)                LTTNG_REF(e)->events_size
+#define LTTNG_POLL_GET_PREV_FD(e, i, nb_fd) __lttng_epoll_get_prev_fd(LTTNG_REF(e), i, nb_fd)
 
 /* Create the epoll set. */
-extern int compat_epoll_create(struct lttng_poll_event *events,
-               int size, int flags);
-#define lttng_poll_create(events, size, flags) \
-       compat_epoll_create(events, size, flags)
+extern int compat_epoll_create(struct lttng_poll_event *events, int size, int flags);
+#define lttng_poll_create(events, size, flags) compat_epoll_create(events, size, flags)
 
 #if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC)
-static inline int compat_glibc_epoll_create(int size __attribute__((unused)),
-               int flags)
+static inline int compat_glibc_epoll_create(int size __attribute__((unused)), int flags)
 {
        return epoll_create1(flags);
 }
@@ -125,42 +121,33 @@ static inline int compat_glibc_epoll_create(int size, int flags)
  * Wait on epoll set with the number of fd registered to the lttng_poll_event
  * data structure (events).
  */
-extern int compat_epoll_wait(struct lttng_poll_event *events, int timeout,
-               bool interruptible);
-#define lttng_poll_wait(events, timeout) \
-       compat_epoll_wait(events, timeout, false)
-#define lttng_poll_wait_interruptible(events, timeout) \
-       compat_epoll_wait(events, timeout, true)
+extern int compat_epoll_wait(struct lttng_poll_event *events, int timeout, bool interruptible);
+#define lttng_poll_wait(events, timeout)              compat_epoll_wait(events, timeout, false)
+#define lttng_poll_wait_interruptible(events, timeout) compat_epoll_wait(events, timeout, true)
 
 /*
  * Add a fd to the epoll set and resize the epoll_event structure if needed.
  */
-extern int compat_epoll_add(struct lttng_poll_event *events,
-               int fd, uint32_t req_events);
-#define lttng_poll_add(events, fd, req_events) \
-       compat_epoll_add(events, fd, req_events)
+extern int compat_epoll_add(struct lttng_poll_event *events, int fd, uint32_t req_events);
+#define lttng_poll_add(events, fd, req_events) compat_epoll_add(events, fd, req_events)
 
 /*
  * Remove a fd from the epoll set.
  */
 extern int compat_epoll_del(struct lttng_poll_event *events, int fd);
-#define lttng_poll_del(events, fd) \
-       compat_epoll_del(events, fd)
+#define lttng_poll_del(events, fd) compat_epoll_del(events, fd)
 
 /*
  * Modify an fd's events in the epoll set.
  */
-extern int compat_epoll_mod(struct lttng_poll_event *events,
-               int fd, uint32_t req_events);
-#define lttng_poll_mod(events, fd, req_events) \
-       compat_epoll_mod(events, fd, req_events)
+extern int compat_epoll_mod(struct lttng_poll_event *events, int fd, uint32_t req_events);
+#define lttng_poll_mod(events, fd, req_events) compat_epoll_mod(events, fd, req_events)
 
 /*
  * Set up the poll set limits variable poll_max_size
  */
-extern int compat_epoll_set_max_size(void);
-#define lttng_poll_set_max_size() \
-       compat_epoll_set_max_size()
+extern int compat_epoll_set_max_size();
+#define lttng_poll_set_max_size() compat_epoll_set_max_size()
 
 /*
  * This function memset with zero the structure since it can be reused at each
@@ -170,8 +157,7 @@ extern int compat_epoll_set_max_size(void);
 static inline void lttng_poll_reset(struct lttng_poll_event *events)
 {
        if (events && events->events) {
-               memset(events->events, 0,
-                               events->nb_fd * sizeof(struct epoll_event));
+               memset(events->events, 0, events->nb_fd * sizeof(struct epoll_event));
        }
 }
 
@@ -208,21 +194,11 @@ static inline void lttng_poll_clean(struct lttng_poll_event *events)
        __lttng_poll_free((void *) events->events);
 }
 
-#else  /* HAVE_EPOLL */
+#else /* HAVE_EPOLL */
 /*
  * Fallback on poll(2) API
  */
 
-/* Needed for some poll event values */
-#ifndef __USE_XOPEN
-#define __USE_XOPEN
-#endif
-
-/* Needed for some poll event values */
-#ifndef __USE_GNU
-#define __USE_GNU
-#endif
-
 #include <poll.h>
 #include <stdint.h>
 
@@ -235,15 +211,13 @@ enum {
        LPOLLRDBAND = POLLRDBAND,
        LPOLLWRNORM = POLLWRNORM,
        LPOLLWRBAND = POLLWRBAND,
-#ifdef __linux__
+#ifdef __USE_GNU
        LPOLLMSG = POLLMSG,
        LPOLLRDHUP = POLLRDHUP,
-#elif (defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__sun__) || defined(__APPLE__))
+#else
        LPOLLMSG = 0,
        LPOLLRDHUP = 0,
-#else
-#error "Please add support for your OS."
-#endif /* __linux__ */
+#endif /* __USE_GNU */
        LPOLLERR = POLLERR,
        LPOLLHUP = POLLHUP | POLLNVAL,
        /* Close on exec feature does not exist for poll(2) */
@@ -251,7 +225,7 @@ enum {
 };
 
 struct compat_poll_event_array {
-       uint32_t nb_fd;       /* Current number of fd in events */
+       uint32_t nb_fd; /* Current number of fd in events */
        uint32_t alloc_size; /* Size of events array */
        /* Initial size of the pollset. We never shrink below that. */
        uint32_t init_size;
@@ -273,10 +247,10 @@ struct compat_poll_event {
        /* Indicate if wait.events need to be updated from current. */
        int need_update:1;
 };
-#define lttng_poll_event compat_poll_event
+#define lttng_poll_event                              compat_poll_event
 
-static inline int __lttng_poll_get_prev_fd(struct lttng_poll_event *events,
-               int index, uint32_t nb_fd)
+static inline int
+__lttng_poll_get_prev_fd(struct lttng_poll_event *events, int index, uint32_t nb_fd)
 {
        LTTNG_ASSERT(events);
        LTTNG_ASSERT(index != nb_fd);
@@ -294,38 +268,31 @@ static inline int __lttng_poll_get_prev_fd(struct lttng_poll_event *events,
  * LTTNG_POLL_GETNB is always used after lttng_poll_wait, thus we can use the
  * current list for test compatibility purposes.
  */
-#define LTTNG_POLL_GETFD(e, i) LTTNG_REF(e)->wait.events[i].fd
-#define LTTNG_POLL_GETEV(e, i) LTTNG_REF(e)->wait.events[i].revents
-#define LTTNG_POLL_GETNB(e) LTTNG_REF(e)->current.nb_fd
-#define LTTNG_POLL_GETSZ(e) LTTNG_REF(e)->wait.events_size
-#define LTTNG_POLL_GET_PREV_FD(e, i, nb_fd) \
-       __lttng_poll_get_prev_fd(LTTNG_REF(e), i, nb_fd)
+#define LTTNG_POLL_GETFD(e, i)                        LTTNG_REF(e)->wait.events[i].fd
+#define LTTNG_POLL_GETEV(e, i)                        LTTNG_REF(e)->wait.events[i].revents
+#define LTTNG_POLL_GETNB(e)                           LTTNG_REF(e)->current.nb_fd
+#define LTTNG_POLL_GETSZ(e)                           LTTNG_REF(e)->wait.events_size
+#define LTTNG_POLL_GET_PREV_FD(e, i, nb_fd)           __lttng_poll_get_prev_fd(LTTNG_REF(e), i, nb_fd)
 
 /*
  * Create a pollfd structure of size 'size'.
  */
 extern int compat_poll_create(struct lttng_poll_event *events, int size);
-#define lttng_poll_create(events, size, flags) \
-       compat_poll_create(events, size)
+#define lttng_poll_create(events, size, flags)        compat_poll_create(events, size)
 
 /*
  * Wait on poll(2) event with nb_fd registered to the lttng_poll_event data
  * structure.
  */
-extern int compat_poll_wait(struct lttng_poll_event *events, int timeout,
-               bool interruptible);
-#define lttng_poll_wait(events, timeout) \
-       compat_poll_wait(events, timeout, false)
-#define lttng_poll_wait_interruptible(events, timeout) \
-       compat_poll_wait(events, timeout, true)
+extern int compat_poll_wait(struct lttng_poll_event *events, int timeout, bool interruptible);
+#define lttng_poll_wait(events, timeout)              compat_poll_wait(events, timeout, false)
+#define lttng_poll_wait_interruptible(events, timeout) compat_poll_wait(events, timeout, true)
 
 /*
  * Add the fd to the pollfd structure. Resize if needed.
  */
-extern int compat_poll_add(struct lttng_poll_event *events,
-               int fd, uint32_t req_events);
-#define lttng_poll_add(events, fd, req_events) \
-       compat_poll_add(events, fd, req_events)
+extern int compat_poll_add(struct lttng_poll_event *events, int fd, uint32_t req_events);
+#define lttng_poll_add(events, fd, req_events)        compat_poll_add(events, fd, req_events)
 
 /*
  * Remove the fd from the pollfd. Memory allocation is done to recreate a new
@@ -333,30 +300,26 @@ extern int compat_poll_add(struct lttng_poll_event *events,
  * one is freed().
  */
 extern int compat_poll_del(struct lttng_poll_event *events, int fd);
-#define lttng_poll_del(events, fd) \
-       compat_poll_del(events, fd)
+#define lttng_poll_del(events, fd)                    compat_poll_del(events, fd)
 
 /*
  * Modify an fd's events in the poll set.
  */
-extern int compat_poll_mod(struct lttng_poll_event *events,
-               int fd, uint32_t req_events);
-#define lttng_poll_mod(events, fd, req_events) \
-       compat_poll_mod(events, fd, req_events)
+extern int compat_poll_mod(struct lttng_poll_event *events, int fd, uint32_t req_events);
+#define lttng_poll_mod(events, fd, req_events)        compat_poll_mod(events, fd, req_events)
 
 /*
  * Set up the poll set limits variable poll_max_size
  */
 extern int compat_poll_set_max_size(void);
-#define lttng_poll_set_max_size() \
-       compat_poll_set_max_size()
+#define lttng_poll_set_max_size()                     compat_poll_set_max_size()
 
 /*
  * No need to reset a pollfd structure for poll(2)
  */
-static inline void lttng_poll_reset(
-               struct lttng_poll_event *events __attribute__((unused)))
-{}
+static inline void lttng_poll_reset(struct lttng_poll_event *events __attribute__((unused)))
+{
+}
 
 /*
  * Initialize an already allocated poll event data structure.
index 7883cd1ba303c5ecbcb88c5e842af6a3d7e0a61f..f8908992436853c78231637b274ae7028e0170ee 100644 (file)
@@ -8,8 +8,9 @@
 #ifndef _COMPAT_PTHREAD_H
 #define _COMPAT_PTHREAD_H
 
-#include <pthread.h>
 #include <common/compat/errno.hpp>
+
+#include <pthread.h>
 #include <string.h>
 
 #ifdef __FreeBSD__
@@ -19,8 +20,7 @@
 #define LTTNG_PTHREAD_NAMELEN 16
 
 #if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
-static inline
-int lttng_pthread_setname_np(const char *name)
+static inline int lttng_pthread_setname_np(const char *name)
 {
        /*
         * Some implementations don't error out, replicate this behavior for
@@ -33,15 +33,13 @@ int lttng_pthread_setname_np(const char *name)
        return pthread_setname_np(pthread_self(), name);
 }
 #elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
-static inline
-int lttng_pthread_setname_np(const char *name)
+static inline int lttng_pthread_setname_np(const char *name)
 {
        return pthread_setname_np(name);
 }
 #elif defined(HAVE_PTHREAD_SET_NAME_NP_WITH_TID)
 
-static inline
-int lttng_pthread_setname_np(const char *name)
+static inline int lttng_pthread_setname_np(const char *name)
 {
        /* Replicate pthread_setname_np's behavior. */
        if (strnlen(name, LTTNG_PTHREAD_NAMELEN) >= LTTNG_PTHREAD_NAMELEN) {
@@ -56,8 +54,7 @@ int lttng_pthread_setname_np(const char *name)
 /* Fallback on prtctl on Linux */
 #include <sys/prctl.h>
 
-static inline
-int lttng_pthread_setname_np(const char *name)
+static inline int lttng_pthread_setname_np(const char *name)
 {
        /* Replicate pthread_setname_np's behavior. */
        if (strnlen(name, LTTNG_PTHREAD_NAMELEN) >= LTTNG_PTHREAD_NAMELEN) {
@@ -69,29 +66,24 @@ int lttng_pthread_setname_np(const char *name)
 /*
  * For platforms without thread name support, do nothing.
  */
-static inline
-int lttng_pthread_setname_np(const char *name)
+static inline int lttng_pthread_setname_np(const char *name)
 {
        return -ENOSYS;
 }
 #endif
 
-
 #if defined(HAVE_PTHREAD_GETNAME_NP_WITH_TID)
-static inline
-int lttng_pthread_getname_np(char *name, size_t len)
+static inline int lttng_pthread_getname_np(char *name, size_t len)
 {
        return pthread_getname_np(pthread_self(), name, len);
 }
 #elif defined(HAVE_PTHREAD_GETNAME_NP_WITHOUT_TID)
-static inline
-int lttng_pthread_getname_np(char *name, size_t len)
+static inline int lttng_pthread_getname_np(char *name, size_t len)
 {
        return pthread_getname_np(name, len);
 }
 #elif defined(HAVE_PTHREAD_GET_NAME_NP_WITH_TID)
-static inline
-int lttng_pthread_getname_np(char *name, size_t len)
+static inline int lttng_pthread_getname_np(char *name, size_t len)
 {
        pthread_get_name_np(pthread_self(), name, len);
        return 0;
@@ -101,8 +93,7 @@ int lttng_pthread_getname_np(char *name, size_t len)
 /* Fallback on prtctl on Linux */
 #include <sys/prctl.h>
 
-static inline
-int lttng_pthread_getname_np(char *name, size_t len)
+static inline int lttng_pthread_getname_np(char *name, size_t len)
 {
        return prctl(PR_GET_NAME, name, 0, 0, 0);
 }
@@ -110,8 +101,7 @@ int lttng_pthread_getname_np(char *name, size_t len)
 /*
  * For platforms without thread name support, do nothing.
  */
-static inline
-int lttng_pthread_getname_np(char *name, size_t len)
+static inline int lttng_pthread_getname_np(char *name, size_t len)
 {
        return -ENOSYS;
 }
index 599998ef5f6b63de04e355af59fbded74bcd87fc..dadd1fe8d6a6b6594a6d09eda2dc81197e5bfd54 100644 (file)
@@ -8,31 +8,30 @@
 #ifndef _COMPAT_SOCKET_H
 #define _COMPAT_SOCKET_H
 
+#include <common/macros.hpp>
+
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <unistd.h>
 
-#include <common/macros.hpp>
-
 #ifndef MSG_NOSIGNAL
-# ifdef SO_NOSIGPIPE
-#   define MSG_NOSIGNAL SO_NOSIGPIPE
-# endif
+#ifdef SO_NOSIGPIPE
+#define MSG_NOSIGNAL SO_NOSIGPIPE
+#endif
 #endif
 
 #if defined(MSG_NOSIGNAL)
-static inline
-ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
+static inline ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
 {
        return recvmsg(sockfd, msg, MSG_NOSIGNAL);
 }
 #else
 
-#include <signal.h>
 #include <common/compat/errno.hpp>
 
-static inline
-ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
+#include <signal.h>
+
+static inline ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
 {
        ssize_t received;
        int saved_err;
@@ -82,8 +81,7 @@ ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
                int ret;
 
                do {
-                       ret = sigtimedwait(&sigpipe_set, NULL,
-                               &timeout);
+                       ret = sigtimedwait(&sigpipe_set, NULL, &timeout);
                } while (ret == -1 && errno == EINTR);
        }
        if (!sigpipe_was_pending) {
@@ -100,25 +98,24 @@ ssize_t lttng_recvmsg_nosigpipe(int sockfd, struct msghdr *msg)
 
 #ifdef __sun__
 
-# ifndef CMSG_ALIGN
-#  ifdef _CMSG_DATA_ALIGN
-#   define CMSG_ALIGN(len) _CMSG_DATA_ALIGN(len)
-#  else
-    /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
-#   define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & ~(sizeof (long) - 1))
-#  endif
-#  ifndef CMSG_SPACE
-#    define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + CMSG_ALIGN (len))
-#  endif
-#  ifndef CMSG_LEN
-#    define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
-#  endif
-# endif
+#ifndef CMSG_ALIGN
+#ifdef _CMSG_DATA_ALIGN
+#define CMSG_ALIGN(len) _CMSG_DATA_ALIGN(len)
+#else
+/* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
+#define CMSG_ALIGN(len) (((len) + sizeof(long) - 1) & ~(sizeof(long) - 1))
+#endif
+#ifndef CMSG_SPACE
+#define CMSG_SPACE(len) (CMSG_ALIGN(sizeof(struct cmsghdr)) + CMSG_ALIGN(len))
+#endif
+#ifndef CMSG_LEN
+#define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr)) + (len))
+#endif
+#endif
 
 #include <ucred.h>
 
-static inline
-int getpeereid(int s, uid_t *euid, gid_t *gid)
+static inline int getpeereid(int s, uid_t *euid, gid_t *gid)
 {
        int ret = 0;
        ucred_t *ucred = NULL;
@@ -148,12 +145,11 @@ end:
 }
 #endif /* __sun__ */
 
-
 #if defined(__linux__) || defined(__CYGWIN__)
 
 #define LTTNG_SOCK_CREDS SCM_CREDENTIALS
 
-typedef struct ucred lttng_sock_cred;
+using lttng_sock_cred = struct ucred;
 
 #define LTTNG_SOCK_SET_UID_CRED(c, u) LTTNG_REF(c)->uid = u
 #define LTTNG_SOCK_SET_GID_CRED(c, g) LTTNG_REF(c)->gid = g
@@ -183,8 +179,7 @@ typedef struct lttng_sock_cred lttng_sock_cred;
 
 #ifdef __APPLE__
 
-static inline
-int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
+static inline int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
 {
        socklen_t pid_len = (socklen_t) sizeof(*pid);
 
@@ -195,8 +190,7 @@ int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
 #elif defined(__sun__)
 
 /* Use the getpeerucreds interface on Solaris. */
-static inline
-int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
+static inline int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
 {
        int ret = 0;
        ucred_t *ucred = NULL;
@@ -223,15 +217,14 @@ end:
 
 #include <sys/ucred.h>
 
-static inline
-int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
+static inline int lttng_get_unix_socket_peer_pid(int socket_fd, pid_t *pid)
 {
        int ret;
        struct xucred sock_creds = {};
+       socklen_t sock_creds_len = (socklen_t) sizeof(sock_creds);
 
        /* Only available in FreeBSD 13.0 and up. */
-       ret = getsockopt(socket_fd, SOL_LOCAL, LOCAL_PEERCRED, &sock_creds,
-                       &((socklen_t) {sizeof(sock_creds)}));
+       ret = getsockopt(socket_fd, SOL_LOCAL, LOCAL_PEERCRED, &sock_creds, &sock_creds_len);
        if (ret) {
                goto end;
        }
@@ -243,9 +236,7 @@ end:
 
 #endif /* __APPLE__ */
 
-
-static inline
-int lttng_get_unix_socket_peer_creds(int socket_fd, struct lttng_sock_cred *creds)
+static inline int lttng_get_unix_socket_peer_creds(int socket_fd, struct lttng_sock_cred *creds)
 {
        int ret;
 
index 526f2b2ced3b200ecfa696083baa9fadc72408eb..c34c7aa49b04feed30e23b01f0130dd2f7437db5 100644 (file)
@@ -9,18 +9,16 @@
 #ifndef _COMPAT_STRING_H
 #define _COMPAT_STRING_H
 
-#include <string.h>
 #include <stdlib.h>
+#include <string.h>
 
 #ifdef HAVE_STRNLEN
-static inline
-size_t lttng_strnlen(const char *str, size_t max)
+static inline size_t lttng_strnlen(const char *str, size_t max)
 {
        return strnlen(str, max);
 }
 #else
-static inline
-size_t lttng_strnlen(const char *str, size_t max)
+static inline size_t lttng_strnlen(const char *str, size_t max)
 {
        size_t ret;
        const char *end;
@@ -38,14 +36,12 @@ size_t lttng_strnlen(const char *str, size_t max)
 #endif /* HAVE_STRNLEN */
 
 #ifdef HAVE_STRNDUP
-static inline
-char *lttng_strndup(const char *s, size_t n)
+static inline char *lttng_strndup(const char *s, size_t n)
 {
        return strndup(s, n);
 }
 #else
-static inline
-char *lttng_strndup(const char *s, size_t n)
+static inline char *lttng_strndup(const char *s, size_t n)
 {
        char *ret;
        size_t navail;
@@ -110,20 +106,18 @@ static inline int lttng_fls(int val)
 #endif /* HAVE_FLS */
 
 #ifdef HAVE_MEMRCHR
-static inline
-void *lttng_memrchr(const void *s, int c, size_t n)
+static inline void *lttng_memrchr(const void *s, int c, size_t n)
 {
        return (void *) memrchr(s, c, n);
 }
 #else
-static inline
-void *lttng_memrchr(const void *s, int c, size_t n)
+static inline void *lttng_memrchr(const void *s, int c, size_t n)
 {
        int i;
        const char *str = (const char *) s;
-       for (i = n-1; i >= 0; i--) {
-               if (str[i] == (char)c) {
-                       return (void *)(str+i);
+       for (i = n - 1; i >= 0; i--) {
+               if (str[i] == (char) c) {
+                       return (void *) (str + i);
                }
        }
        return NULL;
index 4a6ff74c2954a2dbb53e842c600cb7c7513f573f..adf048e98fd36174e17063f1d16a43306401c39d 100644 (file)
@@ -15,7 +15,7 @@
 #if defined(__NR_gettid)
 
 #include <unistd.h>
-static inline pid_t lttng_gettid(void)
+static inline pid_t lttng_gettid()
 {
        return syscall(__NR_gettid);
 }
index 37f472a4aad1378d95542fde0f258132b76c368c..aed37ceedbfcd74f36ae4e60c12c000ab69287f2 100644 (file)
 
 #ifdef __APPLE__
 
+#include <cstdint>
+
 typedef uint64_t timer_t;
 
-#include <mach/mach.h>
-#include <mach/clock.h>
 #include <common/compat/errno.hpp>
 
+#include <mach/clock.h>
+#include <mach/mach.h>
+
 #undef NSEC_PER_SEC
 #undef NSEC_PER_MSEC
 #undef NSEC_PER_USEC
@@ -29,11 +32,10 @@ typedef uint64_t timer_t;
 #if defined(__APPLE__) && !defined(LTTNG_HAVE_CLOCK_GETTIME)
 
 typedef int clockid_t;
-#define CLOCK_REALTIME CALENDAR_CLOCK
+#define CLOCK_REALTIME CALENDAR_CLOCK
 #define CLOCK_MONOTONIC SYSTEM_CLOCK
 
-static inline
-int lttng_clock_gettime(clockid_t clk_id, struct timespec *tp)
+static inline int lttng_clock_gettime(clockid_t clk_id, struct timespec *tp)
 {
        int ret = 0;
        clock_serv_t clock;
@@ -64,8 +66,7 @@ end:
 
 #else /* __APPLE__ && !LTTNG_HAVE_CLOCK_GETTIME */
 
-static inline
-int lttng_clock_gettime(clockid_t clk_id, struct timespec *tp)
+static inline int lttng_clock_gettime(clockid_t clk_id, struct timespec *tp)
 {
        return clock_gettime(clk_id, tp);
 }
diff --git a/src/common/compiler.hpp b/src/common/compiler.hpp
new file mode 100644 (file)
index 0000000..bb080ad
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_COMPILER_HPP
+#define LTTNG_COMPILER_HPP
+
+/*
+ * A bug in gcc [6.1, 7.4] causes flexible array members to generate a destructor
+ * for compound types. In turn, this makes any type that contains a flexible array
+ * a non-POD object which is a problem under some use-case (e.g., being allocated
+ * using C-style memory management facilities).
+ *
+ * Explicitly specifying a length of zero works around this bug, see:
+ * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70932
+ * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71147
+ */
+#if !defined(__clang__) && defined(__GNUC__) && \
+       ((__GNUC__ == 6 && __GNUC_MINOR__ >= 1) || ((__GNUC__ == 7 && __GNUC_MINOR__ <= 4)))
+#define LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH 0
+#else
+#define LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH
+#endif /* gcc version [6.1, 7.4]. */
+
+#endif /* LTTNG_COMPILER_HPP */
index 6830877a189e63f6fc98405eb6a54fd6e2933db8..c78528735063cb261a0f4830fb023131397cd496 100644 (file)
@@ -8,42 +8,38 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
-#include <float.h>
+
 #include <lttng/condition/buffer-usage-internal.hpp>
 #include <lttng/condition/condition-internal.hpp>
+
+#include <float.h>
 #include <math.h>
 #include <time.h>
 
-#define IS_USAGE_CONDITION(condition) ( \
-       lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW || \
-       lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH   \
-       )
+#define IS_USAGE_CONDITION(condition)                                                    \
+       (lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW || \
+        lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH)
 
-static
-bool is_usage_evaluation(const struct lttng_evaluation *evaluation)
+static bool is_usage_evaluation(const struct lttng_evaluation *evaluation)
 {
        enum lttng_condition_type type = lttng_evaluation_get_type(evaluation);
 
        return type == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW ||
-                       type == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH;
+               type == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH;
 }
 
-static
-void lttng_condition_buffer_usage_destroy(struct lttng_condition *condition)
+static void lttng_condition_buffer_usage_destroy(struct lttng_condition *condition)
 {
        struct lttng_condition_buffer_usage *usage;
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
 
        free(usage->session_name);
        free(usage->channel_name);
        free(usage);
 }
 
-static
-bool lttng_condition_buffer_usage_validate(
-               const struct lttng_condition *condition)
+static bool lttng_condition_buffer_usage_validate(const struct lttng_condition *condition)
 {
        bool valid = false;
        struct lttng_condition_buffer_usage *usage;
@@ -52,8 +48,7 @@ bool lttng_condition_buffer_usage_validate(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->session_name) {
                ERR("Invalid buffer condition: a target session name must be set.");
                goto end;
@@ -76,10 +71,8 @@ end:
        return valid;
 }
 
-static
-int lttng_condition_buffer_usage_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload)
+static int lttng_condition_buffer_usage_serialize(const struct lttng_condition *condition,
+                                                 struct lttng_payload *payload)
 {
        int ret;
        struct lttng_condition_buffer_usage *usage;
@@ -92,13 +85,11 @@ int lttng_condition_buffer_usage_serialize(
        }
 
        DBG("Serializing buffer usage condition");
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
 
        session_name_len = strlen(usage->session_name) + 1;
        channel_name_len = strlen(usage->channel_name) + 1;
-       if (session_name_len > LTTNG_NAME_MAX ||
-                       channel_name_len > LTTNG_NAME_MAX) {
+       if (session_name_len > LTTNG_NAME_MAX || channel_name_len > LTTNG_NAME_MAX) {
                ret = -1;
                goto end;
        }
@@ -114,20 +105,17 @@ int lttng_condition_buffer_usage_serialize(
                usage_comm.threshold_ratio = usage->threshold_ratio.value;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &usage_comm,
-                       sizeof(usage_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &usage_comm, sizeof(usage_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, usage->session_name,
-                       session_name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, usage->session_name, session_name_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, usage->channel_name,
-                       channel_name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, usage->channel_name, channel_name_len);
        if (ret) {
                goto end;
        }
@@ -135,9 +123,8 @@ end:
        return ret;
 }
 
-static
-bool lttng_condition_buffer_usage_is_equal(const struct lttng_condition *_a,
-               const struct lttng_condition *_b)
+static bool lttng_condition_buffer_usage_is_equal(const struct lttng_condition *_a,
+                                                 const struct lttng_condition *_b)
 {
        bool is_equal = false;
        struct lttng_condition_buffer_usage *a, *b;
@@ -146,7 +133,7 @@ bool lttng_condition_buffer_usage_is_equal(const struct lttng_condition *_a,
        b = lttng::utils::container_of(_b, &lttng_condition_buffer_usage::parent);
 
        if ((a->threshold_ratio.set && !b->threshold_ratio.set) ||
-                       (a->threshold_bytes.set && !b->threshold_bytes.set)) {
+           (a->threshold_bytes.set && !b->threshold_bytes.set)) {
                goto end;
        }
 
@@ -173,13 +160,13 @@ bool lttng_condition_buffer_usage_is_equal(const struct lttng_condition *_a,
        /* Condition is not valid if this is not true. */
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
        LTTNG_ASSERT(a->channel_name);
        LTTNG_ASSERT(b->channel_name);
-       if (strcmp(a->channel_name, b->channel_name)) {
+       if (strcmp(a->channel_name, b->channel_name) != 0) {
                goto end;
        }
 
@@ -193,39 +180,35 @@ end:
        return is_equal;
 }
 
-static enum lttng_error_code lttng_condition_buffer_usage_mi_serialize(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_condition_buffer_usage_mi_serialize(const struct lttng_condition *condition,
+                                         struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_condition_status status;
-       const char *session_name = NULL, *channel_name = NULL;
+       const char *session_name = nullptr, *channel_name = nullptr;
        enum lttng_domain_type domain_type;
        bool is_threshold_bytes = false;
        double threshold_ratio;
        uint64_t threshold_bytes;
-       const char *condition_type_str = NULL;
+       const char *condition_type_str = nullptr;
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(IS_USAGE_CONDITION(condition));
 
-       status = lttng_condition_buffer_usage_get_session_name(
-                       condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(condition, &session_name);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(session_name);
 
-       status = lttng_condition_buffer_usage_get_channel_name(
-                       condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(condition, &channel_name);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(session_name);
 
-       status = lttng_condition_buffer_usage_get_domain_type(
-                       condition, &domain_type);
+       status = lttng_condition_buffer_usage_get_domain_type(condition, &domain_type);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
 
-       status = lttng_condition_buffer_usage_get_threshold(
-                       condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(condition, &threshold_bytes);
        if (status == LTTNG_CONDITION_STATUS_OK) {
                is_threshold_bytes = true;
        } else if (status != LTTNG_CONDITION_STATUS_UNSET) {
@@ -235,19 +218,17 @@ static enum lttng_error_code lttng_condition_buffer_usage_mi_serialize(
        }
 
        if (!is_threshold_bytes) {
-               status = lttng_condition_buffer_usage_get_threshold_ratio(
-                               condition, &threshold_ratio);
+               status = lttng_condition_buffer_usage_get_threshold_ratio(condition,
+                                                                         &threshold_ratio);
                LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        }
 
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
-               condition_type_str =
-                               mi_lttng_element_condition_buffer_usage_high;
+               condition_type_str = mi_lttng_element_condition_buffer_usage_high;
                break;
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
-               condition_type_str =
-                               mi_lttng_element_condition_buffer_usage_low;
+               condition_type_str = mi_lttng_element_condition_buffer_usage_low;
                break;
        default:
                abort();
@@ -262,39 +243,36 @@ static enum lttng_error_code lttng_condition_buffer_usage_mi_serialize(
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Channel name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_condition_channel_name, channel_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_condition_channel_name, channel_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Domain. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_domain,
-                       mi_lttng_domaintype_string(domain_type));
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_domain, mi_lttng_domaintype_string(domain_type));
        if (ret) {
                goto mi_error;
        }
 
        if (is_threshold_bytes) {
                /* Usage in bytes. */
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               mi_lttng_element_condition_threshold_bytes,
-                               threshold_bytes);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer, mi_lttng_element_condition_threshold_bytes, threshold_bytes);
                if (ret) {
                        goto mi_error;
                }
        } else {
                /* Ratio. */
-               ret = mi_lttng_writer_write_element_double(writer,
-                               mi_lttng_element_condition_threshold_ratio,
-                               threshold_ratio);
+               ret = mi_lttng_writer_write_element_double(
+                       writer, mi_lttng_element_condition_threshold_ratio, threshold_ratio);
                if (ret) {
                        goto mi_error;
                }
@@ -315,15 +293,13 @@ end:
        return ret_code;
 }
 
-static
-struct lttng_condition *lttng_condition_buffer_usage_create(
-               enum lttng_condition_type type)
+static struct lttng_condition *lttng_condition_buffer_usage_create(enum lttng_condition_type type)
 {
        struct lttng_condition_buffer_usage *condition;
 
        condition = zmalloc<lttng_condition_buffer_usage>();
        if (!condition) {
-               return NULL;
+               return nullptr;
        }
 
        lttng_condition_init(&condition->parent, type);
@@ -337,19 +313,16 @@ struct lttng_condition *lttng_condition_buffer_usage_create(
 
 struct lttng_condition *lttng_condition_buffer_usage_low_create(void)
 {
-       return lttng_condition_buffer_usage_create(
-                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW);
+       return lttng_condition_buffer_usage_create(LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW);
 }
 
 struct lttng_condition *lttng_condition_buffer_usage_high_create(void)
 {
-       return lttng_condition_buffer_usage_create(
-                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH);
+       return lttng_condition_buffer_usage_create(LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH);
 }
 
-static
-ssize_t init_condition_from_payload(struct lttng_condition *condition,
-               struct lttng_payload_view *src_view)
+static ssize_t init_condition_from_payload(struct lttng_condition *condition,
+                                          struct lttng_payload_view *src_view)
 {
        ssize_t ret, condition_size;
        enum lttng_condition_status status;
@@ -358,8 +331,7 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        struct lttng_buffer_view names_view;
        const struct lttng_condition_buffer_usage_comm *condition_comm;
        const struct lttng_payload_view condition_comm_view =
-                       lttng_payload_view_from_view(
-                                       src_view, 0, sizeof(*condition_comm));
+               lttng_payload_view_from_view(src_view, 0, sizeof(*condition_comm));
 
        if (!lttng_payload_view_is_valid(&condition_comm_view)) {
                ERR("Failed to initialize from malformed condition buffer: buffer too short to contain header");
@@ -368,30 +340,28 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        }
 
        condition_comm = (typeof(condition_comm)) condition_comm_view.buffer.data;
-       names_view = lttng_buffer_view_from_view(&src_view->buffer,
-                       sizeof(*condition_comm), -1);
+       names_view = lttng_buffer_view_from_view(&src_view->buffer, sizeof(*condition_comm), -1);
 
        if (condition_comm->session_name_len > LTTNG_NAME_MAX ||
-                       condition_comm->channel_name_len > LTTNG_NAME_MAX) {
+           condition_comm->channel_name_len > LTTNG_NAME_MAX) {
                ERR("Failed to initialize from malformed condition buffer: name exceeds LTTNG_MAX_NAME");
                ret = -1;
                goto end;
        }
 
        if (names_view.size <
-                       (condition_comm->session_name_len +
-                       condition_comm->channel_name_len)) {
+           (condition_comm->session_name_len + condition_comm->channel_name_len)) {
                ERR("Failed to initialize from malformed condition buffer: buffer too short to contain element names");
                ret = -1;
                goto end;
        }
 
        if (condition_comm->threshold_set_in_bytes) {
-               status = lttng_condition_buffer_usage_set_threshold(condition,
-                               condition_comm->threshold_bytes);
+               status = lttng_condition_buffer_usage_set_threshold(
+                       condition, condition_comm->threshold_bytes);
        } else {
                status = lttng_condition_buffer_usage_set_threshold_ratio(
-                               condition, condition_comm->threshold_ratio);
+                       condition, condition_comm->threshold_ratio);
        }
 
        if (status != LTTNG_CONDITION_STATUS_OK) {
@@ -401,17 +371,16 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        }
 
        if (condition_comm->domain_type <= LTTNG_DOMAIN_NONE ||
-                       condition_comm->domain_type > LTTNG_DOMAIN_PYTHON) {
+           condition_comm->domain_type > LTTNG_DOMAIN_PYTHON) {
                /* Invalid domain value. */
                ERR("Invalid domain type value (%i) found in condition buffer",
-                               (int) condition_comm->domain_type);
+                   (int) condition_comm->domain_type);
                ret = -1;
                goto end;
        }
 
        domain_type = (enum lttng_domain_type) condition_comm->domain_type;
-       status = lttng_condition_buffer_usage_set_domain_type(condition,
-                       domain_type);
+       status = lttng_condition_buffer_usage_set_domain_type(condition, domain_type);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to set buffer usage condition domain");
                ret = -1;
@@ -432,16 +401,14 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       status = lttng_condition_buffer_usage_set_session_name(condition,
-                       session_name);
+       status = lttng_condition_buffer_usage_set_session_name(condition, session_name);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to set buffer usage session name");
                ret = -1;
                goto end;
        }
 
-       status = lttng_condition_buffer_usage_set_channel_name(condition,
-                       channel_name);
+       status = lttng_condition_buffer_usage_set_channel_name(condition, channel_name);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to set buffer usage channel name");
                ret = -1;
@@ -453,21 +420,18 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       condition_size = sizeof(*condition_comm) +
-                       (ssize_t) condition_comm->session_name_len +
-                       (ssize_t) condition_comm->channel_name_len;
+       condition_size = sizeof(*condition_comm) + (ssize_t) condition_comm->session_name_len +
+               (ssize_t) condition_comm->channel_name_len;
        ret = condition_size;
 end:
        return ret;
 }
 
-ssize_t lttng_condition_buffer_usage_low_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **_condition)
+ssize_t lttng_condition_buffer_usage_low_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_condition **_condition)
 {
        ssize_t ret;
-       struct lttng_condition *condition =
-                       lttng_condition_buffer_usage_low_create();
+       struct lttng_condition *condition = lttng_condition_buffer_usage_low_create();
 
        if (!_condition || !condition) {
                ret = -1;
@@ -486,13 +450,11 @@ error:
        return ret;
 }
 
-ssize_t lttng_condition_buffer_usage_high_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **_condition)
+ssize_t lttng_condition_buffer_usage_high_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_condition **_condition)
 {
        ssize_t ret;
-       struct lttng_condition *condition =
-                       lttng_condition_buffer_usage_high_create();
+       struct lttng_condition *condition = lttng_condition_buffer_usage_high_create();
 
        if (!_condition || !condition) {
                ret = -1;
@@ -511,39 +473,34 @@ error:
        return ret;
 }
 
-static
-struct lttng_evaluation *create_evaluation_from_payload(
-               enum lttng_condition_type type,
-               struct lttng_payload_view *view)
+static struct lttng_evaluation *create_evaluation_from_payload(enum lttng_condition_type type,
+                                                              struct lttng_payload_view *view)
 {
-       const struct lttng_evaluation_buffer_usage_comm *comm =
-                       (typeof(comm)) view->buffer.data;
-       struct lttng_evaluation *evaluation = NULL;
+       const struct lttng_evaluation_buffer_usage_comm *comm = (typeof(comm)) view->buffer.data;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (view->buffer.size < sizeof(*comm)) {
                goto end;
        }
 
-       evaluation = lttng_evaluation_buffer_usage_create(type,
-                       comm->buffer_use, comm->buffer_capacity);
+       evaluation =
+               lttng_evaluation_buffer_usage_create(type, comm->buffer_use, comm->buffer_capacity);
 end:
        return evaluation;
 }
 
-ssize_t lttng_evaluation_buffer_usage_low_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+ssize_t lttng_evaluation_buffer_usage_low_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_evaluation **_evaluation)
 {
        ssize_t ret;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (!_evaluation) {
                ret = -1;
                goto error;
        }
 
-       evaluation = create_evaluation_from_payload(
-                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW, view);
+       evaluation = create_evaluation_from_payload(LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW, view);
        if (!evaluation) {
                ret = -1;
                goto error;
@@ -557,20 +514,19 @@ error:
        return ret;
 }
 
-ssize_t lttng_evaluation_buffer_usage_high_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+ssize_t
+lttng_evaluation_buffer_usage_high_create_from_payload(struct lttng_payload_view *view,
+                                                      struct lttng_evaluation **_evaluation)
 {
        ssize_t ret;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (!_evaluation) {
                ret = -1;
                goto error;
        }
 
-       evaluation = create_evaluation_from_payload(
-                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH, view);
+       evaluation = create_evaluation_from_payload(LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH, view);
        if (!evaluation) {
                ret = -1;
                goto error;
@@ -585,21 +541,18 @@ error:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_get_threshold_ratio(
-               const struct lttng_condition *condition,
-               double *threshold_ratio)
+lttng_condition_buffer_usage_get_threshold_ratio(const struct lttng_condition *condition,
+                                                double *threshold_ratio)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !IS_USAGE_CONDITION(condition) ||
-                       !threshold_ratio) {
+       if (!condition || !IS_USAGE_CONDITION(condition) || !threshold_ratio) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->threshold_ratio.set) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -611,21 +564,19 @@ end:
 
 /* threshold_ratio expressed as [0.0, 1.0]. */
 enum lttng_condition_status
-lttng_condition_buffer_usage_set_threshold_ratio(
-               struct lttng_condition *condition, double threshold_ratio)
+lttng_condition_buffer_usage_set_threshold_ratio(struct lttng_condition *condition,
+                                                double threshold_ratio)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !IS_USAGE_CONDITION(condition) ||
-                       threshold_ratio < 0.0 ||
-                       threshold_ratio > 1.0) {
+       if (!condition || !IS_USAGE_CONDITION(condition) || threshold_ratio < 0.0 ||
+           threshold_ratio > 1.0) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        usage->threshold_ratio.set = true;
        usage->threshold_bytes.set = false;
        usage->threshold_ratio.value = threshold_ratio;
@@ -634,9 +585,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_get_threshold(
-               const struct lttng_condition *condition,
-               uint64_t *threshold_bytes)
+lttng_condition_buffer_usage_get_threshold(const struct lttng_condition *condition,
+                                          uint64_t *threshold_bytes)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -646,8 +596,7 @@ lttng_condition_buffer_usage_get_threshold(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->threshold_bytes.set) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -658,8 +607,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_set_threshold(
-               struct lttng_condition *condition, uint64_t threshold_bytes)
+lttng_condition_buffer_usage_set_threshold(struct lttng_condition *condition,
+                                          uint64_t threshold_bytes)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -669,8 +618,7 @@ lttng_condition_buffer_usage_set_threshold(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        usage->threshold_ratio.set = false;
        usage->threshold_bytes.set = true;
        usage->threshold_bytes.value = threshold_bytes;
@@ -679,9 +627,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name)
+lttng_condition_buffer_usage_get_session_name(const struct lttng_condition *condition,
+                                             const char **session_name)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -691,8 +638,7 @@ lttng_condition_buffer_usage_get_session_name(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->session_name) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -703,21 +649,20 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_set_session_name(
-               struct lttng_condition *condition, const char *session_name)
+lttng_condition_buffer_usage_set_session_name(struct lttng_condition *condition,
+                                             const char *session_name)
 {
        char *session_name_copy;
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
        if (!condition || !IS_USAGE_CONDITION(condition) || !session_name ||
-                       strlen(session_name) == 0) {
+           strlen(session_name) == 0) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        session_name_copy = strdup(session_name);
        if (!session_name_copy) {
                status = LTTNG_CONDITION_STATUS_ERROR;
@@ -733,9 +678,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_get_channel_name(
-               const struct lttng_condition *condition,
-               const char **channel_name)
+lttng_condition_buffer_usage_get_channel_name(const struct lttng_condition *condition,
+                                             const char **channel_name)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -745,8 +689,7 @@ lttng_condition_buffer_usage_get_channel_name(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->channel_name) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -757,21 +700,20 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_set_channel_name(
-               struct lttng_condition *condition, const char *channel_name)
+lttng_condition_buffer_usage_set_channel_name(struct lttng_condition *condition,
+                                             const char *channel_name)
 {
        char *channel_name_copy;
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
        if (!condition || !IS_USAGE_CONDITION(condition) || !channel_name ||
-                       strlen(channel_name) == 0) {
+           strlen(channel_name) == 0) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        channel_name_copy = strdup(channel_name);
        if (!channel_name_copy) {
                status = LTTNG_CONDITION_STATUS_ERROR;
@@ -787,9 +729,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_get_domain_type(
-               const struct lttng_condition *condition,
-               enum lttng_domain_type *type)
+lttng_condition_buffer_usage_get_domain_type(const struct lttng_condition *condition,
+                                            enum lttng_domain_type *type)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -799,8 +740,7 @@ lttng_condition_buffer_usage_get_domain_type(
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        if (!usage->domain.set) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -811,56 +751,48 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_buffer_usage_set_domain_type(
-               struct lttng_condition *condition, enum lttng_domain_type type)
+lttng_condition_buffer_usage_set_domain_type(struct lttng_condition *condition,
+                                            enum lttng_domain_type type)
 {
        struct lttng_condition_buffer_usage *usage;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !IS_USAGE_CONDITION(condition) ||
-                       type == LTTNG_DOMAIN_NONE) {
+       if (!condition || !IS_USAGE_CONDITION(condition) || type == LTTNG_DOMAIN_NONE) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       usage = lttng::utils::container_of(condition,
-                       &lttng_condition_buffer_usage::parent);
+       usage = lttng::utils::container_of(condition, &lttng_condition_buffer_usage::parent);
        usage->domain.set = true;
        usage->domain.type = type;
 end:
        return status;
 }
 
-static
-int lttng_evaluation_buffer_usage_serialize(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload)
+static int lttng_evaluation_buffer_usage_serialize(const struct lttng_evaluation *evaluation,
+                                                  struct lttng_payload *payload)
 {
        struct lttng_evaluation_buffer_usage *usage;
        struct lttng_evaluation_buffer_usage_comm comm;
 
-       usage = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_buffer_usage::parent);
+       usage = lttng::utils::container_of(evaluation, &lttng_evaluation_buffer_usage::parent);
        comm.buffer_use = usage->buffer_use;
        comm.buffer_capacity = usage->buffer_capacity;
 
-       return lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       return lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
 }
 
-static
-void lttng_evaluation_buffer_usage_destroy(
-               struct lttng_evaluation *evaluation)
+static void lttng_evaluation_buffer_usage_destroy(struct lttng_evaluation *evaluation)
 {
        struct lttng_evaluation_buffer_usage *usage;
 
-       usage = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_buffer_usage::parent);
+       usage = lttng::utils::container_of(evaluation, &lttng_evaluation_buffer_usage::parent);
        free(usage);
 }
 
-struct lttng_evaluation *lttng_evaluation_buffer_usage_create(
-               enum lttng_condition_type type, uint64_t use, uint64_t capacity)
+struct lttng_evaluation *lttng_evaluation_buffer_usage_create(enum lttng_condition_type type,
+                                                             uint64_t use,
+                                                             uint64_t capacity)
 {
        struct lttng_evaluation_buffer_usage *usage;
 
@@ -883,8 +815,8 @@ end:
  * evaluate to "true".
  */
 enum lttng_evaluation_status
-lttng_evaluation_buffer_usage_get_usage_ratio(
-               const struct lttng_evaluation *evaluation, double *usage_ratio)
+lttng_evaluation_buffer_usage_get_usage_ratio(const struct lttng_evaluation *evaluation,
+                                             double *usage_ratio)
 {
        struct lttng_evaluation_buffer_usage *usage;
        enum lttng_evaluation_status status = LTTNG_EVALUATION_STATUS_OK;
@@ -894,18 +826,15 @@ lttng_evaluation_buffer_usage_get_usage_ratio(
                goto end;
        }
 
-       usage = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_buffer_usage::parent);
-       *usage_ratio = (double) usage->buffer_use /
-                       (double) usage->buffer_capacity;
+       usage = lttng::utils::container_of(evaluation, &lttng_evaluation_buffer_usage::parent);
+       *usage_ratio = (double) usage->buffer_use / (double) usage->buffer_capacity;
 end:
        return status;
 }
 
 enum lttng_evaluation_status
-lttng_evaluation_buffer_usage_get_usage(
-               const struct lttng_evaluation *evaluation,
-               uint64_t *usage_bytes)
+lttng_evaluation_buffer_usage_get_usage(const struct lttng_evaluation *evaluation,
+                                       uint64_t *usage_bytes)
 {
        struct lttng_evaluation_buffer_usage *usage;
        enum lttng_evaluation_status status = LTTNG_EVALUATION_STATUS_OK;
@@ -915,8 +844,7 @@ lttng_evaluation_buffer_usage_get_usage(
                goto end;
        }
 
-       usage = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_buffer_usage::parent);
+       usage = lttng::utils::container_of(evaluation, &lttng_evaluation_buffer_usage::parent);
        *usage_bytes = usage->buffer_use;
 end:
        return status;
index 1efab164d8c39610b509c32a1e898cf041836623..598a84dc8e96db637caa3eada6aba35a884fb3da 100644 (file)
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/condition/buffer-usage-internal.hpp>
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/condition/session-consumed-size-internal.hpp>
 #include <lttng/condition/session-rotation-internal.hpp>
 #include <lttng/error-query-internal.hpp>
+
 #include <stdbool.h>
 
-enum lttng_condition_type lttng_condition_get_type(
-               const struct lttng_condition *condition)
+enum lttng_condition_type lttng_condition_get_type(const struct lttng_condition *condition)
 {
        return condition ? condition->type : LTTNG_CONDITION_TYPE_UNKNOWN;
 }
@@ -31,8 +32,7 @@ void lttng_condition_destroy(struct lttng_condition *condition)
 
 static void condition_destroy_ref(struct urcu_ref *ref)
 {
-       struct lttng_condition *condition =
-               lttng::utils::container_of(ref, &lttng_condition::ref);
+       struct lttng_condition *condition = lttng::utils::container_of(ref, &lttng_condition::ref);
 
        condition->destroy(condition);
 }
@@ -52,7 +52,6 @@ void lttng_condition_put(struct lttng_condition *condition)
        urcu_ref_put(&condition->ref, condition_destroy_ref);
 }
 
-
 bool lttng_condition_validate(const struct lttng_condition *condition)
 {
        bool valid;
@@ -74,7 +73,7 @@ end:
 }
 
 int lttng_condition_serialize(const struct lttng_condition *condition,
-               struct lttng_payload *payload)
+                             struct lttng_payload *payload)
 {
        int ret;
        struct lttng_condition_comm condition_comm = {};
@@ -86,8 +85,8 @@ int lttng_condition_serialize(const struct lttng_condition *condition,
 
        condition_comm.condition_type = (int8_t) condition->type;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &condition_comm,
-                       sizeof(condition_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &condition_comm, sizeof(condition_comm));
        if (ret) {
                goto end;
        }
@@ -100,8 +99,7 @@ end:
        return ret;
 }
 
-bool lttng_condition_is_equal(const struct lttng_condition *a,
-               const struct lttng_condition *b)
+bool lttng_condition_is_equal(const struct lttng_condition *a, const struct lttng_condition *b)
 {
        bool is_equal = false;
 
@@ -123,16 +121,14 @@ end:
        return is_equal;
 }
 
-ssize_t lttng_condition_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition)
+ssize_t lttng_condition_create_from_payload(struct lttng_payload_view *view,
+                                           struct lttng_condition **condition)
 {
        ssize_t ret, condition_size = 0;
-       condition_create_from_payload_cb create_from_payload = NULL;
+       condition_create_from_payload_cb create_from_payload = nullptr;
        const struct lttng_condition_comm *condition_comm;
        const struct lttng_payload_view condition_comm_view =
-                       lttng_payload_view_from_view(
-                                       view, 0, sizeof(*condition_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*condition_comm));
 
        if (!view || !condition) {
                ret = -1;
@@ -163,23 +159,22 @@ ssize_t lttng_condition_create_from_payload(
                create_from_payload = lttng_condition_session_rotation_ongoing_create_from_payload;
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED:
-               create_from_payload = lttng_condition_session_rotation_completed_create_from_payload;
+               create_from_payload =
+                       lttng_condition_session_rotation_completed_create_from_payload;
                break;
        case LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES:
-               create_from_payload =
-                               lttng_condition_event_rule_matches_create_from_payload;
+               create_from_payload = lttng_condition_event_rule_matches_create_from_payload;
                break;
        default:
                ERR("Attempted to create condition of unknown type (%i)",
-                               (int) condition_comm->condition_type);
+                   (int) condition_comm->condition_type);
                ret = -1;
                goto end;
        }
 
        if (create_from_payload) {
                struct lttng_payload_view condition_view =
-                               lttng_payload_view_from_view(view,
-                                       sizeof(*condition_comm), -1);
+                       lttng_payload_view_from_view(view, sizeof(*condition_comm), -1);
 
                ret = create_from_payload(&condition_view, condition);
                if (ret < 0) {
@@ -196,8 +191,7 @@ end:
        return ret;
 }
 
-void lttng_condition_init(struct lttng_condition *condition,
-               enum lttng_condition_type type)
+void lttng_condition_init(struct lttng_condition *condition, enum lttng_condition_type type)
 {
        condition->type = type;
        urcu_ref_init(&condition->ref);
@@ -232,15 +226,15 @@ const char *lttng_condition_type_str(enum lttng_condition_type type)
        }
 }
 
-enum lttng_error_code lttng_condition_mi_serialize(
-               const struct lttng_trigger *trigger,
-               const struct lttng_condition *condition,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks *error_query_callbacks)
+enum lttng_error_code
+lttng_condition_mi_serialize(const struct lttng_trigger *trigger,
+                            const struct lttng_condition *condition,
+                            struct mi_writer *writer,
+                            const struct mi_lttng_error_query_callbacks *error_query_callbacks)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct lttng_error_query_results *error_query_results = NULL;
+       struct lttng_error_query_results *error_query_results = nullptr;
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(writer);
@@ -260,14 +254,12 @@ enum lttng_error_code lttng_condition_mi_serialize(
 
        /* Serialize error query results for the action. */
        if (error_query_callbacks && error_query_callbacks->action_cb) {
-               ret_code = error_query_callbacks->condition_cb(
-                               trigger, &error_query_results);
+               ret_code = error_query_callbacks->condition_cb(trigger, &error_query_results);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
 
-               ret_code = lttng_error_query_results_mi_serialize(
-                               error_query_results, writer);
+               ret_code = lttng_error_query_results_mi_serialize(error_query_results, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
index d302500c68a10aeefb381cc92e877167140586c9..d86d2ad7b048b036133f8e9ee8f66049287de5f6 100644 (file)
@@ -8,8 +8,7 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
-#include <inttypes.h>
-#include <limits.h>
+
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/condition/event-rule-matches.h>
 #include <lttng/event-field-value-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/lttng-error.h>
+
+#include <vendor/msgpack/msgpack.h>
+
+#include <inttypes.h>
+#include <limits.h>
 #include <stdbool.h>
 #include <stdint.h>
-#include <vendor/msgpack/msgpack.h>
 
 #define IS_EVENT_RULE_MATCHES_CONDITION(condition) \
-       (lttng_condition_get_type(condition) ==    \
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES)
+       (lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES)
 
-static bool is_event_rule_matches_evaluation(
-               const struct lttng_evaluation *evaluation)
+static bool is_event_rule_matches_evaluation(const struct lttng_evaluation *evaluation)
 {
        enum lttng_condition_type type = lttng_evaluation_get_type(evaluation);
 
        return type == LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES;
 }
 
-static bool lttng_condition_event_rule_matches_validate(
-               const struct lttng_condition *condition);
-static int lttng_condition_event_rule_matches_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload);
-static bool lttng_condition_event_rule_matches_is_equal(
-               const struct lttng_condition *_a,
-               const struct lttng_condition *_b);
-static void lttng_condition_event_rule_matches_destroy(
-               struct lttng_condition *condition);
-
-static bool lttng_condition_event_rule_matches_validate(
-               const struct lttng_condition *condition)
+static bool lttng_condition_event_rule_matches_validate(const struct lttng_condition *condition);
+static int lttng_condition_event_rule_matches_serialize(const struct lttng_condition *condition,
+                                                       struct lttng_payload *payload);
+static bool lttng_condition_event_rule_matches_is_equal(const struct lttng_condition *_a,
+                                                       const struct lttng_condition *_b);
+static void lttng_condition_event_rule_matches_destroy(struct lttng_condition *condition);
+
+static bool lttng_condition_event_rule_matches_validate(const struct lttng_condition *condition)
 {
        bool valid = false;
        struct lttng_condition_event_rule_matches *event_rule;
@@ -55,8 +51,8 @@ static bool lttng_condition_event_rule_matches_validate(
                goto end;
        }
 
-       event_rule = lttng::utils::container_of(condition,
-                       &lttng_condition_event_rule_matches::parent);
+       event_rule =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
        if (!event_rule->rule) {
                ERR("Invalid on event condition: a rule must be set");
                goto end;
@@ -119,15 +115,15 @@ static const char *msgpack_object_type_str(msgpack_object_type type)
  * Encoding is the length of `str` plus one (for the null character),
  * and then the string, including its null terminator.
  */
-static
-int serialize_cstr(const char *str, struct lttng_dynamic_buffer *buf)
+static int serialize_cstr(const char *str, struct lttng_dynamic_buffer *buf)
 {
        int ret;
        const uint32_t len = strlen(str) + 1;
 
        /* Serialize the length, including the null terminator. */
        DBG("Serializing C string's length (including null terminator): "
-                       "%" PRIu32, len);
+           "%" PRIu32,
+           len);
        ret = lttng_dynamic_buffer_append(buf, &len, sizeof(len));
        if (ret) {
                goto end;
@@ -147,9 +143,7 @@ end:
 /*
  * Serializes the event expression `expr` into `buf`.
  */
-static
-int serialize_event_expr(const struct lttng_event_expr *expr,
-               struct lttng_payload *payload)
+static int serialize_event_expr(const struct lttng_event_expr *expr, struct lttng_payload *payload)
 {
        const uint8_t type = expr->type;
        int ret;
@@ -167,12 +161,10 @@ int serialize_event_expr(const struct lttng_event_expr *expr,
        case LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD:
        {
                const struct lttng_event_expr_field *field_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_field::parent);
+                       lttng::utils::container_of(expr, &lttng_event_expr_field::parent);
 
                /* Serialize the field name. */
-               DBG("Serializing field event expression's field name: '%s'",
-                               field_expr->name);
+               DBG("Serializing field event expression's field name: '%s'", field_expr->name);
                ret = serialize_cstr(field_expr->name, &payload->buffer);
                if (ret) {
                        goto end;
@@ -183,13 +175,13 @@ int serialize_event_expr(const struct lttng_event_expr *expr,
        case LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD:
        {
                const struct lttng_event_expr_app_specific_context_field *field_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_app_specific_context_field::parent);
+                       lttng::utils::container_of(
+                               expr, &lttng_event_expr_app_specific_context_field::parent);
 
                /* Serialize the provider name. */
                DBG("Serializing app-specific context field event expression's "
-                               "provider name: '%s'",
-                               field_expr->provider_name);
+                   "provider name: '%s'",
+                   field_expr->provider_name);
                ret = serialize_cstr(field_expr->provider_name, &payload->buffer);
                if (ret) {
                        goto end;
@@ -197,8 +189,8 @@ int serialize_event_expr(const struct lttng_event_expr *expr,
 
                /* Serialize the type name. */
                DBG("Serializing app-specific context field event expression's "
-                               "type name: '%s'",
-                               field_expr->provider_name);
+                   "type name: '%s'",
+                   field_expr->provider_name);
                ret = serialize_cstr(field_expr->type_name, &payload->buffer);
                if (ret) {
                        goto end;
@@ -209,13 +201,14 @@ int serialize_event_expr(const struct lttng_event_expr *expr,
        case LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT:
        {
                const struct lttng_event_expr_array_field_element *elem_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_array_field_element::parent);
+                       lttng::utils::container_of(expr,
+                                                  &lttng_event_expr_array_field_element::parent);
                const uint32_t index = elem_expr->index;
 
                /* Serialize the index. */
                DBG("Serializing array field element event expression's "
-                               "index: %u", elem_expr->index);
+                   "index: %u",
+                   elem_expr->index);
                ret = lttng_dynamic_buffer_append(&payload->buffer, &index, sizeof(index));
                if (ret) {
                        goto end;
@@ -223,7 +216,7 @@ int serialize_event_expr(const struct lttng_event_expr *expr,
 
                /* Serialize the parent array field expression. */
                DBG("Serializing array field element event expression's "
-                               "parent array field event expression");
+                   "parent array field event expression");
                ret = serialize_event_expr(elem_expr->array_field_expr, payload);
                if (ret) {
                        goto end;
@@ -241,12 +234,11 @@ end:
 
 static struct lttng_capture_descriptor *
 lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
-               const struct lttng_condition *condition, unsigned int index)
+       const struct lttng_condition *condition, unsigned int index)
 {
-       const struct lttng_condition_event_rule_matches
-                       *event_rule_matches_cond = lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
-       struct lttng_capture_descriptor *desc = NULL;
+       const struct lttng_condition_event_rule_matches *event_rule_matches_cond =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
+       struct lttng_capture_descriptor *desc = nullptr;
        unsigned int count;
        enum lttng_condition_status status;
 
@@ -254,8 +246,7 @@ lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
                goto end;
        }
 
-       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &count);
+       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(condition, &count);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                goto end;
        }
@@ -265,14 +256,13 @@ lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
        }
 
        desc = (lttng_capture_descriptor *) lttng_dynamic_pointer_array_get_pointer(
-                       &event_rule_matches_cond->capture_descriptors, index);
+               &event_rule_matches_cond->capture_descriptors, index);
 end:
        return desc;
 }
 
-static int lttng_condition_event_rule_matches_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload)
+static int lttng_condition_event_rule_matches_serialize(const struct lttng_condition *condition,
+                                                       struct lttng_payload *payload)
 {
        int ret;
        struct lttng_condition_event_rule_matches *event_rule_matches_condition;
@@ -286,38 +276,36 @@ static int lttng_condition_event_rule_matches_serialize(
        }
 
        DBG("Serializing on event condition");
-       event_rule_matches_condition = lttng::utils::container_of(condition,
-                       &lttng_condition_event_rule_matches::parent);
+       event_rule_matches_condition =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
 
        DBG("Serializing on event condition's event rule");
-       ret = lttng_event_rule_serialize(
-                       event_rule_matches_condition->rule, payload);
+       ret = lttng_event_rule_serialize(event_rule_matches_condition->rule, payload);
        if (ret) {
                goto end;
        }
 
        status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &capture_descr_count);
+               condition, &capture_descr_count);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ret = -1;
                goto end;
        };
 
        DBG("Serializing on event condition's capture descriptor count: %" PRIu32,
-                       capture_descr_count);
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &capture_descr_count,
-                       sizeof(capture_descr_count));
+           capture_descr_count);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &capture_descr_count, sizeof(capture_descr_count));
        if (ret) {
                goto end;
        }
 
        for (i = 0; i < capture_descr_count; i++) {
                const struct lttng_capture_descriptor *desc =
-                               lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
-                                               condition, i);
+                       lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
+                               condition, i);
 
-               DBG("Serializing on event condition's capture descriptor %" PRIu32,
-                               i);
+               DBG("Serializing on event condition's capture descriptor %" PRIu32, i);
                ret = serialize_event_expr(desc->event_expression, payload);
                if (ret) {
                        goto end;
@@ -328,10 +316,8 @@ end:
        return ret;
 }
 
-static
-bool capture_descriptors_are_equal(
-               const struct lttng_condition *condition_a,
-               const struct lttng_condition *condition_b)
+static bool capture_descriptors_are_equal(const struct lttng_condition *condition_a,
+                                         const struct lttng_condition *condition_b)
 {
        bool is_equal = true;
        unsigned int capture_descr_count_a;
@@ -340,13 +326,13 @@ bool capture_descriptors_are_equal(
        enum lttng_condition_status status;
 
        status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition_a, &capture_descr_count_a);
+               condition_a, &capture_descr_count_a);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                goto not_equal;
        }
 
        status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition_b, &capture_descr_count_b);
+               condition_b, &capture_descr_count_b);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                goto not_equal;
        }
@@ -357,11 +343,11 @@ bool capture_descriptors_are_equal(
 
        for (i = 0; i < capture_descr_count_a; i++) {
                const struct lttng_event_expr *expr_a =
-                               lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-                                               condition_a, i);
+                       lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
+                               condition_a, i);
                const struct lttng_event_expr *expr_b =
-                               lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-                                               condition_b, i);
+                       lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
+                               condition_b, i);
 
                if (!lttng_event_expr_is_equal(expr_a, expr_b)) {
                        goto not_equal;
@@ -377,9 +363,8 @@ end:
        return is_equal;
 }
 
-static bool lttng_condition_event_rule_matches_is_equal(
-               const struct lttng_condition *_a,
-               const struct lttng_condition *_b)
+static bool lttng_condition_event_rule_matches_is_equal(const struct lttng_condition *_a,
+                                                       const struct lttng_condition *_b)
 {
        bool is_equal = false;
        struct lttng_condition_event_rule_matches *a, *b;
@@ -404,39 +389,35 @@ end:
        return is_equal;
 }
 
-static void lttng_condition_event_rule_matches_destroy(
-               struct lttng_condition *condition)
+static void lttng_condition_event_rule_matches_destroy(struct lttng_condition *condition)
 {
        struct lttng_condition_event_rule_matches *event_rule_matches_condition;
 
-       event_rule_matches_condition = lttng::utils::container_of(condition,
-                       &lttng_condition_event_rule_matches::parent);
+       event_rule_matches_condition =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
 
        lttng_event_rule_put(event_rule_matches_condition->rule);
-       lttng_dynamic_pointer_array_reset(
-                       &event_rule_matches_condition->capture_descriptors);
+       lttng_dynamic_pointer_array_reset(&event_rule_matches_condition->capture_descriptors);
        free(event_rule_matches_condition);
 }
 
-static
-void destroy_capture_descriptor(void *ptr)
+static void destroy_capture_descriptor(void *ptr)
 {
-       struct lttng_capture_descriptor *desc =
-                       (struct lttng_capture_descriptor *) ptr;
+       struct lttng_capture_descriptor *desc = (struct lttng_capture_descriptor *) ptr;
 
        lttng_event_expr_destroy(desc->event_expression);
        free(desc->bytecode);
        free(desc);
 }
 
-static enum lttng_error_code lttng_condition_event_rule_matches_mi_serialize(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_condition_event_rule_matches_mi_serialize(const struct lttng_condition *condition,
+                                               struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_condition_status status;
-       const struct lttng_event_rule *rule = NULL;
+       const struct lttng_event_rule *rule = nullptr;
        unsigned int capture_descriptor_count, i;
 
        LTTNG_ASSERT(condition);
@@ -445,15 +426,14 @@ static enum lttng_error_code lttng_condition_event_rule_matches_mi_serialize(
 
        status = lttng_condition_event_rule_matches_get_rule(condition, &rule);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
-       LTTNG_ASSERT(rule != NULL);
+       LTTNG_ASSERT(rule != nullptr);
 
        status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &capture_descriptor_count);
+               condition, &capture_descriptor_count);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
 
        /* Open condition event rule matches element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_condition_event_rule_matches);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_condition_event_rule_matches);
        if (ret) {
                goto mi_error;
        }
@@ -465,17 +445,16 @@ static enum lttng_error_code lttng_condition_event_rule_matches_mi_serialize(
        }
 
        /* Open the capture descriptors element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_capture_descriptors);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_capture_descriptors);
        if (ret) {
                goto mi_error;
        }
 
        for (i = 0; i < capture_descriptor_count; i++) {
-               const struct lttng_event_expr *descriptor = NULL;
+               const struct lttng_event_expr *descriptor = nullptr;
 
                descriptor = lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-                               condition, i);
+                       condition, i);
                LTTNG_ASSERT(descriptor);
 
                ret_code = lttng_event_expr_mi_serialize(descriptor, writer);
@@ -504,11 +483,10 @@ end:
        return ret_code;
 }
 
-struct lttng_condition *lttng_condition_event_rule_matches_create(
-               struct lttng_event_rule *rule)
+struct lttng_condition *lttng_condition_event_rule_matches_create(struct lttng_event_rule *rule)
 {
-       struct lttng_condition *parent = NULL;
-       struct lttng_condition_event_rule_matches *condition = NULL;
+       struct lttng_condition *parent = nullptr;
+       struct lttng_condition_event_rule_matches *condition = nullptr;
 
        if (!rule) {
                goto end;
@@ -516,38 +494,32 @@ struct lttng_condition *lttng_condition_event_rule_matches_create(
 
        condition = zmalloc<lttng_condition_event_rule_matches>();
        if (!condition) {
-               return NULL;
+               return nullptr;
        }
 
-       lttng_condition_init(&condition->parent,
-                       LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
-       condition->parent.validate =
-                       lttng_condition_event_rule_matches_validate,
-       condition->parent.serialize =
-                       lttng_condition_event_rule_matches_serialize,
+       lttng_condition_init(&condition->parent, LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+       condition->parent.validate = lttng_condition_event_rule_matches_validate,
+       condition->parent.serialize = lttng_condition_event_rule_matches_serialize,
        condition->parent.equal = lttng_condition_event_rule_matches_is_equal,
        condition->parent.destroy = lttng_condition_event_rule_matches_destroy,
        condition->parent.mi_serialize = lttng_condition_event_rule_matches_mi_serialize,
 
        lttng_event_rule_get(rule);
        condition->rule = rule;
-       rule = NULL;
+       rule = nullptr;
 
        lttng_dynamic_pointer_array_init(&condition->capture_descriptors,
-                       destroy_capture_descriptor);
+                                        destroy_capture_descriptor);
 
        parent = &condition->parent;
 end:
        return parent;
 }
 
-static
-uint64_t uint_from_buffer(const struct lttng_buffer_view *view, size_t size,
-               size_t *offset)
+static uint64_t uint_from_buffer(const struct lttng_buffer_view *view, size_t size, size_t *offset)
 {
        uint64_t ret;
-       const struct lttng_buffer_view uint_view =
-                       lttng_buffer_view_from_view(view, *offset, size);
+       const struct lttng_buffer_view uint_view = lttng_buffer_view_from_view(view, *offset, size);
 
        if (!lttng_buffer_view_is_valid(&uint_view)) {
                ret = UINT64_C(-1);
@@ -556,7 +528,7 @@ uint64_t uint_from_buffer(const struct lttng_buffer_view *view, size_t size,
 
        switch (size) {
        case 1:
-               ret = (uint64_t) *uint_view.data;
+               ret = (unsigned char) *uint_view.data;
                break;
        case sizeof(uint32_t):
        {
@@ -579,9 +551,7 @@ end:
        return ret;
 }
 
-static
-const char *str_from_buffer(const struct lttng_buffer_view *view,
-               size_t *offset)
+static const char *str_from_buffer(const struct lttng_buffer_view *view, size_t *offset)
 {
        uint64_t len;
        const char *ret;
@@ -601,17 +571,16 @@ const char *str_from_buffer(const struct lttng_buffer_view *view,
        goto end;
 
 error:
-       ret = NULL;
+       ret = nullptr;
 
 end:
        return ret;
 }
 
-static
-struct lttng_event_expr *event_expr_from_payload(
-               struct lttng_payload_view *view, size_t *offset)
+static struct lttng_event_expr *event_expr_from_payload(struct lttng_payload_view *view,
+                                                       size_t *offset)
 {
-       struct lttng_event_expr *expr = NULL;
+       struct lttng_event_expr *expr = nullptr;
        const char *str;
        uint64_t type;
 
@@ -652,15 +621,13 @@ struct lttng_event_expr *event_expr_from_payload(
                        goto error;
                }
 
-               expr = lttng_event_expr_app_specific_context_field_create(
-                               provider_name, type_name);
+               expr = lttng_event_expr_app_specific_context_field_create(provider_name, type_name);
                break;
        }
        case LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT:
        {
                struct lttng_event_expr *array_field_expr;
-               const uint64_t index = uint_from_buffer(
-                               &view->buffer, sizeof(uint32_t), offset);
+               const uint64_t index = uint_from_buffer(&view->buffer, sizeof(uint32_t), offset);
 
                if (index == UINT64_C(-1)) {
                        goto error;
@@ -673,8 +640,8 @@ struct lttng_event_expr *event_expr_from_payload(
                }
 
                /* Move ownership of `array_field_expr` to new expression. */
-               expr = lttng_event_expr_array_field_element_create(
-                               array_field_expr, (unsigned int) index);
+               expr = lttng_event_expr_array_field_element_create(array_field_expr,
+                                                                  (unsigned int) index);
                if (!expr) {
                        /* `array_field_expr` not moved: destroy it. */
                        lttng_event_expr_destroy(array_field_expr);
@@ -684,7 +651,7 @@ struct lttng_event_expr *event_expr_from_payload(
        }
        default:
                ERR("Invalid event expression type encoutered while deserializing event expression: type = %" PRIu64,
-                               type);
+                   type);
                goto error;
        }
 
@@ -692,22 +659,21 @@ struct lttng_event_expr *event_expr_from_payload(
 
 error:
        lttng_event_expr_destroy(expr);
-       expr = NULL;
+       expr = nullptr;
 
 end:
        return expr;
 }
 
-ssize_t lttng_condition_event_rule_matches_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **_condition)
+ssize_t lttng_condition_event_rule_matches_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_condition **_condition)
 {
        ssize_t consumed_length;
        size_t offset = 0;
        ssize_t event_rule_length;
        uint32_t i, capture_descr_count;
-       struct lttng_condition *condition = NULL;
-       struct lttng_event_rule *event_rule = NULL;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
 
        if (!view || !_condition) {
                goto error;
@@ -716,10 +682,10 @@ ssize_t lttng_condition_event_rule_matches_create_from_payload(
        /* Struct lttng_event_rule. */
        {
                struct lttng_payload_view event_rule_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
-               event_rule_length = lttng_event_rule_create_from_payload(
-                               &event_rule_view, &event_rule);
+               event_rule_length =
+                       lttng_event_rule_create_from_payload(&event_rule_view, &event_rule);
        }
 
        if (event_rule_length < 0 || !event_rule) {
@@ -744,16 +710,15 @@ ssize_t lttng_condition_event_rule_matches_create_from_payload(
        /* Capture descriptors. */
        for (i = 0; i < capture_descr_count; i++) {
                enum lttng_condition_status status;
-               struct lttng_event_expr *expr = event_expr_from_payload(
-                               view, &offset);
+               struct lttng_event_expr *expr = event_expr_from_payload(view, &offset);
 
                if (!expr) {
                        goto error;
                }
 
                /* Move ownership of `expr` to `condition`. */
-               status = lttng_condition_event_rule_matches_append_capture_descriptor(
-                               condition, expr);
+               status = lttng_condition_event_rule_matches_append_capture_descriptor(condition,
+                                                                                     expr);
                if (status != LTTNG_CONDITION_STATUS_OK) {
                        /* `expr` not moved: destroy it. */
                        lttng_event_expr_destroy(expr);
@@ -763,7 +728,7 @@ ssize_t lttng_condition_event_rule_matches_create_from_payload(
 
        consumed_length = (ssize_t) offset;
        *_condition = condition;
-       condition = NULL;
+       condition = nullptr;
        goto end;
 
 error:
@@ -776,21 +741,19 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_event_rule_matches_borrow_rule_mutable(
-               const struct lttng_condition *condition,
-               struct lttng_event_rule **rule)
+lttng_condition_event_rule_matches_borrow_rule_mutable(const struct lttng_condition *condition,
+                                                      struct lttng_event_rule **rule)
 {
        struct lttng_condition_event_rule_matches *event_rule;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) ||
-                       !rule) {
+       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) || !rule) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       event_rule = lttng::utils::container_of(condition,
-                       &lttng_condition_event_rule_matches::parent);
+       event_rule =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
        if (!event_rule->rule) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -801,56 +764,50 @@ end:
        return status;
 }
 
-enum lttng_condition_status lttng_condition_event_rule_matches_get_rule(
-               const struct lttng_condition *condition,
-               const struct lttng_event_rule **rule)
+enum lttng_condition_status
+lttng_condition_event_rule_matches_get_rule(const struct lttng_condition *condition,
+                                           const struct lttng_event_rule **rule)
 {
-       struct lttng_event_rule *mutable_rule = NULL;
+       struct lttng_event_rule *mutable_rule = nullptr;
        const enum lttng_condition_status status =
-                       lttng_condition_event_rule_matches_borrow_rule_mutable(
-                                       condition, &mutable_rule);
+               lttng_condition_event_rule_matches_borrow_rule_mutable(condition, &mutable_rule);
 
        *rule = mutable_rule;
        return status;
 }
 
-void lttng_condition_event_rule_matches_set_error_counter_index(
-               struct lttng_condition *condition, uint64_t error_counter_index)
+void lttng_condition_event_rule_matches_set_error_counter_index(struct lttng_condition *condition,
+                                                               uint64_t error_counter_index)
 {
        struct lttng_condition_event_rule_matches *event_rule_matches_cond =
-                       lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
 
-       LTTNG_OPTIONAL_SET(&event_rule_matches_cond->error_counter_index,
-                       error_counter_index);
+       LTTNG_OPTIONAL_SET(&event_rule_matches_cond->error_counter_index, error_counter_index);
 }
 
-uint64_t lttng_condition_event_rule_matches_get_error_counter_index(
-               const struct lttng_condition *condition)
+uint64_t
+lttng_condition_event_rule_matches_get_error_counter_index(const struct lttng_condition *condition)
 {
-       const struct lttng_condition_event_rule_matches
-                       *event_rule_matches_cond = lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
+       const struct lttng_condition_event_rule_matches *event_rule_matches_cond =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
 
        return LTTNG_OPTIONAL_GET(event_rule_matches_cond->error_counter_index);
 }
 
 enum lttng_condition_status
-lttng_condition_event_rule_matches_append_capture_descriptor(
-               struct lttng_condition *condition,
-               struct lttng_event_expr *expr)
+lttng_condition_event_rule_matches_append_capture_descriptor(struct lttng_condition *condition,
+                                                            struct lttng_event_expr *expr)
 {
        int ret;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
        struct lttng_condition_event_rule_matches *event_rule_matches_cond =
-                       lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
-       struct lttng_capture_descriptor *descriptor = NULL;
-       const struct lttng_event_rule *rule = NULL;
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
+       struct lttng_capture_descriptor *descriptor = nullptr;
+       const struct lttng_event_rule *rule = nullptr;
 
        /* Only accept l-values. */
-       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) ||
-                       !expr || !lttng_event_expr_is_lvalue(expr)) {
+       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) || !expr ||
+           !lttng_event_expr_is_lvalue(expr)) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
@@ -860,7 +817,7 @@ lttng_condition_event_rule_matches_append_capture_descriptor(
                goto end;
        }
 
-       switch(lttng_event_rule_get_type(rule)) {
+       switch (lttng_event_rule_get_type(rule)) {
        case LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT:
        case LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT:
        case LTTNG_EVENT_RULE_TYPE_JUL_LOGGING:
@@ -883,61 +840,56 @@ lttng_condition_event_rule_matches_append_capture_descriptor(
        }
 
        descriptor = malloc<lttng_capture_descriptor>();
-       if (descriptor == NULL) {
+       if (descriptor == nullptr) {
                status = LTTNG_CONDITION_STATUS_ERROR;
                goto end;
        }
 
        descriptor->event_expression = expr;
-       descriptor->bytecode = NULL;
+       descriptor->bytecode = nullptr;
 
-       ret = lttng_dynamic_pointer_array_add_pointer(
-                       &event_rule_matches_cond->capture_descriptors,
-                       descriptor);
+       ret = lttng_dynamic_pointer_array_add_pointer(&event_rule_matches_cond->capture_descriptors,
+                                                     descriptor);
        if (ret) {
                status = LTTNG_CONDITION_STATUS_ERROR;
                goto end;
        }
 
        /* Ownership is transfered to the internal capture_descriptors array */
-       descriptor = NULL;
+       descriptor = nullptr;
 end:
        free(descriptor);
        return status;
 }
 
-enum lttng_condition_status
-lttng_condition_event_rule_matches_get_capture_descriptor_count(
-               const struct lttng_condition *condition, unsigned int *count)
+enum lttng_condition_status lttng_condition_event_rule_matches_get_capture_descriptor_count(
+       const struct lttng_condition *condition, unsigned int *count)
 {
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
-       const struct lttng_condition_event_rule_matches
-                       *event_rule_matches_condition = lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
+       const struct lttng_condition_event_rule_matches *event_rule_matches_condition =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
 
-       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) ||
-                       !count) {
+       if (!condition || !IS_EVENT_RULE_MATCHES_CONDITION(condition) || !count) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
        *count = lttng_dynamic_pointer_array_get_count(
-                       &event_rule_matches_condition->capture_descriptors);
+               &event_rule_matches_condition->capture_descriptors);
 
 end:
        return status;
 }
 
-const struct lttng_event_expr *
-lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
-               const struct lttng_condition *condition, unsigned int index)
+const struct lttng_event_expr *lttng_condition_event_rule_matches_get_capture_descriptor_at_index(
+       const struct lttng_condition *condition, unsigned int index)
 {
-       const struct lttng_event_expr *expr = NULL;
-       const struct lttng_capture_descriptor *desc = NULL;
+       const struct lttng_event_expr *expr = nullptr;
+       const struct lttng_capture_descriptor *desc = nullptr;
 
        desc = lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
-                       condition, index);
-       if (desc == NULL) {
+               condition, index);
+       if (desc == nullptr) {
                goto end;
        }
        expr = desc->event_expression;
@@ -947,14 +899,14 @@ end:
 }
 
 ssize_t lttng_evaluation_event_rule_matches_create_from_payload(
-               const struct lttng_condition_event_rule_matches *condition,
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+       const struct lttng_condition_event_rule_matches *condition,
+       struct lttng_payload_view *view,
+       struct lttng_evaluation **_evaluation)
 {
        ssize_t ret, offset = 0;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
        uint32_t capture_payload_size;
-       const char *capture_payload = NULL;
+       const char *capture_payload = nullptr;
 
        if (!_evaluation) {
                ret = -1;
@@ -963,21 +915,22 @@ ssize_t lttng_evaluation_event_rule_matches_create_from_payload(
 
        {
                const struct lttng_payload_view current_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
                if (current_view.buffer.size < sizeof(capture_payload_size)) {
                        ret = -1;
                        goto error;
                }
 
-               memcpy(&capture_payload_size, current_view.buffer.data,
-                               sizeof(capture_payload_size));
+               memcpy(&capture_payload_size,
+                      current_view.buffer.data,
+                      sizeof(capture_payload_size));
        }
        offset += sizeof(capture_payload_size);
 
        if (capture_payload_size > 0) {
                const struct lttng_payload_view current_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
                if (current_view.buffer.size < capture_payload_size) {
                        ret = -1;
@@ -988,7 +941,7 @@ ssize_t lttng_evaluation_event_rule_matches_create_from_payload(
        }
 
        evaluation = lttng_evaluation_event_rule_matches_create(
-                       condition, capture_payload, capture_payload_size, true);
+               condition, capture_payload, capture_payload_size, true);
        if (!evaluation) {
                ret = -1;
                goto error;
@@ -996,7 +949,7 @@ ssize_t lttng_evaluation_event_rule_matches_create_from_payload(
 
        offset += capture_payload_size;
        *_evaluation = evaluation;
-       evaluation = NULL;
+       evaluation = nullptr;
        ret = offset;
 
 error:
@@ -1004,26 +957,24 @@ error:
        return ret;
 }
 
-static int lttng_evaluation_event_rule_matches_serialize(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload)
+static int lttng_evaluation_event_rule_matches_serialize(const struct lttng_evaluation *evaluation,
+                                                        struct lttng_payload *payload)
 {
        int ret = 0;
        struct lttng_evaluation_event_rule_matches *hit;
        uint32_t capture_payload_size;
 
-       hit = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_event_rule_matches::parent);
+       hit = lttng::utils::container_of(evaluation, &lttng_evaluation_event_rule_matches::parent);
 
        capture_payload_size = (uint32_t) hit->capture_payload.size;
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &capture_payload_size,
-                       sizeof(capture_payload_size));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &capture_payload_size, sizeof(capture_payload_size));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, hit->capture_payload.data,
-                       hit->capture_payload.size);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, hit->capture_payload.data, hit->capture_payload.size);
        if (ret) {
                goto end;
        }
@@ -1032,8 +983,7 @@ end:
        return ret;
 }
 
-static
-bool msgpack_str_is_equal(const struct msgpack_object *obj, const char *str)
+static bool msgpack_str_is_equal(const struct msgpack_object *obj, const char *str)
 {
        bool is_equal = true;
 
@@ -1053,11 +1003,10 @@ end:
        return is_equal;
 }
 
-static
-const msgpack_object *get_msgpack_map_obj(const struct msgpack_object *map_obj,
-               const char *name)
+static const msgpack_object *get_msgpack_map_obj(const struct msgpack_object *map_obj,
+                                                const char *name)
 {
-       const msgpack_object *ret = NULL;
+       const msgpack_object *ret = nullptr;
        size_t i;
 
        LTTNG_ASSERT(map_obj->type == MSGPACK_OBJECT_MAP);
@@ -1077,21 +1026,18 @@ end:
        return ret;
 }
 
-static void lttng_evaluation_event_rule_matches_destroy(
-               struct lttng_evaluation *evaluation)
+static void lttng_evaluation_event_rule_matches_destroy(struct lttng_evaluation *evaluation)
 {
        struct lttng_evaluation_event_rule_matches *hit;
 
-       hit = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_event_rule_matches::parent);
+       hit = lttng::utils::container_of(evaluation, &lttng_evaluation_event_rule_matches::parent);
        lttng_dynamic_buffer_reset(&hit->capture_payload);
        lttng_event_field_value_destroy(hit->captured_values);
        free(hit);
 }
 
-static
-int event_field_value_from_obj(const msgpack_object *obj,
-               struct lttng_event_field_value **field_val)
+static int event_field_value_from_obj(const msgpack_object *obj,
+                                     struct lttng_event_field_value **field_val)
 {
        int ret = 0;
 
@@ -1101,24 +1047,21 @@ int event_field_value_from_obj(const msgpack_object *obj,
        switch (obj->type) {
        case MSGPACK_OBJECT_NIL:
                /* Unavailable. */
-               *field_val = NULL;
+               *field_val = nullptr;
                goto end;
        case MSGPACK_OBJECT_POSITIVE_INTEGER:
-               *field_val = lttng_event_field_value_uint_create(
-                               obj->via.u64);
+               *field_val = lttng_event_field_value_uint_create(obj->via.u64);
                break;
        case MSGPACK_OBJECT_NEGATIVE_INTEGER:
-               *field_val = lttng_event_field_value_int_create(
-                               obj->via.i64);
+               *field_val = lttng_event_field_value_int_create(obj->via.i64);
                break;
        case MSGPACK_OBJECT_FLOAT32:
        case MSGPACK_OBJECT_FLOAT64:
-               *field_val = lttng_event_field_value_real_create(
-                               obj->via.f64);
+               *field_val = lttng_event_field_value_real_create(obj->via.f64);
                break;
        case MSGPACK_OBJECT_STR:
-               *field_val = lttng_event_field_value_string_create_with_size(
-                               obj->via.str.ptr, obj->via.str.size);
+               *field_val = lttng_event_field_value_string_create_with_size(obj->via.str.ptr,
+                                                                            obj->via.str.size);
                break;
        case MSGPACK_OBJECT_ARRAY:
        {
@@ -1133,18 +1076,16 @@ int event_field_value_from_obj(const msgpack_object *obj,
                        const msgpack_object *elem_obj = &obj->via.array.ptr[i];
                        struct lttng_event_field_value *elem_field_val;
 
-                       ret = event_field_value_from_obj(elem_obj,
-                                       &elem_field_val);
+                       ret = event_field_value_from_obj(elem_obj, &elem_field_val);
                        if (ret) {
                                goto error;
                        }
 
                        if (elem_field_val) {
-                               ret = lttng_event_field_value_array_append(
-                                               *field_val, elem_field_val);
+                               ret = lttng_event_field_value_array_append(*field_val,
+                                                                          elem_field_val);
                        } else {
-                               ret = lttng_event_field_value_array_append_unavailable(
-                                               *field_val);
+                               ret = lttng_event_field_value_array_append_unavailable(*field_val);
                        }
 
                        if (ret) {
@@ -1179,7 +1120,7 @@ int event_field_value_from_obj(const msgpack_object *obj,
 
                if (inner_obj->type != MSGPACK_OBJECT_STR) {
                        ERR("Map object's `type` entry is not a string: type = %s",
-                                       msgpack_object_type_str(inner_obj->type));
+                           msgpack_object_type_str(inner_obj->type));
                        goto error;
                }
 
@@ -1195,14 +1136,12 @@ int event_field_value_from_obj(const msgpack_object *obj,
                }
 
                if (inner_obj->type == MSGPACK_OBJECT_POSITIVE_INTEGER) {
-                       *field_val = lttng_event_field_value_enum_uint_create(
-                                       inner_obj->via.u64);
+                       *field_val = lttng_event_field_value_enum_uint_create(inner_obj->via.u64);
                } else if (inner_obj->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) {
-                       *field_val = lttng_event_field_value_enum_int_create(
-                                       inner_obj->via.i64);
+                       *field_val = lttng_event_field_value_enum_int_create(inner_obj->via.i64);
                } else {
                        ERR("Map object's `value` entry is not an integer: type = %s",
-                                       msgpack_object_type_str(inner_obj->type));
+                           msgpack_object_type_str(inner_obj->type));
                        goto error;
                }
 
@@ -1218,25 +1157,22 @@ int event_field_value_from_obj(const msgpack_object *obj,
 
                if (inner_obj->type != MSGPACK_OBJECT_ARRAY) {
                        ERR("Map object's `labels` entry is not an array: type = %s",
-                                       msgpack_object_type_str(inner_obj->type));
+                           msgpack_object_type_str(inner_obj->type));
                        goto error;
                }
 
-               for (label_i = 0; label_i < inner_obj->via.array.size;
-                               label_i++) {
+               for (label_i = 0; label_i < inner_obj->via.array.size; label_i++) {
                        int iret;
-                       const msgpack_object *elem_obj =
-                                       &inner_obj->via.array.ptr[label_i];
+                       const msgpack_object *elem_obj = &inner_obj->via.array.ptr[label_i];
 
                        if (elem_obj->type != MSGPACK_OBJECT_STR) {
                                ERR("Map object's `labels` entry's type is not a string: type = %s",
-                                               msgpack_object_type_str(elem_obj->type));
+                                   msgpack_object_type_str(elem_obj->type));
                                goto error;
                        }
 
                        iret = lttng_event_field_value_enum_append_label_with_size(
-                                       *field_val, elem_obj->via.str.ptr,
-                                       elem_obj->via.str.size);
+                               *field_val, elem_obj->via.str.ptr, elem_obj->via.str.size);
                        if (iret) {
                                goto error;
                        }
@@ -1245,8 +1181,7 @@ int event_field_value_from_obj(const msgpack_object *obj,
                break;
        }
        default:
-               ERR("Unexpected object type: type = %s",
-                               msgpack_object_type_str(obj->type));
+               ERR("Unexpected object type: type = %s", msgpack_object_type_str(obj->type));
                goto error;
        }
 
@@ -1258,19 +1193,19 @@ int event_field_value_from_obj(const msgpack_object *obj,
 
 error:
        lttng_event_field_value_destroy(*field_val);
-       *field_val = NULL;
+       *field_val = nullptr;
        ret = -1;
 
 end:
        return ret;
 }
 
-static struct lttng_event_field_value *event_field_value_from_capture_payload(
-               const struct lttng_condition_event_rule_matches *condition,
-               const char *capture_payload,
-               size_t capture_payload_size)
+static struct lttng_event_field_value *
+event_field_value_from_capture_payload(const struct lttng_condition_event_rule_matches *condition,
+                                      const char *capture_payload,
+                                      size_t capture_payload_size)
 {
-       struct lttng_event_field_value *ret = NULL;
+       struct lttng_event_field_value *ret = nullptr;
        msgpack_unpacked unpacked;
        msgpack_unpack_return unpack_return;
        const msgpack_object *root_obj;
@@ -1285,13 +1220,14 @@ static struct lttng_event_field_value *event_field_value_from_capture_payload(
        msgpack_unpacked_init(&unpacked);
 
        /* Decode. */
-       unpack_return = msgpack_unpack_next(&unpacked, capture_payload,
-                       capture_payload_size, NULL);
+       unpack_return =
+               msgpack_unpack_next(&unpacked, capture_payload, capture_payload_size, nullptr);
        if (unpack_return != MSGPACK_UNPACK_SUCCESS) {
                ERR("msgpack_unpack_next() failed to decode the "
-                               "MessagePack-encoded capture payload: "
-                               "size = %zu, ret = %d",
-                               capture_payload_size, unpack_return);
+                   "MessagePack-encoded capture payload: "
+                   "size = %zu, ret = %d",
+                   capture_payload_size,
+                   unpack_return);
                goto error;
        }
 
@@ -1300,7 +1236,7 @@ static struct lttng_event_field_value *event_field_value_from_capture_payload(
 
        if (root_obj->type != MSGPACK_OBJECT_ARRAY) {
                ERR("Expecting an array as the root object: type = %s",
-                               msgpack_object_type_str(root_obj->type));
+                   msgpack_object_type_str(root_obj->type));
                goto error;
        }
 
@@ -1322,14 +1258,13 @@ static struct lttng_event_field_value *event_field_value_from_capture_payload(
         *
         * 3. Append it to `ret` (the root array event field value).
         */
-       count = lttng_dynamic_pointer_array_get_count(
-                       &condition->capture_descriptors);
+       count = lttng_dynamic_pointer_array_get_count(&condition->capture_descriptors);
        LTTNG_ASSERT(count > 0);
 
        for (i = 0; i < count; i++) {
                const struct lttng_capture_descriptor *capture_descriptor =
-                               lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
-                                               &condition->parent, i);
+                       lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
+                               &condition->parent, i);
                const msgpack_object *elem_obj;
                struct lttng_event_field_value *elem_field_val;
                int iret;
@@ -1337,18 +1272,15 @@ static struct lttng_event_field_value *event_field_value_from_capture_payload(
                LTTNG_ASSERT(capture_descriptor);
 
                elem_obj = &root_array_obj->ptr[i];
-               iret = event_field_value_from_obj(elem_obj,
-                               &elem_field_val);
+               iret = event_field_value_from_obj(elem_obj, &elem_field_val);
                if (iret) {
                        goto error;
                }
 
                if (elem_field_val) {
-                       iret = lttng_event_field_value_array_append(ret,
-                                       elem_field_val);
+                       iret = lttng_event_field_value_array_append(ret, elem_field_val);
                } else {
-                       iret = lttng_event_field_value_array_append_unavailable(
-                                       ret);
+                       iret = lttng_event_field_value_array_append_unavailable(ret);
                }
 
                if (iret) {
@@ -1361,7 +1293,7 @@ static struct lttng_event_field_value *event_field_value_from_capture_payload(
 
 error:
        lttng_event_field_value_destroy(ret);
-       ret = NULL;
+       ret = nullptr;
 
 end:
        msgpack_unpacked_destroy(&unpacked);
@@ -1369,13 +1301,13 @@ end:
 }
 
 struct lttng_evaluation *lttng_evaluation_event_rule_matches_create(
-               const struct lttng_condition_event_rule_matches *condition,
-               const char *capture_payload,
-               size_t capture_payload_size,
-               bool decode_capture_payload)
+       const struct lttng_condition_event_rule_matches *condition,
+       const char *capture_payload,
+       size_t capture_payload_size,
+       bool decode_capture_payload)
 {
        struct lttng_evaluation_event_rule_matches *hit;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
 
        hit = zmalloc<lttng_evaluation_event_rule_matches>();
        if (!hit) {
@@ -1386,22 +1318,18 @@ struct lttng_evaluation *lttng_evaluation_event_rule_matches_create(
 
        if (capture_payload) {
                const int ret = lttng_dynamic_buffer_append(
-                               &hit->capture_payload, capture_payload,
-                               capture_payload_size);
+                       &hit->capture_payload, capture_payload, capture_payload_size);
                if (ret) {
                        ERR("Failed to initialize capture payload of event rule evaluation");
                        goto error;
                }
 
                if (decode_capture_payload) {
-                       hit->captured_values =
-                                       event_field_value_from_capture_payload(
-                                               condition,
-                                               capture_payload,
-                                               capture_payload_size);
+                       hit->captured_values = event_field_value_from_capture_payload(
+                               condition, capture_payload, capture_payload_size);
                        if (!hit->captured_values) {
                                ERR("Failed to decode the capture payload: size = %zu",
-                                               capture_payload_size);
+                                   capture_payload_size);
                                goto error;
                        }
                }
@@ -1412,7 +1340,7 @@ struct lttng_evaluation *lttng_evaluation_event_rule_matches_create(
        hit->parent.destroy = lttng_evaluation_event_rule_matches_destroy;
 
        evaluation = &hit->parent;
-       hit = NULL;
+       hit = nullptr;
 
 error:
        if (hit) {
@@ -1424,21 +1352,18 @@ error:
 
 enum lttng_evaluation_event_rule_matches_status
 lttng_evaluation_event_rule_matches_get_captured_values(
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_event_field_value **field_val)
+       const struct lttng_evaluation *evaluation, const struct lttng_event_field_value **field_val)
 {
        struct lttng_evaluation_event_rule_matches *hit;
        enum lttng_evaluation_event_rule_matches_status status =
-                       LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_OK;
+               LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_OK;
 
-       if (!evaluation || !is_event_rule_matches_evaluation(evaluation) ||
-                       !field_val) {
+       if (!evaluation || !is_event_rule_matches_evaluation(evaluation) || !field_val) {
                status = LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_INVALID;
                goto end;
        }
 
-       hit = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_event_rule_matches::parent);
+       hit = lttng::utils::container_of(evaluation, &lttng_evaluation_event_rule_matches::parent);
        if (!hit->captured_values) {
                status = LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_NONE;
                goto end;
@@ -1450,9 +1375,8 @@ end:
        return status;
 }
 
-enum lttng_error_code
-lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
-               struct lttng_condition *condition)
+enum lttng_error_code lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
+       struct lttng_condition *condition)
 {
        enum lttng_error_code ret;
        enum lttng_condition_status status;
@@ -1463,8 +1387,8 @@ lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
                goto end;
        }
 
-       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &capture_count);
+       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(condition,
+                                                                                &capture_count);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ret = LTTNG_ERR_FATAL;
                goto end;
@@ -1472,20 +1396,19 @@ lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
 
        for (i = 0; i < capture_count; i++) {
                struct lttng_capture_descriptor *local_capture_desc =
-                               lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
-                                               condition, i);
+                       lttng_condition_event_rule_matches_get_internal_capture_descriptor_at_index(
+                               condition, i);
                int bytecode_ret;
 
-               if (local_capture_desc == NULL) {
+               if (local_capture_desc == nullptr) {
                        ret = LTTNG_ERR_FATAL;
                        goto end;
                }
 
                /* Generate the bytecode. */
-               bytecode_ret = lttng_event_expr_to_bytecode(
-                               local_capture_desc->event_expression,
-                               &local_capture_desc->bytecode);
-               if (bytecode_ret < 0 || local_capture_desc->bytecode == NULL) {
+               bytecode_ret = lttng_event_expr_to_bytecode(local_capture_desc->event_expression,
+                                                           &local_capture_desc->bytecode);
+               if (bytecode_ret < 0 || local_capture_desc->bytecode == nullptr) {
                        ret = LTTNG_ERR_INVALID_CAPTURE_EXPRESSION;
                        goto end;
                }
@@ -1498,15 +1421,13 @@ end:
        return ret;
 }
 
-const struct lttng_bytecode *
-lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
-               const struct lttng_condition *condition, unsigned int index)
+const struct lttng_bytecode *lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
+       const struct lttng_condition *condition, unsigned int index)
 {
-       const struct lttng_condition_event_rule_matches
-                       *event_rule_matches_cond = lttng::utils::container_of(condition,
-                                       &lttng_condition_event_rule_matches::parent);
-       struct lttng_capture_descriptor *desc = NULL;
-       struct lttng_bytecode *bytecode = NULL;
+       const struct lttng_condition_event_rule_matches *event_rule_matches_cond =
+               lttng::utils::container_of(condition, &lttng_condition_event_rule_matches::parent);
+       struct lttng_capture_descriptor *desc = nullptr;
+       struct lttng_bytecode *bytecode = nullptr;
        unsigned int count;
        enum lttng_condition_status status;
 
@@ -1514,8 +1435,7 @@ lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
                goto end;
        }
 
-       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(
-                       condition, &count);
+       status = lttng_condition_event_rule_matches_get_capture_descriptor_count(condition, &count);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                goto end;
        }
@@ -1525,8 +1445,8 @@ lttng_condition_event_rule_matches_get_capture_bytecode_at_index(
        }
 
        desc = (lttng_capture_descriptor *) lttng_dynamic_pointer_array_get_pointer(
-                       &event_rule_matches_cond->capture_descriptors, index);
-       if (desc == NULL) {
+               &event_rule_matches_cond->capture_descriptors, index);
+       if (desc == nullptr) {
                goto end;
        }
 
index 69951b5c27d1ecc728e9f4574c7c6db231b89747..1e9cb4379a428609e5e6de5e72d68350a8e9dc25 100644 (file)
@@ -8,36 +8,33 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
-#include <float.h>
+
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/session-consumed-size-internal.hpp>
 #include <lttng/constant.h>
+
+#include <float.h>
 #include <math.h>
 #include <time.h>
 
-#define IS_CONSUMED_SIZE_CONDITION(condition) ( \
-       lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE \
-       )
+#define IS_CONSUMED_SIZE_CONDITION(condition) \
+       (lttng_condition_get_type(condition) == LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE)
 
-#define IS_CONSUMED_SIZE_EVALUATION(evaluation) ( \
-       lttng_evaluation_get_type(evaluation) == LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE \
-       )
+#define IS_CONSUMED_SIZE_EVALUATION(evaluation) \
+       (lttng_evaluation_get_type(evaluation) == LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE)
 
-static
-void lttng_condition_session_consumed_size_destroy(struct lttng_condition *condition)
+static void lttng_condition_session_consumed_size_destroy(struct lttng_condition *condition)
 {
        struct lttng_condition_session_consumed_size *consumed_size;
 
        consumed_size = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                                  &lttng_condition_session_consumed_size::parent);
 
        free(consumed_size->session_name);
        free(consumed_size);
 }
 
-static
-bool lttng_condition_session_consumed_size_validate(
-               const struct lttng_condition *condition)
+static bool lttng_condition_session_consumed_size_validate(const struct lttng_condition *condition)
 {
        bool valid = false;
        struct lttng_condition_session_consumed_size *consumed;
@@ -47,7 +44,7 @@ bool lttng_condition_session_consumed_size_validate(
        }
 
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
        if (!consumed->session_name) {
                ERR("Invalid session consumed size condition: a target session name must be set.");
                goto end;
@@ -62,10 +59,8 @@ end:
        return valid;
 }
 
-static
-int lttng_condition_session_consumed_size_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload)
+static int lttng_condition_session_consumed_size_serialize(const struct lttng_condition *condition,
+                                                          struct lttng_payload *payload)
 {
        int ret;
        size_t session_name_len;
@@ -79,7 +74,7 @@ int lttng_condition_session_consumed_size_serialize(
 
        DBG("Serializing session consumed size condition");
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
 
        session_name_len = strlen(consumed->session_name) + 1;
        if (session_name_len > LTTNG_NAME_MAX) {
@@ -87,18 +82,16 @@ int lttng_condition_session_consumed_size_serialize(
                goto end;
        }
 
-       consumed_comm.consumed_threshold_bytes =
-                       consumed->consumed_threshold_bytes.value;
+       consumed_comm.consumed_threshold_bytes = consumed->consumed_threshold_bytes.value;
        consumed_comm.session_name_len = (uint32_t) session_name_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &consumed_comm,
-                       sizeof(consumed_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &consumed_comm, sizeof(consumed_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, consumed->session_name,
-                       session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, consumed->session_name, session_name_len);
        if (ret) {
                goto end;
        }
@@ -106,9 +99,8 @@ end:
        return ret;
 }
 
-static
-bool lttng_condition_session_consumed_size_is_equal(const struct lttng_condition *_a,
-               const struct lttng_condition *_b)
+static bool lttng_condition_session_consumed_size_is_equal(const struct lttng_condition *_a,
+                                                          const struct lttng_condition *_b)
 {
        bool is_equal = false;
        struct lttng_condition_session_consumed_size *a, *b;
@@ -128,7 +120,7 @@ bool lttng_condition_session_consumed_size_is_equal(const struct lttng_condition
 
        LTTNG_ASSERT(a->session_name);
        LTTNG_ASSERT(b->session_name);
-       if (strcmp(a->session_name, b->session_name)) {
+       if (strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
@@ -137,48 +129,44 @@ end:
        return is_equal;
 }
 
-static
-enum lttng_error_code lttng_condition_session_consumed_size_mi_serialize(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_condition_session_consumed_size_mi_serialize(const struct lttng_condition *condition,
+                                                  struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_condition_status status;
-       const char *session_name = NULL;
+       const char *session_name = nullptr;
        uint64_t threshold_bytes;
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_CONSUMED_SIZE_CONDITION(condition));
 
-       status = lttng_condition_session_consumed_size_get_session_name(
-                       condition, &session_name);
+       status = lttng_condition_session_consumed_size_get_session_name(condition, &session_name);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(session_name);
 
-       status = lttng_condition_session_consumed_size_get_threshold(
-                       condition, &threshold_bytes);
+       status = lttng_condition_session_consumed_size_get_threshold(condition, &threshold_bytes);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
 
        /* Open condition session consumed size element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_condition_session_consumed_size);
+                                          mi_lttng_element_condition_session_consumed_size);
        if (ret) {
                goto mi_error;
        }
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Threshold in bytes. */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_condition_threshold_bytes,
-                       threshold_bytes);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_condition_threshold_bytes, threshold_bytes);
        if (ret) {
                goto mi_error;
        }
@@ -204,7 +192,7 @@ struct lttng_condition *lttng_condition_session_consumed_size_create(void)
 
        condition = zmalloc<lttng_condition_session_consumed_size>();
        if (!condition) {
-               return NULL;
+               return nullptr;
        }
 
        lttng_condition_init(&condition->parent, LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE);
@@ -216,17 +204,16 @@ struct lttng_condition *lttng_condition_session_consumed_size_create(void)
        return &condition->parent;
 }
 
-static
-ssize_t init_condition_from_payload(struct lttng_condition *condition,
-               struct lttng_payload_view *src_view)
+static ssize_t init_condition_from_payload(struct lttng_condition *condition,
+                                          struct lttng_payload_view *src_view)
 {
        ssize_t ret, condition_size;
        enum lttng_condition_status status;
        const char *session_name;
        struct lttng_buffer_view session_name_view;
        const struct lttng_condition_session_consumed_size_comm *condition_comm;
-       struct lttng_payload_view condition_comm_view = lttng_payload_view_from_view(
-                       src_view, 0, sizeof(*condition_comm));
+       struct lttng_payload_view condition_comm_view =
+               lttng_payload_view_from_view(src_view, 0, sizeof(*condition_comm));
 
        if (!lttng_payload_view_is_valid(&condition_comm_view)) {
                ERR("Failed to initialize from malformed condition buffer: buffer too short to contain header");
@@ -235,8 +222,8 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        }
 
        condition_comm = (typeof(condition_comm)) condition_comm_view.buffer.data;
-       session_name_view = lttng_buffer_view_from_view(&src_view->buffer,
-                       sizeof(*condition_comm), condition_comm->session_name_len);
+       session_name_view = lttng_buffer_view_from_view(
+               &src_view->buffer, sizeof(*condition_comm), condition_comm->session_name_len);
 
        if (condition_comm->session_name_len > LTTNG_NAME_MAX) {
                ERR("Failed to initialize from malformed condition buffer: name exceeds LTTNG_MAX_NAME");
@@ -250,8 +237,8 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       status = lttng_condition_session_consumed_size_set_threshold(condition,
-                       condition_comm->consumed_threshold_bytes);
+       status = lttng_condition_session_consumed_size_set_threshold(
+               condition, condition_comm->consumed_threshold_bytes);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to initialize session consumed size condition threshold");
                ret = -1;
@@ -265,8 +252,7 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       status = lttng_condition_session_consumed_size_set_session_name(condition,
-                       session_name);
+       status = lttng_condition_session_consumed_size_set_session_name(condition, session_name);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to set session consumed size condition's session name");
                ret = -1;
@@ -278,20 +264,18 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       condition_size = sizeof(*condition_comm) +
-                       (ssize_t) condition_comm->session_name_len;
+       condition_size = sizeof(*condition_comm) + (ssize_t) condition_comm->session_name_len;
        ret = condition_size;
 end:
        return ret;
 }
 
-ssize_t lttng_condition_session_consumed_size_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **_condition)
+ssize_t
+lttng_condition_session_consumed_size_create_from_payload(struct lttng_payload_view *view,
+                                                         struct lttng_condition **_condition)
 {
        ssize_t ret;
-       struct lttng_condition *condition =
-                       lttng_condition_session_consumed_size_create();
+       struct lttng_condition *condition = lttng_condition_session_consumed_size_create();
 
        if (!_condition || !condition) {
                ret = -1;
@@ -310,30 +294,28 @@ error:
        return ret;
 }
 
-static
-struct lttng_evaluation *create_evaluation_from_payload(
-               const struct lttng_payload_view *view)
+static struct lttng_evaluation *
+create_evaluation_from_payload(const struct lttng_payload_view *view)
 {
        const struct lttng_evaluation_session_consumed_size_comm *comm =
-                       (typeof(comm)) view->buffer.data;
-       struct lttng_evaluation *evaluation = NULL;
+               (typeof(comm)) view->buffer.data;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (view->buffer.size < sizeof(*comm)) {
                goto end;
        }
 
-       evaluation = lttng_evaluation_session_consumed_size_create(
-                       comm->session_consumed);
+       evaluation = lttng_evaluation_session_consumed_size_create(comm->session_consumed);
 end:
        return evaluation;
 }
 
-ssize_t lttng_evaluation_session_consumed_size_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+ssize_t
+lttng_evaluation_session_consumed_size_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_evaluation **_evaluation)
 {
        ssize_t ret;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (!_evaluation) {
                ret = -1;
@@ -355,9 +337,8 @@ error:
 }
 
 enum lttng_condition_status
-lttng_condition_session_consumed_size_get_threshold(
-               const struct lttng_condition *condition,
-               uint64_t *consumed_threshold_bytes)
+lttng_condition_session_consumed_size_get_threshold(const struct lttng_condition *condition,
+                                                   uint64_t *consumed_threshold_bytes)
 {
        struct lttng_condition_session_consumed_size *consumed;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -368,7 +349,7 @@ lttng_condition_session_consumed_size_get_threshold(
        }
 
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
        if (!consumed->consumed_threshold_bytes.set) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -379,8 +360,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_session_consumed_size_set_threshold(
-               struct lttng_condition *condition, uint64_t consumed_threshold_bytes)
+lttng_condition_session_consumed_size_set_threshold(struct lttng_condition *condition,
+                                                   uint64_t consumed_threshold_bytes)
 {
        struct lttng_condition_session_consumed_size *consumed;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -391,7 +372,7 @@ lttng_condition_session_consumed_size_set_threshold(
        }
 
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
        consumed->consumed_threshold_bytes.set = true;
        consumed->consumed_threshold_bytes.value = consumed_threshold_bytes;
 end:
@@ -399,9 +380,8 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_session_consumed_size_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name)
+lttng_condition_session_consumed_size_get_session_name(const struct lttng_condition *condition,
+                                                      const char **session_name)
 {
        struct lttng_condition_session_consumed_size *consumed;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -412,7 +392,7 @@ lttng_condition_session_consumed_size_get_session_name(
        }
 
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
        if (!consumed->session_name) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -423,21 +403,21 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_session_consumed_size_set_session_name(
-               struct lttng_condition *condition, const char *session_name)
+lttng_condition_session_consumed_size_set_session_name(struct lttng_condition *condition,
+                                                      const char *session_name)
 {
        char *session_name_copy;
        struct lttng_condition_session_consumed_size *consumed;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !IS_CONSUMED_SIZE_CONDITION(condition) ||
-                       !session_name || strlen(session_name) == 0) {
+       if (!condition || !IS_CONSUMED_SIZE_CONDITION(condition) || !session_name ||
+           strlen(session_name) == 0) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
        consumed = lttng::utils::container_of(condition,
-                       &lttng_condition_session_consumed_size::parent);
+                                             &lttng_condition_session_consumed_size::parent);
        session_name_copy = strdup(session_name);
        if (!session_name_copy) {
                status = LTTNG_CONDITION_STATUS_ERROR;
@@ -452,34 +432,29 @@ end:
        return status;
 }
 
-static
-int lttng_evaluation_session_consumed_size_serialize(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload)
+static int
+lttng_evaluation_session_consumed_size_serialize(const struct lttng_evaluation *evaluation,
+                                                struct lttng_payload *payload)
 {
        struct lttng_evaluation_session_consumed_size *consumed;
        struct lttng_evaluation_session_consumed_size_comm comm;
 
        consumed = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_consumed_size::parent);
+                                             &lttng_evaluation_session_consumed_size::parent);
        comm.session_consumed = consumed->session_consumed;
-       return lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       return lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
 }
 
-static
-void lttng_evaluation_session_consumed_size_destroy(
-               struct lttng_evaluation *evaluation)
+static void lttng_evaluation_session_consumed_size_destroy(struct lttng_evaluation *evaluation)
 {
        struct lttng_evaluation_session_consumed_size *consumed;
 
        consumed = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_consumed_size::parent);
+                                             &lttng_evaluation_session_consumed_size::parent);
        free(consumed);
 }
 
-struct lttng_evaluation *lttng_evaluation_session_consumed_size_create(
-               uint64_t consumed)
+struct lttng_evaluation *lttng_evaluation_session_consumed_size_create(uint64_t consumed)
 {
        struct lttng_evaluation_session_consumed_size *consumed_eval;
 
@@ -497,21 +472,19 @@ end:
 }
 
 enum lttng_evaluation_status
-lttng_evaluation_session_consumed_size_get_consumed_size(
-               const struct lttng_evaluation *evaluation,
-               uint64_t *session_consumed)
+lttng_evaluation_session_consumed_size_get_consumed_size(const struct lttng_evaluation *evaluation,
+                                                        uint64_t *session_consumed)
 {
        struct lttng_evaluation_session_consumed_size *consumed;
        enum lttng_evaluation_status status = LTTNG_EVALUATION_STATUS_OK;
 
-       if (!evaluation || !IS_CONSUMED_SIZE_EVALUATION(evaluation) ||
-                       !session_consumed) {
+       if (!evaluation || !IS_CONSUMED_SIZE_EVALUATION(evaluation) || !session_consumed) {
                status = LTTNG_EVALUATION_STATUS_INVALID;
                goto end;
        }
 
        consumed = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_consumed_size::parent);
+                                             &lttng_evaluation_session_consumed_size::parent);
        *session_consumed = consumed->session_consumed;
 end:
        return status;
index 7f0896f927adba5b38df6f964eb8ab14e348f9e4..20af727cf8ff29feea0d6023208c0141b45dc70f 100644 (file)
@@ -8,32 +8,25 @@
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/session-rotation-internal.hpp>
 #include <lttng/location-internal.hpp>
+
 #include <stdbool.h>
 
-static
-bool lttng_condition_session_rotation_validate(
-               const struct lttng_condition *condition);
-static
-int lttng_condition_session_rotation_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload);
-static
-bool lttng_condition_session_rotation_is_equal(const struct lttng_condition *_a,
-               const struct lttng_condition *_b);
-static
-void lttng_condition_session_rotation_destroy(
-               struct lttng_condition *condition);
-
-static
-enum lttng_error_code lttng_condition_session_rotation_mi_serialize(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer);
-
-static const
-struct lttng_condition rotation_condition_template = {
+static bool lttng_condition_session_rotation_validate(const struct lttng_condition *condition);
+static int lttng_condition_session_rotation_serialize(const struct lttng_condition *condition,
+                                                     struct lttng_payload *payload);
+static bool lttng_condition_session_rotation_is_equal(const struct lttng_condition *_a,
+                                                     const struct lttng_condition *_b);
+static void lttng_condition_session_rotation_destroy(struct lttng_condition *condition);
+
+static enum lttng_error_code
+lttng_condition_session_rotation_mi_serialize(const struct lttng_condition *condition,
+                                             struct mi_writer *writer);
+
+static const struct lttng_condition rotation_condition_template = {
        {},
        LTTNG_CONDITION_TYPE_UNKNOWN, /* type unset, shall be set on creation. */
        lttng_condition_session_rotation_validate,
@@ -43,42 +36,33 @@ struct lttng_condition rotation_condition_template = {
        lttng_condition_session_rotation_mi_serialize,
 };
 
-static
-int lttng_evaluation_session_rotation_serialize(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload);
-static
-void lttng_evaluation_session_rotation_destroy(
-               struct lttng_evaluation *evaluation);
+static int lttng_evaluation_session_rotation_serialize(const struct lttng_evaluation *evaluation,
+                                                      struct lttng_payload *payload);
+static void lttng_evaluation_session_rotation_destroy(struct lttng_evaluation *evaluation);
 
-static const
-struct lttng_evaluation rotation_evaluation_template = {
+static const struct lttng_evaluation rotation_evaluation_template = {
        LTTNG_CONDITION_TYPE_UNKNOWN, /* type unset, shall be set on creation. */
        lttng_evaluation_session_rotation_serialize,
        lttng_evaluation_session_rotation_destroy,
 };
 
-static
-bool is_rotation_condition(const struct lttng_condition *condition)
+static bool is_rotation_condition(const struct lttng_condition *condition)
 {
        enum lttng_condition_type type = lttng_condition_get_type(condition);
 
        return type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING ||
-                       type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED;
+               type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED;
 }
 
-static
-bool is_rotation_evaluation(const struct lttng_evaluation *evaluation)
+static bool is_rotation_evaluation(const struct lttng_evaluation *evaluation)
 {
        enum lttng_condition_type type = lttng_evaluation_get_type(evaluation);
 
        return type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING ||
-                       type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED;
+               type == LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED;
 }
 
-static
-bool lttng_condition_session_rotation_validate(
-               const struct lttng_condition *condition)
+static bool lttng_condition_session_rotation_validate(const struct lttng_condition *condition)
 {
        bool valid = false;
        struct lttng_condition_session_rotation *rotation;
@@ -87,8 +71,7 @@ bool lttng_condition_session_rotation_validate(
                goto end;
        }
 
-       rotation = lttng::utils::container_of(condition,
-                       &lttng_condition_session_rotation::parent);
+       rotation = lttng::utils::container_of(condition, &lttng_condition_session_rotation::parent);
        if (!rotation->session_name) {
                ERR("Invalid session rotation condition: a target session name must be set.");
                goto end;
@@ -99,10 +82,8 @@ end:
        return valid;
 }
 
-static
-int lttng_condition_session_rotation_serialize(
-               const struct lttng_condition *condition,
-               struct lttng_payload *payload)
+static int lttng_condition_session_rotation_serialize(const struct lttng_condition *condition,
+                                                     struct lttng_payload *payload)
 {
        int ret;
        size_t session_name_len;
@@ -115,8 +96,7 @@ int lttng_condition_session_rotation_serialize(
        }
 
        DBG("Serializing session rotation condition");
-       rotation = lttng::utils::container_of(condition,
-                       &lttng_condition_session_rotation::parent);
+       rotation = lttng::utils::container_of(condition, &lttng_condition_session_rotation::parent);
 
        session_name_len = strlen(rotation->session_name) + 1;
        if (session_name_len > LTTNG_NAME_MAX) {
@@ -125,13 +105,12 @@ int lttng_condition_session_rotation_serialize(
        }
 
        rotation_comm.session_name_len = session_name_len;
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &rotation_comm,
-                       sizeof(rotation_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &rotation_comm, sizeof(rotation_comm));
        if (ret) {
                goto end;
        }
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       rotation->session_name, session_name_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, rotation->session_name, session_name_len);
        if (ret) {
                goto end;
        }
@@ -139,9 +118,8 @@ end:
        return ret;
 }
 
-static
-bool lttng_condition_session_rotation_is_equal(const struct lttng_condition *_a,
-               const struct lttng_condition *_b)
+static bool lttng_condition_session_rotation_is_equal(const struct lttng_condition *_a,
+                                                     const struct lttng_condition *_b)
 {
        bool is_equal = false;
        struct lttng_condition_session_rotation *a, *b;
@@ -150,14 +128,12 @@ bool lttng_condition_session_rotation_is_equal(const struct lttng_condition *_a,
        b = lttng::utils::container_of(_b, &lttng_condition_session_rotation::parent);
 
        /* Both session names must be set or both must be unset. */
-       if ((a->session_name && !b->session_name) ||
-                       (!a->session_name && b->session_name)) {
+       if ((a->session_name && !b->session_name) || (!a->session_name && b->session_name)) {
                WARN("Comparing session rotation conditions with uninitialized session names.");
                goto end;
        }
 
-       if (a->session_name && b->session_name &&
-                       strcmp(a->session_name, b->session_name)) {
+       if (a->session_name && b->session_name && strcmp(a->session_name, b->session_name) != 0) {
                goto end;
        }
 
@@ -166,32 +142,27 @@ end:
        return is_equal;
 }
 
-static
-void lttng_condition_session_rotation_destroy(
-               struct lttng_condition *condition)
+static void lttng_condition_session_rotation_destroy(struct lttng_condition *condition)
 {
        struct lttng_condition_session_rotation *rotation;
 
-       rotation = lttng::utils::container_of(condition,
-                       &lttng_condition_session_rotation::parent);
+       rotation = lttng::utils::container_of(condition, &lttng_condition_session_rotation::parent);
 
        free(rotation->session_name);
        free(rotation);
 }
 
-static
-struct lttng_condition *lttng_condition_session_rotation_create(
-               enum lttng_condition_type type)
+static struct lttng_condition *
+lttng_condition_session_rotation_create(enum lttng_condition_type type)
 {
        struct lttng_condition_session_rotation *condition;
 
        condition = zmalloc<lttng_condition_session_rotation>();
        if (!condition) {
-               return NULL;
+               return nullptr;
        }
 
-       memcpy(&condition->parent, &rotation_condition_template,
-                       sizeof(condition->parent));
+       memcpy(&condition->parent, &rotation_condition_template, sizeof(condition->parent));
        lttng_condition_init(&condition->parent, type);
        return &condition->parent;
 }
@@ -199,18 +170,17 @@ struct lttng_condition *lttng_condition_session_rotation_create(
 struct lttng_condition *lttng_condition_session_rotation_ongoing_create(void)
 {
        return lttng_condition_session_rotation_create(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
 }
 
 struct lttng_condition *lttng_condition_session_rotation_completed_create(void)
 {
        return lttng_condition_session_rotation_create(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
 }
 
-static
-ssize_t init_condition_from_payload(struct lttng_condition *condition,
-               struct lttng_payload_view *src_view)
+static ssize_t init_condition_from_payload(struct lttng_condition *condition,
+                                          struct lttng_payload_view *src_view)
 {
        ssize_t ret, condition_size;
        enum lttng_condition_status status;
@@ -218,8 +188,7 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        struct lttng_buffer_view name_view;
        const struct lttng_condition_session_rotation_comm *condition_comm;
        struct lttng_payload_view condition_comm_view =
-                       lttng_payload_view_from_view(
-                                       src_view, 0, sizeof(*condition_comm));
+               lttng_payload_view_from_view(src_view, 0, sizeof(*condition_comm));
 
        if (!lttng_payload_view_is_valid(&condition_comm_view)) {
                ERR("Failed to initialize from malformed condition buffer: buffer too short to contain header");
@@ -228,8 +197,8 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
        }
 
        condition_comm = (typeof(condition_comm)) src_view->buffer.data;
-       name_view = lttng_buffer_view_from_view(&src_view->buffer,
-                                               sizeof(*condition_comm), condition_comm->session_name_len);
+       name_view = lttng_buffer_view_from_view(
+               &src_view->buffer, sizeof(*condition_comm), condition_comm->session_name_len);
 
        if (!lttng_buffer_view_is_valid(&name_view)) {
                ERR("Failed to initialize from malformed condition buffer: buffer too short to contain session name");
@@ -250,8 +219,7 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       status = lttng_condition_session_rotation_set_session_name(condition,
-                       session_name);
+       status = lttng_condition_session_rotation_set_session_name(condition, session_name);
        if (status != LTTNG_CONDITION_STATUS_OK) {
                ERR("Failed to set buffer consumed session name");
                ret = -1;
@@ -263,21 +231,19 @@ ssize_t init_condition_from_payload(struct lttng_condition *condition,
                goto end;
        }
 
-       condition_size = sizeof(*condition_comm) +
-                       (ssize_t) condition_comm->session_name_len;
+       condition_size = sizeof(*condition_comm) + (ssize_t) condition_comm->session_name_len;
        ret = condition_size;
 end:
        return ret;
 }
 
-static
-ssize_t lttng_condition_session_rotation_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **_condition,
-               enum lttng_condition_type type)
+static ssize_t
+lttng_condition_session_rotation_create_from_payload(struct lttng_payload_view *view,
+                                                    struct lttng_condition **_condition,
+                                                    enum lttng_condition_type type)
 {
        ssize_t ret;
-       struct lttng_condition *condition = NULL;
+       struct lttng_condition *condition = nullptr;
 
        switch (type) {
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
@@ -308,38 +274,33 @@ error:
        return ret;
 }
 
-ssize_t lttng_condition_session_rotation_ongoing_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition)
+ssize_t
+lttng_condition_session_rotation_ongoing_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_condition **condition)
 {
-       return lttng_condition_session_rotation_create_from_payload(view,
-                       condition,
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
+       return lttng_condition_session_rotation_create_from_payload(
+               view, condition, LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
 }
 
-ssize_t lttng_condition_session_rotation_completed_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_condition **condition)
+ssize_t
+lttng_condition_session_rotation_completed_create_from_payload(struct lttng_payload_view *view,
+                                                              struct lttng_condition **condition)
 {
-       return lttng_condition_session_rotation_create_from_payload(view,
-                       condition,
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
+       return lttng_condition_session_rotation_create_from_payload(
+               view, condition, LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
 }
 
-static
-struct lttng_evaluation *lttng_evaluation_session_rotation_create(
-               enum lttng_condition_type type, uint64_t id,
-               struct lttng_trace_archive_location *location)
+static struct lttng_evaluation *lttng_evaluation_session_rotation_create(
+       enum lttng_condition_type type, uint64_t id, struct lttng_trace_archive_location *location)
 {
        struct lttng_evaluation_session_rotation *evaluation;
 
        evaluation = zmalloc<lttng_evaluation_session_rotation>();
        if (!evaluation) {
-               return NULL;
+               return nullptr;
        }
 
-       memcpy(&evaluation->parent, &rotation_evaluation_template,
-                       sizeof(evaluation->parent));
+       memcpy(&evaluation->parent, &rotation_evaluation_template, sizeof(evaluation->parent));
        lttng_evaluation_init(&evaluation->parent, type);
        evaluation->id = id;
        if (location) {
@@ -349,18 +310,15 @@ struct lttng_evaluation *lttng_evaluation_session_rotation_create(
        return &evaluation->parent;
 }
 
-static
-ssize_t create_evaluation_from_payload(
-               enum lttng_condition_type type,
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+static ssize_t create_evaluation_from_payload(enum lttng_condition_type type,
+                                             struct lttng_payload_view *view,
+                                             struct lttng_evaluation **_evaluation)
 {
        ssize_t ret, size;
-       struct lttng_evaluation *evaluation = NULL;
-       struct lttng_trace_archive_location *location = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
+       struct lttng_trace_archive_location *location = nullptr;
        const struct lttng_evaluation_session_rotation_comm *comm;
-       struct lttng_payload_view comm_view = lttng_payload_view_from_view(
-                       view, 0, sizeof(*comm));
+       struct lttng_payload_view comm_view = lttng_payload_view_from_view(view, 0, sizeof(*comm));
 
        if (!lttng_payload_view_is_valid(&comm_view)) {
                goto error;
@@ -370,23 +328,20 @@ ssize_t create_evaluation_from_payload(
        size = sizeof(*comm);
        if (comm->has_location) {
                const struct lttng_buffer_view location_view =
-                               lttng_buffer_view_from_view(
-                                               &view->buffer, sizeof(*comm), -1);
+                       lttng_buffer_view_from_view(&view->buffer, sizeof(*comm), -1);
 
                if (!lttng_buffer_view_is_valid(&location_view)) {
                        goto error;
                }
 
-               ret = lttng_trace_archive_location_create_from_buffer(
-                               &location_view, &location);
+               ret = lttng_trace_archive_location_create_from_buffer(&location_view, &location);
                if (ret < 0) {
                        goto error;
                }
                size += ret;
        }
 
-       evaluation = lttng_evaluation_session_rotation_create(type, comm->id,
-                       location);
+       evaluation = lttng_evaluation_session_rotation_create(type, comm->id, location);
        if (!evaluation) {
                goto error;
        }
@@ -397,18 +352,17 @@ ssize_t create_evaluation_from_payload(
        return ret;
 error:
        lttng_trace_archive_location_put(location);
-       evaluation = NULL;
+       evaluation = nullptr;
        return -1;
 }
 
-static
-ssize_t lttng_evaluation_session_rotation_create_from_payload(
-               enum lttng_condition_type type,
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **_evaluation)
+static ssize_t
+lttng_evaluation_session_rotation_create_from_payload(enum lttng_condition_type type,
+                                                     struct lttng_payload_view *view,
+                                                     struct lttng_evaluation **_evaluation)
 {
        ssize_t ret;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_evaluation *evaluation = nullptr;
 
        if (!_evaluation) {
                ret = -1;
@@ -427,44 +381,38 @@ error:
        return ret;
 }
 
-ssize_t lttng_evaluation_session_rotation_ongoing_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation)
+ssize_t
+lttng_evaluation_session_rotation_ongoing_create_from_payload(struct lttng_payload_view *view,
+                                                             struct lttng_evaluation **evaluation)
 {
        return lttng_evaluation_session_rotation_create_from_payload(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING,
-                       view, evaluation);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING, view, evaluation);
 }
 
 ssize_t lttng_evaluation_session_rotation_completed_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_evaluation **evaluation)
+       struct lttng_payload_view *view, struct lttng_evaluation **evaluation)
 {
        return lttng_evaluation_session_rotation_create_from_payload(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED,
-                       view, evaluation);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED, view, evaluation);
 }
 
-struct lttng_evaluation *lttng_evaluation_session_rotation_ongoing_create(
-               uint64_t id)
+struct lttng_evaluation *lttng_evaluation_session_rotation_ongoing_create(uint64_t id)
 {
        return lttng_evaluation_session_rotation_create(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING, id,
-                       NULL);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING, id, nullptr);
 }
 
-struct lttng_evaluation *lttng_evaluation_session_rotation_completed_create(
-               uint64_t id, struct lttng_trace_archive_location *location)
+struct lttng_evaluation *
+lttng_evaluation_session_rotation_completed_create(uint64_t id,
+                                                  struct lttng_trace_archive_location *location)
 {
        return lttng_evaluation_session_rotation_create(
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED, id,
-                       location);
+               LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED, id, location);
 }
 
 enum lttng_condition_status
-lttng_condition_session_rotation_get_session_name(
-               const struct lttng_condition *condition,
-               const char **session_name)
+lttng_condition_session_rotation_get_session_name(const struct lttng_condition *condition,
+                                                 const char **session_name)
 {
        struct lttng_condition_session_rotation *rotation;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
@@ -474,8 +422,7 @@ lttng_condition_session_rotation_get_session_name(
                goto end;
        }
 
-       rotation = lttng::utils::container_of(condition,
-                       &lttng_condition_session_rotation::parent);
+       rotation = lttng::utils::container_of(condition, &lttng_condition_session_rotation::parent);
        if (!rotation->session_name) {
                status = LTTNG_CONDITION_STATUS_UNSET;
                goto end;
@@ -486,21 +433,20 @@ end:
 }
 
 enum lttng_condition_status
-lttng_condition_session_rotation_set_session_name(
-               struct lttng_condition *condition, const char *session_name)
+lttng_condition_session_rotation_set_session_name(struct lttng_condition *condition,
+                                                 const char *session_name)
 {
        char *session_name_copy;
        struct lttng_condition_session_rotation *rotation;
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
 
-       if (!condition || !is_rotation_condition(condition) ||
-                       !session_name || strlen(session_name) == 0) {
+       if (!condition || !is_rotation_condition(condition) || !session_name ||
+           strlen(session_name) == 0) {
                status = LTTNG_CONDITION_STATUS_INVALID;
                goto end;
        }
 
-       rotation = lttng::utils::container_of(condition,
-                       &lttng_condition_session_rotation::parent);
+       rotation = lttng::utils::container_of(condition, &lttng_condition_session_rotation::parent);
        session_name_copy = strdup(session_name);
        if (!session_name_copy) {
                status = LTTNG_CONDITION_STATUS_ERROR;
@@ -513,48 +459,41 @@ end:
        return status;
 }
 
-static
-int lttng_evaluation_session_rotation_serialize(
-               const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload)
+static int lttng_evaluation_session_rotation_serialize(const struct lttng_evaluation *evaluation,
+                                                      struct lttng_payload *payload)
 {
        int ret;
        struct lttng_evaluation_session_rotation *rotation;
        struct lttng_evaluation_session_rotation_comm comm = {};
 
-       rotation = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_rotation::parent);
+       rotation =
+               lttng::utils::container_of(evaluation, &lttng_evaluation_session_rotation::parent);
        comm.id = rotation->id;
        comm.has_location = !!rotation->location;
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                goto end;
        }
        if (!rotation->location) {
                goto end;
        }
-       ret = lttng_trace_archive_location_serialize(rotation->location,
-                       &payload->buffer);
+       ret = lttng_trace_archive_location_serialize(rotation->location, &payload->buffer);
 end:
        return ret;
 }
 
-static
-void lttng_evaluation_session_rotation_destroy(
-               struct lttng_evaluation *evaluation)
+static void lttng_evaluation_session_rotation_destroy(struct lttng_evaluation *evaluation)
 {
        struct lttng_evaluation_session_rotation *rotation;
 
-       rotation = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_rotation::parent);
+       rotation =
+               lttng::utils::container_of(evaluation, &lttng_evaluation_session_rotation::parent);
        lttng_trace_archive_location_put(rotation->location);
        free(rotation);
 }
 
 enum lttng_evaluation_status
-lttng_evaluation_session_rotation_get_id(
-               const struct lttng_evaluation *evaluation, uint64_t *id)
+lttng_evaluation_session_rotation_get_id(const struct lttng_evaluation *evaluation, uint64_t *id)
 {
        const struct lttng_evaluation_session_rotation *rotation;
        enum lttng_evaluation_status status = LTTNG_EVALUATION_STATUS_OK;
@@ -564,8 +503,8 @@ lttng_evaluation_session_rotation_get_id(
                goto end;
        }
 
-       rotation = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_rotation::parent);
+       rotation =
+               lttng::utils::container_of(evaluation, &lttng_evaluation_session_rotation::parent);
        *id = rotation->id;
 end:
        return status;
@@ -577,37 +516,35 @@ end:
  * trace archive location. Hence, users of liblttng-ctl have no visibility of
  * the reference counting of archive locations.
  */
-enum lttng_evaluation_status
-lttng_evaluation_session_rotation_completed_get_location(
-               const struct lttng_evaluation *evaluation,
-               const struct lttng_trace_archive_location **location)
+enum lttng_evaluation_status lttng_evaluation_session_rotation_completed_get_location(
+       const struct lttng_evaluation *evaluation,
+       const struct lttng_trace_archive_location **location)
 {
        const struct lttng_evaluation_session_rotation *rotation;
        enum lttng_evaluation_status status = LTTNG_EVALUATION_STATUS_OK;
 
        if (!evaluation || !location ||
-                       evaluation->type != LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED) {
+           evaluation->type != LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED) {
                status = LTTNG_EVALUATION_STATUS_INVALID;
                goto end;
        }
 
-       rotation = lttng::utils::container_of(evaluation,
-                       &lttng_evaluation_session_rotation::parent);
+       rotation =
+               lttng::utils::container_of(evaluation, &lttng_evaluation_session_rotation::parent);
        *location = rotation->location;
 end:
        return status;
 }
 
-static
-enum lttng_error_code lttng_condition_session_rotation_mi_serialize(
-               const struct lttng_condition *condition,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_condition_session_rotation_mi_serialize(const struct lttng_condition *condition,
+                                             struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_condition_status status;
-       const char *session_name = NULL;
-       const char *type_element_str = NULL;
+       const char *session_name = nullptr;
+       const char *type_element_str = nullptr;
 
        LTTNG_ASSERT(condition);
        LTTNG_ASSERT(writer);
@@ -615,20 +552,17 @@ enum lttng_error_code lttng_condition_session_rotation_mi_serialize(
 
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED:
-               type_element_str =
-                               mi_lttng_element_condition_session_rotation_completed;
+               type_element_str = mi_lttng_element_condition_session_rotation_completed;
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
-               type_element_str =
-                               mi_lttng_element_condition_session_rotation_ongoing;
+               type_element_str = mi_lttng_element_condition_session_rotation_ongoing;
                break;
        default:
                abort();
                break;
        }
 
-       status = lttng_condition_session_rotation_get_session_name(
-                       condition, &session_name);
+       status = lttng_condition_session_rotation_get_session_name(condition, &session_name);
        LTTNG_ASSERT(status == LTTNG_CONDITION_STATUS_OK);
        LTTNG_ASSERT(session_name);
 
@@ -640,7 +574,7 @@ enum lttng_error_code lttng_condition_session_rotation_mi_serialize(
 
        /* Session name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_session_name, session_name);
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto mi_error;
        }
index f921a7363953a172db1f0d688aba09b9c665f00d..f56b4bd0d3cfd1902c8e89d4b70e473c308a207b 100644 (file)
 
 #include <lttng/lttng-export.h>
 
-extern const char * const config_element_all;
-LTTNG_EXPORT extern const char * const config_element_channel;
-LTTNG_EXPORT extern const char * const config_element_channels;
-LTTNG_EXPORT extern const char * const config_element_domain;
-LTTNG_EXPORT extern const char * const config_element_domains;
-LTTNG_EXPORT extern const char * const config_element_event;
-LTTNG_EXPORT extern const char * const config_element_events;
-LTTNG_EXPORT extern const char * const config_element_context;
-LTTNG_EXPORT extern const char * const config_element_contexts;
-LTTNG_EXPORT extern const char * const config_element_attributes;
-LTTNG_EXPORT extern const char * const config_element_exclusion;
-LTTNG_EXPORT extern const char * const config_element_exclusions;
-LTTNG_EXPORT extern const char * const config_element_function_attributes;
-LTTNG_EXPORT extern const char * const config_element_probe_attributes;
-LTTNG_EXPORT extern const char * const config_element_symbol_name;
-LTTNG_EXPORT extern const char * const config_element_address;
-LTTNG_EXPORT extern const char * const config_element_offset;
-extern const char * const config_element_userspace_probe_lookup;
-extern const char * const config_element_userspace_probe_lookup_function_default;
-extern const char * const config_element_userspace_probe_lookup_function_elf;
-extern const char * const config_element_userspace_probe_lookup_tracepoint_sdt;
-extern const char * const config_element_userspace_probe_location_binary_path;
-extern const char * const config_element_userspace_probe_function_attributes;
-extern const char * const config_element_userspace_probe_function_location_function_name;
-extern const char * const config_element_userspace_probe_tracepoint_attributes;
-extern const char * const config_element_userspace_probe_tracepoint_location_provider_name;
-extern const char * const config_element_userspace_probe_tracepoint_location_probe_name;
-extern const char * const config_element_name;
-LTTNG_EXPORT extern const char * const config_element_enabled;
-LTTNG_EXPORT extern const char * const config_element_overwrite_mode;
-LTTNG_EXPORT extern const char * const config_element_subbuf_size;
-LTTNG_EXPORT extern const char * const config_element_num_subbuf;
-LTTNG_EXPORT extern const char * const config_element_switch_timer_interval;
-LTTNG_EXPORT extern const char * const config_element_read_timer_interval;
-extern const char * const config_element_monitor_timer_interval;
-extern const char * const config_element_blocking_timeout;
-LTTNG_EXPORT extern const char * const config_element_output;
-LTTNG_EXPORT extern const char * const config_element_output_type;
-LTTNG_EXPORT extern const char * const config_element_tracefile_size;
-LTTNG_EXPORT extern const char * const config_element_tracefile_count;
-LTTNG_EXPORT extern const char * const config_element_live_timer_interval;
-extern const char * const config_element_discarded_events;
-extern const char * const config_element_lost_packets;
-LTTNG_EXPORT extern const char * const config_element_type;
-LTTNG_EXPORT extern const char * const config_element_buffer_type;
-LTTNG_EXPORT extern const char * const config_element_session;
-LTTNG_EXPORT extern const char * const config_element_sessions;
-extern const char * const config_element_context_perf;
-extern const char * const config_element_context_app;
-extern const char * const config_element_context_app_provider_name;
-extern const char * const config_element_context_app_ctx_name;
-LTTNG_EXPORT extern const char * const config_element_config;
-LTTNG_EXPORT extern const char * const config_element_started;
-LTTNG_EXPORT extern const char * const config_element_snapshot_mode;
-LTTNG_EXPORT extern const char * const config_element_loglevel;
-LTTNG_EXPORT extern const char * const config_element_loglevel_type;
-LTTNG_EXPORT extern const char * const config_element_filter;
-extern const char * const config_element_filter_expression;
-LTTNG_EXPORT extern const char * const config_element_snapshot_outputs;
-LTTNG_EXPORT extern const char * const config_element_consumer_output;
-LTTNG_EXPORT extern const char * const config_element_destination;
-LTTNG_EXPORT extern const char * const config_element_path;
-LTTNG_EXPORT extern const char * const config_element_net_output;
-LTTNG_EXPORT extern const char * const config_element_control_uri;
-LTTNG_EXPORT extern const char * const config_element_data_uri;
-LTTNG_EXPORT extern const char * const config_element_max_size;
-LTTNG_EXPORT extern const char * const config_element_pid;
-extern const char * const config_element_process_attr_id;
-LTTNG_EXPORT extern const char * const config_element_pids;
-LTTNG_EXPORT extern const char * const config_element_name;
-LTTNG_EXPORT extern const char * const config_element_shared_memory_path;
-extern const char * const config_element_process_attr_tracker_pid;
-extern const char * const config_element_process_attr_tracker_vpid;
-extern const char * const config_element_process_attr_tracker_uid;
-extern const char * const config_element_process_attr_tracker_vuid;
-extern const char * const config_element_process_attr_tracker_gid;
-extern const char * const config_element_process_attr_tracker_vgid;
-extern const char * const config_element_process_attr_trackers;
-extern const char * const config_element_process_attr_values;
-extern const char * const config_element_process_attr_value_type;
-extern const char * const config_element_process_attr_pid_value;
-extern const char * const config_element_process_attr_vpid_value;
-extern const char * const config_element_process_attr_uid_value;
-extern const char * const config_element_process_attr_vuid_value;
-extern const char * const config_element_process_attr_gid_value;
-extern const char * const config_element_process_attr_vgid_value;
-extern const char * const config_element_process_attr_tracker_type;
-extern const char * const config_element_rotation_timer_interval;
-extern const char * const config_element_rotation_size;
-extern const char * const config_element_rotation_schedule;
+extern const char *const config_element_all;
+LTTNG_EXPORT extern const char *const config_element_channel;
+LTTNG_EXPORT extern const char *const config_element_channels;
+LTTNG_EXPORT extern const char *const config_element_domain;
+LTTNG_EXPORT extern const char *const config_element_domains;
+LTTNG_EXPORT extern const char *const config_element_event;
+LTTNG_EXPORT extern const char *const config_element_events;
+LTTNG_EXPORT extern const char *const config_element_context;
+LTTNG_EXPORT extern const char *const config_element_contexts;
+LTTNG_EXPORT extern const char *const config_element_attributes;
+LTTNG_EXPORT extern const char *const config_element_exclusion;
+LTTNG_EXPORT extern const char *const config_element_exclusions;
+LTTNG_EXPORT extern const char *const config_element_function_attributes;
+LTTNG_EXPORT extern const char *const config_element_probe_attributes;
+LTTNG_EXPORT extern const char *const config_element_symbol_name;
+LTTNG_EXPORT extern const char *const config_element_address;
+LTTNG_EXPORT extern const char *const config_element_offset;
+extern const char *const config_element_userspace_probe_lookup;
+extern const char *const config_element_userspace_probe_lookup_function_default;
+extern const char *const config_element_userspace_probe_lookup_function_elf;
+extern const char *const config_element_userspace_probe_lookup_tracepoint_sdt;
+extern const char *const config_element_userspace_probe_location_binary_path;
+extern const char *const config_element_userspace_probe_function_attributes;
+extern const char *const config_element_userspace_probe_function_location_function_name;
+extern const char *const config_element_userspace_probe_tracepoint_attributes;
+extern const char *const config_element_userspace_probe_tracepoint_location_provider_name;
+extern const char *const config_element_userspace_probe_tracepoint_location_probe_name;
+extern const char *const config_element_name;
+LTTNG_EXPORT extern const char *const config_element_enabled;
+LTTNG_EXPORT extern const char *const config_element_overwrite_mode;
+LTTNG_EXPORT extern const char *const config_element_subbuf_size;
+LTTNG_EXPORT extern const char *const config_element_num_subbuf;
+LTTNG_EXPORT extern const char *const config_element_switch_timer_interval;
+LTTNG_EXPORT extern const char *const config_element_read_timer_interval;
+extern const char *const config_element_monitor_timer_interval;
+extern const char *const config_element_blocking_timeout;
+LTTNG_EXPORT extern const char *const config_element_output;
+LTTNG_EXPORT extern const char *const config_element_output_type;
+LTTNG_EXPORT extern const char *const config_element_tracefile_size;
+LTTNG_EXPORT extern const char *const config_element_tracefile_count;
+LTTNG_EXPORT extern const char *const config_element_live_timer_interval;
+extern const char *const config_element_discarded_events;
+extern const char *const config_element_lost_packets;
+LTTNG_EXPORT extern const char *const config_element_type;
+LTTNG_EXPORT extern const char *const config_element_buffer_type;
+LTTNG_EXPORT extern const char *const config_element_session;
+LTTNG_EXPORT extern const char *const config_element_sessions;
+extern const char *const config_element_context_perf;
+extern const char *const config_element_context_app;
+extern const char *const config_element_context_app_provider_name;
+extern const char *const config_element_context_app_ctx_name;
+LTTNG_EXPORT extern const char *const config_element_config;
+LTTNG_EXPORT extern const char *const config_element_started;
+LTTNG_EXPORT extern const char *const config_element_snapshot_mode;
+LTTNG_EXPORT extern const char *const config_element_loglevel;
+LTTNG_EXPORT extern const char *const config_element_loglevel_type;
+LTTNG_EXPORT extern const char *const config_element_filter;
+extern const char *const config_element_filter_expression;
+LTTNG_EXPORT extern const char *const config_element_snapshot_outputs;
+LTTNG_EXPORT extern const char *const config_element_consumer_output;
+LTTNG_EXPORT extern const char *const config_element_destination;
+LTTNG_EXPORT extern const char *const config_element_path;
+LTTNG_EXPORT extern const char *const config_element_net_output;
+LTTNG_EXPORT extern const char *const config_element_control_uri;
+LTTNG_EXPORT extern const char *const config_element_data_uri;
+LTTNG_EXPORT extern const char *const config_element_max_size;
+LTTNG_EXPORT extern const char *const config_element_pid;
+extern const char *const config_element_process_attr_id;
+LTTNG_EXPORT extern const char *const config_element_pids;
+LTTNG_EXPORT extern const char *const config_element_name;
+LTTNG_EXPORT extern const char *const config_element_shared_memory_path;
+extern const char *const config_element_process_attr_tracker_pid;
+extern const char *const config_element_process_attr_tracker_vpid;
+extern const char *const config_element_process_attr_tracker_uid;
+extern const char *const config_element_process_attr_tracker_vuid;
+extern const char *const config_element_process_attr_tracker_gid;
+extern const char *const config_element_process_attr_tracker_vgid;
+extern const char *const config_element_process_attr_trackers;
+extern const char *const config_element_process_attr_values;
+extern const char *const config_element_process_attr_value_type;
+extern const char *const config_element_process_attr_pid_value;
+extern const char *const config_element_process_attr_vpid_value;
+extern const char *const config_element_process_attr_uid_value;
+extern const char *const config_element_process_attr_vuid_value;
+extern const char *const config_element_process_attr_gid_value;
+extern const char *const config_element_process_attr_vgid_value;
+extern const char *const config_element_process_attr_tracker_type;
+extern const char *const config_element_rotation_timer_interval;
+extern const char *const config_element_rotation_size;
+extern const char *const config_element_rotation_schedule;
 
-LTTNG_EXPORT extern const char * const config_domain_type_kernel;
-LTTNG_EXPORT extern const char * const config_domain_type_ust;
-LTTNG_EXPORT extern const char * const config_domain_type_jul;
-LTTNG_EXPORT extern const char * const config_domain_type_log4j;
-LTTNG_EXPORT extern const char * const config_domain_type_python;
+LTTNG_EXPORT extern const char *const config_domain_type_kernel;
+LTTNG_EXPORT extern const char *const config_domain_type_ust;
+LTTNG_EXPORT extern const char *const config_domain_type_jul;
+LTTNG_EXPORT extern const char *const config_domain_type_log4j;
+LTTNG_EXPORT extern const char *const config_domain_type_python;
 
-LTTNG_EXPORT extern const char * const config_buffer_type_per_pid;
-LTTNG_EXPORT extern const char * const config_buffer_type_per_uid;
-LTTNG_EXPORT extern const char * const config_buffer_type_global;
+LTTNG_EXPORT extern const char *const config_buffer_type_per_pid;
+LTTNG_EXPORT extern const char *const config_buffer_type_per_uid;
+LTTNG_EXPORT extern const char *const config_buffer_type_global;
 
-LTTNG_EXPORT extern const char * const config_overwrite_mode_discard;
-LTTNG_EXPORT extern const char * const config_overwrite_mode_overwrite;
+LTTNG_EXPORT extern const char *const config_overwrite_mode_discard;
+LTTNG_EXPORT extern const char *const config_overwrite_mode_overwrite;
 
-LTTNG_EXPORT extern const char * const config_output_type_splice;
-LTTNG_EXPORT extern const char * const config_output_type_mmap;
+LTTNG_EXPORT extern const char *const config_output_type_splice;
+LTTNG_EXPORT extern const char *const config_output_type_mmap;
 
-LTTNG_EXPORT extern const char * const config_loglevel_type_all;
-LTTNG_EXPORT extern const char * const config_loglevel_type_range;
-LTTNG_EXPORT extern const char * const config_loglevel_type_single;
+LTTNG_EXPORT extern const char *const config_loglevel_type_all;
+LTTNG_EXPORT extern const char *const config_loglevel_type_range;
+LTTNG_EXPORT extern const char *const config_loglevel_type_single;
 
-LTTNG_EXPORT extern const char * const config_event_type_all;
-LTTNG_EXPORT extern const char * const config_event_type_tracepoint;
-LTTNG_EXPORT extern const char * const config_event_type_probe;
-extern const char * const config_event_type_userspace_probe;
-LTTNG_EXPORT extern const char * const config_event_type_function;
-LTTNG_EXPORT extern const char * const config_event_type_function_entry;
-LTTNG_EXPORT extern const char * const config_event_type_noop;
-LTTNG_EXPORT extern const char * const config_event_type_syscall;
-LTTNG_EXPORT extern const char * const config_event_type_kprobe;
-LTTNG_EXPORT extern const char * const config_event_type_kretprobe;
+LTTNG_EXPORT extern const char *const config_event_type_all;
+LTTNG_EXPORT extern const char *const config_event_type_tracepoint;
+LTTNG_EXPORT extern const char *const config_event_type_probe;
+extern const char *const config_event_type_userspace_probe;
+LTTNG_EXPORT extern const char *const config_event_type_function;
+LTTNG_EXPORT extern const char *const config_event_type_function_entry;
+LTTNG_EXPORT extern const char *const config_event_type_noop;
+LTTNG_EXPORT extern const char *const config_event_type_syscall;
+LTTNG_EXPORT extern const char *const config_event_type_kprobe;
+LTTNG_EXPORT extern const char *const config_event_type_kretprobe;
 
-LTTNG_EXPORT extern const char * const config_event_context_pid;
-LTTNG_EXPORT extern const char * const config_event_context_procname;
-LTTNG_EXPORT extern const char * const config_event_context_prio;
-LTTNG_EXPORT extern const char * const config_event_context_nice;
-LTTNG_EXPORT extern const char * const config_event_context_vpid;
-LTTNG_EXPORT extern const char * const config_event_context_tid;
-LTTNG_EXPORT extern const char * const config_event_context_vtid;
-LTTNG_EXPORT extern const char * const config_event_context_ppid;
-LTTNG_EXPORT extern const char * const config_event_context_vppid;
-LTTNG_EXPORT extern const char * const config_event_context_pthread_id;
-LTTNG_EXPORT extern const char * const config_event_context_hostname;
-LTTNG_EXPORT extern const char * const config_event_context_ip;
-LTTNG_EXPORT extern const char * const config_event_context_perf_thread_counter;
-extern const char * const config_event_context_app;
-extern const char * const config_event_context_interruptible;
-extern const char * const config_event_context_preemptible;
-extern const char * const config_event_context_need_reschedule;
-extern const char * const config_event_context_migratable;
-extern const char * const config_event_context_callstack_user;
-extern const char * const config_event_context_callstack_kernel;
+LTTNG_EXPORT extern const char *const config_event_context_pid;
+LTTNG_EXPORT extern const char *const config_event_context_procname;
+LTTNG_EXPORT extern const char *const config_event_context_prio;
+LTTNG_EXPORT extern const char *const config_event_context_nice;
+LTTNG_EXPORT extern const char *const config_event_context_vpid;
+LTTNG_EXPORT extern const char *const config_event_context_tid;
+LTTNG_EXPORT extern const char *const config_event_context_vtid;
+LTTNG_EXPORT extern const char *const config_event_context_ppid;
+LTTNG_EXPORT extern const char *const config_event_context_vppid;
+LTTNG_EXPORT extern const char *const config_event_context_pthread_id;
+LTTNG_EXPORT extern const char *const config_event_context_hostname;
+LTTNG_EXPORT extern const char *const config_event_context_ip;
+LTTNG_EXPORT extern const char *const config_event_context_perf_thread_counter;
+extern const char *const config_event_context_app;
+extern const char *const config_event_context_interruptible;
+extern const char *const config_event_context_preemptible;
+extern const char *const config_event_context_need_reschedule;
+extern const char *const config_event_context_migratable;
+extern const char *const config_event_context_callstack_user;
+extern const char *const config_event_context_callstack_kernel;
 
-extern const char * const config_element_rotation_schedules;
-extern const char * const config_element_rotation_schedule_periodic;
-extern const char * const config_element_rotation_schedule_periodic_time_us;
-extern const char * const config_element_rotation_schedule_size_threshold;
-extern const char * const config_element_rotation_schedule_size_threshold_bytes;
-extern const char * const config_event_context_cgroup_ns;
-extern const char * const config_event_context_ipc_ns;
-extern const char * const config_event_context_mnt_ns;
-extern const char * const config_event_context_net_ns;
-extern const char * const config_event_context_pid_ns;
-extern const char * const config_event_context_time_ns;
-extern const char * const config_event_context_user_ns;
-extern const char * const config_event_context_uts_ns;
-extern const char * const config_event_context_uid;
-extern const char * const config_event_context_euid;
-extern const char * const config_event_context_suid;
-extern const char * const config_event_context_gid;
-extern const char * const config_event_context_egid;
-extern const char * const config_event_context_sgid;
-extern const char * const config_event_context_vuid;
-extern const char * const config_event_context_veuid;
-extern const char * const config_event_context_vsuid;
-extern const char * const config_event_context_vgid;
-extern const char * const config_event_context_vegid;
-extern const char * const config_event_context_vsgid;
+extern const char *const config_element_rotation_schedules;
+extern const char *const config_element_rotation_schedule_periodic;
+extern const char *const config_element_rotation_schedule_periodic_time_us;
+extern const char *const config_element_rotation_schedule_size_threshold;
+extern const char *const config_element_rotation_schedule_size_threshold_bytes;
+extern const char *const config_event_context_cgroup_ns;
+extern const char *const config_event_context_ipc_ns;
+extern const char *const config_event_context_mnt_ns;
+extern const char *const config_event_context_net_ns;
+extern const char *const config_event_context_pid_ns;
+extern const char *const config_event_context_time_ns;
+extern const char *const config_event_context_user_ns;
+extern const char *const config_event_context_uts_ns;
+extern const char *const config_event_context_uid;
+extern const char *const config_event_context_euid;
+extern const char *const config_event_context_suid;
+extern const char *const config_event_context_gid;
+extern const char *const config_event_context_egid;
+extern const char *const config_event_context_sgid;
+extern const char *const config_event_context_vuid;
+extern const char *const config_event_context_veuid;
+extern const char *const config_event_context_vsuid;
+extern const char *const config_event_context_vgid;
+extern const char *const config_event_context_vegid;
+extern const char *const config_event_context_vsgid;
 
 #endif /* CONFIG_SESSION_INTERNAL_H */
index de0b519f7b7e614cdb82ed6a1d73396148f9705b..9af61fa93fb349f037b1e07c5039587c61944729 100644 (file)
@@ -7,35 +7,36 @@
 
 #include "lttng/tracker.h"
 #define _LGPL_SOURCE
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <inttypes.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdbool.h>
+#include "config-internal.hpp"
+#include "session-config.hpp"
 
+#include <common/compat/getenv.hpp>
 #include <common/defaults.hpp>
+#include <common/dynamic-buffer.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/utils.hpp>
-#include <common/dynamic-buffer.hpp>
-#include <common/compat/getenv.hpp>
+
 #include <lttng/lttng-error.h>
-#include <libxml/parser.h>
-#include <libxml/valid.h>
-#include <libxml/xmlschemas.h>
-#include <libxml/tree.h>
 #include <lttng/lttng.h>
-#include <lttng/snapshot.h>
 #include <lttng/rotation.h>
+#include <lttng/snapshot.h>
 #include <lttng/userspace-probe.h>
 
-#include "session-config.hpp"
-#include "config-internal.hpp"
+#include <ctype.h>
+#include <dirent.h>
+#include <inttypes.h>
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+#include <libxml/valid.h>
+#include <libxml/xmlschemas.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #define CONFIG_USERSPACE_PROBE_LOOKUP_METHOD_NAME_MAX_LEN 7
 
@@ -47,185 +48,189 @@ struct session_config_validation_ctx {
 };
 } /* namespace */
 
-const char * const config_element_all = "all";
+const char *const config_element_all = "all";
 LTTNG_EXPORT const char *config_xml_encoding = "UTF-8";
-LTTNG_EXPORT size_t config_xml_encoding_bytes_per_char = 2;    /* Size of the encoding's largest character */
+LTTNG_EXPORT size_t config_xml_encoding_bytes_per_char = 2; /* Size of the encoding's largest
+                                                              character */
 LTTNG_EXPORT const char *config_xml_indent_string = "\t";
 LTTNG_EXPORT const char *config_xml_true = "true";
 LTTNG_EXPORT const char *config_xml_false = "false";
 
-const char * const config_element_channel = "channel";
-const char * const config_element_channels = "channels";
-const char * const config_element_domain = "domain";
-const char * const config_element_domains = "domains";
-const char * const config_element_event = "event";
-const char * const config_element_events = "events";
-const char * const config_element_context = "context";
-const char * const config_element_contexts = "contexts";
-const char * const config_element_attributes = "attributes";
-const char * const config_element_exclusion = "exclusion";
-const char * const config_element_exclusions = "exclusions";
-const char * const config_element_function_attributes = "function_attributes";
-const char * const config_element_probe_attributes = "probe_attributes";
-const char * const config_element_symbol_name = "symbol_name";
-const char * const config_element_address = "address";
-const char * const config_element_offset = "offset";
-
-const char * const config_element_userspace_probe_lookup = "lookup_method";
-const char * const config_element_userspace_probe_lookup_function_default = "DEFAULT";
-const char * const config_element_userspace_probe_lookup_function_elf = "ELF";
-const char * const config_element_userspace_probe_lookup_tracepoint_sdt = "SDT";
-const char * const config_element_userspace_probe_location_binary_path = "binary_path";
-const char * const config_element_userspace_probe_function_attributes = "userspace_probe_function_attributes";
-const char * const config_element_userspace_probe_function_location_function_name = "function_name";
-const char * const config_element_userspace_probe_tracepoint_attributes = "userspace_probe_tracepoint_attributes";
-const char * const config_element_userspace_probe_tracepoint_location_provider_name = "provider_name";
-const char * const config_element_userspace_probe_tracepoint_location_probe_name = "probe_name";
-
-const char * const config_element_name = "name";
-const char * const config_element_enabled = "enabled";
-const char * const config_element_overwrite_mode = "overwrite_mode";
-const char * const config_element_subbuf_size = "subbuffer_size";
-const char * const config_element_num_subbuf = "subbuffer_count";
-const char * const config_element_switch_timer_interval = "switch_timer_interval";
-const char * const config_element_read_timer_interval = "read_timer_interval";
-const char * const config_element_monitor_timer_interval = "monitor_timer_interval";
-const char * const config_element_blocking_timeout = "blocking_timeout";
-const char * const config_element_output = "output";
-const char * const config_element_output_type = "output_type";
-const char * const config_element_tracefile_size = "tracefile_size";
-const char * const config_element_tracefile_count = "tracefile_count";
-const char * const config_element_live_timer_interval = "live_timer_interval";
-const char * const config_element_discarded_events = "discarded_events";
-const char * const config_element_lost_packets = "lost_packets";
-const char * const config_element_type = "type";
-const char * const config_element_buffer_type = "buffer_type";
-const char * const config_element_session = "session";
-const char * const config_element_sessions = "sessions";
-const char * const config_element_context_perf = "perf";
-const char * const config_element_context_app = "app";
-const char * const config_element_context_app_provider_name = "provider_name";
-const char * const config_element_context_app_ctx_name = "ctx_name";
-const char * const config_element_config = "config";
-const char * const config_element_started = "started";
-const char * const config_element_snapshot_mode = "snapshot_mode";
-const char * const config_element_loglevel = "loglevel";
-const char * const config_element_loglevel_type = "loglevel_type";
-const char * const config_element_filter = "filter";
-const char * const config_element_filter_expression = "filter_expression";
-const char * const config_element_snapshot_outputs = "snapshot_outputs";
-const char * const config_element_consumer_output = "consumer_output";
-const char * const config_element_destination = "destination";
-const char * const config_element_path = "path";
-const char * const config_element_net_output = "net_output";
-const char * const config_element_control_uri = "control_uri";
-const char * const config_element_data_uri = "data_uri";
-const char * const config_element_max_size = "max_size";
-const char * const config_element_pid = "pid";
-const char * const config_element_pids = "pids";
-const char * const config_element_shared_memory_path = "shared_memory_path";
-
-const char * const config_element_process_attr_id = "id";
-const char * const config_element_process_attr_tracker_pid = "pid_process_attr_tracker";
-const char * const config_element_process_attr_tracker_vpid = "vpid_process_attr_tracker";
-const char * const config_element_process_attr_tracker_uid = "uid_process_attr_tracker";
-const char * const config_element_process_attr_tracker_vuid = "vuid_process_attr_tracker";
-const char * const config_element_process_attr_tracker_gid = "gid_process_attr_tracker";
-const char * const config_element_process_attr_tracker_vgid = "vgid_process_attr_tracker";
-const char * const config_element_process_attr_trackers = "process_attr_trackers";
-const char * const config_element_process_attr_values = "process_attr_values";
-const char * const config_element_process_attr_value_type = "process_attr_value_type";
-const char * const config_element_process_attr_pid_value = "pid";
-const char * const config_element_process_attr_vpid_value = "vpid";
-const char * const config_element_process_attr_uid_value = "uid";
-const char * const config_element_process_attr_vuid_value = "vuid";
-const char * const config_element_process_attr_gid_value = "gid";
-const char * const config_element_process_attr_vgid_value = "vgid";
-const char * const config_element_process_attr_tracker_type = "process_attr_tracker_type";
+const char *const config_element_channel = "channel";
+const char *const config_element_channels = "channels";
+const char *const config_element_domain = "domain";
+const char *const config_element_domains = "domains";
+const char *const config_element_event = "event";
+const char *const config_element_events = "events";
+const char *const config_element_context = "context";
+const char *const config_element_contexts = "contexts";
+const char *const config_element_attributes = "attributes";
+const char *const config_element_exclusion = "exclusion";
+const char *const config_element_exclusions = "exclusions";
+const char *const config_element_function_attributes = "function_attributes";
+const char *const config_element_probe_attributes = "probe_attributes";
+const char *const config_element_symbol_name = "symbol_name";
+const char *const config_element_address = "address";
+const char *const config_element_offset = "offset";
+
+const char *const config_element_userspace_probe_lookup = "lookup_method";
+const char *const config_element_userspace_probe_lookup_function_default = "DEFAULT";
+const char *const config_element_userspace_probe_lookup_function_elf = "ELF";
+const char *const config_element_userspace_probe_lookup_tracepoint_sdt = "SDT";
+const char *const config_element_userspace_probe_location_binary_path = "binary_path";
+const char *const config_element_userspace_probe_function_attributes =
+       "userspace_probe_function_attributes";
+const char *const config_element_userspace_probe_function_location_function_name = "function_name";
+const char *const config_element_userspace_probe_tracepoint_attributes =
+       "userspace_probe_tracepoint_attributes";
+const char *const config_element_userspace_probe_tracepoint_location_provider_name =
+       "provider_name";
+const char *const config_element_userspace_probe_tracepoint_location_probe_name = "probe_name";
+
+const char *const config_element_name = "name";
+const char *const config_element_enabled = "enabled";
+const char *const config_element_overwrite_mode = "overwrite_mode";
+const char *const config_element_subbuf_size = "subbuffer_size";
+const char *const config_element_num_subbuf = "subbuffer_count";
+const char *const config_element_switch_timer_interval = "switch_timer_interval";
+const char *const config_element_read_timer_interval = "read_timer_interval";
+const char *const config_element_monitor_timer_interval = "monitor_timer_interval";
+const char *const config_element_blocking_timeout = "blocking_timeout";
+const char *const config_element_output = "output";
+const char *const config_element_output_type = "output_type";
+const char *const config_element_tracefile_size = "tracefile_size";
+const char *const config_element_tracefile_count = "tracefile_count";
+const char *const config_element_live_timer_interval = "live_timer_interval";
+const char *const config_element_discarded_events = "discarded_events";
+const char *const config_element_lost_packets = "lost_packets";
+const char *const config_element_type = "type";
+const char *const config_element_buffer_type = "buffer_type";
+const char *const config_element_session = "session";
+const char *const config_element_sessions = "sessions";
+const char *const config_element_context_perf = "perf";
+const char *const config_element_context_app = "app";
+const char *const config_element_context_app_provider_name = "provider_name";
+const char *const config_element_context_app_ctx_name = "ctx_name";
+const char *const config_element_config = "config";
+const char *const config_element_started = "started";
+const char *const config_element_snapshot_mode = "snapshot_mode";
+const char *const config_element_loglevel = "loglevel";
+const char *const config_element_loglevel_type = "loglevel_type";
+const char *const config_element_filter = "filter";
+const char *const config_element_filter_expression = "filter_expression";
+const char *const config_element_snapshot_outputs = "snapshot_outputs";
+const char *const config_element_consumer_output = "consumer_output";
+const char *const config_element_destination = "destination";
+const char *const config_element_path = "path";
+const char *const config_element_net_output = "net_output";
+const char *const config_element_control_uri = "control_uri";
+const char *const config_element_data_uri = "data_uri";
+const char *const config_element_max_size = "max_size";
+const char *const config_element_pid = "pid";
+const char *const config_element_pids = "pids";
+const char *const config_element_shared_memory_path = "shared_memory_path";
+
+const char *const config_element_process_attr_id = "id";
+const char *const config_element_process_attr_tracker_pid = "pid_process_attr_tracker";
+const char *const config_element_process_attr_tracker_vpid = "vpid_process_attr_tracker";
+const char *const config_element_process_attr_tracker_uid = "uid_process_attr_tracker";
+const char *const config_element_process_attr_tracker_vuid = "vuid_process_attr_tracker";
+const char *const config_element_process_attr_tracker_gid = "gid_process_attr_tracker";
+const char *const config_element_process_attr_tracker_vgid = "vgid_process_attr_tracker";
+const char *const config_element_process_attr_trackers = "process_attr_trackers";
+const char *const config_element_process_attr_values = "process_attr_values";
+const char *const config_element_process_attr_value_type = "process_attr_value_type";
+const char *const config_element_process_attr_pid_value = "pid";
+const char *const config_element_process_attr_vpid_value = "vpid";
+const char *const config_element_process_attr_uid_value = "uid";
+const char *const config_element_process_attr_vuid_value = "vuid";
+const char *const config_element_process_attr_gid_value = "gid";
+const char *const config_element_process_attr_vgid_value = "vgid";
+const char *const config_element_process_attr_tracker_type = "process_attr_tracker_type";
 
 /* Used for support of legacy tracker serialization (< 2.12). */
-const char * const config_element_trackers_legacy = "trackers";
-const char * const config_element_pid_tracker_legacy = "pid_tracker";
-const char * const config_element_tracker_targets_legacy = "targets";
-const char * const config_element_tracker_pid_legacy = "pid";
-
-const char * const config_element_rotation_schedules = "rotation_schedules";
-const char * const config_element_rotation_schedule_periodic = "periodic";
-const char * const config_element_rotation_schedule_periodic_time_us = "time_us";
-const char * const config_element_rotation_schedule_size_threshold = "size_threshold";
-const char * const config_element_rotation_schedule_size_threshold_bytes = "bytes";
-
-const char * const config_domain_type_kernel = "KERNEL";
-const char * const config_domain_type_ust = "UST";
-const char * const config_domain_type_jul = "JUL";
-const char * const config_domain_type_log4j = "LOG4J";
-const char * const config_domain_type_python = "PYTHON";
-
-const char * const config_buffer_type_per_pid = "PER_PID";
-const char * const config_buffer_type_per_uid = "PER_UID";
-const char * const config_buffer_type_global = "GLOBAL";
-
-const char * const config_overwrite_mode_discard = "DISCARD";
-const char * const config_overwrite_mode_overwrite = "OVERWRITE";
-
-const char * const config_output_type_splice = "SPLICE";
-const char * const config_output_type_mmap = "MMAP";
-
-const char * const config_loglevel_type_all = "ALL";
-const char * const config_loglevel_type_range = "RANGE";
-const char * const config_loglevel_type_single = "SINGLE";
-
-const char * const config_event_type_all = "ALL";
-const char * const config_event_type_tracepoint = "TRACEPOINT";
-const char * const config_event_type_probe = "PROBE";
-const char * const config_event_type_userspace_probe = "USERSPACE_PROBE";
-const char * const config_event_type_function = "FUNCTION";
-const char * const config_event_type_function_entry = "FUNCTION_ENTRY";
-const char * const config_event_type_noop = "NOOP";
-const char * const config_event_type_syscall = "SYSCALL";
-const char * const config_event_type_kprobe = "KPROBE";
-const char * const config_event_type_kretprobe = "KRETPROBE";
-
-const char * const config_event_context_pid = "PID";
-const char * const config_event_context_procname = "PROCNAME";
-const char * const config_event_context_prio = "PRIO";
-const char * const config_event_context_nice = "NICE";
-const char * const config_event_context_vpid = "VPID";
-const char * const config_event_context_tid = "TID";
-const char * const config_event_context_vtid = "VTID";
-const char * const config_event_context_ppid = "PPID";
-const char * const config_event_context_vppid = "VPPID";
-const char * const config_event_context_pthread_id = "PTHREAD_ID";
-const char * const config_event_context_hostname = "HOSTNAME";
-const char * const config_event_context_ip = "IP";
-const char * const config_event_context_perf_thread_counter = "PERF_THREAD_COUNTER";
-const char * const config_event_context_app = "APP";
-const char * const config_event_context_interruptible = "INTERRUPTIBLE";
-const char * const config_event_context_preemptible = "PREEMPTIBLE";
-const char * const config_event_context_need_reschedule = "NEED_RESCHEDULE";
-const char * const config_event_context_migratable = "MIGRATABLE";
-const char * const config_event_context_callstack_user= "CALLSTACK_USER";
-const char * const config_event_context_callstack_kernel = "CALLSTACK_KERNEL";
-const char * const config_event_context_cgroup_ns = "CGROUP_NS";
-const char * const config_event_context_ipc_ns = "IPC_NS";
-const char * const config_event_context_mnt_ns = "MNT_NS";
-const char * const config_event_context_net_ns = "NET_NS";
-const char * const config_event_context_pid_ns = "PID_NS";
-const char * const config_event_context_time_ns = "TIME_NS";
-const char * const config_event_context_user_ns = "USER_NS";
-const char * const config_event_context_uts_ns = "UTS_NS";
-const char * const config_event_context_uid = "UID";
-const char * const config_event_context_euid = "EUID";
-const char * const config_event_context_suid = "SUID";
-const char * const config_event_context_gid = "GID";
-const char * const config_event_context_egid = "EGID";
-const char * const config_event_context_sgid = "SGID";
-const char * const config_event_context_vuid = "VUID";
-const char * const config_event_context_veuid = "VEUID";
-const char * const config_event_context_vsuid = "VSUID";
-const char * const config_event_context_vgid = "VGID";
-const char * const config_event_context_vegid = "VEGID";
-const char * const config_event_context_vsgid = "VSGID";
+const char *const config_element_trackers_legacy = "trackers";
+const char *const config_element_pid_tracker_legacy = "pid_tracker";
+const char *const config_element_tracker_targets_legacy = "targets";
+const char *const config_element_tracker_pid_legacy = "pid";
+
+const char *const config_element_rotation_schedules = "rotation_schedules";
+const char *const config_element_rotation_schedule_periodic = "periodic";
+const char *const config_element_rotation_schedule_periodic_time_us = "time_us";
+const char *const config_element_rotation_schedule_size_threshold = "size_threshold";
+const char *const config_element_rotation_schedule_size_threshold_bytes = "bytes";
+
+const char *const config_domain_type_kernel = "KERNEL";
+const char *const config_domain_type_ust = "UST";
+const char *const config_domain_type_jul = "JUL";
+const char *const config_domain_type_log4j = "LOG4J";
+const char *const config_domain_type_python = "PYTHON";
+
+const char *const config_buffer_type_per_pid = "PER_PID";
+const char *const config_buffer_type_per_uid = "PER_UID";
+const char *const config_buffer_type_global = "GLOBAL";
+
+const char *const config_overwrite_mode_discard = "DISCARD";
+const char *const config_overwrite_mode_overwrite = "OVERWRITE";
+
+const char *const config_output_type_splice = "SPLICE";
+const char *const config_output_type_mmap = "MMAP";
+
+const char *const config_loglevel_type_all = "ALL";
+const char *const config_loglevel_type_range = "RANGE";
+const char *const config_loglevel_type_single = "SINGLE";
+
+const char *const config_event_type_all = "ALL";
+const char *const config_event_type_tracepoint = "TRACEPOINT";
+const char *const config_event_type_probe = "PROBE";
+const char *const config_event_type_userspace_probe = "USERSPACE_PROBE";
+const char *const config_event_type_function = "FUNCTION";
+const char *const config_event_type_function_entry = "FUNCTION_ENTRY";
+const char *const config_event_type_noop = "NOOP";
+const char *const config_event_type_syscall = "SYSCALL";
+const char *const config_event_type_kprobe = "KPROBE";
+const char *const config_event_type_kretprobe = "KRETPROBE";
+
+const char *const config_event_context_pid = "PID";
+const char *const config_event_context_procname = "PROCNAME";
+const char *const config_event_context_prio = "PRIO";
+const char *const config_event_context_nice = "NICE";
+const char *const config_event_context_vpid = "VPID";
+const char *const config_event_context_tid = "TID";
+const char *const config_event_context_vtid = "VTID";
+const char *const config_event_context_ppid = "PPID";
+const char *const config_event_context_vppid = "VPPID";
+const char *const config_event_context_pthread_id = "PTHREAD_ID";
+const char *const config_event_context_hostname = "HOSTNAME";
+const char *const config_event_context_ip = "IP";
+const char *const config_event_context_perf_thread_counter = "PERF_THREAD_COUNTER";
+const char *const config_event_context_app = "APP";
+const char *const config_event_context_interruptible = "INTERRUPTIBLE";
+const char *const config_event_context_preemptible = "PREEMPTIBLE";
+const char *const config_event_context_need_reschedule = "NEED_RESCHEDULE";
+const char *const config_event_context_migratable = "MIGRATABLE";
+const char *const config_event_context_callstack_user = "CALLSTACK_USER";
+const char *const config_event_context_callstack_kernel = "CALLSTACK_KERNEL";
+const char *const config_event_context_cgroup_ns = "CGROUP_NS";
+const char *const config_event_context_ipc_ns = "IPC_NS";
+const char *const config_event_context_mnt_ns = "MNT_NS";
+const char *const config_event_context_net_ns = "NET_NS";
+const char *const config_event_context_pid_ns = "PID_NS";
+const char *const config_event_context_time_ns = "TIME_NS";
+const char *const config_event_context_user_ns = "USER_NS";
+const char *const config_event_context_uts_ns = "UTS_NS";
+const char *const config_event_context_uid = "UID";
+const char *const config_event_context_euid = "EUID";
+const char *const config_event_context_suid = "SUID";
+const char *const config_event_context_gid = "GID";
+const char *const config_event_context_egid = "EGID";
+const char *const config_event_context_sgid = "SGID";
+const char *const config_event_context_vuid = "VUID";
+const char *const config_event_context_veuid = "VEUID";
+const char *const config_event_context_vsuid = "VSUID";
+const char *const config_event_context_vgid = "VGID";
+const char *const config_event_context_vegid = "VEGID";
+const char *const config_event_context_vsgid = "VSGID";
 
 /* Deprecated symbols */
 LTTNG_EXPORT const char *config_element_perf;
@@ -249,7 +254,7 @@ struct consumer_output {
  */
 static xmlChar *encode_string(const char *in_str)
 {
-       xmlChar *out_str = NULL;
+       xmlChar *out_str = nullptr;
        xmlCharEncodingHandlerPtr handler;
        int out_len, ret, in_len;
 
@@ -275,7 +280,7 @@ static xmlChar *encode_string(const char *in_str)
        ret = handler->input(out_str, &out_len, (const xmlChar *) in_str, &in_len);
        if (ret < 0) {
                xmlFree(out_str);
-               out_str = NULL;
+               out_str = nullptr;
                goto end;
        }
 
@@ -297,20 +302,18 @@ struct config_writer *config_writer_create(int fd_output, int indent)
                goto end;
        }
 
-       buffer = xmlOutputBufferCreateFd(fd_output, NULL);
+       buffer = xmlOutputBufferCreateFd(fd_output, nullptr);
        if (!buffer) {
                goto error_destroy;
        }
 
        writer->writer = xmlNewTextWriter(buffer);
-       ret = xmlTextWriterStartDocument(writer->writer, NULL,
-               config_xml_encoding, NULL);
+       ret = xmlTextWriterStartDocument(writer->writer, nullptr, config_xml_encoding, nullptr);
        if (ret < 0) {
                goto error_destroy;
        }
 
-       ret = xmlTextWriterSetIndentString(writer->writer,
-               BAD_CAST config_xml_indent_string);
+       ret = xmlTextWriterSetIndentString(writer->writer, BAD_CAST config_xml_indent_string);
        if (ret) {
                goto error_destroy;
        }
@@ -324,7 +327,7 @@ end:
        return writer;
 error_destroy:
        config_writer_destroy(writer);
-       return NULL;
+       return nullptr;
 }
 
 int config_writer_destroy(struct config_writer *writer)
@@ -350,8 +353,7 @@ end:
        return ret;
 }
 
-int config_writer_open_element(struct config_writer *writer,
-       const char *element_name)
+int config_writer_open_element(struct config_writer *writer, const char *element_name)
 {
        int ret;
        xmlChar *encoded_element_name;
@@ -373,12 +375,11 @@ end:
        return ret >= 0 ? 0 : ret;
 }
 
-int config_writer_write_attribute(struct config_writer *writer,
-               const char *name, const char *value)
+int config_writer_write_attribute(struct config_writer *writer, const char *name, const char *value)
 {
        int ret;
-       xmlChar *encoded_name = NULL;
-       xmlChar *encoded_value = NULL;
+       xmlChar *encoded_name = nullptr;
+       xmlChar *encoded_value = nullptr;
 
        if (!writer || !writer->writer || !name || !name[0]) {
                ret = -1;
@@ -397,8 +398,7 @@ int config_writer_write_attribute(struct config_writer *writer,
                goto end;
        }
 
-       ret = xmlTextWriterWriteAttribute(writer->writer, encoded_name,
-                       encoded_value);
+       ret = xmlTextWriterWriteAttribute(writer->writer, encoded_name, encoded_value);
 end:
        xmlFree(encoded_name);
        xmlFree(encoded_value);
@@ -420,7 +420,8 @@ end:
 }
 
 int config_writer_write_element_unsigned_int(struct config_writer *writer,
-               const char *element_name, uint64_t value)
+                                            const char *element_name,
+                                            uint64_t value)
 {
        int ret;
        xmlChar *encoded_element_name;
@@ -436,15 +437,16 @@ int config_writer_write_element_unsigned_int(struct config_writer *writer,
                goto end;
        }
 
-       ret = xmlTextWriterWriteFormatElement(writer->writer,
-               encoded_element_name, "%" PRIu64, value);
+       ret = xmlTextWriterWriteFormatElement(
+               writer->writer, encoded_element_name, "%" PRIu64, value);
        xmlFree(encoded_element_name);
 end:
        return ret >= 0 ? 0 : ret;
 }
 
 int config_writer_write_element_signed_int(struct config_writer *writer,
-               const char *element_name, int64_t value)
+                                          const char *element_name,
+                                          int64_t value)
 {
        int ret;
        xmlChar *encoded_element_name;
@@ -460,23 +462,24 @@ int config_writer_write_element_signed_int(struct config_writer *writer,
                goto end;
        }
 
-       ret = xmlTextWriterWriteFormatElement(writer->writer,
-               encoded_element_name, "%" PRIi64, value);
+       ret = xmlTextWriterWriteFormatElement(
+               writer->writer, encoded_element_name, "%" PRIi64, value);
        xmlFree(encoded_element_name);
 end:
        return ret >= 0 ? 0 : ret;
 }
 
 int config_writer_write_element_bool(struct config_writer *writer,
-               const char *element_name, int value)
+                                    const char *element_name,
+                                    int value)
 {
-       return config_writer_write_element_string(writer, element_name,
-               value ? config_xml_true : config_xml_false);
+       return config_writer_write_element_string(
+               writer, element_name, value ? config_xml_true : config_xml_false);
 }
 
 int config_writer_write_element_double(struct config_writer *writer,
-               const char *element_name,
-               double value)
+                                      const char *element_name,
+                                      double value)
 {
        int ret;
        xmlChar *encoded_element_name;
@@ -492,22 +495,21 @@ int config_writer_write_element_double(struct config_writer *writer,
                goto end;
        }
 
-       ret = xmlTextWriterWriteFormatElement(
-                       writer->writer, encoded_element_name, "%f", value);
+       ret = xmlTextWriterWriteFormatElement(writer->writer, encoded_element_name, "%f", value);
        xmlFree(encoded_element_name);
 end:
        return ret >= 0 ? 0 : ret;
 }
 
 int config_writer_write_element_string(struct config_writer *writer,
-               const char *element_name, const char *value)
+                                      const char *element_name,
+                                      const char *value)
 {
        int ret;
-       xmlChar *encoded_element_name = NULL;
-       xmlChar *encoded_value = NULL;
+       xmlChar *encoded_element_name = nullptr;
+       xmlChar *encoded_value = nullptr;
 
-       if (!writer || !writer->writer || !element_name || !element_name[0] ||
-               !value) {
+       if (!writer || !writer->writer || !element_name || !element_name[0] || !value) {
                ret = -1;
                goto end;
        }
@@ -524,16 +526,16 @@ int config_writer_write_element_string(struct config_writer *writer,
                goto end;
        }
 
-       ret = xmlTextWriterWriteElement(writer->writer, encoded_element_name,
-                       encoded_value);
+       ret = xmlTextWriterWriteElement(writer->writer, encoded_element_name, encoded_value);
 end:
        xmlFree(encoded_element_name);
        xmlFree(encoded_value);
        return ret >= 0 ? 0 : ret;
 }
 
-static ATTR_FORMAT_PRINTF(2, 3)
-void xml_error_handler(void *ctx __attribute__((unused)), const char *format, ...)
+static ATTR_FORMAT_PRINTF(2, 3) void xml_error_handler(void *ctx __attribute__((unused)),
+                                                      const char *format,
+                                                      ...)
 {
        char *errMsg;
        va_list args;
@@ -551,9 +553,7 @@ void xml_error_handler(void *ctx __attribute__((unused)), const char *format, ..
        free(errMsg);
 }
 
-static
-void fini_session_config_validation_ctx(
-       struct session_config_validation_ctx *ctx)
+static void fini_session_config_validation_ctx(struct session_config_validation_ctx *ctx)
 {
        if (ctx->parser_ctx) {
                xmlSchemaFreeParserCtxt(ctx->parser_ctx);
@@ -570,8 +570,7 @@ void fini_session_config_validation_ctx(
        memset(ctx, 0, sizeof(struct session_config_validation_ctx));
 }
 
-static
-char *get_session_config_xsd_path(void)
+static char *get_session_config_xsd_path()
 {
        char *xsd_path;
        const char *base_path = lttng_secure_getenv(DEFAULT_SESSION_CONFIG_XSD_PATH_ENV);
@@ -583,8 +582,7 @@ char *get_session_config_xsd_path(void)
        }
 
        base_path_len = strlen(base_path);
-       max_path_len = base_path_len +
-               sizeof(DEFAULT_SESSION_CONFIG_XSD_FILENAME) + 1;
+       max_path_len = base_path_len + sizeof(DEFAULT_SESSION_CONFIG_XSD_FILENAME) + 1;
        xsd_path = zmalloc<char>(max_path_len);
        if (!xsd_path) {
                goto end;
@@ -600,9 +598,7 @@ end:
        return xsd_path;
 }
 
-static
-int init_session_config_validation_ctx(
-       struct session_config_validation_ctx *ctx)
+static int init_session_config_validation_ctx(struct session_config_validation_ctx *ctx)
 {
        int ret;
        char *xsd_path = get_session_config_xsd_path();
@@ -618,8 +614,7 @@ int init_session_config_validation_ctx(
                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                goto end;
        }
-       xmlSchemaSetParserErrors(ctx->parser_ctx, xml_error_handler,
-               xml_error_handler, NULL);
+       xmlSchemaSetParserErrors(ctx->parser_ctx, xml_error_handler, xml_error_handler, nullptr);
 
        ctx->schema = xmlSchemaParse(ctx->parser_ctx);
        if (!ctx->schema) {
@@ -635,8 +630,8 @@ int init_session_config_validation_ctx(
                goto end;
        }
 
-       xmlSchemaSetValidErrors(ctx->schema_validation_ctx, xml_error_handler,
-                       xml_error_handler, NULL);
+       xmlSchemaSetValidErrors(
+               ctx->schema_validation_ctx, xml_error_handler, xml_error_handler, nullptr);
        ret = 0;
 
 end:
@@ -648,8 +643,7 @@ end:
        return ret;
 }
 
-static
-int parse_uint(xmlChar *str, uint64_t *val)
+static int parse_uint(xmlChar *str, uint64_t *val)
 {
        int ret;
        char *endptr;
@@ -670,8 +664,7 @@ end:
        return ret;
 }
 
-static
-int parse_int(xmlChar *str, int64_t *val)
+static int parse_int(xmlChar *str, int64_t *val)
 {
        int ret;
        char *endptr;
@@ -692,8 +685,7 @@ end:
        return ret;
 }
 
-static
-int parse_bool(xmlChar *str, int *val)
+static int parse_bool(xmlChar *str, int *val)
 {
        int ret = 0;
 
@@ -702,23 +694,20 @@ int parse_bool(xmlChar *str, int *val)
                goto end;
        }
 
-       if (!strcmp((const char *) str, config_xml_true) ||
-                       !strcmp((const char *) str, "1")) {
+       if (!strcmp((const char *) str, config_xml_true) || !strcmp((const char *) str, "1")) {
                *val = 1;
        } else if (!strcmp((const char *) str, config_xml_false) ||
-                       !strcmp((const char *) str, "0")) {
+                  !strcmp((const char *) str, "0")) {
                *val = 0;
        } else {
-               WARN("Invalid boolean value encountered (%s).",
-                       (const char *) str);
+               WARN("Invalid boolean value encountered (%s).", (const char *) str);
                ret = -1;
        }
 end:
        return ret;
 }
 
-static
-int get_domain_type(xmlChar *domain)
+static int get_domain_type(xmlChar *domain)
 {
        int ret;
 
@@ -745,8 +734,7 @@ error:
        return -1;
 }
 
-static
-int get_buffer_type(xmlChar *buffer_type)
+static int get_buffer_type(xmlChar *buffer_type)
 {
        int ret;
 
@@ -769,8 +757,7 @@ error:
        return -1;
 }
 
-static
-int get_overwrite_mode(xmlChar *overwrite_mode)
+static int get_overwrite_mode(xmlChar *overwrite_mode)
 {
        int ret;
 
@@ -780,8 +767,7 @@ int get_overwrite_mode(xmlChar *overwrite_mode)
 
        if (!strcmp((char *) overwrite_mode, config_overwrite_mode_overwrite)) {
                ret = 1;
-       } else if (!strcmp((char *) overwrite_mode,
-               config_overwrite_mode_discard)) {
+       } else if (!strcmp((char *) overwrite_mode, config_overwrite_mode_discard)) {
                ret = 0;
        } else {
                goto error;
@@ -792,8 +778,7 @@ error:
        return -1;
 }
 
-static
-int get_output_type(xmlChar *output_type)
+static int get_output_type(xmlChar *output_type)
 {
        int ret;
 
@@ -814,8 +799,7 @@ error:
        return -1;
 }
 
-static
-int get_event_type(xmlChar *event_type)
+static int get_event_type(xmlChar *event_type)
 {
        int ret;
 
@@ -829,13 +813,11 @@ int get_event_type(xmlChar *event_type)
                ret = LTTNG_EVENT_TRACEPOINT;
        } else if (!strcmp((char *) event_type, config_event_type_probe)) {
                ret = LTTNG_EVENT_PROBE;
-       } else if (!strcmp((char *) event_type,
-                               config_event_type_userspace_probe)) {
+       } else if (!strcmp((char *) event_type, config_event_type_userspace_probe)) {
                ret = LTTNG_EVENT_USERSPACE_PROBE;
        } else if (!strcmp((char *) event_type, config_event_type_function)) {
                ret = LTTNG_EVENT_FUNCTION;
-       } else if (!strcmp((char *) event_type,
-                               config_event_type_function_entry)) {
+       } else if (!strcmp((char *) event_type, config_event_type_function_entry)) {
                ret = LTTNG_EVENT_FUNCTION_ENTRY;
        } else if (!strcmp((char *) event_type, config_event_type_noop)) {
                ret = LTTNG_EVENT_NOOP;
@@ -850,8 +832,7 @@ error:
        return -1;
 }
 
-static
-int get_loglevel_type(xmlChar *loglevel_type)
+static int get_loglevel_type(xmlChar *loglevel_type)
 {
        int ret;
 
@@ -861,11 +842,9 @@ int get_loglevel_type(xmlChar *loglevel_type)
 
        if (!strcmp((char *) loglevel_type, config_loglevel_type_all)) {
                ret = LTTNG_EVENT_LOGLEVEL_ALL;
-       } else if (!strcmp((char *) loglevel_type,
-               config_loglevel_type_range)) {
+       } else if (!strcmp((char *) loglevel_type, config_loglevel_type_range)) {
                ret = LTTNG_EVENT_LOGLEVEL_RANGE;
-       } else if (!strcmp((char *) loglevel_type,
-               config_loglevel_type_single)) {
+       } else if (!strcmp((char *) loglevel_type, config_loglevel_type_single)) {
                ret = LTTNG_EVENT_LOGLEVEL_SINGLE;
        } else {
                goto error;
@@ -879,8 +858,7 @@ error:
 /*
  * Return the context type or -1 on error.
  */
-static
-int get_context_type(xmlChar *context_type)
+static int get_context_type(xmlChar *context_type)
 {
        int ret;
 
@@ -890,116 +868,79 @@ int get_context_type(xmlChar *context_type)
 
        if (!strcmp((char *) context_type, config_event_context_pid)) {
                ret = LTTNG_EVENT_CONTEXT_PID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_procname)) {
+       } else if (!strcmp((char *) context_type, config_event_context_procname)) {
                ret = LTTNG_EVENT_CONTEXT_PROCNAME;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_prio)) {
+       } else if (!strcmp((char *) context_type, config_event_context_prio)) {
                ret = LTTNG_EVENT_CONTEXT_PRIO;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_nice)) {
+       } else if (!strcmp((char *) context_type, config_event_context_nice)) {
                ret = LTTNG_EVENT_CONTEXT_NICE;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vpid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vpid)) {
                ret = LTTNG_EVENT_CONTEXT_VPID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_tid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_tid)) {
                ret = LTTNG_EVENT_CONTEXT_TID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vtid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vtid)) {
                ret = LTTNG_EVENT_CONTEXT_VTID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_ppid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_ppid)) {
                ret = LTTNG_EVENT_CONTEXT_PPID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vppid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vppid)) {
                ret = LTTNG_EVENT_CONTEXT_VPPID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_pthread_id)) {
+       } else if (!strcmp((char *) context_type, config_event_context_pthread_id)) {
                ret = LTTNG_EVENT_CONTEXT_PTHREAD_ID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_hostname)) {
+       } else if (!strcmp((char *) context_type, config_event_context_hostname)) {
                ret = LTTNG_EVENT_CONTEXT_HOSTNAME;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_ip)) {
+       } else if (!strcmp((char *) context_type, config_event_context_ip)) {
                ret = LTTNG_EVENT_CONTEXT_IP;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_interruptible)) {
+       } else if (!strcmp((char *) context_type, config_event_context_interruptible)) {
                ret = LTTNG_EVENT_CONTEXT_INTERRUPTIBLE;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_preemptible)) {
+       } else if (!strcmp((char *) context_type, config_event_context_preemptible)) {
                ret = LTTNG_EVENT_CONTEXT_PREEMPTIBLE;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_need_reschedule)) {
+       } else if (!strcmp((char *) context_type, config_event_context_need_reschedule)) {
                ret = LTTNG_EVENT_CONTEXT_NEED_RESCHEDULE;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_migratable)) {
+       } else if (!strcmp((char *) context_type, config_event_context_migratable)) {
                ret = LTTNG_EVENT_CONTEXT_MIGRATABLE;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_callstack_user)) {
+       } else if (!strcmp((char *) context_type, config_event_context_callstack_user)) {
                ret = LTTNG_EVENT_CONTEXT_CALLSTACK_USER;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_callstack_kernel)) {
+       } else if (!strcmp((char *) context_type, config_event_context_callstack_kernel)) {
                ret = LTTNG_EVENT_CONTEXT_CALLSTACK_KERNEL;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_cgroup_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_cgroup_ns)) {
                ret = LTTNG_EVENT_CONTEXT_CGROUP_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_ipc_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_ipc_ns)) {
                ret = LTTNG_EVENT_CONTEXT_IPC_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_mnt_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_mnt_ns)) {
                ret = LTTNG_EVENT_CONTEXT_MNT_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_net_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_net_ns)) {
                ret = LTTNG_EVENT_CONTEXT_NET_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_pid_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_pid_ns)) {
                ret = LTTNG_EVENT_CONTEXT_PID_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_time_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_time_ns)) {
                ret = LTTNG_EVENT_CONTEXT_TIME_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_user_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_user_ns)) {
                ret = LTTNG_EVENT_CONTEXT_USER_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_uts_ns)) {
+       } else if (!strcmp((char *) context_type, config_event_context_uts_ns)) {
                ret = LTTNG_EVENT_CONTEXT_UTS_NS;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_uid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_uid)) {
                ret = LTTNG_EVENT_CONTEXT_UID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_euid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_euid)) {
                ret = LTTNG_EVENT_CONTEXT_EUID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_suid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_suid)) {
                ret = LTTNG_EVENT_CONTEXT_SUID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_gid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_gid)) {
                ret = LTTNG_EVENT_CONTEXT_GID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_egid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_egid)) {
                ret = LTTNG_EVENT_CONTEXT_EGID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_sgid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_sgid)) {
                ret = LTTNG_EVENT_CONTEXT_SGID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vuid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vuid)) {
                ret = LTTNG_EVENT_CONTEXT_VUID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_veuid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_veuid)) {
                ret = LTTNG_EVENT_CONTEXT_VEUID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vsuid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vsuid)) {
                ret = LTTNG_EVENT_CONTEXT_VSUID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vgid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vgid)) {
                ret = LTTNG_EVENT_CONTEXT_VGID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vegid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vegid)) {
                ret = LTTNG_EVENT_CONTEXT_VEGID;
-       } else if (!strcmp((char *) context_type,
-               config_event_context_vsgid)) {
+       } else if (!strcmp((char *) context_type, config_event_context_vsgid)) {
                ret = LTTNG_EVENT_CONTEXT_VSGID;
        } else {
                goto error;
@@ -1010,14 +951,12 @@ error:
        return -1;
 }
 
-static
-int init_domain(xmlNodePtr domain_node, struct lttng_domain *domain)
+static int init_domain(xmlNodePtr domain_node, struct lttng_domain *domain)
 {
        int ret;
        xmlNodePtr node;
 
-       for (node = xmlFirstElementChild(domain_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(domain_node); node; node = xmlNextElementSibling(node)) {
                if (!strcmp((const char *) node->name, config_element_type)) {
                        /* domain type */
                        xmlChar *node_content = xmlNodeGetContent(node);
@@ -1034,8 +973,7 @@ int init_domain(xmlNodePtr domain_node, struct lttng_domain *domain)
                        }
 
                        domain->type = (lttng_domain_type) ret;
-               } else if (!strcmp((const char *) node->name,
-                       config_element_buffer_type)) {
+               } else if (!strcmp((const char *) node->name, config_element_buffer_type)) {
                        /* buffer type */
                        xmlChar *node_content = xmlNodeGetContent(node);
                        if (!node_content) {
@@ -1058,14 +996,12 @@ end:
        return ret;
 }
 
-static
-int get_net_output_uris(xmlNodePtr net_output_node, char **control_uri,
-       char **data_uri)
+static int get_net_output_uris(xmlNodePtr net_output_node, char **control_uri, char **data_uri)
 {
        xmlNodePtr node;
 
        for (node = xmlFirstElementChild(net_output_node); node;
-               node = xmlNextElementSibling(node)) {
+            node = xmlNextElementSibling(node)) {
                if (!strcmp((const char *) node->name, config_element_control_uri)) {
                        /* control_uri */
                        *control_uri = (char *) xmlNodeGetContent(node);
@@ -1084,9 +1020,7 @@ int get_net_output_uris(xmlNodePtr net_output_node, char **control_uri,
        return *control_uri || *data_uri ? 0 : -LTTNG_ERR_LOAD_INVALID_CONFIG;
 }
 
-static
-int process_consumer_output(xmlNodePtr consumer_output_node,
-       struct consumer_output *output)
+static int process_consumer_output(xmlNodePtr consumer_output_node, struct consumer_output *output)
 {
        int ret;
        xmlNodePtr node;
@@ -1094,7 +1028,7 @@ int process_consumer_output(xmlNodePtr consumer_output_node,
        LTTNG_ASSERT(output);
 
        for (node = xmlFirstElementChild(consumer_output_node); node;
-                       node = xmlNextElementSibling(node)) {
+            node = xmlNextElementSibling(node)) {
                if (!strcmp((const char *) node->name, config_element_enabled)) {
                        xmlChar *enabled_str = xmlNodeGetContent(node);
 
@@ -1119,8 +1053,7 @@ int process_consumer_output(xmlNodePtr consumer_output_node,
                                goto end;
                        }
 
-                       if (!strcmp((const char *) output_type_node->name,
-                                       config_element_path)) {
+                       if (!strcmp((const char *) output_type_node->name, config_element_path)) {
                                /* path */
                                output->path = (char *) xmlNodeGetContent(output_type_node);
                                if (!output->path) {
@@ -1129,8 +1062,8 @@ int process_consumer_output(xmlNodePtr consumer_output_node,
                                }
                        } else {
                                /* net_output */
-                               ret = get_net_output_uris(output_type_node,
-                                               &output->control_uri, &output->data_uri);
+                               ret = get_net_output_uris(
+                                       output_type_node, &output->control_uri, &output->data_uri);
                                if (ret) {
                                        goto end;
                                }
@@ -1149,82 +1082,60 @@ end:
        return ret;
 }
 
-static
-int create_session_net_output(const char *name, const char *control_uri,
-               const char *data_uri)
+static int create_snapshot_session(const char *session_name,
+                                  xmlNodePtr output_node,
+                                  const struct config_load_session_override_attr *overrides)
 {
        int ret;
-       struct lttng_handle *handle;
-       const char *uri = NULL;
-
-       LTTNG_ASSERT(name);
-
-       handle = lttng_create_handle(name, NULL);
-       if (!handle) {
-               ret = -LTTNG_ERR_NOMEM;
-               goto end;
-       }
-
-       if (!control_uri || !data_uri) {
-               uri = control_uri ? control_uri : data_uri;
-               control_uri = uri;
-               data_uri = uri;
-       }
-
-       ret = lttng_set_consumer_url(handle, control_uri, data_uri);
-       lttng_destroy_handle(handle);
-end:
-       return ret;
-}
-
-static
-int create_snapshot_session(const char *session_name, xmlNodePtr output_node,
-               const struct config_load_session_override_attr *overrides)
-{
-       int ret;
-       xmlNodePtr node = NULL;
+       enum lttng_error_code ret_code;
+       xmlNodePtr node = nullptr;
        xmlNodePtr snapshot_output_list_node;
        xmlNodePtr snapshot_output_node;
+       struct lttng_session_descriptor *session_descriptor = nullptr;
 
        LTTNG_ASSERT(session_name);
+       LTTNG_ASSERT(output_node);
 
-       ret = lttng_create_session_snapshot(session_name, NULL);
-       if (ret) {
+       /*
+        * Use a descriptor without output since consumer output size is not
+        * exposed by the session descriptor api.
+        */
+       session_descriptor = lttng_session_descriptor_snapshot_create(session_name);
+       if (session_descriptor == nullptr) {
+               ret = -LTTNG_ERR_NOMEM;
                goto end;
        }
 
-       if (!output_node) {
+       ret_code = lttng_create_session_ext(session_descriptor);
+       if (ret_code != LTTNG_OK) {
+               ret = -ret_code;
                goto end;
        }
 
        snapshot_output_list_node = xmlFirstElementChild(output_node);
 
        /* Parse and create snapshot outputs */
-
-       for (snapshot_output_node =
-                       xmlFirstElementChild(snapshot_output_list_node);
-                       snapshot_output_node; snapshot_output_node =
-                       xmlNextElementSibling(snapshot_output_node)) {
-               char *name = NULL;
+       for (snapshot_output_node = xmlFirstElementChild(snapshot_output_list_node);
+            snapshot_output_node;
+            snapshot_output_node = xmlNextElementSibling(snapshot_output_node)) {
+               char *name = nullptr;
                uint64_t max_size = UINT64_MAX;
                struct consumer_output output = {};
-               struct lttng_snapshot_output *snapshot_output = NULL;
-               const char *control_uri = NULL;
-               const char *data_uri = NULL;
-               const char *path = NULL;
+               struct lttng_snapshot_output *snapshot_output = nullptr;
+               const char *control_uri = nullptr;
+               const char *data_uri = nullptr;
+               const char *path = nullptr;
 
                for (node = xmlFirstElementChild(snapshot_output_node); node;
-                               node = xmlNextElementSibling(node)) {
-                       if (!strcmp((const char *) node->name,
-                               config_element_name)) {
+                    node = xmlNextElementSibling(node)) {
+                       if (!strcmp((const char *) node->name, config_element_name)) {
                                /* name */
                                name = (char *) xmlNodeGetContent(node);
                                if (!name) {
                                        ret = -LTTNG_ERR_NOMEM;
                                        goto error_snapshot_output;
                                }
-                       } else if (!strcmp((const char *) node->name,
-                               config_element_max_size)) {
+                       } else if (!strcmp((const char *) node->name, config_element_max_size)) {
                                xmlChar *content = xmlNodeGetContent(node);
 
                                /* max_size */
@@ -1255,18 +1166,18 @@ int create_snapshot_session(const char *session_name, xmlNodePtr output_node,
                        if (overrides->path_url) {
                                path = overrides->path_url;
                                /* Control/data_uri are null */
-                               control_uri = NULL;
-                               data_uri = NULL;
+                               control_uri = nullptr;
+                               data_uri = nullptr;
                        } else {
                                if (overrides->ctrl_url) {
                                        control_uri = overrides->ctrl_url;
                                        /* path is null */
-                                       path = NULL;
+                                       path = nullptr;
                                }
                                if (overrides->data_url) {
                                        data_uri = overrides->data_url;
                                        /* path is null */
-                                       path = NULL;
+                                       path = nullptr;
                                }
                        }
                }
@@ -1288,23 +1199,21 @@ int create_snapshot_session(const char *session_name, xmlNodePtr output_node,
                }
 
                if (path) {
-                       ret = lttng_snapshot_output_set_ctrl_url(path,
-                                       snapshot_output);
+                       ret = lttng_snapshot_output_set_ctrl_url(path, snapshot_output);
                        if (ret) {
                                goto error_snapshot_output;
                        }
                } else {
                        if (control_uri) {
                                ret = lttng_snapshot_output_set_ctrl_url(control_uri,
-                                               snapshot_output);
+                                                                        snapshot_output);
                                if (ret) {
                                        goto error_snapshot_output;
                                }
                        }
 
                        if (data_uri) {
-                               ret = lttng_snapshot_output_set_data_url(data_uri,
-                                               snapshot_output);
+                               ret = lttng_snapshot_output_set_data_url(data_uri, snapshot_output);
                                if (ret) {
                                        goto error_snapshot_output;
                                }
@@ -1312,7 +1221,7 @@ int create_snapshot_session(const char *session_name, xmlNodePtr output_node,
                }
 
                ret = lttng_snapshot_add_output(session_name, snapshot_output);
-error_snapshot_output:
+       error_snapshot_output:
                free(name);
                free(output.path);
                free(output.control_uri);
@@ -1323,21 +1232,23 @@ error_snapshot_output:
                }
        }
 end:
+       lttng_session_descriptor_destroy(session_descriptor);
        return ret;
 }
 
-static
-int create_session(const char *name,
-       xmlNodePtr output_node,
-       uint64_t live_timer_interval,
-       const struct config_load_session_override_attr *overrides)
+static int create_session(const char *name,
+                         xmlNodePtr output_node,
+                         uint64_t live_timer_interval,
+                         const struct config_load_session_override_attr *overrides)
 {
-       int ret;
+       int ret = 0;
+       enum lttng_error_code ret_code;
        struct consumer_output output = {};
        xmlNodePtr consumer_output_node;
-       const char *control_uri = NULL;
-       const char *data_uri = NULL;
-       const char *path = NULL;
+       const char *control_uri = nullptr;
+       const char *data_uri = nullptr;
+       const char *path = nullptr;
+       struct lttng_session_descriptor *session_descriptor = nullptr;
 
        LTTNG_ASSERT(name);
 
@@ -1349,9 +1260,9 @@ int create_session(const char *name,
                }
 
                if (strcmp((const char *) consumer_output_node->name,
-                       config_element_consumer_output)) {
+                          config_element_consumer_output) != 0) {
                        WARN("Invalid output type, expected %s node",
-                               config_element_consumer_output);
+                            config_element_consumer_output);
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
@@ -1371,23 +1282,22 @@ int create_session(const char *name,
                if (overrides->path_url) {
                        path = overrides->path_url;
                        /* control/data_uri are null */;
-                       control_uri = NULL;
-                       data_uri = NULL;
+                       control_uri = nullptr;
+                       data_uri = nullptr;
                } else {
                        if (overrides->ctrl_url) {
                                control_uri = overrides->ctrl_url;
                                /* path is null */
-                               path = NULL;
+                               path = nullptr;
                        }
                        if (overrides->data_url) {
                                data_uri = overrides->data_url;
                                /* path is null */
-                               path = NULL;
+                               path = nullptr;
                        }
                }
        }
 
-
        if (live_timer_interval != UINT64_MAX && !control_uri && !data_uri) {
                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                goto end;
@@ -1401,42 +1311,46 @@ int create_session(const char *name,
                         * with a live timer the data and control URIs are provided. So,
                         * NULL is passed here and will be set right after.
                         */
-                       ret = lttng_create_session_live(name, NULL, live_timer_interval);
+                       session_descriptor = lttng_session_descriptor_live_network_create(
+                               name, control_uri, data_uri, live_timer_interval);
                } else {
-                       ret = lttng_create_session(name, NULL);
-               }
-               if (ret) {
-                       goto end;
-               }
-
-               ret = create_session_net_output(name, control_uri, data_uri);
-               if (ret) {
-                       goto end;
+                       session_descriptor = lttng_session_descriptor_network_create(
+                               name, control_uri, data_uri);
                }
 
+       } else if (path != nullptr) {
+               session_descriptor = lttng_session_descriptor_local_create(name, path);
        } else {
-               /* either local output or no output */
-               ret = lttng_create_session(name, path);
-               if (ret) {
-                       goto end;
-               }
+               /* No output */
+               session_descriptor = lttng_session_descriptor_create(name);
+       }
+
+       if (session_descriptor == nullptr) {
+               ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
+               goto end;
+       }
+
+       ret_code = lttng_create_session_ext(session_descriptor);
+       if (ret_code != LTTNG_OK) {
+               ret = -ret_code;
+               goto end;
        }
+
 end:
        free(output.path);
        free(output.control_uri);
        free(output.data_uri);
+       lttng_session_descriptor_destroy(session_descriptor);
        return ret;
 }
 
-static
-struct lttng_userspace_probe_location *
-process_userspace_probe_function_attribute_node(
-               xmlNodePtr attribute_node)
+static struct lttng_userspace_probe_location *
+process_userspace_probe_function_attribute_node(xmlNodePtr attribute_node)
 {
        xmlNodePtr function_attribute_node;
-       char *function_name = NULL, *binary_path = NULL;
-       struct lttng_userspace_probe_location *location = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
+       char *function_name = nullptr, *binary_path = nullptr;
+       struct lttng_userspace_probe_location *location = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
 
        /*
         * Process userspace probe location function attributes. The order of
@@ -1444,30 +1358,27 @@ process_userspace_probe_function_attribute_node(
         * and check at the end if everything we need for this location type is
         * there.
         */
-       for (function_attribute_node =
-                       xmlFirstElementChild(attribute_node);
-                       function_attribute_node;
-                       function_attribute_node = xmlNextElementSibling(
-                               function_attribute_node)) {
+       for (function_attribute_node = xmlFirstElementChild(attribute_node);
+            function_attribute_node;
+            function_attribute_node = xmlNextElementSibling(function_attribute_node)) {
                /* Handle function name, binary path and lookup method. */
                if (!strcmp((const char *) function_attribute_node->name,
-                                       config_element_userspace_probe_function_location_function_name)) {
+                           config_element_userspace_probe_function_location_function_name)) {
                        function_name = (char *) xmlNodeGetContent(function_attribute_node);
                        if (!function_name) {
                                goto error;
                        }
                } else if (!strcmp((const char *) function_attribute_node->name,
-                                       config_element_userspace_probe_location_binary_path)) {
+                                  config_element_userspace_probe_location_binary_path)) {
                        binary_path = (char *) xmlNodeGetContent(function_attribute_node);
                        if (!binary_path) {
                                goto error;
                        }
                } else if (!strcmp((const char *) function_attribute_node->name,
-                                       config_element_userspace_probe_lookup)) {
+                                  config_element_userspace_probe_lookup)) {
                        char *lookup_method_name;
 
-                       lookup_method_name = (char *) xmlNodeGetContent(
-                                       function_attribute_node);
+                       lookup_method_name = (char *) xmlNodeGetContent(function_attribute_node);
                        if (!lookup_method_name) {
                                goto error;
                        }
@@ -1476,9 +1387,12 @@ process_userspace_probe_function_attribute_node(
                         * function_default lookup method defaults to
                         * function_elf lookup method at the moment.
                         */
-                       if (!strcmp(lookup_method_name, config_element_userspace_probe_lookup_function_elf)
-                                       || !strcmp(lookup_method_name, config_element_userspace_probe_lookup_function_default)) {
-                               lookup_method = lttng_userspace_probe_location_lookup_method_function_elf_create();
+                       if (!strcmp(lookup_method_name,
+                                   config_element_userspace_probe_lookup_function_elf) ||
+                           !strcmp(lookup_method_name,
+                                   config_element_userspace_probe_lookup_function_default)) {
+                               lookup_method =
+                                       lttng_userspace_probe_location_lookup_method_function_elf_create();
                                if (!lookup_method) {
                                        PERROR("Error creating function default/ELF lookup method");
                                }
@@ -1497,11 +1411,9 @@ process_userspace_probe_function_attribute_node(
                /* Check if all the necessary fields were found. */
                if (binary_path && function_name && lookup_method) {
                        /* Ownership of lookup_method is transferred. */
-                       location =
-                               lttng_userspace_probe_location_function_create(
-                                               binary_path, function_name,
-                                               lookup_method);
-                       lookup_method = NULL;
+                       location = lttng_userspace_probe_location_function_create(
+                               binary_path, function_name, lookup_method);
+                       lookup_method = nullptr;
                        goto error;
                }
        }
@@ -1512,15 +1424,13 @@ error:
        return location;
 }
 
-static
-struct lttng_userspace_probe_location *
-process_userspace_probe_tracepoint_attribute_node(
-               xmlNodePtr attribute_node)
+static struct lttng_userspace_probe_location *
+process_userspace_probe_tracepoint_attribute_node(xmlNodePtr attribute_node)
 {
        xmlNodePtr tracepoint_attribute_node;
-       char *probe_name = NULL, *provider_name = NULL, *binary_path = NULL;
-       struct lttng_userspace_probe_location *location = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
+       char *probe_name = nullptr, *provider_name = nullptr, *binary_path = nullptr;
+       struct lttng_userspace_probe_location *location = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
 
        /*
         * Process userspace probe location tracepoint attributes. The order of
@@ -1528,40 +1438,38 @@ process_userspace_probe_tracepoint_attribute_node(
         * and check at the end if everything we need for this location type is
         * there.
         */
-       for (tracepoint_attribute_node =
-               xmlFirstElementChild(attribute_node); tracepoint_attribute_node;
-               tracepoint_attribute_node = xmlNextElementSibling(
-                               tracepoint_attribute_node)) {
+       for (tracepoint_attribute_node = xmlFirstElementChild(attribute_node);
+            tracepoint_attribute_node;
+            tracepoint_attribute_node = xmlNextElementSibling(tracepoint_attribute_node)) {
                if (!strcmp((const char *) tracepoint_attribute_node->name,
-                                       config_element_userspace_probe_tracepoint_location_probe_name)) {
+                           config_element_userspace_probe_tracepoint_location_probe_name)) {
                        probe_name = (char *) xmlNodeGetContent(tracepoint_attribute_node);
                        if (!probe_name) {
                                goto error;
                        }
                } else if (!strcmp((const char *) tracepoint_attribute_node->name,
-                                       config_element_userspace_probe_tracepoint_location_provider_name)) {
+                                  config_element_userspace_probe_tracepoint_location_provider_name)) {
                        provider_name = (char *) xmlNodeGetContent(tracepoint_attribute_node);
                        if (!provider_name) {
                                goto error;
                        }
                } else if (!strcmp((const char *) tracepoint_attribute_node->name,
-                                       config_element_userspace_probe_location_binary_path)) {
+                                  config_element_userspace_probe_location_binary_path)) {
                        binary_path = (char *) xmlNodeGetContent(tracepoint_attribute_node);
                        if (!binary_path) {
                                goto error;
                        }
                } else if (!strcmp((const char *) tracepoint_attribute_node->name,
-                                       config_element_userspace_probe_lookup)) {
+                                  config_element_userspace_probe_lookup)) {
                        char *lookup_method_name;
 
-                       lookup_method_name = (char *) xmlNodeGetContent(
-                                       tracepoint_attribute_node);
+                       lookup_method_name = (char *) xmlNodeGetContent(tracepoint_attribute_node);
                        if (!lookup_method_name) {
                                goto error;
                        }
 
                        if (!strcmp(lookup_method_name,
-                                               config_element_userspace_probe_lookup_tracepoint_sdt)) {
+                                   config_element_userspace_probe_lookup_tracepoint_sdt)) {
                                lookup_method =
                                        lttng_userspace_probe_location_lookup_method_tracepoint_sdt_create();
                                if (!lookup_method) {
@@ -1583,11 +1491,9 @@ process_userspace_probe_tracepoint_attribute_node(
                /* Check if all the necessary fields were found. */
                if (binary_path && provider_name && probe_name && lookup_method) {
                        /* Ownership of lookup_method is transferred. */
-                       location =
-                               lttng_userspace_probe_location_tracepoint_create(
-                                               binary_path, provider_name,
-                                               probe_name, lookup_method);
-                       lookup_method = NULL;
+                       location = lttng_userspace_probe_location_tracepoint_create(
+                               binary_path, provider_name, probe_name, lookup_method);
+                       lookup_method = nullptr;
                        goto error;
                }
        }
@@ -1599,17 +1505,15 @@ error:
        return location;
 }
 
-static
-int process_probe_attribute_node(xmlNodePtr probe_attribute_node,
-       struct lttng_event_probe_attr *attr)
+static int process_probe_attribute_node(xmlNodePtr probe_attribute_node,
+                                       struct lttng_event_probe_attr *attr)
 {
        int ret;
 
        LTTNG_ASSERT(probe_attribute_node);
        LTTNG_ASSERT(attr);
 
-       if (!strcmp((const char *) probe_attribute_node->name,
-               config_element_address)) {
+       if (!strcmp((const char *) probe_attribute_node->name, config_element_address)) {
                xmlChar *content;
                uint64_t addr = 0;
 
@@ -1628,8 +1532,7 @@ int process_probe_attribute_node(xmlNodePtr probe_attribute_node,
                }
 
                attr->addr = addr;
-       } else if (!strcmp((const char *) probe_attribute_node->name,
-               config_element_offset)) {
+       } else if (!strcmp((const char *) probe_attribute_node->name, config_element_offset)) {
                xmlChar *content;
                uint64_t offset = 0;
 
@@ -1648,8 +1551,7 @@ int process_probe_attribute_node(xmlNodePtr probe_attribute_node,
                }
 
                attr->offset = offset;
-       } else if (!strcmp((const char *) probe_attribute_node->name,
-               config_element_symbol_name)) {
+       } else if (!strcmp((const char *) probe_attribute_node->name, config_element_symbol_name)) {
                xmlChar *content;
 
                /* symbol_name */
@@ -1659,14 +1561,13 @@ int process_probe_attribute_node(xmlNodePtr probe_attribute_node,
                        goto end;
                }
 
-               ret = lttng_strncpy(attr->symbol_name,
-                               (const char *) content,
-                               LTTNG_SYMBOL_NAME_LEN);
+               ret = lttng_strncpy(
+                       attr->symbol_name, (const char *) content, LTTNG_SYMBOL_NAME_LEN);
                if (ret == -1) {
-                       ERR("symbol name \"%s\"'s length (%zu) exceeds the maximal permitted length (%d) in session configuration",
-                                       (const char *) content,
-                                       strlen((const char *) content),
-                                       LTTNG_SYMBOL_NAME_LEN);
+                       ERR("symbol name \"%s\"'s length (%zu) exceeds the maximal permitted length (%d) in session configuration",
+                           (const char *) content,
+                           strlen((const char *) content),
+                           LTTNG_SYMBOL_NAME_LEN);
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        free(content);
                        goto end;
@@ -1678,16 +1579,17 @@ end:
        return ret;
 }
 
-static
-int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
-       const char *channel_name, const enum process_event_node_phase phase)
+static int process_event_node(xmlNodePtr event_node,
+                             struct lttng_handle *handle,
+                             const char *channel_name,
+                             const enum process_event_node_phase phase)
 {
        int ret = 0, i;
        xmlNodePtr node;
        struct lttng_event *event;
-       char **exclusions = NULL;
+       char **exclusions = nullptr;
        unsigned long exclusion_count = 0;
-       char *filter_expression = NULL;
+       char *filter_expression = nullptr;
 
        LTTNG_ASSERT(event_node);
        LTTNG_ASSERT(handle);
@@ -1700,8 +1602,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
        }
 
        /* Initialize default log level which varies by domain */
-       switch (handle->domain.type)
-       {
+       switch (handle->domain.type) {
        case LTTNG_DOMAIN_JUL:
                event->loglevel = LTTNG_LOGLEVEL_JUL_ALL;
                break;
@@ -1719,8 +1620,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                abort();
        }
 
-       for (node = xmlFirstElementChild(event_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(event_node); node; node = xmlNextElementSibling(node)) {
                if (!strcmp((const char *) node->name, config_element_name)) {
                        xmlChar *content;
 
@@ -1731,21 +1631,19 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                                goto end;
                        }
 
-                       ret = lttng_strncpy(event->name,
-                                       (const char *) content,
-                                       LTTNG_SYMBOL_NAME_LEN);
+                       ret = lttng_strncpy(
+                               event->name, (const char *) content, LTTNG_SYMBOL_NAME_LEN);
                        if (ret == -1) {
                                WARN("Event \"%s\"'s name length (%zu) exceeds the maximal permitted length (%d) in session configuration",
-                                               (const char *) content,
-                                               strlen((const char *) content),
-                                               LTTNG_SYMBOL_NAME_LEN);
+                                    (const char *) content,
+                                    strlen((const char *) content),
+                                    LTTNG_SYMBOL_NAME_LEN);
                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                free(content);
                                goto end;
                        }
                        free(content);
-               } else if (!strcmp((const char *) node->name,
-                       config_element_enabled)) {
+               } else if (!strcmp((const char *) node->name, config_element_enabled)) {
                        xmlChar *content = xmlNodeGetContent(node);
 
                        /* enabled */
@@ -1760,8 +1658,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                goto end;
                        }
-               } else if (!strcmp((const char *) node->name,
-                       config_element_type)) {
+               } else if (!strcmp((const char *) node->name, config_element_type)) {
                        xmlChar *content = xmlNodeGetContent(node);
 
                        /* type */
@@ -1778,8 +1675,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        event->type = (lttng_event_type) ret;
-               } else if (!strcmp((const char *) node->name,
-                       config_element_loglevel_type)) {
+               } else if (!strcmp((const char *) node->name, config_element_loglevel_type)) {
                        xmlChar *content = xmlNodeGetContent(node);
 
                        /* loglevel_type */
@@ -1796,8 +1692,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        event->loglevel_type = (lttng_loglevel_type) ret;
-               } else if (!strcmp((const char *) node->name,
-                       config_element_loglevel)) {
+               } else if (!strcmp((const char *) node->name, config_element_loglevel)) {
                        xmlChar *content;
                        int64_t loglevel = 0;
 
@@ -1822,10 +1717,8 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        event->loglevel = loglevel;
-               } else if (!strcmp((const char *) node->name,
-                       config_element_filter)) {
-                       xmlChar *content =
-                               xmlNodeGetContent(node);
+               } else if (!strcmp((const char *) node->name, config_element_filter)) {
+                       xmlChar *content = xmlNodeGetContent(node);
 
                        /* filter */
                        if (!content) {
@@ -1840,8 +1733,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                                ret = -LTTNG_ERR_NOMEM;
                                goto end;
                        }
-               } else if (!strcmp((const char *) node->name,
-                       config_element_exclusions)) {
+               } else if (!strcmp((const char *) node->name, config_element_exclusions)) {
                        xmlNodePtr exclusion_node;
                        int exclusion_index = 0;
 
@@ -1868,9 +1760,8 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        for (exclusion_node = xmlFirstElementChild(node); exclusion_node;
-                                       exclusion_node = xmlNextElementSibling(exclusion_node)) {
-                               xmlChar *content =
-                                       xmlNodeGetContent(exclusion_node);
+                            exclusion_node = xmlNextElementSibling(exclusion_node)) {
+                               xmlChar *content = xmlNodeGetContent(exclusion_node);
 
                                if (!content) {
                                        ret = -LTTNG_ERR_NOMEM;
@@ -1887,8 +1778,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        event->exclusion = 1;
-               } else if (!strcmp((const char *) node->name,
-                       config_element_attributes)) {
+               } else if (!strcmp((const char *) node->name, config_element_attributes)) {
                        xmlNodePtr attribute_node = xmlFirstElementChild(node);
 
                        /* attributes */
@@ -1898,23 +1788,22 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                        }
 
                        if (!strcmp((const char *) attribute_node->name,
-                                               config_element_probe_attributes)) {
+                                   config_element_probe_attributes)) {
                                xmlNodePtr probe_attribute_node;
 
                                /* probe_attributes */
-                               for (probe_attribute_node =
-                                       xmlFirstElementChild(attribute_node); probe_attribute_node;
-                                       probe_attribute_node = xmlNextElementSibling(
-                                                       probe_attribute_node)) {
-
+                               for (probe_attribute_node = xmlFirstElementChild(attribute_node);
+                                    probe_attribute_node;
+                                    probe_attribute_node =
+                                            xmlNextElementSibling(probe_attribute_node)) {
                                        ret = process_probe_attribute_node(probe_attribute_node,
-                                                       &event->attr.probe);
+                                                                          &event->attr.probe);
                                        if (ret) {
                                                goto end;
                                        }
                                }
                        } else if (!strcmp((const char *) attribute_node->name,
-                                               config_element_function_attributes)) {
+                                          config_element_function_attributes)) {
                                size_t sym_len;
                                xmlChar *content;
                                xmlNodePtr symbol_node = xmlFirstElementChild(attribute_node);
@@ -1935,8 +1824,7 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                                }
 
                                ret = lttng_strncpy(
-                                               event->attr.ftrace.symbol_name,
-                                               (char *) content, sym_len);
+                                       event->attr.ftrace.symbol_name, (char *) content, sym_len);
                                if (ret == -1) {
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        free(content);
@@ -1944,43 +1832,39 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
                                }
                                free(content);
                        } else if (!strcmp((const char *) attribute_node->name,
-                                               config_element_userspace_probe_tracepoint_attributes)) {
+                                          config_element_userspace_probe_tracepoint_attributes)) {
                                struct lttng_userspace_probe_location *location;
 
-                               location = process_userspace_probe_tracepoint_attribute_node(attribute_node);
+                               location = process_userspace_probe_tracepoint_attribute_node(
+                                       attribute_node);
                                if (!location) {
                                        WARN("Error processing userspace probe tracepoint attribute");
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        goto end;
                                }
-                               ret = lttng_event_set_userspace_probe_location(
-                                               event, location);
+                               ret = lttng_event_set_userspace_probe_location(event, location);
                                if (ret) {
                                        WARN("Error setting userspace probe location field");
-                                       lttng_userspace_probe_location_destroy(
-                                                       location);
+                                       lttng_userspace_probe_location_destroy(location);
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        goto end;
                                }
                        } else if (!strcmp((const char *) attribute_node->name,
-                                               config_element_userspace_probe_function_attributes)) {
+                                          config_element_userspace_probe_function_attributes)) {
                                struct lttng_userspace_probe_location *location;
 
-                               location =
-                                       process_userspace_probe_function_attribute_node(
-                                                       attribute_node);
+                               location = process_userspace_probe_function_attribute_node(
+                                       attribute_node);
                                if (!location) {
                                        WARN("Error processing userspace probe function attribute");
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        goto end;
                                }
 
-                               ret = lttng_event_set_userspace_probe_location(
-                                               event, location);
+                               ret = lttng_event_set_userspace_probe_location(event, location);
                                if (ret) {
                                        WARN("Error setting userspace probe location field");
-                                       lttng_userspace_probe_location_destroy(
-                                                       location);
+                                       lttng_userspace_probe_location_destroy(location);
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        goto end;
                                }
@@ -1993,8 +1877,8 @@ int process_event_node(xmlNodePtr event_node, struct lttng_handle *handle,
        }
 
        if ((event->enabled && phase == ENABLE) || phase == CREATION) {
-               ret = lttng_enable_event_with_exclusions(handle, event, channel_name,
-                               filter_expression, exclusion_count, exclusions);
+               ret = lttng_enable_event_with_exclusions(
+                       handle, event, channel_name, filter_expression, exclusion_count, exclusions);
                if (ret < 0) {
                        WARN("Enabling event (name:%s) on load failed.", event->name);
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
@@ -2013,9 +1897,8 @@ end:
        return ret;
 }
 
-static
-int process_events_node(xmlNodePtr events_node, struct lttng_handle *handle,
-       const char *channel_name)
+static int
+process_events_node(xmlNodePtr events_node, struct lttng_handle *handle, const char *channel_name)
 {
        int ret = 0;
        struct lttng_event event;
@@ -2025,8 +1908,7 @@ int process_events_node(xmlNodePtr events_node, struct lttng_handle *handle,
        LTTNG_ASSERT(handle);
        LTTNG_ASSERT(channel_name);
 
-       for (node = xmlFirstElementChild(events_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(events_node); node; node = xmlNextElementSibling(node)) {
                ret = process_event_node(node, handle, channel_name, CREATION);
                if (ret) {
                        goto end;
@@ -2041,13 +1923,12 @@ int process_events_node(xmlNodePtr events_node, struct lttng_handle *handle,
        memset(&event, 0, sizeof(event));
        event.loglevel = -1;
        event.type = LTTNG_EVENT_ALL;
-       ret = lttng_disable_event_ext(handle, &event, channel_name, NULL);
+       ret = lttng_disable_event_ext(handle, &event, channel_name, nullptr);
        if (ret) {
                goto end;
        }
 
-       for (node = xmlFirstElementChild(events_node); node;
-                       node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(events_node); node; node = xmlNextElementSibling(node)) {
                ret = process_event_node(node, handle, channel_name, ENABLE);
                if (ret) {
                        goto end;
@@ -2058,10 +1939,10 @@ end:
        return ret;
 }
 
-static
-int process_channel_attr_node(xmlNodePtr attr_node,
-               struct lttng_channel *channel, xmlNodePtr *contexts_node,
-               xmlNodePtr *events_node)
+static int process_channel_attr_node(xmlNodePtr attr_node,
+                                    struct lttng_channel *channel,
+                                    xmlNodePtr *contexts_node,
+                                    xmlNodePtr *events_node)
 {
        int ret;
 
@@ -2080,21 +1961,18 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               ret = lttng_strncpy(channel->name,
-                               (const char *) content,
-                               LTTNG_SYMBOL_NAME_LEN);
+               ret = lttng_strncpy(channel->name, (const char *) content, LTTNG_SYMBOL_NAME_LEN);
                if (ret == -1) {
                        WARN("Channel \"%s\"'s name length (%zu) exceeds the maximal permitted length (%d) in session configuration",
-                                       (const char *) content,
-                                       strlen((const char *) content),
-                                       LTTNG_SYMBOL_NAME_LEN);
+                            (const char *) content,
+                            strlen((const char *) content),
+                            LTTNG_SYMBOL_NAME_LEN);
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        free(content);
                        goto end;
                }
                free(content);
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_enabled)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_enabled)) {
                xmlChar *content;
                int enabled;
 
@@ -2113,8 +1991,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                }
 
                channel->enabled = enabled;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_overwrite_mode)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_overwrite_mode)) {
                xmlChar *content;
 
                /* overwrite_mode */
@@ -2132,8 +2009,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                }
 
                channel->attr.overwrite = ret;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_subbuf_size)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_subbuf_size)) {
                xmlChar *content;
 
                /* subbuffer_size */
@@ -2149,8 +2025,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_num_subbuf)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_num_subbuf)) {
                xmlChar *content;
 
                /* subbuffer_count */
@@ -2166,8 +2041,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_switch_timer_interval)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_switch_timer_interval)) {
                xmlChar *content;
                uint64_t switch_timer_interval = 0;
 
@@ -2191,10 +2065,8 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               channel->attr.switch_timer_interval =
-                       switch_timer_interval;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_read_timer_interval)) {
+               channel->attr.switch_timer_interval = switch_timer_interval;
+       } else if (!strcmp((const char *) attr_node->name, config_element_read_timer_interval)) {
                xmlChar *content;
                uint64_t read_timer_interval = 0;
 
@@ -2218,10 +2090,8 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               channel->attr.read_timer_interval =
-                       read_timer_interval;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_output_type)) {
+               channel->attr.read_timer_interval = read_timer_interval;
+       } else if (!strcmp((const char *) attr_node->name, config_element_output_type)) {
                xmlChar *content;
 
                /* output_type */
@@ -2239,8 +2109,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                }
 
                channel->attr.output = (lttng_event_output) ret;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_tracefile_size)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_tracefile_size)) {
                xmlChar *content;
 
                /* tracefile_size */
@@ -2256,8 +2125,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_tracefile_count)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_tracefile_count)) {
                xmlChar *content;
 
                /* tracefile_count */
@@ -2273,8 +2141,7 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_live_timer_interval)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_live_timer_interval)) {
                xmlChar *content;
                uint64_t live_timer_interval = 0;
 
@@ -2298,10 +2165,8 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               channel->attr.live_timer_interval =
-                       live_timer_interval;
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_monitor_timer_interval)) {
+               channel->attr.live_timer_interval = live_timer_interval;
+       } else if (!strcmp((const char *) attr_node->name, config_element_monitor_timer_interval)) {
                xmlChar *content;
                uint64_t monitor_timer_interval = 0;
 
@@ -2319,14 +2184,12 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               ret = lttng_channel_set_monitor_timer_interval(channel,
-                       monitor_timer_interval);
+               ret = lttng_channel_set_monitor_timer_interval(channel, monitor_timer_interval);
                if (ret) {
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_blocking_timeout)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_blocking_timeout)) {
                xmlChar *content;
                int64_t blocking_timeout = 0;
 
@@ -2344,14 +2207,12 @@ int process_channel_attr_node(xmlNodePtr attr_node,
                        goto end;
                }
 
-               ret = lttng_channel_set_blocking_timeout(channel,
-                       blocking_timeout);
+               ret = lttng_channel_set_blocking_timeout(channel, blocking_timeout);
                if (ret) {
                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                        goto end;
                }
-       } else if (!strcmp((const char *) attr_node->name,
-                       config_element_events)) {
+       } else if (!strcmp((const char *) attr_node->name, config_element_events)) {
                /* events */
                *events_node = attr_node;
        } else {
@@ -2363,9 +2224,8 @@ end:
        return ret;
 }
 
-static
-int process_context_node(xmlNodePtr context_node,
-       struct lttng_handle *handle, const char *channel_name)
+static int
+process_context_node(xmlNodePtr context_node, struct lttng_handle *handle, const char *channel_name)
 {
        int ret;
        struct lttng_event_context context;
@@ -2381,8 +2241,7 @@ int process_context_node(xmlNodePtr context_node,
 
        memset(&context, 0, sizeof(context));
 
-       if (!strcmp((const char *) context_child_node->name,
-               config_element_type)) {
+       if (!strcmp((const char *) context_child_node->name, config_element_type)) {
                /* type */
                xmlChar *content = xmlNodeGetContent(context_child_node);
 
@@ -2399,19 +2258,16 @@ int process_context_node(xmlNodePtr context_node,
                }
 
                context.ctx = (lttng_event_context_type) ret;
-       } else if (!strcmp((const char *) context_child_node->name,
-               config_element_context_perf)) {
+       } else if (!strcmp((const char *) context_child_node->name, config_element_context_perf)) {
                /* perf */
                xmlNodePtr perf_attr_node;
 
                context.ctx = handle->domain.type == LTTNG_DOMAIN_KERNEL ?
                        LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER :
                        LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER;
-               for (perf_attr_node = xmlFirstElementChild(context_child_node);
-                       perf_attr_node; perf_attr_node =
-                               xmlNextElementSibling(perf_attr_node)) {
-                       if (!strcmp((const char *) perf_attr_node->name,
-                               config_element_type)) {
+               for (perf_attr_node = xmlFirstElementChild(context_child_node); perf_attr_node;
+                    perf_attr_node = xmlNextElementSibling(perf_attr_node)) {
+                       if (!strcmp((const char *) perf_attr_node->name, config_element_type)) {
                                xmlChar *content;
                                uint64_t type = 0;
 
@@ -2437,7 +2293,7 @@ int process_context_node(xmlNodePtr context_node,
 
                                context.u.perf_counter.type = type;
                        } else if (!strcmp((const char *) perf_attr_node->name,
-                               config_element_config)) {
+                                          config_element_config)) {
                                xmlChar *content;
                                uint64_t config = 0;
 
@@ -2457,7 +2313,7 @@ int process_context_node(xmlNodePtr context_node,
 
                                context.u.perf_counter.config = config;
                        } else if (!strcmp((const char *) perf_attr_node->name,
-                               config_element_name)) {
+                                          config_element_name)) {
                                xmlChar *content;
 
                                /* name */
@@ -2468,13 +2324,13 @@ int process_context_node(xmlNodePtr context_node,
                                }
 
                                ret = lttng_strncpy(context.u.perf_counter.name,
-                                               (const char *) content,
-                                               LTTNG_SYMBOL_NAME_LEN);
+                                                   (const char *) content,
+                                                   LTTNG_SYMBOL_NAME_LEN);
                                if (ret == -1) {
                                        WARN("Perf counter \"%s\"'s name length (%zu) exceeds the maximal permitted length (%d) in session configuration",
-                                                       (const char *) content,
-                                                       strlen((const char *) content),
-                                                       LTTNG_SYMBOL_NAME_LEN);
+                                            (const char *) content,
+                                            strlen((const char *) content),
+                                            LTTNG_SYMBOL_NAME_LEN);
                                        ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                        free(content);
                                        goto end;
@@ -2482,21 +2338,18 @@ int process_context_node(xmlNodePtr context_node,
                                free(content);
                        }
                }
-       } else if (!strcmp((const char *) context_child_node->name,
-               config_element_context_app)) {
+       } else if (!strcmp((const char *) context_child_node->name, config_element_context_app)) {
                /* application context */
                xmlNodePtr app_ctx_node;
 
                context.ctx = LTTNG_EVENT_CONTEXT_APP_CONTEXT;
-               for (app_ctx_node = xmlFirstElementChild(context_child_node);
-                               app_ctx_node; app_ctx_node =
-                               xmlNextElementSibling(app_ctx_node)) {
+               for (app_ctx_node = xmlFirstElementChild(context_child_node); app_ctx_node;
+                    app_ctx_node = xmlNextElementSibling(app_ctx_node)) {
                        xmlChar *content;
-                       char **target = strcmp(
-                               (const char *) app_ctx_node->name,
-                               config_element_context_app_provider_name) == 0 ?
-                                       &context.u.app_ctx.provider_name :
-                                       &context.u.app_ctx.ctx_name;
+                       char **target = strcmp((const char *) app_ctx_node->name,
+                                              config_element_context_app_provider_name) == 0 ?
+                               &context.u.app_ctx.provider_name :
+                               &context.u.app_ctx.ctx_name;
 
                        content = xmlNodeGetContent(app_ctx_node);
                        if (!content) {
@@ -2512,7 +2365,7 @@ int process_context_node(xmlNodePtr context_node,
                goto end;
        }
 
-       ret = lttng_add_context(handle, &context, NULL, channel_name);
+       ret = lttng_add_context(handle, &context, nullptr, channel_name);
        if (context.ctx == LTTNG_EVENT_CONTEXT_APP_CONTEXT) {
                free(context.u.app_ctx.provider_name);
                free(context.u.app_ctx.ctx_name);
@@ -2521,15 +2374,15 @@ end:
        return ret;
 }
 
-static
-int process_contexts_node(xmlNodePtr contexts_node,
-       struct lttng_handle *handle, const char *channel_name)
+static int process_contexts_node(xmlNodePtr contexts_node,
+                                struct lttng_handle *handle,
+                                const char *channel_name)
 {
        int ret = 0;
        xmlNodePtr context_node;
 
        for (context_node = xmlFirstElementChild(contexts_node); context_node;
-                       context_node = xmlNextElementSibling(context_node)) {
+            context_node = xmlNextElementSibling(context_node)) {
                ret = process_context_node(context_node, handle, channel_name);
                if (ret) {
                        goto end;
@@ -2540,11 +2393,11 @@ end:
 }
 
 static int get_tracker_elements(enum lttng_process_attr process_attr,
-               const char **element_id_tracker,
-               const char **element_value_type,
-               const char **element_value,
-               const char **element_value_alias,
-               const char **element_name)
+                               const char **element_id_tracker,
+                               const char **element_value_type,
+                               const char **element_value,
+                               const char **element_value_alias,
+                               const char **element_name)
 {
        int ret = 0;
 
@@ -2554,41 +2407,41 @@ static int get_tracker_elements(enum lttng_process_attr process_attr,
                *element_value_type = config_element_process_attr_pid_value;
                *element_value = config_element_process_attr_id;
                *element_value_alias = config_element_process_attr_id;
-               *element_name = NULL;
+               *element_name = nullptr;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
                *element_id_tracker = config_element_process_attr_tracker_vpid;
                *element_value_type = config_element_process_attr_vpid_value;
                *element_value = config_element_process_attr_id;
-               *element_value_alias = NULL;
-               *element_name = NULL;
+               *element_value_alias = nullptr;
+               *element_name = nullptr;
                break;
        case LTTNG_PROCESS_ATTR_USER_ID:
                *element_id_tracker = config_element_process_attr_tracker_uid;
                *element_value_type = config_element_process_attr_uid_value;
                *element_value = config_element_process_attr_id;
-               *element_value_alias = NULL;
+               *element_value_alias = nullptr;
                *element_name = config_element_name;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
                *element_id_tracker = config_element_process_attr_tracker_vuid;
                *element_value_type = config_element_process_attr_vuid_value;
                *element_value = config_element_process_attr_id;
-               *element_value_alias = NULL;
+               *element_value_alias = nullptr;
                *element_name = config_element_name;
                break;
        case LTTNG_PROCESS_ATTR_GROUP_ID:
                *element_id_tracker = config_element_process_attr_tracker_gid;
                *element_value_type = config_element_process_attr_gid_value;
                *element_value = config_element_process_attr_id;
-               *element_value_alias = NULL;
+               *element_value_alias = nullptr;
                *element_name = config_element_name;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                *element_id_tracker = config_element_process_attr_tracker_vgid;
                *element_value_type = config_element_process_attr_vgid_value;
                *element_value = config_element_process_attr_id;
-               *element_value_alias = NULL;
+               *element_value_alias = nullptr;
                *element_name = config_element_name;
                break;
        default:
@@ -2597,11 +2450,10 @@ static int get_tracker_elements(enum lttng_process_attr process_attr,
        return ret;
 }
 
-static int process_legacy_pid_tracker_node(
-               xmlNodePtr trackers_node, struct lttng_handle *handle)
+static int process_legacy_pid_tracker_node(xmlNodePtr trackers_node, struct lttng_handle *handle)
 {
        int ret = 0, child_count;
-       xmlNodePtr targets_node = NULL;
+       xmlNodePtr targets_node = nullptr;
        xmlNodePtr node;
        const char *element_id_tracker;
        const char *element_target_id;
@@ -2609,36 +2461,34 @@ static int process_legacy_pid_tracker_node(
        const char *element_id_alias;
        const char *element_name;
        enum lttng_error_code tracker_handle_ret_code;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
        enum lttng_process_attr_tracker_handle_status status;
-       const enum lttng_process_attr process_attr =
-                       handle->domain.type == LTTNG_DOMAIN_UST ?
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID :
-                                       LTTNG_PROCESS_ATTR_PROCESS_ID;
+       const enum lttng_process_attr process_attr = handle->domain.type == LTTNG_DOMAIN_UST ?
+               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID :
+               LTTNG_PROCESS_ATTR_PROCESS_ID;
 
        LTTNG_ASSERT(handle);
 
        tracker_handle_ret_code = lttng_session_get_tracker_handle(
-                       handle->session_name, handle->domain.type,
-                       process_attr,
-                       &tracker_handle);
+               handle->session_name, handle->domain.type, process_attr, &tracker_handle);
        if (tracker_handle_ret_code != LTTNG_OK) {
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = get_tracker_elements(process_attr, &element_id_tracker,
-                       &element_target_id, &element_id, &element_id_alias,
-                       &element_name);
+       ret = get_tracker_elements(process_attr,
+                                  &element_id_tracker,
+                                  &element_target_id,
+                                  &element_id,
+                                  &element_id_alias,
+                                  &element_name);
        if (ret) {
                goto end;
        }
 
        /* Get the targets node */
-       for (node = xmlFirstElementChild(trackers_node); node;
-                       node = xmlNextElementSibling(node)) {
-               if (!strcmp((const char *) node->name,
-                               config_element_tracker_targets_legacy)) {
+       for (node = xmlFirstElementChild(trackers_node); node; node = xmlNextElementSibling(node)) {
+               if (!strcmp((const char *) node->name, config_element_tracker_targets_legacy)) {
                        targets_node = node;
                        break;
                }
@@ -2652,24 +2502,22 @@ static int process_legacy_pid_tracker_node(
        /* Go through all id target node */
        child_count = xmlChildElementCount(targets_node);
        status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                       tracker_handle,
-                       child_count == 0 ? LTTNG_TRACKING_POLICY_EXCLUDE_ALL :
-                                          LTTNG_TRACKING_POLICY_INCLUDE_SET);
+               tracker_handle,
+               child_count == 0 ? LTTNG_TRACKING_POLICY_EXCLUDE_ALL :
+                                  LTTNG_TRACKING_POLICY_INCLUDE_SET);
        if (status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                ret = LTTNG_ERR_UNK;
                goto end;
        }
 
        /* Add all tracked values. */
-       for (node = xmlFirstElementChild(targets_node); node;
-                       node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(targets_node); node; node = xmlNextElementSibling(node)) {
                xmlNodePtr pid_target_node = node;
 
                /* get pid_target node and track it */
                for (node = xmlFirstElementChild(pid_target_node); node;
-                               node = xmlNextElementSibling(node)) {
-                       if (!strcmp((const char *) node->name,
-                                           config_element_tracker_pid_legacy)) {
+                    node = xmlNextElementSibling(node)) {
+                       if (!strcmp((const char *) node->name, config_element_tracker_pid_legacy)) {
                                int64_t id;
                                xmlChar *content = xmlNodeGetContent(node);
 
@@ -2687,14 +2535,14 @@ static int process_legacy_pid_tracker_node(
 
                                switch (process_attr) {
                                case LTTNG_PROCESS_ATTR_PROCESS_ID:
-                                       status = lttng_process_attr_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) id);
+                                       status =
+                                               lttng_process_attr_process_id_tracker_handle_add_pid(
+                                                       tracker_handle, (pid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
-                                       status = lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) id);
+                                       status =
+                                               lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
+                                                       tracker_handle, (pid_t) id);
                                        break;
                                default:
                                        ret = LTTNG_ERR_INVALID;
@@ -2726,14 +2574,14 @@ static int process_legacy_pid_tracker_node(
 end:
        lttng_process_attr_tracker_handle_destroy(tracker_handle);
        return ret;
- }
+}
 
 static int process_id_tracker_node(xmlNodePtr id_tracker_node,
-               struct lttng_handle *handle,
-               enum lttng_process_attr process_attr)
+                                  struct lttng_handle *handle,
+                                  enum lttng_process_attr process_attr)
 {
        int ret = 0, child_count;
-       xmlNodePtr values_node = NULL;
+       xmlNodePtr values_node = nullptr;
        xmlNodePtr node;
        const char *element_id_tracker;
        const char *element_target_id;
@@ -2741,32 +2589,33 @@ static int process_id_tracker_node(xmlNodePtr id_tracker_node,
        const char *element_id_alias;
        const char *element_name;
        enum lttng_error_code tracker_handle_ret_code;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
        enum lttng_process_attr_tracker_handle_status status;
 
        LTTNG_ASSERT(handle);
        LTTNG_ASSERT(id_tracker_node);
 
        tracker_handle_ret_code = lttng_session_get_tracker_handle(
-                       handle->session_name, handle->domain.type, process_attr,
-                       &tracker_handle);
+               handle->session_name, handle->domain.type, process_attr, &tracker_handle);
        if (tracker_handle_ret_code != LTTNG_OK) {
                ret = LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = get_tracker_elements(process_attr, &element_id_tracker,
-                       &element_target_id, &element_id, &element_id_alias,
-                       &element_name);
+       ret = get_tracker_elements(process_attr,
+                                  &element_id_tracker,
+                                  &element_target_id,
+                                  &element_id,
+                                  &element_id_alias,
+                                  &element_name);
        if (ret) {
                goto end;
        }
 
        /* get the values node */
        for (node = xmlFirstElementChild(id_tracker_node); node;
-                       node = xmlNextElementSibling(node)) {
-               if (!strcmp((const char *) node->name,
-                               config_element_process_attr_values)) {
+            node = xmlNextElementSibling(node)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_values)) {
                        values_node = node;
                        break;
                }
@@ -2780,26 +2629,24 @@ static int process_id_tracker_node(xmlNodePtr id_tracker_node,
        /* Go through all id target node */
        child_count = xmlChildElementCount(values_node);
        status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                       tracker_handle,
-                       child_count == 0 ? LTTNG_TRACKING_POLICY_EXCLUDE_ALL :
-                                          LTTNG_TRACKING_POLICY_INCLUDE_SET);
+               tracker_handle,
+               child_count == 0 ? LTTNG_TRACKING_POLICY_EXCLUDE_ALL :
+                                  LTTNG_TRACKING_POLICY_INCLUDE_SET);
        if (status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                ret = LTTNG_ERR_UNK;
                goto end;
        }
 
        /* Add all tracked values. */
-       for (node = xmlFirstElementChild(values_node); node;
-                       node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(values_node); node; node = xmlNextElementSibling(node)) {
                xmlNodePtr id_target_node = node;
 
                /* get id node and track it */
                for (node = xmlFirstElementChild(id_target_node); node;
-                               node = xmlNextElementSibling(node)) {
+                    node = xmlNextElementSibling(node)) {
                        if (!strcmp((const char *) node->name, element_id) ||
-                                       (element_id_alias &&
-                                                       !strcmp((const char *) node->name,
-                                                                       element_id_alias))) {
+                           (element_id_alias &&
+                            !strcmp((const char *) node->name, element_id_alias))) {
                                int64_t id;
                                xmlChar *content = xmlNodeGetContent(node);
 
@@ -2817,42 +2664,39 @@ static int process_id_tracker_node(xmlNodePtr id_tracker_node,
 
                                switch (process_attr) {
                                case LTTNG_PROCESS_ATTR_PROCESS_ID:
-                                       status = lttng_process_attr_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) id);
+                                       status =
+                                               lttng_process_attr_process_id_tracker_handle_add_pid(
+                                                       tracker_handle, (pid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
-                                       status = lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) id);
+                                       status =
+                                               lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
+                                                       tracker_handle, (pid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_USER_ID:
                                        status = lttng_process_attr_user_id_tracker_handle_add_uid(
-                                                       tracker_handle,
-                                                       (uid_t) id);
+                                               tracker_handle, (uid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
-                                       status = lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
-                                                       tracker_handle,
-                                                       (uid_t) id);
+                                       status =
+                                               lttng_process_attr_virtual_user_id_tracker_handle_add_uid(
+                                                       tracker_handle, (uid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_GROUP_ID:
                                        status = lttng_process_attr_group_id_tracker_handle_add_gid(
-                                                       tracker_handle,
-                                                       (gid_t) id);
+                                               tracker_handle, (gid_t) id);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
-                                       status = lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
-                                                       tracker_handle,
-                                                       (gid_t) id);
+                                       status =
+                                               lttng_process_attr_virtual_group_id_tracker_handle_add_gid(
+                                                       tracker_handle, (gid_t) id);
                                        break;
                                default:
                                        ret = LTTNG_ERR_INVALID;
                                        goto end;
                                }
                        } else if (element_name &&
-                                       !strcmp((const char *) node->name,
-                                                       element_name)) {
+                                  !strcmp((const char *) node->name, element_name)) {
                                xmlChar *content = xmlNodeGetContent(node);
 
                                if (!content) {
@@ -2862,24 +2706,24 @@ static int process_id_tracker_node(xmlNodePtr id_tracker_node,
 
                                switch (process_attr) {
                                case LTTNG_PROCESS_ATTR_USER_ID:
-                                       status = lttng_process_attr_user_id_tracker_handle_add_user_name(
-                                                       tracker_handle,
-                                                       (const char *) content);
+                                       status =
+                                               lttng_process_attr_user_id_tracker_handle_add_user_name(
+                                                       tracker_handle, (const char *) content);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
-                                       status = lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
-                                                       tracker_handle,
-                                                       (const char *) content);
+                                       status =
+                                               lttng_process_attr_virtual_user_id_tracker_handle_add_user_name(
+                                                       tracker_handle, (const char *) content);
                                        break;
                                case LTTNG_PROCESS_ATTR_GROUP_ID:
-                                       status = lttng_process_attr_group_id_tracker_handle_add_group_name(
-                                                       tracker_handle,
-                                                       (const char *) content);
+                                       status =
+                                               lttng_process_attr_group_id_tracker_handle_add_group_name(
+                                                       tracker_handle, (const char *) content);
                                        break;
                                case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
-                                       status = lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
-                                                       tracker_handle,
-                                                       (const char *) content);
+                                       status =
+                                               lttng_process_attr_virtual_group_id_tracker_handle_add_group_name(
+                                                       tracker_handle, (const char *) content);
                                        break;
                                default:
                                        free(content);
@@ -2915,21 +2759,20 @@ end:
        return ret;
 }
 
-static
-int process_domain_node(xmlNodePtr domain_node, const char *session_name)
+static int process_domain_node(xmlNodePtr domain_node, const char *session_name)
 {
        int ret;
        struct lttng_domain domain {};
-       struct lttng_handle *handle = NULL;
-       struct lttng_channel *channel = NULL;
-       xmlNodePtr channels_node = NULL;
-       xmlNodePtr trackers_node = NULL;
-       xmlNodePtr pid_tracker_node = NULL;
-       xmlNodePtr vpid_tracker_node = NULL;
-       xmlNodePtr uid_tracker_node = NULL;
-       xmlNodePtr vuid_tracker_node = NULL;
-       xmlNodePtr gid_tracker_node = NULL;
-       xmlNodePtr vgid_tracker_node = NULL;
+       struct lttng_handle *handle = nullptr;
+       struct lttng_channel *channel = nullptr;
+       xmlNodePtr channels_node = nullptr;
+       xmlNodePtr trackers_node = nullptr;
+       xmlNodePtr pid_tracker_node = nullptr;
+       xmlNodePtr vpid_tracker_node = nullptr;
+       xmlNodePtr uid_tracker_node = nullptr;
+       xmlNodePtr vuid_tracker_node = nullptr;
+       xmlNodePtr gid_tracker_node = nullptr;
+       xmlNodePtr vgid_tracker_node = nullptr;
        xmlNodePtr node;
 
        LTTNG_ASSERT(session_name);
@@ -2946,10 +2789,8 @@ int process_domain_node(xmlNodePtr domain_node, const char *session_name)
        }
 
        /* get the channels node */
-       for (node = xmlFirstElementChild(domain_node); node;
-               node = xmlNextElementSibling(node)) {
-               if (!strcmp((const char *) node->name,
-                       config_element_channels)) {
+       for (node = xmlFirstElementChild(domain_node); node; node = xmlNextElementSibling(node)) {
+               if (!strcmp((const char *) node->name, config_element_channels)) {
                        channels_node = node;
                        break;
                }
@@ -2960,11 +2801,10 @@ int process_domain_node(xmlNodePtr domain_node, const char *session_name)
        }
 
        /* create all channels */
-       for (node = xmlFirstElementChild(channels_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(channels_node); node; node = xmlNextElementSibling(node)) {
                const enum lttng_domain_type original_domain = domain.type;
-               xmlNodePtr contexts_node = NULL;
-               xmlNodePtr events_node = NULL;
+               xmlNodePtr contexts_node = nullptr;
+               xmlNodePtr events_node = nullptr;
                xmlNodePtr channel_attr_node;
 
                /*
@@ -2993,11 +2833,10 @@ int process_domain_node(xmlNodePtr domain_node, const char *session_name)
                        goto end;
                }
 
-               for (channel_attr_node = xmlFirstElementChild(node);
-                       channel_attr_node; channel_attr_node =
-                       xmlNextElementSibling(channel_attr_node)) {
-                       ret = process_channel_attr_node(channel_attr_node,
-                               channel, &contexts_node, &events_node);
+               for (channel_attr_node = xmlFirstElementChild(node); channel_attr_node;
+                    channel_attr_node = xmlNextElementSibling(channel_attr_node)) {
+                       ret = process_channel_attr_node(
+                               channel_attr_node, channel, &contexts_node, &events_node);
                        if (ret) {
                                goto end;
                        }
@@ -3016,27 +2855,23 @@ int process_domain_node(xmlNodePtr domain_node, const char *session_name)
                        goto end;
                }
 
-               ret = process_contexts_node(contexts_node, handle,
-                       channel->name);
+               ret = process_contexts_node(contexts_node, handle, channel->name);
                if (ret) {
                        goto end;
                }
 
                lttng_channel_destroy(channel);
        }
-       channel = NULL;
+       channel = nullptr;
 
        /* get the trackers node */
-       for (node = xmlFirstElementChild(domain_node); node;
-                       node = xmlNextElementSibling(node)) {
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_trackers) ||
-                               !strcmp((const char *) node->name,
-                                               config_element_trackers_legacy)) {
+       for (node = xmlFirstElementChild(domain_node); node; node = xmlNextElementSibling(node)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_trackers) ||
+                   !strcmp((const char *) node->name, config_element_trackers_legacy)) {
                        if (trackers_node) {
                                ERR("Only one instance of `%s` or `%s` is allowed in a session configuration",
-                                               config_element_process_attr_trackers,
-                                               config_element_trackers_legacy);
+                                   config_element_process_attr_trackers,
+                                   config_element_trackers_legacy);
                                ret = -1;
                                goto end;
                        }
@@ -3049,64 +2884,56 @@ int process_domain_node(xmlNodePtr domain_node, const char *session_name)
                goto end;
        }
 
-       for (node = xmlFirstElementChild(trackers_node); node;
-                       node = xmlNextElementSibling(node)) {
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_pid)) {
+       for (node = xmlFirstElementChild(trackers_node); node; node = xmlNextElementSibling(node)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_pid)) {
                        pid_tracker_node = node;
-                       ret = process_id_tracker_node(pid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_PROCESS_ID);
+                       ret = process_id_tracker_node(
+                               pid_tracker_node, handle, LTTNG_PROCESS_ATTR_PROCESS_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_vpid)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_vpid)) {
                        vpid_tracker_node = node;
-                       ret = process_id_tracker_node(vpid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
+                       ret = process_id_tracker_node(
+                               vpid_tracker_node, handle, LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_uid)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_uid)) {
                        uid_tracker_node = node;
-                       ret = process_id_tracker_node(uid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_USER_ID);
+                       ret = process_id_tracker_node(
+                               uid_tracker_node, handle, LTTNG_PROCESS_ATTR_USER_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_vuid)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_vuid)) {
                        vuid_tracker_node = node;
-                       ret = process_id_tracker_node(vuid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
+                       ret = process_id_tracker_node(
+                               vuid_tracker_node, handle, LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_gid)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_gid)) {
                        gid_tracker_node = node;
-                       ret = process_id_tracker_node(gid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_GROUP_ID);
+                       ret = process_id_tracker_node(
+                               gid_tracker_node, handle, LTTNG_PROCESS_ATTR_GROUP_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_process_attr_tracker_vgid)) {
+               if (!strcmp((const char *) node->name, config_element_process_attr_tracker_vgid)) {
                        vgid_tracker_node = node;
-                       ret = process_id_tracker_node(vgid_tracker_node, handle,
-                                       LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
+                       ret = process_id_tracker_node(
+                               vgid_tracker_node, handle, LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID);
                        if (ret) {
                                goto end;
                        }
                }
-               if (!strcmp((const char *) node->name,
-                                   config_element_pid_tracker_legacy)) {
+               if (!strcmp((const char *) node->name, config_element_pid_tracker_legacy)) {
                        ret = process_legacy_pid_tracker_node(node, handle);
                        if (ret) {
                                goto end;
@@ -3120,21 +2947,18 @@ end:
        return ret;
 }
 
-static
-int add_periodic_rotation(const char *name, uint64_t time_us)
+static int add_periodic_rotation(const char *name, uint64_t time_us)
 {
        int ret;
        enum lttng_rotation_status status;
-       struct lttng_rotation_schedule *periodic =
-                       lttng_rotation_schedule_periodic_create();
+       struct lttng_rotation_schedule *periodic = lttng_rotation_schedule_periodic_create();
 
        if (!periodic) {
                ret = -LTTNG_ERR_NOMEM;
                goto error;
        }
 
-       status = lttng_rotation_schedule_periodic_set_period(periodic,
-                       time_us);
+       status = lttng_rotation_schedule_periodic_set_period(periodic, time_us);
        if (status != LTTNG_ROTATION_STATUS_OK) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -3158,21 +2982,18 @@ error:
        return ret;
 }
 
-static
-int add_size_rotation(const char *name, uint64_t size_bytes)
+static int add_size_rotation(const char *name, uint64_t size_bytes)
 {
        int ret;
        enum lttng_rotation_status status;
-       struct lttng_rotation_schedule *size =
-                       lttng_rotation_schedule_size_threshold_create();
+       struct lttng_rotation_schedule *size = lttng_rotation_schedule_size_threshold_create();
 
        if (!size) {
                ret = -LTTNG_ERR_NOMEM;
                goto error;
        }
 
-       status = lttng_rotation_schedule_size_threshold_set_threshold(size,
-                       size_bytes);
+       status = lttng_rotation_schedule_size_threshold_set_threshold(size, size_bytes);
        if (status != LTTNG_ROTATION_STATUS_OK) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -3196,28 +3017,25 @@ error:
        return ret;
 }
 
-static
-int process_session_rotation_schedules_node(
-               xmlNodePtr schedules_node,
-               uint64_t *rotation_timer_interval,
-               uint64_t *rotation_size)
+static int process_session_rotation_schedules_node(xmlNodePtr schedules_node,
+                                                  uint64_t *rotation_timer_interval,
+                                                  uint64_t *rotation_size)
 {
        int ret = 0;
        xmlNodePtr child;
 
-       for (child = xmlFirstElementChild(schedules_node);
-                       child;
-                       child = xmlNextElementSibling(child)) {
+       for (child = xmlFirstElementChild(schedules_node); child;
+            child = xmlNextElementSibling(child)) {
                if (!strcmp((const char *) child->name,
-                               config_element_rotation_schedule_periodic)) {
+                           config_element_rotation_schedule_periodic)) {
                        xmlChar *content;
                        xmlNodePtr time_us_node;
 
                        /* periodic rotation schedule */
                        time_us_node = xmlFirstElementChild(child);
                        if (!time_us_node ||
-                                       strcmp((const char *) time_us_node->name,
-                                               config_element_rotation_schedule_periodic_time_us)) {
+                           strcmp((const char *) time_us_node->name,
+                                  config_element_rotation_schedule_periodic_time_us) != 0) {
                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                goto end;
                        }
@@ -3235,15 +3053,15 @@ int process_session_rotation_schedules_node(
                                goto end;
                        }
                } else if (!strcmp((const char *) child->name,
-                               config_element_rotation_schedule_size_threshold)) {
+                                  config_element_rotation_schedule_size_threshold)) {
                        xmlChar *content;
                        xmlNodePtr bytes_node;
 
                        /* size_threshold rotation schedule */
                        bytes_node = xmlFirstElementChild(child);
                        if (!bytes_node ||
-                                       strcmp((const char *) bytes_node->name,
-                                               config_element_rotation_schedule_size_threshold_bytes)) {
+                           strcmp((const char *) bytes_node->name,
+                                  config_element_rotation_schedule_size_threshold_bytes) != 0) {
                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                goto end;
                        }
@@ -3267,31 +3085,27 @@ end:
        return ret;
 }
 
-static
-int process_session_node(xmlNodePtr session_node, const char *session_name,
-               int overwrite,
-               const struct config_load_session_override_attr *overrides)
+static int process_session_node(xmlNodePtr session_node,
+                               const char *session_name,
+                               int overwrite,
+                               const struct config_load_session_override_attr *overrides)
 {
        int ret, started = -1, snapshot_mode = -1;
-       uint64_t live_timer_interval = UINT64_MAX,
-                        rotation_timer_interval = 0,
-                        rotation_size = 0;
-       xmlChar *name = NULL;
-       xmlChar *shm_path = NULL;
-       xmlNodePtr domains_node = NULL;
-       xmlNodePtr output_node = NULL;
+       uint64_t live_timer_interval = UINT64_MAX, rotation_timer_interval = 0, rotation_size = 0;
+       xmlChar *name = nullptr;
+       xmlChar *shm_path = nullptr;
+       xmlNodePtr domains_node = nullptr;
+       xmlNodePtr output_node = nullptr;
        xmlNodePtr node;
        xmlNodePtr attributes_child;
-       struct lttng_domain *kernel_domain = NULL;
-       struct lttng_domain *ust_domain = NULL;
-       struct lttng_domain *jul_domain = NULL;
-       struct lttng_domain *log4j_domain = NULL;
-       struct lttng_domain *python_domain = NULL;
-
-       for (node = xmlFirstElementChild(session_node); node;
-               node = xmlNextElementSibling(node)) {
-               if (!name && !strcmp((const char *) node->name,
-                       config_element_name)) {
+       struct lttng_domain *kernel_domain = nullptr;
+       struct lttng_domain *ust_domain = nullptr;
+       struct lttng_domain *jul_domain = nullptr;
+       struct lttng_domain *log4j_domain = nullptr;
+       struct lttng_domain *python_domain = nullptr;
+
+       for (node = xmlFirstElementChild(session_node); node; node = xmlNextElementSibling(node)) {
+               if (!name && !strcmp((const char *) node->name, config_element_name)) {
                        /* name */
                        xmlChar *node_content = xmlNodeGetContent(node);
                        if (!node_content) {
@@ -3300,12 +3114,12 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                        }
 
                        name = node_content;
-               } else if (!domains_node && !strcmp((const char *) node->name,
-                       config_element_domains)) {
+               } else if (!domains_node &&
+                          !strcmp((const char *) node->name, config_element_domains)) {
                        /* domains */
                        domains_node = node;
-               } else if (started == -1 && !strcmp((const char *) node->name,
-                       config_element_started)) {
+               } else if (started == -1 &&
+                          !strcmp((const char *) node->name, config_element_started)) {
                        /* started */
                        xmlChar *node_content = xmlNodeGetContent(node);
                        if (!node_content) {
@@ -3319,12 +3133,12 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                goto error;
                        }
-               } else if (!output_node && !strcmp((const char *) node->name,
-                       config_element_output)) {
+               } else if (!output_node &&
+                          !strcmp((const char *) node->name, config_element_output)) {
                        /* output */
                        output_node = node;
-               } else if (!shm_path && !strcmp((const char *) node->name,
-                       config_element_shared_memory_path)) {
+               } else if (!shm_path &&
+                          !strcmp((const char *) node->name, config_element_shared_memory_path)) {
                        /* shared memory path */
                        xmlChar *node_content = xmlNodeGetContent(node);
                        if (!node_content) {
@@ -3339,9 +3153,9 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                         * rotation_timer_interval.
                         */
                        for (attributes_child = xmlFirstElementChild(node); attributes_child;
-                                       attributes_child = xmlNextElementSibling(attributes_child)) {
+                            attributes_child = xmlNextElementSibling(attributes_child)) {
                                if (!strcmp((const char *) attributes_child->name,
-                                                       config_element_snapshot_mode)) {
+                                           config_element_snapshot_mode)) {
                                        /* snapshot_mode */
                                        xmlChar *snapshot_mode_content =
                                                xmlNodeGetContent(attributes_child);
@@ -3357,7 +3171,7 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                                                goto error;
                                        }
                                } else if (!strcmp((const char *) attributes_child->name,
-                                                       config_element_live_timer_interval)) {
+                                                  config_element_live_timer_interval)) {
                                        /* live_timer_interval */
                                        xmlChar *timer_interval_content =
                                                xmlNodeGetContent(attributes_child);
@@ -3366,23 +3180,23 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                                                goto error;
                                        }
 
-                                       ret = parse_uint(timer_interval_content, &live_timer_interval);
+                                       ret = parse_uint(timer_interval_content,
+                                                        &live_timer_interval);
                                        free(timer_interval_content);
                                        if (ret) {
                                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                                goto error;
                                        }
                                } else if (!strcmp((const char *) attributes_child->name,
-                                                       config_element_rotation_schedules)) {
+                                                  config_element_rotation_schedules)) {
                                        ret = process_session_rotation_schedules_node(
-                                                       attributes_child,
-                                                       &rotation_timer_interval,
-                                                       &rotation_size);
+                                               attributes_child,
+                                               &rotation_timer_interval,
+                                               &rotation_size);
                                        if (ret) {
                                                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                                                goto error;
                                        }
-
                                }
                        }
                }
@@ -3394,15 +3208,14 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                goto error;
        }
 
-       if (session_name && strcmp((char *) name, session_name)) {
+       if (session_name && strcmp((char *) name, session_name) != 0) {
                /* This is not the session we are looking for */
                ret = -LTTNG_ERR_NO_SESSION;
                goto error;
        }
 
        /* Init domains to create the session handles */
-       for (node = xmlFirstElementChild(domains_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(domains_node); node; node = xmlNextElementSibling(node)) {
                lttng_domain *domain = zmalloc<lttng_domain>();
 
                if (!domain) {
@@ -3456,7 +3269,7 @@ int process_session_node(xmlNodePtr session_node, const char *session_name,
                        goto domain_init_error;
                }
                continue;
-domain_init_error:
+       domain_init_error:
                free(domain);
                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                goto error;
@@ -3488,31 +3301,26 @@ domain_init_error:
 
        /* Create session type depending on output type */
        if (snapshot_mode && snapshot_mode != -1) {
-               ret = create_snapshot_session((const char *) name, output_node,
-                               overrides);
-       } else if (live_timer_interval &&
-               live_timer_interval != UINT64_MAX) {
-               ret = create_session((const char *) name,
-                               output_node, live_timer_interval, overrides);
+               ret = create_snapshot_session((const char *) name, output_node, overrides);
+       } else if (live_timer_interval && live_timer_interval != UINT64_MAX) {
+               ret = create_session(
+                       (const char *) name, output_node, live_timer_interval, overrides);
        } else {
                /* regular session */
-               ret = create_session((const char *) name,
-                               output_node, UINT64_MAX, overrides);
+               ret = create_session((const char *) name, output_node, UINT64_MAX, overrides);
        }
        if (ret) {
                goto error;
        }
 
        if (shm_path) {
-               ret = lttng_set_session_shm_path((const char *) name,
-                               (const char *) shm_path);
+               ret = lttng_set_session_shm_path((const char *) name, (const char *) shm_path);
                if (ret) {
                        goto error;
                }
        }
 
-       for (node = xmlFirstElementChild(domains_node); node;
-               node = xmlNextElementSibling(node)) {
+       for (node = xmlFirstElementChild(domains_node); node; node = xmlNextElementSibling(node)) {
                ret = process_domain_node(node, (const char *) name);
                if (ret) {
                        goto end;
@@ -3520,15 +3328,13 @@ domain_init_error:
        }
 
        if (rotation_timer_interval) {
-               ret = add_periodic_rotation((const char *) name,
-                               rotation_timer_interval);
+               ret = add_periodic_rotation((const char *) name, rotation_timer_interval);
                if (ret < 0) {
                        goto error;
                }
        }
        if (rotation_size) {
-               ret = add_size_rotation((const char *) name,
-                               rotation_size);
+               ret = add_size_rotation((const char *) name, rotation_size);
                if (ret < 0) {
                        goto error;
                }
@@ -3543,8 +3349,7 @@ domain_init_error:
 
 end:
        if (ret < 0) {
-               ERR("Failed to load session %s: %s", (const char *) name,
-                       lttng_strerror(ret));
+               ERR("Failed to load session %s: %s", (const char *) name, lttng_strerror(ret));
                lttng_destroy_session((const char *) name);
        }
 
@@ -3584,13 +3389,14 @@ valid:
        return 1;
 }
 
-static
-int load_session_from_file(const char *path, const char *session_name,
-       struct session_config_validation_ctx *validation_ctx, int overwrite,
-       const struct config_load_session_override_attr *overrides)
+static int load_session_from_file(const char *path,
+                                 const char *session_name,
+                                 struct session_config_validation_ctx *validation_ctx,
+                                 int overwrite,
+                                 const struct config_load_session_override_attr *overrides)
 {
        int ret, session_found = !session_name;
-       xmlDocPtr doc = NULL;
+       xmlDocPtr doc = nullptr;
        xmlNodePtr sessions_node;
        xmlNodePtr session_node;
 
@@ -3626,11 +3432,9 @@ int load_session_from_file(const char *path, const char *session_name,
                goto end;
        }
 
-       for (session_node = xmlFirstElementChild(sessions_node);
-               session_node; session_node =
-                       xmlNextElementSibling(session_node)) {
-               ret = process_session_node(session_node,
-                       session_name, overwrite, overrides);
+       for (session_node = xmlFirstElementChild(sessions_node); session_node;
+            session_node = xmlNextElementSibling(session_node)) {
+               ret = process_session_node(session_node, session_name, overwrite, overrides);
                if (!session_name && ret) {
                        /* Loading error occurred. */
                        goto end;
@@ -3659,13 +3463,14 @@ end:
        return ret;
 }
 
-static
-int load_session_from_path(const char *path, const char *session_name,
-       struct session_config_validation_ctx *validation_ctx, int overwrite,
-       const struct config_load_session_override_attr *overrides)
+static int load_session_from_path(const char *path,
+                                 const char *session_name,
+                                 struct session_config_validation_ctx *validation_ctx,
+                                 int overwrite,
+                                 const struct config_load_session_override_attr *overrides)
 {
        int ret, session_found = !session_name;
-       DIR *directory = NULL;
+       DIR *directory = nullptr;
        struct lttng_dynamic_buffer file_path;
        size_t path_len;
 
@@ -3675,7 +3480,9 @@ int load_session_from_path(const char *path, const char *session_name,
        lttng_dynamic_buffer_init(&file_path);
        if (path_len >= LTTNG_PATH_MAX) {
                ERR("Session configuration load path \"%s\" length (%zu) exceeds the maximal length allowed (%d)",
-                               path, path_len, LTTNG_PATH_MAX);
+                   path,
+                   path_len,
+                   LTTNG_PATH_MAX);
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -3697,21 +3504,20 @@ int load_session_from_path(const char *path, const char *session_name,
        if (directory) {
                size_t file_path_root_len;
 
-               ret = lttng_dynamic_buffer_set_capacity(&file_path,
-                               LTTNG_PATH_MAX);
+               ret = lttng_dynamic_buffer_set_capacity(&file_path, LTTNG_PATH_MAX);
                if (ret) {
                        ret = -LTTNG_ERR_NOMEM;
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&file_path, path, path_len);
+               ret = lttng_dynamic_buffer_append(&file_path, path, path_len);
                if (ret) {
                        ret = -LTTNG_ERR_NOMEM;
                        goto end;
                }
 
                if (file_path.data[file_path.size - 1] != '/') {
-                       ret = lttng_dynamic_buffer_append(&file_path, "/", 1);
+                       ret = lttng_dynamic_buffer_append(&file_path, "/", 1);
                        if (ret) {
                                ret = -LTTNG_ERR_NOMEM;
                                goto end;
@@ -3741,7 +3547,8 @@ int load_session_from_path(const char *path, const char *session_name,
                        /* Reached end of dir stream or error out. */
                        if (!result) {
                                if (errno) {
-                                       PERROR("Failed to enumerate the contents of path \"%s\" while loading session, readdir returned", path);
+                                       PERROR("Failed to enumerate the contents of path \"%s\" while loading session, readdir returned",
+                                              path);
                                        ret = -LTTNG_ERR_LOAD_IO_FAIL;
                                        goto end;
                                }
@@ -3750,38 +3557,37 @@ int load_session_from_path(const char *path, const char *session_name,
 
                        file_name_len = strlen(result->d_name);
 
-                       if (file_name_len <=
-                               sizeof(DEFAULT_SESSION_CONFIG_FILE_EXTENSION)) {
+                       if (file_name_len <= sizeof(DEFAULT_SESSION_CONFIG_FILE_EXTENSION)) {
                                continue;
                        }
 
                        if (file_path.size + file_name_len >= LTTNG_PATH_MAX) {
                                WARN("Ignoring file \"%s\" since the path's length (%zu) would exceed the maximal permitted size (%d)",
-                                               result->d_name,
-                                               /* +1 to account for NULL terminator. */
-                                               file_path.size + file_name_len + 1,
-                                               LTTNG_PATH_MAX);
+                                    result->d_name,
+                                    /* +1 to account for NULL terminator. */
+                                    file_path.size + file_name_len + 1,
+                                    LTTNG_PATH_MAX);
                                continue;
                        }
 
                        /* Does the file end with .lttng? */
                        if (strcmp(DEFAULT_SESSION_CONFIG_FILE_EXTENSION,
-                                       result->d_name + file_name_len - sizeof(
-                                       DEFAULT_SESSION_CONFIG_FILE_EXTENSION) + 1)) {
+                                  result->d_name + file_name_len -
+                                          sizeof(DEFAULT_SESSION_CONFIG_FILE_EXTENSION) + 1) !=
+                           0) {
                                continue;
                        }
 
-                       ret = lttng_dynamic_buffer_append(&file_path, result->d_name,
-                                       file_name_len + 1);
+                       ret = lttng_dynamic_buffer_append(
+                               &file_path, result->d_name, file_name_len + 1);
                        if (ret) {
                                ret = -LTTNG_ERR_NOMEM;
                                goto end;
                        }
 
-                       ret = load_session_from_file(file_path.data, session_name,
-                               validation_ctx, overwrite, overrides);
-                       if (session_name &&
-                                       (!ret || ret != -LTTNG_ERR_LOAD_SESSION_NOENT)) {
+                       ret = load_session_from_file(
+                               file_path.data, session_name, validation_ctx, overwrite, overrides);
+                       if (session_name && (!ret || ret != -LTTNG_ERR_LOAD_SESSION_NOENT)) {
                                session_found = 1;
                                break;
                        }
@@ -3792,16 +3598,15 @@ int load_session_from_path(const char *path, const char *session_name,
                         * Reset the buffer's size to the location of the
                         * path's trailing '/'.
                         */
-                       ret = lttng_dynamic_buffer_set_size(&file_path,
-                                       file_path_root_len);
+                       ret = lttng_dynamic_buffer_set_size(&file_path, file_path_root_len);
                        if (ret) {
                                ret = -LTTNG_ERR_UNK;
                                goto end;
                        }
                }
        } else {
-               ret = load_session_from_file(path, session_name,
-                       validation_ctx, overwrite, overrides);
+               ret = load_session_from_file(
+                       path, session_name, validation_ctx, overwrite, overrides);
                if (ret) {
                        goto end;
                }
@@ -3855,13 +3660,15 @@ invalid:
        return 0;
 }
 
-int config_load_session(const char *path, const char *session_name,
-               int overwrite, unsigned int autoload,
-               const struct config_load_session_override_attr *overrides)
+int config_load_session(const char *path,
+                       const char *session_name,
+                       int overwrite,
+                       unsigned int autoload,
+                       const struct config_load_session_override_attr *overrides)
 {
        int ret;
        bool session_loaded = false;
-       const char *path_ptr = NULL;
+       const char *path_ptr = nullptr;
        struct session_config_validation_ctx validation_ctx = {};
 
        ret = init_session_config_validation_ctx(&validation_ctx);
@@ -3883,10 +3690,11 @@ int config_load_session(const char *path, const char *session_name,
                         * continue loading the system wide sessions.
                         */
                        if (autoload) {
-                               ret = snprintf(path_buf, sizeof(path_buf),
-                                               DEFAULT_SESSION_HOME_CONFIGPATH
-                                               "/" DEFAULT_SESSION_CONFIG_AUTOLOAD,
-                                               home_path);
+                               ret = snprintf(path_buf,
+                                              sizeof(path_buf),
+                                              DEFAULT_SESSION_HOME_CONFIGPATH
+                                              "/" DEFAULT_SESSION_CONFIG_AUTOLOAD,
+                                              home_path);
                                if (ret < 0) {
                                        PERROR("snprintf session autoload home config path");
                                        ret = -LTTNG_ERR_INVALID;
@@ -3903,9 +3711,10 @@ int config_load_session(const char *path, const char *session_name,
                                        path_ptr = path_buf;
                                }
                        } else {
-                               ret = snprintf(path_buf, sizeof(path_buf),
-                                               DEFAULT_SESSION_HOME_CONFIGPATH,
-                                               home_path);
+                               ret = snprintf(path_buf,
+                                              sizeof(path_buf),
+                                              DEFAULT_SESSION_HOME_CONFIGPATH,
+                                              home_path);
                                if (ret < 0) {
                                        PERROR("snprintf session home config path");
                                        ret = -LTTNG_ERR_INVALID;
@@ -3914,8 +3723,11 @@ int config_load_session(const char *path, const char *session_name,
                                path_ptr = path_buf;
                        }
                        if (path_ptr) {
-                               ret = load_session_from_path(path_ptr, session_name,
-                                               &validation_ctx, overwrite, overrides);
+                               ret = load_session_from_path(path_ptr,
+                                                            session_name,
+                                                            &validation_ctx,
+                                                            overwrite,
+                                                            overrides);
                                if (ret && ret != -LTTNG_ERR_LOAD_SESSION_NOENT) {
                                        goto end;
                                }
@@ -3928,12 +3740,12 @@ int config_load_session(const char *path, const char *session_name,
                }
 
                /* Reset path pointer for the system wide dir. */
-               path_ptr = NULL;
+               path_ptr = nullptr;
 
                /* Try system wide configuration directory. */
                if (autoload) {
-                       sys_path = DEFAULT_SESSION_SYSTEM_CONFIGPATH "/"
-                               DEFAULT_SESSION_CONFIG_AUTOLOAD;
+                       sys_path = DEFAULT_SESSION_SYSTEM_CONFIGPATH
+                               "/" DEFAULT_SESSION_CONFIG_AUTOLOAD;
                        ret = validate_path_creds(sys_path);
                        if (ret) {
                                path_ptr = sys_path;
@@ -3944,8 +3756,8 @@ int config_load_session(const char *path, const char *session_name,
                }
 
                if (path_ptr) {
-                       ret = load_session_from_path(path_ptr, session_name,
-                                       &validation_ctx, overwrite, overrides);
+                       ret = load_session_from_path(
+                               path_ptr, session_name, &validation_ctx, overwrite, overrides);
                        if (!ret) {
                                session_loaded = true;
                        }
@@ -3971,8 +3783,8 @@ int config_load_session(const char *path, const char *session_name,
                        goto end;
                }
 
-               ret = load_session_from_path(path, session_name,
-                       &validation_ctx, overwrite, overrides);
+               ret = load_session_from_path(
+                       path, session_name, &validation_ctx, overwrite, overrides);
        }
 end:
        fini_session_config_validation_ctx(&validation_ctx);
@@ -3991,8 +3803,7 @@ end:
        return ret;
 }
 
-static
-void __attribute__((destructor)) session_config_exit(void)
+static void __attribute__((destructor)) session_config_exit()
 {
        xmlCleanupParser();
 }
index 71270a4efdd9f2dc4ad59b147cbc2ef9fd4ec67d..472ec8140d538b282fbc36a72464f77245ed9752 100644 (file)
@@ -10,6 +10,7 @@
 
 #include <common/config/config-session-abi.hpp>
 #include <common/macros.hpp>
+
 #include <stdint.h>
 
 struct config_load_session_override_attr {
@@ -56,8 +57,7 @@ int config_writer_destroy(struct config_writer *writer);
  * Returns zero if the XML element could be opened.
  * Negative values indicate an error.
  */
-int config_writer_open_element(struct config_writer *writer,
-               const char *element_name);
+int config_writer_open_element(struct config_writer *writer, const char *element_name);
 
 /*
  * Write an element tag attribute.
@@ -70,7 +70,8 @@ int config_writer_open_element(struct config_writer *writer,
  * Negative values indicate an error.
  */
 int config_writer_write_attribute(struct config_writer *writer,
-               const char *name, const char *value);
+                                 const char *name,
+                                 const char *value);
 
 /*
  * Close the current element tag.
@@ -95,7 +96,8 @@ int config_writer_close_element(struct config_writer *writer);
  * Negative values indicate an error.
  */
 int config_writer_write_element_unsigned_int(struct config_writer *writer,
-               const char *element_name, uint64_t value);
+                                            const char *element_name,
+                                            uint64_t value);
 
 /*
  * Write an element of type signed int.
@@ -110,7 +112,8 @@ int config_writer_write_element_unsigned_int(struct config_writer *writer,
  * Negative values indicate an error.
  */
 int config_writer_write_element_signed_int(struct config_writer *writer,
-               const char *element_name, int64_t value);
+                                          const char *element_name,
+                                          int64_t value);
 
 /*
  * Write an element of type boolean.
@@ -125,7 +128,8 @@ int config_writer_write_element_signed_int(struct config_writer *writer,
  * Negative values indicate an error.
  */
 int config_writer_write_element_bool(struct config_writer *writer,
-               const char *element_name, int value);
+                                    const char *element_name,
+                                    int value);
 
 /*
  * Write an element of type string.
@@ -140,7 +144,8 @@ int config_writer_write_element_bool(struct config_writer *writer,
  * Negative values indicate an error.
  */
 int config_writer_write_element_string(struct config_writer *writer,
-               const char *element_name, const char *value);
+                                      const char *element_name,
+                                      const char *value);
 
 /*
  * Write an element of type double.
@@ -155,8 +160,8 @@ int config_writer_write_element_string(struct config_writer *writer,
  * Negative values indicate an error.
  */
 int config_writer_write_element_double(struct config_writer *writer,
-               const char *element_name,
-               double value);
+                                      const char *element_name,
+                                      double value);
 
 /*
  * Load session configurations from a file.
@@ -177,8 +182,10 @@ int config_writer_write_element_double(struct config_writer *writer,
  * Returns zero if the session could be loaded successfully. Returns
  * a negative LTTNG_ERR code on error.
  */
-int config_load_session(const char *path, const char *session_name,
-               int overwrite, unsigned int autoload,
-               const struct config_load_session_override_attr *overrides);
+int config_load_session(const char *path,
+                       const char *session_name,
+                       int overwrite,
+                       unsigned int autoload,
+                       const struct config_load_session_override_attr *overrides);
 
 #endif /* _CONFIG_H */
index 274ecf48fa71275ee28803f850049b7ab882f763..5e84f2b96f277ca7b80c4144feda327b717c2f99 100644 (file)
@@ -7,20 +7,20 @@
  */
 
 #define _LGPL_SOURCE
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <inttypes.h>
+#include "consumer-metadata-cache.hpp"
 
 #include <common/common.hpp>
-#include <common/utils.hpp>
+#include <common/consumer/consumer.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/ust-consumer/ust-consumer.hpp>
-#include <common/consumer/consumer.hpp>
+#include <common/utils.hpp>
 
-#include "consumer-metadata-cache.hpp"
+#include <inttypes.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 enum metadata_cache_update_version_status {
        METADATA_CACHE_UPDATE_STATUS_VERSION_UPDATED,
@@ -32,8 +32,7 @@ extern struct lttng_consumer_global_data the_consumer_data;
 /*
  * Reset the metadata cache.
  */
-static
-void metadata_cache_reset(struct consumer_metadata_cache *cache)
+static void metadata_cache_reset(struct consumer_metadata_cache *cache)
 {
        const int ret = lttng_dynamic_buffer_set_size(&cache->contents, 0);
 
@@ -45,8 +44,8 @@ void metadata_cache_reset(struct consumer_metadata_cache *cache)
  * If it did, reset the metadata cache.
  * The metadata cache lock MUST be held.
  */
-static enum metadata_cache_update_version_status metadata_cache_update_version(
-               struct consumer_metadata_cache *cache, uint64_t version)
+static enum metadata_cache_update_version_status
+metadata_cache_update_version(struct consumer_metadata_cache *cache, uint64_t version)
 {
        enum metadata_cache_update_version_status status;
 
@@ -74,8 +73,10 @@ end:
  */
 enum consumer_metadata_cache_write_status
 consumer_metadata_cache_write(struct consumer_metadata_cache *cache,
-               unsigned int offset, unsigned int len, uint64_t version,
-               const char *data)
+                             unsigned int offset,
+                             unsigned int len,
+                             uint64_t version,
+                             const char *data)
 {
        int ret = 0;
        enum consumer_metadata_cache_write_status status;
@@ -87,15 +88,14 @@ consumer_metadata_cache_write(struct consumer_metadata_cache *cache,
        original_size = cache->contents.size;
 
        if (metadata_cache_update_version(cache, version) ==
-                       METADATA_CACHE_UPDATE_STATUS_VERSION_UPDATED) {
+           METADATA_CACHE_UPDATE_STATUS_VERSION_UPDATED) {
                metadata_cache_reset(cache);
                cache_is_invalidated = true;
        }
 
        DBG("Writing %u bytes from offset %u in metadata cache", len, offset);
        if (offset + len > cache->contents.size) {
-               ret = lttng_dynamic_buffer_set_size(
-                               &cache->contents, offset + len);
+               ret = lttng_dynamic_buffer_set_size(&cache->contents, offset + len);
                if (ret) {
                        ERR("Extending metadata cache");
                        status = CONSUMER_METADATA_CACHE_WRITE_STATUS_ERROR;
@@ -135,26 +135,24 @@ int consumer_metadata_cache_allocate(struct lttng_consumer_channel *channel)
                ret = -1;
                goto end;
        }
-       ret = pthread_mutex_init(&channel->metadata_cache->lock, NULL);
+       ret = pthread_mutex_init(&channel->metadata_cache->lock, nullptr);
        if (ret != 0) {
                PERROR("mutex init");
                goto end_free_cache;
        }
 
        lttng_dynamic_buffer_init(&channel->metadata_cache->contents);
-       ret = lttng_dynamic_buffer_set_capacity(
-                       &channel->metadata_cache->contents,
-                       DEFAULT_METADATA_CACHE_SIZE);
+       ret = lttng_dynamic_buffer_set_capacity(&channel->metadata_cache->contents,
+                                               DEFAULT_METADATA_CACHE_SIZE);
        if (ret) {
                PERROR("Failed to pre-allocate metadata cache storage of %d bytes on creation",
-                               DEFAULT_METADATA_CACHE_SIZE);
+                      DEFAULT_METADATA_CACHE_SIZE);
                ret = -1;
                goto end_free_mutex;
        }
 
        DBG("Allocated metadata cache: current capacity = %zu",
-                       lttng_dynamic_buffer_get_capacity_left(
-                                       &channel->metadata_cache->contents));
+           lttng_dynamic_buffer_get_capacity_left(&channel->metadata_cache->contents));
 
        ret = 0;
        goto end;
@@ -186,17 +184,16 @@ void consumer_metadata_cache_destroy(struct lttng_consumer_channel *channel)
 /*
  * Check if the cache is flushed up to the offset passed in parameter.
  *
- * Return 0 if everything has been flushed, 1 if there is data not flushed.
+ * Return true if everything has been flushed, false if there is data not flushed.
  */
-int consumer_metadata_cache_flushed(struct lttng_consumer_channel *channel,
-               uint64_t offset, int timer)
+namespace {
+bool consumer_metadata_cache_is_flushed(struct lttng_consumer_channel *channel,
+                                       uint64_t offset,
+                                       int timer)
 {
-       int ret = 0;
+       bool done_flushing = false;
        struct lttng_consumer_stream *metadata_stream;
 
-       LTTNG_ASSERT(channel);
-       LTTNG_ASSERT(channel->metadata_cache);
-
        /*
         * If not called from a timer handler, we have to take the
         * channel lock to be mutually exclusive with channel teardown.
@@ -214,7 +211,7 @@ int consumer_metadata_cache_flushed(struct lttng_consumer_channel *channel,
                 * Having no metadata stream means the channel is being destroyed so there
                 * is no cache to flush anymore.
                 */
-               ret = 0;
+               done_flushing = true;
                goto end_unlock_channel;
        }
 
@@ -222,23 +219,56 @@ int consumer_metadata_cache_flushed(struct lttng_consumer_channel *channel,
        pthread_mutex_lock(&channel->metadata_cache->lock);
 
        if (metadata_stream->ust_metadata_pushed >= offset) {
-               ret = 0;
-       } else if (channel->metadata_stream->endpoint_status !=
-                       CONSUMER_ENDPOINT_ACTIVE) {
+               done_flushing = true;
+       } else if (channel->metadata_stream->endpoint_status != CONSUMER_ENDPOINT_ACTIVE) {
                /* An inactive endpoint means we don't have to flush anymore. */
-               ret = 0;
+               done_flushing = true;
        } else {
                /* Still not completely flushed. */
-               ret = 1;
+               done_flushing = false;
        }
 
        pthread_mutex_unlock(&channel->metadata_cache->lock);
        pthread_mutex_unlock(&metadata_stream->lock);
+
 end_unlock_channel:
        pthread_mutex_unlock(&channel->timer_lock);
        if (!timer) {
                pthread_mutex_unlock(&channel->lock);
        }
 
-       return ret;
+       return done_flushing;
+}
+} /* namespace */
+
+/*
+ * Wait until the cache is flushed up to the offset passed in parameter or the
+ * metadata stream has been destroyed.
+ */
+void consumer_wait_metadata_cache_flushed(struct lttng_consumer_channel *channel,
+                                         uint64_t offset,
+                                         bool invoked_by_timer)
+{
+       assert(channel);
+       assert(channel->metadata_cache);
+
+       if (consumer_metadata_cache_is_flushed(channel, offset, invoked_by_timer)) {
+               return;
+       }
+
+       /* Metadata cache is not currently flushed, wait on wait queue. */
+       for (;;) {
+               lttng::synchro::waiter waiter;
+
+               channel->metadata_pushed_wait_queue.add(waiter);
+               if (consumer_metadata_cache_is_flushed(channel, offset, invoked_by_timer)) {
+                       /* Wake up all waiters, ourself included. */
+                       channel->metadata_pushed_wait_queue.wake_all();
+                       /* Ensure proper teardown of waiter. */
+                       waiter.wait();
+                       break;
+               }
+
+               waiter.wait();
+       }
 }
index 6e60e5c15c2eab9852d7b941c9c75b650c494601..529b9f0756f560023393f9bacb16b89470df785d 100644 (file)
@@ -52,11 +52,14 @@ struct consumer_metadata_cache {
 
 enum consumer_metadata_cache_write_status
 consumer_metadata_cache_write(struct consumer_metadata_cache *cache,
-               unsigned int offset, unsigned int len, uint64_t version,
-               const char *data);
+                             unsigned int offset,
+                             unsigned int len,
+                             uint64_t version,
+                             const char *data);
 int consumer_metadata_cache_allocate(struct lttng_consumer_channel *channel);
 void consumer_metadata_cache_destroy(struct lttng_consumer_channel *channel);
-int consumer_metadata_cache_flushed(struct lttng_consumer_channel *channel,
-               uint64_t offset, int timer);
+void consumer_wait_metadata_cache_flushed(struct lttng_consumer_channel *channel,
+                                         uint64_t offset,
+                                         bool invoked_by_timer);
 
 #endif /* CONSUMER_METADATA_CACHE_H */
index bb0ec0a2436db1a9fb042b29b1e53b622c2eb60e..0742c865296bad5754c074afb88a6ef08eea8a20 100644 (file)
@@ -8,34 +8,32 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <sys/mman.h>
-#include <unistd.h>
+#include "consumer-stream.hpp"
 
 #include <common/common.hpp>
 #include <common/consumer/consumer-timer.hpp>
-#include <common/consumer/consumer-timer.hpp>
-#include <common/consumer/consumer.hpp>
 #include <common/consumer/consumer.hpp>
 #include <common/consumer/metadata-bucket.hpp>
-#include <common/consumer/metadata-bucket.hpp>
 #include <common/index/index.hpp>
 #include <common/kernel-consumer/kernel-consumer.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
 #include <common/macros.hpp>
 #include <common/relayd/relayd.hpp>
+#include <common/urcu.hpp>
 #include <common/ust-consumer/ust-consumer.hpp>
 #include <common/utils.hpp>
 
-#include "consumer-stream.hpp"
+#include <fcntl.h>
+#include <inttypes.h>
+#include <sys/mman.h>
+#include <unistd.h>
 
 /*
  * RCU call to free stream. MUST only be used with call_rcu().
  */
 static void free_stream_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_u64 *node =
-               lttng::utils::container_of(head, &lttng_ht_node_u64::head);
+       struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
        struct lttng_consumer_stream *stream =
                lttng::utils::container_of(node, &lttng_consumer_stream::node);
 
@@ -81,7 +79,7 @@ static void consumer_stream_metadata_assert_locked_all(struct lttng_consumer_str
 
 /* Only used for data streams. */
 static int consumer_stream_update_stats(struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuf)
+                                       const struct stream_subbuffer *subbuf)
 {
        int ret = 0;
        uint64_t sequence_number;
@@ -103,13 +101,12 @@ static int consumer_stream_update_stats(struct lttng_consumer_stream *stream,
        if (stream->last_sequence_number == -1ULL) {
                stream->last_sequence_number = sequence_number;
        } else if (sequence_number > stream->last_sequence_number) {
-               stream->chan->lost_packets += sequence_number -
-                               stream->last_sequence_number - 1;
+               stream->chan->lost_packets += sequence_number - stream->last_sequence_number - 1;
        } else {
                /* seq <= last_sequence_number */
-               ERR("Sequence number inconsistent : prev = %" PRIu64
-                   ", current = %" PRIu64,
-                               stream->last_sequence_number, sequence_number);
+               ERR("Sequence number inconsistent : prev = %" PRIu64 ", current = %" PRIu64,
+                   stream->last_sequence_number,
+                   sequence_number);
                ret = -1;
                goto end;
        }
@@ -120,13 +117,10 @@ static int consumer_stream_update_stats(struct lttng_consumer_stream *stream,
                 * Overflow has occurred. We assume only one wrap-around
                 * has occurred.
                 */
-               stream->chan->discarded_events +=
-                               (1ULL << (CAA_BITS_PER_LONG - 1)) -
-                               stream->last_discarded_events +
-                               discarded_events;
+               stream->chan->discarded_events += (1ULL << (CAA_BITS_PER_LONG - 1)) -
+                       stream->last_discarded_events + discarded_events;
        } else {
-               stream->chan->discarded_events += discarded_events -
-                                                 stream->last_discarded_events;
+               stream->chan->discarded_events += discarded_events - stream->last_discarded_events;
        }
        stream->last_discarded_events = discarded_events;
        ret = 0;
@@ -135,40 +129,37 @@ end:
        return ret;
 }
 
-static
-void ctf_packet_index_populate(struct ctf_packet_index *index,
-               off_t offset, const struct stream_subbuffer *subbuffer)
+static void ctf_packet_index_populate(struct ctf_packet_index *index,
+                                     off_t offset,
+                                     const struct stream_subbuffer *subbuffer)
 {
        *index = (typeof(*index)){
                .offset = htobe64(offset),
                .packet_size = htobe64(subbuffer->info.data.packet_size),
                .content_size = htobe64(subbuffer->info.data.content_size),
-               .timestamp_begin = htobe64(
-                               subbuffer->info.data.timestamp_begin),
-               .timestamp_end = htobe64(
-                               subbuffer->info.data.timestamp_end),
-               .events_discarded = htobe64(
-                               subbuffer->info.data.events_discarded),
+               .timestamp_begin = htobe64(subbuffer->info.data.timestamp_begin),
+               .timestamp_end = htobe64(subbuffer->info.data.timestamp_end),
+               .events_discarded = htobe64(subbuffer->info.data.events_discarded),
                .stream_id = htobe64(subbuffer->info.data.stream_id),
-               .stream_instance_id = htobe64(
-                               subbuffer->info.data.stream_instance_id.is_set ?
-                               subbuffer->info.data.stream_instance_id.value : -1ULL),
-               .packet_seq_num = htobe64(
-                               subbuffer->info.data.sequence_number.is_set ?
-                               subbuffer->info.data.sequence_number.value : -1ULL),
+               .stream_instance_id =
+                       htobe64(subbuffer->info.data.stream_instance_id.is_set ?
+                                       subbuffer->info.data.stream_instance_id.value :
+                                       -1ULL),
+               .packet_seq_num = htobe64(subbuffer->info.data.sequence_number.is_set ?
+                                                 subbuffer->info.data.sequence_number.value :
+                                                 -1ULL),
        };
 }
 
-static ssize_t consumer_stream_consume_mmap(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer)
+static ssize_t consumer_stream_consume_mmap(struct lttng_consumer_local_data *ctx
+                                           __attribute__((unused)),
+                                           struct lttng_consumer_stream *stream,
+                                           const struct stream_subbuffer *subbuffer)
 {
        const unsigned long padding_size =
-                       subbuffer->info.data.padded_subbuf_size -
-                       subbuffer->info.data.subbuf_size;
+               subbuffer->info.data.padded_subbuf_size - subbuffer->info.data.subbuf_size;
        const ssize_t written_bytes = lttng_consumer_on_read_subbuffer_mmap(
-                       stream, &subbuffer->buffer.buffer, padding_size);
+               stream, &subbuffer->buffer.buffer, padding_size);
 
        if (stream->net_seq_idx == -1ULL) {
                /*
@@ -177,8 +168,8 @@ static ssize_t consumer_stream_consume_mmap(
                 */
                if (written_bytes != subbuffer->info.data.padded_subbuf_size) {
                        DBG("Failed to write the entire padded subbuffer on disk (written_bytes: %zd, padded subbuffer size %lu)",
-                                       written_bytes,
-                                       subbuffer->info.data.padded_subbuf_size);
+                           written_bytes,
+                           subbuffer->info.data.padded_subbuf_size);
                }
        } else {
                /*
@@ -187,8 +178,8 @@ static ssize_t consumer_stream_consume_mmap(
                 */
                if (written_bytes != subbuffer->info.data.subbuf_size) {
                        DBG("Failed to write only the subbuffer over the network (written_bytes: %zd, subbuffer size %lu)",
-                                       written_bytes,
-                                       subbuffer->info.data.subbuf_size);
+                           written_bytes,
+                           subbuffer->info.data.subbuf_size);
                }
        }
 
@@ -203,18 +194,17 @@ static ssize_t consumer_stream_consume_mmap(
        return written_bytes;
 }
 
-static ssize_t consumer_stream_consume_splice(
-               struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer)
+static ssize_t consumer_stream_consume_splice(struct lttng_consumer_local_data *ctx,
+                                             struct lttng_consumer_stream *stream,
+                                             const struct stream_subbuffer *subbuffer)
 {
        const ssize_t written_bytes = lttng_consumer_on_read_subbuffer_splice(
-                       ctx, stream, subbuffer->info.data.padded_subbuf_size, 0);
+               ctx, stream, subbuffer->info.data.padded_subbuf_size, 0);
 
        if (written_bytes != subbuffer->info.data.padded_subbuf_size) {
                DBG("Failed to write the entire padded subbuffer (written_bytes: %zd, padded subbuffer size %lu)",
-                               written_bytes,
-                               subbuffer->info.data.padded_subbuf_size);
+                   written_bytes,
+                   subbuffer->info.data.padded_subbuf_size);
        }
 
        /*
@@ -228,10 +218,9 @@ static ssize_t consumer_stream_consume_splice(
        return written_bytes;
 }
 
-static int consumer_stream_send_index(
-               struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer,
-               struct lttng_consumer_local_data *ctx __attribute__((unused)))
+static int consumer_stream_send_index(struct lttng_consumer_stream *stream,
+                                     const struct stream_subbuffer *subbuffer,
+                                     struct lttng_consumer_local_data *ctx __attribute__((unused)))
 {
        off_t packet_offset = 0;
        struct ctf_packet_index index = {};
@@ -241,8 +230,7 @@ static int consumer_stream_send_index(
         * effect this sub-buffer from the offset.
         */
        if (stream->net_seq_idx == (uint64_t) -1ULL) {
-               packet_offset = stream->out_fd_offset -
-                               subbuffer->info.data.padded_subbuf_size;
+               packet_offset = stream->out_fd_offset - subbuffer->info.data.padded_subbuf_size;
        }
 
        ctf_packet_index_populate(&index, packet_offset, subbuffer);
@@ -256,7 +244,7 @@ static int consumer_stream_send_index(
  * indicating that there is no metadata available for that stream.
  */
 static int do_sync_metadata(struct lttng_consumer_stream *metadata,
-               struct lttng_consumer_local_data *ctx)
+                           struct lttng_consumer_local_data *ctx)
 {
        int ret;
        enum sync_metadata_status status;
@@ -373,11 +361,10 @@ end_unlock_mutex:
  *
  * Return 0 on success or else a negative value.
  */
-int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx,
-               uint64_t session_id)
+int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx, uint64_t session_id)
 {
        int ret;
-       struct lttng_consumer_stream *stream = NULL;
+       struct lttng_consumer_stream *stream = nullptr;
        struct lttng_ht_iter iter;
        struct lttng_ht *ht;
 
@@ -386,13 +373,18 @@ int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx,
        /* Ease our life a bit. */
        ht = the_consumer_data.stream_list_ht;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Search the metadata associated with the session id of the given stream. */
 
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&session_id, lttng_ht_seed), ht->match_fct,
-                       &session_id, &iter.iter, stream, node_session_id.node) {
+                                         ht->hash_fct(&session_id, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &session_id,
+                                         &iter.iter,
+                                         stream,
+                                         node_session_id.node)
+       {
                if (!stream->metadata_flag) {
                        continue;
                }
@@ -410,14 +402,12 @@ int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx,
        ret = 0;
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-static int consumer_stream_sync_metadata_index(
-               struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer,
-               struct lttng_consumer_local_data *ctx)
+static int consumer_stream_sync_metadata_index(struct lttng_consumer_stream *stream,
+                                              const struct stream_subbuffer *subbuffer,
+                                              struct lttng_consumer_local_data *ctx)
 {
        bool missed_metadata_flush;
        int ret;
@@ -469,17 +459,15 @@ end:
  * of the metadata stream in the kernel. If it was updated, set the reset flag
  * on the stream.
  */
-static
-int metadata_stream_check_version(struct lttng_consumer_stream *stream,
-       const struct stream_subbuffer *subbuffer)
+static int metadata_stream_check_version(struct lttng_consumer_stream *stream,
+                                        const struct stream_subbuffer *subbuffer)
 {
        if (stream->metadata_version == subbuffer->info.metadata.version) {
                goto end;
        }
 
        DBG("New metadata version detected");
-       consumer_stream_metadata_set_version(stream,
-                       subbuffer->info.metadata.version);
+       consumer_stream_metadata_set_version(stream, subbuffer->info.metadata.version);
 
        if (stream->read_subbuffer_ops.reset_metadata) {
                stream->read_subbuffer_ops.reset_metadata(stream);
@@ -489,9 +477,7 @@ end:
        return 0;
 }
 
-static
-bool stream_is_rotating_to_null_chunk(
-               const struct lttng_consumer_stream *stream)
+static bool stream_is_rotating_to_null_chunk(const struct lttng_consumer_stream *stream)
 {
        bool rotating_to_null_chunk = false;
 
@@ -500,16 +486,15 @@ bool stream_is_rotating_to_null_chunk(
                goto end;
        }
 
-       if (stream->trace_chunk == stream->chan->trace_chunk ||
-                       !stream->chan->trace_chunk) {
+       if (stream->trace_chunk == stream->chan->trace_chunk || !stream->chan->trace_chunk) {
                rotating_to_null_chunk = true;
        }
 end:
        return rotating_to_null_chunk;
 }
 
-enum consumer_stream_open_packet_status consumer_stream_open_packet(
-               struct lttng_consumer_stream *stream)
+enum consumer_stream_open_packet_status
+consumer_stream_open_packet(struct lttng_consumer_stream *stream)
 {
        int ret;
        enum consumer_stream_open_packet_status status;
@@ -518,30 +503,32 @@ enum consumer_stream_open_packet_status consumer_stream_open_packet(
        ret = lttng_consumer_sample_snapshot_positions(stream);
        if (ret < 0) {
                ERR("Failed to snapshot positions before post-rotation empty packet flush: stream id = %" PRIu64
-                               ", channel name = %s, session id = %" PRIu64,
-                               stream->key, stream->chan->name,
-                               stream->chan->session_id);
+                   ", channel name = %s, session id = %" PRIu64,
+                   stream->key,
+                   stream->chan->name,
+                   stream->chan->session_id);
                status = CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR;
                goto end;
        }
 
-       ret = lttng_consumer_get_produced_snapshot(
-                       stream, &produced_pos_before);
+       ret = lttng_consumer_get_produced_snapshot(stream, &produced_pos_before);
        if (ret < 0) {
                ERR("Failed to read produced position before post-rotation empty packet flush: stream id = %" PRIu64
-                               ", channel name = %s, session id = %" PRIu64,
-                               stream->key, stream->chan->name,
-                               stream->chan->session_id);
+                   ", channel name = %s, session id = %" PRIu64,
+                   stream->key,
+                   stream->chan->name,
+                   stream->chan->session_id);
                status = CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR;
                goto end;
        }
 
-       ret = consumer_stream_flush_buffer(stream, 0);
+       ret = consumer_stream_flush_buffer(stream, false);
        if (ret) {
                ERR("Failed to flush an empty packet at rotation point: stream id = %" PRIu64
-                               ", channel name = %s, session id = %" PRIu64,
-                               stream->key, stream->chan->name,
-                               stream->chan->session_id);
+                   ", channel name = %s, session id = %" PRIu64,
+                   stream->key,
+                   stream->chan->name,
+                   stream->chan->session_id);
                status = CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR;
                goto end;
        }
@@ -549,9 +536,10 @@ enum consumer_stream_open_packet_status consumer_stream_open_packet(
        ret = lttng_consumer_sample_snapshot_positions(stream);
        if (ret < 0) {
                ERR("Failed to snapshot positions after post-rotation empty packet flush: stream id = %" PRIu64
-                               ", channel name = %s, session id = %" PRIu64,
-                               stream->key, stream->chan->name,
-                               stream->chan->session_id);
+                   ", channel name = %s, session id = %" PRIu64,
+                   stream->key,
+                   stream->chan->name,
+                   stream->chan->session_id);
                status = CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR;
                goto end;
        }
@@ -559,9 +547,10 @@ enum consumer_stream_open_packet_status consumer_stream_open_packet(
        ret = lttng_consumer_get_produced_snapshot(stream, &produced_pos_after);
        if (ret < 0) {
                ERR("Failed to read produced position after post-rotation empty packet flush: stream id = %" PRIu64
-                               ", channel name = %s, session id = %" PRIu64,
-                               stream->key, stream->chan->name,
-                               stream->chan->session_id);
+                   ", channel name = %s, session id = %" PRIu64,
+                   stream->key,
+                   stream->chan->name,
+                   stream->chan->session_id);
                status = CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR;
                goto end;
        }
@@ -571,8 +560,8 @@ enum consumer_stream_open_packet_status consumer_stream_open_packet(
         * positons before and after the flush.
         */
        status = produced_pos_before != produced_pos_after ?
-                       CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED :
-                       CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE;
+               CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED :
+               CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE;
        if (status == CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED) {
                stream->opened_packet_in_current_trace_chunk = true;
        }
@@ -589,25 +578,26 @@ end:
  * ring-buffer. In that case, a second attempt is performed after consuming
  * a packet since that will have freed enough space in the ring-buffer.
  */
-static
-int post_consume_open_new_packet(struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer __attribute__((unused)),
-               struct lttng_consumer_local_data *ctx __attribute__((unused)))
+static int post_consume_open_new_packet(struct lttng_consumer_stream *stream,
+                                       const struct stream_subbuffer *subbuffer
+                                       __attribute__((unused)),
+                                       struct lttng_consumer_local_data *ctx
+                                       __attribute__((unused)))
 {
        int ret = 0;
 
-       if (!stream->opened_packet_in_current_trace_chunk &&
-                       stream->trace_chunk &&
-                       !stream_is_rotating_to_null_chunk(stream)) {
+       if (!stream->opened_packet_in_current_trace_chunk && stream->trace_chunk &&
+           !stream_is_rotating_to_null_chunk(stream)) {
                const enum consumer_stream_open_packet_status status =
-                               consumer_stream_open_packet(stream);
+                       consumer_stream_open_packet(stream);
 
                switch (status) {
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
                        DBG("Opened a packet after consuming a packet rotation: stream id = %" PRIu64
-                                       ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
+                           ", channel name = %s, session id = %" PRIu64,
+                           stream->key,
+                           stream->chan->name,
+                           stream->chan->session_id);
                        stream->opened_packet_in_current_trace_chunk = true;
                        break;
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
@@ -618,9 +608,10 @@ int post_consume_open_new_packet(struct lttng_consumer_stream *stream,
                         * anyhow.
                         */
                        DBG("No space left to open a packet after consuming a packet: stream id = %" PRIu64
-                                       ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
+                           ", channel name = %s, session id = %" PRIu64,
+                           stream->key,
+                           stream->chan->name,
+                           stream->chan->session_id);
                        stream->opened_packet_in_current_trace_chunk = true;
                        break;
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
@@ -638,31 +629,29 @@ end:
        return ret;
 }
 
-struct lttng_consumer_stream *consumer_stream_create(
-               struct lttng_consumer_channel *channel,
-               uint64_t channel_key,
-               uint64_t stream_key,
-               const char *channel_name,
-               uint64_t relayd_id,
-               uint64_t session_id,
-               struct lttng_trace_chunk *trace_chunk,
-               int cpu,
-               int *alloc_ret,
-               enum consumer_channel_type type,
-               unsigned int monitor)
+struct lttng_consumer_stream *consumer_stream_create(struct lttng_consumer_channel *channel,
+                                                    uint64_t channel_key,
+                                                    uint64_t stream_key,
+                                                    const char *channel_name,
+                                                    uint64_t relayd_id,
+                                                    uint64_t session_id,
+                                                    struct lttng_trace_chunk *trace_chunk,
+                                                    int cpu,
+                                                    int *alloc_ret,
+                                                    enum consumer_channel_type type,
+                                                    unsigned int monitor)
 {
        int ret;
        struct lttng_consumer_stream *stream;
+       lttng::urcu::read_lock_guard read_lock;
 
        stream = zmalloc<lttng_consumer_stream>();
-       if (stream == NULL) {
+       if (stream == nullptr) {
                PERROR("malloc struct lttng_consumer_stream");
                ret = -ENOMEM;
                goto end;
        }
 
-       rcu_read_lock();
-
        if (trace_chunk && !lttng_trace_chunk_get(trace_chunk)) {
                ERR("Failed to acquire trace chunk reference during the creation of a stream");
                ret = -1;
@@ -680,13 +669,13 @@ struct lttng_consumer_stream *consumer_stream_create(
        stream->session_id = session_id;
        stream->monitor = monitor;
        stream->endpoint_status = CONSUMER_ENDPOINT_ACTIVE;
-       stream->index_file = NULL;
+       stream->index_file = nullptr;
        stream->last_sequence_number = -1ULL;
        stream->rotate_position = -1ULL;
        /* Buffer is created with an open packet. */
        stream->opened_packet_in_current_trace_chunk = true;
-       pthread_mutex_init(&stream->lock, NULL);
-       pthread_mutex_init(&stream->metadata_timer_lock, NULL);
+       pthread_mutex_init(&stream->lock, nullptr);
+       pthread_mutex_init(&stream->metadata_timer_lock, nullptr);
 
        /* If channel is the metadata, flag this stream as metadata. */
        if (type == CONSUMER_CHANNEL_TYPE_METADATA) {
@@ -694,12 +683,11 @@ struct lttng_consumer_stream *consumer_stream_create(
                /* Metadata is flat out. */
                strncpy(stream->name, DEFAULT_METADATA_NAME, sizeof(stream->name));
                /* Live rendez-vous point. */
-               pthread_cond_init(&stream->metadata_rdv, NULL);
-               pthread_mutex_init(&stream->metadata_rdv_lock, NULL);
+               pthread_cond_init(&stream->metadata_rdv, nullptr);
+               pthread_mutex_init(&stream->metadata_rdv_lock, nullptr);
        } else {
                /* Format stream name to <channel_name>_<cpu_number> */
-               ret = snprintf(stream->name, sizeof(stream->name), "%s_%d",
-                               channel_name, cpu);
+               ret = snprintf(stream->name, sizeof(stream->name), "%s_%d", channel_name, cpu);
                if (ret < 0) {
                        PERROR("snprintf stream name");
                        goto error;
@@ -730,69 +718,58 @@ struct lttng_consumer_stream *consumer_stream_create(
        /* Init session id node with the stream session id */
        lttng_ht_node_init_u64(&stream->node_session_id, stream->session_id);
 
-       DBG3("Allocated stream %s (key %" PRIu64 ", chan_key %" PRIu64
-                       " relayd_id %" PRIu64 ", session_id %" PRIu64,
-                       stream->name, stream->key, channel_key,
-                       stream->net_seq_idx, stream->session_id);
-
-       rcu_read_unlock();
+       DBG3("Allocated stream %s (key %" PRIu64 ", chan_key %" PRIu64 " relayd_id %" PRIu64
+            ", session_id %" PRIu64,
+            stream->name,
+            stream->key,
+            channel_key,
+            stream->net_seq_idx,
+            stream->session_id);
 
-       lttng_dynamic_array_init(&stream->read_subbuffer_ops.post_consume_cbs,
-                       sizeof(post_consume_cb), NULL);
+       lttng_dynamic_array_init(
+               &stream->read_subbuffer_ops.post_consume_cbs, sizeof(post_consume_cb), nullptr);
 
        if (type == CONSUMER_CHANNEL_TYPE_METADATA) {
-               stream->read_subbuffer_ops.lock =
-                               consumer_stream_metadata_lock_all;
-               stream->read_subbuffer_ops.unlock =
-                               consumer_stream_metadata_unlock_all;
+               stream->read_subbuffer_ops.lock = consumer_stream_metadata_lock_all;
+               stream->read_subbuffer_ops.unlock = consumer_stream_metadata_unlock_all;
                stream->read_subbuffer_ops.assert_locked =
-                               consumer_stream_metadata_assert_locked_all;
-               stream->read_subbuffer_ops.pre_consume_subbuffer =
-                               metadata_stream_check_version;
+                       consumer_stream_metadata_assert_locked_all;
+               stream->read_subbuffer_ops.pre_consume_subbuffer = metadata_stream_check_version;
        } else {
                const post_consume_cb post_consume_index_op = channel->is_live ?
-                               consumer_stream_sync_metadata_index :
-                               consumer_stream_send_index;
-               const post_consume_cb post_consume_open_new_packet_ =
-                               post_consume_open_new_packet;
-
-               ret = lttng_dynamic_array_add_element(
-                               &stream->read_subbuffer_ops.post_consume_cbs,
-                               &post_consume_index_op);
+                       consumer_stream_sync_metadata_index :
+                       consumer_stream_send_index;
+               const post_consume_cb post_consume_open_new_packet_ = post_consume_open_new_packet;
+
+               ret = lttng_dynamic_array_add_element(&stream->read_subbuffer_ops.post_consume_cbs,
+                                                     &post_consume_index_op);
                if (ret) {
                        PERROR("Failed to add `send index` callback to stream's post consumption callbacks");
                        goto error;
                }
 
-               ret = lttng_dynamic_array_add_element(
-                               &stream->read_subbuffer_ops.post_consume_cbs,
-                               &post_consume_open_new_packet_);
+               ret = lttng_dynamic_array_add_element(&stream->read_subbuffer_ops.post_consume_cbs,
+                                                     &post_consume_open_new_packet_);
                if (ret) {
                        PERROR("Failed to add `open new packet` callback to stream's post consumption callbacks");
                        goto error;
                }
 
                stream->read_subbuffer_ops.lock = consumer_stream_data_lock_all;
-               stream->read_subbuffer_ops.unlock =
-                               consumer_stream_data_unlock_all;
-               stream->read_subbuffer_ops.assert_locked =
-                               consumer_stream_data_assert_locked_all;
-               stream->read_subbuffer_ops.pre_consume_subbuffer =
-                               consumer_stream_update_stats;
+               stream->read_subbuffer_ops.unlock = consumer_stream_data_unlock_all;
+               stream->read_subbuffer_ops.assert_locked = consumer_stream_data_assert_locked_all;
+               stream->read_subbuffer_ops.pre_consume_subbuffer = consumer_stream_update_stats;
        }
 
        if (channel->output == CONSUMER_CHANNEL_MMAP) {
-               stream->read_subbuffer_ops.consume_subbuffer =
-                               consumer_stream_consume_mmap;
+               stream->read_subbuffer_ops.consume_subbuffer = consumer_stream_consume_mmap;
        } else {
-               stream->read_subbuffer_ops.consume_subbuffer =
-                               consumer_stream_consume_splice;
+               stream->read_subbuffer_ops.consume_subbuffer = consumer_stream_consume_splice;
        }
 
        return stream;
 
 error:
-       rcu_read_unlock();
        lttng_trace_chunk_put(stream->trace_chunk);
        lttng_dynamic_array_reset(&stream->read_subbuffer_ops.post_consume_cbs);
        free(stream);
@@ -800,7 +777,7 @@ end:
        if (alloc_ret) {
                *alloc_ret = ret;
        }
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -811,7 +788,7 @@ end:
  * a hash table before calling this.
  */
 void consumer_stream_relayd_close(struct lttng_consumer_stream *stream,
-               struct consumer_relayd_sock_pair *relayd)
+                                 struct consumer_relayd_sock_pair *relayd)
 {
        int ret;
 
@@ -825,18 +802,17 @@ void consumer_stream_relayd_close(struct lttng_consumer_stream *stream,
 
        /* Closing streams requires to lock the control socket. */
        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-       ret = relayd_send_close_stream(&relayd->control_sock,
-                       stream->relayd_stream_id,
-                       stream->next_net_seq_num - 1);
+       ret = relayd_send_close_stream(
+               &relayd->control_sock, stream->relayd_stream_id, stream->next_net_seq_num - 1);
        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
        if (ret < 0) {
-               ERR("Relayd send close stream failed. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
+               ERR("Relayd send close stream failed. Cleaning up relayd %" PRIu64 ".",
+                   relayd->net_seq_idx);
                lttng_consumer_cleanup_relayd(relayd);
        }
 
        /* Both conditions are met, we destroy the relayd. */
-       if (uatomic_read(&relayd->refcount) == 0 &&
-                       uatomic_read(&relayd->destroy_flag)) {
+       if (uatomic_read(&relayd->refcount) == 0 && uatomic_read(&relayd->destroy_flag)) {
                consumer_destroy_relayd(relayd);
        }
        stream->net_seq_idx = (uint64_t) -1ULL;
@@ -850,87 +826,37 @@ void consumer_stream_relayd_close(struct lttng_consumer_stream *stream,
  * The consumer data lock MUST be acquired.
  * The stream lock MUST be acquired.
  */
-void consumer_stream_close(struct lttng_consumer_stream *stream)
+void consumer_stream_close_output(struct lttng_consumer_stream *stream)
 {
-       int ret;
        struct consumer_relayd_sock_pair *relayd;
 
        LTTNG_ASSERT(stream);
 
-       switch (the_consumer_data.type) {
-       case LTTNG_CONSUMER_KERNEL:
-               if (stream->mmap_base != NULL) {
-                       ret = munmap(stream->mmap_base, stream->mmap_len);
-                       if (ret != 0) {
-                               PERROR("munmap");
-                       }
-               }
-
-               if (stream->wait_fd >= 0) {
-                       ret = close(stream->wait_fd);
-                       if (ret) {
-                               PERROR("close");
-                       }
-                       stream->wait_fd = -1;
-               }
-               if (stream->chan->output == CONSUMER_CHANNEL_SPLICE) {
-                       utils_close_pipe(stream->splice_pipe);
-               }
-               break;
-       case LTTNG_CONSUMER32_UST:
-       case LTTNG_CONSUMER64_UST:
-       {
-               /*
-                * Special case for the metadata since the wait fd is an internal pipe
-                * polled in the metadata thread.
-                */
-               if (stream->metadata_flag && stream->chan->monitor) {
-                       int rpipe = stream->ust_metadata_poll_pipe[0];
-
-                       /*
-                        * This will stop the channel timer if one and close the write side
-                        * of the metadata poll pipe.
-                        */
-                       lttng_ustconsumer_close_metadata(stream->chan);
-                       if (rpipe >= 0) {
-                               ret = close(rpipe);
-                               if (ret < 0) {
-                                       PERROR("closing metadata pipe read side");
-                               }
-                               stream->ust_metadata_poll_pipe[0] = -1;
-                       }
-               }
-               break;
-       }
-       default:
-               ERR("Unknown consumer_data type");
-               abort();
-       }
-
        /* Close output fd. Could be a socket or local file at this point. */
        if (stream->out_fd >= 0) {
-               ret = close(stream->out_fd);
+               const auto ret = close(stream->out_fd);
                if (ret) {
-                       PERROR("close");
+                       PERROR("Failed to close stream output file descriptor");
                }
+
                stream->out_fd = -1;
        }
 
        if (stream->index_file) {
                lttng_index_file_put(stream->index_file);
-               stream->index_file = NULL;
+               stream->index_file = nullptr;
        }
 
        lttng_trace_chunk_put(stream->trace_chunk);
-       stream->trace_chunk = NULL;
+       stream->trace_chunk = nullptr;
 
        /* Check and cleanup relayd if needed. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        relayd = consumer_find_relayd(stream->net_seq_idx);
-       if (relayd != NULL) {
+       if (relayd != nullptr) {
                consumer_stream_relayd_close(stream, relayd);
+               stream->net_seq_idx = -1ULL;
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -939,8 +865,7 @@ void consumer_stream_close(struct lttng_consumer_stream *stream)
  * The consumer data lock MUST be acquired.
  * The stream lock MUST be acquired.
  */
-void consumer_stream_delete(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht)
+void consumer_stream_delete(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
 {
        int ret;
        struct lttng_ht_iter iter;
@@ -949,7 +874,7 @@ void consumer_stream_delete(struct lttng_consumer_stream *stream,
        /* Should NEVER be called not in monitor mode. */
        LTTNG_ASSERT(stream->chan->monitor);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (ht) {
                iter.iter.node = &stream->node.node;
@@ -972,8 +897,6 @@ void consumer_stream_delete(struct lttng_consumer_stream *stream,
        /* See the previous ht del on why we ignore the returned value. */
        (void) lttng_ht_del(the_consumer_data.stream_list_ht, &iter);
 
-       rcu_read_unlock();
-
        if (!stream->metadata_flag) {
                /* Decrement the stream count of the global consumer data. */
                LTTNG_ASSERT(the_consumer_data.stream_count > 0);
@@ -1001,9 +924,54 @@ void consumer_stream_destroy_buffers(struct lttng_consumer_stream *stream)
 
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
+               if (stream->mmap_base != nullptr) {
+                       const auto ret = munmap(stream->mmap_base, stream->mmap_len);
+
+                       if (ret != 0) {
+                               PERROR("munmap");
+                       }
+               }
+
+               if (stream->wait_fd >= 0) {
+                       const auto ret = close(stream->wait_fd);
+
+                       if (ret) {
+                               PERROR("close");
+                       }
+
+                       stream->wait_fd = -1;
+               }
+
+               if (stream->chan->output == CONSUMER_CHANNEL_SPLICE) {
+                       utils_close_pipe(stream->splice_pipe);
+               }
+
                break;
        case LTTNG_CONSUMER32_UST:
        case LTTNG_CONSUMER64_UST:
+               /*
+                * Special case for the metadata since the wait fd is an internal pipe
+                * polled in the metadata thread.
+                */
+               if (stream->metadata_flag && stream->chan->monitor) {
+                       const auto rpipe = stream->ust_metadata_poll_pipe[0];
+
+                       /*
+                        * This will stop the channel timer if one and close the write side
+                        * of the metadata poll pipe.
+                        */
+                       lttng_ustconsumer_close_metadata(stream->chan);
+                       if (rpipe >= 0) {
+                               const auto ret = close(rpipe);
+
+                               if (ret < 0) {
+                                       PERROR("closing metadata pipe read side");
+                               }
+
+                               stream->ust_metadata_poll_pipe[0] = -1;
+                       }
+               }
+
                lttng_ustconsumer_del_stream(stream);
                break;
        default:
@@ -1024,24 +992,23 @@ static void destroy_close_stream(struct lttng_consumer_stream *stream)
        /* Destroy tracer buffers of the stream. */
        consumer_stream_destroy_buffers(stream);
        /* Close down everything including the relayd if one. */
-       consumer_stream_close(stream);
+       consumer_stream_close_output(stream);
 }
 
 /*
  * Decrement the stream's channel refcount and if down to 0, return the channel
  * pointer so it can be destroyed by the caller or NULL if not.
  */
-static struct lttng_consumer_channel *unref_channel(
-               struct lttng_consumer_stream *stream)
+static struct lttng_consumer_channel *unref_channel(struct lttng_consumer_stream *stream)
 {
-       struct lttng_consumer_channel *free_chan = NULL;
+       struct lttng_consumer_channel *free_chan = nullptr;
 
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->chan);
 
        /* Update refcount of channel and see if we need to destroy it. */
-       if (!uatomic_sub_return(&stream->chan->refcount, 1)
-                       && !uatomic_read(&stream->chan->nb_init_stream_left)) {
+       if (!uatomic_sub_return(&stream->chan->refcount, 1) &&
+           !uatomic_read(&stream->chan->nb_init_stream_left)) {
                free_chan = stream->chan;
        }
 
@@ -1056,8 +1023,7 @@ static struct lttng_consumer_channel *unref_channel(
  * This MUST be called WITHOUT the consumer data and stream lock acquired if
  * the stream is in _monitor_ mode else it does not matter.
  */
-void consumer_stream_destroy(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht)
+void consumer_stream_destroy(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
 {
        LTTNG_ASSERT(stream);
 
@@ -1065,7 +1031,7 @@ void consumer_stream_destroy(struct lttng_consumer_stream *stream,
 
        /* Stream is in monitor mode. */
        if (stream->monitor) {
-               struct lttng_consumer_channel *free_chan = NULL;
+               struct lttng_consumer_channel *free_chan = nullptr;
 
                /*
                 * This means that the stream was successfully removed from the streams
@@ -1080,7 +1046,6 @@ void consumer_stream_destroy(struct lttng_consumer_stream *stream,
                        /* Remove every reference of the stream in the consumer. */
                        consumer_stream_delete(stream, ht);
 
-
                        destroy_close_stream(stream);
 
                        /* Update channel's refcount of the stream. */
@@ -1110,7 +1075,7 @@ void consumer_stream_destroy(struct lttng_consumer_stream *stream,
 
        /* Free stream within a RCU call. */
        lttng_trace_chunk_put(stream->trace_chunk);
-       stream->trace_chunk = NULL;
+       stream->trace_chunk = nullptr;
        lttng_dynamic_array_reset(&stream->read_subbuffer_ops.post_consume_cbs);
        consumer_stream_free(stream);
 }
@@ -1121,34 +1086,38 @@ void consumer_stream_destroy(struct lttng_consumer_stream *stream,
  * Return 0 on success or else a negative value.
  */
 int consumer_stream_write_index(struct lttng_consumer_stream *stream,
-               struct ctf_packet_index *element)
+                               struct ctf_packet_index *element)
 {
        int ret;
 
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(element);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        if (stream->net_seq_idx != (uint64_t) -1ULL) {
                struct consumer_relayd_sock_pair *relayd;
                relayd = consumer_find_relayd(stream->net_seq_idx);
                if (relayd) {
                        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-                       ret = relayd_send_index(&relayd->control_sock, element,
-                               stream->relayd_stream_id, stream->next_net_seq_num - 1);
+                       ret = relayd_send_index(&relayd->control_sock,
+                                               element,
+                                               stream->relayd_stream_id,
+                                               stream->next_net_seq_num - 1);
                        if (ret < 0) {
                                /*
                                 * Communication error with lttng-relayd,
                                 * perform cleanup now
                                 */
-                               ERR("Relayd send index failed. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
+                               ERR("Relayd send index failed. Cleaning up relayd %" PRIu64 ".",
+                                   relayd->net_seq_idx);
                                lttng_consumer_cleanup_relayd(relayd);
                                ret = -1;
                        }
                        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                } else {
                        ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't write index.",
-                                       stream->key, stream->net_seq_idx);
+                           stream->key,
+                           stream->net_seq_idx);
                        ret = -1;
                }
        } else {
@@ -1163,12 +1132,10 @@ int consumer_stream_write_index(struct lttng_consumer_stream *stream,
        }
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
-int consumer_stream_create_output_files(struct lttng_consumer_stream *stream,
-               bool create_index)
+int consumer_stream_create_output_files(struct lttng_consumer_stream *stream, bool create_index)
 {
        int ret;
        enum lttng_trace_chunk_status chunk_status;
@@ -1179,10 +1146,13 @@ int consumer_stream_create_output_files(struct lttng_consumer_stream *stream,
        ASSERT_LOCKED(stream->lock);
        LTTNG_ASSERT(stream->trace_chunk);
 
-       ret = utils_stream_file_path(stream->chan->pathname, stream->name,
-                       stream->chan->tracefile_size,
-                       stream->tracefile_count_current, NULL,
-                       stream_path, sizeof(stream_path));
+       ret = utils_stream_file_path(stream->chan->pathname,
+                                    stream->name,
+                                    stream->chan->tracefile_size,
+                                    stream->tracefile_count_current,
+                                    nullptr,
+                                    stream_path,
+                                    sizeof(stream_path));
        if (ret < 0) {
                goto end;
        }
@@ -1190,16 +1160,15 @@ int consumer_stream_create_output_files(struct lttng_consumer_stream *stream,
        if (stream->out_fd >= 0) {
                ret = close(stream->out_fd);
                if (ret < 0) {
-                       PERROR("Failed to close stream file \"%s\"",
-                                       stream->name);
+                       PERROR("Failed to close stream file \"%s\"", stream->name);
                        goto end;
                }
                stream->out_fd = -1;
        }
 
        DBG("Opening stream output file \"%s\"", stream_path);
-       chunk_status = lttng_trace_chunk_open_file(stream->trace_chunk, stream_path,
-                       flags, mode, &stream->out_fd, false);
+       chunk_status = lttng_trace_chunk_open_file(
+               stream->trace_chunk, stream_path, flags, mode, &stream->out_fd, false);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ERR("Failed to open stream file \"%s\"", stream->name);
                ret = -1;
@@ -1210,14 +1179,16 @@ int consumer_stream_create_output_files(struct lttng_consumer_stream *stream,
                if (stream->index_file) {
                        lttng_index_file_put(stream->index_file);
                }
-               chunk_status = lttng_index_file_create_from_trace_chunk(
-                               stream->trace_chunk,
-                               stream->chan->pathname,
-                               stream->name,
-                               stream->chan->tracefile_size,
-                               stream->tracefile_count_current,
-                               CTF_INDEX_MAJOR, CTF_INDEX_MINOR,
-                               false, &stream->index_file);
+               chunk_status =
+                       lttng_index_file_create_from_trace_chunk(stream->trace_chunk,
+                                                                stream->chan->pathname,
+                                                                stream->name,
+                                                                stream->chan->tracefile_size,
+                                                                stream->tracefile_count_current,
+                                                                CTF_INDEX_MAJOR,
+                                                                CTF_INDEX_MINOR,
+                                                                false,
+                                                                &stream->index_file);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret = -1;
                        goto end;
@@ -1237,8 +1208,7 @@ int consumer_stream_rotate_output_files(struct lttng_consumer_stream *stream)
 
        stream->tracefile_count_current++;
        if (stream->chan->tracefile_count > 0) {
-               stream->tracefile_count_current %=
-                               stream->chan->tracefile_count;
+               stream->tracefile_count_current %= stream->chan->tracefile_count;
        }
 
        DBG("Rotating output files of stream \"%s\"", stream->name);
@@ -1261,13 +1231,12 @@ bool consumer_stream_is_deleted(struct lttng_consumer_stream *stream)
        return cds_lfht_is_node_deleted(&stream->node.node);
 }
 
-static ssize_t metadata_bucket_flush(
-               const struct stream_subbuffer *buffer, void *data)
+static ssize_t metadata_bucket_flush(const struct stream_subbuffer *buffer, void *data)
 {
        ssize_t ret;
        struct lttng_consumer_stream *stream = (lttng_consumer_stream *) data;
 
-       ret = consumer_stream_consume_mmap(NULL, stream, buffer);
+       ret = consumer_stream_consume_mmap(nullptr, stream, buffer);
        if (ret < 0) {
                goto end;
        }
@@ -1275,10 +1244,10 @@ end:
        return ret;
 }
 
-static ssize_t metadata_bucket_consume(
-               struct lttng_consumer_local_data *unused __attribute__((unused)),
-               struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer)
+static ssize_t metadata_bucket_consume(struct lttng_consumer_local_data *unused
+                                      __attribute__((unused)),
+                                      struct lttng_consumer_stream *stream,
+                                      const struct stream_subbuffer *subbuffer)
 {
        ssize_t ret;
        enum metadata_bucket_status status;
@@ -1296,8 +1265,7 @@ static ssize_t metadata_bucket_consume(
        return ret;
 }
 
-int consumer_stream_enable_metadata_bucketization(
-               struct lttng_consumer_stream *stream)
+int consumer_stream_enable_metadata_bucketization(struct lttng_consumer_stream *stream)
 {
        int ret = 0;
 
@@ -1305,8 +1273,7 @@ int consumer_stream_enable_metadata_bucketization(
        LTTNG_ASSERT(!stream->metadata_bucket);
        LTTNG_ASSERT(stream->chan->output == CONSUMER_CHANNEL_MMAP);
 
-       stream->metadata_bucket = metadata_bucket_create(
-                       metadata_bucket_flush, stream);
+       stream->metadata_bucket = metadata_bucket_create(metadata_bucket_flush, stream);
        if (!stream->metadata_bucket) {
                ret = -1;
                goto end;
@@ -1317,8 +1284,8 @@ end:
        return ret;
 }
 
-void consumer_stream_metadata_set_version(
-               struct lttng_consumer_stream *stream, uint64_t new_version)
+void consumer_stream_metadata_set_version(struct lttng_consumer_stream *stream,
+                                         uint64_t new_version)
 {
        LTTNG_ASSERT(new_version > stream->metadata_version);
        stream->metadata_version = new_version;
@@ -1329,8 +1296,7 @@ void consumer_stream_metadata_set_version(
        }
 }
 
-int consumer_stream_flush_buffer(struct lttng_consumer_stream *stream,
-               bool producer_active)
+int consumer_stream_flush_buffer(struct lttng_consumer_stream *stream, bool producer_active)
 {
        int ret = 0;
 
index a8e5ddd5507b3a31ed7db90e50406a89ddab2dfe..97fbd145b1a95d0ac749b2a9157ec7f2dbaf09e8 100644 (file)
@@ -21,18 +21,17 @@ enum consumer_stream_open_packet_status {
  *
  * The channel lock MUST be acquired.
  */
-struct lttng_consumer_stream *consumer_stream_create(
-               struct lttng_consumer_channel *channel,
-               uint64_t channel_key,
-               uint64_t stream_key,
-               const char *channel_name,
-               uint64_t relayd_id,
-               uint64_t session_id,
-               struct lttng_trace_chunk *trace_chunk,
-               int cpu,
-               int *alloc_ret,
-               enum consumer_channel_type type,
-               unsigned int monitor);
+struct lttng_consumer_stream *consumer_stream_create(struct lttng_consumer_channel *channel,
+                                                    uint64_t channel_key,
+                                                    uint64_t stream_key,
+                                                    const char *channel_name,
+                                                    uint64_t relayd_id,
+                                                    uint64_t session_id,
+                                                    struct lttng_trace_chunk *trace_chunk,
+                                                    int cpu,
+                                                    int *alloc_ret,
+                                                    enum consumer_channel_type type,
+                                                    unsigned int monitor);
 
 /*
  * Close stream's file descriptors and, if needed, close stream also on the
@@ -41,7 +40,7 @@ struct lttng_consumer_stream *consumer_stream_create(
  * The stream lock MUST be acquired.
  * The consumer data lock MUST be acquired.
  */
-void consumer_stream_close(struct lttng_consumer_stream *stream);
+void consumer_stream_close_output(struct lttng_consumer_stream *stream);
 
 /*
  * Close stream on the relayd side. This call can destroy a relayd if the
@@ -51,15 +50,14 @@ void consumer_stream_close(struct lttng_consumer_stream *stream);
  * a hash table before calling this.
  */
 void consumer_stream_relayd_close(struct lttng_consumer_stream *stream,
-               struct consumer_relayd_sock_pair *relayd);
+                                 struct consumer_relayd_sock_pair *relayd);
 
 /*
  * Delete the stream from all possible hash tables.
  *
  * The consumer data lock MUST be acquired.
  */
-void consumer_stream_delete(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht);
+void consumer_stream_delete(struct lttng_consumer_stream *stream, struct lttng_ht *ht);
 
 /*
  * Free the given stream within a RCU call.
@@ -73,8 +71,7 @@ void consumer_stream_free(struct lttng_consumer_stream *stream);
  *
  * This MUST be called WITHOUT the consumer data and stream lock acquired.
  */
-void consumer_stream_destroy(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht);
+void consumer_stream_destroy(struct lttng_consumer_stream *stream, struct lttng_ht *ht);
 
 /*
  * Destroy the stream's buffers on the tracer side. This is also called in a
@@ -86,18 +83,16 @@ void consumer_stream_destroy_buffers(struct lttng_consumer_stream *stream);
  * Write index of a specific stream either on the relayd or local disk.
  */
 int consumer_stream_write_index(struct lttng_consumer_stream *stream,
-               struct ctf_packet_index *index);
+                               struct ctf_packet_index *index);
 
-int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx,
-               uint64_t session_id);
+int consumer_stream_sync_metadata(struct lttng_consumer_local_data *ctx, uint64_t session_id);
 
 /*
  * Create the output files of a local stream.
  *
  * This must be called with the channel's and the stream's lock held.
  */
-int consumer_stream_create_output_files(struct lttng_consumer_stream *stream,
-               bool create_index);
+int consumer_stream_create_output_files(struct lttng_consumer_stream *stream, bool create_index);
 
 /*
  * Rotate the output files of a local stream. This will change the
@@ -123,8 +118,7 @@ bool consumer_stream_is_deleted(struct lttng_consumer_stream *stream);
  *
  * This must be called on initialization before any subbuffer is consumed.
  */
-int consumer_stream_enable_metadata_bucketization(
-               struct lttng_consumer_stream *stream);
+int consumer_stream_enable_metadata_bucketization(struct lttng_consumer_stream *stream);
 
 /*
  * Set the version of a metadata stream (i.e. following a metadata
@@ -133,16 +127,16 @@ int consumer_stream_enable_metadata_bucketization(
  * Changing the version of a metadata stream will cause any bucketized metadata
  * to be discarded and will mark the metadata stream for future `reset`.
  */
-void consumer_stream_metadata_set_version(
-               struct lttng_consumer_stream *stream, uint64_t new_version);
+void consumer_stream_metadata_set_version(struct lttng_consumer_stream *stream,
+                                         uint64_t new_version);
 
 /*
  * Attempt to open a packet in a stream.
  *
  * This function must be called with the stream and channel locks held.
  */
-enum consumer_stream_open_packet_status consumer_stream_open_packet(
-               struct lttng_consumer_stream *stream);
+enum consumer_stream_open_packet_status
+consumer_stream_open_packet(struct lttng_consumer_stream *stream);
 
 /*
  * Flush a stream's buffer.
@@ -153,7 +147,6 @@ enum consumer_stream_open_packet_status consumer_stream_open_packet(
  *
  * This function must be called with the stream and channel locks held.
  */
-int consumer_stream_flush_buffer(struct lttng_consumer_stream *stream,
-               bool producer_active);
+int consumer_stream_flush_buffer(struct lttng_consumer_stream *stream, bool producer_active);
 
 #endif /* LTTNG_CONSUMER_STREAM_H */
index 8dae11fa2d5b465ccc3dab61f2aed7b948ab518a..2ae7f0f73d1b2fdaffe59ed6b21b3814b78e8c22 100644 (file)
@@ -7,25 +7,24 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <signal.h>
-
-#include <bin/lttng-consumerd/health-consumerd.hpp>
 #include <common/common.hpp>
 #include <common/compat/endian.hpp>
-#include <common/kernel-ctl/kernel-ctl.hpp>
-#include <common/kernel-consumer/kernel-consumer.hpp>
 #include <common/consumer/consumer-stream.hpp>
-#include <common/consumer/consumer-timer.hpp>
 #include <common/consumer/consumer-testpoint.hpp>
+#include <common/consumer/consumer-timer.hpp>
+#include <common/kernel-consumer/kernel-consumer.hpp>
+#include <common/kernel-ctl/kernel-ctl.hpp>
+#include <common/urcu.hpp>
 #include <common/ust-consumer/ust-consumer.hpp>
 
-typedef int (*sample_positions_cb)(struct lttng_consumer_stream *stream);
-typedef int (*get_consumed_cb)(struct lttng_consumer_stream *stream,
-               unsigned long *consumed);
-typedef int (*get_produced_cb)(struct lttng_consumer_stream *stream,
-               unsigned long *produced);
-typedef int (*flush_index_cb)(struct lttng_consumer_stream *stream);
+#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <inttypes.h>
+#include <signal.h>
+
+using sample_positions_cb = int (*)(struct lttng_consumer_stream *);
+using get_consumed_cb = int (*)(struct lttng_consumer_stream *, unsigned long *);
+using get_produced_cb = int (*)(struct lttng_consumer_stream *, unsigned long *);
+using flush_index_cb = int (*)(struct lttng_consumer_stream *);
 
 static struct timer_signal_data timer_signal = {
        .tid = 0,
@@ -76,8 +75,7 @@ static int the_channel_monitor_pipe = -1;
  * while consumer_timer_switch_stop() is called. It would result in
  * deadlocks.
  */
-static void metadata_switch_timer(struct lttng_consumer_local_data *ctx,
-               siginfo_t *si)
+static void metadata_switch_timer(struct lttng_consumer_local_data *ctx, siginfo_t *si)
 {
        int ret;
        struct lttng_consumer_channel *channel;
@@ -98,7 +96,7 @@ static void metadata_switch_timer(struct lttng_consumer_local_data *ctx,
                 * - metadata_socket_lock
                 *   - Calling lttng_ustconsumer_recv_metadata():
                 *     - channel->metadata_cache->lock
-                *     - Calling consumer_metadata_cache_flushed():
+                *     - Calling consumer_wait_metadata_cache_flushed():
                 *       - channel->timer_lock
                 *         - channel->metadata_cache->lock
                 *
@@ -107,7 +105,7 @@ static void metadata_switch_timer(struct lttng_consumer_local_data *ctx,
                 * they are held while consumer_timer_switch_stop() is
                 * called.
                 */
-               ret = lttng_ustconsumer_request_metadata(ctx, channel, 1, 1);
+               ret = lttng_ustconsumer_request_metadata(ctx, channel, true, 1);
                if (ret < 0) {
                        channel->switch_timer_error = 1;
                }
@@ -119,8 +117,7 @@ static void metadata_switch_timer(struct lttng_consumer_local_data *ctx,
        }
 }
 
-static int send_empty_index(struct lttng_consumer_stream *stream, uint64_t ts,
-               uint64_t stream_id)
+static int send_empty_index(struct lttng_consumer_stream *stream, uint64_t ts, uint64_t stream_id)
 {
        int ret;
        struct ctf_packet_index index;
@@ -175,8 +172,7 @@ end:
        return ret;
 }
 
-static int check_stream(struct lttng_consumer_stream *stream,
-               flush_index_cb flush_index)
+static int check_stream(struct lttng_consumer_stream *stream, flush_index_cb flush_index)
 {
        int ret;
 
@@ -195,14 +191,14 @@ static int check_stream(struct lttng_consumer_stream *stream,
                ret = pthread_mutex_trylock(&stream->lock);
                switch (ret) {
                case 0:
-                       break;  /* We have the lock. */
+                       break; /* We have the lock. */
                case EBUSY:
                        pthread_mutex_lock(&stream->metadata_timer_lock);
                        if (stream->waiting_on_metadata) {
                                ret = 0;
                                stream->missed_metadata_flush = true;
                                pthread_mutex_unlock(&stream->metadata_timer_lock);
-                               goto end;       /* Bail out. */
+                               goto end; /* Bail out. */
                        }
                        pthread_mutex_unlock(&stream->metadata_timer_lock);
                        /* Try again. */
@@ -267,18 +263,16 @@ end:
 /*
  * Execute action on a live timer
  */
-static void live_timer(struct lttng_consumer_local_data *ctx,
-               siginfo_t *si)
+static void live_timer(struct lttng_consumer_local_data *ctx, siginfo_t *si)
 {
        int ret;
        struct lttng_consumer_channel *channel;
        struct lttng_consumer_stream *stream;
        struct lttng_ht_iter iter;
        const struct lttng_ht *ht = the_consumer_data.stream_per_chan_id_ht;
-       const flush_index_cb flush_index =
-                       ctx->type == LTTNG_CONSUMER_KERNEL ?
-                                       consumer_flush_kernel_index :
-                                       consumer_flush_ust_index;
+       const flush_index_cb flush_index = ctx->type == LTTNG_CONSUMER_KERNEL ?
+               consumer_flush_kernel_index :
+               consumer_flush_ust_index;
 
        channel = (lttng_consumer_channel *) si->si_value.sival_ptr;
        LTTNG_ASSERT(channel);
@@ -289,26 +283,29 @@ static void live_timer(struct lttng_consumer_local_data *ctx,
 
        DBG("Live timer for channel %" PRIu64, channel->key);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key, &iter.iter,
-                       stream, node_channel_id.node) {
-               ret = check_stream(stream, flush_index);
-               if (ret < 0) {
-                       goto error_unlock;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry_duplicate(ht->ht,
+                                                 ht->hash_fct(&channel->key, lttng_ht_seed),
+                                                 ht->match_fct,
+                                                 &channel->key,
+                                                 &iter.iter,
+                                                 stream,
+                                                 node_channel_id.node)
+               {
+                       ret = check_stream(stream, flush_index);
+                       if (ret < 0) {
+                               goto error_unlock;
+                       }
                }
        }
-
 error_unlock:
-       rcu_read_unlock();
 
 error:
        return;
 }
 
-static
-void consumer_timer_signal_thread_qs(unsigned int signr)
+static void consumer_timer_signal_thread_qs(unsigned int signr)
 {
        sigset_t pending_set;
        int ret;
@@ -365,10 +362,10 @@ void consumer_timer_signal_thread_qs(unsigned int signr)
  * Returns a negative value on error, 0 if a timer was created, and
  * a positive value if no timer was created (not an error).
  */
-static
-int consumer_channel_timer_start(timer_t *timer_id,
-               struct lttng_consumer_channel *channel,
-               unsigned int timer_interval_us, int signal)
+static int consumer_channel_timer_start(timer_t *timer_id,
+                                       struct lttng_consumer_channel *channel,
+                                       unsigned int timer_interval_us,
+                                       int signal)
 {
        int ret = 0, delete_ret;
        struct sigevent sev = {};
@@ -397,7 +394,7 @@ int consumer_channel_timer_start(timer_t *timer_id,
        its.it_interval.tv_sec = its.it_value.tv_sec;
        its.it_interval.tv_nsec = its.it_value.tv_nsec;
 
-       ret = timer_settime(*timer_id, 0, &its, NULL);
+       ret = timer_settime(*timer_id, 0, &its, nullptr);
        if (ret == -1) {
                PERROR("timer_settime");
                goto error_destroy_timer;
@@ -412,8 +409,7 @@ error_destroy_timer:
        goto end;
 }
 
-static
-int consumer_channel_timer_stop(timer_t *timer_id, int signal)
+static int consumer_channel_timer_stop(timer_t *timer_id, int signal)
 {
        int ret = 0;
 
@@ -424,7 +420,7 @@ int consumer_channel_timer_stop(timer_t *timer_id, int signal)
        }
 
        consumer_timer_signal_thread_qs(signal);
-       *timer_id = 0;
+       *timer_id = nullptr;
 end:
        return ret;
 }
@@ -433,15 +429,17 @@ end:
  * Set the channel's switch timer.
  */
 void consumer_timer_switch_start(struct lttng_consumer_channel *channel,
-               unsigned int switch_timer_interval_us)
+                                unsigned int switch_timer_interval_us)
 {
        int ret;
 
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(channel->key);
 
-       ret = consumer_channel_timer_start(&channel->switch_timer, channel,
-                       switch_timer_interval_us, LTTNG_CONSUMER_SIG_SWITCH);
+       ret = consumer_channel_timer_start(&channel->switch_timer,
+                                          channel,
+                                          switch_timer_interval_us,
+                                          LTTNG_CONSUMER_SIG_SWITCH);
 
        channel->switch_timer_enabled = !!(ret == 0);
 }
@@ -455,8 +453,7 @@ void consumer_timer_switch_stop(struct lttng_consumer_channel *channel)
 
        LTTNG_ASSERT(channel);
 
-       ret = consumer_channel_timer_stop(&channel->switch_timer,
-                       LTTNG_CONSUMER_SIG_SWITCH);
+       ret = consumer_channel_timer_stop(&channel->switch_timer, LTTNG_CONSUMER_SIG_SWITCH);
        if (ret == -1) {
                ERR("Failed to stop switch timer");
        }
@@ -468,15 +465,15 @@ void consumer_timer_switch_stop(struct lttng_consumer_channel *channel)
  * Set the channel's live timer.
  */
 void consumer_timer_live_start(struct lttng_consumer_channel *channel,
-               unsigned int live_timer_interval_us)
+                              unsigned int live_timer_interval_us)
 {
        int ret;
 
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(channel->key);
 
-       ret = consumer_channel_timer_start(&channel->live_timer, channel,
-                       live_timer_interval_us, LTTNG_CONSUMER_SIG_LIVE);
+       ret = consumer_channel_timer_start(
+               &channel->live_timer, channel, live_timer_interval_us, LTTNG_CONSUMER_SIG_LIVE);
 
        channel->live_timer_enabled = !!(ret == 0);
 }
@@ -490,8 +487,7 @@ void consumer_timer_live_stop(struct lttng_consumer_channel *channel)
 
        LTTNG_ASSERT(channel);
 
-       ret = consumer_channel_timer_stop(&channel->live_timer,
-                       LTTNG_CONSUMER_SIG_LIVE);
+       ret = consumer_channel_timer_stop(&channel->live_timer, LTTNG_CONSUMER_SIG_LIVE);
        if (ret == -1) {
                ERR("Failed to stop live timer");
        }
@@ -506,7 +502,7 @@ void consumer_timer_live_stop(struct lttng_consumer_channel *channel)
  * a positive value if no timer was created (not an error).
  */
 int consumer_timer_monitor_start(struct lttng_consumer_channel *channel,
-               unsigned int monitor_timer_interval_us)
+                                unsigned int monitor_timer_interval_us)
 {
        int ret;
 
@@ -514,8 +510,10 @@ int consumer_timer_monitor_start(struct lttng_consumer_channel *channel,
        LTTNG_ASSERT(channel->key);
        LTTNG_ASSERT(!channel->monitor_timer_enabled);
 
-       ret = consumer_channel_timer_start(&channel->monitor_timer, channel,
-                       monitor_timer_interval_us, LTTNG_CONSUMER_SIG_MONITOR);
+       ret = consumer_channel_timer_start(&channel->monitor_timer,
+                                          channel,
+                                          monitor_timer_interval_us,
+                                          LTTNG_CONSUMER_SIG_MONITOR);
        channel->monitor_timer_enabled = !!(ret == 0);
        return ret;
 }
@@ -530,10 +528,9 @@ int consumer_timer_monitor_stop(struct lttng_consumer_channel *channel)
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(channel->monitor_timer_enabled);
 
-       ret = consumer_channel_timer_stop(&channel->monitor_timer,
-                       LTTNG_CONSUMER_SIG_MONITOR);
+       ret = consumer_channel_timer_stop(&channel->monitor_timer, LTTNG_CONSUMER_SIG_MONITOR);
        if (ret == -1) {
-               ERR("Failed to stop live timer");
+               ERR("Failed to stop monitor timer");
                goto end;
        }
 
@@ -546,14 +543,14 @@ end:
  * Block the RT signals for the entire process. It must be called from the
  * consumer main before creating the threads
  */
-int consumer_signal_init(void)
+int consumer_signal_init()
 {
        int ret;
        sigset_t mask;
 
        /* Block signal for entire process, so only our thread processes it. */
        setmask(&mask);
-       ret = pthread_sigmask(SIG_BLOCK, &mask, NULL);
+       ret = pthread_sigmask(SIG_BLOCK, &mask, nullptr);
        if (ret) {
                errno = ret;
                PERROR("pthread_sigmask");
@@ -562,11 +559,13 @@ int consumer_signal_init(void)
        return 0;
 }
 
-static
-int sample_channel_positions(struct lttng_consumer_channel *channel,
-               uint64_t *_highest_use, uint64_t *_lowest_use, uint64_t *_total_consumed,
-               sample_positions_cb sample, get_consumed_cb get_consumed,
-               get_produced_cb get_produced)
+static int sample_channel_positions(struct lttng_consumer_channel *channel,
+                                   uint64_t *_highest_use,
+                                   uint64_t *_lowest_use,
+                                   uint64_t *_total_consumed,
+                                   sample_positions_cb sample,
+                                   get_consumed_cb get_consumed,
+                                   get_produced_cb get_produced)
 {
        int ret = 0;
        struct lttng_ht_iter iter;
@@ -577,12 +576,16 @@ int sample_channel_positions(struct lttng_consumer_channel *channel,
 
        *_total_consumed = 0;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key,
-                       &iter.iter, stream, node_channel_id.node) {
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                unsigned long produced, consumed, usage;
 
                empty_channel = false;
@@ -594,7 +597,8 @@ int sample_channel_positions(struct lttng_consumer_channel *channel,
 
                ret = sample(stream);
                if (ret) {
-                       ERR("Failed to take buffer position snapshot in monitor timer (ret = %d)", ret);
+                       ERR("Failed to take buffer position snapshot in monitor timer (ret = %d)",
+                           ret);
                        pthread_mutex_unlock(&stream->lock);
                        goto end;
                }
@@ -630,7 +634,6 @@ int sample_channel_positions(struct lttng_consumer_channel *channel,
        *_highest_use = high;
        *_lowest_use = low;
 end:
-       rcu_read_unlock();
        if (empty_channel) {
                ret = -1;
        }
@@ -641,8 +644,7 @@ end:
 void sample_and_send_channel_buffer_stats(struct lttng_consumer_channel *channel)
 {
        int ret;
-       int channel_monitor_pipe =
-                       consumer_timer_thread_get_channel_monitor_pipe();
+       int channel_monitor_pipe = consumer_timer_thread_get_channel_monitor_pipe();
        struct lttcomm_consumer_channel_monitor_msg msg = {
                .key = channel->key,
                .session_id = channel->session_id,
@@ -677,8 +679,8 @@ void sample_and_send_channel_buffer_stats(struct lttng_consumer_channel *channel
                abort();
        }
 
-       ret = sample_channel_positions(channel, &highest, &lowest,
-                       &total_consumed, sample, get_consumed, get_produced);
+       ret = sample_channel_positions(
+               channel, &highest, &lowest, &total_consumed, sample, get_consumed, get_produced);
        if (ret) {
                return;
        }
@@ -700,19 +702,21 @@ void sample_and_send_channel_buffer_stats(struct lttng_consumer_channel *channel
                if (errno == EAGAIN) {
                        /* Not an error, the sample is merely dropped. */
                        DBG("Channel monitor pipe is full; dropping sample for channel key = %" PRIu64,
-                                       channel->key);
+                           channel->key);
                } else {
                        PERROR("write to the channel monitor pipe");
                }
        } else {
                DBG("Sent channel monitoring sample for channel key %" PRIu64
-                               ", (highest = %" PRIu64 ", lowest = %" PRIu64 ")",
-                               channel->key, msg.highest, msg.lowest);
+                   ", (highest = %" PRIu64 ", lowest = %" PRIu64 ")",
+                   channel->key,
+                   msg.highest,
+                   msg.lowest);
                channel->last_consumed_size_sample_sent = msg.consumed_since_last_sample;
        }
 }
 
-int consumer_timer_thread_get_channel_monitor_pipe(void)
+int consumer_timer_thread_get_channel_monitor_pipe()
 {
        return uatomic_read(&the_channel_monitor_pipe);
 }
@@ -757,7 +761,7 @@ void *consumer_timer_thread(void *data)
        setmask(&mask);
        CMM_STORE_SHARED(timer_signal.tid, pthread_self());
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                health_poll_entry();
@@ -802,5 +806,5 @@ error_testpoint:
 end:
        health_unregister(health_consumerd);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
index 3445ed57fd1fd2399824912e36ee135a88c26695..50025d727cf98db138f394c6aef78835417561f4 100644 (file)
 #ifndef CONSUMER_TIMER_H
 #define CONSUMER_TIMER_H
 
-#include <pthread.h>
-
 #include "consumer.hpp"
 
-#define LTTNG_CONSUMER_SIG_SWITCH      SIGRTMIN + 10
-#define LTTNG_CONSUMER_SIG_TEARDOWN    SIGRTMIN + 11
-#define LTTNG_CONSUMER_SIG_LIVE                SIGRTMIN + 12
-#define LTTNG_CONSUMER_SIG_MONITOR     SIGRTMIN + 13
-#define LTTNG_CONSUMER_SIG_EXIT                SIGRTMIN + 14
+#include <pthread.h>
+
+#define LTTNG_CONSUMER_SIG_SWITCH   ((SIGRTMIN + 10))
+#define LTTNG_CONSUMER_SIG_TEARDOWN ((SIGRTMIN + 11))
+#define LTTNG_CONSUMER_SIG_LIVE            ((SIGRTMIN + 12))
+#define LTTNG_CONSUMER_SIG_MONITOR  ((SIGRTMIN + 13))
+#define LTTNG_CONSUMER_SIG_EXIT            ((SIGRTMIN + 14))
 
 #define CLOCKID CLOCK_MONOTONIC
 
  * exclusion.
  */
 struct timer_signal_data {
-       pthread_t tid;  /* thread id managing signals */
+       pthread_t tid; /* thread id managing signals */
        int setup_done;
        int qs_done;
        pthread_mutex_t lock;
 };
 
 void consumer_timer_switch_start(struct lttng_consumer_channel *channel,
-               unsigned int switch_timer_interval_us);
+                                unsigned int switch_timer_interval_us);
 void consumer_timer_switch_stop(struct lttng_consumer_channel *channel);
 void consumer_timer_live_start(struct lttng_consumer_channel *channel,
-               unsigned int live_timer_interval_us);
+                              unsigned int live_timer_interval_us);
 void consumer_timer_live_stop(struct lttng_consumer_channel *channel);
 int consumer_timer_monitor_start(struct lttng_consumer_channel *channel,
-               unsigned int monitor_timer_interval_us);
+                                unsigned int monitor_timer_interval_us);
 int consumer_timer_monitor_stop(struct lttng_consumer_channel *channel);
 void *consumer_timer_thread(void *data);
-int consumer_signal_init(void);
+int consumer_signal_init();
 
 int consumer_flush_kernel_index(struct lttng_consumer_stream *stream);
 int consumer_flush_ust_index(struct lttng_consumer_stream *stream);
 
-int consumer_timer_thread_get_channel_monitor_pipe(void);
+int consumer_timer_thread_get_channel_monitor_pipe();
 int consumer_timer_thread_set_channel_monitor_pipe(int fd);
 
 #endif /* CONSUMER_TIMER_H */
index 3272c129fe353c2ad6b75f3f359391ce55ced9bf..ed844f8dfd8a4d27826ea6b8644d04fc244b0014 100644 (file)
@@ -8,18 +8,6 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <poll.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <bin/lttng-consumerd/health-consumerd.hpp>
 #include <common/align.hpp>
 #include <common/common.hpp>
 #include <common/compat/endian.hpp>
@@ -32,6 +20,7 @@
 #include <common/dynamic-array.hpp>
 #include <common/index/ctf-index.hpp>
 #include <common/index/index.hpp>
+#include <common/io-hint.hpp>
 #include <common/kernel-consumer/kernel-consumer.hpp>
 #include <common/kernel-ctl/kernel-ctl.hpp>
 #include <common/relayd/relayd.hpp>
 #include <common/time.hpp>
 #include <common/trace-chunk-registry.hpp>
 #include <common/trace-chunk.hpp>
+#include <common/urcu.hpp>
 #include <common/ust-consumer/ust-consumer.hpp>
 #include <common/utils.hpp>
 
+#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <poll.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <type_traits>
+#include <unistd.h>
+
 lttng_consumer_global_data the_consumer_data;
 
 enum consumer_channel_action {
@@ -55,8 +59,8 @@ enum consumer_channel_action {
 namespace {
 struct consumer_channel_msg {
        enum consumer_channel_action action;
-       struct lttng_consumer_channel *chan;    /* add */
-       uint64_t key;                           /* del */
+       struct lttng_consumer_channel *chan; /* add */
+       uint64_t key; /* del */
 };
 
 /*
@@ -79,7 +83,7 @@ int data_consumption_paused;
  */
 int consumer_quit;
 
-static const char *get_consumer_domain(void)
+static const char *get_consumer_domain()
 {
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -100,11 +104,12 @@ static const char *get_consumer_domain(void)
  */
 static void notify_thread_lttng_pipe(struct lttng_pipe *pipe)
 {
-       struct lttng_consumer_stream *null_stream = NULL;
+       struct lttng_consumer_stream *null_stream = nullptr;
 
        LTTNG_ASSERT(pipe);
 
-       (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream));
+       (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream)); /* NOLINT sizeof used on a
+                                                                            pointer. */
 }
 
 static void notify_health_quit_pipe(int *pipe)
@@ -118,9 +123,9 @@ static void notify_health_quit_pipe(int *pipe)
 }
 
 static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_channel *chan,
-               uint64_t key,
-               enum consumer_channel_action action)
+                               struct lttng_consumer_channel *chan,
+                               uint64_t key,
+                               enum consumer_channel_action action)
 {
        struct consumer_channel_msg msg;
        ssize_t ret;
@@ -136,16 +141,15 @@ static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
        }
 }
 
-void notify_thread_del_channel(struct lttng_consumer_local_data *ctx,
-               uint64_t key)
+void notify_thread_del_channel(struct lttng_consumer_local_data *ctx, uint64_t key)
 {
-       notify_channel_pipe(ctx, NULL, key, CONSUMER_CHANNEL_DEL);
+       notify_channel_pipe(ctx, nullptr, key, CONSUMER_CHANNEL_DEL);
 }
 
 static int read_channel_pipe(struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_channel **chan,
-               uint64_t *key,
-               enum consumer_channel_action *action)
+                            struct lttng_consumer_channel **chan,
+                            uint64_t *key,
+                            enum consumer_channel_action *action)
 {
        struct consumer_channel_msg msg;
        ssize_t ret;
@@ -173,8 +177,7 @@ static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
        LTTNG_ASSERT(channel);
 
        /* Delete streams that might have been left in the stream list. */
-       cds_list_for_each_entry_safe(stream, stmp, &channel->streams.head,
-                       send_node) {
+       cds_list_for_each_entry_safe (stream, stmp, &channel->streams.head, send_node) {
                /*
                 * Once a stream is added to this list, the buffers were created so we
                 * have a guarantee that this call will succeed. Setting the monitor
@@ -182,7 +185,7 @@ static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
                 * global hash table.
                 */
                stream->monitor = 0;
-               consumer_stream_destroy(stream, NULL);
+               consumer_stream_destroy(stream, nullptr);
        }
 }
 
@@ -190,30 +193,27 @@ static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
  * Find a stream. The consumer_data.lock must be locked during this
  * call.
  */
-static struct lttng_consumer_stream *find_stream(uint64_t key,
-               struct lttng_ht *ht)
+static struct lttng_consumer_stream *find_stream(uint64_t key, struct lttng_ht *ht)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
-       struct lttng_consumer_stream *stream = NULL;
+       struct lttng_consumer_stream *stream = nullptr;
 
        LTTNG_ASSERT(ht);
 
        /* -1ULL keys are lookup failures */
        if (key == (uint64_t) -1ULL) {
-               return NULL;
+               return nullptr;
        }
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        lttng_ht_lookup(ht, &key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node != NULL) {
+       if (node != nullptr) {
                stream = lttng::utils::container_of(node, &lttng_consumer_stream::node);
        }
 
-       rcu_read_unlock();
-
        return stream;
 }
 
@@ -221,7 +221,7 @@ static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
 {
        struct lttng_consumer_stream *stream;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        stream = find_stream(key, ht);
        if (stream) {
                stream->key = (uint64_t) -1ULL;
@@ -232,7 +232,6 @@ static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
                 */
                stream->node.key = (uint64_t) -1ULL;
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -245,18 +244,18 @@ struct lttng_consumer_channel *consumer_find_channel(uint64_t key)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
-       struct lttng_consumer_channel *channel = NULL;
+       struct lttng_consumer_channel *channel = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
        /* -1ULL keys are lookup failures */
        if (key == (uint64_t) -1ULL) {
-               return NULL;
+               return nullptr;
        }
 
        lttng_ht_lookup(the_consumer_data.channel_ht, &key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node != NULL) {
+       if (node != nullptr) {
                channel = lttng::utils::container_of(node, &lttng_consumer_channel::node);
        }
 
@@ -275,7 +274,7 @@ static void steal_channel_key(uint64_t key)
 {
        struct lttng_consumer_channel *channel;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        channel = consumer_find_channel(key);
        if (channel) {
                channel->key = (uint64_t) -1ULL;
@@ -286,13 +285,11 @@ static void steal_channel_key(uint64_t key)
                 */
                channel->node.key = (uint64_t) -1ULL;
        }
-       rcu_read_unlock();
 }
 
 static void free_channel_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_u64 *node =
-               lttng::utils::container_of(head, &lttng_ht_node_u64::head);
+       struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
        struct lttng_consumer_channel *channel =
                lttng::utils::container_of(node, &lttng_consumer_channel::node);
 
@@ -307,7 +304,8 @@ static void free_channel_rcu(struct rcu_head *head)
                ERR("Unknown consumer_data type");
                abort();
        }
-       free(channel);
+
+       delete channel;
 }
 
 /*
@@ -315,8 +313,7 @@ static void free_channel_rcu(struct rcu_head *head)
  */
 static void free_relayd_rcu(struct rcu_head *head)
 {
-       struct lttng_ht_node_u64 *node =
-               lttng::utils::container_of(head, &lttng_ht_node_u64::head);
+       struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
        struct consumer_relayd_sock_pair *relayd =
                lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
 
@@ -343,7 +340,7 @@ void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd)
        int ret;
        struct lttng_ht_iter iter;
 
-       if (relayd == NULL) {
+       if (relayd == nullptr) {
                return;
        }
 
@@ -403,21 +400,19 @@ void consumer_del_channel(struct lttng_consumer_channel *channel)
        }
 
        lttng_trace_chunk_put(channel->trace_chunk);
-       channel->trace_chunk = NULL;
+       channel->trace_chunk = nullptr;
 
        if (channel->is_published) {
                int ret;
 
-               rcu_read_lock();
+               lttng::urcu::read_lock_guard read_lock;
                iter.iter.node = &channel->node.node;
                ret = lttng_ht_del(the_consumer_data.channel_ht, &iter);
                LTTNG_ASSERT(!ret);
 
                iter.iter.node = &channel->channels_by_session_id_ht_node.node;
-               ret = lttng_ht_del(the_consumer_data.channels_by_session_id_ht,
-                               &iter);
+               ret = lttng_ht_del(the_consumer_data.channels_by_session_id_ht, &iter);
                LTTNG_ASSERT(!ret);
-               rcu_read_unlock();
        }
 
        channel->is_deleted = true;
@@ -431,20 +426,20 @@ end:
  * Iterate over the relayd hash table and destroy each element. Finally,
  * destroy the whole hash table.
  */
-static void cleanup_relayd_ht(void)
+static void cleanup_relayd_ht()
 {
        struct lttng_ht_iter iter;
        struct consumer_relayd_sock_pair *relayd;
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(the_consumer_data.relayd_ht->ht, &iter.iter,
-                       relayd, node.node) {
-               consumer_destroy_relayd(relayd);
+               cds_lfht_for_each_entry (
+                       the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
+                       consumer_destroy_relayd(relayd);
+               }
        }
 
-       rcu_read_unlock();
-
        lttng_ht_destroy(the_consumer_data.relayd_ht);
 }
 
@@ -456,31 +451,32 @@ static void cleanup_relayd_ht(void)
  * because we handle the write/read race with a pipe wakeup for each thread.
  */
 static void update_endpoint_status_by_netidx(uint64_t net_seq_idx,
-               enum consumer_endpoint_status status)
+                                            enum consumer_endpoint_status status)
 {
        struct lttng_ht_iter iter;
        struct lttng_consumer_stream *stream;
 
        DBG("Consumer set delete flag on stream by idx %" PRIu64, net_seq_idx);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Let's begin with metadata */
-       cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
+       cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
                if (stream->net_seq_idx == net_seq_idx) {
                        uatomic_set(&stream->endpoint_status, status);
+                       stream->chan->metadata_pushed_wait_queue.wake_all();
+
                        DBG("Delete flag set to metadata stream %d", stream->wait_fd);
                }
        }
 
        /* Follow up by the data streams */
-       cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
+       cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
                if (stream->net_seq_idx == net_seq_idx) {
                        uatomic_set(&stream->endpoint_status, status);
                        DBG("Delete flag set to data stream %d", stream->wait_fd);
                }
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -547,8 +543,7 @@ void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd)
  *
  * One this call returns, the stream object is not longer usable nor visible.
  */
-void consumer_del_stream(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht)
+void consumer_del_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
 {
        consumer_stream_destroy(stream, ht);
 }
@@ -566,12 +561,10 @@ void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream)
        consumer_stream_destroy(stream, metadata_ht);
 }
 
-void consumer_stream_update_channel_attributes(
-               struct lttng_consumer_stream *stream,
-               struct lttng_consumer_channel *channel)
+void consumer_stream_update_channel_attributes(struct lttng_consumer_stream *stream,
+                                              struct lttng_consumer_channel *channel)
 {
-       stream->channel_read_only_attributes.tracefile_size =
-                       channel->tracefile_size;
+       stream->channel_read_only_attributes.tracefile_size = channel->tracefile_size;
 }
 
 /*
@@ -590,23 +583,21 @@ void consumer_add_data_stream(struct lttng_consumer_stream *stream)
        pthread_mutex_lock(&stream->chan->lock);
        pthread_mutex_lock(&stream->chan->timer_lock);
        pthread_mutex_lock(&stream->lock);
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Steal stream identifier to avoid having streams with the same key */
        steal_stream_key(stream->key, ht);
 
        lttng_ht_add_unique_u64(ht, &stream->node);
 
-       lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht,
-                       &stream->node_channel_id);
+       lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
 
        /*
         * Add stream to the stream_list_ht of the consumer data. No need to steal
         * the key since the HT does not use it and we allow to add redundant keys
         * into this table.
         */
-       lttng_ht_add_u64(the_consumer_data.stream_list_ht,
-                       &stream->node_session_id);
+       lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
 
        /*
         * When nb_init_stream_left reaches 0, we don't need to trigger any action
@@ -625,7 +616,6 @@ void consumer_add_data_stream(struct lttng_consumer_stream *stream)
        the_consumer_data.stream_count++;
        the_consumer_data.need_update = 1;
 
-       rcu_read_unlock();
        pthread_mutex_unlock(&stream->lock);
        pthread_mutex_unlock(&stream->chan->timer_lock);
        pthread_mutex_unlock(&stream->chan->lock);
@@ -645,10 +635,9 @@ static int add_relayd(struct consumer_relayd_sock_pair *relayd)
        LTTNG_ASSERT(relayd);
        ASSERT_RCU_READ_LOCKED();
 
-       lttng_ht_lookup(the_consumer_data.relayd_ht, &relayd->net_seq_idx,
-                       &iter);
+       lttng_ht_lookup(the_consumer_data.relayd_ht, &relayd->net_seq_idx, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node != NULL) {
+       if (node != nullptr) {
                goto end;
        }
        lttng_ht_add_unique_u64(the_consumer_data.relayd_ht, &relayd->node);
@@ -660,10 +649,9 @@ end:
 /*
  * Allocate and return a consumer relayd socket.
  */
-static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(
-               uint64_t net_seq_idx)
+static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(uint64_t net_seq_idx)
 {
-       struct consumer_relayd_sock_pair *obj = NULL;
+       struct consumer_relayd_sock_pair *obj = nullptr;
 
        /* net sequence index of -1 is a failure */
        if (net_seq_idx == (uint64_t) -1ULL) {
@@ -671,7 +659,7 @@ static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(
        }
 
        obj = zmalloc<consumer_relayd_sock_pair>();
-       if (obj == NULL) {
+       if (obj == nullptr) {
                PERROR("zmalloc relayd sock");
                goto error;
        }
@@ -682,7 +670,7 @@ static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(
        obj->control_sock.sock.fd = -1;
        obj->data_sock.sock.fd = -1;
        lttng_ht_node_init_u64(&obj->node, obj->net_seq_idx);
-       pthread_mutex_init(&obj->ctrl_sock_mutex, NULL);
+       pthread_mutex_init(&obj->ctrl_sock_mutex, nullptr);
 
 error:
        return obj;
@@ -699,7 +687,7 @@ struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
 {
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
@@ -710,7 +698,7 @@ struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
 
        lttng_ht_lookup(the_consumer_data.relayd_ht, &key, &iter);
        node = lttng_ht_iter_get_node_u64(&iter);
-       if (node != NULL) {
+       if (node != nullptr) {
                relayd = lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
        }
 
@@ -723,8 +711,7 @@ error:
  *
  * Returns 0 on success, < 0 on error
  */
-int consumer_send_relayd_stream(struct lttng_consumer_stream *stream,
-               char *path)
+int consumer_send_relayd_stream(struct lttng_consumer_stream *stream, char *path)
 {
        int ret = 0;
        struct consumer_relayd_sock_pair *relayd;
@@ -734,19 +721,23 @@ int consumer_send_relayd_stream(struct lttng_consumer_stream *stream,
        LTTNG_ASSERT(path);
 
        /* The stream is not metadata. Get relayd reference if exists. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        relayd = consumer_find_relayd(stream->net_seq_idx);
-       if (relayd != NULL) {
+       if (relayd != nullptr) {
                /* Add stream on the relayd */
                pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-               ret = relayd_add_stream(&relayd->control_sock, stream->name,
-                               get_consumer_domain(), path, &stream->relayd_stream_id,
-                               stream->chan->tracefile_size,
-                               stream->chan->tracefile_count,
-                               stream->trace_chunk);
+               ret = relayd_add_stream(&relayd->control_sock,
+                                       stream->name,
+                                       get_consumer_domain(),
+                                       path,
+                                       &stream->relayd_stream_id,
+                                       stream->chan->tracefile_size,
+                                       stream->chan->tracefile_count,
+                                       stream->trace_chunk);
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                if (ret < 0) {
-                       ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+                       ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64 ".",
+                           relayd->net_seq_idx);
                        lttng_consumer_cleanup_relayd(relayd);
                        goto end;
                }
@@ -755,16 +746,18 @@ int consumer_send_relayd_stream(struct lttng_consumer_stream *stream,
                stream->sent_to_relayd = 1;
        } else {
                ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't send it.",
-                               stream->key, stream->net_seq_idx);
+                   stream->key,
+                   stream->net_seq_idx);
                ret = -1;
                goto end;
        }
 
        DBG("Stream %s with key %" PRIu64 " sent to relayd id %" PRIu64,
-                       stream->name, stream->key, stream->net_seq_idx);
+           stream->name,
+           stream->key,
+           stream->net_seq_idx);
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -781,21 +774,21 @@ int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
        LTTNG_ASSERT(net_seq_idx != -1ULL);
 
        /* The stream is not metadata. Get relayd reference if exists. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        relayd = consumer_find_relayd(net_seq_idx);
-       if (relayd != NULL) {
+       if (relayd != nullptr) {
                /* Add stream on the relayd */
                pthread_mutex_lock(&relayd->ctrl_sock_mutex);
                ret = relayd_streams_sent(&relayd->control_sock);
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                if (ret < 0) {
-                       ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+                       ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64 ".",
+                           relayd->net_seq_idx);
                        lttng_consumer_cleanup_relayd(relayd);
                        goto end;
                }
        } else {
-               ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.",
-                               net_seq_idx);
+               ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.", net_seq_idx);
                ret = -1;
                goto end;
        }
@@ -804,7 +797,6 @@ int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
        DBG("All streams sent relayd id %" PRIu64, net_seq_idx);
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -816,12 +808,11 @@ void close_relayd_stream(struct lttng_consumer_stream *stream)
        struct consumer_relayd_sock_pair *relayd;
 
        /* The stream is not metadata. Get relayd reference if exists. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        relayd = consumer_find_relayd(stream->net_seq_idx);
        if (relayd) {
                consumer_stream_relayd_close(stream, relayd);
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -831,8 +822,9 @@ void close_relayd_stream(struct lttng_consumer_stream *stream)
  * Return destination file descriptor or negative value on error.
  */
 static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
-               size_t data_size, unsigned long padding,
-               struct consumer_relayd_sock_pair *relayd)
+                                     size_t data_size,
+                                     unsigned long padding,
+                                     struct consumer_relayd_sock_pair *relayd)
 {
        int outfd = -1, ret;
        struct lttcomm_relayd_data_hdr data_hdr;
@@ -869,8 +861,7 @@ static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
                data_hdr.net_seq_num = htobe64(stream->next_net_seq_num);
                /* Other fields are zeroed previously */
 
-               ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr,
-                               sizeof(data_hdr));
+               ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr, sizeof(data_hdr));
                if (ret < 0) {
                        goto error;
                }
@@ -893,13 +884,11 @@ int consumer_metadata_wakeup_pipe(const struct lttng_consumer_channel *channel)
 {
        int ret = 0;
 
-       DBG("Waking up metadata poll thread (writing to pipe): channel name = '%s'",
-                       channel->name);
+       DBG("Waking up metadata poll thread (writing to pipe): channel name = '%s'", channel->name);
        if (channel->monitor && channel->metadata_stream) {
                const char dummy = 'c';
-               const ssize_t write_ret = lttng_write(
-                               channel->metadata_stream->ust_metadata_poll_pipe[1],
-                               &dummy, 1);
+               const ssize_t write_ret =
+                       lttng_write(channel->metadata_stream->ust_metadata_poll_pipe[1], &dummy, 1);
 
                if (write_ret < 1) {
                        if (errno == EWOULDBLOCK) {
@@ -929,8 +918,7 @@ end:
  *
  * The caller must hold the channel and stream locks.
  */
-static
-int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
+static int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
 {
        int ret;
 
@@ -966,10 +954,8 @@ int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
        return ret;
 }
 
-static
-int lttng_consumer_channel_set_trace_chunk(
-               struct lttng_consumer_channel *channel,
-               struct lttng_trace_chunk *new_trace_chunk)
+static int lttng_consumer_channel_set_trace_chunk(struct lttng_consumer_channel *channel,
+                                                 struct lttng_trace_chunk *new_trace_chunk)
 {
        pthread_mutex_lock(&channel->lock);
        if (channel->is_deleted) {
@@ -989,8 +975,7 @@ int lttng_consumer_channel_set_trace_chunk(
         * chunk is already held by the caller.
         */
        if (new_trace_chunk) {
-               const bool acquired_reference = lttng_trace_chunk_get(
-                               new_trace_chunk);
+               const bool acquired_reference = lttng_trace_chunk_get(new_trace_chunk);
 
                LTTNG_ASSERT(acquired_reference);
        }
@@ -1009,37 +994,38 @@ end:
  * On error, return NULL.
  */
 struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
-               uint64_t session_id,
-               const uint64_t *chunk_id,
-               const char *pathname,
-               const char *name,
-               uint64_t relayd_id,
-               enum lttng_event_output output,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               uint64_t session_id_per_pid,
-               unsigned int monitor,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               const char *root_shm_path,
-               const char *shm_path)
+                                                        uint64_t session_id,
+                                                        const uint64_t *chunk_id,
+                                                        const char *pathname,
+                                                        const char *name,
+                                                        uint64_t relayd_id,
+                                                        enum lttng_event_output output,
+                                                        uint64_t tracefile_size,
+                                                        uint64_t tracefile_count,
+                                                        uint64_t session_id_per_pid,
+                                                        unsigned int monitor,
+                                                        unsigned int live_timer_interval,
+                                                        bool is_in_live_session,
+                                                        const char *root_shm_path,
+                                                        const char *shm_path)
 {
-       struct lttng_consumer_channel *channel = NULL;
-       struct lttng_trace_chunk *trace_chunk = NULL;
+       struct lttng_consumer_channel *channel = nullptr;
+       struct lttng_trace_chunk *trace_chunk = nullptr;
 
        if (chunk_id) {
                trace_chunk = lttng_trace_chunk_registry_find_chunk(
-                               the_consumer_data.chunk_registry, session_id,
-                               *chunk_id);
+                       the_consumer_data.chunk_registry, session_id, *chunk_id);
                if (!trace_chunk) {
                        ERR("Failed to find trace chunk reference during creation of channel");
                        goto end;
                }
        }
 
-       channel = zmalloc<lttng_consumer_channel>();
-       if (channel == NULL) {
-               PERROR("malloc struct lttng_consumer_channel");
+       try {
+               channel = new lttng_consumer_channel;
+       } catch (const std::bad_alloc& e) {
+               ERR("Failed to allocate lttng_consumer_channel: %s", e.what());
+               channel = nullptr;
                goto end;
        }
 
@@ -1065,8 +1051,8 @@ struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
                break;
        default:
                abort();
-               free(channel);
-               channel = NULL;
+               delete channel;
+               channel = nullptr;
                goto end;
        }
 
@@ -1099,15 +1085,13 @@ struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
        }
 
        lttng_ht_node_init_u64(&channel->node, channel->key);
-       lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node,
-                       channel->session_id);
+       lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node, channel->session_id);
 
        channel->wait_fd = -1;
        CDS_INIT_LIST_HEAD(&channel->streams.head);
 
        if (trace_chunk) {
-               int ret = lttng_consumer_channel_set_trace_chunk(channel,
-                               trace_chunk);
+               int ret = lttng_consumer_channel_set_trace_chunk(channel, trace_chunk);
                if (ret) {
                        goto error;
                }
@@ -1120,7 +1104,7 @@ end:
        return channel;
 error:
        consumer_del_channel(channel);
-       channel = NULL;
+       channel = nullptr;
        goto end;
 }
 
@@ -1130,7 +1114,7 @@ error:
  * Always return 0 indicating success.
  */
 int consumer_add_channel(struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx)
+                        struct lttng_consumer_local_data *ctx)
 {
        pthread_mutex_lock(&the_consumer_data.lock);
        pthread_mutex_lock(&channel->lock);
@@ -1143,11 +1127,10 @@ int consumer_add_channel(struct lttng_consumer_channel *channel,
         */
        steal_channel_key(channel->key);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        lttng_ht_add_unique_u64(the_consumer_data.channel_ht, &channel->node);
        lttng_ht_add_u64(the_consumer_data.channels_by_session_id_ht,
-                       &channel->channels_by_session_id_ht_node);
-       rcu_read_unlock();
+                        &channel->channels_by_session_id_ht_node);
        channel->is_published = true;
 
        pthread_mutex_unlock(&channel->timer_lock);
@@ -1169,8 +1152,10 @@ int consumer_add_channel(struct lttng_consumer_channel *channel,
  * Returns the number of fds in the structures.
  */
 static int update_poll_array(struct lttng_consumer_local_data *ctx,
-               struct pollfd **pollfd, struct lttng_consumer_stream **local_stream,
-               struct lttng_ht *ht, int *nb_inactive_fd)
+                            struct pollfd **pollfd,
+                            struct lttng_consumer_stream **local_stream,
+                            struct lttng_ht *ht,
+                            int *nb_inactive_fd)
 {
        int i = 0;
        struct lttng_ht_iter iter;
@@ -1183,35 +1168,34 @@ static int update_poll_array(struct lttng_consumer_local_data *ctx,
 
        DBG("Updating poll fd array");
        *nb_inactive_fd = 0;
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
-               /*
-                * Only active streams with an active end point can be added to the
-                * poll set and local stream storage of the thread.
-                *
-                * There is a potential race here for endpoint_status to be updated
-                * just after the check. However, this is OK since the stream(s) will
-                * be deleted once the thread is notified that the end point state has
-                * changed where this function will be called back again.
-                *
-                * We track the number of inactive FDs because they still need to be
-                * closed by the polling thread after a wakeup on the data_pipe or
-                * metadata_pipe.
-                */
-               if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
-                       (*nb_inactive_fd)++;
-                       continue;
+
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
+                       /*
+                        * Only active streams with an active end point can be added to the
+                        * poll set and local stream storage of the thread.
+                        *
+                        * There is a potential race here for endpoint_status to be updated
+                        * just after the check. However, this is OK since the stream(s) will
+                        * be deleted once the thread is notified that the end point state has
+                        * changed where this function will be called back again.
+                        *
+                        * We track the number of inactive FDs because they still need to be
+                        * closed by the polling thread after a wakeup on the data_pipe or
+                        * metadata_pipe.
+                        */
+                       if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
+                               (*nb_inactive_fd)++;
+                               continue;
+                       }
+
+                       (*pollfd)[i].fd = stream->wait_fd;
+                       (*pollfd)[i].events = POLLIN | POLLPRI;
+                       local_stream[i] = stream;
+                       i++;
                }
-               /*
-                * This clobbers way too much the debug output. Uncomment that if you
-                * need it for debugging purposes.
-                */
-               (*pollfd)[i].fd = stream->wait_fd;
-               (*pollfd)[i].events = POLLIN | POLLPRI;
-               local_stream[i] = stream;
-               i++;
        }
-       rcu_read_unlock();
 
        /*
         * Insert the consumer_data_pipe at the end of the array and don't
@@ -1255,8 +1239,7 @@ restart:
 /*
  * Set the error socket.
  */
-void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
-               int sock)
+void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx, int sock)
 {
        ctx->consumer_error_socket = sock;
 }
@@ -1264,8 +1247,7 @@ void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
 /*
  * Set the command socket path.
  */
-void lttng_consumer_set_command_sock_path(
-               struct lttng_consumer_local_data *ctx, char *sock)
+void lttng_consumer_set_command_sock_path(struct lttng_consumer_local_data *ctx, char *sock)
 {
        ctx->consumer_command_sock_path = sock;
 }
@@ -1274,11 +1256,17 @@ void lttng_consumer_set_command_sock_path(
  * Send return code to the session daemon.
  * If the socket is not defined, we return 0, it is not a fatal error
  */
-int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
+int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx,
+                             enum lttcomm_return_code error_code)
 {
        if (ctx->consumer_error_socket > 0) {
-               return lttcomm_send_unix_sock(ctx->consumer_error_socket, &cmd,
-                               sizeof(enum lttcomm_sessiond_command));
+               const std::int32_t comm_code = std::int32_t(error_code);
+
+               static_assert(
+                       sizeof(comm_code) >= sizeof(std::underlying_type<lttcomm_return_code>),
+                       "Fixed-size communication type too small to accomodate lttcomm_return_code");
+               return lttcomm_send_unix_sock(
+                       ctx->consumer_error_socket, &comm_code, sizeof(comm_code));
        }
 
        return 0;
@@ -1288,21 +1276,21 @@ int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
  * Close all the tracefiles and stream fds and MUST be called when all
  * instances are destroyed i.e. when all threads were joined and are ended.
  */
-void lttng_consumer_cleanup(void)
+void lttng_consumer_cleanup()
 {
        struct lttng_ht_iter iter;
        struct lttng_consumer_channel *channel;
        unsigned int trace_chunks_left;
 
-       rcu_read_lock();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-       cds_lfht_for_each_entry(the_consumer_data.channel_ht->ht, &iter.iter,
-                       channel, node.node) {
-               consumer_del_channel(channel);
+               cds_lfht_for_each_entry (
+                       the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
+                       consumer_del_channel(channel);
+               }
        }
 
-       rcu_read_unlock();
-
        lttng_ht_destroy(the_consumer_data.channel_ht);
        lttng_ht_destroy(the_consumer_data.channels_by_session_id_ht);
 
@@ -1329,12 +1317,12 @@ void lttng_consumer_cleanup(void)
         * session daemon and not emptying the registry would cause an assertion
         * to hit.
         */
-       trace_chunks_left = lttng_trace_chunk_registry_put_each_chunk(
-                       the_consumer_data.chunk_registry);
+       trace_chunks_left =
+               lttng_trace_chunk_registry_put_each_chunk(the_consumer_data.chunk_registry);
        if (trace_chunks_left) {
                ERR("%u trace chunks are leaked by lttng-consumerd. "
-                               "This can be caused by an internal error of the session daemon.",
-                               trace_chunks_left);
+                   "This can be caused by an internal error of the session daemon.",
+                   trace_chunks_left);
        }
        /* Run all callbacks freeing each chunk. */
        rcu_barrier();
@@ -1357,15 +1345,11 @@ void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
        DBG("Consumer flag that it should quit");
 }
 
-
 /*
  * Flush pending writes to trace output disk file.
  */
-static
-void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
-               off_t orig_offset)
+static void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream, off_t orig_offset)
 {
-       int ret;
        int outfd = stream->out_fd;
 
        /*
@@ -1377,31 +1361,8 @@ void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
        if (orig_offset < stream->max_sb_size) {
                return;
        }
-       lttng_sync_file_range(outfd, orig_offset - stream->max_sb_size,
-                       stream->max_sb_size,
-                       SYNC_FILE_RANGE_WAIT_BEFORE
-                       | SYNC_FILE_RANGE_WRITE
-                       | SYNC_FILE_RANGE_WAIT_AFTER);
-       /*
-        * Give hints to the kernel about how we access the file:
-        * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
-        * we write it.
-        *
-        * We need to call fadvise again after the file grows because the
-        * kernel does not seem to apply fadvise to non-existing parts of the
-        * file.
-        *
-        * Call fadvise _after_ having waited for the page writeback to
-        * complete because the dirty page writeback semantic is not well
-        * defined. So it can be expected to lead to lower throughput in
-        * streaming.
-        */
-       ret = posix_fadvise(outfd, orig_offset - stream->max_sb_size,
-                       stream->max_sb_size, POSIX_FADV_DONTNEED);
-       if (ret && ret != -ENOSYS) {
-               errno = ret;
-               PERROR("posix_fadvise on fd %i", outfd);
-       }
+       lttng::io::hint_flush_range_dont_need_sync(
+               outfd, orig_offset - stream->max_sb_size, stream->max_sb_size);
 }
 
 /*
@@ -1418,30 +1379,31 @@ void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
  *
  * Returns a pointer to the new context or NULL on error.
  */
-struct lttng_consumer_local_data *lttng_consumer_create(
-               enum lttng_consumer_type type,
-               ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
-                       struct lttng_consumer_local_data *ctx, bool locked_by_caller),
-               int (*recv_channel)(struct lttng_consumer_channel *channel),
-               int (*recv_stream)(struct lttng_consumer_stream *stream),
-               int (*update_stream)(uint64_t stream_key, uint32_t state))
+struct lttng_consumer_local_data *
+lttng_consumer_create(enum lttng_consumer_type type,
+                     ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
+                                             struct lttng_consumer_local_data *ctx,
+                                             bool locked_by_caller),
+                     int (*recv_channel)(struct lttng_consumer_channel *channel),
+                     int (*recv_stream)(struct lttng_consumer_stream *stream),
+                     int (*update_stream)(uint64_t stream_key, uint32_t state))
 {
        int ret;
        struct lttng_consumer_local_data *ctx;
 
        LTTNG_ASSERT(the_consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
-                       the_consumer_data.type == type);
+                    the_consumer_data.type == type);
        the_consumer_data.type = type;
 
        ctx = zmalloc<lttng_consumer_local_data>();
-       if (ctx == NULL) {
+       if (ctx == nullptr) {
                PERROR("allocating context");
                goto error;
        }
 
        ctx->consumer_error_socket = -1;
        ctx->consumer_metadata_socket = -1;
-       pthread_mutex_init(&ctx->metadata_socket_lock, NULL);
+       pthread_mutex_init(&ctx->metadata_socket_lock, nullptr);
        /* assign the callbacks */
        ctx->on_buffer_ready = buffer_ready;
        ctx->on_recv_channel = recv_channel;
@@ -1490,7 +1452,7 @@ error_wakeup_pipe:
 error_poll_pipe:
        free(ctx);
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1501,19 +1463,20 @@ static void destroy_data_stream_ht(struct lttng_ht *ht)
        struct lttng_ht_iter iter;
        struct lttng_consumer_stream *stream;
 
-       if (ht == NULL) {
+       if (ht == nullptr) {
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
-               /*
-                * Ignore return value since we are currently cleaning up so any error
-                * can't be handled.
-                */
-               (void) consumer_del_stream(stream, ht);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
+                       /*
+                        * Ignore return value since we are currently cleaning up so any error
+                        * can't be handled.
+                        */
+                       (void) consumer_del_stream(stream, ht);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(ht);
 }
@@ -1527,19 +1490,20 @@ static void destroy_metadata_stream_ht(struct lttng_ht *ht)
        struct lttng_ht_iter iter;
        struct lttng_consumer_stream *stream;
 
-       if (ht == NULL) {
+       if (ht == nullptr) {
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
-               /*
-                * Ignore return value since we are currently cleaning up so any error
-                * can't be handled.
-                */
-               (void) consumer_del_metadata_stream(stream, ht);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
+                       /*
+                        * Ignore return value since we are currently cleaning up so any error
+                        * can't be handled.
+                        */
+                       (void) consumer_del_metadata_stream(stream, ht);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(ht);
 }
@@ -1581,9 +1545,8 @@ void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
 /*
  * Write the metadata stream id on the specified file descriptor.
  */
-static int write_relayd_metadata_id(int fd,
-               struct lttng_consumer_stream *stream,
-               unsigned long padding)
+static int
+write_relayd_metadata_id(int fd, struct lttng_consumer_stream *stream, unsigned long padding)
 {
        ssize_t ret;
        struct lttcomm_relayd_metadata_payload hdr;
@@ -1610,7 +1573,8 @@ static int write_relayd_metadata_id(int fd,
                goto end;
        }
        DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
-                       stream->relayd_stream_id, padding);
+           stream->relayd_stream_id,
+           padding);
 
 end:
        return (int) ret;
@@ -1627,29 +1591,27 @@ end:
  *
  * Returns the number of bytes written
  */
-ssize_t lttng_consumer_on_read_subbuffer_mmap(
-               struct lttng_consumer_stream *stream,
-               const struct lttng_buffer_view *buffer,
-               unsigned long padding)
+ssize_t lttng_consumer_on_read_subbuffer_mmap(struct lttng_consumer_stream *stream,
+                                             const struct lttng_buffer_view *buffer,
+                                             unsigned long padding)
 {
        ssize_t ret = 0;
        off_t orig_offset = stream->out_fd_offset;
        /* Default is on the disk */
        int outfd = stream->out_fd;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
        unsigned int relayd_hang_up = 0;
        const size_t subbuf_content_size = buffer->size - padding;
        size_t write_len;
 
        /* RCU lock for the relayd pointer */
-       rcu_read_lock();
-       LTTNG_ASSERT(stream->net_seq_idx != (uint64_t) -1ULL ||
-                       stream->trace_chunk);
+       lttng::urcu::read_lock_guard read_lock;
+       LTTNG_ASSERT(stream->net_seq_idx != (uint64_t) -1ULL || stream->trace_chunk);
 
        /* Flag that the current stream if set for network streaming. */
        if (stream->net_seq_idx != (uint64_t) -1ULL) {
                relayd = consumer_find_relayd(stream->net_seq_idx);
-               if (relayd == NULL) {
+               if (relayd == nullptr) {
                        ret = -EPIPE;
                        goto end;
                }
@@ -1668,8 +1630,8 @@ ssize_t lttng_consumer_on_read_subbuffer_mmap(
                        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
                        if (stream->reset_metadata_flag) {
                                ret = relayd_reset_metadata(&relayd->control_sock,
-                                               stream->relayd_stream_id,
-                                               stream->metadata_version);
+                                                           stream->relayd_stream_id,
+                                                           stream->metadata_version);
                                if (ret < 0) {
                                        relayd_hang_up = 1;
                                        goto write_error;
@@ -1712,8 +1674,8 @@ ssize_t lttng_consumer_on_read_subbuffer_mmap(
                 * Check if we need to change the tracefile before writing the packet.
                 */
                if (stream->chan->tracefile_size > 0 &&
-                               (stream->tracefile_size_current + buffer->size) >
-                               stream->chan->tracefile_size) {
+                   (stream->tracefile_size_current + buffer->size) >
+                           stream->chan->tracefile_size) {
                        ret = consumer_stream_rotate_output_files(stream);
                        if (ret) {
                                goto end;
@@ -1752,8 +1714,7 @@ ssize_t lttng_consumer_on_read_subbuffer_mmap(
                        DBG("Consumer mmap write detected relayd hang up");
                } else {
                        /* Unhandled error, print it and stop function right now. */
-                       PERROR("Error in write mmap (ret %zd != write_len %zu)", ret,
-                                       write_len);
+                       PERROR("Error in write mmap (ret %zd != write_len %zu)", ret, write_len);
                }
                goto write_error;
        }
@@ -1762,8 +1723,7 @@ ssize_t lttng_consumer_on_read_subbuffer_mmap(
        /* This call is useless on a socket so better save a syscall. */
        if (!relayd) {
                /* This won't block, but will start writeout asynchronously */
-               lttng_sync_file_range(outfd, stream->out_fd_offset, write_len,
-                               SYNC_FILE_RANGE_WRITE);
+               lttng::io::hint_flush_range_async(outfd, stream->out_fd_offset, write_len);
                stream->out_fd_offset += write_len;
                lttng_consumer_sync_trace_file(stream, orig_offset);
        }
@@ -1774,7 +1734,7 @@ write_error:
         * cleanup the relayd object and all associated streams.
         */
        if (relayd && relayd_hang_up) {
-               ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+               ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
                lttng_consumer_cleanup_relayd(relayd);
        }
 
@@ -1784,7 +1744,6 @@ end:
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
        }
 
-       rcu_read_unlock();
        return ret;
 }
 
@@ -1795,10 +1754,10 @@ end:
  *
  * Returns the number of bytes spliced.
  */
-ssize_t lttng_consumer_on_read_subbuffer_splice(
-               struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_stream *stream, unsigned long len,
-               unsigned long padding)
+ssize_t lttng_consumer_on_read_subbuffer_splice(struct lttng_consumer_local_data *ctx,
+                                               struct lttng_consumer_stream *stream,
+                                               unsigned long len,
+                                               unsigned long padding)
 {
        ssize_t ret = 0, written = 0, ret_splice = 0;
        loff_t offset = 0;
@@ -1806,7 +1765,7 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
        int fd = stream->wait_fd;
        /* Default is on the disk */
        int outfd = stream->out_fd;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
        int *splice_pipe;
        unsigned int relayd_hang_up = 0;
 
@@ -1823,12 +1782,12 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
        }
 
        /* RCU lock for the relayd pointer */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Flag that the current stream if set for network streaming. */
        if (stream->net_seq_idx != (uint64_t) -1ULL) {
                relayd = consumer_find_relayd(stream->net_seq_idx);
-               if (relayd == NULL) {
+               if (relayd == nullptr) {
                        written = -ret;
                        goto end;
                }
@@ -1848,16 +1807,15 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
 
                        if (stream->reset_metadata_flag) {
                                ret = relayd_reset_metadata(&relayd->control_sock,
-                                               stream->relayd_stream_id,
-                                               stream->metadata_version);
+                                                           stream->relayd_stream_id,
+                                                           stream->metadata_version);
                                if (ret < 0) {
                                        relayd_hang_up = 1;
                                        goto write_error;
                                }
                                stream->reset_metadata_flag = 0;
                        }
-                       ret = write_relayd_metadata_id(splice_pipe[1], stream,
-                                       padding);
+                       ret = write_relayd_metadata_id(splice_pipe[1], stream, padding);
                        if (ret < 0) {
                                written = ret;
                                relayd_hang_up = 1;
@@ -1891,8 +1849,7 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
                 * Check if we need to change the tracefile before writing the packet.
                 */
                if (stream->chan->tracefile_size > 0 &&
-                               (stream->tracefile_size_current + len) >
-                               stream->chan->tracefile_size) {
+                   (stream->tracefile_size_current + len) > stream->chan->tracefile_size) {
                        ret = consumer_stream_rotate_output_files(stream);
                        if (ret < 0) {
                                written = ret;
@@ -1906,9 +1863,12 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
 
        while (len > 0) {
                DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
-                               (unsigned long)offset, len, fd, splice_pipe[1]);
-               ret_splice = splice(fd, &offset, splice_pipe[1], NULL, len,
-                               SPLICE_F_MOVE | SPLICE_F_MORE);
+                   (unsigned long) offset,
+                   len,
+                   fd,
+                   splice_pipe[1]);
+               ret_splice = splice(
+                       fd, &offset, splice_pipe[1], nullptr, len, SPLICE_F_MOVE | SPLICE_F_MORE);
                DBG("splice chan to pipe, ret %zd", ret_splice);
                if (ret_splice < 0) {
                        ret = errno;
@@ -1933,10 +1893,13 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
                }
 
                /* Splice data out */
-               ret_splice = splice(splice_pipe[0], NULL, outfd, NULL,
-                               ret_splice, SPLICE_F_MOVE | SPLICE_F_MORE);
-               DBG("Consumer splice pipe to file (out_fd: %d), ret %zd",
-                               outfd, ret_splice);
+               ret_splice = splice(splice_pipe[0],
+                                   nullptr,
+                                   outfd,
+                                   nullptr,
+                                   ret_splice,
+                                   SPLICE_F_MOVE | SPLICE_F_MORE);
+               DBG("Consumer splice pipe to file (out_fd: %d), ret %zd", outfd, ret_splice);
                if (ret_splice < 0) {
                        ret = errno;
                        written = -ret;
@@ -1949,8 +1912,7 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
                         */
                        ret = errno;
                        written += ret_splice;
-                       PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice,
-                                       len);
+                       PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice, len);
                        goto splice_error;
                } else {
                        /* All good, update current len and continue. */
@@ -1960,8 +1922,7 @@ ssize_t lttng_consumer_on_read_subbuffer_splice(
                /* This call is useless on a socket so better save a syscall. */
                if (!relayd) {
                        /* This won't block, but will start writeout asynchronously */
-                       lttng_sync_file_range(outfd, stream->out_fd_offset, ret_splice,
-                                       SYNC_FILE_RANGE_WRITE);
+                       lttng::io::hint_flush_range_async(outfd, stream->out_fd_offset, ret_splice);
                        stream->out_fd_offset += ret_splice;
                }
                stream->output_written += ret_splice;
@@ -1978,7 +1939,7 @@ write_error:
         * cleanup the relayd object and all associated streams.
         */
        if (relayd && relayd_hang_up) {
-               ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+               ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
                lttng_consumer_cleanup_relayd(relayd);
                /* Skip splice error so the consumer does not fail */
                goto end;
@@ -2003,7 +1964,6 @@ end:
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
        }
 
-       rcu_read_unlock();
        return written;
 }
 
@@ -2051,8 +2011,7 @@ int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos)
+int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
 {
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -2072,8 +2031,7 @@ int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos)
+int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
 {
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -2089,7 +2047,8 @@ int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
 }
 
 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll)
+                           int sock,
+                           struct pollfd *consumer_sockpoll)
 {
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -2104,8 +2063,7 @@ int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
        }
 }
 
-static
-void lttng_consumer_close_all_metadata(void)
+static void lttng_consumer_close_all_metadata()
 {
        switch (the_consumer_data.type) {
        case LTTNG_CONSUMER_KERNEL:
@@ -2134,10 +2092,9 @@ void lttng_consumer_close_all_metadata(void)
 /*
  * Clean up a metadata stream and free its memory.
  */
-void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht)
+void consumer_del_metadata_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
 {
-       struct lttng_consumer_channel *channel = NULL;
+       struct lttng_consumer_channel *channel = nullptr;
        bool free_channel = false;
 
        LTTNG_ASSERT(stream);
@@ -2167,24 +2124,25 @@ void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
        consumer_stream_delete(stream, ht);
 
        /* Close down everything including the relayd if one. */
-       consumer_stream_close(stream);
+       consumer_stream_close_output(stream);
        /* Destroy tracer buffers of the stream. */
        consumer_stream_destroy_buffers(stream);
 
        /* Atomically decrement channel refcount since other threads can use it. */
-       if (!uatomic_sub_return(&channel->refcount, 1)
-                       && !uatomic_read(&channel->nb_init_stream_left)) {
+       if (!uatomic_sub_return(&channel->refcount, 1) &&
+           !uatomic_read(&channel->nb_init_stream_left)) {
                /* Go for channel deletion! */
                free_channel = true;
        }
-       stream->chan = NULL;
+       stream->chan = nullptr;
 
        /*
         * Nullify the stream reference so it is not used after deletion. The
         * channel lock MUST be acquired before being able to check for a NULL
         * pointer value.
         */
-       channel->metadata_stream = NULL;
+       channel->metadata_stream = nullptr;
+       channel->metadata_pushed_wait_queue.wake_all();
 
        if (channel->metadata_cache) {
                pthread_mutex_unlock(&channel->metadata_cache->lock);
@@ -2198,7 +2156,7 @@ void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
        }
 
        lttng_trace_chunk_put(stream->trace_chunk);
-       stream->trace_chunk = NULL;
+       stream->trace_chunk = nullptr;
        consumer_stream_free(stream);
 }
 
@@ -2227,7 +2185,7 @@ void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
         * after this point.
         */
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * Lookup the stream just to make sure it does not exist in our internal
@@ -2252,18 +2210,14 @@ void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
 
        lttng_ht_add_unique_u64(ht, &stream->node);
 
-       lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht,
-                       &stream->node_channel_id);
+       lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
 
        /*
         * Add stream to the stream_list_ht of the consumer data. No need to steal
         * the key since the HT does not use it and we allow to add redundant keys
         * into this table.
         */
-       lttng_ht_add_u64(the_consumer_data.stream_list_ht,
-                       &stream->node_session_id);
-
-       rcu_read_unlock();
+       lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
 
        pthread_mutex_unlock(&stream->lock);
        pthread_mutex_unlock(&stream->chan->lock);
@@ -2274,30 +2228,31 @@ void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
 /*
  * Delete data stream that are flagged for deletion (endpoint_status).
  */
-static void validate_endpoint_status_data_stream(void)
+static void validate_endpoint_status_data_stream()
 {
        struct lttng_ht_iter iter;
        struct lttng_consumer_stream *stream;
 
        DBG("Consumer delete flagged data stream");
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
-               /* Validate delete flag of the stream */
-               if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
-                       continue;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
+                       /* Validate delete flag of the stream */
+                       if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
+                               continue;
+                       }
+                       /* Delete it right now */
+                       consumer_del_stream(stream, data_ht);
                }
-               /* Delete it right now */
-               consumer_del_stream(stream, data_ht);
        }
-       rcu_read_unlock();
 }
 
 /*
  * Delete metadata stream that are flagged for deletion (endpoint_status).
  */
-static void validate_endpoint_status_metadata_stream(
-               struct lttng_poll_event *pollset)
+static void validate_endpoint_status_metadata_stream(struct lttng_poll_event *pollset)
 {
        struct lttng_ht_iter iter;
        struct lttng_consumer_stream *stream;
@@ -2306,22 +2261,23 @@ static void validate_endpoint_status_metadata_stream(
 
        LTTNG_ASSERT(pollset);
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
-               /* Validate delete flag of the stream */
-               if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
-                       continue;
-               }
-               /*
-                * Remove from pollset so the metadata thread can continue without
-                * blocking on a deleted stream.
-                */
-               lttng_poll_del(pollset, stream->wait_fd);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
+                       /* Validate delete flag of the stream */
+                       if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
+                               continue;
+                       }
+                       /*
+                        * Remove from pollset so the metadata thread can continue without
+                        * blocking on a deleted stream.
+                        */
+                       lttng_poll_del(pollset, stream->wait_fd);
 
-               /* Delete it right now */
-               consumer_del_metadata_stream(stream, metadata_ht);
+                       /* Delete it right now */
+                       consumer_del_metadata_stream(stream, metadata_ht);
+               }
        }
-       rcu_read_unlock();
 }
 
 /*
@@ -2332,7 +2288,7 @@ void *consumer_thread_metadata_poll(void *data)
 {
        int ret, i, pollfd, err = -1;
        uint32_t revents, nb_fd;
-       struct lttng_consumer_stream *stream = NULL;
+       struct lttng_consumer_stream *stream = nullptr;
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
        struct lttng_poll_event events;
@@ -2358,8 +2314,7 @@ void *consumer_thread_metadata_poll(void *data)
                goto end_poll;
        }
 
-       ret = lttng_poll_add(&events,
-                       lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
+       ret = lttng_poll_add(&events, lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
        if (ret < 0) {
                goto end;
        }
@@ -2367,14 +2322,13 @@ void *consumer_thread_metadata_poll(void *data)
        /* Main loop */
        DBG("Metadata main loop started");
 
-       while (1) {
-restart:
+       while (true) {
+       restart:
                health_code_update();
                health_poll_entry();
                DBG("Metadata poll wait");
                ret = lttng_poll_wait(&events, -1);
-               DBG("Metadata poll return from wait with %d fd(s)",
-                               LTTNG_POLL_GETNB(&events));
+               DBG("Metadata poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
                health_poll_exit();
                DBG("Metadata event caught in thread");
                if (ret < 0) {
@@ -2383,7 +2337,7 @@ restart:
                                goto restart;
                        }
                        if (LTTNG_POLL_GETNB(&events) == 0) {
-                               err = 0;        /* All is OK */
+                               err = 0; /* All is OK */
                        }
                        goto end;
                }
@@ -2402,46 +2356,55 @@ restart:
                                        ssize_t pipe_len;
 
                                        pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
-                                                       &stream, sizeof(stream));
-                                       if (pipe_len < sizeof(stream)) {
+                                                                  &stream,
+                                                                  sizeof(stream)); /* NOLINT sizeof
+                                                                                      used on a
+                                                                                      pointer. */
+                                       if (pipe_len < sizeof(stream)) { /* NOLINT sizeof used on a
+                                                                           pointer. */
                                                if (pipe_len < 0) {
                                                        PERROR("read metadata stream");
                                                }
                                                /*
-                                                * Remove the pipe from the poll set and continue the loop
-                                                * since their might be data to consume.
+                                                * Remove the pipe from the poll set and continue
+                                                * the loop since their might be data to consume.
                                                 */
-                                               lttng_poll_del(&events,
-                                                               lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
+                                               lttng_poll_del(
+                                                       &events,
+                                                       lttng_pipe_get_readfd(
+                                                               ctx->consumer_metadata_pipe));
                                                lttng_pipe_read_close(ctx->consumer_metadata_pipe);
                                                continue;
                                        }
 
                                        /* A NULL stream means that the state has changed. */
-                                       if (stream == NULL) {
+                                       if (stream == nullptr) {
                                                /* Check for deleted streams. */
                                                validate_endpoint_status_metadata_stream(&events);
                                                goto restart;
                                        }
 
                                        DBG("Adding metadata stream %d to poll set",
-                                                       stream->wait_fd);
+                                           stream->wait_fd);
 
                                        /* Add metadata stream to the global poll events list */
-                                       lttng_poll_add(&events, stream->wait_fd,
-                                                       LPOLLIN | LPOLLPRI | LPOLLHUP);
+                                       lttng_poll_add(
+                                               &events, stream->wait_fd, LPOLLIN | LPOLLPRI);
                                } else if (revents & (LPOLLERR | LPOLLHUP)) {
                                        DBG("Metadata thread pipe hung up");
                                        /*
                                         * Remove the pipe from the poll set and continue the loop
                                         * since their might be data to consume.
                                         */
-                                       lttng_poll_del(&events,
-                                                       lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
+                                       lttng_poll_del(
+                                               &events,
+                                               lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
                                        lttng_pipe_read_close(ctx->consumer_metadata_pipe);
                                        continue;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto end;
                                }
 
@@ -2449,7 +2412,7 @@ restart:
                                continue;
                        }
 
-                       rcu_read_lock();
+                       lttng::urcu::read_lock_guard read_lock;
                        {
                                uint64_t tmp_id = (uint64_t) pollfd;
 
@@ -2458,8 +2421,7 @@ restart:
                        node = lttng_ht_iter_get_node_u64(&iter);
                        LTTNG_ASSERT(node);
 
-                       stream = caa_container_of(node, struct lttng_consumer_stream,
-                                       node);
+                       stream = caa_container_of(node, struct lttng_consumer_stream, node);
 
                        if (revents & (LPOLLIN | LPOLLPRI)) {
                                /* Get the data out of the metadata file descriptor */
@@ -2487,9 +2449,8 @@ restart:
                        } else if (revents & (LPOLLERR | LPOLLHUP)) {
                                DBG("Metadata fd %d is hup|err.", pollfd);
                                if (!stream->hangup_flush_done &&
-                                               (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
-                                                               the_consumer_data.type ==
-                                                                               LTTNG_CONSUMER64_UST)) {
+                                   (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
+                                    the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
                                        DBG("Attempting to flush and consume the UST buffers");
                                        lttng_ustconsumer_on_stream_hangup(stream);
 
@@ -2499,10 +2460,10 @@ restart:
 
                                                len = ctx->on_buffer_ready(stream, ctx, false);
                                                /*
-                                                * We don't check the return value here since if we get
-                                                * a negative len, it means an error occurred thus we
-                                                * simply remove it from the poll set and free the
-                                                * stream.
+                                                * We don't check the return value here since if we
+                                                * get a negative len, it means an error occurred
+                                                * thus we simply remove it from the poll set and
+                                                * free the stream.
                                                 */
                                        } while (len > 0);
                                }
@@ -2515,11 +2476,9 @@ restart:
                                consumer_del_metadata_stream(stream, metadata_ht);
                        } else {
                                ERR("Unexpected poll events %u for sock %d", revents, pollfd);
-                               rcu_read_unlock();
                                goto end;
                        }
                        /* Release RCU lock for the stream looked up */
-                       rcu_read_unlock();
                }
        }
 
@@ -2537,7 +2496,7 @@ error_testpoint:
        }
        health_unregister(health_consumerd);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -2546,10 +2505,10 @@ error_testpoint:
  */
 void *consumer_thread_data_poll(void *data)
 {
-       int num_rdy, num_hup, high_prio, ret, i, err = -1;
-       struct pollfd *pollfd = NULL;
+       int num_rdy, high_prio, ret, i, err = -1;
+       struct pollfd *pollfd = nullptr;
        /* local view of the streams */
-       struct lttng_consumer_stream **local_stream = NULL, *new_stream = NULL;
+       struct lttng_consumer_stream **local_stream = nullptr, *new_stream = nullptr;
        /* local view of consumer_data.fds_count */
        int nb_fd = 0;
        /* 2 for the consumer_data_pipe and wake up pipe */
@@ -2570,16 +2529,15 @@ void *consumer_thread_data_poll(void *data)
        health_code_update();
 
        local_stream = zmalloc<lttng_consumer_stream *>();
-       if (local_stream == NULL) {
+       if (local_stream == nullptr) {
                PERROR("local_stream malloc");
                goto end;
        }
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                high_prio = 0;
-               num_hup = 0;
 
                /*
                 * the fds set has been updated, we need to update our
@@ -2588,27 +2546,29 @@ void *consumer_thread_data_poll(void *data)
                pthread_mutex_lock(&the_consumer_data.lock);
                if (the_consumer_data.need_update) {
                        free(pollfd);
-                       pollfd = NULL;
+                       pollfd = nullptr;
 
                        free(local_stream);
-                       local_stream = NULL;
+                       local_stream = nullptr;
 
                        /* Allocate for all fds */
-                       pollfd = calloc<struct pollfd>(the_consumer_data.stream_count + nb_pipes_fd);
-                       if (pollfd == NULL) {
+                       pollfd =
+                               calloc<struct pollfd>(the_consumer_data.stream_count + nb_pipes_fd);
+                       if (pollfd == nullptr) {
                                PERROR("pollfd malloc");
                                pthread_mutex_unlock(&the_consumer_data.lock);
                                goto end;
                        }
 
-                       local_stream = calloc<lttng_consumer_stream *>(the_consumer_data.stream_count + nb_pipes_fd);
-                       if (local_stream == NULL) {
+                       local_stream = calloc<lttng_consumer_stream *>(
+                               the_consumer_data.stream_count + nb_pipes_fd);
+                       if (local_stream == nullptr) {
                                PERROR("local_stream malloc");
                                pthread_mutex_unlock(&the_consumer_data.lock);
                                goto end;
                        }
-                       ret = update_poll_array(ctx, &pollfd, local_stream,
-                                       data_ht, &nb_inactive_fd);
+                       ret = update_poll_array(
+                               ctx, &pollfd, local_stream, data_ht, &nb_inactive_fd);
                        if (ret < 0) {
                                ERR("Error in allocating pollfd or local_outfds");
                                lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
@@ -2621,9 +2581,8 @@ void *consumer_thread_data_poll(void *data)
                pthread_mutex_unlock(&the_consumer_data.lock);
 
                /* No FDs and consumer_quit, consumer_cleanup the thread */
-               if (nb_fd == 0 && nb_inactive_fd == 0 &&
-                               CMM_LOAD_SHARED(consumer_quit) == 1) {
-                       err = 0;        /* All is OK */
+               if (nb_fd == 0 && nb_inactive_fd == 0 && CMM_LOAD_SHARED(consumer_quit) == 1) {
+                       err = 0; /* All is OK */
                        goto end;
                }
                /* poll on the array of fds */
@@ -2667,8 +2626,11 @@ void *consumer_thread_data_poll(void *data)
 
                        DBG("consumer_data_pipe wake up");
                        pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
-                                       &new_stream, sizeof(new_stream));
-                       if (pipe_readlen < sizeof(new_stream)) {
+                                                      &new_stream,
+                                                      sizeof(new_stream)); /* NOLINT sizeof used on
+                                                                              a pointer. */
+                       if (pipe_readlen < sizeof(new_stream)) { /* NOLINT sizeof used on a pointer.
+                                                                 */
                                PERROR("Consumer data pipe");
                                /* Continue so we can at least handle the current stream(s). */
                                continue;
@@ -2679,7 +2641,7 @@ void *consumer_thread_data_poll(void *data)
                         * the sessiond poll thread changed the consumer_quit state and is
                         * waking us up to test it.
                         */
-                       if (new_stream == NULL) {
+                       if (new_stream == nullptr) {
                                validate_endpoint_status_data_stream();
                                continue;
                        }
@@ -2693,8 +2655,8 @@ void *consumer_thread_data_poll(void *data)
                        char dummy;
                        ssize_t pipe_readlen;
 
-                       pipe_readlen = lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy,
-                                       sizeof(dummy));
+                       pipe_readlen =
+                               lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy, sizeof(dummy));
                        if (pipe_readlen < 0) {
                                PERROR("Consumer data wakeup pipe");
                        }
@@ -2706,7 +2668,7 @@ void *consumer_thread_data_poll(void *data)
                for (i = 0; i < nb_fd; i++) {
                        health_code_update();
 
-                       if (local_stream[i] == NULL) {
+                       if (local_stream[i] == nullptr) {
                                continue;
                        }
                        if (pollfd[i].revents & POLLPRI) {
@@ -2717,9 +2679,10 @@ void *consumer_thread_data_poll(void *data)
                                if (len < 0 && len != -EAGAIN && len != -ENODATA) {
                                        /* Clean the stream and free it. */
                                        consumer_del_stream(local_stream[i], data_ht);
-                                       local_stream[i] = NULL;
+                                       local_stream[i] = nullptr;
                                } else if (len > 0) {
-                                       local_stream[i]->has_data_left_to_be_read_before_teardown = 1;
+                                       local_stream[i]->has_data_left_to_be_read_before_teardown =
+                                               1;
                                }
                        }
                }
@@ -2736,21 +2699,21 @@ void *consumer_thread_data_poll(void *data)
                for (i = 0; i < nb_fd; i++) {
                        health_code_update();
 
-                       if (local_stream[i] == NULL) {
+                       if (local_stream[i] == nullptr) {
                                continue;
                        }
-                       if ((pollfd[i].revents & POLLIN) ||
-                                       local_stream[i]->hangup_flush_done ||
-                                       local_stream[i]->has_data) {
+                       if ((pollfd[i].revents & POLLIN) || local_stream[i]->hangup_flush_done ||
+                           local_stream[i]->has_data) {
                                DBG("Normal read on fd %d", pollfd[i].fd);
                                len = ctx->on_buffer_ready(local_stream[i], ctx, false);
                                /* it's ok to have an unavailable sub-buffer */
                                if (len < 0 && len != -EAGAIN && len != -ENODATA) {
                                        /* Clean the stream and free it. */
                                        consumer_del_stream(local_stream[i], data_ht);
-                                       local_stream[i] = NULL;
+                                       local_stream[i] = nullptr;
                                } else if (len > 0) {
-                                       local_stream[i]->has_data_left_to_be_read_before_teardown = 1;
+                                       local_stream[i]->has_data_left_to_be_read_before_teardown =
+                                               1;
                                }
                        }
                }
@@ -2759,15 +2722,15 @@ void *consumer_thread_data_poll(void *data)
                for (i = 0; i < nb_fd; i++) {
                        health_code_update();
 
-                       if (local_stream[i] == NULL) {
+                       if (local_stream[i] == nullptr) {
                                continue;
                        }
-                       if (!local_stream[i]->hangup_flush_done
-                                       && (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
-                                       && (the_consumer_data.type == LTTNG_CONSUMER32_UST
-                                               || the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
+                       if (!local_stream[i]->hangup_flush_done &&
+                           (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL)) &&
+                           (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
+                            the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
                                DBG("fd %d is hup|err|nval. Attempting flush and read.",
-                                               pollfd[i].fd);
+                                   pollfd[i].fd);
                                lttng_ustconsumer_on_stream_hangup(local_stream[i]);
                                /* Attempt read again, for the data we just flushed. */
                                local_stream[i]->has_data_left_to_be_read_before_teardown = 1;
@@ -2789,25 +2752,22 @@ void *consumer_thread_data_poll(void *data)
                                DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
                                if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
                                        consumer_del_stream(local_stream[i], data_ht);
-                                       local_stream[i] = NULL;
-                                       num_hup++;
+                                       local_stream[i] = nullptr;
                                }
                        } else if (pollfd[i].revents & POLLERR) {
                                ERR("Error returned in polling fd %d.", pollfd[i].fd);
                                if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
                                        consumer_del_stream(local_stream[i], data_ht);
-                                       local_stream[i] = NULL;
-                                       num_hup++;
+                                       local_stream[i] = nullptr;
                                }
                        } else if (pollfd[i].revents & POLLNVAL) {
                                ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
                                if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
                                        consumer_del_stream(local_stream[i], data_ht);
-                                       local_stream[i] = NULL;
-                                       num_hup++;
+                                       local_stream[i] = nullptr;
                                }
                        }
-                       if (local_stream[i] != NULL) {
+                       if (local_stream[i] != nullptr) {
                                local_stream[i]->has_data_left_to_be_read_before_teardown = 0;
                        }
                }
@@ -2837,7 +2797,7 @@ error_testpoint:
        health_unregister(health_consumerd);
 
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -2845,8 +2805,7 @@ error_testpoint:
  * allow the poll() on the stream read-side to detect when the
  * write-side (application) finally closes them.
  */
-static
-void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
+static void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
 {
        struct lttng_ht *ht;
        struct lttng_consumer_stream *stream;
@@ -2854,11 +2813,15 @@ void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
 
        ht = the_consumer_data.stream_per_chan_id_ht;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key,
-                       &iter.iter, stream, node_channel_id.node) {
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                /*
                 * Protect against teardown with mutex.
                 */
@@ -2890,7 +2853,6 @@ void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
        next:
                pthread_mutex_unlock(&stream->lock);
        }
-       rcu_read_unlock();
 }
 
 static void destroy_channel_ht(struct lttng_ht *ht)
@@ -2899,16 +2861,18 @@ static void destroy_channel_ht(struct lttng_ht *ht)
        struct lttng_consumer_channel *channel;
        int ret;
 
-       if (ht == NULL) {
+       if (ht == nullptr) {
                return;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(ht->ht, &iter.iter, channel, wait_fd_node.node) {
-               ret = lttng_ht_del(ht, &iter);
-               LTTNG_ASSERT(ret != 0);
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (ht->ht, &iter.iter, channel, wait_fd_node.node) {
+                       ret = lttng_ht_del(ht, &iter);
+                       LTTNG_ASSERT(ret != 0);
+               }
        }
-       rcu_read_unlock();
 
        lttng_ht_destroy(ht);
 }
@@ -2924,7 +2888,7 @@ void *consumer_thread_channel_poll(void *data)
 {
        int ret, i, pollfd, err = -1;
        uint32_t revents, nb_fd;
-       struct lttng_consumer_channel *chan = NULL;
+       struct lttng_consumer_channel *chan = nullptr;
        struct lttng_ht_iter iter;
        struct lttng_ht_node_u64 *node;
        struct lttng_poll_event events;
@@ -2964,14 +2928,13 @@ void *consumer_thread_channel_poll(void *data)
        /* Main loop */
        DBG("Channel main loop started");
 
-       while (1) {
-restart:
+       while (true) {
+       restart:
                health_code_update();
                DBG("Channel poll wait");
                health_poll_entry();
                ret = lttng_poll_wait(&events, -1);
-               DBG("Channel poll return from wait with %d fd(s)",
-                               LTTNG_POLL_GETNB(&events));
+               DBG("Channel poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
                health_poll_exit();
                DBG("Channel event caught in thread");
                if (ret < 0) {
@@ -2980,7 +2943,7 @@ restart:
                                goto restart;
                        }
                        if (LTTNG_POLL_GETNB(&events) == 0) {
-                               err = 0;        /* All is OK */
+                               err = 0; /* All is OK */
                        }
                        goto end;
                }
@@ -3004,41 +2967,45 @@ restart:
                                                if (ret < 0) {
                                                        ERR("Error reading channel pipe");
                                                }
-                                               lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
+                                               lttng_poll_del(&events,
+                                                              ctx->consumer_channel_pipe[0]);
                                                continue;
                                        }
 
                                        switch (action) {
                                        case CONSUMER_CHANNEL_ADD:
-                                               DBG("Adding channel %d to poll set",
-                                                       chan->wait_fd);
+                                       {
+                                               DBG("Adding channel %d to poll set", chan->wait_fd);
 
                                                lttng_ht_node_init_u64(&chan->wait_fd_node,
-                                                       chan->wait_fd);
-                                               rcu_read_lock();
+                                                                      chan->wait_fd);
+                                               lttng::urcu::read_lock_guard read_lock;
                                                lttng_ht_add_unique_u64(channel_ht,
-                                                               &chan->wait_fd_node);
-                                               rcu_read_unlock();
+                                                                       &chan->wait_fd_node);
                                                /* Add channel to the global poll events list */
-                                               lttng_poll_add(&events, chan->wait_fd,
-                                                               LPOLLERR | LPOLLHUP);
+                                               // FIXME: Empty flag on a pipe pollset, this might
+                                               // hang on FreeBSD.
+                                               lttng_poll_add(&events, chan->wait_fd, 0);
                                                break;
+                                       }
                                        case CONSUMER_CHANNEL_DEL:
                                        {
                                                /*
-                                                * This command should never be called if the channel
-                                                * has streams monitored by either the data or metadata
-                                                * thread. The consumer only notify this thread with a
-                                                * channel del. command if it receives a destroy
-                                                * channel command from the session daemon that send it
-                                                * if a command prior to the GET_CHANNEL failed.
+                                                * This command should never be called if the
+                                                * channel has streams monitored by either the data
+                                                * or metadata thread. The consumer only notify this
+                                                * thread with a channel del. command if it receives
+                                                * a destroy channel command from the session daemon
+                                                * that send it if a command prior to the
+                                                * GET_CHANNEL failed.
                                                 */
 
-                                               rcu_read_lock();
+                                               lttng::urcu::read_lock_guard read_lock;
                                                chan = consumer_find_channel(key);
                                                if (!chan) {
-                                                       rcu_read_unlock();
-                                                       ERR("UST consumer get channel key %" PRIu64 " not found for del channel", key);
+                                                       ERR("UST consumer get channel key %" PRIu64
+                                                           " not found for del channel",
+                                                           key);
                                                        break;
                                                }
                                                lttng_poll_del(&events, chan->wait_fd);
@@ -3052,7 +3019,8 @@ restart:
                                                case LTTNG_CONSUMER32_UST:
                                                case LTTNG_CONSUMER64_UST:
                                                        health_code_update();
-                                                       /* Destroy streams that might have been left in the stream list. */
+                                                       /* Destroy streams that might have been left
+                                                        * in the stream list. */
                                                        clean_channel_stream_list(chan);
                                                        break;
                                                default:
@@ -3061,21 +3029,21 @@ restart:
                                                }
 
                                                /*
-                                                * Release our own refcount. Force channel deletion even if
-                                                * streams were not initialized.
+                                                * Release our own refcount. Force channel deletion
+                                                * even if streams were not initialized.
                                                 */
                                                if (!uatomic_sub_return(&chan->refcount, 1)) {
                                                        consumer_del_channel(chan);
                                                }
-                                               rcu_read_unlock();
                                                goto restart;
                                        }
                                        case CONSUMER_CHANNEL_QUIT:
                                                /*
-                                                * Remove the pipe from the poll set and continue the loop
-                                                * since their might be data to consume.
+                                                * Remove the pipe from the poll set and continue
+                                                * the loop since their might be data to consume.
                                                 */
-                                               lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
+                                               lttng_poll_del(&events,
+                                                              ctx->consumer_channel_pipe[0]);
                                                continue;
                                        default:
                                                ERR("Unknown action");
@@ -3090,7 +3058,9 @@ restart:
                                        lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
                                        continue;
                                } else {
-                                       ERR("Unexpected poll events %u for sock %d", revents, pollfd);
+                                       ERR("Unexpected poll events %u for sock %d",
+                                           revents,
+                                           pollfd);
                                        goto end;
                                }
 
@@ -3098,7 +3068,7 @@ restart:
                                continue;
                        }
 
-                       rcu_read_lock();
+                       lttng::urcu::read_lock_guard read_lock;
                        {
                                uint64_t tmp_id = (uint64_t) pollfd;
 
@@ -3107,8 +3077,7 @@ restart:
                        node = lttng_ht_iter_get_node_u64(&iter);
                        LTTNG_ASSERT(node);
 
-                       chan = caa_container_of(node, struct lttng_consumer_channel,
-                                       wait_fd_node);
+                       chan = caa_container_of(node, struct lttng_consumer_channel, wait_fd_node);
 
                        /* Check for error event */
                        if (revents & (LPOLLERR | LPOLLHUP)) {
@@ -3126,18 +3095,16 @@ restart:
                                consumer_close_channel_streams(chan);
 
                                /* Release our own refcount */
-                               if (!uatomic_sub_return(&chan->refcount, 1)
-                                               && !uatomic_read(&chan->nb_init_stream_left)) {
+                               if (!uatomic_sub_return(&chan->refcount, 1) &&
+                                   !uatomic_read(&chan->nb_init_stream_left)) {
                                        consumer_del_channel(chan);
                                }
                        } else {
                                ERR("Unexpected poll events %u for sock %d", revents, pollfd);
-                               rcu_read_unlock();
                                goto end;
                        }
 
                        /* Release RCU lock for the channel looked up */
-                       rcu_read_unlock();
                }
        }
 
@@ -3156,11 +3123,12 @@ error_testpoint:
        }
        health_unregister(health_consumerd);
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
-               struct pollfd *sockpoll, int client_socket)
+                              struct pollfd *sockpoll,
+                              int client_socket)
 {
        int ret;
 
@@ -3278,7 +3246,7 @@ void *consumer_thread_sessiond_poll(void *data)
        consumer_sockpoll[1].fd = sock;
        consumer_sockpoll[1].events = POLLIN | POLLPRI;
 
-       while (1) {
+       while (true) {
                health_code_update();
 
                health_poll_entry();
@@ -3304,7 +3272,7 @@ void *consumer_thread_sessiond_poll(void *data)
                }
                if (CMM_LOAD_SHARED(consumer_quit)) {
                        DBG("consumer_thread_receive_fds received quit from signal");
-                       err = 0;        /* All is OK */
+                       err = 0; /* All is OK */
                        goto end;
                }
                DBG("Received command on sock");
@@ -3335,7 +3303,7 @@ end:
         */
        notify_thread_lttng_pipe(ctx->consumer_data_pipe);
 
-       notify_channel_pipe(ctx, NULL, -1, CONSUMER_CHANNEL_QUIT);
+       notify_channel_pipe(ctx, nullptr, -1, CONSUMER_CHANNEL_QUIT);
 
        notify_health_quit_pipe(health_quit_pipe);
 
@@ -3361,22 +3329,21 @@ error_testpoint:
        health_unregister(health_consumerd);
 
        rcu_unregister_thread();
-       return NULL;
+       return nullptr;
 }
 
 static int post_consume(struct lttng_consumer_stream *stream,
-               const struct stream_subbuffer *subbuffer,
-               struct lttng_consumer_local_data *ctx)
+                       const struct stream_subbuffer *subbuffer,
+                       struct lttng_consumer_local_data *ctx)
 {
        size_t i;
        int ret = 0;
-       const size_t count = lttng_dynamic_array_get_count(
-                       &stream->read_subbuffer_ops.post_consume_cbs);
+       const size_t count =
+               lttng_dynamic_array_get_count(&stream->read_subbuffer_ops.post_consume_cbs);
 
        for (i = 0; i < count; i++) {
                const post_consume_cb op = *(post_consume_cb *) lttng_dynamic_array_get_element(
-                               &stream->read_subbuffer_ops.post_consume_cbs,
-                               i);
+                       &stream->read_subbuffer_ops.post_consume_cbs, i);
 
                ret = op(stream, subbuffer, ctx);
                if (ret) {
@@ -3388,8 +3355,8 @@ end:
 }
 
 ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx,
-               bool locked_by_caller)
+                                     struct lttng_consumer_local_data *ctx,
+                                     bool locked_by_caller)
 {
        ssize_t ret, written_bytes = 0;
        int rotation_ret;
@@ -3422,8 +3389,7 @@ ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
                }
        }
 
-       get_next_status = stream->read_subbuffer_ops.get_next_subbuffer(
-                       stream, &subbuffer);
+       get_next_status = stream->read_subbuffer_ops.get_next_subbuffer(stream, &subbuffer);
        switch (get_next_status) {
        case GET_NEXT_SUBBUFFER_STATUS_OK:
                break;
@@ -3438,14 +3404,12 @@ ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
                abort();
        }
 
-       ret = stream->read_subbuffer_ops.pre_consume_subbuffer(
-                       stream, &subbuffer);
+       ret = stream->read_subbuffer_ops.pre_consume_subbuffer(stream, &subbuffer);
        if (ret) {
                goto error_put_subbuf;
        }
 
-       written_bytes = stream->read_subbuffer_ops.consume_subbuffer(
-                       ctx, stream, &subbuffer);
+       written_bytes = stream->read_subbuffer_ops.consume_subbuffer(ctx, stream, &subbuffer);
        if (written_bytes <= 0) {
                ERR("Error consuming subbuffer: (%zd)", written_bytes);
                ret = (int) written_bytes;
@@ -3519,15 +3483,14 @@ int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream)
 /*
  * Allocate and set consumer data hash tables.
  */
-int lttng_consumer_init(void)
+int lttng_consumer_init()
 {
        the_consumer_data.channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        if (!the_consumer_data.channel_ht) {
                goto error;
        }
 
-       the_consumer_data.channels_by_session_id_ht =
-                       lttng_ht_new(0, LTTNG_HT_TYPE_U64);
+       the_consumer_data.channels_by_session_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        if (!the_consumer_data.channels_by_session_id_ht) {
                goto error;
        }
@@ -3542,8 +3505,7 @@ int lttng_consumer_init(void)
                goto error;
        }
 
-       the_consumer_data.stream_per_chan_id_ht =
-                       lttng_ht_new(0, LTTNG_HT_TYPE_U64);
+       the_consumer_data.stream_per_chan_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
        if (!the_consumer_data.stream_per_chan_id_ht) {
                goto error;
        }
@@ -3576,19 +3538,19 @@ error:
  * The caller MUST acquire a RCU read side lock before calling it.
  */
 void consumer_add_relayd_socket(uint64_t net_seq_idx,
-               int sock_type,
-               struct lttng_consumer_local_data *ctx,
-               int sock,
-               struct pollfd *consumer_sockpoll,
-               uint64_t sessiond_id,
-               uint64_t relayd_session_id,
-               uint32_t relayd_version_major,
-               uint32_t relayd_version_minor,
-               enum lttcomm_sock_proto relayd_socket_protocol)
+                               int sock_type,
+                               struct lttng_consumer_local_data *ctx,
+                               int sock,
+                               struct pollfd *consumer_sockpoll,
+                               uint64_t sessiond_id,
+                               uint64_t relayd_session_id,
+                               uint32_t relayd_version_major,
+                               uint32_t relayd_version_minor,
+                               enum lttcomm_sock_proto relayd_socket_protocol)
 {
        int fd = -1, ret = -1, relayd_created = 0;
        enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
 
        LTTNG_ASSERT(ctx);
        LTTNG_ASSERT(sock >= 0);
@@ -3598,11 +3560,11 @@ void consumer_add_relayd_socket(uint64_t net_seq_idx,
 
        /* Get relayd reference if exists. */
        relayd = consumer_find_relayd(net_seq_idx);
-       if (relayd == NULL) {
+       if (relayd == nullptr) {
                LTTNG_ASSERT(sock_type == LTTNG_STREAM_CONTROL);
                /* Not found. Allocate one. */
                relayd = consumer_allocate_relayd_sock_pair(net_seq_idx);
-               if (relayd == NULL) {
+               if (relayd == nullptr) {
                        ret_code = LTTCOMM_CONSUMERD_ENOMEM;
                        goto error;
                } else {
@@ -3641,7 +3603,7 @@ void consumer_add_relayd_socket(uint64_t net_seq_idx,
        /* Get relayd socket from session daemon */
        ret = lttcomm_recv_fds_unix_sock(sock, &fd, 1);
        if (ret != sizeof(fd)) {
-               fd = -1;        /* Just in case it gets set with an invalid value. */
+               fd = -1; /* Just in case it gets set with an invalid value. */
 
                /*
                 * Failing to receive FDs might indicate a major problem such as
@@ -3662,8 +3624,7 @@ void consumer_add_relayd_socket(uint64_t net_seq_idx,
        case LTTNG_STREAM_CONTROL:
                /* Copy received lttcomm socket */
                ret = lttcomm_populate_sock_from_open_socket(
-                               &relayd->control_sock.sock, fd,
-                               relayd_socket_protocol);
+                       &relayd->control_sock.sock, fd, relayd_socket_protocol);
 
                /* Assign version values. */
                relayd->control_sock.major = relayd_version_major;
@@ -3675,8 +3636,7 @@ void consumer_add_relayd_socket(uint64_t net_seq_idx,
        case LTTNG_STREAM_DATA:
                /* Copy received lttcomm socket */
                ret = lttcomm_populate_sock_from_open_socket(
-                               &relayd->data_sock.sock, fd,
-                               relayd_socket_protocol);
+                       &relayd->data_sock.sock, fd, relayd_socket_protocol);
                /* Assign version values. */
                relayd->data_sock.major = relayd_version_major;
                relayd->data_sock.minor = relayd_version_minor;
@@ -3693,8 +3653,9 @@ void consumer_add_relayd_socket(uint64_t net_seq_idx,
        }
 
        DBG("Consumer %s socket created successfully with net idx %" PRIu64 " (fd: %d)",
-                       sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
-                       relayd->net_seq_idx, fd);
+           sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
+           relayd->net_seq_idx,
+           fd);
        /*
         * We gave the ownership of the fd to the relayd structure. Set the
         * fd to -1 so we don't call close() on it in the error path below.
@@ -3746,13 +3707,12 @@ error_nosignal:
 static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
 {
        struct lttng_ht_iter iter;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
 
        ASSERT_RCU_READ_LOCKED();
 
        /* Iterate over all relayd since they are indexed by net_seq_idx. */
-       cds_lfht_for_each_entry(the_consumer_data.relayd_ht->ht, &iter.iter,
-                       relayd, node.node) {
+       cds_lfht_for_each_entry (the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
                /*
                 * Check by sessiond id which is unique here where the relayd session
                 * id might not be when having multiple relayd.
@@ -3763,7 +3723,7 @@ static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
                }
        }
 
-       return NULL;
+       return nullptr;
 
 found:
        return relayd;
@@ -3781,12 +3741,12 @@ int consumer_data_pending(uint64_t id)
        struct lttng_ht_iter iter;
        struct lttng_ht *ht;
        struct lttng_consumer_stream *stream;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
        int (*data_pending)(struct lttng_consumer_stream *);
 
        DBG("Consumer data pending command on session id %" PRIu64, id);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        pthread_mutex_lock(&the_consumer_data.lock);
 
        switch (the_consumer_data.type) {
@@ -3806,9 +3766,13 @@ int consumer_data_pending(uint64_t id)
        ht = the_consumer_data.stream_list_ht;
 
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&id, lttng_ht_seed),
-                       ht->match_fct, &id,
-                       &iter.iter, stream, node_session_id.node) {
+                                         ht->hash_fct(&id, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &id,
+                                         &iter.iter,
+                                         stream,
+                                         node_session_id.node)
+       {
                pthread_mutex_lock(&stream->lock);
 
                /*
@@ -3836,8 +3800,7 @@ int consumer_data_pending(uint64_t id)
 
                /* Send init command for data pending. */
                pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-               ret = relayd_begin_data_pending(&relayd->control_sock,
-                               relayd->relayd_session_id);
+               ret = relayd_begin_data_pending(&relayd->control_sock, relayd->relayd_session_id);
                if (ret < 0) {
                        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                        /* Communication error thus the relayd so no data pending. */
@@ -3845,23 +3808,28 @@ int consumer_data_pending(uint64_t id)
                }
 
                cds_lfht_for_each_entry_duplicate(ht->ht,
-                               ht->hash_fct(&id, lttng_ht_seed),
-                               ht->match_fct, &id,
-                               &iter.iter, stream, node_session_id.node) {
+                                                 ht->hash_fct(&id, lttng_ht_seed),
+                                                 ht->match_fct,
+                                                 &id,
+                                                 &iter.iter,
+                                                 stream,
+                                                 node_session_id.node)
+               {
                        if (stream->metadata_flag) {
                                ret = relayd_quiescent_control(&relayd->control_sock,
-                                               stream->relayd_stream_id);
+                                                              stream->relayd_stream_id);
                        } else {
                                ret = relayd_data_pending(&relayd->control_sock,
-                                               stream->relayd_stream_id,
-                                               stream->next_net_seq_num - 1);
+                                                         stream->relayd_stream_id,
+                                                         stream->next_net_seq_num - 1);
                        }
 
                        if (ret == 1) {
                                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                                goto data_pending;
                        } else if (ret < 0) {
-                               ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+                               ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64 ".",
+                                   relayd->net_seq_idx);
                                lttng_consumer_cleanup_relayd(relayd);
                                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                                goto data_not_pending;
@@ -3869,11 +3837,12 @@ int consumer_data_pending(uint64_t id)
                }
 
                /* Send end command for data pending. */
-               ret = relayd_end_data_pending(&relayd->control_sock,
-                               relayd->relayd_session_id, &is_data_inflight);
+               ret = relayd_end_data_pending(
+                       &relayd->control_sock, relayd->relayd_session_id, &is_data_inflight);
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                if (ret < 0) {
-                       ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
+                       ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64 ".",
+                           relayd->net_seq_idx);
                        lttng_consumer_cleanup_relayd(relayd);
                        goto data_not_pending;
                }
@@ -3891,13 +3860,11 @@ int consumer_data_pending(uint64_t id)
 data_not_pending:
        /* Data is available to be read by a viewer. */
        pthread_mutex_unlock(&the_consumer_data.lock);
-       rcu_read_unlock();
        return 0;
 
 data_pending:
        /* Data is still being extracted from buffers. */
        pthread_mutex_unlock(&the_consumer_data.lock);
-       rcu_read_unlock();
        return 1;
 }
 
@@ -3921,8 +3888,7 @@ int consumer_send_status_msg(int sock, int ret_code)
  *
  * Return the sendmsg() return value.
  */
-int consumer_send_status_channel(int sock,
-               struct lttng_consumer_channel *channel)
+int consumer_send_status_channel(int sock, struct lttng_consumer_channel *channel)
 {
        struct lttcomm_consumer_status_channel msg;
 
@@ -3941,25 +3907,27 @@ int consumer_send_status_channel(int sock,
 }
 
 unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
-               unsigned long produced_pos, uint64_t nb_packets_per_stream,
-               uint64_t max_sb_size)
+                                            unsigned long produced_pos,
+                                            uint64_t nb_packets_per_stream,
+                                            uint64_t max_sb_size)
 {
        unsigned long start_pos;
 
        if (!nb_packets_per_stream) {
-               return consumed_pos;    /* Grab everything */
+               return consumed_pos; /* Grab everything */
        }
        start_pos = produced_pos - lttng_offset_align_floor(produced_pos, max_sb_size);
        start_pos -= max_sb_size * nb_packets_per_stream;
        if ((long) (start_pos - consumed_pos) < 0) {
-               return consumed_pos;    /* Grab everything */
+               return consumed_pos; /* Grab everything */
        }
        return start_pos;
 }
 
 /* Stream lock must be held by the caller. */
 static int sample_stream_positions(struct lttng_consumer_stream *stream,
-                           unsigned long *produced, unsigned long *consumed)
+                                  unsigned long *produced,
+                                  unsigned long *consumed)
 {
        int ret;
 
@@ -3997,7 +3965,8 @@ end:
  * Returns 0 on success, < 0 on error
  */
 int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
-               uint64_t key, uint64_t relayd_id)
+                                 uint64_t key,
+                                 uint64_t relayd_id)
 {
        int ret;
        struct lttng_consumer_stream *stream;
@@ -4007,7 +3976,7 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
        uint64_t next_chunk_id, stream_count = 0;
        enum lttng_trace_chunk_status chunk_status;
        const bool is_local_trace = relayd_id == -1ULL;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
        bool rotating_to_new_chunk = true;
        /* Array of `struct lttng_consumer_stream *` */
        struct lttng_dynamic_pointer_array streams_packet_to_open;
@@ -4018,24 +3987,28 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
        DBG("Consumer sample rotate position for channel %" PRIu64, key);
 
        lttng_dynamic_array_init(&stream_rotation_positions,
-                       sizeof(struct relayd_stream_rotation_position), NULL);
-       lttng_dynamic_pointer_array_init(&streams_packet_to_open, NULL);
+                                sizeof(struct relayd_stream_rotation_position),
+                                nullptr);
+       lttng_dynamic_pointer_array_init(&streams_packet_to_open, nullptr);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        pthread_mutex_lock(&channel->lock);
        LTTNG_ASSERT(channel->trace_chunk);
-       chunk_status = lttng_trace_chunk_get_id(channel->trace_chunk,
-                       &next_chunk_id);
+       chunk_status = lttng_trace_chunk_get_id(channel->trace_chunk, &next_chunk_id);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end_unlock_channel;
        }
 
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key, &iter.iter,
-                       stream, node_channel_id.node) {
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                unsigned long produced_pos = 0, consumed_pos = 0;
 
                health_code_update();
@@ -4094,7 +4067,8 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                                         * for this stream during this trace
                                         * chunk's lifetime.
                                         */
-                                       ret = sample_stream_positions(stream, &produced_pos, &consumed_pos);
+                                       ret = sample_stream_positions(
+                                               stream, &produced_pos, &consumed_pos);
                                        if (ret) {
                                                goto end_unlock_stream;
                                        }
@@ -4110,9 +4084,9 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                                                uint64_t trace_chunk_id;
 
                                                chunk_status = lttng_trace_chunk_get_name(
-                                                               stream->trace_chunk,
-                                                               &trace_chunk_name,
-                                                               NULL);
+                                                       stream->trace_chunk,
+                                                       &trace_chunk_name,
+                                                       nullptr);
                                                if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NONE) {
                                                        trace_chunk_name = "none";
                                                }
@@ -4122,15 +4096,17 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                                                 * never anonymous.
                                                 */
                                                chunk_status = lttng_trace_chunk_get_id(
-                                                               stream->trace_chunk,
-                                                               &trace_chunk_id);
+                                                       stream->trace_chunk, &trace_chunk_id);
                                                LTTNG_ASSERT(chunk_status ==
-                                                               LTTNG_TRACE_CHUNK_STATUS_OK);
+                                                            LTTNG_TRACE_CHUNK_STATUS_OK);
 
                                                DBG("Unable to open packet for stream during trace chunk's lifetime. "
-                                                               "Flushing an empty packet to prevent an empty file from being created: "
-                                                               "stream id = %" PRIu64 ", trace chunk name = `%s`, trace chunk id = %" PRIu64,
-                                                               stream->key, trace_chunk_name, trace_chunk_id);
+                                                   "Flushing an empty packet to prevent an empty file from being created: "
+                                                   "stream id = %" PRIu64
+                                                   ", trace chunk name = `%s`, trace chunk id = %" PRIu64,
+                                                   stream->key,
+                                                   trace_chunk_name,
+                                                   trace_chunk_id);
                                        }
                                }
                        }
@@ -4142,7 +4118,7 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                        ret = consumer_stream_flush_buffer(stream, flush_active);
                        if (ret < 0) {
                                ERR("Failed to flush stream %" PRIu64 " during channel rotation",
-                                               stream->key);
+                                   stream->key);
                                goto end_unlock_stream;
                        }
                }
@@ -4153,15 +4129,13 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                        goto end_unlock_stream;
                }
                if (!ret) {
-                       ret = lttng_consumer_get_produced_snapshot(stream,
-                                       &produced_pos);
+                       ret = lttng_consumer_get_produced_snapshot(stream, &produced_pos);
                        if (ret < 0) {
                                ERR("Failed to sample produced position during channel rotation");
                                goto end_unlock_stream;
                        }
 
-                       ret = lttng_consumer_get_consumed_snapshot(stream,
-                                       &consumed_pos);
+                       ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos);
                        if (ret < 0) {
                                ERR("Failed to sample consumed position during channel rotation");
                                goto end_unlock_stream;
@@ -4174,12 +4148,16 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                produced_pos = lttng_align_floor(produced_pos, stream->max_sb_size);
                if (consumed_pos == produced_pos) {
                        DBG("Set rotate ready for stream %" PRIu64 " produced = %lu consumed = %lu",
-                                       stream->key, produced_pos, consumed_pos);
+                           stream->key,
+                           produced_pos,
+                           consumed_pos);
                        stream->rotate_ready = true;
                } else {
                        DBG("Different consumed and produced positions "
-                                       "for stream %" PRIu64 " produced = %lu consumed = %lu",
-                                       stream->key, produced_pos, consumed_pos);
+                           "for stream %" PRIu64 " produced = %lu consumed = %lu",
+                           stream->key,
+                           produced_pos,
+                           consumed_pos);
                }
                /*
                 * The rotation position is based on the packet_seq_num of the
@@ -4198,14 +4176,15 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                         * not implement packet sequence number.
                         */
                        ERR("Failure to rotate stream %" PRIu64 ": sequence number unavailable",
-                                       stream->key);
+                           stream->key);
                        ret = -1;
                        goto end_unlock_stream;
                }
                stream->rotate_position = stream->last_sequence_number + 1 +
-                               ((produced_pos - consumed_pos) / stream->max_sb_size);
+                       ((produced_pos - consumed_pos) / stream->max_sb_size);
                DBG("Set rotation position for stream %" PRIu64 " at position %" PRIu64,
-                               stream->key, stream->rotate_position);
+                   stream->key,
+                   stream->rotate_position);
 
                if (!is_local_trace) {
                        /*
@@ -4218,9 +4197,8 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                                .rotate_at_seq_num = stream->rotate_position,
                        };
 
-                       ret = lttng_dynamic_array_add_element(
-                                       &stream_rotation_positions,
-                                       &position);
+                       ret = lttng_dynamic_array_add_element(&stream_rotation_positions,
+                                                             &position);
                        if (ret) {
                                ERR("Failed to allocate stream rotation position");
                                goto end_unlock_stream;
@@ -4280,8 +4258,8 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                         * is performed in a stream that has no active trace
                         * chunk.
                         */
-                       ret = lttng_dynamic_pointer_array_add_pointer(
-                                       &streams_packet_to_open, stream);
+                       ret = lttng_dynamic_pointer_array_add_pointer(&streams_packet_to_open,
+                                                                     stream);
                        if (ret) {
                                PERROR("Failed to add a stream pointer to array of streams in which to open a packet");
                                ret = -1;
@@ -4291,7 +4269,7 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
 
                pthread_mutex_unlock(&stream->lock);
        }
-       stream = NULL;
+       stream = nullptr;
 
        if (!is_local_trace) {
                relayd = consumer_find_relayd(relayd_id);
@@ -4302,28 +4280,27 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                }
 
                pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-               ret = relayd_rotate_streams(&relayd->control_sock, stream_count,
-                               rotating_to_new_chunk ? &next_chunk_id : NULL,
-                               (const struct relayd_stream_rotation_position *)
-                                               stream_rotation_positions.buffer
-                                                               .data);
+               ret = relayd_rotate_streams(&relayd->control_sock,
+                                           stream_count,
+                                           rotating_to_new_chunk ? &next_chunk_id : nullptr,
+                                           (const struct relayd_stream_rotation_position *)
+                                                   stream_rotation_positions.buffer.data);
                pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                if (ret < 0) {
                        ERR("Relayd rotate stream failed. Cleaning up relayd %" PRIu64,
-                                       relayd->net_seq_idx);
+                           relayd->net_seq_idx);
                        lttng_consumer_cleanup_relayd(relayd);
                        goto end_unlock_channel;
                }
        }
 
        for (stream_idx = 0;
-                       stream_idx < lttng_dynamic_pointer_array_get_count(
-                               &streams_packet_to_open);
-                       stream_idx++) {
+            stream_idx < lttng_dynamic_pointer_array_get_count(&streams_packet_to_open);
+            stream_idx++) {
                enum consumer_stream_open_packet_status status;
 
                stream = (lttng_consumer_stream *) lttng_dynamic_pointer_array_get_pointer(
-                               &streams_packet_to_open, stream_idx);
+                       &streams_packet_to_open, stream_idx);
 
                pthread_mutex_lock(&stream->lock);
                status = consumer_stream_open_packet(stream);
@@ -4332,8 +4309,9 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
                        DBG("Opened a packet after a rotation: stream id = %" PRIu64
                            ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
+                           stream->key,
+                           stream->chan->name,
+                           stream->chan->session_id);
                        break;
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
                        /*
@@ -4343,8 +4321,9 @@ int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
                         */
                        DBG("No space left to open a packet after a rotation: stream id = %" PRIu64
                            ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
+                           stream->key,
+                           stream->chan->name,
+                           stream->chan->session_id);
                        break;
                case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
                        /* Logged by callee. */
@@ -4364,14 +4343,12 @@ end_unlock_stream:
 end_unlock_channel:
        pthread_mutex_unlock(&channel->lock);
 end:
-       rcu_read_unlock();
        lttng_dynamic_array_reset(&stream_rotation_positions);
        lttng_dynamic_pointer_array_reset(&streams_packet_to_open);
        return ret;
 }
 
-static
-int consumer_clear_buffer(struct lttng_consumer_stream *stream)
+static int consumer_clear_buffer(struct lttng_consumer_stream *stream)
 {
        int ret = 0;
        unsigned long consumed_pos_before, consumed_pos_after;
@@ -4424,23 +4401,20 @@ end:
        return ret;
 }
 
-static
-int consumer_clear_stream(struct lttng_consumer_stream *stream)
+static int consumer_clear_stream(struct lttng_consumer_stream *stream)
 {
        int ret;
 
-       ret = consumer_stream_flush_buffer(stream, 1);
+       ret = consumer_stream_flush_buffer(stream, true);
        if (ret < 0) {
-               ERR("Failed to flush stream %" PRIu64 " during channel clear",
-                               stream->key);
+               ERR("Failed to flush stream %" PRIu64 " during channel clear", stream->key);
                ret = LTTCOMM_CONSUMERD_FATAL;
                goto error;
        }
 
        ret = consumer_clear_buffer(stream);
        if (ret < 0) {
-               ERR("Failed to clear stream %" PRIu64 " during channel clear",
-                               stream->key);
+               ERR("Failed to clear stream %" PRIu64 " during channel clear", stream->key);
                ret = LTTCOMM_CONSUMERD_FATAL;
                goto error;
        }
@@ -4450,15 +4424,14 @@ error:
        return ret;
 }
 
-static
-int consumer_clear_unmonitored_channel(struct lttng_consumer_channel *channel)
+static int consumer_clear_unmonitored_channel(struct lttng_consumer_channel *channel)
 {
        int ret;
        struct lttng_consumer_stream *stream;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        pthread_mutex_lock(&channel->lock);
-       cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
+       cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
                health_code_update();
                pthread_mutex_lock(&stream->lock);
                ret = consumer_clear_stream(stream);
@@ -4468,13 +4441,11 @@ int consumer_clear_unmonitored_channel(struct lttng_consumer_channel *channel)
                pthread_mutex_unlock(&stream->lock);
        }
        pthread_mutex_unlock(&channel->lock);
-       rcu_read_unlock();
        return 0;
 
 error_unlock:
        pthread_mutex_unlock(&stream->lock);
        pthread_mutex_unlock(&channel->lock);
-       rcu_read_unlock();
        return ret;
 }
 
@@ -4486,11 +4457,12 @@ error_unlock:
  */
 int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
 {
-       DBG("Check is rotate ready for stream %" PRIu64
-                       " ready %u rotate_position %" PRIu64
-                       " last_sequence_number %" PRIu64,
-                       stream->key, stream->rotate_ready,
-                       stream->rotate_position, stream->last_sequence_number);
+       DBG("Check is rotate ready for stream %" PRIu64 " ready %u rotate_position %" PRIu64
+           " last_sequence_number %" PRIu64,
+           stream->key,
+           stream->rotate_ready,
+           stream->rotate_position,
+           stream->last_sequence_number);
        if (stream->rotate_ready) {
                return 1;
        }
@@ -4503,13 +4475,12 @@ int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
         */
        if (stream->sequence_number_unavailable) {
                ERR("Internal error: rotation used on stream %" PRIu64
-                               " with unavailable sequence number",
-                               stream->key);
+                   " with unavailable sequence number",
+                   stream->key);
                return -1;
        }
 
-       if (stream->rotate_position == -1ULL ||
-                       stream->last_sequence_number == -1ULL) {
+       if (stream->rotate_position == -1ULL || stream->last_sequence_number == -1ULL) {
                return 0;
        }
 
@@ -4520,11 +4491,11 @@ int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
         * packet of the current chunk, hence the "rotate_position - 1".
         */
 
-       DBG("Check is rotate ready for stream %" PRIu64
-                       " last_sequence_number %" PRIu64
-                       " rotate_position %" PRIu64,
-                       stream->key, stream->last_sequence_number,
-                       stream->rotate_position);
+       DBG("Check is rotate ready for stream %" PRIu64 " last_sequence_number %" PRIu64
+           " rotate_position %" PRIu64,
+           stream->key,
+           stream->last_sequence_number,
+           stream->rotate_position);
        if (stream->last_sequence_number >= stream->rotate_position - 1) {
                return 1;
        }
@@ -4537,8 +4508,7 @@ int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
  */
 void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stream)
 {
-       DBG("lttng_consumer_reset_stream_rotate_state for stream %" PRIu64,
-                       stream->key);
+       DBG("lttng_consumer_reset_stream_rotate_state for stream %" PRIu64, stream->key);
        stream->rotate_position = -1ULL;
        stream->rotate_ready = false;
 }
@@ -4546,14 +4516,13 @@ void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stre
 /*
  * Perform the rotation a local stream file.
  */
-static
-int rotate_local_stream(struct lttng_consumer_stream *stream)
+static int rotate_local_stream(struct lttng_consumer_stream *stream)
 {
        int ret = 0;
 
        DBG("Rotate local stream: stream key %" PRIu64 ", channel key %" PRIu64,
-                       stream->key,
-                       stream->chan->key);
+           stream->key,
+           stream->chan->key);
        stream->tracefile_size_current = 0;
        stream->tracefile_count_current = 0;
 
@@ -4561,14 +4530,14 @@ int rotate_local_stream(struct lttng_consumer_stream *stream)
                ret = close(stream->out_fd);
                if (ret) {
                        PERROR("Failed to close stream out_fd of channel \"%s\"",
-                               stream->chan->name);
+                              stream->chan->name);
                }
                stream->out_fd = -1;
        }
 
        if (stream->index_file) {
                lttng_index_file_put(stream->index_file);
-               stream->index_file = NULL;
+               stream->index_file = nullptr;
        }
 
        if (!stream->trace_chunk) {
@@ -4606,9 +4575,8 @@ int lttng_consumer_rotate_stream(struct lttng_consumer_stream *stream)
                 * parent channel, becomes part of no chunk and can't output
                 * anything until a new trace chunk is created.
                 */
-               stream->trace_chunk = NULL;
-       } else if (stream->chan->trace_chunk &&
-                       !lttng_trace_chunk_get(stream->chan->trace_chunk)) {
+               stream->trace_chunk = nullptr;
+       } else if (stream->chan->trace_chunk && !lttng_trace_chunk_get(stream->chan->trace_chunk)) {
                ERR("Failed to acquire a reference to channel's trace chunk during stream rotation");
                ret = -1;
                goto error;
@@ -4664,8 +4632,7 @@ error:
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel,
-               uint64_t key)
+int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel, uint64_t key)
 {
        int ret;
        struct lttng_consumer_stream *stream;
@@ -4674,14 +4641,18 @@ int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel,
 
        ASSERT_RCU_READ_LOCKED();
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        DBG("Consumer rotate ready streams in channel %" PRIu64, key);
 
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key, &iter.iter,
-                       stream, node_channel_id.node) {
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                health_code_update();
 
                pthread_mutex_lock(&stream->chan->lock);
@@ -4705,13 +4676,11 @@ int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel,
        ret = 0;
 
 end:
-       rcu_read_unlock();
        return ret;
 }
 
-enum lttcomm_return_code lttng_consumer_init_command(
-               struct lttng_consumer_local_data *ctx,
-               const lttng_uuid& sessiond_uuid)
+enum lttcomm_return_code lttng_consumer_init_command(struct lttng_consumer_local_data *ctx,
+                                                    const lttng_uuid& sessiond_uuid)
 {
        enum lttcomm_return_code ret;
        char uuid_str[LTTNG_UUID_STR_LEN];
@@ -4730,17 +4699,18 @@ end:
        return ret;
 }
 
-enum lttcomm_return_code lttng_consumer_create_trace_chunk(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id,
-               time_t chunk_creation_timestamp,
-               const char *chunk_override_name,
-               const struct lttng_credentials *credentials,
-               struct lttng_directory_handle *chunk_directory_handle)
+enum lttcomm_return_code
+lttng_consumer_create_trace_chunk(const uint64_t *relayd_id,
+                                 uint64_t session_id,
+                                 uint64_t chunk_id,
+                                 time_t chunk_creation_timestamp,
+                                 const char *chunk_override_name,
+                                 const struct lttng_credentials *credentials,
+                                 struct lttng_directory_handle *chunk_directory_handle)
 {
        int ret;
        enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
-       struct lttng_trace_chunk *created_chunk = NULL, *published_chunk = NULL;
+       struct lttng_trace_chunk *created_chunk = nullptr, *published_chunk = nullptr;
        enum lttng_trace_chunk_status chunk_status;
        char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
        char creation_timestamp_buffer[ISO8601_STR_LEN];
@@ -4751,8 +4721,7 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
 
        if (relayd_id) {
                /* Only used for logging purposes. */
-               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
-                               "%" PRIu64, *relayd_id);
+               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
                if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
                        relayd_id_str = relayd_id_buffer;
                } else {
@@ -4763,18 +4732,18 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
        /* Local protocol error. */
        LTTNG_ASSERT(chunk_creation_timestamp);
        ret = time_to_iso8601_str(chunk_creation_timestamp,
-                       creation_timestamp_buffer,
-                       sizeof(creation_timestamp_buffer));
-       creation_timestamp_str = !ret ? creation_timestamp_buffer :
-                       "(formatting error)";
+                                 creation_timestamp_buffer,
+                                 sizeof(creation_timestamp_buffer));
+       creation_timestamp_str = !ret ? creation_timestamp_buffer : "(formatting error)";
 
        DBG("Consumer create trace chunk command: relay_id = %s"
-                       ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
-                       ", chunk_override_name = %s"
-                       ", chunk_creation_timestamp = %s",
-                       relayd_id_str, session_id, chunk_id,
-                       chunk_override_name ? : "(none)",
-                       creation_timestamp_str);
+           ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", chunk_override_name = %s"
+           ", chunk_creation_timestamp = %s",
+           relayd_id_str,
+           session_id,
+           chunk_id,
+           chunk_override_name ?: "(none)",
+           creation_timestamp_str);
 
        /*
         * The trace chunk registry, as used by the consumer daemon, implicitly
@@ -4790,8 +4759,7 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
         * the session daemon through the LTTNG_CONSUMER_CREATE_TRACE_CHUNK
         * and LTTNG_CONSUMER_DESTROY_TRACE_CHUNK commands.
         */
-       created_chunk = lttng_trace_chunk_create(chunk_id,
-                       chunk_creation_timestamp, NULL);
+       created_chunk = lttng_trace_chunk_create(chunk_id, chunk_creation_timestamp, nullptr);
        if (!created_chunk) {
                ERR("Failed to create trace chunk");
                ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
@@ -4799,8 +4767,7 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
        }
 
        if (chunk_override_name) {
-               chunk_status = lttng_trace_chunk_override_name(created_chunk,
-                               chunk_override_name);
+               chunk_status = lttng_trace_chunk_override_name(created_chunk, chunk_override_name);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
                        goto error;
@@ -4808,8 +4775,7 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
        }
 
        if (chunk_directory_handle) {
-               chunk_status = lttng_trace_chunk_set_credentials(created_chunk,
-                               credentials);
+               chunk_status = lttng_trace_chunk_set_credentials(created_chunk, credentials);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Failed to set trace chunk credentials");
                        ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
@@ -4819,9 +4785,8 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
                 * The consumer daemon has no ownership of the chunk output
                 * directory.
                 */
-               chunk_status = lttng_trace_chunk_set_as_user(created_chunk,
-                               chunk_directory_handle);
-               chunk_directory_handle = NULL;
+               chunk_status = lttng_trace_chunk_set_as_user(created_chunk, chunk_directory_handle);
+               chunk_directory_handle = nullptr;
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Failed to set trace chunk's directory handle");
                        ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
@@ -4830,51 +4795,59 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
        }
 
        published_chunk = lttng_trace_chunk_registry_publish_chunk(
-                       the_consumer_data.chunk_registry, session_id,
-                       created_chunk);
+               the_consumer_data.chunk_registry, session_id, created_chunk);
        lttng_trace_chunk_put(created_chunk);
-       created_chunk = NULL;
+       created_chunk = nullptr;
        if (!published_chunk) {
                ERR("Failed to publish trace chunk");
                ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
                goto error;
        }
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry_duplicate(
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry_duplicate(
                        the_consumer_data.channels_by_session_id_ht->ht,
-                       the_consumer_data.channels_by_session_id_ht->hash_fct(
-                                       &session_id, lttng_ht_seed),
+                       the_consumer_data.channels_by_session_id_ht->hash_fct(&session_id,
+                                                                             lttng_ht_seed),
                        the_consumer_data.channels_by_session_id_ht->match_fct,
-                       &session_id, &iter.iter, channel,
-                       channels_by_session_id_ht_node.node) {
-               ret = lttng_consumer_channel_set_trace_chunk(channel,
-                               published_chunk);
-               if (ret) {
-                       /*
-                        * Roll-back the creation of this chunk.
-                        *
-                        * This is important since the session daemon will
-                        * assume that the creation of this chunk failed and
-                        * will never ask for it to be closed, resulting
-                        * in a leak and an inconsistent state for some
-                        * channels.
-                        */
-                       enum lttcomm_return_code close_ret;
-                       char path[LTTNG_PATH_MAX];
+                       &session_id,
+                       &iter.iter,
+                       channel,
+                       channels_by_session_id_ht_node.node)
+               {
+                       ret = lttng_consumer_channel_set_trace_chunk(channel, published_chunk);
+                       if (ret) {
+                               /*
+                                * Roll-back the creation of this chunk.
+                                *
+                                * This is important since the session daemon will
+                                * assume that the creation of this chunk failed and
+                                * will never ask for it to be closed, resulting
+                                * in a leak and an inconsistent state for some
+                                * channels.
+                                */
+                               enum lttcomm_return_code close_ret;
+                               char path[LTTNG_PATH_MAX];
+
+                               DBG("Failed to set new trace chunk on existing channels, rolling back");
+                               close_ret =
+                                       lttng_consumer_close_trace_chunk(relayd_id,
+                                                                        session_id,
+                                                                        chunk_id,
+                                                                        chunk_creation_timestamp,
+                                                                        nullptr,
+                                                                        path);
+                               if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
+                                       ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
+                                           ", chunk_id = %" PRIu64,
+                                           session_id,
+                                           chunk_id);
+                               }
 
-                       DBG("Failed to set new trace chunk on existing channels, rolling back");
-                       close_ret = lttng_consumer_close_trace_chunk(relayd_id,
-                                       session_id, chunk_id,
-                                       chunk_creation_timestamp, NULL,
-                                       path);
-                       if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
-                               ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
-                                               session_id, chunk_id);
+                               ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
+                               break;
                        }
-
-                       ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
-                       break;
                }
        }
 
@@ -4884,8 +4857,7 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
                relayd = consumer_find_relayd(*relayd_id);
                if (relayd) {
                        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-                       ret = relayd_create_trace_chunk(
-                                       &relayd->control_sock, published_chunk);
+                       ret = relayd_create_trace_chunk(&relayd->control_sock, published_chunk);
                        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                } else {
                        ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
@@ -4896,14 +4868,16 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
                        char path[LTTNG_PATH_MAX];
 
                        close_ret = lttng_consumer_close_trace_chunk(relayd_id,
-                                       session_id,
-                                       chunk_id,
-                                       chunk_creation_timestamp,
-                                       NULL, path);
+                                                                    session_id,
+                                                                    chunk_id,
+                                                                    chunk_creation_timestamp,
+                                                                    nullptr,
+                                                                    path);
                        if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
-                               ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
-                                               session_id,
-                                               chunk_id);
+                               ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
+                                   ", chunk_id = %" PRIu64,
+                                   session_id,
+                                   chunk_id);
                        }
 
                        ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
@@ -4911,7 +4885,6 @@ enum lttcomm_return_code lttng_consumer_create_trace_chunk(
                }
        }
 error_unlock:
-       rcu_read_unlock();
 error:
        /* Release the reference returned by the "publish" operation. */
        lttng_trace_chunk_put(published_chunk);
@@ -4919,11 +4892,13 @@ error:
        return ret_code;
 }
 
-enum lttcomm_return_code lttng_consumer_close_trace_chunk(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id, time_t chunk_close_timestamp,
-               const enum lttng_trace_chunk_command_type *close_command,
-               char *path)
+enum lttcomm_return_code
+lttng_consumer_close_trace_chunk(const uint64_t *relayd_id,
+                                uint64_t session_id,
+                                uint64_t chunk_id,
+                                time_t chunk_close_timestamp,
+                                const enum lttng_trace_chunk_command_type *close_command,
+                                char *path)
 {
        enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
        struct lttng_trace_chunk *chunk;
@@ -4938,8 +4913,7 @@ enum lttcomm_return_code lttng_consumer_close_trace_chunk(
                int ret;
 
                /* Only used for logging purposes. */
-               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
-                               "%" PRIu64, *relayd_id);
+               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
                if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
                        relayd_id_str = relayd_id_buffer;
                } else {
@@ -4947,36 +4921,34 @@ enum lttcomm_return_code lttng_consumer_close_trace_chunk(
                }
        }
        if (close_command) {
-               close_command_name = lttng_trace_chunk_command_type_get_name(
-                               *close_command);
+               close_command_name = lttng_trace_chunk_command_type_get_name(*close_command);
        }
 
        DBG("Consumer close trace chunk command: relayd_id = %s"
-                       ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
-                       ", close command = %s",
-                       relayd_id_str, session_id, chunk_id,
-                       close_command_name);
+           ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", close command = %s",
+           relayd_id_str,
+           session_id,
+           chunk_id,
+           close_command_name);
 
        chunk = lttng_trace_chunk_registry_find_chunk(
-                       the_consumer_data.chunk_registry, session_id, chunk_id);
+               the_consumer_data.chunk_registry, session_id, chunk_id);
        if (!chunk) {
-               ERR("Failed to find chunk: session_id = %" PRIu64
-                               ", chunk_id = %" PRIu64,
-                               session_id, chunk_id);
+               ERR("Failed to find chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
+                   session_id,
+                   chunk_id);
                ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
                goto end;
        }
 
-       chunk_status = lttng_trace_chunk_set_close_timestamp(chunk,
-                       chunk_close_timestamp);
+       chunk_status = lttng_trace_chunk_set_close_timestamp(chunk, chunk_close_timestamp);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
                goto end;
        }
 
        if (close_command) {
-               chunk_status = lttng_trace_chunk_set_close_command(
-                               chunk, *close_command);
+               chunk_status = lttng_trace_chunk_set_close_command(chunk, *close_command);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
                        goto end;
@@ -4988,31 +4960,32 @@ enum lttcomm_return_code lttng_consumer_close_trace_chunk(
         * it; it is only kept around to compare it (by address) to the
         * current chunk found in the session's channels.
         */
-       rcu_read_lock();
-       cds_lfht_for_each_entry(the_consumer_data.channel_ht->ht, &iter.iter,
-                       channel, node.node) {
-               int ret;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_lfht_for_each_entry (
+                       the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
+                       int ret;
 
-               /*
-                * Only change the channel's chunk to NULL if it still
-                * references the chunk being closed. The channel may
-                * reference a newer channel in the case of a session
-                * rotation. When a session rotation occurs, the "next"
-                * chunk is created before the "current" chunk is closed.
-                */
-               if (channel->trace_chunk != chunk) {
-                       continue;
-               }
-               ret = lttng_consumer_channel_set_trace_chunk(channel, NULL);
-               if (ret) {
                        /*
-                        * Attempt to close the chunk on as many channels as
-                        * possible.
+                        * Only change the channel's chunk to NULL if it still
+                        * references the chunk being closed. The channel may
+                        * reference a newer channel in the case of a session
+                        * rotation. When a session rotation occurs, the "next"
+                        * chunk is created before the "current" chunk is closed.
                         */
-                       ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
+                       if (channel->trace_chunk != chunk) {
+                               continue;
+                       }
+                       ret = lttng_consumer_channel_set_trace_chunk(channel, nullptr);
+                       if (ret) {
+                               /*
+                                * Attempt to close the chunk on as many channels as
+                                * possible.
+                                */
+                               ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
+                       }
                }
        }
-
        if (relayd_id) {
                int ret;
                struct consumer_relayd_sock_pair *relayd;
@@ -5020,13 +4993,10 @@ enum lttcomm_return_code lttng_consumer_close_trace_chunk(
                relayd = consumer_find_relayd(*relayd_id);
                if (relayd) {
                        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-                       ret = relayd_close_trace_chunk(
-                                       &relayd->control_sock, chunk,
-                                       path);
+                       ret = relayd_close_trace_chunk(&relayd->control_sock, chunk, path);
                        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
                } else {
-                       ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64,
-                                       *relayd_id);
+                       ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
                }
 
                if (!relayd || ret) {
@@ -5035,7 +5005,6 @@ enum lttcomm_return_code lttng_consumer_close_trace_chunk(
                }
        }
 error_unlock:
-       rcu_read_unlock();
 end:
        /*
         * Release the reference returned by the "find" operation and
@@ -5047,22 +5016,21 @@ end:
        return ret_code;
 }
 
-enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id)
+enum lttcomm_return_code
+lttng_consumer_trace_chunk_exists(const uint64_t *relayd_id, uint64_t session_id, uint64_t chunk_id)
 {
        int ret;
        enum lttcomm_return_code ret_code;
        char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
        const char *relayd_id_str = "(none)";
        const bool is_local_trace = !relayd_id;
-       struct consumer_relayd_sock_pair *relayd = NULL;
+       struct consumer_relayd_sock_pair *relayd = nullptr;
        bool chunk_exists_local, chunk_exists_remote;
+       lttng::urcu::read_lock_guard read_lock;
 
        if (relayd_id) {
                /* Only used for logging purposes. */
-               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
-                               "%" PRIu64, *relayd_id);
+               ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
                if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
                        relayd_id_str = relayd_id_buffer;
                } else {
@@ -5071,19 +5039,18 @@ enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
        }
 
        DBG("Consumer trace chunk exists command: relayd_id = %s"
-                       ", chunk_id = %" PRIu64, relayd_id_str,
-                       chunk_id);
+           ", chunk_id = %" PRIu64,
+           relayd_id_str,
+           chunk_id);
        ret = lttng_trace_chunk_registry_chunk_exists(
-                       the_consumer_data.chunk_registry, session_id, chunk_id,
-                       &chunk_exists_local);
+               the_consumer_data.chunk_registry, session_id, chunk_id, &chunk_exists_local);
        if (ret) {
                /* Internal error. */
                ERR("Failed to query the existence of a trace chunk");
                ret_code = LTTCOMM_CONSUMERD_FATAL;
                goto end;
        }
-       DBG("Trace chunk %s locally",
-                       chunk_exists_local ? "exists" : "does not exist");
+       DBG("Trace chunk %s locally", chunk_exists_local ? "exists" : "does not exist");
        if (chunk_exists_local) {
                ret_code = LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_LOCAL;
                goto end;
@@ -5092,7 +5059,6 @@ enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
                goto end;
        }
 
-       rcu_read_lock();
        relayd = consumer_find_relayd(*relayd_id);
        if (!relayd) {
                ERR("Failed to find relayd %" PRIu64, *relayd_id);
@@ -5101,8 +5067,7 @@ enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
        }
        DBG("Looking up existence of trace chunk on relay daemon");
        pthread_mutex_lock(&relayd->ctrl_sock_mutex);
-       ret = relayd_trace_chunk_exists(&relayd->control_sock, chunk_id,
-                       &chunk_exists_remote);
+       ret = relayd_trace_chunk_exists(&relayd->control_sock, chunk_id, &chunk_exists_remote);
        pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
        if (ret < 0) {
                ERR("Failed to look-up the existence of trace chunk on relay daemon");
@@ -5110,20 +5075,16 @@ enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
                goto end_rcu_unlock;
        }
 
-       ret_code = chunk_exists_remote ?
-                       LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE :
-                       LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
-       DBG("Trace chunk %s on relay daemon",
-                       chunk_exists_remote ? "exists" : "does not exist");
+       ret_code = chunk_exists_remote ? LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE :
+                                        LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
+       DBG("Trace chunk %s on relay daemon", chunk_exists_remote ? "exists" : "does not exist");
 
 end_rcu_unlock:
-       rcu_read_unlock();
 end:
        return ret_code;
 }
 
-static
-int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
+static int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
 {
        struct lttng_ht *ht;
        struct lttng_consumer_stream *stream;
@@ -5132,11 +5093,15 @@ int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
 
        ht = the_consumer_data.stream_per_chan_id_ht;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed),
-                       ht->match_fct, &channel->key,
-                       &iter.iter, stream, node_channel_id.node) {
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                /*
                 * Protect against teardown with mutex.
                 */
@@ -5151,12 +5116,10 @@ int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
        next:
                pthread_mutex_unlock(&stream->lock);
        }
-       rcu_read_unlock();
        return LTTCOMM_CONSUMERD_SUCCESS;
 
 error_unlock:
        pthread_mutex_unlock(&stream->lock);
-       rcu_read_unlock();
        return ret;
 }
 
@@ -5186,8 +5149,7 @@ end:
        return ret;
 }
 
-enum lttcomm_return_code lttng_consumer_open_channel_packets(
-               struct lttng_consumer_channel *channel)
+enum lttcomm_return_code lttng_consumer_open_channel_packets(struct lttng_consumer_channel *channel)
 {
        struct lttng_consumer_stream *stream;
        enum lttcomm_return_code ret = LTTCOMM_CONSUMERD_SUCCESS;
@@ -5198,53 +5160,56 @@ enum lttcomm_return_code lttng_consumer_open_channel_packets(
                goto end;
        }
 
-       rcu_read_lock();
-       cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
-               enum consumer_stream_open_packet_status status;
+       {
+               lttng::urcu::read_lock_guard read_lock;
+               cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
+                       enum consumer_stream_open_packet_status status;
 
-               pthread_mutex_lock(&stream->lock);
-               if (cds_lfht_is_node_deleted(&stream->node.node)) {
-                       goto next;
-               }
+                       pthread_mutex_lock(&stream->lock);
+                       if (cds_lfht_is_node_deleted(&stream->node.node)) {
+                               goto next;
+                       }
 
-               status = consumer_stream_open_packet(stream);
-               switch (status) {
-               case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
-                       DBG("Opened a packet in \"open channel packets\" command: stream id = %" PRIu64
-                                       ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
-                       stream->opened_packet_in_current_trace_chunk = true;
-                       break;
-               case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
-                       DBG("No space left to open a packet in \"open channel packets\" command: stream id = %" PRIu64
-                                       ", channel name = %s, session id = %" PRIu64,
-                                       stream->key, stream->chan->name,
-                                       stream->chan->session_id);
-                       break;
-               case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
-                       /*
-                        * Only unexpected internal errors can lead to this
-                        * failing. Report an unknown error.
-                        */
-                       ERR("Failed to flush empty buffer in \"open channel packets\" command: stream id = %" PRIu64
-                                       ", channel id = %" PRIu64
-                                       ", channel name = %s"
-                                       ", session id = %" PRIu64,
-                                       stream->key, channel->key,
-                                       channel->name, channel->session_id);
-                       ret = LTTCOMM_CONSUMERD_UNKNOWN_ERROR;
-                       goto error_unlock;
-               default:
-                       abort();
-               }
+                       status = consumer_stream_open_packet(stream);
+                       switch (status) {
+                       case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
+                               DBG("Opened a packet in \"open channel packets\" command: stream id = %" PRIu64
+                                   ", channel name = %s, session id = %" PRIu64,
+                                   stream->key,
+                                   stream->chan->name,
+                                   stream->chan->session_id);
+                               stream->opened_packet_in_current_trace_chunk = true;
+                               break;
+                       case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
+                               DBG("No space left to open a packet in \"open channel packets\" command: stream id = %" PRIu64
+                                   ", channel name = %s, session id = %" PRIu64,
+                                   stream->key,
+                                   stream->chan->name,
+                                   stream->chan->session_id);
+                               break;
+                       case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
+                               /*
+                                * Only unexpected internal errors can lead to this
+                                * failing. Report an unknown error.
+                                */
+                               ERR("Failed to flush empty buffer in \"open channel packets\" command: stream id = %" PRIu64
+                                   ", channel id = %" PRIu64 ", channel name = %s"
+                                   ", session id = %" PRIu64,
+                                   stream->key,
+                                   channel->key,
+                                   channel->name,
+                                   channel->session_id);
+                               ret = LTTCOMM_CONSUMERD_UNKNOWN_ERROR;
+                               goto error_unlock;
+                       default:
+                               abort();
+                       }
 
-       next:
-               pthread_mutex_unlock(&stream->lock);
+               next:
+                       pthread_mutex_unlock(&stream->lock);
+               }
        }
-
 end_rcu_unlock:
-       rcu_read_unlock();
 end:
        return ret;
 
index fb7f59bb21883ec8c8888c1069ab66020b548d45..310969172d73f656a258d038cfdb1c0c55c9441f 100644 (file)
 #ifndef LIB_CONSUMER_H
 #define LIB_CONSUMER_H
 
+#include <common/buffer-view.hpp>
+#include <common/credentials.hpp>
+#include <common/dynamic-array.hpp>
+#include <common/hashtable/hashtable.hpp>
+#include <common/index/ctf-index.hpp>
+#include <common/pipe.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/trace-chunk-registry.hpp>
+#include <common/uuid.hpp>
+#include <common/waiter.hpp>
+
+#include <lttng/lttng.h>
+
 #include <limits.h>
 #include <poll.h>
 #include <stdint.h>
 #include <unistd.h>
 #include <urcu/list.h>
 
-#include <lttng/lttng.h>
-
-#include <common/hashtable/hashtable.hpp>
-#include <common/compat/fcntl.hpp>
-#include <common/uuid.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/pipe.hpp>
-#include <common/index/ctf-index.hpp>
-#include <common/trace-chunk-registry.hpp>
-#include <common/credentials.hpp>
-#include <common/buffer-view.hpp>
-#include <common/dynamic-array.hpp>
-
 struct lttng_consumer_local_data;
 
 /* Commands for consumer */
@@ -39,7 +39,7 @@ enum lttng_consumer_command {
        /* pause, delete, active depending on fd state */
        LTTNG_CONSUMER_UPDATE_STREAM,
        /* inform the consumer to quit when all fd has hang up */
-       LTTNG_CONSUMER_STOP,    /* deprecated */
+       LTTNG_CONSUMER_STOP, /* deprecated */
        LTTNG_CONSUMER_ADD_RELAYD_SOCKET,
        /* Inform the consumer to kill a specific relayd connection */
        LTTNG_CONSUMER_DESTROY_RELAYD,
@@ -82,13 +82,13 @@ enum consumer_endpoint_status {
 };
 
 enum consumer_channel_output {
-       CONSUMER_CHANNEL_MMAP   = 0,
-       CONSUMER_CHANNEL_SPLICE = 1,
+       CONSUMER_CHANNEL_MMAP = 0,
+       CONSUMER_CHANNEL_SPLICE = 1,
 };
 
 enum consumer_channel_type {
-       CONSUMER_CHANNEL_TYPE_METADATA  = 0,
-       CONSUMER_CHANNEL_TYPE_DATA      = 1,
+       CONSUMER_CHANNEL_TYPE_METADATA = 0,
+       CONSUMER_CHANNEL_TYPE_DATA = 1,
 };
 
 enum sync_metadata_status {
@@ -109,30 +109,30 @@ struct consumer_metadata_cache;
 
 struct lttng_consumer_channel {
        /* Is the channel published in the channel hash tables? */
-       bool is_published;
+       bool is_published = false;
        /*
         * Was the channel deleted (logically) and waiting to be reclaimed?
         * If this flag is set, no modification that is not cleaned-up by the
         * RCU reclamation callback should be made
         */
-       bool is_deleted;
+       bool is_deleted = false;
        /* HT node used for consumer_data.channel_ht */
-       struct lttng_ht_node_u64 node;
+       struct lttng_ht_node_u64 node = {};
        /* HT node used for consumer_data.channels_by_session_id_ht */
-       struct lttng_ht_node_u64 channels_by_session_id_ht_node;
+       struct lttng_ht_node_u64 channels_by_session_id_ht_node = {};
        /* Indexed key. Incremented value in the consumer. */
-       uint64_t key;
+       uint64_t key = 0;
        /* Number of streams referencing this channel */
-       int refcount;
+       int refcount = 0;
        /* Tracing session id on the session daemon side. */
-       uint64_t session_id;
+       uint64_t session_id = 0;
        /* Current trace chunk of the session in which this channel exists. */
-       struct lttng_trace_chunk *trace_chunk;
+       struct lttng_trace_chunk *trace_chunk = nullptr;
        /*
         * Session id when requesting metadata to the session daemon for
         * a session with per-PID buffers.
         */
-       uint64_t session_id_per_pid;
+       uint64_t session_id_per_pid = 0;
        /*
         * In the case of local streams, this field contains the channel's
         * output path; a path relative to the session's output path.
@@ -144,72 +144,77 @@ struct lttng_consumer_channel {
         * peers, this contains a path of the form:
         *   /hostname/session_path/ust/uid/1000/64-bit
         */
-       char pathname[PATH_MAX];
+       char pathname[PATH_MAX] = {};
        /* Channel name. */
-       char name[LTTNG_SYMBOL_NAME_LEN];
+       char name[LTTNG_SYMBOL_NAME_LEN] = {};
        /* Relayd id of the channel. -1ULL if it does not apply. */
-       uint64_t relayd_id;
+       uint64_t relayd_id = 0;
        /*
         * Number of streams NOT initialized yet. This is used in order to not
         * delete this channel if streams are getting initialized.
         */
-       unsigned int nb_init_stream_left;
+       unsigned int nb_init_stream_left = 0;
        /* Output type (mmap or splice). */
-       enum consumer_channel_output output;
+       enum consumer_channel_output output = CONSUMER_CHANNEL_MMAP;
        /* Channel type for stream */
-       enum consumer_channel_type type;
+       enum consumer_channel_type type = CONSUMER_CHANNEL_TYPE_METADATA;
 
        /* For UST */
-       uid_t ust_app_uid;      /* Application UID. */
-       struct lttng_ust_ctl_consumer_channel *uchan;
-       unsigned char uuid[LTTNG_UUID_STR_LEN];
+       uid_t ust_app_uid = 65534; /* Application UID. */
+       struct lttng_ust_ctl_consumer_channel *uchan = nullptr;
+       unsigned char uuid[LTTNG_UUID_STR_LEN] = {};
        /*
         * Temporary stream list used to store the streams once created and waiting
         * to be sent to the session daemon by receiving the
         * LTTNG_CONSUMER_GET_CHANNEL.
         */
-       struct stream_list streams;
+       struct stream_list streams = {};
 
        /*
         * Set if the channel is metadata. We keep a reference to the stream
         * because we have to flush data once pushed by the session daemon. For a
         * regular channel, this is always set to NULL.
         */
-       struct lttng_consumer_stream *metadata_stream;
+       struct lttng_consumer_stream *metadata_stream = nullptr;
 
        /* for UST */
-       int wait_fd;
+       int wait_fd = -1;
        /* Node within channel thread ht */
-       struct lttng_ht_node_u64 wait_fd_node;
+       struct lttng_ht_node_u64 wait_fd_node = {};
 
        /* Metadata cache is metadata channel */
-       struct consumer_metadata_cache *metadata_cache;
+       struct consumer_metadata_cache *metadata_cache = nullptr;
+
+       /*
+        * Wait queue awaiting updates to metadata stream's flushed position.
+        */
+       lttng::synchro::wait_queue metadata_pushed_wait_queue;
 
        /* For UST metadata periodical flush */
-       int switch_timer_enabled;
-       timer_t switch_timer;
-       int switch_timer_error;
+       int switch_timer_enabled = 0;
+       timer_t switch_timer = {};
+       int switch_timer_error = 0;
 
        /* For the live mode */
-       int live_timer_enabled;
-       timer_t live_timer;
-       int live_timer_error;
+       int live_timer_enabled = 0;
+       timer_t live_timer = {};
+       int live_timer_error = 0;
        /* Channel is part of a live session ? */
-       bool is_live;
+       bool is_live = false;
 
        /* For channel monitoring timer. */
-       int monitor_timer_enabled;
-       timer_t monitor_timer;
+       int monitor_timer_enabled = 0;
+       timer_t monitor_timer = {};
 
        /* On-disk circular buffer */
-       uint64_t tracefile_size;
-       uint64_t tracefile_count;
+       uint64_t tracefile_size = 0;
+       uint64_t tracefile_count = 0;
        /*
         * Monitor or not the streams of this channel meaning this indicates if the
         * streams should be sent to the data/metadata thread or added to the no
         * monitor list of the channel.
         */
-       unsigned int monitor;
+       unsigned int monitor = 0;
 
        /*
         * Channel lock.
@@ -222,7 +227,7 @@ struct lttng_consumer_channel {
         * This is nested OUTSIDE stream lock.
         * This is nested OUTSIDE consumer_relayd_sock_pair lock.
         */
-       pthread_mutex_t lock;
+       pthread_mutex_t lock = {};
 
        /*
         * Channel teardown lock.
@@ -236,24 +241,24 @@ struct lttng_consumer_channel {
         * This is nested OUTSIDE stream lock.
         * This is nested OUTSIDE consumer_relayd_sock_pair lock.
         */
-       pthread_mutex_t timer_lock;
+       pthread_mutex_t timer_lock = {};
 
        /* Timer value in usec for live streaming. */
-       unsigned int live_timer_interval;
+       unsigned int live_timer_interval = 0;
 
-       int *stream_fds;
-       int nr_stream_fds;
-       char root_shm_path[PATH_MAX];
-       char shm_path[PATH_MAX];
+       int *stream_fds = nullptr;
+       int nr_stream_fds = 0;
+       char root_shm_path[PATH_MAX] = {};
+       char shm_path[PATH_MAX] = {};
        /* Only set for UST channels. */
-       LTTNG_OPTIONAL(struct lttng_credentials) buffer_credentials;
+       LTTNG_OPTIONAL(struct lttng_credentials) buffer_credentials = {};
        /* Total number of discarded events for that channel. */
-       uint64_t discarded_events;
+       uint64_t discarded_events = 0;
        /* Total number of missed packets due to overwriting (overwrite). */
-       uint64_t lost_packets;
+       uint64_t lost_packets = 0;
 
-       bool streams_sent_to_relayd;
-       uint64_t last_consumed_size_sample_sent;
+       bool streams_sent_to_relayd = false;
+       uint64_t last_consumed_size_sample_sent = false;
 };
 
 struct stream_subbuffer {
@@ -313,7 +318,7 @@ enum get_next_subbuffer_status {
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*on_wake_up_cb)(struct lttng_consumer_stream *);
+using on_wake_up_cb = int (*)(struct lttng_consumer_stream *);
 
 /*
  * Perform any operation required before a consumer stream is put
@@ -321,16 +326,15 @@ typedef int (*on_wake_up_cb)(struct lttng_consumer_stream *);
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*on_sleep_cb)(struct lttng_consumer_stream *,
-               struct lttng_consumer_local_data *);
+using on_sleep_cb = int (*)(struct lttng_consumer_stream *, struct lttng_consumer_local_data *);
 
 /*
  * Acquire the subbuffer at the current 'consumed' position.
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef enum get_next_subbuffer_status (*get_next_subbuffer_cb)(
-               struct lttng_consumer_stream *, struct stream_subbuffer *);
+using get_next_subbuffer_cb = enum get_next_subbuffer_status (*)(struct lttng_consumer_stream *,
+                                                                struct stream_subbuffer *);
 
 /*
  * Populate the stream_subbuffer's info member. The info to populate
@@ -338,25 +342,25 @@ typedef enum get_next_subbuffer_status (*get_next_subbuffer_cb)(
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*extract_subbuffer_info_cb)(
-               struct lttng_consumer_stream *, struct stream_subbuffer *);
+using extract_subbuffer_info_cb = int (*)(struct lttng_consumer_stream *,
+                                         struct stream_subbuffer *);
 
 /*
  * Invoked after a subbuffer's info has been filled.
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*pre_consume_subbuffer_cb)(struct lttng_consumer_stream *,
-               const struct stream_subbuffer *);
+using pre_consume_subbuffer_cb = int (*)(struct lttng_consumer_stream *,
+                                        const struct stream_subbuffer *);
 
 /*
  * Consume subbuffer contents.
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef ssize_t (*consume_subbuffer_cb)(struct lttng_consumer_local_data *,
-               struct lttng_consumer_stream *,
-               const struct stream_subbuffer *);
+using consume_subbuffer_cb = ssize_t (*)(struct lttng_consumer_local_data *,
+                                        struct lttng_consumer_stream *,
+                                        const struct stream_subbuffer *);
 
 /*
  * Release the current subbuffer and advance the 'consumed' position by
@@ -364,31 +368,30 @@ typedef ssize_t (*consume_subbuffer_cb)(struct lttng_consumer_local_data *,
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*put_next_subbuffer_cb)(struct lttng_consumer_stream *,
-               struct stream_subbuffer *);
+using put_next_subbuffer_cb = int (*)(struct lttng_consumer_stream *, struct stream_subbuffer *);
 
 /*
  * Invoked after consuming a subbuffer.
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*post_consume_cb)(struct lttng_consumer_stream *,
-               const struct stream_subbuffer *,
-               struct lttng_consumer_local_data *);
+using post_consume_cb = int (*)(struct lttng_consumer_stream *,
+                               const struct stream_subbuffer *,
+                               struct lttng_consumer_local_data *);
 
 /*
  * Send a live beacon if no data is available.
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef int (*send_live_beacon_cb)(struct lttng_consumer_stream *);
+using send_live_beacon_cb = int (*)(struct lttng_consumer_stream *);
 
 /*
  * Lock the stream and channel locks and any other stream-type specific
  * lock that need to be acquired during the processing of an
  * availability notification.
  */
-typedef void (*lock_cb)(struct lttng_consumer_stream *);
+using lock_cb = void (*)(struct lttng_consumer_stream *);
 
 /*
  * Unlock the stream and channel locks and any other stream-type specific
@@ -396,14 +399,14 @@ typedef void (*lock_cb)(struct lttng_consumer_stream *);
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef void (*unlock_cb)(struct lttng_consumer_stream *);
+using unlock_cb = void (*)(struct lttng_consumer_stream *);
 
 /*
  * Assert that the stream and channel lock and any other stream type specific
  * lock that need to be acquired during the processing of a read_subbuffer
  * operation is acquired.
  */
-typedef void (*assert_locked_cb)(struct lttng_consumer_stream *);
+using assert_locked_cb = void (*)(struct lttng_consumer_stream *);
 
 /*
  * Invoked when a subbuffer's metadata version does not match the last
@@ -411,7 +414,7 @@ typedef void (*assert_locked_cb)(struct lttng_consumer_stream *);
  *
  * Stream and channel locks are acquired during this call.
  */
-typedef void (*reset_metadata_cb)(struct lttng_consumer_stream *);
+using reset_metadata_cb = void (*)(struct lttng_consumer_stream *);
 
 /*
  * Internal representation of the streams, sessiond_key is used to identify
@@ -723,8 +726,8 @@ struct lttng_consumer_local_data {
         * Returns the number of bytes read, or negative error value.
         */
        ssize_t (*on_buffer_ready)(struct lttng_consumer_stream *stream,
-                       struct lttng_consumer_local_data *ctx,
-                       bool locked_by_caller);
+                                  struct lttng_consumer_local_data *ctx,
+                                  bool locked_by_caller);
        /*
         * function to call when we receive a new channel, it receives a
         * newly allocated channel, depending on the return code of this
@@ -816,7 +819,7 @@ struct lttng_consumer_global_data {
         * This is nested OUTSIDE the stream lock.
         * This is nested OUTSIDE the consumer_relayd_sock_pair lock.
         */
-       pthread_mutex_t lock {};
+       pthread_mutex_t lock{};
 
        /*
         * Number of streams in the data stream hash table declared outside.
@@ -881,8 +884,7 @@ extern int consumer_quit;
 LTTNG_EXPORT extern int data_consumption_paused;
 
 /* Return a human-readable consumer type string that is suitable for logging. */
-static inline
-const char *lttng_consumer_type_str(enum lttng_consumer_type type)
+static inline const char *lttng_consumer_type_str(enum lttng_consumer_type type)
 {
        switch (type) {
        case LTTNG_CONSUMER_UNKNOWN:
@@ -901,19 +903,17 @@ const char *lttng_consumer_type_str(enum lttng_consumer_type type)
 /*
  * Init consumer data structures.
  */
-int lttng_consumer_init(void);
+int lttng_consumer_init();
 
 /*
  * Set the error socket for communication with a session daemon.
  */
-void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
-               int sock);
+void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx, int sock);
 
 /*
  * Set the command socket path for communication with a session daemon.
  */
-void lttng_consumer_set_command_sock_path(
-               struct lttng_consumer_local_data *ctx, char *sock);
+void lttng_consumer_set_command_sock_path(struct lttng_consumer_local_data *ctx, char *sock);
 
 /*
  * Send return code to session daemon.
@@ -921,7 +921,8 @@ void lttng_consumer_set_command_sock_path(
  * Returns the return code of sendmsg : the number of bytes transmitted or -1
  * on error.
  */
-int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd);
+int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx,
+               enum lttcomm_return_code error_code);
 
 /*
  * Called from signal handler to ensure a clean exit.
@@ -931,7 +932,7 @@ void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx);
 /*
  * Cleanup the daemon's socket on exit.
  */
-void lttng_consumer_cleanup(void);
+void lttng_consumer_cleanup();
 
 /*
  * Poll on the should_quit pipe and the command socket return -1 on error and
@@ -943,43 +944,39 @@ int lttng_consumer_poll_socket(struct pollfd *kconsumer_sockpoll);
  * Copy the fields from the channel that need to be accessed (read-only)
  * directly from the stream.
  */
-void consumer_stream_update_channel_attributes(
-               struct lttng_consumer_stream *stream,
-               struct lttng_consumer_channel *channel);
-
-struct lttng_consumer_stream *consumer_allocate_stream(
-               struct lttng_consumer_channel *channel,
-               uint64_t channel_key,
-               uint64_t stream_key,
-               const char *channel_name,
-               uint64_t relayd_id,
-               uint64_t session_id,
-               struct lttng_trace_chunk *trace_chunk,
-               int cpu,
-               int *alloc_ret,
-               enum consumer_channel_type type,
-               unsigned int monitor);
+void consumer_stream_update_channel_attributes(struct lttng_consumer_stream *stream,
+                                              struct lttng_consumer_channel *channel);
+
+struct lttng_consumer_stream *consumer_allocate_stream(struct lttng_consumer_channel *channel,
+                                                      uint64_t channel_key,
+                                                      uint64_t stream_key,
+                                                      const char *channel_name,
+                                                      uint64_t relayd_id,
+                                                      uint64_t session_id,
+                                                      struct lttng_trace_chunk *trace_chunk,
+                                                      int cpu,
+                                                      int *alloc_ret,
+                                                      enum consumer_channel_type type,
+                                                      unsigned int monitor);
 struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
-               uint64_t session_id,
-               const uint64_t *chunk_id,
-               const char *pathname,
-               const char *name,
-               uint64_t relayd_id,
-               enum lttng_event_output output,
-               uint64_t tracefile_size,
-               uint64_t tracefile_count,
-               uint64_t session_id_per_pid,
-               unsigned int monitor,
-               unsigned int live_timer_interval,
-               bool is_in_live_session,
-               const char *root_shm_path,
-               const char *shm_path);
-void consumer_del_stream(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht);
-void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
-               struct lttng_ht *ht);
+                                                        uint64_t session_id,
+                                                        const uint64_t *chunk_id,
+                                                        const char *pathname,
+                                                        const char *name,
+                                                        uint64_t relayd_id,
+                                                        enum lttng_event_output output,
+                                                        uint64_t tracefile_size,
+                                                        uint64_t tracefile_count,
+                                                        uint64_t session_id_per_pid,
+                                                        unsigned int monitor,
+                                                        unsigned int live_timer_interval,
+                                                        bool is_in_live_session,
+                                                        const char *root_shm_path,
+                                                        const char *shm_path);
+void consumer_del_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht);
+void consumer_del_metadata_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht);
 int consumer_add_channel(struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx);
+                        struct lttng_consumer_local_data *ctx);
 void consumer_del_channel(struct lttng_consumer_channel *channel);
 
 /* lttng-relayd consumer command */
@@ -988,33 +985,29 @@ int consumer_send_relayd_stream(struct lttng_consumer_stream *stream, char *path
 int consumer_send_relayd_streams_sent(uint64_t net_seq_idx);
 void close_relayd_stream(struct lttng_consumer_stream *stream);
 struct lttng_consumer_channel *consumer_find_channel(uint64_t key);
-int consumer_handle_stream_before_relayd(struct lttng_consumer_stream *stream,
-               size_t data_size);
+int consumer_handle_stream_before_relayd(struct lttng_consumer_stream *stream, size_t data_size);
 void consumer_steal_stream_key(int key, struct lttng_ht *ht);
 
-struct lttng_consumer_local_data *lttng_consumer_create(
-               enum lttng_consumer_type type,
-               ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
-                       struct lttng_consumer_local_data *ctx,
-                       bool locked_by_caller),
-               int (*recv_channel)(struct lttng_consumer_channel *channel),
-               int (*recv_stream)(struct lttng_consumer_stream *stream),
-               int (*update_stream)(uint64_t sessiond_key, uint32_t state));
+struct lttng_consumer_local_data *
+lttng_consumer_create(enum lttng_consumer_type type,
+                     ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
+                                             struct lttng_consumer_local_data *ctx,
+                                             bool locked_by_caller),
+                     int (*recv_channel)(struct lttng_consumer_channel *channel),
+                     int (*recv_stream)(struct lttng_consumer_stream *stream),
+                     int (*update_stream)(uint64_t sessiond_key, uint32_t state));
 void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx);
-ssize_t lttng_consumer_on_read_subbuffer_mmap(
-               struct lttng_consumer_stream *stream,
-               const struct lttng_buffer_view *buffer,
-               unsigned long padding);
-ssize_t lttng_consumer_on_read_subbuffer_splice(
-               struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_stream *stream, unsigned long len,
-               unsigned long padding);
+ssize_t lttng_consumer_on_read_subbuffer_mmap(struct lttng_consumer_stream *stream,
+                                             const struct lttng_buffer_view *buffer,
+                                             unsigned long padding);
+ssize_t lttng_consumer_on_read_subbuffer_splice(struct lttng_consumer_local_data *ctx,
+                                               struct lttng_consumer_stream *stream,
+                                               unsigned long len,
+                                               unsigned long padding);
 int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream);
 int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream);
-int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos);
-int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos);
+int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos);
+int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos);
 int lttng_ustconsumer_get_wakeup_fd(struct lttng_consumer_stream *stream);
 int lttng_ustconsumer_close_wakeup_fd(struct lttng_consumer_stream *stream);
 void *consumer_thread_metadata_poll(void *data);
@@ -1022,68 +1015,69 @@ void *consumer_thread_data_poll(void *data);
 void *consumer_thread_sessiond_poll(void *data);
 void *consumer_thread_channel_poll(void *data);
 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll);
+                           int sock,
+                           struct pollfd *consumer_sockpoll);
 
 ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx,
-               bool locked_by_caller);
+                                     struct lttng_consumer_local_data *ctx,
+                                     bool locked_by_caller);
 int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream);
 void consumer_add_relayd_socket(uint64_t net_seq_idx,
-               int sock_type,
-               struct lttng_consumer_local_data *ctx,
-               int sock,
-               struct pollfd *consumer_sockpoll,
-               uint64_t sessiond_id,
-               uint64_t relayd_session_id,
-               uint32_t relayd_version_major,
-               uint32_t relayd_version_minor,
-               enum lttcomm_sock_proto relayd_socket_protocol);
-void consumer_flag_relayd_for_destroy(
-               struct consumer_relayd_sock_pair *relayd);
+                               int sock_type,
+                               struct lttng_consumer_local_data *ctx,
+                               int sock,
+                               struct pollfd *consumer_sockpoll,
+                               uint64_t sessiond_id,
+                               uint64_t relayd_session_id,
+                               uint32_t relayd_version_major,
+                               uint32_t relayd_version_minor,
+                               enum lttcomm_sock_proto relayd_socket_protocol);
+void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd);
 int consumer_data_pending(uint64_t id);
 int consumer_send_status_msg(int sock, int ret_code);
-int consumer_send_status_channel(int sock,
-               struct lttng_consumer_channel *channel);
-void notify_thread_del_channel(struct lttng_consumer_local_data *ctx,
-               uint64_t key);
+int consumer_send_status_channel(int sock, struct lttng_consumer_channel *channel);
+void notify_thread_del_channel(struct lttng_consumer_local_data *ctx, uint64_t key);
 void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd);
 unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
-               unsigned long produced_pos, uint64_t nb_packets_per_stream,
-               uint64_t max_sb_size);
+                                            unsigned long produced_pos,
+                                            uint64_t nb_packets_per_stream,
+                                            uint64_t max_sb_size);
 void consumer_add_data_stream(struct lttng_consumer_stream *stream);
 void consumer_del_stream_for_data(struct lttng_consumer_stream *stream);
 void consumer_add_metadata_stream(struct lttng_consumer_stream *stream);
 void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream);
 int consumer_create_index_file(struct lttng_consumer_stream *stream);
 int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
-               uint64_t key, uint64_t relayd_id);
+                                 uint64_t key,
+                                 uint64_t relayd_id);
 int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream);
 int lttng_consumer_rotate_stream(struct lttng_consumer_stream *stream);
-int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel,
-               uint64_t key);
+int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel, uint64_t key);
 void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stream);
-enum lttcomm_return_code lttng_consumer_create_trace_chunk(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id,
-               time_t chunk_creation_timestamp,
-               const char *chunk_override_name,
-               const struct lttng_credentials *credentials,
-               struct lttng_directory_handle *chunk_directory_handle);
-enum lttcomm_return_code lttng_consumer_close_trace_chunk(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id, time_t chunk_close_timestamp,
-               const enum lttng_trace_chunk_command_type *close_command,
-               char *path);
-enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
-               const uint64_t *relayd_id, uint64_t session_id,
-               uint64_t chunk_id);
+enum lttcomm_return_code
+lttng_consumer_create_trace_chunk(const uint64_t *relayd_id,
+                                 uint64_t session_id,
+                                 uint64_t chunk_id,
+                                 time_t chunk_creation_timestamp,
+                                 const char *chunk_override_name,
+                                 const struct lttng_credentials *credentials,
+                                 struct lttng_directory_handle *chunk_directory_handle);
+enum lttcomm_return_code
+lttng_consumer_close_trace_chunk(const uint64_t *relayd_id,
+                                uint64_t session_id,
+                                uint64_t chunk_id,
+                                time_t chunk_close_timestamp,
+                                const enum lttng_trace_chunk_command_type *close_command,
+                                char *path);
+enum lttcomm_return_code lttng_consumer_trace_chunk_exists(const uint64_t *relayd_id,
+                                                          uint64_t session_id,
+                                                          uint64_t chunk_id);
 void lttng_consumer_cleanup_relayd(struct consumer_relayd_sock_pair *relayd);
-enum lttcomm_return_code lttng_consumer_init_command(
-               struct lttng_consumer_local_data *ctx,
-               const lttng_uuid& sessiond_uuid);
+enum lttcomm_return_code lttng_consumer_init_command(struct lttng_consumer_local_data *ctx,
+                                                    const lttng_uuid& sessiond_uuid);
 int lttng_consumer_clear_channel(struct lttng_consumer_channel *channel);
-enum lttcomm_return_code lttng_consumer_open_channel_packets(
-               struct lttng_consumer_channel *channel);
+enum lttcomm_return_code
+lttng_consumer_open_channel_packets(struct lttng_consumer_channel *channel);
 int consumer_metadata_wakeup_pipe(const struct lttng_consumer_channel *channel);
 void lttng_consumer_sigbus_handle(void *addr);
 void sample_and_send_channel_buffer_stats(struct lttng_consumer_channel *channel);
index f9c35e22ce4c4d3e25521c53e02d91dc9694c1eb..dbcc76acb904cf584c7ab867493ffd9d1c158ba6 100644 (file)
@@ -10,8 +10,8 @@
 #include <common/buffer-view.hpp>
 #include <common/consumer/consumer.hpp>
 #include <common/dynamic-buffer.hpp>
-#include <common/macros.hpp>
 #include <common/error.hpp>
+#include <common/macros.hpp>
 
 struct metadata_bucket {
        struct lttng_dynamic_buffer content;
@@ -22,8 +22,7 @@ struct metadata_bucket {
        unsigned int buffer_count;
 };
 
-struct metadata_bucket *metadata_bucket_create(
-               metadata_bucket_flush_cb flush, void *data)
+struct metadata_bucket *metadata_bucket_create(metadata_bucket_flush_cb flush, void *data)
 {
        metadata_bucket *bucket = zmalloc<metadata_bucket>();
        if (!bucket) {
@@ -46,7 +45,8 @@ void metadata_bucket_destroy(struct metadata_bucket *bucket)
 
        if (bucket->content.size > 0) {
                WARN("Stream metadata bucket destroyed with remaining data: size = %zu, buffer count = %u",
-                               bucket->content.size, bucket->buffer_count);
+                    bucket->content.size,
+                    bucket->buffer_count);
        }
 
        lttng_dynamic_buffer_reset(&bucket->content);
@@ -61,24 +61,22 @@ void metadata_bucket_reset(struct metadata_bucket *bucket)
 }
 
 enum metadata_bucket_status metadata_bucket_fill(struct metadata_bucket *bucket,
-               const struct stream_subbuffer *buffer)
+                                                const struct stream_subbuffer *buffer)
 {
        ssize_t ret;
        struct lttng_buffer_view flushed_view;
        struct stream_subbuffer flushed_subbuffer;
        enum metadata_bucket_status status;
-       const bool should_flush =
-                       LTTNG_OPTIONAL_GET(buffer->info.metadata.coherent);
+       const bool should_flush = LTTNG_OPTIONAL_GET(buffer->info.metadata.coherent);
        const size_t padding_this_buffer =
-                       buffer->info.metadata.padded_subbuf_size -
-                       buffer->info.metadata.subbuf_size;
+               buffer->info.metadata.padded_subbuf_size - buffer->info.metadata.subbuf_size;
        size_t flush_size;
 
        DBG("Metadata bucket filled with %zu bytes buffer view, sub-buffer size: %lu, padded sub-buffer size: %lu, coherent: %s",
-                       buffer->buffer.buffer.size,
-                       buffer->info.metadata.subbuf_size,
-                       buffer->info.metadata.padded_subbuf_size,
-                       buffer->info.metadata.coherent.value ? "true" : "false");
+           buffer->buffer.buffer.size,
+           buffer->info.metadata.subbuf_size,
+           buffer->info.metadata.padded_subbuf_size,
+           buffer->info.metadata.coherent.value ? "true" : "false");
        /*
         * If no metadata was accumulated and this buffer should be
         * flushed, don't copy it unecessarily; just flush it directly.
@@ -98,8 +96,7 @@ enum metadata_bucket_status metadata_bucket_fill(struct metadata_bucket *bucket,
                 * the bucket is not sent, which is what really matters
                 * from an efficiency point of view.
                 */
-               ret = lttng_dynamic_buffer_append_view(
-                       &bucket->content, &buffer->buffer.buffer);
+               ret = lttng_dynamic_buffer_append_view(&bucket->content, &buffer->buffer.buffer);
                if (ret) {
                        status = METADATA_BUCKET_STATUS_ERROR;
                        goto end;
@@ -138,8 +135,9 @@ enum metadata_bucket_status metadata_bucket_fill(struct metadata_bucket *bucket,
        };
 
        DBG("Metadata bucket flushing %zu bytes (%u sub-buffer%s)",
-                       flushed_view.size, bucket->buffer_count,
-                       bucket->buffer_count > 1 ? "s" : "");
+           flushed_view.size,
+           bucket->buffer_count,
+           bucket->buffer_count > 1 ? "s" : "");
        ret = bucket->flush.fn(&flushed_subbuffer, bucket->flush.data);
        if (ret >= 0) {
                status = METADATA_BUCKET_STATUS_OK;
index 2c6961c88d2df0acb42942b4027313019900d6b2..ca9ee28c5adaa8ac7beb359259ccbcfb0aea936a 100644 (file)
 
 struct metadata_bucket;
 
-typedef ssize_t (*metadata_bucket_flush_cb)(
-               const struct stream_subbuffer *buffer, void *data);
+using metadata_bucket_flush_cb = ssize_t (*)(const struct stream_subbuffer *, void *);
 
 enum metadata_bucket_status {
        METADATA_BUCKET_STATUS_OK,
        METADATA_BUCKET_STATUS_ERROR,
 };
 
-struct metadata_bucket *metadata_bucket_create(
-               metadata_bucket_flush_cb flush, void *data);
+struct metadata_bucket *metadata_bucket_create(metadata_bucket_flush_cb flush, void *data);
 
 void metadata_bucket_destroy(struct metadata_bucket *bucket);
 
 enum metadata_bucket_status metadata_bucket_fill(struct metadata_bucket *bucket,
-               const struct stream_subbuffer *buffer);
+                                                const struct stream_subbuffer *buffer);
 
 void metadata_bucket_reset(struct metadata_bucket *bucket);
 
diff --git a/src/common/container-wrapper.hpp b/src/common/container-wrapper.hpp
new file mode 100644 (file)
index 0000000..25385fc
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_CONTAINER_WRAPPER_H
+#define LTTNG_CONTAINER_WRAPPER_H
+
+#include <common/exception.hpp>
+#include <common/format.hpp>
+#include <common/macros.hpp>
+
+#include <cstddef>
+#include <iterator>
+
+namespace lttng {
+namespace utils {
+
+/*
+ * random_access_container_wrapper is a helper to provide an idiomatic C++ interface
+ * from a C container API. ElementAccessorCallable and ElementCountAccessorCallable
+ * are two functors which must be provided to allow access to the underlying elements
+ * of the container and to its size.
+ */
+template <typename ContainerType, typename ElementType, typename ContainerOperations>
+class random_access_container_wrapper {
+       template <typename IteratorContainerType, typename IteratorElementType>
+       class _iterator : public std::iterator<std::random_access_iterator_tag, std::size_t> {
+       public:
+               explicit _iterator(IteratorContainerType& container, std::size_t start_index = 0) :
+                       _container(container), _index(start_index)
+               {
+               }
+
+               _iterator& operator++() noexcept
+               {
+                       ++_index;
+                       return *this;
+               }
+
+               _iterator& operator--() noexcept
+               {
+                       --_index;
+                       return *this;
+               }
+
+               _iterator& operator++(int) noexcept
+               {
+                       auto this_before_increment = *this;
+
+                       _index++;
+                       return this_before_increment;
+               }
+
+               _iterator& operator--(int) noexcept
+               {
+                       _index--;
+                       return *this;
+               }
+
+               ptrdiff_t operator-(const _iterator& other) const
+               {
+                       return _index - other._index;
+               }
+
+               bool operator==(const _iterator& other) const noexcept
+               {
+                       return _index == other._index;
+               }
+
+               bool operator!=(const _iterator& other) const noexcept
+               {
+                       return !(*this == other);
+               }
+
+               typename std::conditional<std::is_pointer<IteratorElementType>::value,
+                                         IteratorElementType,
+                                         IteratorElementType&>::type
+               operator*() const
+               {
+                       return _container[_index];
+               }
+
+       private:
+               IteratorContainerType& _container;
+               std::size_t _index;
+       };
+
+       using iterator = _iterator<random_access_container_wrapper, ElementType>;
+       using const_iterator = _iterator<const random_access_container_wrapper, const ElementType>;
+
+public:
+       explicit random_access_container_wrapper(ContainerType container) :
+               _container{ std::move(container) }
+       {
+       }
+
+       iterator begin() noexcept
+       {
+               return iterator(*this);
+       }
+
+       iterator end()
+       {
+               return iterator(*this, size());
+       }
+
+       const_iterator begin() const noexcept
+       {
+               return const_iterator(*this);
+       }
+
+       const_iterator end() const
+       {
+               return const_iterator(*this, size());
+       }
+
+       std::size_t size() const
+       {
+               return ContainerOperations::size(_container);
+       }
+
+       bool empty() const
+       {
+               return size() == 0;
+       }
+
+       typename std::conditional<std::is_pointer<ElementType>::value, ElementType, ElementType&>::type
+       operator[](std::size_t index)
+       {
+               /*
+                * To share code between the const and mutable versions of this operator, 'this'
+                * is casted to a const reference. A const_cast then ensures that a mutable
+                * reference (or pointer) is returned.
+                *
+                * We typically avoid const_cast, but this is safe: if the user is calling the
+                * mutable version of this operator, it had a mutable object anyhow.
+                *
+                * For more information, see Item 3 of Effective C++.
+                */
+               const auto& const_this = static_cast<const random_access_container_wrapper&>(*this);
+
+               /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) */
+               return const_cast<typename std::conditional<std::is_pointer<ElementType>::value,
+                                                           ElementType,
+                                                           ElementType&>::type>(const_this[index]);
+       }
+
+       typename std::conditional<std::is_pointer<ElementType>::value,
+                                 const ElementType,
+                                 const ElementType&>::type
+       operator[](std::size_t index) const
+       {
+               if (index >= ContainerOperations::size(_container)) {
+                       throw std::invalid_argument(lttng::format(
+                               "Out of bound access through random_access_container_wrapper: index={}, size={}",
+                               index,
+                               size()));
+               }
+
+               return ContainerOperations::get(_container, index);
+       }
+
+protected:
+       ContainerType _container;
+};
+} /* namespace utils */
+} /* namespace lttng */
+
+#endif /* LTTNG_CONTAINER_WRAPPER_H */
index a4111ad9002e9a29fcd073b4b4c6f93b41041040..14763c00d3b83beb680861304a4982bfa287fb9f 100644 (file)
@@ -6,16 +6,17 @@
  */
 
 #include "context.hpp"
-#include <stddef.h>
-#include <string.h>
+
 #include <common/error.hpp>
 #include <common/macros.hpp>
 
-int parse_application_context(const char *str, char **out_provider_name,
-               char **out_ctx_name)
+#include <stddef.h>
+#include <string.h>
+
+int parse_application_context(const char *str, char **out_provider_name, char **out_ctx_name)
 {
        const char app_ctx_prefix[] = "$app.";
-       char *provider_name = NULL, *ctx_name = NULL;
+       char *provider_name = nullptr, *ctx_name = nullptr;
        size_t i, len, colon_pos = 0, provider_name_len, ctx_name_len;
 
        if (!str || !out_provider_name || !out_ctx_name) {
@@ -28,7 +29,7 @@ int parse_application_context(const char *str, char **out_provider_name,
        }
 
        /* String starts with $app. */
-       if (strncmp(str, app_ctx_prefix, sizeof(app_ctx_prefix) - 1)) {
+       if (strncmp(str, app_ctx_prefix, sizeof(app_ctx_prefix) - 1) != 0) {
                goto not_found;
        }
 
@@ -46,8 +47,7 @@ int parse_application_context(const char *str, char **out_provider_name,
         * No colon found or no ctx name ("$app.provider:") or no provider name
         * given ("$app.:..."), which is invalid.
         */
-       if (!colon_pos || colon_pos == len ||
-                       colon_pos == sizeof(app_ctx_prefix)) {
+       if (!colon_pos || colon_pos == len || colon_pos == sizeof(app_ctx_prefix)) {
                goto not_found;
        }
 
@@ -57,8 +57,7 @@ int parse_application_context(const char *str, char **out_provider_name,
                PERROR("malloc provider_name");
                goto not_found;
        }
-       strncpy(provider_name, str + sizeof(app_ctx_prefix) - 1,
-                       provider_name_len - 1);
+       strncpy(provider_name, str + sizeof(app_ctx_prefix) - 1, provider_name_len - 1);
 
        ctx_name_len = len - colon_pos;
        ctx_name = calloc<char>(ctx_name_len);
@@ -76,4 +75,3 @@ not_found:
        free(ctx_name);
        return -1;
 }
-
index 324ef535e52b5e5658c144be778ae7d095ecc0dc..bcf34cd2daa5543ff533867bebaf7a75e28208df 100644 (file)
@@ -21,7 +21,6 @@
  * Returns 0 if the string is a valid application context, else a negative
  * value on error.
  */
-int parse_application_context(const char *str, char **provider_name,
-               char **ctx_name);
+int parse_application_context(const char *str, char **provider_name, char **ctx_name);
 
 #endif /* LTTNG_COMMON_CONTEXT_H */
index f936736db4919760dcc5c42094c35497d25ddb7b..6c9d258aeb6567ded9ff58f5f10dbc7c0f73117c 100644 (file)
@@ -5,9 +5,10 @@
  *
  */
 
-#include <stdbool.h>
 #include "credentials.hpp"
 
+#include <stdbool.h>
+
 uid_t lttng_credentials_get_uid(const struct lttng_credentials *creds)
 {
        return LTTNG_OPTIONAL_GET(creds->uid);
@@ -19,7 +20,7 @@ gid_t lttng_credentials_get_gid(const struct lttng_credentials *creds)
 }
 
 bool lttng_credentials_is_equal_uid(const struct lttng_credentials *a,
-               const struct lttng_credentials *b)
+                                   const struct lttng_credentials *b)
 {
        LTTNG_ASSERT(a);
        LTTNG_ASSERT(b);
@@ -38,7 +39,7 @@ bool lttng_credentials_is_equal_uid(const struct lttng_credentials *a,
 }
 
 bool lttng_credentials_is_equal_gid(const struct lttng_credentials *a,
-               const struct lttng_credentials *b)
+                                   const struct lttng_credentials *b)
 {
        LTTNG_ASSERT(a);
        LTTNG_ASSERT(b);
@@ -57,11 +58,10 @@ bool lttng_credentials_is_equal_gid(const struct lttng_credentials *a,
 }
 
 bool lttng_credentials_is_equal(const struct lttng_credentials *a,
-               const struct lttng_credentials *b)
+                               const struct lttng_credentials *b)
 {
        LTTNG_ASSERT(a);
        LTTNG_ASSERT(b);
 
-       return lttng_credentials_is_equal_uid(a, b) &&
-                       lttng_credentials_is_equal_gid(a, b);
+       return lttng_credentials_is_equal_uid(a, b) && lttng_credentials_is_equal_gid(a, b);
 }
index 340e64ee96fb92a72f0aa45cc84abf5d81115804..70eaa77b422a022da4c903d40f4da1912de84531 100644 (file)
@@ -8,12 +8,12 @@
 #ifndef LTTNG_CREDENTIALS_H
 #define LTTNG_CREDENTIALS_H
 
-#include <sys/types.h>
-#include <stdbool.h>
 #include "macros.hpp"
-
 #include "optional.hpp"
 
+#include <stdbool.h>
+#include <sys/types.h>
+
 struct lttng_credentials {
        LTTNG_OPTIONAL(uid_t) uid;
        LTTNG_OPTIONAL(gid_t) gid;
@@ -24,12 +24,12 @@ uid_t lttng_credentials_get_uid(const struct lttng_credentials *creds);
 gid_t lttng_credentials_get_gid(const struct lttng_credentials *creds);
 
 bool lttng_credentials_is_equal_uid(const struct lttng_credentials *a,
-               const struct lttng_credentials *b);
+                                   const struct lttng_credentials *b);
 
 bool lttng_credentials_is_equal_gid(const struct lttng_credentials *a,
-               const struct lttng_credentials *b);
+                                   const struct lttng_credentials *b);
 
 bool lttng_credentials_is_equal(const struct lttng_credentials *a,
-               const struct lttng_credentials *b);
+                               const struct lttng_credentials *b);
 
 #endif /* LTTNG_CREDENTIALS_H */
index 0ed35556e81a52a87c8a94e8295e10a1fd1f3eca..489f0144c8fbc26ce489d70efbaefdeb71854f04 100644 (file)
@@ -7,19 +7,17 @@
  */
 
 #define _LGPL_SOURCE
-#include <unistd.h>
 #include <common/compat/paths.hpp>
+#include <common/daemonize.hpp>
+#include <common/error.hpp>
+
 #include <fcntl.h>
-#include <sys/wait.h>
 #include <stdlib.h>
-
+#include <sys/wait.h>
+#include <unistd.h>
 #include <urcu/system.h>
 
-#include <common/daemonize.hpp>
-#include <common/error.hpp>
-
-int lttng_daemonize(pid_t *child_ppid, int *completion_flag,
-               int close_fds)
+int lttng_daemonize(pid_t *child_ppid, int *completion_flag, int close_fds)
 {
        pid_t pid;
 
index d1ec1cb424400382fde60e02928f5c40ee91b460..9e39e2b19dbd81cfe65ee0db41de347aecde97e8 100644 (file)
@@ -9,9 +9,10 @@
  *
  */
 
-#include <unistd.h>
 #include <common/macros.hpp>
 
+#include <unistd.h>
+
 /*
  * Daemonize this process by forking and making the parent wait for the child
  * to signal it indicating readiness. Once received, the parent successfully
@@ -22,7 +23,6 @@
  *
  * Return 0 on success else -1 on error.
  */
-int lttng_daemonize(pid_t *child_ppid, int *completion_flag,
-               int close_fds);
+int lttng_daemonize(pid_t *child_ppid, int *completion_flag, int close_fds);
 
 #endif /* LTTNG_DAEMONIZE_H */
index d79e42a6b63b5a35490f42798412b98c68417d59..e5d70b9e6db73e805db1bc8efd9ed2b3fc46c38c 100644 (file)
@@ -6,21 +6,21 @@
  */
 
 #define _LGPL_SOURCE
-#include <stddef.h>
-#include <unistd.h>
-#include <stdbool.h>
-#include <sys/resource.h>
-#include <pthread.h>
-#include <algorithm>
-
 #include "defaults.hpp"
-#include "macros.hpp"
 #include "error.hpp"
+#include "macros.hpp"
+
+#include <algorithm>
+#include <pthread.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <sys/resource.h>
+#include <unistd.h>
 
 static int pthread_attr_init_done;
 static pthread_attr_t tattr;
 
-static size_t get_page_size(void)
+static size_t get_page_size()
 {
        const long ret = sysconf(_SC_PAGE_SIZE);
 
@@ -35,42 +35,42 @@ static size_t get_page_size(void)
        return (size_t) ret;
 }
 
-size_t default_get_channel_subbuf_size(void)
+size_t default_get_channel_subbuf_size()
 {
        return std::max<size_t>(_DEFAULT_CHANNEL_SUBBUF_SIZE, get_page_size());
 }
 
-size_t default_get_metadata_subbuf_size(void)
+size_t default_get_metadata_subbuf_size()
 {
        return std::max<size_t>(DEFAULT_METADATA_SUBBUF_SIZE, get_page_size());
 }
 
-size_t default_get_kernel_channel_subbuf_size(void)
+size_t default_get_kernel_channel_subbuf_size()
 {
        return std::max<size_t>(DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE, get_page_size());
 }
 
-size_t default_get_ust_pid_channel_subbuf_size(void)
+size_t default_get_ust_pid_channel_subbuf_size()
 {
        return std::max<size_t>(DEFAULT_UST_PID_CHANNEL_SUBBUF_SIZE, get_page_size());
 }
 
-size_t default_get_ust_uid_channel_subbuf_size(void)
+size_t default_get_ust_uid_channel_subbuf_size()
 {
        return std::max<size_t>(DEFAULT_UST_UID_CHANNEL_SUBBUF_SIZE, get_page_size());
 }
 
-pthread_attr_t *default_pthread_attr(void)
+pthread_attr_t *default_pthread_attr()
 {
        if (pthread_attr_init_done) {
                return &tattr;
        }
 
        WARN("Uninitialized pthread attributes, using libc defaults.");
-       return NULL;
+       return nullptr;
 }
 
-static void __attribute__((constructor)) init_default_pthread_attr(void)
+static void __attribute__((constructor)) init_default_pthread_attr()
 {
        int ret;
        struct rlimit rlim;
@@ -90,16 +90,15 @@ static void __attribute__((constructor)) init_default_pthread_attr(void)
                goto error_destroy;
        }
        DBG("Stack size limits: soft %lld, hard %lld bytes",
-                       (long long) rlim.rlim_cur,
-                       (long long) rlim.rlim_max);
+           (long long) rlim.rlim_cur,
+           (long long) rlim.rlim_max);
 
        /*
         * getrlimit() may return a stack size of "-1", meaning "unlimited".
         * In this case, we impose a known-good default minimum value which will
         * override the libc's default stack size if it is smaller.
         */
-       system_ss = rlim.rlim_cur != -1 ? rlim.rlim_cur :
-                       DEFAULT_LTTNG_THREAD_STACK_SIZE;
+       system_ss = rlim.rlim_cur != -1 ? rlim.rlim_cur : DEFAULT_LTTNG_THREAD_STACK_SIZE;
 
        /* Get pthread default thread stack size. */
        ret = pthread_attr_getstacksize(&tattr, &pthread_ss);
@@ -112,13 +111,14 @@ static void __attribute__((constructor)) init_default_pthread_attr(void)
        selected_ss = std::max(pthread_ss, system_ss);
        if (selected_ss < DEFAULT_LTTNG_THREAD_STACK_SIZE) {
                DBG("Default stack size is too small, setting it to %zu bytes",
-                       (size_t) DEFAULT_LTTNG_THREAD_STACK_SIZE);
+                   (size_t) DEFAULT_LTTNG_THREAD_STACK_SIZE);
                selected_ss = DEFAULT_LTTNG_THREAD_STACK_SIZE;
        }
 
        if (rlim.rlim_max > 0 && selected_ss > rlim.rlim_max) {
                WARN("Your system's stack size restrictions (%zu bytes) may be too low for the LTTng daemons to function properly, please set the stack size limit to at least %zu bytes to ensure reliable operation",
-                       (size_t) rlim.rlim_max, (size_t) DEFAULT_LTTNG_THREAD_STACK_SIZE);
+                    (size_t) rlim.rlim_max,
+                    (size_t) DEFAULT_LTTNG_THREAD_STACK_SIZE);
                selected_ss = (size_t) rlim.rlim_max;
        }
 
@@ -138,7 +138,7 @@ error_destroy:
        }
 }
 
-static void __attribute__((destructor)) fini_default_pthread_attr(void)
+static void __attribute__((destructor)) fini_default_pthread_attr()
 {
        int ret;
 
index 61e2891a1e9acd9552cb221c793202f30b951902..149c483ec668cb7912dc6e5aa47b31244db5efc8 100644 (file)
 #ifndef _DEFAULTS_H
 #define _DEFAULTS_H
 
-#include <pthread.h>
 #include <common/macros.hpp>
 
+#include <pthread.h>
+
 /* Default unix group name for tracing. */
-#define DEFAULT_TRACING_GROUP                   "tracing"
+#define DEFAULT_TRACING_GROUP "tracing"
 
 /*
  * This value is defined in the CTF specification (see
  * git://git.efficios.com/ctf.git in the file
  * common-trace-format-specification.txt.
  */
-#define DEFAULT_METADATA_NAME                   "metadata"
+#define DEFAULT_METADATA_NAME "metadata"
 
 /* Environment variable to set session daemon binary path. */
-#define DEFAULT_SESSIOND_PATH_ENV               "LTTNG_SESSIOND_PATH"
+#define DEFAULT_SESSIOND_PATH_ENV "LTTNG_SESSIOND_PATH"
 
 /* Environment variable to set man pager binary path. */
-#define DEFAULT_MAN_BIN_PATH_ENV                "LTTNG_MAN_BIN_PATH"
+#define DEFAULT_MAN_BIN_PATH_ENV "LTTNG_MAN_BIN_PATH"
+
+/* Environment variable to set man manpath. */
+#define DEFAULT_MANPATH "LTTNG_MANPATH"
 
 /* Default man pager binary path. */
-#define DEFAULT_MAN_BIN_PATH                    "/usr/bin/man"
+#define DEFAULT_MAN_BIN_PATH "/usr/bin/man"
 
 /* Default trace output directory name */
-#define DEFAULT_TRACE_DIR_NAME                  "lttng-traces"
+#define DEFAULT_TRACE_DIR_NAME "lttng-traces"
 
 /* Default size of a hash table */
-#define DEFAULT_HT_SIZE                         4
+#define DEFAULT_HT_SIZE 4
 
 /* Default session daemon paths */
-#define DEFAULT_HOME_DIR                                               "/tmp"
-#define DEFAULT_UST_SOCK_DIR                    DEFAULT_HOME_DIR "/ust-app-socks"
-#define DEFAULT_GLOBAL_APPS_PIPE                DEFAULT_UST_SOCK_DIR "/global"
-#define DEFAULT_TRACE_OUTPUT                    DEFAULT_HOME_DIR "/lttng"
+#define DEFAULT_HOME_DIR        "/tmp"
+#define DEFAULT_UST_SOCK_DIR    DEFAULT_HOME_DIR "/ust-app-socks"
+#define DEFAULT_GLOBAL_APPS_PIPE DEFAULT_UST_SOCK_DIR "/global"
+#define DEFAULT_TRACE_OUTPUT    DEFAULT_HOME_DIR "/lttng"
 
 /* Default directory where the trace are written in per domain */
-#define DEFAULT_KERNEL_TRACE_DIR                "kernel"
-#define DEFAULT_UST_TRACE_DIR                   "ust"
+#define DEFAULT_KERNEL_TRACE_DIR "kernel"
+#define DEFAULT_UST_TRACE_DIR   "ust"
 
 /* Subpath for per PID or UID sessions. */
-#define DEFAULT_UST_TRACE_PID_PATH               "pid"
-#define DEFAULT_UST_TRACE_UID_PATH               "uid/%d/%u-bit"
+#define DEFAULT_UST_TRACE_PID_PATH "pid"
+#define DEFAULT_UST_TRACE_UID_PATH "uid/%d/%u-bit"
 
 /*
  * Default session name for the lttng command line. This default value will
  * get the date and time appended (%Y%m%d-%H%M%S) to it.
  */
-#define DEFAULT_SESSION_NAME                    "auto"
+#define DEFAULT_SESSION_NAME "auto"
 
 /* Default consumer paths */
-#define DEFAULT_CONSUMERD_FILE                  "lttng-consumerd"
+#define DEFAULT_CONSUMERD_FILE "lttng-consumerd"
 
 /* Default consumer paths */
-#define DEFAULT_CONSUMERD_RUNDIR                "%s"
+#define DEFAULT_CONSUMERD_RUNDIR "%s"
 
 /* Kernel consumer path */
-#define DEFAULT_KCONSUMERD_PATH                 DEFAULT_CONSUMERD_RUNDIR "/kconsumerd"
-#define DEFAULT_KCONSUMERD_CMD_SOCK_PATH        DEFAULT_KCONSUMERD_PATH "/command"
-#define DEFAULT_KCONSUMERD_ERR_SOCK_PATH        DEFAULT_KCONSUMERD_PATH "/error"
+#define DEFAULT_KCONSUMERD_PATH                 DEFAULT_CONSUMERD_RUNDIR "/kconsumerd"
+#define DEFAULT_KCONSUMERD_CMD_SOCK_PATH DEFAULT_KCONSUMERD_PATH "/command"
+#define DEFAULT_KCONSUMERD_ERR_SOCK_PATH DEFAULT_KCONSUMERD_PATH "/error"
 
 /* UST 64-bit consumer path */
-#define DEFAULT_USTCONSUMERD64_PATH             DEFAULT_CONSUMERD_RUNDIR "/ustconsumerd64"
-#define DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH    DEFAULT_USTCONSUMERD64_PATH "/command"
-#define DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH    DEFAULT_USTCONSUMERD64_PATH "/error"
+#define DEFAULT_USTCONSUMERD64_PATH         DEFAULT_CONSUMERD_RUNDIR "/ustconsumerd64"
+#define DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH DEFAULT_USTCONSUMERD64_PATH "/command"
+#define DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH DEFAULT_USTCONSUMERD64_PATH "/error"
 
 /* UST 32-bit consumer path */
-#define DEFAULT_USTCONSUMERD32_PATH             DEFAULT_CONSUMERD_RUNDIR "/ustconsumerd32"
-#define DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH    DEFAULT_USTCONSUMERD32_PATH "/command"
-#define DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH    DEFAULT_USTCONSUMERD32_PATH "/error"
+#define DEFAULT_USTCONSUMERD32_PATH         DEFAULT_CONSUMERD_RUNDIR "/ustconsumerd32"
+#define DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH DEFAULT_USTCONSUMERD32_PATH "/command"
+#define DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH DEFAULT_USTCONSUMERD32_PATH "/error"
 
 /* Relayd path */
-#define DEFAULT_RELAYD_RUNDIR                  "%s"
-#define DEFAULT_RELAYD_PATH                    DEFAULT_RELAYD_RUNDIR "/relayd"
+#define DEFAULT_RELAYD_RUNDIR "%s"
+#define DEFAULT_RELAYD_PATH   DEFAULT_RELAYD_RUNDIR "/relayd"
 
-#define DEFAULT_RELAYD_MIN_FD_POOL_SIZE                100
+#define DEFAULT_RELAYD_MIN_FD_POOL_SIZE 100
 /*
  * The file descriptor pool size needs a reserve buffer to accommodates the
  * indirect use of short-lived file descriptors. For instance, glibc will
  *
  * This value must be less than DEFAULT_RELAYD_MIN_FD_POOL_SIZE.
  */
-#define DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE    10
+#define DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE 10
 
 /* Default lttng run directory */
-#define DEFAULT_LTTNG_HOME_ENV_VAR              "LTTNG_HOME"
-#define DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR    "HOME"
-#define DEFAULT_LTTNG_RUNDIR                    CONFIG_LTTNG_SYSTEM_RUNDIR
-#define DEFAULT_LTTNG_HOME_RUNDIR               "%s/.lttng"
-#define DEFAULT_LTTNG_SESSIOND_PIDFILE          "lttng-sessiond.pid"
-#define DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE   "agent.port"
-#define DEFAULT_LTTNG_SESSIOND_LOCKFILE         "lttng-sessiond.lck"
+#define DEFAULT_LTTNG_HOME_ENV_VAR           "LTTNG_HOME"
+#define DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR   "HOME"
+#define DEFAULT_LTTNG_RUNDIR                 CONFIG_LTTNG_SYSTEM_RUNDIR
+#define DEFAULT_LTTNG_HOME_RUNDIR            "%s/.lttng"
+#define DEFAULT_LTTNG_SESSIOND_PIDFILE       "lttng-sessiond.pid"
+#define DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE "agent.port"
+#define DEFAULT_LTTNG_SESSIOND_LOCKFILE              "lttng-sessiond.lck"
 
 /* Default probes list */
-#define DEFAULT_LTTNG_KMOD_PROBES              "LTTNG_KMOD_PROBES"
+#define DEFAULT_LTTNG_KMOD_PROBES "LTTNG_KMOD_PROBES"
 
 /* Default extra probes list */
-#define DEFAULT_LTTNG_EXTRA_KMOD_PROBES                "LTTNG_EXTRA_KMOD_PROBES"
+#define DEFAULT_LTTNG_EXTRA_KMOD_PROBES "LTTNG_EXTRA_KMOD_PROBES"
 
 /* Default unix socket path */
-#define DEFAULT_GLOBAL_CLIENT_UNIX_SOCK                DEFAULT_LTTNG_RUNDIR "/client-lttng-sessiond"
-#define DEFAULT_HOME_CLIENT_UNIX_SOCK                  DEFAULT_LTTNG_HOME_RUNDIR "/client-lttng-sessiond"
-#define DEFAULT_GLOBAL_HEALTH_UNIX_SOCK                DEFAULT_LTTNG_RUNDIR "/sessiond-health"
-#define DEFAULT_HOME_HEALTH_UNIX_SOCK                  DEFAULT_LTTNG_HOME_RUNDIR "/sessiond-health"
-#define DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK   DEFAULT_LTTNG_RUNDIR "/sessiond-notification"
-#define DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK    DEFAULT_LTTNG_HOME_RUNDIR "/sessiond-notification"
+#define DEFAULT_GLOBAL_CLIENT_UNIX_SOCK                      DEFAULT_LTTNG_RUNDIR "/client-lttng-sessiond"
+#define DEFAULT_HOME_CLIENT_UNIX_SOCK                DEFAULT_LTTNG_HOME_RUNDIR "/client-lttng-sessiond"
+#define DEFAULT_GLOBAL_HEALTH_UNIX_SOCK                      DEFAULT_LTTNG_RUNDIR "/sessiond-health"
+#define DEFAULT_HOME_HEALTH_UNIX_SOCK                DEFAULT_LTTNG_HOME_RUNDIR "/sessiond-health"
+#define DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK DEFAULT_LTTNG_RUNDIR "/sessiond-notification"
+#define DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK \
+       DEFAULT_LTTNG_HOME_RUNDIR "/sessiond-notification"
 
 /* Default consumer health unix socket path */
-#define DEFAULT_GLOBAL_USTCONSUMER32_HEALTH_UNIX_SOCK  DEFAULT_LTTNG_RUNDIR "/ustconsumerd32/health"
-#define DEFAULT_HOME_USTCONSUMER32_HEALTH_UNIX_SOCK    DEFAULT_LTTNG_HOME_RUNDIR "/ustconsumerd32/health"
-#define DEFAULT_GLOBAL_USTCONSUMER64_HEALTH_UNIX_SOCK  DEFAULT_LTTNG_RUNDIR "/ustconsumerd64/health"
-#define DEFAULT_HOME_USTCONSUMER64_HEALTH_UNIX_SOCK    DEFAULT_LTTNG_HOME_RUNDIR "/ustconsumerd64/health"
-#define DEFAULT_GLOBAL_KCONSUMER_HEALTH_UNIX_SOCK      DEFAULT_LTTNG_RUNDIR "/kconsumerd/health"
-#define DEFAULT_HOME_KCONSUMER_HEALTH_UNIX_SOCK                DEFAULT_LTTNG_HOME_RUNDIR "/kconsumerd/health"
+#define DEFAULT_GLOBAL_USTCONSUMER32_HEALTH_UNIX_SOCK DEFAULT_LTTNG_RUNDIR "/ustconsumerd32/health"
+#define DEFAULT_HOME_USTCONSUMER32_HEALTH_UNIX_SOCK \
+       DEFAULT_LTTNG_HOME_RUNDIR "/ustconsumerd32/health"
+#define DEFAULT_GLOBAL_USTCONSUMER64_HEALTH_UNIX_SOCK DEFAULT_LTTNG_RUNDIR "/ustconsumerd64/health"
+#define DEFAULT_HOME_USTCONSUMER64_HEALTH_UNIX_SOCK \
+       DEFAULT_LTTNG_HOME_RUNDIR "/ustconsumerd64/health"
+#define DEFAULT_GLOBAL_KCONSUMER_HEALTH_UNIX_SOCK DEFAULT_LTTNG_RUNDIR "/kconsumerd/health"
+#define DEFAULT_HOME_KCONSUMER_HEALTH_UNIX_SOCK          DEFAULT_LTTNG_HOME_RUNDIR "/kconsumerd/health"
 
 /* Default relay health unix socket path */
-#define DEFAULT_GLOBAL_RELAY_HEALTH_UNIX_SOCK          DEFAULT_LTTNG_RUNDIR "/relayd/health-%d"
-#define DEFAULT_HOME_RELAY_HEALTH_UNIX_SOCK            DEFAULT_LTTNG_HOME_RUNDIR "/relayd/health-%d"
+#define DEFAULT_GLOBAL_RELAY_HEALTH_UNIX_SOCK DEFAULT_LTTNG_RUNDIR "/relayd/health-%d"
+#define DEFAULT_HOME_RELAY_HEALTH_UNIX_SOCK   DEFAULT_LTTNG_HOME_RUNDIR "/relayd/health-%d"
 
 /* Default daemon configuration file path */
-#define DEFAULT_SYSTEM_CONFIGPATH               CONFIG_LTTNG_SYSTEM_CONFIGDIR \
+#define DEFAULT_SYSTEM_CONFIGPATH     \
+       CONFIG_LTTNG_SYSTEM_CONFIGDIR \
        "/lttng"
 
-#define DEFAULT_DAEMON_CONFIG_FILE              "lttng.conf"
-#define DEFAULT_DAEMON_HOME_CONFIGPATH          DEFAULT_LTTNG_HOME_RUNDIR "/" \
-       DEFAULT_DAEMON_CONFIG_FILE
-#define DEFAULT_DAEMON_SYSTEM_CONFIGPATH        DEFAULT_SYSTEM_CONFIGPATH "/" \
-       DEFAULT_DAEMON_CONFIG_FILE
+#define DEFAULT_DAEMON_CONFIG_FILE      "lttng.conf"
+#define DEFAULT_DAEMON_HOME_CONFIGPATH  DEFAULT_LTTNG_HOME_RUNDIR "/" DEFAULT_DAEMON_CONFIG_FILE
+#define DEFAULT_DAEMON_SYSTEM_CONFIGPATH DEFAULT_SYSTEM_CONFIGPATH "/" DEFAULT_DAEMON_CONFIG_FILE
 
 /* Default session configuration file path */
-#define DEFAULT_SESSION_PATH                    "sessions"
+#define DEFAULT_SESSION_PATH "sessions"
 /* Auto load session in that directory. */
-#define DEFAULT_SESSION_CONFIG_AUTOLOAD         "auto"
-#define DEFAULT_SESSION_HOME_CONFIGPATH         DEFAULT_LTTNG_HOME_RUNDIR "/" \
-       DEFAULT_SESSION_PATH
-#define DEFAULT_SESSION_SYSTEM_CONFIGPATH       DEFAULT_SYSTEM_CONFIGPATH "/" \
-       DEFAULT_SESSION_PATH
-#define DEFAULT_SESSION_CONFIG_FILE_EXTENSION   ".lttng"
-#define DEFAULT_SESSION_CONFIG_XSD_FILENAME     "session.xsd"
-#define DEFAULT_SESSION_CONFIG_XSD_PATH         CONFIG_LTTNG_SYSTEM_DATADIR "/xml/lttng/"
-#define DEFAULT_SESSION_CONFIG_XSD_PATH_ENV     "LTTNG_SESSION_CONFIG_XSD_PATH"
-
-#define DEFAULT_GLOBAL_APPS_UNIX_SOCK \
-       DEFAULT_LTTNG_RUNDIR "/" LTTNG_UST_SOCK_FILENAME
-#define DEFAULT_HOME_APPS_UNIX_SOCK \
-       DEFAULT_LTTNG_HOME_RUNDIR "/" LTTNG_UST_SOCK_FILENAME
-#define DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH \
-       "/" LTTNG_UST_WAIT_FILENAME
-#define DEFAULT_HOME_APPS_WAIT_SHM_PATH \
-       DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH "-%d"
+#define DEFAULT_SESSION_CONFIG_AUTOLOAD              "auto"
+#define DEFAULT_SESSION_HOME_CONFIGPATH              DEFAULT_LTTNG_HOME_RUNDIR "/" DEFAULT_SESSION_PATH
+#define DEFAULT_SESSION_SYSTEM_CONFIGPATH     DEFAULT_SYSTEM_CONFIGPATH "/" DEFAULT_SESSION_PATH
+#define DEFAULT_SESSION_CONFIG_FILE_EXTENSION ".lttng"
+#define DEFAULT_SESSION_CONFIG_XSD_FILENAME   "session.xsd"
+#define DEFAULT_SESSION_CONFIG_XSD_PATH              CONFIG_LTTNG_SYSTEM_DATADIR "/xml/lttng/"
+#define DEFAULT_SESSION_CONFIG_XSD_PATH_ENV   "LTTNG_SESSION_CONFIG_XSD_PATH"
+
+#define DEFAULT_GLOBAL_APPS_UNIX_SOCK    DEFAULT_LTTNG_RUNDIR "/" LTTNG_UST_SOCK_FILENAME
+#define DEFAULT_HOME_APPS_UNIX_SOCK      DEFAULT_LTTNG_HOME_RUNDIR "/" LTTNG_UST_SOCK_FILENAME
+#define DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH "/" LTTNG_UST_WAIT_FILENAME
+#define DEFAULT_HOME_APPS_WAIT_SHM_PATH          DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH "-%d"
 
 /*
  * Value taken from the hard limit allowed by the kernel when using setrlimit
  * than enough. We might end up with quantum computing in a cell phone when
  * reaching this limit.
  */
-#define DEFAULT_STREAM_NAME_LEN        LTTNG_SYMBOL_NAME_LEN + 8
+#define DEFAULT_STREAM_NAME_LEN (LTTNG_SYMBOL_NAME_LEN + 8)
 
 /* Default channel attributes */
-#define DEFAULT_CHANNEL_NAME            "channel0"
+#define DEFAULT_CHANNEL_NAME "channel0"
 /* Default JUL domain channel name. */
-#define DEFAULT_JUL_CHANNEL_NAME        "lttng_jul_channel"
+#define DEFAULT_JUL_CHANNEL_NAME "lttng_jul_channel"
 /* Default JUL tracepoint name. This is a wildcard for the JUL domain. */
-#define DEFAULT_JUL_EVENT_COMPONENT     "lttng_jul"
-#define DEFAULT_JUL_EVENT_NAME          DEFAULT_JUL_EVENT_COMPONENT ":*"
+#define DEFAULT_JUL_EVENT_COMPONENT "lttng_jul"
+#define DEFAULT_JUL_EVENT_NAME     DEFAULT_JUL_EVENT_COMPONENT ":*"
 
 /* Default log4j domain channel name. */
-#define DEFAULT_LOG4J_CHANNEL_NAME        "lttng_log4j_channel"
+#define DEFAULT_LOG4J_CHANNEL_NAME "lttng_log4j_channel"
 /* Default log4j tracepoint name. This is a wildcard for the log4j domain. */
-#define DEFAULT_LOG4J_EVENT_COMPONENT     "lttng_log4j"
-#define DEFAULT_LOG4J_EVENT_NAME          DEFAULT_LOG4J_EVENT_COMPONENT ":*"
+#define DEFAULT_LOG4J_EVENT_COMPONENT "lttng_log4j"
+#define DEFAULT_LOG4J_EVENT_NAME      DEFAULT_LOG4J_EVENT_COMPONENT ":*"
 
 /* Default Python domain channel name. */
-#define DEFAULT_PYTHON_CHANNEL_NAME       "lttng_python_channel"
+#define DEFAULT_PYTHON_CHANNEL_NAME "lttng_python_channel"
 /* Default Python tracepoint name. This is a wildcard for the python domain. */
-#define DEFAULT_PYTHON_EVENT_COMPONENT    "lttng_python"
-#define DEFAULT_PYTHON_EVENT_NAME         DEFAULT_PYTHON_EVENT_COMPONENT ":*"
+#define DEFAULT_PYTHON_EVENT_COMPONENT "lttng_python"
+#define DEFAULT_PYTHON_EVENT_NAME      DEFAULT_PYTHON_EVENT_COMPONENT ":*"
 
-#define DEFAULT_CHANNEL_OVERWRITE       -1
-#define DEFAULT_CHANNEL_TRACEFILE_SIZE  CONFIG_DEFAULT_CHANNEL_TRACEFILE_SIZE
+#define DEFAULT_CHANNEL_OVERWRITE      (-1)
+#define DEFAULT_CHANNEL_TRACEFILE_SIZE CONFIG_DEFAULT_CHANNEL_TRACEFILE_SIZE
 #define DEFAULT_CHANNEL_TRACEFILE_COUNT CONFIG_DEFAULT_CHANNEL_TRACEFILE_COUNT
 
-#define _DEFAULT_CHANNEL_SUBBUF_SIZE   CONFIG_DEFAULT_CHANNEL_SUBBUF_SIZE
-#define _DEFAULT_CHANNEL_OUTPUT                        LTTNG_EVENT_MMAP
+#define _DEFAULT_CHANNEL_SUBBUF_SIZE CONFIG_DEFAULT_CHANNEL_SUBBUF_SIZE
+#define _DEFAULT_CHANNEL_OUTPUT             LTTNG_EVENT_MMAP
 
 /* Metadata channel defaults. */
-#define DEFAULT_METADATA_SUBBUF_SIZE    CONFIG_DEFAULT_METADATA_SUBBUF_SIZE
-#define DEFAULT_METADATA_SUBBUF_NUM     CONFIG_DEFAULT_METADATA_SUBBUF_NUM
-#define DEFAULT_METADATA_CACHE_SIZE     CONFIG_DEFAULT_METADATA_CACHE_SIZE
-#define DEFAULT_METADATA_SWITCH_TIMER  0
-#define DEFAULT_METADATA_READ_TIMER    0
-#define DEFAULT_METADATA_OVERWRITE     0
-#define DEFAULT_METADATA_OUTPUT                LTTNG_EVENT_MMAP
+#define DEFAULT_METADATA_SUBBUF_SIZE  CONFIG_DEFAULT_METADATA_SUBBUF_SIZE
+#define DEFAULT_METADATA_SUBBUF_NUM   CONFIG_DEFAULT_METADATA_SUBBUF_NUM
+#define DEFAULT_METADATA_CACHE_SIZE   CONFIG_DEFAULT_METADATA_CACHE_SIZE
+#define DEFAULT_METADATA_SWITCH_TIMER 0
+#define DEFAULT_METADATA_READ_TIMER   0
+#define DEFAULT_METADATA_OVERWRITE    0
+#define DEFAULT_METADATA_OUTPUT              LTTNG_EVENT_MMAP
 
 /* Kernel has different defaults */
 
 /* DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE must always be a power of 2 */
-#define DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE     CONFIG_DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE
+#define DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE CONFIG_DEFAULT_KERNEL_CHANNEL_SUBBUF_SIZE
 /*
  * DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM must always be a power of 2.
  * Update help manually if override.
  */
-#define DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM      CONFIG_DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM
+#define DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM CONFIG_DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM
 /* See lttng-kernel.h enum lttng_kernel_output for channel output */
-#define DEFAULT_KERNEL_CHANNEL_OUTPUT                  LTTNG_EVENT_SPLICE
+#define DEFAULT_KERNEL_CHANNEL_OUTPUT          LTTNG_EVENT_SPLICE
 #define DEFAULT_KERNEL_CHANNEL_SWITCH_TIMER    CONFIG_DEFAULT_KERNEL_CHANNEL_SWITCH_TIMER
 #define DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER   CONFIG_DEFAULT_KERNEL_CHANNEL_MONITOR_TIMER
 #define DEFAULT_KERNEL_CHANNEL_READ_TIMER      CONFIG_DEFAULT_KERNEL_CHANNEL_READ_TIMER
 #define DEFAULT_KERNEL_CHANNEL_LIVE_TIMER      CONFIG_DEFAULT_KERNEL_CHANNEL_LIVE_TIMER
-#define DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT        CONFIG_DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT
+#define DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT CONFIG_DEFAULT_KERNEL_CHANNEL_BLOCKING_TIMEOUT
 
 /* User space defaults */
 
 /* Must be a power of 2 */
-#define DEFAULT_UST_PID_CHANNEL_SUBBUF_SIZE    CONFIG_DEFAULT_UST_PID_CHANNEL_SUBBUF_SIZE
-#define DEFAULT_UST_UID_CHANNEL_SUBBUF_SIZE    CONFIG_DEFAULT_UST_UID_CHANNEL_SUBBUF_SIZE
+#define DEFAULT_UST_PID_CHANNEL_SUBBUF_SIZE CONFIG_DEFAULT_UST_PID_CHANNEL_SUBBUF_SIZE
+#define DEFAULT_UST_UID_CHANNEL_SUBBUF_SIZE CONFIG_DEFAULT_UST_UID_CHANNEL_SUBBUF_SIZE
 /* Must be a power of 2. Update help manuall if override. */
-#define DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM     CONFIG_DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM
-#define DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM     CONFIG_DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM
+#define DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM CONFIG_DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM
+#define DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM CONFIG_DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM
 /* See lttng-ust.h enum lttng_ust_output */
-#define DEFAULT_UST_PID_CHANNEL_OUTPUT                 _DEFAULT_CHANNEL_OUTPUT
-#define DEFAULT_UST_UID_CHANNEL_OUTPUT                 _DEFAULT_CHANNEL_OUTPUT
+#define DEFAULT_UST_PID_CHANNEL_OUTPUT _DEFAULT_CHANNEL_OUTPUT
+#define DEFAULT_UST_UID_CHANNEL_OUTPUT _DEFAULT_CHANNEL_OUTPUT
 /* Timers in usec. */
-#define DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER   CONFIG_DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER
-#define DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER   CONFIG_DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER
-#define DEFAULT_UST_PID_CHANNEL_LIVE_TIMER     CONFIG_DEFAULT_UST_PID_CHANNEL_LIVE_TIMER
-#define DEFAULT_UST_UID_CHANNEL_LIVE_TIMER     CONFIG_DEFAULT_UST_UID_CHANNEL_LIVE_TIMER
-#define DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER  CONFIG_DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER
-#define DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER  CONFIG_DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER
+#define DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER  CONFIG_DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER
+#define DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER  CONFIG_DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER
+#define DEFAULT_UST_PID_CHANNEL_LIVE_TIMER    CONFIG_DEFAULT_UST_PID_CHANNEL_LIVE_TIMER
+#define DEFAULT_UST_UID_CHANNEL_LIVE_TIMER    CONFIG_DEFAULT_UST_UID_CHANNEL_LIVE_TIMER
+#define DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER CONFIG_DEFAULT_UST_PID_CHANNEL_MONITOR_TIMER
+#define DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER CONFIG_DEFAULT_UST_UID_CHANNEL_MONITOR_TIMER
 
-#define DEFAULT_UST_PID_CHANNEL_READ_TIMER      CONFIG_DEFAULT_UST_PID_CHANNEL_READ_TIMER
-#define DEFAULT_UST_UID_CHANNEL_READ_TIMER      CONFIG_DEFAULT_UST_UID_CHANNEL_READ_TIMER
+#define DEFAULT_UST_PID_CHANNEL_READ_TIMER CONFIG_DEFAULT_UST_PID_CHANNEL_READ_TIMER
+#define DEFAULT_UST_UID_CHANNEL_READ_TIMER CONFIG_DEFAULT_UST_UID_CHANNEL_READ_TIMER
 
-#define DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT       CONFIG_DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT
-#define DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT       CONFIG_DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT
+#define DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT CONFIG_DEFAULT_UST_PID_CHANNEL_BLOCKING_TIMEOUT
+#define DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT CONFIG_DEFAULT_UST_UID_CHANNEL_BLOCKING_TIMEOUT
 
 /*
  * Default timeout value for the sem_timedwait() call. Blocking forever is not
  * wanted so a timeout is used to control the data flow and not freeze the
  * session daemon.
  */
-#define DEFAULT_SEM_WAIT_TIMEOUT            30    /* in seconds */
+#define DEFAULT_SEM_WAIT_TIMEOUT 30 /* in seconds */
 
 /* Default bind addresses for network services. */
-#define DEFAULT_NETWORK_CONTROL_BIND_ADDRESS    CONFIG_DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
-#define DEFAULT_NETWORK_DATA_BIND_ADDRESS              CONFIG_DEFAULT_NETWORK_DATA_BIND_ADDRESS
-#define DEFAULT_NETWORK_VIEWER_BIND_ADDRESS     CONFIG_DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
-#define DEFAULT_AGENT_BIND_ADDRESS              CONFIG_DEFAULT_AGENT_BIND_ADDRESS
+#define DEFAULT_NETWORK_CONTROL_BIND_ADDRESS CONFIG_DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
+#define DEFAULT_NETWORK_DATA_BIND_ADDRESS    CONFIG_DEFAULT_NETWORK_DATA_BIND_ADDRESS
+#define DEFAULT_NETWORK_VIEWER_BIND_ADDRESS  CONFIG_DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
+#define DEFAULT_AGENT_BIND_ADDRESS          CONFIG_DEFAULT_AGENT_BIND_ADDRESS
 
 /* Default network ports for trace streaming support. */
-#define DEFAULT_NETWORK_CONTROL_PORT        CONFIG_DEFAULT_NETWORK_CONTROL_PORT
-#define DEFAULT_NETWORK_DATA_PORT           CONFIG_DEFAULT_NETWORK_DATA_PORT
-#define DEFAULT_NETWORK_VIEWER_PORT         CONFIG_DEFAULT_NETWORK_VIEWER_PORT
+#define DEFAULT_NETWORK_CONTROL_PORT CONFIG_DEFAULT_NETWORK_CONTROL_PORT
+#define DEFAULT_NETWORK_DATA_PORT    CONFIG_DEFAULT_NETWORK_DATA_PORT
+#define DEFAULT_NETWORK_VIEWER_PORT  CONFIG_DEFAULT_NETWORK_VIEWER_PORT
 
 /* Agent registration TCP port range. */
-#define DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN  CONFIG_DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN
-#define DEFAULT_AGENT_TCP_PORT_RANGE_END    CONFIG_DEFAULT_AGENT_TCP_PORT_RANGE_END
+#define DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN CONFIG_DEFAULT_AGENT_TCP_PORT_RANGE_BEGIN
+#define DEFAULT_AGENT_TCP_PORT_RANGE_END   CONFIG_DEFAULT_AGENT_TCP_PORT_RANGE_END
 
 /* Number of buckets in the event notifier error count map. */
-#define DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE CONFIG_DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE
+#define DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE \
+       CONFIG_DEFAULT_EVENT_NOTIFIER_ERROR_COUNT_MAP_SIZE
 
 /*
  * If a thread stalls for this amount of time, it will be considered bogus (bad
  * health).
  */
-#define DEFAULT_HEALTH_CHECK_DELTA_S        20
-#define DEFAULT_HEALTH_CHECK_DELTA_NS       0
+#define DEFAULT_HEALTH_CHECK_DELTA_S  20
+#define DEFAULT_HEALTH_CHECK_DELTA_NS 0
 
 /*
  * Wait period before retrying the lttng_data_pending command in the lttng
  * stop command of liblttng-ctl.
  */
-#define DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US 200000  /* usec */
+#define DEFAULT_DATA_AVAILABILITY_WAIT_TIME_US 200000 /* usec */
 
 /*
  * Wait period before retrying the lttng_consumer_flushed_cache when
  * the consumer receives metadata.
  */
-#define DEFAULT_METADATA_AVAILABILITY_WAIT_TIME 200000  /* usec */
+#define DEFAULT_METADATA_AVAILABILITY_WAIT_TIME 200000 /* usec */
 
 /*
  * The usual value for the maximum TCP SYN retries time and TCP FIN timeout is
  * 180 and 60 seconds on most Linux system and the default value since kernel
  * 2.2 thus using the highest value. See tcp(7) for more details.
  */
-#define DEFAULT_INET_TCP_TIMEOUT                       180     /* sec */
+#define DEFAULT_INET_TCP_TIMEOUT 180 /* sec */
 
 /* Maximum payload size for a control connection */
 
-#define DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE CONFIG_DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
+#define DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE \
+       CONFIG_DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
 
 /*
  * Default receiving and sending timeout for an application socket.
  */
-#define DEFAULT_APP_SOCKET_RW_TIMEOUT       CONFIG_DEFAULT_APP_SOCKET_RW_TIMEOUT
-#define DEFAULT_APP_SOCKET_TIMEOUT_ENV      "LTTNG_APP_SOCKET_TIMEOUT"
+#define DEFAULT_APP_SOCKET_RW_TIMEOUT  CONFIG_DEFAULT_APP_SOCKET_RW_TIMEOUT
+#define DEFAULT_APP_SOCKET_TIMEOUT_ENV "LTTNG_APP_SOCKET_TIMEOUT"
 
-#define DEFAULT_UST_STREAM_FD_NUM                      2 /* Number of fd per UST stream. */
+#define DEFAULT_UST_STREAM_FD_NUM 2 /* Number of fd per UST stream. */
 
-#define DEFAULT_SNAPSHOT_NAME                          "snapshot"
-#define DEFAULT_SNAPSHOT_MAX_SIZE                      0 /* Unlimited. */
+#define DEFAULT_SNAPSHOT_NAME    "snapshot"
+#define DEFAULT_SNAPSHOT_MAX_SIZE 0 /* Unlimited. */
 
 /* Suffix of an index file. */
-#define DEFAULT_INDEX_FILE_SUFFIX                      ".idx"
-#define DEFAULT_INDEX_DIR                                      "index"
+#define DEFAULT_INDEX_FILE_SUFFIX ".idx"
+#define DEFAULT_INDEX_DIR        "index"
 
 /* Default lttng command live timer value in usec. */
-#define DEFAULT_LTTNG_LIVE_TIMER                       CONFIG_DEFAULT_LTTNG_LIVE_TIMER
+#define DEFAULT_LTTNG_LIVE_TIMER CONFIG_DEFAULT_LTTNG_LIVE_TIMER
 
 /* Default runas worker name */
-#define DEFAULT_RUN_AS_WORKER_NAME                     "lttng-runas"
+#define DEFAULT_RUN_AS_WORKER_NAME "lttng-runas"
 
 /* Default LTTng MI XML namespace. */
-#define DEFAULT_LTTNG_MI_NAMESPACE             "https://lttng.org/xml/ns/lttng-mi"
+#define DEFAULT_LTTNG_MI_NAMESPACE "https://lttng.org/xml/ns/lttng-mi"
 
 /* Default thread stack size; the default mandated by pthread_create(3) */
-#define DEFAULT_LTTNG_THREAD_STACK_SIZE                2097152
+#define DEFAULT_LTTNG_THREAD_STACK_SIZE 2097152
 
 /* Default maximal size of message notification channel message payloads. */
-#define DEFAULT_MAX_NOTIFICATION_CLIENT_MESSAGE_PAYLOAD_SIZE   65536
+#define DEFAULT_MAX_NOTIFICATION_CLIENT_MESSAGE_PAYLOAD_SIZE 65536
 
 /* Default maximal size of trace archive location. */
-#define DEFAULT_MAX_TRACE_ARCHIVE_LOCATION_PAYLOAD_SIZE                65536
+#define DEFAULT_MAX_TRACE_ARCHIVE_LOCATION_PAYLOAD_SIZE 65536
 
 /* Default maximal size of message notification channel message payloads. */
-#define DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT          100
-
+#define DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT 100
 
-#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ENV "LTTNG_RELAYD_TCP_KEEP_ALIVE"
+#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ENV                  "LTTNG_RELAYD_TCP_KEEP_ALIVE"
 #define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME_ENV "LTTNG_RELAYD_TCP_KEEP_ALIVE_IDLE_TIME"
-#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV "LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT"
-#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV "LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL"
-#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV "LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD"
+#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT_ENV \
+       "LTTNG_RELAYD_TCP_KEEP_ALIVE_MAX_PROBE_COUNT"
+#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL_ENV \
+       "LTTNG_RELAYD_TCP_KEEP_ALIVE_PROBE_INTERVAL"
+#define DEFAULT_LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD_ENV \
+       "LTTNG_RELAYD_TCP_KEEP_ALIVE_ABORT_THRESHOLD"
 #define DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV "LTTNG_RELAYD_DISALLOW_CLEAR"
 
 #define DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV "LTTNG_RELAYD_WORKING_DIRECTORY"
  * Name of the intermediate directory used to rename the trace chunk of a
  * session's first rotation.
  */
-#define DEFAULT_CHUNK_TMP_OLD_DIRECTORY                        ".tmp_old_chunk"
-#define DEFAULT_CHUNK_TMP_NEW_DIRECTORY                        ".tmp_new_chunk"
-#define DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY                "archives"
-#define DEFAULT_UNLINKED_FILES_DIRECTORY               ".unlinked"
+#define DEFAULT_CHUNK_TMP_OLD_DIRECTORY                ".tmp_old_chunk"
+#define DEFAULT_CHUNK_TMP_NEW_DIRECTORY                ".tmp_new_chunk"
+#define DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY "archives"
+#define DEFAULT_UNLINKED_FILES_DIRECTORY       ".unlinked"
 
 /*
  * Default timer value in usec for the rotate pending polling check on the
  * relay when a rotation has completed on the consumer.
  */
-#define DEFAULT_ROTATE_PENDING_TIMER   CONFIG_DEFAULT_ROTATE_PENDING_TIMER
+#define DEFAULT_ROTATE_PENDING_TIMER CONFIG_DEFAULT_ROTATE_PENDING_TIMER
 
 /*
  * Returns the default subbuf size.
  * This function depends on a value that is set at constructor time, so it is
  * unsafe to call it from another constructor.
  */
-size_t default_get_channel_subbuf_size(void);
+size_t default_get_channel_subbuf_size();
 
 /*
  * Returns the default metadata subbuf size.
@@ -387,7 +391,7 @@ size_t default_get_channel_subbuf_size(void);
  * This function depends on a value that is set at constructor time, so it is
  * unsafe to call it from another constructor.
  */
-size_t default_get_metadata_subbuf_size(void);
+size_t default_get_metadata_subbuf_size();
 
 /*
  * Returns the default subbuf size for the kernel domain.
@@ -395,7 +399,7 @@ size_t default_get_metadata_subbuf_size(void);
  * This function depends on a value that is set at constructor time, so it is
  * unsafe to call it from another constructor.
  */
-size_t default_get_kernel_channel_subbuf_size(void);
+size_t default_get_kernel_channel_subbuf_size();
 
 /*
  * Returns the default subbuf size for the UST domain per PID.
@@ -403,7 +407,7 @@ size_t default_get_kernel_channel_subbuf_size(void);
  * This function depends on a value that is set at constructor time, so it is
  * unsafe to call it from another constructor.
  */
-size_t default_get_ust_pid_channel_subbuf_size(void);
+size_t default_get_ust_pid_channel_subbuf_size();
 
 /*
  * Returns the default subbuf size for the UST domain per UID.
@@ -411,7 +415,7 @@ size_t default_get_ust_pid_channel_subbuf_size(void);
  * This function depends on a value that is set at constructor time, so it is
  * unsafe to call it from another constructor.
  */
-size_t default_get_ust_uid_channel_subbuf_size(void);
+size_t default_get_ust_uid_channel_subbuf_size();
 
 /*
  * Get the default pthread_attr to use on thread creation.
@@ -422,6 +426,6 @@ size_t default_get_ust_uid_channel_subbuf_size(void);
  * pthread_attr_t pointer where the thread stack size is set to the soft stack
  * size limit.
  */
-pthread_attr_t *default_pthread_attr(void);
+pthread_attr_t *default_pthread_attr();
 
 #endif /* _DEFAULTS_H */
index 2c39c66e1ac6e4459a2860e09bb833f9034ecf25..7b331d0491e45a294b537b1f1e38beb19c03463d 100644 (file)
@@ -5,8 +5,8 @@
  *
  */
 
-#include "lttng/domain-internal.hpp"
 #include "common/macros.hpp"
+#include "lttng/domain-internal.hpp"
 
 const char *lttng_domain_type_str(enum lttng_domain_type domain_type)
 {
@@ -16,13 +16,13 @@ const char *lttng_domain_type_str(enum lttng_domain_type domain_type)
        case LTTNG_DOMAIN_KERNEL:
                return "kernel";
        case LTTNG_DOMAIN_UST:
-               return "ust";
+               return "user space";
        case LTTNG_DOMAIN_JUL:
-               return "jul";
+               return "java.util.logging (JUL)";
        case LTTNG_DOMAIN_LOG4J:
                return "log4j";
        case LTTNG_DOMAIN_PYTHON:
-               return "python";
+               return "Python logging";
        default:
                return "???";
        }
index ddc691bb13e76f4e5d0472584f5568b83633f523..c18a484711038cc782945283b2c9c192d3359758 100644 (file)
@@ -8,8 +8,8 @@
 #include <common/dynamic-array.hpp>
 
 void lttng_dynamic_array_init(struct lttng_dynamic_array *array,
-               size_t element_size,
-               lttng_dynamic_array_element_destructor destructor)
+                             size_t element_size,
+                             lttng_dynamic_array_element_destructor destructor)
 {
        lttng_dynamic_buffer_init(&array->buffer);
        array->element_size = element_size;
@@ -17,8 +17,7 @@ void lttng_dynamic_array_init(struct lttng_dynamic_array *array,
        array->destructor = destructor;
 }
 
-int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array,
-               size_t new_element_count)
+int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array, size_t new_element_count)
 {
        int ret;
 
@@ -31,8 +30,7 @@ int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array,
                size_t i;
 
                for (i = new_element_count; i < array->size; i++) {
-                       void *element = lttng_dynamic_array_get_element(
-                                       array, i);
+                       void *element = lttng_dynamic_array_get_element(array, i);
 
                        array->destructor(element);
                }
@@ -40,13 +38,12 @@ int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array,
 
        array->size = new_element_count;
        ret = lttng_dynamic_buffer_set_size(&array->buffer,
-                       new_element_count * array->element_size);
+                                           new_element_count * array->element_size);
 end:
        return ret;
 }
 
-int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array,
-               const void *element)
+int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array, const void *element)
 {
        int ret;
 
@@ -55,8 +52,7 @@ int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array,
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&array->buffer, element,
-                       array->element_size);
+       ret = lttng_dynamic_buffer_append(&array->buffer, element, array->element_size);
        if (ret) {
                goto end;
        }
@@ -65,25 +61,23 @@ end:
        return ret;
 }
 
-int lttng_dynamic_array_remove_element(struct lttng_dynamic_array *array,
-               size_t element_index)
+int lttng_dynamic_array_remove_element(struct lttng_dynamic_array *array, size_t element_index)
 {
-       void *element = lttng_dynamic_array_get_element(array,
-                       element_index);
+       void *element = lttng_dynamic_array_get_element(array, element_index);
 
        if (array->destructor) {
                array->destructor(element);
        }
        if (element_index != lttng_dynamic_array_get_count(array) - 1) {
-               void *next_element = lttng_dynamic_array_get_element(array,
-                               element_index + 1);
+               void *next_element = lttng_dynamic_array_get_element(array, element_index + 1);
 
-               memmove(element, next_element,
-                               (array->size - element_index - 1) * array->element_size);
+               memmove(element,
+                       next_element,
+                       (array->size - element_index - 1) * array->element_size);
        }
        array->size--;
        return lttng_dynamic_buffer_set_size(&array->buffer,
-                       array->buffer.size - array->element_size);
+                                            array->buffer.size - array->element_size);
 }
 
 void lttng_dynamic_array_reset(struct lttng_dynamic_array *array)
@@ -92,8 +86,7 @@ void lttng_dynamic_array_reset(struct lttng_dynamic_array *array)
                size_t i;
 
                for (i = 0; i < lttng_dynamic_array_get_count(array); i++) {
-                       array->destructor(lttng_dynamic_array_get_element(array,
-                                       i));
+                       array->destructor(lttng_dynamic_array_get_element(array, i));
                }
        }
 
@@ -107,8 +100,7 @@ void lttng_dynamic_array_clear(struct lttng_dynamic_array *array)
                size_t i;
 
                for (i = 0; i < lttng_dynamic_array_get_count(array); i++) {
-                       array->destructor(lttng_dynamic_array_get_element(array,
-                                       i));
+                       array->destructor(lttng_dynamic_array_get_element(array, i));
                }
        }
 
@@ -116,28 +108,25 @@ void lttng_dynamic_array_clear(struct lttng_dynamic_array *array)
        array->size = 0;
 }
 
-void lttng_dynamic_pointer_array_init(
-               struct lttng_dynamic_pointer_array *array,
-               lttng_dynamic_pointer_array_destructor destructor)
+void lttng_dynamic_pointer_array_init(struct lttng_dynamic_pointer_array *array,
+                                     lttng_dynamic_pointer_array_destructor destructor)
 {
        lttng_dynamic_array_init(&array->array, sizeof(void *), destructor);
-}      
+}
 
-int lttng_dynamic_pointer_array_remove_pointer(
-               struct lttng_dynamic_pointer_array *array, size_t index)
+int lttng_dynamic_pointer_array_remove_pointer(struct lttng_dynamic_pointer_array *array,
+                                              size_t index)
 {
        int ret;
-       const lttng_dynamic_array_element_destructor destructor =
-                       array->array.destructor;
+       const lttng_dynamic_array_element_destructor destructor = array->array.destructor;
 
        /*
         * Prevent the destructor from being used by the underlying
         * dynamic array.
         */
-       array->array.destructor = NULL;
+       array->array.destructor = nullptr;
        if (destructor) {
-               destructor(lttng_dynamic_pointer_array_get_pointer(array,
-                               index));
+               destructor(lttng_dynamic_pointer_array_get_pointer(array, index));
        }
        ret = lttng_dynamic_array_remove_element(&array->array, index);
        array->array.destructor = destructor;
@@ -145,43 +134,38 @@ int lttng_dynamic_pointer_array_remove_pointer(
 }
 
 /* Release any memory used by the dynamic array. */
-void lttng_dynamic_pointer_array_reset(
-               struct lttng_dynamic_pointer_array *array)
+void lttng_dynamic_pointer_array_reset(struct lttng_dynamic_pointer_array *array)
 {
        if (array->array.destructor) {
                size_t i, count = lttng_dynamic_pointer_array_get_count(array);
 
                for (i = 0; i < count; i++) {
-                       void *ptr = lttng_dynamic_pointer_array_get_pointer(
-                                       array, i);
+                       void *ptr = lttng_dynamic_pointer_array_get_pointer(array, i);
                        array->array.destructor(ptr);
                }
                /*
                 * Prevent the destructor from being used by the underlying
                 * dynamic array.
                 */
-               array->array.destructor = NULL;
+               array->array.destructor = nullptr;
        }
        lttng_dynamic_array_reset(&array->array);
 }
 
-void lttng_dynamic_pointer_array_clear(
-               struct lttng_dynamic_pointer_array *array)
+void lttng_dynamic_pointer_array_clear(struct lttng_dynamic_pointer_array *array)
 {
-       const lttng_dynamic_array_element_destructor destructor =
-                       array->array.destructor;
+       const lttng_dynamic_array_element_destructor destructor = array->array.destructor;
 
        /*
         * Prevent the destructor from being used by the underlying
         * dynamic array.
         */
-       array->array.destructor = NULL;
+       array->array.destructor = nullptr;
        if (destructor) {
                size_t i, count = lttng_dynamic_pointer_array_get_count(array);
 
                for (i = 0; i < count; i++) {
-                       void *ptr = lttng_dynamic_pointer_array_get_pointer(
-                                       array, i);
+                       void *ptr = lttng_dynamic_pointer_array_get_pointer(array, i);
                        destructor(ptr);
                }
        }
index 23f3a39b9fe2b78eb41be42af592270204191496..a50fac10bf9ba4e655f3480c4198c903a56c3b59 100644 (file)
@@ -10,8 +10,8 @@
 
 #include <common/dynamic-buffer.hpp>
 
-typedef void (*lttng_dynamic_array_element_destructor)(void *element);
-typedef void (*lttng_dynamic_pointer_array_destructor)(void *ptr);
+using lttng_dynamic_array_element_destructor = void (*)(void *);
+using lttng_dynamic_pointer_array_destructor = void (*)(void *);
 
 struct lttng_dynamic_array {
        struct lttng_dynamic_buffer buffer;
@@ -29,15 +29,13 @@ struct lttng_dynamic_pointer_array {
  * allocation and can't fail.
  */
 void lttng_dynamic_array_init(struct lttng_dynamic_array *array,
-               size_t element_size,
-               lttng_dynamic_array_element_destructor destructor);
+                             size_t element_size,
+                             lttng_dynamic_array_element_destructor destructor);
 
 /*
  * Returns the number of elements in the dynamic array.
  */
-static inline
-size_t lttng_dynamic_array_get_count(
-               const struct lttng_dynamic_array *array)
+static inline size_t lttng_dynamic_array_get_count(const struct lttng_dynamic_array *array)
 {
        return array->size;
 }
@@ -46,9 +44,8 @@ size_t lttng_dynamic_array_get_count(
  * Returns a pointer to the element. Mutating operations on the array invalidate
  * the returned pointer.
  */
-static inline
-void *lttng_dynamic_array_get_element(const struct lttng_dynamic_array *array,
-               size_t element_index)
+static inline void *lttng_dynamic_array_get_element(const struct lttng_dynamic_array *array,
+                                                   size_t element_index)
 {
        LTTNG_ASSERT(element_index < array->size);
        return array->buffer.data + (element_index * array->element_size);
@@ -69,8 +66,7 @@ void *lttng_dynamic_array_get_element(const struct lttng_dynamic_array *array,
  * NOTE: It is striclty _invalid_ to access memory after _size_, regardless
  *       of prior calls to set_capacity().
  */
-int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array,
-               size_t new_element_count);
+int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array, size_t new_element_count);
 
 /*
  * Add an element to the end of a dynamic array. The array's element count is
@@ -78,16 +74,14 @@ int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array,
  *
  * element is a pointer to the element to add (copy) to the array.
  */
-int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array,
-               const void *element);
+int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array, const void *element);
 
 /*
  * Remove an element from the dynamic array. The array's element count is
  * decreased by one and the following elements are shifted to take its place
  * (when applicable).
  */
-int lttng_dynamic_array_remove_element(struct lttng_dynamic_array *array,
-               size_t element_index);
+int lttng_dynamic_array_remove_element(struct lttng_dynamic_array *array, size_t element_index);
 
 /* Release any memory used by the dynamic array. */
 void lttng_dynamic_array_reset(struct lttng_dynamic_array *array);
@@ -106,16 +100,14 @@ void lttng_dynamic_array_clear(struct lttng_dynamic_array *array);
  * Initialize a resizable array of fixed-size elements. This performs no
  * allocation and can't fail.
  */
-void lttng_dynamic_pointer_array_init(
-               struct lttng_dynamic_pointer_array *array,
-               lttng_dynamic_pointer_array_destructor destructor);
+void lttng_dynamic_pointer_array_init(struct lttng_dynamic_pointer_array *array,
+                                     lttng_dynamic_pointer_array_destructor destructor);
 
 /*
  * Returns the number of pointers in the dynamic pointer array.
  */
-static inline
-size_t lttng_dynamic_pointer_array_get_count(
-               const struct lttng_dynamic_pointer_array *array)
+static inline size_t
+lttng_dynamic_pointer_array_get_count(const struct lttng_dynamic_pointer_array *array)
 {
        return lttng_dynamic_array_get_count(&array->array);
 }
@@ -123,9 +115,9 @@ size_t lttng_dynamic_pointer_array_get_count(
 /*
  * Returns the pointer at index `index`.
  */
-static inline
-void *lttng_dynamic_pointer_array_get_pointer(
-               const struct lttng_dynamic_pointer_array *array, size_t index)
+static inline void *
+lttng_dynamic_pointer_array_get_pointer(const struct lttng_dynamic_pointer_array *array,
+                                       size_t index)
 {
        void **element = (void **) lttng_dynamic_array_get_element(&array->array, index);
 
@@ -137,14 +129,13 @@ void *lttng_dynamic_pointer_array_get_pointer(
  * run the destructor.
  */
 
-static inline
-void *lttng_dynamic_pointer_array_steal_pointer(
-               struct lttng_dynamic_pointer_array *array, size_t index)
+static inline void *
+lttng_dynamic_pointer_array_steal_pointer(struct lttng_dynamic_pointer_array *array, size_t index)
 {
        void **p_element = (void **) lttng_dynamic_array_get_element(&array->array, index);
        void *element = *p_element;
 
-       *p_element = NULL;
+       *p_element = nullptr;
 
        return element;
 }
@@ -154,9 +145,8 @@ void *lttng_dynamic_pointer_array_steal_pointer(
  * count is increased by one and its underlying capacity is adjusted
  * automatically.
  */
-static inline
-int lttng_dynamic_pointer_array_add_pointer(
-               struct lttng_dynamic_pointer_array *array, void *pointer)
+static inline int lttng_dynamic_pointer_array_add_pointer(struct lttng_dynamic_pointer_array *array,
+                                                         void *pointer)
 {
        return lttng_dynamic_array_add_element(&array->array, &pointer);
 }
@@ -166,15 +156,13 @@ int lttng_dynamic_pointer_array_add_pointer(
  * count is decreased by one and the following pointers are shifted to
  * take the place of the removed pointer (if applicable).
  */
-int lttng_dynamic_pointer_array_remove_pointer(
-               struct lttng_dynamic_pointer_array *array, size_t index);
+int lttng_dynamic_pointer_array_remove_pointer(struct lttng_dynamic_pointer_array *array,
+                                              size_t index);
 
 /* Release any memory used by the dynamic array. */
-void lttng_dynamic_pointer_array_reset(
-               struct lttng_dynamic_pointer_array *array);
+void lttng_dynamic_pointer_array_reset(struct lttng_dynamic_pointer_array *array);
 
 /* Remove all elements from the dynamic pointer array. */
-void lttng_dynamic_pointer_array_clear(
-               struct lttng_dynamic_pointer_array *array);
+void lttng_dynamic_pointer_array_clear(struct lttng_dynamic_pointer_array *array);
 
 #endif /* LTTNG_DYNAMIC_ARRAY_H */
index a12e1485d02132b77b60d153062c1b06879d21d1..b64e9676ad3e9eb3d01428ce8a9731eb73333feb 100644 (file)
@@ -5,16 +5,15 @@
  *
  */
 
-#include <common/dynamic-buffer.hpp>
 #include <common/buffer-view.hpp>
+#include <common/dynamic-buffer.hpp>
 #include <common/utils.hpp>
 
 /*
  * Round to (upper) power of two, val is returned if it already is a power of
  * two.
  */
-static
-size_t round_to_power_of_2(size_t val)
+static size_t round_to_power_of_2(size_t val)
 {
        size_t rounded;
        const int order = utils_get_count_order_u64(val);
@@ -32,8 +31,7 @@ void lttng_dynamic_buffer_init(struct lttng_dynamic_buffer *buffer)
        memset(buffer, 0, sizeof(*buffer));
 }
 
-int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer,
-               const void *buf, size_t len)
+int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer, const void *buf, size_t len)
 {
        int ret = 0;
 
@@ -49,9 +47,8 @@ int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer,
 
        LTTNG_ASSERT(buffer->_capacity >= buffer->size);
        if (buffer->_capacity < (len + buffer->size)) {
-               ret = lttng_dynamic_buffer_set_capacity(buffer,
-                               buffer->_capacity +
-                               (len - (buffer->_capacity - buffer->size)));
+               ret = lttng_dynamic_buffer_set_capacity(
+                       buffer, buffer->_capacity + (len - (buffer->_capacity - buffer->size)));
                if (ret) {
                        goto end;
                }
@@ -64,7 +61,7 @@ end:
 }
 
 int lttng_dynamic_buffer_append_buffer(struct lttng_dynamic_buffer *dst_buffer,
-               const struct lttng_dynamic_buffer *src_buffer)
+                                      const struct lttng_dynamic_buffer *src_buffer)
 {
        int ret;
 
@@ -73,14 +70,13 @@ int lttng_dynamic_buffer_append_buffer(struct lttng_dynamic_buffer *dst_buffer,
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(dst_buffer, src_buffer->data,
-                       src_buffer->size);
+       ret = lttng_dynamic_buffer_append(dst_buffer, src_buffer->data, src_buffer->size);
 end:
        return ret;
 }
 
 int lttng_dynamic_buffer_append_view(struct lttng_dynamic_buffer *buffer,
-               const struct lttng_buffer_view *src)
+                                    const struct lttng_buffer_view *src)
 {
        int ret;
 
@@ -89,14 +85,12 @@ int lttng_dynamic_buffer_append_view(struct lttng_dynamic_buffer *buffer,
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(buffer, src->data,
-                       src->size);
+       ret = lttng_dynamic_buffer_append(buffer, src->data, src->size);
 end:
        return ret;
 }
 
-int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer *buffer,
-               size_t new_size)
+int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer *buffer, size_t new_size)
 {
        int ret = 0;
 
@@ -134,13 +128,11 @@ end:
        return ret;
 }
 
-int lttng_dynamic_buffer_set_capacity(struct lttng_dynamic_buffer *buffer,
-               size_t demanded_capacity)
+int lttng_dynamic_buffer_set_capacity(struct lttng_dynamic_buffer *buffer, size_t demanded_capacity)
 {
        int ret = 0;
        void *new_buf;
-       size_t new_capacity = demanded_capacity ?
-                       round_to_power_of_2(demanded_capacity) : 0;
+       size_t new_capacity = demanded_capacity ? round_to_power_of_2(demanded_capacity) : 0;
 
        if (!buffer || demanded_capacity < buffer->size) {
                /*
@@ -178,11 +170,10 @@ void lttng_dynamic_buffer_reset(struct lttng_dynamic_buffer *buffer)
        buffer->size = 0;
        buffer->_capacity = 0;
        free(buffer->data);
-       buffer->data = NULL;
+       buffer->data = nullptr;
 }
 
-size_t lttng_dynamic_buffer_get_capacity_left(
-               struct lttng_dynamic_buffer *buffer)
+size_t lttng_dynamic_buffer_get_capacity_left(struct lttng_dynamic_buffer *buffer)
 {
        if (!buffer) {
                return 0;
index 65b15752d5404fec9037e58a0f74f1e329434c5e..228b0c5ea1d29e9852d0b3eaec66865d73bb572a 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef LTTNG_DYNAMIC_BUFFER_H
 #define LTTNG_DYNAMIC_BUFFER_H
 
+#include <common/macros.hpp>
+
 #include <stddef.h>
 #include <stdint.h>
-#include <common/macros.hpp>
 
 struct lttng_buffer_view;
 
@@ -36,8 +37,7 @@ void lttng_dynamic_buffer_init(struct lttng_dynamic_buffer *buffer);
  * (after its current "size"). The dynamic buffer's size is increased by
  * "len", and its capacity is adjusted automatically.
  */
-int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer,
-               const void *buf, size_t len);
+int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer, const void *buf, size_t len);
 
 /*
  * Performs the same action as lttng_dynamic_buffer_append(), but using another
@@ -45,7 +45,7 @@ int lttng_dynamic_buffer_append(struct lttng_dynamic_buffer *buffer,
  * of "len".
  */
 int lttng_dynamic_buffer_append_buffer(struct lttng_dynamic_buffer *dst_buffer,
-               const struct lttng_dynamic_buffer *src_buffer);
+                                      const struct lttng_dynamic_buffer *src_buffer);
 
 /*
  * Performs the same action as lttng_dynamic_buffer_append(), but using a
@@ -53,7 +53,7 @@ int lttng_dynamic_buffer_append_buffer(struct lttng_dynamic_buffer *dst_buffer,
  * of "len".
  */
 int lttng_dynamic_buffer_append_view(struct lttng_dynamic_buffer *buffer,
-               const struct lttng_buffer_view *view);
+                                    const struct lttng_buffer_view *view);
 
 /*
  * Set the buffer's size to new_size. The capacity of the buffer will
@@ -71,8 +71,7 @@ int lttng_dynamic_buffer_append_view(struct lttng_dynamic_buffer *buffer,
  * NOTE: It is striclty _invalid_ to access memory after _size_, regardless
  *       of prior calls to set_capacity().
  */
-int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer *buffer,
-               size_t new_size);
+int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer *buffer, size_t new_size);
 
 /*
  * Set the buffer's capacity to accommodates the new_capacity, allocating memory
@@ -82,14 +81,12 @@ int lttng_dynamic_buffer_set_size(struct lttng_dynamic_buffer *buffer,
  *
  * If the current size > new_capacity, the operation will fail.
  */
-int lttng_dynamic_buffer_set_capacity(struct lttng_dynamic_buffer *buffer,
-               size_t new_capacity);
+int lttng_dynamic_buffer_set_capacity(struct lttng_dynamic_buffer *buffer, size_t new_capacity);
 
 /* Release any memory used by the dynamic buffer. */
 void lttng_dynamic_buffer_reset(struct lttng_dynamic_buffer *buffer);
 
 /* Get the space left in the buffer before a new resize is needed. */
-size_t lttng_dynamic_buffer_get_capacity_left(
-               struct lttng_dynamic_buffer *buffer);
+size_t lttng_dynamic_buffer_get_capacity_left(struct lttng_dynamic_buffer *buffer);
 
 #endif /* LTTNG_DYNAMIC_BUFFER_H */
index 52d3d22d315fabfdcbd711544e869520a4b48b22..8724c156962b1443f7adc2200252fd7db13969df 100644 (file)
@@ -7,18 +7,16 @@
 
 #include <lttng/endpoint-internal.hpp>
 
-static
-struct lttng_endpoint lttng_session_daemon_notification_endpoint_instance = {
+static struct lttng_endpoint lttng_session_daemon_notification_endpoint_instance = {
        .type = LTTNG_ENDPOINT_TYPE_DEFAULT_SESSIOND_NOTIFICATION,
 };
 
-static
-struct lttng_endpoint lttng_session_daemon_command_endpoint_instance = {
+static struct lttng_endpoint lttng_session_daemon_command_endpoint_instance = {
        .type = LTTNG_ENDPOINT_TYPE_DEFAULT_SESSIOND_COMMAND,
 };
 
 struct lttng_endpoint *lttng_session_daemon_notification_endpoint =
-               &lttng_session_daemon_notification_endpoint_instance;
+       &lttng_session_daemon_notification_endpoint_instance;
 
 struct lttng_endpoint *lttng_session_daemon_command_endpoint =
-               &lttng_session_daemon_command_endpoint_instance;
+       &lttng_session_daemon_command_endpoint_instance;
index d3831ae81b86bf6c509c42818119fc937394cde2..2410d9b1c876a2a7aeb2bf0d478755bdc3e22946 100644 (file)
@@ -3,7 +3,7 @@
  *
  * Copyright (C) 2021 Jérémie Galarneau <jeremie.galarneau@efficios.com>
  *
- * SPDX-License-Identifier: GPL-2.1-only
+ * SPDX-License-Identifier: LGPL-2.1-only
  *
  */
 
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/list-internal.hpp>
 #include <lttng/action/path-internal.hpp>
 #include <lttng/error-query-internal.hpp>
 #include <lttng/error-query.h>
 #include <lttng/trigger/trigger-internal.hpp>
+
 #include <stddef.h>
 
 struct lttng_error_query {
@@ -88,21 +90,18 @@ struct lttng_error_query_results_comm {
 } LTTNG_PACKED;
 } /* namespace */
 
-static
-enum lttng_error_code lttng_error_query_result_mi_serialize(
-               const struct lttng_error_query_result *result,
-               struct mi_writer *writer);
+static enum lttng_error_code
+lttng_error_query_result_mi_serialize(const struct lttng_error_query_result *result,
+                                     struct mi_writer *writer);
 
-static
-enum lttng_error_code lttng_error_query_result_counter_mi_serialize(
-               const struct lttng_error_query_result *result,
-               struct mi_writer *writer);
+static enum lttng_error_code
+lttng_error_query_result_counter_mi_serialize(const struct lttng_error_query_result *result,
+                                             struct mi_writer *writer);
 
-struct lttng_error_query *lttng_error_query_trigger_create(
-               const struct lttng_trigger *trigger)
+struct lttng_error_query *lttng_error_query_trigger_create(const struct lttng_trigger *trigger)
 {
-       struct lttng_error_query_trigger *query = NULL;
-       struct lttng_trigger *trigger_copy = NULL;
+       struct lttng_error_query_trigger *query = nullptr;
+       struct lttng_trigger *trigger_copy = nullptr;
 
        if (!trigger) {
                goto end;
@@ -121,19 +120,18 @@ struct lttng_error_query *lttng_error_query_trigger_create(
 
        query->parent.target_type = LTTNG_ERROR_QUERY_TARGET_TYPE_TRIGGER;
        query->trigger = trigger_copy;
-       trigger_copy = NULL;
+       trigger_copy = nullptr;
 
 error:
        lttng_trigger_put(trigger_copy);
 end:
-       return query ? &query->parent : NULL;
+       return query ? &query->parent : nullptr;
 }
 
-struct lttng_error_query *lttng_error_query_condition_create(
-               const struct lttng_trigger *trigger)
+struct lttng_error_query *lttng_error_query_condition_create(const struct lttng_trigger *trigger)
 {
-       struct lttng_error_query_condition *query = NULL;
-       struct lttng_trigger *trigger_copy = NULL;
+       struct lttng_error_query_condition *query = nullptr;
+       struct lttng_trigger *trigger_copy = nullptr;
 
        if (!trigger) {
                goto end;
@@ -152,25 +150,23 @@ struct lttng_error_query *lttng_error_query_condition_create(
 
        query->parent.target_type = LTTNG_ERROR_QUERY_TARGET_TYPE_CONDITION;
        query->trigger = trigger_copy;
-       trigger_copy = NULL;
+       trigger_copy = nullptr;
 
 error:
        lttng_trigger_put(trigger_copy);
 end:
-       return query ? &query->parent : NULL;
+       return query ? &query->parent : nullptr;
 }
 
-static
-struct lttng_action *get_trigger_action_from_path(
-               struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path)
+static struct lttng_action *
+get_trigger_action_from_path(struct lttng_trigger *trigger,
+                            const struct lttng_action_path *action_path)
 {
        size_t index_count, i;
        enum lttng_action_path_status path_status;
-       struct lttng_action *current_action = NULL;
+       struct lttng_action *current_action = nullptr;
 
-       path_status = lttng_action_path_get_index_count(
-                       action_path, &index_count);
+       path_status = lttng_action_path_get_index_count(action_path, &index_count);
        if (path_status != LTTNG_ACTION_PATH_STATUS_OK) {
                goto end;
        }
@@ -179,10 +175,9 @@ struct lttng_action *get_trigger_action_from_path(
        for (i = 0; i < index_count; i++) {
                uint64_t path_index;
 
-               path_status = lttng_action_path_get_index_at_index(
-                               action_path, i, &path_index);
-               current_action = lttng_action_list_borrow_mutable_at_index(
-                               current_action, path_index);
+               path_status = lttng_action_path_get_index_at_index(action_path, i, &path_index);
+               current_action =
+                       lttng_action_list_borrow_mutable_at_index(current_action, path_index);
                if (!current_action) {
                        /* Invalid action path. */
                        goto end;
@@ -193,28 +188,25 @@ end:
        return current_action;
 }
 
-static
-bool is_valid_action_path(const struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path)
+static bool is_valid_action_path(const struct lttng_trigger *trigger,
+                                const struct lttng_action_path *action_path)
 {
        /*
         * While 'trigger's constness is casted-away, the trigger and resulting
         * action are not modified; we merely check for the action's existence.
         */
-       return !!get_trigger_action_from_path(
-                       (struct lttng_trigger *) trigger, action_path);
+       return !!get_trigger_action_from_path((struct lttng_trigger *) trigger, action_path);
 }
 
-struct lttng_error_query *lttng_error_query_action_create(
-               const struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path)
+struct lttng_error_query *
+lttng_error_query_action_create(const struct lttng_trigger *trigger,
+                               const struct lttng_action_path *action_path)
 {
-       struct lttng_error_query_action *query = NULL;
-       struct lttng_trigger *trigger_copy = NULL;
+       struct lttng_error_query_action *query = nullptr;
+       struct lttng_trigger *trigger_copy = nullptr;
        int ret_copy;
 
-       if (!trigger || !action_path ||
-                       !is_valid_action_path(trigger, action_path)) {
+       if (!trigger || !action_path || !is_valid_action_path(trigger, action_path)) {
                goto end;
        }
 
@@ -236,14 +228,14 @@ struct lttng_error_query *lttng_error_query_action_create(
 
        query->parent.target_type = LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION;
        query->trigger = trigger_copy;
-       trigger_copy = NULL;
+       trigger_copy = nullptr;
        goto end;
 
 error:
        lttng_trigger_put(trigger_copy);
-       lttng_error_query_destroy(query ? &query->parent : NULL);
+       lttng_error_query_destroy(query ? &query->parent : nullptr);
 end:
-       return query ? &query->parent : NULL;
+       return query ? &query->parent : nullptr;
 }
 
 void lttng_error_query_destroy(struct lttng_error_query *query)
@@ -256,7 +248,7 @@ void lttng_error_query_destroy(struct lttng_error_query *query)
        case LTTNG_ERROR_QUERY_TARGET_TYPE_TRIGGER:
        {
                struct lttng_error_query_trigger *trigger_query =
-                               lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
+                       lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
 
                lttng_trigger_put(trigger_query->trigger);
                free(trigger_query);
@@ -264,8 +256,8 @@ void lttng_error_query_destroy(struct lttng_error_query *query)
        }
        case LTTNG_ERROR_QUERY_TARGET_TYPE_CONDITION:
        {
-               struct lttng_error_query_condition *condition_query = lttng::utils::container_of(
-                               query, &lttng_error_query_condition::parent);
+               struct lttng_error_query_condition *condition_query =
+                       lttng::utils::container_of(query, &lttng_error_query_condition::parent);
 
                lttng_trigger_put(condition_query->trigger);
                free(condition_query);
@@ -273,8 +265,8 @@ void lttng_error_query_destroy(struct lttng_error_query *query)
        }
        case LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION:
        {
-               struct lttng_error_query_action *action_query = lttng::utils::container_of(
-                               query, &lttng_error_query_action::parent);
+               struct lttng_error_query_action *action_query =
+                       lttng::utils::container_of(query, &lttng_error_query_action::parent);
 
                lttng_trigger_put(action_query->trigger);
                lttng_action_path_destroy(action_query->action_path);
@@ -286,29 +278,25 @@ void lttng_error_query_destroy(struct lttng_error_query *query)
        }
 }
 
-static
-int lttng_error_query_result_counter_serialize(
-               const struct lttng_error_query_result *result,
-               struct lttng_payload *payload)
+static int lttng_error_query_result_counter_serialize(const struct lttng_error_query_result *result,
+                                                     struct lttng_payload *payload)
 {
        const struct lttng_error_query_result_counter *counter_result;
 
        LTTNG_ASSERT(result->type == LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER);
-       counter_result = lttng::utils::container_of(
-                       result, &lttng_error_query_result_counter::parent);
+       counter_result =
+               lttng::utils::container_of(result, &lttng_error_query_result_counter::parent);
 
        lttng_error_query_result_counter_comm comm = {
                .value = counter_result->value,
        };
 
-       return lttng_dynamic_buffer_append(&payload->buffer,
-                       &comm,
-                       sizeof(struct lttng_error_query_result_counter_comm));
+       return lttng_dynamic_buffer_append(
+               &payload->buffer, &comm, sizeof(struct lttng_error_query_result_counter_comm));
 }
 
-int lttng_error_query_result_serialize(
-               const struct lttng_error_query_result *result,
-               struct lttng_payload *payload)
+int lttng_error_query_result_serialize(const struct lttng_error_query_result *result,
+                                      struct lttng_payload *payload)
 {
        int ret;
        struct lttng_error_query_result_comm header;
@@ -318,24 +306,22 @@ int lttng_error_query_result_serialize(
        header.description_len = (typeof(header.name_len)) strlen(result->description) + 1;
 
        /* Header. */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &header, sizeof(header));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &header, sizeof(header));
        if (ret) {
                ERR("Failed to append error query result communication header to payload");
                goto end;
        }
 
        /* Name. */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, result->name, header.name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, result->name, header.name_len);
        if (ret) {
                ERR("Failed to append error query result name to payload");
                goto end;
        }
 
        /* Description. */
-       ret = lttng_dynamic_buffer_append(&payload->buffer, result->description,
-                       header.description_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, result->description, header.description_len);
        if (ret) {
                ERR("Failed to append error query result description to payload");
                goto end;
@@ -344,8 +330,7 @@ int lttng_error_query_result_serialize(
        /* Type-specific payload. */
        switch (result->type) {
        case LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER:
-               ret = lttng_error_query_result_counter_serialize(
-                               result, payload);
+               ret = lttng_error_query_result_counter_serialize(result, payload);
                if (ret) {
                        ERR("Failed to serialize counter error query result");
                        goto end;
@@ -359,12 +344,10 @@ end:
        return ret;
 }
 
-static
-int lttng_error_query_result_init(
-               struct lttng_error_query_result *result,
-               enum lttng_error_query_result_type result_type,
-               const char *name,
-               const char *description)
+static int lttng_error_query_result_init(struct lttng_error_query_result *result,
+                                        enum lttng_error_query_result_type result_type,
+                                        const char *name,
+                                        const char *description)
 {
        int ret;
 
@@ -412,8 +395,7 @@ void lttng_error_query_result_destroy(struct lttng_error_query_result *counter)
 }
 
 struct lttng_error_query_result *
-lttng_error_query_result_counter_create(
-               const char *name, const char *description, uint64_t value)
+lttng_error_query_result_counter_create(const char *name, const char *description, uint64_t value)
 {
        int init_ret;
        struct lttng_error_query_result_counter *counter;
@@ -424,9 +406,8 @@ lttng_error_query_result_counter_create(
                goto end;
        }
 
-       init_ret = lttng_error_query_result_init(&counter->parent,
-                       LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER, name,
-                       description);
+       init_ret = lttng_error_query_result_init(
+               &counter->parent, LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER, name, description);
        if (init_ret) {
                goto error;
        }
@@ -436,18 +417,17 @@ lttng_error_query_result_counter_create(
 error:
        lttng_error_query_result_destroy(&counter->parent);
 end:
-       return counter ? &counter->parent : NULL;
+       return counter ? &counter->parent : nullptr;
 }
 
-static
-void destroy_result(void *ptr)
+static void destroy_result(void *ptr)
 {
        struct lttng_error_query_result *result = (typeof(result)) ptr;
 
        lttng_error_query_result_destroy(result);
 }
 
-struct lttng_error_query_results *lttng_error_query_results_create(void)
+struct lttng_error_query_results *lttng_error_query_results_create()
 {
        struct lttng_error_query_results *set = zmalloc<lttng_error_query_results>();
 
@@ -461,22 +441,19 @@ end:
        return set;
 }
 
-int lttng_error_query_results_add_result(
-               struct lttng_error_query_results *results,
-               struct lttng_error_query_result *result)
+int lttng_error_query_results_add_result(struct lttng_error_query_results *results,
+                                        struct lttng_error_query_result *result)
 {
-       return lttng_dynamic_pointer_array_add_pointer(
-                       &results->results, result);
+       return lttng_dynamic_pointer_array_add_pointer(&results->results, result);
 }
 
-ssize_t lttng_error_query_result_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_error_query_result **result)
+ssize_t lttng_error_query_result_create_from_payload(struct lttng_payload_view *view,
+                                                    struct lttng_error_query_result **result)
 {
        ssize_t used_size = 0;
        struct lttng_error_query_result_comm *header;
        struct lttng_payload_view header_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*header));
+               lttng_payload_view_from_view(view, 0, sizeof(*header));
        const char *name;
        const char *description;
 
@@ -490,14 +467,11 @@ ssize_t lttng_error_query_result_create_from_payload(
 
        {
                struct lttng_payload_view name_view =
-                               lttng_payload_view_from_view(view, used_size,
-                                               header->name_len);
+                       lttng_payload_view_from_view(view, used_size, header->name_len);
 
                if (!lttng_payload_view_is_valid(&name_view) ||
-                               !lttng_buffer_view_contains_string(
-                                               &name_view.buffer,
-                                               name_view.buffer.data,
-                                               header->name_len)) {
+                   !lttng_buffer_view_contains_string(
+                           &name_view.buffer, name_view.buffer.data, header->name_len)) {
                        used_size = -1;
                        goto end;
                }
@@ -508,14 +482,12 @@ ssize_t lttng_error_query_result_create_from_payload(
 
        {
                struct lttng_payload_view description_view =
-                               lttng_payload_view_from_view(view, used_size,
-                                               header->description_len);
+                       lttng_payload_view_from_view(view, used_size, header->description_len);
 
                if (!lttng_payload_view_is_valid(&description_view) ||
-                               !lttng_buffer_view_contains_string(
-                                               &description_view.buffer,
-                                               description_view.buffer.data,
-                                               header->description_len)) {
+                   !lttng_buffer_view_contains_string(&description_view.buffer,
+                                                      description_view.buffer.data,
+                                                      header->description_len)) {
                        used_size = -1;
                        goto end;
                }
@@ -529,8 +501,7 @@ ssize_t lttng_error_query_result_create_from_payload(
        {
                struct lttng_error_query_result_counter_comm *counter;
                struct lttng_payload_view counter_payload_view =
-                               lttng_payload_view_from_view(view, used_size,
-                                               sizeof(*counter));
+                       lttng_payload_view_from_view(view, used_size, sizeof(*counter));
 
                if (!lttng_payload_view_is_valid(&counter_payload_view)) {
                        used_size = -1;
@@ -538,8 +509,8 @@ ssize_t lttng_error_query_result_create_from_payload(
                }
 
                counter = (typeof(counter)) counter_payload_view.buffer.data;
-               *result = lttng_error_query_result_counter_create(
-                               name, description, counter->value);
+               *result =
+                       lttng_error_query_result_counter_create(name, description, counter->value);
                if (!*result) {
                        used_size = -1;
                        goto end;
@@ -557,14 +528,12 @@ end:
        return used_size;
 }
 
-int lttng_error_query_results_serialize(
-               const struct lttng_error_query_results *results,
-               struct lttng_payload *payload)
+int lttng_error_query_results_serialize(const struct lttng_error_query_results *results,
+                                       struct lttng_payload *payload)
 {
        int ret;
        size_t result_index;
-       const size_t result_count = lttng_dynamic_pointer_array_get_count(
-                       &results->results);
+       const size_t result_count = lttng_dynamic_pointer_array_get_count(&results->results);
        struct lttng_error_query_results_comm header;
 
        header.count = (decltype(header.count)) result_count;
@@ -578,10 +547,9 @@ int lttng_error_query_results_serialize(
 
        /* Results. */
        for (result_index = 0; result_index < result_count; result_index++) {
-               const struct lttng_error_query_result *result = (typeof(result))
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               &results->results,
-                                               result_index);
+               const struct lttng_error_query_result *result =
+                       (typeof(result)) lttng_dynamic_pointer_array_get_pointer(&results->results,
+                                                                                result_index);
 
                ret = lttng_error_query_result_serialize(result, payload);
                if (ret) {
@@ -593,16 +561,15 @@ end:
        return ret;
 }
 
-ssize_t lttng_error_query_results_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_error_query_results **_results)
+ssize_t lttng_error_query_results_create_from_payload(struct lttng_payload_view *view,
+                                                     struct lttng_error_query_results **_results)
 {
        size_t result_index;
        ssize_t total_used_size = 0;
        struct lttng_error_query_results_comm *header;
        struct lttng_payload_view header_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*header));
-       struct lttng_error_query_results *results = NULL;
+               lttng_payload_view_from_view(view, 0, sizeof(*header));
+       struct lttng_error_query_results *results = nullptr;
 
        if (!lttng_payload_view_is_valid(&header_view)) {
                ERR("Failed to map view to error query result set header");
@@ -622,16 +589,14 @@ ssize_t lttng_error_query_results_create_from_payload(
                ssize_t used_size;
                struct lttng_error_query_result *result;
                struct lttng_payload_view result_view =
-                               lttng_payload_view_from_view(
-                                               view, total_used_size, -1);
+                       lttng_payload_view_from_view(view, total_used_size, -1);
 
                if (!lttng_payload_view_is_valid(&result_view)) {
                        total_used_size = -1;
                        goto end;
                }
 
-               used_size = lttng_error_query_result_create_from_payload(
-                               &result_view, &result);
+               used_size = lttng_error_query_result_create_from_payload(&result_view, &result);
                if (used_size < 0) {
                        total_used_size = -1;
                        goto end;
@@ -639,8 +604,7 @@ ssize_t lttng_error_query_results_create_from_payload(
 
                total_used_size += used_size;
 
-               if (lttng_dynamic_pointer_array_add_pointer(
-                                   &results->results, result)) {
+               if (lttng_dynamic_pointer_array_add_pointer(&results->results, result)) {
                        lttng_error_query_result_destroy(result);
                        total_used_size = -1;
                        goto end;
@@ -648,19 +612,18 @@ ssize_t lttng_error_query_results_create_from_payload(
        }
 
        *_results = results;
-       results = NULL;
+       results = nullptr;
 end:
        lttng_error_query_results_destroy(results);
        return total_used_size;
 }
 
-static
-int lttng_error_query_trigger_serialize(const struct lttng_error_query *query,
-               struct lttng_payload *payload)
+static int lttng_error_query_trigger_serialize(const struct lttng_error_query *query,
+                                              struct lttng_payload *payload)
 {
        int ret;
        const struct lttng_error_query_trigger *query_trigger =
-                       lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
+               lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
 
        if (!lttng_trigger_validate(query_trigger->trigger)) {
                ret = -1;
@@ -676,13 +639,12 @@ end:
        return ret;
 }
 
-static
-int lttng_error_query_condition_serialize(const struct lttng_error_query *query,
-               struct lttng_payload *payload)
+static int lttng_error_query_condition_serialize(const struct lttng_error_query *query,
+                                                struct lttng_payload *payload)
 {
        int ret;
        const struct lttng_error_query_condition *query_trigger =
-                       lttng::utils::container_of(query, &lttng_error_query_condition::parent);
+               lttng::utils::container_of(query, &lttng_error_query_condition::parent);
 
        if (!lttng_trigger_validate(query_trigger->trigger)) {
                ret = -1;
@@ -698,13 +660,12 @@ end:
        return ret;
 }
 
-static
-int lttng_error_query_action_serialize(const struct lttng_error_query *query,
-               struct lttng_payload *payload)
+static int lttng_error_query_action_serialize(const struct lttng_error_query *query,
+                                             struct lttng_payload *payload)
 {
        int ret;
        const struct lttng_error_query_action *query_action =
-                       lttng::utils::container_of(query, &lttng_error_query_action::parent);
+               lttng::utils::container_of(query, &lttng_error_query_action::parent);
 
        if (!lttng_trigger_validate(query_action->trigger)) {
                ret = -1;
@@ -725,59 +686,58 @@ end:
        return ret;
 }
 
-enum lttng_error_query_target_type lttng_error_query_get_target_type(
-               const struct lttng_error_query *query)
+enum lttng_error_query_target_type
+lttng_error_query_get_target_type(const struct lttng_error_query *query)
 {
        return query->target_type;
 }
 
-const struct lttng_trigger *lttng_error_query_trigger_borrow_target(
-               const struct lttng_error_query *query)
+const struct lttng_trigger *
+lttng_error_query_trigger_borrow_target(const struct lttng_error_query *query)
 {
        const struct lttng_error_query_trigger *query_trigger =
-                       lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
+               lttng::utils::container_of(query, &lttng_error_query_trigger::parent);
 
        return query_trigger->trigger;
 }
 
-const struct lttng_trigger *lttng_error_query_condition_borrow_target(
-               const struct lttng_error_query *query)
+const struct lttng_trigger *
+lttng_error_query_condition_borrow_target(const struct lttng_error_query *query)
 {
        const struct lttng_error_query_condition *query_trigger =
-                       lttng::utils::container_of(query, &lttng_error_query_condition::parent);
+               lttng::utils::container_of(query, &lttng_error_query_condition::parent);
 
        return query_trigger->trigger;
 }
 
-const struct lttng_trigger *lttng_error_query_action_borrow_trigger_target(
-               const struct lttng_error_query *query)
+const struct lttng_trigger *
+lttng_error_query_action_borrow_trigger_target(const struct lttng_error_query *query)
 {
        const struct lttng_error_query_action *query_action =
-                       lttng::utils::container_of(query, &lttng_error_query_action::parent);
+               lttng::utils::container_of(query, &lttng_error_query_action::parent);
 
        return query_action->trigger;
 }
 
-struct lttng_action *lttng_error_query_action_borrow_action_target(
-               const struct lttng_error_query *query, struct lttng_trigger *trigger)
+struct lttng_action *
+lttng_error_query_action_borrow_action_target(const struct lttng_error_query *query,
+                                             struct lttng_trigger *trigger)
 {
        const struct lttng_error_query_action *query_action =
-                       lttng::utils::container_of(query, &lttng_error_query_action::parent);
+               lttng::utils::container_of(query, &lttng_error_query_action::parent);
 
-       return get_trigger_action_from_path(
-                       trigger, query_action->action_path);
+       return get_trigger_action_from_path(trigger, query_action->action_path);
 }
 
 int lttng_error_query_serialize(const struct lttng_error_query *query,
-               struct lttng_payload *payload)
+                               struct lttng_payload *payload)
 {
        int ret;
        struct lttng_error_query_comm header;
 
        header.target_type = (decltype(header.target_type)) query->target_type;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &header, sizeof(header));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &header, sizeof(header));
        if (ret) {
                ERR("Failed to append error query header to payload");
                goto end;
@@ -813,13 +773,13 @@ end:
 }
 
 ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_error_query **query)
+                                             struct lttng_error_query **query)
 {
        ssize_t used_size = 0;
        struct lttng_error_query_comm *header;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_trigger *trigger = nullptr;
        struct lttng_payload_view header_view =
-                       lttng_payload_view_from_view(view, 0, sizeof(*header));
+               lttng_payload_view_from_view(view, 0, sizeof(*header));
 
        if (!lttng_payload_view_is_valid(&header_view)) {
                ERR("Failed to map error query header");
@@ -835,16 +795,14 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
        {
                ssize_t trigger_used_size;
                struct lttng_payload_view trigger_view =
-                               lttng_payload_view_from_view(
-                                               view, used_size, -1);
+                       lttng_payload_view_from_view(view, used_size, -1);
 
                if (!lttng_payload_view_is_valid(&trigger_view)) {
                        used_size = -1;
                        goto end;
                }
 
-               trigger_used_size = lttng_trigger_create_from_payload(
-                               &trigger_view, &trigger);
+               trigger_used_size = lttng_trigger_create_from_payload(&trigger_view, &trigger);
                if (trigger_used_size < 0) {
                        used_size = -1;
                        goto end;
@@ -864,16 +822,14 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
        {
                ssize_t trigger_used_size;
                struct lttng_payload_view trigger_view =
-                               lttng_payload_view_from_view(
-                                               view, used_size, -1);
+                       lttng_payload_view_from_view(view, used_size, -1);
 
                if (!lttng_payload_view_is_valid(&trigger_view)) {
                        used_size = -1;
                        goto end;
                }
 
-               trigger_used_size = lttng_trigger_create_from_payload(
-                               &trigger_view, &trigger);
+               trigger_used_size = lttng_trigger_create_from_payload(&trigger_view, &trigger);
                if (trigger_used_size < 0) {
                        used_size = -1;
                        goto end;
@@ -891,21 +847,20 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
        }
        case LTTNG_ERROR_QUERY_TARGET_TYPE_ACTION:
        {
-               struct lttng_action_path *action_path = NULL;
+               struct lttng_action_path *action_path = nullptr;
 
                {
                        ssize_t trigger_used_size;
                        struct lttng_payload_view trigger_view =
-                                       lttng_payload_view_from_view(
-                                                       view, used_size, -1);
+                               lttng_payload_view_from_view(view, used_size, -1);
 
                        if (!lttng_payload_view_is_valid(&trigger_view)) {
                                used_size = -1;
                                goto end;
                        }
 
-                       trigger_used_size = lttng_trigger_create_from_payload(
-                                       &trigger_view, &trigger);
+                       trigger_used_size =
+                               lttng_trigger_create_from_payload(&trigger_view, &trigger);
                        if (trigger_used_size < 0) {
                                used_size = -1;
                                goto end;
@@ -917,8 +872,7 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
                {
                        ssize_t action_path_used_size;
                        struct lttng_payload_view action_path_view =
-                                       lttng_payload_view_from_view(
-                                                       view, used_size, -1);
+                               lttng_payload_view_from_view(view, used_size, -1);
 
                        if (!lttng_payload_view_is_valid(&action_path_view)) {
                                used_size = -1;
@@ -926,7 +880,7 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
                        }
 
                        action_path_used_size = lttng_action_path_create_from_payload(
-                                       &action_path_view, &action_path);
+                               &action_path_view, &action_path);
                        if (action_path_used_size < 0) {
                                used_size = -1;
                                goto end;
@@ -935,8 +889,7 @@ ssize_t lttng_error_query_create_from_payload(struct lttng_payload_view *view,
                        used_size += action_path_used_size;
                }
 
-               *query = lttng_error_query_action_create(
-                               trigger, action_path);
+               *query = lttng_error_query_action_create(trigger, action_path);
                lttng_action_path_destroy(action_path);
                if (!*query) {
                        used_size = -1;
@@ -955,9 +908,9 @@ end:
        return used_size;
 }
 
-enum lttng_error_query_results_status lttng_error_query_results_get_count(
-               const struct lttng_error_query_results *results,
-               unsigned int *count)
+enum lttng_error_query_results_status
+lttng_error_query_results_get_count(const struct lttng_error_query_results *results,
+                                   unsigned int *count)
 {
        enum lttng_error_query_results_status status;
 
@@ -973,10 +926,9 @@ end:
 }
 
 enum lttng_error_query_results_status
-lttng_error_query_results_get_result(
-               const struct lttng_error_query_results *results,
-               const struct lttng_error_query_result **result,
-               unsigned int index)
+lttng_error_query_results_get_result(const struct lttng_error_query_results *results,
+                                    const struct lttng_error_query_result **result,
+                                    unsigned int index)
 {
        unsigned int result_count;
        enum lttng_error_query_results_status status;
@@ -996,16 +948,15 @@ lttng_error_query_results_get_result(
                goto end;
        }
 
-       *result = (typeof(*result)) lttng_dynamic_pointer_array_get_pointer(
-                       &results->results, index);
+       *result =
+               (typeof(*result)) lttng_dynamic_pointer_array_get_pointer(&results->results, index);
        LTTNG_ASSERT(*result);
        status = LTTNG_ERROR_QUERY_RESULTS_STATUS_OK;
 end:
        return status;
 }
 
-void lttng_error_query_results_destroy(
-               struct lttng_error_query_results *results)
+void lttng_error_query_results_destroy(struct lttng_error_query_results *results)
 {
        if (!results) {
                return;
@@ -1021,9 +972,8 @@ lttng_error_query_result_get_type(const struct lttng_error_query_result *result)
        return result ? result->type : LTTNG_ERROR_QUERY_RESULT_TYPE_UNKNOWN;
 }
 
-enum lttng_error_query_result_status lttng_error_query_result_get_name(
-               const struct lttng_error_query_result *result,
-               const char **name)
+enum lttng_error_query_result_status
+lttng_error_query_result_get_name(const struct lttng_error_query_result *result, const char **name)
 {
        enum lttng_error_query_result_status status;
 
@@ -1038,9 +988,9 @@ end:
        return status;
 }
 
-enum lttng_error_query_result_status lttng_error_query_result_get_description(
-               const struct lttng_error_query_result *result,
-               const char **description)
+enum lttng_error_query_result_status
+lttng_error_query_result_get_description(const struct lttng_error_query_result *result,
+                                        const char **description)
 {
        enum lttng_error_query_result_status status;
 
@@ -1055,21 +1005,20 @@ end:
        return status;
 }
 
-enum lttng_error_query_result_status lttng_error_query_result_counter_get_value(
-               const struct lttng_error_query_result *result,
-               uint64_t *value)
+enum lttng_error_query_result_status
+lttng_error_query_result_counter_get_value(const struct lttng_error_query_result *result,
+                                          uint64_t *value)
 {
        enum lttng_error_query_result_status status;
        const struct lttng_error_query_result_counter *counter_result;
 
-       if (!result || !value ||
-                       result->type != LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER) {
+       if (!result || !value || result->type != LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER) {
                status = LTTNG_ERROR_QUERY_RESULT_STATUS_INVALID_PARAMETER;
                goto end;
        }
 
-       counter_result = lttng::utils::container_of(
-                       result, &lttng_error_query_result_counter::parent);
+       counter_result =
+               lttng::utils::container_of(result, &lttng_error_query_result_counter::parent);
 
        *value = counter_result->value;
        status = LTTNG_ERROR_QUERY_RESULT_STATUS_OK;
@@ -1077,10 +1026,9 @@ end:
        return status;
 }
 
-static
-enum lttng_error_code lttng_error_query_result_counter_mi_serialize(
-               const struct lttng_error_query_result *result,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_error_query_result_counter_mi_serialize(const struct lttng_error_query_result *result,
+                                             struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -1094,16 +1042,14 @@ enum lttng_error_code lttng_error_query_result_counter_mi_serialize(
        LTTNG_ASSERT(status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
 
        /* Open error query result counter element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_error_query_result_counter);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_error_query_result_counter);
        if (ret) {
                goto mi_error;
        }
 
        /* Value. */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_error_query_result_counter_value,
-                       value);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_error_query_result_counter_value, value);
        if (ret) {
                goto mi_error;
        }
@@ -1123,17 +1069,16 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code lttng_error_query_result_mi_serialize(
-               const struct lttng_error_query_result *result,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_error_query_result_mi_serialize(const struct lttng_error_query_result *result,
+                                     struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_error_query_result_status result_status;
        enum lttng_error_query_result_type type;
-       const char *name = NULL;
-       const char *description = NULL;
+       const char *name = nullptr;
+       const char *description = nullptr;
 
        LTTNG_ASSERT(result);
        LTTNG_ASSERT(writer);
@@ -1143,28 +1088,25 @@ enum lttng_error_code lttng_error_query_result_mi_serialize(
        result_status = lttng_error_query_result_get_name(result, &name);
        LTTNG_ASSERT(result_status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
 
-       result_status = lttng_error_query_result_get_description(
-                       result, &description);
+       result_status = lttng_error_query_result_get_description(result, &description);
        LTTNG_ASSERT(result_status == LTTNG_ERROR_QUERY_RESULT_STATUS_OK);
 
        /* Open error query result element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_error_query_result);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_error_query_result);
        if (ret) {
                goto mi_error;
        }
 
        /* Name. */
        ret = mi_lttng_writer_write_element_string(
-                       writer, mi_lttng_element_error_query_result_name, name);
+               writer, mi_lttng_element_error_query_result_name, name);
        if (ret) {
                goto mi_error;
        }
 
        /* Description. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_error_query_result_description,
-                       description);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_error_query_result_description, description);
        if (ret) {
                goto mi_error;
        }
@@ -1172,8 +1114,7 @@ enum lttng_error_code lttng_error_query_result_mi_serialize(
        /* Serialize the result according to its sub type. */
        switch (type) {
        case LTTNG_ERROR_QUERY_RESULT_TYPE_COUNTER:
-               ret_code = lttng_error_query_result_counter_mi_serialize(
-                               result, writer);
+               ret_code = lttng_error_query_result_counter_mi_serialize(result, writer);
                break;
        default:
                abort();
@@ -1198,9 +1139,9 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code lttng_error_query_results_mi_serialize(
-               const struct lttng_error_query_results *results,
-               struct mi_writer *writer)
+enum lttng_error_code
+lttng_error_query_results_mi_serialize(const struct lttng_error_query_results *results,
+                                      struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -1211,8 +1152,7 @@ enum lttng_error_code lttng_error_query_results_mi_serialize(
        LTTNG_ASSERT(writer);
 
        /* Open error query results element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_error_query_results);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_error_query_results);
        if (ret) {
                goto mi_error;
        }
@@ -1223,8 +1163,7 @@ enum lttng_error_code lttng_error_query_results_mi_serialize(
        for (i = 0; i < count; i++) {
                const struct lttng_error_query_result *result;
 
-               results_status = lttng_error_query_results_get_result(
-                               results, &result, i);
+               results_status = lttng_error_query_results_get_result(results, &result, i);
                LTTNG_ASSERT(results_status == LTTNG_ERROR_QUERY_RESULTS_STATUS_OK);
 
                /* A single error query result. */
index 150d2e53fbfe75ef02517a766356eea7db809f7d..32704548c655dd379f8eec7970c352472aa4dcbd 100644 (file)
@@ -6,30 +6,35 @@
  */
 
 #define _LGPL_SOURCE
-#include <inttypes.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
+#include "error.hpp"
 
 #include <common/common.hpp>
-#include <common/thread.hpp>
 #include <common/compat/errno.hpp>
 #include <common/compat/getenv.hpp>
+#include <common/thread.hpp>
+
 #include <lttng/lttng-error.h>
 
-#include "error.hpp"
+#include <inttypes.h>
+#include <iostream>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
 
+namespace {
 /*
  * lttng_opt_abort_on_error: unset: -1, disabled: 0, enabled: 1.
  * Controlled by the LTTNG_ABORT_ON_ERROR environment variable.
  */
-static int lttng_opt_abort_on_error = -1;
+int lttng_opt_abort_on_error = -1;
 
 /* TLS variable that contains the time of one single log entry. */
-DEFINE_URCU_TLS(struct log_time, error_log_time);
-DEFINE_URCU_TLS(const char *, logger_thread_name);
+thread_local struct log_time error_log_time;
+} /* namespace */
+
+thread_local const char *logger_thread_name;
 
-const char *log_add_time(void)
+const char *log_add_time()
 {
        int ret;
        struct tm tm, *res;
@@ -49,15 +54,19 @@ const char *log_add_time(void)
        }
 
        /* Format time in the TLS variable. */
-       ret = snprintf(URCU_TLS(error_log_time).str, sizeof(URCU_TLS(error_log_time).str),
-                       "%02d:%02d:%02d.%09ld",
-                       tm.tm_hour, tm.tm_min, tm.tm_sec, tp.tv_nsec);
+       ret = snprintf(error_log_time.str,
+                      sizeof(error_log_time.str),
+                      "%02d:%02d:%02d.%09ld",
+                      tm.tm_hour,
+                      tm.tm_min,
+                      tm.tm_sec,
+                      tp.tv_nsec);
        if (ret < 0) {
                goto error;
        }
 
        errno = errsv;
-       return URCU_TLS(error_log_time).str;
+       return error_log_time.str;
 
 error:
        /* Return an empty string on error so logging is not affected. */
@@ -70,7 +79,7 @@ void logger_set_thread_name(const char *name, bool set_pthread_name)
        int ret;
 
        LTTNG_ASSERT(name);
-       URCU_TLS(logger_thread_name) = name;
+       logger_thread_name = name;
 
        if (set_pthread_name) {
                ret = lttng_thread_setname(name);
@@ -84,8 +93,7 @@ void logger_set_thread_name(const char *name, bool set_pthread_name)
 /*
  * Human readable error message.
  */
-static
-const char *lttng_error_code_str(lttng_error_code code)
+static const char *lttng_error_code_str(lttng_error_code code)
 {
        switch (code) {
        case LTTNG_OK:
@@ -107,7 +115,7 @@ const char *lttng_error_code_str(lttng_error_code code)
        case LTTNG_ERR_FATAL:
                return "Fatal error of the session daemon";
        case LTTNG_ERR_SELECT_SESS:
-               return "A session MUST be selected";
+               return "A session must be selected";
        case LTTNG_ERR_EXIST_SESS:
                return "Session name already exists";
        case LTTNG_ERR_NO_EVENT:
@@ -153,45 +161,45 @@ const char *lttng_error_code_str(lttng_error_code code)
        case LTTNG_ERR_KERN_LIST_FAIL:
                return "Listing kernel events failed";
        case LTTNG_ERR_UST_CALIBRATE_FAIL:
-               return "UST calibration failed";
+               return "User space tracer calibration failed";
        case LTTNG_ERR_UST_SESS_FAIL:
-               return "UST create session failed";
+               return "User space tracer session creation failed";
        case LTTNG_ERR_UST_CHAN_FAIL:
-               return "UST create channel failed";
+               return "User space tracer channel creation failed";
        case LTTNG_ERR_UST_CHAN_EXIST:
-               return "UST channel already exist";
+               return "User space tracer channel already exist";
        case LTTNG_ERR_UST_CHAN_NOT_FOUND:
-               return "UST channel not found";
+               return "User space tracer channel not found";
        case LTTNG_ERR_UST_CHAN_DISABLE_FAIL:
-               return "Disable UST channel failed";
+               return "Disabling user space tracer channel failed";
        case LTTNG_ERR_UST_CHAN_ENABLE_FAIL:
-               return "Enable UST channel failed";
+               return "Enabling user space tracer channel failed";
        case LTTNG_ERR_UST_ENABLE_FAIL:
-               return "Enable UST event failed";
+               return "Enabling user space event failed";
        case LTTNG_ERR_UST_DISABLE_FAIL:
-               return "Disable UST event failed";
+               return "Disabling user space event failed";
        case LTTNG_ERR_UST_META_FAIL:
                return "Opening metadata failed";
        case LTTNG_ERR_UST_START_FAIL:
-               return "Starting UST trace failed";
+               return "Starting user space tracer session failed";
        case LTTNG_ERR_UST_STOP_FAIL:
-               return "Stopping UST trace failed";
+               return "Stopping user space tracer session trace failed";
        case LTTNG_ERR_UST_CONSUMER64_FAIL:
-               return "64-bit UST consumer start failed";
+               return "64-bit user space trace consumer start failed";
        case LTTNG_ERR_UST_CONSUMER32_FAIL:
-               return "32-bit UST consumer start failed";
+               return "32-bit user space trace consumer start failed";
        case LTTNG_ERR_UST_STREAM_FAIL:
-               return "UST create stream failed";
+               return "User space tracer stream creation failed";
        case LTTNG_ERR_UST_LIST_FAIL:
-               return "Listing UST events failed";
+               return "Listing of user space tracer events failed";
        case LTTNG_ERR_UST_EVENT_EXIST:
-               return "UST event already exist";
+               return "User space event already exist";
        case LTTNG_ERR_UST_EVENT_NOT_FOUND:
-               return "UST event not found";
+               return "User space event not found";
        case LTTNG_ERR_UST_CONTEXT_EXIST:
-               return "UST context already exist";
+               return "User space tracing context already exists";
        case LTTNG_ERR_UST_CONTEXT_INVAL:
-               return "UST invalid context";
+               return "Invalid user space tracing context";
        case LTTNG_ERR_NEED_ROOT_SESSIOND:
                return "Tracing the kernel requires a root lttng-sessiond daemon, as well as \"tracing\" group membership or root user ID for the lttng client";
        case LTTNG_ERR_NO_UST:
@@ -241,7 +249,7 @@ const char *lttng_error_code_str(lttng_error_code code)
        case LTTNG_ERR_NOT_SUPPORTED:
                return "Operation not supported";
        case LTTNG_ERR_UST_EVENT_ENABLED:
-               return "UST event already enabled";
+               return "User space event rule already enabled";
        case LTTNG_ERR_SET_URL:
                return "Error setting URL";
        case LTTNG_ERR_URL_EXIST:
@@ -445,3 +453,12 @@ void lttng_abort_on_error(void)
                abort();
        }
 }
+
+[[noreturn]] void
+lttng::logging::details::die_formatting_exception(const char *format,
+                                                 const std::exception& formatting_exception)
+{
+       std::cerr << "Error occurred while formatting logging message: msg=`" << format
+                 << "`: " << formatting_exception.what();
+       abort();
+}
index fdae1e72c293bb0aefc16b008621dfb772993033..23d840c2daafcd3870ba4445708921c1ea3b93ad 100644 (file)
@@ -9,22 +9,25 @@
 #define _ERROR_H
 
 #include <common/compat/errno.hpp>
-#include <stdio.h>
+#include <common/compat/time.hpp>
+#include <common/format.hpp>
+#include <common/macros.hpp>
+#include <common/string-utils/format.hpp>
+
+#include <stdbool.h>
 #include <stdint.h>
+#include <stdio.h>
 #include <string.h>
-#include <stdbool.h>
 #include <urcu/tls-compat.h>
-#include <common/compat/time.hpp>
-#include <common/string-utils/format.hpp>
-#include <common/macros.hpp>
 
 #ifndef _GNU_SOURCE
 #error "lttng-tools error.h needs _GNU_SOURCE"
 #endif
 
-#include <lttng/lttng-error.h>
 #include <common/compat/tid.hpp>
 
+#include <lttng/lttng-error.h>
+
 /* Avoid conflict with Solaris <sys/regset.h> */
 #if defined(ERR) && defined(__sun__)
 #undef ERR
@@ -32,7 +35,7 @@
 
 /* Stringify the expansion of a define */
 #define XSTR(d) STR(d)
-#define STR(s) #s
+#define STR(s) #s
 
 /*
  * Contains the string of the log entry time. This is used as a thread local
@@ -43,8 +46,8 @@ struct log_time {
        /* Format: 00:00:00.000000000 plus NULL byte. */
        char str[19];
 };
-extern LTTNG_EXPORT  DECLARE_URCU_TLS(struct log_time, error_log_time);
-extern DECLARE_URCU_TLS(const char *, logger_thread_name);
+
+extern thread_local const char *logger_thread_name;
 
 extern int lttng_opt_quiet;
 extern int lttng_opt_verbose;
@@ -52,13 +55,13 @@ extern int lttng_opt_mi;
 
 /* Error type. */
 enum lttng_error_level {
-       PRINT_ERR =     0,
-       PRINT_BUG =     1,
-       PRINT_WARN =    2,
-       PRINT_MSG =     3,
-       PRINT_DBG =     4,
-       PRINT_DBG2 =    5,
-       PRINT_DBG3 =    6,
+       PRINT_ERR = 0,
+       PRINT_BUG = 1,
+       PRINT_WARN = 2,
+       PRINT_MSG = 3,
+       PRINT_DBG = 4,
+       PRINT_DBG2 = 5,
+       PRINT_DBG3 = 6,
 };
 
 static inline bool __lttng_print_check_opt(enum lttng_error_level type)
@@ -133,101 +136,99 @@ static inline void __lttng_print_check_abort(enum lttng_error_level type)
  * want any nested msg to show up when printing mi to stdout(if it's the case).
  * All warnings and errors should be printed to stderr as normal.
  */
-#define __lttng_print(type, fmt, args...)                                              \
-       do {                                                                            \
-               if (__lttng_print_check_opt(type)) {                                    \
-                       fprintf((type) == PRINT_MSG ? stdout : stderr, fmt, ## args);   \
-               }                                                                       \
-               __lttng_print_check_abort(type);                                        \
+#define __lttng_print(type, fmt, args...)                                            \
+       do {                                                                         \
+               if (__lttng_print_check_opt(type)) {                                 \
+                       fprintf((type) == PRINT_MSG ? stdout : stderr, fmt, ##args); \
+               }                                                                    \
+               __lttng_print_check_abort(type);                                     \
        } while (0)
 
 /* Three level of debug. Use -v, -vv or -vvv for the levels */
-#define _ERRMSG(msg, type, fmt, args...)                                \
-       do {                                                            \
-               if (caa_unlikely(__lttng_print_check_opt(type))) {      \
-                       char generic_name[MAX_INT_DEC_LEN(long) +       \
-                                         MAX_INT_DEC_LEN(long)];       \
-                                                                        \
-                       snprintf(generic_name, sizeof(generic_name),    \
-                                       "%ld/%ld", (long) getpid(),     \
-                                       (long) lttng_gettid());         \
-                                                                        \
-                       __lttng_print(type,                             \
-                                       msg " - %s [%s]: " fmt          \
-                                           " (in %s() at " __FILE__    \
-                                           ":" XSTR(__LINE__) ")\n",   \
-                                       log_add_time(),                 \
-                                       URCU_TLS(logger_thread_name) ?: \
-                                                       generic_name,   \
-                                       ##args, __func__);              \
-               }                                                       \
+#define _ERRMSG(msg, type, fmt, args...)                                                  \
+       do {                                                                              \
+               if (caa_unlikely(__lttng_print_check_opt(type))) {                        \
+                       char generic_name[MAX_INT_DEC_LEN(long) + MAX_INT_DEC_LEN(long)]; \
+                                                                                          \
+                       snprintf(generic_name,                                            \
+                                sizeof(generic_name),                                    \
+                                "%ld/%ld",                                               \
+                                (long) getpid(),                                         \
+                                (long) lttng_gettid());                                  \
+                                                                                          \
+                       __lttng_print(type,                                               \
+                                     msg " - %s [%s]: " fmt " (in %s() at " __FILE__     \
+                                         ":" XSTR(__LINE__) ")\n",                       \
+                                     log_add_time(),                                     \
+                                     logger_thread_name ?: generic_name,                 \
+                                     ##args,                                             \
+                                     __func__);                                          \
+               }                                                                         \
        } while (0)
 
-#define _ERRMSG_NO_LOC(msg, type, fmt, args...)                          \
-       do {                                                             \
-               if (caa_unlikely(__lttng_print_check_opt(type))) {       \
-                       char generic_name[MAX_INT_DEC_LEN(long) +        \
-                                         MAX_INT_DEC_LEN(long)];        \
-                                                                         \
-                       snprintf(generic_name, sizeof(generic_name),     \
-                                       "%ld/%ld", (long) getpid(),      \
-                                       (long) lttng_gettid());          \
-                                                                         \
-                       __lttng_print(type, msg " - %s [%s]: " fmt "\n", \
-                                       log_add_time(),                  \
-                                       URCU_TLS(logger_thread_name) ?:  \
-                                                       generic_name,    \
-                                       ##args);                         \
-               }                                                        \
+#define _ERRMSG_NO_LOC(msg, type, fmt, args...)                                           \
+       do {                                                                              \
+               if (caa_unlikely(__lttng_print_check_opt(type))) {                        \
+                       char generic_name[MAX_INT_DEC_LEN(long) + MAX_INT_DEC_LEN(long)]; \
+                                                                                          \
+                       snprintf(generic_name,                                            \
+                                sizeof(generic_name),                                    \
+                                "%ld/%ld",                                               \
+                                (long) getpid(),                                         \
+                                (long) lttng_gettid());                                  \
+                                                                                          \
+                       __lttng_print(type,                                               \
+                                     msg " - %s [%s]: " fmt "\n",                        \
+                                     log_add_time(),                                     \
+                                     logger_thread_name ?: generic_name,                 \
+                                     ##args);                                            \
+               }                                                                         \
        } while (0)
 
-#define MSG(fmt, args...) \
-       __lttng_print(PRINT_MSG, fmt "\n", ## args)
-#define _MSG(fmt, args...) \
-       __lttng_print(PRINT_MSG, fmt, ## args)
-#define ERR(fmt, args...) \
-       __lttng_print(PRINT_ERR, "Error: " fmt "\n", ## args)
-#define WARN(fmt, args...) \
-       __lttng_print(PRINT_WARN, "Warning: " fmt "\n", ## args)
-
-#define BUG(fmt, args...) _ERRMSG("BUG", PRINT_BUG, fmt, ## args)
-
-#define DBG(fmt, args...) _ERRMSG("DBG1", PRINT_DBG, fmt, ## args)
-#define DBG_NO_LOC(fmt, args...) _ERRMSG_NO_LOC("DBG1", PRINT_DBG, fmt, ## args)
-#define DBG2(fmt, args...) _ERRMSG("DBG2", PRINT_DBG2, fmt, ## args)
-#define DBG3(fmt, args...) _ERRMSG("DBG3", PRINT_DBG3, fmt, ## args)
-#define LOG(type, fmt, args...)                        \
-       do {                                    \
-               switch (type) {                 \
-               case PRINT_ERR:                 \
-                       ERR(fmt, ## args);      \
-                       break;                  \
-               case PRINT_WARN:                \
-                       WARN(fmt, ## args);     \
-                       break;                  \
-               case PRINT_BUG:                 \
-                       BUG(fmt, ## args);      \
-                       break;                  \
-               case PRINT_MSG:                 \
-                       MSG(fmt, ## args);      \
-                       break;                  \
-               case PRINT_DBG:                 \
-                       DBG(fmt, ## args);      \
-                       break;                  \
-               case PRINT_DBG2:                \
-                       DBG2(fmt, ## args);     \
-                       break;                  \
-               case PRINT_DBG3:                \
-                       DBG3(fmt, ## args);     \
-                       break;                  \
-               default:                        \
-                       abort();                \
-               }                               \
-       } while(0);
-
-#define _PERROR(fmt, args...) _ERRMSG("PERROR", PRINT_ERR, fmt, ## args)
-
-#if !defined(__GLIBC__) || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
+#define MSG(fmt, args...)  __lttng_print(PRINT_MSG, fmt "\n", ##args)
+#define _MSG(fmt, args...) __lttng_print(PRINT_MSG, fmt, ##args)
+#define ERR(fmt, args...)  __lttng_print(PRINT_ERR, "Error: " fmt "\n", ##args)
+#define WARN(fmt, args...) __lttng_print(PRINT_WARN, "Warning: " fmt "\n", ##args)
+
+#define BUG(fmt, args...) _ERRMSG("BUG", PRINT_BUG, fmt, ##args)
+
+#define DBG(fmt, args...)       _ERRMSG("DBG1", PRINT_DBG, fmt, ##args)
+#define DBG_NO_LOC(fmt, args...) _ERRMSG_NO_LOC("DBG1", PRINT_DBG, fmt, ##args)
+#define DBG2(fmt, args...)      _ERRMSG("DBG2", PRINT_DBG2, fmt, ##args)
+#define DBG3(fmt, args...)      _ERRMSG("DBG3", PRINT_DBG3, fmt, ##args)
+#define LOG(type, fmt, args...)            \
+       do {                               \
+               switch (type) {            \
+               case PRINT_ERR:            \
+                       ERR(fmt, ##args);  \
+                       break;             \
+               case PRINT_WARN:           \
+                       WARN(fmt, ##args); \
+                       break;             \
+               case PRINT_BUG:            \
+                       BUG(fmt, ##args);  \
+                       break;             \
+               case PRINT_MSG:            \
+                       MSG(fmt, ##args);  \
+                       break;             \
+               case PRINT_DBG:            \
+                       DBG(fmt, ##args);  \
+                       break;             \
+               case PRINT_DBG2:           \
+                       DBG2(fmt, ##args); \
+                       break;             \
+               case PRINT_DBG3:           \
+                       DBG3(fmt, ##args); \
+                       break;             \
+               default:                   \
+                       abort();           \
+               }                          \
+       } while (0);
+
+#define _PERROR(fmt, args...) _ERRMSG("PERROR", PRINT_ERR, fmt, ##args)
+
+#if !defined(__GLIBC__) || \
+       ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
 
 /*
  * Version using XSI strerror_r.
@@ -242,24 +243,62 @@ static inline void __lttng_print_check_abort(enum lttng_error_level type)
 /*
  * Version using GNU strerror_r, for linux with appropriate defines.
  */
-#define PERROR(call, args...)                                             \
-       do {                                                              \
-               char *_perror_buf;                                        \
-               char _perror_tmp[200];                                    \
-               _perror_buf = strerror_r(                                 \
-                               errno, _perror_tmp, sizeof(_perror_tmp)); \
-               _PERROR(call ": %s", ##args, _perror_buf);                \
+#define PERROR(call, args...)                                                      \
+       do {                                                                       \
+               char *_perror_buf;                                                 \
+               char _perror_tmp[200];                                             \
+               _perror_buf = strerror_r(errno, _perror_tmp, sizeof(_perror_tmp)); \
+               _PERROR(call ": %s", ##args, _perror_buf);                         \
        } while (0);
 #endif
 
 const char *error_get_str(int32_t code);
 
+namespace lttng {
+namespace logging {
+namespace details {
+[[noreturn]] void die_formatting_exception(const char *format,
+                                          const std::exception& formatting_exception);
+} /* namespace details */
+} /* namespace logging */
+} /* namespace lttng */
+
+#define DBG_FMT(format_str, args...)                                                              \
+       do {                                                                                      \
+               try {                                                                             \
+                       DBG("%s", lttng::format(format_str, ##args).c_str());                     \
+               } catch (const std::exception& _formatting_exception) {                           \
+                       lttng::logging::details::die_formatting_exception(format_str,             \
+                                                                         _formatting_exception); \
+               }                                                                                 \
+       } while (0);
+
+#define WARN_FMT(format_str, args...)                                                             \
+       do {                                                                                      \
+               try {                                                                             \
+                       WARN("%s", lttng::format(format_str, ##args).c_str());                    \
+               } catch (const std::exception& _formatting_exception) {                           \
+                       lttng::logging::details::die_formatting_exception(format_str,             \
+                                                                         _formatting_exception); \
+               }                                                                                 \
+       } while (0);
+
+#define ERR_FMT(format_str, args...)                                                              \
+       do {                                                                                      \
+               try {                                                                             \
+                       ERR("%s", lttng::format(format_str, ##args).c_str());                     \
+               } catch (const std::exception& _formatting_exception) {                           \
+                       lttng::logging::details::die_formatting_exception(format_str,             \
+                                                                         _formatting_exception); \
+               }                                                                                 \
+       } while (0);
+
 /*
  * Function that format the time and return the reference of log_time.str to
  * the caller. On error, an empty string is returned thus no time will be
  * printed in the log.
  */
-const char *log_add_time(void);
+const char *log_add_time();
 
 /* Name must be a statically-allocated string. */
 void logger_set_thread_name(const char *name, bool set_pthread_name);
index 2b57de62cbb5ab07c37cceb9e38bd63188390194..150e1c3f91f950ff02f9d75c2e5aa0e0a8b9bbdc 100644 (file)
@@ -5,32 +5,33 @@
  *
  */
 
+#include <common/error.hpp>
+#include <common/macros.hpp>
+
+#include <lttng/condition/buffer-usage-internal.hpp>
 #include <lttng/condition/condition-internal.hpp>
 #include <lttng/condition/evaluation-internal.hpp>
-#include <lttng/condition/buffer-usage-internal.hpp>
+#include <lttng/condition/event-rule-matches-internal.hpp>
 #include <lttng/condition/session-consumed-size-internal.hpp>
 #include <lttng/condition/session-rotation-internal.hpp>
-#include <lttng/condition/event-rule-matches-internal.hpp>
-#include <common/macros.hpp>
-#include <common/error.hpp>
+
 #include <stdbool.h>
 
-void lttng_evaluation_init(struct lttng_evaluation *evaluation,
-               enum lttng_condition_type type)
+void lttng_evaluation_init(struct lttng_evaluation *evaluation, enum lttng_condition_type type)
 {
        evaluation->type = type;
 }
 
 int lttng_evaluation_serialize(const struct lttng_evaluation *evaluation,
-               struct lttng_payload *payload)
+                              struct lttng_payload *payload)
 {
        int ret;
        struct lttng_evaluation_comm evaluation_comm;
 
        evaluation_comm.type = (int8_t) evaluation->type;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &evaluation_comm,
-                       sizeof(evaluation_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &evaluation_comm, sizeof(evaluation_comm));
        if (ret) {
                goto end;
        }
@@ -45,19 +46,16 @@ end:
        return ret;
 }
 
-ssize_t lttng_evaluation_create_from_payload(
-               const struct lttng_condition *condition,
-               struct lttng_payload_view *src_view,
-               struct lttng_evaluation **evaluation)
+ssize_t lttng_evaluation_create_from_payload(const struct lttng_condition *condition,
+                                            struct lttng_payload_view *src_view,
+                                            struct lttng_evaluation **evaluation)
 {
        ssize_t ret, evaluation_size = 0;
        const struct lttng_evaluation_comm *evaluation_comm;
        struct lttng_payload_view evaluation_comm_view =
-                       lttng_payload_view_from_view(
-                                       src_view, 0, sizeof(*evaluation_comm));
+               lttng_payload_view_from_view(src_view, 0, sizeof(*evaluation_comm));
        struct lttng_payload_view evaluation_view =
-                       lttng_payload_view_from_view(src_view,
-                                       sizeof(*evaluation_comm), -1);
+               lttng_payload_view_from_view(src_view, sizeof(*evaluation_comm), -1);
 
        if (!src_view || !evaluation) {
                ret = -1;
@@ -74,24 +72,24 @@ ssize_t lttng_evaluation_create_from_payload(
 
        switch ((enum lttng_condition_type) evaluation_comm->type) {
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
-               ret = lttng_evaluation_buffer_usage_low_create_from_payload(
-                               &evaluation_view, evaluation);
+               ret = lttng_evaluation_buffer_usage_low_create_from_payload(&evaluation_view,
+                                                                           evaluation);
                if (ret < 0) {
                        goto end;
                }
                evaluation_size += ret;
                break;
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
-               ret = lttng_evaluation_buffer_usage_high_create_from_payload(
-                               &evaluation_view, evaluation);
+               ret = lttng_evaluation_buffer_usage_high_create_from_payload(&evaluation_view,
+                                                                            evaluation);
                if (ret < 0) {
                        goto end;
                }
                evaluation_size += ret;
                break;
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
-               ret = lttng_evaluation_session_consumed_size_create_from_payload(
-                               &evaluation_view, evaluation);
+               ret = lttng_evaluation_session_consumed_size_create_from_payload(&evaluation_view,
+                                                                                evaluation);
                if (ret < 0) {
                        goto end;
                }
@@ -99,7 +97,7 @@ ssize_t lttng_evaluation_create_from_payload(
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING:
                ret = lttng_evaluation_session_rotation_ongoing_create_from_payload(
-                               &evaluation_view, evaluation);
+                       &evaluation_view, evaluation);
                if (ret < 0) {
                        goto end;
                }
@@ -107,7 +105,7 @@ ssize_t lttng_evaluation_create_from_payload(
                break;
        case LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED:
                ret = lttng_evaluation_session_rotation_completed_create_from_payload(
-                               &evaluation_view, evaluation);
+                       &evaluation_view, evaluation);
                if (ret < 0) {
                        goto end;
                }
@@ -115,12 +113,12 @@ ssize_t lttng_evaluation_create_from_payload(
                break;
        case LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES:
                LTTNG_ASSERT(condition);
-               LTTNG_ASSERT(condition->type ==
-                               LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
+               LTTNG_ASSERT(condition->type == LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES);
                ret = lttng_evaluation_event_rule_matches_create_from_payload(
-                               lttng::utils::container_of(condition,
-                                               &lttng_condition_event_rule_matches::parent),
-                               &evaluation_view, evaluation);
+                       lttng::utils::container_of(condition,
+                                                  &lttng_condition_event_rule_matches::parent),
+                       &evaluation_view,
+                       evaluation);
                if (ret < 0) {
                        goto end;
                }
@@ -128,7 +126,7 @@ ssize_t lttng_evaluation_create_from_payload(
                break;
        default:
                ERR("Attempted to create evaluation of unknown type (%i)",
-                               (int) evaluation_comm->type);
+                   (int) evaluation_comm->type);
                ret = -1;
                goto end;
        }
@@ -138,8 +136,7 @@ end:
        return ret;
 }
 
-enum lttng_condition_type lttng_evaluation_get_type(
-               const struct lttng_evaluation *evaluation)
+enum lttng_condition_type lttng_evaluation_get_type(const struct lttng_evaluation *evaluation)
 {
        return evaluation ? evaluation->type : LTTNG_CONDITION_TYPE_UNKNOWN;
 }
index 0dd0398f2797c379499663635c91c8258673d6b0..221d8e6cbf9518290026dd57b213b302b887c495 100644 (file)
@@ -8,18 +8,18 @@
  */
 
 #define _LGPL_SOURCE
-#include <stddef.h>
-
 #include <common/bytecode/bytecode.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/event-expr-internal.hpp>
 #include <lttng/event-expr.h>
+
+#include <stddef.h>
 #include <stdio.h>
 
-enum lttng_event_expr_type lttng_event_expr_get_type(
-               const struct lttng_event_expr *expr)
+enum lttng_event_expr_type lttng_event_expr_get_type(const struct lttng_event_expr *expr)
 {
        enum lttng_event_expr_type type;
 
@@ -34,9 +34,7 @@ end:
        return type;
 }
 
-static
-struct lttng_event_expr *create_empty_expr(enum lttng_event_expr_type type,
-               size_t size)
+static struct lttng_event_expr *create_empty_expr(enum lttng_event_expr_type type, size_t size)
 {
        struct lttng_event_expr *expr;
 
@@ -51,13 +49,11 @@ end:
        return expr;
 }
 
-static
-struct lttng_event_expr_field *create_field_event_expr(
-               enum lttng_event_expr_type type,
-               const char *name)
+static struct lttng_event_expr_field *create_field_event_expr(enum lttng_event_expr_type type,
+                                                             const char *name)
 {
        struct lttng_event_expr_field *expr = lttng::utils::container_of(
-                       create_empty_expr(type, sizeof(*expr)), &lttng_event_expr_field::parent);
+               create_empty_expr(type, sizeof(*expr)), &lttng_event_expr_field::parent);
 
        if (!expr) {
                goto error;
@@ -75,60 +71,55 @@ error:
        if (expr) {
                lttng_event_expr_destroy(&expr->parent);
        }
-       expr = NULL;
+       expr = nullptr;
 
 end:
        return expr;
 }
 
-struct lttng_event_expr *lttng_event_expr_event_payload_field_create(
-               const char *field_name)
+struct lttng_event_expr *lttng_event_expr_event_payload_field_create(const char *field_name)
 {
-       struct lttng_event_expr *expr = NULL;
+       struct lttng_event_expr *expr = nullptr;
 
        if (!field_name) {
                goto end;
        }
 
-       expr = &create_field_event_expr(
-                       LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD,
-                       field_name)->parent;
+       expr = &create_field_event_expr(LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD, field_name)
+                       ->parent;
 
 end:
        return expr;
 }
 
-struct lttng_event_expr *lttng_event_expr_channel_context_field_create(
-               const char *field_name)
+struct lttng_event_expr *lttng_event_expr_channel_context_field_create(const char *field_name)
 {
-       struct lttng_event_expr *expr = NULL;
+       struct lttng_event_expr *expr = nullptr;
 
        if (!field_name) {
                goto end;
        }
 
-       expr = &create_field_event_expr(
-                       LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD,
-                       field_name)->parent;
+       expr = &create_field_event_expr(LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD, field_name)
+                       ->parent;
 
 end:
        return expr;
 }
 
-struct lttng_event_expr *lttng_event_expr_app_specific_context_field_create(
-               const char *provider_name, const char *type_name)
+struct lttng_event_expr *
+lttng_event_expr_app_specific_context_field_create(const char *provider_name, const char *type_name)
 {
-       struct lttng_event_expr_app_specific_context_field *expr = NULL;
+       struct lttng_event_expr_app_specific_context_field *expr = nullptr;
        struct lttng_event_expr *ret_parent_expr;
 
        if (!type_name || !provider_name) {
                goto error;
        }
 
-       expr = lttng::utils::container_of(create_empty_expr(
-                       LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD,
-                       sizeof(*expr)),
-                       &lttng_event_expr_app_specific_context_field::parent);
+       expr = lttng::utils::container_of(
+               create_empty_expr(LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD, sizeof(*expr)),
+               &lttng_event_expr_app_specific_context_field::parent);
        if (!expr) {
                goto error;
        }
@@ -150,29 +141,27 @@ error:
        if (expr) {
                lttng_event_expr_destroy(&expr->parent);
        }
-       ret_parent_expr = NULL;
+       ret_parent_expr = nullptr;
 
 end:
        return ret_parent_expr;
 }
 
-struct lttng_event_expr *lttng_event_expr_array_field_element_create(
-               struct lttng_event_expr *array_field_expr,
-               unsigned int index)
+struct lttng_event_expr *
+lttng_event_expr_array_field_element_create(struct lttng_event_expr *array_field_expr,
+                                           unsigned int index)
 {
-       struct lttng_event_expr_array_field_element *expr = NULL;
+       struct lttng_event_expr_array_field_element *expr = nullptr;
        struct lttng_event_expr *ret_parent_expr;
 
        /* The parent array field expression must be an l-value */
-       if (!array_field_expr ||
-                       !lttng_event_expr_is_lvalue(array_field_expr)) {
+       if (!array_field_expr || !lttng_event_expr_is_lvalue(array_field_expr)) {
                goto error;
        }
 
-       expr = lttng::utils::container_of(create_empty_expr(
-                       LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT,
-                       sizeof(*expr)),
-                       &lttng_event_expr_array_field_element::parent);
+       expr = lttng::utils::container_of(
+               create_empty_expr(LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT, sizeof(*expr)),
+               &lttng_event_expr_array_field_element::parent);
        if (!expr) {
                goto error;
        }
@@ -183,113 +172,108 @@ struct lttng_event_expr *lttng_event_expr_array_field_element_create(
        goto end;
 
 error:
-       ret_parent_expr = NULL;
+       ret_parent_expr = nullptr;
 
 end:
        return ret_parent_expr;
 }
 
-const char *lttng_event_expr_event_payload_field_get_name(
-               const struct lttng_event_expr *expr)
+const char *lttng_event_expr_event_payload_field_get_name(const struct lttng_event_expr *expr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD) {
                goto end;
        }
 
-       ret = lttng::utils::container_of(expr,
-                       &lttng_event_expr_field::parent)->name;
+       ret = lttng::utils::container_of(expr, &lttng_event_expr_field::parent)->name;
 
 end:
        return ret;
 }
 
-const char *lttng_event_expr_channel_context_field_get_name(
-               const struct lttng_event_expr *expr)
+const char *lttng_event_expr_channel_context_field_get_name(const struct lttng_event_expr *expr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD) {
                goto end;
        }
 
-       ret = lttng::utils::container_of(expr,
-                       &lttng_event_expr_field::parent)->name;
+       ret = lttng::utils::container_of(expr, &lttng_event_expr_field::parent)->name;
 
 end:
        return ret;
 }
 
-const char *lttng_event_expr_app_specific_context_field_get_provider_name(
-               const struct lttng_event_expr *expr)
+const char *
+lttng_event_expr_app_specific_context_field_get_provider_name(const struct lttng_event_expr *expr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD) {
                goto end;
        }
 
-       ret = lttng::utils::container_of(expr,
-                       &lttng_event_expr_app_specific_context_field::parent)->provider_name;
+       ret = lttng::utils::container_of(expr, &lttng_event_expr_app_specific_context_field::parent)
+                     ->provider_name;
 
 end:
        return ret;
 }
 
-const char *lttng_event_expr_app_specific_context_field_get_type_name(
-               const struct lttng_event_expr *expr)
+const char *
+lttng_event_expr_app_specific_context_field_get_type_name(const struct lttng_event_expr *expr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD) {
                goto end;
        }
 
-       ret = lttng::utils::container_of(expr,
-                       &lttng_event_expr_app_specific_context_field::parent)->type_name;
+       ret = lttng::utils::container_of(expr, &lttng_event_expr_app_specific_context_field::parent)
+                     ->type_name;
 
 end:
        return ret;
 }
 
 const struct lttng_event_expr *
-lttng_event_expr_array_field_element_get_parent_expr(
-               const struct lttng_event_expr *expr)
+lttng_event_expr_array_field_element_get_parent_expr(const struct lttng_event_expr *expr)
 {
-       const struct lttng_event_expr *ret = NULL;
+       const struct lttng_event_expr *ret = nullptr;
 
        if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT) {
                goto end;
        }
 
-       ret = lttng::utils::container_of(expr,
-                       &lttng_event_expr_array_field_element::parent)->array_field_expr;
+       ret = lttng::utils::container_of(expr, &lttng_event_expr_array_field_element::parent)
+                     ->array_field_expr;
 
 end:
        return ret;
 }
 
-enum lttng_event_expr_status lttng_event_expr_array_field_element_get_index(
-               const struct lttng_event_expr *expr, unsigned int *index)
+enum lttng_event_expr_status
+lttng_event_expr_array_field_element_get_index(const struct lttng_event_expr *expr,
+                                              unsigned int *index)
 {
        enum lttng_event_expr_status ret = LTTNG_EVENT_EXPR_STATUS_OK;
 
-       if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT ||
-                       !index) {
+       if (!expr || expr->type != LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT || !index) {
                ret = LTTNG_EVENT_EXPR_STATUS_INVALID;
                goto end;
        }
 
-       *index = lttng::utils::container_of(expr,
-                       &lttng_event_expr_array_field_element::parent)->index;
+       *index = lttng::utils::container_of(expr, &lttng_event_expr_array_field_element::parent)
+                        ->index;
 
 end:
        return ret;
 }
 
 bool lttng_event_expr_is_equal(const struct lttng_event_expr *expr_a,
-               const struct lttng_event_expr *expr_b)
+                              const struct lttng_event_expr *expr_b)
 {
        bool is_equal = true;
 
@@ -313,11 +297,9 @@ bool lttng_event_expr_is_equal(const struct lttng_event_expr *expr_a,
        case LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD:
        {
                const struct lttng_event_expr_field *field_expr_a =
-                               lttng::utils::container_of(expr_a,
-                                       &lttng_event_expr_field::parent);
+                       lttng::utils::container_of(expr_a, &lttng_event_expr_field::parent);
                const struct lttng_event_expr_field *field_expr_b =
-                               lttng::utils::container_of(expr_b,
-                                       &lttng_event_expr_field::parent);
+                       lttng::utils::container_of(expr_b, &lttng_event_expr_field::parent);
 
                if (strcmp(field_expr_a->name, field_expr_b->name) != 0) {
                        goto not_equal;
@@ -328,19 +310,17 @@ bool lttng_event_expr_is_equal(const struct lttng_event_expr *expr_a,
        case LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD:
        {
                const struct lttng_event_expr_app_specific_context_field *field_expr_a =
-                               lttng::utils::container_of(expr_a,
-                                       &lttng_event_expr_app_specific_context_field::parent);
+                       lttng::utils::container_of(
+                               expr_a, &lttng_event_expr_app_specific_context_field::parent);
                const struct lttng_event_expr_app_specific_context_field *field_expr_b =
-                               lttng::utils::container_of(expr_b,
-                                       &lttng_event_expr_app_specific_context_field::parent);
+                       lttng::utils::container_of(
+                               expr_b, &lttng_event_expr_app_specific_context_field::parent);
 
-               if (strcmp(field_expr_a->provider_name,
-                               field_expr_b->provider_name) != 0) {
+               if (strcmp(field_expr_a->provider_name, field_expr_b->provider_name) != 0) {
                        goto not_equal;
                }
 
-               if (strcmp(field_expr_a->type_name,
-                               field_expr_b->type_name) != 0) {
+               if (strcmp(field_expr_a->type_name, field_expr_b->type_name) != 0) {
                        goto not_equal;
                }
 
@@ -349,14 +329,14 @@ bool lttng_event_expr_is_equal(const struct lttng_event_expr *expr_a,
        case LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT:
        {
                const struct lttng_event_expr_array_field_element *elem_expr_a =
-                               lttng::utils::container_of(expr_a,
-                                       &lttng_event_expr_array_field_element::parent);
+                       lttng::utils::container_of(expr_a,
+                                                  &lttng_event_expr_array_field_element::parent);
                const struct lttng_event_expr_array_field_element *elem_expr_b =
-                               lttng::utils::container_of(expr_b,
-                                       &lttng_event_expr_array_field_element::parent);
+                       lttng::utils::container_of(expr_b,
+                                                  &lttng_event_expr_array_field_element::parent);
 
                if (!lttng_event_expr_is_equal(elem_expr_a->array_field_expr,
-                               elem_expr_b->array_field_expr)) {
+                                              elem_expr_b->array_field_expr)) {
                        goto not_equal;
                }
 
@@ -390,8 +370,7 @@ void lttng_event_expr_destroy(struct lttng_event_expr *expr)
        case LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD:
        {
                struct lttng_event_expr_field *field_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_field::parent);
+                       lttng::utils::container_of(expr, &lttng_event_expr_field::parent);
 
                free(field_expr->name);
                break;
@@ -399,8 +378,8 @@ void lttng_event_expr_destroy(struct lttng_event_expr *expr)
        case LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD:
        {
                struct lttng_event_expr_app_specific_context_field *field_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_app_specific_context_field::parent);
+                       lttng::utils::container_of(
+                               expr, &lttng_event_expr_app_specific_context_field::parent);
 
                free(field_expr->provider_name);
                free(field_expr->type_name);
@@ -408,9 +387,8 @@ void lttng_event_expr_destroy(struct lttng_event_expr *expr)
        }
        case LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT:
        {
-               struct lttng_event_expr_array_field_element *elem_expr =
-                               lttng::utils::container_of(expr,
-                                       &lttng_event_expr_array_field_element::parent);
+               struct lttng_event_expr_array_field_element *elem_expr = lttng::utils::container_of(
+                       expr, &lttng_event_expr_array_field_element::parent);
 
                lttng_event_expr_destroy(elem_expr->array_field_expr);
                break;
@@ -426,8 +404,8 @@ end:
 }
 
 static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
-               struct lttng_bytecode_alloc **bytecode,
-               struct lttng_bytecode_alloc **bytecode_reloc)
+                                           struct lttng_bytecode_alloc **bytecode,
+                                           struct lttng_bytecode_alloc **bytecode_reloc)
 {
        int status;
        enum lttng_event_expr_status event_expr_status;
@@ -450,8 +428,7 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
                        goto end;
                }
 
-               status = bytecode_push_get_symbol(
-                               bytecode, bytecode_reloc, name);
+               status = bytecode_push_get_symbol(bytecode, bytecode_reloc, name);
                if (status) {
                        ERR("Failed to push 'get symbol %s' in bytecode", name);
                        goto end;
@@ -476,8 +453,7 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
                        goto end;
                }
 
-               status = bytecode_push_get_symbol(
-                               bytecode, bytecode_reloc, name);
+               status = bytecode_push_get_symbol(bytecode, bytecode_reloc, name);
                if (status) {
                        ERR("Failed to push 'get symbol %s' in bytecode", name);
                        goto end;
@@ -488,7 +464,7 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
        case LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD:
        {
                int ret;
-               char *name = NULL;
+               char *name = nullptr;
                const char *provider_name, *type_name;
 
                status = bytecode_push_get_app_context_root(bytecode);
@@ -497,16 +473,14 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
                        goto end;
                }
 
-               provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(
-                               expr);
+               provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(expr);
                if (!provider_name) {
                        ERR("Failed to get application context provider name from event expression");
                        status = -1;
                        goto end;
                }
 
-               type_name = lttng_event_expr_app_specific_context_field_get_type_name(
-                               expr);
+               type_name = lttng_event_expr_app_specific_context_field_get_type_name(expr);
                if (!type_name) {
                        ERR("Failed to get application context type name from event expression");
                        status = -1;
@@ -519,17 +493,18 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
                ret = asprintf(&name, "%s:%s", provider_name, type_name);
                if (ret < 0) {
                        PERROR("Failed to format application specific context: provider_name = '%s', type_name = '%s'",
-                                       provider_name, type_name);
+                              provider_name,
+                              type_name);
                        status = -1;
                        goto end;
                }
 
-               status = bytecode_push_get_symbol(
-                               bytecode, bytecode_reloc, name);
+               status = bytecode_push_get_symbol(bytecode, bytecode_reloc, name);
                free(name);
                if (status) {
                        ERR("Failed to push 'get symbol %s:%s' in bytecode",
-                                       provider_name, type_name);
+                           provider_name,
+                           type_name);
                        goto end;
                }
 
@@ -540,23 +515,19 @@ static int event_expr_to_bytecode_recursive(const struct lttng_event_expr *expr,
                unsigned int index;
                const struct lttng_event_expr *parent;
 
-               parent = lttng_event_expr_array_field_element_get_parent_expr(
-                               expr);
+               parent = lttng_event_expr_array_field_element_get_parent_expr(expr);
                if (!parent) {
                        ERR("Failed to get parent expression from array event expression");
                        status = -1;
                        goto end;
                }
 
-               status = event_expr_to_bytecode_recursive(
-                               parent, bytecode, bytecode_reloc);
+               status = event_expr_to_bytecode_recursive(parent, bytecode, bytecode_reloc);
                if (status) {
                        goto end;
                }
 
-               event_expr_status =
-                               lttng_event_expr_array_field_element_get_index(
-                                               expr, &index);
+               event_expr_status = lttng_event_expr_array_field_element_get_index(expr, &index);
                if (event_expr_status != LTTNG_EVENT_EXPR_STATUS_OK) {
                        ERR("Failed to get array field element index from event expression");
                        status = -1;
@@ -581,12 +552,12 @@ end:
 }
 
 int lttng_event_expr_to_bytecode(const struct lttng_event_expr *expr,
-               struct lttng_bytecode **bytecode_out)
+                                struct lttng_bytecode **bytecode_out)
 {
        int status;
        struct return_op ret_insn;
-       struct lttng_bytecode_alloc *bytecode = NULL;
-       struct lttng_bytecode_alloc *bytecode_reloc = NULL;
+       struct lttng_bytecode_alloc *bytecode = nullptr;
+       struct lttng_bytecode_alloc *bytecode_reloc = nullptr;
 
        status = bytecode_init(&bytecode);
        if (status) {
@@ -600,8 +571,7 @@ int lttng_event_expr_to_bytecode(const struct lttng_event_expr *expr,
                goto end;
        }
 
-       status = event_expr_to_bytecode_recursive(
-                       expr, &bytecode, &bytecode_reloc);
+       status = event_expr_to_bytecode_recursive(expr, &bytecode, &bytecode_reloc);
        if (status) {
                /* Errors already logged. */
                goto end;
@@ -612,8 +582,8 @@ int lttng_event_expr_to_bytecode(const struct lttng_event_expr *expr,
 
        /* Append symbol table to bytecode. */
        bytecode->b.reloc_table_offset = bytecode_get_len(&bytecode->b);
-       status = bytecode_push(&bytecode, bytecode_reloc->b.data, 1,
-                       bytecode_get_len(&bytecode_reloc->b));
+       status = bytecode_push(
+               &bytecode, bytecode_reloc->b.data, 1, bytecode_get_len(&bytecode_reloc->b));
        if (status) {
                ERR("Failed to push symbol table to bytecode");
                goto end;
@@ -638,14 +608,13 @@ end:
        return status;
 }
 
-static
-enum lttng_error_code lttng_event_expr_event_payload_field_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_expr_event_payload_field_mi_serialize(const struct lttng_event_expr *expression,
+                                                 struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const char *name = NULL;
+       const char *name = nullptr;
 
        LTTNG_ASSERT(expression);
        LTTNG_ASSERT(writer);
@@ -655,15 +624,13 @@ enum lttng_error_code lttng_event_expr_event_payload_field_mi_serialize(
        LTTNG_ASSERT(name);
 
        /* Open event expr payload field element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_expr_payload_field);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_expr_payload_field);
        if (ret) {
                goto mi_error;
        }
 
        /* Name. */
-       ret = mi_lttng_writer_write_element_string(
-                       writer, config_element_name, name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, name);
        if (ret) {
                goto mi_error;
        }
@@ -683,14 +650,13 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code lttng_event_expr_channel_context_field_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_expr_channel_context_field_mi_serialize(const struct lttng_event_expr *expression,
+                                                   struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const char *name = NULL;
+       const char *name = nullptr;
 
        LTTNG_ASSERT(expression);
        LTTNG_ASSERT(writer);
@@ -701,14 +667,13 @@ enum lttng_error_code lttng_event_expr_channel_context_field_mi_serialize(
 
        /* Open event expr channel context field element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_event_expr_channel_context_field);
+                                          mi_lttng_element_event_expr_channel_context_field);
        if (ret) {
                goto mi_error;
        }
 
        /* Name. */
-       ret = mi_lttng_writer_write_element_string(
-                       writer, config_element_name, name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, name);
        if (ret) {
                goto mi_error;
        }
@@ -728,47 +693,42 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code lttng_event_expr_app_specific_context_field_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_expr_app_specific_context_field_mi_serialize(const struct lttng_event_expr *expression,
+                                                        struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const char *provider_name = NULL;
-       const char *type_name = NULL;
+       const char *provider_name = nullptr;
+       const char *type_name = nullptr;
 
        LTTNG_ASSERT(expression);
        LTTNG_ASSERT(writer);
-       LTTNG_ASSERT(expression->type ==
-                       LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD);
+       LTTNG_ASSERT(expression->type == LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD);
 
-       provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(
-                       expression);
+       provider_name = lttng_event_expr_app_specific_context_field_get_provider_name(expression);
        LTTNG_ASSERT(provider_name);
 
-       type_name = lttng_event_expr_app_specific_context_field_get_type_name(
-                       expression);
+       type_name = lttng_event_expr_app_specific_context_field_get_type_name(expression);
        LTTNG_ASSERT(provider_name);
 
        /* Open event expr app specific context field element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_event_expr_app_specific_context_field);
+                                          mi_lttng_element_event_expr_app_specific_context_field);
        if (ret) {
                goto mi_error;
        }
 
        /* Provider name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_expr_provider_name,
-                       provider_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_expr_provider_name, provider_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Type name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_expr_type_name, type_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_expr_type_name, type_name);
        if (ret) {
                goto mi_error;
        }
@@ -788,39 +748,35 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code lttng_event_expr_array_field_element_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_expr_array_field_element_mi_serialize(const struct lttng_event_expr *expression,
+                                                 struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_expr_status status;
-       const struct lttng_event_expr *parent_expr = NULL;
+       const struct lttng_event_expr *parent_expr = nullptr;
        unsigned int index;
 
        LTTNG_ASSERT(expression);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(expression->type == LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT);
 
-       status = lttng_event_expr_array_field_element_get_index(
-                       expression, &index);
+       status = lttng_event_expr_array_field_element_get_index(expression, &index);
        LTTNG_ASSERT(status == LTTNG_EVENT_EXPR_STATUS_OK);
 
-       parent_expr = lttng_event_expr_array_field_element_get_parent_expr(
-                       expression);
-       LTTNG_ASSERT(parent_expr != NULL);
+       parent_expr = lttng_event_expr_array_field_element_get_parent_expr(expression);
+       LTTNG_ASSERT(parent_expr != nullptr);
 
        /* Open event expr array field element. */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_event_expr_array_field_element);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_expr_array_field_element);
        if (ret) {
                goto mi_error;
        }
 
        /* Index. */
        ret = mi_lttng_writer_write_element_unsigned_int(
-                       writer, mi_lttng_element_event_expr_index, index);
+               writer, mi_lttng_element_event_expr_index, index);
        if (ret) {
                goto mi_error;
        }
@@ -846,9 +802,8 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code lttng_event_expr_mi_serialize(
-               const struct lttng_event_expr *expression,
-               struct mi_writer *writer)
+enum lttng_error_code lttng_event_expr_mi_serialize(const struct lttng_event_expr *expression,
+                                                   struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -863,20 +818,17 @@ enum lttng_error_code lttng_event_expr_mi_serialize(
 
        switch (expression->type) {
        case LTTNG_EVENT_EXPR_TYPE_EVENT_PAYLOAD_FIELD:
-               ret_code = lttng_event_expr_event_payload_field_mi_serialize(
-                               expression, writer);
+               ret_code = lttng_event_expr_event_payload_field_mi_serialize(expression, writer);
                break;
        case LTTNG_EVENT_EXPR_TYPE_CHANNEL_CONTEXT_FIELD:
-               ret_code = lttng_event_expr_channel_context_field_mi_serialize(
-                               expression, writer);
+               ret_code = lttng_event_expr_channel_context_field_mi_serialize(expression, writer);
                break;
        case LTTNG_EVENT_EXPR_TYPE_APP_SPECIFIC_CONTEXT_FIELD:
-               ret_code = lttng_event_expr_app_specific_context_field_mi_serialize(
-                               expression, writer);
+               ret_code = lttng_event_expr_app_specific_context_field_mi_serialize(expression,
+                                                                                   writer);
                break;
        case LTTNG_EVENT_EXPR_TYPE_ARRAY_FIELD_ELEMENT:
-               ret_code = lttng_event_expr_array_field_element_mi_serialize(
-                               expression, writer);
+               ret_code = lttng_event_expr_array_field_element_mi_serialize(expression, writer);
                break;
        default:
                abort();
index 8017fd0814983a8a2009d5d44f5d4e78a1120f92..a52f192684093bf7ab996313e0546a27a346594d 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <stddef.h>
-#include <stdbool.h>
-
 #include <common/error.hpp>
 #include <common/macros.hpp>
+
 #include <lttng/event-field-value-internal.hpp>
 
-static
-struct lttng_event_field_value *create_empty_field_val(
-               enum lttng_event_field_value_type type, size_t size)
+#include <stdbool.h>
+#include <stddef.h>
+
+static struct lttng_event_field_value *
+create_empty_field_val(enum lttng_event_field_value_type type, size_t size)
 {
        struct lttng_event_field_value *field_val;
 
@@ -34,15 +34,14 @@ end:
        return field_val;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_uint_create(
-               uint64_t val)
+struct lttng_event_field_value *lttng_event_field_value_uint_create(uint64_t val)
 {
        struct lttng_event_field_value_uint *field_val;
 
-       field_val = lttng::utils::container_of(create_empty_field_val(
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT,
-                       sizeof(*field_val)),
-                       &lttng_event_field_value_uint::parent);
+       field_val = lttng::utils::container_of(
+               create_empty_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT,
+                                      sizeof(*field_val)),
+               &lttng_event_field_value_uint::parent);
        if (!field_val) {
                goto error;
        }
@@ -57,15 +56,13 @@ end:
        return &field_val->parent;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_int_create(
-               int64_t val)
+struct lttng_event_field_value *lttng_event_field_value_int_create(int64_t val)
 {
        struct lttng_event_field_value_int *field_val;
 
-       field_val = lttng::utils::container_of(create_empty_field_val(
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT,
-                       sizeof(*field_val)),
-                       &lttng_event_field_value_int::parent);
+       field_val = lttng::utils::container_of(
+               create_empty_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT, sizeof(*field_val)),
+               &lttng_event_field_value_int::parent);
        if (!field_val) {
                goto error;
        }
@@ -80,14 +77,13 @@ end:
        return &field_val->parent;
 }
 
-static
-struct lttng_event_field_value_enum *create_enum_field_val(
-               enum lttng_event_field_value_type type, size_t size)
+static struct lttng_event_field_value_enum *
+create_enum_field_val(enum lttng_event_field_value_type type, size_t size)
 {
        struct lttng_event_field_value_enum *field_val;
 
        field_val = lttng::utils::container_of(create_empty_field_val(type, size),
-                       &lttng_event_field_value_enum::parent);
+                                              &lttng_event_field_value_enum::parent);
        if (!field_val) {
                goto error;
        }
@@ -102,15 +98,14 @@ end:
        return field_val;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_enum_uint_create(
-               uint64_t val)
+struct lttng_event_field_value *lttng_event_field_value_enum_uint_create(uint64_t val)
 {
        struct lttng_event_field_value_enum_uint *field_val;
 
-       field_val = lttng::utils::container_of(create_enum_field_val(
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM,
-                       sizeof(*field_val)),
-                       &lttng_event_field_value_enum_uint::parent);
+       field_val = lttng::utils::container_of(
+               create_enum_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM,
+                                     sizeof(*field_val)),
+               &lttng_event_field_value_enum_uint::parent);
        if (!field_val) {
                goto error;
        }
@@ -125,15 +120,13 @@ end:
        return &field_val->parent.parent;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_enum_int_create(
-               int64_t val)
+struct lttng_event_field_value *lttng_event_field_value_enum_int_create(int64_t val)
 {
        struct lttng_event_field_value_enum_int *field_val;
 
-       field_val = lttng::utils::container_of(create_enum_field_val(
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM,
-                       sizeof(*field_val)),
-                       &lttng_event_field_value_enum_int::parent);
+       field_val = lttng::utils::container_of(
+               create_enum_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM, sizeof(*field_val)),
+               &lttng_event_field_value_enum_int::parent);
        if (!field_val) {
                goto error;
        }
@@ -151,10 +144,8 @@ end:
 struct lttng_event_field_value *lttng_event_field_value_real_create(double val)
 {
        struct lttng_event_field_value_real *field_val = lttng::utils::container_of(
-                       create_empty_field_val(
-                               LTTNG_EVENT_FIELD_VALUE_TYPE_REAL,
-                               sizeof(*field_val)),
-                       &lttng_event_field_value_real::parent);
+               create_empty_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_REAL, sizeof(*field_val)),
+               &lttng_event_field_value_real::parent);
 
        if (!field_val) {
                goto error;
@@ -170,21 +161,27 @@ end:
        return &field_val->parent;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_string_create_with_size(
-               const char *val, size_t size)
+struct lttng_event_field_value *lttng_event_field_value_string_create_with_size(const char *val,
+                                                                               size_t size)
 {
        struct lttng_event_field_value_string *field_val = lttng::utils::container_of(
-                       create_empty_field_val(
-                               LTTNG_EVENT_FIELD_VALUE_TYPE_STRING,
-                               sizeof(*field_val)),
-                       &lttng_event_field_value_string::parent);
+               create_empty_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_STRING, sizeof(*field_val)),
+               &lttng_event_field_value_string::parent);
 
        if (!field_val) {
                goto error;
        }
 
-       LTTNG_ASSERT(val);
-       field_val->val = strndup(val, size);
+       if (size) {
+               LTTNG_ASSERT(val);
+               field_val->val = strndup(val, size);
+       } else {
+               /*
+                * User code do not expect a NULL string pointer. Populate with
+                * an empty string when length is 0.
+                */
+               field_val->val = strdup("");
+       }
        if (!field_val->val) {
                goto error;
        }
@@ -198,27 +195,22 @@ end:
        return &field_val->parent;
 }
 
-struct lttng_event_field_value *lttng_event_field_value_string_create(
-               const char *val)
+struct lttng_event_field_value *lttng_event_field_value_string_create(const char *val)
 {
        LTTNG_ASSERT(val);
-       return lttng_event_field_value_string_create_with_size(val,
-                       strlen(val));
+       return lttng_event_field_value_string_create_with_size(val, strlen(val));
 }
 
-static
-void destroy_field_val(void *field_val)
+static void destroy_field_val(void *field_val)
 {
        lttng_event_field_value_destroy((lttng_event_field_value *) field_val);
 }
 
-struct lttng_event_field_value *lttng_event_field_value_array_create(void)
+struct lttng_event_field_value *lttng_event_field_value_array_create()
 {
        struct lttng_event_field_value_array *field_val = lttng::utils::container_of(
-                       create_empty_field_val(
-                               LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY,
-                               sizeof(*field_val)),
-                       &lttng_event_field_value_array::parent);
+               create_empty_field_val(LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY, sizeof(*field_val)),
+               &lttng_event_field_value_array::parent);
 
        if (!field_val) {
                goto error;
@@ -244,27 +236,24 @@ void lttng_event_field_value_destroy(struct lttng_event_field_value *field_val)
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM:
        case LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM:
        {
-               struct lttng_event_field_value_enum *enum_field_val =
-                               lttng::utils::container_of(field_val,
-                                       &lttng_event_field_value_enum::parent);
+               struct lttng_event_field_value_enum *enum_field_val = lttng::utils::container_of(
+                       field_val, &lttng_event_field_value_enum::parent);
 
                lttng_dynamic_pointer_array_reset(&enum_field_val->labels);
                break;
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_STRING:
        {
-               struct lttng_event_field_value_string *str_field_val =
-                               lttng::utils::container_of(field_val,
-                                       &lttng_event_field_value_string::parent);
+               struct lttng_event_field_value_string *str_field_val = lttng::utils::container_of(
+                       field_val, &lttng_event_field_value_string::parent);
 
                free(str_field_val->val);
                break;
        }
        case LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY:
        {
-               struct lttng_event_field_value_array *array_field_expr =
-                               lttng::utils::container_of(field_val,
-                                       &lttng_event_field_value_array::parent);
+               struct lttng_event_field_value_array *array_field_expr = lttng::utils::container_of(
+                       field_val, &lttng_event_field_value_array::parent);
 
                lttng_dynamic_pointer_array_reset(&array_field_expr->elems);
                break;
@@ -279,9 +268,9 @@ end:
        return;
 }
 
-int lttng_event_field_value_enum_append_label_with_size(
-               struct lttng_event_field_value *field_val,
-               const char *label, size_t size)
+int lttng_event_field_value_enum_append_label_with_size(struct lttng_event_field_value *field_val,
+                                                       const char *label,
+                                                       size_t size)
 {
        int ret;
        char *new_label;
@@ -295,11 +284,11 @@ int lttng_event_field_value_enum_append_label_with_size(
        }
 
        ret = lttng_dynamic_pointer_array_add_pointer(
-                       &lttng::utils::container_of(field_val,
-                               &lttng_event_field_value_enum::parent)->labels,
-                       new_label);
+               &lttng::utils::container_of(field_val, &lttng_event_field_value_enum::parent)
+                        ->labels,
+               new_label);
        if (ret == 0) {
-               new_label = NULL;
+               new_label = nullptr;
        }
 
 end:
@@ -307,39 +296,35 @@ end:
        return ret;
 }
 
-int lttng_event_field_value_enum_append_label(
-               struct lttng_event_field_value *field_val,
-               const char *label)
+int lttng_event_field_value_enum_append_label(struct lttng_event_field_value *field_val,
+                                             const char *label)
 {
        LTTNG_ASSERT(label);
-       return lttng_event_field_value_enum_append_label_with_size(field_val,
-                       label, strlen(label));
+       return lttng_event_field_value_enum_append_label_with_size(field_val, label, strlen(label));
 }
 
-int lttng_event_field_value_array_append(
-               struct lttng_event_field_value *array_field_val,
-               struct lttng_event_field_value *field_val)
+int lttng_event_field_value_array_append(struct lttng_event_field_value *array_field_val,
+                                        struct lttng_event_field_value *field_val)
 {
        LTTNG_ASSERT(array_field_val);
        LTTNG_ASSERT(field_val);
        return lttng_dynamic_pointer_array_add_pointer(
-                       &lttng::utils::container_of(array_field_val,
-                               &lttng_event_field_value_array::parent)->elems,
-                       field_val);
+               &lttng::utils::container_of(array_field_val, &lttng_event_field_value_array::parent)
+                        ->elems,
+               field_val);
 }
 
-int lttng_event_field_value_array_append_unavailable(
-               struct lttng_event_field_value *array_field_val)
+int lttng_event_field_value_array_append_unavailable(struct lttng_event_field_value *array_field_val)
 {
        LTTNG_ASSERT(array_field_val);
        return lttng_dynamic_pointer_array_add_pointer(
-                       &lttng::utils::container_of(array_field_val,
-                               &lttng_event_field_value_array::parent)->elems,
-                       NULL);
+               &lttng::utils::container_of(array_field_val, &lttng_event_field_value_array::parent)
+                        ->elems,
+               nullptr);
 }
 
-enum lttng_event_field_value_type lttng_event_field_value_get_type(
-               const struct lttng_event_field_value *field_val)
+enum lttng_event_field_value_type
+lttng_event_field_value_get_type(const struct lttng_event_field_value *field_val)
 {
        enum lttng_event_field_value_type type;
 
@@ -355,8 +340,8 @@ end:
 }
 
 enum lttng_event_field_value_status
-lttng_event_field_value_unsigned_int_get_value(
-               const struct lttng_event_field_value *field_val, uint64_t *val)
+lttng_event_field_value_unsigned_int_get_value(const struct lttng_event_field_value *field_val,
+                                              uint64_t *val)
 {
        enum lttng_event_field_value_status status;
 
@@ -367,17 +352,17 @@ lttng_event_field_value_unsigned_int_get_value(
 
        switch (field_val->type) {
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT:
-               *val = lttng::utils::container_of(field_val,
-                               &lttng_event_field_value_uint::parent)->val;
+               *val = lttng::utils::container_of(field_val, &lttng_event_field_value_uint::parent)
+                              ->val;
                break;
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM:
        {
                const struct lttng_event_field_value_enum *field_val_enum =
-                               lttng::utils::container_of(
-                                               field_val, &lttng_event_field_value_enum::parent);
+                       lttng::utils::container_of(field_val,
+                                                  &lttng_event_field_value_enum::parent);
                const struct lttng_event_field_value_enum_uint *field_val_enum_uint =
-                               lttng::utils::container_of(field_val_enum,
-                                               &lttng_event_field_value_enum_uint::parent);
+                       lttng::utils::container_of(field_val_enum,
+                                                  &lttng_event_field_value_enum_uint::parent);
                *val = field_val_enum_uint->val;
                break;
        }
@@ -393,8 +378,8 @@ end:
 }
 
 enum lttng_event_field_value_status
-lttng_event_field_value_signed_int_get_value(
-               const struct lttng_event_field_value *field_val, int64_t *val)
+lttng_event_field_value_signed_int_get_value(const struct lttng_event_field_value *field_val,
+                                            int64_t *val)
 {
        enum lttng_event_field_value_status status;
 
@@ -405,17 +390,17 @@ lttng_event_field_value_signed_int_get_value(
 
        switch (field_val->type) {
        case LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT:
-               *val = lttng::utils::container_of(field_val,
-                               &lttng_event_field_value_int::parent)->val;
+               *val = lttng::utils::container_of(field_val, &lttng_event_field_value_int::parent)
+                              ->val;
                break;
        case LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM:
        {
-               const struct lttng_event_field_value_enum *field_val_enum = lttng::utils::container_of(
-                               field_val,
-                               &lttng_event_field_value_enum::parent);
+               const struct lttng_event_field_value_enum *field_val_enum =
+                       lttng::utils::container_of(field_val,
+                                                  &lttng_event_field_value_enum::parent);
                const struct lttng_event_field_value_enum_int *field_val_enum_uint =
-                               lttng::utils::container_of(field_val_enum,
-                                               &lttng_event_field_value_enum_int::parent);
+                       lttng::utils::container_of(field_val_enum,
+                                                  &lttng_event_field_value_enum_int::parent);
                *val = field_val_enum_uint->val;
                break;
        }
@@ -431,36 +416,31 @@ end:
 }
 
 enum lttng_event_field_value_status
-lttng_event_field_value_real_get_value(
-               const struct lttng_event_field_value *field_val, double *val)
+lttng_event_field_value_real_get_value(const struct lttng_event_field_value *field_val, double *val)
 {
        enum lttng_event_field_value_status status;
 
-       if (!field_val || field_val->type != LTTNG_EVENT_FIELD_VALUE_TYPE_REAL ||
-                       !val) {
+       if (!field_val || field_val->type != LTTNG_EVENT_FIELD_VALUE_TYPE_REAL || !val) {
                status = LTTNG_EVENT_FIELD_VALUE_STATUS_INVALID;
                goto end;
        }
 
-       *val = lttng::utils::container_of(field_val,
-                       &lttng_event_field_value_real::parent)->val;
+       *val = lttng::utils::container_of(field_val, &lttng_event_field_value_real::parent)->val;
        status = LTTNG_EVENT_FIELD_VALUE_STATUS_OK;
 
 end:
        return status;
 }
 
-static
-bool is_enum_field_val(const struct lttng_event_field_value *field_val)
+static bool is_enum_field_val(const struct lttng_event_field_value *field_val)
 {
        return field_val->type == LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM ||
                field_val->type == LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM;
 }
 
 enum lttng_event_field_value_status
-lttng_event_field_value_enum_get_label_count(
-               const struct lttng_event_field_value *field_val,
-               unsigned int *count)
+lttng_event_field_value_enum_get_label_count(const struct lttng_event_field_value *field_val,
+                                            unsigned int *count)
 {
        enum lttng_event_field_value_status status;
 
@@ -470,44 +450,44 @@ lttng_event_field_value_enum_get_label_count(
        }
 
        *count = (unsigned int) lttng_dynamic_pointer_array_get_count(
-                       &lttng::utils::container_of(field_val,
-                               &lttng_event_field_value_enum::parent)->labels);
+               &lttng::utils::container_of(field_val, &lttng_event_field_value_enum::parent)
+                        ->labels);
        status = LTTNG_EVENT_FIELD_VALUE_STATUS_OK;
 
 end:
        return status;
 }
 
-const char *lttng_event_field_value_enum_get_label_at_index(
-               const struct lttng_event_field_value *field_val,
-               unsigned int index)
+const char *
+lttng_event_field_value_enum_get_label_at_index(const struct lttng_event_field_value *field_val,
+                                               unsigned int index)
 {
        const char *ret;
        const struct lttng_event_field_value_enum *enum_field_val;
 
        if (!field_val || !is_enum_field_val(field_val)) {
-               ret = NULL;
+               ret = nullptr;
                goto end;
        }
 
-       enum_field_val = lttng::utils::container_of(field_val,
-                       &lttng_event_field_value_enum::parent);
+       enum_field_val =
+               lttng::utils::container_of(field_val, &lttng_event_field_value_enum::parent);
 
        if (index >= lttng_dynamic_pointer_array_get_count(&enum_field_val->labels)) {
-               ret = NULL;
+               ret = nullptr;
                goto end;
        }
 
        ret = (const char *) lttng_dynamic_pointer_array_get_pointer(&enum_field_val->labels,
-                       index);
+                                                                    index);
 
 end:
        return ret;
 }
 
-enum lttng_event_field_value_status lttng_event_field_value_string_get_value(
-               const struct lttng_event_field_value *field_val,
-               const char **value)
+enum lttng_event_field_value_status
+lttng_event_field_value_string_get_value(const struct lttng_event_field_value *field_val,
+                                        const char **value)
 {
        enum lttng_event_field_value_status status;
 
@@ -516,52 +496,50 @@ enum lttng_event_field_value_status lttng_event_field_value_string_get_value(
                goto end;
        }
 
-       *value = lttng::utils::container_of(field_val,
-                       &lttng_event_field_value_string::parent)->val;
+       *value =
+               lttng::utils::container_of(field_val, &lttng_event_field_value_string::parent)->val;
        status = LTTNG_EVENT_FIELD_VALUE_STATUS_OK;
 
 end:
        return status;
 }
 
-enum lttng_event_field_value_status lttng_event_field_value_array_get_length(
-               const struct lttng_event_field_value *field_val,
-               unsigned int *length)
+enum lttng_event_field_value_status
+lttng_event_field_value_array_get_length(const struct lttng_event_field_value *field_val,
+                                        unsigned int *length)
 {
        enum lttng_event_field_value_status status;
 
-       if (!field_val || field_val->type != LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY ||
-                       !length) {
+       if (!field_val || field_val->type != LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY || !length) {
                status = LTTNG_EVENT_FIELD_VALUE_STATUS_INVALID;
                goto end;
        }
 
        *length = (unsigned int) lttng_dynamic_pointer_array_get_count(
-                       &lttng::utils::container_of(field_val,
-                               &lttng_event_field_value_array::parent)->elems);
+               &lttng::utils::container_of(field_val, &lttng_event_field_value_array::parent)
+                        ->elems);
        status = LTTNG_EVENT_FIELD_VALUE_STATUS_OK;
 
 end:
        return status;
 }
 
-enum lttng_event_field_value_status
-lttng_event_field_value_array_get_element_at_index(
-               const struct lttng_event_field_value *field_val,
-               unsigned int index,
-               const struct lttng_event_field_value **elem_field_val)
+enum lttng_event_field_value_status lttng_event_field_value_array_get_element_at_index(
+       const struct lttng_event_field_value *field_val,
+       unsigned int index,
+       const struct lttng_event_field_value **elem_field_val)
 {
        enum lttng_event_field_value_status status;
        const struct lttng_event_field_value_array *array_field_val;
 
        if (!field_val || field_val->type != LTTNG_EVENT_FIELD_VALUE_TYPE_ARRAY ||
-                       !elem_field_val) {
+           !elem_field_val) {
                status = LTTNG_EVENT_FIELD_VALUE_STATUS_INVALID;
                goto end;
        }
 
-       array_field_val = lttng::utils::container_of(
-                       field_val, &lttng_event_field_value_array::parent);
+       array_field_val =
+               lttng::utils::container_of(field_val, &lttng_event_field_value_array::parent);
 
        if (index >= lttng_dynamic_pointer_array_get_count(&array_field_val->elems)) {
                status = LTTNG_EVENT_FIELD_VALUE_STATUS_INVALID;
@@ -569,7 +547,7 @@ lttng_event_field_value_array_get_element_at_index(
        }
 
        *elem_field_val = (lttng_event_field_value *) lttng_dynamic_pointer_array_get_pointer(
-                       &array_field_val->elems, index);
+               &array_field_val->elems, index);
        if (*elem_field_val) {
                status = LTTNG_EVENT_FIELD_VALUE_STATUS_OK;
        } else {
index 5139eed5a6dbc44daac914f703fc8ca127c1790c..3e862b2464cd54e35ea4569b9103fc27971c2011 100644 (file)
@@ -13,6 +13,7 @@
 #include <common/mi-lttng.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/jul-logging-internal.hpp>
 #include <lttng/event-rule/kernel-kprobe-internal.hpp>
 #include <lttng/event-rule/log4j-logging-internal.hpp>
 #include <lttng/event-rule/python-logging-internal.hpp>
 #include <lttng/event-rule/user-tracepoint-internal.hpp>
+
 #include <stdbool.h>
 
-enum lttng_event_rule_type lttng_event_rule_get_type(
-               const struct lttng_event_rule *event_rule)
+enum lttng_event_rule_type lttng_event_rule_get_type(const struct lttng_event_rule *event_rule)
 {
        return event_rule ? event_rule->type : LTTNG_EVENT_RULE_TYPE_UNKNOWN;
 }
 
-enum lttng_domain_type lttng_event_rule_get_domain_type(
-               const struct lttng_event_rule *event_rule)
+enum lttng_domain_type lttng_event_rule_get_domain_type(const struct lttng_event_rule *event_rule)
 {
        enum lttng_domain_type domain_type = LTTNG_DOMAIN_NONE;
 
@@ -65,7 +65,7 @@ enum lttng_domain_type lttng_event_rule_get_domain_type(
 static void lttng_event_rule_release(struct urcu_ref *ref)
 {
        struct lttng_event_rule *event_rule =
-                       lttng::utils::container_of(ref, &lttng_event_rule::ref);
+               lttng::utils::container_of(ref, &lttng_event_rule::ref);
 
        LTTNG_ASSERT(event_rule->destroy);
        event_rule->destroy(event_rule);
@@ -97,7 +97,7 @@ end:
 }
 
 int lttng_event_rule_serialize(const struct lttng_event_rule *event_rule,
-               struct lttng_payload *payload)
+                              struct lttng_payload *payload)
 {
        int ret;
        struct lttng_event_rule_comm event_rule_comm = {};
@@ -110,7 +110,7 @@ int lttng_event_rule_serialize(const struct lttng_event_rule *event_rule,
        event_rule_comm.event_rule_type = (int8_t) event_rule->type;
 
        ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &event_rule_comm, sizeof(event_rule_comm));
+               &payload->buffer, &event_rule_comm, sizeof(event_rule_comm));
        if (ret) {
                goto end;
        }
@@ -123,8 +123,7 @@ end:
        return ret;
 }
 
-bool lttng_event_rule_is_equal(const struct lttng_event_rule *a,
-               const struct lttng_event_rule *b)
+bool lttng_event_rule_is_equal(const struct lttng_event_rule *a, const struct lttng_event_rule *b)
 {
        bool is_equal = false;
 
@@ -146,16 +145,14 @@ end:
        return is_equal;
 }
 
-ssize_t lttng_event_rule_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **event_rule)
+ssize_t lttng_event_rule_create_from_payload(struct lttng_payload_view *view,
+                                            struct lttng_event_rule **event_rule)
 {
        ssize_t ret, consumed = 0;
-       event_rule_create_from_payload_cb create_from_payload = NULL;
+       event_rule_create_from_payload_cb create_from_payload = nullptr;
        const struct lttng_event_rule_comm *event_rule_comm;
        const struct lttng_payload_view event_rule_comm_view =
-                       lttng_payload_view_from_view(
-                                       view, 0, sizeof(*event_rule_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*event_rule_comm));
 
        if (!view || !event_rule) {
                ret = -1;
@@ -179,32 +176,26 @@ ssize_t lttng_event_rule_create_from_payload(
                create_from_payload = lttng_event_rule_kernel_uprobe_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL:
-               create_from_payload =
-                               lttng_event_rule_kernel_syscall_create_from_payload;
+               create_from_payload = lttng_event_rule_kernel_syscall_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT:
-               create_from_payload =
-                               lttng_event_rule_kernel_tracepoint_create_from_payload;
+               create_from_payload = lttng_event_rule_kernel_tracepoint_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT:
-               create_from_payload =
-                               lttng_event_rule_user_tracepoint_create_from_payload;
+               create_from_payload = lttng_event_rule_user_tracepoint_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_JUL_LOGGING:
-               create_from_payload =
-                               lttng_event_rule_jul_logging_create_from_payload;
+               create_from_payload = lttng_event_rule_jul_logging_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING:
-               create_from_payload =
-                               lttng_event_rule_log4j_logging_create_from_payload;
+               create_from_payload = lttng_event_rule_log4j_logging_create_from_payload;
                break;
        case LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING:
-               create_from_payload =
-                               lttng_event_rule_python_logging_create_from_payload;
+               create_from_payload = lttng_event_rule_python_logging_create_from_payload;
                break;
        default:
                ERR("Attempted to create event rule of unknown type (%i)",
-                               (int) event_rule_comm->event_rule_type);
+                   (int) event_rule_comm->event_rule_type);
                ret = -1;
                goto end;
        }
@@ -213,8 +204,7 @@ ssize_t lttng_event_rule_create_from_payload(
 
        {
                struct lttng_payload_view child_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
                ret = create_from_payload(&child_view, event_rule);
                if (ret < 0) {
@@ -234,8 +224,7 @@ end:
        return ret;
 }
 
-void lttng_event_rule_init(struct lttng_event_rule *event_rule,
-               enum lttng_event_rule_type type)
+void lttng_event_rule_init(struct lttng_event_rule *event_rule, enum lttng_event_rule_type type)
 {
        urcu_ref_init(&event_rule->ref);
        event_rule->type = type;
@@ -256,9 +245,9 @@ void lttng_event_rule_put(struct lttng_event_rule *event_rule)
        urcu_ref_put(&event_rule->ref, lttng_event_rule_release);
 }
 
-enum lttng_error_code lttng_event_rule_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+enum lttng_error_code
+lttng_event_rule_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                         const struct lttng_credentials *creds)
 {
        LTTNG_ASSERT(rule->generate_filter_bytecode);
        return rule->generate_filter_bytecode(rule, creds);
@@ -270,8 +259,8 @@ const char *lttng_event_rule_get_filter(const struct lttng_event_rule *rule)
        return rule->get_filter(rule);
 }
 
-const struct lttng_bytecode *lttng_event_rule_get_filter_bytecode(
-               const struct lttng_event_rule *rule)
+const struct lttng_bytecode *
+lttng_event_rule_get_filter_bytecode(const struct lttng_event_rule *rule)
 {
        LTTNG_ASSERT(rule->get_filter_bytecode);
        return rule->get_filter_bytecode(rule);
@@ -279,14 +268,13 @@ const struct lttng_bytecode *lttng_event_rule_get_filter_bytecode(
 
 enum lttng_event_rule_generate_exclusions_status
 lttng_event_rule_generate_exclusions(const struct lttng_event_rule *rule,
-               struct lttng_event_exclusion **exclusions)
+                                    struct lttng_event_exclusion **exclusions)
 {
        LTTNG_ASSERT(rule->generate_exclusions);
        return rule->generate_exclusions(rule, exclusions);
 }
 
-struct lttng_event *lttng_event_rule_generate_lttng_event(
-               const struct lttng_event_rule *rule)
+struct lttng_event *lttng_event_rule_generate_lttng_event(const struct lttng_event_rule *rule)
 {
        LTTNG_ASSERT(rule->generate_lttng_event);
        return rule->generate_lttng_event(rule);
@@ -347,8 +335,8 @@ unsigned long lttng_event_rule_hash(const struct lttng_event_rule *rule)
        return rule->hash(rule);
 }
 
-enum lttng_error_code lttng_event_rule_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+enum lttng_error_code lttng_event_rule_mi_serialize(const struct lttng_event_rule *rule,
+                                                   struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
index 138d9c1020dbcfbda13e5412def50f8dc4bc2f6b..97876cd35ef782690435316dd1b35f45bdecfc18 100644 (file)
@@ -16,6 +16,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/jul-logging-internal.hpp>
 #include <lttng/event.h>
@@ -28,12 +29,11 @@ static void lttng_event_rule_jul_logging_destroy(struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        lttng_log_level_rule_destroy(jul_logging->log_level_rule);
        free(jul_logging->pattern);
@@ -43,8 +43,7 @@ static void lttng_event_rule_jul_logging_destroy(struct lttng_event_rule *rule)
        free(jul_logging);
 }
 
-static bool lttng_event_rule_jul_logging_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_jul_logging_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_jul_logging *jul_logging;
@@ -53,8 +52,7 @@ static bool lttng_event_rule_jul_logging_validate(
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        /* Required field. */
        if (!jul_logging->pattern) {
@@ -67,9 +65,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_jul_logging_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_jul_logging_serialize(const struct lttng_event_rule *rule,
+                                                 struct lttng_payload *payload)
 {
        int ret;
        size_t pattern_len, filter_expression_len, header_offset;
@@ -86,14 +83,12 @@ static int lttng_event_rule_jul_logging_serialize(
        header_offset = payload->buffer.size;
 
        DBG("Serializing jul_logging event rule.");
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        pattern_len = strlen(jul_logging->pattern) + 1;
 
-       if (jul_logging->filter_expression != NULL) {
-               filter_expression_len =
-                               strlen(jul_logging->filter_expression) + 1;
+       if (jul_logging->filter_expression != nullptr) {
+               filter_expression_len = strlen(jul_logging->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
        }
@@ -101,20 +96,19 @@ static int lttng_event_rule_jul_logging_serialize(
        jul_logging_comm.pattern_len = pattern_len;
        jul_logging_comm.filter_expression_len = filter_expression_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &jul_logging_comm,
-                       sizeof(jul_logging_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &jul_logging_comm, sizeof(jul_logging_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, jul_logging->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, jul_logging->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, jul_logging->filter_expression,
-                       filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, jul_logging->filter_expression, filter_expression_len);
        if (ret) {
                goto end;
        }
@@ -127,16 +121,14 @@ static int lttng_event_rule_jul_logging_serialize(
        }
 
        header = (typeof(header)) ((char *) payload->buffer.data + header_offset);
-       header->log_level_rule_len =
-                       payload->buffer.size - size_before_log_level_rule;
+       header->log_level_rule_len = payload->buffer.size - size_before_log_level_rule;
 
 end:
        return ret;
 }
 
-static bool lttng_event_rule_jul_logging_is_equal(
-               const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+static bool lttng_event_rule_jul_logging_is_equal(const struct lttng_event_rule *_a,
+                                                 const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_jul_logging *a, *b;
@@ -153,12 +145,12 @@ static bool lttng_event_rule_jul_logging_is_equal(
        /* Long check. */
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -166,8 +158,7 @@ static bool lttng_event_rule_jul_logging_is_equal(
                goto end;
        }
 
-       if (!lttng_log_level_rule_is_equal(
-                               a->log_level_rule, b->log_level_rule)) {
+       if (!lttng_log_level_rule_is_equal(a->log_level_rule, b->log_level_rule)) {
                goto end;
        }
 
@@ -183,15 +174,14 @@ end:
  *
  * An event with NO loglevel and the name is * will return NULL.
  */
-static int generate_agent_filter(
-               const struct lttng_event_rule *rule, char **_agent_filter)
+static int generate_agent_filter(const struct lttng_event_rule *rule, char **_agent_filter)
 {
        int err;
        int ret = 0;
-       char *agent_filter = NULL;
+       char *agent_filter = nullptr;
        const char *pattern;
        const char *filter;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
        enum lttng_event_rule_status status;
 
        LTTNG_ASSERT(rule);
@@ -205,22 +195,19 @@ static int generate_agent_filter(
 
        status = lttng_event_rule_jul_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
-
        /* Don't add filter for the '*' event. */
        if (strcmp(pattern, "*") != 0) {
                if (filter) {
-                       err = asprintf(&agent_filter,
-                                       "(%s) && (logger_name == \"%s\")",
-                                       filter, pattern);
+                       err = asprintf(
+                               &agent_filter, "(%s) && (logger_name == \"%s\")", filter, pattern);
                } else {
-                       err = asprintf(&agent_filter, "logger_name == \"%s\"",
-                                       pattern);
+                       err = asprintf(&agent_filter, "logger_name == \"%s\"", pattern);
                }
 
                if (err < 0) {
@@ -230,23 +217,20 @@ static int generate_agent_filter(
                }
        }
 
-       status = lttng_event_rule_jul_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_jul_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
                const char *op;
                int level;
 
-               switch (lttng_log_level_rule_get_type(log_level_rule))
-               {
+               switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &level);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule, &level);
                        op = "==";
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &level);
+                               log_level_rule, &level);
                        op = ">=";
                        break;
                default:
@@ -262,16 +246,16 @@ static int generate_agent_filter(
                        char *new_filter;
 
                        err = asprintf(&new_filter,
-                                       "(%s) && (int_loglevel %s %d)",
-                                       agent_filter ? agent_filter : filter,
-                                       op, level);
+                                      "(%s) && (int_loglevel %s %d)",
+                                      agent_filter ? agent_filter : filter,
+                                      op,
+                                      level);
                        if (agent_filter) {
                                free(agent_filter);
                        }
                        agent_filter = new_filter;
                } else {
-                       err = asprintf(&agent_filter, "int_loglevel %s %d", op,
-                                       level);
+                       err = asprintf(&agent_filter, "int_loglevel %s %d", op, level);
                }
 
                if (err < 0) {
@@ -282,7 +266,7 @@ static int generate_agent_filter(
        }
 
        *_agent_filter = agent_filter;
-       agent_filter = NULL;
+       agent_filter = nullptr;
 
 end:
        free(agent_filter);
@@ -290,26 +274,24 @@ end:
 }
 
 static enum lttng_error_code
-lttng_event_rule_jul_logging_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+lttng_event_rule_jul_logging_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                     const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        char *agent_filter;
 
        LTTNG_ASSERT(rule);
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        status = lttng_event_rule_jul_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -328,21 +310,20 @@ lttng_event_rule_jul_logging_generate_filter_bytecode(
 
        jul_logging->internal_filter.filter = agent_filter;
 
-       if (jul_logging->internal_filter.filter == NULL) {
+       if (jul_logging->internal_filter.filter == nullptr) {
                ret_code = LTTNG_OK;
                goto end;
        }
 
        ret = run_as_generate_filter_bytecode(
-                       jul_logging->internal_filter.filter, creds,
-                       &bytecode);
+               jul_logging->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
        }
 
        jul_logging->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
        ret_code = LTTNG_OK;
 
 error:
@@ -351,48 +332,43 @@ end:
        return ret_code;
 }
 
-static const char *lttng_event_rule_jul_logging_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_jul_logging_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
 
        LTTNG_ASSERT(rule);
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        return jul_logging->internal_filter.filter;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_jul_logging_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_jul_logging_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
 
        LTTNG_ASSERT(rule);
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        return jul_logging->internal_filter.bytecode;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_jul_logging_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **_exclusions)
+lttng_event_rule_jul_logging_generate_exclusions(const struct lttng_event_rule *rule
+                                                __attribute__((unused)),
+                                                struct lttng_event_exclusion **_exclusions)
 {
        /* Unsupported. */
-       *_exclusions = NULL;
+       *_exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long lttng_event_rule_jul_logging_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_jul_logging_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_jul_logging *tp_rule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_JUL_LOGGING,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_JUL_LOGGING, lttng_ht_seed);
        hash ^= hash_key_str(tp_rule->pattern, lttng_ht_seed);
 
        if (tp_rule->filter_expression) {
@@ -406,20 +382,19 @@ static unsigned long lttng_event_rule_jul_logging_hash(
        return hash;
 }
 
-static struct lttng_event *lttng_event_rule_jul_logging_generate_lttng_event(
-               const struct lttng_event_rule *rule)
+static struct lttng_event *
+lttng_event_rule_jul_logging_generate_lttng_event(const struct lttng_event_rule *rule)
 {
        int ret;
        const struct lttng_event_rule_jul_logging *jul_logging;
-       struct lttng_event *local_event = NULL;
-       struct lttng_event *event = NULL;
+       struct lttng_event *local_event = nullptr;
+       struct lttng_event *event = nullptr;
        enum lttng_loglevel_type loglevel_type;
        int loglevel_value = 0;
        enum lttng_event_rule_status status;
        const struct lttng_log_level_rule *log_level_rule;
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        local_event = zmalloc<lttng_event>();
        if (!local_event) {
@@ -427,33 +402,30 @@ static struct lttng_event *lttng_event_rule_jul_logging_generate_lttng_event(
        }
 
        local_event->type = LTTNG_EVENT_TRACEPOINT;
-       ret = lttng_strncpy(local_event->name, jul_logging->pattern,
-                           sizeof(local_event->name));
+       ret = lttng_strncpy(local_event->name, jul_logging->pattern, sizeof(local_event->name));
        if (ret) {
                ERR("Truncation occurred when copying event rule pattern to `lttng_event` structure: pattern = '%s'",
-                               jul_logging->pattern);
+                   jul_logging->pattern);
                goto error;
        }
 
-
        /* Map the log level rule to an equivalent lttng_loglevel. */
-       status = lttng_event_rule_jul_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_jul_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
                loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               loglevel_value = 0;
+               loglevel_value = LTTNG_LOGLEVEL_JUL_ALL;
        } else if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
 
                switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &loglevel_value);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule,
+                                                                           &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_SINGLE;
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &loglevel_value);
+                               log_level_rule, &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_RANGE;
                        break;
                default:
@@ -472,60 +444,57 @@ static struct lttng_event *lttng_event_rule_jul_logging_generate_lttng_event(
        local_event->loglevel = loglevel_value;
 
        event = local_event;
-       local_event = NULL;
+       local_event = nullptr;
 error:
        free(local_event);
        return event;
 }
 
-static enum lttng_error_code lttng_event_rule_jul_logging_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_jul_logging_mi_serialize(const struct lttng_event_rule *rule,
+                                         struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
 
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_JUL_LOGGING_EVENT_RULE(rule));
 
-       status = lttng_event_rule_jul_logging_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_jul_logging_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_jul_logging_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
-       status = lttng_event_rule_jul_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_jul_logging_get_log_level_rule(rule, &log_level_rule);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        /* Open event rule jul logging element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_jul_logging);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_jul_logging);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter expression. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -533,8 +502,7 @@ static enum lttng_error_code lttng_event_rule_jul_logging_mi_serialize(
 
        /* Log level rule. */
        if (log_level_rule) {
-               ret_code = lttng_log_level_rule_mi_serialize(
-                               log_level_rule, writer);
+               ret_code = lttng_log_level_rule_mi_serialize(log_level_rule, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
@@ -557,7 +525,7 @@ end:
 
 struct lttng_event_rule *lttng_event_rule_jul_logging_create(void)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_jul_logging *tp_rule;
        enum lttng_event_rule_status status;
 
@@ -573,51 +541,47 @@ struct lttng_event_rule *lttng_event_rule_jul_logging_create(void)
        tp_rule->parent.equal = lttng_event_rule_jul_logging_is_equal;
        tp_rule->parent.destroy = lttng_event_rule_jul_logging_destroy;
        tp_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_jul_logging_generate_filter_bytecode;
-       tp_rule->parent.get_filter =
-                       lttng_event_rule_jul_logging_get_internal_filter;
+               lttng_event_rule_jul_logging_generate_filter_bytecode;
+       tp_rule->parent.get_filter = lttng_event_rule_jul_logging_get_internal_filter;
        tp_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_jul_logging_get_internal_filter_bytecode;
-       tp_rule->parent.generate_exclusions =
-                       lttng_event_rule_jul_logging_generate_exclusions;
+               lttng_event_rule_jul_logging_get_internal_filter_bytecode;
+       tp_rule->parent.generate_exclusions = lttng_event_rule_jul_logging_generate_exclusions;
        tp_rule->parent.hash = lttng_event_rule_jul_logging_hash;
-       tp_rule->parent.generate_lttng_event =
-                       lttng_event_rule_jul_logging_generate_lttng_event;
+       tp_rule->parent.generate_lttng_event = lttng_event_rule_jul_logging_generate_lttng_event;
        tp_rule->parent.mi_serialize = lttng_event_rule_jul_logging_mi_serialize;
 
-       tp_rule->log_level_rule = NULL;
+       tp_rule->log_level_rule = nullptr;
 
        /* Default pattern is '*'. */
        status = lttng_event_rule_jul_logging_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_jul_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_jul_logging_create_from_payload(struct lttng_payload_view *view,
+                                                        struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_jul_logging_comm *jul_logging_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
+       const char *filter_expression = nullptr;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_log_level_rule *log_level_rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*jul_logging_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*jul_logging_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule jul_logging: buffer too short to contain header.");
                ret = -1;
@@ -637,8 +601,8 @@ ssize_t lttng_event_rule_jul_logging_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the pattern. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, jul_logging_comm->pattern_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, jul_logging_comm->pattern_len);
 
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
@@ -646,8 +610,8 @@ ssize_t lttng_event_rule_jul_logging_create_from_payload(
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       jul_logging_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, jul_logging_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -660,8 +624,8 @@ ssize_t lttng_event_rule_jul_logging_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       jul_logging_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, jul_logging_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
@@ -669,8 +633,8 @@ ssize_t lttng_event_rule_jul_logging_create_from_payload(
 
        filter_expression = current_buffer_view.data;
        if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                       filter_expression,
-                       jul_logging_comm->filter_expression_len)) {
+                                              filter_expression,
+                                              jul_logging_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -685,12 +649,11 @@ skip_filter_expression:
 
        {
                /* Map the log level rule. */
-               struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               jul_logging_comm->log_level_rule_len);
+               struct lttng_payload_view current_payload_view = lttng_payload_view_from_view(
+                       view, offset, jul_logging_comm->log_level_rule_len);
 
-               ret = lttng_log_level_rule_create_from_payload(
-                               &current_payload_view, &log_level_rule);
+               ret = lttng_log_level_rule_create_from_payload(&current_payload_view,
+                                                              &log_level_rule);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -712,8 +675,7 @@ skip_log_level_rule:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_jul_logging_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_jul_logging_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule jul_logging pattern.");
                        ret = -1;
@@ -722,8 +684,7 @@ skip_log_level_rule:
        }
 
        if (log_level_rule) {
-               status = lttng_event_rule_jul_logging_set_log_level_rule(
-                               rule, log_level_rule);
+               status = lttng_event_rule_jul_logging_set_log_level_rule(rule, log_level_rule);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule jul_logging log level rule.");
                        ret = -1;
@@ -732,7 +693,7 @@ skip_log_level_rule:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_log_level_rule_destroy(log_level_rule);
@@ -740,21 +701,19 @@ end:
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_jul_logging_set_name_pattern(struct lttng_event_rule *rule, const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_JUL_LOGGING_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_JUL_LOGGING_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        pattern_copy = strdup(pattern);
        if (!pattern_copy) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
@@ -767,13 +726,14 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_set_name_pattern(
        free(jul_logging->pattern);
 
        jul_logging->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_jul_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                             const char **pattern)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -783,8 +743,7 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_get_name_pattern(
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        if (!jul_logging->pattern) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -795,21 +754,19 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status lttng_event_rule_jul_logging_set_filter(struct lttng_event_rule *rule,
+                                                                    const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_JUL_LOGGING_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+       if (!rule || !IS_JUL_LOGGING_EVENT_RULE(rule) || !expression || strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        expression_copy = strdup(expression);
        if (!expression_copy) {
                PERROR("Failed to copy filter expression");
@@ -822,13 +779,14 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_set_filter(
        }
 
        jul_logging->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_jul_logging_get_filter(const struct lttng_event_rule *rule,
+                                       const char **expression)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -838,8 +796,7 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_get_filter(
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
        if (!jul_logging->filter_expression) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -850,8 +807,7 @@ end:
        return status;
 }
 
-static bool log_level_rule_valid(
-               const struct lttng_log_level_rule *rule __attribute__((unused)))
+static bool log_level_rule_valid(const struct lttng_log_level_rule *rule __attribute__((unused)))
 {
        /*
         * For both JUL and LOG4J custom log level are possible and can
@@ -860,21 +816,20 @@ static bool log_level_rule_valid(
        return true;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_set_log_level_rule(
-               struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule)
+enum lttng_event_rule_status
+lttng_event_rule_jul_logging_set_log_level_rule(struct lttng_event_rule *rule,
+                                               const struct lttng_log_level_rule *log_level_rule)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
-       struct lttng_log_level_rule *copy = NULL;
+       struct lttng_log_level_rule *copy = nullptr;
 
        if (!rule || !IS_JUL_LOGGING_EVENT_RULE(rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
 
        if (!log_level_rule_valid(log_level_rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
@@ -882,7 +837,7 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_set_log_level_rule(
        }
 
        copy = lttng_log_level_rule_copy(log_level_rule);
-       if (copy == NULL) {
+       if (copy == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
                goto end;
        }
@@ -897,10 +852,9 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_jul_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule
-               )
+enum lttng_event_rule_status
+lttng_event_rule_jul_logging_get_log_level_rule(const struct lttng_event_rule *rule,
+                                               const struct lttng_log_level_rule **log_level_rule)
 {
        struct lttng_event_rule_jul_logging *jul_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -910,9 +864,8 @@ enum lttng_event_rule_status lttng_event_rule_jul_logging_get_log_level_rule(
                goto end;
        }
 
-       jul_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_jul_logging::parent);
-       if (jul_logging->log_level_rule == NULL) {
+       jul_logging = lttng::utils::container_of(rule, &lttng_event_rule_jul_logging::parent);
+       if (jul_logging->log_level_rule == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
        }
index 239373aa90136f21bcaf5a885cb2deb8b0de9587..bae7bdfa78380ac0e224cffae54ca77aee58d4a0 100644 (file)
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
 #include <common/runas.hpp>
-#include <ctype.h>
+
 #include <lttng/constant.h>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/event-rule.h>
 #include <lttng/event-rule/kernel-kprobe-internal.hpp>
 #include <lttng/kernel-probe-internal.hpp>
 #include <lttng/kernel-probe.h>
+
+#include <ctype.h>
 #include <stdio.h>
 
 #define IS_KPROBE_EVENT_RULE(rule) \
@@ -41,8 +43,7 @@ static void lttng_event_rule_kernel_kprobe_destroy(struct lttng_event_rule *rule
        free(kprobe);
 }
 
-static bool lttng_event_rule_kernel_kprobe_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_kernel_kprobe_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_kernel_kprobe *kprobe;
@@ -60,7 +61,7 @@ static bool lttng_event_rule_kernel_kprobe_validate(
        }
 
        /* Required field. */
-       if(!kprobe->location) {
+       if (!kprobe->location) {
                ERR("Invalid name event rule: a location must be set.");
                goto end;
        }
@@ -70,9 +71,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_kernel_kprobe_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_kernel_kprobe_serialize(const struct lttng_event_rule *rule,
+                                                   struct lttng_payload *payload)
 {
        int ret;
        size_t name_len, header_offset, size_before_location;
@@ -93,8 +93,7 @@ static int lttng_event_rule_kernel_kprobe_serialize(
        name_len = strlen(kprobe->name) + 1;
        kprobe_comm.name_len = name_len;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &kprobe_comm, sizeof(kprobe_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &kprobe_comm, sizeof(kprobe_comm));
        if (ret) {
                goto end;
        }
@@ -112,8 +111,8 @@ static int lttng_event_rule_kernel_kprobe_serialize(
        }
 
        /* Update the header regarding the probe size. */
-       header = (struct lttng_event_rule_kernel_kprobe_comm*) (
-                       (char *) payload->buffer.data + header_offset);
+       header = (struct lttng_event_rule_kernel_kprobe_comm *) ((char *) payload->buffer.data +
+                                                                header_offset);
        header->location_len = payload->buffer.size - size_before_location;
 
        ret = 0;
@@ -123,7 +122,7 @@ end:
 }
 
 static bool lttng_event_rule_kernel_kprobe_is_equal(const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+                                                   const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_kernel_kprobe *a, *b;
@@ -139,72 +138,66 @@ static bool lttng_event_rule_kernel_kprobe_is_equal(const struct lttng_event_rul
        /* Long check */
        LTTNG_ASSERT(a->name);
        LTTNG_ASSERT(b->name);
-       if (strcmp(a->name, b->name)) {
+       if (strcmp(a->name, b->name) != 0) {
                goto end;
        }
 
-       is_equal = lttng_kernel_probe_location_is_equal(
-                       a->location, b->location);
+       is_equal = lttng_kernel_probe_location_is_equal(a->location, b->location);
 end:
        return is_equal;
 }
 
 static enum lttng_error_code lttng_event_rule_kernel_kprobe_generate_filter_bytecode(
-               struct lttng_event_rule *rule __attribute__((unused)),
-               const struct lttng_credentials *creds __attribute__((unused)))
+       struct lttng_event_rule *rule __attribute__((unused)),
+       const struct lttng_credentials *creds __attribute__((unused)))
 {
        /* Nothing to do. */
        return LTTNG_OK;
 }
 
-static const char *lttng_event_rule_kernel_kprobe_get_filter(
-               const struct lttng_event_rule *rule __attribute__((unused)))
+static const char *lttng_event_rule_kernel_kprobe_get_filter(const struct lttng_event_rule *rule
+                                                            __attribute__((unused)))
 {
        /* Not supported. */
-       return NULL;
+       return nullptr;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_kernel_kprobe_get_filter_bytecode(
-               const struct lttng_event_rule *rule __attribute__((unused)))
+lttng_event_rule_kernel_kprobe_get_filter_bytecode(const struct lttng_event_rule *rule
+                                                  __attribute__((unused)))
 {
        /* Not supported. */
-       return NULL;
+       return nullptr;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_kernel_kprobe_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **exclusions)
+lttng_event_rule_kernel_kprobe_generate_exclusions(const struct lttng_event_rule *rule
+                                                  __attribute__((unused)),
+                                                  struct lttng_event_exclusion **exclusions)
 {
        /* Not supported. */
-       *exclusions = NULL;
+       *exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long
-lttng_event_rule_kernel_kprobe_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_kernel_kprobe_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_kernel_kprobe *krule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_kernel_kprobe::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_kernel_kprobe::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_KPROBE,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_KPROBE, lttng_ht_seed);
        hash ^= hash_key_str(krule->name, lttng_ht_seed);
        hash ^= lttng_kernel_probe_location_hash(krule->location);
 
        return hash;
 }
 
-static
-int kernel_probe_set_location(
-               struct lttng_event_rule_kernel_kprobe *kprobe,
-               const struct lttng_kernel_probe_location *location)
+static int kernel_probe_set_location(struct lttng_event_rule_kernel_kprobe *kprobe,
+                                    const struct lttng_kernel_probe_location *location)
 {
        int ret;
-       struct lttng_kernel_probe_location *location_copy = NULL;
+       struct lttng_kernel_probe_location *location_copy = nullptr;
 
        if (!kprobe || !location || kprobe->location) {
                ret = -1;
@@ -218,29 +211,28 @@ int kernel_probe_set_location(
        }
 
        kprobe->location = location_copy;
-       location_copy = NULL;
+       location_copy = nullptr;
        ret = 0;
 end:
        lttng_kernel_probe_location_destroy(location_copy);
        return ret;
 }
 
-static
-enum lttng_error_code lttng_event_rule_kernel_kprobe_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_kernel_kprobe_mi_serialize(const struct lttng_event_rule *rule,
+                                           struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *event_name = NULL;
-       const struct lttng_kernel_probe_location *location = NULL;
+       const char *event_name = nullptr;
+       const struct lttng_kernel_probe_location *location = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_KPROBE_EVENT_RULE(rule));
 
-       status = lttng_event_rule_kernel_kprobe_get_event_name(
-                       rule, &event_name);
+       status = lttng_event_rule_kernel_kprobe_get_event_name(rule, &event_name);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(event_name);
 
@@ -249,15 +241,14 @@ enum lttng_error_code lttng_event_rule_kernel_kprobe_mi_serialize(
        LTTNG_ASSERT(location);
 
        /* Open event rule kernel kprobe element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_kernel_kprobe);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_kernel_kprobe);
        if (ret) {
                goto mi_error;
        }
 
        /* Name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_event_name, event_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_event_name, event_name);
        if (ret) {
                goto mi_error;
        }
@@ -283,10 +274,10 @@ end:
        return ret_code;
 }
 
-struct lttng_event_rule *lttng_event_rule_kernel_kprobe_create(
-               const struct lttng_kernel_probe_location *location)
+struct lttng_event_rule *
+lttng_event_rule_kernel_kprobe_create(const struct lttng_kernel_probe_location *location)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_kernel_kprobe *krule;
 
        krule = zmalloc<lttng_event_rule_kernel_kprobe>();
@@ -301,43 +292,40 @@ struct lttng_event_rule *lttng_event_rule_kernel_kprobe_create(
        krule->parent.equal = lttng_event_rule_kernel_kprobe_is_equal;
        krule->parent.destroy = lttng_event_rule_kernel_kprobe_destroy;
        krule->parent.generate_filter_bytecode =
-                       lttng_event_rule_kernel_kprobe_generate_filter_bytecode;
+               lttng_event_rule_kernel_kprobe_generate_filter_bytecode;
        krule->parent.get_filter = lttng_event_rule_kernel_kprobe_get_filter;
-       krule->parent.get_filter_bytecode =
-                       lttng_event_rule_kernel_kprobe_get_filter_bytecode;
-       krule->parent.generate_exclusions =
-                       lttng_event_rule_kernel_kprobe_generate_exclusions;
+       krule->parent.get_filter_bytecode = lttng_event_rule_kernel_kprobe_get_filter_bytecode;
+       krule->parent.generate_exclusions = lttng_event_rule_kernel_kprobe_generate_exclusions;
        krule->parent.hash = lttng_event_rule_kernel_kprobe_hash;
        krule->parent.mi_serialize = lttng_event_rule_kernel_kprobe_mi_serialize;
 
        if (kernel_probe_set_location(krule, location)) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_kernel_kprobe_comm *kprobe_comm;
        const char *name;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_kernel_probe_location *location = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_kernel_probe_location *location = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*kprobe_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*kprobe_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule kprobe: buffer too short to contain header.");
                ret = -1;
@@ -352,8 +340,7 @@ ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
        {
                /* Map the name. */
                struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               kprobe_comm->name_len);
+                       lttng_payload_view_from_view(view, offset, kprobe_comm->name_len);
 
                if (!lttng_payload_view_is_valid(&current_payload_view)) {
                        ret = -1;
@@ -362,8 +349,7 @@ ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
 
                name = current_payload_view.buffer.data;
                if (!lttng_buffer_view_contains_string(
-                               &current_payload_view.buffer, name,
-                               kprobe_comm->name_len)) {
+                           &current_payload_view.buffer, name, kprobe_comm->name_len)) {
                        ret = -1;
                        goto end;
                }
@@ -375,16 +361,15 @@ ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
        /* Map the kernel probe location. */
        {
                struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               kprobe_comm->location_len);
+                       lttng_payload_view_from_view(view, offset, kprobe_comm->location_len);
 
                if (!lttng_payload_view_is_valid(&current_payload_view)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_kernel_probe_location_create_from_payload(
-                               &current_payload_view, &location);
+               ret = lttng_kernel_probe_location_create_from_payload(&current_payload_view,
+                                                                     &location);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -414,7 +399,7 @@ ssize_t lttng_event_rule_kernel_kprobe_create_from_payload(
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_kernel_probe_location_destroy(location);
@@ -422,9 +407,9 @@ end:
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_get_location(
-               const struct lttng_event_rule *rule,
-               const struct lttng_kernel_probe_location **location)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_get_location(const struct lttng_event_rule *rule,
+                                           const struct lttng_kernel_probe_location **location)
 {
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
        struct lttng_event_rule_kernel_kprobe *kprobe;
@@ -446,15 +431,14 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_set_event_name(
-               struct lttng_event_rule *rule, const char *name)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_set_event_name(struct lttng_event_rule *rule, const char *name)
 {
-       char *name_copy = NULL;
+       char *name_copy = nullptr;
        struct lttng_event_rule_kernel_kprobe *kprobe;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_KPROBE_EVENT_RULE(rule) || !name ||
-                       strlen(name) == 0) {
+       if (!rule || !IS_KPROBE_EVENT_RULE(rule) || !name || strlen(name) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
@@ -469,13 +453,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_set_event_name(
        free(kprobe->name);
 
        kprobe->name = name_copy;
-       name_copy = NULL;
+       name_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_kprobe_get_event_name(
-               const struct lttng_event_rule *rule, const char **name)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_kprobe_get_event_name(const struct lttng_event_rule *rule,
+                                             const char **name)
 {
        struct lttng_event_rule_kernel_kprobe *kprobe;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
index 633c4698b3558e1b823005f66fb9338de59648bc..23a432aacaaff285e6f0e3cb735d8cb1b4b3f26a 100644 (file)
@@ -15,6 +15,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-syscall-internal.hpp>
 
@@ -25,7 +26,7 @@ static void lttng_event_rule_kernel_syscall_destroy(struct lttng_event_rule *rul
 {
        struct lttng_event_rule_kernel_syscall *syscall;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
@@ -38,8 +39,7 @@ static void lttng_event_rule_kernel_syscall_destroy(struct lttng_event_rule *rul
        free(syscall);
 }
 
-static bool lttng_event_rule_kernel_syscall_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_kernel_syscall_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_kernel_syscall *syscall;
@@ -61,9 +61,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_kernel_syscall_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_kernel_syscall_serialize(const struct lttng_event_rule *rule,
+                                                    struct lttng_payload *payload)
 {
        int ret;
        size_t pattern_len, filter_expression_len;
@@ -80,7 +79,7 @@ static int lttng_event_rule_kernel_syscall_serialize(
 
        pattern_len = strlen(syscall->pattern) + 1;
 
-       if (syscall->filter_expression != NULL) {
+       if (syscall->filter_expression != nullptr) {
                filter_expression_len = strlen(syscall->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
@@ -90,26 +89,24 @@ static int lttng_event_rule_kernel_syscall_serialize(
        syscall_comm.filter_expression_len = filter_expression_len;
        syscall_comm.emission_site = syscall->emission_site;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &syscall_comm, sizeof(syscall_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &syscall_comm, sizeof(syscall_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, syscall->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, syscall->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       syscall->filter_expression, filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, syscall->filter_expression, filter_expression_len);
 end:
        return ret;
 }
 
 static bool lttng_event_rule_kernel_syscall_is_equal(const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+                                                    const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_kernel_syscall *a, *b;
@@ -123,12 +120,12 @@ static bool lttng_event_rule_kernel_syscall_is_equal(const struct lttng_event_ru
 
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -141,16 +138,16 @@ end:
        return is_equal;
 }
 
-static enum lttng_error_code lttng_event_rule_kernel_syscall_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+static enum lttng_error_code
+lttng_event_rule_kernel_syscall_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                        const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        struct lttng_event_rule_kernel_syscall *syscall;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
 
        LTTNG_ASSERT(rule);
 
@@ -159,7 +156,7 @@ static enum lttng_error_code lttng_event_rule_kernel_syscall_generate_filter_byt
        /* Generate the filter bytecode. */
        status = lttng_event_rule_kernel_syscall_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -170,34 +167,33 @@ static enum lttng_error_code lttng_event_rule_kernel_syscall_generate_filter_byt
                goto end;
        }
 
-       if (filter == NULL) {
+       if (filter == nullptr) {
                /* Nothing to do. */
                ret = LTTNG_OK;
                goto end;
        }
 
        syscall->internal_filter.filter = strdup(filter);
-       if (syscall->internal_filter.filter == NULL) {
+       if (syscall->internal_filter.filter == nullptr) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
        }
 
-       ret = run_as_generate_filter_bytecode(
-                       syscall->internal_filter.filter, creds, &bytecode);
+       ret = run_as_generate_filter_bytecode(syscall->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
        }
 
        syscall->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
 
 end:
        free(bytecode);
        return ret_code;
 }
 
-static const char *lttng_event_rule_kernel_syscall_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_kernel_syscall_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_kernel_syscall *syscall;
 
@@ -208,8 +204,7 @@ static const char *lttng_event_rule_kernel_syscall_get_internal_filter(
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_kernel_syscall_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_kernel_syscall_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_kernel_syscall *syscall;
 
@@ -220,58 +215,54 @@ lttng_event_rule_kernel_syscall_get_internal_filter_bytecode(
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_kernel_syscall_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **exclusions)
+lttng_event_rule_kernel_syscall_generate_exclusions(const struct lttng_event_rule *rule
+                                                   __attribute__((unused)),
+                                                   struct lttng_event_exclusion **exclusions)
 {
        /* Unsupported. */
-       *exclusions = NULL;
+       *exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long
-lttng_event_rule_kernel_syscall_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_kernel_syscall_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_kernel_syscall *syscall_rule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_kernel_syscall::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_kernel_syscall::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL, lttng_ht_seed);
        hash ^= hash_key_str(syscall_rule->pattern, lttng_ht_seed);
        if (syscall_rule->filter_expression) {
-               hash ^= hash_key_str(syscall_rule->filter_expression,
-                               lttng_ht_seed);
+               hash ^= hash_key_str(syscall_rule->filter_expression, lttng_ht_seed);
        }
 
        return hash;
 }
 
-static enum lttng_error_code lttng_event_rule_kernel_syscall_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_kernel_syscall_mi_serialize(const struct lttng_event_rule *rule,
+                                            struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
 
        enum lttng_event_rule_kernel_syscall_emission_site site_type;
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
-       const char *site_type_str = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
+       const char *site_type_str = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_SYSCALL_EVENT_RULE(rule));
 
-       status = lttng_event_rule_kernel_syscall_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_kernel_syscall_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_kernel_syscall_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        site_type = lttng_event_rule_kernel_syscall_get_emission_site(rule);
 
@@ -291,32 +282,29 @@ static enum lttng_error_code lttng_event_rule_kernel_syscall_mi_serialize(
        }
 
        /* Open event rule kernel syscall element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_kernel_syscall);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_kernel_syscall);
        if (ret) {
                goto mi_error;
        }
 
        /* Emission site. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_kernel_syscall_emission_site,
-                       site_type_str);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_kernel_syscall_emission_site, site_type_str);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -338,10 +326,9 @@ end:
 }
 
 struct lttng_event_rule *lttng_event_rule_kernel_syscall_create(
-               enum lttng_event_rule_kernel_syscall_emission_site
-                               emission_site)
+       enum lttng_event_rule_kernel_syscall_emission_site emission_site)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_kernel_syscall *syscall_rule;
        enum lttng_event_rule_status status;
 
@@ -362,20 +349,18 @@ struct lttng_event_rule *lttng_event_rule_kernel_syscall_create(
        }
 
        rule = &syscall_rule->parent;
-       lttng_event_rule_init(
-                       &syscall_rule->parent, LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL);
+       lttng_event_rule_init(&syscall_rule->parent, LTTNG_EVENT_RULE_TYPE_KERNEL_SYSCALL);
        syscall_rule->parent.validate = lttng_event_rule_kernel_syscall_validate;
        syscall_rule->parent.serialize = lttng_event_rule_kernel_syscall_serialize;
        syscall_rule->parent.equal = lttng_event_rule_kernel_syscall_is_equal;
        syscall_rule->parent.destroy = lttng_event_rule_kernel_syscall_destroy;
        syscall_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_kernel_syscall_generate_filter_bytecode;
-       syscall_rule->parent.get_filter =
-                       lttng_event_rule_kernel_syscall_get_internal_filter;
+               lttng_event_rule_kernel_syscall_generate_filter_bytecode;
+       syscall_rule->parent.get_filter = lttng_event_rule_kernel_syscall_get_internal_filter;
        syscall_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_kernel_syscall_get_internal_filter_bytecode;
+               lttng_event_rule_kernel_syscall_get_internal_filter_bytecode;
        syscall_rule->parent.generate_exclusions =
-                       lttng_event_rule_kernel_syscall_generate_exclusions;
+               lttng_event_rule_kernel_syscall_generate_exclusions;
        syscall_rule->parent.hash = lttng_event_rule_kernel_syscall_hash;
        syscall_rule->parent.mi_serialize = lttng_event_rule_kernel_syscall_mi_serialize;
 
@@ -383,7 +368,7 @@ struct lttng_event_rule *lttng_event_rule_kernel_syscall_create(
        status = lttng_event_rule_kernel_syscall_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
        /* Emission site type */
@@ -393,17 +378,16 @@ end:
        return rule;
 }
 
-ssize_t lttng_event_rule_kernel_syscall_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_kernel_syscall_create_from_payload(struct lttng_payload_view *view,
+                                                           struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_kernel_syscall_comm *syscall_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
+       const char *filter_expression = nullptr;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
@@ -416,15 +400,16 @@ ssize_t lttng_event_rule_kernel_syscall_create_from_payload(
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*syscall_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*syscall_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
        }
 
        syscall_comm = (typeof(syscall_comm)) current_buffer_view.data;
-       rule = lttng_event_rule_kernel_syscall_create((lttng_event_rule_kernel_syscall_emission_site) syscall_comm->emission_site);
+       rule = lttng_event_rule_kernel_syscall_create(
+               (lttng_event_rule_kernel_syscall_emission_site) syscall_comm->emission_site);
        if (!rule) {
                ERR("Failed to create event rule syscall");
                ret = -1;
@@ -435,16 +420,16 @@ ssize_t lttng_event_rule_kernel_syscall_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the pattern. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, syscall_comm->pattern_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, syscall_comm->pattern_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       syscall_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, syscall_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -457,17 +442,16 @@ ssize_t lttng_event_rule_kernel_syscall_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       syscall_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, syscall_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
        }
 
        filter_expression = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                               filter_expression,
-                               syscall_comm->filter_expression_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, filter_expression, syscall_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -485,8 +469,7 @@ skip_filter_expression:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_kernel_syscall_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_kernel_syscall_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule syscall pattern");
                        ret = -1;
@@ -495,22 +478,21 @@ skip_filter_expression:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_event_rule_destroy(rule);
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_set_name_pattern(struct lttng_event_rule *rule, const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_kernel_syscall *syscall;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_SYSCALL_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_SYSCALL_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
@@ -527,13 +509,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_name_pattern(
        free(syscall->pattern);
 
        syscall->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_syscall_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_get_name_pattern(const struct lttng_event_rule *rule,
+                                                const char **pattern)
 {
        struct lttng_event_rule_kernel_syscall *syscall;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -554,17 +537,16 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_set_filter(struct lttng_event_rule *rule, const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_kernel_syscall *syscall;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
        /* TODO: validate that the passed expression is valid. */
 
-       if (!rule || !IS_SYSCALL_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+       if (!rule || !IS_SYSCALL_EVENT_RULE(rule) || !expression || strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
@@ -581,13 +563,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_syscall_set_filter(
        }
 
        syscall->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_syscall_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_syscall_get_filter(const struct lttng_event_rule *rule,
+                                          const char **expression)
 {
        struct lttng_event_rule_kernel_syscall *syscall;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -608,8 +591,7 @@ end:
        return status;
 }
 extern enum lttng_event_rule_kernel_syscall_emission_site
-lttng_event_rule_kernel_syscall_get_emission_site(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_kernel_syscall_get_emission_site(const struct lttng_event_rule *rule)
 {
        enum lttng_event_rule_kernel_syscall_emission_site emission_site =
                LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_UNKNOWN;
@@ -627,7 +609,7 @@ end:
 }
 
 const char *lttng_event_rule_kernel_syscall_emission_site_str(
-               enum lttng_event_rule_kernel_syscall_emission_site emission_site)
+       enum lttng_event_rule_kernel_syscall_emission_site emission_site)
 {
        switch (emission_site) {
        case LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY:
index 939b83fbbe954ec3d8519b8b5891d0207af39246..50dda01b73774b4ae0cf4b7b1126060842aecba3 100644 (file)
@@ -16,6 +16,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-tracepoint-internal.hpp>
 #include <lttng/event.h>
@@ -27,12 +28,11 @@ static void lttng_event_rule_kernel_tracepoint_destroy(struct lttng_event_rule *
 {
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
 
        free(tracepoint->pattern);
        free(tracepoint->filter_expression);
@@ -41,8 +41,7 @@ static void lttng_event_rule_kernel_tracepoint_destroy(struct lttng_event_rule *
        free(tracepoint);
 }
 
-static bool lttng_event_rule_kernel_tracepoint_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_kernel_tracepoint_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
@@ -51,8 +50,7 @@ static bool lttng_event_rule_kernel_tracepoint_validate(
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
 
        /* Required field. */
        if (!tracepoint->pattern) {
@@ -65,9 +63,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_kernel_tracepoint_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_kernel_tracepoint_serialize(const struct lttng_event_rule *rule,
+                                                       struct lttng_payload *payload)
 {
        int ret;
        size_t pattern_len, filter_expression_len;
@@ -80,14 +77,12 @@ static int lttng_event_rule_kernel_tracepoint_serialize(
        }
 
        DBG("Serializing kernel tracepoint event rule.");
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
 
        pattern_len = strlen(tracepoint->pattern) + 1;
 
-       if (tracepoint->filter_expression != NULL) {
-               filter_expression_len =
-                               strlen(tracepoint->filter_expression) + 1;
+       if (tracepoint->filter_expression != nullptr) {
+               filter_expression_len = strlen(tracepoint->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
        }
@@ -95,20 +90,19 @@ static int lttng_event_rule_kernel_tracepoint_serialize(
        tracepoint_comm.pattern_len = pattern_len;
        tracepoint_comm.filter_expression_len = filter_expression_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &tracepoint_comm,
-                       sizeof(tracepoint_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &tracepoint_comm, sizeof(tracepoint_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, tracepoint->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, tracepoint->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, tracepoint->filter_expression,
-                       filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, tracepoint->filter_expression, filter_expression_len);
        if (ret) {
                goto end;
        }
@@ -117,9 +111,8 @@ end:
        return ret;
 }
 
-static bool lttng_event_rule_kernel_tracepoint_is_equal(
-               const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+static bool lttng_event_rule_kernel_tracepoint_is_equal(const struct lttng_event_rule *_a,
+                                                       const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_kernel_tracepoint *a, *b;
@@ -134,12 +127,12 @@ static bool lttng_event_rule_kernel_tracepoint_is_equal(
        /* Long check. */
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -153,25 +146,23 @@ end:
 }
 
 static enum lttng_error_code
-lttng_event_rule_kernel_tracepoint_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+lttng_event_rule_kernel_tracepoint_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                           const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
 
        LTTNG_ASSERT(rule);
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
 
        status = lttng_event_rule_kernel_tracepoint_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -184,29 +175,27 @@ lttng_event_rule_kernel_tracepoint_generate_filter_bytecode(
 
        if (filter) {
                tracepoint->internal_filter.filter = strdup(filter);
-               if (tracepoint->internal_filter.filter == NULL) {
+               if (tracepoint->internal_filter.filter == nullptr) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto error;
                }
        } else {
-               tracepoint->internal_filter.filter = NULL;
+               tracepoint->internal_filter.filter = nullptr;
        }
 
-       if (tracepoint->internal_filter.filter == NULL) {
+       if (tracepoint->internal_filter.filter == nullptr) {
                ret_code = LTTNG_OK;
                goto end;
        }
 
-       ret = run_as_generate_filter_bytecode(
-                       tracepoint->internal_filter.filter, creds,
-                       &bytecode);
+       ret = run_as_generate_filter_bytecode(tracepoint->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
        }
 
        tracepoint->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
        ret_code = LTTNG_OK;
 
 error:
@@ -215,48 +204,43 @@ end:
        return ret_code;
 }
 
-static const char *lttng_event_rule_kernel_tracepoint_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_kernel_tracepoint_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
 
        LTTNG_ASSERT(rule);
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        return tracepoint->internal_filter.filter;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_kernel_tracepoint_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_kernel_tracepoint_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
 
        LTTNG_ASSERT(rule);
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        return tracepoint->internal_filter.bytecode;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_kernel_tracepoint_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **_exclusions)
+lttng_event_rule_kernel_tracepoint_generate_exclusions(const struct lttng_event_rule *rule
+                                                      __attribute__((unused)),
+                                                      struct lttng_event_exclusion **_exclusions)
 {
        /* Unsupported. */
-       *_exclusions = NULL;
+       *_exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long lttng_event_rule_kernel_tracepoint_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_kernel_tracepoint_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
-       struct lttng_event_rule_kernel_tracepoint *tp_rule = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       struct lttng_event_rule_kernel_tracepoint *tp_rule =
+               lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_TRACEPOINT, lttng_ht_seed);
        hash ^= hash_key_str(tp_rule->pattern, lttng_ht_seed);
 
        if (tp_rule->filter_expression) {
@@ -266,47 +250,45 @@ static unsigned long lttng_event_rule_kernel_tracepoint_hash(
        return hash;
 }
 
-static enum lttng_error_code lttng_event_rule_kernel_tracepoint_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_kernel_tracepoint_mi_serialize(const struct lttng_event_rule *rule,
+                                               struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_KERNEL_TRACEPOINT_EVENT_RULE(rule));
 
-       status = lttng_event_rule_kernel_tracepoint_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_kernel_tracepoint_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_kernel_tracepoint_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        /* Open event rule kernel tracepoint element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_kernel_tracepoint);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_kernel_tracepoint);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -329,7 +311,7 @@ end:
 
 struct lttng_event_rule *lttng_event_rule_kernel_tracepoint_create(void)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_kernel_tracepoint *tp_rule;
        enum lttng_event_rule_status status;
 
@@ -345,49 +327,48 @@ struct lttng_event_rule *lttng_event_rule_kernel_tracepoint_create(void)
        tp_rule->parent.equal = lttng_event_rule_kernel_tracepoint_is_equal;
        tp_rule->parent.destroy = lttng_event_rule_kernel_tracepoint_destroy;
        tp_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_kernel_tracepoint_generate_filter_bytecode;
-       tp_rule->parent.get_filter =
-                       lttng_event_rule_kernel_tracepoint_get_internal_filter;
+               lttng_event_rule_kernel_tracepoint_generate_filter_bytecode;
+       tp_rule->parent.get_filter = lttng_event_rule_kernel_tracepoint_get_internal_filter;
        tp_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_kernel_tracepoint_get_internal_filter_bytecode;
+               lttng_event_rule_kernel_tracepoint_get_internal_filter_bytecode;
        tp_rule->parent.generate_exclusions =
-                       lttng_event_rule_kernel_tracepoint_generate_exclusions;
+               lttng_event_rule_kernel_tracepoint_generate_exclusions;
        tp_rule->parent.hash = lttng_event_rule_kernel_tracepoint_hash;
        tp_rule->parent.mi_serialize = lttng_event_rule_kernel_tracepoint_mi_serialize;
 
        /* Not necessary for now. */
-       tp_rule->parent.generate_lttng_event = NULL;
+       tp_rule->parent.generate_lttng_event = nullptr;
 
        /* Default pattern is '*'. */
        status = lttng_event_rule_kernel_tracepoint_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t
+lttng_event_rule_kernel_tracepoint_create_from_payload(struct lttng_payload_view *view,
+                                                      struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_kernel_tracepoint_comm *tracepoint_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
+       const char *filter_expression = nullptr;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*tracepoint_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*tracepoint_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule kernel tracepoint: buffer too short to contain header.");
                ret = -1;
@@ -400,8 +381,8 @@ ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the pattern. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, tracepoint_comm->pattern_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, tracepoint_comm->pattern_len);
 
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
@@ -409,8 +390,8 @@ ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       tracepoint_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, tracepoint_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -423,8 +404,8 @@ ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       tracepoint_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, tracepoint_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
@@ -432,8 +413,8 @@ ssize_t lttng_event_rule_kernel_tracepoint_create_from_payload(
 
        filter_expression = current_buffer_view.data;
        if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                       filter_expression,
-                       tracepoint_comm->filter_expression_len)) {
+                                              filter_expression,
+                                              tracepoint_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -458,8 +439,7 @@ skip_filter_expression:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_kernel_tracepoint_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_kernel_tracepoint_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule kernel tracepoint pattern.");
                        ret = -1;
@@ -468,28 +448,27 @@ skip_filter_expression:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_event_rule_destroy(rule);
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_set_name_pattern(struct lttng_event_rule *rule,
+                                                   const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_KERNEL_TRACEPOINT_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_KERNEL_TRACEPOINT_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        pattern_copy = strdup(pattern);
        if (!pattern_copy) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
@@ -502,13 +481,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_name_pattern
        free(tracepoint->pattern);
 
        tracepoint->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_get_name_pattern(const struct lttng_event_rule *rule,
+                                                   const char **pattern)
 {
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -518,8 +498,7 @@ enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_name_pattern
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        if (!tracepoint->pattern) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -530,21 +509,20 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_set_filter(struct lttng_event_rule *rule, const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
        if (!rule || !IS_KERNEL_TRACEPOINT_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+           strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        expression_copy = strdup(expression);
        if (!expression_copy) {
                PERROR("Failed to copy filter expression");
@@ -557,13 +535,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_set_filter(
        }
 
        tracepoint->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_tracepoint_get_filter(const struct lttng_event_rule *rule,
+                                             const char **expression)
 {
        struct lttng_event_rule_kernel_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -573,8 +552,7 @@ enum lttng_event_rule_status lttng_event_rule_kernel_tracepoint_get_filter(
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_kernel_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_kernel_tracepoint::parent);
        if (!tracepoint->filter_expression) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
index cee5b2e65b30ccf9979c396b75f68419bd6e32c1..6e750576cf1e69040a441c9e61e66f381de8da01 100644 (file)
@@ -14,6 +14,7 @@
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
 #include <common/runas.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/kernel-uprobe-internal.hpp>
 #include <lttng/userspace-probe-internal.hpp>
@@ -32,8 +33,7 @@ static void lttng_event_rule_kernel_uprobe_destroy(struct lttng_event_rule *rule
        free(uprobe);
 }
 
-static bool lttng_event_rule_kernel_uprobe_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_kernel_uprobe_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_kernel_uprobe *uprobe;
@@ -60,9 +60,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_kernel_uprobe_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_kernel_uprobe_serialize(const struct lttng_event_rule *rule,
+                                                   struct lttng_payload *payload)
 {
        int ret;
        size_t name_len, header_offset, size_before_probe;
@@ -84,13 +83,11 @@ static int lttng_event_rule_kernel_uprobe_serialize(
 
        uprobe_comm.name_len = name_len;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &uprobe_comm, sizeof(uprobe_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &uprobe_comm, sizeof(uprobe_comm));
        if (ret) {
                goto end;
        }
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, uprobe->name, name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, uprobe->name, name_len);
        if (ret) {
                goto end;
        }
@@ -98,16 +95,14 @@ static int lttng_event_rule_kernel_uprobe_serialize(
        size_before_probe = payload->buffer.size;
 
        /* This serialize return the size taken in the buffer. */
-       ret = lttng_userspace_probe_location_serialize(
-                       uprobe->location, payload);
+       ret = lttng_userspace_probe_location_serialize(uprobe->location, payload);
        if (ret < 0) {
                goto end;
        }
 
        /* Update the header regarding the probe size. */
-       header = (struct lttng_event_rule_kernel_uprobe_comm
-                                       *) ((char *) payload->buffer.data +
-                       header_offset);
+       header = (struct lttng_event_rule_kernel_uprobe_comm *) ((char *) payload->buffer.data +
+                                                                header_offset);
        header->location_len = payload->buffer.size - size_before_probe;
 
        ret = 0;
@@ -117,7 +112,7 @@ end:
 }
 
 static bool lttng_event_rule_kernel_uprobe_is_equal(const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+                                                   const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_kernel_uprobe *a, *b;
@@ -128,74 +123,68 @@ static bool lttng_event_rule_kernel_uprobe_is_equal(const struct lttng_event_rul
        /* uprobe is invalid if this is not true. */
        LTTNG_ASSERT(a->name);
        LTTNG_ASSERT(b->name);
-       if (strcmp(a->name, b->name)) {
+       if (strcmp(a->name, b->name) != 0) {
                goto end;
        }
 
        LTTNG_ASSERT(a->location);
        LTTNG_ASSERT(b->location);
-       is_equal = lttng_userspace_probe_location_is_equal(
-                       a->location, b->location);
+       is_equal = lttng_userspace_probe_location_is_equal(a->location, b->location);
 end:
        return is_equal;
 }
 
 static enum lttng_error_code lttng_event_rule_kernel_uprobe_generate_filter_bytecode(
-               struct lttng_event_rule *rule __attribute__((unused)),
-               const struct lttng_credentials *creds __attribute__((unused)))
+       struct lttng_event_rule *rule __attribute__((unused)),
+       const struct lttng_credentials *creds __attribute__((unused)))
 {
        /* Nothing to do. */
        return LTTNG_OK;
 }
 
-static const char *lttng_event_rule_kernel_uprobe_get_filter(
-               const struct lttng_event_rule *rule __attribute__((unused)))
+static const char *lttng_event_rule_kernel_uprobe_get_filter(const struct lttng_event_rule *rule
+                                                            __attribute__((unused)))
 {
        /* Unsupported. */
-       return NULL;
+       return nullptr;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_kernel_uprobe_get_filter_bytecode(
-               const struct lttng_event_rule *rule __attribute__((unused)))
+lttng_event_rule_kernel_uprobe_get_filter_bytecode(const struct lttng_event_rule *rule
+                                                  __attribute__((unused)))
 {
        /* Unsupported. */
-       return NULL;
+       return nullptr;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_kernel_uprobe_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **exclusions)
+lttng_event_rule_kernel_uprobe_generate_exclusions(const struct lttng_event_rule *rule
+                                                  __attribute__((unused)),
+                                                  struct lttng_event_exclusion **exclusions)
 {
        /* Unsupported. */
-       *exclusions = NULL;
+       *exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long
-lttng_event_rule_kernel_uprobe_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_kernel_uprobe_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_kernel_uprobe *urule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_kernel_uprobe::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_kernel_uprobe::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_KERNEL_UPROBE, lttng_ht_seed);
        hash ^= hash_key_str(urule->name, lttng_ht_seed);
        hash ^= lttng_userspace_probe_location_hash(urule->location);
 
        return hash;
 }
 
-static
-int userspace_probe_set_location(
-               struct lttng_event_rule_kernel_uprobe *uprobe,
-               const struct lttng_userspace_probe_location *location)
+static int userspace_probe_set_location(struct lttng_event_rule_kernel_uprobe *uprobe,
+                                       const struct lttng_userspace_probe_location *location)
 {
        int ret;
-       struct lttng_userspace_probe_location *location_copy = NULL;
+       struct lttng_userspace_probe_location *location_copy = nullptr;
 
        if (!uprobe || !location || uprobe->location) {
                ret = -1;
@@ -209,28 +198,28 @@ int userspace_probe_set_location(
        }
 
        uprobe->location = location_copy;
-       location_copy = NULL;
+       location_copy = nullptr;
        ret = 0;
 end:
        lttng_userspace_probe_location_destroy(location_copy);
        return ret;
 }
 
-static enum lttng_error_code lttng_event_rule_kernel_uprobe_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_kernel_uprobe_mi_serialize(const struct lttng_event_rule *rule,
+                                           struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *event_name = NULL;
-       const struct lttng_userspace_probe_location *location = NULL;
+       const char *event_name = nullptr;
+       const struct lttng_userspace_probe_location *location = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_UPROBE_EVENT_RULE(rule));
 
-       status = lttng_event_rule_kernel_uprobe_get_event_name(
-                       rule, &event_name);
+       status = lttng_event_rule_kernel_uprobe_get_event_name(rule, &event_name);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(event_name);
 
@@ -239,15 +228,14 @@ static enum lttng_error_code lttng_event_rule_kernel_uprobe_mi_serialize(
        LTTNG_ASSERT(location);
 
        /* Open event rule kernel uprobe element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_kernel_uprobe);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_kernel_uprobe);
        if (ret) {
                goto mi_error;
        }
 
        /* Event name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_event_name, event_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_event_name, event_name);
        if (ret) {
                goto mi_error;
        }
@@ -273,10 +261,10 @@ end:
        return ret_code;
 }
 
-struct lttng_event_rule *lttng_event_rule_kernel_uprobe_create(
-               const struct lttng_userspace_probe_location *location)
+struct lttng_event_rule *
+lttng_event_rule_kernel_uprobe_create(const struct lttng_userspace_probe_location *location)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_kernel_uprobe *urule;
 
        urule = zmalloc<lttng_event_rule_kernel_uprobe>();
@@ -291,34 +279,31 @@ struct lttng_event_rule *lttng_event_rule_kernel_uprobe_create(
        urule->parent.equal = lttng_event_rule_kernel_uprobe_is_equal;
        urule->parent.destroy = lttng_event_rule_kernel_uprobe_destroy;
        urule->parent.generate_filter_bytecode =
-                       lttng_event_rule_kernel_uprobe_generate_filter_bytecode;
+               lttng_event_rule_kernel_uprobe_generate_filter_bytecode;
        urule->parent.get_filter = lttng_event_rule_kernel_uprobe_get_filter;
-       urule->parent.get_filter_bytecode =
-                       lttng_event_rule_kernel_uprobe_get_filter_bytecode;
-       urule->parent.generate_exclusions =
-                       lttng_event_rule_kernel_uprobe_generate_exclusions;
+       urule->parent.get_filter_bytecode = lttng_event_rule_kernel_uprobe_get_filter_bytecode;
+       urule->parent.generate_exclusions = lttng_event_rule_kernel_uprobe_generate_exclusions;
        urule->parent.hash = lttng_event_rule_kernel_uprobe_hash;
        urule->parent.mi_serialize = lttng_event_rule_kernel_uprobe_mi_serialize;
 
        if (userspace_probe_set_location(urule, location)) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        const struct lttng_event_rule_kernel_uprobe_comm *uprobe_comm;
        const char *name;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_userspace_probe_location *location = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_userspace_probe_location *location = nullptr;
        enum lttng_event_rule_status status;
 
        if (!_event_rule) {
@@ -326,8 +311,8 @@ ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*uprobe_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*uprobe_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule uprobe: buffer too short to contain header");
                ret = -1;
@@ -340,16 +325,15 @@ ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the name. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, uprobe_comm->name_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, uprobe_comm->name_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
        }
 
        name = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, name,
-                       uprobe_comm->name_len)) {
+       if (!lttng_buffer_view_contains_string(&current_buffer_view, name, uprobe_comm->name_len)) {
                ret = -1;
                goto end;
        }
@@ -360,8 +344,7 @@ ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
        /* Map the location. */
        {
                struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               uprobe_comm->location_len);
+                       lttng_payload_view_from_view(view, offset, uprobe_comm->location_len);
 
                if (!lttng_payload_view_is_valid(&current_payload_view)) {
                        ERR("Failed to initialize from malformed event rule uprobe: buffer too short to contain location");
@@ -369,8 +352,8 @@ ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
                        goto end;
                }
 
-               ret = lttng_userspace_probe_location_create_from_payload(
-                               &current_payload_view, &location);
+               ret = lttng_userspace_probe_location_create_from_payload(&current_payload_view,
+                                                                        &location);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -401,7 +384,7 @@ ssize_t lttng_event_rule_kernel_uprobe_create_from_payload(
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_userspace_probe_location_destroy(location);
@@ -409,10 +392,9 @@ end:
        return ret;
 }
 
-
-enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_get_location(
-               const struct lttng_event_rule *rule,
-               const struct lttng_userspace_probe_location **location)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_get_location(const struct lttng_event_rule *rule,
+                                           const struct lttng_userspace_probe_location **location)
 {
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
@@ -432,8 +414,7 @@ end:
 }
 
 struct lttng_userspace_probe_location *
-lttng_event_rule_kernel_uprobe_get_location_mutable(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_kernel_uprobe_get_location_mutable(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_kernel_uprobe *uprobe;
 
@@ -443,15 +424,14 @@ lttng_event_rule_kernel_uprobe_get_location_mutable(
        return uprobe->location;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_set_event_name(
-               struct lttng_event_rule *rule, const char *name)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_set_event_name(struct lttng_event_rule *rule, const char *name)
 {
-       char *name_copy = NULL;
+       char *name_copy = nullptr;
        struct lttng_event_rule_kernel_uprobe *uprobe;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_UPROBE_EVENT_RULE(rule) || !name ||
-                       strlen(name) == 0) {
+       if (!rule || !IS_UPROBE_EVENT_RULE(rule) || !name || strlen(name) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
@@ -468,13 +448,14 @@ enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_set_event_name(
        }
 
        uprobe->name = name_copy;
-       name_copy = NULL;
+       name_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_kernel_uprobe_get_event_name(
-               const struct lttng_event_rule *rule, const char **name)
+enum lttng_event_rule_status
+lttng_event_rule_kernel_uprobe_get_event_name(const struct lttng_event_rule *rule,
+                                             const char **name)
 {
        struct lttng_event_rule_kernel_uprobe *uprobe;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
index 11e775c3f893f9d4269f76b020d2e9204057c20c..ba440b979e1685082558baa73e20660bcc2cc7cc 100644 (file)
@@ -16,6 +16,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/log4j-logging-internal.hpp>
 #include <lttng/event.h>
@@ -28,12 +29,11 @@ static void lttng_event_rule_log4j_logging_destroy(struct lttng_event_rule *rule
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        lttng_log_level_rule_destroy(log4j_logging->log_level_rule);
        free(log4j_logging->pattern);
@@ -43,8 +43,7 @@ static void lttng_event_rule_log4j_logging_destroy(struct lttng_event_rule *rule
        free(log4j_logging);
 }
 
-static bool lttng_event_rule_log4j_logging_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_log4j_logging_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_log4j_logging *log4j_logging;
@@ -53,8 +52,7 @@ static bool lttng_event_rule_log4j_logging_validate(
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        /* Required field. */
        if (!log4j_logging->pattern) {
@@ -67,9 +65,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_log4j_logging_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_log4j_logging_serialize(const struct lttng_event_rule *rule,
+                                                   struct lttng_payload *payload)
 {
        int ret;
        size_t pattern_len, filter_expression_len, header_offset;
@@ -86,14 +83,12 @@ static int lttng_event_rule_log4j_logging_serialize(
        header_offset = payload->buffer.size;
 
        DBG("Serializing log4j_logging event rule.");
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        pattern_len = strlen(log4j_logging->pattern) + 1;
 
-       if (log4j_logging->filter_expression != NULL) {
-               filter_expression_len =
-                               strlen(log4j_logging->filter_expression) + 1;
+       if (log4j_logging->filter_expression != nullptr) {
+               filter_expression_len = strlen(log4j_logging->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
        }
@@ -101,20 +96,19 @@ static int lttng_event_rule_log4j_logging_serialize(
        log4j_logging_comm.pattern_len = pattern_len;
        log4j_logging_comm.filter_expression_len = filter_expression_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &log4j_logging_comm,
-                       sizeof(log4j_logging_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &log4j_logging_comm, sizeof(log4j_logging_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, log4j_logging->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, log4j_logging->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, log4j_logging->filter_expression,
-                       filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, log4j_logging->filter_expression, filter_expression_len);
        if (ret) {
                goto end;
        }
@@ -127,16 +121,14 @@ static int lttng_event_rule_log4j_logging_serialize(
        }
 
        header = (typeof(header)) ((char *) payload->buffer.data + header_offset);
-       header->log_level_rule_len =
-                       payload->buffer.size - size_before_log_level_rule;
+       header->log_level_rule_len = payload->buffer.size - size_before_log_level_rule;
 
 end:
        return ret;
 }
 
-static bool lttng_event_rule_log4j_logging_is_equal(
-               const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+static bool lttng_event_rule_log4j_logging_is_equal(const struct lttng_event_rule *_a,
+                                                   const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_log4j_logging *a, *b;
@@ -153,12 +145,12 @@ static bool lttng_event_rule_log4j_logging_is_equal(
        /* Long check. */
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -166,8 +158,7 @@ static bool lttng_event_rule_log4j_logging_is_equal(
                goto end;
        }
 
-       if (!lttng_log_level_rule_is_equal(
-                               a->log_level_rule, b->log_level_rule)) {
+       if (!lttng_log_level_rule_is_equal(a->log_level_rule, b->log_level_rule)) {
                goto end;
        }
 
@@ -183,15 +174,14 @@ end:
  *
  * An event with NO loglevel and the name is * will return NULL.
  */
-static int generate_agent_filter(
-               const struct lttng_event_rule *rule, char **_agent_filter)
+static int generate_agent_filter(const struct lttng_event_rule *rule, char **_agent_filter)
 {
        int err;
        int ret = 0;
-       char *agent_filter = NULL;
+       char *agent_filter = nullptr;
        const char *pattern;
        const char *filter;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
        enum lttng_event_rule_status status;
 
        LTTNG_ASSERT(rule);
@@ -205,22 +195,19 @@ static int generate_agent_filter(
 
        status = lttng_event_rule_log4j_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
-
        /* Don't add filter for the '*' event. */
        if (strcmp(pattern, "*") != 0) {
                if (filter) {
-                       err = asprintf(&agent_filter,
-                                       "(%s) && (logger_name == \"%s\")",
-                                       filter, pattern);
+                       err = asprintf(
+                               &agent_filter, "(%s) && (logger_name == \"%s\")", filter, pattern);
                } else {
-                       err = asprintf(&agent_filter, "logger_name == \"%s\"",
-                                       pattern);
+                       err = asprintf(&agent_filter, "logger_name == \"%s\"", pattern);
                }
 
                if (err < 0) {
@@ -230,23 +217,20 @@ static int generate_agent_filter(
                }
        }
 
-       status = lttng_event_rule_log4j_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_log4j_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
                const char *op;
                int level;
 
-               switch (lttng_log_level_rule_get_type(log_level_rule))
-               {
+               switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &level);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule, &level);
                        op = "==";
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &level);
+                               log_level_rule, &level);
                        op = ">=";
                        break;
                default:
@@ -262,16 +246,16 @@ static int generate_agent_filter(
                        char *new_filter;
 
                        err = asprintf(&new_filter,
-                                       "(%s) && (int_loglevel %s %d)",
-                                       agent_filter ? agent_filter : filter,
-                                       op, level);
+                                      "(%s) && (int_loglevel %s %d)",
+                                      agent_filter ? agent_filter : filter,
+                                      op,
+                                      level);
                        if (agent_filter) {
                                free(agent_filter);
                        }
                        agent_filter = new_filter;
                } else {
-                       err = asprintf(&agent_filter, "int_loglevel %s %d", op,
-                                       level);
+                       err = asprintf(&agent_filter, "int_loglevel %s %d", op, level);
                }
 
                if (err < 0) {
@@ -282,7 +266,7 @@ static int generate_agent_filter(
        }
 
        *_agent_filter = agent_filter;
-       agent_filter = NULL;
+       agent_filter = nullptr;
 
 end:
        free(agent_filter);
@@ -290,26 +274,24 @@ end:
 }
 
 static enum lttng_error_code
-lttng_event_rule_log4j_logging_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+lttng_event_rule_log4j_logging_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                       const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        char *agent_filter;
 
        LTTNG_ASSERT(rule);
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        status = lttng_event_rule_log4j_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -328,21 +310,20 @@ lttng_event_rule_log4j_logging_generate_filter_bytecode(
 
        log4j_logging->internal_filter.filter = agent_filter;
 
-       if (log4j_logging->internal_filter.filter == NULL) {
+       if (log4j_logging->internal_filter.filter == nullptr) {
                ret_code = LTTNG_OK;
                goto end;
        }
 
        ret = run_as_generate_filter_bytecode(
-                       log4j_logging->internal_filter.filter, creds,
-                       &bytecode);
+               log4j_logging->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
        }
 
        log4j_logging->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
        ret_code = LTTNG_OK;
 
 error:
@@ -351,48 +332,43 @@ end:
        return ret_code;
 }
 
-static const char *lttng_event_rule_log4j_logging_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_log4j_logging_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
 
        LTTNG_ASSERT(rule);
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        return log4j_logging->internal_filter.filter;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_log4j_logging_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_log4j_logging_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
 
        LTTNG_ASSERT(rule);
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        return log4j_logging->internal_filter.bytecode;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_log4j_logging_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **_exclusions)
+lttng_event_rule_log4j_logging_generate_exclusions(const struct lttng_event_rule *rule
+                                                  __attribute__((unused)),
+                                                  struct lttng_event_exclusion **_exclusions)
 {
        /* Unsupported. */
-       *_exclusions = NULL;
+       *_exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long lttng_event_rule_log4j_logging_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_log4j_logging_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_log4j_logging *tp_rule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING, lttng_ht_seed);
        hash ^= hash_key_str(tp_rule->pattern, lttng_ht_seed);
 
        if (tp_rule->filter_expression) {
@@ -406,20 +382,19 @@ static unsigned long lttng_event_rule_log4j_logging_hash(
        return hash;
 }
 
-static struct lttng_event *lttng_event_rule_log4j_logging_generate_lttng_event(
-               const struct lttng_event_rule *rule)
+static struct lttng_event *
+lttng_event_rule_log4j_logging_generate_lttng_event(const struct lttng_event_rule *rule)
 {
        int ret;
        const struct lttng_event_rule_log4j_logging *log4j_logging;
-       struct lttng_event *local_event = NULL;
-       struct lttng_event *event = NULL;
+       struct lttng_event *local_event = nullptr;
+       struct lttng_event *event = nullptr;
        enum lttng_loglevel_type loglevel_type;
        int loglevel_value = 0;
        enum lttng_event_rule_status status;
        const struct lttng_log_level_rule *log_level_rule;
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        local_event = zmalloc<lttng_event>();
        if (!local_event) {
@@ -427,33 +402,30 @@ static struct lttng_event *lttng_event_rule_log4j_logging_generate_lttng_event(
        }
 
        local_event->type = LTTNG_EVENT_TRACEPOINT;
-       ret = lttng_strncpy(local_event->name, log4j_logging->pattern,
-                           sizeof(local_event->name));
+       ret = lttng_strncpy(local_event->name, log4j_logging->pattern, sizeof(local_event->name));
        if (ret) {
                ERR("Truncation occurred when copying event rule pattern to `lttng_event` structure: pattern = '%s'",
-                               log4j_logging->pattern);
+                   log4j_logging->pattern);
                goto error;
        }
 
-
        /* Map the log level rule to an equivalent lttng_loglevel. */
-       status = lttng_event_rule_log4j_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_log4j_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
                loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               loglevel_value = 0;
+               loglevel_value = LTTNG_LOGLEVEL_LOG4J_ALL;
        } else if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
 
                switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &loglevel_value);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule,
+                                                                           &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_SINGLE;
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &loglevel_value);
+                               log_level_rule, &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_RANGE;
                        break;
                default:
@@ -472,59 +444,56 @@ static struct lttng_event *lttng_event_rule_log4j_logging_generate_lttng_event(
        local_event->loglevel = loglevel_value;
 
        event = local_event;
-       local_event = NULL;
+       local_event = nullptr;
 error:
        free(local_event);
        return event;
 }
 
-static enum lttng_error_code lttng_event_rule_log4j_logging_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_log4j_logging_mi_serialize(const struct lttng_event_rule *rule,
+                                           struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_LOG4J_LOGGING_EVENT_RULE(rule));
 
-       status = lttng_event_rule_log4j_logging_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_log4j_logging_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_log4j_logging_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
-       status = lttng_event_rule_log4j_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_log4j_logging_get_log_level_rule(rule, &log_level_rule);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        /* Open event rule log4j logging element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_log4j_logging);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_log4j_logging);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter expression. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -532,8 +501,7 @@ static enum lttng_error_code lttng_event_rule_log4j_logging_mi_serialize(
 
        /* Log level rule. */
        if (log_level_rule) {
-               ret_code = lttng_log_level_rule_mi_serialize(
-                               log_level_rule, writer);
+               ret_code = lttng_log_level_rule_mi_serialize(log_level_rule, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
@@ -556,7 +524,7 @@ end:
 
 struct lttng_event_rule *lttng_event_rule_log4j_logging_create(void)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_log4j_logging *tp_rule;
        enum lttng_event_rule_status status;
 
@@ -572,51 +540,47 @@ struct lttng_event_rule *lttng_event_rule_log4j_logging_create(void)
        tp_rule->parent.equal = lttng_event_rule_log4j_logging_is_equal;
        tp_rule->parent.destroy = lttng_event_rule_log4j_logging_destroy;
        tp_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_log4j_logging_generate_filter_bytecode;
-       tp_rule->parent.get_filter =
-                       lttng_event_rule_log4j_logging_get_internal_filter;
+               lttng_event_rule_log4j_logging_generate_filter_bytecode;
+       tp_rule->parent.get_filter = lttng_event_rule_log4j_logging_get_internal_filter;
        tp_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_log4j_logging_get_internal_filter_bytecode;
-       tp_rule->parent.generate_exclusions =
-                       lttng_event_rule_log4j_logging_generate_exclusions;
+               lttng_event_rule_log4j_logging_get_internal_filter_bytecode;
+       tp_rule->parent.generate_exclusions = lttng_event_rule_log4j_logging_generate_exclusions;
        tp_rule->parent.hash = lttng_event_rule_log4j_logging_hash;
-       tp_rule->parent.generate_lttng_event =
-                       lttng_event_rule_log4j_logging_generate_lttng_event;
+       tp_rule->parent.generate_lttng_event = lttng_event_rule_log4j_logging_generate_lttng_event;
        tp_rule->parent.mi_serialize = lttng_event_rule_log4j_logging_mi_serialize;
 
-       tp_rule->log_level_rule = NULL;
+       tp_rule->log_level_rule = nullptr;
 
        /* Default pattern is '*'. */
        status = lttng_event_rule_log4j_logging_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_log4j_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_log4j_logging_create_from_payload(struct lttng_payload_view *view,
+                                                          struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_log4j_logging_comm *log4j_logging_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
+       const char *filter_expression = nullptr;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_log_level_rule *log_level_rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*log4j_logging_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*log4j_logging_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule log4j_logging: buffer too short to contain header.");
                ret = -1;
@@ -636,8 +600,8 @@ ssize_t lttng_event_rule_log4j_logging_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the pattern. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, log4j_logging_comm->pattern_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, log4j_logging_comm->pattern_len);
 
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
@@ -645,8 +609,8 @@ ssize_t lttng_event_rule_log4j_logging_create_from_payload(
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       log4j_logging_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, log4j_logging_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -659,8 +623,8 @@ ssize_t lttng_event_rule_log4j_logging_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       log4j_logging_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, log4j_logging_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
@@ -668,8 +632,8 @@ ssize_t lttng_event_rule_log4j_logging_create_from_payload(
 
        filter_expression = current_buffer_view.data;
        if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                       filter_expression,
-                       log4j_logging_comm->filter_expression_len)) {
+                                              filter_expression,
+                                              log4j_logging_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -684,12 +648,11 @@ skip_filter_expression:
 
        {
                /* Map the log level rule. */
-               struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               log4j_logging_comm->log_level_rule_len);
+               struct lttng_payload_view current_payload_view = lttng_payload_view_from_view(
+                       view, offset, log4j_logging_comm->log_level_rule_len);
 
-               ret = lttng_log_level_rule_create_from_payload(
-                               &current_payload_view, &log_level_rule);
+               ret = lttng_log_level_rule_create_from_payload(&current_payload_view,
+                                                              &log_level_rule);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -711,8 +674,7 @@ skip_log_level_rule:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_log4j_logging_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_log4j_logging_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule log4j_logging pattern.");
                        ret = -1;
@@ -721,8 +683,7 @@ skip_log_level_rule:
        }
 
        if (log_level_rule) {
-               status = lttng_event_rule_log4j_logging_set_log_level_rule(
-                               rule, log_level_rule);
+               status = lttng_event_rule_log4j_logging_set_log_level_rule(rule, log_level_rule);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule log4j_logging log level rule.");
                        ret = -1;
@@ -731,7 +692,7 @@ skip_log_level_rule:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_log_level_rule_destroy(log_level_rule);
@@ -739,21 +700,19 @@ end:
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_set_name_pattern(struct lttng_event_rule *rule, const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_LOG4J_LOGGING_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_LOG4J_LOGGING_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        pattern_copy = strdup(pattern);
        if (!pattern_copy) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
@@ -766,13 +725,14 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_name_pattern(
        free(log4j_logging->pattern);
 
        log4j_logging->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                               const char **pattern)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -782,8 +742,7 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_name_pattern(
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        if (!log4j_logging->pattern) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -794,21 +753,19 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_set_filter(struct lttng_event_rule *rule, const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_LOG4J_LOGGING_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+       if (!rule || !IS_LOG4J_LOGGING_EVENT_RULE(rule) || !expression || strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        expression_copy = strdup(expression);
        if (!expression_copy) {
                PERROR("Failed to copy filter expression");
@@ -821,13 +778,14 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_filter(
        }
 
        log4j_logging->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_get_filter(const struct lttng_event_rule *rule,
+                                         const char **expression)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -837,8 +795,7 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_filter(
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
        if (!log4j_logging->filter_expression) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -849,8 +806,7 @@ end:
        return status;
 }
 
-static bool log_level_rule_valid(
-               const struct lttng_log_level_rule *rule __attribute__((unused)))
+static bool log_level_rule_valid(const struct lttng_log_level_rule *rule __attribute__((unused)))
 {
        /*
         * For both LOG4J custom log level are possible and can
@@ -859,21 +815,20 @@ static bool log_level_rule_valid(
        return true;
 }
 
-enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_log_level_rule(
-               struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule)
+enum lttng_event_rule_status
+lttng_event_rule_log4j_logging_set_log_level_rule(struct lttng_event_rule *rule,
+                                                 const struct lttng_log_level_rule *log_level_rule)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
-       struct lttng_log_level_rule *copy = NULL;
+       struct lttng_log_level_rule *copy = nullptr;
 
        if (!rule || !IS_LOG4J_LOGGING_EVENT_RULE(rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
 
        if (!log_level_rule_valid(log_level_rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
@@ -881,7 +836,7 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_set_log_level_rule(
        }
 
        copy = lttng_log_level_rule_copy(log_level_rule);
-       if (copy == NULL) {
+       if (copy == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
                goto end;
        }
@@ -897,9 +852,7 @@ end:
 }
 
 enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule
-               )
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule)
 {
        struct lttng_event_rule_log4j_logging *log4j_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -909,9 +862,8 @@ enum lttng_event_rule_status lttng_event_rule_log4j_logging_get_log_level_rule(
                goto end;
        }
 
-       log4j_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_log4j_logging::parent);
-       if (log4j_logging->log_level_rule == NULL) {
+       log4j_logging = lttng::utils::container_of(rule, &lttng_event_rule_log4j_logging::parent);
+       if (log4j_logging->log_level_rule == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
        }
index 47b1e0366a79d94cf942572c5acc64caa85f37cb..9fcfaba9c66aad722c7aa8b3c23470c6c651e847 100644 (file)
@@ -16,6 +16,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/python-logging-internal.hpp>
 #include <lttng/event.h>
@@ -28,12 +29,11 @@ static void lttng_event_rule_python_logging_destroy(struct lttng_event_rule *rul
 {
        struct lttng_event_rule_python_logging *python_logging;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        lttng_log_level_rule_destroy(python_logging->log_level_rule);
        free(python_logging->pattern);
@@ -43,8 +43,7 @@ static void lttng_event_rule_python_logging_destroy(struct lttng_event_rule *rul
        free(python_logging);
 }
 
-static bool lttng_event_rule_python_logging_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_python_logging_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_python_logging *python_logging;
@@ -53,8 +52,7 @@ static bool lttng_event_rule_python_logging_validate(
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        /* Required field. */
        if (!python_logging->pattern) {
@@ -67,9 +65,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_python_logging_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_python_logging_serialize(const struct lttng_event_rule *rule,
+                                                    struct lttng_payload *payload)
 {
        int ret;
        size_t pattern_len, filter_expression_len, header_offset;
@@ -86,14 +83,12 @@ static int lttng_event_rule_python_logging_serialize(
        header_offset = payload->buffer.size;
 
        DBG("Serializing python_logging event rule.");
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        pattern_len = strlen(python_logging->pattern) + 1;
 
-       if (python_logging->filter_expression != NULL) {
-               filter_expression_len =
-                               strlen(python_logging->filter_expression) + 1;
+       if (python_logging->filter_expression != nullptr) {
+               filter_expression_len = strlen(python_logging->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
        }
@@ -101,20 +96,19 @@ static int lttng_event_rule_python_logging_serialize(
        python_logging_comm.pattern_len = pattern_len;
        python_logging_comm.filter_expression_len = filter_expression_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &python_logging_comm,
-                       sizeof(python_logging_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &python_logging_comm, sizeof(python_logging_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, python_logging->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, python_logging->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, python_logging->filter_expression,
-                       filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, python_logging->filter_expression, filter_expression_len);
        if (ret) {
                goto end;
        }
@@ -127,16 +121,14 @@ static int lttng_event_rule_python_logging_serialize(
        }
 
        header = (typeof(header)) ((char *) payload->buffer.data + header_offset);
-       header->log_level_rule_len =
-                       payload->buffer.size - size_before_log_level_rule;
+       header->log_level_rule_len = payload->buffer.size - size_before_log_level_rule;
 
 end:
        return ret;
 }
 
-static bool lttng_event_rule_python_logging_is_equal(
-               const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+static bool lttng_event_rule_python_logging_is_equal(const struct lttng_event_rule *_a,
+                                                    const struct lttng_event_rule *_b)
 {
        bool is_equal = false;
        struct lttng_event_rule_python_logging *a, *b;
@@ -153,12 +145,12 @@ static bool lttng_event_rule_python_logging_is_equal(
        /* Long check. */
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -166,8 +158,7 @@ static bool lttng_event_rule_python_logging_is_equal(
                goto end;
        }
 
-       if (!lttng_log_level_rule_is_equal(
-                               a->log_level_rule, b->log_level_rule)) {
+       if (!lttng_log_level_rule_is_equal(a->log_level_rule, b->log_level_rule)) {
                goto end;
        }
 
@@ -183,15 +174,14 @@ end:
  *
  * An event with NO loglevel and the name is * will return NULL.
  */
-static int generate_agent_filter(
-               const struct lttng_event_rule *rule, char **_agent_filter)
+static int generate_agent_filter(const struct lttng_event_rule *rule, char **_agent_filter)
 {
        int err;
        int ret = 0;
-       char *agent_filter = NULL;
+       char *agent_filter = nullptr;
        const char *pattern;
        const char *filter;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
        enum lttng_event_rule_status status;
 
        LTTNG_ASSERT(rule);
@@ -205,22 +195,19 @@ static int generate_agent_filter(
 
        status = lttng_event_rule_python_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
-
        /* Don't add filter for the '*' event. */
        if (strcmp(pattern, "*") != 0) {
                if (filter) {
-                       err = asprintf(&agent_filter,
-                                       "(%s) && (logger_name == \"%s\")",
-                                       filter, pattern);
+                       err = asprintf(
+                               &agent_filter, "(%s) && (logger_name == \"%s\")", filter, pattern);
                } else {
-                       err = asprintf(&agent_filter, "logger_name == \"%s\"",
-                                       pattern);
+                       err = asprintf(&agent_filter, "logger_name == \"%s\"", pattern);
                }
 
                if (err < 0) {
@@ -230,23 +217,20 @@ static int generate_agent_filter(
                }
        }
 
-       status = lttng_event_rule_python_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_python_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
                const char *op;
                int level;
 
-               switch (lttng_log_level_rule_get_type(log_level_rule))
-               {
+               switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &level);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule, &level);
                        op = "==";
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &level);
+                               log_level_rule, &level);
                        op = ">=";
                        break;
                default:
@@ -262,16 +246,16 @@ static int generate_agent_filter(
                        char *new_filter;
 
                        err = asprintf(&new_filter,
-                                       "(%s) && (int_loglevel %s %d)",
-                                       agent_filter ? agent_filter : filter,
-                                       op, level);
+                                      "(%s) && (int_loglevel %s %d)",
+                                      agent_filter ? agent_filter : filter,
+                                      op,
+                                      level);
                        if (agent_filter) {
                                free(agent_filter);
                        }
                        agent_filter = new_filter;
                } else {
-                       err = asprintf(&agent_filter, "int_loglevel %s %d", op,
-                                       level);
+                       err = asprintf(&agent_filter, "int_loglevel %s %d", op, level);
                }
 
                if (err < 0) {
@@ -282,7 +266,7 @@ static int generate_agent_filter(
        }
 
        *_agent_filter = agent_filter;
-       agent_filter = NULL;
+       agent_filter = nullptr;
 
 end:
        free(agent_filter);
@@ -290,26 +274,24 @@ end:
 }
 
 static enum lttng_error_code
-lttng_event_rule_python_logging_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+lttng_event_rule_python_logging_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                        const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        char *agent_filter;
 
        LTTNG_ASSERT(rule);
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        status = lttng_event_rule_python_logging_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -328,21 +310,20 @@ lttng_event_rule_python_logging_generate_filter_bytecode(
 
        python_logging->internal_filter.filter = agent_filter;
 
-       if (python_logging->internal_filter.filter == NULL) {
+       if (python_logging->internal_filter.filter == nullptr) {
                ret_code = LTTNG_OK;
                goto end;
        }
 
        ret = run_as_generate_filter_bytecode(
-                       python_logging->internal_filter.filter, creds,
-                       &bytecode);
+               python_logging->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
        }
 
        python_logging->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
        ret_code = LTTNG_OK;
 
 error:
@@ -351,48 +332,43 @@ end:
        return ret_code;
 }
 
-static const char *lttng_event_rule_python_logging_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_python_logging_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_python_logging *python_logging;
 
        LTTNG_ASSERT(rule);
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        return python_logging->internal_filter.filter;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_python_logging_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_python_logging_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_python_logging *python_logging;
 
        LTTNG_ASSERT(rule);
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        return python_logging->internal_filter.bytecode;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_python_logging_generate_exclusions(
-               const struct lttng_event_rule *rule __attribute__((unused)),
-               struct lttng_event_exclusion **_exclusions)
+lttng_event_rule_python_logging_generate_exclusions(const struct lttng_event_rule *rule
+                                                   __attribute__((unused)),
+                                                   struct lttng_event_exclusion **_exclusions)
 {
        /* Unsupported. */
-       *_exclusions = NULL;
+       *_exclusions = nullptr;
        return LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
 }
 
-static unsigned long lttng_event_rule_python_logging_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_python_logging_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        struct lttng_event_rule_python_logging *tp_rule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING, lttng_ht_seed);
        hash ^= hash_key_str(tp_rule->pattern, lttng_ht_seed);
 
        if (tp_rule->filter_expression) {
@@ -406,20 +382,19 @@ static unsigned long lttng_event_rule_python_logging_hash(
        return hash;
 }
 
-static struct lttng_event *lttng_event_rule_python_logging_generate_lttng_event(
-               const struct lttng_event_rule *rule)
+static struct lttng_event *
+lttng_event_rule_python_logging_generate_lttng_event(const struct lttng_event_rule *rule)
 {
        int ret;
        const struct lttng_event_rule_python_logging *python_logging;
-       struct lttng_event *local_event = NULL;
-       struct lttng_event *event = NULL;
+       struct lttng_event *local_event = nullptr;
+       struct lttng_event *event = nullptr;
        enum lttng_loglevel_type loglevel_type;
        int loglevel_value = 0;
        enum lttng_event_rule_status status;
        const struct lttng_log_level_rule *log_level_rule;
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        local_event = zmalloc<lttng_event>();
        if (!local_event) {
@@ -427,33 +402,30 @@ static struct lttng_event *lttng_event_rule_python_logging_generate_lttng_event(
        }
 
        local_event->type = LTTNG_EVENT_TRACEPOINT;
-       ret = lttng_strncpy(local_event->name, python_logging->pattern,
-                           sizeof(local_event->name));
+       ret = lttng_strncpy(local_event->name, python_logging->pattern, sizeof(local_event->name));
        if (ret) {
                ERR("Truncation occurred when copying event rule pattern to `lttng_event` structure: pattern = '%s'",
-                               python_logging->pattern);
+                   python_logging->pattern);
                goto error;
        }
 
-
        /* Map the log level rule to an equivalent lttng_loglevel. */
-       status = lttng_event_rule_python_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_python_logging_get_log_level_rule(rule, &log_level_rule);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
                loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
-               loglevel_value = 0;
+               loglevel_value = LTTNG_LOGLEVEL_PYTHON_NOTSET;
        } else if (status == LTTNG_EVENT_RULE_STATUS_OK) {
                enum lttng_log_level_rule_status llr_status;
 
                switch (lttng_log_level_rule_get_type(log_level_rule)) {
                case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-                       llr_status = lttng_log_level_rule_exactly_get_level(
-                                       log_level_rule, &loglevel_value);
+                       llr_status = lttng_log_level_rule_exactly_get_level(log_level_rule,
+                                                                           &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_SINGLE;
                        break;
                case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                        llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                                       log_level_rule, &loglevel_value);
+                               log_level_rule, &loglevel_value);
                        loglevel_type = LTTNG_EVENT_LOGLEVEL_RANGE;
                        break;
                default:
@@ -472,59 +444,56 @@ static struct lttng_event *lttng_event_rule_python_logging_generate_lttng_event(
        local_event->loglevel = loglevel_value;
 
        event = local_event;
-       local_event = NULL;
+       local_event = nullptr;
 error:
        free(local_event);
        return event;
 }
 
-static enum lttng_error_code lttng_event_rule_python_logging_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_python_logging_mi_serialize(const struct lttng_event_rule *rule,
+                                            struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_PYTHON_LOGGING_EVENT_RULE(rule));
 
-       status = lttng_event_rule_python_logging_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_python_logging_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_python_logging_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
-       status = lttng_event_rule_python_logging_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_python_logging_get_log_level_rule(rule, &log_level_rule);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        /* Open event rule python logging element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_python_logging);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_python_logging);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter expression. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -532,8 +501,7 @@ static enum lttng_error_code lttng_event_rule_python_logging_mi_serialize(
 
        /* Log level rule. */
        if (log_level_rule) {
-               ret_code = lttng_log_level_rule_mi_serialize(
-                               log_level_rule, writer);
+               ret_code = lttng_log_level_rule_mi_serialize(log_level_rule, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
@@ -556,7 +524,7 @@ end:
 
 struct lttng_event_rule *lttng_event_rule_python_logging_create(void)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_python_logging *tp_rule;
        enum lttng_event_rule_status status;
 
@@ -572,51 +540,47 @@ struct lttng_event_rule *lttng_event_rule_python_logging_create(void)
        tp_rule->parent.equal = lttng_event_rule_python_logging_is_equal;
        tp_rule->parent.destroy = lttng_event_rule_python_logging_destroy;
        tp_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_python_logging_generate_filter_bytecode;
-       tp_rule->parent.get_filter =
-                       lttng_event_rule_python_logging_get_internal_filter;
+               lttng_event_rule_python_logging_generate_filter_bytecode;
+       tp_rule->parent.get_filter = lttng_event_rule_python_logging_get_internal_filter;
        tp_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_python_logging_get_internal_filter_bytecode;
-       tp_rule->parent.generate_exclusions =
-                       lttng_event_rule_python_logging_generate_exclusions;
+               lttng_event_rule_python_logging_get_internal_filter_bytecode;
+       tp_rule->parent.generate_exclusions = lttng_event_rule_python_logging_generate_exclusions;
        tp_rule->parent.hash = lttng_event_rule_python_logging_hash;
-       tp_rule->parent.generate_lttng_event =
-                       lttng_event_rule_python_logging_generate_lttng_event;
+       tp_rule->parent.generate_lttng_event = lttng_event_rule_python_logging_generate_lttng_event;
        tp_rule->parent.mi_serialize = lttng_event_rule_python_logging_mi_serialize;
 
-       tp_rule->log_level_rule = NULL;
+       tp_rule->log_level_rule = nullptr;
 
        /* Default pattern is '*'. */
        status = lttng_event_rule_python_logging_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_python_logging_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_python_logging_create_from_payload(struct lttng_payload_view *view,
+                                                           struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_python_logging_comm *python_logging_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
+       const char *filter_expression = nullptr;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_log_level_rule *log_level_rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*python_logging_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*python_logging_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule python_logging: buffer too short to contain header.");
                ret = -1;
@@ -637,7 +601,7 @@ ssize_t lttng_event_rule_python_logging_create_from_payload(
 
        /* Map the pattern. */
        current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, python_logging_comm->pattern_len);
+               &view->buffer, offset, python_logging_comm->pattern_len);
 
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
@@ -645,8 +609,8 @@ ssize_t lttng_event_rule_python_logging_create_from_payload(
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       python_logging_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, python_logging_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -659,8 +623,8 @@ ssize_t lttng_event_rule_python_logging_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       python_logging_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, python_logging_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
@@ -668,8 +632,8 @@ ssize_t lttng_event_rule_python_logging_create_from_payload(
 
        filter_expression = current_buffer_view.data;
        if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                       filter_expression,
-                       python_logging_comm->filter_expression_len)) {
+                                              filter_expression,
+                                              python_logging_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -684,12 +648,11 @@ skip_filter_expression:
 
        {
                /* Map the log level rule. */
-               struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               python_logging_comm->log_level_rule_len);
+               struct lttng_payload_view current_payload_view = lttng_payload_view_from_view(
+                       view, offset, python_logging_comm->log_level_rule_len);
 
-               ret = lttng_log_level_rule_create_from_payload(
-                               &current_payload_view, &log_level_rule);
+               ret = lttng_log_level_rule_create_from_payload(&current_payload_view,
+                                                              &log_level_rule);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -711,8 +674,7 @@ skip_log_level_rule:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_python_logging_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_python_logging_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule python_logging pattern.");
                        ret = -1;
@@ -721,8 +683,7 @@ skip_log_level_rule:
        }
 
        if (log_level_rule) {
-               status = lttng_event_rule_python_logging_set_log_level_rule(
-                               rule, log_level_rule);
+               status = lttng_event_rule_python_logging_set_log_level_rule(rule, log_level_rule);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule python_logging log level rule.");
                        ret = -1;
@@ -731,7 +692,7 @@ skip_log_level_rule:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        lttng_log_level_rule_destroy(log_level_rule);
@@ -739,21 +700,19 @@ end:
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_python_logging_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_python_logging_set_name_pattern(struct lttng_event_rule *rule, const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_PYTHON_LOGGING_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_PYTHON_LOGGING_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        pattern_copy = strdup(pattern);
        if (!pattern_copy) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
@@ -766,13 +725,14 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_set_name_pattern(
        free(python_logging->pattern);
 
        python_logging->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_python_logging_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_python_logging_get_name_pattern(const struct lttng_event_rule *rule,
+                                                const char **pattern)
 {
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -782,8 +742,7 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_get_name_pattern(
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        if (!python_logging->pattern) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -794,21 +753,20 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_python_logging_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status
+lttng_event_rule_python_logging_set_filter(struct lttng_event_rule *rule, const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
        if (!rule || !IS_PYTHON_LOGGING_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+           strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        expression_copy = strdup(expression);
        if (!expression_copy) {
                PERROR("Failed to copy filter expression");
@@ -821,13 +779,14 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_set_filter(
        }
 
        python_logging->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_python_logging_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_python_logging_get_filter(const struct lttng_event_rule *rule,
+                                          const char **expression)
 {
        const struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -837,8 +796,7 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_get_filter(
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
        if (!python_logging->filter_expression) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -849,8 +807,7 @@ end:
        return status;
 }
 
-static bool log_level_rule_valid(
-               const struct lttng_log_level_rule *rule __attribute__((unused)))
+static bool log_level_rule_valid(const struct lttng_log_level_rule *rule __attribute__((unused)))
 {
        /*
         * For python, custom log level are possible, it is not clear if
@@ -862,20 +819,18 @@ static bool log_level_rule_valid(
 }
 
 enum lttng_event_rule_status lttng_event_rule_python_logging_set_log_level_rule(
-               struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule)
+       struct lttng_event_rule *rule, const struct lttng_log_level_rule *log_level_rule)
 {
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
-       struct lttng_log_level_rule *copy = NULL;
+       struct lttng_log_level_rule *copy = nullptr;
 
        if (!rule || !IS_PYTHON_LOGGING_EVENT_RULE(rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
 
        if (!log_level_rule_valid(log_level_rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
@@ -883,7 +838,7 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_set_log_level_rule(
        }
 
        copy = lttng_log_level_rule_copy(log_level_rule);
-       if (copy == NULL) {
+       if (copy == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
                goto end;
        }
@@ -899,9 +854,7 @@ end:
 }
 
 enum lttng_event_rule_status lttng_event_rule_python_logging_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule
-               )
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule)
 {
        struct lttng_event_rule_python_logging *python_logging;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -911,9 +864,8 @@ enum lttng_event_rule_status lttng_event_rule_python_logging_get_log_level_rule(
                goto end;
        }
 
-       python_logging = lttng::utils::container_of(
-                       rule, &lttng_event_rule_python_logging::parent);
-       if (python_logging->log_level_rule == NULL) {
+       python_logging = lttng::utils::container_of(rule, &lttng_event_rule_python_logging::parent);
+       if (python_logging->log_level_rule == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
        }
index 318bc21c805281bbd3fc46f38501be1e8a2e6704..e892b0ce89cf4d2c3274f2785226d76bd77e5431 100644 (file)
@@ -16,6 +16,7 @@
 #include <common/payload.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/string-utils.hpp>
+
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/event-rule/user-tracepoint-internal.hpp>
 #include <lttng/event.h>
@@ -28,12 +29,11 @@ static void lttng_event_rule_user_tracepoint_destroy(struct lttng_event_rule *ru
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
 
-       if (rule == NULL) {
+       if (rule == nullptr) {
                return;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
        lttng_log_level_rule_destroy(tracepoint->log_level_rule);
        lttng_dynamic_pointer_array_reset(&tracepoint->exclusions);
@@ -44,8 +44,7 @@ static void lttng_event_rule_user_tracepoint_destroy(struct lttng_event_rule *ru
        free(tracepoint);
 }
 
-static bool lttng_event_rule_user_tracepoint_validate(
-               const struct lttng_event_rule *rule)
+static bool lttng_event_rule_user_tracepoint_validate(const struct lttng_event_rule *rule)
 {
        bool valid = false;
        struct lttng_event_rule_user_tracepoint *tracepoint;
@@ -54,8 +53,7 @@ static bool lttng_event_rule_user_tracepoint_validate(
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
        /* Required field. */
        if (!tracepoint->pattern) {
@@ -68,9 +66,8 @@ end:
        return valid;
 }
 
-static int lttng_event_rule_user_tracepoint_serialize(
-               const struct lttng_event_rule *rule,
-               struct lttng_payload *payload)
+static int lttng_event_rule_user_tracepoint_serialize(const struct lttng_event_rule *rule,
+                                                     struct lttng_payload *payload)
 {
        int ret, i;
        size_t pattern_len, filter_expression_len, exclusions_len, header_offset;
@@ -90,17 +87,16 @@ static int lttng_event_rule_user_tracepoint_serialize(
        header_offset = payload->buffer.size;
 
        DBG("Serializing user tracepoint event rule.");
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
-       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(rule, &exclusion_count);
+       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
+               rule, &exclusion_count);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
        pattern_len = strlen(tracepoint->pattern) + 1;
 
-       if (tracepoint->filter_expression != NULL) {
-               filter_expression_len =
-                               strlen(tracepoint->filter_expression) + 1;
+       if (tracepoint->filter_expression != nullptr) {
+               filter_expression_len = strlen(tracepoint->filter_expression) + 1;
        } else {
                filter_expression_len = 0;
        }
@@ -110,7 +106,7 @@ static int lttng_event_rule_user_tracepoint_serialize(
                const char *exclusion;
 
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               rule, i, &exclusion);
+                       rule, i, &exclusion);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
                /* Length field. */
@@ -124,20 +120,19 @@ static int lttng_event_rule_user_tracepoint_serialize(
        tracepoint_comm.exclusions_count = exclusion_count;
        tracepoint_comm.exclusions_len = exclusions_len;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &tracepoint_comm,
-                       sizeof(tracepoint_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &tracepoint_comm, sizeof(tracepoint_comm));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, tracepoint->pattern, pattern_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, tracepoint->pattern, pattern_len);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, tracepoint->filter_expression,
-                       filter_expression_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, tracepoint->filter_expression, filter_expression_len);
        if (ret) {
                goto end;
        }
@@ -150,21 +145,23 @@ static int lttng_event_rule_user_tracepoint_serialize(
        }
 
        header = (typeof(header)) ((char *) payload->buffer.data + header_offset);
-       header->log_level_rule_len =
-                       payload->buffer.size - size_before_log_level_rule;
+       header->log_level_rule_len = payload->buffer.size - size_before_log_level_rule;
 
        for (i = 0; i < exclusion_count; i++) {
                size_t len;
+               uint32_t serialized_len;
                const char *exclusion;
 
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               rule, i, &exclusion);
+                       rule, i, &exclusion);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
                len = strlen(exclusion) + 1;
+
+               serialized_len = len;
                /* Append exclusion length, includes the null terminator. */
                ret = lttng_dynamic_buffer_append(
-                               &payload->buffer, &len, sizeof(uint32_t));
+                       &payload->buffer, &serialized_len, sizeof(serialized_len));
                if (ret) {
                        goto end;
                }
@@ -172,8 +169,7 @@ static int lttng_event_rule_user_tracepoint_serialize(
                exclusions_appended_len += sizeof(uint32_t);
 
                /* Include the '\0' in the payload. */
-               ret = lttng_dynamic_buffer_append(
-                               &payload->buffer, exclusion, len);
+               ret = lttng_dynamic_buffer_append(&payload->buffer, exclusion, len);
                if (ret) {
                        goto end;
                }
@@ -187,9 +183,8 @@ end:
        return ret;
 }
 
-static bool lttng_event_rule_user_tracepoint_is_equal(
-               const struct lttng_event_rule *_a,
-               const struct lttng_event_rule *_b)
+static bool lttng_event_rule_user_tracepoint_is_equal(const struct lttng_event_rule *_a,
+                                                     const struct lttng_event_rule *_b)
 {
        int i;
        bool is_equal = false;
@@ -217,12 +212,12 @@ static bool lttng_event_rule_user_tracepoint_is_equal(
        /* Long check. */
        LTTNG_ASSERT(a->pattern);
        LTTNG_ASSERT(b->pattern);
-       if (strcmp(a->pattern, b->pattern)) {
+       if (strcmp(a->pattern, b->pattern) != 0) {
                goto end;
        }
 
        if (a->filter_expression && b->filter_expression) {
-               if (strcmp(a->filter_expression, b->filter_expression)) {
+               if (strcmp(a->filter_expression, b->filter_expression) != 0) {
                        goto end;
                }
        } else if (!!a->filter_expression != !!b->filter_expression) {
@@ -230,8 +225,7 @@ static bool lttng_event_rule_user_tracepoint_is_equal(
                goto end;
        }
 
-       if (!lttng_log_level_rule_is_equal(
-                               a->log_level_rule, b->log_level_rule)) {
+       if (!lttng_log_level_rule_is_equal(a->log_level_rule, b->log_level_rule)) {
                goto end;
        }
 
@@ -239,12 +233,12 @@ static bool lttng_event_rule_user_tracepoint_is_equal(
                const char *exclusion_a, *exclusion_b;
 
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               _a, i, &exclusion_a);
+                       _a, i, &exclusion_a);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               _b, i, &exclusion_b);
+                       _b, i, &exclusion_b);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
-               if (strcmp(exclusion_a, exclusion_b)) {
+               if (strcmp(exclusion_a, exclusion_b) != 0) {
                        goto end;
                }
        }
@@ -255,25 +249,23 @@ end:
 }
 
 static enum lttng_error_code
-lttng_event_rule_user_tracepoint_generate_filter_bytecode(
-               struct lttng_event_rule *rule,
-               const struct lttng_credentials *creds)
+lttng_event_rule_user_tracepoint_generate_filter_bytecode(struct lttng_event_rule *rule,
+                                                         const struct lttng_credentials *creds)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status;
        const char *filter;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
 
        LTTNG_ASSERT(rule);
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
        status = lttng_event_rule_user_tracepoint_get_filter(rule, &filter);
        if (status == LTTNG_EVENT_RULE_STATUS_UNSET) {
-               filter = NULL;
+               filter = nullptr;
        } else if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
@@ -286,29 +278,27 @@ lttng_event_rule_user_tracepoint_generate_filter_bytecode(
 
        if (filter) {
                tracepoint->internal_filter.filter = strdup(filter);
-               if (tracepoint->internal_filter.filter == NULL) {
+               if (tracepoint->internal_filter.filter == nullptr) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto error;
                }
        } else {
-               tracepoint->internal_filter.filter = NULL;
+               tracepoint->internal_filter.filter = nullptr;
        }
 
-       if (tracepoint->internal_filter.filter == NULL) {
+       if (tracepoint->internal_filter.filter == nullptr) {
                ret_code = LTTNG_OK;
                goto end;
        }
 
-       ret = run_as_generate_filter_bytecode(
-                       tracepoint->internal_filter.filter, creds,
-                       &bytecode);
+       ret = run_as_generate_filter_bytecode(tracepoint->internal_filter.filter, creds, &bytecode);
        if (ret) {
                ret_code = LTTNG_ERR_FILTER_INVAL;
                goto end;
        }
 
        tracepoint->internal_filter.bytecode = bytecode;
-       bytecode = NULL;
+       bytecode = nullptr;
        ret_code = LTTNG_OK;
 
 error:
@@ -317,33 +307,29 @@ end:
        return ret_code;
 }
 
-static const char *lttng_event_rule_user_tracepoint_get_internal_filter(
-               const struct lttng_event_rule *rule)
+static const char *
+lttng_event_rule_user_tracepoint_get_internal_filter(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
 
        LTTNG_ASSERT(rule);
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        return tracepoint->internal_filter.filter;
 }
 
 static const struct lttng_bytecode *
-lttng_event_rule_user_tracepoint_get_internal_filter_bytecode(
-               const struct lttng_event_rule *rule)
+lttng_event_rule_user_tracepoint_get_internal_filter_bytecode(const struct lttng_event_rule *rule)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
 
        LTTNG_ASSERT(rule);
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        return tracepoint->internal_filter.bytecode;
 }
 
 static enum lttng_event_rule_generate_exclusions_status
-lttng_event_rule_user_tracepoint_generate_exclusions(
-               const struct lttng_event_rule *rule,
-               struct lttng_event_exclusion **_exclusions)
+lttng_event_rule_user_tracepoint_generate_exclusions(const struct lttng_event_rule *rule,
+                                                    struct lttng_event_exclusion **_exclusions)
 {
        unsigned int nb_exclusions = 0, i;
        struct lttng_event_exclusion *exclusions;
@@ -353,16 +339,17 @@ lttng_event_rule_user_tracepoint_generate_exclusions(
        LTTNG_ASSERT(_exclusions);
 
        event_rule_status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-                       rule, &nb_exclusions);
+               rule, &nb_exclusions);
        LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
        if (nb_exclusions == 0) {
                /* Nothing to do. */
-               exclusions = NULL;
+               exclusions = nullptr;
                ret_status = LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_NONE;
                goto end;
        }
 
-       exclusions = zmalloc<lttng_event_exclusion>(sizeof(struct lttng_event_exclusion) + (LTTNG_SYMBOL_NAME_LEN * nb_exclusions));
+       exclusions = zmalloc<lttng_event_exclusion>(sizeof(struct lttng_event_exclusion) +
+                                                   (LTTNG_SYMBOL_NAME_LEN * nb_exclusions));
        if (!exclusions) {
                PERROR("Failed to allocate exclusions buffer");
                ret_status = LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_OUT_OF_MEMORY;
@@ -375,17 +362,16 @@ lttng_event_rule_user_tracepoint_generate_exclusions(
                const char *exclusion_str;
 
                event_rule_status =
-                               lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                                               rule, i, &exclusion_str);
+                       lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
+                               rule, i, &exclusion_str);
                LTTNG_ASSERT(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK);
 
-               copy_ret = lttng_strncpy(
-                               LTTNG_EVENT_EXCLUSION_NAME_AT(exclusions, i),
-                               exclusion_str,
-                               sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusions, i)));
+               copy_ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusions, i),
+                                        exclusion_str,
+                                        sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusions, i)));
                if (copy_ret) {
                        free(exclusions);
-                       exclusions = NULL;
+                       exclusions = nullptr;
                        ret_status = LTTNG_EVENT_RULE_GENERATE_EXCLUSIONS_STATUS_ERROR;
                        goto end;
                }
@@ -403,17 +389,15 @@ static void destroy_lttng_exclusions_element(void *ptr)
        free(ptr);
 }
 
-static unsigned long lttng_event_rule_user_tracepoint_hash(
-               const struct lttng_event_rule *rule)
+static unsigned long lttng_event_rule_user_tracepoint_hash(const struct lttng_event_rule *rule)
 {
        unsigned long hash;
        unsigned int i, exclusion_count;
        enum lttng_event_rule_status status;
        struct lttng_event_rule_user_tracepoint *tp_rule =
-                       lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
+               lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
-       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT,
-                       lttng_ht_seed);
+       hash = hash_key_ulong((void *) LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT, lttng_ht_seed);
        hash ^= hash_key_str(tp_rule->pattern, lttng_ht_seed);
 
        if (tp_rule->filter_expression) {
@@ -424,15 +408,15 @@ static unsigned long lttng_event_rule_user_tracepoint_hash(
                hash ^= lttng_log_level_rule_hash(tp_rule->log_level_rule);
        }
 
-       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(rule,
-                       &exclusion_count);
+       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
+               rule, &exclusion_count);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
        for (i = 0; i < exclusion_count; i++) {
                const char *exclusion;
 
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               rule, i, &exclusion);
+                       rule, i, &exclusion);
                LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
                hash ^= hash_key_str(exclusion, lttng_ht_seed);
        }
@@ -440,58 +424,55 @@ static unsigned long lttng_event_rule_user_tracepoint_hash(
        return hash;
 }
 
-static enum lttng_error_code lttng_event_rule_user_tracepoint_mi_serialize(
-               const struct lttng_event_rule *rule, struct mi_writer *writer)
+static enum lttng_error_code
+lttng_event_rule_user_tracepoint_mi_serialize(const struct lttng_event_rule *rule,
+                                             struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_event_rule_status status;
-       const char *filter = NULL;
-       const char *name_pattern = NULL;
-       const struct lttng_log_level_rule *log_level_rule = NULL;
+       const char *filter = nullptr;
+       const char *name_pattern = nullptr;
+       const struct lttng_log_level_rule *log_level_rule = nullptr;
        unsigned int exclusion_count = 0;
 
        LTTNG_ASSERT(rule);
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(IS_USER_TRACEPOINT_EVENT_RULE(rule));
 
-       status = lttng_event_rule_user_tracepoint_get_name_pattern(
-                       rule, &name_pattern);
+       status = lttng_event_rule_user_tracepoint_get_name_pattern(rule, &name_pattern);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
        LTTNG_ASSERT(name_pattern);
 
        status = lttng_event_rule_user_tracepoint_get_filter(rule, &filter);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
-       status = lttng_event_rule_user_tracepoint_get_log_level_rule(
-                       rule, &log_level_rule);
+       status = lttng_event_rule_user_tracepoint_get_log_level_rule(rule, &log_level_rule);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK ||
-                       status == LTTNG_EVENT_RULE_STATUS_UNSET);
+                    status == LTTNG_EVENT_RULE_STATUS_UNSET);
 
        status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-                       rule, &exclusion_count);
+               rule, &exclusion_count);
        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
        /* Open event rule user tracepoint element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_event_rule_user_tracepoint);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_event_rule_user_tracepoint);
        if (ret) {
                goto mi_error;
        }
 
        /* Name pattern. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_event_rule_name_pattern, name_pattern);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_event_rule_name_pattern, name_pattern);
        if (ret) {
                goto mi_error;
        }
 
        /* Filter expression. */
-       if (filter != NULL) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_event_rule_filter_expression,
-                               filter);
+       if (filter != nullptr) {
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_event_rule_filter_expression, filter);
                if (ret) {
                        goto mi_error;
                }
@@ -499,8 +480,7 @@ static enum lttng_error_code lttng_event_rule_user_tracepoint_mi_serialize(
 
        /* Log level rule. */
        if (log_level_rule) {
-               ret_code = lttng_log_level_rule_mi_serialize(
-                               log_level_rule, writer);
+               ret_code = lttng_log_level_rule_mi_serialize(log_level_rule, writer);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
@@ -510,8 +490,9 @@ static enum lttng_error_code lttng_event_rule_user_tracepoint_mi_serialize(
                int i;
 
                /* Open the exclusion list. */
-               ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions);
+               ret = mi_lttng_writer_open_element(
+                       writer,
+                       mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions);
                if (ret) {
                        goto mi_error;
                }
@@ -519,13 +500,15 @@ static enum lttng_error_code lttng_event_rule_user_tracepoint_mi_serialize(
                for (i = 0; i < exclusion_count; i++) {
                        const char *exclusion;
 
-                       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
+                       status =
+                               lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
                                        rule, i, &exclusion);
                        LTTNG_ASSERT(status == LTTNG_EVENT_RULE_STATUS_OK);
 
-                       ret = mi_lttng_writer_write_element_string(writer,
-                                       mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion,
-                                       exclusion);
+                       ret = mi_lttng_writer_write_element_string(
+                               writer,
+                               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion,
+                               exclusion);
                        if (ret) {
                                goto mi_error;
                        }
@@ -555,7 +538,7 @@ end:
 
 struct lttng_event_rule *lttng_event_rule_user_tracepoint_create(void)
 {
-       struct lttng_event_rule *rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
        struct lttng_event_rule_user_tracepoint *tp_rule;
        enum lttng_event_rule_status status;
 
@@ -571,59 +554,55 @@ struct lttng_event_rule *lttng_event_rule_user_tracepoint_create(void)
        tp_rule->parent.equal = lttng_event_rule_user_tracepoint_is_equal;
        tp_rule->parent.destroy = lttng_event_rule_user_tracepoint_destroy;
        tp_rule->parent.generate_filter_bytecode =
-                       lttng_event_rule_user_tracepoint_generate_filter_bytecode;
-       tp_rule->parent.get_filter =
-                       lttng_event_rule_user_tracepoint_get_internal_filter;
+               lttng_event_rule_user_tracepoint_generate_filter_bytecode;
+       tp_rule->parent.get_filter = lttng_event_rule_user_tracepoint_get_internal_filter;
        tp_rule->parent.get_filter_bytecode =
-                       lttng_event_rule_user_tracepoint_get_internal_filter_bytecode;
-       tp_rule->parent.generate_exclusions =
-                       lttng_event_rule_user_tracepoint_generate_exclusions;
+               lttng_event_rule_user_tracepoint_get_internal_filter_bytecode;
+       tp_rule->parent.generate_exclusions = lttng_event_rule_user_tracepoint_generate_exclusions;
        tp_rule->parent.hash = lttng_event_rule_user_tracepoint_hash;
        tp_rule->parent.mi_serialize = lttng_event_rule_user_tracepoint_mi_serialize;
 
        /* Not necessary for now. */
-       tp_rule->parent.generate_lttng_event = NULL;
+       tp_rule->parent.generate_lttng_event = nullptr;
 
-       tp_rule->log_level_rule = NULL;
+       tp_rule->log_level_rule = nullptr;
 
-       lttng_dynamic_pointer_array_init(&tp_rule->exclusions,
-                       destroy_lttng_exclusions_element);
+       lttng_dynamic_pointer_array_init(&tp_rule->exclusions, destroy_lttng_exclusions_element);
 
        /* Default pattern is '*'. */
        status = lttng_event_rule_user_tracepoint_set_name_pattern(rule, "*");
        if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                lttng_event_rule_destroy(rule);
-               rule = NULL;
+               rule = nullptr;
        }
 
 end:
        return rule;
 }
 
-ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_rule **_event_rule)
+ssize_t lttng_event_rule_user_tracepoint_create_from_payload(struct lttng_payload_view *view,
+                                                            struct lttng_event_rule **_event_rule)
 {
        ssize_t ret, offset = 0;
        int i;
        enum lttng_event_rule_status status;
        const struct lttng_event_rule_user_tracepoint_comm *tracepoint_comm;
        const char *pattern;
-       const char *filter_expression = NULL;
-       const char **exclusions = NULL;
+       const char *filter_expression = nullptr;
+       const char **exclusions = nullptr;
        const uint32_t *exclusion_len;
        const char *exclusion;
        struct lttng_buffer_view current_buffer_view;
-       struct lttng_event_rule *rule = NULL;
-       struct lttng_log_level_rule *log_level_rule = NULL;
+       struct lttng_event_rule *rule = nullptr;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
 
        if (!_event_rule) {
                ret = -1;
                goto end;
        }
 
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*tracepoint_comm));
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*tracepoint_comm));
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ERR("Failed to initialize from malformed event rule tracepoint: buffer too short to contain header.");
                ret = -1;
@@ -643,8 +622,8 @@ ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
        offset += current_buffer_view.size;
 
        /* Map the pattern. */
-       current_buffer_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, tracepoint_comm->pattern_len);
+       current_buffer_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, tracepoint_comm->pattern_len);
 
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
@@ -652,8 +631,8 @@ ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
        }
 
        pattern = current_buffer_view.data;
-       if (!lttng_buffer_view_contains_string(&current_buffer_view, pattern,
-                       tracepoint_comm->pattern_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &current_buffer_view, pattern, tracepoint_comm->pattern_len)) {
                ret = -1;
                goto end;
        }
@@ -666,8 +645,8 @@ ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
        }
 
        /* Map the filter_expression. */
-       current_buffer_view = lttng_buffer_view_from_view(&view->buffer, offset,
-                       tracepoint_comm->filter_expression_len);
+       current_buffer_view = lttng_buffer_view_from_view(
+               &view->buffer, offset, tracepoint_comm->filter_expression_len);
        if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                ret = -1;
                goto end;
@@ -675,8 +654,8 @@ ssize_t lttng_event_rule_user_tracepoint_create_from_payload(
 
        filter_expression = current_buffer_view.data;
        if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                       filter_expression,
-                       tracepoint_comm->filter_expression_len)) {
+                                              filter_expression,
+                                              tracepoint_comm->filter_expression_len)) {
                ret = -1;
                goto end;
        }
@@ -691,12 +670,11 @@ skip_filter_expression:
 
        {
                /* Map the log level rule. */
-               struct lttng_payload_view current_payload_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               tracepoint_comm->log_level_rule_len);
+               struct lttng_payload_view current_payload_view = lttng_payload_view_from_view(
+                       view, offset, tracepoint_comm->log_level_rule_len);
 
-               ret = lttng_log_level_rule_create_from_payload(
-                               &current_payload_view, &log_level_rule);
+               ret = lttng_log_level_rule_create_from_payload(&current_payload_view,
+                                                              &log_level_rule);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -710,8 +688,8 @@ skip_filter_expression:
 
 skip_log_level_rule:
        for (i = 0; i < tracepoint_comm->exclusions_count; i++) {
-               current_buffer_view = lttng_buffer_view_from_view(
-                               &view->buffer, offset, sizeof(*exclusion_len));
+               current_buffer_view =
+                       lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*exclusion_len));
                if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                        ret = -1;
                        goto end;
@@ -720,24 +698,25 @@ skip_log_level_rule:
                exclusion_len = (typeof(exclusion_len)) current_buffer_view.data;
                offset += sizeof(*exclusion_len);
 
-               current_buffer_view = lttng_buffer_view_from_view(
-                               &view->buffer, offset, *exclusion_len);
+               current_buffer_view =
+                       lttng_buffer_view_from_view(&view->buffer, offset, *exclusion_len);
                if (!lttng_buffer_view_is_valid(&current_buffer_view)) {
                        ret = -1;
                        goto end;
                }
 
                exclusion = current_buffer_view.data;
-               if (!lttng_buffer_view_contains_string(&current_buffer_view,
-                               exclusion, *exclusion_len)) {
+               if (!lttng_buffer_view_contains_string(
+                           &current_buffer_view, exclusion, *exclusion_len)) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(rule, exclusion);
+               status = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(rule,
+                                                                                    exclusion);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to add event rule user tracepoint exclusion \"%s\".",
-                                       exclusion);
+                           exclusion);
                        ret = -1;
                        goto end;
                }
@@ -754,8 +733,7 @@ skip_log_level_rule:
        }
 
        if (filter_expression) {
-               status = lttng_event_rule_user_tracepoint_set_filter(
-                               rule, filter_expression);
+               status = lttng_event_rule_user_tracepoint_set_filter(rule, filter_expression);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule user tracepoint pattern.");
                        ret = -1;
@@ -764,8 +742,7 @@ skip_log_level_rule:
        }
 
        if (log_level_rule) {
-               status = lttng_event_rule_user_tracepoint_set_log_level_rule(
-                               rule, log_level_rule);
+               status = lttng_event_rule_user_tracepoint_set_log_level_rule(rule, log_level_rule);
                if (status != LTTNG_EVENT_RULE_STATUS_OK) {
                        ERR("Failed to set event rule user tracepoint log level rule.");
                        ret = -1;
@@ -774,7 +751,7 @@ skip_log_level_rule:
        }
 
        *_event_rule = rule;
-       rule = NULL;
+       rule = nullptr;
        ret = offset;
 end:
        free(exclusions);
@@ -783,21 +760,20 @@ end:
        return ret;
 }
 
-enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_name_pattern(
-               struct lttng_event_rule *rule, const char *pattern)
+enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_set_name_pattern(struct lttng_event_rule *rule,
+                                                 const char *pattern)
 {
-       char *pattern_copy = NULL;
+       char *pattern_copy = nullptr;
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule) || !pattern ||
-                       strlen(pattern) == 0) {
+       if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule) || !pattern || strlen(pattern) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        pattern_copy = strdup(pattern);
        if (!pattern_copy) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
@@ -810,13 +786,14 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_name_pattern(
        free(tracepoint->pattern);
 
        tracepoint->pattern = pattern_copy;
-       pattern_copy = NULL;
+       pattern_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern(
-               const struct lttng_event_rule *rule, const char **pattern)
+enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_get_name_pattern(const struct lttng_event_rule *rule,
+                                                 const char **pattern)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -826,8 +803,7 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern(
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        if (!tracepoint->pattern) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -838,21 +814,20 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_filter(
-               struct lttng_event_rule *rule, const char *expression)
+enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_set_filter(struct lttng_event_rule *rule, const char *expression)
 {
-       char *expression_copy = NULL;
+       char *expression_copy = nullptr;
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
        if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule) || !expression ||
-                       strlen(expression) == 0) {
+           strlen(expression) == 0) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        expression_copy = strdup(expression);
        if (!expression_copy) {
                PERROR("Failed to copy filter expression");
@@ -865,13 +840,14 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_filter(
        }
 
        tracepoint->filter_expression = expression_copy;
-       expression_copy = NULL;
+       expression_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_filter(
-               const struct lttng_event_rule *rule, const char **expression)
+enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_get_filter(const struct lttng_event_rule *rule,
+                                           const char **expression)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -881,8 +857,7 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_filter(
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        if (!tracepoint->filter_expression) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
@@ -904,8 +879,7 @@ static bool log_level_rule_valid(const struct lttng_log_level_rule *rule)
                status = lttng_log_level_rule_exactly_get_level(rule, &level);
                break;
        case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
-               status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                               rule, &level);
+               status = lttng_log_level_rule_at_least_as_severe_as_get_level(rule, &level);
                break;
        default:
                abort();
@@ -929,20 +903,18 @@ end:
 }
 
 enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_log_level_rule(
-               struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule)
+       struct lttng_event_rule *rule, const struct lttng_log_level_rule *log_level_rule)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
-       struct lttng_log_level_rule *copy = NULL;
+       struct lttng_log_level_rule *copy = nullptr;
 
        if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
        if (!log_level_rule_valid(log_level_rule)) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
@@ -950,7 +922,7 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_set_log_level_rule
        }
 
        copy = lttng_log_level_rule_copy(log_level_rule);
-       if (copy == NULL) {
+       if (copy == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
                goto end;
        }
@@ -966,9 +938,7 @@ end:
 }
 
 enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_log_level_rule(
-               const struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule **log_level_rule
-               )
+       const struct lttng_event_rule *rule, const struct lttng_log_level_rule **log_level_rule)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -978,9 +948,8 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_log_level_rule
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
-       if (tracepoint->log_level_rule == NULL) {
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
+       if (tracepoint->log_level_rule == nullptr) {
                status = LTTNG_EVENT_RULE_STATUS_UNSET;
                goto end;
        }
@@ -990,23 +959,21 @@ end:
        return status;
 }
 
-enum lttng_event_rule_status lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
-               struct lttng_event_rule *rule,
-               const char *exclusion)
+enum lttng_event_rule_status
+lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(struct lttng_event_rule *rule,
+                                                           const char *exclusion)
 {
        int ret;
-       char *exclusion_copy = NULL;
+       char *exclusion_copy = nullptr;
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
 
-       if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule) ||
-                       !exclusion) {
+       if (!rule || !IS_USER_TRACEPOINT_EVENT_RULE(rule) || !exclusion) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
 
        if (strlen(exclusion) >= LTTNG_SYMBOL_NAME_LEN) {
                status = LTTNG_EVENT_RULE_STATUS_INVALID;
@@ -1019,21 +986,20 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_add_name_pattern_e
                goto end;
        }
 
-       ret = lttng_dynamic_pointer_array_add_pointer(&tracepoint->exclusions,
-                       exclusion_copy);
+       ret = lttng_dynamic_pointer_array_add_pointer(&tracepoint->exclusions, exclusion_copy);
        if (ret < 0) {
                status = LTTNG_EVENT_RULE_STATUS_ERROR;
                goto end;
        }
 
-       exclusion_copy = NULL;
+       exclusion_copy = nullptr;
 end:
        free(exclusion_copy);
        return status;
 }
 
 enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-               const struct lttng_event_rule *rule, unsigned int *count)
+       const struct lttng_event_rule *rule, unsigned int *count)
 {
        struct lttng_event_rule_user_tracepoint *tracepoint;
        enum lttng_event_rule_status status = LTTNG_EVENT_RULE_STATUS_OK;
@@ -1043,17 +1009,14 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern_e
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        *count = lttng_dynamic_pointer_array_get_count(&tracepoint->exclusions);
 end:
        return status;
 }
 
 enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-               const struct lttng_event_rule *rule,
-               unsigned int index,
-               const char **exclusion)
+       const struct lttng_event_rule *rule, unsigned int index, const char **exclusion)
 {
        unsigned int count;
        struct lttng_event_rule_user_tracepoint *tracepoint;
@@ -1064,10 +1027,9 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern_e
                goto end;
        }
 
-       tracepoint = lttng::utils::container_of(
-                       rule, &lttng_event_rule_user_tracepoint::parent);
+       tracepoint = lttng::utils::container_of(rule, &lttng_event_rule_user_tracepoint::parent);
        if (lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(rule, &count) !=
-                       LTTNG_EVENT_RULE_STATUS_OK) {
+           LTTNG_EVENT_RULE_STATUS_OK) {
                goto end;
        }
 
@@ -1075,8 +1037,8 @@ enum lttng_event_rule_status lttng_event_rule_user_tracepoint_get_name_pattern_e
                goto end;
        }
 
-       *exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                       &tracepoint->exclusions, index);
+       *exclusion = (const char *) lttng_dynamic_pointer_array_get_pointer(&tracepoint->exclusions,
+                                                                           index);
 end:
        return status;
 }
index f33518eee4eece45c2c8ce762cb22765a682209b..a6d48eaf7f80e2001226aba7467394e34793183b 100644 (file)
@@ -67,20 +67,18 @@ end:
        return new_event;
 error:
        free(new_event);
-       new_event = NULL;
+       new_event = nullptr;
        goto end;
 }
 
-static int lttng_event_probe_attr_serialize(
-               const struct lttng_event_probe_attr *probe,
-               struct lttng_payload *payload)
+static int lttng_event_probe_attr_serialize(const struct lttng_event_probe_attr *probe,
+                                           struct lttng_payload *payload)
 {
        int ret;
        size_t symbol_name_len;
        struct lttng_event_probe_attr_comm comm = {};
 
-       symbol_name_len = lttng_strnlen(
-                       probe->symbol_name, sizeof(probe->symbol_name));
+       symbol_name_len = lttng_strnlen(probe->symbol_name, sizeof(probe->symbol_name));
        if (symbol_name_len == sizeof(probe->symbol_name)) {
                /* Not null-termintated. */
                ret = -1;
@@ -94,22 +92,19 @@ static int lttng_event_probe_attr_serialize(
        comm.addr = probe->addr;
        comm.offset = probe->addr;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret < 0) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, probe->symbol_name, symbol_name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, probe->symbol_name, symbol_name_len);
 end:
        return ret;
 }
 
-static int lttng_event_function_attr_serialize(
-               const struct lttng_event_function_attr *function,
-               struct lttng_payload *payload)
+static int lttng_event_function_attr_serialize(const struct lttng_event_function_attr *function,
+                                              struct lttng_payload *payload)
 {
        int ret;
        size_t symbol_name_len;
@@ -117,8 +112,7 @@ static int lttng_event_function_attr_serialize(
 
        comm.symbol_name_len = 0;
 
-       symbol_name_len = lttng_strnlen(
-                       function->symbol_name, sizeof(function->symbol_name));
+       symbol_name_len = lttng_strnlen(function->symbol_name, sizeof(function->symbol_name));
        if (symbol_name_len == sizeof(function->symbol_name)) {
                /* Not null-termintated. */
                ret = -1;
@@ -130,28 +124,26 @@ static int lttng_event_function_attr_serialize(
 
        comm.symbol_name_len = (uint32_t) symbol_name_len;
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret < 0) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       function->symbol_name, symbol_name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, function->symbol_name, symbol_name_len);
 end:
        return ret;
 }
 
-static ssize_t lttng_event_probe_attr_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_probe_attr **probe_attr)
+static ssize_t
+lttng_event_probe_attr_create_from_payload(struct lttng_payload_view *view,
+                                          struct lttng_event_probe_attr **probe_attr)
 {
        ssize_t ret, offset = 0;
        const struct lttng_event_probe_attr_comm *comm;
-       struct lttng_event_probe_attr *local_attr = NULL;
-       struct lttng_payload_view comm_view = lttng_payload_view_from_view(
-                       view, offset, sizeof(*comm));
+       struct lttng_event_probe_attr *local_attr = nullptr;
+       struct lttng_payload_view comm_view =
+               lttng_payload_view_from_view(view, offset, sizeof(*comm));
 
        if (!lttng_payload_view_is_valid(&comm_view)) {
                ret = -1;
@@ -162,7 +154,7 @@ static ssize_t lttng_event_probe_attr_create_from_payload(
        offset += sizeof(*comm);
 
        local_attr = zmalloc<lttng_event_probe_attr>();
-       if (local_attr == NULL) {
+       if (local_attr == nullptr) {
                ret = -1;
                goto end;
        }
@@ -173,8 +165,7 @@ static ssize_t lttng_event_probe_attr_create_from_payload(
        {
                const char *name;
                struct lttng_payload_view name_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               comm->symbol_name_len);
+                       lttng_payload_view_from_view(view, offset, comm->symbol_name_len);
 
                if (!lttng_payload_view_is_valid(&name_view)) {
                        ret = -1;
@@ -183,14 +174,13 @@ static ssize_t lttng_event_probe_attr_create_from_payload(
 
                name = name_view.buffer.data;
 
-               if (!lttng_buffer_view_contains_string(&name_view.buffer, name,
-                                   comm->symbol_name_len)) {
+               if (!lttng_buffer_view_contains_string(
+                           &name_view.buffer, name, comm->symbol_name_len)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(local_attr->symbol_name, name,
-                               sizeof(local_attr->symbol_name));
+               ret = lttng_strncpy(local_attr->symbol_name, name, sizeof(local_attr->symbol_name));
                if (ret) {
                        ret = -1;
                        goto end;
@@ -200,22 +190,22 @@ static ssize_t lttng_event_probe_attr_create_from_payload(
        }
 
        *probe_attr = local_attr;
-       local_attr = NULL;
+       local_attr = nullptr;
        ret = offset;
 end:
        free(local_attr);
        return ret;
 }
 
-static ssize_t lttng_event_function_attr_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_function_attr **function_attr)
+static ssize_t
+lttng_event_function_attr_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_event_function_attr **function_attr)
 {
        ssize_t ret, offset = 0;
        const struct lttng_event_function_attr_comm *comm;
-       struct lttng_event_function_attr *local_attr = NULL;
-       struct lttng_payload_view comm_view = lttng_payload_view_from_view(
-                       view, offset, sizeof(*comm));
+       struct lttng_event_function_attr *local_attr = nullptr;
+       struct lttng_payload_view comm_view =
+               lttng_payload_view_from_view(view, offset, sizeof(*comm));
 
        if (!lttng_payload_view_is_valid(&comm_view)) {
                ret = -1;
@@ -226,7 +216,7 @@ static ssize_t lttng_event_function_attr_create_from_payload(
        offset += sizeof(*comm);
 
        local_attr = zmalloc<lttng_event_function_attr>();
-       if (local_attr == NULL) {
+       if (local_attr == nullptr) {
                ret = -1;
                goto end;
        }
@@ -234,8 +224,7 @@ static ssize_t lttng_event_function_attr_create_from_payload(
        {
                const char *name;
                struct lttng_payload_view name_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               comm->symbol_name_len);
+                       lttng_payload_view_from_view(view, offset, comm->symbol_name_len);
 
                if (!lttng_payload_view_is_valid(&name_view)) {
                        ret = -1;
@@ -244,14 +233,13 @@ static ssize_t lttng_event_function_attr_create_from_payload(
 
                name = name_view.buffer.data;
 
-               if (!lttng_buffer_view_contains_string(&name_view.buffer, name,
-                                   comm->symbol_name_len)) {
+               if (!lttng_buffer_view_contains_string(
+                           &name_view.buffer, name, comm->symbol_name_len)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(local_attr->symbol_name, name,
-                               sizeof(local_attr->symbol_name));
+               ret = lttng_strncpy(local_attr->symbol_name, name, sizeof(local_attr->symbol_name));
                if (ret) {
                        ret = -1;
                        goto end;
@@ -261,17 +249,16 @@ static ssize_t lttng_event_function_attr_create_from_payload(
        }
 
        *function_attr = local_attr;
-       local_attr = NULL;
+       local_attr = nullptr;
        ret = offset;
 end:
        free(local_attr);
        return ret;
 }
 
-static ssize_t lttng_event_exclusions_create_from_payload(
-               struct lttng_payload_view *view,
-               uint32_t count,
-               struct lttng_event_exclusion **exclusions)
+static ssize_t lttng_event_exclusions_create_from_payload(struct lttng_payload_view *view,
+                                                         uint32_t count,
+                                                         struct lttng_event_exclusion **exclusions)
 {
        ssize_t ret, offset = 0;
        const size_t size = (count * LTTNG_SYMBOL_NAME_LEN);
@@ -279,8 +266,8 @@ static ssize_t lttng_event_exclusions_create_from_payload(
        const struct lttng_event_exclusion_comm *comm;
        struct lttng_event_exclusion *local_exclusions;
 
-       local_exclusions = zmalloc<lttng_event_exclusion>(
-                       sizeof(struct lttng_event_exclusion) + size);
+       local_exclusions =
+               zmalloc<lttng_event_exclusion>(sizeof(struct lttng_event_exclusion) + size);
        if (!local_exclusions) {
                ret = -1;
                goto end;
@@ -292,8 +279,7 @@ static ssize_t lttng_event_exclusions_create_from_payload(
                const char *string;
                struct lttng_buffer_view string_view;
                const struct lttng_buffer_view comm_view =
-                               lttng_buffer_view_from_view(&view->buffer,
-                                               offset, sizeof(*comm));
+                       lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*comm));
 
                if (!lttng_buffer_view_is_valid(&comm_view)) {
                        ret = -1;
@@ -303,8 +289,7 @@ static ssize_t lttng_event_exclusions_create_from_payload(
                comm = (typeof(comm)) comm_view.data;
                offset += sizeof(*comm);
 
-               string_view = lttng_buffer_view_from_view(
-                               &view->buffer, offset, comm->len);
+               string_view = lttng_buffer_view_from_view(&view->buffer, offset, comm->len);
 
                if (!lttng_buffer_view_is_valid(&string_view)) {
                        ret = -1;
@@ -313,14 +298,14 @@ static ssize_t lttng_event_exclusions_create_from_payload(
 
                string = string_view.data;
 
-               if (!lttng_buffer_view_contains_string(
-                                   &string_view, string, comm->len)) {
+               if (!lttng_buffer_view_contains_string(&string_view, string, comm->len)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(local_exclusions, i), string,
-                               sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(local_exclusions, i)));
+               ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(local_exclusions, i),
+                                   string,
+                                   sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(local_exclusions, i)));
                if (ret) {
                        ret = -1;
                        goto end;
@@ -330,7 +315,7 @@ static ssize_t lttng_event_exclusions_create_from_payload(
        }
 
        *exclusions = local_exclusions;
-       local_exclusions = NULL;
+       local_exclusions = nullptr;
        ret = offset;
 end:
        free(local_exclusions);
@@ -338,21 +323,20 @@ end:
 }
 
 ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
-               struct lttng_event **out_event,
-               struct lttng_event_exclusion **out_exclusion,
-               char **out_filter_expression,
-               struct lttng_bytecode **out_bytecode)
+                                       struct lttng_event **out_event,
+                                       struct lttng_event_exclusion **out_exclusion,
+                                       char **out_filter_expression,
+                                       struct lttng_bytecode **out_bytecode)
 {
        ssize_t ret, offset = 0;
-       struct lttng_event *local_event = NULL;
-       struct lttng_event_exclusion *local_exclusions = NULL;
-       struct lttng_bytecode *local_bytecode = NULL;
-       char *local_filter_expression = NULL;
+       struct lttng_event *local_event = nullptr;
+       struct lttng_event_exclusion *local_exclusions = nullptr;
+       struct lttng_bytecode *local_bytecode = nullptr;
+       char *local_filter_expression = nullptr;
        const struct lttng_event_comm *event_comm;
-       struct lttng_event_function_attr *local_function_attr = NULL;
-       struct lttng_event_probe_attr *local_probe_attr = NULL;
-       struct lttng_userspace_probe_location *local_userspace_probe_location =
-                       NULL;
+       struct lttng_event_function_attr *local_function_attr = nullptr;
+       struct lttng_event_probe_attr *local_probe_attr = nullptr;
+       struct lttng_userspace_probe_location *local_userspace_probe_location = nullptr;
 
        /*
         * Only event is obligatory, the other output argument are optional and
@@ -363,8 +347,7 @@ ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
 
        {
                struct lttng_payload_view comm_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               sizeof(*event_comm));
+                       lttng_payload_view_from_view(view, offset, sizeof(*event_comm));
 
                if (!lttng_payload_view_is_valid(&comm_view)) {
                        ret = -1;
@@ -377,7 +360,7 @@ ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
        }
 
        local_event = lttng_event_create();
-       if (local_event == NULL) {
+       if (local_event == nullptr) {
                ret = -1;
                goto end;
        }
@@ -385,15 +368,14 @@ ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
        local_event->type = (enum lttng_event_type) event_comm->event_type;
        local_event->loglevel_type = (enum lttng_loglevel_type) event_comm->loglevel_type;
        local_event->loglevel = event_comm->loglevel;
-       local_event->enabled = event_comm->enabled;
+       local_event->enabled = !!event_comm->enabled;
        local_event->pid = event_comm->pid;
        local_event->flags = (enum lttng_event_flag) event_comm->flags;
 
        {
                const char *name;
                const struct lttng_buffer_view name_view =
-                               lttng_buffer_view_from_view(&view->buffer,
-                                               offset, event_comm->name_len);
+                       lttng_buffer_view_from_view(&view->buffer, offset, event_comm->name_len);
 
                if (!lttng_buffer_view_is_valid(&name_view)) {
                        ret = -1;
@@ -402,14 +384,12 @@ ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
 
                name = (const char *) name_view.data;
 
-               if (!lttng_buffer_view_contains_string(
-                                   &name_view, name, event_comm->name_len)) {
+               if (!lttng_buffer_view_contains_string(&name_view, name, event_comm->name_len)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(local_event->name, name,
-                               sizeof(local_event->name));
+               ret = lttng_strncpy(local_event->name, name, sizeof(local_event->name));
                if (ret) {
                        ret = -1;
                        goto end;
@@ -425,16 +405,15 @@ ssize_t lttng_event_create_from_payload(struct lttng_payload_view *view,
 
        {
                struct lttng_payload_view exclusions_view =
-                               lttng_payload_view_from_view(
-                                               view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
                if (!lttng_payload_view_is_valid(&exclusions_view)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_event_exclusions_create_from_payload(&exclusions_view,
-                               event_comm->exclusion_count, &local_exclusions);
+               ret = lttng_event_exclusions_create_from_payload(
+                       &exclusions_view, event_comm->exclusion_count, &local_exclusions);
                if (ret < 0) {
                        ret = -1;
                        goto end;
@@ -462,9 +441,8 @@ deserialize_filter_expression:
 
        {
                const char *filter_expression_buffer;
-               struct lttng_buffer_view filter_expression_view =
-                               lttng_buffer_view_from_view(&view->buffer, offset,
-                                               event_comm->filter_expression_len);
+               struct lttng_buffer_view filter_expression_view = lttng_buffer_view_from_view(
+                       &view->buffer, offset, event_comm->filter_expression_len);
 
                if (!lttng_buffer_view_is_valid(&filter_expression_view)) {
                        ret = -1;
@@ -474,15 +452,14 @@ deserialize_filter_expression:
                filter_expression_buffer = filter_expression_view.data;
 
                if (!lttng_buffer_view_contains_string(&filter_expression_view,
-                                   filter_expression_buffer,
-                                   event_comm->filter_expression_len)) {
+                                                      filter_expression_buffer,
+                                                      event_comm->filter_expression_len)) {
                        ret = -1;
                        goto end;
                }
 
-               local_filter_expression = lttng_strndup(
-                               filter_expression_buffer,
-                               event_comm->filter_expression_len);
+               local_filter_expression =
+                       lttng_strndup(filter_expression_buffer, event_comm->filter_expression_len);
                if (!local_filter_expression) {
                        ret = -1;
                        goto end;
@@ -504,8 +481,7 @@ deserialize_filter_expression:
        /* Bytecode */
        {
                struct lttng_payload_view bytecode_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               event_comm->bytecode_len);
+                       lttng_payload_view_from_view(view, offset, event_comm->bytecode_len);
 
                if (!lttng_payload_view_is_valid(&bytecode_view)) {
                        ret = -1;
@@ -518,10 +494,8 @@ deserialize_filter_expression:
                        goto end;
                }
 
-               memcpy(local_bytecode, bytecode_view.buffer.data,
-                               event_comm->bytecode_len);
-               if ((local_bytecode->len + sizeof(*local_bytecode)) !=
-                               event_comm->bytecode_len) {
+               memcpy(local_bytecode, bytecode_view.buffer.data, event_comm->bytecode_len);
+               if ((local_bytecode->len + sizeof(*local_bytecode)) != event_comm->bytecode_len) {
                        ret = -1;
                        goto end;
                }
@@ -536,9 +510,8 @@ deserialize_event_type_payload:
                /* Fallthrough */
        case LTTNG_EVENT_PROBE:
        {
-               struct lttng_payload_view probe_attr_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               event_comm->lttng_event_probe_attr_len);
+               struct lttng_payload_view probe_attr_view = lttng_payload_view_from_view(
+                       view, offset, event_comm->lttng_event_probe_attr_len);
 
                if (event_comm->lttng_event_probe_attr_len == 0) {
                        ret = -1;
@@ -550,25 +523,23 @@ deserialize_event_type_payload:
                        goto end;
                }
 
-               ret = lttng_event_probe_attr_create_from_payload(
-                               &probe_attr_view, &local_probe_attr);
+               ret = lttng_event_probe_attr_create_from_payload(&probe_attr_view,
+                                                                &local_probe_attr);
                if (ret < 0 || ret != event_comm->lttng_event_probe_attr_len) {
                        ret = -1;
                        goto end;
                }
 
                /* Copy to the local event. */
-               memcpy(&local_event->attr.probe, local_probe_attr,
-                               sizeof(local_event->attr.probe));
+               memcpy(&local_event->attr.probe, local_probe_attr, sizeof(local_event->attr.probe));
 
                offset += ret;
                break;
        }
        case LTTNG_EVENT_FUNCTION_ENTRY:
        {
-               struct lttng_payload_view function_attr_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               event_comm->lttng_event_function_attr_len);
+               struct lttng_payload_view function_attr_view = lttng_payload_view_from_view(
+                       view, offset, event_comm->lttng_event_function_attr_len);
 
                if (event_comm->lttng_event_function_attr_len == 0) {
                        ret = -1;
@@ -580,16 +551,17 @@ deserialize_event_type_payload:
                        goto end;
                }
 
-               ret = lttng_event_function_attr_create_from_payload(
-                               &function_attr_view, &local_function_attr);
+               ret = lttng_event_function_attr_create_from_payload(&function_attr_view,
+                                                                   &local_function_attr);
                if (ret < 0 || ret != event_comm->lttng_event_function_attr_len) {
                        ret = -1;
                        goto end;
                }
 
                /* Copy to the local event. */
-               memcpy(&local_event->attr.ftrace, local_function_attr,
-                               sizeof(local_event->attr.ftrace));
+               memcpy(&local_event->attr.ftrace,
+                      local_function_attr,
+                      sizeof(local_event->attr.ftrace));
 
                offset += ret;
 
@@ -598,23 +570,21 @@ deserialize_event_type_payload:
        case LTTNG_EVENT_USERSPACE_PROBE:
        {
                struct lttng_payload_view userspace_probe_location_view =
-                               lttng_payload_view_from_view(view, offset,
-                                               event_comm->userspace_probe_location_len);
+                       lttng_payload_view_from_view(
+                               view, offset, event_comm->userspace_probe_location_len);
 
                if (event_comm->userspace_probe_location_len == 0) {
                        ret = -1;
                        goto end;
                }
 
-               if (!lttng_payload_view_is_valid(
-                                   &userspace_probe_location_view)) {
+               if (!lttng_payload_view_is_valid(&userspace_probe_location_view)) {
                        ret = -1;
                        goto end;
                }
 
                ret = lttng_userspace_probe_location_create_from_payload(
-                               &userspace_probe_location_view,
-                               &local_userspace_probe_location);
+                       &userspace_probe_location_view, &local_userspace_probe_location);
                if (ret < 0) {
                        WARN("Failed to create a userspace probe location from the received buffer");
                        ret = -1;
@@ -622,14 +592,17 @@ deserialize_event_type_payload:
                }
 
                if (ret != event_comm->userspace_probe_location_len) {
-                       WARN("Userspace probe location from the received buffer is not the advertised length: header length = %" PRIu32 ", payload length = %zd", event_comm->userspace_probe_location_len, ret);
+                       WARN("Userspace probe location from the received buffer is not the advertised length: header length = %" PRIu32
+                            ", payload length = %zd",
+                            event_comm->userspace_probe_location_len,
+                            ret);
                        ret = -1;
                        goto end;
                }
 
                /* Attach the probe location to the event. */
-               ret = lttng_event_set_userspace_probe_location(
-                               local_event, local_userspace_probe_location);
+               ret = lttng_event_set_userspace_probe_location(local_event,
+                                                              local_userspace_probe_location);
                if (ret) {
                        ret = LTTNG_ERR_PROBE_LOCATION_INVAL;
                        goto end;
@@ -639,7 +612,7 @@ deserialize_event_type_payload:
                 * Userspace probe location object ownership transfered to the
                 * event object.
                 */
-               local_userspace_probe_location = NULL;
+               local_userspace_probe_location = nullptr;
                offset += event_comm->userspace_probe_location_len;
                break;
        }
@@ -660,21 +633,21 @@ deserialize_event_type_payload:
 
        /* Transfer ownership to the caller. */
        *out_event = local_event;
-       local_event = NULL;
+       local_event = nullptr;
 
        if (out_bytecode) {
                *out_bytecode = local_bytecode;
-               local_bytecode = NULL;
+               local_bytecode = nullptr;
        }
 
        if (out_exclusion) {
                *out_exclusion = local_exclusions;
-               local_exclusions = NULL;
+               local_exclusions = nullptr;
        }
 
        if (out_filter_expression) {
                *out_filter_expression = local_filter_expression;
-               local_filter_expression = NULL;
+               local_filter_expression = nullptr;
        }
 
        ret = offset;
@@ -690,12 +663,12 @@ end:
 }
 
 int lttng_event_serialize(const struct lttng_event *event,
-               unsigned int exclusion_count,
-               char **exclusion_list,
-               char *filter_expression,
-               size_t bytecode_len,
-               struct lttng_bytecode *bytecode,
-               struct lttng_payload *payload)
+                         unsigned int exclusion_count,
+                         const char *const *exclusion_list,
+                         const char *filter_expression,
+                         size_t bytecode_len,
+                         struct lttng_bytecode *bytecode,
+                         struct lttng_payload *payload)
 {
        int ret;
        unsigned int i;
@@ -744,29 +717,26 @@ int lttng_event_serialize(const struct lttng_event *event,
        event_comm.flags = (int32_t) event->flags;
 
        if (filter_expression) {
-               event_comm.filter_expression_len =
-                               strlen(filter_expression) + 1;
+               event_comm.filter_expression_len = strlen(filter_expression) + 1;
        }
 
        /* Header */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &event_comm, sizeof(event_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &event_comm, sizeof(event_comm));
        if (ret) {
                goto end;
        }
 
        /* Event name */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, event->name, name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, event->name, name_len);
        if (ret) {
                goto end;
        }
 
        /* Exclusions */
        for (i = 0; i < exclusion_count; i++) {
-               const size_t exclusion_len = lttng_strnlen(
-                               *(exclusion_list + i), LTTNG_SYMBOL_NAME_LEN);
-               struct lttng_event_exclusion_comm exclusion_header;
+               const size_t exclusion_len =
+                       lttng_strnlen(*(exclusion_list + i), LTTNG_SYMBOL_NAME_LEN);
+               struct lttng_event_exclusion_comm exclusion_header = {};
 
                exclusion_header.len = (uint32_t) exclusion_len + 1;
 
@@ -776,14 +746,14 @@ int lttng_event_serialize(const struct lttng_event *event,
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               &exclusion_header, sizeof(exclusion_header));
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, &exclusion_header, sizeof(exclusion_header));
                if (ret) {
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               *(exclusion_list + i), exclusion_len + 1);
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, *(exclusion_list + i), exclusion_len + 1);
                if (ret) {
                        goto end;
                }
@@ -791,9 +761,8 @@ int lttng_event_serialize(const struct lttng_event *event,
 
        /* Filter expression and its bytecode */
        if (filter_expression) {
-               ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               filter_expression,
-                               event_comm.filter_expression_len);
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, filter_expression, event_comm.filter_expression_len);
                if (ret) {
                        goto end;
                }
@@ -803,8 +772,7 @@ int lttng_event_serialize(const struct lttng_event *event,
                 * for listing.
                 */
                if (bytecode) {
-                       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                                       bytecode, bytecode_len);
+                       ret = lttng_dynamic_buffer_append(&payload->buffer, bytecode, bytecode_len);
                        if (ret) {
                                goto end;
                        }
@@ -824,32 +792,28 @@ int lttng_event_serialize(const struct lttng_event *event,
                        goto end;
                }
 
-               header = (struct lttng_event_comm *) ((char *) payload->buffer.data +
-                                                     header_offset);
-               header->lttng_event_probe_attr_len =
-                               payload->buffer.size - size_before_payload;
+               header =
+                       (struct lttng_event_comm *) ((char *) payload->buffer.data + header_offset);
+               header->lttng_event_probe_attr_len = payload->buffer.size - size_before_payload;
 
                break;
        case LTTNG_EVENT_FUNCTION_ENTRY:
-               ret = lttng_event_function_attr_serialize(
-                               &event->attr.ftrace, payload);
+               ret = lttng_event_function_attr_serialize(&event->attr.ftrace, payload);
                if (ret) {
                        ret = -1;
                        goto end;
                }
 
                /* Update the lttng_event_function_attr len. */
-               header = (struct lttng_event_comm *) ((char *) payload->buffer.data +
-                                                     header_offset);
-               header->lttng_event_function_attr_len =
-                               payload->buffer.size - size_before_payload;
+               header =
+                       (struct lttng_event_comm *) ((char *) payload->buffer.data + header_offset);
+               header->lttng_event_function_attr_len = payload->buffer.size - size_before_payload;
 
                break;
        case LTTNG_EVENT_USERSPACE_PROBE:
        {
                const struct lttng_event_extended *ev_ext =
-                               (const struct lttng_event_extended *)
-                                               event->extended.ptr;
+                       (const struct lttng_event_extended *) event->extended.ptr;
 
                assert(event->extended.ptr);
                assert(ev_ext->probe_location);
@@ -860,8 +824,8 @@ int lttng_event_serialize(const struct lttng_event *event,
                         * lttng_userspace_probe_location_serialize returns the
                         * number of bytes that were appended to the buffer.
                         */
-                       ret = lttng_userspace_probe_location_serialize(
-                                       ev_ext->probe_location, payload);
+                       ret = lttng_userspace_probe_location_serialize(ev_ext->probe_location,
+                                                                      payload);
                        if (ret < 0) {
                                goto end;
                        }
@@ -872,7 +836,7 @@ int lttng_event_serialize(const struct lttng_event *event,
                        header = (struct lttng_event_comm *) ((char *) payload->buffer.data +
                                                              header_offset);
                        header->userspace_probe_location_len =
-                                       payload->buffer.size - size_before_payload;
+                               payload->buffer.size - size_before_payload;
                }
                break;
        }
@@ -889,16 +853,15 @@ end:
        return ret;
 }
 
-static ssize_t lttng_event_context_app_populate_from_payload(
-               const struct lttng_payload_view *view,
-               struct lttng_event_context *event_ctx)
+static ssize_t lttng_event_context_app_populate_from_payload(const struct lttng_payload_view *view,
+                                                            struct lttng_event_context *event_ctx)
 {
        ssize_t ret, offset = 0;
        const struct lttng_event_context_app_comm *comm;
-       char *provider_name = NULL, *context_name = NULL;
+       char *provider_name = nullptr, *context_name = nullptr;
        size_t provider_name_len, context_name_len;
-       const struct lttng_buffer_view comm_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*comm));
+       const struct lttng_buffer_view comm_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*comm));
 
        assert(event_ctx->ctx == LTTNG_EVENT_CONTEXT_APP_CONTEXT);
 
@@ -925,9 +888,7 @@ static ssize_t lttng_event_context_app_populate_from_payload(
        {
                const char *name;
                const struct lttng_buffer_view provider_name_view =
-                               lttng_buffer_view_from_view(&view->buffer,
-                                               offset,
-                                               provider_name_len);
+                       lttng_buffer_view_from_view(&view->buffer, offset, provider_name_len);
 
                if (!lttng_buffer_view_is_valid(&provider_name_view)) {
                        ret = -1;
@@ -936,8 +897,8 @@ static ssize_t lttng_event_context_app_populate_from_payload(
 
                name = provider_name_view.data;
 
-               if (!lttng_buffer_view_contains_string(&provider_name_view,
-                               name, provider_name_len)) {
+               if (!lttng_buffer_view_contains_string(
+                           &provider_name_view, name, provider_name_len)) {
                        ret = -1;
                        goto end;
                }
@@ -954,9 +915,7 @@ static ssize_t lttng_event_context_app_populate_from_payload(
        {
                const char *name;
                const struct lttng_buffer_view context_name_view =
-                               lttng_buffer_view_from_view(
-                                               &view->buffer, offset,
-                                               context_name_len);
+                       lttng_buffer_view_from_view(&view->buffer, offset, context_name_len);
 
                if (!lttng_buffer_view_is_valid(&context_name_view)) {
                        ret = -1;
@@ -965,8 +924,7 @@ static ssize_t lttng_event_context_app_populate_from_payload(
 
                name = context_name_view.data;
 
-               if (!lttng_buffer_view_contains_string(&context_name_view, name,
-                                   context_name_len)) {
+               if (!lttng_buffer_view_contains_string(&context_name_view, name, context_name_len)) {
                        ret = -1;
                        goto end;
                }
@@ -983,8 +941,8 @@ static ssize_t lttng_event_context_app_populate_from_payload(
        /* Transfer ownership of the strings */
        event_ctx->u.app_ctx.provider_name = provider_name;
        event_ctx->u.app_ctx.ctx_name = context_name;
-       provider_name = NULL;
-       context_name = NULL;
+       provider_name = nullptr;
+       context_name = nullptr;
 
        ret = offset;
 end:
@@ -994,21 +952,20 @@ end:
        return ret;
 }
 
-static ssize_t lttng_event_context_perf_counter_populate_from_payload(
-               const struct lttng_payload_view *view,
-               struct lttng_event_context *event_ctx)
+static ssize_t
+lttng_event_context_perf_counter_populate_from_payload(const struct lttng_payload_view *view,
+                                                      struct lttng_event_context *event_ctx)
 {
        int ret;
        ssize_t consumed, offset = 0;
        const struct lttng_event_context_perf_counter_comm *comm;
        size_t name_len;
-       const struct lttng_buffer_view comm_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*comm));
+       const struct lttng_buffer_view comm_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*comm));
 
        assert(event_ctx->ctx == LTTNG_EVENT_CONTEXT_PERF_COUNTER ||
-                       event_ctx->ctx ==
-                                       LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER ||
-                       event_ctx->ctx == LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER);
+              event_ctx->ctx == LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER ||
+              event_ctx->ctx == LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER);
 
        if (!lttng_buffer_view_is_valid(&comm_view)) {
                consumed = -1;
@@ -1023,9 +980,7 @@ static ssize_t lttng_event_context_perf_counter_populate_from_payload(
        {
                const char *name;
                const struct lttng_buffer_view provider_name_view =
-                               lttng_buffer_view_from_view(
-                                               &view->buffer, offset,
-                                               name_len);
+                       lttng_buffer_view_from_view(&view->buffer, offset, name_len);
 
                if (!lttng_buffer_view_is_valid(&provider_name_view)) {
                        consumed = -1;
@@ -1034,14 +989,14 @@ static ssize_t lttng_event_context_perf_counter_populate_from_payload(
 
                name = provider_name_view.data;
 
-               if (!lttng_buffer_view_contains_string(
-                                   &provider_name_view, name, name_len)) {
+               if (!lttng_buffer_view_contains_string(&provider_name_view, name, name_len)) {
                        consumed = -1;
                        goto end;
                }
 
-               ret = lttng_strncpy(event_ctx->u.perf_counter.name, name,
-                               sizeof(event_ctx->u.perf_counter.name));
+               ret = lttng_strncpy(event_ctx->u.perf_counter.name,
+                                   name,
+                                   sizeof(event_ctx->u.perf_counter.name));
                if (ret) {
                        consumed = -1;
                        goto end;
@@ -1058,15 +1013,14 @@ end:
        return consumed;
 }
 
-ssize_t lttng_event_context_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_context **event_ctx)
+ssize_t lttng_event_context_create_from_payload(struct lttng_payload_view *view,
+                                               struct lttng_event_context **event_ctx)
 {
        ssize_t ret, offset = 0;
        const struct lttng_event_context_comm *comm;
-       struct lttng_event_context *local_context = NULL;
-       struct lttng_buffer_view comm_view = lttng_buffer_view_from_view(
-                       &view->buffer, offset, sizeof(*comm));
+       struct lttng_event_context *local_context = nullptr;
+       struct lttng_buffer_view comm_view =
+               lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*comm));
 
        assert(event_ctx);
        assert(view);
@@ -1089,18 +1043,18 @@ ssize_t lttng_event_context_create_from_payload(
 
        {
                struct lttng_payload_view subtype_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
                switch (local_context->ctx) {
                case LTTNG_EVENT_CONTEXT_APP_CONTEXT:
-                       ret = lttng_event_context_app_populate_from_payload(
-                                       &subtype_view, local_context);
+                       ret = lttng_event_context_app_populate_from_payload(&subtype_view,
+                                                                           local_context);
                        break;
                case LTTNG_EVENT_CONTEXT_PERF_COUNTER:
                case LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER:
                case LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER:
-                       ret = lttng_event_context_perf_counter_populate_from_payload(
-                                       &subtype_view, local_context);
+                       ret = lttng_event_context_perf_counter_populate_from_payload(&subtype_view,
+                                                                                    local_context);
                        break;
                default:
                        /* Nothing else to deserialize. */
@@ -1116,7 +1070,7 @@ ssize_t lttng_event_context_create_from_payload(
        offset += ret;
 
        *event_ctx = local_context;
-       local_context = NULL;
+       local_context = nullptr;
        ret = offset;
 
 end:
@@ -1124,9 +1078,8 @@ end:
        return ret;
 }
 
-static int lttng_event_context_app_serialize(
-               struct lttng_event_context *context,
-               struct lttng_payload *payload)
+static int lttng_event_context_app_serialize(struct lttng_event_context *context,
+                                            struct lttng_payload *payload)
 {
        int ret;
        struct lttng_event_context_app_comm comm = {};
@@ -1167,22 +1120,19 @@ static int lttng_event_context_app_serialize(
        comm.ctx_name_len = ctx_len;
 
        /* Header */
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm,
-                       sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, provider_name,
-                       provider_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, provider_name, provider_len);
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, ctx_name,
-                       ctx_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, ctx_name, ctx_len);
        if (ret) {
                ret = -1;
                goto end;
@@ -1192,9 +1142,8 @@ end:
        return ret;
 }
 
-static int lttng_event_context_perf_counter_serialize(
-               struct lttng_event_perf_counter_ctx *context,
-               struct lttng_payload *payload)
+static int lttng_event_context_perf_counter_serialize(struct lttng_event_perf_counter_ctx *context,
+                                                     struct lttng_payload *payload)
 {
        int ret;
        struct lttng_event_context_perf_counter_comm comm = {};
@@ -1215,15 +1164,13 @@ static int lttng_event_context_perf_counter_serialize(
        comm.name_len += 1;
 
        /* Header */
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm,
-                       sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                ret = -1;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer, context->name,
-                       comm.name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, context->name, comm.name_len);
        if (ret) {
                ret = -1;
                goto end;
@@ -1234,7 +1181,7 @@ end:
 }
 
 int lttng_event_context_serialize(struct lttng_event_context *context,
-               struct lttng_payload *payload)
+                                 struct lttng_payload *payload)
 {
        int ret;
        struct lttng_event_context_comm context_comm;
@@ -1247,8 +1194,7 @@ int lttng_event_context_serialize(struct lttng_event_context *context,
        context_comm.type = (uint32_t) context->ctx;
 
        /* Header */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &context_comm, sizeof(context_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &context_comm, sizeof(context_comm));
        if (ret) {
                goto end;
        }
@@ -1260,8 +1206,7 @@ int lttng_event_context_serialize(struct lttng_event_context *context,
        case LTTNG_EVENT_CONTEXT_PERF_COUNTER:
        case LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER:
        case LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER:
-               ret = lttng_event_context_perf_counter_serialize(
-                               &context->u.perf_counter, payload);
+               ret = lttng_event_context_perf_counter_serialize(&context->u.perf_counter, payload);
                break;
        default:
                /* Nothing else to serialize. */
@@ -1295,33 +1240,30 @@ void lttng_event_context_destroy(struct lttng_event_context *context)
  * the extension field of the lttng_event struct and simply copies what it can
  * to the internal struct lttng_event of a lttng_event_field.
  */
-static void lttng_event_field_populate_lttng_event_from_event(
-               const struct lttng_event *src, struct lttng_event *destination)
+static void lttng_event_field_populate_lttng_event_from_event(const struct lttng_event *src,
+                                                             struct lttng_event *destination)
 {
        memcpy(destination, src, sizeof(*destination));
 
        /* Remove all possible dynamic data from the destination event rule. */
-       destination->extended.ptr = NULL;
+       destination->extended.ptr = nullptr;
 }
 
-ssize_t lttng_event_field_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_event_field **field)
+ssize_t lttng_event_field_create_from_payload(struct lttng_payload_view *view,
+                                             struct lttng_event_field **field)
 {
        ssize_t ret, offset = 0;
-       struct lttng_event_field *local_event_field = NULL;
-       struct lttng_event *event = NULL;
+       struct lttng_event_field *local_event_field = nullptr;
+       struct lttng_event *event = nullptr;
        const struct lttng_event_field_comm *comm;
-       const char* name = NULL;
+       const char *name = nullptr;
 
        assert(field);
        assert(view);
 
        {
                const struct lttng_buffer_view comm_view =
-                               lttng_buffer_view_from_view(
-                                               &view->buffer, offset,
-                                               sizeof(*comm));
+                       lttng_buffer_view_from_view(&view->buffer, offset, sizeof(*comm));
 
                if (!lttng_buffer_view_is_valid(&comm_view)) {
                        ret = -1;
@@ -1345,9 +1287,7 @@ ssize_t lttng_event_field_create_from_payload(
        /* Field name */
        {
                const struct lttng_buffer_view name_view =
-                               lttng_buffer_view_from_view(
-                                               &view->buffer, offset,
-                                               comm->name_len);
+                       lttng_buffer_view_from_view(&view->buffer, offset, comm->name_len);
 
                if (!lttng_buffer_view_is_valid(&name_view)) {
                        ret = -1;
@@ -1356,8 +1296,7 @@ ssize_t lttng_event_field_create_from_payload(
 
                name = name_view.data;
 
-               if (!lttng_buffer_view_contains_string(&name_view,
-                               name_view.data, comm->name_len)) {
+               if (!lttng_buffer_view_contains_string(&name_view, name_view.data, comm->name_len)) {
                        ret = -1;
                        goto end;
                }
@@ -1374,17 +1313,15 @@ ssize_t lttng_event_field_create_from_payload(
        /* Event */
        {
                struct lttng_payload_view event_view =
-                               lttng_payload_view_from_view(
-                                               view, offset,
-                                               comm->event_len);
+                       lttng_payload_view_from_view(view, offset, comm->event_len);
 
                if (!lttng_payload_view_is_valid(&event_view)) {
                        ret = -1;
                        goto end;
                }
 
-               ret = lttng_event_create_from_payload(&event_view, &event, NULL,
-                               NULL, NULL);
+               ret = lttng_event_create_from_payload(
+                       &event_view, &event, nullptr, nullptr, nullptr);
                if (ret != comm->event_len) {
                        ret = -1;
                        goto end;
@@ -1396,17 +1333,16 @@ ssize_t lttng_event_field_create_from_payload(
        assert(name);
        assert(event);
 
-       if (lttng_strncpy(local_event_field->field_name, name,
-                       sizeof(local_event_field->field_name))) {
+       if (lttng_strncpy(
+                   local_event_field->field_name, name, sizeof(local_event_field->field_name))) {
                ret = -1;
                goto end;
        }
 
-       lttng_event_field_populate_lttng_event_from_event(
-                       event, &local_event_field->event);
+       lttng_event_field_populate_lttng_event_from_event(event, &local_event_field->event);
 
        *field = local_event_field;
-       local_event_field = NULL;
+       local_event_field = nullptr;
        ret = offset;
 end:
        lttng_event_destroy(event);
@@ -1415,7 +1351,7 @@ end:
 }
 
 int lttng_event_field_serialize(const struct lttng_event_field *field,
-               struct lttng_payload *payload)
+                               struct lttng_payload *payload)
 {
        int ret;
        size_t header_offset, size_before_event;
@@ -1440,44 +1376,39 @@ int lttng_event_field_serialize(const struct lttng_event_field *field,
        name_len += 1;
 
        event_field_comm.type = field->type;
-       event_field_comm.nowrite = (uint8_t)field->nowrite;
+       event_field_comm.nowrite = (uint8_t) field->nowrite;
        event_field_comm.name_len = name_len;
 
        /* Header */
        ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &event_field_comm,
-                       sizeof(event_field_comm));
+               &payload->buffer, &event_field_comm, sizeof(event_field_comm));
        if (ret) {
                goto end;
        }
 
        /* Field name */
-       ret = lttng_dynamic_buffer_append(&payload->buffer, field->field_name,
-                       name_len);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, field->field_name, name_len);
        if (ret) {
                goto end;
        }
 
        size_before_event = payload->buffer.size;
-       ret = lttng_event_serialize(
-                       &field->event, 0, NULL, NULL, 0, 0, payload);
+       ret = lttng_event_serialize(&field->event, 0, nullptr, nullptr, 0, nullptr, payload);
        if (ret) {
                ret = -1;
                goto end;
        }
 
        /* Update the event len. */
-       header = (struct lttng_event_field_comm *)
-                       ((char *) payload->buffer.data +
-                               header_offset);
+       header = (struct lttng_event_field_comm *) ((char *) payload->buffer.data + header_offset);
        header->event_len = payload->buffer.size - size_before_event;
 
 end:
        return ret;
 }
 
-static enum lttng_error_code compute_flattened_size(
-               struct lttng_dynamic_pointer_array *events, size_t *size)
+static enum lttng_error_code compute_flattened_size(struct lttng_dynamic_pointer_array *events,
+                                                   size_t *size)
 {
        enum lttng_error_code ret_code;
        int ret = 0;
@@ -1496,16 +1427,14 @@ static enum lttng_error_code compute_flattened_size(
 
        for (i = 0; i < event_count; i++) {
                int probe_storage_req = 0;
-               const struct event_list_element *element = (const struct event_list_element *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               events, i);
-               const struct lttng_userspace_probe_location *location = NULL;
+               const struct event_list_element *element =
+                       (const struct event_list_element *) lttng_dynamic_pointer_array_get_pointer(
+                               events, i);
+               const struct lttng_userspace_probe_location *location = nullptr;
 
-               location = lttng_event_get_userspace_probe_location(
-                               element->event);
+               location = lttng_event_get_userspace_probe_location(element->event);
                if (location) {
-                       ret = lttng_userspace_probe_location_flatten(
-                                       location, NULL);
+                       ret = lttng_userspace_probe_location_flatten(location, nullptr);
                        if (ret < 0) {
                                ret_code = LTTNG_ERR_PROBE_LOCATION_INVAL;
                                goto end;
@@ -1519,8 +1448,7 @@ static enum lttng_error_code compute_flattened_size(
                }
 
                if (element->exclusions) {
-                       storage_req += element->exclusions->count *
-                               LTTNG_SYMBOL_NAME_LEN;
+                       storage_req += element->exclusions->count * LTTNG_SYMBOL_NAME_LEN;
                }
 
                /* Padding to ensure the flat probe is aligned. */
@@ -1557,9 +1485,8 @@ end:
  *     - padding to align to 64-bits
  *     - flattened version of userspace_probe_location
  */
-static enum lttng_error_code flatten_lttng_events(
-               struct lttng_dynamic_pointer_array *events,
-               struct lttng_event **flattened_events)
+static enum lttng_error_code flatten_lttng_events(struct lttng_dynamic_pointer_array *events,
+                                                 struct lttng_event **flattened_events)
 {
        enum lttng_error_code ret_code;
        int ret, i;
@@ -1582,8 +1509,7 @@ static enum lttng_error_code flatten_lttng_events(
         * We must ensure that "local_flattened_events" is never resized so as
         * to preserve the validity of the flattened objects.
         */
-       ret = lttng_dynamic_buffer_set_capacity(
-                       &local_flattened_events, storage_req);
+       ret = lttng_dynamic_buffer_set_capacity(&local_flattened_events, storage_req);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -1591,17 +1517,17 @@ static enum lttng_error_code flatten_lttng_events(
 
        /* Start by laying the struct lttng_event */
        for (i = 0; i < nb_events; i++) {
-               const struct event_list_element *element = (const struct event_list_element *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               events, i);
+               const struct event_list_element *element =
+                       (const struct event_list_element *) lttng_dynamic_pointer_array_get_pointer(
+                               events, i);
 
                if (!element) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto end;
                }
 
-               ret = lttng_dynamic_buffer_append(&local_flattened_events,
-                               element->event, sizeof(struct lttng_event));
+               ret = lttng_dynamic_buffer_append(
+                       &local_flattened_events, element->event, sizeof(struct lttng_event));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -1609,21 +1535,23 @@ static enum lttng_error_code flatten_lttng_events(
        }
 
        for (i = 0; i < nb_events; i++) {
-               const struct event_list_element *element = (const struct event_list_element *)
-                               lttng_dynamic_pointer_array_get_pointer(events, i);
-               struct lttng_event *event = (struct lttng_event *)
-                       (local_flattened_events.data + (sizeof(struct lttng_event) * i));
+               const struct event_list_element *element =
+                       (const struct event_list_element *) lttng_dynamic_pointer_array_get_pointer(
+                               events, i);
+               struct lttng_event *event =
+                       (struct lttng_event *) (local_flattened_events.data +
+                                               (sizeof(struct lttng_event) * i));
                struct lttng_event_extended *event_extended =
-                       (struct lttng_event_extended *)
-                               (local_flattened_events.data + local_flattened_events.size);
-               const struct lttng_userspace_probe_location *location = NULL;
+                       (struct lttng_event_extended *) (local_flattened_events.data +
+                                                        local_flattened_events.size);
+               const struct lttng_userspace_probe_location *location = nullptr;
 
                assert(element);
 
                /* Insert struct lttng_event_extended. */
                ret = lttng_dynamic_buffer_set_size(&local_flattened_events,
-                               local_flattened_events.size +
-                                               sizeof(*event_extended));
+                                                   local_flattened_events.size +
+                                                           sizeof(*event_extended));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -1635,11 +1563,9 @@ static enum lttng_error_code flatten_lttng_events(
                        const size_t len = strlen(element->filter_expression) + 1;
 
                        event_extended->filter_expression =
-                                       local_flattened_events.data +
-                                       local_flattened_events.size;
+                               local_flattened_events.data + local_flattened_events.size;
                        ret = lttng_dynamic_buffer_append(
-                                       &local_flattened_events,
-                                       element->filter_expression, len);
+                               &local_flattened_events, element->filter_expression, len);
                        if (ret) {
                                ret_code = LTTNG_ERR_NOMEM;
                                goto end;
@@ -1648,17 +1574,14 @@ static enum lttng_error_code flatten_lttng_events(
 
                /* Insert exclusions. */
                if (element->exclusions) {
-                       event_extended->exclusions.count =
-                                       element->exclusions->count;
+                       event_extended->exclusions.count = element->exclusions->count;
                        event_extended->exclusions.strings =
-                                       local_flattened_events.data +
-                                       local_flattened_events.size;
+                               local_flattened_events.data + local_flattened_events.size;
 
-                       ret = lttng_dynamic_buffer_append(
-                                       &local_flattened_events,
-                                       element->exclusions->names,
-                                       element->exclusions->count *
-                                                       LTTNG_SYMBOL_NAME_LEN);
+                       ret = lttng_dynamic_buffer_append(&local_flattened_events,
+                                                         element->exclusions->names,
+                                                         element->exclusions->count *
+                                                                 LTTNG_SYMBOL_NAME_LEN);
                        if (ret) {
                                ret_code = LTTNG_ERR_NOMEM;
                                goto end;
@@ -1667,20 +1590,20 @@ static enum lttng_error_code flatten_lttng_events(
 
                /* Insert padding to align to 64-bits. */
                ret = lttng_dynamic_buffer_set_size(&local_flattened_events,
-                               lttng_align_ceil(local_flattened_events.size,
-                                               sizeof(uint64_t)));
+                                                   lttng_align_ceil(local_flattened_events.size,
+                                                                    sizeof(uint64_t)));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
                }
 
-               location = lttng_event_get_userspace_probe_location(
-                               element->event);
+               location = lttng_event_get_userspace_probe_location(element->event);
                if (location) {
-                       event_extended->probe_location = (struct lttng_userspace_probe_location *)
-                                       (local_flattened_events.data + local_flattened_events.size);
-                       ret = lttng_userspace_probe_location_flatten(
-                                       location, &local_flattened_events);
+                       event_extended->probe_location = (struct lttng_userspace_probe_location
+                                                                 *) (local_flattened_events.data +
+                                                                     local_flattened_events.size);
+                       ret = lttng_userspace_probe_location_flatten(location,
+                                                                    &local_flattened_events);
                        if (ret < 0) {
                                ret_code = LTTNG_ERR_PROBE_LOCATION_INVAL;
                                goto end;
@@ -1697,10 +1620,10 @@ end:
        return ret_code;
 }
 
-static enum lttng_error_code event_list_create_from_payload(
-               struct lttng_payload_view *view,
-               unsigned int count,
-               struct lttng_dynamic_pointer_array *event_list)
+static enum lttng_error_code
+event_list_create_from_payload(struct lttng_payload_view *view,
+                              unsigned int count,
+                              struct lttng_dynamic_pointer_array *event_list)
 {
        enum lttng_error_code ret_code;
        int ret;
@@ -1713,7 +1636,7 @@ static enum lttng_error_code event_list_create_from_payload(
        for (i = 0; i < count; i++) {
                ssize_t event_size;
                struct lttng_payload_view event_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
                struct event_list_element *element = zmalloc<event_list_element>();
 
                if (!element) {
@@ -1725,8 +1648,7 @@ static enum lttng_error_code event_list_create_from_payload(
                 * Lifetime and management of the object is now bound to the
                 * array.
                 */
-               ret = lttng_dynamic_pointer_array_add_pointer(
-                               event_list, element);
+               ret = lttng_dynamic_pointer_array_add_pointer(event_list, element);
                if (ret) {
                        event_list_destructor(element);
                        ret_code = LTTNG_ERR_NOMEM;
@@ -1738,9 +1660,10 @@ static enum lttng_error_code event_list_create_from_payload(
                 * care about it.
                 */
                event_size = lttng_event_create_from_payload(&event_view,
-                               &element->event,
-                               &element->exclusions,
-                               &element->filter_expression, NULL);
+                                                            &element->event,
+                                                            &element->exclusions,
+                                                            &element->filter_expression,
+                                                            nullptr);
                if (event_size < 0) {
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
@@ -1761,9 +1684,7 @@ end:
 }
 
 enum lttng_error_code lttng_events_create_and_flatten_from_payload(
-               struct lttng_payload_view *payload,
-               unsigned int count,
-               struct lttng_event **events)
+       struct lttng_payload_view *payload, unsigned int count, struct lttng_event **events)
 {
        enum lttng_error_code ret = LTTNG_OK;
        struct lttng_dynamic_pointer_array local_events;
@@ -1773,10 +1694,9 @@ enum lttng_error_code lttng_events_create_and_flatten_from_payload(
        /* Deserialize the events. */
        {
                struct lttng_payload_view events_view =
-                               lttng_payload_view_from_view(payload, 0, -1);
+                       lttng_payload_view_from_view(payload, 0, -1);
 
-               ret = event_list_create_from_payload(
-                               &events_view, count, &local_events);
+               ret = event_list_create_from_payload(&events_view, count, &local_events);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -1792,9 +1712,9 @@ end:
        return ret;
 }
 
-static enum lttng_error_code flatten_lttng_event_fields(
-               struct lttng_dynamic_pointer_array *event_fields,
-               struct lttng_event_field **flattened_event_fields)
+static enum lttng_error_code
+flatten_lttng_event_fields(struct lttng_dynamic_pointer_array *event_fields,
+                          struct lttng_event_field **flattened_event_fields)
 {
        int ret, i;
        enum lttng_error_code ret_code;
@@ -1823,8 +1743,7 @@ static enum lttng_error_code flatten_lttng_event_fields(
         * We must ensure that "local_flattened_event_fields" is never resized
         * so as to preserve the validity of the flattened objects.
         */
-       ret = lttng_dynamic_buffer_set_capacity(
-                       &local_flattened_event_fields, storage_req);
+       ret = lttng_dynamic_buffer_set_capacity(&local_flattened_event_fields, storage_req);
        if (ret) {
                ret_code = LTTNG_ERR_NOMEM;
                goto end;
@@ -1832,16 +1751,15 @@ static enum lttng_error_code flatten_lttng_event_fields(
 
        for (i = 0; i < nb_event_field; i++) {
                const struct lttng_event_field *element =
-                               (const struct lttng_event_field *)
-                                       lttng_dynamic_pointer_array_get_pointer(
-                                               event_fields, i);
+                       (const struct lttng_event_field *) lttng_dynamic_pointer_array_get_pointer(
+                               event_fields, i);
 
                if (!element) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto end;
                }
-               ret = lttng_dynamic_buffer_append(&local_flattened_event_fields,
-                               element, sizeof(struct lttng_event_field));
+               ret = lttng_dynamic_buffer_append(
+                       &local_flattened_event_fields, element, sizeof(struct lttng_event_field));
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -1857,15 +1775,15 @@ end:
        return ret_code;
 }
 
-static enum lttng_error_code event_field_list_create_from_payload(
-               struct lttng_payload_view *view,
-               unsigned int count,
-               struct lttng_dynamic_pointer_array **event_field_list)
+static enum lttng_error_code
+event_field_list_create_from_payload(struct lttng_payload_view *view,
+                                    unsigned int count,
+                                    struct lttng_dynamic_pointer_array **event_field_list)
 {
        enum lttng_error_code ret_code;
        int ret, offset = 0;
        unsigned int i;
-       struct lttng_dynamic_pointer_array *list = NULL;
+       struct lttng_dynamic_pointer_array *list = nullptr;
 
        assert(view);
        assert(event_field_list);
@@ -1880,12 +1798,11 @@ static enum lttng_error_code event_field_list_create_from_payload(
 
        for (i = 0; i < count; i++) {
                ssize_t event_field_size;
-               struct lttng_event_field *field = NULL;
+               struct lttng_event_field *field = nullptr;
                struct lttng_payload_view event_field_view =
-                               lttng_payload_view_from_view(view, offset, -1);
+                       lttng_payload_view_from_view(view, offset, -1);
 
-               event_field_size = lttng_event_field_create_from_payload(
-                               &event_field_view, &field);
+               event_field_size = lttng_event_field_create_from_payload(&event_field_view, &field);
                if (event_field_size < 0) {
                        ret_code = LTTNG_ERR_INVALID;
                        goto end;
@@ -1908,7 +1825,7 @@ static enum lttng_error_code event_field_list_create_from_payload(
        }
 
        *event_field_list = list;
-       list = NULL;
+       list = nullptr;
        ret_code = LTTNG_OK;
 
 end:
@@ -1921,15 +1838,12 @@ end:
 }
 
 enum lttng_error_code lttng_event_fields_create_and_flatten_from_payload(
-               struct lttng_payload_view *view,
-               unsigned int count,
-               struct lttng_event_field **fields)
+       struct lttng_payload_view *view, unsigned int count, struct lttng_event_field **fields)
 {
        enum lttng_error_code ret_code;
-       struct lttng_dynamic_pointer_array *local_event_fields = NULL;
+       struct lttng_dynamic_pointer_array *local_event_fields = nullptr;
 
-       ret_code = event_field_list_create_from_payload(
-                       view, count, &local_event_fields);
+       ret_code = event_field_list_create_from_payload(view, count, &local_event_fields);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
diff --git a/src/common/eventfd.cpp b/src/common/eventfd.cpp
new file mode 100644 (file)
index 0000000..cb12a51
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "eventfd.hpp"
+
+#include <common/exception.hpp>
+#include <common/format.hpp>
+#include <common/readwrite.hpp>
+
+#include <sys/eventfd.h>
+
+lttng::eventfd::eventfd(bool use_semaphore_semantics, std::uint64_t initial_value) :
+       file_descriptor([use_semaphore_semantics, initial_value]() {
+               int flags = ::EFD_CLOEXEC;
+
+               if (use_semaphore_semantics) {
+                       flags |= ::EFD_SEMAPHORE;
+               }
+
+               const auto raw_fd = ::eventfd(initial_value, flags);
+               if (raw_fd < 0) {
+                       LTTNG_THROW_POSIX("Failed to create eventfd", errno);
+               }
+
+               return raw_fd;
+       }())
+{
+}
+
+void lttng::eventfd::increment(std::uint64_t value)
+{
+       try {
+               write(&value, sizeof(value));
+       } catch (const std::exception& e) {
+               LTTNG_THROW_ERROR(lttng::format("Failed to increment eventfd: {}", e.what()));
+       }
+}
+
+std::uint64_t lttng::eventfd::decrement()
+{
+       std::uint64_t value;
+
+       try {
+               read(&value, sizeof(value));
+       } catch (const std::exception& e) {
+               LTTNG_THROW_ERROR(lttng::format("Failed to decrement eventfd: {}", e.what()));
+       }
+
+       return value;
+}
diff --git a/src/common/eventfd.hpp b/src/common/eventfd.hpp
new file mode 100644 (file)
index 0000000..5bcd2d3
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_EVENTFD_HPP
+#define LTTNG_EVENTFD_HPP
+
+#include <common/file-descriptor.hpp>
+
+#include <cstdint>
+
+namespace lttng {
+
+class eventfd : public file_descriptor {
+public:
+       /* Throws a posix_error exception on failure to create the underlying resource. */
+       explicit eventfd(bool use_semaphore_semantics = true, std::uint64_t initial_value = 0);
+       eventfd(const eventfd&) = delete;
+       eventfd& operator=(const eventfd&) = delete;
+       eventfd(eventfd&&) = delete;
+       void operator=(eventfd&&) = delete;
+       ~eventfd() = default;
+
+       /* Throws on error. */
+       void increment(std::uint64_t value = 1);
+       /*
+        * Note that decrement() will block if the underlying value of the eventfd is 0 when
+        * semaphore semantics are used, see EVENTFD(2).
+        *
+        * decrement() returns the new value of the underlying counter of the eventfd.
+        *
+        * Throws on error.
+        */
+       std::uint64_t decrement();
+};
+
+} /* namespace lttng */
+
+#endif /* LTTNG_EVENTFD_HPP */
index f1c530f7e4249928541a7603f311dcaac2cbee82..028d253f2d885a6c9d9c29a4dc8c875a40b698f2 100644 (file)
@@ -6,12 +6,14 @@
  */
 
 #include "exception.hpp"
-#include <sstream>
+
 #include <common/error.hpp>
 
+#include <sstream>
+
 namespace {
-std::string format_throw_location(
-               const char *file_name, const char *function_name, unsigned int line_number)
+std::string
+format_throw_location(const char *file_name, const char *function_name, unsigned int line_number)
 {
        std::stringstream location;
 
@@ -22,54 +24,66 @@ std::string format_throw_location(
 }
 } /* namespace */
 
-lttng::ctl::error::error(lttng_error_code error_code,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
-       runtime_error(std::string(error_get_str(error_code)), file_name, function_name, line_number),
-       _error_code{error_code}
+lttng::ctl::error::error(const std::string& msg,
+                        lttng_error_code error_code,
+                        const char *file_name,
+                        const char *function_name,
+                        unsigned int line_number) :
+       runtime_error(msg + ": " + std::string(error_get_str(error_code)),
+                     file_name,
+                     function_name,
+                     line_number),
+       _error_code{ error_code }
 {
 }
 
 lttng::posix_error::posix_error(const std::string& msg,
-               int errno_code,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
+                               int errno_code,
+                               const char *file_name,
+                               const char *function_name,
+                               unsigned int line_number) :
        std::system_error(errno_code,
-                       std::generic_category(),
-                       msg + " " + format_throw_location(file_name, function_name, line_number))
+                         std::generic_category(),
+                         msg + " " + format_throw_location(file_name, function_name, line_number))
 {
 }
 
 lttng::runtime_error::runtime_error(const std::string& msg,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
+                                   const char *file_name,
+                                   const char *function_name,
+                                   unsigned int line_number) :
+       std::runtime_error(msg + " " + format_throw_location(file_name, function_name, line_number))
+{
+}
+
+lttng::unsupported_error::unsupported_error(const std::string& msg,
+                                           const char *file_name,
+                                           const char *function_name,
+                                           unsigned int line_number) :
        std::runtime_error(msg + " " + format_throw_location(file_name, function_name, line_number))
 {
 }
 
 lttng::communication_error::communication_error(const std::string& msg,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
+                                               const char *file_name,
+                                               const char *function_name,
+                                               unsigned int line_number) :
        runtime_error(msg, file_name, function_name, line_number)
 {
 }
 
 lttng::protocol_error::protocol_error(const std::string& msg,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
+                                     const char *file_name,
+                                     const char *function_name,
+                                     unsigned int line_number) :
        communication_error(msg, file_name, function_name, line_number)
 {
 }
 
 lttng::invalid_argument_error::invalid_argument_error(const std::string& msg,
-               const char *file_name,
-               const char *function_name,
-               unsigned int line_number) :
+                                                     const char *file_name,
+                                                     const char *function_name,
+                                                     unsigned int line_number) :
        runtime_error(msg, file_name, function_name, line_number)
 {
 }
index b7e8261ed65217f5652fd88192c37e78c178dd76..1880978e76997c3ee9df65f556516fd5f16b9581 100644 (file)
@@ -8,18 +8,19 @@
 #ifndef LTTNG_EXCEPTION_H_
 #define LTTNG_EXCEPTION_H_
 
-#include <string>
+#include <lttng/lttng-error.h>
+
 #include <stdexcept>
+#include <string>
 #include <system_error>
 
-#include <lttng/lttng-error.h>
-
-#define LTTNG_THROW_CTL(error_code) \
+#define LTTNG_THROW_CTL(msg, error_code) \
        throw lttng::ctl::error(msg, error_code, __FILE__, __func__, __LINE__)
 #define LTTNG_THROW_POSIX(msg, errno_code) \
        throw lttng::posix_error(msg, errno_code, __FILE__, __func__, __LINE__)
-#define LTTNG_THROW_ERROR(msg) \
-       throw lttng::runtime_error(msg, __FILE__, __func__, __LINE__)
+#define LTTNG_THROW_ERROR(msg) throw lttng::runtime_error(msg, __FILE__, __func__, __LINE__)
+#define LTTNG_THROW_UNSUPPORTED_ERROR(msg) \
+       throw lttng::unsupported_error(msg, __FILE__, __func__, __LINE__)
 #define LTTNG_THROW_COMMUNICATION_ERROR(msg) \
        throw lttng::communication_error(msg, __FILE__, __func__, __LINE__)
 #define LTTNG_THROW_PROTOCOL_ERROR(msg) \
@@ -31,57 +32,70 @@ namespace lttng {
 class runtime_error : public std::runtime_error {
 public:
        explicit runtime_error(const std::string& msg,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
+                              const char *file_name,
+                              const char *function_name,
+                              unsigned int line_number);
+};
+
+class unsupported_error : public std::runtime_error {
+public:
+       explicit unsupported_error(const std::string& msg,
+                                  const char *file_name,
+                                  const char *function_name,
+                                  unsigned int line_number);
 };
 
 namespace ctl {
 /* Wrap lttng_error_code errors which may be reported through liblttng-ctl's interface. */
 class error : public runtime_error {
 public:
-       explicit error(lttng_error_code error_code,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
-       lttng_error_code get_code() const;
+       explicit error(const std::string& msg,
+                      lttng_error_code error_code,
+                      const char *file_name,
+                      const char *function_name,
+                      unsigned int line_number);
+
+       lttng_error_code code() const noexcept
+       {
+               return _error_code;
+       }
 
 private:
-       lttng_error_code _error_code;
+       const lttng_error_code _error_code;
 };
 } /* namespace ctl */
 
 class posix_error : public std::system_error {
 public:
        explicit posix_error(const std::string& msg,
-                       int errno_code,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
+                            int errno_code,
+                            const char *file_name,
+                            const char *function_name,
+                            unsigned int line_number);
 };
 
 class communication_error : public runtime_error {
 public:
        explicit communication_error(const std::string& msg,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
+                                    const char *file_name,
+                                    const char *function_name,
+                                    unsigned int line_number);
 };
 
 class protocol_error : public communication_error {
 public:
        explicit protocol_error(const std::string& msg,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
+                               const char *file_name,
+                               const char *function_name,
+                               unsigned int line_number);
 };
 
 class invalid_argument_error : public runtime_error {
 public:
        explicit invalid_argument_error(const std::string& msg,
-                       const char *file_name,
-                       const char *function_name,
-                       unsigned int line_number);
+                                       const char *file_name,
+                                       const char *function_name,
+                                       unsigned int line_number);
 };
 
 }; /* namespace lttng */
index 8a0d95243bcdfebf4035da2981ff13cbaed454d9..6cf382757cb01cd9f2792b17b1da81375482681e 100644 (file)
@@ -5,12 +5,13 @@
  *
  */
 
-#include <unistd.h>
-#include <urcu/ref.h>
-
 #include "fd-handle.hpp"
+
 #include <common/error.hpp>
 
+#include <unistd.h>
+#include <urcu/ref.h>
+
 struct fd_handle {
        struct urcu_ref ref;
        int fd;
@@ -25,7 +26,7 @@ static void fd_handle_release(struct urcu_ref *ref)
        ret = close(handle->fd);
        if (ret == -1) {
                PERROR("Failed to close file descriptor of fd_handle upon release: fd = %d",
-                               handle->fd);
+                      handle->fd);
        }
 
        free(handle);
@@ -33,11 +34,11 @@ static void fd_handle_release(struct urcu_ref *ref)
 
 struct fd_handle *fd_handle_create(int fd)
 {
-       struct fd_handle *handle = NULL;
+       struct fd_handle *handle = nullptr;
 
        if (fd < 0) {
                ERR("Attempted to create an fd_handle from an invalid file descriptor: fd = %d",
-                               fd);
+                   fd);
                goto end;
        }
 
@@ -80,11 +81,12 @@ int fd_handle_get_fd(struct fd_handle *handle)
 
 struct fd_handle *fd_handle_copy(const struct fd_handle *handle)
 {
-       struct fd_handle *new_handle = NULL;
+       struct fd_handle *new_handle = nullptr;
        const int new_fd = dup(handle->fd);
 
        if (new_fd < 0) {
-               PERROR("Failed to duplicate file descriptor while copying fd_handle: fd = %d", handle->fd);
+               PERROR("Failed to duplicate file descriptor while copying fd_handle: fd = %d",
+                      handle->fd);
                goto end;
        }
 
index 0c24eab5ea016e74b51e818af1bbcbb02c5b24ff..7f4c2b5b2b698f81116570d94380720c7ceda7c6 100644 (file)
@@ -5,16 +5,8 @@
  *
  */
 
-#include <urcu.h>
-#include <urcu/list.h>
-#include <urcu/rculfhash.h>
-
-#include <fcntl.h>
-#include <inttypes.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <sys/stat.h>
-#include <sys/types.h>
+#include "fd-tracker.hpp"
+#include "inode.hpp"
 
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/urcu.hpp>
 
-#include "fd-tracker.hpp"
-#include "inode.hpp"
+#include <fcntl.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <urcu.h>
+#include <urcu/list.h>
+#include <urcu/rculfhash.h>
 
 /* Tracker lock must be taken by the user. */
-#define TRACKED_COUNT(tracker)                                 \
-       (tracker->count.suspendable.active +                   \
-                       tracker->count.suspendable.suspended + \
-                       tracker->count.unsuspendable)
+#define TRACKED_COUNT(tracker)                                                          \
+       ((tracker)->count.suspendable.active + (tracker)->count.suspendable.suspended + \
+        (tracker)->count.unsuspendable)
 
 /* Tracker lock must be taken by the user. */
-#define ACTIVE_COUNT(tracker) \
-       (tracker->count.suspendable.active + tracker->count.unsuspendable)
+#define ACTIVE_COUNT(tracker) ((tracker)->count.suspendable.active + (tracker)->count.unsuspendable)
 
 /* Tracker lock must be taken by the user. */
-#define SUSPENDED_COUNT(tracker) (tracker->count.suspendable.suspended)
+#define SUSPENDED_COUNT(tracker) ((tracker)->count.suspendable.suspended)
 
 /* Tracker lock must be taken by the user. */
-#define SUSPENDABLE_COUNT(tracker)           \
-       (tracker->count.suspendable.active + \
-                       tracker->count.suspendable.suspended)
+#define SUSPENDABLE_COUNT(tracker) \
+       ((tracker)->count.suspendable.active + (tracker)->count.suspendable.suspended)
 
 /* Tracker lock must be taken by the user. */
-#define UNSUSPENDABLE_COUNT(tracker) (tracker->count.unsuspendable)
+#define UNSUSPENDABLE_COUNT(tracker) ((tracker)->count.unsuspendable)
 
 struct fd_tracker {
        pthread_mutex_t lock;
@@ -138,10 +135,10 @@ struct {
 
 static int match_fd(struct cds_lfht_node *node, const void *key);
 static void unsuspendable_fd_destroy(struct unsuspendable_fd *entry);
-static struct unsuspendable_fd *unsuspendable_fd_create(
-               const char *name, int fd);
+static struct unsuspendable_fd *unsuspendable_fd_create(const char *name, int fd);
 static int open_from_properties(const struct lttng_directory_handle *dir_handle,
-               const char *path, struct open_properties *properties);
+                               const char *path,
+                               struct open_properties *properties);
 
 static void fs_handle_tracked_log(struct fs_handle_tracked *handle);
 static int fs_handle_tracked_suspend(struct fs_handle_tracked *handle);
@@ -151,29 +148,23 @@ static void fs_handle_tracked_put_fd(struct fs_handle *_handle);
 static int fs_handle_tracked_unlink(struct fs_handle *_handle);
 static int fs_handle_tracked_close(struct fs_handle *_handle);
 
-static void fd_tracker_track(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle);
-static void fd_tracker_untrack(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle);
-static int fd_tracker_suspend_handles(
-               struct fd_tracker *tracker, unsigned int count);
-static int fd_tracker_restore_handle(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle);
+static void fd_tracker_track(struct fd_tracker *tracker, struct fs_handle_tracked *handle);
+static void fd_tracker_untrack(struct fd_tracker *tracker, struct fs_handle_tracked *handle);
+static int fd_tracker_suspend_handles(struct fd_tracker *tracker, unsigned int count);
+static int fd_tracker_restore_handle(struct fd_tracker *tracker, struct fs_handle_tracked *handle);
 
 /* Match function of the tracker's unsuspendable_fds hash table. */
 static int match_fd(struct cds_lfht_node *node, const void *key)
 {
-       struct unsuspendable_fd *entry = lttng::utils::container_of(
-                       node, &unsuspendable_fd::tracker_node);
+       struct unsuspendable_fd *entry =
+               lttng::utils::container_of(node, &unsuspendable_fd::tracker_node);
 
-       return hash_match_key_ulong(
-                       (void *) (unsigned long) entry->fd, (void *) key);
+       return hash_match_key_ulong((void *) (unsigned long) entry->fd, (void *) key);
 }
 
 static void delete_unsuspendable_fd(struct rcu_head *head)
 {
-       struct unsuspendable_fd *fd = caa_container_of(
-                       head, struct unsuspendable_fd, rcu_head);
+       struct unsuspendable_fd *fd = caa_container_of(head, struct unsuspendable_fd, rcu_head);
 
        free(fd->name);
        free(fd);
@@ -187,8 +178,7 @@ static void unsuspendable_fd_destroy(struct unsuspendable_fd *entry)
        call_rcu(&entry->rcu_head, delete_unsuspendable_fd);
 }
 
-static struct unsuspendable_fd *unsuspendable_fd_create(
-               const char *name, int fd)
+static struct unsuspendable_fd *unsuspendable_fd_create(const char *name, int fd)
 {
        struct unsuspendable_fd *entry = zmalloc<unsuspendable_fd>();
 
@@ -206,7 +196,7 @@ static struct unsuspendable_fd *unsuspendable_fd_create(
        return entry;
 error:
        unsuspendable_fd_destroy(entry);
-       return NULL;
+       return nullptr;
 }
 
 static void fs_handle_tracked_log(struct fs_handle_tracked *handle)
@@ -214,11 +204,13 @@ static void fs_handle_tracked_log(struct fs_handle_tracked *handle)
        const char *path;
 
        pthread_mutex_lock(&handle->lock);
-       lttng_inode_borrow_location(handle->inode, NULL, &path);
+       lttng_inode_borrow_location(handle->inode, nullptr, &path);
 
        if (handle->fd >= 0) {
-               DBG_NO_LOC("    %s [active, fd %d%s]", path, handle->fd,
-                               handle->in_use ? ", in use" : "");
+               DBG_NO_LOC("    %s [active, fd %d%s]",
+                          path,
+                          handle->fd,
+                          handle->in_use ? ", in use" : "");
        } else {
                DBG_NO_LOC("    %s [suspended]", path);
        }
@@ -234,8 +226,7 @@ static int fs_handle_tracked_suspend(struct fs_handle_tracked *handle)
        const struct lttng_directory_handle *node_directory_handle;
 
        pthread_mutex_lock(&handle->lock);
-       lttng_inode_borrow_location(
-                       handle->inode, &node_directory_handle, &path);
+       lttng_inode_borrow_location(handle->inode, &node_directory_handle, &path);
        LTTNG_ASSERT(handle->fd >= 0);
        if (handle->in_use) {
                /* This handle can't be suspended as it is currently in use. */
@@ -243,19 +234,16 @@ static int fs_handle_tracked_suspend(struct fs_handle_tracked *handle)
                goto end;
        }
 
-       ret = lttng_directory_handle_stat(
-                       node_directory_handle, path, &fs_stat);
+       ret = lttng_directory_handle_stat(node_directory_handle, path, &fs_stat);
        if (ret) {
-               PERROR("Filesystem handle to %s cannot be suspended as stat() failed",
-                               path);
+               PERROR("Filesystem handle to %s cannot be suspended as stat() failed", path);
                ret = -errno;
                goto end;
        }
 
        if (fs_stat.st_ino != handle->ino) {
                /* Don't suspend as the handle would not be restorable. */
-               WARN("Filesystem handle to %s cannot be suspended as its inode changed",
-                               path);
+               WARN("Filesystem handle to %s cannot be suspended as its inode changed", path);
                ret = -ENOENT;
                goto end;
        }
@@ -263,20 +251,21 @@ static int fs_handle_tracked_suspend(struct fs_handle_tracked *handle)
        handle->offset = lseek(handle->fd, 0, SEEK_CUR);
        if (handle->offset == -1) {
                WARN("Filesystem handle to %s cannot be suspended as lseek() failed to sample its current position",
-                               path);
+                    path);
                ret = -errno;
                goto end;
        }
 
        ret = close(handle->fd);
        if (ret) {
-               PERROR("Filesystem handle to %s cannot be suspended as close() failed",
-                               path);
+               PERROR("Filesystem handle to %s cannot be suspended as close() failed", path);
                ret = -errno;
                goto end;
        }
        DBG("Suspended filesystem handle to %s (fd %i) at position %" PRId64,
-                       path, handle->fd, handle->offset);
+           path,
+           handle->fd,
+           handle->offset);
        handle->fd = -1;
 end:
        if (ret) {
@@ -293,16 +282,13 @@ static int fs_handle_tracked_restore(struct fs_handle_tracked *handle)
        const char *path;
        const struct lttng_directory_handle *node_directory_handle;
 
-       lttng_inode_borrow_location(
-                       handle->inode, &node_directory_handle, &path);
+       lttng_inode_borrow_location(handle->inode, &node_directory_handle, &path);
 
        LTTNG_ASSERT(handle->fd == -1);
        LTTNG_ASSERT(path);
-       ret = open_from_properties(
-                       node_directory_handle, path, &handle->properties);
+       ret = open_from_properties(node_directory_handle, path, &handle->properties);
        if (ret < 0) {
-               PERROR("Failed to restore filesystem handle to %s, open() failed",
-                               path);
+               PERROR("Failed to restore filesystem handle to %s, open() failed", path);
                ret = -errno;
                goto end;
        }
@@ -310,13 +296,14 @@ static int fs_handle_tracked_restore(struct fs_handle_tracked *handle)
 
        ret = lseek(fd, handle->offset, SEEK_SET);
        if (ret < 0) {
-               PERROR("Failed to restore filesystem handle to %s, lseek() failed",
-                               path);
+               PERROR("Failed to restore filesystem handle to %s, lseek() failed", path);
                ret = -errno;
                goto end;
        }
        DBG("Restored filesystem handle to %s (fd %i) at position %" PRId64,
-                       path, fd, handle->offset);
+           path,
+           fd,
+           handle->offset);
        ret = 0;
        handle->fd = fd;
        fd = -1;
@@ -328,7 +315,8 @@ end:
 }
 
 static int open_from_properties(const struct lttng_directory_handle *dir_handle,
-               const char *path, struct open_properties *properties)
+                               const char *path,
+                               struct open_properties *properties)
 {
        int ret;
 
@@ -339,11 +327,10 @@ static int open_from_properties(const struct lttng_directory_handle *dir_handle,
         * thus it is ignored here.
         */
        if ((properties->flags & O_CREAT) && properties->mode.is_set) {
-               ret = lttng_directory_handle_open_file(dir_handle, path,
-                               properties->flags, properties->mode.value);
+               ret = lttng_directory_handle_open_file(
+                       dir_handle, path, properties->flags, properties->mode.value);
        } else {
-               ret = lttng_directory_handle_open_file(dir_handle, path,
-                               properties->flags, 0);
+               ret = lttng_directory_handle_open_file(dir_handle, path, properties->flags, 0);
        }
        /*
         * Some flags should not be used beyond the initial open() of a
@@ -364,8 +351,7 @@ end:
        return ret;
 }
 
-struct fd_tracker *fd_tracker_create(const char *unlinked_file_path,
-               unsigned int capacity)
+struct fd_tracker *fd_tracker_create(const char *unlinked_file_path, unsigned int capacity)
 {
        struct fd_tracker *tracker = zmalloc<fd_tracker>();
 
@@ -375,7 +361,7 @@ struct fd_tracker *fd_tracker_create(const char *unlinked_file_path,
 
        pthread_mutex_lock(&seed.lock);
        if (!seed.initialized) {
-               seed.value = (unsigned long) time(NULL);
+               seed.value = (unsigned long) time(nullptr);
                seed.initialized = true;
        }
        pthread_mutex_unlock(&seed.lock);
@@ -383,8 +369,8 @@ struct fd_tracker *fd_tracker_create(const char *unlinked_file_path,
        CDS_INIT_LIST_HEAD(&tracker->active_handles);
        CDS_INIT_LIST_HEAD(&tracker->suspended_handles);
        tracker->capacity = capacity;
-       tracker->unsuspendable_fds = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       tracker->unsuspendable_fds = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!tracker->unsuspendable_fds) {
                ERR("Failed to create fd-tracker's unsuspendable_fds hash table");
                goto error;
@@ -395,18 +381,17 @@ struct fd_tracker *fd_tracker_create(const char *unlinked_file_path,
                goto error;
        }
 
-       tracker->unlinked_file_pool =
-                       lttng_unlinked_file_pool_create(unlinked_file_path);
+       tracker->unlinked_file_pool = lttng_unlinked_file_pool_create(unlinked_file_path);
        if (!tracker->unlinked_file_pool) {
                goto error;
        }
        DBG("File descriptor tracker created with a limit of %u simultaneously-opened FDs",
-                       capacity);
+           capacity);
 end:
        return tracker;
 error:
        fd_tracker_destroy(tracker);
-       return NULL;
+       return nullptr;
 }
 
 void fd_tracker_log(struct fd_tracker *tracker)
@@ -429,12 +414,10 @@ void fd_tracker_log(struct fd_tracker *tracker)
        DBG_NO_LOC("    capacity:        %u", tracker->capacity);
 
        DBG_NO_LOC("  Tracked suspendable file descriptors");
-       cds_list_for_each_entry(
-                       handle, &tracker->active_handles, handles_list_node) {
+       cds_list_for_each_entry (handle, &tracker->active_handles, handles_list_node) {
                fs_handle_tracked_log(handle);
        }
-       cds_list_for_each_entry(handle, &tracker->suspended_handles,
-                       handles_list_node) {
+       cds_list_for_each_entry (handle, &tracker->suspended_handles, handles_list_node) {
                fs_handle_tracked_log(handle);
        }
        if (!SUSPENDABLE_COUNT(tracker)) {
@@ -442,14 +425,18 @@ void fd_tracker_log(struct fd_tracker *tracker)
        }
 
        DBG_NO_LOC("  Tracked unsuspendable file descriptors");
-       rcu_read_lock();
-       cds_lfht_for_each_entry(tracker->unsuspendable_fds, &iter,
-                       unsuspendable_fd, tracker_node) {
-               DBG_NO_LOC("    %s [active, fd %d]",
-                               unsuspendable_fd->name ?: "Unnamed",
-                               unsuspendable_fd->fd);
-       }
-       rcu_read_unlock();
+
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       tracker->unsuspendable_fds, &iter, unsuspendable_fd, tracker_node) {
+                       DBG_NO_LOC("    %s [active, fd %d]",
+                                  unsuspendable_fd->name ?: "Unnamed",
+                                  unsuspendable_fd->fd);
+               }
+       }
+
        if (!UNSUSPENDABLE_COUNT(tracker)) {
                DBG_NO_LOC("    None");
        }
@@ -471,7 +458,7 @@ int fd_tracker_destroy(struct fd_tracker *tracker)
        pthread_mutex_lock(&tracker->lock);
        if (TRACKED_COUNT(tracker)) {
                ERR("A file descriptor leak has been detected: %u tracked file descriptors are still being tracked",
-                               TRACKED_COUNT(tracker));
+                   TRACKED_COUNT(tracker));
                pthread_mutex_unlock(&tracker->lock);
                fd_tracker_log(tracker);
                ret = -1;
@@ -480,7 +467,7 @@ int fd_tracker_destroy(struct fd_tracker *tracker)
        pthread_mutex_unlock(&tracker->lock);
 
        if (tracker->unsuspendable_fds) {
-               ret = cds_lfht_destroy(tracker->unsuspendable_fds, NULL);
+               ret = cds_lfht_destroy(tracker->unsuspendable_fds, nullptr);
                LTTNG_ASSERT(!ret);
        }
 
@@ -493,21 +480,20 @@ end:
 }
 
 struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
-               struct lttng_directory_handle *directory,
-               const char *path,
-               int flags,
-               mode_t *mode)
+                                           struct lttng_directory_handle *directory,
+                                           const char *path,
+                                           int flags,
+                                           mode_t *mode)
 {
        int ret;
-       struct fs_handle_tracked *handle = NULL;
+       struct fs_handle_tracked *handle = nullptr;
        struct stat fd_stat;
-       struct open_properties properties = {
-               .flags = flags,
-               .mode = {
-                       .is_set = !!mode,
-                       .value = static_cast<mode_t>(mode ? *mode : 0),
-               }
-       };
+       struct open_properties properties = { .flags = flags,
+                                             .mode = {
+                                                     .is_set = !!mode,
+                                                     .value =
+                                                             static_cast<mode_t>(mode ? *mode : 0),
+                                             } };
 
        pthread_mutex_lock(&tracker->lock);
        if (ACTIVE_COUNT(tracker) == tracker->capacity) {
@@ -523,7 +509,7 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
                         * the tracker's capacity.
                         */
                        WARN("Cannot open file system handle, too many unsuspendable file descriptors are opened (%u)",
-                                       tracker->count.unsuspendable);
+                            tracker->count.unsuspendable);
                        goto end;
                }
        }
@@ -532,7 +518,7 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
        if (!handle) {
                goto end;
        }
-       handle->parent = (typeof(handle->parent)) {
+       handle->parent = (typeof(handle->parent)){
                .get_fd = fs_handle_tracked_get_fd,
                .put_fd = fs_handle_tracked_put_fd,
                .unlink = fs_handle_tracked_unlink,
@@ -541,7 +527,7 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
 
        handle->tracker = tracker;
 
-       ret = pthread_mutex_init(&handle->lock, NULL);
+       ret = pthread_mutex_init(&handle->lock, nullptr);
        if (ret) {
                PERROR("Failed to initialize handle mutex while creating fs handle");
                goto error_mutex_init;
@@ -555,9 +541,8 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
 
        handle->properties = properties;
 
-       handle->inode = lttng_inode_registry_get_inode(tracker->inode_registry,
-                       directory, path, handle->fd,
-                       tracker->unlinked_file_pool);
+       handle->inode = lttng_inode_registry_get_inode(
+               tracker->inode_registry, directory, path, handle->fd, tracker->unlinked_file_pool);
        if (!handle->inode) {
                ERR("Failed to get lttng_inode corresponding to file %s", path);
                goto error;
@@ -572,7 +557,7 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
        fd_tracker_track(tracker, handle);
 end:
        pthread_mutex_unlock(&tracker->lock);
-       return handle ? &handle->parent : NULL;
+       return handle ? &handle->parent : nullptr;
 error:
        if (handle->inode) {
                lttng_inode_put(handle->inode);
@@ -580,20 +565,18 @@ error:
        pthread_mutex_destroy(&handle->lock);
 error_mutex_init:
        free(handle);
-       handle = NULL;
+       handle = nullptr;
        goto end;
 }
 
 /* Caller must hold the tracker's lock. */
-static int fd_tracker_suspend_handles(
-               struct fd_tracker *tracker, unsigned int count)
+static int fd_tracker_suspend_handles(struct fd_tracker *tracker, unsigned int count)
 {
        unsigned int left_to_close = count;
        unsigned int attempts_left = tracker->count.suspendable.active;
        struct fs_handle_tracked *handle, *tmp;
 
-       cds_list_for_each_entry_safe(handle, tmp, &tracker->active_handles,
-                       handles_list_node) {
+       cds_list_for_each_entry_safe (handle, tmp, &tracker->active_handles, handles_list_node) {
                int ret;
 
                fd_tracker_untrack(tracker, handle);
@@ -612,15 +595,16 @@ static int fd_tracker_suspend_handles(
 }
 
 int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
-               int *out_fds,
-               const char **names,
-               unsigned int fd_count,
-               fd_open_cb open,
-               void *user_data)
+                                    int *out_fds,
+                                    const char **names,
+                                    unsigned int fd_count,
+                                    fd_open_cb open,
+                                    void *user_data)
 {
        int ret, user_ret, i, fds_to_suspend;
        unsigned int active_fds;
        struct unsuspendable_fd **entries;
+       lttng::urcu::read_lock_guard read_lock;
 
        entries = calloc<unsuspendable_fd *>(fd_count);
        if (!entries) {
@@ -631,12 +615,10 @@ int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
        pthread_mutex_lock(&tracker->lock);
 
        active_fds = ACTIVE_COUNT(tracker);
-       fds_to_suspend = (int) active_fds + (int) fd_count -
-                       (int) tracker->capacity;
+       fds_to_suspend = (int) active_fds + (int) fd_count - (int) tracker->capacity;
        if (fds_to_suspend > 0) {
                if (fds_to_suspend <= tracker->count.suspendable.active) {
-                       ret = fd_tracker_suspend_handles(
-                                       tracker, fds_to_suspend);
+                       ret = fd_tracker_suspend_handles(tracker, fds_to_suspend);
                        if (ret) {
                                goto end_unlock;
                        }
@@ -647,7 +629,7 @@ int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
                         * tracker's capacity.
                         */
                        WARN("Cannot open unsuspendable fd, too many unsuspendable file descriptors are opened (%u)",
-                                       tracker->count.unsuspendable);
+                            tracker->count.unsuspendable);
                        ret = -EMFILE;
                        goto end_unlock;
                }
@@ -664,8 +646,8 @@ int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
         * of unsuspendable fds.
         */
        for (i = 0; i < fd_count; i++) {
-               struct unsuspendable_fd *entry = unsuspendable_fd_create(
-                               names ? names[i] : NULL, out_fds[i]);
+               struct unsuspendable_fd *entry =
+                       unsuspendable_fd_create(names ? names[i] : nullptr, out_fds[i]);
 
                if (!entry) {
                        ret = -1;
@@ -674,27 +656,24 @@ int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
                entries[i] = entry;
        }
 
-       rcu_read_lock();
        for (i = 0; i < fd_count; i++) {
                struct cds_lfht_node *node;
                struct unsuspendable_fd *entry = entries[i];
 
                node = cds_lfht_add_unique(tracker->unsuspendable_fds,
-                               hash_key_ulong((void *) (unsigned long)
-                                                               out_fds[i],
-                                               seed.value),
-                               match_fd, (void *) (unsigned long) out_fds[i],
-                               &entry->tracker_node);
+                                          hash_key_ulong((void *) (unsigned long) out_fds[i],
+                                                         seed.value),
+                                          match_fd,
+                                          (void *) (unsigned long) out_fds[i],
+                                          &entry->tracker_node);
 
                if (node != &entry->tracker_node) {
                        ret = -EEXIST;
-                       rcu_read_unlock();
                        goto end_free_entries;
                }
-               entries[i] = NULL;
+               entries[i] = nullptr;
        }
        tracker->count.unsuspendable += fd_count;
-       rcu_read_unlock();
        ret = user_ret;
 end_unlock:
        pthread_mutex_unlock(&tracker->lock);
@@ -709,13 +688,14 @@ end_free_entries:
 }
 
 int fd_tracker_close_unsuspendable_fd(struct fd_tracker *tracker,
-               int *fds_in,
-               unsigned int fd_count,
-               fd_close_cb close,
-               void *user_data)
+                                     int *fds_in,
+                                     unsigned int fd_count,
+                                     fd_close_cb close,
+                                     void *user_data)
 {
        int i, ret, user_ret;
-       int *fds = NULL;
+       int *fds = nullptr;
+       lttng::urcu::read_lock_guard read_lock;
 
        /*
         * Maintain a local copy of fds_in as the user's callback may modify its
@@ -729,7 +709,6 @@ int fd_tracker_close_unsuspendable_fd(struct fd_tracker *tracker,
        memcpy(fds, fds_in, sizeof(*fds) * fd_count);
 
        pthread_mutex_lock(&tracker->lock);
-       rcu_read_lock();
 
        /* Let the user close the file descriptors. */
        user_ret = close(user_data, fds_in);
@@ -745,20 +724,19 @@ int fd_tracker_close_unsuspendable_fd(struct fd_tracker *tracker,
                struct unsuspendable_fd *entry;
 
                cds_lfht_lookup(tracker->unsuspendable_fds,
-                               hash_key_ulong((void *) (unsigned long) fds[i],
-                                               seed.value),
-                               match_fd, (void *) (unsigned long) fds[i],
+                               hash_key_ulong((void *) (unsigned long) fds[i], seed.value),
+                               match_fd,
+                               (void *) (unsigned long) fds[i],
                                &iter);
                node = cds_lfht_iter_get_node(&iter);
                if (!node) {
                        /* Unknown file descriptor. */
                        WARN("Untracked file descriptor %d passed to fd_tracker_close_unsuspendable_fd()",
-                                       fds[i]);
+                            fds[i]);
                        ret = -EINVAL;
                        goto end_unlock;
                }
-               entry = lttng::utils::container_of(
-                               node, &unsuspendable_fd::tracker_node);
+               entry = lttng::utils::container_of(node, &unsuspendable_fd::tracker_node);
 
                cds_lfht_del(tracker->unsuspendable_fds, node);
                unsuspendable_fd_destroy(entry);
@@ -768,7 +746,6 @@ int fd_tracker_close_unsuspendable_fd(struct fd_tracker *tracker,
        tracker->count.unsuspendable -= fd_count;
        ret = 0;
 end_unlock:
-       rcu_read_unlock();
        pthread_mutex_unlock(&tracker->lock);
        free(fds);
 end:
@@ -776,23 +753,19 @@ end:
 }
 
 /* Caller must have taken the tracker's and handle's locks. */
-static void fd_tracker_track(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle)
+static void fd_tracker_track(struct fd_tracker *tracker, struct fs_handle_tracked *handle)
 {
        if (handle->fd >= 0) {
                tracker->count.suspendable.active++;
-               cds_list_add_tail(&handle->handles_list_node,
-                               &tracker->active_handles);
+               cds_list_add_tail(&handle->handles_list_node, &tracker->active_handles);
        } else {
                tracker->count.suspendable.suspended++;
-               cds_list_add_tail(&handle->handles_list_node,
-                               &tracker->suspended_handles);
+               cds_list_add_tail(&handle->handles_list_node, &tracker->suspended_handles);
        }
 }
 
 /* Caller must have taken the tracker's and handle's locks. */
-static void fd_tracker_untrack(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle)
+static void fd_tracker_untrack(struct fd_tracker *tracker, struct fs_handle_tracked *handle)
 {
        if (handle->fd >= 0) {
                tracker->count.suspendable.active--;
@@ -803,8 +776,7 @@ static void fd_tracker_untrack(
 }
 
 /* Caller must have taken the tracker's and handle's locks. */
-static int fd_tracker_restore_handle(
-               struct fd_tracker *tracker, struct fs_handle_tracked *handle)
+static int fd_tracker_restore_handle(struct fd_tracker *tracker, struct fs_handle_tracked *handle)
 {
        int ret;
 
@@ -825,7 +797,7 @@ static int fs_handle_tracked_get_fd(struct fs_handle *_handle)
 {
        int ret;
        struct fs_handle_tracked *handle =
-                       lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
+               lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
 
        /*
         * TODO This should be optimized as it is a fairly hot path.
@@ -866,7 +838,7 @@ end:
 static void fs_handle_tracked_put_fd(struct fs_handle *_handle)
 {
        struct fs_handle_tracked *handle =
-                       lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
+               lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
 
        pthread_mutex_lock(&handle->lock);
        handle->in_use = false;
@@ -877,7 +849,7 @@ static int fs_handle_tracked_unlink(struct fs_handle *_handle)
 {
        int ret;
        struct fs_handle_tracked *handle =
-                       lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
+               lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
 
        pthread_mutex_lock(&handle->tracker->lock);
        pthread_mutex_lock(&handle->lock);
@@ -890,10 +862,10 @@ static int fs_handle_tracked_unlink(struct fs_handle *_handle)
 static int fs_handle_tracked_close(struct fs_handle *_handle)
 {
        int ret = 0;
-       const char *path = NULL;
+       const char *path = nullptr;
        struct fs_handle_tracked *handle =
-                       lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
-       struct lttng_directory_handle *inode_directory_handle = NULL;
+               lttng::utils::container_of(_handle, &fs_handle_tracked::parent);
+       struct lttng_directory_handle *inode_directory_handle = nullptr;
 
        if (!handle) {
                ret = -EINVAL;
@@ -903,7 +875,7 @@ static int fs_handle_tracked_close(struct fs_handle *_handle)
        pthread_mutex_lock(&handle->tracker->lock);
        pthread_mutex_lock(&handle->lock);
        if (handle->inode) {
-               lttng_inode_borrow_location(handle->inode, NULL, &path);
+               lttng_inode_borrow_location(handle->inode, nullptr, &path);
                /*
                 * Here a reference to the inode's directory handle is acquired
                 * to prevent the last reference to it from being released while
@@ -923,9 +895,7 @@ static int fs_handle_tracked_close(struct fs_handle *_handle)
                 * enough to not attempt to recursively acquire the tracker's
                 * lock twice.
                 */
-               inode_directory_handle =
-                               lttng_inode_get_location_directory_handle(
-                                               handle->inode);
+               inode_directory_handle = lttng_inode_get_location_directory_handle(handle->inode);
        }
        fd_tracker_untrack(handle->tracker, handle);
        if (handle->fd >= 0) {
@@ -935,7 +905,8 @@ static int fs_handle_tracked_close(struct fs_handle *_handle)
                 */
                if (close(handle->fd)) {
                        PERROR("Failed to close the file descriptor (%d) of fs handle to %s, close() returned",
-                                       handle->fd, path ? path : "Unknown");
+                              handle->fd,
+                              path ? path : "Unknown");
                }
                handle->fd = -1;
        }
index a38c880bdfebdfc0e2cd9e6f28af8cf2601e19e2..06e9b1d1499b306b3bf32c451d7ecdd31651f9a3 100644 (file)
@@ -10,6 +10,7 @@
 
 #include <common/compat/directory-handle.hpp>
 #include <common/macros.hpp>
+
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -26,7 +27,7 @@ struct fd_tracker;
  *
  * Must return zero on success. Negative values should map to a UNIX error code.
  */
-typedef int (*fd_open_cb)(void *, int *out_fds);
+using fd_open_cb = int (*)(void *, int *);
 
 /*
  * Callback to allow the user to close a now-untracked file descriptor. This
@@ -38,7 +39,7 @@ typedef int (*fd_open_cb)(void *, int *out_fds);
  *
  * Must return zero on success. Negative values should map to a UNIX error code.
  */
-typedef int (*fd_close_cb)(void *, int *in_fds);
+using fd_close_cb = int (*)(void *, int *);
 
 /*
  * Set the maximal number of fds that the process should be allowed to open at
@@ -49,8 +50,7 @@ typedef int (*fd_close_cb)(void *, int *in_fds);
  * under which unlinked files will be stored for as long as a reference to them
  * is held.
  */
-struct fd_tracker *fd_tracker_create(const char *unlinked_file_path,
-               unsigned int capacity);
+struct fd_tracker *fd_tracker_create(const char *unlinked_file_path, unsigned int capacity);
 
 /* Returns an error if file descriptors are leaked. */
 int fd_tracker_destroy(struct fd_tracker *tracker);
@@ -78,10 +78,10 @@ int fd_tracker_destroy(struct fd_tracker *tracker);
  * open.
  */
 struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
-               struct lttng_directory_handle *directory,
-               const char *path,
-               int flags,
-               mode_t *mode);
+                                           struct lttng_directory_handle *directory,
+                                           const char *path,
+                                           int flags,
+                                           mode_t *mode);
 
 /*
  * Open a tracked unsuspendable file descriptor.
@@ -106,11 +106,11 @@ struct fs_handle *fd_tracker_open_fs_handle(struct fd_tracker *tracker,
  *             accommodates the request for a new unsuspendable entry.
  */
 int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
-               int *out_fds,
-               const char **names,
-               unsigned int fd_count,
-               fd_open_cb open,
-               void *data);
+                                    int *out_fds,
+                                    const char **names,
+                                    unsigned int fd_count,
+                                    fd_open_cb open,
+                                    void *data);
 
 /*
  * Close a tracked unsuspendable file descriptor.
@@ -127,11 +127,8 @@ int fd_tracker_open_unsuspendable_fd(struct fd_tracker *tracker,
  * Closed fds are set to -1 in the fds array which, in the event of an error,
  * allows the user to know which file descriptors are no longer being tracked.
  */
-int fd_tracker_close_unsuspendable_fd(struct fd_tracker *tracker,
-               int *fds,
-               unsigned int fd_count,
-               fd_close_cb close,
-               void *data);
+int fd_tracker_close_unsuspendable_fd(
+       struct fd_tracker *tracker, int *fds, unsigned int fd_count, fd_close_cb close, void *data);
 
 /*
  * Log the contents of the fd_tracker.
index c00f9d81ff1686e8ec16b30cc32095a53884f12c..c98f6ad455c39598bcafb8eb9918852b822aba07 100644 (file)
@@ -5,15 +5,20 @@
  *
  */
 
+#include "inode.hpp"
+
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
 #include <common/string-utils/format.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
-#include <inttypes.h>
+
 #include <lttng/constant.h>
+
+#include <inttypes.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -21,8 +26,6 @@
 #include <urcu/rculfhash.h>
 #include <urcu/ref.h>
 
-#include "inode.hpp"
-
 namespace {
 struct inode_id {
        dev_t device;
@@ -68,9 +71,9 @@ struct {
        bool initialized;
        unsigned long value;
 } seed = {
-               .lock = PTHREAD_MUTEX_INITIALIZER,
-               .initialized = false,
-               .value = 0,
+       .lock = PTHREAD_MUTEX_INITIALIZER,
+       .initialized = false,
+       .value = 0,
 };
 } /* namespace */
 
@@ -78,38 +81,34 @@ static unsigned long lttng_inode_id_hash(const struct inode_id *id)
 {
        uint64_t device = id->device, inode_no = id->inode;
 
-       return hash_key_u64(&device, seed.value) ^
-              hash_key_u64(&inode_no, seed.value);
+       return hash_key_u64(&device, seed.value) ^ hash_key_u64(&inode_no, seed.value);
 }
 
 static int lttng_inode_match(struct cds_lfht_node *node, const void *key)
 {
        const struct inode_id *id = (inode_id *) key;
-       const struct lttng_inode *inode = lttng::utils::container_of(
-                       node, &lttng_inode::registry_node);
+       const struct lttng_inode *inode =
+               lttng::utils::container_of(node, &lttng_inode::registry_node);
 
        return inode->id.device == id->device && inode->id.inode == id->inode;
 }
 
 static void lttng_inode_free(struct rcu_head *head)
 {
-       struct lttng_inode *inode =
-                       lttng::utils::container_of(head, &lttng_inode::rcu_head);
+       struct lttng_inode *inode = lttng::utils::container_of(head, &lttng_inode::rcu_head);
 
        free(inode);
 }
 
-static int lttng_unlinked_file_pool_add_inode(
-               struct lttng_unlinked_file_pool *pool,
-               struct lttng_inode *inode)
+static int lttng_unlinked_file_pool_add_inode(struct lttng_unlinked_file_pool *pool,
+                                             struct lttng_inode *inode)
 {
        int ret;
        const unsigned int unlinked_id = pool->next_id++;
        char *inode_unlinked_name;
        bool reference_acquired;
 
-       DBG("Adding inode of %s to unlinked file pool as id %u",
-                       inode->location.path, unlinked_id);
+       DBG("Adding inode of %s to unlinked file pool as id %u", inode->location.path, unlinked_id);
        ret = asprintf(&inode_unlinked_name, "%u", unlinked_id);
        if (ret < 0) {
                ERR("Failed to format unlinked inode name");
@@ -118,11 +117,9 @@ static int lttng_unlinked_file_pool_add_inode(
        }
 
        if (pool->file_count == 0) {
-               DBG("Creating unlinked files directory at %s",
-                               pool->unlink_directory_path);
+               DBG("Creating unlinked files directory at %s", pool->unlink_directory_path);
                LTTNG_ASSERT(!pool->unlink_directory_handle);
-               ret = utils_mkdir(pool->unlink_directory_path,
-                               S_IRWXU | S_IRWXG, -1, -1);
+               ret = utils_mkdir(pool->unlink_directory_path, S_IRWXU | S_IRWXG, -1, -1);
                if (ret) {
                        if (errno == EEXIST) {
                                /*
@@ -130,40 +127,40 @@ static int lttng_unlinked_file_pool_add_inode(
                                 * error.
                                 */
                                DBG("Unlinked file directory \"%s\" already exists",
-                                               pool->unlink_directory_path);
+                                   pool->unlink_directory_path);
                        } else {
                                PERROR("Failed to create unlinked files directory at %s",
-                                               pool->unlink_directory_path);
+                                      pool->unlink_directory_path);
                                goto end;
                        }
                }
-               pool->unlink_directory_handle = lttng_directory_handle_create(
-                               pool->unlink_directory_path);
+               pool->unlink_directory_handle =
+                       lttng_directory_handle_create(pool->unlink_directory_path);
                if (!pool->unlink_directory_handle) {
                        ERR("Failed to create directory handle to unlinked file pool at %s",
-                                       pool->unlink_directory_path);
+                           pool->unlink_directory_path);
                        ret = -1;
                        goto end;
                }
        }
 
        ret = lttng_directory_handle_rename(inode->location.directory_handle,
-                       inode->location.path, pool->unlink_directory_handle,
-                       inode_unlinked_name);
+                                           inode->location.path,
+                                           pool->unlink_directory_handle,
+                                           inode_unlinked_name);
        if (ret) {
                goto end;
        }
 
        lttng_directory_handle_put(inode->location.directory_handle);
-       inode->location.directory_handle = NULL;
-       reference_acquired = lttng_directory_handle_get(
-                       pool->unlink_directory_handle);
+       inode->location.directory_handle = nullptr;
+       reference_acquired = lttng_directory_handle_get(pool->unlink_directory_handle);
        LTTNG_ASSERT(reference_acquired);
        inode->location.directory_handle = pool->unlink_directory_handle;
 
        free(inode->location.path);
        inode->location.path = inode_unlinked_name;
-       inode_unlinked_name = NULL;
+       inode_unlinked_name = nullptr;
        LTTNG_OPTIONAL_SET(&inode->unlinked_id, unlinked_id);
        pool->file_count++;
 end:
@@ -171,26 +168,25 @@ end:
        return ret;
 }
 
-static int lttng_unlinked_file_pool_remove_inode(
-               struct lttng_unlinked_file_pool *pool,
-               struct lttng_inode *inode)
+static int lttng_unlinked_file_pool_remove_inode(struct lttng_unlinked_file_pool *pool,
+                                                struct lttng_inode *inode)
 {
        int ret;
 
        DBG("Removing inode with unlinked id %u from unlinked file pool",
-                       LTTNG_OPTIONAL_GET(inode->unlinked_id));
+           LTTNG_OPTIONAL_GET(inode->unlinked_id));
 
-       ret = lttng_directory_handle_unlink_file(
-                       inode->location.directory_handle, inode->location.path);
+       ret = lttng_directory_handle_unlink_file(inode->location.directory_handle,
+                                                inode->location.path);
        if (ret) {
                PERROR("Failed to unlink file %s from unlinked file directory",
-                               inode->location.path);
+                      inode->location.path);
                goto end;
        }
        free(inode->location.path);
-       inode->location.path = NULL;
+       inode->location.path = nullptr;
        lttng_directory_handle_put(inode->location.directory_handle);
-       inode->location.directory_handle = NULL;
+       inode->location.directory_handle = nullptr;
 
        pool->file_count--;
        if (pool->file_count == 0) {
@@ -201,10 +197,10 @@ static int lttng_unlinked_file_pool_remove_inode(
                         * error except through logging.
                         */
                        PERROR("Failed to remove unlinked files directory at %s",
-                                       pool->unlink_directory_path);
+                              pool->unlink_directory_path);
                }
                lttng_directory_handle_put(pool->unlink_directory_handle);
-               pool->unlink_directory_handle = NULL;
+               pool->unlink_directory_handle = nullptr;
        }
 end:
        return ret;
@@ -216,28 +212,25 @@ static void lttng_inode_destroy(struct lttng_inode *inode)
                return;
        }
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_del(inode->registry_ht, &inode->registry_node);
-       rcu_read_unlock();
 
        if (inode->unlink_pending) {
                int ret;
 
                LTTNG_ASSERT(inode->location.directory_handle);
                LTTNG_ASSERT(inode->location.path);
-               DBG("Removing %s from unlinked file pool",
-                               inode->location.path);
+               DBG("Removing %s from unlinked file pool", inode->location.path);
                ret = lttng_unlinked_file_pool_remove_inode(inode->unlinked_file_pool, inode);
                if (ret) {
                        PERROR("Failed to unlink %s", inode->location.path);
                }
        }
 
-       lttng_directory_handle_put(
-                       inode->location.directory_handle);
-       inode->location.directory_handle = NULL;
+       lttng_directory_handle_put(inode->location.directory_handle);
+       inode->location.directory_handle = nullptr;
        free(inode->location.path);
-       inode->location.path = NULL;
+       inode->location.path = nullptr;
        call_rcu(&inode->rcu_head, lttng_inode_free);
 }
 
@@ -251,8 +244,7 @@ static void lttng_inode_get(struct lttng_inode *inode)
        urcu_ref_get(&inode->ref);
 }
 
-struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(
-               const char *path)
+struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(const char *path)
 {
        struct lttng_unlinked_file_pool *pool = zmalloc<lttng_unlinked_file_pool>();
 
@@ -262,7 +254,7 @@ struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(
 
        if (!path || *path != '/') {
                ERR("Unlinked file pool must be created with an absolute path, path = \"%s\"",
-                               path ? path : "NULL");
+                   path ? path : "NULL");
                goto error;
        }
 
@@ -275,11 +267,10 @@ struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(
        return pool;
 error:
        lttng_unlinked_file_pool_destroy(pool);
-       return NULL;
+       return nullptr;
 }
 
-void lttng_unlinked_file_pool_destroy(
-               struct lttng_unlinked_file_pool *pool)
+void lttng_unlinked_file_pool_destroy(struct lttng_unlinked_file_pool *pool)
 {
        if (!pool) {
                return;
@@ -296,13 +287,11 @@ void lttng_inode_put(struct lttng_inode *inode)
        urcu_ref_put(&inode->ref, lttng_inode_release);
 }
 
-struct lttng_directory_handle *
-lttng_inode_get_location_directory_handle(
-               struct lttng_inode *inode)
+struct lttng_directory_handle *lttng_inode_get_location_directory_handle(struct lttng_inode *inode)
 {
        if (inode->location.directory_handle) {
-               const bool reference_acquired = lttng_directory_handle_get(
-                               inode->location.directory_handle);
+               const bool reference_acquired =
+                       lttng_directory_handle_get(inode->location.directory_handle);
 
                LTTNG_ASSERT(reference_acquired);
        }
@@ -310,8 +299,8 @@ lttng_inode_get_location_directory_handle(
 }
 
 void lttng_inode_borrow_location(struct lttng_inode *inode,
-               const struct lttng_directory_handle **out_directory_handle,
-               const char **out_path)
+                                const struct lttng_directory_handle **out_directory_handle,
+                                const char **out_path)
 {
        if (out_directory_handle) {
                *out_directory_handle = inode->location.directory_handle;
@@ -321,24 +310,23 @@ void lttng_inode_borrow_location(struct lttng_inode *inode,
        }
 }
 
-int lttng_inode_rename(
-               struct lttng_inode *inode,
-               struct lttng_directory_handle *old_directory_handle,
-               const char *old_path,
-               struct lttng_directory_handle *new_directory_handle,
-               const char *new_path,
-               bool overwrite)
+int lttng_inode_rename(struct lttng_inode *inode,
+                      struct lttng_directory_handle *old_directory_handle,
+                      const char *old_path,
+                      struct lttng_directory_handle *new_directory_handle,
+                      const char *new_path,
+                      bool overwrite)
 {
        int ret = 0;
        char *new_path_copy = strdup(new_path);
        bool reference_acquired;
 
        DBG("Performing rename of inode from %s to %s with %s directory handles",
-                       old_path, new_path,
-                       lttng_directory_handle_equals(old_directory_handle,
-                                       new_directory_handle) ?
-                                       "identical" :
-                                       "different");
+           old_path,
+           new_path,
+           lttng_directory_handle_equals(old_directory_handle, new_directory_handle) ?
+                   "identical" :
+                   "different");
 
        if (!new_path_copy) {
                ret = -ENOMEM;
@@ -347,7 +335,8 @@ int lttng_inode_rename(
 
        if (inode->unlink_pending) {
                WARN("An attempt to rename an unlinked file from %s to %s has been performed",
-                               old_path, new_path);
+                    old_path,
+                    new_path);
                ret = -ENOENT;
                goto end;
        }
@@ -356,11 +345,9 @@ int lttng_inode_rename(
                /* Verify that file doesn't exist. */
                struct stat statbuf;
 
-               ret = lttng_directory_handle_stat(
-                               new_directory_handle, new_path, &statbuf);
+               ret = lttng_directory_handle_stat(new_directory_handle, new_path, &statbuf);
                if (ret == 0) {
-                       ERR("Refusing to rename %s as the destination already exists",
-                                       old_path);
+                       ERR("Refusing to rename %s as the destination already exists", old_path);
                        ret = -EEXIST;
                        goto end;
                } else if (ret < 0 && errno != ENOENT) {
@@ -370,8 +357,8 @@ int lttng_inode_rename(
                }
        }
 
-       ret = lttng_directory_handle_rename(old_directory_handle, old_path,
-                       new_directory_handle, new_path);
+       ret = lttng_directory_handle_rename(
+               old_directory_handle, old_path, new_directory_handle, new_path);
        if (ret) {
                PERROR("Failed to rename file %s to %s", old_path, new_path);
                ret = -errno;
@@ -385,7 +372,7 @@ int lttng_inode_rename(
        inode->location.directory_handle = new_directory_handle;
        /* Ownership transferred. */
        inode->location.path = new_path_copy;
-       new_path_copy = NULL;
+       new_path_copy = nullptr;
 end:
        free(new_path_copy);
        return ret;
@@ -399,7 +386,7 @@ int lttng_inode_unlink(struct lttng_inode *inode)
 
        if (inode->unlink_pending) {
                WARN("An attempt to re-unlink %s has been performed, ignoring.",
-                               inode->location.path);
+                    inode->location.path);
                ret = -ENOENT;
                goto end;
        }
@@ -408,11 +395,10 @@ int lttng_inode_unlink(struct lttng_inode *inode)
         * Move to the temporary "deleted" directory until all
         * references are released.
         */
-       ret = lttng_unlinked_file_pool_add_inode(
-                       inode->unlinked_file_pool, inode);
+       ret = lttng_unlinked_file_pool_add_inode(inode->unlinked_file_pool, inode);
        if (ret) {
                PERROR("Failed to add inode \"%s\" to the unlinked file pool",
-                               inode->location.path);
+                      inode->location.path);
                goto end;
        }
        inode->unlink_pending = true;
@@ -421,12 +407,12 @@ end:
 }
 
 static struct lttng_inode *lttng_inode_create(const struct inode_id *id,
-               struct cds_lfht *ht,
-               struct lttng_unlinked_file_pool *unlinked_file_pool,
-               struct lttng_directory_handle *directory_handle,
-               const char *path)
+                                             struct cds_lfht *ht,
+                                             struct lttng_unlinked_file_pool *unlinked_file_pool,
+                                             struct lttng_directory_handle *directory_handle,
+                                             const char *path)
 {
-       struct lttng_inode *inode = NULL;
+       struct lttng_inode *inode = nullptr;
        char *path_copy;
        bool reference_acquired;
 
@@ -450,14 +436,14 @@ static struct lttng_inode *lttng_inode_create(const struct inode_id *id,
        inode->unlinked_file_pool = unlinked_file_pool;
        /* Ownership of path copy is transferred to inode. */
        inode->location.path = path_copy;
-       path_copy = NULL;
+       path_copy = nullptr;
        inode->location.directory_handle = directory_handle;
 end:
        free(path_copy);
        return inode;
 }
 
-struct lttng_inode_registry *lttng_inode_registry_create(void)
+struct lttng_inode_registry *lttng_inode_registry_create()
 {
        struct lttng_inode_registry *registry = zmalloc<lttng_inode_registry>();
 
@@ -467,13 +453,13 @@ struct lttng_inode_registry *lttng_inode_registry_create(void)
 
        pthread_mutex_lock(&seed.lock);
        if (!seed.initialized) {
-               seed.value = (unsigned long) time(NULL);
+               seed.value = (unsigned long) time(nullptr);
                seed.initialized = true;
        }
        pthread_mutex_unlock(&seed.lock);
 
-       registry->inodes = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       registry->inodes = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!registry->inodes) {
                goto error;
        }
@@ -481,36 +467,36 @@ end:
        return registry;
 error:
        lttng_inode_registry_destroy(registry);
-       return NULL;
+       return nullptr;
 }
 
-void lttng_inode_registry_destroy(
-               struct lttng_inode_registry *registry)
+void lttng_inode_registry_destroy(struct lttng_inode_registry *registry)
 {
        if (!registry) {
                return;
        }
        if (registry->inodes) {
-               int ret = cds_lfht_destroy(registry->inodes, NULL);
+               int ret = cds_lfht_destroy(registry->inodes, nullptr);
 
                LTTNG_ASSERT(!ret);
        }
        free(registry);
 }
 
-struct lttng_inode *lttng_inode_registry_get_inode(
-               struct lttng_inode_registry *registry,
-               struct lttng_directory_handle *handle,
-               const char *path,
-               int fd,
-               struct lttng_unlinked_file_pool *unlinked_file_pool)
+struct lttng_inode *
+lttng_inode_registry_get_inode(struct lttng_inode_registry *registry,
+                              struct lttng_directory_handle *handle,
+                              const char *path,
+                              int fd,
+                              struct lttng_unlinked_file_pool *unlinked_file_pool)
 {
        int ret;
        struct stat statbuf;
        struct inode_id id;
        struct cds_lfht_iter iter;
        struct cds_lfht_node *node;
-       struct lttng_inode *inode = NULL;
+       struct lttng_inode *inode = nullptr;
+       lttng::urcu::read_lock_guard read_lock;
 
        ret = fstat(fd, &statbuf);
        if (ret < 0) {
@@ -521,29 +507,25 @@ struct lttng_inode *lttng_inode_registry_get_inode(
        id.device = statbuf.st_dev;
        id.inode = statbuf.st_ino;
 
-       rcu_read_lock();
-       cds_lfht_lookup(registry->inodes, lttng_inode_id_hash(&id),
-                       lttng_inode_match, &id, &iter);
+       cds_lfht_lookup(registry->inodes, lttng_inode_id_hash(&id), lttng_inode_match, &id, &iter);
        node = cds_lfht_iter_get_node(&iter);
        if (node) {
-               inode = lttng::utils::container_of(
-                               node, &lttng_inode::registry_node);
+               inode = lttng::utils::container_of(node, &lttng_inode::registry_node);
                lttng_inode_get(inode);
-               goto end_unlock;
+               goto end;
        }
 
-       inode = lttng_inode_create(&id, registry->inodes, unlinked_file_pool,
-                       handle, path);
+       inode = lttng_inode_create(&id, registry->inodes, unlinked_file_pool, handle, path);
        if (!inode) {
-               goto end_unlock;
+               goto end;
        }
 
        node = cds_lfht_add_unique(registry->inodes,
-                       lttng_inode_id_hash(&inode->id), lttng_inode_match,
-                       &inode->id, &inode->registry_node);
+                                  lttng_inode_id_hash(&inode->id),
+                                  lttng_inode_match,
+                                  &inode->id,
+                                  &inode->registry_node);
        LTTNG_ASSERT(node == &inode->registry_node);
-end_unlock:
-       rcu_read_unlock();
 end:
        return inode;
 }
index d4cb28239cfc45641d0d6a431e4eab2319254bef..4206117d8890d4d4e17efff310deb316c59b94a6 100644 (file)
@@ -9,6 +9,7 @@
 #define FD_TRACKER_INODE_H
 
 #include <common/compat/directory-handle.hpp>
+
 #include <stdbool.h>
 
 struct lttng_inode;
@@ -24,38 +25,34 @@ struct lttng_directory_handle;
  * by the fd-tracker. Users of the fd-tracker should account for this extra
  * file descriptor.
  */
-struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(
-               const char *path);
+struct lttng_unlinked_file_pool *lttng_unlinked_file_pool_create(const char *path);
 
-void lttng_unlinked_file_pool_destroy(
-               struct lttng_unlinked_file_pool *pool);
+void lttng_unlinked_file_pool_destroy(struct lttng_unlinked_file_pool *pool);
 
 /* The inode registry is protected by the fd-tracker's lock. */
-struct lttng_inode_registry *lttng_inode_registry_create(void);
+struct lttng_inode_registry *lttng_inode_registry_create();
 
-struct lttng_inode *lttng_inode_registry_get_inode(
-               struct lttng_inode_registry *registry,
-               struct lttng_directory_handle *handle,
-               const char *path,
-               int fd,
-               struct lttng_unlinked_file_pool *pool);
+struct lttng_inode *lttng_inode_registry_get_inode(struct lttng_inode_registry *registry,
+                                                  struct lttng_directory_handle *handle,
+                                                  const char *path,
+                                                  int fd,
+                                                  struct lttng_unlinked_file_pool *pool);
 
 void lttng_inode_registry_destroy(struct lttng_inode_registry *registry);
 
 void lttng_inode_borrow_location(struct lttng_inode *inode,
-               const struct lttng_directory_handle **out_directory_handle,
-               const char **out_path);
+                                const struct lttng_directory_handle **out_directory_handle,
+                                const char **out_path);
 
 /* Returns a new reference to the inode's location directory handle. */
-struct lttng_directory_handle *lttng_inode_get_location_directory_handle(
-               struct lttng_inode *inode);
+struct lttng_directory_handle *lttng_inode_get_location_directory_handle(struct lttng_inode *inode);
 
 int lttng_inode_rename(struct lttng_inode *inode,
-               struct lttng_directory_handle *old_directory_handle,
-               const char *old_path,
-               struct lttng_directory_handle *new_directory_handle,
-               const char *new_path,
-               bool overwrite);
+                      struct lttng_directory_handle *old_directory_handle,
+                      const char *old_path,
+                      struct lttng_directory_handle *new_directory_handle,
+                      const char *new_path,
+                      bool overwrite);
 
 int lttng_inode_unlink(struct lttng_inode *inode);
 
index 8c252851ee667df1319633ded704b1e9ea8169e3..20e4ae872201d9ad538c70c3afb7c9fa9ec34b07 100644 (file)
@@ -5,8 +5,6 @@
  *
  */
 
-#include <common/compat/poll.hpp>
-
 #include "utils.hpp"
 
 #ifdef HAVE_EPOLL
@@ -46,10 +44,10 @@ static int close_epoll(void *data, int *in_fd __attribute__((unused)))
  * must be tracked.
  */
 int fd_tracker_util_poll_create(struct fd_tracker *tracker,
-               const char *name,
-               struct lttng_poll_event *events,
-               int size,
-               int flags)
+                               const char *name,
+                               struct lttng_poll_event *events,
+                               int size,
+                               int flags)
 {
        int out_fd;
        struct create_args create_args = {
@@ -59,14 +57,12 @@ int fd_tracker_util_poll_create(struct fd_tracker *tracker,
        };
 
        return fd_tracker_open_unsuspendable_fd(
-                       tracker, &out_fd, &name, 1, open_epoll, &create_args);
+               tracker, &out_fd, &name, 1, open_epoll, &create_args);
 }
 
-int fd_tracker_util_poll_clean(
-               struct fd_tracker *tracker, struct lttng_poll_event *events)
+int fd_tracker_util_poll_clean(struct fd_tracker *tracker, struct lttng_poll_event *events)
 {
-       return fd_tracker_close_unsuspendable_fd(
-                       tracker, &events->epfd, 1, close_epoll, events);
+       return fd_tracker_close_unsuspendable_fd(tracker, &events->epfd, 1, close_epoll, events);
 }
 
 #else /* HAVE_EPOLL */
@@ -75,19 +71,17 @@ int fd_tracker_util_poll_clean(
  * The epoll variant of the poll compat layer creates an unsuspendable fd which
  * must be tracked.
  */
-int fd_tracker_util_poll_create(
-               struct fd_tracker *tracker __attribute__((unused)),
-               const char *name __attribute__((unused)),
-               struct lttng_poll_event *events,
-               int size,
-               int flags __attribute__((unused)))
+int fd_tracker_util_poll_create(struct fd_tracker *tracker __attribute__((unused)),
+                               const char *name __attribute__((unused)),
+                               struct lttng_poll_event *events,
+                               int size,
+                               int flags __attribute__((unused)))
 {
        return lttng_poll_create(events, size, flags);
 }
 
-int fd_tracker_util_poll_clean(
-               struct fd_tracker *tracker __attribute__((unused)),
-               struct lttng_poll_event *events)
+int fd_tracker_util_poll_clean(struct fd_tracker *tracker __attribute__((unused)),
+                              struct lttng_poll_event *events)
 {
        lttng_poll_clean(events);
        return 0;
index d4a7329282651b714b0937f3889b42ab9de82e40..408c5afc65756fcb92172c16db0b810dcc514cf7 100644 (file)
@@ -8,19 +8,19 @@
 #include <common/error.hpp>
 #include <common/fd-tracker/utils.hpp>
 #include <common/utils.hpp>
+
 #include <lttng/constant.h>
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 
-static
-int open_pipe_cloexec(void *data __attribute__((unused)), int *fds)
+static int open_pipe_cloexec(void *data __attribute__((unused)), int *fds)
 {
        return utils_create_pipe_cloexec(fds);
 }
 
-static
-int close_pipe(void *data __attribute__((unused)), int *pipe)
+static int close_pipe(void *data __attribute__((unused)), int *pipe)
 {
        utils_close_pipe(pipe);
        pipe[0] = pipe[1] = -1;
@@ -32,8 +32,7 @@ int fd_tracker_util_close_fd(void *unused __attribute__((unused)), int *fd)
        return close(*fd);
 }
 
-int fd_tracker_util_pipe_open_cloexec(
-               struct fd_tracker *tracker, const char *name, int *pipe)
+int fd_tracker_util_pipe_open_cloexec(struct fd_tracker *tracker, const char *name, int *pipe)
 {
        int ret;
        const char *name_prefix;
@@ -49,8 +48,8 @@ int fd_tracker_util_pipe_open_cloexec(
                goto end;
        }
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, pipe,
-                       (const char **) names, 2, open_pipe_cloexec, NULL);
+       ret = fd_tracker_open_unsuspendable_fd(
+               tracker, pipe, (const char **) names, 2, open_pipe_cloexec, nullptr);
        free(names[0]);
        free(names[1]);
 end:
@@ -59,8 +58,7 @@ end:
 
 int fd_tracker_util_pipe_close(struct fd_tracker *tracker, int *pipe)
 {
-       return fd_tracker_close_unsuspendable_fd(
-                       tracker, pipe, 2, close_pipe, NULL);
+       return fd_tracker_close_unsuspendable_fd(tracker, pipe, 2, close_pipe, nullptr);
 }
 
 namespace {
@@ -71,17 +69,15 @@ struct open_directory_handle_args {
 };
 } /* namespace */
 
-static
-int open_directory_handle(void *_args, int *out_fds)
+static int open_directory_handle(void *_args, int *out_fds)
 {
        int ret = 0;
        struct open_directory_handle_args *args = (open_directory_handle_args *) _args;
-       struct lttng_directory_handle *new_handle = NULL;
+       struct lttng_directory_handle *new_handle = nullptr;
 
        new_handle = args->in_handle ?
-                       lttng_directory_handle_create_from_handle(
-                               args->path, args->in_handle) :
-                       lttng_directory_handle_create(args->path);
+               lttng_directory_handle_create_from_handle(args->path, args->in_handle) :
+               lttng_directory_handle_create(args->path);
        if (!new_handle) {
                ret = -errno;
                goto end;
@@ -105,15 +101,13 @@ int open_directory_handle(void *_args, int *out_fds)
 #else
                abort();
 #endif
-
        }
 end:
        return ret;
 }
 
 #ifdef HAVE_DIRFD
-static
-int fd_close(void *unused __attribute__((unused)), int *in_fds)
+static int fd_close(void *unused __attribute__((unused)), int *in_fds)
 {
        const int ret = close(in_fds[0]);
 
@@ -121,13 +115,11 @@ int fd_close(void *unused __attribute__((unused)), int *in_fds)
        return ret;
 }
 
-static
-void directory_handle_destroy(
-               struct lttng_directory_handle *handle, void *data)
+static void directory_handle_destroy(struct lttng_directory_handle *handle, void *data)
 {
        struct fd_tracker *tracker = (fd_tracker *) data;
-       const int ret = fd_tracker_close_unsuspendable_fd(
-                       tracker, &handle->dirfd, 1, fd_close, NULL);
+       const int ret =
+               fd_tracker_close_unsuspendable_fd(tracker, &handle->dirfd, 1, fd_close, nullptr);
 
        if (ret) {
                ERR("Failed to untrack directory handle file descriptor");
@@ -135,24 +127,21 @@ void directory_handle_destroy(
 }
 #endif
 
-struct lttng_directory_handle *fd_tracker_create_directory_handle(
-               struct fd_tracker *tracker, const char *path)
+struct lttng_directory_handle *fd_tracker_create_directory_handle(struct fd_tracker *tracker,
+                                                                 const char *path)
 {
-       return fd_tracker_create_directory_handle_from_handle(
-                       tracker, NULL, path);
+       return fd_tracker_create_directory_handle_from_handle(tracker, nullptr, path);
 }
 
 struct lttng_directory_handle *fd_tracker_create_directory_handle_from_handle(
-               struct fd_tracker *tracker,
-               struct lttng_directory_handle *in_handle,
-               const char *path)
+       struct fd_tracker *tracker, struct lttng_directory_handle *in_handle, const char *path)
 {
        int ret;
        int dirfd = -1;
-       char *handle_name = NULL;
+       char *handle_name = nullptr;
        char cwd_path[LTTNG_PATH_MAX] = "working directory";
-       struct lttng_directory_handle *new_handle = NULL;
-       open_directory_handle_args open_args {};
+       struct lttng_directory_handle *new_handle = nullptr;
+       open_directory_handle_args open_args{};
 
        open_args.in_handle = in_handle;
        open_args.path = path;
@@ -164,18 +153,17 @@ struct lttng_directory_handle *fd_tracker_create_directory_handle_from_handle(
                }
        }
 
-       ret = asprintf(&handle_name, "Directory handle to %s",
-                       path ? path : cwd_path);
+       ret = asprintf(&handle_name, "Directory handle to %s", path ? path : cwd_path);
        if (ret < 0) {
                PERROR("Failed to format directory handle name");
                goto end;
        }
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &dirfd,
-                       (const char **) &handle_name, 1, open_directory_handle,
-                       &open_args);
+       ret = fd_tracker_open_unsuspendable_fd(
+               tracker, &dirfd, (const char **) &handle_name, 1, open_directory_handle, &open_args);
        if (ret && ret != ENOTSUP) {
-               ERR("Failed to open directory handle to %s through the fd tracker", path ? path : cwd_path);
+               ERR("Failed to open directory handle to %s through the fd tracker",
+                   path ? path : cwd_path);
        }
        new_handle = open_args.ret_handle;
 
index 064e09c0e480504ef5d7b29a5357458cdafa67b1..0dfdb29f951830591610e2e3518009361971ba80 100644 (file)
@@ -9,11 +9,10 @@
 #define FD_TRACKER_UTILS_H
 
 #include <common/compat/directory-handle.hpp>
+#include <common/compat/poll.hpp>
 #include <common/fd-tracker/fd-tracker.hpp>
 #include <common/macros.hpp>
 
-struct lttng_poll_event;
-
 /*
  * Utility implementing a close_fd callback which receives one file descriptor
  * and closes it, returning close()'s return value.
@@ -23,27 +22,23 @@ int fd_tracker_util_close_fd(void *, int *fd);
 /*
  * Create a pipe and track its underlying fds.
  */
-int fd_tracker_util_pipe_open_cloexec(
-               struct fd_tracker *tracker, const char *name, int *pipe);
+int fd_tracker_util_pipe_open_cloexec(struct fd_tracker *tracker, const char *name, int *pipe);
 int fd_tracker_util_pipe_close(struct fd_tracker *tracker, int *pipe);
 
 /*
  * Create a poll event and track its underlying fd, if applicable.
  */
 int fd_tracker_util_poll_create(struct fd_tracker *tracker,
-               const char *name,
-               struct lttng_poll_event *events,
-               int size,
-               int flags);
-int fd_tracker_util_poll_clean(
-               struct fd_tracker *tracker, struct lttng_poll_event *events);
+                               const char *name,
+                               struct lttng_poll_event *events,
+                               int size,
+                               int flags);
+int fd_tracker_util_poll_clean(struct fd_tracker *tracker, struct lttng_poll_event *events);
 
-struct lttng_directory_handle *fd_tracker_create_directory_handle(
-               struct fd_tracker *tracker, const char *path);
+struct lttng_directory_handle *fd_tracker_create_directory_handle(struct fd_tracker *tracker,
+                                                                 const char *path);
 
 struct lttng_directory_handle *fd_tracker_create_directory_handle_from_handle(
-               struct fd_tracker *tracker,
-               struct lttng_directory_handle *handle,
-               const char *path);
+       struct fd_tracker *tracker, struct lttng_directory_handle *handle, const char *path);
 
 #endif /* FD_TRACKER_UTILS_H */
diff --git a/src/common/file-descriptor.cpp b/src/common/file-descriptor.cpp
new file mode 100644 (file)
index 0000000..93d7b69
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "file-descriptor.hpp"
+
+#include <common/error.hpp>
+#include <common/exception.hpp>
+#include <common/format.hpp>
+#include <common/readwrite.hpp>
+
+#include <algorithm>
+#include <limits>
+#include <unistd.h>
+
+namespace {
+bool is_valid_fd(int fd)
+{
+       return fd >= 0;
+}
+} // anonymous namespace
+
+lttng::file_descriptor::file_descriptor(int raw_fd) noexcept : _raw_fd{ raw_fd }
+{
+       LTTNG_ASSERT(is_valid_fd(_raw_fd));
+}
+
+lttng::file_descriptor::file_descriptor(lttng::file_descriptor&& other) noexcept
+{
+       std::swap(_raw_fd, other._raw_fd);
+}
+
+lttng::file_descriptor& lttng::file_descriptor::operator=(lttng::file_descriptor&& other) noexcept
+{
+       _cleanup();
+       std::swap(_raw_fd, other._raw_fd);
+       return *this;
+}
+
+lttng::file_descriptor::~file_descriptor() noexcept
+{
+       _cleanup();
+}
+
+int lttng::file_descriptor::fd() const noexcept
+{
+       LTTNG_ASSERT(is_valid_fd(_raw_fd));
+       return _raw_fd;
+}
+
+void lttng::file_descriptor::_cleanup() noexcept
+{
+       if (!is_valid_fd(_raw_fd)) {
+               return;
+       }
+
+       const auto ret = ::close(_raw_fd);
+
+       _raw_fd = -1;
+       if (ret) {
+               PERROR("Failed to close file descriptor: fd=%i", _raw_fd);
+       }
+}
+
+void lttng::file_descriptor::write(const void *buffer, std::size_t size)
+{
+       /*
+        * This is a limitation of the internal helper that is not a problem in practice for the
+        * moment.
+        */
+       using lttng_write_return_type = decltype(lttng_write(
+               std::declval<int>(), std::declval<const void *>(), std::declval<size_t>()));
+       constexpr auto max_supported_write_size =
+               std::numeric_limits<lttng_write_return_type>::max();
+
+       if (size > max_supported_write_size) {
+               LTTNG_THROW_UNSUPPORTED_ERROR(lttng::format(
+                       "Write size exceeds the maximal supported value of lttng_write: write_size={}, maximal_write_size={}",
+                       size,
+                       max_supported_write_size));
+       }
+
+       const auto write_ret = lttng_write(fd(), buffer, size);
+       if (write_ret < 0 || static_cast<std::size_t>(write_ret) != size) {
+               LTTNG_THROW_POSIX(lttng::format("Failed to write to file descriptor: fd={}", fd()),
+                                 errno);
+       }
+}
+
+void lttng::file_descriptor::read(void *buffer, std::size_t size)
+{
+       /*
+        * This is a limitation of the internal helper that is not a problem in practice for the
+        * moment.
+        */
+       using lttng_read_return_type = decltype(lttng_read(
+               std::declval<int>(), std::declval<void *>(), std::declval<size_t>()));
+       constexpr auto max_supported_read_size = std::numeric_limits<lttng_read_return_type>::max();
+
+       if (size > max_supported_read_size) {
+               LTTNG_THROW_UNSUPPORTED_ERROR(lttng::format(
+                       "Read size exceeds the maximal supported value of lttng_read: read_size={}, maximal_read_size={}",
+                       size,
+                       max_supported_read_size));
+       }
+
+       const auto read_ret = lttng_read(fd(), buffer, size);
+       if (read_ret < 0 || static_cast<std::size_t>(read_ret) != size) {
+               LTTNG_THROW_POSIX(lttng::format("Failed to read from file descriptor: fd={}", fd()),
+                                 errno);
+       }
+}
diff --git a/src/common/file-descriptor.hpp b/src/common/file-descriptor.hpp
new file mode 100644 (file)
index 0000000..b467e2e
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_FILE_DESCRIPTOR_HPP
+#define LTTNG_FILE_DESCRIPTOR_HPP
+
+#include <cstddef>
+
+namespace lttng {
+
+/* RAII wrapper around a UNIX file descriptor. */
+class file_descriptor {
+public:
+       file_descriptor() noexcept = default;
+
+       explicit file_descriptor(int raw_fd) noexcept;
+       file_descriptor(const file_descriptor&) = delete;
+       file_descriptor& operator=(const file_descriptor&) = delete;
+
+       file_descriptor(file_descriptor&& other) noexcept;
+
+       file_descriptor& operator=(file_descriptor&& other) noexcept;
+
+       ~file_descriptor() noexcept;
+
+       /*
+        * Read `size` bytes from the underlying file descriptor, assuming
+        * raw_fd behaves as a blocking device.
+        *
+        * Throws an exception if the requested amount of bytes couldn't be read.
+        */
+       void read(void *buffer, std::size_t size);
+       /*
+        * Write `size` bytes to the underlying file descriptor, assuming
+        * raw_fd behaves as a blocking device.
+        *
+        * Throws an exception if the requested amount of bytes couldn't be written.
+        */
+       void write(const void *buffer, std::size_t size);
+
+       int fd() const noexcept;
+
+protected:
+       void _cleanup() noexcept;
+
+private:
+       int _raw_fd = -1;
+};
+
+} /* namespace lttng */
+
+#endif /* LTTNG_FILE_DESCRIPTOR_HPP */
index 5b8082fd48da905e3f95280201dfa682668e444e..e45bfa0eb76dd8926a713efebfea3ada0a0d711b 100644 (file)
@@ -9,17 +9,17 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
-
-#include <common/compat/errno.hpp>
 #include <common/bytecode/bytecode.hpp>
+#include <common/compat/errno.hpp>
 #include <common/filter/filter-ast.hpp>
 #include <common/filter/filter-parser.hpp>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
@@ -29,8 +29,7 @@ int main(int argc, char **argv)
 {
        struct filter_parser_ctx *ctx;
        int ret;
-       int print_xml = 0, generate_ir = 0, generate_bytecode = 0,
-               print_bytecode = 0;
+       int print_xml = 0, generate_ir = 0, generate_bytecode = 0, print_bytecode = 0;
        int argidx;
 
        for (argidx = 1; argidx < argc; argidx++) {
@@ -108,7 +107,7 @@ int main(int argc, char **argv)
                }
                printf("done\n");
                printf("Size of bytecode generated: %u bytes.\n",
-                       bytecode_get_len(&ctx->bytecode->b));
+                      bytecode_get_len(&ctx->bytecode->b));
        }
 
        if (print_bytecode) {
@@ -118,14 +117,12 @@ int main(int argc, char **argv)
                bytecode_len = ctx->bytecode->b.reloc_table_offset;
                printf("Bytecode:\n");
                for (i = 0; i < bytecode_len; i++) {
-                       printf("0x%X ",
-                               ((uint8_t *) ctx->bytecode->b.data)[i]);
+                       printf("0x%X ", ((uint8_t *) ctx->bytecode->b.data)[i]);
                }
                printf("\n");
                printf("Reloc table:\n");
                for (i = bytecode_len; i < len;) {
-                       printf("{ 0x%X, ",
-                               *(uint16_t *) &ctx->bytecode->b.data[i]);
+                       printf("{ 0x%X, ", *(uint16_t *) &ctx->bytecode->b.data[i]);
                        i += sizeof(uint16_t);
                        printf("%s } ", &((char *) ctx->bytecode->b.data)[i]);
                        i += strlen(&((char *) ctx->bytecode->b.data)[i]) + 1;
index f0b248e88155e51e54773163532a90da3e949cca..39e403dfbafd7132fdee9914a269ea5e35d55593 100644 (file)
@@ -6,6 +6,7 @@
  */
 
 #include "filter.hpp"
+
 #include <stddef.h>
 
 struct bytecode_symbol_iterator {
@@ -14,10 +15,9 @@ struct bytecode_symbol_iterator {
        size_t offset, len;
 };
 
-struct bytecode_symbol_iterator *bytecode_symbol_iterator_create(
-               struct lttng_bytecode *bytecode)
+struct bytecode_symbol_iterator *bytecode_symbol_iterator_create(struct lttng_bytecode *bytecode)
 {
-       struct bytecode_symbol_iterator *it = NULL;
+       struct bytecode_symbol_iterator *it = nullptr;
 
        if (!bytecode) {
                goto end;
@@ -64,12 +64,11 @@ int bytecode_symbol_iterator_get_type(struct bytecode_symbol_iterator *it)
        ret = *((uint16_t *) (it->bytecode + it->offset));
 end:
        return ret;
- }
+}
 
-const char *bytecode_symbol_iterator_get_name(
-               struct bytecode_symbol_iterator *it)
+const char *bytecode_symbol_iterator_get_name(struct bytecode_symbol_iterator *it)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!it) {
                goto end;
index 085d6d03442ea36e42e425f5dcf1c7b0e493551a..ae061fd9390ec7f59001c79a3c4ca07bb1e2430b 100644 (file)
@@ -16,8 +16,7 @@ struct bytecode_symbol_iterator;
  * Create an iterator on a bytecode's symbols. The iterator points to the
  * first element after creation.
  */
-struct bytecode_symbol_iterator *bytecode_symbol_iterator_create(
-               struct lttng_bytecode *bytecode);
+struct bytecode_symbol_iterator *bytecode_symbol_iterator_create(struct lttng_bytecode *bytecode);
 
 /*
  * Advance iterator of one element.
@@ -28,8 +27,7 @@ int bytecode_symbol_iterator_next(struct bytecode_symbol_iterator *it);
 
 int bytecode_symbol_iterator_get_type(struct bytecode_symbol_iterator *it);
 
-const char *bytecode_symbol_iterator_get_name(
-               struct bytecode_symbol_iterator *it);
+const char *bytecode_symbol_iterator_get_name(struct bytecode_symbol_iterator *it);
 
 void bytecode_symbol_iterator_destroy(struct bytecode_symbol_iterator *it);
 
diff --git a/src/common/filter/.clang-tidy b/src/common/filter/.clang-tidy
new file mode 100644 (file)
index 0000000..b298fbc
--- /dev/null
@@ -0,0 +1,8 @@
+# clang-tidy uses the closest .clang-tidy in a parent directory
+# to override settings.
+#
+# Add a dummy check since we can't disable them all without
+# clang-tidy complaining. This ensures that generated code
+# is not flagged.
+
+Checks: '-*,llvm-twine-local'
diff --git a/src/common/filter/.clang-tidy.ignore b/src/common/filter/.clang-tidy.ignore
new file mode 100644 (file)
index 0000000..4e4c75e
--- /dev/null
@@ -0,0 +1,3 @@
+# Ensures that generated code is not flagged.
+
+filter-parser.hpp
index 2b460b401ef669d87a3ab9da67e973a564914e59..51a36326bdbabd88ebd48b91ea435f6913797136 100644 (file)
  * Note: filter-ast.h should be included before filter-parser.h.
  */
 
-#include <urcu/list.h>
-#include <stdio.h>
 #include <stdint.h>
+#include <stdio.h>
+#include <urcu/list.h>
 
-#define printf_debug(fmt, args...)                                     \
-       do {                                                            \
-               if (filter_parser_debug)                                \
-                       fprintf(stdout, "[debug] " fmt, ## args);       \
+#define printf_debug(fmt, args...)                               \
+       do {                                                     \
+               if (filter_parser_debug)                         \
+                       fprintf(stdout, "[debug] " fmt, ##args); \
        } while (0)
 
 // the parameter name (of the reentrant 'yyparse' function)
@@ -32,7 +32,7 @@
 
 #ifndef YY_TYPEDEF_YY_SCANNER_T
 #define YY_TYPEDEF_YY_SCANNER_T
-typedef void* yyscan_t;
+using yyscan_t = void *;
 #endif
 
 extern int filter_parser_debug;
@@ -117,8 +117,8 @@ struct filter_node {
                } root;
                struct {
                        enum ast_expt_type type;
-                       enum ast_link_type post_op;     /* reverse */
-                       enum ast_link_type pre_op;      /* forward */
+                       enum ast_link_type post_op; /* reverse */
+                       enum ast_link_type pre_op; /* forward */
                        union {
                                const char *string;
                                uint64_t constant;
@@ -169,17 +169,15 @@ struct filter_parser_ctx {
 struct filter_parser_ctx *filter_parser_ctx_alloc(FILE *input);
 void filter_parser_ctx_free(struct filter_parser_ctx *parser_ctx);
 int filter_parser_ctx_append_ast(struct filter_parser_ctx *parser_ctx);
-int filter_parser_ctx_create_from_filter_expression(
-               const char *filter_expression, struct filter_parser_ctx **ctxp);
+int filter_parser_ctx_create_from_filter_expression(const char *filter_expression,
+                                                   struct filter_parser_ctx **ctxp);
 
-static inline
-struct filter_ast *filter_parser_get_ast(struct filter_parser_ctx *parser_ctx)
+static inline struct filter_ast *filter_parser_get_ast(struct filter_parser_ctx *parser_ctx)
 {
        return parser_ctx->ast;
 }
 
-int filter_visitor_print_xml(struct filter_parser_ctx *ctx, FILE *stream,
-                       int indent);
+int filter_visitor_print_xml(struct filter_parser_ctx *ctx, FILE *stream, int indent);
 int filter_visitor_ir_generate(struct filter_parser_ctx *ctx);
 void filter_ir_free(struct filter_parser_ctx *ctx);
 int filter_visitor_bytecode_generate(struct filter_parser_ctx *ctx);
index 068d3aa5c4e5920437ed5c5b61149b046b7efbd7..715f78eaa8b8ab8be975687da506cd8999a2262a 100644 (file)
 
 #include "filter-ast.hpp"
 
+#include <cstdlib>
+
 enum ir_op_signedness {
        IR_SIGN_UNKNOWN = 0,
        IR_SIGNED,
        IR_UNSIGNED,
-       IR_SIGN_DYN,            /* signedness determined dynamically */
+       IR_SIGN_DYN, /* signedness determined dynamically */
 };
 
 enum ir_data_type {
        IR_DATA_UNKNOWN = 0,
        IR_DATA_STRING,
-       IR_DATA_NUMERIC,        /* numeric and boolean */
+       IR_DATA_NUMERIC, /* numeric and boolean */
        IR_DATA_FLOAT,
        IR_DATA_FIELD_REF,
        IR_DATA_GET_CONTEXT_REF,
        IR_DATA_EXPRESSION,
 };
 
-static inline
-const char *ir_data_type_str(enum ir_data_type type)
+static inline const char *ir_data_type_str(enum ir_data_type type)
 {
        switch (type) {
        case IR_DATA_UNKNOWN:
@@ -63,8 +64,7 @@ enum ir_op_type {
        IR_OP_LOGICAL,
 };
 
-static inline
-const char *ir_op_type_str(enum ir_op_type type)
+static inline const char *ir_op_type_str(enum ir_op_type type)
 {
        switch (type) {
        case IR_OP_UNKNOWN:
@@ -115,8 +115,7 @@ enum ir_load_expression_type {
        IR_LOAD_EXPRESSION_LOAD_FIELD,
 };
 
-static inline
-const char *ir_load_expression_type_str(enum ir_load_expression_type type)
+static inline const char *ir_load_expression_type_str(enum ir_load_expression_type type)
 {
        switch (type) {
        case IR_LOAD_EXPRESSION_GET_CONTEXT_ROOT:
index 0f11c234d6197f30ab3b9cea48ea749bf6697fbe..e3fae6394fcaa0cb6a76eaec0191829714d14045 100644 (file)
@@ -22,6 +22,7 @@
 #include "memstream.hpp"
 
 #include <common/compat/errno.hpp>
+#include <common/compiler.hpp>
 #include <common/macros.hpp>
 
 #define WIDTH_u64_SCANF_IS_A_BROKEN_API        "20"
 #define WIDTH_x64_SCANF_IS_A_BROKEN_API        "17"
 #define WIDTH_lg_SCANF_IS_A_BROKEN_API "4096"  /* Hugely optimistic approximation */
 
+/*
+ * bison 3.8.2 produces a parser with unused, but set, which results in warnings
+ * at build time.
+ */
+#ifdef __clang__
+#pragma clang diagnostic ignored "-Wunused-but-set-variable"
+#endif /* __clang__ */
+
 #ifdef DEBUG
 static const int print_xml = 1;
 #define dbg_printf(fmt, args...)       \
@@ -54,7 +63,7 @@ void yyrestart(FILE * in_str, yyscan_t parser_ctx);
 struct gc_string {
        struct cds_list_head gc;
        size_t alloclen;
-       char s[];
+       char s[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 };
 
 static
index 27aaada54cba315f49aedd12226e220fecc3d21e..acae7aafb66c1c28d56cd85d0a1d58002b504ff9 100644 (file)
  *
  */
 
-#define yy_create_buffer lttng_filter_yy_create_buffer
-#define yy_delete_buffer lttng_filter_yy_delete_buffer
-#define yy_flush_buffer lttng_filter_yy_flush_buffer
-#define yy_scan_buffer lttng_filter_yy_scan_buffer
-#define yy_scan_bytes lttng_filter_yy_scan_bytes
-#define yy_scan_string lttng_filter_yy_scan_string
+#define yy_create_buffer    lttng_filter_yy_create_buffer
+#define yy_delete_buffer    lttng_filter_yy_delete_buffer
+#define yy_flush_buffer            lttng_filter_yy_flush_buffer
+#define yy_scan_buffer     lttng_filter_yy_scan_buffer
+#define yy_scan_bytes      lttng_filter_yy_scan_bytes
+#define yy_scan_string     lttng_filter_yy_scan_string
 #define yy_switch_to_buffer lttng_filter_yy_switch_to_buffer
-#define yyalloc lttng_filter_yyalloc
-#define yyfree lttng_filter_yyfree
-#define yyget_column lttng_filter_yyget_column
-#define yyget_debug lttng_filter_yyget_debug
-#define yyget_extra lttng_filter_yyget_extra
-#define yyget_in lttng_filter_yyget_in
-#define yyget_leng lttng_filter_yyget_leng
-#define yyget_lineno lttng_filter_yyget_lineno
-#define yyget_lval lttng_filter_yyget_lval
-#define yyget_out lttng_filter_yyget_out
-#define yyget_text lttng_filter_yyget_text
-#define yylex_init lttng_filter_yylex_init
-#define yypop_buffer_state lttng_filter_yypop_buffer_state
+#define yyalloc                    lttng_filter_yyalloc
+#define yyfree             lttng_filter_yyfree
+#define yyget_column       lttng_filter_yyget_column
+#define yyget_debug        lttng_filter_yyget_debug
+#define yyget_extra        lttng_filter_yyget_extra
+#define yyget_in           lttng_filter_yyget_in
+#define yyget_leng         lttng_filter_yyget_leng
+#define yyget_lineno       lttng_filter_yyget_lineno
+#define yyget_lval         lttng_filter_yyget_lval
+#define yyget_out          lttng_filter_yyget_out
+#define yyget_text         lttng_filter_yyget_text
+#define yylex_init         lttng_filter_yylex_init
+#define yypop_buffer_state  lttng_filter_yypop_buffer_state
 #define yypush_buffer_state lttng_filter_yypush_buffer_state
-#define yyrealloc lttng_filter_yyrealloc
-#define yyset_column lttng_filter_yyset_column
-#define yyset_debug lttng_filter_yyset_debug
-#define yyset_extra lttng_filter_yyset_extra
-#define yyset_in lttng_filter_yyset_in
-#define yyset_lineno lttng_filter_yyset_lineno
-#define yyset_lval lttng_filter_yyset_lval
-#define yyset_out lttng_filter_yyset_out
+#define yyrealloc          lttng_filter_yyrealloc
+#define yyset_column       lttng_filter_yyset_column
+#define yyset_debug        lttng_filter_yyset_debug
+#define yyset_extra        lttng_filter_yyset_extra
+#define yyset_in           lttng_filter_yyset_in
+#define yyset_lineno       lttng_filter_yyset_lineno
+#define yyset_lval         lttng_filter_yyset_lval
+#define yyset_out          lttng_filter_yyset_out
 
 #endif /* _FILTER_SYMBOLS_H */
index 252a83870e87032b1ab101286c9bf89e783d2dcc..81822137f13ae2122359ef9b3a9a581a5049cb5e 100644 (file)
@@ -9,12 +9,6 @@
  *
  */
 
-#include <stdlib.h>
-#include <string.h>
-#include <common/align.hpp>
-#include <common/compat/errno.hpp>
-#include <common/compat/string.hpp>
-
 #include "common/align.hpp"
 #include "common/bytecode/bytecode.hpp"
 #include "common/compat/string.hpp"
 #include "filter-ast.hpp"
 #include "filter-ir.hpp"
 
-static
-int recursive_visit_gen_bytecode(struct filter_parser_ctx *ctx,
-               struct ir_op *node);
+#include <common/align.hpp>
+#include <common/compat/errno.hpp>
+#include <common/compat/string.hpp>
+
+#include <stdlib.h>
+#include <string.h>
+
+static int recursive_visit_gen_bytecode(struct filter_parser_ctx *ctx, struct ir_op *node);
 
-static
-int bytecode_patch(struct lttng_bytecode_alloc **fb,
-               const void *data,
-               uint16_t offset,
-               uint32_t len)
+static int
+bytecode_patch(struct lttng_bytecode_alloc **fb, const void *data, uint16_t offset, uint32_t len)
 {
        if (offset >= (*fb)->b.len) {
                return -EINVAL;
@@ -40,8 +36,7 @@ int bytecode_patch(struct lttng_bytecode_alloc **fb,
        return 0;
 }
 
-static
-int visit_node_root(struct filter_parser_ctx *ctx, struct ir_op *node)
+static int visit_node_root(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        int ret;
        struct return_op insn;
@@ -61,10 +56,9 @@ int visit_node_root(struct filter_parser_ctx *ctx, struct ir_op *node)
  * 0: no match
  * < 0: error
  */
-static
-int load_expression_legacy_match(const struct ir_load_expression *exp,
-               enum bytecode_op *op_type,
-               char **symbol)
+static int load_expression_legacy_match(const struct ir_load_expression *exp,
+                                       enum bytecode_op *op_type,
+                                       char **symbol)
 {
        const struct ir_load_expression_op *op;
        bool need_dot = false;
@@ -94,13 +88,13 @@ int load_expression_legacy_match(const struct ir_load_expression *exp,
        case IR_LOAD_EXPRESSION_GET_INDEX:
        case IR_LOAD_EXPRESSION_LOAD_FIELD:
        default:
-               return 0;       /* no match */
+               return 0; /* no match */
        }
 
        for (;;) {
                op = op->next;
                if (!op) {
-                       return 0;       /* no match */
+                       return 0; /* no match */
                }
                switch (op->type) {
                case IR_LOAD_EXPRESSION_LOAD_FIELD:
@@ -114,12 +108,12 @@ int load_expression_legacy_match(const struct ir_load_expression *exp,
                        }
                        break;
                default:
-                       return 0;        /* no match */
+                       return 0; /* no match */
                }
                need_dot = true;
        }
 end:
-       return 1;       /* Legacy match */
+       return 1; /* Legacy match */
 }
 
 /*
@@ -127,14 +121,12 @@ end:
  * 0: no legacy match
  * < 0: error
  */
-static
-int visit_node_load_expression_legacy(struct filter_parser_ctx *ctx,
-               const struct ir_load_expression *exp,
-               const struct ir_load_expression_op *op)
+static int visit_node_load_expression_legacy(struct filter_parser_ctx *ctx,
+                                            const struct ir_load_expression *exp,
+                                            const struct ir_load_expression_op *op)
 {
        struct load_op *insn = NULL;
-       uint32_t insn_len = sizeof(struct load_op)
-               + sizeof(struct field_ref);
+       uint32_t insn_len = sizeof(struct load_op) + sizeof(struct field_ref);
        struct field_ref ref_offset;
        uint32_t reloc_offset_u32;
        uint16_t reloc_offset;
@@ -166,26 +158,22 @@ int visit_node_load_expression_legacy(struct filter_parser_ctx *ctx,
                goto end;
        }
        /* append reloc */
-       ret = bytecode_push(&ctx->bytecode_reloc, &reloc_offset,
-                               1, sizeof(reloc_offset));
+       ret = bytecode_push(&ctx->bytecode_reloc, &reloc_offset, 1, sizeof(reloc_offset));
        if (ret) {
                goto end;
        }
-       ret = bytecode_push(&ctx->bytecode_reloc, symbol,
-                               1, strlen(symbol) + 1);
+       ret = bytecode_push(&ctx->bytecode_reloc, symbol, 1, strlen(symbol) + 1);
        if (ret) {
                goto end;
        }
-       ret = 1;        /* legacy */
+       ret = 1; /* legacy */
 end:
        free(insn);
        free(symbol);
        return ret;
 }
 
-static
-int visit_node_load_expression(struct filter_parser_ctx *ctx,
-               const struct ir_op *node)
+static int visit_node_load_expression(struct filter_parser_ctx *ctx, const struct ir_op *node)
 {
        struct ir_load_expression *exp;
        struct ir_load_expression_op *op;
@@ -209,7 +197,7 @@ int visit_node_load_expression(struct filter_parser_ctx *ctx,
                return ret;
        }
        if (ret > 0) {
-               return 0;       /* legacy */
+               return 0; /* legacy */
        }
 
        for (; op != NULL; op = op->next) {
@@ -226,8 +214,7 @@ int visit_node_load_expression(struct filter_parser_ctx *ctx,
                }
                case IR_LOAD_EXPRESSION_GET_APP_CONTEXT_ROOT:
                {
-                       ret = bytecode_push_get_app_context_root(
-                                       &ctx->bytecode);
+                       ret = bytecode_push_get_app_context_root(&ctx->bytecode);
 
                        if (ret) {
                                return ret;
@@ -247,8 +234,8 @@ int visit_node_load_expression(struct filter_parser_ctx *ctx,
                }
                case IR_LOAD_EXPRESSION_GET_SYMBOL:
                {
-                       ret = bytecode_push_get_symbol(&ctx->bytecode,
-                                       &ctx->bytecode_reloc, op->u.symbol);
+                       ret = bytecode_push_get_symbol(
+                               &ctx->bytecode, &ctx->bytecode_reloc, op->u.symbol);
 
                        if (ret) {
                                return ret;
@@ -258,8 +245,7 @@ int visit_node_load_expression(struct filter_parser_ctx *ctx,
                }
                case IR_LOAD_EXPRESSION_GET_INDEX:
                {
-                       ret = bytecode_push_get_index_u64(
-                                       &ctx->bytecode, op->u.index);
+                       ret = bytecode_push_get_index_u64(&ctx->bytecode, op->u.index);
 
                        if (ret) {
                                return ret;
@@ -288,23 +274,21 @@ int visit_node_load_expression(struct filter_parser_ctx *ctx,
        return 0;
 }
 
-static
-int visit_node_load(struct filter_parser_ctx *ctx, struct ir_op *node)
+static int visit_node_load(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        int ret;
 
        switch (node->data_type) {
        case IR_DATA_UNKNOWN:
        default:
-               fprintf(stderr, "[error] Unknown data type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown data type in %s\n", __func__);
                return -EINVAL;
 
        case IR_DATA_STRING:
        {
                struct load_op *insn;
-               uint32_t insn_len = sizeof(struct load_op)
-                       + strlen(node->u.load.u.string.value) + 1;
+               uint32_t insn_len =
+                       sizeof(struct load_op) + strlen(node->u.load.u.string.value) + 1;
 
                insn = (load_op *) calloc(insn_len, 1);
                if (!insn)
@@ -343,8 +327,7 @@ int visit_node_load(struct filter_parser_ctx *ctx, struct ir_op *node)
        case IR_DATA_NUMERIC:
        {
                struct load_op *insn;
-               uint32_t insn_len = sizeof(struct load_op)
-                       + sizeof(struct literal_numeric);
+               uint32_t insn_len = sizeof(struct load_op) + sizeof(struct literal_numeric);
 
                insn = (load_op *) calloc(insn_len, 1);
                if (!insn)
@@ -358,8 +341,7 @@ int visit_node_load(struct filter_parser_ctx *ctx, struct ir_op *node)
        case IR_DATA_FLOAT:
        {
                struct load_op *insn;
-               uint32_t insn_len = sizeof(struct load_op)
-                       + sizeof(struct literal_double);
+               uint32_t insn_len = sizeof(struct load_op) + sizeof(struct literal_double);
 
                insn = (load_op *) calloc(insn_len, 1);
                if (!insn)
@@ -375,8 +357,7 @@ int visit_node_load(struct filter_parser_ctx *ctx, struct ir_op *node)
        }
 }
 
-static
-int visit_node_unary(struct filter_parser_ctx *ctx, struct ir_op *node)
+static int visit_node_unary(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        int ret;
        struct unary_op insn;
@@ -390,8 +371,7 @@ int visit_node_unary(struct filter_parser_ctx *ctx, struct ir_op *node)
        switch (node->u.unary.type) {
        case AST_UNARY_UNKNOWN:
        default:
-               fprintf(stderr, "[error] Unknown unary node type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown unary node type in %s\n", __func__);
                return -EINVAL;
        case AST_UNARY_PLUS:
                /* Nothing to do. */
@@ -412,8 +392,7 @@ int visit_node_unary(struct filter_parser_ctx *ctx, struct ir_op *node)
  * Binary comparator nesting is disallowed. This allows fitting into
  * only 2 registers.
  */
-static
-int visit_node_binary(struct filter_parser_ctx *ctx, struct ir_op *node)
+static int visit_node_binary(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        int ret;
        struct binary_op insn;
@@ -429,14 +408,12 @@ int visit_node_binary(struct filter_parser_ctx *ctx, struct ir_op *node)
        switch (node->u.binary.type) {
        case AST_OP_UNKNOWN:
        default:
-               fprintf(stderr, "[error] Unknown unary node type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown unary node type in %s\n", __func__);
                return -EINVAL;
 
        case AST_OP_AND:
        case AST_OP_OR:
-               fprintf(stderr, "[error] Unexpected logical node type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unexpected logical node type in %s\n", __func__);
                return -EINVAL;
 
        case AST_OP_MUL:
@@ -495,8 +472,7 @@ int visit_node_binary(struct filter_parser_ctx *ctx, struct ir_op *node)
 /*
  * A logical op always return a s64 (1 or 0).
  */
-static
-int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
+static int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        int ret;
        struct logical_op insn;
@@ -508,28 +484,26 @@ int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
        if (ret)
                return ret;
        /* Cast to s64 if float or field ref */
-       if ((node->u.binary.left->data_type == IR_DATA_FIELD_REF
-                               || node->u.binary.left->data_type == IR_DATA_GET_CONTEXT_REF
-                               || node->u.binary.left->data_type == IR_DATA_EXPRESSION)
-                       || node->u.binary.left->data_type == IR_DATA_FLOAT) {
+       if ((node->u.binary.left->data_type == IR_DATA_FIELD_REF ||
+            node->u.binary.left->data_type == IR_DATA_GET_CONTEXT_REF ||
+            node->u.binary.left->data_type == IR_DATA_EXPRESSION) ||
+           node->u.binary.left->data_type == IR_DATA_FLOAT) {
                struct cast_op cast_insn;
 
-               if (node->u.binary.left->data_type == IR_DATA_FIELD_REF
-                               || node->u.binary.left->data_type == IR_DATA_GET_CONTEXT_REF
-                               || node->u.binary.left->data_type == IR_DATA_EXPRESSION) {
+               if (node->u.binary.left->data_type == IR_DATA_FIELD_REF ||
+                   node->u.binary.left->data_type == IR_DATA_GET_CONTEXT_REF ||
+                   node->u.binary.left->data_type == IR_DATA_EXPRESSION) {
                        cast_insn.op = BYTECODE_OP_CAST_TO_S64;
                } else {
                        cast_insn.op = BYTECODE_OP_CAST_DOUBLE_TO_S64;
                }
-               ret = bytecode_push(&ctx->bytecode, &cast_insn,
-                                       1, sizeof(cast_insn));
+               ret = bytecode_push(&ctx->bytecode, &cast_insn, 1, sizeof(cast_insn));
                if (ret)
                        return ret;
        }
        switch (node->u.logical.type) {
        default:
-               fprintf(stderr, "[error] Unknown node type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown node type in %s\n", __func__);
                return -EINVAL;
 
        case AST_OP_AND:
@@ -539,9 +513,8 @@ int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
                insn.op = BYTECODE_OP_OR;
                break;
        }
-       insn.skip_offset = (uint16_t) -1UL;     /* Temporary */
-       ret = bytecode_push_logical(&ctx->bytecode, &insn, 1, sizeof(insn),
-                       &skip_offset_loc);
+       insn.skip_offset = (uint16_t) -1UL; /* Temporary */
+       ret = bytecode_push_logical(&ctx->bytecode, &insn, 1, sizeof(insn), &skip_offset_loc);
        if (ret)
                return ret;
        /* Visit right child */
@@ -549,30 +522,29 @@ int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
        if (ret)
                return ret;
        /* Cast to s64 if float or field ref */
-       if ((node->u.binary.right->data_type == IR_DATA_FIELD_REF
-                               || node->u.binary.right->data_type == IR_DATA_GET_CONTEXT_REF
-                               || node->u.binary.right->data_type == IR_DATA_EXPRESSION)
-                       || node->u.binary.right->data_type == IR_DATA_FLOAT) {
+       if ((node->u.binary.right->data_type == IR_DATA_FIELD_REF ||
+            node->u.binary.right->data_type == IR_DATA_GET_CONTEXT_REF ||
+            node->u.binary.right->data_type == IR_DATA_EXPRESSION) ||
+           node->u.binary.right->data_type == IR_DATA_FLOAT) {
                struct cast_op cast_insn;
 
-               if (node->u.binary.right->data_type == IR_DATA_FIELD_REF
-                               || node->u.binary.right->data_type == IR_DATA_GET_CONTEXT_REF
-                               || node->u.binary.right->data_type == IR_DATA_EXPRESSION) {
+               if (node->u.binary.right->data_type == IR_DATA_FIELD_REF ||
+                   node->u.binary.right->data_type == IR_DATA_GET_CONTEXT_REF ||
+                   node->u.binary.right->data_type == IR_DATA_EXPRESSION) {
                        cast_insn.op = BYTECODE_OP_CAST_TO_S64;
                } else {
                        cast_insn.op = BYTECODE_OP_CAST_DOUBLE_TO_S64;
                }
-               ret = bytecode_push(&ctx->bytecode, &cast_insn,
-                                       1, sizeof(cast_insn));
+               ret = bytecode_push(&ctx->bytecode, &cast_insn, 1, sizeof(cast_insn));
                if (ret)
                        return ret;
        }
        /* We now know where the logical op can skip. */
        target_loc = (uint16_t) bytecode_get_len(&ctx->bytecode->b);
        ret = bytecode_patch(&ctx->bytecode,
-                       &target_loc,                    /* Offset to jump to */
-                       skip_offset_loc,                /* Where to patch */
-                       sizeof(uint16_t));
+                            &target_loc, /* Offset to jump to */
+                            skip_offset_loc, /* Where to patch */
+                            sizeof(uint16_t));
        return ret;
 }
 
@@ -580,15 +552,12 @@ int visit_node_logical(struct filter_parser_ctx *ctx, struct ir_op *node)
  * Postorder traversal of the tree. We need the children result before
  * we can evaluate the parent.
  */
-static
-int recursive_visit_gen_bytecode(struct filter_parser_ctx *ctx,
-               struct ir_op *node)
+static int recursive_visit_gen_bytecode(struct filter_parser_ctx *ctx, struct ir_op *node)
 {
        switch (node->op) {
        case IR_OP_UNKNOWN:
        default:
-               fprintf(stderr, "[error] Unknown node type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown node type in %s\n", __func__);
                return -EINVAL;
 
        case IR_OP_ROOT:
@@ -637,8 +606,10 @@ int filter_visitor_bytecode_generate(struct filter_parser_ctx *ctx)
 
        /* Finally, append symbol table to bytecode */
        ctx->bytecode->b.reloc_table_offset = bytecode_get_len(&ctx->bytecode->b);
-       return bytecode_push(&ctx->bytecode, ctx->bytecode_reloc->b.data,
-                       1, bytecode_get_len(&ctx->bytecode_reloc->b));
+       return bytecode_push(&ctx->bytecode,
+                            ctx->bytecode_reloc->b.data,
+                            1,
+                            bytecode_get_len(&ctx->bytecode_reloc->b));
 
 error:
        filter_bytecode_free(ctx);
index 1bfe66c6f0d5010d71c2d8fe02f774f5eb5744a7..9283fc3d1bfd973d8faefc12d8a833555800d3d2 100644 (file)
@@ -9,25 +9,24 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
 #include "filter-ast.hpp"
-#include "filter-parser.hpp"
 #include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 #include <common/macros.hpp>
 #include <common/string-utils/string-utils.hpp>
 
-static
-struct ir_op *generate_ir_recursive(struct filter_parser_ctx *ctx,
-               struct filter_node *node, enum ir_side side);
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static struct ir_op *
+generate_ir_recursive(struct filter_parser_ctx *ctx, struct filter_node *node, enum ir_side side);
 
-static
-struct ir_op *make_op_root(struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_root(struct ir_op *child, enum ir_side side)
 {
        struct ir_op *op;
 
@@ -59,8 +58,7 @@ struct ir_op *make_op_root(struct ir_op *child, enum ir_side side)
        return op;
 }
 
-static
-enum ir_load_string_type get_literal_string_type(const char *string)
+static enum ir_load_string_type get_literal_string_type(const char *string)
 {
        LTTNG_ASSERT(string);
 
@@ -75,8 +73,7 @@ enum ir_load_string_type get_literal_string_type(const char *string)
        return IR_LOAD_STRING_TYPE_PLAIN;
 }
 
-static
-struct ir_op *make_op_load_string(const char *string, enum ir_side side)
+static struct ir_op *make_op_load_string(const char *string, enum ir_side side)
 {
        struct ir_op *op;
 
@@ -96,8 +93,7 @@ struct ir_op *make_op_load_string(const char *string, enum ir_side side)
        return op;
 }
 
-static
-struct ir_op *make_op_load_numeric(int64_t v, enum ir_side side)
+static struct ir_op *make_op_load_numeric(int64_t v, enum ir_side side)
 {
        struct ir_op *op;
 
@@ -113,8 +109,7 @@ struct ir_op *make_op_load_numeric(int64_t v, enum ir_side side)
        return op;
 }
 
-static
-struct ir_op *make_op_load_float(double v, enum ir_side side)
+static struct ir_op *make_op_load_float(double v, enum ir_side side)
 {
        struct ir_op *op;
 
@@ -129,8 +124,7 @@ struct ir_op *make_op_load_float(double v, enum ir_side side)
        return op;
 }
 
-static
-void free_load_expression(struct ir_load_expression *load_expression)
+static void free_load_expression(struct ir_load_expression *load_expression)
 {
        struct ir_load_expression_op *exp_op;
 
@@ -164,8 +158,7 @@ void free_load_expression(struct ir_load_expression *load_expression)
  * Returns the first node of the chain, after initializing the next
  * pointers.
  */
-static
-struct filter_node *load_expression_get_forward_chain(struct filter_node *node)
+static struct filter_node *load_expression_get_forward_chain(struct filter_node *node)
 {
        struct filter_node *prev_node;
 
@@ -181,8 +174,7 @@ struct filter_node *load_expression_get_forward_chain(struct filter_node *node)
        return prev_node;
 }
 
-static
-struct ir_load_expression *create_load_expression(struct filter_node *node)
+static struct ir_load_expression *create_load_expression(struct filter_node *node)
 {
        struct ir_load_expression *load_exp;
        struct ir_load_expression_op *load_exp_op, *prev_op;
@@ -239,15 +231,15 @@ struct ir_load_expression *create_load_expression(struct filter_node *node)
                        goto error;
 
                /* Explore brackets from current node. */
-               for (bracket_node = node->u.expression.next_bracket;
-                               bracket_node != NULL;
-                               bracket_node = bracket_node->u.expression.next_bracket) {
+               for (bracket_node = node->u.expression.next_bracket; bracket_node != NULL;
+                    bracket_node = bracket_node->u.expression.next_bracket) {
                        prev_op = load_exp_op;
                        if (bracket_node->type != NODE_EXPRESSION ||
-                               bracket_node->u.expression.type != AST_EXP_CONSTANT) {
-                                       fprintf(stderr, "[error] Expecting constant index in array expression\n");
-                                       goto error;
-                               }
+                           bracket_node->u.expression.type != AST_EXP_CONSTANT) {
+                               fprintf(stderr,
+                                       "[error] Expecting constant index in array expression\n");
+                               goto error;
+                       }
                        load_exp_op = zmalloc<ir_load_expression_op>();
                        if (!load_exp_op)
                                goto error;
@@ -275,9 +267,7 @@ error:
        return NULL;
 }
 
-static
-struct ir_op *make_op_load_expression(struct filter_node *node,
-               enum ir_side side)
+static struct ir_op *make_op_load_expression(struct filter_node *node, enum ir_side side)
 {
        struct ir_op *op;
 
@@ -300,15 +290,18 @@ error:
        return NULL;
 }
 
-static
-struct ir_op *make_op_unary(enum unary_op_type unary_op_type,
-                       const char *op_str, enum ir_op_signedness signedness,
-                       struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_unary(enum unary_op_type unary_op_type,
+                                  const char *op_str,
+                                  enum ir_op_signedness signedness,
+                                  struct ir_op *child,
+                                  enum ir_side side)
 {
        struct ir_op *op = NULL;
 
        if (child->data_type == IR_DATA_STRING) {
-               fprintf(stderr, "[error] unary operation '%s' not allowed on string literal\n", op_str);
+               fprintf(stderr,
+                       "[error] unary operation '%s' not allowed on string literal\n",
+                       op_str);
                goto error;
        }
 
@@ -331,51 +324,42 @@ error:
 /*
  * unary + is pretty much useless.
  */
-static
-struct ir_op *make_op_unary_plus(struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_unary_plus(struct ir_op *child, enum ir_side side)
 {
-       return make_op_unary(AST_UNARY_PLUS, "+", child->signedness,
-                       child, side);
+       return make_op_unary(AST_UNARY_PLUS, "+", child->signedness, child, side);
 }
 
-static
-struct ir_op *make_op_unary_minus(struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_unary_minus(struct ir_op *child, enum ir_side side)
 {
-       return make_op_unary(AST_UNARY_MINUS, "-", child->signedness,
-                       child, side);
+       return make_op_unary(AST_UNARY_MINUS, "-", child->signedness, child, side);
 }
 
-static
-struct ir_op *make_op_unary_not(struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_unary_not(struct ir_op *child, enum ir_side side)
 {
-       return make_op_unary(AST_UNARY_NOT, "!", child->signedness,
-                       child, side);
+       return make_op_unary(AST_UNARY_NOT, "!", child->signedness, child, side);
 }
 
-static
-struct ir_op *make_op_unary_bit_not(struct ir_op *child, enum ir_side side)
+static struct ir_op *make_op_unary_bit_not(struct ir_op *child, enum ir_side side)
 {
-       return make_op_unary(AST_UNARY_BIT_NOT, "~", child->signedness,
-                       child, side);
+       return make_op_unary(AST_UNARY_BIT_NOT, "~", child->signedness, child, side);
 }
 
-static
-struct ir_op *make_op_binary_compare(enum op_type bin_op_type,
-               const char *op_str, struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_compare(enum op_type bin_op_type,
+                                           const char *op_str,
+                                           struct ir_op *left,
+                                           struct ir_op *right,
+                                           enum ir_side side)
 {
        struct ir_op *op = NULL;
 
-       if (left->data_type == IR_DATA_UNKNOWN
-               || right->data_type == IR_DATA_UNKNOWN) {
+       if (left->data_type == IR_DATA_UNKNOWN || right->data_type == IR_DATA_UNKNOWN) {
                fprintf(stderr, "[error] binary operation '%s' has unknown operand type\n", op_str);
                goto error;
-
        }
-       if ((left->data_type == IR_DATA_STRING
-               && (right->data_type == IR_DATA_NUMERIC || right->data_type == IR_DATA_FLOAT))
-               || ((left->data_type == IR_DATA_NUMERIC || left->data_type == IR_DATA_FLOAT) &&
-                       right->data_type == IR_DATA_STRING)) {
+       if ((left->data_type == IR_DATA_STRING &&
+            (right->data_type == IR_DATA_NUMERIC || right->data_type == IR_DATA_FLOAT)) ||
+           ((left->data_type == IR_DATA_NUMERIC || left->data_type == IR_DATA_FLOAT) &&
+            right->data_type == IR_DATA_STRING)) {
                fprintf(stderr, "[error] binary operation '%s' operand type mismatch\n", op_str);
                goto error;
        }
@@ -400,64 +384,52 @@ error:
        return NULL;
 }
 
-static
-struct ir_op *make_op_binary_eq(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_eq(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_EQ, "==", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_ne(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_ne(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_NE, "!=", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_gt(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_gt(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_GT, ">", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_lt(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_lt(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_LT, "<", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_ge(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_ge(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_GE, ">=", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_le(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_le(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_compare(AST_OP_LE, "<=", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_logical(enum op_type bin_op_type,
-               const char *op_str, struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_logical(enum op_type bin_op_type,
+                                           const char *op_str,
+                                           struct ir_op *left,
+                                           struct ir_op *right,
+                                           enum ir_side side)
 {
        struct ir_op *op = NULL;
 
-       if (left->data_type == IR_DATA_UNKNOWN
-               || right->data_type == IR_DATA_UNKNOWN) {
+       if (left->data_type == IR_DATA_UNKNOWN || right->data_type == IR_DATA_UNKNOWN) {
                fprintf(stderr, "[error] binary operation '%s' has unknown operand type\n", op_str);
                goto error;
-
        }
-       if (left->data_type == IR_DATA_STRING
-               || right->data_type == IR_DATA_STRING) {
-               fprintf(stderr, "[error] logical binary operation '%s' cannot have string operand\n", op_str);
+       if (left->data_type == IR_DATA_STRING || right->data_type == IR_DATA_STRING) {
+               fprintf(stderr,
+                       "[error] logical binary operation '%s' cannot have string operand\n",
+                       op_str);
                goto error;
        }
 
@@ -481,27 +453,30 @@ error:
        return NULL;
 }
 
-static
-struct ir_op *make_op_binary_bitwise(enum op_type bin_op_type,
-               const char *op_str, struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *make_op_binary_bitwise(enum op_type bin_op_type,
+                                           const char *op_str,
+                                           struct ir_op *left,
+                                           struct ir_op *right,
+                                           enum ir_side side)
 {
        struct ir_op *op = NULL;
 
-       if (left->data_type == IR_DATA_UNKNOWN
-               || right->data_type == IR_DATA_UNKNOWN) {
-               fprintf(stderr, "[error] bitwise binary operation '%s' has unknown operand type\n", op_str);
+       if (left->data_type == IR_DATA_UNKNOWN || right->data_type == IR_DATA_UNKNOWN) {
+               fprintf(stderr,
+                       "[error] bitwise binary operation '%s' has unknown operand type\n",
+                       op_str);
                goto error;
-
        }
-       if (left->data_type == IR_DATA_STRING
-               || right->data_type == IR_DATA_STRING) {
-               fprintf(stderr, "[error] bitwise binary operation '%s' cannot have string operand\n", op_str);
+       if (left->data_type == IR_DATA_STRING || right->data_type == IR_DATA_STRING) {
+               fprintf(stderr,
+                       "[error] bitwise binary operation '%s' cannot have string operand\n",
+                       op_str);
                goto error;
        }
-       if (left->data_type == IR_DATA_FLOAT
-               || right->data_type == IR_DATA_FLOAT) {
-               fprintf(stderr, "[error] bitwise binary operation '%s' cannot have floating point operand\n", op_str);
+       if (left->data_type == IR_DATA_FLOAT || right->data_type == IR_DATA_FLOAT) {
+               fprintf(stderr,
+                       "[error] bitwise binary operation '%s' cannot have floating point operand\n",
+                       op_str);
                goto error;
        }
 
@@ -525,65 +500,56 @@ error:
        return NULL;
 }
 
-static
-struct ir_op *make_op_binary_logical_and(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_logical_and(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_logical(AST_OP_AND, "&&", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_logical_or(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_logical_or(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_logical(AST_OP_OR, "||", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_bitwise_rshift(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_bitwise_rshift(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_bitwise(AST_OP_BIT_RSHIFT, ">>", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_bitwise_lshift(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_bitwise_lshift(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_bitwise(AST_OP_BIT_LSHIFT, "<<", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_bitwise_and(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_bitwise_and(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_bitwise(AST_OP_BIT_AND, "&", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_bitwise_or(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_bitwise_or(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_bitwise(AST_OP_BIT_OR, "|", left, right, side);
 }
 
-static
-struct ir_op *make_op_binary_bitwise_xor(struct ir_op *left, struct ir_op *right,
-               enum ir_side side)
+static struct ir_op *
+make_op_binary_bitwise_xor(struct ir_op *left, struct ir_op *right, enum ir_side side)
 {
        return make_op_binary_bitwise(AST_OP_BIT_XOR, "^", left, right, side);
 }
 
-static
-void filter_free_ir_recursive(struct ir_op *op)
+static void filter_free_ir_recursive(struct ir_op *op)
 {
        if (!op)
                return;
        switch (op->op) {
        case IR_OP_UNKNOWN:
        default:
-               fprintf(stderr, "[error] Unknown op type in %s\n",
-                       __func__);
+               fprintf(stderr, "[error] Unknown op type in %s\n", __func__);
                break;
        case IR_OP_ROOT:
                filter_free_ir_recursive(op->u.root.child);
@@ -593,7 +559,7 @@ void filter_free_ir_recursive(struct ir_op *op)
                case IR_DATA_STRING:
                        free(op->u.load.u.string.value);
                        break;
-               case IR_DATA_FIELD_REF:         /* fall-through */
+               case IR_DATA_FIELD_REF: /* fall-through */
                case IR_DATA_GET_CONTEXT_REF:
                        free(op->u.load.u.ref);
                        break;
@@ -618,9 +584,8 @@ void filter_free_ir_recursive(struct ir_op *op)
        free(op);
 }
 
-static
-struct ir_op *make_expression(struct filter_parser_ctx *ctx,
-               struct filter_node *node, enum ir_side side)
+static struct ir_op *
+make_expression(struct filter_parser_ctx *ctx, struct filter_node *node, enum ir_side side)
 {
        switch (node->u.expression.type) {
        case AST_EXP_UNKNOWN:
@@ -631,23 +596,19 @@ struct ir_op *make_expression(struct filter_parser_ctx *ctx,
        case AST_EXP_STRING:
                return make_op_load_string(node->u.expression.u.string, side);
        case AST_EXP_CONSTANT:
-               return make_op_load_numeric(node->u.expression.u.constant,
-                                       side);
+               return make_op_load_numeric(node->u.expression.u.constant, side);
        case AST_EXP_FLOAT_CONSTANT:
-               return make_op_load_float(node->u.expression.u.float_constant,
-                                       side);
+               return make_op_load_float(node->u.expression.u.float_constant, side);
        case AST_EXP_IDENTIFIER:
        case AST_EXP_GLOBAL_IDENTIFIER:
                return make_op_load_expression(node, side);
        case AST_EXP_NESTED:
-               return generate_ir_recursive(ctx, node->u.expression.u.child,
-                                       side);
+               return generate_ir_recursive(ctx, node->u.expression.u.child, side);
        }
 }
 
-static
-struct ir_op *make_op(struct filter_parser_ctx *ctx,
-               struct filter_node *node, enum ir_side side)
+static struct ir_op *
+make_op(struct filter_parser_ctx *ctx, struct filter_node *node, enum ir_side side)
 {
        struct ir_op *op = NULL, *lchild, *rchild;
        const char *op_str = "?";
@@ -777,14 +738,12 @@ struct ir_op *make_op(struct filter_parser_ctx *ctx,
        return op;
 
 error_not_supported:
-       fprintf(stderr, "[error] %s: binary operation '%s' not supported\n",
-               __func__, op_str);
+       fprintf(stderr, "[error] %s: binary operation '%s' not supported\n", __func__, op_str);
        return NULL;
 }
 
-static
-struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
-               struct filter_node *node, enum ir_side side)
+static struct ir_op *
+make_unary_op(struct filter_parser_ctx *ctx, struct filter_node *node, enum ir_side side)
 {
        switch (node->u.unary_op.type) {
        case AST_UNARY_UNKNOWN:
@@ -796,8 +755,7 @@ struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
        {
                struct ir_op *op, *child;
 
-               child = generate_ir_recursive(ctx, node->u.unary_op.child,
-                                       side);
+               child = generate_ir_recursive(ctx, node->u.unary_op.child, side);
                if (!child)
                        return NULL;
                op = make_op_unary_plus(child, side);
@@ -811,8 +769,7 @@ struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
        {
                struct ir_op *op, *child;
 
-               child = generate_ir_recursive(ctx, node->u.unary_op.child,
-                                       side);
+               child = generate_ir_recursive(ctx, node->u.unary_op.child, side);
                if (!child)
                        return NULL;
                op = make_op_unary_minus(child, side);
@@ -826,8 +783,7 @@ struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
        {
                struct ir_op *op, *child;
 
-               child = generate_ir_recursive(ctx, node->u.unary_op.child,
-                                       side);
+               child = generate_ir_recursive(ctx, node->u.unary_op.child, side);
                if (!child)
                        return NULL;
                op = make_op_unary_not(child, side);
@@ -841,8 +797,7 @@ struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
        {
                struct ir_op *op, *child;
 
-               child = generate_ir_recursive(ctx, node->u.unary_op.child,
-                                       side);
+               child = generate_ir_recursive(ctx, node->u.unary_op.child, side);
                if (!child)
                        return NULL;
                op = make_op_unary_bit_not(child, side);
@@ -857,9 +812,8 @@ struct ir_op *make_unary_op(struct filter_parser_ctx *ctx,
        return NULL;
 }
 
-static
-struct ir_op *generate_ir_recursive(struct filter_parser_ctx *ctx,
-               struct filter_node *node, enum ir_side side)
+static struct ir_op *
+generate_ir_recursive(struct filter_parser_ctx *ctx, struct filter_node *node, enum ir_side side)
 {
        switch (node->type) {
        case NODE_UNKNOWN:
@@ -871,8 +825,7 @@ struct ir_op *generate_ir_recursive(struct filter_parser_ctx *ctx,
        {
                struct ir_op *op, *child;
 
-               child = generate_ir_recursive(ctx, node->u.root.child,
-                                       side);
+               child = generate_ir_recursive(ctx, node->u.root.child, side);
                if (!child)
                        return NULL;
                op = make_op_root(child, side);
index 2699abde8b5379d52f81673d1d0b12ba1affc0e3..1384ff551fc8b37482a33d7e39230c5d226ade7a 100644 (file)
@@ -9,20 +9,19 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
+#include "filter-ast.hpp"
+#include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 
-#include "filter-ast.hpp"
-#include "filter-parser.hpp"
-#include "filter-ir.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-static
-int check_bin_comparator(struct ir_op *node)
+static int check_bin_comparator(struct ir_op *node)
 {
        switch (node->op) {
        case IR_OP_UNKNOWN:
@@ -40,12 +39,11 @@ int check_bin_comparator(struct ir_op *node)
        {
                int ret;
 
-               if (node->u.binary.left->data_type == IR_DATA_STRING
-                               || node->u.binary.right->data_type
-                                       == IR_DATA_STRING) {
-                       if (node->u.binary.type != AST_OP_EQ
-                                       && node->u.binary.type != AST_OP_NE) {
-                               fprintf(stderr, "[error] Only '==' and '!=' comparators are allowed for strings\n");
+               if (node->u.binary.left->data_type == IR_DATA_STRING ||
+                   node->u.binary.right->data_type == IR_DATA_STRING) {
+                       if (node->u.binary.type != AST_OP_EQ && node->u.binary.type != AST_OP_NE) {
+                               fprintf(stderr,
+                                       "[error] Only '==' and '!=' comparators are allowed for strings\n");
                                return -EINVAL;
                        }
                }
index 9c3dd76737f64f57e3d1a5a5aea34768d4190c54..5ebbc43eeaafd740a182dd473ff020d90aebcc33 100644 (file)
@@ -9,20 +9,20 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
 #include "filter-ast.hpp"
-#include "filter-parser.hpp"
 #include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 #include <common/macros.hpp>
 
-static
-int check_bin_op_nesting_recursive(struct ir_op *node, int nesting)
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static int check_bin_op_nesting_recursive(struct ir_op *node, int nesting)
 {
        switch (node->op) {
        case IR_OP_UNKNOWN:
@@ -31,34 +31,28 @@ int check_bin_op_nesting_recursive(struct ir_op *node, int nesting)
                return -EINVAL;
 
        case IR_OP_ROOT:
-               return check_bin_op_nesting_recursive(node->u.root.child,
-                               nesting);
+               return check_bin_op_nesting_recursive(node->u.root.child, nesting);
        case IR_OP_LOAD:
                return 0;
        case IR_OP_UNARY:
-               return check_bin_op_nesting_recursive(node->u.unary.child,
-                               nesting);
+               return check_bin_op_nesting_recursive(node->u.unary.child, nesting);
        case IR_OP_BINARY:
        {
                int ret;
 
-               ret = check_bin_op_nesting_recursive(node->u.binary.left,
-                               nesting + 1);
+               ret = check_bin_op_nesting_recursive(node->u.binary.left, nesting + 1);
                if (ret)
                        return ret;
-               return check_bin_op_nesting_recursive(node->u.binary.right,
-                               nesting + 1);
+               return check_bin_op_nesting_recursive(node->u.binary.right, nesting + 1);
        }
        case IR_OP_LOGICAL:
        {
                int ret;
 
-               ret = check_bin_op_nesting_recursive(node->u.logical.left,
-                               nesting);
+               ret = check_bin_op_nesting_recursive(node->u.logical.left, nesting);
                if (ret)
                        return ret;
-               return check_bin_op_nesting_recursive(node->u.logical.right,
-                               nesting);
+               return check_bin_op_nesting_recursive(node->u.logical.right, nesting);
        }
        }
 }
index 446c720db635e9ea0e0eb1d33c9c625f408980d8..517bd5128c9f4d3d6449cd3b876d24fc9e58991b 100644 (file)
@@ -9,22 +9,21 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
+#include "filter-ast.hpp"
+#include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 #include <common/macros.hpp>
 #include <common/string-utils/string-utils.hpp>
 
-#include "filter-ast.hpp"
-#include "filter-parser.hpp"
-#include "filter-ir.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-static
-int normalize_glob_patterns(struct ir_op *node)
+static int normalize_glob_patterns(struct ir_op *node)
 {
        switch (node->op) {
        case IR_OP_UNKNOWN:
@@ -37,13 +36,11 @@ int normalize_glob_patterns(struct ir_op *node)
        case IR_OP_LOAD:
        {
                if (node->data_type == IR_DATA_STRING) {
-                       enum ir_load_string_type type =
-                               node->u.load.u.string.type;
+                       enum ir_load_string_type type = node->u.load.u.string.type;
                        if (type == IR_LOAD_STRING_TYPE_GLOB_STAR_END ||
-                                       type == IR_LOAD_STRING_TYPE_GLOB_STAR) {
+                           type == IR_LOAD_STRING_TYPE_GLOB_STAR) {
                                LTTNG_ASSERT(node->u.load.u.string.value);
-                               strutils_normalize_star_glob_pattern(
-                                       node->u.load.u.string.value);
+                               strutils_normalize_star_glob_pattern(node->u.load.u.string.value);
                        }
                }
 
index 718098a433403bea810158b9e8b5b2fe27ca030a..f0a236345ad69dc0d8a2322d5e0434da1e7d24c2 100644 (file)
@@ -9,21 +9,20 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
+#include "filter-ast.hpp"
+#include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 #include <common/macros.hpp>
 
-#include "filter-ast.hpp"
-#include "filter-parser.hpp"
-#include "filter-ir.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-static
-int validate_globbing(struct ir_op *node)
+static int validate_globbing(struct ir_op *node)
 {
        int ret;
 
@@ -45,30 +44,32 @@ int validate_globbing(struct ir_op *node)
                struct ir_op *right = node->u.binary.right;
 
                if (left->op == IR_OP_LOAD && right->op == IR_OP_LOAD &&
-                               left->data_type == IR_DATA_STRING &&
-                               right->data_type == IR_DATA_STRING) {
+                   left->data_type == IR_DATA_STRING && right->data_type == IR_DATA_STRING) {
                        /* Test 1. */
                        if (left->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR &&
-                                       right->u.load.u.string.type != IR_LOAD_STRING_TYPE_PLAIN) {
+                           right->u.load.u.string.type != IR_LOAD_STRING_TYPE_PLAIN) {
                                fprintf(stderr, "[error] Cannot compare two globbing patterns\n");
                                return -1;
                        }
 
                        if (right->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR &&
-                                       left->u.load.u.string.type != IR_LOAD_STRING_TYPE_PLAIN) {
+                           left->u.load.u.string.type != IR_LOAD_STRING_TYPE_PLAIN) {
                                fprintf(stderr, "[error] Cannot compare two globbing patterns\n");
                                return -1;
                        }
                }
 
                if ((left->op == IR_OP_LOAD && left->data_type == IR_DATA_STRING) ||
-                               (right->op == IR_OP_LOAD && right->data_type == IR_DATA_STRING)) {
-                       if ((left->op == IR_OP_LOAD && left->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR) ||
-                                       (right->op == IR_OP_LOAD && right->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR)) {
+                   (right->op == IR_OP_LOAD && right->data_type == IR_DATA_STRING)) {
+                       if ((left->op == IR_OP_LOAD &&
+                            left->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR) ||
+                           (right->op == IR_OP_LOAD &&
+                            right->u.load.u.string.type == IR_LOAD_STRING_TYPE_GLOB_STAR)) {
                                /* Test 2. */
                                if (node->u.binary.type != AST_OP_EQ &&
-                                               node->u.binary.type != AST_OP_NE) {
-                                       fprintf(stderr, "[error] Only the `==` and `!=` operators are allowed with a globbing pattern\n");
+                                   node->u.binary.type != AST_OP_NE) {
+                                       fprintf(stderr,
+                                               "[error] Only the `==` and `!=` operators are allowed with a globbing pattern\n");
                                        return -1;
                                }
                        }
index 9e060ce2b64e4fe77817c0af71fe76e150be308a..fd1feeed6cfcce6fed8c56158e69c90003277644 100644 (file)
@@ -9,18 +9,18 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
+#include "filter-ast.hpp"
+#include "filter-ir.hpp"
+#include "filter-parser.hpp"
 
-#include <common/macros.hpp>
 #include <common/compat/errno.hpp>
+#include <common/macros.hpp>
 
-#include "filter-ast.hpp"
-#include "filter-parser.hpp"
-#include "filter-ir.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
 enum parse_char_result {
        PARSE_CHAR_UNKNOWN = -2,
@@ -28,8 +28,7 @@ enum parse_char_result {
        PARSE_CHAR_NORMAL = 0,
 };
 
-static
-enum parse_char_result parse_char(const char **p)
+static enum parse_char_result parse_char(const char **p)
 {
        switch (**p) {
        case '\\':
@@ -48,8 +47,7 @@ enum parse_char_result parse_char(const char **p)
        }
 }
 
-static
-int validate_string(struct ir_op *node)
+static int validate_string(struct ir_op *node)
 {
        switch (node->op) {
        case IR_OP_UNKNOWN:
@@ -82,8 +80,7 @@ int validate_string(struct ir_op *node)
                                switch (res) {
                                case PARSE_CHAR_UNKNOWN:
                                        ret = -EINVAL;
-                                       fprintf(stderr,
-                                               "Unsupported escape character detected.\n");
+                                       fprintf(stderr, "Unsupported escape character detected.\n");
                                        goto end_load;
                                case PARSE_CHAR_NORMAL:
                                default:
@@ -91,7 +88,7 @@ int validate_string(struct ir_op *node)
                                }
                        }
                }
-end_load:
+       end_load:
                return ret;
        }
        case IR_OP_UNARY:
index 5b531a28979ad7a09eb788fdf55b47d62493cbd8..5d1bdb9d393ee8c2f4a8a9624fa5348537f3000d 100644 (file)
@@ -9,24 +9,23 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <inttypes.h>
 #include "filter-ast.hpp"
 #include "filter-parser.hpp"
 
 #include <common/compat/errno.hpp>
 #include <common/macros.hpp>
 
-#define fprintf_dbg(fd, fmt, args...)  fprintf(fd, "%s: " fmt, __func__, ## args)
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-static
-int recursive_visit_print(struct filter_node *node, FILE *stream, int indent);
+#define fprintf_dbg(fd, fmt, args...) fprintf(fd, "%s: " fmt, __func__, ##args)
 
-static
-void print_tabs(FILE *fd, int depth)
+static int recursive_visit_print(struct filter_node *node, FILE *stream, int indent);
+
+static void print_tabs(FILE *fd, int depth)
 {
        int i;
 
@@ -34,9 +33,7 @@ void print_tabs(FILE *fd, int depth)
                fprintf(fd, "\t");
 }
 
-static
-int recursive_visit_print_expression(struct filter_node *node,
-               FILE *stream, int indent)
+static int recursive_visit_print_expression(struct filter_node *node, FILE *stream, int indent)
 {
        struct filter_node *iter_node;
 
@@ -51,50 +48,47 @@ int recursive_visit_print_expression(struct filter_node *node,
                return -EINVAL;
        case AST_EXP_STRING:
                print_tabs(stream, indent);
-               fprintf(stream, "<string value=\"%s\"/>\n",
-                       node->u.expression.u.string);
+               fprintf(stream, "<string value=\"%s\"/>\n", node->u.expression.u.string);
                break;
        case AST_EXP_CONSTANT:
                print_tabs(stream, indent);
-               fprintf(stream, "<constant value=\"%" PRIu64 "\"/>\n",
+               fprintf(stream,
+                       "<constant value=\"%" PRIu64 "\"/>\n",
                        node->u.expression.u.constant);
                break;
        case AST_EXP_FLOAT_CONSTANT:
                print_tabs(stream, indent);
-               fprintf(stream, "<float_constant value=\"%lg\"/>\n",
+               fprintf(stream,
+                       "<float_constant value=\"%lg\"/>\n",
                        node->u.expression.u.float_constant);
                break;
-       case AST_EXP_IDENTIFIER:                /* fall-through */
+       case AST_EXP_IDENTIFIER: /* fall-through */
        case AST_EXP_GLOBAL_IDENTIFIER:
                print_tabs(stream, indent);
-               fprintf(stream, "<%s value=\"%s\"/>\n",
-                       node->u.expression.type == AST_EXP_IDENTIFIER ?
-                               "identifier" : "global_identifier",
+               fprintf(stream,
+                       "<%s value=\"%s\"/>\n",
+                       node->u.expression.type == AST_EXP_IDENTIFIER ? "identifier" :
+                                                                       "global_identifier",
                        node->u.expression.u.identifier);
                iter_node = node->u.expression.next;
                while (iter_node) {
                        print_tabs(stream, indent);
                        fprintf(stream, "<bracket>\n");
-                       if (recursive_visit_print_expression(iter_node,
-                                       stream, indent + 1)) {
+                       if (recursive_visit_print_expression(iter_node, stream, indent + 1)) {
                                return -EINVAL;
                        }
                        print_tabs(stream, indent);
                        fprintf(stream, "</bracket>\n");
                        iter_node = iter_node->u.expression.next;
-
                }
                break;
        case AST_EXP_NESTED:
-               return recursive_visit_print(node->u.expression.u.child,
-                               stream, indent + 1);
+               return recursive_visit_print(node->u.expression.u.child, stream, indent + 1);
        }
        return 0;
 }
 
-
-static
-int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
+static int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
 {
        int ret;
 
@@ -110,16 +104,14 @@ int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
        case NODE_ROOT:
                print_tabs(stream, indent);
                fprintf(stream, "<root>\n");
-               ret = recursive_visit_print(node->u.root.child, stream,
-                                       indent + 1);
+               ret = recursive_visit_print(node->u.root.child, stream, indent + 1);
                print_tabs(stream, indent);
                fprintf(stream, "</root>\n");
                return ret;
        case NODE_EXPRESSION:
                print_tabs(stream, indent);
                fprintf(stream, "<expression>\n");
-               ret = recursive_visit_print_expression(node, stream,
-                                       indent + 1);
+               ret = recursive_visit_print_expression(node, stream, indent + 1);
                print_tabs(stream, indent);
                fprintf(stream, "</expression>\n");
                return ret;
@@ -188,12 +180,10 @@ int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
                        break;
                }
                fprintf(stream, ">\n");
-               ret = recursive_visit_print(node->u.op.lchild,
-                                       stream, indent + 1);
+               ret = recursive_visit_print(node->u.op.lchild, stream, indent + 1);
                if (ret)
                        return ret;
-               ret = recursive_visit_print(node->u.op.rchild,
-                                       stream, indent + 1);
+               ret = recursive_visit_print(node->u.op.rchild, stream, indent + 1);
                if (ret)
                        return ret;
                print_tabs(stream, indent);
@@ -221,8 +211,7 @@ int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
                        break;
                }
                fprintf(stream, ">\n");
-               ret = recursive_visit_print(node->u.unary_op.child,
-                                       stream, indent + 1);
+               ret = recursive_visit_print(node->u.unary_op.child, stream, indent + 1);
                print_tabs(stream, indent);
                fprintf(stream, "</unary_op>\n");
                return ret;
@@ -230,8 +219,7 @@ int recursive_visit_print(struct filter_node *node, FILE *stream, int indent)
        return 0;
 }
 
-int filter_visitor_print_xml(struct filter_parser_ctx *ctx, FILE *stream,
-                       int indent)
+int filter_visitor_print_xml(struct filter_parser_ctx *ctx, FILE *stream, int indent)
 {
        return recursive_visit_print(&ctx->ast->root, stream, indent);
 }
index 26b124a9521086b7030b9c6bae13f2a58373a241..4fbdc02fe2bd241eaeb9fae25d92d37a3fc85946 100644 (file)
 #ifdef LTTNG_HAVE_FMEMOPEN
 #include <stdio.h>
 
-static inline
-FILE *lttng_fmemopen(void *buf, size_t size, const char *mode)
+static inline FILE *lttng_fmemopen(void *buf, size_t size, const char *mode)
 {
        return fmemopen(buf, size, mode);
 }
 
 #else /* LTTNG_HAVE_FMEMOPEN */
 
-#include <stdlib.h>
-#include <stdio.h>
 #include <common/error.hpp>
 
+#include <stdio.h>
+#include <stdlib.h>
+
 /*
  * Fallback for systems which don't have fmemopen. Copy buffer to a
  * temporary file, and use that file as FILE * input.
  */
-static inline
-FILE *lttng_fmemopen(void *buf, size_t size, const char *mode)
+static inline FILE *lttng_fmemopen(void *buf, size_t size, const char *mode)
 {
        char tmpname[PATH_MAX];
        size_t len;
index 020766eb5ddd788dfd7c8114a6bd993e7817cfdf..2ba6cef125ab735ae8977c88dde7298c0c889f93 100644 (file)
@@ -9,8 +9,9 @@
 
 #include <common/macros.hpp>
 
-#include <string>
 #include <cxxabi.h>
+#include <string>
+#include <utility>
 
 DIAGNOSTIC_PUSH
 DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
@@ -19,6 +20,8 @@ DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
 #include <vendor/fmt/core.h>
 DIAGNOSTIC_POP
 
+#include <common/make-unique-wrapper.hpp>
+
 /*
  * Due to a bug in g++ < 7.1, this specialization must be enclosed in the fmt namespace,
  * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480.
@@ -26,18 +29,35 @@ DIAGNOSTIC_POP
 namespace fmt {
 template <>
 struct formatter<std::type_info> : formatter<std::string> {
-       template <typename FormatCtx>
-       typename FormatCtx::iterator format(const std::type_info& type_info, FormatCtx& ctx)
+       template <typename FormatContextType>
+       typename FormatContextType::iterator format(const std::type_info& type_info,
+                                                   FormatContextType& ctx)
        {
                int status;
-               auto demangled_name = abi::__cxa_demangle(type_info.name(), nullptr, 0, &status);
-               auto it = status == 0 ? formatter<std::string>::format(demangled_name, ctx) :
-                                       formatter<std::string>::format(type_info.name(), ctx);
+               /*
+                * The documentation of __cxa_demangle mentions the returned string is allocated
+                * using malloc (not new), hence the use of lttng::memory::free.
+                */
+               const auto demangled_name = lttng::make_unique_wrapper<char, lttng::memory::free>(
+                       abi::__cxa_demangle(type_info.name(), nullptr, nullptr, &status));
 
-               free(demangled_name);
+               auto it = status == 0 ? formatter<std::string>::format(demangled_name.get(), ctx) :
+                                       formatter<std::string>::format(type_info.name(), ctx);
                return it;
        }
 };
 } /* namespace fmt */
 
+namespace lttng {
+template <typename... FormattingArguments>
+std::string format(FormattingArguments&&...args)
+{
+       try {
+               return fmt::format(std::forward<FormattingArguments>(args)...);
+       } catch (const fmt::format_error& ex) {
+               return std::string("Failed to format string: ") += ex.what();
+       }
+}
+} /* namespace lttng */
+
 #endif /* LTTNG_FORMAT_H */
index 08824673d3e1e93165dabe2e0aa47739eb989689..5d1e1340972a1828c13f1917e315b5c2ba3b3ee1 100644 (file)
@@ -18,10 +18,10 @@ struct fs_handle;
  * to use an fd-tracker.
  */
 
-typedef int (*fs_handle_get_fd_cb)(struct fs_handle *);
-typedef void (*fs_handle_put_fd_cb)(struct fs_handle *);
-typedef int (*fs_handle_unlink_cb)(struct fs_handle *);
-typedef int (*fs_handle_close_cb)(struct fs_handle *);
+using fs_handle_get_fd_cb = int (*)(struct fs_handle *);
+using fs_handle_put_fd_cb = void (*)(struct fs_handle *);
+using fs_handle_unlink_cb = int (*)(struct fs_handle *);
+using fs_handle_close_cb = int (*)(struct fs_handle *);
 
 struct fs_handle {
        fs_handle_get_fd_cb get_fd;
index 8b3a882a952c3cb4ea88fe7737978f7d33b1d5de..491db0a1397626b2c058da729375cf7766006d16 100644 (file)
@@ -9,6 +9,7 @@
 #define FS_HANDLE_H
 
 #include <common/macros.hpp>
+
 #include <stdio.h>
 
 struct fs_handle;
index e178b7e1b4f1e8a99de25e42b10733266353ada0..b0e01fc73d4d8d4a6cbec6e669958fe80fa94b5e 100644 (file)
@@ -7,15 +7,15 @@
  */
 
 #define _LGPL_SOURCE
+#include "futex.hpp"
+
+#include <common/common.hpp>
+
 #include <limits.h>
 #include <unistd.h>
 #include <urcu.h>
 #include <urcu/futex.h>
 
-#include <common/common.hpp>
-
-#include "futex.hpp"
-
 /*
  * This futex wait/wake scheme only works for N wakers / 1 waiters. Hence the
  * "nto1" added to all function signature.
@@ -42,8 +42,7 @@ void futex_wait_update(int32_t *futex, int active)
 {
        if (active) {
                uatomic_set(futex, 1);
-               if (futex_async(futex, FUTEX_WAKE,
-                               INT_MAX, NULL, NULL, 0) < 0) {
+               if (futex_async(futex, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0) < 0) {
                        PERROR("futex_async");
                        abort();
                }
@@ -73,7 +72,7 @@ void futex_nto1_wait(int32_t *futex)
        cmm_smp_mb();
 
        while (uatomic_read(futex) == -1) {
-               if (!futex_async(futex, FUTEX_WAIT, -1, NULL, NULL, 0)) {
+               if (!futex_async(futex, FUTEX_WAIT, -1, nullptr, nullptr, 0)) {
                        /*
                         * Prior queued wakeups queued by unrelated code
                         * using the same address can cause futex wait to
@@ -90,7 +89,7 @@ void futex_nto1_wait(int32_t *futex)
                        goto end;
                case EINTR:
                        /* Retry if interrupted by signal. */
-                       break;  /* Get out of switch. Check again. */
+                       break; /* Get out of switch. Check again. */
                default:
                        /* Unexpected error. */
                        PERROR("futex_async");
@@ -109,7 +108,7 @@ void futex_nto1_wake(int32_t *futex)
        if (caa_unlikely(uatomic_read(futex) != -1))
                goto end;
        uatomic_set(futex, 0);
-       if (futex_async(futex, FUTEX_WAKE, 1, NULL, NULL, 0) < 0) {
+       if (futex_async(futex, FUTEX_WAKE, 1, nullptr, nullptr, 0) < 0) {
                PERROR("futex_async");
                abort();
        }
index e0faa9711013ad3f26ab58bcf3b86f42bf737389..7b961caf9a023c9da33a25f4a9f17b84a19e644f 100644 (file)
@@ -9,6 +9,8 @@
 #ifndef _LTT_FUTEX_H
 #define _LTT_FUTEX_H
 
+#include <cstdint>
+
 void futex_wait_update(int32_t *futex, int active);
 void futex_nto1_prepare(int32_t *futex);
 void futex_nto1_wait(int32_t *futex);
index 5f22c0e820b26a46ef97eb7ec0460e80d2f8a46f..5fd1cbe2b97e3a39ea0e761ba459ca74e03eaf3b 100644 (file)
  *
  */
 
-#define _cds_lfht_new lttng__cds_lfht_new
-#define cds_lfht_add lttng_cds_lfht_add
-#define cds_lfht_add_replace lttng_cds_lfht_add_replace
-#define cds_lfht_add_unique lttng_cds_lfht_add_unique
-#define cds_lfht_count_nodes lttng_cds_lfht_count_nodes
-#define cds_lfht_del lttng_cds_lfht_del
-#define cds_lfht_destroy lttng_cds_lfht_destroy
-#define cds_lfht_first lttng_cds_lfht_first
-#define cds_lfht_fls_ulong lttng_cds_lfht_fls_ulong
-#define cds_lfht_get_count_order_u32 lttng_cds_lfht_get_count_order_u32
+#define _cds_lfht_new                 lttng__cds_lfht_new
+#define cds_lfht_add                  lttng_cds_lfht_add
+#define cds_lfht_add_replace          lttng_cds_lfht_add_replace
+#define cds_lfht_add_unique           lttng_cds_lfht_add_unique
+#define cds_lfht_count_nodes          lttng_cds_lfht_count_nodes
+#define cds_lfht_del                  lttng_cds_lfht_del
+#define cds_lfht_destroy              lttng_cds_lfht_destroy
+#define cds_lfht_first                lttng_cds_lfht_first
+#define cds_lfht_fls_ulong            lttng_cds_lfht_fls_ulong
+#define cds_lfht_get_count_order_u32   lttng_cds_lfht_get_count_order_u32
 #define cds_lfht_get_count_order_ulong lttng_cds_lfht_get_count_order_ulong
-#define cds_lfht_is_node_deleted lttng_cds_lfht_is_node_deleted
-#define cds_lfht_lookup lttng_cds_lfht_lookup
-#define cds_lfht_next lttng_cds_lfht_next
-#define cds_lfht_next_duplicate lttng_cds_lfht_next_duplicate
-#define cds_lfht_replace lttng_cds_lfht_replace
-#define cds_lfht_resize lttng_cds_lfht_resize
+#define cds_lfht_is_node_deleted       lttng_cds_lfht_is_node_deleted
+#define cds_lfht_lookup                       lttng_cds_lfht_lookup
+#define cds_lfht_next                 lttng_cds_lfht_next
+#define cds_lfht_next_duplicate               lttng_cds_lfht_next_duplicate
+#define cds_lfht_replace              lttng_cds_lfht_replace
+#define cds_lfht_resize                       lttng_cds_lfht_resize
 
 #endif /* _HASHTABLE_SYMBOLS_H */
index 3aa3d79d42210dcfb192a21056c1a1a2319c7716..29d3ac499715f1e9da4e8eb8d7b4c79b2c786157 100644 (file)
@@ -6,15 +6,16 @@
  */
 
 #define _LGPL_SOURCE
-#include <string.h>
-#include <urcu.h>
-#include <urcu/compiler.h>
+#include "hashtable.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/defaults.hpp>
+#include <common/urcu.hpp>
 
-#include "hashtable.hpp"
-#include "utils.hpp"
+#include <string.h>
+#include <urcu.h>
+#include <urcu/compiler.h>
 
 /* seed_lock protects both seed_init and lttng_ht_seed. */
 static pthread_mutex_t seed_lock = PTHREAD_MUTEX_INITIALIZER;
@@ -74,8 +75,7 @@ static int match_two_u64(struct cds_lfht_node *node, const void *key)
        return hash_match_key_two_u64((void *) &match_node->key, (void *) key);
 }
 
-static inline
-const char *lttng_ht_type_str(enum lttng_ht_type type)
+static inline const char *lttng_ht_type_str(enum lttng_ht_type type)
 {
        switch (type) {
        case LTTNG_HT_TYPE_STRING:
@@ -105,19 +105,22 @@ struct lttng_ht *lttng_ht_new(unsigned long size, lttng_ht_type type)
 
        pthread_mutex_lock(&seed_lock);
        if (!seed_init) {
-               lttng_ht_seed = (unsigned long) time(NULL);
+               lttng_ht_seed = (unsigned long) time(nullptr);
                seed_init = true;
        }
        pthread_mutex_unlock(&seed_lock);
 
        ht = zmalloc<lttng_ht>();
-       if (ht == NULL) {
+       if (ht == nullptr) {
                PERROR("zmalloc lttng_ht");
                goto error;
        }
 
-       ht->ht = cds_lfht_new(size, min_hash_alloc_size, max_hash_buckets_size,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       ht->ht = cds_lfht_new(size,
+                             min_hash_alloc_size,
+                             max_hash_buckets_size,
+                             CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING,
+                             nullptr);
        /*
         * There is already an assert in the RCU hashtable code so if the ht is
         * NULL here there is a *huge* problem.
@@ -147,13 +150,12 @@ struct lttng_ht *lttng_ht_new(unsigned long size, lttng_ht_type type)
                goto error;
        }
 
-       DBG3("Created hashtable size %lu at %p of type %s", size, ht->ht,
-                       lttng_ht_type_str(type));
+       DBG3("Created hashtable size %lu at %p of type %s", size, ht->ht, lttng_ht_type_str(type));
 
        return ht;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -163,7 +165,7 @@ void lttng_ht_destroy(struct lttng_ht *ht)
 {
        int ret;
 
-       ret = cds_lfht_destroy(ht->ht, NULL);
+       ret = cds_lfht_destroy(ht->ht, nullptr);
        LTTNG_ASSERT(!ret);
        free(ht);
 }
@@ -182,8 +184,7 @@ void lttng_ht_node_init_str(struct lttng_ht_node_str *node, char *key)
 /*
  * Init lttng ht node unsigned long.
  */
-void lttng_ht_node_init_ulong(struct lttng_ht_node_ulong *node,
-               unsigned long key)
+void lttng_ht_node_init_ulong(struct lttng_ht_node_ulong *node, unsigned long key)
 {
        LTTNG_ASSERT(node);
 
@@ -194,8 +195,7 @@ void lttng_ht_node_init_ulong(struct lttng_ht_node_ulong *node,
 /*
  * Init lttng ht node uint64_t.
  */
-void lttng_ht_node_init_u64(struct lttng_ht_node_u64 *node,
-               uint64_t key)
+void lttng_ht_node_init_u64(struct lttng_ht_node_u64 *node, uint64_t key)
 {
        LTTNG_ASSERT(node);
 
@@ -206,8 +206,7 @@ void lttng_ht_node_init_u64(struct lttng_ht_node_u64 *node,
 /*
  * Init lttng ht node with two uint64_t.
  */
-void lttng_ht_node_init_two_u64(struct lttng_ht_node_two_u64 *node,
-               uint64_t key1, uint64_t key2)
+void lttng_ht_node_init_two_u64(struct lttng_ht_node_two_u64 *node, uint64_t key1, uint64_t key2)
 {
        LTTNG_ASSERT(node);
 
@@ -255,21 +254,18 @@ void lttng_ht_node_free_two_u64(struct lttng_ht_node_two_u64 *node)
 /*
  * Lookup function in hashtable.
  */
-void lttng_ht_lookup(struct lttng_ht *ht, const void *key,
-               struct lttng_ht_iter *iter)
+void lttng_ht_lookup(struct lttng_ht *ht, const void *key, struct lttng_ht_iter *iter)
 {
        LTTNG_ASSERT(ht);
        LTTNG_ASSERT(ht->ht);
 
-       cds_lfht_lookup(ht->ht, ht->hash_fct(key, lttng_ht_seed),
-                       ht->match_fct, key, &iter->iter);
+       cds_lfht_lookup(ht->ht, ht->hash_fct(key, lttng_ht_seed), ht->match_fct, key, &iter->iter);
 }
 
 /*
  * Add unique string node to hashtable.
  */
-void lttng_ht_add_unique_str(struct lttng_ht *ht,
-               struct lttng_ht_node_str *node)
+void lttng_ht_add_unique_str(struct lttng_ht *ht, struct lttng_ht_node_str *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -277,28 +273,27 @@ void lttng_ht_add_unique_str(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
-       node_ptr = cds_lfht_add_unique(ht->ht, ht->hash_fct(node->key, lttng_ht_seed),
-                       ht->match_fct, node->key, &node->node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       node_ptr = cds_lfht_add_unique(ht->ht,
+                                      ht->hash_fct(node->key, lttng_ht_seed),
+                                      ht->match_fct,
+                                      node->key,
+                                      &node->node);
        LTTNG_ASSERT(node_ptr == &node->node);
 }
 
 /*
  * Add string node to hashtable.
  */
-void lttng_ht_add_str(struct lttng_ht *ht,
-               struct lttng_ht_node_str *node)
+void lttng_ht_add_str(struct lttng_ht *ht, struct lttng_ht_node_str *node)
 {
        LTTNG_ASSERT(ht);
        LTTNG_ASSERT(ht->ht);
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
-       cds_lfht_add(ht->ht, ht->hash_fct(node->key, lttng_ht_seed),
-                       &node->node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_add(ht->ht, ht->hash_fct(node->key, lttng_ht_seed), &node->node);
 }
 
 /*
@@ -311,10 +306,8 @@ void lttng_ht_add_ulong(struct lttng_ht *ht, struct lttng_ht_node_ulong *node)
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
-       cds_lfht_add(ht->ht, ht->hash_fct((void *) node->key, lttng_ht_seed),
-                       &node->node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_add(ht->ht, ht->hash_fct((void *) node->key, lttng_ht_seed), &node->node);
 }
 
 /*
@@ -327,17 +320,14 @@ void lttng_ht_add_u64(struct lttng_ht *ht, struct lttng_ht_node_u64 *node)
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
-       cds_lfht_add(ht->ht, ht->hash_fct(&node->key, lttng_ht_seed),
-                       &node->node);
-       rcu_read_unlock();
+       lttng::urcu::read_lock_guard read_lock;
+       cds_lfht_add(ht->ht, ht->hash_fct(&node->key, lttng_ht_seed), &node->node);
 }
 
 /*
  * Add unique unsigned long node to hashtable.
  */
-void lttng_ht_add_unique_ulong(struct lttng_ht *ht,
-               struct lttng_ht_node_ulong *node)
+void lttng_ht_add_unique_ulong(struct lttng_ht *ht, struct lttng_ht_node_ulong *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -345,19 +335,19 @@ void lttng_ht_add_unique_ulong(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct((void *) node->key, lttng_ht_seed), ht->match_fct,
-                       (void *) node->key, &node->node);
-       rcu_read_unlock();
+                                      ht->hash_fct((void *) node->key, lttng_ht_seed),
+                                      ht->match_fct,
+                                      (void *) node->key,
+                                      &node->node);
        LTTNG_ASSERT(node_ptr == &node->node);
 }
 
 /*
  * Add unique uint64_t node to hashtable.
  */
-void lttng_ht_add_unique_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_u64 *node)
+void lttng_ht_add_unique_u64(struct lttng_ht *ht, struct lttng_ht_node_u64 *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -365,19 +355,19 @@ void lttng_ht_add_unique_u64(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct(&node->key, lttng_ht_seed), ht->match_fct,
-                       &node->key, &node->node);
-       rcu_read_unlock();
+                                      ht->hash_fct(&node->key, lttng_ht_seed),
+                                      ht->match_fct,
+                                      &node->key,
+                                      &node->node);
        LTTNG_ASSERT(node_ptr == &node->node);
 }
 
 /*
  * Add unique two uint64_t node to hashtable.
  */
-void lttng_ht_add_unique_two_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_two_u64 *node)
+void lttng_ht_add_unique_two_u64(struct lttng_ht *ht, struct lttng_ht_node_two_u64 *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -385,11 +375,12 @@ void lttng_ht_add_unique_two_u64(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        node_ptr = cds_lfht_add_unique(ht->ht,
-                       ht->hash_fct((void *) &node->key, lttng_ht_seed), ht->match_fct,
-                       (void *) &node->key, &node->node);
-       rcu_read_unlock();
+                                      ht->hash_fct((void *) &node->key, lttng_ht_seed),
+                                      ht->match_fct,
+                                      (void *) &node->key,
+                                      &node->node);
        LTTNG_ASSERT(node_ptr == &node->node);
 }
 
@@ -397,7 +388,7 @@ void lttng_ht_add_unique_two_u64(struct lttng_ht *ht,
  * Add replace unsigned long node to hashtable.
  */
 struct lttng_ht_node_ulong *lttng_ht_add_replace_ulong(struct lttng_ht *ht,
-               struct lttng_ht_node_ulong *node)
+                                                      struct lttng_ht_node_ulong *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -405,24 +396,24 @@ struct lttng_ht_node_ulong *lttng_ht_add_replace_ulong(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        node_ptr = cds_lfht_add_replace(ht->ht,
-                       ht->hash_fct((void *) node->key, lttng_ht_seed), ht->match_fct,
-                       (void *) node->key, &node->node);
-       rcu_read_unlock();
+                                       ht->hash_fct((void *) node->key, lttng_ht_seed),
+                                       ht->match_fct,
+                                       (void *) node->key,
+                                       &node->node);
        if (!node_ptr) {
-               return NULL;
+               return nullptr;
        } else {
                return lttng::utils::container_of(node_ptr, &lttng_ht_node_ulong::node);
        }
-       LTTNG_ASSERT(node_ptr == &node->node);
 }
 
 /*
  * Add replace unsigned long node to hashtable.
  */
 struct lttng_ht_node_u64 *lttng_ht_add_replace_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_u64 *node)
+                                                  struct lttng_ht_node_u64 *node)
 {
        struct cds_lfht_node *node_ptr;
        LTTNG_ASSERT(ht);
@@ -430,17 +421,18 @@ struct lttng_ht_node_u64 *lttng_ht_add_replace_u64(struct lttng_ht *ht,
        LTTNG_ASSERT(node);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        node_ptr = cds_lfht_add_replace(ht->ht,
-                       ht->hash_fct(&node->key, lttng_ht_seed), ht->match_fct,
-                       &node->key, &node->node);
-       rcu_read_unlock();
+                                       ht->hash_fct(&node->key, lttng_ht_seed),
+                                       ht->match_fct,
+                                       &node->key,
+                                       &node->node);
        if (!node_ptr) {
-               return NULL;
+               return nullptr;
        } else {
+               LTTNG_ASSERT(node_ptr == &node->node);
                return lttng::utils::container_of(node_ptr, &lttng_ht_node_u64::node);
        }
-       LTTNG_ASSERT(node_ptr == &node->node);
 }
 
 /*
@@ -455,9 +447,8 @@ int lttng_ht_del(struct lttng_ht *ht, struct lttng_ht_iter *iter)
        LTTNG_ASSERT(iter);
 
        /* RCU read lock protects from ABA. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        ret = cds_lfht_del(ht->ht, iter->iter.node);
-       rcu_read_unlock();
        return ret;
 }
 
@@ -497,9 +488,8 @@ unsigned long lttng_ht_get_count(struct lttng_ht *ht)
        LTTNG_ASSERT(ht->ht);
 
        /* RCU read lock protects from ABA and allows RCU traversal. */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_count_nodes(ht->ht, &scb, &count, &sca);
-       rcu_read_unlock();
 
        return count;
 }
@@ -507,15 +497,14 @@ unsigned long lttng_ht_get_count(struct lttng_ht *ht)
 /*
  * Return lttng ht string node from iterator.
  */
-struct lttng_ht_node_str *lttng_ht_iter_get_node_str(
-               struct lttng_ht_iter *iter)
+struct lttng_ht_node_str *lttng_ht_iter_get_node_str(struct lttng_ht_iter *iter)
 {
        struct cds_lfht_node *node;
 
        LTTNG_ASSERT(iter);
        node = cds_lfht_iter_get_node(&iter->iter);
        if (!node) {
-               return NULL;
+               return nullptr;
        }
        return lttng::utils::container_of(node, &lttng_ht_node_str::node);
 }
@@ -523,15 +512,14 @@ struct lttng_ht_node_str *lttng_ht_iter_get_node_str(
 /*
  * Return lttng ht unsigned long node from iterator.
  */
-struct lttng_ht_node_ulong *lttng_ht_iter_get_node_ulong(
-               struct lttng_ht_iter *iter)
+struct lttng_ht_node_ulong *lttng_ht_iter_get_node_ulong(struct lttng_ht_iter *iter)
 {
        struct cds_lfht_node *node;
 
        LTTNG_ASSERT(iter);
        node = cds_lfht_iter_get_node(&iter->iter);
        if (!node) {
-               return NULL;
+               return nullptr;
        }
        return lttng::utils::container_of(node, &lttng_ht_node_ulong::node);
 }
@@ -539,15 +527,14 @@ struct lttng_ht_node_ulong *lttng_ht_iter_get_node_ulong(
 /*
  * Return lttng ht unsigned long node from iterator.
  */
-struct lttng_ht_node_u64 *lttng_ht_iter_get_node_u64(
-               struct lttng_ht_iter *iter)
+struct lttng_ht_node_u64 *lttng_ht_iter_get_node_u64(struct lttng_ht_iter *iter)
 {
        struct cds_lfht_node *node;
 
        LTTNG_ASSERT(iter);
        node = cds_lfht_iter_get_node(&iter->iter);
        if (!node) {
-               return NULL;
+               return nullptr;
        }
        return lttng::utils::container_of(node, &lttng_ht_node_u64::node);
 }
@@ -555,15 +542,14 @@ struct lttng_ht_node_u64 *lttng_ht_iter_get_node_u64(
 /*
  * Return lttng ht stream and index id node from iterator.
  */
-struct lttng_ht_node_two_u64 *lttng_ht_iter_get_node_two_u64(
-               struct lttng_ht_iter *iter)
+struct lttng_ht_node_two_u64 *lttng_ht_iter_get_node_two_u64(struct lttng_ht_iter *iter)
 {
        struct cds_lfht_node *node;
 
        LTTNG_ASSERT(iter);
        node = cds_lfht_iter_get_node(&iter->iter);
        if (!node) {
-               return NULL;
+               return nullptr;
        }
        return lttng::utils::container_of(node, &lttng_ht_node_two_u64::node);
 }
index dee40ddfdf935e4a5f53a8852de6ad21d303e24e..ac1af7eed6669824dd981b7f84e91d8984ae2918 100644 (file)
@@ -8,18 +8,19 @@
 #ifndef _LTT_HT_H
 #define _LTT_HT_H
 
-#include <urcu.h>
-#include <stdint.h>
-#include <memory>
-
 #include <common/macros.hpp>
+
 #include <lttng/lttng-export.h>
+
+#include <memory>
+#include <stdint.h>
+#include <urcu.h>
 #include <urcu/rculfhash.h>
 
 LTTNG_EXPORT extern unsigned long lttng_ht_seed;
 
-typedef unsigned long (*hash_fct_type)(const void *_key, unsigned long seed);
-typedef cds_lfht_match_fct hash_match_fct;
+using hash_fct_type = unsigned long (*)(const void *, unsigned long);
+using hash_match_fct = cds_lfht_match_fct;
 
 enum lttng_ht_type {
        LTTNG_HT_TYPE_STRING,
@@ -74,60 +75,47 @@ struct lttng_ht_node_two_u64 {
 struct lttng_ht *lttng_ht_new(unsigned long size, enum lttng_ht_type type);
 void lttng_ht_destroy(struct lttng_ht *ht);
 struct lttng_ht_deleter {
-       void operator()(lttng_ht *ht) { lttng_ht_destroy(ht); };
+       void operator()(lttng_ht *ht)
+       {
+               lttng_ht_destroy(ht);
+       };
 };
 
 /* Specialized node init and free functions */
 void lttng_ht_node_init_str(struct lttng_ht_node_str *node, char *key);
-void lttng_ht_node_init_ulong(struct lttng_ht_node_ulong *node,
-               unsigned long key);
-void lttng_ht_node_init_u64(struct lttng_ht_node_u64 *node,
-               uint64_t key);
-void lttng_ht_node_init_two_u64(struct lttng_ht_node_two_u64 *node,
-               uint64_t key1, uint64_t key2);
+void lttng_ht_node_init_ulong(struct lttng_ht_node_ulong *node, unsigned long key);
+void lttng_ht_node_init_u64(struct lttng_ht_node_u64 *node, uint64_t key);
+void lttng_ht_node_init_two_u64(struct lttng_ht_node_two_u64 *node, uint64_t key1, uint64_t key2);
 void lttng_ht_node_free_str(struct lttng_ht_node_str *node);
 void lttng_ht_node_free_ulong(struct lttng_ht_node_ulong *node);
 void lttng_ht_node_free_u64(struct lttng_ht_node_u64 *node);
 void lttng_ht_node_free_two_u64(struct lttng_ht_node_two_u64 *node);
 
-void lttng_ht_lookup(struct lttng_ht *ht, const void *key,
-               struct lttng_ht_iter *iter);
+void lttng_ht_lookup(struct lttng_ht *ht, const void *key, struct lttng_ht_iter *iter);
 
 /* Specialized add unique functions */
-void lttng_ht_add_unique_str(struct lttng_ht *ht,
-               struct lttng_ht_node_str *node);
-void lttng_ht_add_unique_ulong(struct lttng_ht *ht,
-               struct lttng_ht_node_ulong *node);
-void lttng_ht_add_unique_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_u64 *node);
-void lttng_ht_add_unique_two_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_two_u64 *node);
-struct lttng_ht_node_ulong *lttng_ht_add_replace_ulong(
-               struct lttng_ht *ht, struct lttng_ht_node_ulong *node);
-struct lttng_ht_node_u64 *lttng_ht_add_replace_u64(
-               struct lttng_ht *ht, struct lttng_ht_node_u64 *node);
-void lttng_ht_add_str(struct lttng_ht *ht,
-               struct lttng_ht_node_str *node);
-void lttng_ht_add_ulong(struct lttng_ht *ht,
-               struct lttng_ht_node_ulong *node);
-void lttng_ht_add_u64(struct lttng_ht *ht,
-               struct lttng_ht_node_u64 *node);
+void lttng_ht_add_unique_str(struct lttng_ht *ht, struct lttng_ht_node_str *node);
+void lttng_ht_add_unique_ulong(struct lttng_ht *ht, struct lttng_ht_node_ulong *node);
+void lttng_ht_add_unique_u64(struct lttng_ht *ht, struct lttng_ht_node_u64 *node);
+void lttng_ht_add_unique_two_u64(struct lttng_ht *ht, struct lttng_ht_node_two_u64 *node);
+struct lttng_ht_node_ulong *lttng_ht_add_replace_ulong(struct lttng_ht *ht,
+                                                      struct lttng_ht_node_ulong *node);
+struct lttng_ht_node_u64 *lttng_ht_add_replace_u64(struct lttng_ht *ht,
+                                                  struct lttng_ht_node_u64 *node);
+void lttng_ht_add_str(struct lttng_ht *ht, struct lttng_ht_node_str *node);
+void lttng_ht_add_ulong(struct lttng_ht *ht, struct lttng_ht_node_ulong *node);
+void lttng_ht_add_u64(struct lttng_ht *ht, struct lttng_ht_node_u64 *node);
 
 int lttng_ht_del(struct lttng_ht *ht, struct lttng_ht_iter *iter);
 
-void lttng_ht_get_first(struct lttng_ht *ht,
-               struct lttng_ht_iter *iter);
+void lttng_ht_get_first(struct lttng_ht *ht, struct lttng_ht_iter *iter);
 void lttng_ht_get_next(struct lttng_ht *ht, struct lttng_ht_iter *iter);
 
 unsigned long lttng_ht_get_count(struct lttng_ht *ht);
 
-struct lttng_ht_node_str *lttng_ht_iter_get_node_str(
-               struct lttng_ht_iter *iter);
-struct lttng_ht_node_ulong *lttng_ht_iter_get_node_ulong(
-               struct lttng_ht_iter *iter);
-struct lttng_ht_node_u64 *lttng_ht_iter_get_node_u64(
-               struct lttng_ht_iter *iter);
-struct lttng_ht_node_two_u64 *lttng_ht_iter_get_node_two_u64(
-               struct lttng_ht_iter *iter);
+struct lttng_ht_node_str *lttng_ht_iter_get_node_str(struct lttng_ht_iter *iter);
+struct lttng_ht_node_ulong *lttng_ht_iter_get_node_ulong(struct lttng_ht_iter *iter);
+struct lttng_ht_node_u64 *lttng_ht_iter_get_node_u64(struct lttng_ht_iter *iter);
+struct lttng_ht_node_two_u64 *lttng_ht_iter_get_node_two_u64(struct lttng_ht_iter *iter);
 
 #endif /* _LTT_HT_H */
index 516deeb64bbb6dcf8b3550abd0f236616bcec6c2..5b9344b15ba36cf430b55c69214328f58ff4293f 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <stdint.h>     /* defines uint32_t etc */
-#include <stdio.h>      /* defines printf for tests */
-#include <string.h>
-#include <sys/param.h>  /* attempt to define endianness */
-#include <time.h>       /* defines time_t for timings in the test */
-#include <urcu/compiler.h>
-
 #include "utils.hpp"
-#include <common/compat/endian.hpp>    /* attempt to define endianness */
+
 #include <common/common.hpp>
+#include <common/compat/endian.hpp> /* attempt to define endianness */
 #include <common/hashtable/hashtable.hpp>
 
+#include <stdint.h> /* defines uint32_t etc */
+#include <stdio.h> /* defines printf for tests */
+#include <string.h>
+#include <sys/param.h> /* attempt to define endianness */
+#include <time.h> /* defines time_t for timings in the test */
+#include <urcu/compiler.h>
+
 /*
  * My best guess at if you are big-endian or little-endian.  This may
  * need adjustment.
  */
-#if (defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && \
-     BYTE_ORDER == LITTLE_ENDIAN) || \
-    (defined(i386) || defined(__i386__) || defined(__i486__) || \
-     defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
-# define HASH_LITTLE_ENDIAN 1
-# define HASH_BIG_ENDIAN 0
-#elif (defined(BYTE_ORDER) && defined(BIG_ENDIAN) && \
-       BYTE_ORDER == BIG_ENDIAN) || \
-      (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
-# define HASH_LITTLE_ENDIAN 0
-# define HASH_BIG_ENDIAN 1
+#if (defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN) ||    \
+       (defined(i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || \
+        defined(__i686__) || defined(vax) || defined(MIPSEL))
+#define HASH_LITTLE_ENDIAN 1
+#define HASH_BIG_ENDIAN           0
+#elif (defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN) || \
+       (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN           1
 #else
-# define HASH_LITTLE_ENDIAN 0
-# define HASH_BIG_ENDIAN 0
+#define HASH_LITTLE_ENDIAN 0
+#define HASH_BIG_ENDIAN           0
 #endif
 
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+#define hashsize(n) ((uint32_t) 1 << (n))
+#define hashmask(n) (hashsize(n) - 1)
+#define rot(x, k)   (((x) << (k)) | ((x) >> (32 - (k))))
 
 /*
  * mix -- mix 3 32-bit values reversibly.
  * on, and rotates are much kinder to the top and bottom bits, so I used
  * rotates.
  */
-#define mix(a,b,c) \
-{ \
-  a -= c;  a ^= rot(c, 4);  c += b; \
-  b -= a;  b ^= rot(a, 6);  a += c; \
-  c -= b;  c ^= rot(b, 8);  b += a; \
-  a -= c;  a ^= rot(c,16);  c += b; \
-  b -= a;  b ^= rot(a,19);  a += c; \
-  c -= b;  c ^= rot(b, 4);  b += a; \
-}
+#define mix(a, b, c)               \
+       {                          \
+               (a) -= (c);        \
+               (a) ^= rot(c, 4);  \
+               (c) += (b);        \
+               (b) -= (a);        \
+               (b) ^= rot(a, 6);  \
+               (a) += (c);        \
+               (c) -= (b);        \
+               (c) ^= rot(b, 8);  \
+               (b) += (a);        \
+               (a) -= (c);        \
+               (a) ^= rot(c, 16); \
+               (c) += (b);        \
+               (b) -= (a);        \
+               (b) ^= rot(a, 19); \
+               (a) += (c);        \
+               (c) -= (b);        \
+               (c) ^= rot(b, 4);  \
+               (b) += (a);        \
+       }
 
 /*
  * final -- final mixing of 3 32-bit values (a,b,c) into c
  *  10  8 15 26 3 22 24
  *  11  8 15 26 3 22 24
  */
-#define final(a,b,c) \
-{ \
-  c ^= b; c -= rot(b,14); \
-  a ^= c; a -= rot(c,11); \
-  b ^= a; b -= rot(a,25); \
-  c ^= b; c -= rot(b,16); \
-  a ^= c; a -= rot(c,4);  \
-  b ^= a; b -= rot(a,14); \
-  c ^= b; c -= rot(b,24); \
-}
+#define final(a, b, c)             \
+       {                          \
+               (c) ^= (b);        \
+               (c) -= rot(b, 14); \
+               (a) ^= (c);        \
+               (a) -= rot(c, 11); \
+               (b) ^= (a);        \
+               (b) -= rot(a, 25); \
+               (c) ^= (b);        \
+               (c) -= rot(b, 16); \
+               (a) ^= (c);        \
+               (a) -= rot(c, 4);  \
+               (b) ^= (a);        \
+               (b) -= rot(a, 14); \
+               (c) ^= (b);        \
+               (c) -= rot(b, 24); \
+       }
 
 /*
  * k - the key, an array of uint32_t values
  * length - the length of the key, in uint32_ts
  * initval - the previous hash, or an arbitrary value
  */
-static uint32_t __attribute__((unused)) hashword(const uint32_t *k,
-               size_t length, uint32_t initval)
+static uint32_t __attribute__((unused)) hashword(const uint32_t *k, size_t length, uint32_t initval)
 {
        uint32_t a, b, c;
 
@@ -186,27 +203,29 @@ static uint32_t __attribute__((unused)) hashword(const uint32_t *k,
        }
 
        /*----------------------------------- handle the last 3 uint32_t's */
-       switch (length) {       /* all the case statements fall through */
-       case 3: c += k[2]; /* fall through */
-       case 2: b += k[1]; /* fall through */
-       case 1: a += k[0];
+       switch (length) { /* all the case statements fall through */
+       case 3:
+               c += k[2]; /* fall through */
+       case 2:
+               b += k[1]; /* fall through */
+       case 1:
+               a += k[0];
                final(a, b, c);
-       case 0:                 /* case 0: nothing left to add */
+       case 0: /* case 0: nothing left to add */
                break;
        }
        /*---------------------------------------------- report the result */
        return c;
 }
 
-
 /*
  * hashword2() -- same as hashword(), but take two seeds and return two 32-bit
  * values.  pc and pb must both be nonnull, and *pc and *pb must both be
  * initialized with seeds.  If you pass in (*pb)==0, the output (*pc) will be
  * the same as the return value from hashword().
  */
-static void __attribute__((unused)) hashword2(const uint32_t *k, size_t length,
-               uint32_t *pc, uint32_t *pb)
+static void __attribute__((unused))
+hashword2(const uint32_t *k, size_t length, uint32_t *pc, uint32_t *pb)
 {
        uint32_t a, b, c;
 
@@ -224,17 +243,17 @@ static void __attribute__((unused)) hashword2(const uint32_t *k, size_t length,
        }
 
        switch (length) {
-       case 3 :
+       case 3:
                c += k[2];
                /* fall through */
-       case 2 :
+       case 2:
                b += k[1];
                /* fall through */
-       case 1 :
+       case 1:
                a += k[0];
                final(a, b, c);
                /* fall through */
-       case 0:     /* case 0: nothing left to add */
+       case 0: /* case 0: nothing left to add */
                break;
        }
 
@@ -267,29 +286,27 @@ static void __attribute__((unused)) hashword2(const uint32_t *k, size_t length,
  * acceptable.  Do NOT use for cryptographic purposes.
  */
 LTTNG_NO_SANITIZE_ADDRESS
-__attribute__((unused))
-static uint32_t hashlittle(const void *key,
-               size_t length, uint32_t initval)
+__attribute__((unused)) static uint32_t hashlittle(const void *key, size_t length, uint32_t initval)
 {
-       uint32_t a,b,c;
+       uint32_t a, b, c;
        union {
                const void *ptr;
                size_t i;
-       } u;     /* needed for Mac Powerbook G4 */
+       } u; /* needed for Mac Powerbook G4 */
 
        /* Set up the internal state */
-       a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+       a = b = c = 0xdeadbeef + ((uint32_t) length) + initval;
 
        u.ptr = key;
        if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
-               const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
+               const uint32_t *k = (const uint32_t *) key; /* read 32-bit chunks */
 
                /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
                while (length > 12) {
                        a += k[0];
                        b += k[1];
                        c += k[2];
-                       mix(a,b,c);
+                       mix(a, b, c);
                        length -= 12;
                        k += 3;
                }
@@ -306,139 +323,207 @@ static uint32_t hashlittle(const void *key,
 #ifndef VALGRIND
 
                switch (length) {
-               case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
-               case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
-               case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
-               case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
-               case 8 : b+=k[1]; a+=k[0]; break;
-               case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
-               case 6 : b+=k[1]&0xffff; a+=k[0]; break;
-               case 5 : b+=k[1]&0xff; a+=k[0]; break;
-               case 4 : a+=k[0]; break;
-               case 3 : a+=k[0]&0xffffff; break;
-               case 2 : a+=k[0]&0xffff; break;
-               case 1 : a+=k[0]&0xff; break;
-               case 0 : return c;              /* zero length strings require no mixing */
+               case 12:
+                       c += k[2];
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 11:
+                       c += k[2] & 0xffffff;
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 10:
+                       c += k[2] & 0xffff;
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 9:
+                       c += k[2] & 0xff;
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 8:
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 7:
+                       b += k[1] & 0xffffff;
+                       a += k[0];
+                       break;
+               case 6:
+                       b += k[1] & 0xffff;
+                       a += k[0];
+                       break;
+               case 5:
+                       b += k[1] & 0xff;
+                       a += k[0];
+                       break;
+               case 4:
+                       a += k[0];
+                       break;
+               case 3:
+                       a += k[0] & 0xffffff;
+                       break;
+               case 2:
+                       a += k[0] & 0xffff;
+                       break;
+               case 1:
+                       a += k[0] & 0xff;
+                       break;
+               case 0:
+                       return c; /* zero length strings require no mixing */
                }
 #else /* make valgrind happy */
                const uint8_t *k8;
 
-               k8 = (const uint8_t *)k;
+               k8 = (const uint8_t *) k;
                switch (length) {
-               case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
-               case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
-               case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
-               case 9 : c+=k8[8];                   /* fall through */
-               case 8 : b+=k[1]; a+=k[0]; break;
-               case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
-               case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
-               case 5 : b+=k8[4];                   /* fall through */
-               case 4 : a+=k[0]; break;
-               case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
-               case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
-               case 1 : a+=k8[0]; break;
-               case 0 : return c;
+               case 12:
+                       c += k[2];
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 11:
+                       c += ((uint32_t) k8[10]) << 16; /* fall through */
+               case 10:
+                       c += ((uint32_t) k8[9]) << 8; /* fall through */
+               case 9:
+                       c += k8[8]; /* fall through */
+               case 8:
+                       b += k[1];
+                       a += k[0];
+                       break;
+               case 7:
+                       b += ((uint32_t) k8[6]) << 16; /* fall through */
+               case 6:
+                       b += ((uint32_t) k8[5]) << 8; /* fall through */
+               case 5:
+                       b += k8[4]; /* fall through */
+               case 4:
+                       a += k[0];
+                       break;
+               case 3:
+                       a += ((uint32_t) k8[2]) << 16; /* fall through */
+               case 2:
+                       a += ((uint32_t) k8[1]) << 8; /* fall through */
+               case 1:
+                       a += k8[0];
+                       break;
+               case 0:
+                       return c;
                }
 #endif /* !valgrind */
        } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
-               const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
+               const uint16_t *k = (const uint16_t *) key; /* read 16-bit chunks */
                const uint8_t *k8;
 
                /*--------------- all but last block: aligned reads and different mixing */
                while (length > 12) {
-                       a += k[0] + (((uint32_t)k[1])<<16);
-                       b += k[2] + (((uint32_t)k[3])<<16);
-                       c += k[4] + (((uint32_t)k[5])<<16);
-                       mix(a,b,c);
+                       a += k[0] + (((uint32_t) k[1]) << 16);
+                       b += k[2] + (((uint32_t) k[3]) << 16);
+                       c += k[4] + (((uint32_t) k[5]) << 16);
+                       mix(a, b, c);
                        length -= 12;
                        k += 6;
                }
 
-               k8 = (const uint8_t *)k;
+               k8 = (const uint8_t *) k;
                switch (length) {
                case 12:
-                       c+=k[4]+(((uint32_t)k[5])<<16);
-                       b+=k[2]+(((uint32_t)k[3])<<16);
-                       a+=k[0]+(((uint32_t)k[1])<<16);
+                       c += k[4] + (((uint32_t) k[5]) << 16);
+                       b += k[2] + (((uint32_t) k[3]) << 16);
+                       a += k[0] + (((uint32_t) k[1]) << 16);
                        break;
                case 11:
-                       c+=((uint32_t)k8[10])<<16;     /* fall through */
+                       c += ((uint32_t) k8[10]) << 16; /* fall through */
                case 10:
-                       c+=k[4];
-                       b+=k[2]+(((uint32_t)k[3])<<16);
-                       a+=k[0]+(((uint32_t)k[1])<<16);
+                       c += k[4];
+                       b += k[2] + (((uint32_t) k[3]) << 16);
+                       a += k[0] + (((uint32_t) k[1]) << 16);
                        break;
                case 9:
-                       c+=k8[8];                      /* fall through */
+                       c += k8[8]; /* fall through */
                case 8:
-                       b+=k[2]+(((uint32_t)k[3])<<16);
-                       a+=k[0]+(((uint32_t)k[1])<<16);
+                       b += k[2] + (((uint32_t) k[3]) << 16);
+                       a += k[0] + (((uint32_t) k[1]) << 16);
                        break;
                case 7:
-                       b+=((uint32_t)k8[6])<<16;      /* fall through */
+                       b += ((uint32_t) k8[6]) << 16; /* fall through */
                case 6:
-                       b+=k[2];
-                       a+=k[0]+(((uint32_t)k[1])<<16);
+                       b += k[2];
+                       a += k[0] + (((uint32_t) k[1]) << 16);
                        break;
                case 5:
-                       b+=k8[4];                      /* fall through */
+                       b += k8[4]; /* fall through */
                case 4:
-                       a+=k[0]+(((uint32_t)k[1])<<16);
+                       a += k[0] + (((uint32_t) k[1]) << 16);
                        break;
                case 3:
-                       a+=((uint32_t)k8[2])<<16;      /* fall through */
+                       a += ((uint32_t) k8[2]) << 16; /* fall through */
                case 2:
-                       a+=k[0];
+                       a += k[0];
                        break;
                case 1:
-                       a+=k8[0];
+                       a += k8[0];
                        break;
                case 0:
-                       return c;   /* zero length requires no mixing */
+                       return c; /* zero length requires no mixing */
                }
 
-       } else {    /* need to read the key one byte at a time */
-               const uint8_t *k = (const uint8_t *)key;
+       } else { /* need to read the key one byte at a time */
+               const uint8_t *k = (const uint8_t *) key;
 
                while (length > 12) {
                        a += k[0];
-                       a += ((uint32_t)k[1])<<8;
-                       a += ((uint32_t)k[2])<<16;
-                       a += ((uint32_t)k[3])<<24;
+                       a += ((uint32_t) k[1]) << 8;
+                       a += ((uint32_t) k[2]) << 16;
+                       a += ((uint32_t) k[3]) << 24;
                        b += k[4];
-                       b += ((uint32_t)k[5])<<8;
-                       b += ((uint32_t)k[6])<<16;
-                       b += ((uint32_t)k[7])<<24;
+                       b += ((uint32_t) k[5]) << 8;
+                       b += ((uint32_t) k[6]) << 16;
+                       b += ((uint32_t) k[7]) << 24;
                        c += k[8];
-                       c += ((uint32_t)k[9])<<8;
-                       c += ((uint32_t)k[10])<<16;
-                       c += ((uint32_t)k[11])<<24;
-                       mix(a,b,c);
+                       c += ((uint32_t) k[9]) << 8;
+                       c += ((uint32_t) k[10]) << 16;
+                       c += ((uint32_t) k[11]) << 24;
+                       mix(a, b, c);
                        length -= 12;
                        k += 12;
                }
 
-               switch(length) {                  /* all the case statements fall through */
-               case 12: c+=((uint32_t)k[11])<<24; /* fall through */
-               case 11: c+=((uint32_t)k[10])<<16; /* fall through */
-               case 10: c+=((uint32_t)k[9])<<8; /* fall through */
-               case 9: c+=k[8]; /* fall through */
-               case 8: b+=((uint32_t)k[7])<<24; /* fall through */
-               case 7: b+=((uint32_t)k[6])<<16; /* fall through */
-               case 6: b+=((uint32_t)k[5])<<8; /* fall through */
-               case 5: b+=k[4]; /* fall through */
-               case 4: a+=((uint32_t)k[3])<<24; /* fall through */
-               case 3: a+=((uint32_t)k[2])<<16; /* fall through */
-               case 2: a+=((uint32_t)k[1])<<8; /* fall through */
+               switch (length) { /* all the case statements fall through */
+               case 12:
+                       c += ((uint32_t) k[11]) << 24; /* fall through */
+               case 11:
+                       c += ((uint32_t) k[10]) << 16; /* fall through */
+               case 10:
+                       c += ((uint32_t) k[9]) << 8; /* fall through */
+               case 9:
+                       c += k[8]; /* fall through */
+               case 8:
+                       b += ((uint32_t) k[7]) << 24; /* fall through */
+               case 7:
+                       b += ((uint32_t) k[6]) << 16; /* fall through */
+               case 6:
+                       b += ((uint32_t) k[5]) << 8; /* fall through */
+               case 5:
+                       b += k[4]; /* fall through */
+               case 4:
+                       a += ((uint32_t) k[3]) << 24; /* fall through */
+               case 3:
+                       a += ((uint32_t) k[2]) << 16; /* fall through */
+               case 2:
+                       a += ((uint32_t) k[1]) << 8; /* fall through */
                case 1:
-                       a+=k[0];
+                       a += k[0];
                        break;
                case 0:
                        return c;
                }
        }
 
-       final(a,b,c);
+       final(a, b, c);
        return c;
 }
 
@@ -495,8 +580,7 @@ unsigned long hash_key_str(const void *key, unsigned long seed)
  */
 unsigned long hash_key_two_u64(const void *key, unsigned long seed)
 {
-       const struct lttng_ht_two_u64 *k =
-               (const struct lttng_ht_two_u64 *) key;
+       const struct lttng_ht_two_u64 *k = (const struct lttng_ht_two_u64 *) key;
 
        return hash_key_u64(&k->key1, seed) ^ hash_key_u64(&k->key2, seed);
 }
@@ -542,13 +626,10 @@ int hash_match_key_str(const void *key1, const void *key2)
  */
 int hash_match_key_two_u64(const void *key1, const void *key2)
 {
-       const struct lttng_ht_two_u64 *k1 =
-               (const struct lttng_ht_two_u64 *) key1;
-       const struct lttng_ht_two_u64 *k2 =
-               (const struct lttng_ht_two_u64 *) key2;
+       const struct lttng_ht_two_u64 *k1 = (const struct lttng_ht_two_u64 *) key1;
+       const struct lttng_ht_two_u64 *k2 = (const struct lttng_ht_two_u64 *) key2;
 
-       if (hash_match_key_u64(&k1->key1, &k2->key1) &&
-                       hash_match_key_u64(&k1->key2, &k2->key2)) {
+       if (hash_match_key_u64(&k1->key1, &k2->key1) && hash_match_key_u64(&k1->key2, &k2->key2)) {
                return 1;
        }
 
index 8181eab931c07aa0c131c8157ce85a6584f8d11c..444621f3a94df593c74327f2eff5a940669e0167 100644 (file)
@@ -7,12 +7,6 @@
  */
 
 #define _LGPL_SOURCE
-#include <algorithm>
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
 #include <common/defaults.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
 
 #include <lttng/health-internal.hpp>
 
+#include <algorithm>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
 /*
  * An application-specific error state for unregistered thread keeps
  * track of thread errors. A thread reporting a health error, normally
@@ -44,23 +44,20 @@ struct health_app {
 };
 
 /* Define TLS health state. */
-DEFINE_URCU_TLS(struct health_state, health_state);
+thread_local struct health_state health_state;
 
 /*
  * Initialize health check subsytem.
  */
-static
-void health_init(struct health_app *ha)
+static void health_init(struct health_app *ha)
 {
        /*
         * Get the maximum value between the default delta value and the TCP
         * timeout with a safety net of the default health check delta.
         */
        ha->time_delta.tv_sec = std::max<unsigned long>(
-                       lttcomm_inet_tcp_timeout + DEFAULT_HEALTH_CHECK_DELTA_S,
-                       ha->time_delta.tv_sec);
-       DBG("Health check time delta in seconds set to %lu",
-                       ha->time_delta.tv_sec);
+               lttcomm_inet_tcp_timeout + DEFAULT_HEALTH_CHECK_DELTA_S, ha->time_delta.tv_sec);
+       DBG("Health check time delta in seconds set to %lu", ha->time_delta.tv_sec);
 }
 
 struct health_app *health_app_create(int nr_types)
@@ -69,14 +66,14 @@ struct health_app *health_app_create(int nr_types)
 
        ha = zmalloc<health_app>();
        if (!ha) {
-               return NULL;
+               return nullptr;
        }
        ha->flags = calloc<health_flags>(nr_types);
        if (!ha->flags) {
                goto error_flags;
        }
        CDS_INIT_LIST_HEAD(&ha->list);
-       pthread_mutex_init(&ha->lock, NULL);
+       pthread_mutex_init(&ha->lock, nullptr);
        ha->nr_types = nr_types;
        ha->time_delta.tv_sec = DEFAULT_HEALTH_CHECK_DELTA_S;
        ha->time_delta.tv_nsec = DEFAULT_HEALTH_CHECK_DELTA_NS;
@@ -85,7 +82,7 @@ struct health_app *health_app_create(int nr_types)
 
 error_flags:
        free(ha);
-       return NULL;
+       return nullptr;
 }
 
 void health_app_destroy(struct health_app *ha)
@@ -113,8 +110,8 @@ static void state_unlock(struct health_app *ha)
 /*
  * Set time difference in res from time_a and time_b.
  */
-static void time_diff(const struct timespec *time_a,
-               const struct timespec *time_b, struct timespec *res)
+static void
+time_diff(const struct timespec *time_a, const struct timespec *time_b, struct timespec *res)
 {
        if (time_a->tv_nsec - time_b->tv_nsec < 0) {
                res->tv_sec = time_a->tv_sec - time_b->tv_sec - 1;
@@ -129,7 +126,8 @@ static void time_diff(const struct timespec *time_a,
  * Return true if time_a - time_b > diff, else false.
  */
 static int time_diff_gt(const struct timespec *time_a,
-               const struct timespec *time_b, const struct timespec *diff)
+                       const struct timespec *time_b,
+                       const struct timespec *diff)
 {
        struct timespec res;
 
@@ -189,8 +187,7 @@ static int validate_state(struct health_app *ha, struct health_state *state)
                state->last = current;
                memcpy(&state->last_time, &current_time, sizeof(current_time));
        } else {
-               if (time_diff_gt(&current_time, &state->last_time,
-                               &ha->time_delta)) {
+               if (time_diff_gt(&current_time, &state->last_time, &ha->time_delta)) {
                        if (current == last && !HEALTH_IS_IN_POLL(current)) {
                                /* error */
                                retval = 0;
@@ -207,8 +204,7 @@ static int validate_state(struct health_app *ha, struct health_state *state)
        }
 
 end:
-       DBG("Health state current %lu, last %lu, ret %d",
-                       current, last, ret);
+       DBG("Health state current %lu, last %lu, ret %d", current, last, ret);
        return retval;
 }
 
@@ -228,7 +224,7 @@ int health_check_state(struct health_app *ha, int type)
 
        state_lock(ha);
 
-       cds_list_for_each_entry(state, &ha->list, node) {
+       cds_list_for_each_entry (state, &ha->list, node) {
                int ret;
 
                if (state->type != type) {
@@ -250,8 +246,7 @@ int health_check_state(struct health_app *ha, int type)
 end:
        state_unlock(ha);
 
-       DBG("Health check for type %d is %s", (int) type,
-                       (retval == 0) ? "BAD" : "GOOD");
+       DBG("Health check for type %d is %s", (int) type, (retval == 0) ? "BAD" : "GOOD");
        return retval;
 }
 
@@ -263,16 +258,16 @@ void health_register(struct health_app *ha, int type)
        LTTNG_ASSERT(type < ha->nr_types);
 
        /* Init TLS state. */
-       uatomic_set(&URCU_TLS(health_state).last, 0);
-       uatomic_set(&URCU_TLS(health_state).last_time.tv_sec, 0);
-       uatomic_set(&URCU_TLS(health_state).last_time.tv_nsec, 0);
-       uatomic_set(&URCU_TLS(health_state).current, 0);
-       uatomic_set(&URCU_TLS(health_state).flags, (health_flags) 0);
-       uatomic_set(&URCU_TLS(health_state).type, type);
+       uatomic_set(&health_state.last, 0);
+       uatomic_set(&health_state.last_time.tv_sec, 0);
+       uatomic_set(&health_state.last_time.tv_nsec, 0);
+       uatomic_set(&health_state.current, 0);
+       uatomic_set(&health_state.flags, (health_flags) 0);
+       uatomic_set(&health_state.type, type);
 
        /* Add it to the global TLS state list. */
        state_lock(ha);
-       cds_list_add(&URCU_TLS(health_state).node, &ha->list);
+       cds_list_add(&health_state.node, &ha->list);
        state_unlock(ha);
 }
 
@@ -286,10 +281,9 @@ void health_unregister(struct health_app *ha)
         * On error, set the global_error_state since we are about to remove
         * the node from the global list.
         */
-       if (uatomic_read(&URCU_TLS(health_state).flags) & HEALTH_ERROR) {
-               uatomic_set(&ha->flags[URCU_TLS(health_state).type],
-                               HEALTH_ERROR);
+       if (uatomic_read(&health_state.flags) & HEALTH_ERROR) {
+               uatomic_set(&ha->flags[health_state.type], HEALTH_ERROR);
        }
-       cds_list_del(&URCU_TLS(health_state).node);
+       cds_list_del(&health_state.node);
        state_unlock(ha);
 }
index 32778cd205eae16652af36770d768769db62724f..c0bb8a1c4188d19f7e99cdc341a6b0e165df4117 100644 (file)
@@ -5,16 +5,14 @@
  *
  */
 
-#include <inttypes.h>
+#include "error.hpp"
+#include "index-allocator.hpp"
+#include "macros.hpp"
 
+#include <inttypes.h>
 #include <urcu.h>
 #include <urcu/list.h>
 
-#include "macros.hpp"
-#include "error.hpp"
-
-#include "index-allocator.hpp"
-
 struct lttng_index_allocator {
        struct cds_list_head unused_list;
        uint64_t size;
@@ -29,10 +27,9 @@ struct lttng_index {
 };
 } /* namespace */
 
-struct lttng_index_allocator *lttng_index_allocator_create(
-               uint64_t index_count)
+struct lttng_index_allocator *lttng_index_allocator_create(uint64_t index_count)
 {
-       struct lttng_index_allocator *allocator = NULL;
+       struct lttng_index_allocator *allocator = nullptr;
 
        allocator = zmalloc<lttng_index_allocator>();
        if (!allocator) {
@@ -55,12 +52,10 @@ uint64_t lttng_index_allocator_get_index_count(struct lttng_index_allocator *all
        return allocator->nb_allocated_indexes;
 }
 
-enum lttng_index_allocator_status lttng_index_allocator_alloc(
-               struct lttng_index_allocator *allocator,
-               uint64_t *allocated_index)
+enum lttng_index_allocator_status
+lttng_index_allocator_alloc(struct lttng_index_allocator *allocator, uint64_t *allocated_index)
 {
-       enum lttng_index_allocator_status status =
-                       LTTNG_INDEX_ALLOCATOR_STATUS_OK;
+       enum lttng_index_allocator_status status = LTTNG_INDEX_ALLOCATOR_STATUS_OK;
 
        if (cds_list_empty(&allocator->unused_list)) {
                if (allocator->position >= allocator->size) {
@@ -73,8 +68,7 @@ enum lttng_index_allocator_status lttng_index_allocator_alloc(
        } else {
                struct lttng_index *index;
 
-               index = cds_list_first_entry(&allocator->unused_list,
-                               typeof(*index), head);
+               index = cds_list_first_entry(&allocator->unused_list, typeof(*index), head);
                cds_list_del(&index->head);
                *allocated_index = index->index;
                free(index);
@@ -85,12 +79,11 @@ end:
        return status;
 }
 
-enum lttng_index_allocator_status lttng_index_allocator_release(
-               struct lttng_index_allocator *allocator, uint64_t idx)
+enum lttng_index_allocator_status
+lttng_index_allocator_release(struct lttng_index_allocator *allocator, uint64_t idx)
 {
-       struct lttng_index *index = NULL;
-       enum lttng_index_allocator_status status =
-                       LTTNG_INDEX_ALLOCATOR_STATUS_OK;
+       struct lttng_index *index = nullptr;
+       enum lttng_index_allocator_status status = LTTNG_INDEX_ALLOCATOR_STATUS_OK;
 
        LTTNG_ASSERT(idx < allocator->size);
 
@@ -111,20 +104,18 @@ end:
 
 void lttng_index_allocator_destroy(struct lttng_index_allocator *allocator)
 {
-       struct lttng_index *index = NULL, *tmp_index = NULL;
+       struct lttng_index *index = nullptr, *tmp_index = nullptr;
 
        if (!allocator) {
                return;
        }
 
        if (lttng_index_allocator_get_index_count(allocator) > 0) {
-               WARN("Destroying index allocator with %" PRIu64
-                               " slot indexes still in use",
-                               lttng_index_allocator_get_index_count(allocator));
+               WARN("Destroying index allocator with %" PRIu64 " slot indexes still in use",
+                    lttng_index_allocator_get_index_count(allocator));
        }
 
-       cds_list_for_each_entry_safe(index, tmp_index,
-                       &allocator->unused_list, head) {
+       cds_list_for_each_entry_safe (index, tmp_index, &allocator->unused_list, head) {
                cds_list_del(&index->head);
                free(index);
        }
index ee7c2ec758dd5dd707780b9a42ae5d3c0d4fab6c..2fa34041263d50f8d971ff15c7bcc43e3020a185 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef _COMMON_INDEX_ALLOCATOR_H
 #define _COMMON_INDEX_ALLOCATOR_H
 
-#include <inttypes.h>
 #include <lttng/lttng-export.h>
 
+#include <inttypes.h>
+
 struct lttng_index_allocator;
 
 enum lttng_index_allocator_status {
@@ -22,37 +23,31 @@ enum lttng_index_allocator_status {
 /*
  * Create an index allocator of `index_count` slots.
  */
-extern "C" LTTNG_EXPORT
-struct lttng_index_allocator *lttng_index_allocator_create(
-               uint64_t index_count);
+extern "C" LTTNG_EXPORT struct lttng_index_allocator *
+lttng_index_allocator_create(uint64_t index_count);
 
 /*
  * Get the number of indexes currently in use.
  */
-extern "C" LTTNG_EXPORT
-uint64_t lttng_index_allocator_get_index_count(
-       struct lttng_index_allocator *allocator);
+extern "C" LTTNG_EXPORT uint64_t
+lttng_index_allocator_get_index_count(struct lttng_index_allocator *allocator);
 
 /*
  * Allocate (i.e. reserve) a slot.
  */
-extern "C" LTTNG_EXPORT
-enum lttng_index_allocator_status lttng_index_allocator_alloc(
-               struct lttng_index_allocator *allocator,
-               uint64_t *index);
+extern "C" LTTNG_EXPORT enum lttng_index_allocator_status
+lttng_index_allocator_alloc(struct lttng_index_allocator *allocator, uint64_t *index);
 
 /*
  * Release a slot by index. The slot will be re-used by the index allocator
  * in future 'alloc' calls.
  */
-extern "C" LTTNG_EXPORT
-enum lttng_index_allocator_status lttng_index_allocator_release(
-               struct lttng_index_allocator *allocator, uint64_t index);
+extern "C" LTTNG_EXPORT enum lttng_index_allocator_status
+lttng_index_allocator_release(struct lttng_index_allocator *allocator, uint64_t index);
 
 /*
  * Destroy an index allocator.
  */
-extern "C" LTTNG_EXPORT
-void lttng_index_allocator_destroy(struct lttng_index_allocator *allocator);
+extern "C" LTTNG_EXPORT void lttng_index_allocator_destroy(struct lttng_index_allocator *allocator);
 
 #endif /* _COMMON_INDEX_ALLOCATOR_H */
index 2b9bc54282f12a7127429a12c7fe46895d5627e6..1d7839122aae4d7941c5e96d70d9c04ebdbec4ff 100644 (file)
@@ -13,9 +13,9 @@
 #include <common/compat/endian.hpp>
 #include <common/macros.hpp>
 
-#include <stdint.h>
 #include <limits.h>
 #include <stddef.h>
+#include <stdint.h>
 
 #define CTF_INDEX_MAGIC 0xC1F1DCC1
 #define CTF_INDEX_MAJOR 1
@@ -38,16 +38,16 @@ struct ctf_packet_index_file_hdr {
  * All integer fields are stored in big endian.
  */
 struct ctf_packet_index {
-       uint64_t offset;                /* offset of the packet in the file, in bytes */
-       uint64_t packet_size;           /* packet size, in bits */
-       uint64_t content_size;          /* content size, in bits */
+       uint64_t offset; /* offset of the packet in the file, in bytes */
+       uint64_t packet_size; /* packet size, in bits */
+       uint64_t content_size; /* content size, in bits */
        uint64_t timestamp_begin;
        uint64_t timestamp_end;
        uint64_t events_discarded;
-       uint64_t stream_id;             /* ID of the channel */
+       uint64_t stream_id; /* ID of the channel */
        /* CTF_INDEX 1.0 limit */
-       uint64_t stream_instance_id;    /* ID of the channel instance */
-       uint64_t packet_seq_num;        /* packet sequence number */
+       uint64_t stream_instance_id; /* ID of the channel instance */
+       uint64_t packet_seq_num; /* packet sequence number */
 } __attribute__((__packed__));
 
 static inline size_t ctf_packet_index_len(uint32_t major, uint32_t minor)
@@ -55,13 +55,11 @@ static inline size_t ctf_packet_index_len(uint32_t major, uint32_t minor)
        if (major == 1) {
                switch (minor) {
                case 0:
-                       return offsetof(struct ctf_packet_index, stream_id)
-                               + member_sizeof(struct ctf_packet_index,
-                                               stream_id);
+                       return offsetof(struct ctf_packet_index, stream_id) +
+                               member_sizeof(struct ctf_packet_index, stream_id);
                case 1:
-                       return offsetof(struct ctf_packet_index, packet_seq_num)
-                               + member_sizeof(struct ctf_packet_index,
-                                               packet_seq_num);
+                       return offsetof(struct ctf_packet_index, packet_seq_num) +
+                               member_sizeof(struct ctf_packet_index, packet_seq_num);
                default:
                        abort();
                }
@@ -70,7 +68,7 @@ static inline size_t ctf_packet_index_len(uint32_t major, uint32_t minor)
 }
 
 static inline uint32_t lttng_to_index_major(uint32_t lttng_major,
-               uint32_t lttng_minor __attribute__((unused)))
+                                           uint32_t lttng_minor __attribute__((unused)))
 {
        if (lttng_major == 2) {
                return 1;
@@ -78,8 +76,7 @@ static inline uint32_t lttng_to_index_major(uint32_t lttng_major,
        abort();
 }
 
-static inline uint32_t lttng_to_index_minor(uint32_t lttng_major,
-               uint32_t lttng_minor)
+static inline uint32_t lttng_to_index_minor(uint32_t lttng_major, uint32_t lttng_minor)
 {
        if (lttng_major == 2) {
                if (lttng_minor < 8) {
@@ -91,16 +88,15 @@ static inline uint32_t lttng_to_index_minor(uint32_t lttng_major,
        abort();
 }
 
-static inline void ctf_packet_index_file_hdr_init(
-               struct ctf_packet_index_file_hdr *hdr,
-               uint32_t idx_major, uint32_t idx_minor)
+static inline void ctf_packet_index_file_hdr_init(struct ctf_packet_index_file_hdr *hdr,
+                                                 uint32_t idx_major,
+                                                 uint32_t idx_minor)
 {
        memset(hdr, 0, sizeof(*hdr));
        hdr->magic = htobe32(CTF_INDEX_MAGIC);
        hdr->index_major = htobe32(idx_major);
        hdr->index_minor = htobe32(idx_minor);
-       hdr->packet_index_len = htobe32(
-                       ctf_packet_index_len(idx_major, idx_minor));
+       hdr->packet_index_len = htobe32(ctf_packet_index_len(idx_major, idx_minor));
 }
 
 #endif /* LTTNG_INDEX_H */
index de66ac4bdd3088427fccd5d9a00f0adc5a4a4da9..863a4c52b0d3781f47fd1e4fab144e658fcccbef 100644 (file)
@@ -8,33 +8,39 @@
  */
 
 #define _LGPL_SOURCE
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <fcntl.h>
+#include "index.hpp"
 
-#include <lttng/constant.h>
 #include <common/common.hpp>
-#include <common/defaults.hpp>
 #include <common/compat/endian.hpp>
+#include <common/defaults.hpp>
 #include <common/utils.hpp>
 
-#include "index.hpp"
+#include <lttng/constant.h>
 
-#define WRITE_FILE_FLAGS       (O_WRONLY | O_CREAT | O_TRUNC)
-#define READ_ONLY_FILE_FLAGS   O_RDONLY
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#define WRITE_FILE_FLAGS     (O_WRONLY | O_CREAT | O_TRUNC)
+#define READ_ONLY_FILE_FLAGS O_RDONLY
 
-static enum lttng_trace_chunk_status _lttng_index_file_create_from_trace_chunk(
-               struct lttng_trace_chunk *chunk,
-               const char *channel_path, const char *stream_name,
-               uint64_t stream_file_size, uint64_t stream_file_index,
-               uint32_t index_major, uint32_t index_minor,
-               bool unlink_existing_file,
-               int flags, bool expect_no_file, struct lttng_index_file **file)
+static enum lttng_trace_chunk_status
+_lttng_index_file_create_from_trace_chunk(struct lttng_trace_chunk *chunk,
+                                         const char *channel_path,
+                                         const char *stream_name,
+                                         uint64_t stream_file_size,
+                                         uint64_t stream_file_index,
+                                         uint32_t index_major,
+                                         uint32_t index_minor,
+                                         bool unlink_existing_file,
+                                         int flags,
+                                         bool expect_no_file,
+                                         struct lttng_index_file **file)
 {
        struct lttng_index_file *index_file;
        enum lttng_trace_chunk_status chunk_status;
        int ret;
-       struct fs_handle *fs_handle = NULL;
+       struct fs_handle *fs_handle = nullptr;
        ssize_t size_ret;
        struct ctf_packet_index_file_hdr hdr;
        char index_directory_path[LTTNG_PATH_MAX];
@@ -58,18 +64,24 @@ static enum lttng_trace_chunk_status _lttng_index_file_create_from_trace_chunk(
        } else {
                separator = "/";
        }
-       ret = snprintf(index_directory_path, sizeof(index_directory_path),
-                       "%s%s" DEFAULT_INDEX_DIR, channel_path, separator);
+       ret = snprintf(index_directory_path,
+                      sizeof(index_directory_path),
+                      "%s%s" DEFAULT_INDEX_DIR,
+                      channel_path,
+                      separator);
        if (ret < 0 || ret >= sizeof(index_directory_path)) {
                ERR("Failed to format index directory path");
                chunk_status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto error;
        }
 
-       ret = utils_stream_file_path(index_directory_path, stream_name,
-                       stream_file_size, stream_file_index,
-                       DEFAULT_INDEX_FILE_SUFFIX,
-                       index_file_path, sizeof(index_file_path));
+       ret = utils_stream_file_path(index_directory_path,
+                                    stream_name,
+                                    stream_file_size,
+                                    stream_file_index,
+                                    DEFAULT_INDEX_FILE_SUFFIX,
+                                    index_file_path,
+                                    sizeof(index_file_path));
        if (ret) {
                chunk_status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto error;
@@ -85,16 +97,15 @@ static enum lttng_trace_chunk_status _lttng_index_file_create_from_trace_chunk(
                 * same name afterwards.
                 */
                chunk_status = (lttng_trace_chunk_status) lttng_trace_chunk_unlink_file(
-                               chunk, index_file_path);
+                       chunk, index_file_path);
                if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK &&
-                               !(chunk_status == LTTNG_TRACE_CHUNK_STATUS_ERROR &&
-                                               errno == ENOENT)) {
+                   !(chunk_status == LTTNG_TRACE_CHUNK_STATUS_ERROR && errno == ENOENT)) {
                        goto error;
                }
        }
 
-       chunk_status = lttng_trace_chunk_open_fs_handle(chunk, index_file_path,
-                       flags, mode, &fs_handle, expect_no_file);
+       chunk_status = lttng_trace_chunk_open_fs_handle(
+               chunk, index_file_path, flags, mode, &fs_handle, expect_no_file);
        if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                goto error;
        }
@@ -124,13 +135,15 @@ static enum lttng_trace_chunk_status _lttng_index_file_create_from_trace_chunk(
                }
                if (index_major != be32toh(hdr.index_major)) {
                        ERR("Index major number mismatch: %u, expect %u",
-                               be32toh(hdr.index_major), index_major);
+                           be32toh(hdr.index_major),
+                           index_major);
                        chunk_status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                        goto error;
                }
                if (index_minor != be32toh(hdr.index_minor)) {
                        ERR("Index minor number mismatch: %u, expect %u",
-                               be32toh(hdr.index_minor), index_minor);
+                           be32toh(hdr.index_minor),
+                           index_minor);
                        chunk_status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                        goto error;
                }
@@ -162,30 +175,52 @@ error:
        return chunk_status;
 }
 
-enum lttng_trace_chunk_status lttng_index_file_create_from_trace_chunk(
-               struct lttng_trace_chunk *chunk,
-               const char *channel_path, const char *stream_name,
-               uint64_t stream_file_size, uint64_t stream_file_index,
-               uint32_t index_major, uint32_t index_minor,
-               bool unlink_existing_file, struct lttng_index_file **file)
+enum lttng_trace_chunk_status
+lttng_index_file_create_from_trace_chunk(struct lttng_trace_chunk *chunk,
+                                        const char *channel_path,
+                                        const char *stream_name,
+                                        uint64_t stream_file_size,
+                                        uint64_t stream_file_index,
+                                        uint32_t index_major,
+                                        uint32_t index_minor,
+                                        bool unlink_existing_file,
+                                        struct lttng_index_file **file)
 {
-       return _lttng_index_file_create_from_trace_chunk(chunk, channel_path,
-                       stream_name, stream_file_size, stream_file_index,
-                       index_major, index_minor, unlink_existing_file,
-                       WRITE_FILE_FLAGS, false, file);
+       return _lttng_index_file_create_from_trace_chunk(chunk,
+                                                        channel_path,
+                                                        stream_name,
+                                                        stream_file_size,
+                                                        stream_file_index,
+                                                        index_major,
+                                                        index_minor,
+                                                        unlink_existing_file,
+                                                        WRITE_FILE_FLAGS,
+                                                        false,
+                                                        file);
 }
 
-enum lttng_trace_chunk_status lttng_index_file_create_from_trace_chunk_read_only(
-               struct lttng_trace_chunk *chunk,
-               const char *channel_path, const char *stream_name,
-               uint64_t stream_file_size, uint64_t stream_file_index,
-               uint32_t index_major, uint32_t index_minor,
-               bool expect_no_file, struct lttng_index_file **file)
+enum lttng_trace_chunk_status
+lttng_index_file_create_from_trace_chunk_read_only(struct lttng_trace_chunk *chunk,
+                                                  const char *channel_path,
+                                                  const char *stream_name,
+                                                  uint64_t stream_file_size,
+                                                  uint64_t stream_file_index,
+                                                  uint32_t index_major,
+                                                  uint32_t index_minor,
+                                                  bool expect_no_file,
+                                                  struct lttng_index_file **file)
 {
-       return _lttng_index_file_create_from_trace_chunk(chunk, channel_path,
-                       stream_name, stream_file_size, stream_file_index,
-                       index_major, index_minor, false,
-                       READ_ONLY_FILE_FLAGS, expect_no_file, file);
+       return _lttng_index_file_create_from_trace_chunk(chunk,
+                                                        channel_path,
+                                                        stream_name,
+                                                        stream_file_size,
+                                                        stream_file_index,
+                                                        index_major,
+                                                        index_minor,
+                                                        false,
+                                                        READ_ONLY_FILE_FLAGS,
+                                                        expect_no_file,
+                                                        file);
 }
 
 /*
@@ -194,10 +229,11 @@ enum lttng_trace_chunk_status lttng_index_file_create_from_trace_chunk_read_only
  * Return 0 on success, -1 on error.
  */
 int lttng_index_file_write(const struct lttng_index_file *index_file,
-               const struct ctf_packet_index *element)
+                          const struct ctf_packet_index *element)
 {
        ssize_t ret;
-       const size_t len = index_file->element_len;;
+       const size_t len = index_file->element_len;
+       ;
 
        LTTNG_ASSERT(index_file);
        LTTNG_ASSERT(element);
@@ -223,7 +259,7 @@ error:
  * Return 0 on success, -1 on error.
  */
 int lttng_index_file_read(const struct lttng_index_file *index_file,
-               struct ctf_packet_index *element)
+                         struct ctf_packet_index *element)
 {
        ssize_t ret;
        const size_t len = index_file->element_len;
@@ -256,8 +292,7 @@ void lttng_index_file_get(struct lttng_index_file *index_file)
 
 static void lttng_index_file_release(struct urcu_ref *ref)
 {
-       struct lttng_index_file *index_file = caa_container_of(ref,
-                       struct lttng_index_file, ref);
+       struct lttng_index_file *index_file = caa_container_of(ref, struct lttng_index_file, ref);
 
        if (fs_handle_close(index_file->file)) {
                PERROR("close index fd");
index 00d8203d3db606e2b78b313fa5a9b677fe63bb68..8a6d4b3a0777021353634b0959b4df2970421eff 100644 (file)
 #ifndef _INDEX_H
 #define _INDEX_H
 
-#include <inttypes.h>
-#include <urcu/ref.h>
-
 #include "ctf-index.hpp"
+
 #include <common/fs-handle.hpp>
 #include <common/trace-chunk.hpp>
 
+#include <inttypes.h>
+#include <urcu/ref.h>
+
 struct lttng_index_file {
        struct fs_handle *file;
        uint32_t major;
@@ -30,24 +31,32 @@ struct lttng_index_file {
  * create and open have refcount of 1. Use put to decrement the
  * refcount. Destroys when reaching 0. Use "get" to increment refcount.
  */
-enum lttng_trace_chunk_status lttng_index_file_create_from_trace_chunk(
-               struct lttng_trace_chunk *chunk,
-               const char *channel_path, const char *stream_name,
-               uint64_t stream_file_size, uint64_t stream_count,
-               uint32_t index_major, uint32_t index_minor,
-               bool unlink_existing_file, struct lttng_index_file **file);
-
-enum lttng_trace_chunk_status lttng_index_file_create_from_trace_chunk_read_only(
-               struct lttng_trace_chunk *chunk,
-               const char *channel_path, const char *stream_name,
-               uint64_t stream_file_size, uint64_t stream_file_index,
-               uint32_t index_major, uint32_t index_minor,
-               bool expect_no_file, struct lttng_index_file **file);
+enum lttng_trace_chunk_status
+lttng_index_file_create_from_trace_chunk(struct lttng_trace_chunk *chunk,
+                                        const char *channel_path,
+                                        const char *stream_name,
+                                        uint64_t stream_file_size,
+                                        uint64_t stream_count,
+                                        uint32_t index_major,
+                                        uint32_t index_minor,
+                                        bool unlink_existing_file,
+                                        struct lttng_index_file **file);
+
+enum lttng_trace_chunk_status
+lttng_index_file_create_from_trace_chunk_read_only(struct lttng_trace_chunk *chunk,
+                                                  const char *channel_path,
+                                                  const char *stream_name,
+                                                  uint64_t stream_file_size,
+                                                  uint64_t stream_file_index,
+                                                  uint32_t index_major,
+                                                  uint32_t index_minor,
+                                                  bool expect_no_file,
+                                                  struct lttng_index_file **file);
 
 int lttng_index_file_write(const struct lttng_index_file *index_file,
-               const struct ctf_packet_index *element);
+                          const struct ctf_packet_index *element);
 int lttng_index_file_read(const struct lttng_index_file *index_file,
-               struct ctf_packet_index *element);
+                         struct ctf_packet_index *element);
 
 void lttng_index_file_get(struct lttng_index_file *index_file);
 void lttng_index_file_put(struct lttng_index_file *index_file);
index da204d988c0aa9557979f550080b72384d0d1c28..ebfe153c276c593870df422ea5ea0c9ed6cad81a 100644 (file)
@@ -12,6 +12,7 @@
 #include <common/ini-config/ini.hpp>
 #include <common/macros.hpp>
 #include <common/utils.hpp>
+
 #include <ctype.h>
 
 LTTNG_EXPORT const char *config_str_yes = "yes";
@@ -23,14 +24,16 @@ LTTNG_EXPORT const char *config_str_off = "off";
 
 namespace {
 struct handler_filter_args {
-       const charsection;
+       const char *section;
        config_entry_handler_cb handler;
        void *user_data;
 };
 } /* namespace */
 
 static int config_entry_handler_filter(struct handler_filter_args *args,
-               const char *section, const char *name, const char *value)
+                                      const char *section,
+                                      const char *name,
+                                      const char *value)
 {
        int ret = 0;
        struct config_entry entry = { section, name, value };
@@ -43,7 +46,7 @@ static int config_entry_handler_filter(struct handler_filter_args *args,
        }
 
        if (args->section) {
-               if (strcmp(args->section, section)) {
+               if (strcmp(args->section, section) != 0) {
                        goto end;
                }
        }
@@ -53,12 +56,14 @@ end:
        return ret;
 }
 
-int config_get_section_entries(const char *override_path, const char *section,
-               config_entry_handler_cb handler, void *user_data)
+int config_get_section_entries(const char *override_path,
+                              const char *section,
+                              config_entry_handler_cb handler,
+                              void *user_data)
 {
        int ret = 0;
        const char *path;
-       FILE *config_file = NULL;
+       FILE *config_file = nullptr;
        struct handler_filter_args filter = { section, handler, user_data };
 
        /* First, try system-wide conf. file. */
@@ -72,8 +77,8 @@ int config_get_section_entries(const char *override_path, const char *section,
                 * continue and try the next possible conf. file.
                 */
                (void) ini_parse_file(config_file,
-                               (ini_entry_handler) config_entry_handler_filter,
-                               (void *) &filter);
+                                     (ini_entry_handler) config_entry_handler_filter,
+                                     (void *) &filter);
                fclose(config_file);
        }
 
@@ -82,8 +87,7 @@ int config_get_section_entries(const char *override_path, const char *section,
        if (path) {
                char fullpath[PATH_MAX];
 
-               ret = snprintf(fullpath, sizeof(fullpath),
-                               DEFAULT_DAEMON_HOME_CONFIGPATH, path);
+               ret = snprintf(fullpath, sizeof(fullpath), DEFAULT_DAEMON_HOME_CONFIGPATH, path);
                if (ret < 0) {
                        PERROR("snprintf user conf. path");
                        goto error;
@@ -97,8 +101,8 @@ int config_get_section_entries(const char *override_path, const char *section,
                         * continue and try the next possible conf. file.
                         */
                        (void) ini_parse_file(config_file,
-                                       (ini_entry_handler) config_entry_handler_filter,
-                                       (void *) &filter);
+                                             (ini_entry_handler) config_entry_handler_filter,
+                                             (void *) &filter);
                        fclose(config_file);
                }
        }
@@ -109,12 +113,11 @@ int config_get_section_entries(const char *override_path, const char *section,
                if (config_file) {
                        DBG("Loading daemon command line conf file at %s", override_path);
                        (void) ini_parse_file(config_file,
-                                       (ini_entry_handler) config_entry_handler_filter,
-                                       (void *) &filter);
+                                             (ini_entry_handler) config_entry_handler_filter,
+                                             (void *) &filter);
                        fclose(config_file);
                } else {
-                       ERR("Failed to open daemon configuration file at %s",
-                               override_path);
+                       ERR("Failed to open daemon configuration file at %s", override_path);
                        ret = -ENOENT;
                        goto error;
                }
@@ -157,13 +160,11 @@ int config_parse_value(const char *value)
                lower_str[i] = tolower(value[i]);
        }
 
-       if (!strcmp(lower_str, config_str_yes) ||
-               !strcmp(lower_str, config_str_true) ||
-               !strcmp(lower_str, config_str_on)) {
+       if (!strcmp(lower_str, config_str_yes) || !strcmp(lower_str, config_str_true) ||
+           !strcmp(lower_str, config_str_on)) {
                ret = 1;
-       } else if (!strcmp(lower_str, config_str_no) ||
-               !strcmp(lower_str, config_str_false) ||
-               !strcmp(lower_str, config_str_off)) {
+       } else if (!strcmp(lower_str, config_str_no) || !strcmp(lower_str, config_str_false) ||
+                  !strcmp(lower_str, config_str_off)) {
                ret = 0;
        } else {
                ret = -1;
index 3e4160596d339c18c8f9328a8910d0eb552a34df..3e6c85187551d3e6334366c781fadc0e2470e636 100644 (file)
@@ -25,7 +25,7 @@ struct config_entry {
  * config_entry_handler_cb may return negative value to indicate an error in
  * the configuration file.
  */
-typedef int (*config_entry_handler_cb)(const struct config_entry *, void *);
+using config_entry_handler_cb = int (*)(const struct config_entry *, void *);
 
 /*
  * Read a section's entries in an INI configuration file.
@@ -41,8 +41,10 @@ typedef int (*config_entry_handler_cb)(const struct config_entry *, void *);
  * Returns 0 on success. Negative values are error codes. If the return value
  * is positive, it represents the line number on which a parsing error occurred.
  */
-int config_get_section_entries(const char *path, const char *section,
-               config_entry_handler_cb handler, void *user_data);
+int config_get_section_entries(const char *path,
+                              const char *section,
+                              config_entry_handler_cb handler,
+                              void *user_data);
 
 /*
  * Parse a configuration value.
index ec5a41119e87c17f66b47d3656909ed670c11ea4..c17a8c0e8684b8d887b799abced290390775e989 100644 (file)
  * http://code.google.com/p/inih/
  */
 
-#include <stdio.h>
-#include <ctype.h>
-#include <string.h>
+#include "ini.hpp"
+
 #include <common/common.hpp>
 
-#include "ini.hpp"
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
 
 #if !INI_USE_STACK
 #include <stdlib.h>
 #endif
 
 #define MAX_SECTION 50
-#define MAX_NAME 50
+#define MAX_NAME    50
 
 /* Strip whitespace chars off end of given string, in place. Return s. */
-static char* rstrip(char* s)
+static char *rstrip(char *s)
 {
-       charp = s + strlen(s);
+       char *p = s + strlen(s);
 
-       while (p > s && isspace((unsigned char)(*--p)))
+       while (p > s && isspace((unsigned char) (*--p)))
                *p = '\0';
        return s;
 }
 
 /* Return pointer to first non-whitespace char in given string. */
-static char* lskip(const char* s)
+static char *lskip(const char *s)
 {
-       while (*s && isspace((unsigned char)(*s)))
+       while (*s && isspace((unsigned char) (*s)))
                s++;
-       return (char*)s;
+       return (char *) s;
 }
 
 /*
@@ -70,19 +71,19 @@ static char* lskip(const char* s)
  * null at end of string if neither found. ';' must be prefixed by a whitespace
  * character to register as a comment.
  */
-static char* find_char_or_comment(const char* s, char c)
+static char *find_char_or_comment(const char *s, char c)
 {
        int was_whitespace = 0;
 
        while (*s && *s != c && !(was_whitespace && *s == ';')) {
-               was_whitespace = isspace((unsigned char)(*s));
+               was_whitespace = isspace((unsigned char) (*s));
                s++;
        }
-       return (char*)s;
+       return (char *) s;
 }
 
 /* Version of strncpy that ensures dest (size bytes) is null-terminated. */
-static char* strncpy0(char* dest, const char* src, size_t size)
+static char *strncpy0(char *dest, const char *src, size_t size)
 {
        strncpy(dest, src, size - 1);
        dest[size - 1] = '\0';
@@ -90,21 +91,21 @@ static char* strncpy0(char* dest, const char* src, size_t size)
 }
 
 /* See documentation in header file. */
-int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
+int ini_parse_file(FILE *file, ini_entry_handler handler, void *user)
 {
        /* Uses a fair bit of stack (use heap instead if you need to) */
 #if INI_USE_STACK
        char line[INI_MAX_LINE];
 #else
-       charline;
+       char *line;
 #endif
        char section[MAX_SECTION] = "";
        char prev_name[MAX_NAME] = "";
 
-       charstart;
-       charend;
-       charname;
-       charvalue;
+       char *start;
+       char *end;
+       char *name;
+       char *value;
        int lineno = 0;
        int error = 0;
 
@@ -116,14 +117,13 @@ int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
 #endif
 
        /* Scan through file line by line */
-       while (fgets(line, INI_MAX_LINE, file) != NULL) {
+       while (fgets(line, INI_MAX_LINE, file) != nullptr) {
                lineno++;
 
                start = line;
 #if INI_ALLOW_BOM
-               if (lineno == 1 && (unsigned char)start[0] == 0xEF &&
-                       (unsigned char)start[1] == 0xBB &&
-                       (unsigned char)start[2] == 0xBF) {
+               if (lineno == 1 && (unsigned char) start[0] == 0xEF &&
+                   (unsigned char) start[1] == 0xBB && (unsigned char) start[2] == 0xBF) {
                        start += 3;
                }
 #endif
@@ -141,8 +141,7 @@ int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
                         * continuation of previous name's value
                         * (as per Python ConfigParser).
                         */
-                       if (handler(user, section, prev_name, start) < 0 &&
-                               !error) {
+                       if (handler(user, section, prev_name, start) < 0 && !error) {
                                error = lineno;
                        }
                }
@@ -154,13 +153,11 @@ int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
                                *end = '\0';
                                strncpy0(section, start + 1, sizeof(section));
                                *prev_name = '\0';
-                       }
-                       else if (!error) {
+                       } else if (!error) {
                                /* No ']' found on section line */
                                error = lineno;
                        }
-               }
-               else if (*start && *start != ';') {
+               } else if (*start && *start != ';') {
                        /* Not a comment, must be a name[=:]value pair */
                        end = find_char_or_comment(start, '=');
                        if (*end != '=') {
@@ -181,13 +178,15 @@ int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
                                 * Valid name[=:]value pair found, call
                                 * handler
                                 */
+                               if (strlen(name) >= sizeof(prev_name)) {
+                                       /* Truncation occurs, report an error. */
+                                       error = lineno;
+                               }
                                strncpy0(prev_name, name, sizeof(prev_name));
-                               if (handler(user, section, name, value) < 0 &&
-                                       !error) {
+                               if (handler(user, section, name, value) < 0 && !error) {
                                        error = lineno;
                                }
-                       }
-                       else if (!error) {
+                       } else if (!error) {
                                /* No '=' or ':' found on name[=:]value line */
                                error = lineno;
                        }
@@ -202,9 +201,9 @@ int ini_parse_file(FILE* file, ini_entry_handler handler, void* user)
 }
 
 /* See documentation in header file. */
-int ini_parse(const char* filename, ini_entry_handler handler, void* user)
+int ini_parse(const char *filename, ini_entry_handler handler, void *user)
 {
-       FILEfile;
+       FILE *file;
        int error;
 
        file = fopen(filename, "r");
index 34b3654eae7b78e933aa1e3bc20287fca193f072..c91f686763776413fad4f242741abb3f641fdd4e 100644 (file)
@@ -39,8 +39,7 @@
 /* Make this header file easier to include in C++ code */
 #include <stdio.h>
 
-typedef int (*ini_entry_handler)(void *, const char *, const char *,
-               const char *);
+using ini_entry_handler = int (*)(void *, const char *, const char *, const char *);
 
 /*
  * Parse given INI-style file. May have [section]s, name=value pairs
diff --git a/src/common/io-hint.cpp b/src/common/io-hint.cpp
new file mode 100644 (file)
index 0000000..2bb9246
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2023 Michael Jeanson <mjeanson@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include <common/error.hpp>
+#include <common/io-hint.hpp>
+#include <common/scope-exit.hpp>
+
+#include <cinttypes>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+/*
+ * Use sync_file_range when available.
+ */
+#ifdef HAVE_SYNC_FILE_RANGE
+
+#include <fcntl.h>
+
+namespace {
+int flush_range(int fd, off_t offset, off_t nbytes, unsigned int flags)
+{
+       int ret;
+
+       ret = sync_file_range(fd, offset, nbytes, flags);
+       if (ret) {
+               PERROR("Failed to sync file range: fd=%i, offset=%" PRIu64 ", nbytes=%" PRIu64
+                      ", flags=%i",
+                      fd,
+                      static_cast<uint64_t>(offset),
+                      static_cast<uint64_t>(nbytes),
+                      flags);
+       }
+
+       return ret;
+}
+
+int flush_range_sync(int fd, off_t offset, off_t nbytes)
+{
+       return flush_range(fd,
+                          offset,
+                          nbytes,
+                          SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE |
+                                  SYNC_FILE_RANGE_WAIT_AFTER);
+}
+
+int flush_range_async(int fd, off_t offset, off_t nbytes)
+{
+       return flush_range(fd, offset, nbytes, SYNC_FILE_RANGE_WRITE);
+}
+} /* namespace */
+
+#else /* HAVE_SYNC_FILE_RANGE */
+
+namespace {
+/*
+ * Use a memory mapping with msync() to emulate sync_file_range().
+ */
+int flush_range(int fd, off_t offset, off_t nbytes, int flags)
+{
+       void *mapped_region = mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
+       if (mapped_region == MAP_FAILED) {
+               PERROR("Failed to mmap region to flush range: fd=%i, offset=%" PRIu64
+                      ", nbytes=%" PRIu64 ", flags=%i",
+                      fd,
+                      static_cast<uint64_t>(offset),
+                      static_cast<uint64_t>(nbytes),
+                      flags);
+               return -1;
+       }
+
+       const auto munmap_on_exit = lttng::make_scope_exit([&]() noexcept {
+               const auto munmap_ret = munmap(mapped_region, nbytes);
+               if (munmap_ret) {
+                       PERROR("Failed to munmap region while flushing range: fd=%i, offset=%" PRIu64
+                              ", nbytes=%" PRIu64 ", flags=%i",
+                              fd,
+                              static_cast<uint64_t>(offset),
+                              static_cast<uint64_t>(nbytes),
+                              flags);
+               }
+       });
+
+       const auto msync_ret = msync(mapped_region, nbytes, flags);
+       if (msync_ret) {
+               PERROR("Failed to msync region while flushing range: fd=%i, offset=%" PRIu64
+                      ", nbytes=%" PRIu64 ", flags=%i",
+                      fd,
+                      static_cast<uint64_t>(offset),
+                      static_cast<uint64_t>(nbytes),
+                      flags);
+               return -1;
+       }
+
+       return 0;
+}
+
+int flush_range_sync(int fd, off_t offset, off_t nbytes)
+{
+       return flush_range(fd, offset, nbytes, MS_SYNC);
+}
+
+int flush_range_async(int fd, off_t offset, off_t nbytes)
+{
+       return flush_range(fd, offset, nbytes, MS_ASYNC);
+}
+} /* namespace */
+#endif /* !HAVE_SYNC_FILE_RANGE */
+
+/*
+ * Use posix_fadvise when available.
+ */
+#ifdef HAVE_POSIX_FADVISE
+namespace {
+int hint_dont_need(int fd, off_t offset, off_t nbytes)
+{
+       const int ret = posix_fadvise(fd, offset, nbytes, POSIX_FADV_DONTNEED);
+       if (ret && ret != -ENOSYS) {
+               PERROR("Failed to mark region as DONTNEED with posix_fadvise: fd=%i, offset=%" PRIu64
+                      ", nbytes=%" PRIu64,
+                      fd,
+                      static_cast<uint64_t>(offset),
+                      static_cast<uint64_t>(nbytes));
+               errno = ret;
+       }
+
+       return ret;
+}
+} /* namespace */
+
+#else /* HAVE_POSIX_FADVISE */
+
+/*
+ * Generic noop compat for platforms wihtout posix_fadvise, this is acceptable
+ * since we are only giving a hint to the kernel.
+ */
+namespace {
+int hint_dont_need(int fd __attribute__((unused)),
+                  off_t offset __attribute__((unused)),
+                  off_t nbytes __attribute__((unused)))
+{
+       return 0;
+}
+} /* namespace */
+#endif /* !HAVE_POSIX_FADVISE */
+
+/*
+ * Give a hint to the kernel that we won't need the data at the specified range
+ * so it can be dropped from the page cache and wait for it to be flushed to
+ * disk.
+ */
+void lttng::io::hint_flush_range_dont_need_sync(int fd, off_t offset, off_t nbytes)
+{
+       /* Waited for the page writeback to complete. */
+       flush_range_sync(fd, offset, nbytes);
+
+       /*
+        * Give hints to the kernel about how we access the file:
+        * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
+        * we write it.
+        *
+        * We need to call fadvise again after the file grows because the
+        * kernel does not seem to apply fadvise to non-existing parts of the
+        * file.
+        *
+        * Call fadvise _after_ having waited for the page writeback to
+        * complete because the dirty page writeback semantic is not well
+        * defined. So it can be expected to lead to lower throughput in
+        * streaming.
+        */
+       hint_dont_need(fd, offset, nbytes);
+}
+
+/*
+ * Give a hint to the kernel that the data at the specified range should be
+ * flushed to disk and wait for it to complete.
+ */
+void lttng::io::hint_flush_range_sync(int fd, off_t offset, off_t nbytes)
+{
+       flush_range_sync(fd, offset, nbytes);
+}
+
+/*
+ * Give a hint to the kernel that the data at the specified range should be
+ * flushed to disk and return immediatly.
+ */
+void lttng::io::hint_flush_range_async(int fd, off_t offset, off_t nbytes)
+{
+       flush_range_async(fd, offset, nbytes);
+}
diff --git a/src/common/io-hint.hpp b/src/common/io-hint.hpp
new file mode 100644 (file)
index 0000000..a9efb65
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2023 Michael Jeanson <mjeanson@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef _LTTNG_IO_HINT_H
+#define _LTTNG_IO_HINT_H
+
+#include <sys/types.h>
+
+namespace lttng {
+namespace io {
+
+void hint_flush_range_dont_need_sync(int fd, off_t offset, off_t nbytes);
+void hint_flush_range_sync(int fd, off_t offset, off_t nbytes);
+void hint_flush_range_async(int fd, off_t offset, off_t nbytes);
+
+} /* namespace io */
+} /* namespace lttng */
+
+#endif
index 9bc66a47880d82247644ba8e1b6c4ba7c707253d..7e8de03f6b1380ca46eaf31c02ce5682b5f20e81 100644 (file)
@@ -8,37 +8,38 @@
  */
 
 #define _LGPL_SOURCE
-#include <poll.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <inttypes.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <stdint.h>
+#include "kernel-consumer.hpp"
 
-#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <common/buffer-view.hpp>
 #include <common/common.hpp>
-#include <common/kernel-ctl/kernel-ctl.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/sessiond-comm/relayd.hpp>
-#include <common/compat/fcntl.hpp>
 #include <common/compat/endian.hpp>
-#include <common/pipe.hpp>
-#include <common/relayd/relayd.hpp>
-#include <common/utils.hpp>
 #include <common/consumer/consumer-stream.hpp>
-#include <common/index/index.hpp>
 #include <common/consumer/consumer-timer.hpp>
-#include <common/optional.hpp>
-#include <common/buffer-view.hpp>
 #include <common/consumer/consumer.hpp>
 #include <common/consumer/metadata-bucket.hpp>
+#include <common/index/index.hpp>
+#include <common/kernel-ctl/kernel-ctl.hpp>
+#include <common/optional.hpp>
+#include <common/pipe.hpp>
+#include <common/relayd/relayd.hpp>
+#include <common/sessiond-comm/relayd.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
 
-#include "kernel-consumer.hpp"
+#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 extern struct lttng_consumer_global_data the_consumer_data;
 extern int consumer_poll_timeout;
@@ -70,8 +71,7 @@ int lttng_kconsumer_take_snapshot(struct lttng_consumer_stream *stream)
  *
  * Returns 0 on success, < 0 on error.
  */
-int lttng_kconsumer_sample_snapshot_positions(
-               struct lttng_consumer_stream *stream)
+int lttng_kconsumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
 {
        LTTNG_ASSERT(stream);
 
@@ -83,8 +83,7 @@ int lttng_kconsumer_sample_snapshot_positions(
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_kconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos)
+int lttng_kconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
 {
        int ret;
        int infd = stream->wait_fd;
@@ -102,8 +101,7 @@ int lttng_kconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_kconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos)
+int lttng_kconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
 {
        int ret;
        int infd = stream->wait_fd;
@@ -116,9 +114,7 @@ int lttng_kconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
        return ret;
 }
 
-static
-int get_current_subbuf_addr(struct lttng_consumer_stream *stream,
-               const char **addr)
+static int get_current_subbuf_addr(struct lttng_consumer_stream *stream, const char **addr)
 {
        int ret;
        unsigned long mmap_offset;
@@ -142,10 +138,11 @@ error:
  *
  * Returns 0 on success, < 0 on error
  */
-static int lttng_kconsumer_snapshot_channel(
-               struct lttng_consumer_channel *channel,
-               uint64_t key, char *path, uint64_t relayd_id,
-               uint64_t nb_packets_per_stream)
+static int lttng_kconsumer_snapshot_channel(struct lttng_consumer_channel *channel,
+                                           uint64_t key,
+                                           char *path,
+                                           uint64_t relayd_id,
+                                           uint64_t nb_packets_per_stream)
 {
        int ret;
        struct lttng_consumer_stream *stream;
@@ -155,17 +152,17 @@ static int lttng_kconsumer_snapshot_channel(
        /* Prevent channel modifications while we perform the snapshot.*/
        pthread_mutex_lock(&channel->lock);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        /* Splice is not supported yet for channel snapshot. */
        if (channel->output != CONSUMER_CHANNEL_MMAP) {
                ERR("Unsupported output type for channel \"%s\": mmap output is required to record a snapshot",
-                               channel->name);
+                   channel->name);
                ret = -1;
                goto end;
        }
 
-       cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
+       cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
                unsigned long consumed_pos, produced_pos;
 
                health_code_update();
@@ -198,16 +195,14 @@ static int lttng_kconsumer_snapshot_channel(
                        ret = consumer_send_relayd_stream(stream, path);
                        if (ret < 0) {
                                ERR("sending stream to relayd");
-                               goto end_unlock;
+                               goto error_close_stream_output;
                        }
                } else {
-                       ret = consumer_stream_create_output_files(stream,
-                                       false);
+                       ret = consumer_stream_create_output_files(stream, false);
                        if (ret < 0) {
-                               goto end_unlock;
+                               goto error_close_stream_output;
                        }
-                       DBG("Kernel consumer snapshot stream (%" PRIu64 ")",
-                                       stream->key);
+                       DBG("Kernel consumer snapshot stream (%" PRIu64 ")", stream->key);
                }
 
                ret = kernctl_buffer_flush_empty(stream->wait_fd);
@@ -222,7 +217,7 @@ static int lttng_kconsumer_snapshot_channel(
                        ret = kernctl_buffer_flush(stream->wait_fd);
                        if (ret < 0) {
                                ERR("Failed to flush kernel stream");
-                               goto end_unlock;
+                               goto error_close_stream_output;
                        }
                        goto end_unlock;
                }
@@ -230,24 +225,23 @@ static int lttng_kconsumer_snapshot_channel(
                ret = lttng_kconsumer_take_snapshot(stream);
                if (ret < 0) {
                        ERR("Taking kernel snapshot");
-                       goto end_unlock;
+                       goto error_close_stream_output;
                }
 
                ret = lttng_kconsumer_get_produced_snapshot(stream, &produced_pos);
                if (ret < 0) {
                        ERR("Produced kernel snapshot position");
-                       goto end_unlock;
+                       goto error_close_stream_output;
                }
 
                ret = lttng_kconsumer_get_consumed_snapshot(stream, &consumed_pos);
                if (ret < 0) {
                        ERR("Consumerd kernel snapshot position");
-                       goto end_unlock;
+                       goto error_close_stream_output;
                }
 
-               consumed_pos = consumer_get_consume_start_pos(consumed_pos,
-                               produced_pos, nb_packets_per_stream,
-                               stream->max_sb_size);
+               consumed_pos = consumer_get_consume_start_pos(
+                       consumed_pos, produced_pos, nb_packets_per_stream, stream->max_sb_size);
 
                while ((long) (consumed_pos - produced_pos) < 0) {
                        ssize_t read_len;
@@ -262,7 +256,7 @@ static int lttng_kconsumer_snapshot_channel(
                        if (ret < 0) {
                                if (ret != -EAGAIN) {
                                        PERROR("kernctl_get_subbuf snapshot");
-                                       goto end_unlock;
+                                       goto error_close_stream_output;
                                }
                                DBG("Kernel consumer get subbuf failed. Skipping it.");
                                consumed_pos += stream->max_sb_size;
@@ -287,11 +281,9 @@ static int lttng_kconsumer_snapshot_channel(
                                goto error_put_subbuf;
                        }
 
-                       subbuf_view = lttng_buffer_view_init(
-                                       subbuf_addr, 0, padded_len);
+                       subbuf_view = lttng_buffer_view_init(subbuf_addr, 0, padded_len);
                        read_len = lttng_consumer_on_read_subbuffer_mmap(
-                                       stream, &subbuf_view,
-                                       padded_len - len);
+                               stream, &subbuf_view, padded_len - len);
                        /*
                         * We write the padded len in local tracefiles but the data len
                         * when using a relay. Display the error but continue processing
@@ -300,38 +292,26 @@ static int lttng_kconsumer_snapshot_channel(
                        if (relayd_id != (uint64_t) -1ULL) {
                                if (read_len != len) {
                                        ERR("Error sending to the relay (ret: %zd != len: %lu)",
-                                                       read_len, len);
+                                           read_len,
+                                           len);
                                }
                        } else {
                                if (read_len != padded_len) {
                                        ERR("Error writing to tracefile (ret: %zd != len: %lu)",
-                                                       read_len, padded_len);
+                                           read_len,
+                                           padded_len);
                                }
                        }
 
                        ret = kernctl_put_subbuf(stream->wait_fd);
                        if (ret < 0) {
                                ERR("Snapshot kernctl_put_subbuf");
-                               goto end_unlock;
+                               goto error_close_stream_output;
                        }
                        consumed_pos += stream->max_sb_size;
                }
 
-               if (relayd_id == (uint64_t) -1ULL) {
-                       if (stream->out_fd >= 0) {
-                               ret = close(stream->out_fd);
-                               if (ret < 0) {
-                                       PERROR("Kernel consumer snapshot close out_fd");
-                                       goto end_unlock;
-                               }
-                               stream->out_fd = -1;
-                       }
-               } else {
-                       close_relayd_stream(stream);
-                       stream->net_seq_idx = (uint64_t) -1ULL;
-               }
-               lttng_trace_chunk_put(stream->trace_chunk);
-               stream->trace_chunk = NULL;
+               consumer_stream_close_output(stream);
                pthread_mutex_unlock(&stream->lock);
        }
 
@@ -344,10 +324,11 @@ error_put_subbuf:
        if (ret < 0) {
                ERR("Snapshot kernctl_put_subbuf error path");
        }
+error_close_stream_output:
+       consumer_stream_close_output(stream);
 end_unlock:
        pthread_mutex_unlock(&stream->lock);
 end:
-       rcu_read_unlock();
        pthread_mutex_unlock(&channel->lock);
        return ret;
 }
@@ -359,10 +340,11 @@ end:
  *
  * Returns 0 on success, < 0 on error
  */
-static int lttng_kconsumer_snapshot_metadata(
-               struct lttng_consumer_channel *metadata_channel,
-               uint64_t key, char *path, uint64_t relayd_id,
-               struct lttng_consumer_local_data *ctx)
+static int lttng_kconsumer_snapshot_metadata(struct lttng_consumer_channel *metadata_channel,
+                                            uint64_t key,
+                                            char *path,
+                                            uint64_t relayd_id,
+                                            struct lttng_consumer_local_data *ctx)
 {
        int ret, use_relayd = 0;
        ssize_t ret_read;
@@ -370,10 +352,9 @@ static int lttng_kconsumer_snapshot_metadata(
 
        LTTNG_ASSERT(ctx);
 
-       DBG("Kernel consumer snapshot metadata with key %" PRIu64 " at path %s",
-                       key, path);
+       DBG("Kernel consumer snapshot metadata with key %" PRIu64 " at path %s", key, path);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        metadata_stream = metadata_channel->metadata_stream;
        LTTNG_ASSERT(metadata_stream);
@@ -393,8 +374,7 @@ static int lttng_kconsumer_snapshot_metadata(
                        goto error_snapshot;
                }
        } else {
-               ret = consumer_stream_create_output_files(metadata_stream,
-                               false);
+               ret = consumer_stream_create_output_files(metadata_stream, false);
                if (ret < 0) {
                        goto error_snapshot;
                }
@@ -405,8 +385,7 @@ static int lttng_kconsumer_snapshot_metadata(
 
                ret_read = lttng_consumer_read_subbuffer(metadata_stream, ctx, true);
                if (ret_read < 0) {
-                       ERR("Kernel snapshot reading metadata subbuffer (ret: %zd)",
-                                       ret_read);
+                       ERR("Kernel snapshot reading metadata subbuffer (ret: %zd)", ret_read);
                        ret = ret_read;
                        goto error_snapshot;
                }
@@ -427,16 +406,15 @@ static int lttng_kconsumer_snapshot_metadata(
                        }
                        metadata_stream->out_fd = -1;
                        lttng_trace_chunk_put(metadata_stream->trace_chunk);
-                       metadata_stream->trace_chunk = NULL;
+                       metadata_stream->trace_chunk = nullptr;
                }
        }
 
        ret = 0;
 error_snapshot:
        metadata_stream->read_subbuffer_ops.unlock(metadata_stream);
-       consumer_stream_destroy(metadata_stream, NULL);
-       metadata_channel->metadata_stream = NULL;
-       rcu_read_unlock();
+       consumer_stream_destroy(metadata_stream, nullptr);
+       metadata_channel->metadata_stream = nullptr;
        return ret;
 }
 
@@ -446,7 +424,8 @@ error_snapshot:
  * Return 1 on success else a negative value or 0.
  */
 int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll)
+                            int sock,
+                            struct pollfd *consumer_sockpoll)
 {
        int ret_func;
        enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
@@ -460,8 +439,7 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                ret_recv = lttcomm_recv_unix_sock(sock, &msg, sizeof(msg));
                if (ret_recv != sizeof(msg)) {
                        if (ret_recv > 0) {
-                               lttng_consumer_send_error(ctx,
-                                               LTTCOMM_CONSUMERD_ERROR_RECV_CMD);
+                               lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_CMD);
                                ret_recv = -1;
                        }
                        return ret_recv;
@@ -476,22 +454,27 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
        health_code_update();
 
        /* relayd needs RCU read-side protection */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        switch (msg.cmd_type) {
        case LTTNG_CONSUMER_ADD_RELAYD_SOCKET:
        {
                uint32_t major = msg.u.relayd_sock.major;
                uint32_t minor = msg.u.relayd_sock.minor;
-               enum lttcomm_sock_proto protocol = (enum lttcomm_sock_proto)
-                               msg.u.relayd_sock.relayd_socket_protocol;
+               enum lttcomm_sock_proto protocol =
+                       (enum lttcomm_sock_proto) msg.u.relayd_sock.relayd_socket_protocol;
 
                /* Session daemon status message are handled in the following call. */
                consumer_add_relayd_socket(msg.u.relayd_sock.net_index,
-                               msg.u.relayd_sock.type, ctx, sock,
-                               consumer_sockpoll, msg.u.relayd_sock.session_id,
-                               msg.u.relayd_sock.relayd_session_id, major,
-                               minor, protocol);
+                                          msg.u.relayd_sock.type,
+                                          ctx,
+                                          sock,
+                                          consumer_sockpoll,
+                                          msg.u.relayd_sock.session_id,
+                                          msg.u.relayd_sock.relayd_session_id,
+                                          major,
+                                          minor,
+                                          protocol);
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_ADD_CHANNEL:
@@ -513,19 +496,22 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                DBG("consumer_add_channel %" PRIu64, msg.u.channel.channel_key);
                new_channel = consumer_allocate_channel(msg.u.channel.channel_key,
-                               msg.u.channel.session_id,
-                               msg.u.channel.chunk_id.is_set ?
-                                               &chunk_id : NULL,
-                               msg.u.channel.pathname,
-                               msg.u.channel.name,
-                               msg.u.channel.relayd_id, msg.u.channel.output,
-                               msg.u.channel.tracefile_size,
-                               msg.u.channel.tracefile_count, 0,
-                               msg.u.channel.monitor,
-                               msg.u.channel.live_timer_interval,
-                               msg.u.channel.is_live,
-                               NULL, NULL);
-               if (new_channel == NULL) {
+                                                       msg.u.channel.session_id,
+                                                       msg.u.channel.chunk_id.is_set ? &chunk_id :
+                                                                                       nullptr,
+                                                       msg.u.channel.pathname,
+                                                       msg.u.channel.name,
+                                                       msg.u.channel.relayd_id,
+                                                       msg.u.channel.output,
+                                                       msg.u.channel.tracefile_size,
+                                                       msg.u.channel.tracefile_count,
+                                                       0,
+                                                       msg.u.channel.monitor,
+                                                       msg.u.channel.live_timer_interval,
+                                                       msg.u.channel.is_live,
+                                                       nullptr,
+                                                       nullptr);
+               if (new_channel == nullptr) {
                        lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_OUTFD_ERROR);
                        goto end_nosignal;
                }
@@ -555,29 +541,23 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                health_code_update();
 
-               if (ctx->on_recv_channel != NULL) {
-                       int ret_recv_channel =
-                                       ctx->on_recv_channel(new_channel);
+               if (ctx->on_recv_channel != nullptr) {
+                       int ret_recv_channel = ctx->on_recv_channel(new_channel);
                        if (ret_recv_channel == 0) {
-                               ret_add_channel = consumer_add_channel(
-                                               new_channel, ctx);
+                               ret_add_channel = consumer_add_channel(new_channel, ctx);
                        } else if (ret_recv_channel < 0) {
                                goto end_nosignal;
                        }
                } else {
-                       ret_add_channel =
-                                       consumer_add_channel(new_channel, ctx);
+                       ret_add_channel = consumer_add_channel(new_channel, ctx);
                }
-               if (msg.u.channel.type == CONSUMER_CHANNEL_TYPE_DATA &&
-                               !ret_add_channel) {
+               if (msg.u.channel.type == CONSUMER_CHANNEL_TYPE_DATA && !ret_add_channel) {
                        int monitor_start_ret;
 
                        DBG("Consumer starting monitor timer");
-                       consumer_timer_live_start(new_channel,
-                                       msg.u.channel.live_timer_interval);
+                       consumer_timer_live_start(new_channel, msg.u.channel.live_timer_interval);
                        monitor_start_ret = consumer_timer_monitor_start(
-                                       new_channel,
-                                       msg.u.channel.monitor_timer_interval);
+                               new_channel, msg.u.channel.monitor_timer_interval);
                        if (monitor_start_ret < 0) {
                                ERR("Starting channel monitoring timer failed");
                                goto end_nosignal;
@@ -588,8 +568,7 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                /* If we received an error in add_channel, we need to report it. */
                if (ret_add_channel < 0) {
-                       ret_send_status = consumer_send_status_msg(
-                                       sock, ret_add_channel);
+                       ret_send_status = consumer_send_status_msg(sock, ret_add_channel);
                        if (ret_send_status < 0) {
                                goto error_fatal;
                        }
@@ -672,19 +651,18 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                health_code_update();
 
                pthread_mutex_lock(&channel->lock);
-               new_stream = consumer_stream_create(
-                               channel,
-                               channel->key,
-                               fd,
-                               channel->name,
-                               channel->relayd_id,
-                               channel->session_id,
-                               channel->trace_chunk,
-                               msg.u.stream.cpu,
-                               &alloc_ret,
-                               channel->type,
-                               channel->monitor);
-               if (new_stream == NULL) {
+               new_stream = consumer_stream_create(channel,
+                                                   channel->key,
+                                                   fd,
+                                                   channel->name,
+                                                   channel->relayd_id,
+                                                   channel->session_id,
+                                                   channel->trace_chunk,
+                                                   msg.u.stream.cpu,
+                                                   &alloc_ret,
+                                                   channel->type,
+                                                   channel->monitor);
+               if (new_stream == nullptr) {
                        switch (alloc_ret) {
                        case -ENOMEM:
                        case -EINVAL:
@@ -697,16 +675,15 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                }
 
                new_stream->wait_fd = fd;
-               ret_get_max_subbuf_size = kernctl_get_max_subbuf_size(
-                               new_stream->wait_fd, &new_stream->max_sb_size);
+               ret_get_max_subbuf_size =
+                       kernctl_get_max_subbuf_size(new_stream->wait_fd, &new_stream->max_sb_size);
                if (ret_get_max_subbuf_size < 0) {
                        pthread_mutex_unlock(&channel->lock);
                        ERR("Failed to get kernel maximal subbuffer size");
                        goto error_add_stream_nosignal;
                }
 
-               consumer_stream_update_channel_attributes(new_stream,
-                               channel);
+               consumer_stream_update_channel_attributes(new_stream, channel);
 
                /*
                 * We've just assigned the channel to the stream so increment the
@@ -749,8 +726,9 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                /* Do not monitor this stream. */
                if (!channel->monitor) {
                        DBG("Kernel consumer add stream %s in no monitor mode with "
-                                       "relayd id %" PRIu64, new_stream->name,
-                                       new_stream->net_seq_idx);
+                           "relayd id %" PRIu64,
+                           new_stream->name,
+                           new_stream->net_seq_idx);
                        cds_list_add(&new_stream->send_node, &channel->streams.head);
                        pthread_mutex_unlock(&new_stream->lock);
                        pthread_mutex_unlock(&channel->lock);
@@ -761,8 +739,8 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                if (new_stream->net_seq_idx != (uint64_t) -1ULL) {
                        int ret_send_relayd_stream;
 
-                       ret_send_relayd_stream = consumer_send_relayd_stream(
-                                       new_stream, new_stream->chan->pathname);
+                       ret_send_relayd_stream =
+                               consumer_send_relayd_stream(new_stream, new_stream->chan->pathname);
                        if (ret_send_relayd_stream < 0) {
                                pthread_mutex_unlock(&new_stream->lock);
                                pthread_mutex_unlock(&channel->lock);
@@ -779,8 +757,7 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                                int ret_send_relayd_streams_sent;
 
                                ret_send_relayd_streams_sent =
-                                               consumer_send_relayd_streams_sent(
-                                                               new_stream->net_seq_idx);
+                                       consumer_send_relayd_streams_sent(new_stream->net_seq_idx);
                                if (ret_send_relayd_streams_sent < 0) {
                                        pthread_mutex_unlock(&new_stream->lock);
                                        pthread_mutex_unlock(&channel->lock);
@@ -805,12 +782,16 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                health_code_update();
 
-               ret_pipe_write = lttng_pipe_write(
-                               stream_pipe, &new_stream, sizeof(new_stream));
+               ret_pipe_write =
+                       lttng_pipe_write(stream_pipe, &new_stream, sizeof(new_stream)); /* NOLINT
+                                                                                          sizeof
+                                                                                          used on a
+                                                                                          pointer.
+                                                                                        */
                if (ret_pipe_write < 0) {
                        ERR("Consumer write %s stream to pipe %d",
-                                       new_stream->metadata_flag ? "metadata" : "data",
-                                       lttng_pipe_get_writefd(stream_pipe));
+                           new_stream->metadata_flag ? "metadata" : "data",
+                           lttng_pipe_get_writefd(stream_pipe));
                        if (new_stream->metadata_flag) {
                                consumer_del_stream_for_metadata(new_stream);
                        } else {
@@ -820,12 +801,15 @@ int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                }
 
                DBG("Kernel consumer ADD_STREAM %s (fd: %d) %s with relayd id %" PRIu64,
-                               new_stream->name, fd, new_stream->chan->pathname, new_stream->relayd_stream_id);
-end_add_stream:
+                   new_stream->name,
+                   fd,
+                   new_stream->chan->pathname,
+                   new_stream->relayd_stream_id);
+       end_add_stream:
                break;
-error_add_stream_nosignal:
+       error_add_stream_nosignal:
                goto end_nosignal;
-error_add_stream_fatal:
+       error_add_stream_fatal:
                goto error_fatal;
        }
        case LTTNG_CONSUMER_STREAMS_SENT:
@@ -843,8 +827,7 @@ error_add_stream_fatal:
                         * We could not find the channel. Can happen if cpu hotplug
                         * happens while tearing down.
                         */
-                       ERR("Unable to find channel key %" PRIu64,
-                                       msg.u.sent_streams.channel_key);
+                       ERR("Unable to find channel key %" PRIu64, msg.u.sent_streams.channel_key);
                        ret_code = LTTCOMM_CONSUMERD_CHAN_NOT_FOUND;
                }
 
@@ -854,8 +837,7 @@ error_add_stream_fatal:
                 * Send status code to session daemon.
                 */
                ret_send_status = consumer_send_status_msg(sock, ret_code);
-               if (ret_send_status < 0 ||
-                               ret_code != LTTCOMM_CONSUMERD_SUCCESS) {
+               if (ret_send_status < 0 || ret_code != LTTCOMM_CONSUMERD_SUCCESS) {
                        /* Somehow, the session daemon is not responding anymore. */
                        goto error_streams_sent_nosignal;
                }
@@ -875,21 +857,20 @@ error_add_stream_fatal:
                if (msg.u.sent_streams.net_seq_idx != (uint64_t) -1ULL) {
                        int ret_send_relay_streams;
 
-                       ret_send_relay_streams = consumer_send_relayd_streams_sent(
-                                       msg.u.sent_streams.net_seq_idx);
+                       ret_send_relay_streams =
+                               consumer_send_relayd_streams_sent(msg.u.sent_streams.net_seq_idx);
                        if (ret_send_relay_streams < 0) {
                                goto error_streams_sent_nosignal;
                        }
                        channel->streams_sent_to_relayd = true;
                }
-end_error_streams_sent:
+       end_error_streams_sent:
                break;
-error_streams_sent_nosignal:
+       error_streams_sent_nosignal:
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_UPDATE_STREAM:
        {
-               rcu_read_unlock();
                return -ENOSYS;
        }
        case LTTNG_CONSUMER_DESTROY_RELAYD:
@@ -902,7 +883,7 @@ error_streams_sent_nosignal:
 
                /* Get relayd reference if exists. */
                relayd = consumer_find_relayd(index);
-               if (relayd == NULL) {
+               if (relayd == nullptr) {
                        DBG("Unable to find relayd %" PRIu64, index);
                        ret_code = LTTCOMM_CONSUMERD_RELAYD_FAIL;
                }
@@ -944,8 +925,8 @@ error_streams_sent_nosignal:
                health_code_update();
 
                /* Send back returned value to session daemon */
-               ret_send = lttcomm_send_unix_sock(sock, &ret_data_pending,
-                               sizeof(ret_data_pending));
+               ret_send =
+                       lttcomm_send_unix_sock(sock, &ret_data_pending, sizeof(ret_data_pending));
                if (ret_send < 0) {
                        PERROR("send data pending ret code");
                        goto error_fatal;
@@ -972,10 +953,11 @@ error_streams_sent_nosignal:
                                int ret_snapshot;
 
                                ret_snapshot = lttng_kconsumer_snapshot_metadata(
-                                               channel, key,
-                                               msg.u.snapshot_channel.pathname,
-                                               msg.u.snapshot_channel.relayd_id,
-                                               ctx);
+                                       channel,
+                                       key,
+                                       msg.u.snapshot_channel.pathname,
+                                       msg.u.snapshot_channel.relayd_id,
+                                       ctx);
                                if (ret_snapshot < 0) {
                                        ERR("Snapshot metadata failed");
                                        ret_code = LTTCOMM_CONSUMERD_SNAPSHOT_FAILED;
@@ -984,11 +966,11 @@ error_streams_sent_nosignal:
                                int ret_snapshot;
 
                                ret_snapshot = lttng_kconsumer_snapshot_channel(
-                                               channel, key,
-                                               msg.u.snapshot_channel.pathname,
-                                               msg.u.snapshot_channel.relayd_id,
-                                               msg.u.snapshot_channel
-                                                               .nb_packets_per_stream);
+                                       channel,
+                                       key,
+                                       msg.u.snapshot_channel.pathname,
+                                       msg.u.snapshot_channel.relayd_id,
+                                       msg.u.snapshot_channel.nb_packets_per_stream);
                                if (ret_snapshot < 0) {
                                        ERR("Snapshot channel failed");
                                        ret_code = LTTCOMM_CONSUMERD_SNAPSHOT_FAILED;
@@ -1044,7 +1026,7 @@ error_streams_sent_nosignal:
                LTTNG_ASSERT(!uatomic_sub_return(&channel->refcount, 1));
 
                consumer_del_channel(channel);
-end_destroy_channel:
+       end_destroy_channel:
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_DISCARDED_EVENTS:
@@ -1055,13 +1037,14 @@ end_destroy_channel:
                uint64_t id = msg.u.discarded_events.session_id;
                uint64_t key = msg.u.discarded_events.channel_key;
 
-               DBG("Kernel consumer discarded events command for session id %"
-                               PRIu64 ", channel key %" PRIu64, id, key);
+               DBG("Kernel consumer discarded events command for session id %" PRIu64
+                   ", channel key %" PRIu64,
+                   id,
+                   key);
 
                channel = consumer_find_channel(key);
                if (!channel) {
-                       ERR("Kernel consumer discarded events channel %"
-                                       PRIu64 " not found", key);
+                       ERR("Kernel consumer discarded events channel %" PRIu64 " not found", key);
                        count = 0;
                } else {
                        count = channel->discarded_events;
@@ -1086,13 +1069,14 @@ end_destroy_channel:
                uint64_t id = msg.u.lost_packets.session_id;
                uint64_t key = msg.u.lost_packets.channel_key;
 
-               DBG("Kernel consumer lost packets command for session id %"
-                               PRIu64 ", channel key %" PRIu64, id, key);
+               DBG("Kernel consumer lost packets command for session id %" PRIu64
+                   ", channel key %" PRIu64,
+                   id,
+                   key);
 
                channel = consumer_find_channel(key);
                if (!channel) {
-                       ERR("Kernel consumer lost packets channel %"
-                                       PRIu64 " not found", key);
+                       ERR("Kernel consumer lost packets channel %" PRIu64 " not found", key);
                        count = 0;
                } else {
                        count = channel->lost_packets;
@@ -1122,8 +1106,7 @@ end_destroy_channel:
                        goto error_fatal;
                }
 
-               ret_recv = lttcomm_recv_fds_unix_sock(
-                               sock, &channel_monitor_pipe, 1);
+               ret_recv = lttcomm_recv_fds_unix_sock(sock, &channel_monitor_pipe, 1);
                if (ret_recv != sizeof(channel_monitor_pipe)) {
                        ERR("Failed to receive channel monitor pipe");
                        goto error_fatal;
@@ -1131,8 +1114,7 @@ end_destroy_channel:
 
                DBG("Received channel monitor pipe (%d)", channel_monitor_pipe);
                ret_set_channel_monitor_pipe =
-                               consumer_timer_thread_set_channel_monitor_pipe(
-                                               channel_monitor_pipe);
+                       consumer_timer_thread_set_channel_monitor_pipe(channel_monitor_pipe);
                if (!ret_set_channel_monitor_pipe) {
                        int flags;
                        int ret_fcntl;
@@ -1146,8 +1128,7 @@ end_destroy_channel:
                        }
                        flags = ret_fcntl;
 
-                       ret_fcntl = fcntl(channel_monitor_pipe, F_SETFL,
-                                       flags | O_NONBLOCK);
+                       ret_fcntl = fcntl(channel_monitor_pipe, F_SETFL, flags | O_NONBLOCK);
                        if (ret_fcntl == -1) {
                                PERROR("fcntl set O_NONBLOCK flag of the channel monitoring pipe");
                                goto error_fatal;
@@ -1181,8 +1162,7 @@ end_destroy_channel:
                        int ret_rotate_channel;
 
                        ret_rotate_channel = lttng_consumer_rotate_channel(
-                                       channel, key,
-                                       msg.u.rotate_channel.relayd_id);
+                               channel, key, msg.u.rotate_channel.relayd_id);
                        if (ret_rotate_channel < 0) {
                                ERR("Rotate channel failed");
                                ret_code = LTTCOMM_CONSUMERD_ROTATION_FAIL;
@@ -1200,14 +1180,13 @@ end_destroy_channel:
                        /* Rotate the streams that are ready right now. */
                        int ret_rotate;
 
-                       ret_rotate = lttng_consumer_rotate_ready_streams(
-                                       channel, key);
+                       ret_rotate = lttng_consumer_rotate_ready_streams(channel, key);
                        if (ret_rotate < 0) {
                                ERR("Rotate ready streams failed");
                        }
                }
                break;
-error_rotate_channel:
+       error_rotate_channel:
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_CLEAR_CHANNEL:
@@ -1223,8 +1202,7 @@ error_rotate_channel:
                } else {
                        int ret_clear_channel;
 
-                       ret_clear_channel =
-                                       lttng_consumer_clear_channel(channel);
+                       ret_clear_channel = lttng_consumer_clear_channel(channel);
                        if (ret_clear_channel) {
                                ERR("Clear channel failed");
                                ret_code = (lttcomm_return_code) ret_clear_channel;
@@ -1246,11 +1224,11 @@ error_rotate_channel:
                int ret_send_status;
                lttng_uuid sessiond_uuid;
 
-               std::copy(std::begin(msg.u.init.sessiond_uuid), std::end(msg.u.init.sessiond_uuid),
-                               sessiond_uuid.begin());
+               std::copy(std::begin(msg.u.init.sessiond_uuid),
+                         std::end(msg.u.init.sessiond_uuid),
+                         sessiond_uuid.begin());
 
-               ret_code = lttng_consumer_init_command(ctx,
-                               sessiond_uuid);
+               ret_code = lttng_consumer_init_command(ctx, sessiond_uuid);
                health_code_update();
                ret_send_status = consumer_send_status_msg(sock, ret_code);
                if (ret_send_status < 0) {
@@ -1262,18 +1240,17 @@ error_rotate_channel:
        case LTTNG_CONSUMER_CREATE_TRACE_CHUNK:
        {
                const struct lttng_credentials credentials = {
-                       .uid = LTTNG_OPTIONAL_INIT_VALUE(msg.u.create_trace_chunk.credentials.value.uid),
-                       .gid = LTTNG_OPTIONAL_INIT_VALUE(msg.u.create_trace_chunk.credentials.value.gid),
+                       .uid = LTTNG_OPTIONAL_INIT_VALUE(
+                               msg.u.create_trace_chunk.credentials.value.uid),
+                       .gid = LTTNG_OPTIONAL_INIT_VALUE(
+                               msg.u.create_trace_chunk.credentials.value.gid),
                };
-               const bool is_local_trace =
-                               !msg.u.create_trace_chunk.relayd_id.is_set;
-               const uint64_t relayd_id =
-                               msg.u.create_trace_chunk.relayd_id.value;
-               const char *chunk_override_name =
-                               *msg.u.create_trace_chunk.override_name ?
-                                       msg.u.create_trace_chunk.override_name :
-                                       NULL;
-               struct lttng_directory_handle *chunk_directory_handle = NULL;
+               const bool is_local_trace = !msg.u.create_trace_chunk.relayd_id.is_set;
+               const uint64_t relayd_id = msg.u.create_trace_chunk.relayd_id.value;
+               const char *chunk_override_name = *msg.u.create_trace_chunk.override_name ?
+                       msg.u.create_trace_chunk.override_name :
+                       nullptr;
+               struct lttng_directory_handle *chunk_directory_handle = nullptr;
 
                /*
                 * The session daemon will only provide a chunk directory file
@@ -1285,24 +1262,21 @@ error_rotate_channel:
                        ssize_t ret_recv;
 
                        /* Acnowledge the reception of the command. */
-                       ret_send_status = consumer_send_status_msg(
-                                       sock, LTTCOMM_CONSUMERD_SUCCESS);
+                       ret_send_status = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
                        if (ret_send_status < 0) {
                                /* Somehow, the session daemon is not responding anymore. */
                                goto end_nosignal;
                        }
 
-                       ret_recv = lttcomm_recv_fds_unix_sock(
-                                       sock, &chunk_dirfd, 1);
+                       ret_recv = lttcomm_recv_fds_unix_sock(sock, &chunk_dirfd, 1);
                        if (ret_recv != sizeof(chunk_dirfd)) {
                                ERR("Failed to receive trace chunk directory file descriptor");
                                goto error_fatal;
                        }
 
-                       DBG("Received trace chunk directory fd (%d)",
-                                       chunk_dirfd);
-                       chunk_directory_handle = lttng_directory_handle_create_from_dirfd(
-                                       chunk_dirfd);
+                       DBG("Received trace chunk directory fd (%d)", chunk_dirfd);
+                       chunk_directory_handle =
+                               lttng_directory_handle_create_from_dirfd(chunk_dirfd);
                        if (!chunk_directory_handle) {
                                ERR("Failed to initialize chunk directory handle from directory file descriptor");
                                if (close(chunk_dirfd)) {
@@ -1313,47 +1287,39 @@ error_rotate_channel:
                }
 
                ret_code = lttng_consumer_create_trace_chunk(
-                               !is_local_trace ? &relayd_id : NULL,
-                               msg.u.create_trace_chunk.session_id,
-                               msg.u.create_trace_chunk.chunk_id,
-                               (time_t) msg.u.create_trace_chunk
-                                               .creation_timestamp,
-                               chunk_override_name,
-                               msg.u.create_trace_chunk.credentials.is_set ?
-                                               &credentials :
-                                               NULL,
-                               chunk_directory_handle);
+                       !is_local_trace ? &relayd_id : nullptr,
+                       msg.u.create_trace_chunk.session_id,
+                       msg.u.create_trace_chunk.chunk_id,
+                       (time_t) msg.u.create_trace_chunk.creation_timestamp,
+                       chunk_override_name,
+                       msg.u.create_trace_chunk.credentials.is_set ? &credentials : nullptr,
+                       chunk_directory_handle);
                lttng_directory_handle_put(chunk_directory_handle);
                goto end_msg_sessiond;
        }
        case LTTNG_CONSUMER_CLOSE_TRACE_CHUNK:
        {
                enum lttng_trace_chunk_command_type close_command =
-                               (lttng_trace_chunk_command_type) msg.u.close_trace_chunk.close_command.value;
-               const uint64_t relayd_id =
-                               msg.u.close_trace_chunk.relayd_id.value;
+                       (lttng_trace_chunk_command_type) msg.u.close_trace_chunk.close_command.value;
+               const uint64_t relayd_id = msg.u.close_trace_chunk.relayd_id.value;
                struct lttcomm_consumer_close_trace_chunk_reply reply;
                char path[LTTNG_PATH_MAX];
                ssize_t ret_send;
 
                ret_code = lttng_consumer_close_trace_chunk(
-                               msg.u.close_trace_chunk.relayd_id.is_set ?
-                                               &relayd_id :
-                                               NULL,
-                               msg.u.close_trace_chunk.session_id,
-                               msg.u.close_trace_chunk.chunk_id,
-                               (time_t) msg.u.close_trace_chunk.close_timestamp,
-                               msg.u.close_trace_chunk.close_command.is_set ?
-                                               &close_command :
-                                               NULL, path);
+                       msg.u.close_trace_chunk.relayd_id.is_set ? &relayd_id : nullptr,
+                       msg.u.close_trace_chunk.session_id,
+                       msg.u.close_trace_chunk.chunk_id,
+                       (time_t) msg.u.close_trace_chunk.close_timestamp,
+                       msg.u.close_trace_chunk.close_command.is_set ? &close_command : nullptr,
+                       path);
                reply.ret_code = ret_code;
                reply.path_length = strlen(path) + 1;
                ret_send = lttcomm_send_unix_sock(sock, &reply, sizeof(reply));
                if (ret_send != sizeof(reply)) {
                        goto error_fatal;
                }
-               ret_send = lttcomm_send_unix_sock(
-                               sock, path, reply.path_length);
+               ret_send = lttcomm_send_unix_sock(sock, path, reply.path_length);
                if (ret_send != reply.path_length) {
                        goto error_fatal;
                }
@@ -1361,21 +1327,18 @@ error_rotate_channel:
        }
        case LTTNG_CONSUMER_TRACE_CHUNK_EXISTS:
        {
-               const uint64_t relayd_id =
-                               msg.u.trace_chunk_exists.relayd_id.value;
+               const uint64_t relayd_id = msg.u.trace_chunk_exists.relayd_id.value;
 
                ret_code = lttng_consumer_trace_chunk_exists(
-                               msg.u.trace_chunk_exists.relayd_id.is_set ?
-                                               &relayd_id : NULL,
-                               msg.u.trace_chunk_exists.session_id,
-                               msg.u.trace_chunk_exists.chunk_id);
+                       msg.u.trace_chunk_exists.relayd_id.is_set ? &relayd_id : nullptr,
+                       msg.u.trace_chunk_exists.session_id,
+                       msg.u.trace_chunk_exists.chunk_id);
                goto end_msg_sessiond;
        }
        case LTTNG_CONSUMER_OPEN_CHANNEL_PACKETS:
        {
                const uint64_t key = msg.u.open_channel_packets.key;
-               struct lttng_consumer_channel *channel =
-                               consumer_find_channel(key);
+               struct lttng_consumer_channel *channel = consumer_find_channel(key);
 
                if (channel) {
                        pthread_mutex_lock(&channel->lock);
@@ -1423,7 +1386,6 @@ end_msg_sessiond:
 
 end:
        health_code_update();
-       rcu_read_unlock();
        return ret_func;
 }
 
@@ -1433,8 +1395,7 @@ end:
  *
  * Metadata stream lock MUST be acquired.
  */
-enum sync_metadata_status lttng_kconsumer_sync_metadata(
-               struct lttng_consumer_stream *metadata)
+enum sync_metadata_status lttng_kconsumer_sync_metadata(struct lttng_consumer_stream *metadata)
 {
        int ret;
        enum sync_metadata_status status;
@@ -1466,20 +1427,18 @@ end:
        return status;
 }
 
-static
-int extract_common_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+static int extract_common_subbuffer_info(struct lttng_consumer_stream *stream,
+                                        struct stream_subbuffer *subbuf)
 {
        int ret;
 
-       ret = kernctl_get_subbuf_size(
-                       stream->wait_fd, &subbuf->info.data.subbuf_size);
+       ret = kernctl_get_subbuf_size(stream->wait_fd, &subbuf->info.data.subbuf_size);
        if (ret) {
                goto end;
        }
 
-       ret = kernctl_get_padded_subbuf_size(
-                       stream->wait_fd, &subbuf->info.data.padded_subbuf_size);
+       ret = kernctl_get_padded_subbuf_size(stream->wait_fd,
+                                            &subbuf->info.data.padded_subbuf_size);
        if (ret) {
                goto end;
        }
@@ -1488,9 +1447,8 @@ end:
        return ret;
 }
 
-static
-int extract_metadata_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+static int extract_metadata_subbuffer_info(struct lttng_consumer_stream *stream,
+                                          struct stream_subbuffer *subbuf)
 {
        int ret;
 
@@ -1499,8 +1457,7 @@ int extract_metadata_subbuffer_info(struct lttng_consumer_stream *stream,
                goto end;
        }
 
-       ret = kernctl_get_metadata_version(
-                       stream->wait_fd, &subbuf->info.metadata.version);
+       ret = kernctl_get_metadata_version(stream->wait_fd, &subbuf->info.metadata.version);
        if (ret) {
                goto end;
        }
@@ -1509,9 +1466,8 @@ end:
        return ret;
 }
 
-static
-int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+static int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
+                                      struct stream_subbuffer *subbuf)
 {
        int ret;
 
@@ -1520,43 +1476,38 @@ int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
                goto end;
        }
 
-       ret = kernctl_get_packet_size(
-                       stream->wait_fd, &subbuf->info.data.packet_size);
+       ret = kernctl_get_packet_size(stream->wait_fd, &subbuf->info.data.packet_size);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer packet size");
                goto end;
        }
 
-       ret = kernctl_get_content_size(
-                       stream->wait_fd, &subbuf->info.data.content_size);
+       ret = kernctl_get_content_size(stream->wait_fd, &subbuf->info.data.content_size);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer content size");
                goto end;
        }
 
-       ret = kernctl_get_timestamp_begin(
-                       stream->wait_fd, &subbuf->info.data.timestamp_begin);
+       ret = kernctl_get_timestamp_begin(stream->wait_fd, &subbuf->info.data.timestamp_begin);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer begin timestamp");
                goto end;
        }
 
-       ret = kernctl_get_timestamp_end(
-                       stream->wait_fd, &subbuf->info.data.timestamp_end);
+       ret = kernctl_get_timestamp_end(stream->wait_fd, &subbuf->info.data.timestamp_end);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer end timestamp");
                goto end;
        }
 
-       ret = kernctl_get_events_discarded(
-                       stream->wait_fd, &subbuf->info.data.events_discarded);
+       ret = kernctl_get_events_discarded(stream->wait_fd, &subbuf->info.data.events_discarded);
        if (ret) {
                PERROR("Failed to get sub-buffer events discarded count");
                goto end;
        }
 
        ret = kernctl_get_sequence_number(stream->wait_fd,
-                       &subbuf->info.data.sequence_number.value);
+                                         &subbuf->info.data.sequence_number.value);
        if (ret) {
                /* May not be supported by older LTTng-modules. */
                if (ret != -ENOTTY) {
@@ -1567,15 +1518,13 @@ int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
                subbuf->info.data.sequence_number.is_set = true;
        }
 
-       ret = kernctl_get_stream_id(
-                       stream->wait_fd, &subbuf->info.data.stream_id);
+       ret = kernctl_get_stream_id(stream->wait_fd, &subbuf->info.data.stream_id);
        if (ret < 0) {
                PERROR("Failed to get stream id");
                goto end;
        }
 
-       ret = kernctl_get_instance_id(stream->wait_fd,
-                       &subbuf->info.data.stream_instance_id.value);
+       ret = kernctl_get_instance_id(stream->wait_fd, &subbuf->info.data.stream_instance_id.value);
        if (ret) {
                /* May not be supported by older LTTng-modules. */
                if (ret != -ENOTTY) {
@@ -1589,10 +1538,8 @@ end:
        return ret;
 }
 
-static
-enum get_next_subbuffer_status get_subbuffer_common(
-               struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status get_subbuffer_common(struct lttng_consumer_stream *stream,
+                                                          struct stream_subbuffer *subbuffer)
 {
        int ret;
        enum get_next_subbuffer_status status;
@@ -1603,7 +1550,7 @@ enum get_next_subbuffer_status get_subbuffer_common(
                status = GET_NEXT_SUBBUFFER_STATUS_OK;
                break;
        case -ENODATA:
-               case -EAGAIN:
+       case -EAGAIN:
                /*
                 * The caller only expects -ENODATA when there is no data to
                 * read, but the kernel tracer returns -EAGAIN when there is
@@ -1618,8 +1565,7 @@ enum get_next_subbuffer_status get_subbuffer_common(
                goto end;
        }
 
-       ret = stream->read_subbuffer_ops.extract_subbuffer_info(
-               stream, subbuffer);
+       ret = stream->read_subbuffer_ops.extract_subbuffer_info(stream, subbuffer);
        if (ret) {
                status = GET_NEXT_SUBBUFFER_STATUS_ERROR;
        }
@@ -1627,13 +1573,10 @@ end:
        return status;
 }
 
-static
-enum get_next_subbuffer_status get_next_subbuffer_splice(
-               struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status
+get_next_subbuffer_splice(struct lttng_consumer_stream *stream, struct stream_subbuffer *subbuffer)
 {
-       const enum get_next_subbuffer_status status =
-                       get_subbuffer_common(stream, subbuffer);
+       const enum get_next_subbuffer_status status = get_subbuffer_common(stream, subbuffer);
 
        if (status != GET_NEXT_SUBBUFFER_STATUS_OK) {
                goto end;
@@ -1644,10 +1587,8 @@ end:
        return status;
 }
 
-static
-enum get_next_subbuffer_status get_next_subbuffer_mmap(
-               struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status get_next_subbuffer_mmap(struct lttng_consumer_stream *stream,
+                                                             struct stream_subbuffer *subbuffer)
 {
        int ret;
        enum get_next_subbuffer_status status;
@@ -1664,29 +1605,27 @@ enum get_next_subbuffer_status get_next_subbuffer_mmap(
                goto end;
        }
 
-       subbuffer->buffer.buffer = lttng_buffer_view_init(
-                       addr, 0, subbuffer->info.data.padded_subbuf_size);
+       subbuffer->buffer.buffer =
+               lttng_buffer_view_init(addr, 0, subbuffer->info.data.padded_subbuf_size);
 end:
        return status;
 }
 
-static
-enum get_next_subbuffer_status get_next_subbuffer_metadata_check(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status
+get_next_subbuffer_metadata_check(struct lttng_consumer_stream *stream,
+                                 struct stream_subbuffer *subbuffer)
 {
        int ret;
        const char *addr;
        bool coherent;
        enum get_next_subbuffer_status status;
 
-       ret = kernctl_get_next_subbuf_metadata_check(stream->wait_fd,
-                       &coherent);
+       ret = kernctl_get_next_subbuf_metadata_check(stream->wait_fd, &coherent);
        if (ret) {
                goto end;
        }
 
-       ret = stream->read_subbuffer_ops.extract_subbuffer_info(
-                       stream, subbuffer);
+       ret = stream->read_subbuffer_ops.extract_subbuffer_info(stream, subbuffer);
        if (ret) {
                goto end;
        }
@@ -1698,11 +1637,11 @@ enum get_next_subbuffer_status get_next_subbuffer_metadata_check(struct lttng_co
                goto end;
        }
 
-       subbuffer->buffer.buffer = lttng_buffer_view_init(
-                       addr, 0, subbuffer->info.data.padded_subbuf_size);
+       subbuffer->buffer.buffer =
+               lttng_buffer_view_init(addr, 0, subbuffer->info.data.padded_subbuf_size);
        DBG("Got metadata packet with padded_subbuf_size = %lu, coherent = %s",
-                       subbuffer->info.metadata.padded_subbuf_size,
-                       coherent ? "true" : "false");
+           subbuffer->info.metadata.padded_subbuf_size,
+           coherent ? "true" : "false");
 end:
        /*
         * The caller only expects -ENODATA when there is no data to read, but
@@ -1733,9 +1672,8 @@ end:
        return status;
 }
 
-static
-int put_next_subbuffer(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer __attribute__((unused)))
+static int put_next_subbuffer(struct lttng_consumer_stream *stream,
+                             struct stream_subbuffer *subbuffer __attribute__((unused)))
 {
        const int ret = kernctl_put_next_subbuf(stream->wait_fd);
 
@@ -1751,10 +1689,9 @@ int put_next_subbuffer(struct lttng_consumer_stream *stream,
        return ret;
 }
 
-static
-bool is_get_next_check_metadata_available(int tracer_fd)
+static bool is_get_next_check_metadata_available(int tracer_fd)
 {
-       const int ret = kernctl_get_next_subbuf_metadata_check(tracer_fd, NULL);
+       const int ret = kernctl_get_next_subbuf_metadata_check(tracer_fd, nullptr);
        const bool available = ret != -ENOTTY;
 
        if (ret == 0) {
@@ -1765,17 +1702,14 @@ bool is_get_next_check_metadata_available(int tracer_fd)
        return available;
 }
 
-static
-int signal_metadata(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx __attribute__((unused)))
+static int signal_metadata(struct lttng_consumer_stream *stream,
+                          struct lttng_consumer_local_data *ctx __attribute__((unused)))
 {
        ASSERT_LOCKED(stream->metadata_rdv_lock);
        return pthread_cond_broadcast(&stream->metadata_rdv) ? -errno : 0;
 }
 
-static
-int lttng_kconsumer_set_stream_ops(
-               struct lttng_consumer_stream *stream)
+static int lttng_kconsumer_set_stream_ops(struct lttng_consumer_stream *stream)
 {
        int ret = 0;
 
@@ -1784,9 +1718,8 @@ int lttng_kconsumer_set_stream_ops(
                if (is_get_next_check_metadata_available(stream->wait_fd)) {
                        DBG("Kernel tracer supports get_next_subbuffer_metadata_check, metadata will be accumulated until a coherent state is reached");
                        stream->read_subbuffer_ops.get_next_subbuffer =
-                                       get_next_subbuffer_metadata_check;
-                       ret = consumer_stream_enable_metadata_bucketization(
-                                       stream);
+                               get_next_subbuffer_metadata_check;
+                       ret = consumer_stream_enable_metadata_bucketization(stream);
                        if (ret) {
                                goto end;
                        }
@@ -1801,7 +1734,7 @@ int lttng_kconsumer_set_stream_ops(
                         */
                        WARN("Kernel tracer does not support get_next_subbuffer_metadata_check which may cause live clients to fail to parse the metadata stream");
                        metadata_bucket_destroy(stream->metadata_bucket);
-                       stream->metadata_bucket = NULL;
+                       stream->metadata_bucket = nullptr;
                }
 
                stream->read_subbuffer_ops.on_sleep = signal_metadata;
@@ -1809,23 +1742,18 @@ int lttng_kconsumer_set_stream_ops(
 
        if (!stream->read_subbuffer_ops.get_next_subbuffer) {
                if (stream->chan->output == CONSUMER_CHANNEL_MMAP) {
-                       stream->read_subbuffer_ops.get_next_subbuffer =
-                                       get_next_subbuffer_mmap;
+                       stream->read_subbuffer_ops.get_next_subbuffer = get_next_subbuffer_mmap;
                } else {
-                       stream->read_subbuffer_ops.get_next_subbuffer =
-                                       get_next_subbuffer_splice;
+                       stream->read_subbuffer_ops.get_next_subbuffer = get_next_subbuffer_splice;
                }
        }
 
        if (stream->metadata_flag) {
-               stream->read_subbuffer_ops.extract_subbuffer_info =
-                               extract_metadata_subbuffer_info;
+               stream->read_subbuffer_ops.extract_subbuffer_info = extract_metadata_subbuffer_info;
        } else {
-               stream->read_subbuffer_ops.extract_subbuffer_info =
-                               extract_data_subbuffer_info;
+               stream->read_subbuffer_ops.extract_subbuffer_info = extract_data_subbuffer_info;
                if (stream->chan->is_live) {
-                       stream->read_subbuffer_ops.send_live_beacon =
-                                       consumer_flush_kernel_index;
+                       stream->read_subbuffer_ops.send_live_beacon = consumer_flush_kernel_index;
                }
        }
 
@@ -1845,7 +1773,7 @@ int lttng_kconsumer_on_recv_stream(struct lttng_consumer_stream *stream)
         * no current trace chunk on the parent channel.
         */
        if (stream->net_seq_idx == (uint64_t) -1ULL && stream->chan->monitor &&
-                       stream->chan->trace_chunk) {
+           stream->chan->trace_chunk) {
                ret = consumer_stream_create_output_files(stream, true);
                if (ret) {
                        goto error;
@@ -1863,8 +1791,8 @@ int lttng_kconsumer_on_recv_stream(struct lttng_consumer_stream *stream)
                }
                stream->mmap_len = (size_t) mmap_len;
 
-               stream->mmap_base = mmap(NULL, stream->mmap_len, PROT_READ,
-                               MAP_PRIVATE, stream->wait_fd, 0);
+               stream->mmap_base =
+                       mmap(nullptr, stream->mmap_len, PROT_READ, MAP_PRIVATE, stream->wait_fd, 0);
                if (stream->mmap_base == MAP_FAILED) {
                        PERROR("Error mmaping");
                        ret = -1;
@@ -1916,7 +1844,7 @@ int lttng_kconsumer_data_pending(struct lttng_consumer_stream *stream)
                /* There is still data so let's put back this subbuffer. */
                ret = kernctl_put_subbuf(stream->wait_fd);
                LTTNG_ASSERT(ret == 0);
-               ret = 1;   /* Data is pending */
+               ret = 1; /* Data is pending */
                goto end;
        }
 
index 7070cfaee6eb4b07c1e46ed18637f5caac1393f9..14e0140b3d25ecef12dabe19022282984bd051b5 100644 (file)
 #ifndef _LTTNG_KCONSUMER_H
 #define _LTTNG_KCONSUMER_H
 
-#include <stdbool.h>
 #include <common/consumer/consumer.hpp>
 
+#include <stdbool.h>
+
 int lttng_kconsumer_take_snapshot(struct lttng_consumer_stream *stream);
-int lttng_kconsumer_sample_snapshot_positions(
-               struct lttng_consumer_stream *stream);
-int lttng_kconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos);
-int lttng_kconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
-               unsigned long *pos);
+int lttng_kconsumer_sample_snapshot_positions(struct lttng_consumer_stream *stream);
+int lttng_kconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos);
+int lttng_kconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos);
 int lttng_kconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll);
+                            int sock,
+                            struct pollfd *consumer_sockpoll);
 int lttng_kconsumer_on_recv_stream(struct lttng_consumer_stream *stream);
 int lttng_kconsumer_data_pending(struct lttng_consumer_stream *stream);
-enum sync_metadata_status lttng_kconsumer_sync_metadata(
-               struct lttng_consumer_stream *metadata);
+enum sync_metadata_status lttng_kconsumer_sync_metadata(struct lttng_consumer_stream *metadata);
 
 #endif /* _LTTNG_KCONSUMER_H */
index 76960307c80abe7924011c22f2f3a3ebccfc626d..d3a97ce843f5bd860a8967c2ac9a64bd3ee0e631 100644 (file)
 #include "lttng/tracker.h"
 #define _LGPL_SOURCE
 #define __USE_LINUX_IOCTL_DEFS
-#include <sys/ioctl.h>
-#include <string.h>
+#include "kernel-ctl.hpp"
+#include "kernel-ioctl.hpp"
+
 #include <common/align.hpp>
-#include <common/macros.hpp>
 #include <common/compat/errno.hpp>
-#include <stdarg.h>
+#include <common/macros.hpp>
 #include <common/time.hpp>
 
-#include "kernel-ctl.hpp"
-#include "kernel-ioctl.hpp"
+#include <stdarg.h>
+#include <string.h>
+#include <sys/ioctl.h>
 
 #define LTTNG_IOCTL_CHECK(fildes, request, ...)                         \
        ({                                                              \
                int _ioctl_ret = ioctl(fildes, request, ##__VA_ARGS__); \
-               LTTNG_ASSERT(_ioctl_ret <= 0);                                \
+               LTTNG_ASSERT(_ioctl_ret <= 0);                          \
                !_ioctl_ret ? 0 : -errno;                               \
        })
 
@@ -51,8 +52,7 @@ static int lttng_kernel_abi_use_old_abi = -1;
  * and new request codes.
  * It returns the return value of the ioctl executed.
  */
-static inline int compat_ioctl_no_arg(int fd, unsigned long oldname,
-               unsigned long newname)
+static inline int compat_ioctl_no_arg(int fd, unsigned long oldname, unsigned long newname)
 {
        int ret;
 
@@ -76,8 +76,7 @@ end:
 
 int kernctl_create_session(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_SESSION,
-                       LTTNG_KERNEL_ABI_SESSION);
+       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_SESSION, LTTNG_KERNEL_ABI_SESSION);
 }
 
 /* open the metadata global channel */
@@ -103,8 +102,7 @@ int kernctl_open_metadata(int fd, struct lttng_channel_attr *chops)
                 */
                memcpy(old_channel.padding, chops->padding, sizeof(chops->padding));
 
-               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_METADATA,
-                               &old_channel);
+               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_METADATA, &old_channel);
        }
 
        memset(&channel, 0, sizeof(channel));
@@ -141,8 +139,7 @@ int kernctl_create_channel(int fd, struct lttng_channel_attr *chops)
                 */
                memcpy(old_channel.padding, chops->padding, sizeof(chops->padding));
 
-               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_CHANNEL,
-                               &old_channel);
+               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_CHANNEL, &old_channel);
        }
 
        channel.overwrite = chops->overwrite;
@@ -158,7 +155,7 @@ int kernctl_create_channel(int fd, struct lttng_channel_attr *chops)
 
 int kernctl_syscall_mask(int fd, char **syscall_mask, uint32_t *nr_bits)
 {
-       struct lttng_kernel_abi_syscall_mask kmask_len, *kmask = NULL;
+       struct lttng_kernel_abi_syscall_mask kmask_len, *kmask = nullptr;
        size_t array_alloc_len;
        char *new_mask;
        int ret = 0;
@@ -209,12 +206,10 @@ end:
 
 int kernctl_track_pid(int fd, int pid)
 {
-       int ret = LTTNG_IOCTL_CHECK(
-                       fd, LTTNG_KERNEL_ABI_SESSION_TRACK_PID, pid);
+       int ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_TRACK_PID, pid);
 
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_PID, pid);
+               ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_PID, pid);
        }
 
        return ret;
@@ -222,12 +217,10 @@ int kernctl_track_pid(int fd, int pid)
 
 int kernctl_untrack_pid(int fd, int pid)
 {
-       int ret = LTTNG_IOCTL_CHECK(
-                       fd, LTTNG_KERNEL_ABI_SESSION_UNTRACK_PID, pid);
+       int ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_UNTRACK_PID, pid);
 
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_PID, pid);
+               ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_PID, pid);
        }
 
        return ret;
@@ -238,8 +231,8 @@ int kernctl_list_tracker_pids(int fd)
        return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_PIDS);
 }
 
-static enum lttng_kernel_abi_tracker_type get_kernel_tracker_type(
-               enum lttng_process_attr process_attr)
+static enum lttng_kernel_abi_tracker_type
+get_kernel_tracker_type(enum lttng_process_attr process_attr)
 {
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_PROCESS_ID:
@@ -273,8 +266,7 @@ int kernctl_track_id(int fd, enum lttng_process_attr process_attr, int id)
 
        ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_TRACK_ID, &args);
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_ID, &args);
+               ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_ID, &args);
        }
 
        return ret;
@@ -294,8 +286,7 @@ int kernctl_untrack_id(int fd, enum lttng_process_attr process_attr, int id)
 
        ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_UNTRACK_ID, &args);
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_ID, &args);
+               ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_ID, &args);
        }
 
        return ret;
@@ -313,12 +304,10 @@ int kernctl_list_tracker_ids(int fd, enum lttng_process_attr process_attr)
                return -1;
        }
 
-       ret = LTTNG_IOCTL_NO_CHECK(
-                       fd, LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_IDS, &args);
+       ret = LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_IDS, &args);
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_NO_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_LIST_TRACKER_IDS,
-                               &args);
+               ret = LTTNG_IOCTL_NO_CHECK(
+                       fd, LTTNG_KERNEL_ABI_OLD_SESSION_LIST_TRACKER_IDS, &args);
        }
 
        return ret;
@@ -344,12 +333,9 @@ int kernctl_session_set_name(int fd, const char *name)
                goto end;
        }
 
-       ret = LTTNG_IOCTL_CHECK(
-                       fd, LTTNG_KERNEL_ABI_SESSION_SET_NAME, &session_name);
+       ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_SET_NAME, &session_name);
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_SET_NAME,
-                               &session_name);
+               ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_SESSION_SET_NAME, &session_name);
        }
 
 end:
@@ -361,18 +347,15 @@ int kernctl_session_set_creation_time(int fd, time_t time)
        int ret;
        struct lttng_kernel_abi_session_creation_time creation_time;
 
-       ret = time_to_iso8601_str(time, creation_time.iso8601,
-                       sizeof(creation_time.iso8601));
+       ret = time_to_iso8601_str(time, creation_time.iso8601, sizeof(creation_time.iso8601));
        if (ret) {
                goto end;
        }
 
-       ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_SET_CREATION_TIME,
-                       &creation_time);
+       ret = LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_SESSION_SET_CREATION_TIME, &creation_time);
        if (ret == -ENOSYS) {
-               ret = LTTNG_IOCTL_CHECK(fd,
-                               LTTNG_KERNEL_ABI_OLD_SESSION_SET_CREATION_TIME,
-                               &creation_time);
+               ret = LTTNG_IOCTL_CHECK(
+                       fd, LTTNG_KERNEL_ABI_OLD_SESSION_SET_CREATION_TIME, &creation_time);
        }
 
 end:
@@ -381,8 +364,7 @@ end:
 
 int kernctl_create_stream(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_STREAM,
-                       LTTNG_KERNEL_ABI_STREAM);
+       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_STREAM, LTTNG_KERNEL_ABI_STREAM);
 }
 
 int kernctl_create_event(int fd, struct lttng_kernel_abi_event *ev)
@@ -398,27 +380,26 @@ int kernctl_create_event(int fd, struct lttng_kernel_abi_event *ev)
                        old_event.u.kprobe.addr = ev->u.kprobe.addr;
                        old_event.u.kprobe.offset = ev->u.kprobe.offset;
                        memcpy(old_event.u.kprobe.symbol_name,
-                               ev->u.kprobe.symbol_name,
-                               sizeof(old_event.u.kprobe.symbol_name));
+                              ev->u.kprobe.symbol_name,
+                              sizeof(old_event.u.kprobe.symbol_name));
                        break;
                case LTTNG_KERNEL_ABI_KRETPROBE:
                        old_event.u.kretprobe.addr = ev->u.kretprobe.addr;
                        old_event.u.kretprobe.offset = ev->u.kretprobe.offset;
                        memcpy(old_event.u.kretprobe.symbol_name,
-                               ev->u.kretprobe.symbol_name,
-                               sizeof(old_event.u.kretprobe.symbol_name));
+                              ev->u.kretprobe.symbol_name,
+                              sizeof(old_event.u.kretprobe.symbol_name));
                        break;
                case LTTNG_KERNEL_ABI_FUNCTION:
                        memcpy(old_event.u.ftrace.symbol_name,
-                                       ev->u.ftrace.symbol_name,
-                                       sizeof(old_event.u.ftrace.symbol_name));
+                              ev->u.ftrace.symbol_name,
+                              sizeof(old_event.u.ftrace.symbol_name));
                        break;
                default:
                        break;
                }
 
-               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_EVENT,
-                               &old_event);
+               return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_OLD_EVENT, &old_event);
        }
        return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_EVENT, ev);
 }
@@ -432,85 +413,74 @@ int kernctl_add_context(int fd, struct lttng_kernel_abi_context *ctx)
                old_ctx.ctx = ctx->ctx;
                /* only type that uses the union */
                if (ctx->ctx == LTTNG_KERNEL_ABI_CONTEXT_PERF_CPU_COUNTER) {
-                       old_ctx.u.perf_counter.type =
-                               ctx->u.perf_counter.type;
-                       old_ctx.u.perf_counter.config =
-                               ctx->u.perf_counter.config;
+                       old_ctx.u.perf_counter.type = ctx->u.perf_counter.type;
+                       old_ctx.u.perf_counter.config = ctx->u.perf_counter.config;
                        memcpy(old_ctx.u.perf_counter.name,
-                               ctx->u.perf_counter.name,
-                               sizeof(old_ctx.u.perf_counter.name));
+                              ctx->u.perf_counter.name,
+                              sizeof(old_ctx.u.perf_counter.name));
                }
-               return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_CONTEXT,
-                               &old_ctx);
+               return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_OLD_CONTEXT, &old_ctx);
        }
        return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_CONTEXT, ctx);
 }
 
-
 /* Enable event, channel and session LTTNG_IOCTL_CHECK */
 int kernctl_enable(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_ENABLE,
-                       LTTNG_KERNEL_ABI_ENABLE);
+       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_ENABLE, LTTNG_KERNEL_ABI_ENABLE);
 }
 
 /* Disable event, channel and session LTTNG_IOCTL_CHECK */
 int kernctl_disable(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_DISABLE,
-                       LTTNG_KERNEL_ABI_DISABLE);
+       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_DISABLE, LTTNG_KERNEL_ABI_DISABLE);
 }
 
 int kernctl_start_session(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_SESSION_START,
-                       LTTNG_KERNEL_ABI_SESSION_START);
+       return compat_ioctl_no_arg(
+               fd, LTTNG_KERNEL_ABI_OLD_SESSION_START, LTTNG_KERNEL_ABI_SESSION_START);
 }
 
 int kernctl_stop_session(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_SESSION_STOP,
-                       LTTNG_KERNEL_ABI_SESSION_STOP);
+       return compat_ioctl_no_arg(
+               fd, LTTNG_KERNEL_ABI_OLD_SESSION_STOP, LTTNG_KERNEL_ABI_SESSION_STOP);
 }
 
 int kernctl_create_event_notifier_group(int fd)
 {
-       return LTTNG_IOCTL_NO_CHECK(fd,
-                       LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_CREATE);
+       return LTTNG_IOCTL_NO_CHECK(fd, LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_CREATE);
 }
 
 int kernctl_create_event_notifier_group_notification_fd(int group_fd)
 {
        return LTTNG_IOCTL_NO_CHECK(group_fd,
-                       LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD);
+                                   LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD);
 }
 
-int kernctl_create_event_notifier_group_error_counter(int group_fd,
-               const struct lttng_kernel_abi_counter_conf *error_counter_conf)
+int kernctl_create_event_notifier_group_error_counter(
+       int group_fd, const struct lttng_kernel_abi_counter_conf *error_counter_conf)
 {
-       return LTTNG_IOCTL_NO_CHECK(group_fd, LTTNG_KERNEL_ABI_COUNTER,
-                       error_counter_conf);
+       return LTTNG_IOCTL_NO_CHECK(group_fd, LTTNG_KERNEL_ABI_COUNTER, error_counter_conf);
 }
 
 int kernctl_counter_get_aggregate_value(int counter_fd,
-               struct lttng_kernel_abi_counter_aggregate *value)
+                                       struct lttng_kernel_abi_counter_aggregate *value)
 {
-       return LTTNG_IOCTL_NO_CHECK(counter_fd, LTTNG_KERNEL_ABI_COUNTER_AGGREGATE,
-                       value);
+       return LTTNG_IOCTL_NO_CHECK(counter_fd, LTTNG_KERNEL_ABI_COUNTER_AGGREGATE, value);
 }
 
-int kernctl_counter_clear(int counter_fd,
-               struct lttng_kernel_abi_counter_clear *clear)
+int kernctl_counter_clear(int counter_fd, struct lttng_kernel_abi_counter_clear *clear)
 {
-       return LTTNG_IOCTL_NO_CHECK(counter_fd, LTTNG_KERNEL_ABI_COUNTER_CLEAR,
-                       clear);
+       return LTTNG_IOCTL_NO_CHECK(counter_fd, LTTNG_KERNEL_ABI_COUNTER_CLEAR, clear);
 }
 
 int kernctl_create_event_notifier(int group_fd,
-               const struct lttng_kernel_abi_event_notifier *event_notifier)
+                                 const struct lttng_kernel_abi_event_notifier *event_notifier)
 {
-       return LTTNG_IOCTL_NO_CHECK(group_fd,
-                       LTTNG_KERNEL_ABI_EVENT_NOTIFIER_CREATE, event_notifier);
+       return LTTNG_IOCTL_NO_CHECK(
+               group_fd, LTTNG_KERNEL_ABI_EVENT_NOTIFIER_CREATE, event_notifier);
 }
 
 int kernctl_capture(int fd, const struct lttng_bytecode *capture)
@@ -561,8 +531,8 @@ int kernctl_add_callsite(int fd, struct lttng_kernel_abi_event_callsite *callsit
 
 int kernctl_tracepoint_list(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_TRACEPOINT_LIST,
-                       LTTNG_KERNEL_ABI_TRACEPOINT_LIST);
+       return compat_ioctl_no_arg(
+               fd, LTTNG_KERNEL_ABI_OLD_TRACEPOINT_LIST, LTTNG_KERNEL_ABI_TRACEPOINT_LIST);
 }
 
 int kernctl_syscall_list(int fd)
@@ -600,16 +570,15 @@ end:
        return ret;
 }
 
-int kernctl_tracer_abi_version(int fd,
-               struct lttng_kernel_abi_tracer_abi_version *v)
+int kernctl_tracer_abi_version(int fd, struct lttng_kernel_abi_tracer_abi_version *v)
 {
        return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_TRACER_ABI_VERSION, v);
 }
 
 int kernctl_wait_quiescent(int fd)
 {
-       return compat_ioctl_no_arg(fd, LTTNG_KERNEL_ABI_OLD_WAIT_QUIESCENT,
-                       LTTNG_KERNEL_ABI_WAIT_QUIESCENT);
+       return compat_ioctl_no_arg(
+               fd, LTTNG_KERNEL_ABI_OLD_WAIT_QUIESCENT, LTTNG_KERNEL_ABI_WAIT_QUIESCENT);
 }
 
 int kernctl_buffer_flush(int fd)
@@ -629,16 +598,14 @@ int kernctl_buffer_clear(int fd)
 
 int kernctl_get_next_subbuf_metadata_check(int fd, bool *consistent)
 {
-       return LTTNG_IOCTL_NO_CHECK(fd,
-                       LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF_METADATA_CHECK,
-                       consistent);
+       return LTTNG_IOCTL_NO_CHECK(
+               fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF_METADATA_CHECK, consistent);
 }
 
 /* returns the version of the metadata. */
 int kernctl_get_metadata_version(int fd, uint64_t *version)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_METADATA_VERSION,
-                       version);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_METADATA_VERSION, version);
 }
 
 int kernctl_metadata_cache_dump(int fd)
@@ -653,15 +620,13 @@ int kernctl_metadata_cache_dump(int fd)
 /* returns the length to mmap. */
 int kernctl_get_mmap_len(int fd, unsigned long *len)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_LEN,
-                       len);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_LEN, len);
 }
 
 /* returns the maximum size for sub-buffers. */
 int kernctl_get_max_subbuf_size(int fd, unsigned long *len)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MAX_SUBBUF_SIZE,
-                       len);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MAX_SUBBUF_SIZE, len);
 }
 
 /*
@@ -672,22 +637,19 @@ int kernctl_get_max_subbuf_size(int fd, unsigned long *len)
 /* returns the offset of the subbuffer belonging to the mmap reader. */
 int kernctl_get_mmap_read_offset(int fd, unsigned long *off)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_READ_OFFSET,
-                       off);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_READ_OFFSET, off);
 }
 
 /* returns the size of the current sub-buffer, without padding (for mmap). */
 int kernctl_get_subbuf_size(int fd, unsigned long *len)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF_SIZE,
-                       len);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF_SIZE, len);
 }
 
 /* returns the size of the current sub-buffer, without padding (for mmap). */
 int kernctl_get_padded_subbuf_size(int fd, unsigned long *len)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_PADDED_SUBBUF_SIZE,
-                       len);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_PADDED_SUBBUF_SIZE, len);
 }
 
 /* Get exclusive read access to the next sub-buffer that can be read. */
@@ -696,7 +658,6 @@ int kernctl_get_next_subbuf(int fd)
        return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF);
 }
 
-
 /* Release exclusive sub-buffer access, move consumer forward. */
 int kernctl_put_next_subbuf(int fd)
 {
@@ -724,22 +685,19 @@ int kernctl_snapshot_sample_positions(int fd)
 /* Get the consumer position (iteration start) */
 int kernctl_snapshot_get_consumed(int fd, unsigned long *pos)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_CONSUMED,
-                       pos);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_CONSUMED, pos);
 }
 
 /* Get the producer position (iteration end) */
 int kernctl_snapshot_get_produced(int fd, unsigned long *pos)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_PRODUCED,
-                       pos);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_PRODUCED, pos);
 }
 
 /* Get exclusive read access to the specified sub-buffer position */
 int kernctl_get_subbuf(int fd, unsigned long *len)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF,
-                       len);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF, len);
 }
 
 /* Release exclusive sub-buffer access */
@@ -751,62 +709,55 @@ int kernctl_put_subbuf(int fd)
 /* Returns the timestamp begin of the current sub-buffer. */
 int kernctl_get_timestamp_begin(int fd, uint64_t *timestamp_begin)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_BEGIN,
-                       timestamp_begin);
+       return LTTNG_IOCTL_CHECK(
+               fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_BEGIN, timestamp_begin);
 }
 
 /* Returns the timestamp end of the current sub-buffer. */
 int kernctl_get_timestamp_end(int fd, uint64_t *timestamp_end)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_END,
-                       timestamp_end);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_END, timestamp_end);
 }
 
 /* Returns the number of discarded events in the current sub-buffer. */
 int kernctl_get_events_discarded(int fd, uint64_t *events_discarded)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_EVENTS_DISCARDED,
-                       events_discarded);
+       return LTTNG_IOCTL_CHECK(
+               fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_EVENTS_DISCARDED, events_discarded);
 }
 
 /* Returns the content size in the current sub-buffer. */
 int kernctl_get_content_size(int fd, uint64_t *content_size)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_CONTENT_SIZE,
-                       content_size);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_CONTENT_SIZE, content_size);
 }
 
 /* Returns the packet size in the current sub-buffer. */
 int kernctl_get_packet_size(int fd, uint64_t *packet_size)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_PACKET_SIZE,
-                       packet_size);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_PACKET_SIZE, packet_size);
 }
 
 /* Returns the stream id of the current sub-buffer. */
 int kernctl_get_stream_id(int fd, uint64_t *stream_id)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_STREAM_ID,
-                       stream_id);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_STREAM_ID, stream_id);
 }
 
 /* Returns the current timestamp. */
 int kernctl_get_current_timestamp(int fd, uint64_t *ts)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_CURRENT_TIMESTAMP,
-                       ts);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_CURRENT_TIMESTAMP, ts);
 }
 
 /* Returns the packet sequence number of the current sub-buffer. */
 int kernctl_get_sequence_number(int fd, uint64_t *seq)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SEQ_NUM,
-                       seq);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_GET_SEQ_NUM, seq);
 }
 
 /* Returns the stream instance id. */
 int kernctl_get_instance_id(int fd, uint64_t *id)
 {
-       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_INSTANCE_ID,
-                       id);
+       return LTTNG_IOCTL_CHECK(fd, LTTNG_KERNEL_ABI_RING_BUFFER_INSTANCE_ID, id);
 }
index 4f47488b56b0e131152cf4e2ccb7e03d09b400e9..f3cfe38ce886a49af924037fcc7321a4c9eeac46 100644 (file)
@@ -9,12 +9,13 @@
 #ifndef _LTTNG_KERNEL_CTL_H
 #define _LTTNG_KERNEL_CTL_H
 
-#include <stdbool.h>
+#include <common/lttng-kernel-old.hpp>
+#include <common/lttng-kernel.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp> /* for struct lttng_filter_bytecode */
 
 #include <lttng/lttng.h>
-#include <common/lttng-kernel.hpp>
-#include <common/lttng-kernel-old.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>      /* for struct lttng_filter_bytecode */
+
+#include <stdbool.h>
 
 int kernctl_create_session(int fd);
 int kernctl_open_metadata(int fd, struct lttng_channel_attr *chops);
@@ -32,15 +33,14 @@ int kernctl_create_event_notifier_group(int fd);
 
 /* Apply on event notifier_group file descriptor. */
 int kernctl_create_event_notifier_group_notification_fd(int fd);
-int kernctl_create_event_notifier_group_error_counter(int fd,
-               const struct lttng_kernel_abi_counter_conf *error_counter_conf);
+int kernctl_create_event_notifier_group_error_counter(
+       int fd, const struct lttng_kernel_abi_counter_conf *error_counter_conf);
 int kernctl_create_event_notifier(int fd,
-               const struct lttng_kernel_abi_event_notifier *event_notifier);
+                                 const struct lttng_kernel_abi_event_notifier *event_notifier);
 
 int kernctl_counter_get_aggregate_value(int counter_fd,
-               struct lttng_kernel_abi_counter_aggregate *value);
-int kernctl_counter_clear(int counter_fd,
-               struct lttng_kernel_abi_counter_clear *clear);
+                                       struct lttng_kernel_abi_counter_aggregate *value);
+int kernctl_counter_clear(int counter_fd, struct lttng_kernel_abi_counter_clear *clear);
 
 /* Apply on event file descriptor. */
 int kernctl_filter(int fd, const struct lttng_bytecode *filter);
@@ -65,8 +65,7 @@ int kernctl_wait_quiescent(int fd);
  * It returns 0 if OK, -1 on error. In all cases (error and OK),
  * @syscall_mask should be freed by the caller with free(3).
  */
-int kernctl_syscall_mask(int fd, char **syscall_mask,
-               uint32_t *nr_bits);
+int kernctl_syscall_mask(int fd, char **syscall_mask, uint32_t *nr_bits);
 
 /* Process ID tracking can be applied to session file descriptor. */
 int kernctl_track_pid(int fd, int pid);
index 68bcc472c009439adc1d76e2207e69ccba2fa5a3..45b01821a997c38989d4bf8990ee9f29f168705a 100644 (file)
 #ifndef _LTT_KERNEL_IOCTL_H
 #define _LTT_KERNEL_IOCTL_H
 
-#define LTTNG_KERNEL_ABI_MAJOR_VERSION         2
-#define LTTNG_KERNEL_ABI_MINOR_VERSION         6
+#define LTTNG_KERNEL_ABI_MAJOR_VERSION 2
+#define LTTNG_KERNEL_ABI_MINOR_VERSION 6
 
 /* Get a snapshot of the current ring buffer producer and consumer positions */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT                _IO(0xF6, 0x00)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT _IO(0xF6, 0x00)
 /* Get the consumer position (iteration start) */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_CONSUMED   _IOR(0xF6, 0x01, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_CONSUMED _IOR(0xF6, 0x01, unsigned long)
 /* Get the producer position (iteration end) */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_PRODUCED   _IOR(0xF6, 0x02, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_GET_PRODUCED _IOR(0xF6, 0x02, unsigned long)
 /* Get exclusive read access to the specified sub-buffer position */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF              _IOW(0xF6, 0x03, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF _IOW(0xF6, 0x03, unsigned long)
 /* Release exclusive sub-buffer access */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_PUT_SUBBUF              _IO(0xF6, 0x04)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_PUT_SUBBUF _IO(0xF6, 0x04)
 
 /* Get exclusive read access to the next sub-buffer that can be read. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF         _IO(0xF6, 0x05)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF _IO(0xF6, 0x05)
 /* Release exclusive sub-buffer access, move consumer forward. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_PUT_NEXT_SUBBUF         _IO(0xF6, 0x06)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_PUT_NEXT_SUBBUF _IO(0xF6, 0x06)
 /* returns the size of the current sub-buffer, without padding (for mmap). */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF_SIZE         _IOR(0xF6, 0x07, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SUBBUF_SIZE _IOR(0xF6, 0x07, unsigned long)
 /* returns the size of the current sub-buffer, with padding (for splice). */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_PADDED_SUBBUF_SIZE  _IOR(0xF6, 0x08, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_PADDED_SUBBUF_SIZE _IOR(0xF6, 0x08, unsigned long)
 /* returns the maximum size for sub-buffers. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MAX_SUBBUF_SIZE     _IOR(0xF6, 0x09, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MAX_SUBBUF_SIZE _IOR(0xF6, 0x09, unsigned long)
 /* returns the length to mmap. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_LEN            _IOR(0xF6, 0x0A, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_LEN _IOR(0xF6, 0x0A, unsigned long)
 /* returns the offset of the subbuffer belonging to the mmap reader. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_READ_OFFSET    _IOR(0xF6, 0x0B, unsigned long)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_MMAP_READ_OFFSET _IOR(0xF6, 0x0B, unsigned long)
 /* Flush the current sub-buffer, if non-empty. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_FLUSH                   _IO(0xF6, 0x0C)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_FLUSH _IO(0xF6, 0x0C)
 /* Get the current version of the metadata cache (after a get_next). */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_METADATA_VERSION    _IOR(0xF6, 0x0D, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_METADATA_VERSION _IOR(0xF6, 0x0D, uint64_t)
 /*
  * Get a snapshot of the current ring buffer producer and consumer positions,
  * regardless of whether or not the two positions are contained within the same
  * sub-buffer.
  */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_SAMPLE_POSITIONS _IO(0xF6, 0x0E)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_SNAPSHOT_SAMPLE_POSITIONS _IO(0xF6, 0x0E)
 /* Flush the current sub-buffer, even if empty. */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_FLUSH_EMPTY                       _IO(0xF6, 0x0F)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_FLUSH_EMPTY _IO(0xF6, 0x0F)
 /*
  * Reset the position of what has been consumed from the metadata cache to 0
  * so it can be read again.
  */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_METADATA_CACHE_DUMP               _IO(0xF6, 0x10)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_METADATA_CACHE_DUMP _IO(0xF6, 0x10)
 /* Clear ring buffer content */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_CLEAR                               _IO(0xF6, 0x11)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_CLEAR                         _IO(0xF6, 0x11)
 #define LTTNG_KERNEL_ABI_RING_BUFFER_GET_NEXT_SUBBUF_METADATA_CHECK _IOR(0xF6, 0x12, uint32_t)
 
 /* returns the timestamp begin of the current sub-buffer */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_BEGIN     _IOR(0xF6, 0x20, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_BEGIN _IOR(0xF6, 0x20, uint64_t)
 /* returns the timestamp end of the current sub-buffer */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_END       _IOR(0xF6, 0x21, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_TIMESTAMP_END _IOR(0xF6, 0x21, uint64_t)
 /* returns the number of events discarded */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_EVENTS_DISCARDED    _IOR(0xF6, 0x22, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_EVENTS_DISCARDED _IOR(0xF6, 0x22, uint64_t)
 /* returns the packet payload size */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_CONTENT_SIZE        _IOR(0xF6, 0x23, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_CONTENT_SIZE _IOR(0xF6, 0x23, uint64_t)
 /* returns the actual packet size */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_PACKET_SIZE         _IOR(0xF6, 0x24, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_PACKET_SIZE _IOR(0xF6, 0x24, uint64_t)
 /* returns the stream id */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_STREAM_ID           _IOR(0xF6, 0x25, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_STREAM_ID _IOR(0xF6, 0x25, uint64_t)
 /* returns the current timestamp */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_CURRENT_TIMESTAMP   _IOR(0xF6, 0x26, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_CURRENT_TIMESTAMP _IOR(0xF6, 0x26, uint64_t)
 /* returns the packet sequence number */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SEQ_NUM             _IOR(0xF6, 0x27, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_GET_SEQ_NUM _IOR(0xF6, 0x27, uint64_t)
 /* returns the stream instance id */
-#define LTTNG_KERNEL_ABI_RING_BUFFER_INSTANCE_ID             _IOR(0xF6, 0x28, uint64_t)
+#define LTTNG_KERNEL_ABI_RING_BUFFER_INSTANCE_ID _IOR(0xF6, 0x28, uint64_t)
 
 /* Old ABI (without support for 32/64 bits compat) */
 /* LTTng file descriptor ioctl */
-#define LTTNG_KERNEL_ABI_OLD_SESSION                _IO(0xF6, 0x40)
-#define LTTNG_KERNEL_ABI_OLD_TRACER_VERSION         \
-               _IOR(0xF6, 0x41, struct lttng_kernel_abi_old_tracer_version)
-#define LTTNG_KERNEL_ABI_OLD_TRACEPOINT_LIST        _IO(0xF6, 0x42)
-#define LTTNG_KERNEL_ABI_OLD_WAIT_QUIESCENT         _IO(0xF6, 0x43)
+#define LTTNG_KERNEL_ABI_OLD_SESSION _IO(0xF6, 0x40)
+#define LTTNG_KERNEL_ABI_OLD_TRACER_VERSION \
+       _IOR(0xF6, 0x41, struct lttng_kernel_abi_old_tracer_version)
+#define LTTNG_KERNEL_ABI_OLD_TRACEPOINT_LIST _IO(0xF6, 0x42)
+#define LTTNG_KERNEL_ABI_OLD_WAIT_QUIESCENT  _IO(0xF6, 0x43)
 
 /* Session FD ioctl */
-#define LTTNG_KERNEL_ABI_OLD_METADATA               \
-               _IOW(0xF6, 0x50, struct lttng_kernel_abi_old_channel)
-#define LTTNG_KERNEL_ABI_OLD_CHANNEL                \
-               _IOW(0xF6, 0x51, struct lttng_kernel_abi_old_channel)
-#define LTTNG_KERNEL_ABI_OLD_SESSION_START          _IO(0xF6, 0x52)
-#define LTTNG_KERNEL_ABI_OLD_SESSION_STOP           _IO(0xF6, 0x53)
+#define LTTNG_KERNEL_ABI_OLD_METADATA     _IOW(0xF6, 0x50, struct lttng_kernel_abi_old_channel)
+#define LTTNG_KERNEL_ABI_OLD_CHANNEL      _IOW(0xF6, 0x51, struct lttng_kernel_abi_old_channel)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_START _IO(0xF6, 0x52)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_STOP  _IO(0xF6, 0x53)
 
 /* Channel FD ioctl */
-#define LTTNG_KERNEL_ABI_OLD_STREAM                 _IO(0xF6, 0x60)
-#define LTTNG_KERNEL_ABI_OLD_EVENT                  \
-               _IOW(0xF6, 0x61, struct lttng_kernel_abi_old_event)
+#define LTTNG_KERNEL_ABI_OLD_STREAM _IO(0xF6, 0x60)
+#define LTTNG_KERNEL_ABI_OLD_EVENT  _IOW(0xF6, 0x61, struct lttng_kernel_abi_old_event)
 
 /* Event and Channel FD ioctl */
-#define LTTNG_KERNEL_ABI_OLD_CONTEXT                \
-               _IOW(0xF6, 0x70, struct lttng_kernel_abi_old_context)
+#define LTTNG_KERNEL_ABI_OLD_CONTEXT _IOW(0xF6, 0x70, struct lttng_kernel_abi_old_context)
 
 /* Event, Channel and Session ioctl */
-#define LTTNG_KERNEL_ABI_OLD_ENABLE                 _IO(0xF6, 0x80)
-#define LTTNG_KERNEL_ABI_OLD_DISABLE                _IO(0xF6, 0x81)
-
+#define LTTNG_KERNEL_ABI_OLD_ENABLE  _IO(0xF6, 0x80)
+#define LTTNG_KERNEL_ABI_OLD_DISABLE _IO(0xF6, 0x81)
 
 /* Current ABI (with suport for 32/64 bits compat) */
 /* LTTng file descriptor ioctl */
-#define LTTNG_KERNEL_ABI_SESSION               _IO(0xF6, 0x45)
-#define LTTNG_KERNEL_ABI_TRACER_VERSION                \
-       _IOR(0xF6, 0x46, struct lttng_kernel_abi_tracer_version)
-#define LTTNG_KERNEL_ABI_TRACEPOINT_LIST       _IO(0xF6, 0x47)
-#define LTTNG_KERNEL_ABI_WAIT_QUIESCENT                _IO(0xF6, 0x48)
-#define LTTNG_KERNEL_ABI_SYSCALL_LIST          _IO(0xF6, 0x4A)
-#define LTTNG_KERNEL_ABI_TRACER_ABI_VERSION            \
+#define LTTNG_KERNEL_ABI_SESSION        _IO(0xF6, 0x45)
+#define LTTNG_KERNEL_ABI_TRACER_VERSION         _IOR(0xF6, 0x46, struct lttng_kernel_abi_tracer_version)
+#define LTTNG_KERNEL_ABI_TRACEPOINT_LIST _IO(0xF6, 0x47)
+#define LTTNG_KERNEL_ABI_WAIT_QUIESCENT         _IO(0xF6, 0x48)
+#define LTTNG_KERNEL_ABI_SYSCALL_LIST   _IO(0xF6, 0x4A)
+#define LTTNG_KERNEL_ABI_TRACER_ABI_VERSION \
        _IOR(0xF6, 0x4B, struct lttng_kernel_abi_tracer_abi_version)
-#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_CREATE \
-       _IO(0xF6, 0x4C)
+#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_CREATE _IO(0xF6, 0x4C)
 
 /* Session FD ioctl */
-#define LTTNG_KERNEL_ABI_METADATA                      \
-       _IOW(0xF6, 0x54, struct lttng_kernel_abi_channel)
-#define LTTNG_KERNEL_ABI_CHANNEL                       \
-       _IOW(0xF6, 0x55, struct lttng_kernel_abi_channel)
-#define LTTNG_KERNEL_ABI_SESSION_START         _IO(0xF6, 0x56)
-#define LTTNG_KERNEL_ABI_SESSION_STOP          _IO(0xF6, 0x57)
-#define LTTNG_KERNEL_ABI_SESSION_TRACK_PID             \
-       _IOW(0xF6, 0x58, int32_t)
-#define LTTNG_KERNEL_ABI_SESSION_UNTRACK_PID   \
-       _IOW(0xF6, 0x59, int32_t)
+#define LTTNG_KERNEL_ABI_METADATA           _IOW(0xF6, 0x54, struct lttng_kernel_abi_channel)
+#define LTTNG_KERNEL_ABI_CHANNEL            _IOW(0xF6, 0x55, struct lttng_kernel_abi_channel)
+#define LTTNG_KERNEL_ABI_SESSION_START      _IO(0xF6, 0x56)
+#define LTTNG_KERNEL_ABI_SESSION_STOP       _IO(0xF6, 0x57)
+#define LTTNG_KERNEL_ABI_SESSION_TRACK_PID   _IOW(0xF6, 0x58, int32_t)
+#define LTTNG_KERNEL_ABI_SESSION_UNTRACK_PID _IOW(0xF6, 0x59, int32_t)
 /*
  * ioctl 0x58 and 0x59 are duplicated here. It works, since _IOR vs _IO
  * are generating two different ioctl numbers, but this was not done on
  * purpose. We should generally try to avoid those duplications.
  */
-#define LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_PIDS  _IO(0xF6, 0x58)
-#define LTTNG_KERNEL_ABI_SESSION_METADATA_REGEN            _IO(0xF6, 0x59)
+#define LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_PIDS _IO(0xF6, 0x58)
+#define LTTNG_KERNEL_ABI_SESSION_METADATA_REGEN           _IO(0xF6, 0x59)
 /* 0x5A and 0x5B are reserved for a future ABI-breaking cleanup. */
-#define LTTNG_KERNEL_ABI_SESSION_STATEDUMP         _IO(0xF6, 0x5C)
-#define LTTNG_KERNEL_ABI_SESSION_SET_NAME              \
-       _IOW(0xF6, 0x5D, struct lttng_kernel_abi_session_name)
-#define LTTNG_KERNEL_ABI_SESSION_SET_CREATION_TIME             \
+#define LTTNG_KERNEL_ABI_SESSION_STATEDUMP _IO(0xF6, 0x5C)
+#define LTTNG_KERNEL_ABI_SESSION_SET_NAME  _IOW(0xF6, 0x5D, struct lttng_kernel_abi_session_name)
+#define LTTNG_KERNEL_ABI_SESSION_SET_CREATION_TIME \
        _IOW(0xF6, 0x5E, struct lttng_kernel_abi_session_creation_time)
 
 /* Channel FD ioctl */
-#define LTTNG_KERNEL_ABI_STREAM                        _IO(0xF6, 0x62)
-#define LTTNG_KERNEL_ABI_EVENT                 \
-       _IOW(0xF6, 0x63, struct lttng_kernel_abi_event)
-#define LTTNG_KERNEL_ABI_SYSCALL_MASK          \
-       _IOWR(0xF6, 0x64, struct lttng_kernel_abi_syscall_mask)
+#define LTTNG_KERNEL_ABI_STREAM              _IO(0xF6, 0x62)
+#define LTTNG_KERNEL_ABI_EVENT       _IOW(0xF6, 0x63, struct lttng_kernel_abi_event)
+#define LTTNG_KERNEL_ABI_SYSCALL_MASK _IOWR(0xF6, 0x64, struct lttng_kernel_abi_syscall_mask)
 
 /* Event and Channel FD ioctl */
-#define LTTNG_KERNEL_ABI_CONTEXT                       \
-       _IOW(0xF6, 0x71, struct lttng_kernel_abi_context)
+#define LTTNG_KERNEL_ABI_CONTEXT _IOW(0xF6, 0x71, struct lttng_kernel_abi_context)
 
 /* Event, event notifier, Channel and Session ioctl */
-#define LTTNG_KERNEL_ABI_ENABLE                        _IO(0xF6, 0x82)
-#define LTTNG_KERNEL_ABI_DISABLE               _IO(0xF6, 0x83)
+#define LTTNG_KERNEL_ABI_ENABLE         _IO(0xF6, 0x82)
+#define LTTNG_KERNEL_ABI_DISABLE _IO(0xF6, 0x83)
 
 /* Event notifier group ioctl */
-#define LTTNG_KERNEL_ABI_COUNTER                       \
-       _IOW(0xF6, 0x84, struct lttng_kernel_abi_counter_conf)
+#define LTTNG_KERNEL_ABI_COUNTER _IOW(0xF6, 0x84, struct lttng_kernel_abi_counter_conf)
 
 /* Event and event notifier FD ioctl */
-#define LTTNG_KERNEL_ABI_FILTER                        _IO(0xF6, 0x90)
-#define LTTNG_KERNEL_ABI_ADD_CALLSITE          _IO(0xF6, 0x91)
+#define LTTNG_KERNEL_ABI_FILTER              _IO(0xF6, 0x90)
+#define LTTNG_KERNEL_ABI_ADD_CALLSITE _IO(0xF6, 0x91)
 
 /* Session FD ioctl (continued) */
-#define LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_IDS      \
+#define LTTNG_KERNEL_ABI_SESSION_LIST_TRACKER_IDS \
        _IOW(0xF6, 0xA0, struct lttng_kernel_abi_tracker_args)
-#define LTTNG_KERNEL_ABI_SESSION_TRACK_ID              \
-       _IOW(0xF6, 0xA1, struct lttng_kernel_abi_tracker_args)
-#define LTTNG_KERNEL_ABI_SESSION_UNTRACK_ID            \
-       _IOW(0xF6, 0xA2, struct lttng_kernel_abi_tracker_args)
+#define LTTNG_KERNEL_ABI_SESSION_TRACK_ID   _IOW(0xF6, 0xA1, struct lttng_kernel_abi_tracker_args)
+#define LTTNG_KERNEL_ABI_SESSION_UNTRACK_ID _IOW(0xF6, 0xA2, struct lttng_kernel_abi_tracker_args)
 
 /* Event notifier group file descriptor ioctl */
-#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_CREATE                 \
+#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_CREATE \
        _IOW(0xF6, 0xB0, struct lttng_kernel_abi_event_notifier)
-#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD  \
-       _IO(0xF6, 0xB1)
+#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_GROUP_NOTIFICATION_FD _IO(0xF6, 0xB1)
 
 /* Event notifier file descriptor ioctl */
-#define LTTNG_KERNEL_ABI_CAPTURE               _IO(0xF6, 0xB8)
+#define LTTNG_KERNEL_ABI_CAPTURE _IO(0xF6, 0xB8)
 
 /* Counter file descriptor ioctl */
-#define LTTNG_KERNEL_ABI_COUNTER_READ          \
-       IOWR(0xF6, 0xC0, struct lttng_kernel_abi_counter_read)
-#define LTTNG_KERNEL_ABI_COUNTER_AGGREGATE             \
+#define LTTNG_KERNEL_ABI_COUNTER_READ IOWR(0xF6, 0xC0, struct lttng_kernel_abi_counter_read)
+#define LTTNG_KERNEL_ABI_COUNTER_AGGREGATE \
        _IOWR(0xF6, 0xC1, struct lttng_kernel_abi_counter_aggregate)
-#define LTTNG_KERNEL_ABI_COUNTER_CLEAR         \
-       _IOW(0xF6, 0xC2, struct lttng_kernel_abi_counter_clear)
+#define LTTNG_KERNEL_ABI_COUNTER_CLEAR _IOW(0xF6, 0xC2, struct lttng_kernel_abi_counter_clear)
 
 /*
-  * Those ioctl numbers use the wrong direction, but are kept for ABI backward
-  * compatibility.
-  */
- #define LTTNG_KERNEL_ABI_OLD_SESSION_SET_NAME        \
-     _IOR(0xF6, 0x5D, struct lttng_kernel_abi_session_name)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_SET_CREATION_TIME    \
-     _IOR(0xF6, 0x5E, struct lttng_kernel_abi_session_creation_time)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_PID        \
-     _IOW(0xF6, 0x58, int32_t)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_PID    \
-     _IOW(0xF6, 0x59, int32_t)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_LIST_TRACKER_IDS    \
-     _IOR(0xF6, 0xA0, struct lttng_kernel_abi_tracker_args)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_ID        \
-     _IOR(0xF6, 0xA1, struct lttng_kernel_abi_tracker_args)
- #define LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_ID        \
-     _IOR(0xF6, 0xA2, struct lttng_kernel_abi_tracker_args)
+ * Those ioctl numbers use the wrong direction, but are kept for ABI backward
+ * compatibility.
+ */
+#define LTTNG_KERNEL_ABI_OLD_SESSION_SET_NAME _IOR(0xF6, 0x5D, struct lttng_kernel_abi_session_name)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_SET_CREATION_TIME \
+       _IOR(0xF6, 0x5E, struct lttng_kernel_abi_session_creation_time)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_PID  _IOW(0xF6, 0x58, int32_t)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_PID _IOW(0xF6, 0x59, int32_t)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_LIST_TRACKER_IDS \
+       _IOR(0xF6, 0xA0, struct lttng_kernel_abi_tracker_args)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_TRACK_ID _IOR(0xF6, 0xA1, struct lttng_kernel_abi_tracker_args)
+#define LTTNG_KERNEL_ABI_OLD_SESSION_UNTRACK_ID \
+       _IOR(0xF6, 0xA2, struct lttng_kernel_abi_tracker_args)
 
 #endif /* _LTT_KERNEL_IOCTL_H */
index b01b44b960a72bf77b92d34ef9fcb41d1657e32d..d1b6744d9eac938b946e694a926d32f0ebedc736 100644 (file)
@@ -6,6 +6,7 @@
  */
 
 #include "lttng/lttng-error.h"
+
 #include <common/error.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/mi-lttng.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
-#include <fcntl.h>
+
 #include <lttng/constant.h>
 #include <lttng/kernel-probe-internal.hpp>
 #include <lttng/kernel-probe.h>
+
+#include <fcntl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-static
-int lttng_kernel_probe_location_address_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload);
-
-static
-int lttng_kernel_probe_location_symbol_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload);
-
-static
-bool lttng_kernel_probe_location_address_is_equal(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b);
-
-static
-bool lttng_kernel_probe_location_symbol_is_equal(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b);
-
-static
-unsigned long lttng_kernel_probe_location_address_hash(
-               const struct lttng_kernel_probe_location *location);
-
-static
-unsigned long lttng_kernel_probe_location_symbol_hash(
-               const struct lttng_kernel_probe_location *location);
-
-static
-enum lttng_error_code lttng_kernel_probe_location_address_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer);
-
-static
-enum lttng_error_code lttng_kernel_probe_location_symbol_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer);
-
-enum lttng_kernel_probe_location_type lttng_kernel_probe_location_get_type(
-               const struct lttng_kernel_probe_location *location)
+static int
+lttng_kernel_probe_location_address_serialize(const struct lttng_kernel_probe_location *location,
+                                             struct lttng_payload *payload);
+
+static int
+lttng_kernel_probe_location_symbol_serialize(const struct lttng_kernel_probe_location *location,
+                                            struct lttng_payload *payload);
+
+static bool
+lttng_kernel_probe_location_address_is_equal(const struct lttng_kernel_probe_location *a,
+                                            const struct lttng_kernel_probe_location *b);
+
+static bool
+lttng_kernel_probe_location_symbol_is_equal(const struct lttng_kernel_probe_location *a,
+                                           const struct lttng_kernel_probe_location *b);
+
+static unsigned long
+lttng_kernel_probe_location_address_hash(const struct lttng_kernel_probe_location *location);
+
+static unsigned long
+lttng_kernel_probe_location_symbol_hash(const struct lttng_kernel_probe_location *location);
+
+static enum lttng_error_code
+lttng_kernel_probe_location_address_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                                struct mi_writer *writer);
+
+static enum lttng_error_code
+lttng_kernel_probe_location_symbol_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                               struct mi_writer *writer);
+
+enum lttng_kernel_probe_location_type
+lttng_kernel_probe_location_get_type(const struct lttng_kernel_probe_location *location)
 {
-       return location ? location->type :
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_UNKNOWN;
+       return location ? location->type : LTTNG_KERNEL_PROBE_LOCATION_TYPE_UNKNOWN;
 }
 
-static
-void lttng_kernel_probe_location_address_destroy(
-               struct lttng_kernel_probe_location *location)
+static void
+lttng_kernel_probe_location_address_destroy(struct lttng_kernel_probe_location *location)
 {
        LTTNG_ASSERT(location);
        free(location);
 }
 
-static
-void lttng_kernel_probe_location_symbol_destroy(
-               struct lttng_kernel_probe_location *location)
+static void lttng_kernel_probe_location_symbol_destroy(struct lttng_kernel_probe_location *location)
 {
-       struct lttng_kernel_probe_location_symbol *location_symbol = NULL;
+       struct lttng_kernel_probe_location_symbol *location_symbol = nullptr;
 
        LTTNG_ASSERT(location);
 
-       location_symbol = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_symbol::parent);
+       location_symbol =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_symbol::parent);
 
        LTTNG_ASSERT(location_symbol);
 
@@ -91,8 +82,7 @@ void lttng_kernel_probe_location_symbol_destroy(
        free(location);
 }
 
-void lttng_kernel_probe_location_destroy(
-               struct lttng_kernel_probe_location *location)
+void lttng_kernel_probe_location_destroy(struct lttng_kernel_probe_location *location)
 {
        if (!location) {
                return;
@@ -110,10 +100,9 @@ void lttng_kernel_probe_location_destroy(
        }
 }
 
-struct lttng_kernel_probe_location *
-lttng_kernel_probe_location_address_create(uint64_t address)
+struct lttng_kernel_probe_location *lttng_kernel_probe_location_address_create(uint64_t address)
 {
-       struct lttng_kernel_probe_location *ret = NULL;
+       struct lttng_kernel_probe_location *ret = nullptr;
        struct lttng_kernel_probe_location_address *location;
 
        location = zmalloc<lttng_kernel_probe_location_address>();
@@ -136,11 +125,10 @@ end:
 }
 
 struct lttng_kernel_probe_location *
-lttng_kernel_probe_location_symbol_create(const char *symbol_name,
-               uint64_t offset)
+lttng_kernel_probe_location_symbol_create(const char *symbol_name, uint64_t offset)
 {
-       char *symbol_name_copy = NULL;
-       struct lttng_kernel_probe_location *ret = NULL;
+       char *symbol_name_copy = nullptr;
+       struct lttng_kernel_probe_location *ret = nullptr;
        struct lttng_kernel_probe_location_symbol *location;
 
        if (!symbol_name || strlen(symbol_name) >= LTTNG_SYMBOL_NAME_LEN) {
@@ -177,78 +165,76 @@ end:
 }
 
 enum lttng_kernel_probe_location_status
-lttng_kernel_probe_location_address_get_address(
-               const struct lttng_kernel_probe_location *location,
-               uint64_t *offset)
+lttng_kernel_probe_location_address_get_address(const struct lttng_kernel_probe_location *location,
+                                               uint64_t *offset)
 {
-       enum lttng_kernel_probe_location_status ret =
-                       LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK;
+       enum lttng_kernel_probe_location_status ret = LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK;
        struct lttng_kernel_probe_location_address *address_location;
 
        LTTNG_ASSERT(offset);
 
-       if (!location || lttng_kernel_probe_location_get_type(location) !=
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS) {
+       if (!location ||
+           lttng_kernel_probe_location_get_type(location) !=
+                   LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                ret = LTTNG_KERNEL_PROBE_LOCATION_STATUS_INVALID;
                goto end;
        }
 
-       address_location = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_address::parent);
+       address_location =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_address::parent);
        *offset = address_location->address;
 end:
        return ret;
 }
 
-const char *lttng_kernel_probe_location_symbol_get_name(
-               const struct lttng_kernel_probe_location *location)
+const char *
+lttng_kernel_probe_location_symbol_get_name(const struct lttng_kernel_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_kernel_probe_location_symbol *symbol_location;
 
-       if (!location || lttng_kernel_probe_location_get_type(location) !=
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET) {
+       if (!location ||
+           lttng_kernel_probe_location_get_type(location) !=
+                   LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       symbol_location = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_symbol::parent);
+       symbol_location =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_symbol::parent);
        ret = symbol_location->symbol_name;
 end:
        return ret;
 }
 
 enum lttng_kernel_probe_location_status
-lttng_kernel_probe_location_symbol_get_offset(
-               const struct lttng_kernel_probe_location *location,
-               uint64_t *offset)
+lttng_kernel_probe_location_symbol_get_offset(const struct lttng_kernel_probe_location *location,
+                                             uint64_t *offset)
 {
-       enum lttng_kernel_probe_location_status ret =
-                       LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK;
+       enum lttng_kernel_probe_location_status ret = LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK;
        struct lttng_kernel_probe_location_symbol *symbol_location;
 
        LTTNG_ASSERT(offset);
 
-       if (!location || lttng_kernel_probe_location_get_type(location) !=
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET) {
+       if (!location ||
+           lttng_kernel_probe_location_get_type(location) !=
+                   LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                ret = LTTNG_KERNEL_PROBE_LOCATION_STATUS_INVALID;
                goto end;
        }
 
-       symbol_location = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_symbol::parent);
+       symbol_location =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_symbol::parent);
        *offset = symbol_location->offset;
 end:
        return ret;
 }
 
-static
-int lttng_kernel_probe_location_symbol_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload)
+static int
+lttng_kernel_probe_location_symbol_serialize(const struct lttng_kernel_probe_location *location,
+                                            struct lttng_payload *payload)
 {
        int ret;
        size_t symbol_name_len;
@@ -263,11 +249,11 @@ int lttng_kernel_probe_location_symbol_serialize(
        }
 
        LTTNG_ASSERT(lttng_kernel_probe_location_get_type(location) ==
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
+                    LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
 
        original_payload_size = payload->buffer.size;
-       location_symbol = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_symbol::parent);
+       location_symbol =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_symbol::parent);
 
        if (!location_symbol->symbol_name) {
                ret = -LTTNG_ERR_INVALID;
@@ -283,16 +269,15 @@ int lttng_kernel_probe_location_symbol_serialize(
        location_symbol_comm.symbol_len = symbol_name_len + 1;
        location_symbol_comm.offset = location_symbol->offset;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       &location_symbol_comm, sizeof(location_symbol_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &location_symbol_comm, sizeof(location_symbol_comm));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       location_symbol->symbol_name,
-                       location_symbol_comm.symbol_len);
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, location_symbol->symbol_name, location_symbol_comm.symbol_len);
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -303,10 +288,9 @@ end:
        return ret;
 }
 
-static
-int lttng_kernel_probe_location_address_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload)
+static int
+lttng_kernel_probe_location_address_serialize(const struct lttng_kernel_probe_location *location,
+                                             struct lttng_payload *payload)
 {
        int ret;
        size_t original_payload_size;
@@ -315,17 +299,16 @@ int lttng_kernel_probe_location_address_serialize(
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(lttng_kernel_probe_location_get_type(location) ==
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
+                    LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
 
        original_payload_size = payload->buffer.size;
-       location_address = lttng::utils::container_of(location,
-                       &lttng_kernel_probe_location_address::parent);
+       location_address =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_address::parent);
 
        location_address_comm.address = location_address->address;
 
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       &location_address_comm,
-                       sizeof(location_address_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &location_address_comm, sizeof(location_address_comm));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -336,9 +319,8 @@ end:
        return ret;
 }
 
-int lttng_kernel_probe_location_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct lttng_payload *payload)
+int lttng_kernel_probe_location_serialize(const struct lttng_kernel_probe_location *location,
+                                         struct lttng_payload *payload)
 {
        int ret;
        size_t original_payload_size;
@@ -352,9 +334,8 @@ int lttng_kernel_probe_location_serialize(
 
        original_payload_size = payload->buffer.size;
        location_generic_comm.type = (int8_t) location->type;
-       ret = lttng_dynamic_buffer_append(&payload->buffer,
-                       &location_generic_comm,
-                       sizeof(location_generic_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &location_generic_comm, sizeof(location_generic_comm));
        if (ret) {
                goto end;
        }
@@ -369,10 +350,8 @@ end:
        return ret;
 }
 
-static
-int lttng_kernel_probe_location_symbol_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_kernel_probe_location **location)
+static int lttng_kernel_probe_location_symbol_create_from_payload(
+       struct lttng_payload_view *view, struct lttng_kernel_probe_location **location)
 {
        struct lttng_kernel_probe_location_symbol_comm *location_symbol_comm;
        const char *symbol_name_src;
@@ -386,11 +365,9 @@ int lttng_kernel_probe_location_symbol_create_from_payload(
                goto end;
        }
 
-       location_symbol_comm =
-                       (typeof(location_symbol_comm)) view->buffer.data;
+       location_symbol_comm = (typeof(location_symbol_comm)) view->buffer.data;
 
-       expected_size = sizeof(*location_symbol_comm) +
-                       location_symbol_comm->symbol_len;
+       expected_size = sizeof(*location_symbol_comm) + location_symbol_comm->symbol_len;
 
        if (view->buffer.size < expected_size) {
                ret = -LTTNG_ERR_INVALID;
@@ -399,14 +376,14 @@ int lttng_kernel_probe_location_symbol_create_from_payload(
 
        symbol_name_src = view->buffer.data + sizeof(*location_symbol_comm);
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, symbol_name_src,
-                       location_symbol_comm->symbol_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, symbol_name_src, location_symbol_comm->symbol_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       *location = lttng_kernel_probe_location_symbol_create(
-                       symbol_name_src, location_symbol_comm->offset);
+       *location = lttng_kernel_probe_location_symbol_create(symbol_name_src,
+                                                             location_symbol_comm->offset);
        if (!(*location)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -417,10 +394,8 @@ end:
        return ret;
 }
 
-static
-ssize_t lttng_kernel_probe_location_address_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_kernel_probe_location **location)
+static ssize_t lttng_kernel_probe_location_address_create_from_payload(
+       struct lttng_payload_view *view, struct lttng_kernel_probe_location **location)
 {
        struct lttng_kernel_probe_location_address_comm *location_address_comm;
        ssize_t ret = 0;
@@ -435,8 +410,7 @@ ssize_t lttng_kernel_probe_location_address_create_from_payload(
                goto end;
        }
 
-       location_address_comm =
-                       (typeof(location_address_comm)) view->buffer.data;
+       location_address_comm = (typeof(location_address_comm)) view->buffer.data;
 
        *location = lttng_kernel_probe_location_address_create(location_address_comm->address);
        if (!(*location)) {
@@ -449,17 +423,16 @@ end:
        return ret;
 }
 
-ssize_t lttng_kernel_probe_location_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_kernel_probe_location **location)
+ssize_t
+lttng_kernel_probe_location_create_from_payload(struct lttng_payload_view *view,
+                                               struct lttng_kernel_probe_location **location)
 {
        enum lttng_kernel_probe_location_type type;
        ssize_t consumed = 0;
        ssize_t ret;
        const struct lttng_kernel_probe_location_comm *probe_location_comm;
        const struct lttng_payload_view probe_location_comm_view =
-                       lttng_payload_view_from_view(
-                                       view, 0, sizeof(*probe_location_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*probe_location_comm));
 
        LTTNG_ASSERT(view);
        LTTNG_ASSERT(location);
@@ -477,20 +450,19 @@ ssize_t lttng_kernel_probe_location_create_from_payload(
        case LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET:
        {
                struct lttng_payload_view location_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
-               ret = lttng_kernel_probe_location_symbol_create_from_payload(
-                               &location_view, location);
+               ret = lttng_kernel_probe_location_symbol_create_from_payload(&location_view,
+                                                                            location);
                break;
        }
        case LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS:
        {
                struct lttng_payload_view location_view =
-                               lttng_payload_view_from_view(view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
-               ret = lttng_kernel_probe_location_address_create_from_payload(
-                               &location_view, location);
+               ret = lttng_kernel_probe_location_address_create_from_payload(&location_view,
+                                                                             location);
                break;
        }
        default:
@@ -509,25 +481,22 @@ end:
        return ret;
 }
 
-static
-unsigned long lttng_kernel_probe_location_address_hash(
-               const struct lttng_kernel_probe_location *location)
+static unsigned long
+lttng_kernel_probe_location_address_hash(const struct lttng_kernel_probe_location *location)
 {
-       unsigned long hash = hash_key_ulong(
-                       (void *) LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS,
-                       lttng_ht_seed);
-       struct lttng_kernel_probe_location_address *address_location = lttng::utils::container_of(
-                       location, &lttng_kernel_probe_location_address::parent);
+       unsigned long hash =
+               hash_key_ulong((void *) LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS, lttng_ht_seed);
+       struct lttng_kernel_probe_location_address *address_location =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_address::parent);
 
        hash ^= hash_key_u64(&address_location->address, lttng_ht_seed);
 
        return hash;
 }
 
-static
-bool lttng_kernel_probe_location_address_is_equal(
-               const struct lttng_kernel_probe_location *_a,
-               const struct lttng_kernel_probe_location *_b)
+static bool
+lttng_kernel_probe_location_address_is_equal(const struct lttng_kernel_probe_location *_a,
+                                            const struct lttng_kernel_probe_location *_b)
 {
        bool is_equal = false;
        struct lttng_kernel_probe_location_address *a, *b;
@@ -545,14 +514,13 @@ end:
        return is_equal;
 }
 
-static
-unsigned long lttng_kernel_probe_location_symbol_hash(
-               const struct lttng_kernel_probe_location *location)
+static unsigned long
+lttng_kernel_probe_location_symbol_hash(const struct lttng_kernel_probe_location *location)
 {
-       unsigned long hash = hash_key_ulong(
-                       (void *) LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET, lttng_ht_seed);
-       struct lttng_kernel_probe_location_symbol *symbol_location = lttng::utils::container_of(
-                       location, &lttng_kernel_probe_location_symbol::parent);
+       unsigned long hash = hash_key_ulong((void *) LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET,
+                                           lttng_ht_seed);
+       struct lttng_kernel_probe_location_symbol *symbol_location =
+               lttng::utils::container_of(location, &lttng_kernel_probe_location_symbol::parent);
 
        hash ^= hash_key_str(symbol_location->symbol_name, lttng_ht_seed);
        hash ^= hash_key_u64(&symbol_location->offset, lttng_ht_seed);
@@ -560,22 +528,19 @@ unsigned long lttng_kernel_probe_location_symbol_hash(
        return hash;
 }
 
-static
-bool lttng_kernel_probe_location_symbol_is_equal(
-               const struct lttng_kernel_probe_location *_a,
-               const struct lttng_kernel_probe_location *_b)
+static bool
+lttng_kernel_probe_location_symbol_is_equal(const struct lttng_kernel_probe_location *_a,
+                                           const struct lttng_kernel_probe_location *_b)
 {
        bool is_equal = false;
        struct lttng_kernel_probe_location_symbol *a, *b;
 
-       a = lttng::utils::container_of(_a,
-                       &lttng_kernel_probe_location_symbol::parent);
-       b = lttng::utils::container_of(_b,
-                       &lttng_kernel_probe_location_symbol::parent);
+       a = lttng::utils::container_of(_a, &lttng_kernel_probe_location_symbol::parent);
+       b = lttng::utils::container_of(_b, &lttng_kernel_probe_location_symbol::parent);
 
        LTTNG_ASSERT(a->symbol_name);
        LTTNG_ASSERT(b->symbol_name);
-       if (strcmp(a->symbol_name, b->symbol_name)) {
+       if (strcmp(a->symbol_name, b->symbol_name) != 0) {
                goto end;
        }
 
@@ -589,9 +554,8 @@ end:
        return is_equal;
 }
 
-bool lttng_kernel_probe_location_is_equal(
-               const struct lttng_kernel_probe_location *a,
-               const struct lttng_kernel_probe_location *b)
+bool lttng_kernel_probe_location_is_equal(const struct lttng_kernel_probe_location *a,
+                                         const struct lttng_kernel_probe_location *b)
 {
        bool is_equal = false;
 
@@ -614,18 +578,17 @@ end:
 }
 
 static struct lttng_kernel_probe_location *
-lttng_kernel_probe_location_symbol_copy(
-               const struct lttng_kernel_probe_location *location)
+lttng_kernel_probe_location_symbol_copy(const struct lttng_kernel_probe_location *location)
 {
-       struct lttng_kernel_probe_location *new_location = NULL;
+       struct lttng_kernel_probe_location *new_location = nullptr;
        enum lttng_kernel_probe_location_status status;
-       const char *symbol_name = NULL;
+       const char *symbol_name = nullptr;
        uint64_t offset;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(location->type == LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
 
-        /* Get probe location offset */
+       /* Get probe location offset */
        status = lttng_kernel_probe_location_symbol_get_offset(location, &offset);
        if (status != LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK) {
                ERR("Get kernel probe location offset failed.");
@@ -639,21 +602,19 @@ lttng_kernel_probe_location_symbol_copy(
        }
 
        /* Create the probe_location */
-       new_location = lttng_kernel_probe_location_symbol_create(
-                       symbol_name, offset);
+       new_location = lttng_kernel_probe_location_symbol_create(symbol_name, offset);
 
        goto end;
 
 error:
-       new_location = NULL;
+       new_location = nullptr;
 end:
        return new_location;
 }
 static struct lttng_kernel_probe_location *
-lttng_kernel_probe_location_address_copy(
-               const struct lttng_kernel_probe_location *location)
+lttng_kernel_probe_location_address_copy(const struct lttng_kernel_probe_location *location)
 {
-       struct lttng_kernel_probe_location *new_location = NULL;
+       struct lttng_kernel_probe_location *new_location = nullptr;
        enum lttng_kernel_probe_location_status status;
        uint64_t address;
 
@@ -673,15 +634,15 @@ lttng_kernel_probe_location_address_copy(
        goto end;
 
 error:
-       new_location = NULL;
+       new_location = nullptr;
 end:
        return new_location;
 }
 
-struct lttng_kernel_probe_location *lttng_kernel_probe_location_copy(
-               const struct lttng_kernel_probe_location *location)
+struct lttng_kernel_probe_location *
+lttng_kernel_probe_location_copy(const struct lttng_kernel_probe_location *location)
 {
-       struct lttng_kernel_probe_location *new_location = NULL;
+       struct lttng_kernel_probe_location *new_location = nullptr;
        enum lttng_kernel_probe_location_type type;
 
        if (!location) {
@@ -691,37 +652,33 @@ struct lttng_kernel_probe_location *lttng_kernel_probe_location_copy(
        type = lttng_kernel_probe_location_get_type(location);
        switch (type) {
        case LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS:
-               new_location =
-                       lttng_kernel_probe_location_address_copy(location);
+               new_location = lttng_kernel_probe_location_address_copy(location);
                if (!new_location) {
                        goto err;
                }
                break;
        case LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET:
-               new_location =
-                       lttng_kernel_probe_location_symbol_copy(location);
+               new_location = lttng_kernel_probe_location_symbol_copy(location);
                if (!new_location) {
                        goto err;
                }
                break;
        default:
-               new_location = NULL;
+               new_location = nullptr;
                goto err;
        }
 err:
        return new_location;
 }
 
-unsigned long lttng_kernel_probe_location_hash(
-       const struct lttng_kernel_probe_location *location)
+unsigned long lttng_kernel_probe_location_hash(const struct lttng_kernel_probe_location *location)
 {
        return location->hash(location);
 }
 
-static
-enum lttng_error_code lttng_kernel_probe_location_address_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_kernel_probe_location_address_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                                struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -732,20 +689,17 @@ enum lttng_error_code lttng_kernel_probe_location_address_mi_serialize(
        LTTNG_ASSERT(writer);
        LTTNG_ASSERT(location->type == LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
 
-       status = lttng_kernel_probe_location_address_get_address(
-                       location, &address);
+       status = lttng_kernel_probe_location_address_get_address(location, &address);
        LTTNG_ASSERT(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK);
 
        /* Open kernel probe location address element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_kernel_probe_location_address);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_kernel_probe_location_address);
        if (ret) {
                goto mi_error;
        }
 
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_kernel_probe_location_address_address,
-                       address);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_kernel_probe_location_address_address, address);
        if (ret) {
                goto mi_error;
        }
@@ -765,48 +719,43 @@ end:
        return ret_code;
 }
 
-static
-enum lttng_error_code lttng_kernel_probe_location_symbol_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer)
+static enum lttng_error_code
+lttng_kernel_probe_location_symbol_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                               struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_kernel_probe_location_status status;
-       const char *name = NULL;
+       const char *name = nullptr;
        uint64_t offset;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(writer);
-       LTTNG_ASSERT(location->type ==
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
+       LTTNG_ASSERT(location->type == LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
 
        name = lttng_kernel_probe_location_symbol_get_name(location);
        LTTNG_ASSERT(name);
 
-       status = lttng_kernel_probe_location_symbol_get_offset(
-                       location, &offset);
+       status = lttng_kernel_probe_location_symbol_get_offset(location, &offset);
        LTTNG_ASSERT(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK);
 
        /* Open kernel probe location symbol offset element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_kernel_probe_location_symbol_offset);
+                                          mi_lttng_element_kernel_probe_location_symbol_offset);
        if (ret) {
                goto mi_error;
        }
 
        /* Name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_kernel_probe_location_symbol_offset_name,
-                       name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_kernel_probe_location_symbol_offset_name, name);
        if (ret) {
                goto mi_error;
        }
 
        /* Offset. */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_kernel_probe_location_symbol_offset_offset,
-                       offset);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_kernel_probe_location_symbol_offset_offset, offset);
        if (ret) {
                goto mi_error;
        }
@@ -826,9 +775,9 @@ end:
        return ret_code;
 }
 
-enum lttng_error_code lttng_kernel_probe_location_mi_serialize(
-               const struct lttng_kernel_probe_location *location,
-               struct mi_writer *writer)
+enum lttng_error_code
+lttng_kernel_probe_location_mi_serialize(const struct lttng_kernel_probe_location *location,
+                                        struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -837,8 +786,7 @@ enum lttng_error_code lttng_kernel_probe_location_mi_serialize(
        LTTNG_ASSERT(writer);
 
        /* Open kernel probe location element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_kernel_probe_location);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_kernel_probe_location);
        if (ret) {
                goto mi_error;
        }
index b09430d617e408f76a88c041bc6fc1d5f96c8cf4..cd4b03a47cdb7c76c0e1928c76e8b25a30f72cba 100644 (file)
@@ -5,14 +5,15 @@
  *
  */
 
-#include <lttng/location-internal.hpp>
+#include <common/error.hpp>
 #include <common/macros.hpp>
+
+#include <lttng/location-internal.hpp>
+
 #include <stdlib.h>
-#include <common/error.hpp>
 
-static
-struct lttng_trace_archive_location *lttng_trace_archive_location_create(
-               enum lttng_trace_archive_location_type type)
+static struct lttng_trace_archive_location *
+lttng_trace_archive_location_create(enum lttng_trace_archive_location_type type)
 {
        struct lttng_trace_archive_location *location;
 
@@ -27,11 +28,10 @@ end:
        return location;
 }
 
-static
-void trace_archive_location_destroy_ref(struct urcu_ref *ref)
+static void trace_archive_location_destroy_ref(struct urcu_ref *ref)
 {
        struct lttng_trace_archive_location *location =
-                       lttng::utils::container_of(ref, &lttng_trace_archive_location::ref);
+               lttng::utils::container_of(ref, &lttng_trace_archive_location::ref);
 
        switch (location->type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
@@ -62,17 +62,16 @@ void lttng_trace_archive_location_put(struct lttng_trace_archive_location *locat
        urcu_ref_put(&location->ref, trace_archive_location_destroy_ref);
 }
 
-struct lttng_trace_archive_location *lttng_trace_archive_location_local_create(
-               const char *absolute_path)
+struct lttng_trace_archive_location *
+lttng_trace_archive_location_local_create(const char *absolute_path)
 {
-       struct lttng_trace_archive_location *location = NULL;
+       struct lttng_trace_archive_location *location = nullptr;
 
        if (!absolute_path) {
                goto end;
        }
 
-       location = lttng_trace_archive_location_create(
-                       LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL);
+       location = lttng_trace_archive_location_create(LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL);
        if (!location) {
                goto end;
        }
@@ -86,23 +85,23 @@ end:
        return location;
 error:
        lttng_trace_archive_location_put(location);
-       return NULL;
+       return nullptr;
 }
 
 struct lttng_trace_archive_location *lttng_trace_archive_location_relay_create(
-               const char *host,
-               enum lttng_trace_archive_location_relay_protocol_type protocol,
-               uint16_t control_port, uint16_t data_port,
-               const char *relative_path)
+       const char *host,
+       enum lttng_trace_archive_location_relay_protocol_type protocol,
+       uint16_t control_port,
+       uint16_t data_port,
+       const char *relative_path)
 {
-       struct lttng_trace_archive_location *location = NULL;
+       struct lttng_trace_archive_location *location = nullptr;
 
        if (!host || !relative_path) {
                goto end;
        }
 
-       location = lttng_trace_archive_location_create(
-                       LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY);
+       location = lttng_trace_archive_location_create(LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY);
        if (!location) {
                goto end;
        }
@@ -123,19 +122,18 @@ end:
        return location;
 error:
        lttng_trace_archive_location_put(location);
-       return NULL;
+       return nullptr;
 }
 
-ssize_t lttng_trace_archive_location_create_from_buffer(
-               const struct lttng_buffer_view *view,
-               struct lttng_trace_archive_location **location)
+ssize_t
+lttng_trace_archive_location_create_from_buffer(const struct lttng_buffer_view *view,
+                                               struct lttng_trace_archive_location **location)
 {
        size_t offset = 0;
        const struct lttng_trace_archive_location_comm *location_comm;
        struct lttng_buffer_view location_comm_view;
 
-       location_comm_view = lttng_buffer_view_from_view(view, 0,
-                       sizeof(*location_comm));
+       location_comm_view = lttng_buffer_view_from_view(view, 0, sizeof(*location_comm));
        if (!lttng_buffer_view_is_valid(&location_comm_view)) {
                goto error;
        }
@@ -146,9 +144,8 @@ ssize_t lttng_trace_archive_location_create_from_buffer(
        switch ((enum lttng_trace_archive_location_type) location_comm->type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
        {
-               const struct lttng_buffer_view absolute_path_view =
-                               lttng_buffer_view_from_view(view, offset,
-                               location_comm->types.local.absolute_path_len);
+               const struct lttng_buffer_view absolute_path_view = lttng_buffer_view_from_view(
+                       view, offset, location_comm->types.local.absolute_path_len);
 
                if (!lttng_buffer_view_is_valid(&absolute_path_view)) {
                        goto error;
@@ -159,8 +156,7 @@ ssize_t lttng_trace_archive_location_create_from_buffer(
                }
                offset += absolute_path_view.size;
 
-               *location = lttng_trace_archive_location_local_create(
-                               absolute_path_view.data);
+               *location = lttng_trace_archive_location_local_create(absolute_path_view.data);
                if (!*location) {
                        goto error;
                }
@@ -168,17 +164,15 @@ ssize_t lttng_trace_archive_location_create_from_buffer(
        }
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY:
        {
-               const struct lttng_buffer_view hostname_view =
-                               lttng_buffer_view_from_view(view, offset,
-                               location_comm->types.relay.hostname_len);
+               const struct lttng_buffer_view hostname_view = lttng_buffer_view_from_view(
+                       view, offset, location_comm->types.relay.hostname_len);
                const struct lttng_buffer_view relative_path_view =
-                               lttng_buffer_view_from_view(view,
-                               offset + hostname_view.size,
-                               location_comm->types.relay.relative_path_len);
+                       lttng_buffer_view_from_view(view,
+                                                   offset + hostname_view.size,
+                                                   location_comm->types.relay.relative_path_len);
 
                if (!lttng_buffer_view_is_valid(&hostname_view) ||
-                               !lttng_buffer_view_is_valid(
-                                               &relative_path_view)) {
+                   !lttng_buffer_view_is_valid(&relative_path_view)) {
                        goto error;
                }
 
@@ -191,11 +185,12 @@ ssize_t lttng_trace_archive_location_create_from_buffer(
                offset += hostname_view.size + relative_path_view.size;
 
                *location = lttng_trace_archive_location_relay_create(
-                               hostname_view.data,
-                               (enum lttng_trace_archive_location_relay_protocol_type) location_comm->types.relay.protocol,
-                               location_comm->types.relay.ports.control,
-                               location_comm->types.relay.ports.data,
-                               relative_path_view.data);
+                       hostname_view.data,
+                       (enum lttng_trace_archive_location_relay_protocol_type)
+                               location_comm->types.relay.protocol,
+                       location_comm->types.relay.ports.control,
+                       location_comm->types.relay.ports.data,
+                       relative_path_view.data);
                if (!*location) {
                        goto error;
                }
@@ -210,9 +205,8 @@ error:
        return -1;
 }
 
-ssize_t lttng_trace_archive_location_serialize(
-               const struct lttng_trace_archive_location *location,
-               struct lttng_dynamic_buffer *buffer)
+ssize_t lttng_trace_archive_location_serialize(const struct lttng_trace_archive_location *location,
+                                              struct lttng_dynamic_buffer *buffer)
 {
        int ret;
        struct lttng_trace_archive_location_comm location_comm;
@@ -222,26 +216,21 @@ ssize_t lttng_trace_archive_location_serialize(
        switch (location->type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
                location_comm.types.local.absolute_path_len =
-                               strlen(location->types.local.absolute_path) + 1;
+                       strlen(location->types.local.absolute_path) + 1;
                break;
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY:
-               location_comm.types.relay.hostname_len =
-                               strlen(location->types.relay.host) + 1;
-               location_comm.types.relay.protocol =
-                               (int8_t) location->types.relay.protocol;
-               location_comm.types.relay.ports.control =
-                               location->types.relay.ports.control;
-               location_comm.types.relay.ports.data =
-                               location->types.relay.ports.data;
+               location_comm.types.relay.hostname_len = strlen(location->types.relay.host) + 1;
+               location_comm.types.relay.protocol = (int8_t) location->types.relay.protocol;
+               location_comm.types.relay.ports.control = location->types.relay.ports.control;
+               location_comm.types.relay.ports.data = location->types.relay.ports.data;
                location_comm.types.relay.relative_path_len =
-                               strlen(location->types.relay.relative_path) + 1;
+                       strlen(location->types.relay.relative_path) + 1;
                break;
        default:
                abort();
        }
 
-       ret = lttng_dynamic_buffer_append(buffer, &location_comm,
-                       sizeof(location_comm));
+       ret = lttng_dynamic_buffer_append(buffer, &location_comm, sizeof(location_comm));
        if (ret) {
                goto error;
        }
@@ -249,22 +238,21 @@ ssize_t lttng_trace_archive_location_serialize(
        switch (location->type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
                ret = lttng_dynamic_buffer_append(buffer,
-                               location->types.local.absolute_path,
-                               location_comm.types.local.absolute_path_len);
+                                                 location->types.local.absolute_path,
+                                                 location_comm.types.local.absolute_path_len);
                if (ret) {
                        goto error;
                }
                break;
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY:
-               ret = lttng_dynamic_buffer_append(buffer,
-                               location->types.relay.host,
-                               location_comm.types.relay.hostname_len);
+               ret = lttng_dynamic_buffer_append(
+                       buffer, location->types.relay.host, location_comm.types.relay.hostname_len);
                if (ret) {
                        goto error;
                }
                ret = lttng_dynamic_buffer_append(buffer,
-                               location->types.relay.relative_path,
-                               location_comm.types.relay.relative_path_len);
+                                                 location->types.relay.relative_path,
+                                                 location_comm.types.relay.relative_path_len);
                if (ret) {
                        goto error;
                }
@@ -278,8 +266,8 @@ error:
        return -1;
 }
 
-enum lttng_trace_archive_location_type lttng_trace_archive_location_get_type(
-               const struct lttng_trace_archive_location *location)
+enum lttng_trace_archive_location_type
+lttng_trace_archive_location_get_type(const struct lttng_trace_archive_location *location)
 {
        enum lttng_trace_archive_location_type type;
 
@@ -293,16 +281,13 @@ end:
        return type;
 }
 
-enum lttng_trace_archive_location_status
-lttng_trace_archive_location_local_get_absolute_path(
-               const struct lttng_trace_archive_location *location,
-               const char **absolute_path)
+enum lttng_trace_archive_location_status lttng_trace_archive_location_local_get_absolute_path(
+       const struct lttng_trace_archive_location *location, const char **absolute_path)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
        if (!location || !absolute_path ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL) {
+           location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
@@ -313,15 +298,12 @@ end:
 }
 
 enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_host(
-               const struct lttng_trace_archive_location *location,
-               const char **relay_host)
+lttng_trace_archive_location_relay_get_host(const struct lttng_trace_archive_location *location,
+                                           const char **relay_host)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
-       if (!location || !relay_host ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
+       if (!location || !relay_host || location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
@@ -331,16 +313,13 @@ end:
        return status;
 }
 
-enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_relative_path(
-               const struct lttng_trace_archive_location *location,
-               const char **relative_path)
+enum lttng_trace_archive_location_status lttng_trace_archive_location_relay_get_relative_path(
+       const struct lttng_trace_archive_location *location, const char **relative_path)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
        if (!location || !relative_path ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
+           location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
@@ -350,16 +329,13 @@ end:
        return status;
 }
 
-enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_control_port(
-               const struct lttng_trace_archive_location *location,
-               uint16_t *control_port)
+enum lttng_trace_archive_location_status lttng_trace_archive_location_relay_get_control_port(
+       const struct lttng_trace_archive_location *location, uint16_t *control_port)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
        if (!location || !control_port ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
+           location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
@@ -369,16 +345,12 @@ end:
        return status;
 }
 
-enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_data_port(
-               const struct lttng_trace_archive_location *location,
-               uint16_t *data_port)
+enum lttng_trace_archive_location_status lttng_trace_archive_location_relay_get_data_port(
+       const struct lttng_trace_archive_location *location, uint16_t *data_port)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
-       if (!location || !data_port ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
+       if (!location || !data_port || location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
@@ -388,16 +360,13 @@ end:
        return status;
 }
 
-enum lttng_trace_archive_location_status
-lttng_trace_archive_location_relay_get_protocol_type(
-               const struct lttng_trace_archive_location *location,
-               enum lttng_trace_archive_location_relay_protocol_type *protocol)
+enum lttng_trace_archive_location_status lttng_trace_archive_location_relay_get_protocol_type(
+       const struct lttng_trace_archive_location *location,
+       enum lttng_trace_archive_location_relay_protocol_type *protocol)
 {
-       enum lttng_trace_archive_location_status status =
-                       LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
+       enum lttng_trace_archive_location_status status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK;
 
-       if (!location || !protocol ||
-                       location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
+       if (!location || !protocol || location->type != LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY) {
                status = LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_INVALID;
                goto end;
        }
index e0ff3f2806ea0a187eff3e8df3af17bb0223b23b..6ccfad70deb35f9955e5f62d84c1120b6c24a4d1 100644 (file)
@@ -46,7 +46,7 @@ public:
                return _value;
        }
 
-        WrappedType* operator->() const
+       WrappedType *operator->() const
        {
                return &_value;
        }
diff --git a/src/common/lockfile.cpp b/src/common/lockfile.cpp
new file mode 100644 (file)
index 0000000..3e972fb
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
+ * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include <common/error.hpp>
+#include <common/lockfile.hpp>
+#include <common/macros.hpp>
+
+#include <fcntl.h>
+
+#ifdef HAVE_FLOCK
+
+#include <sys/file.h>
+
+static int lock_file(const char *filepath, int fd)
+{
+       int ret;
+
+       /*
+        * Attempt to lock the file. If this fails, there is
+        * already a process using the same lock file running
+        * and we should exit.
+        */
+       ret = flock(fd, LOCK_EX | LOCK_NB);
+       if (ret == -1) {
+               /* EWOULDBLOCK are expected if the file is locked: don't spam the logs. */
+               if (errno != EWOULDBLOCK) {
+                       PERROR("Failed to apply lock on lock file: file_path=`%s`", filepath);
+               }
+       }
+
+       return ret;
+}
+
+#else /* HAVE_FLOCK */
+
+static int lock_file(const char *filepath, int fd)
+{
+       int ret;
+       struct flock lock = {};
+
+       lock.l_whence = SEEK_SET;
+       lock.l_type = F_WRLCK;
+
+       /*
+        * Attempt to lock the file. If this fails, there is
+        * already a process using the same lock file running
+        * and we should exit.
+        */
+       ret = fcntl(fd, F_SETLK, &lock);
+       if (ret == -1) {
+               /* EAGAIN and EACCESS are expected if the file is locked: don't spam the logs. */
+               if (errno != EAGAIN && errno != EACCES) {
+                       PERROR("Failed to set lock on lock file: file_path=`%s`", filepath);
+               }
+       }
+
+       return ret;
+}
+
+#endif /* HAVE_FLOCK */
+
+int utils_create_lock_file(const char *filepath)
+{
+       int ret, fd;
+
+       LTTNG_ASSERT(filepath);
+
+       fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
+       if (fd < 0) {
+               PERROR("Failed to open lock file `%s`", filepath);
+               fd = -1;
+               goto error;
+       }
+
+       /*
+        * Attempt to lock the file. If this fails, there is already a process using the same lock
+        * file running and we should exit.
+        *
+        * lock_file is chosen based on the build configuration, see implementations above.
+        */
+       ret = lock_file(filepath, fd);
+       if (ret == -1) {
+               ERR("Could not get lock file `%s`, another instance is running.", filepath);
+
+               if (close(fd)) {
+                       PERROR("Failed to close lock file fd: fd=%d", fd);
+               }
+
+               fd = ret;
+               goto error;
+       }
+
+       DBG_FMT("Acquired lock file: file_path={}", filepath);
+
+error:
+       return fd;
+}
\ No newline at end of file
diff --git a/src/common/lockfile.hpp b/src/common/lockfile.hpp
new file mode 100644 (file)
index 0000000..1f8e01d
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef COMMON_LOCKFILE_H
+#define COMMON_LOCKFILE_H
+
+/*
+ * Create lock file to the given path and filename.
+ * Returns the associated file descriptor, -1 on error.
+ *
+ * Note that on systems that don't support flock, POSIX file locks are used.
+ * As such, the file lock is dropped whenever any of the file descriptors
+ * associated to the file's description is closed.
+ *
+ * For instance, the lock file is dropped if the process forks+exits or
+ * forks+execve as the child process closes a file descriptor referencing
+ * the file description of 'filepath'.
+ */
+int utils_create_lock_file(const char *filepath);
+
+#endif /* COMMON_LOCKFILE_H */
index 4494b31962b7aa760d9fc6043f7d0dabea440bdc..6673ddc8d3504a7c40b496fd277f0274f3d7743c 100644 (file)
 #include <common/hashtable/utils.hpp>
 #include <common/macros.hpp>
 #include <common/mi-lttng.hpp>
+
 #include <lttng/log-level-rule-internal.hpp>
 #include <lttng/log-level-rule.h>
+
 #include <stdbool.h>
 #include <stdlib.h>
 
 static bool is_log_level_rule_exactly_type(const struct lttng_log_level_rule *rule)
 {
-       enum lttng_log_level_rule_type type =
-                       lttng_log_level_rule_get_type(rule);
+       enum lttng_log_level_rule_type type = lttng_log_level_rule_get_type(rule);
 
        return type == LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY;
 }
 
 static bool is_log_level_rule_at_least_as_severe_type(const struct lttng_log_level_rule *rule)
 {
-
-       enum lttng_log_level_rule_type type =
-                       lttng_log_level_rule_get_type(rule);
+       enum lttng_log_level_rule_type type = lttng_log_level_rule_get_type(rule);
 
        return type == LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS;
 }
 
-enum lttng_log_level_rule_type lttng_log_level_rule_get_type(
-               const struct lttng_log_level_rule *rule)
+enum lttng_log_level_rule_type
+lttng_log_level_rule_get_type(const struct lttng_log_level_rule *rule)
 {
        return rule ? rule->type : LTTNG_LOG_LEVEL_RULE_TYPE_UNKNOWN;
 }
 
-struct lttng_log_level_rule *lttng_log_level_rule_exactly_create(
-               int level)
+struct lttng_log_level_rule *lttng_log_level_rule_exactly_create(int level)
 {
-       struct lttng_log_level_rule *rule = NULL;
+       struct lttng_log_level_rule *rule = nullptr;
 
        rule = zmalloc<lttng_log_level_rule>();
        if (!rule) {
@@ -56,11 +54,10 @@ end:
        return rule;
 }
 
-enum lttng_log_level_rule_status lttng_log_level_rule_exactly_get_level(
-               const struct lttng_log_level_rule *rule, int *level)
+enum lttng_log_level_rule_status
+lttng_log_level_rule_exactly_get_level(const struct lttng_log_level_rule *rule, int *level)
 {
-       enum lttng_log_level_rule_status status =
-                       LTTNG_LOG_LEVEL_RULE_STATUS_OK;
+       enum lttng_log_level_rule_status status = LTTNG_LOG_LEVEL_RULE_STATUS_OK;
 
        if (!rule || !level || !is_log_level_rule_exactly_type(rule)) {
                status = LTTNG_LOG_LEVEL_RULE_STATUS_INVALID;
@@ -72,10 +69,9 @@ end:
        return status;
 }
 
-struct lttng_log_level_rule *
-lttng_log_level_rule_at_least_as_severe_as_create(int level)
+struct lttng_log_level_rule *lttng_log_level_rule_at_least_as_severe_as_create(int level)
 {
-       struct lttng_log_level_rule *rule = NULL;
+       struct lttng_log_level_rule *rule = nullptr;
 
        rule = zmalloc<lttng_log_level_rule>();
        if (!rule) {
@@ -90,13 +86,12 @@ end:
 }
 
 enum lttng_log_level_rule_status
-lttng_log_level_rule_at_least_as_severe_as_get_level(
-               const struct lttng_log_level_rule *rule, int *level)
+lttng_log_level_rule_at_least_as_severe_as_get_level(const struct lttng_log_level_rule *rule,
+                                                    int *level)
 {
        enum lttng_log_level_rule_status status = LTTNG_LOG_LEVEL_RULE_STATUS_OK;
 
-       if (!rule || !level ||
-                       !is_log_level_rule_at_least_as_severe_type(rule)) {
+       if (!rule || !level || !is_log_level_rule_at_least_as_severe_type(rule)) {
                status = LTTNG_LOG_LEVEL_RULE_STATUS_INVALID;
                goto end;
        }
@@ -111,16 +106,14 @@ void lttng_log_level_rule_destroy(struct lttng_log_level_rule *log_level_rule)
        free(log_level_rule);
 }
 
-ssize_t lttng_log_level_rule_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_log_level_rule **_rule)
+ssize_t lttng_log_level_rule_create_from_payload(struct lttng_payload_view *view,
+                                                struct lttng_log_level_rule **_rule)
 {
        ssize_t ret;
        size_t offset = 0;
-       struct lttng_log_level_rule *rule = NULL;
+       struct lttng_log_level_rule *rule = nullptr;
        const struct lttng_log_level_rule_comm *comm =
-                       (const struct lttng_log_level_rule_comm *)
-                                       view->buffer.data;
+               (const struct lttng_log_level_rule_comm *) view->buffer.data;
 
        offset += sizeof(*comm);
 
@@ -139,8 +132,7 @@ ssize_t lttng_log_level_rule_create_from_payload(
                rule = lttng_log_level_rule_exactly_create((int) comm->level);
                break;
        case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
-               rule = lttng_log_level_rule_at_least_as_severe_as_create(
-                               (int) comm->level);
+               rule = lttng_log_level_rule_at_least_as_severe_as_create((int) comm->level);
                break;
        default:
                abort();
@@ -159,12 +151,11 @@ end:
 }
 
 int lttng_log_level_rule_serialize(const struct lttng_log_level_rule *rule,
-               struct lttng_payload *payload)
+                                  struct lttng_payload *payload)
 {
        int ret;
        struct lttng_log_level_rule_comm comm;
 
-
        if (!rule) {
                ret = 0;
                goto end;
@@ -174,8 +165,7 @@ int lttng_log_level_rule_serialize(const struct lttng_log_level_rule *rule,
        comm.level = (int32_t) rule->level;
 
        DBG("Serializing log level rule of type %d", rule->type);
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm,
-                       sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                goto end;
        }
@@ -185,17 +175,17 @@ end:
 }
 
 bool lttng_log_level_rule_is_equal(const struct lttng_log_level_rule *a,
-               const struct lttng_log_level_rule *b)
+                                  const struct lttng_log_level_rule *b)
 {
        bool is_equal = false;
 
-       if (a == NULL && b == NULL) {
+       if (a == nullptr && b == nullptr) {
                /* Both are null. */
                is_equal = true;
                goto end;
        }
 
-       if (a == NULL || b == NULL) {
+       if (a == nullptr || b == nullptr) {
                /* One is NULL.*/
                goto end;
        }
@@ -220,10 +210,9 @@ end:
        return is_equal;
 }
 
-struct lttng_log_level_rule *lttng_log_level_rule_copy(
-               const struct lttng_log_level_rule *source)
+struct lttng_log_level_rule *lttng_log_level_rule_copy(const struct lttng_log_level_rule *source)
 {
-       struct lttng_log_level_rule *copy = NULL;
+       struct lttng_log_level_rule *copy = nullptr;
 
        LTTNG_ASSERT(source);
 
@@ -238,10 +227,9 @@ end:
        return copy;
 }
 
-void lttng_log_level_rule_to_loglevel(
-               const struct lttng_log_level_rule *log_level_rule,
-               enum lttng_loglevel_type *loglevel_type,
-               int *loglevel_value)
+void lttng_log_level_rule_to_loglevel(const struct lttng_log_level_rule *log_level_rule,
+                                     enum lttng_loglevel_type *loglevel_type,
+                                     int *loglevel_value)
 {
        LTTNG_ASSERT(log_level_rule);
 
@@ -259,8 +247,7 @@ void lttng_log_level_rule_to_loglevel(
        *loglevel_value = log_level_rule->level;
 }
 
-unsigned long lttng_log_level_rule_hash(
-               const struct lttng_log_level_rule *log_level_rule)
+unsigned long lttng_log_level_rule_hash(const struct lttng_log_level_rule *log_level_rule)
 {
        unsigned long hash;
        enum lttng_log_level_rule_status llr_status;
@@ -273,12 +260,12 @@ unsigned long lttng_log_level_rule_hash(
 
        switch (type) {
        case LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY:
-               llr_status = lttng_log_level_rule_exactly_get_level(
-                               log_level_rule, &log_level_value);
+               llr_status =
+                       lttng_log_level_rule_exactly_get_level(log_level_rule, &log_level_value);
                break;
        case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
-               llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                               log_level_rule, &log_level_value);
+               llr_status = lttng_log_level_rule_at_least_as_severe_as_get_level(log_level_rule,
+                                                                                 &log_level_value);
                break;
        default:
                abort();
@@ -289,20 +276,18 @@ unsigned long lttng_log_level_rule_hash(
 
        hash = hash_key_ulong((void *) (unsigned long) type, lttng_ht_seed);
 
-       hash ^= hash_key_ulong((void *) (unsigned long) log_level_value,
-                       lttng_ht_seed);
+       hash ^= hash_key_ulong((void *) (unsigned long) log_level_value, lttng_ht_seed);
 
        return hash;
 }
 
-enum lttng_error_code lttng_log_level_rule_mi_serialize(
-               const struct lttng_log_level_rule *rule,
-               struct mi_writer *writer)
+enum lttng_error_code lttng_log_level_rule_mi_serialize(const struct lttng_log_level_rule *rule,
+                                                       struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_log_level_rule_status status;
-       const char *element_str = NULL;
+       const char *element_str = nullptr;
        int level;
 
        LTTNG_ASSERT(rule);
@@ -315,8 +300,7 @@ enum lttng_error_code lttng_log_level_rule_mi_serialize(
                break;
        case LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS:
                element_str = mi_lttng_element_log_level_rule_at_least_as_severe_as;
-               status = lttng_log_level_rule_at_least_as_severe_as_get_level(
-                               rule, &level);
+               status = lttng_log_level_rule_at_least_as_severe_as_get_level(rule, &level);
                break;
        default:
                abort();
@@ -326,8 +310,7 @@ enum lttng_error_code lttng_log_level_rule_mi_serialize(
        LTTNG_ASSERT(status == LTTNG_LOG_LEVEL_RULE_STATUS_OK);
 
        /* Open log level rule element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_log_level_rule);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_log_level_rule);
        if (ret) {
                goto mi_error;
        }
@@ -340,7 +323,7 @@ enum lttng_error_code lttng_log_level_rule_mi_serialize(
 
        /* Level. */
        ret = mi_lttng_writer_write_element_signed_int(
-                       writer, mi_lttng_element_log_level_rule_level, level);
+               writer, mi_lttng_element_log_level_rule_level, level);
        if (ret) {
                goto mi_error;
        }
diff --git a/src/common/logging-utils.cpp b/src/common/logging-utils.cpp
new file mode 100644 (file)
index 0000000..a0f307a
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include <common/logging-utils.hpp>
+
+#include <sys/utsname.h>
+
+/* Output system information as logging statements. */
+void lttng::logging::log_system_information(lttng_error_level error_level)
+{
+       struct utsname name = {};
+       const int ret = uname(&name);
+
+       if (ret) {
+               PERROR("Failed to get system information using uname()")
+               return;
+       }
+
+       LOG(error_level, "System information:");
+       LOG(error_level, "\tsysname: `%s`", name.sysname);
+       LOG(error_level, "\tnodename: `%s`", name.nodename);
+       LOG(error_level, "\trelease: `%s`", name.release);
+       LOG(error_level, "\tversion: `%s`", name.version);
+       LOG(error_level, "\tmachine: `%s`", name.machine);
+}
diff --git a/src/common/logging-utils.hpp b/src/common/logging-utils.hpp
new file mode 100644 (file)
index 0000000..1bd6c15
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_LOGGING_UTILS_H
+#define LTTNG_LOGGING_UTILS_H
+
+#include <common/error.hpp>
+
+namespace lttng {
+namespace logging {
+
+/* Output system information as logging statements. */
+void log_system_information(lttng_error_level error_level);
+
+} /* namespace logging */
+} /* namespace lttng */
+
+#endif /* LTTNG_LOGGING_UTILS_H */
index e6b8624386914a38de270fbfbb5a45808d0fe6c1..be1db0250ac02bae4af5cba422c52c3cb41a8132 100644 (file)
@@ -7,12 +7,14 @@
  *
  */
 
-#include <algorithm>
 #include <common/compat/endian.hpp>
 #include <common/error.hpp>
 #include <common/lttng-elf.hpp>
 #include <common/macros.hpp>
 #include <common/readwrite.hpp>
+
+#include <algorithm>
+#include <elf.h>
 #include <fcntl.h>
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <elf.h>
-
-#define BUF_LEN        4096
-#define TEXT_SECTION_NAME      ".text"
-#define SYMBOL_TAB_SECTION_NAME ".symtab"
-#define STRING_TAB_SECTION_NAME ".strtab"
+#define BUF_LEN                                4096
+#define TEXT_SECTION_NAME              ".text"
+#define SYMBOL_TAB_SECTION_NAME                ".symtab"
+#define STRING_TAB_SECTION_NAME                ".strtab"
 #define DYNAMIC_SYMBOL_TAB_SECTION_NAME ".dynsym"
 #define DYNAMIC_STRING_TAB_SECTION_NAME ".dynstr"
-#define NOTE_STAPSDT_SECTION_NAME ".note.stapsdt"
-#define NOTE_STAPSDT_NAME "stapsdt"
-#define NOTE_STAPSDT_TYPE 3
-#define MAX_SECTION_DATA_SIZE   512 * 1024 * 1024
+#define NOTE_STAPSDT_SECTION_NAME      ".note.stapsdt"
+#define NOTE_STAPSDT_NAME              "stapsdt"
+#define NOTE_STAPSDT_TYPE              3
+#define MAX_SECTION_DATA_SIZE          (512 * 1024 * 1024)
 
 #if BYTE_ORDER == LITTLE_ENDIAN
 #define NATIVE_ELF_ENDIANNESS ELFDATA2LSB
 #define NATIVE_ELF_ENDIANNESS ELFDATA2MSB
 #endif
 
-#define next_4bytes_boundary(x) (typeof(x)) ((((uint64_t)x) + 3) & ~0x03)
-
-#define bswap(x)                               \
-       do {                                    \
-               switch (sizeof(x)) {            \
-               case 8:                         \
-                       x = be64toh((uint64_t)x);               \
-                       break;                  \
-               case 4:                         \
-                       x = be32toh((uint32_t)x);               \
-                       break;                  \
-               case 2:                         \
-                       x = be16toh((uint16_t)x);               \
-                       break;                  \
-               case 1:                         \
-                       break;                  \
-               default:                        \
-                       abort();                \
-               }                               \
+#define next_4bytes_boundary(x) (typeof(x)) ((((uint64_t) (x)) + 3) & ~0x03)
+
+#define bswap(x)                                       \
+       do {                                           \
+               switch (sizeof(x)) {                   \
+               case 8:                                \
+                       (x) = be64toh((uint64_t) (x)); \
+                       break;                         \
+               case 4:                                \
+                       (x) = be32toh((uint32_t) (x)); \
+                       break;                         \
+               case 2:                                \
+                       (x) = be16toh((uint16_t) (x)); \
+                       break;                         \
+               case 1:                                \
+                       break;                         \
+               default:                               \
+                       abort();                       \
+               }                                      \
        } while (0)
 
-#define bswap_shdr(shdr)           \
-       do {                                \
-               bswap((shdr).sh_name);      \
-               bswap((shdr).sh_type);      \
-               bswap((shdr).sh_flags);     \
-               bswap((shdr).sh_addr);      \
+#define bswap_shdr(shdr)                    \
+       do {                                \
+               bswap((shdr).sh_name);      \
+               bswap((shdr).sh_type);      \
+               bswap((shdr).sh_flags);     \
+               bswap((shdr).sh_addr);      \
                bswap((shdr).sh_offset);    \
-               bswap((shdr).sh_size);      \
-               bswap((shdr).sh_link);      \
-               bswap((shdr).sh_info);      \
+               bswap((shdr).sh_size);      \
+               bswap((shdr).sh_link);      \
+               bswap((shdr).sh_info);      \
                bswap((shdr).sh_addralign); \
                bswap((shdr).sh_entsize);   \
        } while (0)
 
-#define bswap_ehdr(ehdr)                               \
-       do {                                            \
-               bswap((ehdr).e_type);                   \
-               bswap((ehdr).e_machine);                \
-               bswap((ehdr).e_version);                \
-               bswap((ehdr).e_entry);                  \
-               bswap((ehdr).e_phoff);                  \
-               bswap((ehdr).e_shoff);                  \
-               bswap((ehdr).e_flags);                  \
-               bswap((ehdr).e_ehsize);                 \
-               bswap((ehdr).e_phentsize);              \
-               bswap((ehdr).e_phnum);                  \
-               bswap((ehdr).e_shentsize);              \
-               bswap((ehdr).e_shnum);                  \
-               bswap((ehdr).e_shstrndx);               \
+#define bswap_ehdr(ehdr)                   \
+       do {                               \
+               bswap((ehdr).e_type);      \
+               bswap((ehdr).e_machine);   \
+               bswap((ehdr).e_version);   \
+               bswap((ehdr).e_entry);     \
+               bswap((ehdr).e_phoff);     \
+               bswap((ehdr).e_shoff);     \
+               bswap((ehdr).e_flags);     \
+               bswap((ehdr).e_ehsize);    \
+               bswap((ehdr).e_phentsize); \
+               bswap((ehdr).e_phnum);     \
+               bswap((ehdr).e_shentsize); \
+               bswap((ehdr).e_shnum);     \
+               bswap((ehdr).e_shstrndx);  \
        } while (0)
 
-#define copy_shdr(src_shdr, dst_shdr)                                  \
-       do {                                                            \
-               (dst_shdr).sh_name = (src_shdr).sh_name;                \
-               (dst_shdr).sh_type = (src_shdr).sh_type;                \
-               (dst_shdr).sh_flags = (src_shdr).sh_flags;              \
-               (dst_shdr).sh_addr = (src_shdr).sh_addr;                \
-               (dst_shdr).sh_offset = (src_shdr).sh_offset;            \
-               (dst_shdr).sh_size = (src_shdr).sh_size;                \
-               (dst_shdr).sh_link = (src_shdr).sh_link;                \
-               (dst_shdr).sh_info = (src_shdr).sh_info;                \
-               (dst_shdr).sh_addralign = (src_shdr).sh_addralign;      \
-               (dst_shdr).sh_entsize = (src_shdr).sh_entsize;          \
+#define copy_shdr(src_shdr, dst_shdr)                              \
+       do {                                                       \
+               (dst_shdr).sh_name = (src_shdr).sh_name;           \
+               (dst_shdr).sh_type = (src_shdr).sh_type;           \
+               (dst_shdr).sh_flags = (src_shdr).sh_flags;         \
+               (dst_shdr).sh_addr = (src_shdr).sh_addr;           \
+               (dst_shdr).sh_offset = (src_shdr).sh_offset;       \
+               (dst_shdr).sh_size = (src_shdr).sh_size;           \
+               (dst_shdr).sh_link = (src_shdr).sh_link;           \
+               (dst_shdr).sh_info = (src_shdr).sh_info;           \
+               (dst_shdr).sh_addralign = (src_shdr).sh_addralign; \
+               (dst_shdr).sh_entsize = (src_shdr).sh_entsize;     \
        } while (0)
 
-#define copy_ehdr(src_ehdr, dst_ehdr)                                  \
-       do {                                                            \
-               (dst_ehdr).e_type = (src_ehdr).e_type;                  \
-               (dst_ehdr).e_machine = (src_ehdr).e_machine;            \
-               (dst_ehdr).e_version = (src_ehdr).e_version;            \
-               (dst_ehdr).e_entry = (src_ehdr).e_entry;                \
-               (dst_ehdr).e_phoff = (src_ehdr).e_phoff;                \
-               (dst_ehdr).e_shoff = (src_ehdr).e_shoff;                \
-               (dst_ehdr).e_flags = (src_ehdr).e_flags;                \
-               (dst_ehdr).e_ehsize = (src_ehdr).e_ehsize;              \
-               (dst_ehdr).e_phentsize = (src_ehdr).e_phentsize;        \
-               (dst_ehdr).e_phnum = (src_ehdr).e_phnum;                \
-               (dst_ehdr).e_shentsize = (src_ehdr).e_shentsize;        \
-               (dst_ehdr).e_shnum = (src_ehdr).e_shnum;                \
-               (dst_ehdr).e_shstrndx = (src_ehdr).e_shstrndx;          \
+#define copy_ehdr(src_ehdr, dst_ehdr)                            \
+       do {                                                     \
+               (dst_ehdr).e_type = (src_ehdr).e_type;           \
+               (dst_ehdr).e_machine = (src_ehdr).e_machine;     \
+               (dst_ehdr).e_version = (src_ehdr).e_version;     \
+               (dst_ehdr).e_entry = (src_ehdr).e_entry;         \
+               (dst_ehdr).e_phoff = (src_ehdr).e_phoff;         \
+               (dst_ehdr).e_shoff = (src_ehdr).e_shoff;         \
+               (dst_ehdr).e_flags = (src_ehdr).e_flags;         \
+               (dst_ehdr).e_ehsize = (src_ehdr).e_ehsize;       \
+               (dst_ehdr).e_phentsize = (src_ehdr).e_phentsize; \
+               (dst_ehdr).e_phnum = (src_ehdr).e_phnum;         \
+               (dst_ehdr).e_shentsize = (src_ehdr).e_shentsize; \
+               (dst_ehdr).e_shnum = (src_ehdr).e_shnum;         \
+               (dst_ehdr).e_shstrndx = (src_ehdr).e_shstrndx;   \
        } while (0)
 
-#define copy_sym(src_sym, dst_sym)                     \
-       do {                                            \
-               dst_sym.st_name = src_sym.st_name;      \
-               dst_sym.st_info = src_sym.st_info;      \
-               dst_sym.st_other = src_sym.st_other;    \
-               dst_sym.st_shndx = src_sym.st_shndx;    \
-               dst_sym.st_value = src_sym.st_value;    \
-               dst_sym.st_size = src_sym.st_size;      \
+#define copy_sym(src_sym, dst_sym)                       \
+       do {                                             \
+               (dst_sym).st_name = (src_sym).st_name;   \
+               (dst_sym).st_info = (src_sym).st_info;   \
+               (dst_sym).st_other = (src_sym).st_other; \
+               (dst_sym).st_shndx = (src_sym).st_shndx; \
+               (dst_sym).st_value = (src_sym).st_value; \
+               (dst_sym).st_size = (src_sym).st_size;   \
        } while (0)
 
 #ifndef ELFCLASSNUM
@@ -183,8 +183,8 @@ struct lttng_elf_shdr {
  */
 struct lttng_elf_sym {
        uint32_t st_name;
-       uint8_t  st_info;
-       uint8_t  st_other;
+       uint8_t st_info;
+       uint8_t st_other;
        uint16_t st_shndx;
        uint64_t st_value;
        uint64_t st_size;
@@ -203,28 +203,24 @@ struct lttng_elf {
        struct lttng_elf_ehdr *ehdr;
 };
 
-static inline
-int is_elf_32_bit(struct lttng_elf *elf)
+static inline int is_elf_32_bit(struct lttng_elf *elf)
 {
        return elf->bitness == ELFCLASS32;
 }
 
-static inline
-int is_elf_native_endian(struct lttng_elf *elf)
+static inline int is_elf_native_endian(struct lttng_elf *elf)
 {
        return elf->endianness == NATIVE_ELF_ENDIANNESS;
 }
 
-static
-int populate_section_header(struct lttng_elf * elf, struct lttng_elf_shdr *shdr,
-               uint32_t index)
+static int
+populate_section_header(struct lttng_elf *elf, struct lttng_elf_shdr *shdr, uint32_t index)
 {
        int ret = 0;
        off_t offset;
 
        /* Compute the offset of the section in the file */
-       offset = (off_t) elf->ehdr->e_shoff
-                       + (off_t) index * elf->ehdr->e_shentsize;
+       offset = (off_t) elf->ehdr->e_shoff + (off_t) index * elf->ehdr->e_shentsize;
 
        if (lseek(elf->fd, offset, SEEK_SET) < 0) {
                PERROR("Error seeking to the beginning of ELF section header");
@@ -262,8 +258,7 @@ error:
        return ret;
 }
 
-static
-int populate_elf_header(struct lttng_elf *elf)
+static int populate_elf_header(struct lttng_elf *elf)
 {
        int ret = 0;
 
@@ -314,9 +309,8 @@ error:
  *
  * 0 is returned on succes, -1 on failure.
  */
-static
-int lttng_elf_get_section_hdr(struct lttng_elf *elf,
-               uint16_t index, struct lttng_elf_shdr *out_header)
+static int
+lttng_elf_get_section_hdr(struct lttng_elf *elf, uint16_t index, struct lttng_elf_shdr *out_header)
 {
        int ret = 0;
 
@@ -347,11 +341,10 @@ error:
  *
  * If no name is found, NULL is returned.
  */
-static
-char *lttng_elf_get_section_name(struct lttng_elf *elf, off_t offset)
+static char *lttng_elf_get_section_name(struct lttng_elf *elf, off_t offset)
 {
-       char *name = NULL;
-       size_t name_length = 0, to_read;        /* name_length does not include \0 */
+       char *name = nullptr;
+       size_t name_length = 0, to_read; /* name_length does not include \0 */
 
        if (!elf) {
                goto error;
@@ -396,7 +389,7 @@ end:
         * We found the length of the section name, now seek back to the
         * beginning of the name and copy it in the newly allocated buffer.
         */
-       name = calloc<char>((name_length + 1)); /* + 1 for \0 */
+       name = calloc<char>((name_length + 1)); /* + 1 for \0 */
        if (!name) {
                PERROR("Error allocating ELF section name buffer");
                goto error;
@@ -414,15 +407,14 @@ end:
 
 error:
        free(name);
-       return NULL;
+       return nullptr;
 }
 
-static
-int lttng_elf_validate_and_populate(struct lttng_elf *elf)
+static int lttng_elf_validate_and_populate(struct lttng_elf *elf)
 {
        uint8_t version;
        uint8_t e_ident[EI_NIDENT];
-       uint8_t *magic_number = NULL;
+       uint8_t *magic_number = nullptr;
        int ret = 0;
 
        if (elf->fd == -1) {
@@ -517,7 +509,7 @@ int lttng_elf_validate_and_populate(struct lttng_elf *elf)
 
 free_elf_error:
        free(elf->ehdr);
-       elf->ehdr = NULL;
+       elf->ehdr = nullptr;
 end:
        return ret;
 }
@@ -528,11 +520,10 @@ end:
  *
  * Return a pointer to the instance on success, NULL on failure.
  */
-static
-struct lttng_elf *lttng_elf_create(int fd)
+static struct lttng_elf *lttng_elf_create(int fd)
 {
        struct lttng_elf_shdr section_names_shdr;
-       struct lttng_elf *elf = NULL;
+       struct lttng_elf *elf = nullptr;
        int ret;
        struct stat stat_buf;
 
@@ -568,8 +559,7 @@ struct lttng_elf *lttng_elf_create(int fd)
                goto error;
        }
 
-       ret = lttng_elf_get_section_hdr(
-                       elf, elf->ehdr->e_shstrndx, &section_names_shdr);
+       ret = lttng_elf_get_section_hdr(elf, elf->ehdr->e_shstrndx, &section_names_shdr);
        if (ret) {
                goto error;
        }
@@ -591,14 +581,13 @@ error:
                }
                free(elf);
        }
-       return NULL;
+       return nullptr;
 }
 
 /*
  * Destroy the given lttng_elf instance.
  */
-static
-void lttng_elf_destroy(struct lttng_elf *elf)
+static void lttng_elf_destroy(struct lttng_elf *elf)
 {
        if (!elf) {
                return;
@@ -612,22 +601,21 @@ void lttng_elf_destroy(struct lttng_elf *elf)
        free(elf);
 }
 
-static
-int lttng_elf_get_section_hdr_by_name(struct lttng_elf *elf,
-               const char *section_name, struct lttng_elf_shdr *section_hdr)
+static int lttng_elf_get_section_hdr_by_name(struct lttng_elf *elf,
+                                            const char *section_name,
+                                            struct lttng_elf_shdr *section_hdr)
 {
        int i;
        char *curr_section_name;
 
        for (i = 0; i < elf->ehdr->e_shnum; ++i) {
                bool name_equal;
-               int ret = lttng_elf_get_section_hdr(elf, i, section_hdr);
+               int ret = lttng_elf_get_section_hdr(elf, i, section_hdr);
 
                if (ret) {
                        break;
                }
-               curr_section_name = lttng_elf_get_section_name(elf,
-                               section_hdr->sh_name);
+               curr_section_name = lttng_elf_get_section_name(elf, section_hdr->sh_name);
                if (!curr_section_name) {
                        continue;
                }
@@ -640,9 +628,7 @@ int lttng_elf_get_section_hdr_by_name(struct lttng_elf *elf,
        return LTTNG_ERR_ELF_PARSING;
 }
 
-static
-char *lttng_elf_get_section_data(struct lttng_elf *elf,
-               struct lttng_elf_shdr *shdr)
+static char *lttng_elf_get_section_data(struct lttng_elf *elf, struct lttng_elf_shdr *shdr)
 {
        int ret;
        off_t section_offset;
@@ -662,8 +648,7 @@ char *lttng_elf_get_section_data(struct lttng_elf *elf,
        }
 
        if (shdr->sh_size > max_alloc_size) {
-               ERR("ELF section size exceeds maximal allowed size of %zu bytes",
-                               max_alloc_size);
+               ERR("ELF section size exceeds maximal allowed size of %zu bytes", max_alloc_size);
                goto error;
        }
        data = calloc<char>(shdr->sh_size);
@@ -682,7 +667,7 @@ char *lttng_elf_get_section_data(struct lttng_elf *elf,
 free_error:
        free(data);
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -692,9 +677,9 @@ error:
  *
  * Returns the offset on success or non-zero in case of failure.
  */
-static
-int lttng_elf_convert_addr_in_text_to_offset(struct lttng_elf *elf_handle,
-               size_t addr, uint64_t *offset)
+static int lttng_elf_convert_addr_in_text_to_offset(struct lttng_elf *elf_handle,
+                                                   size_t addr,
+                                                   uint64_t *offset)
 {
        int ret = 0;
        off_t text_section_offset;
@@ -710,8 +695,7 @@ int lttng_elf_convert_addr_in_text_to_offset(struct lttng_elf *elf_handle,
        }
 
        /* Get a pointer to the .text section header. */
-       ret = lttng_elf_get_section_hdr_by_name(elf_handle,
-                       TEXT_SECTION_NAME, &text_section_hdr);
+       ret = lttng_elf_get_section_hdr_by_name(elf_handle, TEXT_SECTION_NAME, &text_section_hdr);
        if (ret) {
                DBG("Text section not found in binary.");
                ret = LTTNG_ERR_ELF_PARSING;
@@ -720,16 +704,17 @@ int lttng_elf_convert_addr_in_text_to_offset(struct lttng_elf *elf_handle,
 
        text_section_offset = text_section_hdr.sh_offset;
        text_section_addr_beg = text_section_hdr.sh_addr;
-       text_section_addr_end =
-                       text_section_addr_beg + text_section_hdr.sh_size;
+       text_section_addr_end = text_section_addr_beg + text_section_hdr.sh_size;
 
        /*
         * Verify that the address is within the .text section boundaries.
         */
        if (addr < text_section_addr_beg || addr > text_section_addr_end) {
                DBG("Address found is outside of the .text section addr=0x%zx, "
-                       ".text section=[0x%jd - 0x%jd].", addr, (intmax_t)text_section_addr_beg,
-                       (intmax_t)text_section_addr_end);
+                   ".text section=[0x%jd - 0x%jd].",
+                   addr,
+                   (intmax_t) text_section_addr_beg,
+                   (intmax_t) text_section_addr_end);
                ret = LTTNG_ERR_ELF_PARSING;
                goto error;
        }
@@ -759,15 +744,15 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
        int sym_count = 0;
        int sym_idx = 0;
        uint64_t addr = 0;
-       char *curr_sym_str = NULL;
-       char *symbol_table_data = NULL;
-       char *string_table_data = NULL;
-       const char *string_table_name = NULL;
+       char *curr_sym_str = nullptr;
+       char *symbol_table_data = nullptr;
+       char *string_table_data = nullptr;
+       const char *string_table_name = nullptr;
        struct lttng_elf_shdr symtab_hdr;
        struct lttng_elf_shdr strtab_hdr;
-       struct lttng_elf *elf = NULL;
+       struct lttng_elf *elf = nullptr;
 
-       if (!symbol || !offset ) {
+       if (!symbol || !offset) {
                ret = LTTNG_ERR_ELF_PARSING;
                goto end;
        }
@@ -784,13 +769,12 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
         * try to get the dynamic symbol table. All symbols in the dynamic
         * symbol tab are in the (normal) symbol table if it exists.
         */
-       ret = lttng_elf_get_section_hdr_by_name(elf, SYMBOL_TAB_SECTION_NAME,
-                       &symtab_hdr);
+       ret = lttng_elf_get_section_hdr_by_name(elf, SYMBOL_TAB_SECTION_NAME, &symtab_hdr);
        if (ret) {
                DBG("Cannot get ELF Symbol Table section. Trying to get ELF Dynamic Symbol Table section.");
                /* Get the dynamic symbol table section header. */
-               ret = lttng_elf_get_section_hdr_by_name(elf, DYNAMIC_SYMBOL_TAB_SECTION_NAME,
-                               &symtab_hdr);
+               ret = lttng_elf_get_section_hdr_by_name(
+                       elf, DYNAMIC_SYMBOL_TAB_SECTION_NAME, &symtab_hdr);
                if (ret) {
                        DBG("Cannot get ELF Symbol Table nor Dynamic Symbol Table sections.");
                        ret = LTTNG_ERR_ELF_PARSING;
@@ -803,15 +787,14 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
 
        /* Get the data associated with the symbol table section. */
        symbol_table_data = lttng_elf_get_section_data(elf, &symtab_hdr);
-       if (symbol_table_data == NULL) {
+       if (symbol_table_data == nullptr) {
                DBG("Cannot get ELF Symbol Table data.");
                ret = LTTNG_ERR_ELF_PARSING;
                goto destroy_elf;
        }
 
        /* Get the string table section header. */
-       ret = lttng_elf_get_section_hdr_by_name(elf, string_table_name,
-                       &strtab_hdr);
+       ret = lttng_elf_get_section_hdr_by_name(elf, string_table_name, &strtab_hdr);
        if (ret) {
                DBG("Cannot get ELF string table section.");
                goto free_symbol_table_data;
@@ -819,7 +802,7 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
 
        /* Get the data associated with the string table section. */
        string_table_data = lttng_elf_get_section_data(elf, &strtab_hdr);
-       if (string_table_data == NULL) {
+       if (string_table_data == nullptr) {
                DBG("Cannot get ELF string table section data.");
                ret = LTTNG_ERR_ELF_PARSING;
                goto free_symbol_table_data;
@@ -873,7 +856,7 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
                 * Compare with the search symbol. If there is a match set the address
                 * output parameter and return success.
                 */
-               if (strcmp(symbol, curr_sym_str) == 0 ) {
+               if (strcmp(symbol, curr_sym_str) == 0) {
                        sym_found = 1;
                        addr = curr_sym.st_value;
                        break;
@@ -896,7 +879,6 @@ int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset)
                goto free_string_table_data;
        }
 
-
 free_string_table_data:
        free(string_table_data);
 free_symbol_table_data:
@@ -915,18 +897,21 @@ end:
  * the SDT probes are.
  * On failure, returns -1.
  */
-int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
-               const char *probe_name, uint64_t **offsets, uint32_t *nb_probes)
+int lttng_elf_get_sdt_probe_offsets(int fd,
+                                   const char *provider_name,
+                                   const char *probe_name,
+                                   uint64_t **offsets,
+                                   uint32_t *nb_probes)
 {
        int ret = 0, nb_match = 0;
        struct lttng_elf_shdr stap_note_section_hdr;
-       struct lttng_elf *elf = NULL;
-       char *stap_note_section_data = NULL;
+       struct lttng_elf *elf = nullptr;
+       char *stap_note_section_data = nullptr;
        char *curr_note_section_begin, *curr_data_ptr, *curr_probe, *curr_provider;
        char *next_note_ptr;
        uint32_t name_size, desc_size, note_type;
        uint64_t curr_probe_location, curr_probe_offset, curr_semaphore_location;
-       uint64_t *probe_locs = NULL, *new_probe_locs = NULL;
+       uint64_t *probe_locs = nullptr, *new_probe_locs = nullptr;
 
        if (!provider_name || !probe_name || !nb_probes || !offsets) {
                DBG("Invalid arguments.");
@@ -942,17 +927,16 @@ int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
        }
 
        /* Get the stap note section header. */
-       ret = lttng_elf_get_section_hdr_by_name(elf, NOTE_STAPSDT_SECTION_NAME,
-                       &stap_note_section_hdr);
+       ret = lttng_elf_get_section_hdr_by_name(
+               elf, NOTE_STAPSDT_SECTION_NAME, &stap_note_section_hdr);
        if (ret) {
                DBG("Cannot get ELF stap note section.");
                goto destroy_elf_error;
        }
 
        /* Get the data associated with the stap note section. */
-       stap_note_section_data =
-                       lttng_elf_get_section_data(elf, &stap_note_section_hdr);
-       if (stap_note_section_data == NULL) {
+       stap_note_section_data = lttng_elf_get_section_data(elf, &stap_note_section_hdr);
+       if (stap_note_section_data == nullptr) {
                DBG("Cannot get ELF stap note section data.");
                ret = LTTNG_ERR_ELF_PARSING;
                goto destroy_elf_error;
@@ -961,32 +945,30 @@ int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
        next_note_ptr = stap_note_section_data;
        curr_note_section_begin = stap_note_section_data;
 
-       *offsets = NULL;
-       while (1) {
+       *offsets = nullptr;
+       while (true) {
                curr_data_ptr = next_note_ptr;
                /* Check if we have reached the end of the note section. */
-               if (curr_data_ptr >=
-                               curr_note_section_begin +
-                                               stap_note_section_hdr.sh_size) {
+               if (curr_data_ptr >= curr_note_section_begin + stap_note_section_hdr.sh_size) {
                        *nb_probes = nb_match;
                        *offsets = probe_locs;
                        ret = 0;
                        break;
                }
                /* Get name size field. */
-               name_size = next_4bytes_boundary(*(uint32_t*) curr_data_ptr);
+               name_size = next_4bytes_boundary(*(uint32_t *) curr_data_ptr);
                curr_data_ptr += sizeof(uint32_t);
 
                /* Sanity check; a zero name_size is reserved. */
                if (name_size == 0) {
                        DBG("Invalid name size field in SDT probe descriptions"
-                               "section.");
+                           "section.");
                        ret = -1;
                        goto realloc_error;
                }
 
                /* Get description size field. */
-               desc_size = next_4bytes_boundary(*(uint32_t*) curr_data_ptr);
+               desc_size = next_4bytes_boundary(*(uint32_t *) curr_data_ptr);
                curr_data_ptr += sizeof(uint32_t);
 
                /* Get type field. */
@@ -1000,15 +982,14 @@ int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
                 * name and the descriptor. To move to the next note, we move
                 * the pointer according to those values.
                 */
-               next_note_ptr = next_note_ptr +
-                       (3 * sizeof(uint32_t)) + desc_size + name_size;
+               next_note_ptr = next_note_ptr + (3 * sizeof(uint32_t)) + desc_size + name_size;
 
                /*
                 * Move ptr to the end of the name string (we don't need it)
                 * and go to the next 4 byte alignement.
                 */
                if (note_type != NOTE_STAPSDT_TYPE ||
-                       strncmp(curr_data_ptr, NOTE_STAPSDT_NAME, name_size) != 0) {
+                   strncmp(curr_data_ptr, NOTE_STAPSDT_NAME, name_size) != 0) {
                        continue;
                }
 
@@ -1033,7 +1014,7 @@ int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
 
                /* Check if the provider and probe name match */
                if (strcmp(provider_name, curr_provider) == 0 &&
-                               strcmp(probe_name, curr_probe) == 0) {
+                   strcmp(probe_name, curr_probe) == 0) {
                        int new_size;
 
                        /*
@@ -1060,14 +1041,14 @@ int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
                                goto realloc_error;
                        }
                        probe_locs = new_probe_locs;
-                       new_probe_locs = NULL;
+                       new_probe_locs = nullptr;
 
                        /*
                         * Use the virtual address of the probe to compute the offset of
                         * this probe from the beginning of the executable file.
                         */
-                       ret = lttng_elf_convert_addr_in_text_to_offset(elf,
-                                       curr_probe_location, &curr_probe_offset);
+                       ret = lttng_elf_convert_addr_in_text_to_offset(
+                               elf, curr_probe_location, &curr_probe_offset);
                        if (ret) {
                                DBG("Conversion error in SDT.");
                                goto realloc_error;
index 41dd496053bcbc0ac98853d952f536325c059e0d..baaea22a6f261fcf0c4eadfc53129a3b7489a5c2 100644 (file)
 
 #include <lttng/lttng-export.h>
 
-extern "C" LTTNG_EXPORT
-int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset);
+#include <stdint.h>
 
-extern "C" LTTNG_EXPORT
-int lttng_elf_get_sdt_probe_offsets(int fd, const char *provider_name,
-               const char *probe_name, uint64_t **offsets, uint32_t *nb_probe);
+extern "C" LTTNG_EXPORT int lttng_elf_get_symbol_offset(int fd, char *symbol, uint64_t *offset);
 
-#endif /* _LTTNG_ELF_H */
+extern "C" LTTNG_EXPORT int lttng_elf_get_sdt_probe_offsets(int fd,
+                                                           const char *provider_name,
+                                                           const char *probe_name,
+                                                           uint64_t **offsets,
+                                                           uint32_t *nb_probe);
+
+#endif /* _LTTNG_ELF_H */
index 2ffb75483240ebfafd6b7278b90f615081d4ef87..f746c3475cbc768cc423fd574c1709e83548ec65 100644 (file)
@@ -9,9 +9,10 @@
 #ifndef _LTTNG_KERNEL_OLD_H
 #define _LTTNG_KERNEL_OLD_H
 
-#include <stdint.h>
 #include <common/lttng-kernel.hpp>
 
+#include <stdint.h>
+
 /*
  * LTTng DebugFS ABI structures.
  *
@@ -26,8 +27,8 @@ struct lttng_kernel_abi_old_perf_counter_ctx {
 };
 
 /* Event/Channel context */
-#define LTTNG_KERNEL_ABI_OLD_CONTEXT_PADDING1  16
-#define LTTNG_KERNEL_ABI_OLD_CONTEXT_PADDING2  LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_OLD_CONTEXT_PADDING1 16
+#define LTTNG_KERNEL_ABI_OLD_CONTEXT_PADDING2 ((LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32))
 struct lttng_kernel_abi_old_context {
        enum lttng_kernel_abi_context_type ctx;
        char padding[LTTNG_KERNEL_ABI_OLD_CONTEXT_PADDING1];
@@ -60,8 +61,8 @@ struct lttng_kernel_abi_old_function {
        char symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN];
 };
 
-#define LTTNG_KERNEL_ABI_OLD_EVENT_PADDING1    16
-#define LTTNG_KERNEL_ABI_OLD_EVENT_PADDING2    LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_OLD_EVENT_PADDING1 16
+#define LTTNG_KERNEL_ABI_OLD_EVENT_PADDING2 ((LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32))
 struct lttng_kernel_abi_old_event {
        char name[LTTNG_KERNEL_ABI_SYM_NAME_LEN];
        enum lttng_kernel_abi_instrumentation instrumentation;
@@ -85,14 +86,14 @@ struct lttng_kernel_abi_old_tracer_version {
 /*
  * kernel channel
  */
-#define LTTNG_KERNEL_ABI_OLD_CHANNEL_PADDING1 LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_OLD_CHANNEL_PADDING1 ((LTTNG_SYMBOL_NAME_LEN + 32))
 struct lttng_kernel_abi_old_channel {
-       int overwrite;                      /* 1: overwrite, 0: discard */
-       uint64_t subbuf_size;               /* bytes */
-       uint64_t num_subbuf;                /* power of 2 */
+       int overwrite; /* 1: overwrite, 0: discard */
+       uint64_t subbuf_size; /* bytes */
+       uint64_t num_subbuf; /* power of 2 */
        unsigned int switch_timer_interval; /* usec */
-       unsigned int read_timer_interval;   /* usec */
-       enum lttng_event_output output;     /* splice, mmap */
+       unsigned int read_timer_interval; /* usec */
+       enum lttng_event_output output; /* splice, mmap */
 
        char padding[LTTNG_KERNEL_ABI_OLD_CHANNEL_PADDING1];
 };
index 6b1f7985db589fd847df9f651a404be55aa06f1e..ad8d03acfc38f4f92fbbd9cabd2cf0dbe77bfa9b 100644 (file)
@@ -9,15 +9,18 @@
 #ifndef _LTTNG_KERNEL_H
 #define _LTTNG_KERNEL_H
 
-#include <stdint.h>
+#include <common/compiler.hpp>
 #include <common/macros.hpp>
+
 #include <lttng/constant.h>
 #include <lttng/event.h>
 
-#define LTTNG_KERNEL_ABI_SYM_NAME_LEN  256
-#define LTTNG_KERNEL_ABI_MAX_UPROBE_NUM  32
-#define LTTNG_KERNEL_ABI_SESSION_NAME_LEN      256
-#define LTTNG_KERNEL_ABI_SESSION_CREATION_TIME_ISO8601_LEN     26
+#include <stdint.h>
+
+#define LTTNG_KERNEL_ABI_SYM_NAME_LEN                     256
+#define LTTNG_KERNEL_ABI_MAX_UPROBE_NUM                           32
+#define LTTNG_KERNEL_ABI_SESSION_NAME_LEN                 256
+#define LTTNG_KERNEL_ABI_SESSION_CREATION_TIME_ISO8601_LEN 26
 
 /*
  * LTTng DebugFS ABI structures.
  */
 
 enum lttng_kernel_abi_instrumentation {
-       LTTNG_KERNEL_ABI_ALL           = -1,   /* Used within lttng-tools */
-       LTTNG_KERNEL_ABI_TRACEPOINT    = 0,
-       LTTNG_KERNEL_ABI_KPROBE        = 1,
-       LTTNG_KERNEL_ABI_FUNCTION      = 2,
-       LTTNG_KERNEL_ABI_KRETPROBE     = 3,
-       LTTNG_KERNEL_ABI_NOOP          = 4,    /* not hooked */
-       LTTNG_KERNEL_ABI_SYSCALL       = 5,
-       LTTNG_KERNEL_ABI_UPROBE        = 6,
+       LTTNG_KERNEL_ABI_ALL = -1, /* Used within lttng-tools */
+       LTTNG_KERNEL_ABI_TRACEPOINT = 0,
+       LTTNG_KERNEL_ABI_KPROBE = 1,
+       LTTNG_KERNEL_ABI_FUNCTION = 2,
+       LTTNG_KERNEL_ABI_KRETPROBE = 3,
+       LTTNG_KERNEL_ABI_NOOP = 4, /* not hooked */
+       LTTNG_KERNEL_ABI_SYSCALL = 5,
+       LTTNG_KERNEL_ABI_UPROBE = 6,
 };
 
 enum lttng_kernel_abi_context_type {
-       LTTNG_KERNEL_ABI_CONTEXT_PID            = 0,
+       LTTNG_KERNEL_ABI_CONTEXT_PID = 0,
        LTTNG_KERNEL_ABI_CONTEXT_PERF_CPU_COUNTER = 1,
-       LTTNG_KERNEL_ABI_CONTEXT_PROCNAME       = 2,
-       LTTNG_KERNEL_ABI_CONTEXT_PRIO           = 3,
-       LTTNG_KERNEL_ABI_CONTEXT_NICE           = 4,
-       LTTNG_KERNEL_ABI_CONTEXT_VPID           = 5,
-       LTTNG_KERNEL_ABI_CONTEXT_TID            = 6,
-       LTTNG_KERNEL_ABI_CONTEXT_VTID           = 7,
-       LTTNG_KERNEL_ABI_CONTEXT_PPID           = 8,
-       LTTNG_KERNEL_ABI_CONTEXT_VPPID          = 9,
-       LTTNG_KERNEL_ABI_CONTEXT_HOSTNAME       = 10,
-       LTTNG_KERNEL_ABI_CONTEXT_CPU_ID         = 11,
-       LTTNG_KERNEL_ABI_CONTEXT_INTERRUPTIBLE  = 12,
-       LTTNG_KERNEL_ABI_CONTEXT_PREEMPTIBLE    = 13,
+       LTTNG_KERNEL_ABI_CONTEXT_PROCNAME = 2,
+       LTTNG_KERNEL_ABI_CONTEXT_PRIO = 3,
+       LTTNG_KERNEL_ABI_CONTEXT_NICE = 4,
+       LTTNG_KERNEL_ABI_CONTEXT_VPID = 5,
+       LTTNG_KERNEL_ABI_CONTEXT_TID = 6,
+       LTTNG_KERNEL_ABI_CONTEXT_VTID = 7,
+       LTTNG_KERNEL_ABI_CONTEXT_PPID = 8,
+       LTTNG_KERNEL_ABI_CONTEXT_VPPID = 9,
+       LTTNG_KERNEL_ABI_CONTEXT_HOSTNAME = 10,
+       LTTNG_KERNEL_ABI_CONTEXT_CPU_ID = 11,
+       LTTNG_KERNEL_ABI_CONTEXT_INTERRUPTIBLE = 12,
+       LTTNG_KERNEL_ABI_CONTEXT_PREEMPTIBLE = 13,
        LTTNG_KERNEL_ABI_CONTEXT_NEED_RESCHEDULE = 14,
-       LTTNG_KERNEL_ABI_CONTEXT_MIGRATABLE     = 15,
+       LTTNG_KERNEL_ABI_CONTEXT_MIGRATABLE = 15,
        LTTNG_KERNEL_ABI_CONTEXT_CALLSTACK_KERNEL = 16,
-       LTTNG_KERNEL_ABI_CONTEXT_CALLSTACK_USER   = 17,
-       LTTNG_KERNEL_ABI_CONTEXT_CGROUP_NS      = 18,
-       LTTNG_KERNEL_ABI_CONTEXT_IPC_NS         = 19,
-       LTTNG_KERNEL_ABI_CONTEXT_MNT_NS         = 20,
-       LTTNG_KERNEL_ABI_CONTEXT_NET_NS         = 21,
-       LTTNG_KERNEL_ABI_CONTEXT_PID_NS         = 22,
-       LTTNG_KERNEL_ABI_CONTEXT_USER_NS        = 23,
-       LTTNG_KERNEL_ABI_CONTEXT_UTS_NS         = 24,
-       LTTNG_KERNEL_ABI_CONTEXT_UID            = 25,
-       LTTNG_KERNEL_ABI_CONTEXT_EUID           = 26,
-       LTTNG_KERNEL_ABI_CONTEXT_SUID           = 27,
-       LTTNG_KERNEL_ABI_CONTEXT_GID            = 28,
-       LTTNG_KERNEL_ABI_CONTEXT_EGID           = 29,
-       LTTNG_KERNEL_ABI_CONTEXT_SGID           = 30,
-       LTTNG_KERNEL_ABI_CONTEXT_VUID           = 31,
-       LTTNG_KERNEL_ABI_CONTEXT_VEUID          = 32,
-       LTTNG_KERNEL_ABI_CONTEXT_VSUID          = 33,
-       LTTNG_KERNEL_ABI_CONTEXT_VGID           = 34,
-       LTTNG_KERNEL_ABI_CONTEXT_VEGID          = 35,
-       LTTNG_KERNEL_ABI_CONTEXT_VSGID          = 36,
-       LTTNG_KERNEL_ABI_CONTEXT_TIME_NS        = 37,
+       LTTNG_KERNEL_ABI_CONTEXT_CALLSTACK_USER = 17,
+       LTTNG_KERNEL_ABI_CONTEXT_CGROUP_NS = 18,
+       LTTNG_KERNEL_ABI_CONTEXT_IPC_NS = 19,
+       LTTNG_KERNEL_ABI_CONTEXT_MNT_NS = 20,
+       LTTNG_KERNEL_ABI_CONTEXT_NET_NS = 21,
+       LTTNG_KERNEL_ABI_CONTEXT_PID_NS = 22,
+       LTTNG_KERNEL_ABI_CONTEXT_USER_NS = 23,
+       LTTNG_KERNEL_ABI_CONTEXT_UTS_NS = 24,
+       LTTNG_KERNEL_ABI_CONTEXT_UID = 25,
+       LTTNG_KERNEL_ABI_CONTEXT_EUID = 26,
+       LTTNG_KERNEL_ABI_CONTEXT_SUID = 27,
+       LTTNG_KERNEL_ABI_CONTEXT_GID = 28,
+       LTTNG_KERNEL_ABI_CONTEXT_EGID = 29,
+       LTTNG_KERNEL_ABI_CONTEXT_SGID = 30,
+       LTTNG_KERNEL_ABI_CONTEXT_VUID = 31,
+       LTTNG_KERNEL_ABI_CONTEXT_VEUID = 32,
+       LTTNG_KERNEL_ABI_CONTEXT_VSUID = 33,
+       LTTNG_KERNEL_ABI_CONTEXT_VGID = 34,
+       LTTNG_KERNEL_ABI_CONTEXT_VEGID = 35,
+       LTTNG_KERNEL_ABI_CONTEXT_VSGID = 36,
+       LTTNG_KERNEL_ABI_CONTEXT_TIME_NS = 37,
 };
 
 /* Perf counter attributes */
@@ -85,8 +88,8 @@ struct lttng_kernel_abi_perf_counter_ctx {
 } LTTNG_PACKED;
 
 /* Event/Channel context */
-#define LTTNG_KERNEL_ABI_CONTEXT_PADDING1  16
-#define LTTNG_KERNEL_ABI_CONTEXT_PADDING2  LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_CONTEXT_PADDING1 16
+#define LTTNG_KERNEL_ABI_CONTEXT_PADDING2 ((LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32))
 struct lttng_kernel_abi_context {
        enum lttng_kernel_abi_context_type ctx;
        char padding[LTTNG_KERNEL_ABI_CONTEXT_PADDING1];
@@ -129,28 +132,28 @@ struct lttng_kernel_abi_event_callsite {
 } LTTNG_PACKED;
 
 enum lttng_kernel_abi_syscall_entryexit {
-       LTTNG_KERNEL_ABI_SYSCALL_ENTRYEXIT      = 0,
-       LTTNG_KERNEL_ABI_SYSCALL_ENTRY  = 1,
-       LTTNG_KERNEL_ABI_SYSCALL_EXIT   = 2,
+       LTTNG_KERNEL_ABI_SYSCALL_ENTRYEXIT = 0,
+       LTTNG_KERNEL_ABI_SYSCALL_ENTRY = 1,
+       LTTNG_KERNEL_ABI_SYSCALL_EXIT = 2,
 };
 
 enum lttng_kernel_abi_syscall_abi {
-       LTTNG_KERNEL_ABI_SYSCALL_ABI_ALL        = 0,
+       LTTNG_KERNEL_ABI_SYSCALL_ABI_ALL = 0,
        LTTNG_KERNEL_ABI_SYSCALL_ABI_NATIVE = 1,
        LTTNG_KERNEL_ABI_SYSCALL_ABI_COMPAT = 2,
 };
 
 enum lttng_kernel_abi_syscall_match {
        LTTNG_KERNEL_ABI_SYSCALL_MATCH_NAME = 0,
-       LTTNG_KERNEL_ABI_SYSCALL_MATCH_NR       = 1,
+       LTTNG_KERNEL_ABI_SYSCALL_MATCH_NR = 1,
 };
 
 struct lttng_kernel_abi_syscall {
-       uint8_t entryexit;      /* enum lttng_kernel_abi_syscall_entryexit */
-       uint8_t abi;            /* enum lttng_kernel_abi_syscall_abi */
-       uint8_t match;          /* enum lttng_kernel_abi_syscall_match */
+       uint8_t entryexit; /* enum lttng_kernel_abi_syscall_entryexit */
+       uint8_t abi; /* enum lttng_kernel_abi_syscall_abi */
+       uint8_t match; /* enum lttng_kernel_abi_syscall_match */
        uint8_t padding;
-       uint32_t nr;            /* For LTTNG_SYSCALL_MATCH_NR */
+       uint32_t nr; /* For LTTNG_SYSCALL_MATCH_NR */
 } LTTNG_PACKED;
 
 /* Function tracer */
@@ -158,8 +161,8 @@ struct lttng_kernel_abi_function {
        char symbol_name[LTTNG_KERNEL_ABI_SYM_NAME_LEN];
 } LTTNG_PACKED;
 
-#define LTTNG_KERNEL_ABI_EVENT_PADDING1    8
-#define LTTNG_KERNEL_ABI_EVENT_PADDING2    LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_EVENT_PADDING1 8
+#define LTTNG_KERNEL_ABI_EVENT_PADDING2 ((LTTNG_KERNEL_ABI_SYM_NAME_LEN + 32))
 struct lttng_kernel_abi_event {
        char name[LTTNG_KERNEL_ABI_SYM_NAME_LEN];
        enum lttng_kernel_abi_instrumentation instrumentation;
@@ -177,7 +180,7 @@ struct lttng_kernel_abi_event {
        } u;
 } LTTNG_PACKED;
 
-#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_PADDING        32
+#define LTTNG_KERNEL_ABI_EVENT_NOTIFIER_PADDING 32
 struct lttng_kernel_abi_event_notifier {
        struct lttng_kernel_abi_event event;
        uint64_t error_counter_idx;
@@ -185,7 +188,7 @@ struct lttng_kernel_abi_event_notifier {
        char padding[LTTNG_KERNEL_ABI_EVENT_NOTIFIER_PADDING];
 } LTTNG_PACKED;
 
-#define LTTNG_KERNEL_ABI_COUNTER_DIMENSION_MAX      4
+#define LTTNG_KERNEL_ABI_COUNTER_DIMENSION_MAX 4
 
 enum lttng_kernel_abi_counter_arithmetic {
        LTTNG_KERNEL_ABI_COUNTER_ARITHMETIC_MODULAR = 0,
@@ -204,10 +207,10 @@ struct lttng_kernel_abi_counter_dimension {
        uint8_t has_overflow;
 } LTTNG_PACKED;
 
-#define LTTNG_KERNEL_ABI_COUNTER_CONF_PADDING1      67
+#define LTTNG_KERNEL_ABI_COUNTER_CONF_PADDING1 67
 struct lttng_kernel_abi_counter_conf {
-       uint32_t arithmetic;    /* enum lttng_kernel_abi_counter_arithmetic */
-       uint32_t bitness;       /* enum lttng_kernel_abi_counter_bitness */
+       uint32_t arithmetic; /* enum lttng_kernel_abi_counter_arithmetic */
+       uint32_t bitness; /* enum lttng_kernel_abi_counter_bitness */
        uint32_t number_dimensions;
        int64_t global_sum_step;
        struct lttng_kernel_abi_counter_dimension dimensions[LTTNG_KERNEL_ABI_COUNTER_DIMENSION_MAX];
@@ -229,15 +232,15 @@ struct lttng_kernel_abi_counter_value {
 #define LTTNG_KERNEL_ABI_COUNTER_READ_PADDING 32
 struct lttng_kernel_abi_counter_read {
        struct lttng_kernel_abi_counter_index index;
-       int32_t cpu;    /* -1 for global counter, >= 0 for specific cpu. */
-       struct lttng_kernel_abi_counter_value value;    /* output */
+       int32_t cpu; /* -1 for global counter, >= 0 for specific cpu. */
+       struct lttng_kernel_abi_counter_value value; /* output */
        char padding[LTTNG_KERNEL_ABI_COUNTER_READ_PADDING];
 } LTTNG_PACKED;
 
 #define LTTNG_KERNEL_ABI_COUNTER_AGGREGATE_PADDING 32
 struct lttng_kernel_abi_counter_aggregate {
        struct lttng_kernel_abi_counter_index index;
-       struct lttng_kernel_abi_counter_value value;    /* output */
+       struct lttng_kernel_abi_counter_value value; /* output */
        char padding[LTTNG_KERNEL_ABI_COUNTER_AGGREGATE_PADDING];
 } LTTNG_PACKED;
 
@@ -254,7 +257,7 @@ struct lttng_kernel_abi_event_notifier_notification {
        char padding[LTTNG_KERNEL_ABI_EVENT_NOTIFIER_NOTIFICATION_PADDING];
 } LTTNG_PACKED;
 
-#define LTTNG_KERNEL_ABI_CAPTURE_BYTECODE_MAX_LEN              65536
+#define LTTNG_KERNEL_ABI_CAPTURE_BYTECODE_MAX_LEN 65536
 struct lttng_kernel_abi_capture_bytecode {
        uint32_t len;
        uint32_t reloc_offset;
@@ -274,26 +277,26 @@ struct lttng_kernel_abi_tracer_abi_version {
 } LTTNG_PACKED;
 
 struct lttng_kernel_abi_syscall_mask {
-       uint32_t len;   /* in bits */
-       char mask[];
+       uint32_t len; /* in bits */
+       char mask[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 /*
  * kernel channel
  */
-#define LTTNG_KERNEL_ABI_CHANNEL_PADDING1 LTTNG_SYMBOL_NAME_LEN + 32
+#define LTTNG_KERNEL_ABI_CHANNEL_PADDING1 ((LTTNG_SYMBOL_NAME_LEN + 32))
 struct lttng_kernel_abi_channel {
-       uint64_t subbuf_size;               /* bytes */
-       uint64_t num_subbuf;                /* power of 2 */
+       uint64_t subbuf_size; /* bytes */
+       uint64_t num_subbuf; /* power of 2 */
        unsigned int switch_timer_interval; /* usec */
-       unsigned int read_timer_interval;   /* usec */
-       enum lttng_event_output output;     /* splice, mmap */
+       unsigned int read_timer_interval; /* usec */
+       enum lttng_event_output output; /* splice, mmap */
 
-       int overwrite;                      /* 1: overwrite, 0: discard */
+       int overwrite; /* 1: overwrite, 0: discard */
        char padding[LTTNG_KERNEL_ABI_CHANNEL_PADDING1];
 } LTTNG_PACKED;
 
-#define KERNEL_FILTER_BYTECODE_MAX_LEN         65536
+#define KERNEL_FILTER_BYTECODE_MAX_LEN 65536
 struct lttng_kernel_abi_filter_bytecode {
        uint32_t len;
        uint32_t reloc_offset;
@@ -316,14 +319,14 @@ struct lttng_kernel_abi_session_creation_time {
 } LTTNG_PACKED;
 
 enum lttng_kernel_abi_tracker_type {
-       LTTNG_KERNEL_ABI_TRACKER_UNKNOWN                = -1,
-
-       LTTNG_KERNEL_ABI_TRACKER_PID            = 0,
-       LTTNG_KERNEL_ABI_TRACKER_VPID           = 1,
-       LTTNG_KERNEL_ABI_TRACKER_UID            = 2,
-       LTTNG_KERNEL_ABI_TRACKER_VUID           = 3,
-       LTTNG_KERNEL_ABI_TRACKER_GID            = 4,
-       LTTNG_KERNEL_ABI_TRACKER_VGID           = 5,
+       LTTNG_KERNEL_ABI_TRACKER_UNKNOWN = -1,
+
+       LTTNG_KERNEL_ABI_TRACKER_PID = 0,
+       LTTNG_KERNEL_ABI_TRACKER_VPID = 1,
+       LTTNG_KERNEL_ABI_TRACKER_UID = 2,
+       LTTNG_KERNEL_ABI_TRACKER_VUID = 3,
+       LTTNG_KERNEL_ABI_TRACKER_GID = 4,
+       LTTNG_KERNEL_ABI_TRACKER_VGID = 5,
 };
 
 struct lttng_kernel_abi_tracker_args {
index cfe6eb5289d637ef1f1d1ddafe1b2f808a78535a..f1d039a1f4643fa3f3fb30771d5b375e934212a1 100644 (file)
 
 #include <common/compat/string.hpp>
 
+#include <memory>
+#include <pthread.h>
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
-
-#include <memory>
-#include <pthread.h>
 #include <type_traits>
 
 /*
  * memory using malloc(), we must use generic accessors for compat in order to
  * *not* use a function to access members and not the variable name.
  */
-#define LTTNG_REF(x) ((typeof(*x) *)(x))
+#define LTTNG_REF(x) ((typeof(*(x)) *) (x))
 
 #ifdef NDEBUG
 /*
-* Force usage of the assertion condition to prevent unused variable warnings
-* when `assert()` are disabled by the `NDEBUG` definition.
-*/
-# define LTTNG_ASSERT(_cond) ((void) sizeof((void) (_cond), 0))
+ * Force usage of the assertion condition to prevent unused variable warnings
+ * when `assert()` are disabled by the `NDEBUG` definition.
+ */
+#define LTTNG_ASSERT(_cond) ((void) sizeof((void) (_cond), 0))
 #else
-# include <assert.h>
-# define LTTNG_ASSERT(_cond) assert(_cond)
+#include <assert.h>
+#define LTTNG_ASSERT(_cond) assert(_cond)
 #endif
 
 /*
  * Memory allocation zeroed
  */
 
-static inline
-void *zmalloc_internal(size_t size)
+static inline void *zmalloc_internal(size_t size)
 {
        return calloc(1, size);
 }
 
-template <typename T>
-struct can_malloc
-{
+template <typename MallocableType>
+struct can_malloc {
        /*
         * gcc versions before 5.0 lack some type traits defined in C++11.
         * Since in this instance we use the trait to prevent misuses
@@ -76,64 +73,69 @@ struct can_malloc
 #if __GNUG__ && __GNUC__ < 5
        static constexpr bool value = true;
 #else
-       static constexpr bool value = std::is_trivially_constructible<T>::value;
+       static constexpr bool value = std::is_trivially_constructible<MallocableType>::value;
 #endif
 };
 
 /*
- * Malloc and zero-initialize an object of type T, asserting that T can be
+ * Malloc and zero-initialize an object of type T, asserting that MallocableType can be
  * safely malloc-ed (is trivially constructible).
  */
-template<typename T>
-T *zmalloc()
+template <typename MallocableType>
+MallocableType *zmalloc()
 {
-       static_assert (can_malloc<T>::value, "type can be malloc'ed");
-       return (T *) zmalloc_internal(sizeof(T));
+       static_assert(can_malloc<MallocableType>::value, "type can be malloc'ed");
+       return (MallocableType *) zmalloc_internal(sizeof(MallocableType)); /* NOLINT sizeof
+                                                                              potentially used on a
+                                                                              pointer. */
 }
 
 /*
- * Malloc and zero-initialize a buffer of size `size`, asserting that type T
+ * Malloc and zero-initialize a buffer of size `size`, asserting that type AllocatedType
  * can be safely malloc-ed (is trivially constructible).
  */
-template<typename T>
-T *zmalloc(size_t size)
+template <typename AllocatedType>
+AllocatedType *zmalloc(size_t size)
 {
-       static_assert (can_malloc<T>::value, "type can be malloc'ed");
-       LTTNG_ASSERT(size >= sizeof(T));
-       return (T *) zmalloc_internal(size);
+       static_assert(can_malloc<AllocatedType>::value, "type can be malloc'ed");
+       LTTNG_ASSERT(size >= sizeof(AllocatedType));
+       return (AllocatedType *) zmalloc_internal(size);
 }
 
 /*
- * Malloc and zero-initialize an array of `nmemb` elements of type T,
- * asserting that T can be safely malloc-ed (is trivially constructible).
+ * Malloc and zero-initialize an array of `nmemb` elements of type AllocatedType,
+ * asserting that AllocatedType can be safely malloc-ed (is trivially constructible).
  */
-template<typename T>
-T *calloc(size_t nmemb)
+template <typename AllocatedType>
+AllocatedType *calloc(size_t nmemb)
 {
-       static_assert (can_malloc<T>::value, "type can be malloc'ed");
-       return (T *) zmalloc_internal(nmemb * sizeof(T));
+       static_assert(can_malloc<AllocatedType>::value, "type can be malloc'ed");
+       return (AllocatedType *) zmalloc_internal(nmemb * sizeof(AllocatedType)); /* NOLINT sizeof
+                                                                                    potentially
+                                                                                    used on a
+                                                                                    pointer. */
 }
 
 /*
- * Malloc an object of type T, asserting that T can be safely malloc-ed (is
+ * Malloc an object of type AllocatedType, asserting that AllocatedType can be safely malloc-ed (is
  * trivially constructible).
  */
-template<typename T>
-T *malloc()
+template <typename AllocatedType>
+AllocatedType *malloc()
 {
-       static_assert (can_malloc<T>::value, "type can be malloc'ed");
-       return (T *) malloc(sizeof(T));
+       static_assert(can_malloc<AllocatedType>::value, "type can be malloc'ed");
+       return (AllocatedType *) malloc(sizeof(AllocatedType));
 }
 
 /*
- * Malloc a buffer of size `size`, asserting that type T can be safely
+ * Malloc a buffer of size `size`, asserting that AllocatedType can be safely
  * malloc-ed (is trivially constructible).
  */
-template<typename T>
-T *malloc(size_t size)
+template <typename AllocatedType>
+AllocatedType *malloc(size_t size)
 {
-       static_assert (can_malloc<T>::value, "type can be malloc'ed");
-       return (T *) malloc(size);
+       static_assert(can_malloc<AllocatedType>::value, "type can be malloc'ed");
+       return (AllocatedType *) malloc(size);
 }
 
 /*
@@ -149,9 +151,8 @@ T *malloc(size_t size)
  * pointers to void, these will not be checked.
  */
 
-template<typename T>
-struct can_free
-{
+template <typename FreedType>
+struct can_free {
        /*
         * gcc versions before 5.0 lack some type traits defined in C++11.
         * Since in this instance we use the trait to prevent misuses
@@ -163,25 +164,26 @@ struct can_free
 #if __GNUG__ && __GNUC__ < 5
        static constexpr bool value = true;
 #else
-       static constexpr bool value = std::is_trivially_destructible<T>::value || std::is_void<T>::value;
+       static constexpr bool value = std::is_trivially_destructible<FreedType>::value ||
+               std::is_void<FreedType>::value;
 #endif
 };
 
-template<typename T, typename = typename std::enable_if<!can_free<T>::value>::type>
-void free(T *p) = delete;
+template <typename FreedType, typename = typename std::enable_if<!can_free<FreedType>::value>::type>
+void free(FreedType *p) = delete;
 
-template<typename T>
-struct can_memset
-{
-       static constexpr bool value = std::is_pod<T>::value || std::is_void<T>::value;
+template <typename InitializedType>
+struct can_memset {
+       static constexpr bool value = std::is_pod<InitializedType>::value ||
+               std::is_void<InitializedType>::value;
 };
 
-template <typename T, typename = typename std::enable_if<!can_memset<T>::value>::type>
-void *memset(T *s, int c, size_t n) = delete;
+template <typename InitializedType,
+         typename = typename std::enable_if<!can_memset<InitializedType>::value>::type>
+void *memset(InitializedType *s, int c, size_t n) = delete;
 
-template<typename T>
-struct can_memcpy
-{
+template <typename T>
+struct can_memcpy {
        /*
         * gcc versions before 5.0 lack some type traits defined in C++11.
         * Since in this instance we use the trait to prevent misuses
@@ -197,14 +199,14 @@ struct can_memcpy
 #endif
 };
 
-template <typename T, typename U,
-               typename = typename std::enable_if<!can_memcpy<T>::value>::type,
-               typename = typename std::enable_if<!can_memcpy<U>::value>::type>
-void *memcpy(T *d, const U *s, size_t n) = delete;
+template <typename DestinationType,
+         typename SourceType,
+         typename = typename std::enable_if<!can_memcpy<DestinationType>::value>::type,
+         typename = typename std::enable_if<!can_memcpy<SourceType>::value>::type>
+void *memcpy(DestinationType *d, const SourceType *s, size_t n) = delete;
 
-template<typename T>
-struct can_memmove
-{
+template <typename MovedType>
+struct can_memmove {
        /*
         * gcc versions before 5.0 lack some type traits defined in C++11.
         * Since in this instance we use the trait to prevent misuses
@@ -216,17 +218,18 @@ struct can_memmove
 #if __GNUG__ && __GNUC__ < 5
        static constexpr bool value = true;
 #else
-       static constexpr bool value = std::is_trivially_copyable<T>::value;
+       static constexpr bool value = std::is_trivially_copyable<MovedType>::value;
 #endif
 };
 
-template <typename T, typename U,
-               typename = typename std::enable_if<!can_memmove<T>::value>::type,
-               typename = typename std::enable_if<!can_memmove<U>::value>::type>
-void *memmove(T *d, const U *s, size_t n) = delete;
+template <typename DestinationType,
+         typename SourceType,
+         typename = typename std::enable_if<!can_memmove<DestinationType>::value>::type,
+         typename = typename std::enable_if<!can_memmove<SourceType>::value>::type>
+void *memmove(DestinationType *d, const SourceType *s, size_t n) = delete;
 
 #ifndef ARRAY_SIZE
-#define ARRAY_SIZE(array)   (sizeof(array) / (sizeof((array)[0])))
+#define ARRAY_SIZE(array) (sizeof(array) / (sizeof((array)[0])))
 #endif
 
 #ifndef LTTNG_PACKED
@@ -234,56 +237,54 @@ void *memmove(T *d, const U *s, size_t n) = delete;
 #endif
 
 #ifndef LTTNG_NO_SANITIZE_ADDRESS
-#if defined(__clang__) || defined (__GNUC__)
+#if defined(__clang__) || defined(__GNUC__)
 #define LTTNG_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
 #else
 #define LTTNG_NO_SANITIZE_ADDRESS
 #endif
 #endif
 
-#define member_sizeof(type, field)     sizeof(((type *) 0)->field)
+#define member_sizeof(type, field) sizeof(((type *) 0)->field)
 
-#define ASSERT_LOCKED(lock) LTTNG_ASSERT(pthread_mutex_trylock(&lock))
-#define ASSERT_RCU_READ_LOCKED(lock) LTTNG_ASSERT(rcu_read_ongoing())
+#define ASSERT_LOCKED(lock)       LTTNG_ASSERT(pthread_mutex_trylock(&(lock)))
+#define ASSERT_RCU_READ_LOCKED()   LTTNG_ASSERT(rcu_read_ongoing())
+#define ASSERT_RCU_READ_UNLOCKED() LTTNG_ASSERT(!rcu_read_ongoing())
 
 /* Attribute suitable to tag functions as having printf()-like arguments. */
 #define ATTR_FORMAT_PRINTF(_string_index, _first_to_check) \
        __attribute__((format(printf, _string_index, _first_to_check)))
 
 /* Attribute suitable to tag functions as having strftime()-like arguments. */
-#define ATTR_FORMAT_STRFTIME(_string_index) \
-       __attribute__((format(strftime, _string_index, 0)))
+#define ATTR_FORMAT_STRFTIME(_string_index) __attribute__((format(strftime, _string_index, 0)))
 
 /* Macros used to ignore specific compiler diagnostics. */
 
 #define DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
-#define DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
+#define DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
 
 #if defined(__clang__)
-  /* Clang */
-# define DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
-# define DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL \
+/* Clang */
+#define DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
+#define DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL \
        _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
-# define DIAGNOSTIC_IGNORE_LOGICAL_OP
-# define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
-# define DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
-       _Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
+#define DIAGNOSTIC_IGNORE_LOGICAL_OP
+#define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
+#define DIAGNOSTIC_IGNORE_INVALID_OFFSETOF
+_Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
 #else
-  /* GCC */
-# define DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT \
+/* GCC */
+#define DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT \
        _Pragma("GCC diagnostic ignored \"-Wsuggest-attribute=format\"")
-# define DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL \
+#define DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL \
        _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
-# define DIAGNOSTIC_IGNORE_LOGICAL_OP \
-       _Pragma("GCC diagnostic ignored \"-Wlogical-op\"")
+#define DIAGNOSTIC_IGNORE_LOGICAL_OP _Pragma("GCC diagnostic ignored \"-Wlogical-op\"")
 #if __GNUG__ && __GNUC__ >= 7
-# define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES                         \
+#define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES \
        _Pragma("GCC diagnostic ignored \"-Wduplicated-branches\"")
 #else
-# define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
+#define DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
 #endif /* __GNUG__ && __GNUC__ >= 7 */
-# define DIAGNOSTIC_IGNORE_INVALID_OFFSETOF                            \
-       _Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
+#define DIAGNOSTIC_IGNORE_INVALID_OFFSETOF _Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
 #endif
 
 /* Used to make specific C++ functions to C code. */
@@ -293,17 +294,16 @@ void *memmove(T *d, const U *s, size_t n) = delete;
 #define C_LINKAGE
 #endif
 
-/*
- * lttng_strncpy returns 0 on success, or nonzero on failure.
- * It checks that the @src string fits into @dst_len before performing
- * the copy. On failure, no copy has been performed.
- *
- * Assumes that 'src' is null-terminated.
- *
- * dst_len includes the string's trailing NULL.
- */
-static inline
-int lttng_strncpy(char *dst, const char *src, size_t dst_len)
+       /*
+        * lttng_strncpy returns 0 on success, or nonzero on failure.
+        * It checks that the @src string fits into @dst_len before performing
+        * the copy. On failure, no copy has been performed.
+        *
+        * Assumes that 'src' is null-terminated.
+        *
+        * dst_len includes the string's trailing NULL.
+        */
+       static inline int lttng_strncpy(char *dst, const char *src, size_t dst_len)
 {
        if (strlen(src) >= dst_len) {
                /* Fail since copying would result in truncation. */
@@ -315,14 +315,14 @@ int lttng_strncpy(char *dst, const char *src, size_t dst_len)
 
 namespace lttng {
 namespace utils {
-template <class Parent, class Member>
-Parent *container_of(const Member *member, const Member Parent::*ptr_to_member)
+template <class ParentType, class MemberType>
+ParentType *container_of(const MemberType *member, const MemberType ParentType::*ptr_to_member)
 {
-       const Parent *dummy_parent = nullptr;
+       const ParentType *dummy_parent = nullptr;
        auto *offset_of_member = reinterpret_cast<const char *>(&(dummy_parent->*ptr_to_member));
        auto address_of_parent = reinterpret_cast<const char *>(member) - offset_of_member;
 
-       return reinterpret_cast<Parent *>(address_of_parent);
+       return reinterpret_cast<ParentType *>(address_of_parent);
 }
 } /* namespace utils */
 } /* namespace lttng */
index 50d1916f20239624525c5226a926f5e76f58e3af..a0a4b541a2fd64bc7c01da8babd6b5c01bb54d5c 100644 (file)
@@ -34,14 +34,13 @@ namespace lttng {
  *                    create_my_c_struct());
  *
  * Note that this facility is intended for use in the scope of a function.
- * If you need to return this unique_ptr instance, you should consider writting
+ * If you need to return this unique_ptr instance, you should consider writing
  * a proper, idiomatic, wrapper.
  */
 
-namespace details
-{
+namespace memory {
 template <typename WrappedType, void (*DeleterFunction)(WrappedType *)>
-struct create_unique_class {
+struct create_deleter_class {
        struct deleter {
                void operator()(WrappedType *instance) const
                {
@@ -54,7 +53,6 @@ struct create_unique_class {
                return std::unique_ptr<WrappedType, deleter>(instance);
        }
 };
-} /* namespace details */
 
 /*
  * 'free' is a utility function for use with make_unique_wrapper. It makes it easier to
@@ -67,12 +65,14 @@ void free(Type *ptr)
 {
        std::free(ptr);
 }
+} /* namespace memory */
 
 template <typename WrappedType, void (*DeleterFunc)(WrappedType *)>
-std::unique_ptr<WrappedType, typename details::create_unique_class<WrappedType, DeleterFunc>::deleter>
-make_unique_wrapper(WrappedType *instance)
+std::unique_ptr<WrappedType,
+               typename memory::create_deleter_class<WrappedType, DeleterFunc>::deleter>
+make_unique_wrapper(WrappedType *instance = nullptr)
 {
-       const details::create_unique_class<WrappedType, DeleterFunc> unique_deleter;
+       const memory::create_deleter_class<WrappedType, DeleterFunc> unique_deleter;
 
        return unique_deleter(instance);
 }
index 01e89b779811a62be5da524148ba41b21f3cb71a..d7833fcd5d871d3e5d46d23d77f0f6d5bc34bfa4 100644 (file)
 #include "lttng/tracker.h"
 #define _LGPL_SOURCE
 #include "mi-lttng.hpp"
+
 #include <common/config/session-config.hpp>
 #include <common/defaults.hpp>
 #include <common/tracker.hpp>
+
 #include <lttng/channel.h>
 #include <lttng/snapshot-internal.hpp>
 
-
 #define MI_SCHEMA_MAJOR_VERSION 4
 #define MI_SCHEMA_MINOR_VERSION 1
 
 /* Machine interface namespace URI */
-const char * const mi_lttng_xmlns = "xmlns";
-const char * const mi_lttng_xmlns_xsi = "xmlns:xsi";
-const char * const mi_lttng_w3_schema_uri = "http://www.w3.org/2001/XMLSchema-instance";
-const char * const mi_lttng_schema_location = "xsi:schemaLocation";
-const char * const mi_lttng_schema_location_uri =
-       DEFAULT_LTTNG_MI_NAMESPACE " "
-       "https://lttng.org/xml/schemas/lttng-mi/" XSTR(MI_SCHEMA_MAJOR_VERSION)
-       "/lttng-mi-" XSTR(MI_SCHEMA_MAJOR_VERSION) "."
-       XSTR(MI_SCHEMA_MINOR_VERSION) ".xsd";
-const char * const mi_lttng_schema_version = "schemaVersion";
-const char * const mi_lttng_schema_version_value = XSTR(MI_SCHEMA_MAJOR_VERSION)
-       "." XSTR(MI_SCHEMA_MINOR_VERSION);
+const char *const mi_lttng_xmlns = "xmlns";
+const char *const mi_lttng_xmlns_xsi = "xmlns:xsi";
+const char *const mi_lttng_w3_schema_uri = "http://www.w3.org/2001/XMLSchema-instance";
+const char *const mi_lttng_schema_location = "xsi:schemaLocation";
+const char *const mi_lttng_schema_location_uri = DEFAULT_LTTNG_MI_NAMESPACE
+       " "
+       "https://lttng.org/xml/schemas/lttng-mi/" XSTR(MI_SCHEMA_MAJOR_VERSION) "/lttng-mi-" XSTR(
+               MI_SCHEMA_MAJOR_VERSION) "." XSTR(MI_SCHEMA_MINOR_VERSION) ".xsd";
+const char *const mi_lttng_schema_version = "schemaVersion";
+const char *const mi_lttng_schema_version_value =
+       XSTR(MI_SCHEMA_MAJOR_VERSION) "." XSTR(MI_SCHEMA_MINOR_VERSION);
 
 /* Strings related to command */
-const char * const mi_lttng_element_command = "command";
-const char * const mi_lttng_element_command_action = "snapshot_action";
-const char * const mi_lttng_element_command_add_context = "add-context";
+const char *const mi_lttng_element_command = "command";
+const char *const mi_lttng_element_command_action = "snapshot_action";
+const char *const mi_lttng_element_command_add_context = "add-context";
 const char *const mi_lttng_element_command_add_trigger = "add-trigger";
-const char * const mi_lttng_element_command_create = "create";
-const char * const mi_lttng_element_command_destroy = "destroy";
-const char * const mi_lttng_element_command_disable_channel = "disable-channel";
-const char * const mi_lttng_element_command_disable_event = "disable-event";
-const char * const mi_lttng_element_command_enable_channels = "enable-channel";
-const char * const mi_lttng_element_command_enable_event = "enable-event";
-const char * const mi_lttng_element_command_list = "list";
+const char *const mi_lttng_element_command_create = "create";
+const char *const mi_lttng_element_command_destroy = "destroy";
+const char *const mi_lttng_element_command_disable_channel = "disable-channel";
+const char *const mi_lttng_element_command_disable_event = "disable-event";
+const char *const mi_lttng_element_command_enable_channels = "enable-channel";
+const char *const mi_lttng_element_command_enable_event = "enable-event";
+const char *const mi_lttng_element_command_list = "list";
 const char *const mi_lttng_element_command_list_trigger = "list-trigger";
-const char * const mi_lttng_element_command_load = "load";
-const char * const mi_lttng_element_command_metadata = "metadata";
-const char * const mi_lttng_element_command_metadata_action = "metadata_action";
-const char * const mi_lttng_element_command_regenerate = "regenerate";
-const char * const mi_lttng_element_command_regenerate_action = "regenerate_action";
-const char * const mi_lttng_element_command_name = "name";
-const char * const mi_lttng_element_command_output = "output";
+const char *const mi_lttng_element_command_load = "load";
+const char *const mi_lttng_element_command_metadata = "metadata";
+const char *const mi_lttng_element_command_metadata_action = "metadata_action";
+const char *const mi_lttng_element_command_regenerate = "regenerate";
+const char *const mi_lttng_element_command_regenerate_action = "regenerate_action";
+const char *const mi_lttng_element_command_name = "name";
+const char *const mi_lttng_element_command_output = "output";
 const char *const mi_lttng_element_command_remove_trigger = "remove-trigger";
-const char * const mi_lttng_element_command_save = "save";
-const char * const mi_lttng_element_command_set_session = "set-session";
-const char * const mi_lttng_element_command_snapshot = "snapshot";
-const char * const mi_lttng_element_command_snapshot_add = "add_snapshot";
-const char * const mi_lttng_element_command_snapshot_del = "del_snapshot";
-const char * const mi_lttng_element_command_snapshot_list = "list_snapshot";
-const char * const mi_lttng_element_command_snapshot_record = "record_snapshot";
-const char * const mi_lttng_element_command_start = "start";
-const char * const mi_lttng_element_command_stop = "stop";
-const char * const mi_lttng_element_command_success = "success";
-const char * const mi_lttng_element_command_track = "track";
-const char * const mi_lttng_element_command_untrack = "untrack";
-const char * const mi_lttng_element_command_version = "version";
-const char * const mi_lttng_element_command_rotate = "rotate";
-const char * const mi_lttng_element_command_enable_rotation = "enable-rotation";
-const char * const mi_lttng_element_command_disable_rotation = "disable-rotation";
-const char * const mi_lttng_element_command_clear = "clear";
+const char *const mi_lttng_element_command_save = "save";
+const char *const mi_lttng_element_command_set_session = "set-session";
+const char *const mi_lttng_element_command_snapshot = "snapshot";
+const char *const mi_lttng_element_command_snapshot_add = "add_snapshot";
+const char *const mi_lttng_element_command_snapshot_del = "del_snapshot";
+const char *const mi_lttng_element_command_snapshot_list = "list_snapshot";
+const char *const mi_lttng_element_command_snapshot_record = "record_snapshot";
+const char *const mi_lttng_element_command_start = "start";
+const char *const mi_lttng_element_command_stop = "stop";
+const char *const mi_lttng_element_command_success = "success";
+const char *const mi_lttng_element_command_track = "track";
+const char *const mi_lttng_element_command_untrack = "untrack";
+const char *const mi_lttng_element_command_version = "version";
+const char *const mi_lttng_element_command_rotate = "rotate";
+const char *const mi_lttng_element_command_enable_rotation = "enable-rotation";
+const char *const mi_lttng_element_command_disable_rotation = "disable-rotation";
+const char *const mi_lttng_element_command_clear = "clear";
 
 /* Strings related to version command */
-const char * const mi_lttng_element_version = "version";
-const char * const mi_lttng_element_version_commit = "commit";
-const char * const mi_lttng_element_version_description = "description";
-const char * const mi_lttng_element_version_license = "license";
-const char * const mi_lttng_element_version_major = "major";
-const char * const mi_lttng_element_version_minor = "minor";
-const char * const mi_lttng_element_version_patch_level = "patchLevel";
-const char * const mi_lttng_element_version_str = "string";
-const char * const mi_lttng_element_version_web = "url";
+const char *const mi_lttng_element_version = "version";
+const char *const mi_lttng_element_version_commit = "commit";
+const char *const mi_lttng_element_version_description = "description";
+const char *const mi_lttng_element_version_license = "license";
+const char *const mi_lttng_element_version_major = "major";
+const char *const mi_lttng_element_version_minor = "minor";
+const char *const mi_lttng_element_version_patch_level = "patchLevel";
+const char *const mi_lttng_element_version_str = "string";
+const char *const mi_lttng_element_version_web = "url";
 
 /* String related to a lttng_event_field */
-const char * const mi_lttng_element_event_field = "event_field";
-const char * const mi_lttng_element_event_fields = "event_fields";
+const char *const mi_lttng_element_event_field = "event_field";
+const char *const mi_lttng_element_event_fields = "event_fields";
 
 /* String related to lttng_event_perf_counter_ctx */
-const char * const mi_lttng_element_perf_counter_context = "perf";
+const char *const mi_lttng_element_perf_counter_context = "perf";
 
 /* Strings related to pid */
-const char * const mi_lttng_element_pid_id = "id";
+const char *const mi_lttng_element_pid_id = "id";
 
 /* Strings related to save command */
-const char * const mi_lttng_element_save = "save";
+const char *const mi_lttng_element_save = "save";
 
 /* Strings related to load command */
-const char * const mi_lttng_element_load = "load";
-const char * const mi_lttng_element_load_overrides = "overrides";
-const char * const mi_lttng_element_load_override_url = "url";
+const char *const mi_lttng_element_load = "load";
+const char *const mi_lttng_element_load_overrides = "overrides";
+const char *const mi_lttng_element_load_override_url = "url";
 
 /* General elements of mi_lttng */
-const char * const mi_lttng_element_empty = "";
-const char * const mi_lttng_element_id = "id";
-const char * const mi_lttng_element_nowrite = "nowrite";
-const char * const mi_lttng_element_success = "success";
-const char * const mi_lttng_element_type_enum = "ENUM";
-const char * const mi_lttng_element_type_float = "FLOAT";
-const char * const mi_lttng_element_type_integer = "INTEGER";
-const char * const mi_lttng_element_type_other = "OTHER";
-const char * const mi_lttng_element_type_string = "STRING";
+const char *const mi_lttng_element_empty = "";
+const char *const mi_lttng_element_id = "id";
+const char *const mi_lttng_element_nowrite = "nowrite";
+const char *const mi_lttng_element_success = "success";
+const char *const mi_lttng_element_type_enum = "ENUM";
+const char *const mi_lttng_element_type_float = "FLOAT";
+const char *const mi_lttng_element_type_integer = "INTEGER";
+const char *const mi_lttng_element_type_other = "OTHER";
+const char *const mi_lttng_element_type_string = "STRING";
 
 /* String related to loglevel */
-const char * const mi_lttng_loglevel_str_alert = "TRACE_ALERT";
-const char * const mi_lttng_loglevel_str_crit = "TRACE_CRIT";
-const char * const mi_lttng_loglevel_str_debug = "TRACE_DEBUG";
-const char * const mi_lttng_loglevel_str_debug_function = "TRACE_DEBUG_FUNCTION";
-const char * const mi_lttng_loglevel_str_debug_line = "TRACE_DEBUG_LINE";
-const char * const mi_lttng_loglevel_str_debug_module = "TRACE_DEBUG_MODULE";
-const char * const mi_lttng_loglevel_str_debug_process = "TRACE_DEBUG_PROCESS";
-const char * const mi_lttng_loglevel_str_debug_program = "TRACE_DEBUG_PROGRAM";
-const char * const mi_lttng_loglevel_str_debug_system = "TRACE_DEBUG_SYSTEM";
-const char * const mi_lttng_loglevel_str_debug_unit = "TRACE_DEBUG_UNIT";
-const char * const mi_lttng_loglevel_str_emerg = "TRACE_EMERG";
-const char * const mi_lttng_loglevel_str_err = "TRACE_ERR";
-const char * const mi_lttng_loglevel_str_info = "TRACE_INFO";
-const char * const mi_lttng_loglevel_str_notice = "TRACE_NOTICE";
-const char * const mi_lttng_loglevel_str_unknown = "UNKNOWN";
-const char * const mi_lttng_loglevel_str_warning = "TRACE_WARNING";
+const char *const mi_lttng_loglevel_str_alert = "TRACE_ALERT";
+const char *const mi_lttng_loglevel_str_crit = "TRACE_CRIT";
+const char *const mi_lttng_loglevel_str_debug = "TRACE_DEBUG";
+const char *const mi_lttng_loglevel_str_debug_function = "TRACE_DEBUG_FUNCTION";
+const char *const mi_lttng_loglevel_str_debug_line = "TRACE_DEBUG_LINE";
+const char *const mi_lttng_loglevel_str_debug_module = "TRACE_DEBUG_MODULE";
+const char *const mi_lttng_loglevel_str_debug_process = "TRACE_DEBUG_PROCESS";
+const char *const mi_lttng_loglevel_str_debug_program = "TRACE_DEBUG_PROGRAM";
+const char *const mi_lttng_loglevel_str_debug_system = "TRACE_DEBUG_SYSTEM";
+const char *const mi_lttng_loglevel_str_debug_unit = "TRACE_DEBUG_UNIT";
+const char *const mi_lttng_loglevel_str_emerg = "TRACE_EMERG";
+const char *const mi_lttng_loglevel_str_err = "TRACE_ERR";
+const char *const mi_lttng_loglevel_str_info = "TRACE_INFO";
+const char *const mi_lttng_loglevel_str_notice = "TRACE_NOTICE";
+const char *const mi_lttng_loglevel_str_unknown = "UNKNOWN";
+const char *const mi_lttng_loglevel_str_warning = "TRACE_WARNING";
 
 /* String related to loglevel JUL */
-const char * const mi_lttng_loglevel_str_jul_all = "JUL_ALL";
-const char * const mi_lttng_loglevel_str_jul_config = "JUL_CONFIG";
-const char * const mi_lttng_loglevel_str_jul_fine = "JUL_FINE";
-const char * const mi_lttng_loglevel_str_jul_finer = "JUL_FINER";
-const char * const mi_lttng_loglevel_str_jul_finest = "JUL_FINEST";
-const char * const mi_lttng_loglevel_str_jul_info = "JUL_INFO";
-const char * const mi_lttng_loglevel_str_jul_off = "JUL_OFF";
-const char * const mi_lttng_loglevel_str_jul_severe = "JUL_SEVERE";
-const char * const mi_lttng_loglevel_str_jul_warning = "JUL_WARNING";
+const char *const mi_lttng_loglevel_str_jul_all = "JUL_ALL";
+const char *const mi_lttng_loglevel_str_jul_config = "JUL_CONFIG";
+const char *const mi_lttng_loglevel_str_jul_fine = "JUL_FINE";
+const char *const mi_lttng_loglevel_str_jul_finer = "JUL_FINER";
+const char *const mi_lttng_loglevel_str_jul_finest = "JUL_FINEST";
+const char *const mi_lttng_loglevel_str_jul_info = "JUL_INFO";
+const char *const mi_lttng_loglevel_str_jul_off = "JUL_OFF";
+const char *const mi_lttng_loglevel_str_jul_severe = "JUL_SEVERE";
+const char *const mi_lttng_loglevel_str_jul_warning = "JUL_WARNING";
 
 /* String related to loglevel LOG4J */
-const char * const mi_lttng_loglevel_str_log4j_off = "LOG4J_OFF";
-const char * const mi_lttng_loglevel_str_log4j_fatal = "LOG4J_FATAL";
-const char * const mi_lttng_loglevel_str_log4j_error = "LOG4J_ERROR";
-const char * const mi_lttng_loglevel_str_log4j_warn = "LOG4J_WARN";
-const char * const mi_lttng_loglevel_str_log4j_info = "LOG4J_INFO";
-const char * const mi_lttng_loglevel_str_log4j_debug = "LOG4J_DEBUG";
-const char * const mi_lttng_loglevel_str_log4j_trace = "LOG4J_TRACE";
-const char * const mi_lttng_loglevel_str_log4j_all = "LOG4J_ALL";
+const char *const mi_lttng_loglevel_str_log4j_off = "LOG4J_OFF";
+const char *const mi_lttng_loglevel_str_log4j_fatal = "LOG4J_FATAL";
+const char *const mi_lttng_loglevel_str_log4j_error = "LOG4J_ERROR";
+const char *const mi_lttng_loglevel_str_log4j_warn = "LOG4J_WARN";
+const char *const mi_lttng_loglevel_str_log4j_info = "LOG4J_INFO";
+const char *const mi_lttng_loglevel_str_log4j_debug = "LOG4J_DEBUG";
+const char *const mi_lttng_loglevel_str_log4j_trace = "LOG4J_TRACE";
+const char *const mi_lttng_loglevel_str_log4j_all = "LOG4J_ALL";
 
 /* String related to loglevel Python */
-const char * const mi_lttng_loglevel_str_python_critical = "PYTHON_CRITICAL";
-const char * const mi_lttng_loglevel_str_python_error = "PYTHON_ERROR";
-const char * const mi_lttng_loglevel_str_python_warning = "PYTHON_WARNING";
-const char * const mi_lttng_loglevel_str_python_info = "PYTHON_INFO";
-const char * const mi_lttng_loglevel_str_python_debug = "PYTHON_DEBUG";
-const char * const mi_lttng_loglevel_str_python_notset = "PYTHON_NOTSET";
+const char *const mi_lttng_loglevel_str_python_critical = "PYTHON_CRITICAL";
+const char *const mi_lttng_loglevel_str_python_error = "PYTHON_ERROR";
+const char *const mi_lttng_loglevel_str_python_warning = "PYTHON_WARNING";
+const char *const mi_lttng_loglevel_str_python_info = "PYTHON_INFO";
+const char *const mi_lttng_loglevel_str_python_debug = "PYTHON_DEBUG";
+const char *const mi_lttng_loglevel_str_python_notset = "PYTHON_NOTSET";
 
 /* String related to loglevel type */
-const char * const mi_lttng_loglevel_type_all = "ALL";
-const char * const mi_lttng_loglevel_type_range = "RANGE";
-const char * const mi_lttng_loglevel_type_single = "SINGLE";
-const char * const mi_lttng_loglevel_type_unknown = "UNKNOWN";
+const char *const mi_lttng_loglevel_type_all = "ALL";
+const char *const mi_lttng_loglevel_type_range = "RANGE";
+const char *const mi_lttng_loglevel_type_single = "SINGLE";
+const char *const mi_lttng_loglevel_type_unknown = "UNKNOWN";
 
 /* String related to a lttng_snapshot_output */
-const char * const mi_lttng_element_snapshot_ctrl_url = "ctrl_url";
-const char * const mi_lttng_element_snapshot_data_url = "data_url";
-const char * const mi_lttng_element_snapshot_max_size = "max_size";
-const char * const mi_lttng_element_snapshot_n_ptr = "n_ptr";
-const char * const mi_lttng_element_snapshot_session_name = "session_name";
-const char * const mi_lttng_element_snapshots = "snapshots";
+const char *const mi_lttng_element_snapshot_ctrl_url = "ctrl_url";
+const char *const mi_lttng_element_snapshot_data_url = "data_url";
+const char *const mi_lttng_element_snapshot_max_size = "max_size";
+const char *const mi_lttng_element_snapshot_n_ptr = "n_ptr";
+const char *const mi_lttng_element_snapshot_session_name = "session_name";
+const char *const mi_lttng_element_snapshots = "snapshots";
 
 /* String related to track/untrack command */
-const char * const mi_lttng_element_track_untrack_all_wildcard = "*";
+const char *const mi_lttng_element_track_untrack_all_wildcard = "*";
 
-const char * const mi_lttng_element_session_name = "session_name";
+const char *const mi_lttng_element_session_name = "session_name";
 
 /* String related to rotate command */
-const char * const mi_lttng_element_rotation = "rotation";
-const char * const mi_lttng_element_rotate_status = "status";
-const char * const mi_lttng_element_rotation_schedule = "rotation_schedule";
-const char * const mi_lttng_element_rotation_schedules = "rotation_schedules";
-const char * const mi_lttng_element_rotation_schedule_result = "rotation_schedule_result";
-const char * const mi_lttng_element_rotation_schedule_results = "rotation_schedule_results";
-const char * const mi_lttng_element_rotation_schedule_periodic = "periodic";
-const char * const mi_lttng_element_rotation_schedule_periodic_time_us = "time_us";
-const char * const mi_lttng_element_rotation_schedule_size_threshold = "size_threshold";
-const char * const mi_lttng_element_rotation_schedule_size_threshold_bytes = "bytes";
-const char * const mi_lttng_element_rotation_state = "state";
-const char * const mi_lttng_element_rotation_location = "location";
-const char * const mi_lttng_element_rotation_location_local = "local";
-const char * const mi_lttng_element_rotation_location_local_absolute_path = "absolute_path";
-const char * const mi_lttng_element_rotation_location_relay = "relay";
-const char * const mi_lttng_element_rotation_location_relay_host = "host";
-const char * const mi_lttng_element_rotation_location_relay_control_port = "control_port";
-const char * const mi_lttng_element_rotation_location_relay_data_port = "data_port";
-const char * const mi_lttng_element_rotation_location_relay_protocol = "protocol";
-const char * const mi_lttng_element_rotation_location_relay_relative_path = "relative_path";
+const char *const mi_lttng_element_rotation = "rotation";
+const char *const mi_lttng_element_rotate_status = "status";
+const char *const mi_lttng_element_rotation_schedule = "rotation_schedule";
+const char *const mi_lttng_element_rotation_schedules = "rotation_schedules";
+const char *const mi_lttng_element_rotation_schedule_result = "rotation_schedule_result";
+const char *const mi_lttng_element_rotation_schedule_results = "rotation_schedule_results";
+const char *const mi_lttng_element_rotation_schedule_periodic = "periodic";
+const char *const mi_lttng_element_rotation_schedule_periodic_time_us = "time_us";
+const char *const mi_lttng_element_rotation_schedule_size_threshold = "size_threshold";
+const char *const mi_lttng_element_rotation_schedule_size_threshold_bytes = "bytes";
+const char *const mi_lttng_element_rotation_state = "state";
+const char *const mi_lttng_element_rotation_location = "location";
+const char *const mi_lttng_element_rotation_location_local = "local";
+const char *const mi_lttng_element_rotation_location_local_absolute_path = "absolute_path";
+const char *const mi_lttng_element_rotation_location_relay = "relay";
+const char *const mi_lttng_element_rotation_location_relay_host = "host";
+const char *const mi_lttng_element_rotation_location_relay_control_port = "control_port";
+const char *const mi_lttng_element_rotation_location_relay_data_port = "data_port";
+const char *const mi_lttng_element_rotation_location_relay_protocol = "protocol";
+const char *const mi_lttng_element_rotation_location_relay_relative_path = "relative_path";
 
 /* String related to enum lttng_rotation_state */
-const char * const mi_lttng_rotation_state_str_ongoing = "ONGOING";
-const char * const mi_lttng_rotation_state_str_completed = "COMPLETED";
-const char * const mi_lttng_rotation_state_str_expired = "EXPIRED";
-const char * const mi_lttng_rotation_state_str_error = "ERROR";
+const char *const mi_lttng_rotation_state_str_ongoing = "ONGOING";
+const char *const mi_lttng_rotation_state_str_completed = "COMPLETED";
+const char *const mi_lttng_rotation_state_str_expired = "EXPIRED";
+const char *const mi_lttng_rotation_state_str_error = "ERROR";
 
 /* String related to enum lttng_trace_archive_location_relay_protocol_type */
-const char * const mi_lttng_rotation_location_relay_protocol_str_tcp = "TCP";
+const char *const mi_lttng_rotation_location_relay_protocol_str_tcp = "TCP";
 
 /* String related to rate_policy elements */
 const char *const mi_lttng_element_rate_policy = "rate_policy";
-const char *const mi_lttng_element_rate_policy_every_n =
-               "rate_policy_every_n";
-const char *const mi_lttng_element_rate_policy_once_after_n =
-               "rate_policy_once_after_n";
+const char *const mi_lttng_element_rate_policy_every_n = "rate_policy_every_n";
+const char *const mi_lttng_element_rate_policy_once_after_n = "rate_policy_once_after_n";
 
-const char *const mi_lttng_element_rate_policy_every_n_interval =
-               "interval";
-const char
-               *const mi_lttng_element_rate_policy_once_after_n_threshold =
-                               "threshold";
+const char *const mi_lttng_element_rate_policy_every_n_interval = "interval";
+const char *const mi_lttng_element_rate_policy_once_after_n_threshold = "threshold";
 
 /* String related to action elements */
 const char *const mi_lttng_element_action = "action";
 const char *const mi_lttng_element_action_list = "action_list";
 const char *const mi_lttng_element_action_notify = "action_notify";
-const char *const mi_lttng_element_action_start_session =
-               "action_start_session";
-const char *const mi_lttng_element_action_stop_session =
-               "action_stop_session";
-const char *const mi_lttng_element_action_rotate_session =
-               "action_rotate_session";
-const char *const mi_lttng_element_action_snapshot_session =
-               "action_snapshot_session";
-const char *const mi_lttng_element_action_snapshot_session_output =
-               "output";
+const char *const mi_lttng_element_action_start_session = "action_start_session";
+const char *const mi_lttng_element_action_stop_session = "action_stop_session";
+const char *const mi_lttng_element_action_rotate_session = "action_rotate_session";
+const char *const mi_lttng_element_action_snapshot_session = "action_snapshot_session";
+const char *const mi_lttng_element_action_snapshot_session_output = "output";
 
 /* String related to condition */
 const char *const mi_lttng_element_condition = "condition";
-const char *const mi_lttng_element_condition_buffer_usage_high =
-               "condition_buffer_usage_high";
-const char *const mi_lttng_element_condition_buffer_usage_low =
-               "condition_buffer_usage_low";
-const char *const mi_lttng_element_condition_event_rule_matches =
-               "condition_event_rule_matches";
+const char *const mi_lttng_element_condition_buffer_usage_high = "condition_buffer_usage_high";
+const char *const mi_lttng_element_condition_buffer_usage_low = "condition_buffer_usage_low";
+const char *const mi_lttng_element_condition_event_rule_matches = "condition_event_rule_matches";
 const char *const mi_lttng_element_condition_session_consumed_size =
-               "condition_session_consumed_size";
-const char *const mi_lttng_element_condition_session_rotation =
-               "condition_session_rotation";
-const char
-               *const mi_lttng_element_condition_session_rotation_completed =
-                               "condition_session_rotation_completed";
-const char
-               *const mi_lttng_element_condition_session_rotation_ongoing =
-                               "condition_session_rotation_ongoing";
-
-const char *const mi_lttng_element_condition_channel_name =
-               "channel_name";
-const char *const mi_lttng_element_condition_threshold_bytes =
-               "threshold_bytes";
-const char *const mi_lttng_element_condition_threshold_ratio =
-               "threshold_ratio";
+       "condition_session_consumed_size";
+const char *const mi_lttng_element_condition_session_rotation = "condition_session_rotation";
+const char *const mi_lttng_element_condition_session_rotation_completed =
+       "condition_session_rotation_completed";
+const char *const mi_lttng_element_condition_session_rotation_ongoing =
+       "condition_session_rotation_ongoing";
+
+const char *const mi_lttng_element_condition_channel_name = "channel_name";
+const char *const mi_lttng_element_condition_threshold_bytes = "threshold_bytes";
+const char *const mi_lttng_element_condition_threshold_ratio = "threshold_ratio";
 
 /* String related to capture descriptor */
-const char *const mi_lttng_element_capture_descriptor =
-               "capture_descriptor";
-const char *const mi_lttng_element_capture_descriptors =
-               "capture_descriptors";
+const char *const mi_lttng_element_capture_descriptor = "capture_descriptor";
+const char *const mi_lttng_element_capture_descriptors = "capture_descriptors";
 
 /* String related to event expression */
 const char *const mi_lttng_element_event_expr = "event_expr";
-const char *const mi_lttng_element_event_expr_payload_field =
-               "event_expr_payload_field";
+const char *const mi_lttng_element_event_expr_payload_field = "event_expr_payload_field";
 const char *const mi_lttng_element_event_expr_channel_context_field =
-               "event_expr_channel_context_field";
-const char
-               *const mi_lttng_element_event_expr_app_specific_context_field =
-                               "event_expr_app_specific_context_field";
+       "event_expr_channel_context_field";
+const char *const mi_lttng_element_event_expr_app_specific_context_field =
+       "event_expr_app_specific_context_field";
 const char *const mi_lttng_element_event_expr_array_field_element =
-               "event_expr_array_field_element";
-const char *const mi_lttng_element_event_expr_provider_name =
-               "provider_name";
-const char *const mi_lttng_element_event_expr_type_name =
-               "type_name";
+       "event_expr_array_field_element";
+const char *const mi_lttng_element_event_expr_provider_name = "provider_name";
+const char *const mi_lttng_element_event_expr_type_name = "type_name";
 const char *const mi_lttng_element_event_expr_index = "index";
 
 /* String related to event rule */
 const char *const mi_lttng_element_event_rule = "event_rule";
 
 /* String related to lttng_event_rule_type */
-const char *const mi_lttng_element_event_rule_event_name =
-               "event_name";
-const char *const mi_lttng_element_event_rule_name_pattern =
-               "name_pattern";
-const char *const mi_lttng_element_event_rule_filter_expression =
-               "filter_expression";
-
-const char *const mi_lttng_element_event_rule_jul_logging =
-               "event_rule_jul_logging";
-const char *const mi_lttng_element_event_rule_kernel_kprobe =
-               "event_rule_kernel_kprobe";
-const char *const mi_lttng_element_event_rule_kernel_syscall =
-               "event_rule_kernel_syscall";
-const char *const mi_lttng_element_event_rule_kernel_tracepoint =
-               "event_rule_kernel_tracepoint";
-const char *const mi_lttng_element_event_rule_kernel_uprobe =
-               "event_rule_kernel_uprobe";
-const char *const mi_lttng_element_event_rule_log4j_logging =
-               "event_rule_log4j_logging";
-const char *const mi_lttng_element_event_rule_python_logging =
-               "event_rule_python_logging";
-const char *const mi_lttng_element_event_rule_user_tracepoint =
-               "event_rule_user_tracepoint";
+const char *const mi_lttng_element_event_rule_event_name = "event_name";
+const char *const mi_lttng_element_event_rule_name_pattern = "name_pattern";
+const char *const mi_lttng_element_event_rule_filter_expression = "filter_expression";
+
+const char *const mi_lttng_element_event_rule_jul_logging = "event_rule_jul_logging";
+const char *const mi_lttng_element_event_rule_kernel_kprobe = "event_rule_kernel_kprobe";
+const char *const mi_lttng_element_event_rule_kernel_syscall = "event_rule_kernel_syscall";
+const char *const mi_lttng_element_event_rule_kernel_tracepoint = "event_rule_kernel_tracepoint";
+const char *const mi_lttng_element_event_rule_kernel_uprobe = "event_rule_kernel_uprobe";
+const char *const mi_lttng_element_event_rule_log4j_logging = "event_rule_log4j_logging";
+const char *const mi_lttng_element_event_rule_python_logging = "event_rule_python_logging";
+const char *const mi_lttng_element_event_rule_user_tracepoint = "event_rule_user_tracepoint";
 
 /* String related to lttng_event_rule_kernel_syscall. */
-const char *const
-               mi_lttng_element_event_rule_kernel_syscall_emission_site =
-                               "emission_site";
+const char *const mi_lttng_element_event_rule_kernel_syscall_emission_site = "emission_site";
 
 /* String related to enum lttng_event_rule_kernel_syscall_emission_site. */
-const char *const
-               mi_lttng_event_rule_kernel_syscall_emission_site_entry_exit =
-                               "entry+exit";
-const char
-               *const mi_lttng_event_rule_kernel_syscall_emission_site_entry =
-                               "entry";
-const char *const
-               mi_lttng_event_rule_kernel_syscall_emission_site_exit = "exit";
+const char *const mi_lttng_event_rule_kernel_syscall_emission_site_entry_exit = "entry+exit";
+const char *const mi_lttng_event_rule_kernel_syscall_emission_site_entry = "entry";
+const char *const mi_lttng_event_rule_kernel_syscall_emission_site_exit = "exit";
 
 /* String related to lttng_event_rule_user_tracepoint */
-const char *const
-               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions =
-                               "name_pattern_exclusions";
-const char *const
-               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion =
-                               "name_pattern_exclusion";
+const char *const mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions =
+       "name_pattern_exclusions";
+const char *const mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion =
+       "name_pattern_exclusion";
 
 /* String related to log level rule. */
-const char *const mi_lttng_element_log_level_rule =
-               "log_level_rule";
-const char *const mi_lttng_element_log_level_rule_exactly =
-               "log_level_rule_exactly";
-const char
-               *const mi_lttng_element_log_level_rule_at_least_as_severe_as =
-                               "log_level_rule_at_least_as_severe_as";
+const char *const mi_lttng_element_log_level_rule = "log_level_rule";
+const char *const mi_lttng_element_log_level_rule_exactly = "log_level_rule_exactly";
+const char *const mi_lttng_element_log_level_rule_at_least_as_severe_as =
+       "log_level_rule_at_least_as_severe_as";
 const char *const mi_lttng_element_log_level_rule_level = "level";
 
 /* String related to kernel probe location. */
-const char *const mi_lttng_element_kernel_probe_location =
-               "kernel_probe_location";
-const char
-               *const mi_lttng_element_kernel_probe_location_symbol_offset =
-                               "kernel_probe_location_symbol_offset";
-const char *const
-               mi_lttng_element_kernel_probe_location_symbol_offset_name =
-                               "name";
-const char *const
-               mi_lttng_element_kernel_probe_location_symbol_offset_offset =
-                               "offset";
-
-const char *const mi_lttng_element_kernel_probe_location_address =
-               "kernel_probe_location_address";
-const char
-               *const mi_lttng_element_kernel_probe_location_address_address =
-                               "address";
+const char *const mi_lttng_element_kernel_probe_location = "kernel_probe_location";
+const char *const mi_lttng_element_kernel_probe_location_symbol_offset =
+       "kernel_probe_location_symbol_offset";
+const char *const mi_lttng_element_kernel_probe_location_symbol_offset_name = "name";
+const char *const mi_lttng_element_kernel_probe_location_symbol_offset_offset = "offset";
+
+const char *const mi_lttng_element_kernel_probe_location_address = "kernel_probe_location_address";
+const char *const mi_lttng_element_kernel_probe_location_address_address = "address";
 
 /* String related to userspace probe location. */
-const char *const mi_lttng_element_userspace_probe_location =
-               "userspace_probe_location";
-const char
-               *const mi_lttng_element_userspace_probe_location_binary_path =
-                               "binary_path";
-const char
-               *const mi_lttng_element_userspace_probe_location_function =
-                               "userspace_probe_location_function";
-const char
-               *const mi_lttng_element_userspace_probe_location_function_name =
-                               "name";
-const char
-               *const mi_lttng_element_userspace_probe_location_lookup_method =
-                               "userspace_probe_location_lookup_method";
-const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_function_default =
-                               "userspace_probe_location_lookup_method_function_default";
-const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_function_elf =
-                               "userspace_probe_location_lookup_method_function_elf";
-const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt =
-                               "userspace_probe_location_lookup_method_tracepoint_sdt";
-const char
-               *const mi_lttng_element_userspace_probe_location_tracepoint =
-                               "userspace_probe_location_tracepoint";
-const char *const
-               mi_lttng_element_userspace_probe_location_tracepoint_probe_name =
-                               "probe_name";
-const char *const
-               mi_lttng_element_userspace_probe_location_tracepoint_provider_name =
-                               "provider_name";
+const char *const mi_lttng_element_userspace_probe_location = "userspace_probe_location";
+const char *const mi_lttng_element_userspace_probe_location_binary_path = "binary_path";
+const char *const mi_lttng_element_userspace_probe_location_function =
+       "userspace_probe_location_function";
+const char *const mi_lttng_element_userspace_probe_location_function_name = "name";
+const char *const mi_lttng_element_userspace_probe_location_lookup_method =
+       "userspace_probe_location_lookup_method";
+const char *const mi_lttng_element_userspace_probe_location_lookup_method_function_default =
+       "userspace_probe_location_lookup_method_function_default";
+const char *const mi_lttng_element_userspace_probe_location_lookup_method_function_elf =
+       "userspace_probe_location_lookup_method_function_elf";
+const char *const mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt =
+       "userspace_probe_location_lookup_method_tracepoint_sdt";
+const char *const mi_lttng_element_userspace_probe_location_tracepoint =
+       "userspace_probe_location_tracepoint";
+const char *const mi_lttng_element_userspace_probe_location_tracepoint_probe_name = "probe_name";
+const char *const mi_lttng_element_userspace_probe_location_tracepoint_provider_name =
+       "provider_name";
 
 /* String related to enum
  * lttng_userspace_probe_location_function_instrumentation_type */
-const char *const
-               mi_lttng_element_userspace_probe_location_function_instrumentation_type =
-                               "instrumentation_type";
-const char *const
-               mi_lttng_userspace_probe_location_function_instrumentation_type_entry =
-                               "ENTRY";
+const char *const mi_lttng_element_userspace_probe_location_function_instrumentation_type =
+       "instrumentation_type";
+const char *const mi_lttng_userspace_probe_location_function_instrumentation_type_entry = "ENTRY";
 
 /* String related to trigger */
 const char *const mi_lttng_element_triggers = "triggers";
@@ -415,23 +341,16 @@ const char *const mi_lttng_element_trigger = "trigger";
 const char *const mi_lttng_element_trigger_owner_uid = "owner_uid";
 
 /* String related to error_query. */
-const char *const mi_lttng_element_error_query_result =
-               "error_query_result";
-const char *const mi_lttng_element_error_query_result_counter =
-               "error_query_result_counter";
-const char *const
-               mi_lttng_element_error_query_result_counter_value = "value";
-const char *const mi_lttng_element_error_query_result_description =
-               "description";
-const char *const mi_lttng_element_error_query_result_name =
-               "name";
-const char *const mi_lttng_element_error_query_result_type =
-               "type";
-const char *const mi_lttng_element_error_query_results =
-               "error_query_results";
+const char *const mi_lttng_element_error_query_result = "error_query_result";
+const char *const mi_lttng_element_error_query_result_counter = "error_query_result_counter";
+const char *const mi_lttng_element_error_query_result_counter_value = "value";
+const char *const mi_lttng_element_error_query_result_description = "description";
+const char *const mi_lttng_element_error_query_result_name = "name";
+const char *const mi_lttng_element_error_query_result_type = "type";
+const char *const mi_lttng_element_error_query_results = "error_query_results";
 
 /* String related to add-context command */
-const char * const mi_lttng_element_context_symbol = "symbol";
+const char *const mi_lttng_element_context_symbol = "symbol";
 
 /* Deprecated symbols preserved for ABI compatibility. */
 LTTNG_EXPORT const char *mi_lttng_context_type_perf_counter;
@@ -576,8 +495,7 @@ const char *mi_lttng_logleveltype_string(enum lttng_loglevel_type value)
        }
 }
 
-static
-const char *mi_lttng_eventtype_string(enum lttng_event_type value)
+static const char *mi_lttng_eventtype_string(enum lttng_event_type value)
 {
        switch (value) {
        case LTTNG_EVENT_ALL:
@@ -601,8 +519,7 @@ const char *mi_lttng_eventtype_string(enum lttng_event_type value)
        }
 }
 
-static
-const char *mi_lttng_event_contexttype_string(enum lttng_event_context_type val)
+static const char *mi_lttng_event_contexttype_string(enum lttng_event_context_type val)
 {
        switch (val) {
        case LTTNG_EVENT_CONTEXT_PID:
@@ -682,20 +599,20 @@ const char *mi_lttng_event_contexttype_string(enum lttng_event_context_type val)
        case LTTNG_EVENT_CONTEXT_VSGID:
                return config_event_context_vsgid;
        default:
-               return NULL;
+               return nullptr;
        }
 }
 
 const char *mi_lttng_eventfieldtype_string(enum lttng_event_field_type val)
 {
        switch (val) {
-       case(LTTNG_EVENT_FIELD_INTEGER):
+       case (LTTNG_EVENT_FIELD_INTEGER):
                return mi_lttng_element_type_integer;
-       case(LTTNG_EVENT_FIELD_ENUM):
+       case (LTTNG_EVENT_FIELD_ENUM):
                return mi_lttng_element_type_enum;
-       case(LTTNG_EVENT_FIELD_FLOAT):
+       case (LTTNG_EVENT_FIELD_FLOAT):
                return mi_lttng_element_type_float;
-       case(LTTNG_EVENT_FIELD_STRING):
+       case (LTTNG_EVENT_FIELD_STRING):
                return mi_lttng_element_type_string;
        default:
                return mi_lttng_element_type_other;
@@ -718,7 +635,7 @@ const char *mi_lttng_domaintype_string(enum lttng_domain_type value)
        default:
                /* Should not have an unknown domain */
                abort();
-               return NULL;
+               return nullptr;
        }
 }
 
@@ -734,7 +651,7 @@ const char *mi_lttng_buffertype_string(enum lttng_buffer_type value)
        default:
                /* Should not have an unknow buffer type */
                abort();
-               return NULL;
+               return nullptr;
        }
 }
 
@@ -752,12 +669,12 @@ const char *mi_lttng_rotation_state_string(enum lttng_rotation_state value)
        default:
                /* Should not have an unknow rotation state. */
                abort();
-               return NULL;
+               return nullptr;
        }
 }
 
 const char *mi_lttng_trace_archive_location_relay_protocol_type_string(
-               enum lttng_trace_archive_location_relay_protocol_type value)
+       enum lttng_trace_archive_location_relay_protocol_type value)
 {
        switch (value) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_RELAY_PROTOCOL_TYPE_TCP:
@@ -765,7 +682,7 @@ const char *mi_lttng_trace_archive_location_relay_protocol_type_string(
        default:
                /* Should not have an unknown relay protocol. */
                abort();
-               return NULL;
+               return nullptr;
        }
 }
 
@@ -793,7 +710,7 @@ end:
 
 err_destroy:
        free(mi_writer);
-       return NULL;
+       return nullptr;
 }
 
 int mi_lttng_writer_destroy(struct mi_writer *writer)
@@ -823,40 +740,36 @@ int mi_lttng_writer_command_open(struct mi_writer *writer, const char *command)
         * A command is always the MI's root node, it must declare the current
         * namespace and schema URIs and the schema's version.
         */
-       ret = config_writer_open_element(writer->writer,
-                       mi_lttng_element_command);
+       ret = config_writer_open_element(writer->writer, mi_lttng_element_command);
        if (ret) {
                goto end;
        }
 
-       ret = config_writer_write_attribute(writer->writer,
-                       mi_lttng_xmlns, DEFAULT_LTTNG_MI_NAMESPACE);
+       ret = config_writer_write_attribute(
+               writer->writer, mi_lttng_xmlns, DEFAULT_LTTNG_MI_NAMESPACE);
        if (ret) {
                goto end;
        }
 
-       ret = config_writer_write_attribute(writer->writer,
-                       mi_lttng_xmlns_xsi, mi_lttng_w3_schema_uri);
+       ret = config_writer_write_attribute(
+               writer->writer, mi_lttng_xmlns_xsi, mi_lttng_w3_schema_uri);
        if (ret) {
                goto end;
        }
 
-       ret = config_writer_write_attribute(writer->writer,
-                       mi_lttng_schema_location,
-                       mi_lttng_schema_location_uri);
+       ret = config_writer_write_attribute(
+               writer->writer, mi_lttng_schema_location, mi_lttng_schema_location_uri);
        if (ret) {
                goto end;
        }
 
-       ret = config_writer_write_attribute(writer->writer,
-                       mi_lttng_schema_version,
-                       mi_lttng_schema_version_value);
+       ret = config_writer_write_attribute(
+               writer->writer, mi_lttng_schema_version, mi_lttng_schema_version_value);
        if (ret) {
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_command_name, command);
+       ret = mi_lttng_writer_write_element_string(writer, mi_lttng_element_command_name, command);
 end:
        return ret;
 }
@@ -866,8 +779,7 @@ int mi_lttng_writer_command_close(struct mi_writer *writer)
        return mi_lttng_writer_close_element(writer);
 }
 
-int mi_lttng_writer_open_element(struct mi_writer *writer,
-               const char *element_name)
+int mi_lttng_writer_open_element(struct mi_writer *writer, const char *element_name)
 {
        return config_writer_open_element(writer->writer, element_name);
 }
@@ -877,8 +789,7 @@ int mi_lttng_writer_close_element(struct mi_writer *writer)
        return config_writer_close_element(writer->writer);
 }
 
-int mi_lttng_close_multi_element(struct mi_writer *writer,
-               unsigned int nb_element)
+int mi_lttng_close_multi_element(struct mi_writer *writer, unsigned int nb_element)
 {
        int ret, i;
 
@@ -897,43 +808,44 @@ end:
 }
 
 int mi_lttng_writer_write_element_unsigned_int(struct mi_writer *writer,
-               const char *element_name, uint64_t value)
+                                              const char *element_name,
+                                              uint64_t value)
 {
-       return config_writer_write_element_unsigned_int(writer->writer,
-                       element_name, value);
+       return config_writer_write_element_unsigned_int(writer->writer, element_name, value);
 }
 
 int mi_lttng_writer_write_element_signed_int(struct mi_writer *writer,
-               const char *element_name, int64_t value)
+                                            const char *element_name,
+                                            int64_t value)
 {
-       return config_writer_write_element_signed_int(writer->writer,
-                       element_name, value);
+       return config_writer_write_element_signed_int(writer->writer, element_name, value);
 }
 
 int mi_lttng_writer_write_element_bool(struct mi_writer *writer,
-               const char *element_name, int value)
+                                      const char *element_name,
+                                      int value)
 {
-       return config_writer_write_element_bool(writer->writer,
-                       element_name, value);
+       return config_writer_write_element_bool(writer->writer, element_name, value);
 }
 
 int mi_lttng_writer_write_element_string(struct mi_writer *writer,
-               const char *element_name, const char *value)
+                                        const char *element_name,
+                                        const char *value)
 {
-       return config_writer_write_element_string(writer->writer,
-                       element_name, value);
+       return config_writer_write_element_string(writer->writer, element_name, value);
 }
 
 int mi_lttng_writer_write_element_double(struct mi_writer *writer,
-               const char *element_name,
-               double value)
+                                        const char *element_name,
+                                        double value)
 {
-       return config_writer_write_element_double(
-                       writer->writer, element_name, value);
+       return config_writer_write_element_double(writer->writer, element_name, value);
 }
 
-int mi_lttng_version(struct mi_writer *writer, struct mi_lttng_version_data *version,
-       const char *lttng_description, const char *lttng_license)
+int mi_lttng_version(struct mi_writer *writer,
+                    struct mi_lttng_version_data *version,
+                    const char *lttng_description,
+                    const char *lttng_license)
 {
        int ret;
 
@@ -944,64 +856,64 @@ int mi_lttng_version(struct mi_writer *writer, struct mi_lttng_version_data *ver
        }
 
        /* Version string (contain info like rc etc.) */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_version_str, version->version);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_version_str, version->version);
        if (ret) {
                goto end;
        }
 
        /* Major version number */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_version_major, version->version_major);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_version_major, version->version_major);
        if (ret) {
                goto end;
        }
 
        /* Minor version number */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_version_minor, version->version_minor);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_version_minor, version->version_minor);
        if (ret) {
                goto end;
        }
 
        /* Commit version number */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_version_commit, version->version_commit);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_version_commit, version->version_commit);
        if (ret) {
                goto end;
        }
 
        /* Patch number */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_version_patch_level, version->version_patchlevel);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_version_patch_level, version->version_patchlevel);
        if (ret) {
                goto end;
        }
 
        /* Name of the version */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, version->version_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_name, version->version_name);
        if (ret) {
                goto end;
        }
 
        /* Description mostly related to beer... */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_version_description, lttng_description);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_version_description, lttng_description);
        if (ret) {
                goto end;
        }
 
        /* url */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_version_web, version->package_url);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_version_web, version->package_url);
        if (ret) {
                goto end;
        }
 
        /* License: free as in free beer...no...*speech* */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_version_license, lttng_license);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_version_license, lttng_license);
        if (ret) {
                goto end;
        }
@@ -1018,52 +930,46 @@ int mi_lttng_sessions_open(struct mi_writer *writer)
        return mi_lttng_writer_open_element(writer, config_element_sessions);
 }
 
-int mi_lttng_session(struct mi_writer *writer,
-               struct lttng_session *session, int is_open)
+int mi_lttng_session(struct mi_writer *writer, const struct lttng_session *session, int is_open)
 {
        int ret;
 
        LTTNG_ASSERT(session);
 
        /* Open sessions element */
-       ret = mi_lttng_writer_open_element(writer,
-                       config_element_session);
+       ret = mi_lttng_writer_open_element(writer, config_element_session);
        if (ret) {
                goto end;
        }
 
        /* Name of the session */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, session->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session->name);
        if (ret) {
                goto end;
        }
 
        /* Path */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_path, session->path);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_path, session->path);
        if (ret) {
                goto end;
        }
 
        /* Enabled ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       config_element_enabled, session->enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, session->enabled);
        if (ret) {
                goto end;
        }
 
        /* Snapshot mode */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       config_element_snapshot_mode, session->snapshot_mode);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_snapshot_mode, session->snapshot_mode);
        if (ret) {
                goto end;
        }
 
        /* Live timer interval in usec */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       config_element_live_timer_interval,
-                       session->live_timer_interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_live_timer_interval, session->live_timer_interval);
        if (ret) {
                goto end;
        }
@@ -1074,7 +980,6 @@ int mi_lttng_session(struct mi_writer *writer,
        }
 end:
        return ret;
-
 }
 
 int mi_lttng_domains_open(struct mi_writer *writer)
@@ -1082,8 +987,7 @@ int mi_lttng_domains_open(struct mi_writer *writer)
        return mi_lttng_writer_open_element(writer, config_element_domains);
 }
 
-int mi_lttng_domain(struct mi_writer *writer,
-               struct lttng_domain *domain, int is_open)
+int mi_lttng_domain(struct mi_writer *writer, struct lttng_domain *domain, int is_open)
 {
        int ret = 0;
        const char *str_domain;
@@ -1099,16 +1003,14 @@ int mi_lttng_domain(struct mi_writer *writer,
 
        /* Domain Type */
        str_domain = mi_lttng_domaintype_string(domain->type);
-       ret = mi_lttng_writer_write_element_string(writer, config_element_type,
-                       str_domain);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_type, str_domain);
        if (ret) {
                goto end;
        }
 
        /* Buffer Type */
-       str_buffer= mi_lttng_buffertype_string(domain->buf_type);
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_buffer_type, str_buffer);
+       str_buffer = mi_lttng_buffertype_string(domain->buf_type);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_buffer_type, str_buffer);
        if (ret) {
                goto end;
        }
@@ -1126,7 +1028,6 @@ int mi_lttng_domain(struct mi_writer *writer,
 
 end:
        return ret;
-
 }
 
 int mi_lttng_channels_open(struct mi_writer *writer)
@@ -1134,8 +1035,7 @@ int mi_lttng_channels_open(struct mi_writer *writer)
        return mi_lttng_writer_open_element(writer, config_element_channels);
 }
 
-int mi_lttng_channel(struct mi_writer *writer,
-               struct lttng_channel *channel, int is_open)
+int mi_lttng_channel(struct mi_writer *writer, struct lttng_channel *channel, int is_open)
 {
        int ret = 0;
 
@@ -1148,15 +1048,13 @@ int mi_lttng_channel(struct mi_writer *writer,
        }
 
        /* Name */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       channel->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, channel->name);
        if (ret) {
                goto end;
        }
 
        /* Enabled ? */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       config_element_enabled, channel->enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, channel->enabled);
        if (ret) {
                goto end;
        }
@@ -1178,12 +1076,10 @@ end:
        return ret;
 }
 
-int mi_lttng_channel_attr(struct mi_writer *writer,
-               struct lttng_channel_attr *attr)
+int mi_lttng_channel_attr(struct mi_writer *writer, struct lttng_channel_attr *attr)
 {
        int ret = 0;
-       struct lttng_channel *chan = caa_container_of(attr,
-                       struct lttng_channel, attr);
+       struct lttng_channel *chan = caa_container_of(attr, struct lttng_channel, attr);
        uint64_t discarded_events, lost_packets, monitor_timer_interval;
        int64_t blocking_timeout;
 
@@ -1199,14 +1095,12 @@ int mi_lttng_channel_attr(struct mi_writer *writer,
                goto end;
        }
 
-       ret = lttng_channel_get_monitor_timer_interval(chan,
-                       &monitor_timer_interval);
+       ret = lttng_channel_get_monitor_timer_interval(chan, &monitor_timer_interval);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_channel_get_blocking_timeout(chan,
-                       &blocking_timeout);
+       ret = lttng_channel_get_blocking_timeout(chan, &blocking_timeout);
        if (ret) {
                goto end;
        }
@@ -1218,105 +1112,97 @@ int mi_lttng_channel_attr(struct mi_writer *writer,
        }
 
        /* Overwrite */
-       ret = mi_lttng_writer_write_element_string(writer,
+       ret = mi_lttng_writer_write_element_string(
+               writer,
                config_element_overwrite_mode,
-               attr->overwrite ? config_overwrite_mode_overwrite :
-                       config_overwrite_mode_discard);
+               attr->overwrite ? config_overwrite_mode_overwrite : config_overwrite_mode_discard);
        if (ret) {
                goto end;
        }
 
        /* Sub buffer size in byte */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_subbuf_size, attr->subbuf_size);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_subbuf_size, attr->subbuf_size);
        if (ret) {
                goto end;
        }
 
        /* Number of subbuffer (power of two) */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_num_subbuf,
-               attr->num_subbuf);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_num_subbuf, attr->num_subbuf);
        if (ret) {
                goto end;
        }
 
        /* Switch timer interval in usec */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_switch_timer_interval,
-               attr->switch_timer_interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_switch_timer_interval, attr->switch_timer_interval);
        if (ret) {
                goto end;
        }
 
        /* Read timer interval in usec */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_read_timer_interval,
-               attr->read_timer_interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_read_timer_interval, attr->read_timer_interval);
        if (ret) {
                goto end;
        }
 
        /* Monitor timer interval in usec */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_monitor_timer_interval,
-               monitor_timer_interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_monitor_timer_interval, monitor_timer_interval);
        if (ret) {
                goto end;
        }
 
        /* Retry timeout in usec */
-       ret = mi_lttng_writer_write_element_signed_int(writer,
-               config_element_blocking_timeout,
-               blocking_timeout);
+       ret = mi_lttng_writer_write_element_signed_int(
+               writer, config_element_blocking_timeout, blocking_timeout);
        if (ret) {
                goto end;
        }
 
        /* Event output */
        ret = mi_lttng_writer_write_element_string(writer,
-               config_element_output_type,
-               attr->output == LTTNG_EVENT_SPLICE ?
-               config_output_type_splice : config_output_type_mmap);
+                                                  config_element_output_type,
+                                                  attr->output == LTTNG_EVENT_SPLICE ?
+                                                          config_output_type_splice :
+                                                          config_output_type_mmap);
        if (ret) {
                goto end;
        }
 
        /* Tracefile size in bytes */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_size, attr->tracefile_size);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_size, attr->tracefile_size);
        if (ret) {
                goto end;
        }
 
        /* Count of tracefiles */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_tracefile_count,
-               attr->tracefile_count);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_tracefile_count, attr->tracefile_count);
        if (ret) {
                goto end;
        }
 
        /* Live timer interval in usec*/
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_live_timer_interval,
-               attr->live_timer_interval);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_live_timer_interval, attr->live_timer_interval);
        if (ret) {
                goto end;
        }
 
        /* Discarded events */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_discarded_events,
-               discarded_events);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_discarded_events, discarded_events);
        if (ret) {
                goto end;
        }
 
        /* Lost packets */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-               config_element_lost_packets,
-               lost_packets);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_lost_packets, lost_packets);
        if (ret) {
                goto end;
        }
@@ -1328,11 +1214,9 @@ int mi_lttng_channel_attr(struct mi_writer *writer,
        }
 end:
        return ret;
-
 }
 
-int mi_lttng_event_common_attributes(struct mi_writer *writer,
-               struct lttng_event *event)
+int mi_lttng_event_common_attributes(struct mi_writer *writer, struct lttng_event *event)
 {
        int ret;
        const char *filter_expression;
@@ -1344,22 +1228,20 @@ int mi_lttng_event_common_attributes(struct mi_writer *writer,
        }
 
        /* Event name */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, event->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, event->name);
        if (ret) {
                goto end;
        }
 
        /* Event type */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_type, mi_lttng_eventtype_string(event->type));
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_type, mi_lttng_eventtype_string(event->type));
        if (ret) {
                goto end;
        }
 
        /* Is event enabled */
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       config_element_enabled, event->enabled);
+       ret = mi_lttng_writer_write_element_bool(writer, config_element_enabled, event->enabled);
        if (ret) {
                goto end;
        }
@@ -1371,9 +1253,8 @@ int mi_lttng_event_common_attributes(struct mi_writer *writer,
        }
 
        if (filter_expression) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_filter_expression,
-                               filter_expression);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_filter_expression, filter_expression);
                if (ret) {
                        goto end;
                }
@@ -1383,8 +1264,7 @@ end:
        return ret;
 }
 
-static int write_event_exclusions(struct mi_writer *writer,
-               struct lttng_event *event)
+static int write_event_exclusions(struct mi_writer *writer, struct lttng_event *event)
 {
        int i;
        int ret;
@@ -1412,8 +1292,7 @@ static int write_event_exclusions(struct mi_writer *writer,
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_exclusion, name);
+               ret = mi_lttng_writer_write_element_string(writer, config_element_exclusion, name);
                if (ret) {
                        /* Close exclusions */
                        mi_lttng_writer_close_element(writer);
@@ -1429,22 +1308,23 @@ end:
 }
 
 int mi_lttng_event_tracepoint_loglevel(struct mi_writer *writer,
-               struct lttng_event *event, enum lttng_domain_type domain)
+                                      struct lttng_event *event,
+                                      enum lttng_domain_type domain)
 {
        int ret;
 
        /* Event loglevel */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_loglevel,
-                       mi_lttng_loglevel_string(event->loglevel, domain));
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_loglevel, mi_lttng_loglevel_string(event->loglevel, domain));
        if (ret) {
                goto end;
        }
 
        /* Log level type */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_loglevel_type,
-                       mi_lttng_logleveltype_string(event->loglevel_type));
+       ret = mi_lttng_writer_write_element_string(
+               writer,
+               config_element_loglevel_type,
+               mi_lttng_logleveltype_string(event->loglevel_type));
        if (ret) {
                goto end;
        }
@@ -1456,15 +1336,13 @@ end:
        return ret;
 }
 
-int mi_lttng_event_tracepoint_no_loglevel(struct mi_writer *writer,
-               struct lttng_event *event)
+int mi_lttng_event_tracepoint_no_loglevel(struct mi_writer *writer, struct lttng_event *event)
 {
        /* event exclusion filter */
        return write_event_exclusions(writer, event);
 }
 
-int mi_lttng_event_function_probe(struct mi_writer *writer,
-               struct lttng_event *event)
+int mi_lttng_event_function_probe(struct mi_writer *writer, struct lttng_event *event)
 {
        int ret;
 
@@ -1480,22 +1358,22 @@ int mi_lttng_event_function_probe(struct mi_writer *writer,
 
        if (event->attr.probe.addr != 0) {
                /* event probe address */
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               config_element_address, event->attr.probe.addr);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer, config_element_address, event->attr.probe.addr);
                if (ret) {
                        goto end;
                }
        } else {
                /* event probe offset */
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               config_element_offset, event->attr.probe.offset);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer, config_element_offset, event->attr.probe.offset);
                if (ret) {
                        goto end;
                }
 
                /* event probe symbol_name */
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_symbol_name, event->attr.probe.symbol_name);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_symbol_name, event->attr.probe.symbol_name);
                if (ret) {
                        goto end;
                }
@@ -1507,9 +1385,7 @@ end:
        return ret;
 }
 
-static
-int mi_lttng_event_userspace_probe(struct mi_writer *writer,
-               struct lttng_event *event)
+static int mi_lttng_event_userspace_probe(struct mi_writer *writer, struct lttng_event *event)
 {
        int ret;
        const struct lttng_userspace_probe_location *location;
@@ -1541,25 +1417,27 @@ int mi_lttng_event_userspace_probe(struct mi_writer *writer,
                const char *function_name;
                const char *binary_path;
 
-               ret = mi_lttng_writer_open_element(writer,
-                               config_element_userspace_probe_function_attributes);
+               ret = mi_lttng_writer_open_element(
+                       writer, config_element_userspace_probe_function_attributes);
                if (ret) {
                        goto end;
                }
 
                switch (lookup_type) {
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
-                       ret = mi_lttng_writer_write_element_string(writer,
-                                       config_element_userspace_probe_lookup,
-                                       config_element_userspace_probe_lookup_function_elf);
+                       ret = mi_lttng_writer_write_element_string(
+                               writer,
+                               config_element_userspace_probe_lookup,
+                               config_element_userspace_probe_lookup_function_elf);
                        if (ret) {
                                goto end;
                        }
                        break;
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT:
-                       ret = mi_lttng_writer_write_element_string(writer,
-                                       config_element_userspace_probe_lookup,
-                                       config_element_userspace_probe_lookup_function_default);
+                       ret = mi_lttng_writer_write_element_string(
+                               writer,
+                               config_element_userspace_probe_lookup,
+                               config_element_userspace_probe_lookup_function_default);
                        if (ret) {
                                goto end;
                        }
@@ -1569,16 +1447,17 @@ int mi_lttng_event_userspace_probe(struct mi_writer *writer,
                }
 
                binary_path = lttng_userspace_probe_location_function_get_binary_path(location);
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_userspace_probe_location_binary_path, binary_path);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_userspace_probe_location_binary_path, binary_path);
                if (ret) {
                        goto end;
                }
 
                function_name = lttng_userspace_probe_location_function_get_function_name(location);
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_userspace_probe_function_location_function_name,
-                               function_name);
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_function_location_function_name,
+                       function_name);
                if (ret) {
                        goto end;
                }
@@ -1590,17 +1469,18 @@ int mi_lttng_event_userspace_probe(struct mi_writer *writer,
                const char *probe_name, *provider_name;
                const char *binary_path;
 
-               ret = mi_lttng_writer_open_element(writer,
-                               config_element_userspace_probe_function_attributes);
+               ret = mi_lttng_writer_open_element(
+                       writer, config_element_userspace_probe_function_attributes);
                if (ret) {
                        goto end;
                }
 
                switch (lookup_type) {
                case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
-                       ret = mi_lttng_writer_write_element_string(writer,
-                                       config_element_userspace_probe_lookup,
-                                       config_element_userspace_probe_lookup_tracepoint_sdt);
+                       ret = mi_lttng_writer_write_element_string(
+                               writer,
+                               config_element_userspace_probe_lookup,
+                               config_element_userspace_probe_lookup_tracepoint_sdt);
                        if (ret) {
                                goto end;
                        }
@@ -1610,24 +1490,27 @@ int mi_lttng_event_userspace_probe(struct mi_writer *writer,
                }
 
                binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(location);
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_userspace_probe_location_binary_path,
-                               binary_path);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_userspace_probe_location_binary_path, binary_path);
                if (ret) {
                        goto end;
                }
 
-               provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(location);
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_userspace_probe_tracepoint_location_provider_name,
-                               provider_name);
+               provider_name =
+                       lttng_userspace_probe_location_tracepoint_get_provider_name(location);
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_tracepoint_location_provider_name,
+                       provider_name);
                if (ret) {
                        goto end;
                }
 
                probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(location);
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_userspace_probe_tracepoint_location_probe_name, probe_name);
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       config_element_userspace_probe_tracepoint_location_probe_name,
+                       probe_name);
                if (ret) {
                        goto end;
                }
@@ -1642,8 +1525,7 @@ end:
        return ret;
 }
 
-int mi_lttng_event_function_entry(struct mi_writer *writer,
-               struct lttng_event *event)
+int mi_lttng_event_function_entry(struct mi_writer *writer, struct lttng_event *event)
 {
        int ret;
 
@@ -1658,8 +1540,8 @@ int mi_lttng_event_function_entry(struct mi_writer *writer,
        }
 
        /* event probe symbol_name */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_symbol_name, event->attr.ftrace.symbol_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_symbol_name, event->attr.ftrace.symbol_name);
        if (ret) {
                goto end;
        }
@@ -1676,7 +1558,9 @@ int mi_lttng_events_open(struct mi_writer *writer)
 }
 
 int mi_lttng_event(struct mi_writer *writer,
-               struct lttng_event *event, int is_open, enum lttng_domain_type domain)
+                  struct lttng_event *event,
+                  int is_open,
+                  enum lttng_domain_type domain)
 {
        int ret;
 
@@ -1726,52 +1610,39 @@ end:
 
 int mi_lttng_trackers_open(struct mi_writer *writer)
 {
-       return mi_lttng_writer_open_element(
-                       writer, config_element_process_attr_trackers);
+       return mi_lttng_writer_open_element(writer, config_element_process_attr_trackers);
 }
 
 static int get_tracker_elements(enum lttng_process_attr process_attr,
-               const char **element_process_attr_tracker,
-               const char **element_process_attr_value)
+                               const char **element_process_attr_tracker,
+                               const char **element_process_attr_value)
 {
        int ret = 0;
 
        switch (process_attr) {
        case LTTNG_PROCESS_ATTR_PROCESS_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_pid;
-               *element_process_attr_value =
-                               config_element_process_attr_pid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_pid;
+               *element_process_attr_value = config_element_process_attr_pid_value;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_vpid;
-               *element_process_attr_value =
-                               config_element_process_attr_vpid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_vpid;
+               *element_process_attr_value = config_element_process_attr_vpid_value;
                break;
        case LTTNG_PROCESS_ATTR_USER_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_uid;
-               *element_process_attr_value =
-                               config_element_process_attr_uid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_uid;
+               *element_process_attr_value = config_element_process_attr_uid_value;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_vuid;
-               *element_process_attr_value =
-                               config_element_process_attr_vuid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_vuid;
+               *element_process_attr_value = config_element_process_attr_vuid_value;
                break;
        case LTTNG_PROCESS_ATTR_GROUP_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_gid;
-               *element_process_attr_value =
-                               config_element_process_attr_gid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_gid;
+               *element_process_attr_value = config_element_process_attr_gid_value;
                break;
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
-               *element_process_attr_tracker =
-                               config_element_process_attr_tracker_vgid;
-               *element_process_attr_value =
-                               config_element_process_attr_vgid_value;
+               *element_process_attr_tracker = config_element_process_attr_tracker_vgid;
+               *element_process_attr_value = config_element_process_attr_vgid_value;
                break;
        default:
                ret = LTTNG_ERR_SAVE_IO_FAIL;
@@ -1779,14 +1650,13 @@ static int get_tracker_elements(enum lttng_process_attr process_attr,
        return ret;
 }
 
-int mi_lttng_process_attribute_tracker_open(
-               struct mi_writer *writer, enum lttng_process_attr process_attr)
+int mi_lttng_process_attribute_tracker_open(struct mi_writer *writer,
+                                           enum lttng_process_attr process_attr)
 {
        int ret;
        const char *element_tracker, *element_value;
 
-       ret = get_tracker_elements(
-                       process_attr, &element_tracker, &element_value);
+       ret = get_tracker_elements(process_attr, &element_tracker, &element_value);
        if (ret) {
                return ret;
        }
@@ -1812,10 +1682,7 @@ int mi_lttng_pids_open(struct mi_writer *writer)
  * TODO: move the listing of pid for user agent to process semantic on
  * mi api bump. The use of process element break the mi api.
  */
-int mi_lttng_pid(struct mi_writer *writer,
-               pid_t pid,
-               const char *name,
-               int is_open)
+int mi_lttng_pid(struct mi_writer *writer, pid_t pid, const char *name, int is_open)
 {
        int ret;
 
@@ -1826,16 +1693,14 @@ int mi_lttng_pid(struct mi_writer *writer,
        }
 
        /* Writing pid number */
-       ret = mi_lttng_writer_write_element_signed_int(writer,
-                       mi_lttng_element_pid_id, (int)pid);
+       ret = mi_lttng_writer_write_element_signed_int(writer, mi_lttng_element_pid_id, (int) pid);
        if (ret) {
                goto end;
        }
 
        /* Writing name of the process */
        if (name) {
-               ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                               name);
+               ret = mi_lttng_writer_write_element_string(writer, config_element_name, name);
                if (ret) {
                        goto end;
                }
@@ -1852,19 +1717,17 @@ end:
 
 int mi_lttng_process_attr_values_open(struct mi_writer *writer)
 {
-       return mi_lttng_writer_open_element(
-                       writer, config_element_process_attr_values);
+       return mi_lttng_writer_open_element(writer, config_element_process_attr_values);
 }
 
 int mi_lttng_all_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               bool is_open)
+                                        enum lttng_process_attr process_attr,
+                                        bool is_open)
 {
        int ret;
        const char *element_id_tracker, *element_target_id;
 
-       ret = get_tracker_elements(
-                       process_attr, &element_id_tracker, &element_target_id);
+       ret = get_tracker_elements(process_attr, &element_id_tracker, &element_target_id);
        if (ret) {
                return ret;
        }
@@ -1900,15 +1763,14 @@ end:
 }
 
 int mi_lttng_integral_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               int64_t value,
-               bool is_open)
+                                             enum lttng_process_attr process_attr,
+                                             int64_t value,
+                                             bool is_open)
 {
        int ret;
        const char *element_id_tracker, *element_target_id;
 
-       ret = get_tracker_elements(
-                       process_attr, &element_id_tracker, &element_target_id);
+       ret = get_tracker_elements(process_attr, &element_id_tracker, &element_target_id);
        if (ret) {
                return ret;
        }
@@ -1924,7 +1786,7 @@ int mi_lttng_integral_process_attribute_value(struct mi_writer *writer,
        }
 
        ret = mi_lttng_writer_write_element_signed_int(
-                       writer, config_element_process_attr_id, value);
+               writer, config_element_process_attr_id, value);
        if (ret) {
                goto end;
        }
@@ -1946,16 +1808,15 @@ end:
 }
 
 int mi_lttng_string_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               const char *value,
-               bool is_open)
+                                           enum lttng_process_attr process_attr,
+                                           const char *value,
+                                           bool is_open)
 
 {
        int ret;
        const char *element_id_tracker, *element_target_id;
 
-       ret = get_tracker_elements(
-                       process_attr, &element_id_tracker, &element_target_id);
+       ret = get_tracker_elements(process_attr, &element_id_tracker, &element_target_id);
        if (ret) {
                return ret;
        }
@@ -1970,8 +1831,7 @@ int mi_lttng_string_process_attribute_value(struct mi_writer *writer,
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_string(
-                       writer, config_element_name, value);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, value);
        if (ret) {
                goto end;
        }
@@ -1997,8 +1857,7 @@ int mi_lttng_event_fields_open(struct mi_writer *writer)
        return mi_lttng_writer_open_element(writer, mi_lttng_element_event_fields);
 }
 
-int mi_lttng_event_field(struct mi_writer *writer,
-               struct lttng_event_field *field)
+int mi_lttng_event_field(struct mi_writer *writer, struct lttng_event_field *field)
 {
        int ret;
 
@@ -2018,22 +1877,21 @@ int mi_lttng_event_field(struct mi_writer *writer,
        }
 
        /* Name */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       field->field_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, field->field_name);
        if (ret) {
                goto end;
        }
 
        /* Type */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_type,
-                       mi_lttng_eventfieldtype_string(field->type));
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_type, mi_lttng_eventfieldtype_string(field->type));
        if (ret) {
                goto end;
        }
 
        /* nowrite  */
-       ret = mi_lttng_writer_write_element_signed_int(writer,
-                       mi_lttng_element_nowrite, field->nowrite);
+       ret = mi_lttng_writer_write_element_signed_int(
+               writer, mi_lttng_element_nowrite, field->nowrite);
        if (ret) {
                goto end;
        }
@@ -2047,34 +1905,32 @@ end:
 }
 
 int mi_lttng_perf_counter_context(struct mi_writer *writer,
-               struct lttng_event_perf_counter_ctx  *perf_context)
+                                 struct lttng_event_perf_counter_ctx *perf_context)
 {
        int ret;
 
        /* Open perf_counter_context */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_perf_counter_context);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_perf_counter_context);
        if (ret) {
                goto end;
        }
 
        /* Type */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       config_element_type, perf_context->type);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_type, perf_context->type);
        if (ret) {
                goto end;
        }
 
        /* Config */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       config_element_config, perf_context->config);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, config_element_config, perf_context->config);
        if (ret) {
                goto end;
        }
 
        /* Name of the perf counter */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, perf_context->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, perf_context->name);
        if (ret) {
                goto end;
        }
@@ -2085,30 +1941,27 @@ end:
        return ret;
 }
 
-static
-int mi_lttng_app_context(struct mi_writer *writer,
-               const char *provider_name, const char *ctx_name)
+static int
+mi_lttng_app_context(struct mi_writer *writer, const char *provider_name, const char *ctx_name)
 {
        int ret;
 
        /* Open app */
-       ret = mi_lttng_writer_open_element(writer,
-                       config_element_context_app);
+       ret = mi_lttng_writer_open_element(writer, config_element_context_app);
        if (ret) {
                goto end;
        }
 
        /* provider_name */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_context_app_provider_name,
-                       provider_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_context_app_provider_name, provider_name);
        if (ret) {
                goto end;
        }
 
        /* ctx_name */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_context_app_ctx_name, ctx_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, config_element_context_app_ctx_name, ctx_name);
        if (ret) {
                goto end;
        }
@@ -2119,13 +1972,12 @@ end:
        return ret;
 }
 
-int mi_lttng_context(struct mi_writer *writer,
-               struct lttng_event_context *context, int is_open)
+int mi_lttng_context(struct mi_writer *writer, struct lttng_event_context *context, int is_open)
 {
        int ret;
 
        /* Open context */
-       ret = mi_lttng_writer_open_element(writer , config_element_context);
+       ret = mi_lttng_writer_open_element(writer, config_element_context);
        if (ret) {
                goto end;
        }
@@ -2137,9 +1989,8 @@ int mi_lttng_context(struct mi_writer *writer,
        case LTTNG_EVENT_CONTEXT_PERF_THREAD_COUNTER:
        case LTTNG_EVENT_CONTEXT_PERF_CPU_COUNTER:
        {
-               struct lttng_event_perf_counter_ctx *perf_context =
-                               &context->u.perf_counter;
-               ret =  mi_lttng_perf_counter_context(writer, perf_context);
+               struct lttng_event_perf_counter_ctx *perf_context = &context->u.perf_counter;
+               ret = mi_lttng_perf_counter_context(writer, perf_context);
                if (ret) {
                        goto end;
                }
@@ -2147,9 +1998,8 @@ int mi_lttng_context(struct mi_writer *writer,
        }
        case LTTNG_EVENT_CONTEXT_APP_CONTEXT:
        {
-               ret = mi_lttng_app_context(writer,
-                               context->u.app_ctx.provider_name,
-                               context->u.app_ctx.ctx_name);
+               ret = mi_lttng_app_context(
+                       writer, context->u.app_ctx.provider_name, context->u.app_ctx.ctx_name);
                if (ret) {
                        goto end;
                }
@@ -2157,16 +2007,15 @@ int mi_lttng_context(struct mi_writer *writer,
        }
        default:
        {
-               const char *type_string = mi_lttng_event_contexttype_string(
-                               context->ctx);
+               const char *type_string = mi_lttng_event_contexttype_string(context->ctx);
                if (!type_string) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
 
                /* Print context type */
-               ret = mi_lttng_writer_write_element_string(writer,
-                               config_element_type, type_string);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, config_element_type, type_string);
                break;
        }
        }
@@ -2180,8 +2029,7 @@ end:
        return ret;
 }
 
-int mi_lttng_snapshot_output_session_name(struct mi_writer *writer,
-               const char *session_name)
+int mi_lttng_snapshot_output_session_name(struct mi_writer *writer, const char *session_name)
 {
        int ret;
 
@@ -2192,8 +2040,7 @@ int mi_lttng_snapshot_output_session_name(struct mi_writer *writer,
        }
 
        /* Snapshot output list for current session name */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, session_name);
        if (ret) {
                goto end;
        }
@@ -2209,48 +2056,45 @@ end:
 }
 
 int mi_lttng_snapshot_list_output(struct mi_writer *writer,
-               const struct lttng_snapshot_output *output)
+                                 const struct lttng_snapshot_output *output)
 {
        int ret;
 
        /* Open element snapshot output */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_snapshot);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_snapshot);
        if (ret) {
                goto end;
        }
 
        /* ID of the snapshot output */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_id, output->id);
+       ret = mi_lttng_writer_write_element_unsigned_int(writer, mi_lttng_element_id, output->id);
        if (ret) {
                goto end;
        }
 
        /* Name of the output */
-       ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                       output->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, output->name);
        if (ret) {
                goto end;
        }
 
        /* Destination of the output (ctrl_url)*/
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
        if (ret) {
                goto end;
        }
 
        /* Destination of the output (data_url) */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_data_url, output->data_url);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_data_url, output->data_url);
        if (ret) {
                goto end;
        }
 
        /* total size of all stream combined */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_snapshot_max_size, output->max_size);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_snapshot_max_size, output->max_size);
        if (ret) {
                goto end;
        }
@@ -2262,26 +2106,25 @@ end:
        return ret;
 }
 
-int mi_lttng_snapshot_del_output(struct mi_writer *writer, int id,
-               const char *name, const char *current_session_name)
+int mi_lttng_snapshot_del_output(struct mi_writer *writer,
+                                int id,
+                                const char *name,
+                                const char *current_session_name)
 {
        int ret;
 
        /* Open element del_snapshot */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_snapshot);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_snapshot);
        if (ret) {
                goto end;
        }
 
-
        if (id != UINT32_MAX) {
                /* "Snapshot output "id" successfully deleted
                 * for "current_session_name"
                 * ID of the snapshot output
                 */
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               mi_lttng_element_id, id);
+               ret = mi_lttng_writer_write_element_unsigned_int(writer, mi_lttng_element_id, id);
                if (ret) {
                        goto end;
                }
@@ -2290,17 +2133,15 @@ int mi_lttng_snapshot_del_output(struct mi_writer *writer, int id,
                 * for session "current_session_name"
                 * Name of the output
                 */
-               ret = mi_lttng_writer_write_element_string(writer, config_element_name,
-                               name);
+               ret = mi_lttng_writer_write_element_string(writer, config_element_name, name);
                if (ret) {
                        goto end;
                }
        }
 
        /* Snapshot was deleted for session "current_session_name"*/
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_session_name,
-                       current_session_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_session_name, current_session_name);
        if (ret) {
                goto end;
        }
@@ -2313,49 +2154,47 @@ end:
 }
 
 int mi_lttng_snapshot_add_output(struct mi_writer *writer,
-               const char *current_session_name, const char *n_ptr,
-               struct lttng_snapshot_output *output)
+                                const char *current_session_name,
+                                const char *n_ptr,
+                                struct lttng_snapshot_output *output)
 {
        int ret;
 
        /* Open element snapshot */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_snapshot);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_snapshot);
        if (ret) {
                goto end;
        }
 
        /* Snapshot output id */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_id, output->id);
+       ret = mi_lttng_writer_write_element_unsigned_int(writer, mi_lttng_element_id, output->id);
        if (ret) {
                goto end;
        }
 
        /* Snapshot output names */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       config_element_name, n_ptr);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, n_ptr);
        if (ret) {
                goto end;
        }
 
        /* Destination of the output (ctrl_url)*/
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
        if (ret) {
                goto end;
        }
 
        /* Snapshot added for session "current_session_name"*/
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_session_name, current_session_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_session_name, current_session_name);
        if (ret) {
                goto end;
        }
 
        /* total size of all stream combined */
-       ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                       mi_lttng_element_snapshot_max_size, output->max_size);
+       ret = mi_lttng_writer_write_element_unsigned_int(
+               writer, mi_lttng_element_snapshot_max_size, output->max_size);
        if (ret) {
                goto end;
        }
@@ -2367,14 +2206,15 @@ end:
        return ret;
 }
 
-int mi_lttng_snapshot_record(struct mi_writer *writer, const char *url,
-               const char *cmdline_ctrl_url, const char *cmdline_data_url)
+int mi_lttng_snapshot_record(struct mi_writer *writer,
+                            const char *url,
+                            const char *cmdline_ctrl_url,
+                            const char *cmdline_data_url)
 {
        int ret;
 
        /* Open element snapshot */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_command_snapshot);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_command_snapshot);
        if (ret) {
                goto end;
        }
@@ -2384,22 +2224,22 @@ int mi_lttng_snapshot_record(struct mi_writer *writer, const char *url,
         * else take the command line data and ctrl urls*/
        if (url) {
                /* Destination of the output (ctrl_url)*/
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_snapshot_ctrl_url, url);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_snapshot_ctrl_url, url);
                if (ret) {
                        goto end;
                }
        } else if (cmdline_ctrl_url) {
                /* Destination of the output (ctrl_url)*/
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_snapshot_ctrl_url, cmdline_ctrl_url);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_snapshot_ctrl_url, cmdline_ctrl_url);
                if (ret) {
                        goto end;
                }
 
                /* Destination of the output (data_url) */
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_snapshot_data_url, cmdline_data_url);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_snapshot_data_url, cmdline_data_url);
                if (ret) {
                        goto end;
                }
@@ -2413,7 +2253,7 @@ end:
 }
 
 int mi_lttng_rotation_schedule(struct mi_writer *writer,
-               const struct lttng_rotation_schedule *schedule)
+                              const struct lttng_rotation_schedule *schedule)
 {
        int ret = 0;
        enum lttng_rotation_status status;
@@ -2424,14 +2264,12 @@ int mi_lttng_rotation_schedule(struct mi_writer *writer,
 
        switch (lttng_rotation_schedule_get_type(schedule)) {
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
-               status = lttng_rotation_schedule_periodic_get_period(schedule,
-                               &value);
+               status = lttng_rotation_schedule_periodic_get_period(schedule, &value);
                element_name = mi_lttng_element_rotation_schedule_periodic;
                value_name = mi_lttng_element_rotation_schedule_periodic_time_us;
                break;
        case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
-               status = lttng_rotation_schedule_size_threshold_get_threshold(
-                               schedule, &value);
+               status = lttng_rotation_schedule_size_threshold_get_threshold(schedule, &value);
                element_name = mi_lttng_element_rotation_schedule_size_threshold;
                value_name = mi_lttng_element_rotation_schedule_size_threshold_bytes;
                break;
@@ -2455,8 +2293,7 @@ int mi_lttng_rotation_schedule(struct mi_writer *writer,
        }
 
        if (!empty_schedule) {
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               value_name, value);
+               ret = mi_lttng_writer_write_element_unsigned_int(writer, value_name, value);
                if (ret) {
                        goto end;
                }
@@ -2472,19 +2309,17 @@ end:
 }
 
 int mi_lttng_rotation_schedule_result(struct mi_writer *writer,
-               const struct lttng_rotation_schedule *schedule,
-               bool success)
+                                     const struct lttng_rotation_schedule *schedule,
+                                     bool success)
 {
        int ret = 0;
 
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_rotation_schedule_result);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rotation_schedule_result);
        if (ret) {
                goto end;
        }
 
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_rotation_schedule);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rotation_schedule);
        if (ret) {
                goto end;
        }
@@ -2500,8 +2335,7 @@ int mi_lttng_rotation_schedule_result(struct mi_writer *writer,
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_bool(writer,
-                       mi_lttng_element_command_success, success);
+       ret = mi_lttng_writer_write_element_bool(writer, mi_lttng_element_command_success, success);
        if (ret) {
                goto end;
        }
@@ -2515,9 +2349,8 @@ end:
        return ret;
 }
 
-static
-int mi_lttng_location(struct mi_writer *writer,
-               const struct lttng_trace_archive_location *location)
+static int mi_lttng_location(struct mi_writer *writer,
+                            const struct lttng_trace_archive_location *location)
 {
        int ret = 0;
        enum lttng_trace_archive_location_type location_type;
@@ -2530,23 +2363,23 @@ int mi_lttng_location(struct mi_writer *writer,
        {
                const char *absolute_path;
 
-               status = lttng_trace_archive_location_local_get_absolute_path(
-                               location, &absolute_path);
+               status = lttng_trace_archive_location_local_get_absolute_path(location,
+                                                                             &absolute_path);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
                ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_rotation_location_local);
+                                                  mi_lttng_element_rotation_location_local);
                if (ret) {
                        goto end;
                }
 
-
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_rotation_location_local_absolute_path,
-                               absolute_path);
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       mi_lttng_element_rotation_location_local_absolute_path,
+                       absolute_path);
                if (ret) {
                        goto end;
                }
@@ -2565,78 +2398,76 @@ int mi_lttng_location(struct mi_writer *writer,
                enum lttng_trace_archive_location_relay_protocol_type protocol;
 
                /* Fetch all relay location parameters. */
-               status = lttng_trace_archive_location_relay_get_protocol_type(
-                               location, &protocol);
+               status = lttng_trace_archive_location_relay_get_protocol_type(location, &protocol);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_host(
-                               location, &host);
+               status = lttng_trace_archive_location_relay_get_host(location, &host);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_control_port(
-                               location, &control_port);
+               status = lttng_trace_archive_location_relay_get_control_port(location,
+                                                                            &control_port);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_data_port(
-                               location, &data_port);
+               status = lttng_trace_archive_location_relay_get_data_port(location, &data_port);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
-               status = lttng_trace_archive_location_relay_get_relative_path(
-                               location, &relative_path);
+               status = lttng_trace_archive_location_relay_get_relative_path(location,
+                                                                             &relative_path);
                if (status != LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK) {
                        ret = -1;
                        goto end;
                }
 
                ret = mi_lttng_writer_open_element(writer,
-                               mi_lttng_element_rotation_location_relay);
+                                                  mi_lttng_element_rotation_location_relay);
                if (ret) {
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_rotation_location_relay_host,
-                               host);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_rotation_location_relay_host, host);
                if (ret) {
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               mi_lttng_element_rotation_location_relay_control_port,
-                               control_port);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer,
+                       mi_lttng_element_rotation_location_relay_control_port,
+                       control_port);
                if (ret) {
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               mi_lttng_element_rotation_location_relay_data_port,
-                               data_port);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer, mi_lttng_element_rotation_location_relay_data_port, data_port);
                if (ret) {
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_rotation_location_relay_protocol,
-                               mi_lttng_trace_archive_location_relay_protocol_type_string(protocol));
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       mi_lttng_element_rotation_location_relay_protocol,
+                       mi_lttng_trace_archive_location_relay_protocol_type_string(protocol));
                if (ret) {
                        goto end;
                }
 
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_rotation_location_relay_relative_path,
-                               relative_path);
+               ret = mi_lttng_writer_write_element_string(
+                       writer,
+                       mi_lttng_element_rotation_location_relay_relative_path,
+                       relative_path);
                if (ret) {
                        goto end;
                }
@@ -2656,28 +2487,26 @@ end:
 }
 
 int mi_lttng_rotate(struct mi_writer *writer,
-               const char *session_name,
-               enum lttng_rotation_state rotation_state,
-               const struct lttng_trace_archive_location *location)
+                   const char *session_name,
+                   enum lttng_rotation_state rotation_state,
+                   const struct lttng_trace_archive_location *location)
 {
        int ret;
 
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_rotation);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rotation);
        if (ret) {
                goto end;
        }
 
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_session_name,
-                       session_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_session_name, session_name);
        if (ret) {
                goto end;
        }
 
        ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_rotation_state,
-                       mi_lttng_rotation_state_string(rotation_state));
+                                                  mi_lttng_element_rotation_state,
+                                                  mi_lttng_rotation_state_string(rotation_state));
        if (ret) {
                goto end;
        }
@@ -2687,8 +2516,7 @@ int mi_lttng_rotate(struct mi_writer *writer,
                goto close_rotation;
        }
 
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_rotation_location);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_rotation_location);
        if (ret) {
                goto end;
        }
index 182a189babc792fefcfe961e3d09c7b0a2a6f19f..10a3e13f509afc5a7b72289c85e1d9438210980b 100644 (file)
@@ -9,13 +9,14 @@
 #ifndef _MI_LTTNG_H
 #define _MI_LTTNG_H
 
-#include <stdint.h>
-
+#include <common/config/session-config.hpp>
 #include <common/error.hpp>
 #include <common/macros.hpp>
-#include <common/config/session-config.hpp>
+
 #include <lttng/lttng.h>
 
+#include <stdint.h>
+
 /* Don't want to reference snapshot-internal.h here */
 struct lttng_snapshot_output;
 
@@ -39,16 +40,14 @@ struct mi_lttng_version_data {
 };
 
 /* Error query callbacks. */
-typedef enum lttng_error_code (*mi_lttng_error_query_trigger_cb)(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results **results);
-typedef enum lttng_error_code (*mi_lttng_error_query_condition_cb)(
-               const struct lttng_trigger *trigger,
-               struct lttng_error_query_results **results);
-typedef enum lttng_error_code (*mi_lttng_error_query_action_cb)(
-               const struct lttng_trigger *trigger,
-               const struct lttng_action_path *action_path,
-               struct lttng_error_query_results **results);
+using mi_lttng_error_query_trigger_cb = enum lttng_error_code (*)(
+       const struct lttng_trigger *, struct lttng_error_query_results **);
+using mi_lttng_error_query_condition_cb = enum lttng_error_code (*)(
+       const struct lttng_trigger *, struct lttng_error_query_results **);
+using mi_lttng_error_query_action_cb =
+       enum lttng_error_code (*)(const struct lttng_trigger *,
+                                 const struct lttng_action_path *,
+                                 struct lttng_error_query_results **);
 
 struct mi_lttng_error_query_callbacks {
        mi_lttng_error_query_trigger_cb trigger_cb;
@@ -57,190 +56,188 @@ struct mi_lttng_error_query_callbacks {
 };
 
 /* Strings related to command */
-LTTNG_EXPORT extern const char * const mi_lttng_element_command;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_action;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_add_context;
-extern const char * const mi_lttng_element_command_add_trigger;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_create;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_destroy;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_disable_channel;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_disable_event;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_enable_channels;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_enable_event;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_list;
-extern const char * const mi_lttng_element_command_list_trigger;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_load;
-extern const char * const mi_lttng_element_command_metadata;
-extern const char * const mi_lttng_element_command_metadata_action;
-extern const char * const mi_lttng_element_command_regenerate;
-extern const char * const mi_lttng_element_command_regenerate_action;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_name;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_output;
-extern const char * const mi_lttng_element_command_remove_trigger;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_save;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_set_session;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_snapshot;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_snapshot_add;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_snapshot_del;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_snapshot_list;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_snapshot_record;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_start;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_stop;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_success;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_track;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_untrack;
-LTTNG_EXPORT extern const char * const mi_lttng_element_command_version;
-extern const char * const mi_lttng_element_command_rotate;
-extern const char * const mi_lttng_element_command_enable_rotation;
-extern const char * const mi_lttng_element_command_disable_rotation;
-extern const char * const mi_lttng_element_command_clear;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_action;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_add_context;
+extern const char *const mi_lttng_element_command_add_trigger;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_create;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_destroy;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_disable_channel;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_disable_event;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_enable_channels;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_enable_event;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_list;
+extern const char *const mi_lttng_element_command_list_trigger;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_load;
+extern const char *const mi_lttng_element_command_metadata;
+extern const char *const mi_lttng_element_command_metadata_action;
+extern const char *const mi_lttng_element_command_regenerate;
+extern const char *const mi_lttng_element_command_regenerate_action;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_name;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_output;
+extern const char *const mi_lttng_element_command_remove_trigger;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_save;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_set_session;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_snapshot;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_snapshot_add;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_snapshot_del;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_snapshot_list;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_snapshot_record;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_start;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_stop;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_success;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_track;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_untrack;
+LTTNG_EXPORT extern const char *const mi_lttng_element_command_version;
+extern const char *const mi_lttng_element_command_rotate;
+extern const char *const mi_lttng_element_command_enable_rotation;
+extern const char *const mi_lttng_element_command_disable_rotation;
+extern const char *const mi_lttng_element_command_clear;
 
 /* Strings related to version command */
-LTTNG_EXPORT extern const char * const mi_lttng_element_version;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_commit;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_description;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_license;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_major;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_minor;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_patch_level;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_str;
-LTTNG_EXPORT extern const char * const mi_lttng_element_version_web;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_commit;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_description;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_license;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_major;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_minor;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_patch_level;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_str;
+LTTNG_EXPORT extern const char *const mi_lttng_element_version_web;
 
 /* String related to a lttng_event_field */
-LTTNG_EXPORT extern const char * const mi_lttng_element_event_field;
-LTTNG_EXPORT extern const char * const mi_lttng_element_event_fields;
+LTTNG_EXPORT extern const char *const mi_lttng_element_event_field;
+LTTNG_EXPORT extern const char *const mi_lttng_element_event_fields;
 
 /* String related to lttng_event_perf_counter_ctx */
-LTTNG_EXPORT extern const char * const mi_lttng_element_perf_counter_context;
+LTTNG_EXPORT extern const char *const mi_lttng_element_perf_counter_context;
 
 /* Strings related to pid */
-LTTNG_EXPORT extern const char * const mi_lttng_element_pid_id;
+LTTNG_EXPORT extern const char *const mi_lttng_element_pid_id;
 
 /* Strings related to save command */
-LTTNG_EXPORT extern const char * const mi_lttng_element_save;
+LTTNG_EXPORT extern const char *const mi_lttng_element_save;
 
 /* Strings related to load command */
-LTTNG_EXPORT extern const char * const mi_lttng_element_load;
-extern const char * const mi_lttng_element_load_overrides;
-extern const char * const mi_lttng_element_load_override_url;
+LTTNG_EXPORT extern const char *const mi_lttng_element_load;
+extern const char *const mi_lttng_element_load_overrides;
+extern const char *const mi_lttng_element_load_override_url;
 
 /* General element of mi_lttng */
-LTTNG_EXPORT extern const char * const mi_lttng_element_empty;
-LTTNG_EXPORT extern const char * const mi_lttng_element_id;
-LTTNG_EXPORT extern const char * const mi_lttng_element_nowrite;
-LTTNG_EXPORT extern const char * const mi_lttng_element_success;
-LTTNG_EXPORT extern const char * const mi_lttng_element_type_enum;
-LTTNG_EXPORT extern const char * const mi_lttng_element_type_float;
-LTTNG_EXPORT extern const char * const mi_lttng_element_type_integer;
-LTTNG_EXPORT extern const char * const mi_lttng_element_type_other;
-LTTNG_EXPORT extern const char * const mi_lttng_element_type_string;
+LTTNG_EXPORT extern const char *const mi_lttng_element_empty;
+LTTNG_EXPORT extern const char *const mi_lttng_element_id;
+LTTNG_EXPORT extern const char *const mi_lttng_element_nowrite;
+LTTNG_EXPORT extern const char *const mi_lttng_element_success;
+LTTNG_EXPORT extern const char *const mi_lttng_element_type_enum;
+LTTNG_EXPORT extern const char *const mi_lttng_element_type_float;
+LTTNG_EXPORT extern const char *const mi_lttng_element_type_integer;
+LTTNG_EXPORT extern const char *const mi_lttng_element_type_other;
+LTTNG_EXPORT extern const char *const mi_lttng_element_type_string;
 
 /* String related to loglevel */
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_alert;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_crit;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_function;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_line;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_module;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_process;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_program;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_system;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_debug_unit;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_emerg;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_err;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_info;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_notice;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_unknown;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_warning;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_alert;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_crit;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_function;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_line;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_module;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_process;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_program;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_system;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_debug_unit;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_emerg;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_err;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_info;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_notice;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_unknown;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_warning;
 
 /* String related to loglevel JUL */
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_all;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_config;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_fine;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_finer;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_finest;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_info;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_off;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_severe;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_jul_warning;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_all;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_config;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_fine;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_finer;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_finest;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_info;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_off;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_severe;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_jul_warning;
 
 /* String related to loglevel Log4j */
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_off;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_fatal;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_error;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_warn;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_info;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_debug;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_trace;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_log4j_all;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_off;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_fatal;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_error;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_warn;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_info;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_debug;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_trace;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_log4j_all;
 
 /* String related to loglevel Python */
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_critical;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_error;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_warning;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_info;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_debug;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_str_python_notset;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_critical;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_error;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_warning;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_info;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_debug;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_str_python_notset;
 
 /* String related to loglevel type */
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_type_all;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_type_range;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_type_single;
-LTTNG_EXPORT extern const char * const mi_lttng_loglevel_type_unknown;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_type_all;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_type_range;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_type_single;
+LTTNG_EXPORT extern const char *const mi_lttng_loglevel_type_unknown;
 
 /* String related to a lttng_snapshot */
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshot_ctrl_url;
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshot_data_url;
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshot_max_size;
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshot_n_ptr;
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshot_session_name;
-LTTNG_EXPORT extern const char * const mi_lttng_element_snapshots;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshot_ctrl_url;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshot_data_url;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshot_max_size;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshot_n_ptr;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshot_session_name;
+LTTNG_EXPORT extern const char *const mi_lttng_element_snapshots;
 
 /* String related to track/untrack command */
-LTTNG_EXPORT extern const char * const mi_lttng_element_track_untrack_all_wildcard;
+LTTNG_EXPORT extern const char *const mi_lttng_element_track_untrack_all_wildcard;
 
-extern const char * const mi_lttng_element_session_name;
+extern const char *const mi_lttng_element_session_name;
 
 /* String related to rotate command */
-extern const char * const mi_lttng_element_rotation;
-extern const char * const mi_lttng_element_rotate_status;
-extern const char * const mi_lttng_element_rotation_schedule;
-extern const char * const mi_lttng_element_rotation_schedules;
-extern const char * const mi_lttng_element_rotation_schedule_periodic;
-extern const char * const mi_lttng_element_rotation_schedule_periodic_time_us;
-extern const char * const mi_lttng_element_rotation_schedule_size_threshold;
-extern const char * const mi_lttng_element_rotation_schedule_size_threshold_bytes;
-extern const char * const mi_lttng_element_rotation_schedule_result;
-extern const char * const mi_lttng_element_rotation_schedule_results;
-extern const char * const mi_lttng_element_rotation_state;
-extern const char * const mi_lttng_element_rotation_location;
-extern const char * const mi_lttng_element_rotation_location_local;
-extern const char * const mi_lttng_element_rotation_location_local_absolute_path;
-extern const char * const mi_lttng_element_rotation_location_relay;
-extern const char * const mi_lttng_element_rotation_location_relay_host;
-extern const char * const mi_lttng_element_rotation_location_relay_control_port;
-extern const char * const mi_lttng_element_rotation_location_relay_data_port;
-extern const char * const mi_lttng_element_rotation_location_relay_protocol;
-extern const char * const mi_lttng_element_rotation_location_relay_relative_path;
+extern const char *const mi_lttng_element_rotation;
+extern const char *const mi_lttng_element_rotate_status;
+extern const char *const mi_lttng_element_rotation_schedule;
+extern const char *const mi_lttng_element_rotation_schedules;
+extern const char *const mi_lttng_element_rotation_schedule_periodic;
+extern const char *const mi_lttng_element_rotation_schedule_periodic_time_us;
+extern const char *const mi_lttng_element_rotation_schedule_size_threshold;
+extern const char *const mi_lttng_element_rotation_schedule_size_threshold_bytes;
+extern const char *const mi_lttng_element_rotation_schedule_result;
+extern const char *const mi_lttng_element_rotation_schedule_results;
+extern const char *const mi_lttng_element_rotation_state;
+extern const char *const mi_lttng_element_rotation_location;
+extern const char *const mi_lttng_element_rotation_location_local;
+extern const char *const mi_lttng_element_rotation_location_local_absolute_path;
+extern const char *const mi_lttng_element_rotation_location_relay;
+extern const char *const mi_lttng_element_rotation_location_relay_host;
+extern const char *const mi_lttng_element_rotation_location_relay_control_port;
+extern const char *const mi_lttng_element_rotation_location_relay_data_port;
+extern const char *const mi_lttng_element_rotation_location_relay_protocol;
+extern const char *const mi_lttng_element_rotation_location_relay_relative_path;
 
 /* String related to enum lttng_rotation_state */
-extern const char * const mi_lttng_rotation_state_str_ongoing;
-extern const char * const mi_lttng_rotation_state_str_completed;
-extern const char * const mi_lttng_rotation_state_str_expired;
-extern const char * const mi_lttng_rotation_state_str_error;
+extern const char *const mi_lttng_rotation_state_str_ongoing;
+extern const char *const mi_lttng_rotation_state_str_completed;
+extern const char *const mi_lttng_rotation_state_str_expired;
+extern const char *const mi_lttng_rotation_state_str_error;
 
 /* String related to enum lttng_trace_archive_location_relay_protocol_type */
-extern const char * const mi_lttng_rotation_location_relay_protocol_str_tcp;
+extern const char *const mi_lttng_rotation_location_relay_protocol_str_tcp;
 
 /* String related to rate_policy elements */
 extern const char *const mi_lttng_element_rate_policy;
 extern const char *const mi_lttng_element_rate_policy_every_n;
 extern const char *const mi_lttng_element_rate_policy_once_after_n;
 
-extern const char
-               *const mi_lttng_element_rate_policy_every_n_interval;
-extern const char
-               *const mi_lttng_element_rate_policy_once_after_n_threshold;
+extern const char *const mi_lttng_element_rate_policy_every_n_interval;
+extern const char *const mi_lttng_element_rate_policy_once_after_n_threshold;
 
 /* String related to action elements */
 extern const char *const mi_lttng_element_action;
@@ -250,25 +247,17 @@ extern const char *const mi_lttng_element_action_start_session;
 extern const char *const mi_lttng_element_action_stop_session;
 extern const char *const mi_lttng_element_action_rotate_session;
 extern const char *const mi_lttng_element_action_snapshot_session;
-extern const char
-               *const mi_lttng_element_action_snapshot_session_output;
+extern const char *const mi_lttng_element_action_snapshot_session_output;
 
 /* String related to condition */
 extern const char *const mi_lttng_element_condition;
-extern const char
-               *const mi_lttng_element_condition_buffer_usage_high;
-extern const char
-               *const mi_lttng_element_condition_buffer_usage_low;
-extern const char
-               *const mi_lttng_element_condition_event_rule_matches;
-extern const char
-               *const mi_lttng_element_condition_session_consumed_size;
-extern const char
-               *const mi_lttng_element_condition_session_rotation;
-extern const char
-               *const mi_lttng_element_condition_session_rotation_completed;
-extern const char
-               *const mi_lttng_element_condition_session_rotation_ongoing;
+extern const char *const mi_lttng_element_condition_buffer_usage_high;
+extern const char *const mi_lttng_element_condition_buffer_usage_low;
+extern const char *const mi_lttng_element_condition_event_rule_matches;
+extern const char *const mi_lttng_element_condition_session_consumed_size;
+extern const char *const mi_lttng_element_condition_session_rotation;
+extern const char *const mi_lttng_element_condition_session_rotation_completed;
+extern const char *const mi_lttng_element_condition_session_rotation_ongoing;
 extern const char *const mi_lttng_element_condition_channel_name;
 extern const char *const mi_lttng_element_condition_threshold_ratio;
 extern const char *const mi_lttng_element_condition_threshold_bytes;
@@ -280,12 +269,9 @@ extern const char *const mi_lttng_element_capture_descriptors;
 /* String related to event expression */
 extern const char *const mi_lttng_element_event_expr;
 extern const char *const mi_lttng_element_event_expr_payload_field;
-extern const char
-               *const mi_lttng_element_event_expr_channel_context_field;
-extern const char
-               *const mi_lttng_element_event_expr_app_specific_context_field;
-extern const char
-               *const mi_lttng_element_event_expr_array_field_element;
+extern const char *const mi_lttng_element_event_expr_channel_context_field;
+extern const char *const mi_lttng_element_event_expr_app_specific_context_field;
+extern const char *const mi_lttng_element_event_expr_array_field_element;
 
 extern const char *const mi_lttng_element_event_expr_provider_name;
 extern const char *const mi_lttng_element_event_expr_type_name;
@@ -297,87 +283,59 @@ extern const char *const mi_lttng_element_event_rule;
 /* String related to lttng_event_rule */
 extern const char *const mi_lttng_element_event_rule_event_name;
 extern const char *const mi_lttng_element_event_rule_name_pattern;
-extern const char
-               *const mi_lttng_element_event_rule_filter_expression;
+extern const char *const mi_lttng_element_event_rule_filter_expression;
 extern const char *const mi_lttng_element_event_rule_jul_logging;
 extern const char *const mi_lttng_element_event_rule_kernel_kprobe;
 extern const char *const mi_lttng_element_event_rule_kernel_syscall;
-extern const char
-               *const mi_lttng_element_event_rule_kernel_tracepoint;
+extern const char *const mi_lttng_element_event_rule_kernel_tracepoint;
 extern const char *const mi_lttng_element_event_rule_kernel_uprobe;
 extern const char *const mi_lttng_element_event_rule_log4j_logging;
 extern const char *const mi_lttng_element_event_rule_python_logging;
-extern const char
-               *const mi_lttng_element_event_rule_user_tracepoint;
+extern const char *const mi_lttng_element_event_rule_user_tracepoint;
 
 /* String related to lttng_event_rule_kernel_syscall. */
-extern const char
-               *const mi_lttng_element_event_rule_kernel_syscall_emission_site;
+extern const char *const mi_lttng_element_event_rule_kernel_syscall_emission_site;
 
 /* String related to enum lttng_event_rule_kernel_syscall_emission_site. */
-extern const char *const
-               mi_lttng_event_rule_kernel_syscall_emission_site_entry_exit;
-extern const char
-               *const mi_lttng_event_rule_kernel_syscall_emission_site_entry;
-extern const char
-               *const mi_lttng_event_rule_kernel_syscall_emission_site_exit;
-
-extern const char *const
-               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions;
-extern const char *const
-               mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion;
+extern const char *const mi_lttng_event_rule_kernel_syscall_emission_site_entry_exit;
+extern const char *const mi_lttng_event_rule_kernel_syscall_emission_site_entry;
+extern const char *const mi_lttng_event_rule_kernel_syscall_emission_site_exit;
+
+extern const char *const mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusions;
+extern const char *const mi_lttng_element_event_rule_user_tracepoint_name_pattern_exclusion;
 
 /* String related to log level rule. */
 extern const char *const mi_lttng_element_log_level_rule;
 extern const char *const mi_lttng_element_log_level_rule_exactly;
-extern const char
-               *const mi_lttng_element_log_level_rule_at_least_as_severe_as;
-extern const char *const
-               mi_lttng_element_log_level_rule_at_least_as_severe_as_thre;
+extern const char *const mi_lttng_element_log_level_rule_at_least_as_severe_as;
+extern const char *const mi_lttng_element_log_level_rule_at_least_as_severe_as_thre;
 extern const char *const mi_lttng_element_log_level_rule_level;
 
 /* String related to kernel probe location. */
 extern const char *const mi_lttng_element_kernel_probe_location;
-extern const char
-               *const mi_lttng_element_kernel_probe_location_symbol_offset;
-extern const char *const
-               mi_lttng_element_kernel_probe_location_symbol_offset_name;
-extern const char *const
-               mi_lttng_element_kernel_probe_location_symbol_offset_offset;
-extern const char
-               *const mi_lttng_element_kernel_probe_location_address;
-extern const char
-               *const mi_lttng_element_kernel_probe_location_address_address;
+extern const char *const mi_lttng_element_kernel_probe_location_symbol_offset;
+extern const char *const mi_lttng_element_kernel_probe_location_symbol_offset_name;
+extern const char *const mi_lttng_element_kernel_probe_location_symbol_offset_offset;
+extern const char *const mi_lttng_element_kernel_probe_location_address;
+extern const char *const mi_lttng_element_kernel_probe_location_address_address;
 
 /* String related to userspace probe location. */
 extern const char *const mi_lttng_element_userspace_probe_location;
-extern const char
-               *const mi_lttng_element_userspace_probe_location_binary_path;
-extern const char
-               *const mi_lttng_element_userspace_probe_location_function;
-extern const char
-               *const mi_lttng_element_userspace_probe_location_function_name;
-extern const char
-               *const mi_lttng_element_userspace_probe_location_lookup_method;
-extern const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_function_default;
-extern const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_function_elf;
-extern const char *const
-               mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt;
-extern const char
-               *const mi_lttng_element_userspace_probe_location_tracepoint;
-extern const char *const
-               mi_lttng_element_userspace_probe_location_tracepoint_probe_name;
-extern const char *const
-               mi_lttng_element_userspace_probe_location_tracepoint_provider_name;
+extern const char *const mi_lttng_element_userspace_probe_location_binary_path;
+extern const char *const mi_lttng_element_userspace_probe_location_function;
+extern const char *const mi_lttng_element_userspace_probe_location_function_name;
+extern const char *const mi_lttng_element_userspace_probe_location_lookup_method;
+extern const char *const mi_lttng_element_userspace_probe_location_lookup_method_function_default;
+extern const char *const mi_lttng_element_userspace_probe_location_lookup_method_function_elf;
+extern const char *const mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt;
+extern const char *const mi_lttng_element_userspace_probe_location_tracepoint;
+extern const char *const mi_lttng_element_userspace_probe_location_tracepoint_probe_name;
+extern const char *const mi_lttng_element_userspace_probe_location_tracepoint_provider_name;
 
 /* String related to enum
  * lttng_userspace_probe_location_function_instrumentation_type */
-extern const char *const
-               mi_lttng_element_userspace_probe_location_function_instrumentation_type;
-extern const char *const
-               mi_lttng_userspace_probe_location_function_instrumentation_type_entry;
+extern const char *const mi_lttng_element_userspace_probe_location_function_instrumentation_type;
+extern const char *const mi_lttng_userspace_probe_location_function_instrumentation_type_entry;
 
 /* String related to trigger */
 extern const char *const mi_lttng_element_triggers;
@@ -386,18 +344,15 @@ extern const char *const mi_lttng_element_trigger_owner_uid;
 
 /* String related to error_query. */
 extern const char *const mi_lttng_element_error_query_result;
-extern const char
-               *const mi_lttng_element_error_query_result_counter;
-extern const char
-               *const mi_lttng_element_error_query_result_counter_value;
-extern const char
-               *const mi_lttng_element_error_query_result_description;
+extern const char *const mi_lttng_element_error_query_result_counter;
+extern const char *const mi_lttng_element_error_query_result_counter_value;
+extern const char *const mi_lttng_element_error_query_result_description;
 extern const char *const mi_lttng_element_error_query_result_name;
 extern const char *const mi_lttng_element_error_query_result_type;
 extern const char *const mi_lttng_element_error_query_results;
 
 /* String related to add-context command */
-extern const char * const mi_lttng_element_context_symbol;
+extern const char *const mi_lttng_element_context_symbol;
 
 /* Utility string function  */
 const char *mi_lttng_loglevel_string(int value, enum lttng_domain_type domain);
@@ -407,7 +362,7 @@ const char *mi_lttng_domaintype_string(enum lttng_domain_type value);
 const char *mi_lttng_buffertype_string(enum lttng_buffer_type value);
 const char *mi_lttng_rotation_state_string(enum lttng_rotation_state value);
 const char *mi_lttng_trace_archive_location_relay_protocol_type_string(
-               enum lttng_trace_archive_location_relay_protocol_type value);
+       enum lttng_trace_archive_location_relay_protocol_type value);
 
 /*
  * Create an instance of a machine interface writer.
@@ -460,8 +415,7 @@ int mi_lttng_writer_command_close(struct mi_writer *writer);
  * Returns zero if the XML document could be closed cleanly.
  * Negative values indicate an error.
  */
-int mi_lttng_writer_open_element(struct mi_writer *writer,
-               const char *element_name);
+int mi_lttng_writer_open_element(struct mi_writer *writer, const char *element_name);
 
 /*
  * Close the current element tag.
@@ -482,8 +436,7 @@ int mi_lttng_writer_close_element(struct mi_writer *writer);
  * Returns zero if the XML document could be closed cleanly.
  * Negative values indicate an error.
  */
-int mi_lttng_close_multi_element(struct mi_writer *writer,
-               unsigned int nb_element);
+int mi_lttng_close_multi_element(struct mi_writer *writer, unsigned int nb_element);
 
 /*
  * Write an element of type unsigned int.
@@ -496,7 +449,8 @@ int mi_lttng_close_multi_element(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_writer_write_element_unsigned_int(struct mi_writer *writer,
-               const char *element_name, uint64_t value);
+                                              const char *element_name,
+                                              uint64_t value);
 
 /*
  * Write an element of type signed int.
@@ -509,7 +463,8 @@ int mi_lttng_writer_write_element_unsigned_int(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_writer_write_element_signed_int(struct mi_writer *writer,
-               const char *element_name, int64_t value);
+                                            const char *element_name,
+                                            int64_t value);
 
 /*
  * Write an element of type boolean.
@@ -522,7 +477,8 @@ int mi_lttng_writer_write_element_signed_int(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_writer_write_element_bool(struct mi_writer *writer,
-               const char *element_name, int value);
+                                      const char *element_name,
+                                      int value);
 
 /*
  * Write an element of type string.
@@ -535,7 +491,8 @@ int mi_lttng_writer_write_element_bool(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_writer_write_element_string(struct mi_writer *writer,
-               const char *element_name, const char *value);
+                                        const char *element_name,
+                                        const char *value);
 
 /*
  * Write an element of type double.
@@ -548,8 +505,8 @@ int mi_lttng_writer_write_element_string(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_writer_write_element_double(struct mi_writer *writer,
-               const char *element_name,
-               double value);
+                                        const char *element_name,
+                                        double value);
 
 /*
  * Machine interface of struct version.
@@ -562,8 +519,10 @@ int mi_lttng_writer_write_element_double(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_version(struct mi_writer *writer, struct mi_lttng_version_data *version,
-               const char *lttng_description, const char *lttng_license);
+int mi_lttng_version(struct mi_writer *writer,
+                    struct mi_lttng_version_data *version,
+                    const char *lttng_description,
+                    const char *lttng_license);
 
 /*
  * Machine interface: open a sessions element.
@@ -589,8 +548,7 @@ int mi_lttng_sessions_open(struct mi_writer *writer);
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_session(struct mi_writer *writer,
-               struct lttng_session *session, int is_open);
+int mi_lttng_session(struct mi_writer *writer, const struct lttng_session *session, int is_open);
 
 /*
  * Machine interface: open a domains element.
@@ -617,8 +575,7 @@ int mi_lttng_domains_open(struct mi_writer *writer);
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_domain(struct mi_writer *writer,
-               struct lttng_domain *domain, int is_open);
+int mi_lttng_domain(struct mi_writer *writer, struct lttng_domain *domain, int is_open);
 
 /*
  * Machine interface: open a channels element.
@@ -645,8 +602,7 @@ int mi_lttng_channels_open(struct mi_writer *writer);
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_channel(struct mi_writer *writer,
-               struct lttng_channel *channel, int is_open);
+int mi_lttng_channel(struct mi_writer *writer, struct lttng_channel *channel, int is_open);
 
 /*
  * Machine interface of struct channel_attr.
@@ -657,27 +613,25 @@ int mi_lttng_channel(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_channel_attr(struct mi_writer *writer,
-               struct lttng_channel_attr *attr);
+int mi_lttng_channel_attr(struct mi_writer *writer, struct lttng_channel_attr *attr);
 
 /*
-* Machine interface for event common attributes.
-*
-* writer An instance of a mi writer.
-* event single trace event.
-*
-* The common attribute are:
-* - mi event element
-* - event name
-* - event type
-* - enabled tag
-* - event filter
-*
-* Returns zero if the element's value could be written.
-* Negative values indicate an error.
-*/
-int mi_lttng_event_common_attributes(struct mi_writer *writer,
-               struct lttng_event *event);
+ * Machine interface for event common attributes.
+ *
+ * writer An instance of a mi writer.
+ * event single trace event.
+ *
+ * The common attribute are:
+ * - mi event element
+ * - event name
+ * - event type
+ * - enabled tag
+ * - event filter
+ *
+ * Returns zero if the element's value could be written.
+ * Negative values indicate an error.
+ */
+int mi_lttng_event_common_attributes(struct mi_writer *writer, struct lttng_event *event);
 
 /*
  * Machine interface for kernel tracepoint event with a loglevel.
@@ -690,7 +644,8 @@ int mi_lttng_event_common_attributes(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_event_tracepoint_loglevel(struct mi_writer *writer,
-               struct lttng_event *event, enum lttng_domain_type domain);
+                                      struct lttng_event *event,
+                                      enum lttng_domain_type domain);
 
 /*
  * Machine interface for kernel tracepoint event with no loglevel.
@@ -701,8 +656,7 @@ int mi_lttng_event_tracepoint_loglevel(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_event_tracepoint_no_loglevel(struct mi_writer *writer,
-               struct lttng_event *event);
+int mi_lttng_event_tracepoint_no_loglevel(struct mi_writer *writer, struct lttng_event *event);
 
 /*
  * Machine interface for kernel function and probe event.
@@ -713,8 +667,7 @@ int mi_lttng_event_tracepoint_no_loglevel(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_event_function_probe(struct mi_writer *writer,
-               struct lttng_event *event);
+int mi_lttng_event_function_probe(struct mi_writer *writer, struct lttng_event *event);
 
 /*
  * Machine interface for kernel function entry event.
@@ -725,8 +678,7 @@ int mi_lttng_event_function_probe(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_event_function_entry(struct mi_writer *writer,
-               struct lttng_event *event);
+int mi_lttng_event_function_entry(struct mi_writer *writer, struct lttng_event *event);
 
 /*
  * Machine interface: open an events element.
@@ -758,8 +710,10 @@ int mi_lttng_events_open(struct mi_writer *writer);
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_event(struct mi_writer *writer, struct lttng_event *event,
-               int is_open, enum lttng_domain_type domain);
+int mi_lttng_event(struct mi_writer *writer,
+                  struct lttng_event *event,
+                  int is_open,
+                  enum lttng_domain_type domain);
 
 /*
  * Machine interface for struct lttng_event_field.
@@ -770,8 +724,7 @@ int mi_lttng_event(struct mi_writer *writer, struct lttng_event *event,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_event_field(struct mi_writer *writer,
-               struct lttng_event_field *field);
+int mi_lttng_event_field(struct mi_writer *writer, struct lttng_event_field *field);
 
 /*
  * Machine interface: open a event_fields element.
@@ -803,8 +756,8 @@ int mi_lttng_trackers_open(struct mi_writer *writer);
  *
  * Note: A targets element is also opened for each tracker definition
  */
-int mi_lttng_process_attribute_tracker_open(
-               struct mi_writer *writer, enum lttng_process_attr process_attr);
+int mi_lttng_process_attribute_tracker_open(struct mi_writer *writer,
+                                           enum lttng_process_attr process_attr);
 
 /*
  * Machine interface: open a PIDs element.
@@ -841,8 +794,7 @@ int mi_lttng_processes_open(struct mi_writer *writer);
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_process(struct mi_writer *writer, pid_t pid , const char *name,
-               int is_open);
+int mi_lttng_process(struct mi_writer *writer, pid_t pid, const char *name, int is_open);
 
 /*
  * TODO: move pid of lttng list -u to process semantic on mi api bump
@@ -860,8 +812,7 @@ int mi_lttng_process(struct mi_writer *writer, pid_t pid , const char *name,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_pid(struct mi_writer *writer, pid_t pid , const char *name,
-               int is_open);
+int mi_lttng_pid(struct mi_writer *writer, pid_t pid, const char *name, int is_open);
 
 /*
  * Machine interface: open a process attribute values element.
@@ -882,8 +833,8 @@ int mi_lttng_process_attr_values_open(struct mi_writer *writer);
  * Negative values indicate an error.
  */
 int mi_lttng_all_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               bool is_open);
+                                        enum lttng_process_attr process_attr,
+                                        bool is_open);
 
 /*
  * Machine interface for track/untrack of an integral process attribute value.
@@ -894,9 +845,9 @@ int mi_lttng_all_process_attribute_value(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_integral_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               int64_t value,
-               bool is_open);
+                                             enum lttng_process_attr process_attr,
+                                             int64_t value,
+                                             bool is_open);
 
 /*
  * Machine interface for track/untrack of a string process attribute value.
@@ -907,9 +858,9 @@ int mi_lttng_integral_process_attribute_value(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_string_process_attribute_value(struct mi_writer *writer,
-               enum lttng_process_attr process_attr,
-               const char *value,
-               bool is_open);
+                                           enum lttng_process_attr process_attr,
+                                           const char *value,
+                                           bool is_open);
 
 /*
  * Machine interface of a context.
@@ -924,8 +875,7 @@ int mi_lttng_string_process_attribute_value(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_context(struct mi_writer *writer,
-               struct lttng_event_context *context, int is_open);
+int mi_lttng_context(struct mi_writer *writer, struct lttng_event_context *context, int is_open);
 
 /*
  * Machine interface of a perf_counter_context.
@@ -938,7 +888,7 @@ int mi_lttng_context(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_perf_counter_context(struct mi_writer *writer,
-               struct lttng_event_perf_counter_ctx  *perf_context);
+                                 struct lttng_event_perf_counter_ctx *perf_context);
 
 /*
  * Machine interface of the snapshot list_output.
@@ -956,8 +906,7 @@ int mi_lttng_perf_counter_context(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_snapshot_output_session_name(struct mi_writer *writer,
-               const char *session_name);
+int mi_lttng_snapshot_output_session_name(struct mi_writer *writer, const char *session_name);
 
 /*
  * Machine interface of the snapshot output.
@@ -976,7 +925,7 @@ int mi_lttng_snapshot_output_session_name(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_snapshot_list_output(struct mi_writer *writer,
-               const struct lttng_snapshot_output *output);
+                                 const struct lttng_snapshot_output *output);
 
 /*
  * Machine interface of the output of the command snapshot del output
@@ -999,8 +948,10 @@ int mi_lttng_snapshot_list_output(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_snapshot_del_output(struct mi_writer *writer, int id,
-               const char *name, const char *current_session_name);
+int mi_lttng_snapshot_del_output(struct mi_writer *writer,
+                                int id,
+                                const char *name,
+                                const char *current_session_name);
 
 /*
  * Machine interface of the output of the command snapshot add output
@@ -1026,8 +977,9 @@ int mi_lttng_snapshot_del_output(struct mi_writer *writer, int id,
  * Negative values indicate an error.
  */
 int mi_lttng_snapshot_add_output(struct mi_writer *writer,
-               const char *current_session_name, const char *n_ptr,
-               struct lttng_snapshot_output *output);
+                                const char *current_session_name,
+                                const char *n_ptr,
+                                struct lttng_snapshot_output *output);
 
 /*
  * Machine interface of the output of the command snapshot
@@ -1047,8 +999,10 @@ int mi_lttng_snapshot_add_output(struct mi_writer *writer,
  * Returns zero if the element's value could be written.
  * Negative values indicate an error.
  */
-int mi_lttng_snapshot_record(struct mi_writer *writer, const char *url,
-               const char *cmdline_ctrl_url, const char *cmdline_data_url);
+int mi_lttng_snapshot_record(struct mi_writer *writer,
+                            const char *url,
+                            const char *cmdline_ctrl_url,
+                            const char *cmdline_data_url);
 
 /*
  * Machine interface representation of a session rotation schedule.
@@ -1064,7 +1018,7 @@ int mi_lttng_snapshot_record(struct mi_writer *writer, const char *url,
  * Negative values indicate an error.
  */
 int mi_lttng_rotation_schedule(struct mi_writer *writer,
-               const struct lttng_rotation_schedule *schedule);
+                              const struct lttng_rotation_schedule *schedule);
 
 /*
  * Machine interface of a session rotation schedule result.
@@ -1085,8 +1039,8 @@ int mi_lttng_rotation_schedule(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_rotation_schedule_result(struct mi_writer *writer,
-               const struct lttng_rotation_schedule *schedule,
-               bool success);
+                                     const struct lttng_rotation_schedule *schedule,
+                                     bool success);
 
 /*
  * Machine interface of a session rotation result.
@@ -1109,8 +1063,8 @@ int mi_lttng_rotation_schedule_result(struct mi_writer *writer,
  * Negative values indicate an error.
  */
 int mi_lttng_rotate(struct mi_writer *writer,
-               const char *session_name,
-               enum lttng_rotation_state rotation_state,
-               const struct lttng_trace_archive_location *location);
+                   const char *session_name,
+                   enum lttng_rotation_state rotation_state,
+                   const struct lttng_trace_archive_location *location);
 
 #endif /* _MI_LTTNG_H */
index 51e5693cd464fb2bb4ebd96c0c60862da6b5ca3d..b024a0c090935a49fce2682e54e80d17511ae239 100644 (file)
@@ -5,20 +5,20 @@
  *
  */
 
-#include <lttng/notification/notification-internal.hpp>
+#include <common/payload-view.hpp>
+#include <common/payload.hpp>
+
 #include <lttng/condition/condition-internal.hpp>
-#include <lttng/condition/evaluation-internal.hpp>
 #include <lttng/condition/condition.h>
+#include <lttng/condition/evaluation-internal.hpp>
 #include <lttng/condition/evaluation.h>
+#include <lttng/notification/notification-internal.hpp>
 #include <lttng/trigger/trigger-internal.hpp>
-#include <common/payload.hpp>
-#include <common/payload-view.hpp>
 
-struct lttng_notification *lttng_notification_create(
-               struct lttng_trigger *trigger,
-               struct lttng_evaluation *evaluation)
+struct lttng_notification *lttng_notification_create(struct lttng_trigger *trigger,
+                                                    struct lttng_evaluation *evaluation)
 {
-       struct lttng_notification *notification = NULL;
+       struct lttng_notification *notification = nullptr;
 
        if (!trigger || !evaluation) {
                goto end;
@@ -36,7 +36,7 @@ end:
 }
 
 int lttng_notification_serialize(const struct lttng_notification *notification,
-               struct lttng_payload *payload)
+                                struct lttng_payload *payload)
 {
        int ret;
        size_t header_offset, size_before_payload;
@@ -46,15 +46,14 @@ int lttng_notification_serialize(const struct lttng_notification *notification,
        notification_comm.length = 0;
 
        header_offset = payload->buffer.size;
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &notification_comm,
-                       sizeof(notification_comm));
+       ret = lttng_dynamic_buffer_append(
+               &payload->buffer, &notification_comm, sizeof(notification_comm));
        if (ret) {
                goto end;
        }
 
        size_before_payload = payload->buffer.size;
-       ret = lttng_trigger_serialize(notification->trigger,
-                       payload);
+       ret = lttng_trigger_serialize(notification->trigger, payload);
        if (ret) {
                goto end;
        }
@@ -69,20 +68,17 @@ int lttng_notification_serialize(const struct lttng_notification *notification,
        header->length = (uint32_t) (payload->buffer.size - size_before_payload);
 end:
        return ret;
-
 }
 
-ssize_t lttng_notification_create_from_payload(
-               struct lttng_payload_view *src_view,
-               struct lttng_notification **notification)
+ssize_t lttng_notification_create_from_payload(struct lttng_payload_view *src_view,
+                                              struct lttng_notification **notification)
 {
        ssize_t ret, notification_size = 0, trigger_size, evaluation_size;
-       struct lttng_trigger *trigger = NULL;
-       struct lttng_evaluation *evaluation = NULL;
+       struct lttng_trigger *trigger = nullptr;
+       struct lttng_evaluation *evaluation = nullptr;
        const struct lttng_notification_comm *notification_comm;
        const struct lttng_payload_view notification_comm_view =
-                       lttng_payload_view_from_view(
-                                       src_view, 0, sizeof(*notification_comm));
+               lttng_payload_view_from_view(src_view, 0, sizeof(*notification_comm));
 
        if (!src_view || !notification) {
                ret = -1;
@@ -100,11 +96,9 @@ ssize_t lttng_notification_create_from_payload(
        {
                /* struct lttng_condition */
                struct lttng_payload_view condition_view =
-                               lttng_payload_view_from_view(src_view,
-                                               notification_size, -1);
+                       lttng_payload_view_from_view(src_view, notification_size, -1);
 
-               trigger_size = lttng_trigger_create_from_payload(
-                               &condition_view, &trigger);
+               trigger_size = lttng_trigger_create_from_payload(&condition_view, &trigger);
        }
 
        if (trigger_size < 0) {
@@ -117,12 +111,10 @@ ssize_t lttng_notification_create_from_payload(
        {
                /* struct lttng_evaluation */
                struct lttng_payload_view evaluation_view =
-                               lttng_payload_view_from_view(src_view,
-                                               notification_size, -1);
+                       lttng_payload_view_from_view(src_view, notification_size, -1);
 
                evaluation_size = lttng_evaluation_create_from_payload(
-                               lttng_trigger_get_const_condition(trigger),
-                               &evaluation_view, &evaluation);
+                       lttng_trigger_get_const_condition(trigger), &evaluation_view, &evaluation);
        }
 
        if (evaluation_size < 0) {
@@ -133,8 +125,7 @@ ssize_t lttng_notification_create_from_payload(
        notification_size += evaluation_size;
 
        /* Unexpected size of inner-elements; the buffer is corrupted. */
-       if ((ssize_t) notification_comm->length !=
-                       trigger_size + evaluation_size) {
+       if ((ssize_t) notification_comm->length != trigger_size + evaluation_size) {
                ret = -1;
                goto error;
        }
@@ -165,38 +156,37 @@ void lttng_notification_destroy(struct lttng_notification *notification)
        free(notification);
 }
 
-const struct lttng_condition *lttng_notification_get_condition(
-               struct lttng_notification *notification)
+const struct lttng_condition *
+lttng_notification_get_condition(struct lttng_notification *notification)
 {
-       return notification ? lttng_trigger_get_const_condition(notification->trigger) : NULL;
+       return notification ? lttng_trigger_get_const_condition(notification->trigger) : nullptr;
 }
 
-const struct lttng_evaluation *lttng_notification_get_evaluation(
-               struct lttng_notification *notification)
+const struct lttng_evaluation *
+lttng_notification_get_evaluation(struct lttng_notification *notification)
 {
-       return notification ? notification->evaluation : NULL;
+       return notification ? notification->evaluation : nullptr;
 }
 
-const struct lttng_condition *lttng_notification_get_const_condition(
-               const struct lttng_notification *notification)
+const struct lttng_condition *
+lttng_notification_get_const_condition(const struct lttng_notification *notification)
 {
-       return notification ? lttng_trigger_get_const_condition(notification->trigger) : NULL;
+       return notification ? lttng_trigger_get_const_condition(notification->trigger) : nullptr;
 }
 
-const struct lttng_evaluation *lttng_notification_get_const_evaluation(
-               const struct lttng_notification *notification)
+const struct lttng_evaluation *
+lttng_notification_get_const_evaluation(const struct lttng_notification *notification)
 {
-       return notification ? notification->evaluation : NULL;
+       return notification ? notification->evaluation : nullptr;
 }
 
-const struct lttng_trigger *lttng_notification_get_const_trigger(
-               const struct lttng_notification *notification)
+const struct lttng_trigger *
+lttng_notification_get_const_trigger(const struct lttng_notification *notification)
 {
-       return notification ? notification->trigger : NULL;
+       return notification ? notification->trigger : nullptr;
 }
 
-const struct lttng_trigger *lttng_notification_get_trigger(
-               struct lttng_notification *notification)
+const struct lttng_trigger *lttng_notification_get_trigger(struct lttng_notification *notification)
 {
-       return notification ? notification->trigger : NULL;
+       return notification ? notification->trigger : nullptr;
 }
index f34c5991fdfd4be070a1362d1968c4b3b88d2526..69bba5be54254041b89e8f3f0213ac4e4d18ad9a 100644 (file)
  *
  * LTTNG_OPTIONAL_UNSET(&foo.b);
  */
-#define LTTNG_OPTIONAL(type) \
-       struct {             \
+#define LTTNG_OPTIONAL(type)    \
+       struct {                \
                uint8_t is_set; \
-               type value;  \
+               type value;     \
        }
 
 /*
  * Since this returns the 'optional' by value, it is not suitable for all
  * wrapped optional types. It is meant to be used with PODs.
  */
-#define LTTNG_OPTIONAL_GET(optional)                   \
-       ({                                              \
-               LTTNG_ASSERT((optional).is_set);                \
-               (optional).value;                       \
+#define LTTNG_OPTIONAL_GET(optional)             \
+       ({                                       \
+               LTTNG_ASSERT((optional).is_set); \
+               (optional).value;                \
        })
 
 /*
  * an optional value is set to LTTNG_ASSERT() that it is set when fecthing the
  * underlying value's address.
  */
-#define LTTNG_OPTIONAL_GET_PTR(optional)                       \
-       ({                                              \
-               LTTNG_ASSERT((optional).is_set);                \
-               &(optional).value;                      \
+#define LTTNG_OPTIONAL_GET_PTR(optional)         \
+       ({                                       \
+               LTTNG_ASSERT((optional).is_set); \
+               &(optional).value;               \
        })
 
 /*
  * The wrapped field is set to the value it would gave if it had static storage
  * duration.
  */
-#define LTTNG_OPTIONAL_INIT_UNSET {}
+#define LTTNG_OPTIONAL_INIT_UNSET \
+       {                         \
+       }
 
 /*
  * Initialize an optional field as 'set' with a given value.
  */
-#define LTTNG_OPTIONAL_INIT_VALUE(val) { .is_set = 1, .value = val }
+#define LTTNG_OPTIONAL_INIT_VALUE(val)      \
+       {                                   \
+               .is_set = 1, .value = (val) \
+       }
 
 /* Set the value of an optional field. */
-#define LTTNG_OPTIONAL_SET(field_ptr, val)     \
-       do {                                    \
-               (field_ptr)->is_set = 1;        \
-               (field_ptr)->value = (val);     \
+#define LTTNG_OPTIONAL_SET(field_ptr, val)  \
+       do {                                \
+               (field_ptr)->is_set = 1;    \
+               (field_ptr)->value = (val); \
        } while (0)
 
 /* Put an optional field in the "unset" (NULL-ed) state. */
-#define LTTNG_OPTIONAL_UNSET(field_ptr)                \
-       do {                                    \
-               (field_ptr)->is_set = 0;        \
+#define LTTNG_OPTIONAL_UNSET(field_ptr)  \
+       do {                             \
+               (field_ptr)->is_set = 0; \
        } while (0)
 
 #endif /* LTTNG_OPTIONAL_H */
index 61e78a5c1d7a583f11b92ce5cbe2e9da20f3c375..14611c2164812245f0d0a2c48a6675e80db40610 100644 (file)
@@ -8,8 +8,8 @@
  */
 
 #define _LGPL_SOURCE
-#include <common/macros.hpp>
 #include <common/common.hpp>
+#include <common/macros.hpp>
 #include <common/path.hpp>
 
 /*
  *
  * Return a newly-allocated string.
  */
-static
-char *utils_partial_realpath(const char *path)
+static char *utils_partial_realpath(const char *path)
 {
-       char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
+       char *cut_path = nullptr, *try_path = nullptr, *try_path_prev = nullptr;
        const char *next, *prev, *end;
-       char *resolved_path = NULL;
+       char *resolved_path = nullptr;
 
        /* Safety net */
-       if (path == NULL) {
+       if (path == nullptr) {
                goto error;
        }
 
@@ -40,7 +39,7 @@ char *utils_partial_realpath(const char *path)
         * the path given as argument
         */
        end = path + strlen(path);
-       if (*(end-1) == '/') {
+       if (*(end - 1) == '/') {
                end--;
        }
 
@@ -48,24 +47,24 @@ char *utils_partial_realpath(const char *path)
        next = path;
        prev = next;
        /* Only to ensure try_path is not NULL to enter the while */
-       try_path = (char *)next;
+       try_path = (char *) next;
 
        /* Resolve the canonical path of the first part of the path */
-       while (try_path != NULL && next != end) {
-               char *try_path_buf = NULL;
+       while (try_path != nullptr && next != end) {
+               char *try_path_buf = nullptr;
 
                /*
                 * If there is not any '/' left, we want to try with
                 * the full path
                 */
                next = strpbrk(next + 1, "/");
-               if (next == NULL) {
+               if (next == nullptr) {
                        next = end;
                }
 
                /* Cut the part we will be trying to resolve */
                cut_path = lttng_strndup(path, next - path);
-               if (cut_path == NULL) {
+               if (cut_path == nullptr) {
                        PERROR("lttng_strndup");
                        goto error;
                }
@@ -78,7 +77,7 @@ char *utils_partial_realpath(const char *path)
 
                /* Try to resolve this part */
                try_path = realpath((char *) cut_path, try_path_buf);
-               if (try_path == NULL) {
+               if (try_path == nullptr) {
                        free(try_path_buf);
                        /*
                         * There was an error, we just want to be assured it
@@ -96,7 +95,7 @@ char *utils_partial_realpath(const char *path)
                        }
                } else {
                        /* Save the place we are before trying the next step */
-                       try_path_buf = NULL;
+                       try_path_buf = nullptr;
                        free(try_path_prev);
                        try_path_prev = try_path;
                        prev = next;
@@ -104,12 +103,12 @@ char *utils_partial_realpath(const char *path)
 
                /* Free the allocated memory */
                free(cut_path);
-               cut_path = NULL;
+               cut_path = nullptr;
        }
 
        /* Allocate memory for the resolved path. */
        resolved_path = zmalloc<char>(LTTNG_PATH_MAX);
-       if (resolved_path == NULL) {
+       if (resolved_path == nullptr) {
                PERROR("zmalloc resolved path");
                goto error;
        }
@@ -118,7 +117,7 @@ char *utils_partial_realpath(const char *path)
         * If we were able to solve at least partially the path, we can concatenate
         * what worked and what didn't work
         */
-       if (try_path_prev != NULL) {
+       if (try_path_prev != nullptr) {
                /* If we risk to concatenate two '/', we remove one of them */
                if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
                        try_path_prev[strlen(try_path_prev) - 1] = '\0';
@@ -129,24 +128,23 @@ char *utils_partial_realpath(const char *path)
                 * path are pointers for the same memory space
                 */
                cut_path = strdup(prev);
-               if (cut_path == NULL) {
+               if (cut_path == nullptr) {
                        PERROR("strdup");
                        goto error;
                }
 
                /* Concatenate the strings */
-               snprintf(resolved_path, LTTNG_PATH_MAX, "%s%s",
-                               try_path_prev, cut_path);
+               snprintf(resolved_path, LTTNG_PATH_MAX, "%s%s", try_path_prev, cut_path);
 
                /* Free the allocated memory */
                free(cut_path);
                free(try_path_prev);
-               cut_path = NULL;
-               try_path_prev = NULL;
-       /*
-        * Else, we just copy the path in our resolved_path to
-        * return it as is
-        */
+               cut_path = nullptr;
+               try_path_prev = nullptr;
+               /*
+                * Else, we just copy the path in our resolved_path to
+                * return it as is
+                */
        } else {
                strncpy(resolved_path, path, LTTNG_PATH_MAX);
        }
@@ -161,11 +159,10 @@ error:
        if (try_path_prev != try_path) {
                free(try_path_prev);
        }
-       return NULL;
+       return nullptr;
 }
 
-static
-int expand_double_slashes_dot_and_dotdot(char *path)
+static int expand_double_slashes_dot_and_dotdot(char *path)
 {
        size_t expanded_path_len, path_len;
        const char *curr_char, *path_last_char, *next_slash, *prev_slash;
@@ -190,14 +187,14 @@ int expand_double_slashes_dot_and_dotdot(char *path)
                }
 
                next_slash = (const char *) memchr(curr_char, '/', path_last_char - curr_char);
-               if (next_slash == NULL) {
+               if (next_slash == nullptr) {
                        /* Reached the end of the provided path. */
                        next_slash = path_last_char;
                }
 
                /* Compute how long is the previous token. */
                curr_token_len = next_slash - curr_char;
-               switch(curr_token_len) {
+               switch (curr_token_len) {
                case 0:
                        /*
                         * The pointer has not move meaning that curr_char is
@@ -230,13 +227,14 @@ int expand_double_slashes_dot_and_dotdot(char *path)
                                 * previous forward slash and substract that
                                 * len to the resulting path.
                                 */
-                               prev_slash = (const char *) lttng_memrchr(path, '/', expanded_path_len);
+                               prev_slash =
+                                       (const char *) lttng_memrchr(path, '/', expanded_path_len);
                                /*
                                 * If prev_slash is NULL, we reached the
                                 * beginning of the path. We can't go back any
                                 * further.
                                 */
-                               if (prev_slash != NULL) {
+                               if (prev_slash != nullptr) {
                                        expanded_path_len = prev_slash - path;
                                }
                                continue;
@@ -274,22 +272,21 @@ error:
  * The returned string was allocated in the function, it is thus of
  * the responsibility of the caller to free this memory.
  */
-static
-char *_utils_expand_path(const char *path, bool keep_symlink)
+static char *_utils_expand_path(const char *path, bool keep_symlink)
 {
        int ret;
-       char *absolute_path = NULL;
+       char *absolute_path = nullptr;
        char *last_token;
        bool is_dot, is_dotdot;
 
        /* Safety net */
-       if (path == NULL) {
+       if (path == nullptr) {
                goto error;
        }
 
        /* Allocate memory for the absolute_path */
        absolute_path = zmalloc<char>(LTTNG_PATH_MAX);
-       if (absolute_path == NULL) {
+       if (absolute_path == nullptr) {
                PERROR("zmalloc expand path");
                goto error;
        }
@@ -316,11 +313,12 @@ char *_utils_expand_path(const char *path, bool keep_symlink)
                 * Get the number of character in the CWD and allocate an array
                 * to can hold it and the path provided by the caller.
                 */
-               ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s",
-                               current_working_dir, path);
+               ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s", current_working_dir, path);
                if (ret >= LTTNG_PATH_MAX) {
                        ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
-                                       current_working_dir, path, LTTNG_PATH_MAX);
+                           current_working_dir,
+                           path,
+                           LTTNG_PATH_MAX);
                        goto error;
                }
        }
@@ -370,7 +368,7 @@ char *_utils_expand_path(const char *path, bool keep_symlink)
 
 error:
        free(absolute_path);
-       return NULL;
+       return nullptr;
 }
 char *utils_expand_path(const char *path)
 {
index d5e67961b54b49b680993b9593986c3166638cea..0f41027bd0dcabb3389a0d80e8ac52ae14ef592b 100644 (file)
@@ -5,10 +5,12 @@
  *
  */
 
-#include <common/dynamic-array.hpp>
-#include <common/buffer-view.hpp>
 #include "payload-view.hpp"
 #include "payload.hpp"
+
+#include <common/buffer-view.hpp>
+#include <common/dynamic-array.hpp>
+
 #include <stddef.h>
 
 bool lttng_payload_view_is_valid(const struct lttng_payload_view *view)
@@ -16,25 +18,25 @@ bool lttng_payload_view_is_valid(const struct lttng_payload_view *view)
        return view && lttng_buffer_view_is_valid(&view->buffer);
 }
 
-struct lttng_payload_view lttng_payload_view_from_payload(
-               const struct lttng_payload *payload, size_t offset,
-               ptrdiff_t len)
+struct lttng_payload_view
+lttng_payload_view_from_payload(const struct lttng_payload *payload, size_t offset, ptrdiff_t len)
 {
-       return payload ? (struct lttng_payload_view) {
-               .buffer = lttng_buffer_view_from_dynamic_buffer(
-                       &payload->buffer, offset, len),
-               ._fd_handles = payload->_fd_handles,
-               ._iterator = {},
-       } : (struct lttng_payload_view) {
-               .buffer = {},
-               ._fd_handles = {},
-               ._iterator = {},
-       };
+       return payload ?
+               (struct lttng_payload_view){
+                       .buffer = lttng_buffer_view_from_dynamic_buffer(
+                               &payload->buffer, offset, len),
+                       ._fd_handles = payload->_fd_handles,
+                       ._iterator = {},
+               } :
+               (struct lttng_payload_view){
+                       .buffer = {},
+                       ._fd_handles = {},
+                       ._iterator = {},
+               };
 }
 
-struct lttng_payload_view lttng_payload_view_from_view(
-               struct lttng_payload_view *view, size_t offset,
-               ptrdiff_t len)
+struct lttng_payload_view
+lttng_payload_view_from_view(struct lttng_payload_view *view, size_t offset, ptrdiff_t len)
 {
        return view ? (struct lttng_payload_view) {
                .buffer = lttng_buffer_view_from_view(
@@ -53,50 +55,49 @@ struct lttng_payload_view lttng_payload_view_from_view(
 }
 
 struct lttng_payload_view lttng_payload_view_from_dynamic_buffer(
-               const struct lttng_dynamic_buffer *buffer, size_t offset,
-               ptrdiff_t len)
+       const struct lttng_dynamic_buffer *buffer, size_t offset, ptrdiff_t len)
 {
-       return buffer ? (struct lttng_payload_view) {
-               .buffer = lttng_buffer_view_from_dynamic_buffer(
-                       buffer, offset, len),
-               ._fd_handles = {},
-               ._iterator = {},
-       } : (struct lttng_payload_view) {
-               .buffer = {},
-               ._fd_handles = {},
-               ._iterator = {},
-       };
+       return buffer ?
+               (struct lttng_payload_view){
+                       .buffer = lttng_buffer_view_from_dynamic_buffer(buffer, offset, len),
+                       ._fd_handles = {},
+                       ._iterator = {},
+               } :
+               (struct lttng_payload_view){
+                       .buffer = {},
+                       ._fd_handles = {},
+                       ._iterator = {},
+               };
 }
 
-struct lttng_payload_view lttng_payload_view_from_buffer_view(
-               const struct lttng_buffer_view *view, size_t offset,
-               ptrdiff_t len)
+struct lttng_payload_view lttng_payload_view_from_buffer_view(const struct lttng_buffer_view *view,
+                                                             size_t offset,
+                                                             ptrdiff_t len)
 {
-       return view ? (struct lttng_payload_view) {
-               .buffer = lttng_buffer_view_from_view(
-                       view, offset, len),
-               ._fd_handles = {},
-               ._iterator = {},
-       } : (struct lttng_payload_view) {
-               .buffer = {},
-               ._fd_handles = {},
-               ._iterator = {},
-       };
+       return view ?
+               (struct lttng_payload_view){
+                       .buffer = lttng_buffer_view_from_view(view, offset, len),
+                       ._fd_handles = {},
+                       ._iterator = {},
+               } :
+               (struct lttng_payload_view){
+                       .buffer = {},
+                       ._fd_handles = {},
+                       ._iterator = {},
+               };
 }
 
-struct lttng_payload_view lttng_payload_view_init_from_buffer(
-       const char *src, size_t offset, ptrdiff_t len)
+struct lttng_payload_view
+lttng_payload_view_init_from_buffer(const char *src, size_t offset, ptrdiff_t len)
 {
-       return (struct lttng_payload_view) {
-               .buffer = lttng_buffer_view_init(
-                       src, offset, len),
+       return (struct lttng_payload_view){
+               .buffer = lttng_buffer_view_init(src, offset, len),
                ._fd_handles = {},
                ._iterator = {},
        };
 }
 
-int lttng_payload_view_get_fd_handle_count(
-               const struct lttng_payload_view *payload_view)
+int lttng_payload_view_get_fd_handle_count(const struct lttng_payload_view *payload_view)
 {
        int ret;
        size_t position;
@@ -112,17 +113,16 @@ int lttng_payload_view_get_fd_handle_count(
        }
 
        position = payload_view->_iterator.p_fd_handles_position ?
-                       *payload_view->_iterator.p_fd_handles_position :
-                       payload_view->_iterator.fd_handles_position;
+               *payload_view->_iterator.p_fd_handles_position :
+               payload_view->_iterator.fd_handles_position;
        ret = ret - (int) position;
 end:
        return ret;
 }
 
-struct fd_handle *lttng_payload_view_pop_fd_handle(
-               struct lttng_payload_view *view)
+struct fd_handle *lttng_payload_view_pop_fd_handle(struct lttng_payload_view *view)
 {
-       struct fd_handle *handle = NULL;
+       struct fd_handle *handle = nullptr;
        size_t fd_handle_count;
        size_t *pos;
 
@@ -135,11 +135,9 @@ struct fd_handle *lttng_payload_view_pop_fd_handle(
                goto end;
        }
 
-       pos = view->_iterator.p_fd_handles_position ?
-                       view->_iterator.p_fd_handles_position :
-                       &view->_iterator.fd_handles_position;
-       handle = (fd_handle *) lttng_dynamic_pointer_array_get_pointer(&view->_fd_handles,
-                       *pos);
+       pos = view->_iterator.p_fd_handles_position ? view->_iterator.p_fd_handles_position :
+                                                     &view->_iterator.fd_handles_position;
+       handle = (fd_handle *) lttng_dynamic_pointer_array_get_pointer(&view->_fd_handles, *pos);
        (*pos)++;
        fd_handle_get(handle);
 end:
index 06bb3d157a2c5fbec8c1882055995c133f791662..1980c0a2f53592204ae29e54297c211ebce64c8c 100644 (file)
@@ -75,9 +75,8 @@ bool lttng_payload_view_is_valid(const struct lttng_payload_view *view);
  *             cause the view to reference the whole payload from the
  *             offset provided.
  */
-struct lttng_payload_view lttng_payload_view_from_payload(
-               const struct lttng_payload *payload, size_t offset,
-               ptrdiff_t len);
+struct lttng_payload_view
+lttng_payload_view_from_payload(const struct lttng_payload *payload, size_t offset, ptrdiff_t len);
 
 /**
  * Return a payload view referencing a subset of a payload referenced by
@@ -89,9 +88,8 @@ struct lttng_payload_view lttng_payload_view_from_payload(
  *             cause the payload view to reference the whole payload view's
  *             buffer view from the offset provided.
  */
-struct lttng_payload_view lttng_payload_view_from_view(
-               struct lttng_payload_view *view, size_t offset,
-               ptrdiff_t len);
+struct lttng_payload_view
+lttng_payload_view_from_view(struct lttng_payload_view *view, size_t offset, ptrdiff_t len);
 
 /**
  * Return a payload view referencing a subset of a dynamic buffer.
@@ -106,8 +104,7 @@ struct lttng_payload_view lttng_payload_view_from_view(
  *             offset provided.
  */
 struct lttng_payload_view lttng_payload_view_from_dynamic_buffer(
-               const struct lttng_dynamic_buffer *buffer, size_t offset,
-               ptrdiff_t len);
+       const struct lttng_dynamic_buffer *buffer, size_t offset, ptrdiff_t len);
 /**
  *
  * Return a payload view referencing a subset of a dynamic buffer.
@@ -121,9 +118,9 @@ struct lttng_payload_view lttng_payload_view_from_dynamic_buffer(
  *             cause the payload view to reference the whole payload from the
  *             offset provided.
  */
-struct lttng_payload_view lttng_payload_view_from_buffer_view(
-               const struct lttng_buffer_view *view, size_t offset,
-               ptrdiff_t len);
+struct lttng_payload_view lttng_payload_view_from_buffer_view(const struct lttng_buffer_view *view,
+                                                             size_t offset,
+                                                             ptrdiff_t len);
 
 /**
  * Return a payload view referencing a subset of the memory referenced by a raw
@@ -136,8 +133,8 @@ struct lttng_payload_view lttng_payload_view_from_buffer_view(
  * Note that a payload view never assumes the ownership of the memory it
  * references.
  */
-struct lttng_payload_view lttng_payload_view_init_from_buffer(
-               const char *src, size_t offset, ptrdiff_t len);
+struct lttng_payload_view
+lttng_payload_view_init_from_buffer(const char *src, size_t offset, ptrdiff_t len);
 
 /**
  * Get the number of file descriptor handles left in a payload view.
@@ -146,8 +143,7 @@ struct lttng_payload_view lttng_payload_view_init_from_buffer(
  *
  * Returns the number of file descriptor handles left on success, -1 on error.
  */
-int lttng_payload_view_get_fd_handle_count(
-               const struct lttng_payload_view *payload_view);
+int lttng_payload_view_get_fd_handle_count(const struct lttng_payload_view *payload_view);
 
 /**
  * Pop an fd handle from a payload view.
@@ -158,7 +154,6 @@ int lttng_payload_view_get_fd_handle_count(
  *
  * Returns an fd_handle on success, -1 on error.
  */
-struct fd_handle *lttng_payload_view_pop_fd_handle(
-               struct lttng_payload_view *payload_view);
+struct fd_handle *lttng_payload_view_pop_fd_handle(struct lttng_payload_view *payload_view);
 
 #endif /* LTTNG_PAYLOAD_VIEW_H */
index fa07dae31c840c2fa7661088e9d35ed691e3bad0..ef095554585c934569b04cf7da76f512d51f195d 100644 (file)
@@ -6,12 +6,12 @@
  */
 
 #include "payload.hpp"
+
 #include <common/dynamic-array.hpp>
 #include <common/dynamic-buffer.hpp>
 #include <common/error.hpp>
 
-static
-void release_fd_handle_ref(void *ptr)
+static void release_fd_handle_ref(void *ptr)
 {
        struct fd_handle *fd_handle = (struct fd_handle *) ptr;
 
@@ -22,29 +22,24 @@ void lttng_payload_init(struct lttng_payload *payload)
 {
        LTTNG_ASSERT(payload);
        lttng_dynamic_buffer_init(&payload->buffer);
-       lttng_dynamic_pointer_array_init(&payload->_fd_handles,
-                       release_fd_handle_ref);
+       lttng_dynamic_pointer_array_init(&payload->_fd_handles, release_fd_handle_ref);
 }
 
-int lttng_payload_copy(const struct lttng_payload *src_payload,
-                      struct lttng_payload *dst_payload)
+int lttng_payload_copy(const struct lttng_payload *src_payload, struct lttng_payload *dst_payload)
 {
        int ret;
        size_t i;
 
-       ret = lttng_dynamic_buffer_append_buffer(
-                       &dst_payload->buffer, &src_payload->buffer);
+       ret = lttng_dynamic_buffer_append_buffer(&dst_payload->buffer, &src_payload->buffer);
        if (ret) {
                goto end;
        }
 
-       for (i = 0; i < lttng_dynamic_pointer_array_get_count(
-                                       &src_payload->_fd_handles);
-                       i++) {
+       for (i = 0; i < lttng_dynamic_pointer_array_get_count(&src_payload->_fd_handles); i++) {
                struct fd_handle *new_fd_handle;
                const struct fd_handle *src_fd_handle =
-                               (fd_handle *) lttng_dynamic_pointer_array_get_pointer(
-                                               &src_payload->_fd_handles, i);
+                       (fd_handle *) lttng_dynamic_pointer_array_get_pointer(
+                               &src_payload->_fd_handles, i);
 
                new_fd_handle = fd_handle_copy(src_fd_handle);
                if (!new_fd_handle) {
@@ -80,8 +75,7 @@ void lttng_payload_clear(struct lttng_payload *payload)
        lttng_dynamic_pointer_array_clear(&payload->_fd_handles);
 }
 
-int lttng_payload_push_fd_handle(struct lttng_payload *payload,
-               struct fd_handle *fd_handle)
+int lttng_payload_push_fd_handle(struct lttng_payload *payload, struct fd_handle *fd_handle)
 {
        int ret;
 
@@ -90,8 +84,7 @@ int lttng_payload_push_fd_handle(struct lttng_payload *payload,
                goto end;
        }
 
-       ret = lttng_dynamic_pointer_array_add_pointer(
-                       &payload->_fd_handles, fd_handle);
+       ret = lttng_dynamic_pointer_array_add_pointer(&payload->_fd_handles, fd_handle);
        if (ret) {
                goto end;
        }
index 9747f59ef3537eb6d699db76feeff945722cdb8a..0e27efa2c2799a1d6814e16983b6a7f5f8229c7c 100644 (file)
@@ -8,8 +8,8 @@
 #ifndef LTTNG_PAYLOAD_H
 #define LTTNG_PAYLOAD_H
 
-#include <common/dynamic-buffer.hpp>
 #include <common/dynamic-array.hpp>
+#include <common/dynamic-buffer.hpp>
 #include <common/fd-handle.hpp>
 
 /*
@@ -30,8 +30,7 @@ struct lttng_payload {
 void lttng_payload_init(struct lttng_payload *payload);
 
 /* Copy a payload. */
-int lttng_payload_copy(const struct lttng_payload *src_payload,
-               struct lttng_payload *dst_payload);
+int lttng_payload_copy(const struct lttng_payload *src_payload, struct lttng_payload *dst_payload);
 
 /* Release any memory and references held by the payload. */
 void lttng_payload_reset(struct lttng_payload *payload);
@@ -54,7 +53,6 @@ void lttng_payload_clear(struct lttng_payload *payload);
  *
  * Returns 0 on success, -1 on allocation error.
  */
-int lttng_payload_push_fd_handle(struct lttng_payload *payload,
-               struct fd_handle *fd_handle);
+int lttng_payload_push_fd_handle(struct lttng_payload *payload, struct fd_handle *fd_handle);
 
 #endif /* LTTNG_PAYLOAD_H */
index 8bf0c1ff33341e54728d3b0b196f62752fc536c6..63a20512d9c8e5bd0fb3012fa899245debf553a3 100644 (file)
@@ -6,14 +6,14 @@
  */
 
 #define _LGPL_SOURCE
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include "pipe.hpp"
 
 #include <common/common.hpp>
 
-#include "pipe.hpp"
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 /*
  * Lock read side of a pipe.
@@ -103,7 +103,7 @@ end:
        return ret_val;
 }
 
-static struct lttng_pipe *_pipe_create(void)
+static struct lttng_pipe *_pipe_create()
 {
        int ret;
        struct lttng_pipe *p;
@@ -115,12 +115,12 @@ static struct lttng_pipe *_pipe_create(void)
        }
        p->fd[0] = p->fd[1] = -1;
 
-       ret = pthread_mutex_init(&p->read_mutex, NULL);
+       ret = pthread_mutex_init(&p->read_mutex, nullptr);
        if (ret) {
                PERROR("pthread_mutex_init read lock pipe create");
                goto error_destroy;
        }
-       ret = pthread_mutex_init(&p->write_mutex, NULL);
+       ret = pthread_mutex_init(&p->write_mutex, nullptr);
        if (ret) {
                PERROR("pthread_mutex_init write lock pipe create");
                goto error_destroy_rmutex;
@@ -131,7 +131,7 @@ error_destroy_rmutex:
        (void) pthread_mutex_destroy(&p->read_mutex);
 error_destroy:
        free(p);
-       return NULL;
+       return nullptr;
 }
 
 static int _pipe_set_flags(struct lttng_pipe *pipe, int flags)
@@ -205,7 +205,7 @@ struct lttng_pipe *lttng_pipe_open(int flags)
        return p;
 error:
        lttng_pipe_destroy(p);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -213,8 +213,7 @@ error:
  *
  * Return a newly allocated lttng pipe on success or else NULL.
  */
-struct lttng_pipe *lttng_pipe_named_open(const char *path, mode_t mode,
-               int flags)
+struct lttng_pipe *lttng_pipe_named_open(const char *path, mode_t mode, int flags)
 {
        int ret, fd_r, fd_w;
        struct lttng_pipe *pipe;
@@ -255,7 +254,7 @@ struct lttng_pipe *lttng_pipe_named_open(const char *path, mode_t mode,
        return pipe;
 error:
        lttng_pipe_destroy(pipe);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -383,8 +382,7 @@ error:
  * Return "count" on success. Return < count on error. errno can be used
  * to check the actual error.
  */
-ssize_t lttng_pipe_write(struct lttng_pipe *pipe, const void *buf,
-               size_t count)
+ssize_t lttng_pipe_write(struct lttng_pipe *pipe, const void *buf, size_t count)
 {
        ssize_t ret;
 
index d46e65d6833a32b97228e7a76573aaca829e2b64..5249061f865ba12a66b842f614abf6316d2b5a3a 100644 (file)
@@ -8,8 +8,10 @@
 #ifndef LTTNG_PIPE_H
 #define LTTNG_PIPE_H
 
-#include <pthread.h>
 #include <common/macros.hpp>
+#include <common/make-unique-wrapper.hpp>
+
+#include <pthread.h>
 #include <sys/types.h>
 
 enum lttng_pipe_state {
@@ -17,7 +19,15 @@ enum lttng_pipe_state {
        LTTNG_PIPE_STATE_CLOSED = 2,
 };
 
+/* Close both side of pipe. */
+int lttng_pipe_close(struct lttng_pipe *pipe);
+void lttng_pipe_destroy(struct lttng_pipe *pipe);
+
 struct lttng_pipe {
+       using uptr = std::unique_ptr<
+               lttng_pipe,
+               lttng::memory::create_deleter_class<lttng_pipe, lttng_pipe_destroy>::deleter>;
+
        /* Read: 0, Write: 1. */
        int fd[2];
        /*
@@ -65,17 +75,12 @@ static inline int lttng_pipe_get_writefd(const struct lttng_pipe *pipe)
 }
 
 struct lttng_pipe *lttng_pipe_open(int flags);
-struct lttng_pipe *lttng_pipe_named_open(const char *path, mode_t mode,
-               int flags);
+struct lttng_pipe *lttng_pipe_named_open(const char *path, mode_t mode, int flags);
 int lttng_pipe_write_close(struct lttng_pipe *pipe);
 int lttng_pipe_read_close(struct lttng_pipe *pipe);
-/* Close both side of pipe. */
-int lttng_pipe_close(struct lttng_pipe *pipe);
-void lttng_pipe_destroy(struct lttng_pipe *pipe);
 
 ssize_t lttng_pipe_read(struct lttng_pipe *pipe, void *buf, size_t count);
-ssize_t lttng_pipe_write(struct lttng_pipe *pipe, const void *buf,
-               size_t count);
+ssize_t lttng_pipe_write(struct lttng_pipe *pipe, const void *buf, size_t count);
 /* Returns and releases the read end of the pipe. */
 int lttng_pipe_release_readfd(struct lttng_pipe *pipe);
 /* Returns and releases the write end of the pipe. */
index d19e3f3fbeb9ba066c19494ce209191859d2b495..7d037e47226cf2469503bf30b8073915fb134349 100644 (file)
@@ -10,8 +10,8 @@
 
 #include <common/exception.hpp>
 
-#include <pthread.h>
 #include <mutex>
+#include <pthread.h>
 
 namespace lttng {
 namespace pthread {
@@ -26,13 +26,17 @@ namespace details {
  */
 class mutex {
 public:
-       mutex(pthread_mutex_t& mutex_p) : _mutex{mutex_p}
+       explicit mutex(pthread_mutex_t& mutex_p) : _mutex(mutex_p)
        {
        }
 
+       ~mutex() = default;
+
        /* "Not copyable" and "not moveable" Mutex requirements. */
-       mutex(mutex const &) = delete;
-       mutex &operator=(mutex const &) = delete;
+       mutex(mutex const&) = delete;
+       mutex(mutex&&) = delete;
+       mutex& operator=(mutex const&) = delete;
+       mutex& operator=(mutex&&) = delete;
 
        void lock()
        {
@@ -76,11 +80,16 @@ private:
  */
 class lock_guard {
 public:
-       lock_guard(pthread_mutex_t& mutex) : _mutex{mutex}, _guard(_mutex)
+       explicit lock_guard(pthread_mutex_t& mutex) : _mutex(mutex), _guard(_mutex)
        {
        }
 
-       lock_guard(const lock_guard &) = delete;
+       ~lock_guard() = default;
+
+       lock_guard(const lock_guard&) = delete;
+       lock_guard(lock_guard&&) = delete;
+       lock_guard& operator=(const lock_guard&) = delete;
+       lock_guard& operator=(lock_guard&&) = delete;
 
 private:
        details::mutex _mutex;
diff --git a/src/common/random.cpp b/src/common/random.cpp
new file mode 100644 (file)
index 0000000..ba9d937
--- /dev/null
@@ -0,0 +1,207 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include <common/error.hpp>
+#include <common/file-descriptor.hpp>
+#include <common/format.hpp>
+#include <common/hashtable/utils.hpp>
+#include <common/random.hpp>
+#include <common/readwrite.hpp>
+#include <common/time.hpp>
+
+#include <lttng/constant.h>
+
+#include <fcntl.h>
+
+#ifdef HAVE_SYS_SYSCALL_H
+#include <sys/syscall.h>
+#endif
+
+#define LTTNG_THROW_RANDOM_PRODUCTION_ERROR(msg) \
+       throw lttng::random::production_error(msg, __FILE__, __func__, __LINE__)
+
+namespace {
+/* getrandom is available in Linux >= 3.17. */
+#if defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H)
+
+#include <sys/random.h>
+
+/* A glibc wrapper is provided only for glibc >= 2.25. */
+#if defined(HAVE_GETRANDOM)
+/* Simply use the existing wrapper, passing the non-block flag. */
+ssize_t _call_getrandom_nonblock(char *out_data, std::size_t size)
+{
+       return getrandom(out_data, size, GRND_NONBLOCK);
+}
+#else
+ssize_t _call_getrandom_nonblock(char *out_data, std::size_t size)
+{
+       const int grnd_nonblock_flag = 0x1;
+
+       auto ret = syscall(SYS_getrandom, out_data, size, grnd_nonblock_flag);
+       if (ret < 0) {
+               errno = -ret;
+               ret = -1;
+       }
+
+       return ret;
+}
+#endif /* defined(HAVE_GETRANDOM) */
+
+/* Returns either with a full read or throws. */
+void getrandom_nonblock(char *out_data, std::size_t size)
+{
+       /*
+        * Since GRND_RANDOM is _not_ used, a partial read can only be caused
+        * by a signal interruption. In this case, retry.
+        */
+       ssize_t ret;
+
+       do {
+               ret = _call_getrandom_nonblock(out_data, size);
+       } while ((ret > 0 && ret != size) || (ret == -1 && errno == EINTR));
+
+       if (ret < 0) {
+               LTTNG_THROW_POSIX(
+                       lttng::format("Failed to get true random data using getrandom(): size={}",
+                                     size),
+                       errno);
+       }
+}
+#elif defined(HAVE_ARC4RANDOM)
+
+#include <stdlib.h>
+
+/*
+ * According to the MacOS / FreeBSD manpage, this function never fails nor blocks.
+ */
+void getrandom_nonblock(char *out_data, std::size_t size)
+{
+       arc4random_buf(out_data, size);
+}
+#else /* defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H) */
+__attribute__((noreturn)) void getrandom_nonblock(char *out_data __attribute__((unused)),
+                                                 std::size_t size __attribute__((unused)))
+{
+       LTTNG_THROW_RANDOM_PRODUCTION_ERROR("getrandom() is not supported by this platform");
+}
+#endif /* defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H) */
+
+lttng::random::seed_t produce_pseudo_random_seed()
+{
+       int ret;
+       struct timespec real_time = {};
+       struct timespec monotonic_time = {};
+       unsigned long hash_seed;
+       char hostname[LTTNG_HOST_NAME_MAX] = {};
+       unsigned long seed;
+
+       ret = clock_gettime(CLOCK_REALTIME, &real_time);
+       if (ret) {
+               LTTNG_THROW_POSIX("Failed to read real time while generating pseudo-random seed",
+                                 errno);
+       }
+
+       ret = clock_gettime(CLOCK_MONOTONIC, &monotonic_time);
+       if (ret) {
+               LTTNG_THROW_POSIX(
+                       "Failed to read monotonic time while generating pseudo-random seed", errno);
+       }
+
+       ret = gethostname(hostname, sizeof(hostname));
+       if (ret) {
+               LTTNG_THROW_POSIX("Failed to get host name while generating pseudo-random seed",
+                                 errno);
+       }
+
+       hash_seed = (unsigned long) real_time.tv_nsec ^ (unsigned long) real_time.tv_sec ^
+               (unsigned long) monotonic_time.tv_nsec ^ (unsigned long) monotonic_time.tv_sec;
+       seed = hash_key_ulong((void *) real_time.tv_sec, hash_seed);
+       seed ^= hash_key_ulong((void *) real_time.tv_nsec, hash_seed);
+       seed ^= hash_key_ulong((void *) monotonic_time.tv_sec, hash_seed);
+       seed ^= hash_key_ulong((void *) monotonic_time.tv_nsec, hash_seed);
+
+       const unsigned long pid = getpid();
+       seed ^= hash_key_ulong((void *) pid, hash_seed);
+       seed ^= hash_key_str(hostname, hash_seed);
+
+       return static_cast<lttng::random::seed_t>(seed);
+}
+
+lttng::random::seed_t produce_random_seed_from_urandom()
+{
+       /*
+        * Open /dev/urandom as a file_descriptor, or throw on error. The
+        * lambda is used to reduce the scope of the raw fd as much as possible.
+        */
+       lttng::file_descriptor urandom{ []() {
+               const auto urandom_raw_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+
+               if (urandom_raw_fd < 0) {
+                       LTTNG_THROW_POSIX("Failed to open `/dev/urandom`", errno);
+               }
+
+               return urandom_raw_fd;
+       }() };
+
+       lttng::random::seed_t seed;
+       try {
+               urandom.read(&seed, sizeof(seed));
+       } catch (const std::exception& e) {
+               LTTNG_THROW_RANDOM_PRODUCTION_ERROR(lttng::format(
+                       "Failed to read from `/dev/urandom`: size={}: {}", sizeof(seed), e.what()));
+       }
+
+       return seed;
+}
+
+} /* namespace */
+
+lttng::random::production_error::production_error(const std::string& msg,
+                                                 const char *file_name,
+                                                 const char *function_name,
+                                                 unsigned int line_number) :
+       lttng::runtime_error(msg, file_name, function_name, line_number)
+{
+}
+
+lttng::random::seed_t lttng::random::produce_true_random_seed()
+{
+       lttng::random::seed_t seed;
+
+       getrandom_nonblock(reinterpret_cast<char *>(&seed), sizeof(seed));
+       return seed;
+}
+
+lttng::random::seed_t lttng::random::produce_best_effort_random_seed()
+{
+       try {
+               return lttng::random::produce_true_random_seed();
+       } catch (const std::exception& e) {
+               WARN("%s",
+                    lttng::format(
+                            "Failed to produce a random seed using getrandom(), falling back to pseudo-random device seed generation which will block until its pool is initialized: {}",
+                            e.what())
+                            .c_str());
+       }
+
+       try {
+               /*
+                * Can fail for various reasons, including not being accessible
+                * under some containerized environments.
+                */
+               produce_random_seed_from_urandom();
+       } catch (const std::exception& e) {
+               WARN("%s",
+                    lttng::format("Failed to produce a random seed from the urandom device: {}",
+                                  e.what())
+                            .c_str());
+       }
+
+       /* Fallback to time-based seed generation. */
+       return produce_pseudo_random_seed();
+}
diff --git a/src/common/random.hpp b/src/common/random.hpp
new file mode 100644 (file)
index 0000000..7ba6ede
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_RANDOM_H
+#define LTTNG_RANDOM_H
+
+#include "exception.hpp"
+
+#include <cstddef>
+#include <string>
+
+namespace lttng {
+namespace random {
+
+using seed_t = unsigned int;
+
+class production_error : public ::lttng::runtime_error {
+public:
+       explicit production_error(const std::string& msg,
+                                 const char *file_name,
+                                 const char *function_name,
+                                 unsigned int line_number);
+};
+
+/*
+ * Get a seed from a reliable source of randomness without blocking, raising
+ * an exception on failure.
+ */
+seed_t produce_true_random_seed();
+
+/*
+ * Get a random seed making a best-effort to use a true randomness source,
+ * but falling back to a pseudo-random seed based on the time and various system
+ * configuration values on failure.
+ *
+ * Note that this function attempts to use the urandom device, which will block
+ * in the unlikely event that its pool is uninitialized, on platforms that don't
+ * provide getrandom().
+ */
+seed_t produce_best_effort_random_seed();
+
+} /* namespace random */
+} /* namespace lttng */
+
+#endif /* LTTNG_RANDOM_H */
index 8e901c9fec81f0027d120064ed90572765710ea6..a9671a5d9e736df7a0d9dbf5b26c55285d903d14 100644 (file)
@@ -6,12 +6,12 @@
  */
 
 #define _LGPL_SOURCE
-#include <limits.h>
-#include <unistd.h>
+#include "readwrite.hpp"
 
 #include <common/compat/errno.hpp>
 
-#include "readwrite.hpp"
+#include <limits.h>
+#include <unistd.h>
 
 /*
  * lttng_read and lttng_write take care of EINTR and partial read/write.
@@ -40,7 +40,7 @@ ssize_t lttng_read(int fd, void *buf, size_t count)
                ret = read(fd, (char *) buf + i, count - i);
                if (ret < 0) {
                        if (errno == EINTR) {
-                               continue;       /* retry operation */
+                               continue; /* retry operation */
                        } else {
                                goto error;
                        }
@@ -77,7 +77,7 @@ ssize_t lttng_write(int fd, const void *buf, size_t count)
                ret = write(fd, (char *) buf + i, count - i);
                if (ret < 0) {
                        if (errno == EINTR) {
-                               continue;       /* retry operation */
+                               continue; /* retry operation */
                        } else {
                                goto error;
                        }
index 1818fdb261f6f7c53f1f1bb788014ec8201c1f25..d3f80929d6cfcf4bb6208559009cca790323b746 100644 (file)
@@ -8,9 +8,10 @@
  *
  */
 
-#include <unistd.h>
 #include <common/macros.hpp>
 
+#include <unistd.h>
+
 /*
  * lttng_read and lttng_write take care of EINTR and partial read/write.
  * Upon success, they return the "count" received as parameter.
index 12658dc6856655320203e84e8e542d97130876c5..59b90b4eaa315bb6ec23d182238da47c79997fae 100644 (file)
@@ -6,25 +6,24 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <inttypes.h>
+#include "relayd.hpp"
 
 #include <common/common.hpp>
-#include <common/defaults.hpp>
 #include <common/compat/endian.hpp>
 #include <common/compat/string.hpp>
-#include <common/sessiond-comm/relayd.hpp>
+#include <common/defaults.hpp>
 #include <common/index/ctf-index.hpp>
-#include <common/trace-chunk.hpp>
+#include <common/sessiond-comm/relayd.hpp>
 #include <common/string-utils/format.hpp>
+#include <common/trace-chunk.hpp>
 
-#include "relayd.hpp"
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
 
-static
-bool relayd_supports_chunks(const struct lttcomm_relayd_sock *sock)
+static bool relayd_supports_chunks(const struct lttcomm_relayd_sock *sock)
 {
        if (sock->major > 2) {
                return true;
@@ -34,8 +33,7 @@ bool relayd_supports_chunks(const struct lttcomm_relayd_sock *sock)
        return false;
 }
 
-static
-bool relayd_supports_get_configuration(const struct lttcomm_relayd_sock *sock)
+static bool relayd_supports_get_configuration(const struct lttcomm_relayd_sock *sock)
 {
        if (sock->major > 2) {
                return true;
@@ -49,8 +47,10 @@ bool relayd_supports_get_configuration(const struct lttcomm_relayd_sock *sock)
  * Send command. Fill up the header and append the data.
  */
 static int send_command(struct lttcomm_relayd_sock *rsock,
-               enum lttcomm_relayd_command cmd, const void *data, size_t size,
-               int flags)
+                       enum lttcomm_relayd_command cmd,
+                       const void *data,
+                       size_t size,
+                       int flags)
 {
        int ret;
        struct lttcomm_relayd_hdr header;
@@ -66,7 +66,7 @@ static int send_command(struct lttcomm_relayd_sock *rsock,
        }
 
        buf = calloc<char>(buf_size);
-       if (buf == NULL) {
+       if (buf == nullptr) {
                PERROR("zmalloc relayd send command buf");
                ret = -1;
                goto alloc_error;
@@ -87,12 +87,14 @@ static int send_command(struct lttcomm_relayd_sock *rsock,
        }
 
        DBG3("Relayd sending command %s of size %" PRIu64,
-                       lttcomm_relayd_command_str(cmd), buf_size);
+            lttcomm_relayd_command_str(cmd),
+            buf_size);
        ret = rsock->sock.ops->sendmsg(&rsock->sock, buf, buf_size, flags);
        if (ret < 0) {
                PERROR("Failed to send command %s of size %" PRIu64,
-                               lttcomm_relayd_command_str(cmd), buf_size);
-       ret = rsock->sock.ops->sendmsg(&rsock->sock, buf, buf_size, flags);
+                      lttcomm_relayd_command_str(cmd),
+                      buf_size);
+               ret = rsock->sock.ops->sendmsg(&rsock->sock, buf, buf_size, flags);
                ret = -errno;
                goto error;
        }
@@ -123,7 +125,9 @@ static int recv_reply(struct lttcomm_relayd_sock *rsock, void *data, size_t size
                        DBG("Socket %d has performed an orderly shutdown", rsock->sock.fd);
                } else {
                        DBG("Receiving reply failed on sock %d for size %zu with ret %d",
-                                       rsock->sock.fd, size, ret);
+                           rsock->sock.fd,
+                           size,
+                           ret);
                }
                /* Always return -1 here and the caller can use errno. */
                ret = -1;
@@ -141,16 +145,21 @@ error:
  * payload size is introduced.
  */
 static int relayd_create_session_2_11(struct lttcomm_relayd_sock *rsock,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               unsigned int snapshot, uint64_t sessiond_session_id,
-               const lttng_uuid& sessiond_uuid, const uint64_t *current_chunk_id,
-               time_t creation_time, bool session_name_contains_creation_time,
-               struct lttcomm_relayd_create_session_reply_2_11 *reply,
-               char *output_path)
+                                     const char *session_name,
+                                     const char *hostname,
+                                     const char *base_path,
+                                     int session_live_timer,
+                                     unsigned int snapshot,
+                                     uint64_t sessiond_session_id,
+                                     const lttng_uuid& sessiond_uuid,
+                                     const uint64_t *current_chunk_id,
+                                     time_t creation_time,
+                                     bool session_name_contains_creation_time,
+                                     struct lttcomm_relayd_create_session_reply_2_11 *reply,
+                                     char *output_path)
 {
        int ret;
-       struct lttcomm_relayd_create_session_2_11 *msg = NULL;
+       struct lttcomm_relayd_create_session_2_11 *msg = nullptr;
        size_t session_name_len;
        size_t hostname_len;
        size_t base_path_len;
@@ -205,8 +214,7 @@ static int relayd_create_session_2_11(struct lttcomm_relayd_sock *rsock,
        msg->session_id = htobe64(sessiond_session_id);
        msg->session_name_contains_creation_time = session_name_contains_creation_time;
        if (current_chunk_id) {
-               LTTNG_OPTIONAL_SET(&msg->current_chunk_id,
-                               htobe64(*current_chunk_id));
+               LTTNG_OPTIONAL_SET(&msg->current_chunk_id, htobe64(*current_chunk_id));
        }
 
        msg->creation_time = htobe64((uint64_t) creation_time);
@@ -225,8 +233,10 @@ static int relayd_create_session_2_11(struct lttcomm_relayd_sock *rsock,
        reply->generic.ret_code = be32toh(reply->generic.ret_code);
        reply->output_path_length = be32toh(reply->output_path_length);
        if (reply->output_path_length >= LTTNG_PATH_MAX) {
-               ERR("Invalid session output path length in reply (%" PRIu32 " bytes) exceeds maximal allowed length (%d bytes)",
-                               reply->output_path_length, LTTNG_PATH_MAX);
+               ERR("Invalid session output path length in reply (%" PRIu32
+                   " bytes) exceeds maximal allowed length (%d bytes)",
+                   reply->output_path_length,
+                   LTTNG_PATH_MAX);
                ret = -1;
                goto error;
        }
@@ -243,15 +253,16 @@ error:
  * support the live reading capability.
  */
 static int relayd_create_session_2_4(struct lttcomm_relayd_sock *rsock,
-               const char *session_name, const char *hostname,
-               int session_live_timer, unsigned int snapshot,
-               struct lttcomm_relayd_status_session *reply)
+                                    const char *session_name,
+                                    const char *hostname,
+                                    int session_live_timer,
+                                    unsigned int snapshot,
+                                    struct lttcomm_relayd_status_session *reply)
 {
        int ret;
        struct lttcomm_relayd_create_session_2_4 msg;
 
-       if (lttng_strncpy(msg.session_name, session_name,
-                       sizeof(msg.session_name))) {
+       if (lttng_strncpy(msg.session_name, session_name, sizeof(msg.session_name))) {
                ret = -1;
                goto error;
        }
@@ -283,12 +294,12 @@ error:
  * RELAYD_CREATE_SESSION from 2.1 to 2.3.
  */
 static int relayd_create_session_2_1(struct lttcomm_relayd_sock *rsock,
-               struct lttcomm_relayd_status_session *reply)
+                                    struct lttcomm_relayd_status_session *reply)
 {
        int ret;
 
        /* Send command */
-       ret = send_command(rsock, RELAYD_CREATE_SESSION, NULL, 0, 0);
+       ret = send_command(rsock, RELAYD_CREATE_SESSION, nullptr, 0, 0);
        if (ret < 0) {
                goto error;
        }
@@ -312,14 +323,18 @@ error:
  * a lttng error code from the relayd.
  */
 int relayd_create_session(struct lttcomm_relayd_sock *rsock,
-               uint64_t *relayd_session_id,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               unsigned int snapshot, uint64_t sessiond_session_id,
-               const lttng_uuid& sessiond_uuid,
-               const uint64_t *current_chunk_id,
-               time_t creation_time, bool session_name_contains_creation_time,
-               char *output_path)
+                         uint64_t *relayd_session_id,
+                         const char *session_name,
+                         const char *hostname,
+                         const char *base_path,
+                         int session_live_timer,
+                         unsigned int snapshot,
+                         uint64_t sessiond_session_id,
+                         const lttng_uuid& sessiond_uuid,
+                         const uint64_t *current_chunk_id,
+                         time_t creation_time,
+                         bool session_name_contains_creation_time,
+                         char *output_path)
 {
        int ret;
        struct lttcomm_relayd_create_session_reply_2_11 reply = {};
@@ -334,17 +349,23 @@ int relayd_create_session(struct lttcomm_relayd_sock *rsock,
                ret = relayd_create_session_2_1(rsock, &reply.generic);
        } else if (rsock->minor >= 4 && rsock->minor < 11) {
                /* From 2.4 to 2.10 */
-               ret = relayd_create_session_2_4(rsock, session_name,
-                               hostname, session_live_timer, snapshot,
-                               &reply.generic);
+               ret = relayd_create_session_2_4(
+                       rsock, session_name, hostname, session_live_timer, snapshot, &reply.generic);
        } else {
                /* From 2.11 to ... */
-               ret = relayd_create_session_2_11(rsock, session_name,
-                               hostname, base_path, session_live_timer, snapshot,
-                               sessiond_session_id, sessiond_uuid,
-                               current_chunk_id, creation_time,
-                               session_name_contains_creation_time,
-                               &reply, output_path);
+               ret = relayd_create_session_2_11(rsock,
+                                                session_name,
+                                                hostname,
+                                                base_path,
+                                                session_live_timer,
+                                                snapshot,
+                                                sessiond_session_id,
+                                                sessiond_uuid,
+                                                current_chunk_id,
+                                                creation_time,
+                                                session_name_contains_creation_time,
+                                                &reply,
+                                                output_path);
        }
 
        if (ret < 0) {
@@ -354,8 +375,7 @@ int relayd_create_session(struct lttcomm_relayd_sock *rsock,
        /* Return session id or negative ret code. */
        if (reply.generic.ret_code != LTTNG_OK) {
                ret = -1;
-               ERR("Relayd create session replied error %d",
-                       reply.generic.ret_code);
+               ERR("Relayd create session replied error %d", reply.generic.ret_code);
                goto error;
        } else {
                ret = 0;
@@ -369,20 +389,19 @@ error:
 }
 
 static int relayd_add_stream_2_1(struct lttcomm_relayd_sock *rsock,
-               const char *channel_name, const char *pathname)
+                                const char *channel_name,
+                                const char *pathname)
 {
        int ret;
        struct lttcomm_relayd_add_stream msg;
 
        memset(&msg, 0, sizeof(msg));
-       if (lttng_strncpy(msg.channel_name, channel_name,
-                               sizeof(msg.channel_name))) {
+       if (lttng_strncpy(msg.channel_name, channel_name, sizeof(msg.channel_name))) {
                ret = -1;
                goto error;
        }
 
-       if (lttng_strncpy(msg.pathname, pathname,
-                               sizeof(msg.pathname))) {
+       if (lttng_strncpy(msg.pathname, pathname, sizeof(msg.pathname))) {
                ret = -1;
                goto error;
        }
@@ -399,21 +418,21 @@ error:
 }
 
 static int relayd_add_stream_2_2(struct lttcomm_relayd_sock *rsock,
-               const char *channel_name, const char *pathname,
-               uint64_t tracefile_size, uint64_t tracefile_count)
+                                const char *channel_name,
+                                const char *pathname,
+                                uint64_t tracefile_size,
+                                uint64_t tracefile_count)
 {
        int ret;
        struct lttcomm_relayd_add_stream_2_2 msg;
 
        memset(&msg, 0, sizeof(msg));
        /* Compat with relayd 2.2 to 2.10 */
-       if (lttng_strncpy(msg.channel_name, channel_name,
-                               sizeof(msg.channel_name))) {
+       if (lttng_strncpy(msg.channel_name, channel_name, sizeof(msg.channel_name))) {
                ret = -1;
                goto error;
        }
-       if (lttng_strncpy(msg.pathname, pathname,
-                               sizeof(msg.pathname))) {
+       if (lttng_strncpy(msg.pathname, pathname, sizeof(msg.pathname))) {
                ret = -1;
                goto error;
        }
@@ -431,12 +450,14 @@ error:
 }
 
 static int relayd_add_stream_2_11(struct lttcomm_relayd_sock *rsock,
-               const char *channel_name, const char *pathname,
-               uint64_t tracefile_size, uint64_t tracefile_count,
-               uint64_t trace_archive_id)
+                                 const char *channel_name,
+                                 const char *pathname,
+                                 uint64_t tracefile_size,
+                                 uint64_t tracefile_count,
+                                 uint64_t trace_archive_id)
 {
        int ret;
-       struct lttcomm_relayd_add_stream_2_11 *msg = NULL;
+       struct lttcomm_relayd_add_stream_2_11 *msg = nullptr;
        size_t channel_name_len;
        size_t pathname_len;
        size_t msg_length;
@@ -492,10 +513,14 @@ error:
  *
  * On success return 0 else return ret_code negative value.
  */
-int relayd_add_stream(struct lttcomm_relayd_sock *rsock, const char *channel_name,
-               const char *domain_name, const char *_pathname, uint64_t *stream_id,
-               uint64_t tracefile_size, uint64_t tracefile_count,
-               struct lttng_trace_chunk *trace_chunk)
+int relayd_add_stream(struct lttcomm_relayd_sock *rsock,
+                     const char *channel_name,
+                     const char *domain_name,
+                     const char *_pathname,
+                     uint64_t *stream_id,
+                     uint64_t tracefile_size,
+                     uint64_t tracefile_count,
+                     struct lttng_trace_chunk *trace_chunk)
 {
        int ret;
        struct lttcomm_relayd_status_stream reply;
@@ -517,8 +542,8 @@ int relayd_add_stream(struct lttcomm_relayd_sock *rsock, const char *channel_nam
 
        } else if (rsock->minor > 1 && rsock->minor < 11) {
                /* From 2.2 to 2.10 */
-               ret = relayd_add_stream_2_2(rsock, channel_name, _pathname,
-                               tracefile_size, tracefile_count);
+               ret = relayd_add_stream_2_2(
+                       rsock, channel_name, _pathname, tracefile_size, tracefile_count);
        } else {
                const char *separator;
                enum lttng_trace_chunk_status chunk_status;
@@ -530,24 +555,25 @@ int relayd_add_stream(struct lttcomm_relayd_sock *rsock, const char *channel_nam
                        separator = "/";
                }
 
-               ret = snprintf(pathname, RELAYD_COMM_LTTNG_PATH_MAX, "%s%s%s",
-                               domain_name, separator, _pathname);
+               ret = snprintf(pathname,
+                              RELAYD_COMM_LTTNG_PATH_MAX,
+                              "%s%s%s",
+                              domain_name,
+                              separator,
+                              _pathname);
                if (ret <= 0 || ret >= RELAYD_COMM_LTTNG_PATH_MAX) {
                        ERR("Failed to format stream path: %s",
-                                       ret <= 0 ? "formatting error" :
-                                                       "path exceeds maximal allowed length");
+                           ret <= 0 ? "formatting error" : "path exceeds maximal allowed length");
                        ret = -1;
                        goto error;
                }
 
-               chunk_status = lttng_trace_chunk_get_id(trace_chunk,
-                               &chunk_id);
+               chunk_status = lttng_trace_chunk_get_id(trace_chunk, &chunk_id);
                LTTNG_ASSERT(chunk_status == LTTNG_TRACE_CHUNK_STATUS_OK);
 
                /* From 2.11 to ...*/
-               ret = relayd_add_stream_2_11(rsock, channel_name, pathname,
-                               tracefile_size, tracefile_count,
-                               chunk_id);
+               ret = relayd_add_stream_2_11(
+                       rsock, channel_name, pathname, tracefile_size, tracefile_count, chunk_id);
        }
 
        if (ret) {
@@ -575,8 +601,7 @@ int relayd_add_stream(struct lttcomm_relayd_sock *rsock, const char *channel_nam
                *stream_id = reply.handle;
        }
 
-       DBG("Relayd stream added successfully with handle %" PRIu64,
-                       reply.handle);
+       DBG("Relayd stream added successfully with handle %" PRIu64, reply.handle);
 
 error:
        return ret;
@@ -604,7 +629,7 @@ int relayd_streams_sent(struct lttcomm_relayd_sock *rsock)
        }
 
        /* Send command */
-       ret = send_command(rsock, RELAYD_STREAMS_SENT, NULL, 0, 0);
+       ret = send_command(rsock, RELAYD_STREAMS_SENT, nullptr, 0, 0);
        if (ret < 0) {
                goto error;
        }
@@ -651,8 +676,7 @@ int relayd_version_check(struct lttcomm_relayd_sock *rsock)
        /* Code flow error. Safety net. */
        LTTNG_ASSERT(rsock);
 
-       DBG("Relayd version check for major.minor %u.%u", rsock->major,
-                       rsock->minor);
+       DBG("Relayd version check for major.minor %u.%u", rsock->major, rsock->minor);
 
        memset(&msg, 0, sizeof(msg));
        /* Prepare network byte order before transmission. */
@@ -685,7 +709,8 @@ int relayd_version_check(struct lttcomm_relayd_sock *rsock)
                /* Not compatible */
                ret = LTTNG_ERR_RELAYD_VERSION_FAIL;
                DBG2("Relayd version is NOT compatible. Relayd version %u != %u (us)",
-                               msg.major, rsock->major);
+                    msg.major,
+                    rsock->major);
                goto error;
        }
 
@@ -700,7 +725,8 @@ int relayd_version_check(struct lttcomm_relayd_sock *rsock)
 
        /* Version number compatible */
        DBG2("Relayd version is compatible, using protocol version %u.%u",
-                       rsock->major, rsock->minor);
+            rsock->major,
+            rsock->minor);
        ret = 0;
 
 error:
@@ -722,7 +748,7 @@ int relayd_send_metadata(struct lttcomm_relayd_sock *rsock, size_t len)
        DBG("Relayd sending metadata of size %zu", len);
 
        /* Send command */
-       ret = send_command(rsock, RELAYD_SEND_METADATA, NULL, len, 0);
+       ret = send_command(rsock, RELAYD_SEND_METADATA, nullptr, len, 0);
        if (ret < 0) {
                goto error;
        }
@@ -806,7 +832,8 @@ end:
  * Send data header structure to the relayd.
  */
 int relayd_send_data_hdr(struct lttcomm_relayd_sock *rsock,
-               struct lttcomm_relayd_data_hdr *hdr, size_t size)
+                        struct lttcomm_relayd_data_hdr *hdr,
+                        size_t size)
 {
        int ret;
 
@@ -844,8 +871,9 @@ error:
 /*
  * Send close stream command to the relayd.
  */
-int relayd_send_close_stream(struct lttcomm_relayd_sock *rsock, uint64_t stream_id,
-               uint64_t last_net_seq_num)
+int relayd_send_close_stream(struct lttcomm_relayd_sock *rsock,
+                            uint64_t stream_id,
+                            uint64_t last_net_seq_num)
 {
        int ret;
        struct lttcomm_relayd_close_stream msg;
@@ -894,8 +922,9 @@ error:
  *
  * Return 0 if NOT pending, 1 if so and a negative value on error.
  */
-int relayd_data_pending(struct lttcomm_relayd_sock *rsock, uint64_t stream_id,
-               uint64_t last_net_seq_num)
+int relayd_data_pending(struct lttcomm_relayd_sock *rsock,
+                       uint64_t stream_id,
+                       uint64_t last_net_seq_num)
 {
        int ret;
        struct lttcomm_relayd_data_pending msg;
@@ -911,8 +940,7 @@ int relayd_data_pending(struct lttcomm_relayd_sock *rsock, uint64_t stream_id,
        msg.last_net_seq_num = htobe64(last_net_seq_num);
 
        /* Send command */
-       ret = send_command(rsock, RELAYD_DATA_PENDING, (void *) &msg,
-                       sizeof(msg), 0);
+       ret = send_command(rsock, RELAYD_DATA_PENDING, (void *) &msg, sizeof(msg), 0);
        if (ret < 0) {
                goto error;
        }
@@ -933,8 +961,7 @@ int relayd_data_pending(struct lttcomm_relayd_sock *rsock, uint64_t stream_id,
        /* At this point, the ret code is either 1 or 0 */
        ret = reply.ret_code;
 
-       DBG("Relayd data is %s pending for stream id %" PRIu64,
-                       ret == 1 ? "" : "NOT", stream_id);
+       DBG("Relayd data is %s pending for stream id %" PRIu64, ret == 1 ? "" : "NOT", stream_id);
 
 error:
        return ret;
@@ -943,8 +970,7 @@ error:
 /*
  * Check on the relayd side for a quiescent state on the control socket.
  */
-int relayd_quiescent_control(struct lttcomm_relayd_sock *rsock,
-               uint64_t metadata_stream_id)
+int relayd_quiescent_control(struct lttcomm_relayd_sock *rsock, uint64_t metadata_stream_id)
 {
        int ret;
        struct lttcomm_relayd_quiescent_control msg;
@@ -1036,8 +1062,9 @@ error:
  * Return 0 on success and set is_data_inflight to 0 if no data is being
  * streamed or 1 if it is the case.
  */
-int relayd_end_data_pending(struct lttcomm_relayd_sock *rsock, uint64_t id,
-               unsigned int *is_data_inflight)
+int relayd_end_data_pending(struct lttcomm_relayd_sock *rsock,
+                           uint64_t id,
+                           unsigned int *is_data_inflight)
 {
        int ret, recv_ret;
        struct lttcomm_relayd_end_data_pending msg;
@@ -1083,8 +1110,9 @@ error:
  * Send index to the relayd.
  */
 int relayd_send_index(struct lttcomm_relayd_sock *rsock,
-               struct ctf_packet_index *index, uint64_t relay_stream_id,
-               uint64_t net_seq_num)
+                     struct ctf_packet_index *index,
+                     uint64_t relay_stream_id,
+                     uint64_t net_seq_num)
 {
        int ret;
        struct lttcomm_relayd_index msg;
@@ -1119,11 +1147,13 @@ int relayd_send_index(struct lttcomm_relayd_sock *rsock,
        }
 
        /* Send command */
-       ret = send_command(rsock, RELAYD_SEND_INDEX, &msg,
-               lttcomm_relayd_index_len(lttng_to_index_major(rsock->major,
-                                                               rsock->minor),
-                               lttng_to_index_minor(rsock->major, rsock->minor)),
-                               0);
+       ret = send_command(
+               rsock,
+               RELAYD_SEND_INDEX,
+               &msg,
+               lttcomm_relayd_index_len(lttng_to_index_major(rsock->major, rsock->minor),
+                                        lttng_to_index_minor(rsock->major, rsock->minor)),
+               0);
        if (ret < 0) {
                goto error;
        }
@@ -1152,8 +1182,7 @@ error:
 /*
  * Ask the relay to reset the metadata trace file (regeneration).
  */
-int relayd_reset_metadata(struct lttcomm_relayd_sock *rsock,
-               uint64_t stream_id, uint64_t version)
+int relayd_reset_metadata(struct lttcomm_relayd_sock *rsock, uint64_t stream_id, uint64_t version)
 {
        int ret;
        struct lttcomm_relayd_reset_metadata msg;
@@ -1205,8 +1234,9 @@ error:
 }
 
 int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
-               unsigned int stream_count, const uint64_t *new_chunk_id,
-               const struct relayd_stream_rotation_position *positions)
+                         unsigned int stream_count,
+                         const uint64_t *new_chunk_id,
+                         const struct relayd_stream_rotation_position *positions)
 {
        int ret;
        unsigned int i;
@@ -1233,8 +1263,8 @@ int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
        LTTNG_ASSERT(sock);
 
        if (new_chunk_id) {
-               ret = snprintf(new_chunk_id_buf, sizeof(new_chunk_id_buf),
-                               "%" PRIu64, *new_chunk_id);
+               ret = snprintf(
+                       new_chunk_id_buf, sizeof(new_chunk_id_buf), "%" PRIu64, *new_chunk_id);
                if (ret == -1 || ret >= sizeof(new_chunk_id_buf)) {
                        new_chunk_id_str = "formatting error";
                } else {
@@ -1245,7 +1275,8 @@ int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
        }
 
        DBG("Preparing \"rotate streams\" command payload: new_chunk_id = %s, stream_count = %u",
-                       new_chunk_id_str, stream_count);
+           new_chunk_id_str,
+           stream_count);
 
        ret = lttng_dynamic_buffer_append(&payload, &msg, sizeof(msg));
        if (ret) {
@@ -1254,19 +1285,16 @@ int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
        }
 
        for (i = 0; i < stream_count; i++) {
-               const struct relayd_stream_rotation_position *position =
-                               &positions[i];
+               const struct relayd_stream_rotation_position *position = &positions[i];
                const struct lttcomm_relayd_stream_rotation_position comm_position = {
                        .stream_id = htobe64(position->stream_id),
-                       .rotate_at_seq_num = htobe64(
-                                       position->rotate_at_seq_num),
+                       .rotate_at_seq_num = htobe64(position->rotate_at_seq_num),
                };
 
                DBG("Rotate stream %" PRIu64 " at sequence number %" PRIu64,
-                               position->stream_id,
-                               position->rotate_at_seq_num);
-               ret = lttng_dynamic_buffer_append(&payload, &comm_position,
-                               sizeof(comm_position));
+                   position->stream_id,
+                   position->rotate_at_seq_num);
+               ret = lttng_dynamic_buffer_append(&payload, &comm_position, sizeof(comm_position));
                if (ret) {
                        ERR("Failed to allocate \"rotate streams\" command payload");
                        goto error;
@@ -1274,8 +1302,7 @@ int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
        }
 
        /* Send command. */
-       ret = send_command(sock, RELAYD_ROTATE_STREAMS, payload.data,
-                       payload.size, 0);
+       ret = send_command(sock, RELAYD_ROTATE_STREAMS, payload.data, payload.size, 0);
        if (ret < 0) {
                ERR("Failed to send \"rotate stream\" command");
                goto error;
@@ -1303,8 +1330,7 @@ error:
        return ret;
 }
 
-int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock,
-               struct lttng_trace_chunk *chunk)
+int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock, struct lttng_trace_chunk *chunk)
 {
        int ret = 0;
        enum lttng_trace_chunk_status status;
@@ -1330,17 +1356,14 @@ int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock,
                goto end;
        }
 
-       status = lttng_trace_chunk_get_creation_timestamp(
-                       chunk, &creation_timestamp);
+       status = lttng_trace_chunk_get_creation_timestamp(chunk, &creation_timestamp);
        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
-       status = lttng_trace_chunk_get_name(
-                       chunk, &chunk_name, &overridden_name);
-       if (status != LTTNG_TRACE_CHUNK_STATUS_OK &&
-                       status != LTTNG_TRACE_CHUNK_STATUS_NONE) {
+       status = lttng_trace_chunk_get_name(chunk, &chunk_name, &overridden_name);
+       if (status != LTTNG_TRACE_CHUNK_STATUS_OK && status != LTTNG_TRACE_CHUNK_STATUS_NONE) {
                ret = -1;
                goto end;
        }
@@ -1355,15 +1378,13 @@ int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock,
                goto end;
        }
        if (chunk_name_length) {
-               ret = lttng_dynamic_buffer_append(
-                               &payload, chunk_name, chunk_name_length);
+               ret = lttng_dynamic_buffer_append(&payload, chunk_name, chunk_name_length);
                if (ret) {
                        goto end;
                }
        }
 
-       ret = send_command(sock, RELAYD_CREATE_TRACE_CHUNK, payload.data,
-                       payload.size, 0);
+       ret = send_command(sock, RELAYD_CREATE_TRACE_CHUNK, payload.data, payload.size, 0);
        if (ret < 0) {
                ERR("Failed to send trace chunk creation command to relay daemon");
                goto end;
@@ -1378,12 +1399,10 @@ int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock,
        reply.ret_code = be32toh(reply.ret_code);
        if (reply.ret_code != LTTNG_OK) {
                ret = -1;
-               ERR("Relayd trace chunk create replied error %d",
-                               reply.ret_code);
+               ERR("Relayd trace chunk create replied error %d", reply.ret_code);
        } else {
                ret = 0;
-               DBG("Relayd successfully created trace chunk: chunk_id = %" PRIu64,
-                               chunk_id);
+               DBG("Relayd successfully created trace chunk: chunk_id = %" PRIu64, chunk_id);
        }
 
 end:
@@ -1392,8 +1411,8 @@ end:
 }
 
 int relayd_close_trace_chunk(struct lttcomm_relayd_sock *sock,
-               struct lttng_trace_chunk *chunk,
-               char *path)
+                            struct lttng_trace_chunk *chunk,
+                            char *path)
 {
        int ret = 0;
        enum lttng_trace_chunk_status status;
@@ -1422,8 +1441,7 @@ int relayd_close_trace_chunk(struct lttcomm_relayd_sock *sock,
                goto end;
        }
 
-       status = lttng_trace_chunk_get_close_command(chunk,
-                       &close_command.value);
+       status = lttng_trace_chunk_get_close_command(chunk, &close_command.value);
        switch (status) {
        case LTTNG_TRACE_CHUNK_STATUS_OK:
                close_command.is_set = 1;
@@ -1445,8 +1463,7 @@ int relayd_close_trace_chunk(struct lttcomm_relayd_sock *sock,
                },
        };
 
-       ret = send_command(sock, RELAYD_CLOSE_TRACE_CHUNK, &msg, sizeof(msg),
-                       0);
+       ret = send_command(sock, RELAYD_CLOSE_TRACE_CHUNK, &msg, sizeof(msg), 0);
        if (ret < 0) {
                ERR("Failed to send trace chunk close command to relay daemon");
                goto end;
@@ -1479,19 +1496,18 @@ int relayd_close_trace_chunk(struct lttcomm_relayd_sock *sock,
        reply.generic.ret_code = be32toh(reply.generic.ret_code);
        if (reply.generic.ret_code != LTTNG_OK) {
                ret = -1;
-               ERR("Relayd trace chunk close replied error %d",
-                               reply.generic.ret_code);
+               ERR("Relayd trace chunk close replied error %d", reply.generic.ret_code);
        } else {
                ret = 0;
-               DBG("Relayd successfully closed trace chunk: chunk_id = %" PRIu64,
-                               chunk_id);
+               DBG("Relayd successfully closed trace chunk: chunk_id = %" PRIu64, chunk_id);
        }
 end:
        return ret;
 }
 
 int relayd_trace_chunk_exists(struct lttcomm_relayd_sock *sock,
-               uint64_t chunk_id, bool *chunk_exists)
+                             uint64_t chunk_id,
+                             bool *chunk_exists)
 {
        int ret = 0;
        struct lttcomm_relayd_trace_chunk_exists msg = {};
@@ -1505,11 +1521,10 @@ int relayd_trace_chunk_exists(struct lttcomm_relayd_sock *sock,
        }
 
        msg = (typeof(msg)){
-                       .chunk_id = htobe64(chunk_id),
+               .chunk_id = htobe64(chunk_id),
        };
 
-       ret = send_command(sock, RELAYD_TRACE_CHUNK_EXISTS, &msg, sizeof(msg),
-                       0);
+       ret = send_command(sock, RELAYD_TRACE_CHUNK_EXISTS, &msg, sizeof(msg), 0);
        if (ret < 0) {
                ERR("Failed to send trace chunk exists command to relay daemon");
                goto end;
@@ -1524,13 +1539,13 @@ int relayd_trace_chunk_exists(struct lttcomm_relayd_sock *sock,
        reply.generic.ret_code = be32toh(reply.generic.ret_code);
        if (reply.generic.ret_code != LTTNG_OK) {
                ret = -1;
-               ERR("Relayd trace chunk close replied error %d",
-                               reply.generic.ret_code);
+               ERR("Relayd trace chunk close replied error %d", reply.generic.ret_code);
        } else {
                ret = 0;
                DBG("Relayd successfully checked trace chunk existence: chunk_id = %" PRIu64
-                               ", exists = %s", chunk_id,
-                               reply.trace_chunk_exists ? "true" : "false");
+                   ", exists = %s",
+                   chunk_id,
+                   reply.trace_chunk_exists ? "true" : "false");
                *chunk_exists = !!reply.trace_chunk_exists;
        }
 end:
@@ -1538,11 +1553,11 @@ end:
 }
 
 int relayd_get_configuration(struct lttcomm_relayd_sock *sock,
-               uint64_t query_flags,
-               uint64_t *result_flags)
+                            uint64_t query_flags,
+                            uint64_t *result_flags)
 {
        int ret = 0;
-       struct lttcomm_relayd_get_configuration msg = (typeof(msg)) {
+       struct lttcomm_relayd_get_configuration msg = (typeof(msg)){
                .query_flags = htobe64(query_flags),
        };
        struct lttcomm_relayd_get_configuration_reply reply = {};
@@ -1557,8 +1572,7 @@ int relayd_get_configuration(struct lttcomm_relayd_sock *sock,
                goto end;
        }
 
-       ret = send_command(sock, RELAYD_GET_CONFIGURATION, &msg, sizeof(msg),
-                       0);
+       ret = send_command(sock, RELAYD_GET_CONFIGURATION, &msg, sizeof(msg), 0);
        if (ret < 0) {
                ERR("Failed to send get configuration command to relay daemon");
                goto end;
@@ -1573,15 +1587,14 @@ int relayd_get_configuration(struct lttcomm_relayd_sock *sock,
        reply.generic.ret_code = be32toh(reply.generic.ret_code);
        if (reply.generic.ret_code != LTTNG_OK) {
                ret = -1;
-               ERR("Relayd get configuration replied error %d",
-                               reply.generic.ret_code);
+               ERR("Relayd get configuration replied error %d", reply.generic.ret_code);
        } else {
-               reply.relayd_configuration_flags =
-                       be64toh(reply.relayd_configuration_flags);
+               reply.relayd_configuration_flags = be64toh(reply.relayd_configuration_flags);
                ret = 0;
                DBG("Relayd successfully got configuration: query_flags = %" PRIu64
-                               ", results_flags = %" PRIu64, query_flags,
-                               reply.relayd_configuration_flags);
+                   ", results_flags = %" PRIu64,
+                   query_flags,
+                   reply.relayd_configuration_flags);
                *result_flags = reply.relayd_configuration_flags;
        }
 end:
index 05d1ec684630a3bb95b6286424aeba78ac646687..f7b16229881915d1689ea8d00e45d42aa91a890d 100644 (file)
@@ -8,13 +8,13 @@
 #ifndef _RELAYD_H
 #define _RELAYD_H
 
-#include <unistd.h>
-#include <stdbool.h>
-
+#include <common/dynamic-array.hpp>
 #include <common/sessiond-comm/relayd.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/trace-chunk.hpp>
-#include <common/dynamic-array.hpp>
+
+#include <stdbool.h>
+#include <unistd.h>
 
 struct relayd_stream_rotation_position {
        uint64_t stream_id;
@@ -30,51 +30,63 @@ struct relayd_stream_rotation_position {
 int relayd_connect(struct lttcomm_relayd_sock *sock);
 int relayd_close(struct lttcomm_relayd_sock *sock);
 int relayd_create_session(struct lttcomm_relayd_sock *rsock,
-               uint64_t *relayd_session_id,
-               const char *session_name, const char *hostname,
-               const char *base_path, int session_live_timer,
-               unsigned int snapshot, uint64_t sessiond_session_id,
-               const lttng_uuid& sessiond_uuid,
-               const uint64_t *current_chunk_id,
-               time_t creation_time, bool session_name_contains_creation_time,
-               char *output_path);
-int relayd_add_stream(struct lttcomm_relayd_sock *sock, const char *channel_name,
-               const char *domain_name, const char *pathname, uint64_t *stream_id,
-               uint64_t tracefile_size, uint64_t tracefile_count,
-               struct lttng_trace_chunk *trace_chunk);
+                         uint64_t *relayd_session_id,
+                         const char *session_name,
+                         const char *hostname,
+                         const char *base_path,
+                         int session_live_timer,
+                         unsigned int snapshot,
+                         uint64_t sessiond_session_id,
+                         const lttng_uuid& sessiond_uuid,
+                         const uint64_t *current_chunk_id,
+                         time_t creation_time,
+                         bool session_name_contains_creation_time,
+                         char *output_path);
+int relayd_add_stream(struct lttcomm_relayd_sock *sock,
+                     const char *channel_name,
+                     const char *domain_name,
+                     const char *pathname,
+                     uint64_t *stream_id,
+                     uint64_t tracefile_size,
+                     uint64_t tracefile_count,
+                     struct lttng_trace_chunk *trace_chunk);
 int relayd_streams_sent(struct lttcomm_relayd_sock *rsock);
-int relayd_send_close_stream(struct lttcomm_relayd_sock *sock, uint64_t stream_id,
-               uint64_t last_net_seq_num);
+int relayd_send_close_stream(struct lttcomm_relayd_sock *sock,
+                            uint64_t stream_id,
+                            uint64_t last_net_seq_num);
 int relayd_version_check(struct lttcomm_relayd_sock *sock);
 int relayd_start_data(struct lttcomm_relayd_sock *sock);
 int relayd_send_metadata(struct lttcomm_relayd_sock *sock, size_t len);
 int relayd_send_data_hdr(struct lttcomm_relayd_sock *sock,
-               struct lttcomm_relayd_data_hdr *hdr, size_t size);
-int relayd_data_pending(struct lttcomm_relayd_sock *sock, uint64_t stream_id,
-               uint64_t last_net_seq_num);
-int relayd_quiescent_control(struct lttcomm_relayd_sock *sock,
-               uint64_t metadata_stream_id);
+                        struct lttcomm_relayd_data_hdr *hdr,
+                        size_t size);
+int relayd_data_pending(struct lttcomm_relayd_sock *sock,
+                       uint64_t stream_id,
+                       uint64_t last_net_seq_num);
+int relayd_quiescent_control(struct lttcomm_relayd_sock *sock, uint64_t metadata_stream_id);
 int relayd_begin_data_pending(struct lttcomm_relayd_sock *sock, uint64_t id);
-int relayd_end_data_pending(struct lttcomm_relayd_sock *sock, uint64_t id,
-               unsigned int *is_data_inflight);
+int relayd_end_data_pending(struct lttcomm_relayd_sock *sock,
+                           uint64_t id,
+                           unsigned int *is_data_inflight);
 int relayd_send_index(struct lttcomm_relayd_sock *rsock,
-               struct ctf_packet_index *index, uint64_t relay_stream_id,
-               uint64_t net_seq_num);
-int relayd_reset_metadata(struct lttcomm_relayd_sock *rsock,
-               uint64_t stream_id, uint64_t version);
+                     struct ctf_packet_index *index,
+                     uint64_t relay_stream_id,
+                     uint64_t net_seq_num);
+int relayd_reset_metadata(struct lttcomm_relayd_sock *rsock, uint64_t stream_id, uint64_t version);
 /* `positions` is an array of `stream_count` relayd_stream_rotation_position. */
 int relayd_rotate_streams(struct lttcomm_relayd_sock *sock,
-               unsigned int stream_count, const uint64_t *new_chunk_id,
-               const struct relayd_stream_rotation_position *positions);
-int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock,
-               struct lttng_trace_chunk *chunk);
+                         unsigned int stream_count,
+                         const uint64_t *new_chunk_id,
+                         const struct relayd_stream_rotation_position *positions);
+int relayd_create_trace_chunk(struct lttcomm_relayd_sock *sock, struct lttng_trace_chunk *chunk);
 int relayd_close_trace_chunk(struct lttcomm_relayd_sock *sock,
-               struct lttng_trace_chunk *chunk,
-               char *path);
+                            struct lttng_trace_chunk *chunk,
+                            char *path);
 int relayd_trace_chunk_exists(struct lttcomm_relayd_sock *sock,
-               uint64_t chunk_id, bool *chunk_exists);
+                             uint64_t chunk_id,
+                             bool *chunk_exists);
 int relayd_get_configuration(struct lttcomm_relayd_sock *sock,
-               uint64_t query_flags,
-               uint64_t *result_flags);
+                            uint64_t query_flags,
+                            uint64_t *result_flags);
 
 #endif /* _RELAYD_H */
index 2c762d5ee797f3a98c92f1f59527a1a9ae92f37c..07d9e171f0a0cf941c78cec5c928af2da9158469 100644 (file)
@@ -8,6 +8,24 @@
  */
 
 #define _LGPL_SOURCE
+#include "runas.hpp"
+
+#include <common/bytecode/bytecode.hpp>
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/compat/getenv.hpp>
+#include <common/compat/string.hpp>
+#include <common/defaults.hpp>
+#include <common/filter/filter-ast.hpp>
+#include <common/lttng-elf.hpp>
+#include <common/lttng-kernel.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/thread.hpp>
+#include <common/unix.hpp>
+#include <common/utils.hpp>
+
+#include <lttng/constant.h>
+
 #include <fcntl.h>
 #include <grp.h>
 #include <limits.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <common/bytecode/bytecode.hpp>
-#include <common/lttng-kernel.hpp>
-#include <common/common.hpp>
-#include <common/utils.hpp>
-#include <common/compat/errno.hpp>
-#include <common/compat/getenv.hpp>
-#include <common/compat/string.hpp>
-#include <common/unix.hpp>
-#include <common/defaults.hpp>
-#include <common/lttng-elf.hpp>
-#include <common/thread.hpp>
-
-#include <lttng/constant.h>
-
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/filter/filter-ast.hpp>
-
-#include "runas.hpp"
-
 #define GETPW_BUFFER_FALLBACK_SIZE 4096
 
 enum run_as_cmd {
@@ -66,7 +65,7 @@ enum run_as_cmd {
 namespace {
 struct run_as_data;
 struct run_as_ret;
-typedef int (*run_as_fct)(struct run_as_data *data, struct run_as_ret *ret_value);
+using run_as_fct = int (*)(struct run_as_data *, struct run_as_ret *);
 
 struct run_as_mkdir_data {
        int dirfd;
@@ -178,31 +177,31 @@ struct run_as_ret {
        bool _error;
 } LTTNG_PACKED;
 
-#define COMMAND_IN_FDS(data_ptr) ({                                    \
-       int *fds = NULL;                                                \
-       if (command_properties[data_ptr->cmd].in_fds_offset != -1) {    \
-               fds = (int *) ((char *) data_ptr + command_properties[data_ptr->cmd].in_fds_offset); \
-       }                                                               \
-       fds;                                                            \
-})
+#define COMMAND_IN_FDS(data_ptr)                                                           \
+       ({                                                                                 \
+               int *fds = NULL;                                                           \
+               if (command_properties[(data_ptr)->cmd].in_fds_offset != -1) {             \
+                       fds = (int *) ((char *) (data_ptr) +                               \
+                                      command_properties[(data_ptr)->cmd].in_fds_offset); \
+               }                                                                          \
+               fds;                                                                       \
+       })
 
-#define COMMAND_OUT_FDS(cmd, ret_ptr) ({                               \
-       int *fds = NULL;                                                \
-       if (command_properties[cmd].out_fds_offset != -1) {             \
-               fds = (int *) ((char *) ret_ptr + command_properties[cmd].out_fds_offset); \
-       }                                                               \
-       fds;                                                            \
-})
+#define COMMAND_OUT_FDS(cmd, ret_ptr)                                           \
+       ({                                                                      \
+               int *fds = NULL;                                                \
+               if (command_properties[cmd].out_fds_offset != -1) {             \
+                       fds = (int *) ((char *) (ret_ptr) +                     \
+                                      command_properties[cmd].out_fds_offset); \
+               }                                                               \
+               fds;                                                            \
+       })
 
-#define COMMAND_IN_FD_COUNT(data_ptr) ({               \
-       command_properties[data_ptr->cmd].in_fd_count;  \
-})
+#define COMMAND_IN_FD_COUNT(data_ptr) ({ command_properties[(data_ptr)->cmd].in_fd_count; })
 
-#define COMMAND_OUT_FD_COUNT(cmd) ({           \
-       command_properties[cmd].out_fd_count;   \
-})
+#define COMMAND_OUT_FD_COUNT(cmd) ({ command_properties[cmd].out_fd_count; })
 
-#define COMMAND_USE_CWD_FD(data_ptr) command_properties[data_ptr->cmd].use_cwd_fd
+#define COMMAND_USE_CWD_FD(data_ptr) command_properties[(data_ptr)->cmd].use_cwd_fd
 
 struct run_as_command_properties {
        /* Set to -1 when not applicable. */
@@ -311,16 +310,14 @@ const struct run_as_command_properties command_properties[] = {
                .use_cwd_fd = false,
        },
        {
-               .in_fds_offset = offsetof(struct run_as_data,
-                               u.extract_elf_symbol_offset.fd),
+               .in_fds_offset = offsetof(struct run_as_data, u.extract_elf_symbol_offset.fd),
                .out_fds_offset = -1,
                .in_fd_count = 1,
                .out_fd_count = 0,
                .use_cwd_fd = false,
        },
        {
-               .in_fds_offset = offsetof(struct run_as_data,
-                               u.extract_sdt_probe_offsets.fd),
+               .in_fds_offset = offsetof(struct run_as_data, u.extract_sdt_probe_offsets.fd),
                .out_fds_offset = -1,
                .in_fd_count = 1,
                .out_fd_count = 0,
@@ -336,7 +333,7 @@ const struct run_as_command_properties command_properties[] = {
 };
 
 struct run_as_worker_data {
-       pid_t pid;      /* Worker PID. */
+       pid_t pid; /* Worker PID. */
        int sockpair[2];
        char *procname;
 };
@@ -348,14 +345,12 @@ pthread_mutex_t worker_lock = PTHREAD_MUTEX_INITIALIZER;
 } /* namespace */
 
 #ifdef VALGRIND
-static
-int use_clone(void)
+static int use_clone(void)
 {
        return 0;
 }
 #else
-static
-int use_clone(void)
+static int use_clone()
 {
        return !lttng_secure_getenv("LTTNG_DEBUG_NOCLONE");
 }
@@ -364,8 +359,7 @@ int use_clone(void)
 /*
  * Create recursively directory using the FULL path.
  */
-static
-int _mkdirat_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _mkdirat_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        const char *path;
        mode_t mode;
@@ -384,17 +378,15 @@ int _mkdirat_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
        /* Ownership of dirfd is transferred to the handle. */
        data->u.mkdir.dirfd = -1;
        /* Safe to call as we have transitioned to the requested uid/gid. */
-       ret_value->u.ret = lttng_directory_handle_create_subdirectory_recursive(
-                       handle, path, mode);
+       ret_value->u.ret = lttng_directory_handle_create_subdirectory_recursive(handle, path, mode);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        lttng_directory_handle_put(handle);
 end:
        return ret_value->u.ret;
 }
 
-static
-int _mkdirat(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _mkdirat(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        const char *path;
        mode_t mode;
@@ -413,17 +405,15 @@ int _mkdirat(struct run_as_data *data, struct run_as_ret *ret_value)
        /* Ownership of dirfd is transferred to the handle. */
        data->u.mkdir.dirfd = -1;
        /* Safe to call as we have transitioned to the requested uid/gid. */
-       ret_value->u.ret = lttng_directory_handle_create_subdirectory(
-                       handle, path, mode);
+       ret_value->u.ret = lttng_directory_handle_create_subdirectory(handle, path, mode);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        lttng_directory_handle_put(handle);
 end:
        return ret_value->u.ret;
 }
 
-static
-int _open(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _open(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        int fd;
        struct lttng_directory_handle *handle;
@@ -438,9 +428,8 @@ int _open(struct run_as_data *data, struct run_as_ret *ret_value)
        /* Ownership of dirfd is transferred to the handle. */
        data->u.open.dirfd = -1;
 
-       fd = lttng_directory_handle_open_file(handle,
-                       data->u.open.path, data->u.open.flags,
-                       data->u.open.mode);
+       fd = lttng_directory_handle_open_file(
+               handle, data->u.open.path, data->u.open.flags, data->u.open.mode);
        if (fd < 0) {
                ret_value->u.ret = -1;
                ret_value->u.open.fd = -1;
@@ -456,8 +445,7 @@ end:
        return ret_value->u.ret;
 }
 
-static
-int _unlink(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _unlink(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        struct lttng_directory_handle *handle;
 
@@ -472,17 +460,15 @@ int _unlink(struct run_as_data *data, struct run_as_ret *ret_value)
        /* Ownership of dirfd is transferred to the handle. */
        data->u.unlink.dirfd = -1;
 
-       ret_value->u.ret = lttng_directory_handle_unlink_file(handle,
-                       data->u.unlink.path);
+       ret_value->u.ret = lttng_directory_handle_unlink_file(handle, data->u.unlink.path);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        lttng_directory_handle_put(handle);
 end:
        return ret_value->u.ret;
 }
 
-static
-int _rmdir(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _rmdir(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        struct lttng_directory_handle *handle;
 
@@ -497,17 +483,15 @@ int _rmdir(struct run_as_data *data, struct run_as_ret *ret_value)
        /* Ownership of dirfd is transferred to the handle. */
        data->u.rmdir.dirfd = -1;
 
-       ret_value->u.ret = lttng_directory_handle_remove_subdirectory(
-                       handle, data->u.rmdir.path);
+       ret_value->u.ret = lttng_directory_handle_remove_subdirectory(handle, data->u.rmdir.path);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        lttng_directory_handle_put(handle);
 end:
        return ret_value->u.ret;
 }
 
-static
-int _rmdir_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _rmdir_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        struct lttng_directory_handle *handle;
 
@@ -523,31 +507,28 @@ int _rmdir_recursive(struct run_as_data *data, struct run_as_ret *ret_value)
        data->u.rmdir.dirfd = -1;
 
        ret_value->u.ret = lttng_directory_handle_remove_subdirectory_recursive(
-                       handle, data->u.rmdir.path, data->u.rmdir.flags);
+               handle, data->u.rmdir.path, data->u.rmdir.flags);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        lttng_directory_handle_put(handle);
 end:
        return ret_value->u.ret;
 }
 
-static
-int _rename(struct run_as_data *data, struct run_as_ret *ret_value)
+static int _rename(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        const char *old_path, *new_path;
-       struct lttng_directory_handle *old_handle = NULL, *new_handle = NULL;
+       struct lttng_directory_handle *old_handle = nullptr, *new_handle = nullptr;
 
        old_path = data->u.rename.old_path;
        new_path = data->u.rename.new_path;
 
-       old_handle = lttng_directory_handle_create_from_dirfd(
-                       data->u.rename.dirfds[0]);
+       old_handle = lttng_directory_handle_create_from_dirfd(data->u.rename.dirfds[0]);
        if (!old_handle) {
                ret_value->u.ret = -1;
                goto end;
        }
-       new_handle = lttng_directory_handle_create_from_dirfd(
-                       data->u.rename.dirfds[1]);
+       new_handle = lttng_directory_handle_create_from_dirfd(data->u.rename.dirfds[1]);
        if (!new_handle) {
                ret_value->u.ret = -1;
                goto end;
@@ -557,28 +538,26 @@ int _rename(struct run_as_data *data, struct run_as_ret *ret_value)
        data->u.rename.dirfds[0] = data->u.rename.dirfds[1] = -1;
 
        /* Safe to call as we have transitioned to the requested uid/gid. */
-       ret_value->u.ret = lttng_directory_handle_rename(
-                       old_handle, old_path, new_handle, new_path);
+       ret_value->u.ret =
+               lttng_directory_handle_rename(old_handle, old_path, new_handle, new_path);
 end:
        lttng_directory_handle_put(old_handle);
        lttng_directory_handle_put(new_handle);
        ret_value->_errno = errno;
-       ret_value->_error = (ret_value->u.ret) ? true : false;
+       ret_value->_error = (ret_value->u.ret) != 0;
        return ret_value->u.ret;
 }
 
 #ifdef HAVE_ELF_H
-static
-int _extract_elf_symbol_offset(struct run_as_data *data,
-               struct run_as_ret *ret_value)
+static int _extract_elf_symbol_offset(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        int ret = 0;
        uint64_t offset;
 
        ret_value->_error = false;
        ret = lttng_elf_get_symbol_offset(data->u.extract_elf_symbol_offset.fd,
-                        data->u.extract_elf_symbol_offset.function,
-                        &offset);
+                                         data->u.extract_elf_symbol_offset.function,
+                                         &offset);
        if (ret) {
                DBG("Failed to extract ELF function offset");
                ret_value->_error = true;
@@ -588,22 +567,20 @@ int _extract_elf_symbol_offset(struct run_as_data *data,
        return ret;
 }
 
-static
-int _extract_sdt_probe_offsets(struct run_as_data *data,
-               struct run_as_ret *ret_value)
+static int _extract_sdt_probe_offsets(struct run_as_data *data, struct run_as_ret *ret_value)
 {
        int ret = 0;
-       uint64_t *offsets = NULL;
+       uint64_t *offsets = nullptr;
        uint32_t num_offset;
 
        ret_value->_error = false;
 
        /* On success, this call allocates the offsets paramater. */
-       ret = lttng_elf_get_sdt_probe_offsets(
-                       data->u.extract_sdt_probe_offsets.fd,
-                       data->u.extract_sdt_probe_offsets.provider_name,
-                       data->u.extract_sdt_probe_offsets.probe_name,
-                       &offsets, &num_offset);
+       ret = lttng_elf_get_sdt_probe_offsets(data->u.extract_sdt_probe_offsets.fd,
+                                             data->u.extract_sdt_probe_offsets.provider_name,
+                                             data->u.extract_sdt_probe_offsets.probe_name,
+                                             &offsets,
+                                             &num_offset);
 
        if (ret) {
                DBG("Failed to extract SDT probe offsets");
@@ -620,7 +597,8 @@ int _extract_sdt_probe_offsets(struct run_as_data *data,
 
        /* Copy the content of the offsets array to the ret struct. */
        memcpy(ret_value->u.extract_sdt_probe_offsets.offsets,
-                       offsets, num_offset * sizeof(uint64_t));
+              offsets,
+              num_offset * sizeof(uint64_t));
 
        ret_value->u.extract_sdt_probe_offsets.num_offset = num_offset;
 
@@ -630,37 +608,33 @@ end:
        return ret;
 }
 #else
-static
-int _extract_elf_symbol_offset(
-               struct run_as_data *data __attribute__((unused)),
-               struct run_as_ret *ret_value __attribute__((unused)))
+static int _extract_elf_symbol_offset(struct run_as_data *data __attribute__((unused)),
+                                     struct run_as_ret *ret_value __attribute__((unused)))
 {
        ERR("Unimplemented runas command RUN_AS_EXTRACT_ELF_SYMBOL_OFFSET");
        return -1;
 }
 
-static
-int _extract_sdt_probe_offsets(
-               struct run_as_data *data __attribute__((unused)),
-               struct run_as_ret *ret_value __attribute__((unused)))
+static int _extract_sdt_probe_offsets(struct run_as_data *data __attribute__((unused)),
+                                     struct run_as_ret *ret_value __attribute__((unused)))
 {
        ERR("Unimplemented runas command RUN_AS_EXTRACT_SDT_PROBE_OFFSETS");
        return -1;
 }
 #endif
 
-static
-int _generate_filter_bytecode(struct run_as_data *data,
-               struct run_as_ret *ret_value) {
+static int _generate_filter_bytecode(struct run_as_data *data, struct run_as_ret *ret_value)
+{
        int ret = 0;
-       const char *filter_expression = NULL;
-       struct filter_parser_ctx *ctx = NULL;
+       const char *filter_expression = nullptr;
+       struct filter_parser_ctx *ctx = nullptr;
 
        ret_value->_error = false;
 
        filter_expression = data->u.generate_filter_bytecode.filter_expression;
 
-       if (lttng_strnlen(filter_expression, LTTNG_FILTER_MAX_LEN - 1) == LTTNG_FILTER_MAX_LEN - 1) {
+       if (lttng_strnlen(filter_expression, LTTNG_FILTER_MAX_LEN - 1) ==
+           LTTNG_FILTER_MAX_LEN - 1) {
                ret_value->_error = true;
                ret = -1;
                goto end;
@@ -673,14 +647,12 @@ int _generate_filter_bytecode(struct run_as_data *data,
                goto end;
        }
 
-       DBG("Size of bytecode generated: %u bytes.",
-                       bytecode_get_len(&ctx->bytecode->b));
+       DBG("Size of bytecode generated: %u bytes.", bytecode_get_len(&ctx->bytecode->b));
 
        /* Copy the lttng_bytecode_filter object to the return structure. */
        memcpy(ret_value->u.generate_filter_bytecode.bytecode,
-                       &ctx->bytecode->b,
-                       sizeof(ctx->bytecode->b) +
-                                       bytecode_get_len(&ctx->bytecode->b));
+              &ctx->bytecode->b,
+              sizeof(ctx->bytecode->b) + bytecode_get_len(&ctx->bytecode->b));
 
 end:
        if (ctx) {
@@ -691,8 +663,7 @@ end:
 
        return ret;
 }
-static
-run_as_fct run_as_enum_to_fct(enum run_as_cmd cmd)
+static run_as_fct run_as_enum_to_fct(enum run_as_cmd cmd)
 {
        switch (cmd) {
        case RUN_AS_MKDIR:
@@ -724,20 +695,18 @@ run_as_fct run_as_enum_to_fct(enum run_as_cmd cmd)
                return _generate_filter_bytecode;
        default:
                ERR("Unknown command %d", (int) cmd);
-               return NULL;
+               return nullptr;
        }
 }
 
-static
-int do_send_fds(int sock, const int *fds, unsigned int fd_count)
+static int do_send_fds(int sock, const int *fds, unsigned int fd_count)
 {
        ssize_t len;
        unsigned int i;
 
        for (i = 0; i < fd_count; i++) {
                if (fds[i] < 0) {
-                       DBG("Attempt to send invalid file descriptor (fd = %i)",
-                                       fds[i]);
+                       DBG("Attempt to send invalid file descriptor (fd = %i)", fds[i]);
                        /* Return 0 as this is not a fatal error. */
                        return 0;
                }
@@ -747,8 +716,7 @@ int do_send_fds(int sock, const int *fds, unsigned int fd_count)
        return len < 0 ? -1 : 0;
 }
 
-static
-int do_recv_fds(int sock, int *fds, unsigned int fd_count)
+static int do_recv_fds(int sock, int *fds, unsigned int fd_count)
 {
        int ret = 0;
        unsigned int i;
@@ -774,9 +742,7 @@ end:
        return ret;
 }
 
-static
-int send_fds_to_worker(const run_as_worker_data *worker,
-               const struct run_as_data *data)
+static int send_fds_to_worker(const run_as_worker_data *worker, const struct run_as_data *data)
 {
        int ret = 0;
        unsigned int i;
@@ -788,14 +754,13 @@ int send_fds_to_worker(const run_as_worker_data *worker,
        for (i = 0; i < COMMAND_IN_FD_COUNT(data); i++) {
                if (COMMAND_IN_FDS(data)[i] < 0) {
                        ERR("Refusing to send invalid fd to worker (fd = %i)",
-                                       COMMAND_IN_FDS(data)[i]);
+                           COMMAND_IN_FDS(data)[i]);
                        ret = -1;
                        goto end;
                }
        }
 
-       ret = do_send_fds(worker->sockpair[0], COMMAND_IN_FDS(data),
-                       COMMAND_IN_FD_COUNT(data));
+       ret = do_send_fds(worker->sockpair[0], COMMAND_IN_FDS(data), COMMAND_IN_FD_COUNT(data));
        if (ret < 0) {
                PERROR("Failed to send file descriptor to run-as worker");
                ret = -1;
@@ -805,9 +770,8 @@ end:
        return ret;
 }
 
-static
-int send_fds_to_master(run_as_worker_data *worker, enum run_as_cmd cmd,
-               struct run_as_ret *run_as_ret)
+static int
+send_fds_to_master(run_as_worker_data *worker, enum run_as_cmd cmd, struct run_as_ret *run_as_ret)
 {
        int ret = 0;
        unsigned int i;
@@ -816,8 +780,8 @@ int send_fds_to_master(run_as_worker_data *worker, enum run_as_cmd cmd,
                goto end;
        }
 
-       ret = do_send_fds(worker->sockpair[1], COMMAND_OUT_FDS(cmd, run_as_ret),
-                       COMMAND_OUT_FD_COUNT(cmd));
+       ret = do_send_fds(
+               worker->sockpair[1], COMMAND_OUT_FDS(cmd, run_as_ret), COMMAND_OUT_FD_COUNT(cmd));
        if (ret < 0) {
                PERROR("Failed to send file descriptor to master process");
                goto end;
@@ -829,8 +793,7 @@ int send_fds_to_master(run_as_worker_data *worker, enum run_as_cmd cmd,
                        int ret_close = close(fd);
 
                        if (ret_close < 0) {
-                               PERROR("Failed to close result file descriptor (fd = %i)",
-                                               fd);
+                               PERROR("Failed to close result file descriptor (fd = %i)", fd);
                        }
                }
        }
@@ -838,9 +801,9 @@ end:
        return ret;
 }
 
-static
-int recv_fds_from_worker(const run_as_worker_data *worker, enum run_as_cmd cmd,
-               struct run_as_ret *run_as_ret)
+static int recv_fds_from_worker(const run_as_worker_data *worker,
+                               enum run_as_cmd cmd,
+                               struct run_as_ret *run_as_ret)
 {
        int ret = 0;
 
@@ -848,8 +811,8 @@ int recv_fds_from_worker(const run_as_worker_data *worker, enum run_as_cmd cmd,
                goto end;
        }
 
-       ret = do_recv_fds(worker->sockpair[0], COMMAND_OUT_FDS(cmd, run_as_ret),
-                       COMMAND_OUT_FD_COUNT(cmd));
+       ret = do_recv_fds(
+               worker->sockpair[0], COMMAND_OUT_FDS(cmd, run_as_ret), COMMAND_OUT_FD_COUNT(cmd));
        if (ret < 0) {
                PERROR("Failed to receive file descriptor from run-as worker");
                ret = -1;
@@ -858,8 +821,7 @@ end:
        return ret;
 }
 
-static
-int recv_fds_from_master(run_as_worker_data *worker, struct run_as_data *data)
+static int recv_fds_from_master(run_as_worker_data *worker, struct run_as_data *data)
 {
        int ret = 0;
 
@@ -876,8 +838,7 @@ int recv_fds_from_master(run_as_worker_data *worker, struct run_as_data *data)
                goto end;
        }
 
-       ret = do_recv_fds(worker->sockpair[1], COMMAND_IN_FDS(data),
-                       COMMAND_IN_FD_COUNT(data));
+       ret = do_recv_fds(worker->sockpair[1], COMMAND_IN_FDS(data), COMMAND_IN_FD_COUNT(data));
        if (ret < 0) {
                PERROR("Failed to receive file descriptors from master process");
                ret = -1;
@@ -886,8 +847,7 @@ end:
        return ret;
 }
 
-static
-int cleanup_received_fds(struct run_as_data *data)
+static int cleanup_received_fds(struct run_as_data *data)
 {
        int ret = 0, i;
 
@@ -905,15 +865,14 @@ end:
        return ret;
 }
 
-static int get_user_infos_from_uid(
-               uid_t uid, char **username, gid_t *primary_gid)
+static int get_user_infos_from_uid(uid_t uid, char **username, gid_t *primary_gid)
 {
        int ret;
-       char *buf = NULL;
+       char *buf = nullptr;
        long raw_get_pw_buf_size;
        size_t get_pw_buf_size;
        struct passwd pwd;
-       struct passwd *result = NULL;
+       struct passwd *result = nullptr;
 
        /* Fetch the max size for the temporary buffer. */
        errno = 0;
@@ -926,34 +885,32 @@ static int get_user_infos_from_uid(
 
                /* Limit is indeterminate. */
                WARN("Failed to query _SC_GETPW_R_SIZE_MAX as it is "
-                       "indeterminate; falling back to default buffer size");
+                    "indeterminate; falling back to default buffer size");
                raw_get_pw_buf_size = GETPW_BUFFER_FALLBACK_SIZE;
        }
 
        get_pw_buf_size = (size_t) raw_get_pw_buf_size;
 
        buf = calloc<char>(get_pw_buf_size);
-       if (buf == NULL) {
+       if (buf == nullptr) {
                PERROR("Failed to allocate buffer to get password file entries");
                goto error;
        }
 
        ret = getpwuid_r(uid, &pwd, buf, get_pw_buf_size, &result);
        if (ret < 0) {
-               PERROR("Failed to get user information for user:  uid = %d",
-                               (int) uid);
+               PERROR("Failed to get user information for user:  uid = %d", (int) uid);
                goto error;
        }
 
-       if (result == NULL) {
-               ERR("Failed to find user information in password entries: uid = %d",
-                               (int) uid);
+       if (result == nullptr) {
+               ERR("Failed to find user information in password entries: uid = %d", (int) uid);
                ret = -1;
                goto error;
        }
 
        *username = strdup(result->pw_name);
-       if (*username == NULL) {
+       if (*username == nullptr) {
                PERROR("Failed to copy user name");
                goto error;
        }
@@ -964,25 +921,23 @@ end:
        free(buf);
        return ret;
 error:
-       *username = NULL;
+       *username = nullptr;
        *primary_gid = -1;
        ret = -1;
        goto end;
 }
 
-static int demote_creds(
-               uid_t prev_uid, gid_t prev_gid, uid_t new_uid, gid_t new_gid)
+static int demote_creds(uid_t prev_uid, gid_t prev_gid, uid_t new_uid, gid_t new_gid)
 {
        int ret = 0;
        gid_t primary_gid;
-       char *username = NULL;
+       char *username = nullptr;
 
        /* Change the group id. */
        if (prev_gid != new_gid) {
                ret = setegid(new_gid);
                if (ret < 0) {
-                       PERROR("Failed to set effective group id: new_gid = %d",
-                                       (int) new_gid);
+                       PERROR("Failed to set effective group id: new_gid = %d", (int) new_gid);
                        goto end;
                }
        }
@@ -1022,15 +977,15 @@ static int demote_creds(
                ret = initgroups(username, primary_gid);
                if (ret < 0) {
                        PERROR("Failed to init the supplementary group access list: "
-                                       "username = `%s`, primary gid = %d", username,
-                                       (int) primary_gid);
+                              "username = `%s`, primary gid = %d",
+                              username,
+                              (int) primary_gid);
                        goto end;
                }
 
                ret = seteuid(new_uid);
                if (ret < 0) {
-                       PERROR("Failed to set effective user id: new_uid = %d",
-                                       (int) new_uid);
+                       PERROR("Failed to set effective user id: new_uid = %d", (int) new_uid);
                        goto end;
                }
        }
@@ -1039,19 +994,17 @@ end:
        return ret;
 }
 
-static int promote_creds(
-               uid_t prev_uid, gid_t prev_gid, uid_t new_uid, gid_t new_gid)
+static int promote_creds(uid_t prev_uid, gid_t prev_gid, uid_t new_uid, gid_t new_gid)
 {
        int ret = 0;
        gid_t primary_gid;
-       char *username = NULL;
+       char *username = nullptr;
 
        /* Change the group id. */
        if (prev_gid != new_gid) {
                ret = setegid(new_gid);
                if (ret < 0) {
-                       PERROR("Failed to set effective group id: new_gid = %d",
-                                       (int) new_gid);
+                       PERROR("Failed to set effective group id: new_gid = %d", (int) new_gid);
                        goto end;
                }
        }
@@ -1069,8 +1022,7 @@ static int promote_creds(
                 */
                ret = seteuid(new_uid);
                if (ret < 0) {
-                       PERROR("Failed to set effective user id: new_uid = %d",
-                                       (int) new_uid);
+                       PERROR("Failed to set effective user id: new_uid = %d", (int) new_uid);
                        goto end;
                }
 
@@ -1086,8 +1038,9 @@ static int promote_creds(
                ret = initgroups(username, primary_gid);
                if (ret < 0) {
                        PERROR("Failed to init the supplementary group access "
-                                       "list: username = `%s`, primary gid = %d",
-                                       username, (int) primary_gid)
+                              "list: username = `%s`, primary gid = %d",
+                              username,
+                              (int) primary_gid)
                        goto end;
                }
        }
@@ -1099,8 +1052,7 @@ end:
 /*
  * Return < 0 on error, 0 if OK, 1 on hangup.
  */
-static
-int handle_one_cmd(run_as_worker_data *worker)
+static int handle_one_cmd(run_as_worker_data *worker)
 {
        int ret = 0, promote_ret;
        struct run_as_data data = {};
@@ -1115,8 +1067,7 @@ int handle_one_cmd(run_as_worker_data *worker)
         * The structure contains the command type and all the parameters needed for
         * its execution
         */
-       readlen = lttcomm_recv_unix_sock(worker->sockpair[1], &data,
-                       sizeof(data));
+       readlen = lttcomm_recv_unix_sock(worker->sockpair[1], &data, sizeof(data));
        if (readlen == 0) {
                /* hang up */
                ret = 1;
@@ -1175,8 +1126,7 @@ write_return:
         * Stage 4: Send run_as_ret structure to the master.
         * This structure contain the return value of the command and the errno.
         */
-       writelen = lttcomm_send_unix_sock(worker->sockpair[1], &sendret,
-                       sizeof(sendret));
+       writelen = lttcomm_send_unix_sock(worker->sockpair[1], &sendret, sizeof(sendret));
        if (writelen < sizeof(sendret)) {
                PERROR("lttcomm_send_unix_sock error");
                ret = -1;
@@ -1204,8 +1154,7 @@ end:
        return ret;
 }
 
-static
-int run_as_worker(run_as_worker_data *worker)
+static int run_as_worker(run_as_worker_data *worker)
 {
        int ret;
        ssize_t writelen;
@@ -1227,8 +1176,7 @@ int run_as_worker(run_as_worker_data *worker)
 
        memset(&sendret, 0, sizeof(sendret));
 
-       writelen = lttcomm_send_unix_sock(worker->sockpair[1], &sendret,
-                       sizeof(sendret));
+       writelen = lttcomm_send_unix_sock(worker->sockpair[1], &sendret, sizeof(sendret));
        if (writelen < sizeof(sendret)) {
                PERROR("lttcomm_send_unix_sock error");
                ret = EXIT_FAILURE;
@@ -1243,7 +1191,7 @@ int run_as_worker(run_as_worker_data *worker)
                } else if (ret > 0) {
                        break;
                } else {
-                       continue;       /* Next command. */
+                       continue; /* Next command. */
                }
        }
        ret = EXIT_SUCCESS;
@@ -1251,12 +1199,12 @@ end:
        return ret;
 }
 
-static
-int run_as_cmd(run_as_worker_data *worker,
-               enum run_as_cmd cmd,
-               struct run_as_data *data,
-               struct run_as_ret *ret_value,
-               uid_t uid, gid_t gid)
+static int run_as_cmd(run_as_worker_data *worker,
+                     enum run_as_cmd cmd,
+                     struct run_as_data *data,
+                     struct run_as_ret *ret_value,
+                     uid_t uid,
+                     gid_t gid)
 {
        int ret = 0;
        ssize_t readlen, writelen;
@@ -1269,7 +1217,8 @@ int run_as_cmd(run_as_worker_data *worker,
                        ret = -1;
                        ret_value->_errno = EPERM;
                        ERR("Client (%d)/Server (%d) UID mismatch (and sessiond is not root)",
-                               (int) uid, (int) geteuid());
+                           (int) uid,
+                           (int) geteuid());
                        goto end;
                }
        }
@@ -1281,8 +1230,7 @@ int run_as_cmd(run_as_worker_data *worker,
        /*
         * Stage 1: Send the run_as_data struct to the worker process
         */
-       writelen = lttcomm_send_unix_sock(worker->sockpair[0], data,
-                       sizeof(*data));
+       writelen = lttcomm_send_unix_sock(worker->sockpair[0], data, sizeof(*data));
        if (writelen < sizeof(*data)) {
                PERROR("Error writing message to run_as");
                ret = -1;
@@ -1309,8 +1257,7 @@ int run_as_cmd(run_as_worker_data *worker,
         * Stage 4: Receive the run_as_ret struct containing the return value and
         * errno
         */
-       readlen = lttcomm_recv_unix_sock(worker->sockpair[0], ret_value,
-                       sizeof(*ret_value));
+       readlen = lttcomm_recv_unix_sock(worker->sockpair[0], ret_value, sizeof(*ret_value));
        if (!readlen) {
                ERR("Run-as worker has hung-up during run_as_cmd");
                ret = -1;
@@ -1345,10 +1292,11 @@ end:
 /*
  * This is for debugging ONLY and should not be considered secure.
  */
-static
-int run_as_noworker(enum run_as_cmd cmd,
-               struct run_as_data *data, struct run_as_ret *ret_value,
-               uid_t uid __attribute__((unused)), gid_t gid __attribute__((unused)))
+static int run_as_noworker(enum run_as_cmd cmd,
+                          struct run_as_data *data,
+                          struct run_as_ret *ret_value,
+                          uid_t uid __attribute__((unused)),
+                          gid_t gid __attribute__((unused)))
 {
        int ret, saved_errno;
        mode_t old_mask;
@@ -1369,8 +1317,7 @@ end:
        return ret;
 }
 
-static
-int reset_sighandler(void)
+static int reset_sighandler()
 {
        int sig;
 
@@ -1381,8 +1328,7 @@ int reset_sighandler(void)
        return 0;
 }
 
-static
-void worker_sighandler(int sig)
+static void worker_sighandler(int sig)
 {
        const char *signame;
 
@@ -1400,7 +1346,7 @@ void worker_sighandler(int sig)
                signame = "SIGTERM";
                break;
        default:
-               signame = NULL;
+               signame = nullptr;
        }
 
        if (signame) {
@@ -1410,8 +1356,7 @@ void worker_sighandler(int sig)
        }
 }
 
-static
-int set_worker_sighandlers(void)
+static int set_worker_sighandlers()
 {
        int ret = 0;
        sigset_t sigset;
@@ -1425,12 +1370,12 @@ int set_worker_sighandlers(void)
        sa.sa_handler = worker_sighandler;
        sa.sa_mask = sigset;
        sa.sa_flags = 0;
-       if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGINT, &sa, nullptr)) < 0) {
                PERROR("sigaction SIGINT");
                goto end;
        }
 
-       if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
+       if ((ret = sigaction(SIGTERM, &sa, nullptr)) < 0) {
                PERROR("sigaction SIGTERM");
                goto end;
        }
@@ -1440,10 +1385,9 @@ end:
        return ret;
 }
 
-static
-int run_as_create_worker_no_lock(const char *procname,
-               post_fork_cleanup_cb clean_up_func,
-               void *clean_up_user_data)
+static int run_as_create_worker_no_lock(const char *procname,
+                                       post_fork_cleanup_cb clean_up_func,
+                                       void *clean_up_user_data)
 {
        pid_t pid;
        int i, ret = 0;
@@ -1537,8 +1481,7 @@ int run_as_create_worker_no_lock(const char *procname,
                worker->sockpair[1] = -1;
                worker->pid = pid;
                /* Wait for worker to become ready. */
-               readlen = lttcomm_recv_unix_sock(worker->sockpair[0],
-                               &recvret, sizeof(recvret));
+               readlen = lttcomm_recv_unix_sock(worker->sockpair[0], &recvret, sizeof(recvret));
                if (readlen < sizeof(recvret)) {
                        ERR("readlen: %zd", readlen);
                        PERROR("Error reading response from run_as at creation");
@@ -1568,8 +1511,7 @@ error_procname_alloc:
        return ret;
 }
 
-static
-void run_as_destroy_worker_no_lock(void)
+static void run_as_destroy_worker_no_lock()
 {
        run_as_worker_data *worker = global_worker;
 
@@ -1599,25 +1541,24 @@ void run_as_destroy_worker_no_lock(void)
 
                if (WIFEXITED(status)) {
                        LOG(WEXITSTATUS(status) == 0 ? PRINT_DBG : PRINT_ERR,
-                                       DEFAULT_RUN_AS_WORKER_NAME " terminated with status code %d",
-                                       WEXITSTATUS(status));
+                           DEFAULT_RUN_AS_WORKER_NAME " terminated with status code %d",
+                           WEXITSTATUS(status));
                        break;
                } else if (WIFSIGNALED(status)) {
                        ERR(DEFAULT_RUN_AS_WORKER_NAME " was killed by signal %d",
-                                       WTERMSIG(status));
+                           WTERMSIG(status));
                        break;
                }
        }
        free(worker->procname);
        free(worker);
-       global_worker = NULL;
+       global_worker = nullptr;
 }
 
-static
-int run_as_restart_worker(run_as_worker_data *worker)
+static int run_as_restart_worker(run_as_worker_data *worker)
 {
        int ret = 0;
-       char *procname = NULL;
+       char *procname = nullptr;
 
        procname = worker->procname;
 
@@ -1625,8 +1566,8 @@ int run_as_restart_worker(run_as_worker_data *worker)
        run_as_destroy_worker_no_lock();
 
        /* Create a new run_as worker process*/
-       ret = run_as_create_worker_no_lock(procname, NULL, NULL);
-       if (ret < 0 ) {
+       ret = run_as_create_worker_no_lock(procname, nullptr, nullptr);
+       if (ret < 0) {
                ERR("Restarting the worker process failed");
                ret = -1;
                goto err;
@@ -1635,9 +1576,11 @@ err:
        return ret;
 }
 
-static
-int run_as(enum run_as_cmd cmd, struct run_as_data *data,
-                  struct run_as_ret *ret_value, uid_t uid, gid_t gid)
+static int run_as(enum run_as_cmd cmd,
+                 struct run_as_data *data,
+                 struct run_as_ret *ret_value,
+                 uid_t uid,
+                 gid_t gid)
 {
        int ret, saved_errno;
 
@@ -1656,7 +1599,7 @@ int run_as(enum run_as_cmd cmd, struct run_as_data *data,
                 */
                if (ret == -1 && saved_errno == EIO) {
                        DBG("Socket closed unexpectedly... "
-                                       "Restarting the worker process");
+                           "Restarting the worker process");
                        ret = run_as_restart_worker(global_worker);
                        if (ret == -1) {
                                ERR("Failed to restart worker process.");
@@ -1677,18 +1620,20 @@ int run_as_mkdir_recursive(const char *path, mode_t mode, uid_t uid, gid_t gid)
        return run_as_mkdirat_recursive(AT_FDCWD, path, mode, uid, gid);
 }
 
-int run_as_mkdirat_recursive(int dirfd, const char *path, mode_t mode,
-               uid_t uid, gid_t gid)
+int run_as_mkdirat_recursive(int dirfd, const char *path, mode_t mode, uid_t uid, gid_t gid)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("mkdirat() recursive fd = %d%s, path = %s, mode = %d, uid = %d, gid = %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, (int) mode, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.mkdir.path, path,
-                       sizeof(data.u.mkdir.path));
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            (int) mode,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.mkdir.path, path, sizeof(data.u.mkdir.path));
        if (ret) {
                ERR("Failed to copy path argument of mkdirat recursive command");
                goto error;
@@ -1697,7 +1642,10 @@ int run_as_mkdirat_recursive(int dirfd, const char *path, mode_t mode,
        data.u.mkdir.mode = mode;
        data.u.mkdir.dirfd = dirfd;
        run_as(dirfd == AT_FDCWD ? RUN_AS_MKDIR_RECURSIVE : RUN_AS_MKDIRAT_RECURSIVE,
-                       &data, &run_as_ret, uid, gid);
+              &data,
+              &run_as_ret,
+              uid,
+              gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
@@ -1709,18 +1657,20 @@ int run_as_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid)
        return run_as_mkdirat(AT_FDCWD, path, mode, uid, gid);
 }
 
-int run_as_mkdirat(int dirfd, const char *path, mode_t mode,
-               uid_t uid, gid_t gid)
+int run_as_mkdirat(int dirfd, const char *path, mode_t mode, uid_t uid, gid_t gid)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("mkdirat() recursive fd = %d%s, path = %s, mode = %d, uid = %d, gid = %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, (int) mode, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.mkdir.path, path,
-                       sizeof(data.u.mkdir.path));
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            (int) mode,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.mkdir.path, path, sizeof(data.u.mkdir.path));
        if (ret) {
                ERR("Failed to copy path argument of mkdirat command");
                goto error;
@@ -1728,30 +1678,32 @@ int run_as_mkdirat(int dirfd, const char *path, mode_t mode,
        data.u.mkdir.path[sizeof(data.u.mkdir.path) - 1] = '\0';
        data.u.mkdir.mode = mode;
        data.u.mkdir.dirfd = dirfd;
-       run_as(dirfd == AT_FDCWD ? RUN_AS_MKDIR : RUN_AS_MKDIRAT,
-                       &data, &run_as_ret, uid, gid);
+       run_as(dirfd == AT_FDCWD ? RUN_AS_MKDIR : RUN_AS_MKDIRAT, &data, &run_as_ret, uid, gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
        return ret;
 }
 
-int run_as_open(const char *path, int flags, mode_t mode, uid_t uid,
-               gid_t gid)
+int run_as_open(const char *path, int flags, mode_t mode, uid_t uid, gid_t gid)
 {
        return run_as_openat(AT_FDCWD, path, flags, mode, uid, gid);
 }
 
-int run_as_openat(int dirfd, const char *path, int flags, mode_t mode,
-               uid_t uid, gid_t gid)
+int run_as_openat(int dirfd, const char *path, int flags, mode_t mode, uid_t uid, gid_t gid)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("openat() fd = %d%s, path = %s, flags = %X, mode = %d, uid %d, gid %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, flags, (int) mode, (int) uid, (int) gid);
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            flags,
+            (int) mode,
+            (int) uid,
+            (int) gid);
        ret = lttng_strncpy(data.u.open.path, path, sizeof(data.u.open.path));
        if (ret) {
                ERR("Failed to copy path argument of open command");
@@ -1760,11 +1712,9 @@ int run_as_openat(int dirfd, const char *path, int flags, mode_t mode,
        data.u.open.flags = flags;
        data.u.open.mode = mode;
        data.u.open.dirfd = dirfd;
-       run_as(dirfd == AT_FDCWD ? RUN_AS_OPEN : RUN_AS_OPENAT,
-                       &data, &run_as_ret, uid, gid);
+       run_as(dirfd == AT_FDCWD ? RUN_AS_OPEN : RUN_AS_OPENAT, &data, &run_as_ret, uid, gid);
        errno = run_as_ret._errno;
-       ret = run_as_ret.u.ret < 0 ? run_as_ret.u.ret :
-                       run_as_ret.u.open.fd;
+       ret = run_as_ret.u.ret < 0 ? run_as_ret.u.ret : run_as_ret.u.open.fd;
 error:
        return ret;
 }
@@ -1781,16 +1731,17 @@ int run_as_unlinkat(int dirfd, const char *path, uid_t uid, gid_t gid)
        struct run_as_ret run_as_ret = {};
 
        DBG3("unlinkat() fd = %d%s, path = %s, uid = %d, gid = %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.unlink.path, path,
-                       sizeof(data.u.unlink.path));
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.unlink.path, path, sizeof(data.u.unlink.path));
        if (ret) {
                goto error;
        }
        data.u.unlink.dirfd = dirfd;
-       run_as(dirfd == AT_FDCWD ? RUN_AS_UNLINK : RUN_AS_UNLINKAT, &data,
-                       &run_as_ret, uid, gid);
+       run_as(dirfd == AT_FDCWD ? RUN_AS_UNLINK : RUN_AS_UNLINKAT, &data, &run_as_ret, uid, gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
@@ -1809,16 +1760,17 @@ int run_as_rmdirat(int dirfd, const char *path, uid_t uid, gid_t gid)
        struct run_as_ret run_as_ret = {};
 
        DBG3("rmdirat() fd = %d%s, path = %s, uid = %d, gid = %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.rmdir.path, path,
-                       sizeof(data.u.rmdir.path));
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.rmdir.path, path, sizeof(data.u.rmdir.path));
        if (ret) {
                goto error;
        }
        data.u.rmdir.dirfd = dirfd;
-       run_as(dirfd == AT_FDCWD ? RUN_AS_RMDIR : RUN_AS_RMDIRAT, &data,
-                       &run_as_ret, uid, gid);
+       run_as(dirfd == AT_FDCWD ? RUN_AS_RMDIR : RUN_AS_RMDIRAT, &data, &run_as_ret, uid, gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
@@ -1837,17 +1789,22 @@ int run_as_rmdirat_recursive(int dirfd, const char *path, uid_t uid, gid_t gid,
        struct run_as_ret run_as_ret = {};
 
        DBG3("rmdirat() recursive fd = %d%s, path = %s, uid = %d, gid = %d",
-                       dirfd, dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       path, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.rmdir.path, path,
-                       sizeof(data.u.rmdir.path));
+            dirfd,
+            dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            path,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.rmdir.path, path, sizeof(data.u.rmdir.path));
        if (ret) {
                goto error;
        }
        data.u.rmdir.dirfd = dirfd;
        data.u.rmdir.flags = flags;
        run_as(dirfd == AT_FDCWD ? RUN_AS_RMDIR_RECURSIVE : RUN_AS_RMDIRAT_RECURSIVE,
-                       &data, &run_as_ret, uid, gid);
+              &data,
+              &run_as_ret,
+              uid,
+              gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
@@ -1859,58 +1816,69 @@ int run_as_rename(const char *old_name, const char *new_name, uid_t uid, gid_t g
        return run_as_renameat(AT_FDCWD, old_name, AT_FDCWD, new_name, uid, gid);
 }
 
-int run_as_renameat(int old_dirfd, const char *old_name,
-               int new_dirfd, const char *new_name, uid_t uid, gid_t gid)
+int run_as_renameat(int old_dirfd,
+                   const char *old_name,
+                   int new_dirfd,
+                   const char *new_name,
+                   uid_t uid,
+                   gid_t gid)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("renameat() old_dirfd = %d%s, old_name = %s, new_dirfd = %d%s, new_name = %s, uid = %d, gid = %d",
-                       old_dirfd, old_dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       old_name,
-                       new_dirfd, new_dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
-                       new_name, (int) uid, (int) gid);
-       ret = lttng_strncpy(data.u.rename.old_path, old_name,
-                       sizeof(data.u.rename.old_path));
+            old_dirfd,
+            old_dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            old_name,
+            new_dirfd,
+            new_dirfd == AT_FDCWD ? " (AT_FDCWD)" : "",
+            new_name,
+            (int) uid,
+            (int) gid);
+       ret = lttng_strncpy(data.u.rename.old_path, old_name, sizeof(data.u.rename.old_path));
        if (ret) {
                goto error;
        }
-       ret = lttng_strncpy(data.u.rename.new_path, new_name,
-                       sizeof(data.u.rename.new_path));
+       ret = lttng_strncpy(data.u.rename.new_path, new_name, sizeof(data.u.rename.new_path));
        if (ret) {
                goto error;
        }
 
        data.u.rename.dirfds[0] = old_dirfd;
        data.u.rename.dirfds[1] = new_dirfd;
-       run_as(old_dirfd == AT_FDCWD && new_dirfd == AT_FDCWD ?
-                       RUN_AS_RENAME : RUN_AS_RENAMEAT,
-                       &data, &run_as_ret, uid, gid);
+       run_as(old_dirfd == AT_FDCWD && new_dirfd == AT_FDCWD ? RUN_AS_RENAME : RUN_AS_RENAMEAT,
+              &data,
+              &run_as_ret,
+              uid,
+              gid);
        errno = run_as_ret._errno;
        ret = run_as_ret.u.ret;
 error:
        return ret;
 }
 
-int run_as_extract_elf_symbol_offset(int fd, const char* function,
-               uid_t uid, gid_t gid, uint64_t *offset)
+int run_as_extract_elf_symbol_offset(
+       int fd, const char *function, uid_t uid, gid_t gid, uint64_t *offset)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("extract_elf_symbol_offset() on fd=%d and function=%s "
-                       "with for uid %d and gid %d", fd, function,
-                       (int) uid, (int) gid);
+            "with for uid %d and gid %d",
+            fd,
+            function,
+            (int) uid,
+            (int) gid);
 
        data.u.extract_elf_symbol_offset.fd = fd;
 
        strncpy(data.u.extract_elf_symbol_offset.function, function, LTTNG_SYMBOL_NAME_LEN - 1);
        data.u.extract_elf_symbol_offset.function[LTTNG_SYMBOL_NAME_LEN - 1] = '\0';
        ret = lttng_strncpy(data.u.extract_elf_symbol_offset.function,
-                       function,
-                       sizeof(data.u.extract_elf_symbol_offset.function));
+                           function,
+                           sizeof(data.u.extract_elf_symbol_offset.function));
        if (ret) {
                goto error;
        }
@@ -1927,28 +1895,37 @@ error:
        return ret;
 }
 
-int run_as_extract_sdt_probe_offsets(int fd, const char* provider_name,
-               const char* probe_name, uid_t uid, gid_t gid,
-               uint64_t **offsets, uint32_t *num_offset)
+int run_as_extract_sdt_probe_offsets(int fd,
+                                    const char *provider_name,
+                                    const char *probe_name,
+                                    uid_t uid,
+                                    gid_t gid,
+                                    uint64_t **offsets,
+                                    uint32_t *num_offset)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
 
        DBG3("extract_sdt_probe_offsets() on fd=%d, probe_name=%s and "
-                       "provider_name=%s with for uid %d and gid %d", fd,
-                       probe_name, provider_name, (int) uid, (int) gid);
+            "provider_name=%s with for uid %d and gid %d",
+            fd,
+            probe_name,
+            provider_name,
+            (int) uid,
+            (int) gid);
 
        data.u.extract_sdt_probe_offsets.fd = fd;
 
-       ret = lttng_strncpy(data.u.extract_sdt_probe_offsets.probe_name, probe_name,
-                       sizeof(data.u.extract_sdt_probe_offsets.probe_name));
+       ret = lttng_strncpy(data.u.extract_sdt_probe_offsets.probe_name,
+                           probe_name,
+                           sizeof(data.u.extract_sdt_probe_offsets.probe_name));
        if (ret) {
                goto error;
        }
        ret = lttng_strncpy(data.u.extract_sdt_probe_offsets.provider_name,
-                       provider_name,
-                       sizeof(data.u.extract_sdt_probe_offsets.provider_name));
+                           provider_name,
+                           sizeof(data.u.extract_sdt_probe_offsets.provider_name));
        if (ret) {
                goto error;
        }
@@ -1967,29 +1944,33 @@ int run_as_extract_sdt_probe_offsets(int fd, const char* provider_name,
                goto error;
        }
 
-       memcpy(*offsets, run_as_ret.u.extract_sdt_probe_offsets.offsets,
-                       *num_offset * sizeof(uint64_t));
+       memcpy(*offsets,
+              run_as_ret.u.extract_sdt_probe_offsets.offsets,
+              *num_offset * sizeof(uint64_t));
 error:
        return ret;
 }
 
 int run_as_generate_filter_bytecode(const char *filter_expression,
-               const struct lttng_credentials *creds,
-               struct lttng_bytecode **bytecode)
+                                   const struct lttng_credentials *creds,
+                                   struct lttng_bytecode **bytecode)
 {
        int ret;
        struct run_as_data data = {};
        struct run_as_ret run_as_ret = {};
-       const struct lttng_bytecode *view_bytecode = NULL;
-       struct lttng_bytecode *local_bytecode = NULL;
+       const struct lttng_bytecode *view_bytecode = nullptr;
+       struct lttng_bytecode *local_bytecode = nullptr;
        const uid_t uid = lttng_credentials_get_uid(creds);
        const gid_t gid = lttng_credentials_get_gid(creds);
 
        DBG3("generate_filter_bytecode() from expression=\"%s\" for uid %d and gid %d",
-                       filter_expression, (int) uid, (int) gid);
+            filter_expression,
+            (int) uid,
+            (int) gid);
 
-       ret = lttng_strncpy(data.u.generate_filter_bytecode.filter_expression, filter_expression,
-                       sizeof(data.u.generate_filter_bytecode.filter_expression));
+       ret = lttng_strncpy(data.u.generate_filter_bytecode.filter_expression,
+                           filter_expression,
+                           sizeof(data.u.generate_filter_bytecode.filter_expression));
        if (ret) {
                goto error;
        }
@@ -2001,7 +1982,8 @@ int run_as_generate_filter_bytecode(const char *filter_expression,
                goto error;
        }
 
-       view_bytecode = (const struct lttng_bytecode *) run_as_ret.u.generate_filter_bytecode.bytecode;
+       view_bytecode =
+               (const struct lttng_bytecode *) run_as_ret.u.generate_filter_bytecode.bytecode;
 
        local_bytecode = calloc<lttng_bytecode>(view_bytecode->len);
        if (!local_bytecode) {
@@ -2009,27 +1991,27 @@ int run_as_generate_filter_bytecode(const char *filter_expression,
                goto error;
        }
 
-       memcpy(local_bytecode, run_as_ret.u.generate_filter_bytecode.bytecode,
-                       sizeof(*local_bytecode) + view_bytecode->len);
+       memcpy(local_bytecode,
+              run_as_ret.u.generate_filter_bytecode.bytecode,
+              sizeof(*local_bytecode) + view_bytecode->len);
        *bytecode = local_bytecode;
 error:
        return ret;
 }
 
 int run_as_create_worker(const char *procname,
-               post_fork_cleanup_cb clean_up_func,
-               void *clean_up_user_data)
+                        post_fork_cleanup_cb clean_up_func,
+                        void *clean_up_user_data)
 {
        int ret;
 
        pthread_mutex_lock(&worker_lock);
-       ret = run_as_create_worker_no_lock(procname, clean_up_func,
-                       clean_up_user_data);
+       ret = run_as_create_worker_no_lock(procname, clean_up_func, clean_up_user_data);
        pthread_mutex_unlock(&worker_lock);
        return ret;
 }
 
-void run_as_destroy_worker(void)
+void run_as_destroy_worker()
 {
        pthread_mutex_lock(&worker_lock);
        run_as_destroy_worker_no_lock();
index 1732286b8ed631f4e5585f37e8f3e27bb030c9cc..db3ba5042f3b1e7a07e27514b04e4a44fefe0aaa 100644 (file)
@@ -9,13 +9,13 @@
  *
  */
 
+#include <common/macros.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <stdint.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/macros.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-
 /*
  * The run-as process is launched by forking without an exec*() call. This means
  * that any resource allocated before the run-as worker is launched should be
  * A negative return value will cause the run-as process to exit with a non-zero
  * value.
  */
-typedef int (*post_fork_cleanup_cb)(void *user_data);
+using post_fork_cleanup_cb = int (*)(void *);
 
 int run_as_mkdir_recursive(const char *path, mode_t mode, uid_t uid, gid_t gid);
-int run_as_mkdirat_recursive(int dirfd, const char *path, mode_t mode,
-               uid_t uid, gid_t gid);
+int run_as_mkdirat_recursive(int dirfd, const char *path, mode_t mode, uid_t uid, gid_t gid);
 int run_as_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid);
-int run_as_mkdirat(int dirfd, const char *path, mode_t mode,
-               uid_t uid, gid_t gid);
+int run_as_mkdirat(int dirfd, const char *path, mode_t mode, uid_t uid, gid_t gid);
 int run_as_open(const char *path, int flags, mode_t mode, uid_t uid, gid_t gid);
-int run_as_openat(int dirfd, const char *filename, int flags, mode_t mode,
-               uid_t uid, gid_t gid);
+int run_as_openat(int dirfd, const char *filename, int flags, mode_t mode, uid_t uid, gid_t gid);
 int run_as_unlink(const char *path, uid_t uid, gid_t gid);
 int run_as_unlinkat(int dirfd, const char *filename, uid_t uid, gid_t gid);
 int run_as_rmdir(const char *path, uid_t uid, gid_t gid);
@@ -47,18 +44,27 @@ int run_as_rmdir_recursive(const char *path, uid_t uid, gid_t gid, int flags);
 int run_as_rmdirat(int dirfd, const char *path, uid_t uid, gid_t gid);
 int run_as_rmdirat_recursive(int dirfd, const char *path, uid_t uid, gid_t gid, int flags);
 int run_as_rename(const char *old_name, const char *new_name, uid_t uid, gid_t gid);
-int run_as_renameat(int old_dirfd, const char *old_name,
-               int new_dirfd, const char *new_name, uid_t uid, gid_t gid);
-int run_as_extract_elf_symbol_offset(int fd, const char* function,
-               uid_t uid, gid_t gid, uint64_t *offset);
-int run_as_extract_sdt_probe_offsets(int fd, const char *provider_name,
-               const char* probe_name, uid_t uid, gid_t gid,
-               uint64_t **offsets, uint32_t *num_offset);
+int run_as_renameat(int old_dirfd,
+                   const char *old_name,
+                   int new_dirfd,
+                   const char *new_name,
+                   uid_t uid,
+                   gid_t gid);
+int run_as_extract_elf_symbol_offset(
+       int fd, const char *function, uid_t uid, gid_t gid, uint64_t *offset);
+int run_as_extract_sdt_probe_offsets(int fd,
+                                    const char *provider_name,
+                                    const char *probe_name,
+                                    uid_t uid,
+                                    gid_t gid,
+                                    uint64_t **offsets,
+                                    uint32_t *num_offset);
 int run_as_generate_filter_bytecode(const char *filter_expression,
-               const struct lttng_credentials *creds,
-               struct lttng_bytecode **bytecode);
+                                   const struct lttng_credentials *creds,
+                                   struct lttng_bytecode **bytecode);
 int run_as_create_worker(const char *procname,
-               post_fork_cleanup_cb clean_up_func, void *clean_up_user_data);
-void run_as_destroy_worker(void);
+                        post_fork_cleanup_cb clean_up_func,
+                        void *clean_up_user_data);
+void run_as_destroy_worker();
 
 #endif /* _RUNAS_H */
diff --git a/src/common/scope-exit.hpp b/src/common/scope-exit.hpp
new file mode 100644 (file)
index 0000000..3f8c90f
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_SCOPE_EXIT_H
+#define LTTNG_SCOPE_EXIT_H
+
+#include <utility>
+
+namespace lttng {
+
+namespace details {
+/* Is operator() of InvocableType is marked as noexcept? */
+template <typename InvocableType>
+struct is_invocation_noexcept
+       : std::integral_constant<bool, noexcept((std::declval<InvocableType>())())> {
+};
+} /* namespace details. */
+
+/*
+ * Generic utility to run a lambda (or any other invocable object) when leaving
+ * a scope.
+ *
+ * Notably, this makes it easy to specify an action (e.g. restore a context)
+ * that must occur at the end of a function or roll-back operations in an
+ * exception-safe way.
+ */
+template <typename ScopeExitInvocableType>
+class scope_exit {
+public:
+       /*
+        * Since ScopeExitInvocableType will be invoked in the destructor, it
+        * must be `noexcept` lest we anger the undefined behaviour gods by throwing
+        * an exception while an exception is active.
+        */
+       static_assert(details::is_invocation_noexcept<ScopeExitInvocableType>::value,
+                     "scope_exit requires a noexcept invocable type");
+
+       explicit scope_exit(ScopeExitInvocableType&& scope_exit_callable) :
+               _on_scope_exit{ std::forward<ScopeExitInvocableType>(scope_exit_callable) }
+       {
+       }
+
+       scope_exit(scope_exit&& rhs) noexcept :
+               _on_scope_exit{ std::move(rhs._on_scope_exit) }, _armed{ rhs._armed }
+       {
+               /* Don't invoke ScopeExitInvocableType for the moved-from copy. */
+               rhs.disarm();
+       }
+
+       /*
+        * The copy constructor is disabled to prevent the action from being
+        * executed twice should a copy be performed accidentaly.
+        *
+        * The move-constructor is present to enable make_scope_exit() but to
+        * also propagate the scope_exit to another scope, should it be needed.
+        */
+       scope_exit(const scope_exit&) = delete;
+       scope_exit& operator=(const scope_exit&) = delete;
+       scope_exit& operator=(scope_exit&&) = delete;
+       scope_exit() = delete;
+
+       void disarm() noexcept
+       {
+               _armed = false;
+       }
+
+       ~scope_exit()
+       {
+               if (_armed) {
+                       _on_scope_exit();
+               }
+       }
+
+private:
+       ScopeExitInvocableType _on_scope_exit;
+       bool _armed = true;
+};
+
+template <typename ScopeExitInvocableType>
+scope_exit<ScopeExitInvocableType> make_scope_exit(ScopeExitInvocableType&& scope_exit_callable)
+{
+       return scope_exit<ScopeExitInvocableType>(
+               std::forward<ScopeExitInvocableType>(scope_exit_callable));
+}
+
+} /* namespace lttng */
+
+#endif /* LTTNG_SCOPE_EXIT_H */
index 1171b2930ce605c2ee465476cd5d4541cd48a646..55db55e5cea78cc7cec48c1b3d986e9a2345810c 100644 (file)
@@ -4,13 +4,15 @@
  * SPDX-License-Identifier: LGPL-2.1-only
  */
 
-#include <lttng/session-descriptor-internal.hpp>
-#include <common/macros.hpp>
-#include <common/uri.hpp>
 #include <common/defaults.hpp>
 #include <common/error.hpp>
-#include <time.h>
+#include <common/macros.hpp>
+#include <common/uri.hpp>
+
+#include <lttng/session-descriptor-internal.hpp>
+
 #include <stdio.h>
+#include <time.h>
 
 namespace {
 struct lttng_session_descriptor_network_location {
@@ -66,10 +68,9 @@ struct lttng_session_descriptor_live_comm {
 } LTTNG_PACKED;
 } /* namespace */
 
-static
-struct lttng_uri *uri_copy(const struct lttng_uri *uri)
+static struct lttng_uri *uri_copy(const struct lttng_uri *uri)
 {
-       struct lttng_uri *new_uri = NULL;
+       struct lttng_uri *new_uri = nullptr;
 
        if (!uri) {
                goto end;
@@ -84,13 +85,11 @@ end:
        return new_uri;
 }
 
-static
-struct lttng_uri *uri_from_path(const char *path)
+static struct lttng_uri *uri_from_path(const char *path)
 {
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
        ssize_t uri_count;
-       char local_protocol_string[LTTNG_PATH_MAX + sizeof("file://")] =
-                       "file://";
+       char local_protocol_string[LTTNG_PATH_MAX + sizeof("file://")] = "file://";
 
        if (strlen(path) >= LTTNG_PATH_MAX) {
                goto end;
@@ -114,22 +113,20 @@ end:
        return uris;
 error:
        free(uris);
-       return NULL;
+       return nullptr;
 }
 
-static
-void network_location_fini(
-               struct lttng_session_descriptor_network_location *location)
+static void network_location_fini(struct lttng_session_descriptor_network_location *location)
 {
        free(location->control);
        free(location->data);
 }
 
 /* Assumes ownership of control and data. */
-static
-int network_location_set_from_lttng_uris(
-               struct lttng_session_descriptor_network_location *location,
-               struct lttng_uri *control, struct lttng_uri *data)
+static int
+network_location_set_from_lttng_uris(struct lttng_session_descriptor_network_location *location,
+                                    struct lttng_uri *control,
+                                    struct lttng_uri *data)
 {
        int ret = 0;
 
@@ -143,8 +140,7 @@ int network_location_set_from_lttng_uris(
                goto end;
        }
 
-       if (control->stype != LTTNG_STREAM_CONTROL ||
-                       data->stype != LTTNG_STREAM_DATA) {
+       if (control->stype != LTTNG_STREAM_CONTROL || data->stype != LTTNG_STREAM_DATA) {
                ret = -1;
                goto end;
        }
@@ -153,24 +149,24 @@ int network_location_set_from_lttng_uris(
        free(location->data);
        location->control = control;
        location->data = data;
-       control = NULL;
-       data = NULL;
+       control = nullptr;
+       data = nullptr;
 end:
        free(control);
        free(data);
        return ret;
 }
 
-static
-int network_location_set_from_uri_strings(
-               struct lttng_session_descriptor_network_location *location,
-               const char *control, const char *data)
+static int
+network_location_set_from_uri_strings(struct lttng_session_descriptor_network_location *location,
+                                     const char *control,
+                                     const char *data)
 {
        int ret = 0;
        ssize_t uri_count;
-       struct lttng_uri *parsed_uris = NULL;
-       struct lttng_uri *control_uri = NULL;
-       struct lttng_uri *data_uri = NULL;
+       struct lttng_uri *parsed_uris = nullptr;
+       struct lttng_uri *control_uri = nullptr;
+       struct lttng_uri *data_uri = nullptr;
 
        uri_count = uri_parse_str_urls(control, data, &parsed_uris);
        if (uri_count != 2 && uri_count != 0) {
@@ -194,12 +190,9 @@ int network_location_set_from_uri_strings(
        }
 
        /* Ownership of control and data uris is transferred. */
-       ret = network_location_set_from_lttng_uris(
-                       location,
-                       control_uri,
-                       data_uri);
-       control_uri = NULL;
-       data_uri = NULL;
+       ret = network_location_set_from_lttng_uris(location, control_uri, data_uri);
+       control_uri = nullptr;
+       data_uri = nullptr;
 end:
        free(parsed_uris);
        free(control_uri);
@@ -207,8 +200,7 @@ end:
        return ret;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_create(const char *name)
+struct lttng_session_descriptor *lttng_session_descriptor_create(const char *name)
 {
        struct lttng_session_descriptor *descriptor;
 
@@ -218,22 +210,19 @@ lttng_session_descriptor_create(const char *name)
        }
 
        descriptor->type = LTTNG_SESSION_DESCRIPTOR_TYPE_REGULAR;
-       descriptor->output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
+       descriptor->output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
        if (lttng_session_descriptor_set_session_name(descriptor, name)) {
                goto error;
        }
        return descriptor;
 error:
        lttng_session_descriptor_destroy(descriptor);
-       return NULL;
+       return nullptr;
 }
 
 /* Ownership of uri is transferred. */
-static
-struct lttng_session_descriptor *
-_lttng_session_descriptor_local_create(const char *name,
-               struct lttng_uri *uri)
+static struct lttng_session_descriptor *
+_lttng_session_descriptor_local_create(const char *name, struct lttng_uri *uri)
 {
        struct lttng_session_descriptor *descriptor;
 
@@ -242,26 +231,25 @@ _lttng_session_descriptor_local_create(const char *name,
                goto error;
        }
        descriptor->type = LTTNG_SESSION_DESCRIPTOR_TYPE_REGULAR;
-       descriptor->output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL;
+       descriptor->output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL;
        if (uri) {
                if (uri->dtype != LTTNG_DST_PATH) {
                        goto error;
                }
                descriptor->output.local = uri;
-               uri = NULL;
+               uri = nullptr;
        }
        return descriptor;
 error:
        free(uri);
        lttng_session_descriptor_destroy(descriptor);
-       return NULL;
+       return nullptr;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_local_create(const char *name, const char *path)
+struct lttng_session_descriptor *lttng_session_descriptor_local_create(const char *name,
+                                                                      const char *path)
 {
-       struct lttng_uri *uri = NULL;
+       struct lttng_uri *uri = nullptr;
        struct lttng_session_descriptor *descriptor;
 
        if (path) {
@@ -273,14 +261,12 @@ lttng_session_descriptor_local_create(const char *name, const char *path)
        descriptor = _lttng_session_descriptor_local_create(name, uri);
        return descriptor;
 error:
-       return NULL;
+       return nullptr;
 }
 
 /* Assumes the ownership of both uris. */
-static
-struct lttng_session_descriptor *
-_lttng_session_descriptor_network_create(const char *name,
-               struct lttng_uri *control, struct lttng_uri *data)
+static struct lttng_session_descriptor *_lttng_session_descriptor_network_create(
+       const char *name, struct lttng_uri *control, struct lttng_uri *data)
 {
        int ret;
        struct lttng_session_descriptor *descriptor;
@@ -293,10 +279,9 @@ _lttng_session_descriptor_network_create(const char *name,
        descriptor->type = LTTNG_SESSION_DESCRIPTOR_TYPE_REGULAR;
        descriptor->output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK;
        /* Assumes the ownership of both uris. */
-       ret = network_location_set_from_lttng_uris(&descriptor->output.network,
-                       control, data);
-       control = NULL;
-       data = NULL;
+       ret = network_location_set_from_lttng_uris(&descriptor->output.network, control, data);
+       control = nullptr;
+       data = nullptr;
        if (ret) {
                goto error;
        }
@@ -305,35 +290,33 @@ error:
        lttng_session_descriptor_destroy(descriptor);
        free(control);
        free(data);
-       return NULL;
+       return nullptr;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_network_create(const char *name,
-               const char *control_url, const char *data_url)
+struct lttng_session_descriptor *lttng_session_descriptor_network_create(const char *name,
+                                                                        const char *control_url,
+                                                                        const char *data_url)
 {
        int ret;
        struct lttng_session_descriptor *descriptor;
 
-       descriptor = _lttng_session_descriptor_network_create(name,
-                       NULL, NULL);
+       descriptor = _lttng_session_descriptor_network_create(name, nullptr, nullptr);
        if (!descriptor) {
                goto error;
        }
 
-       ret = network_location_set_from_uri_strings(&descriptor->output.network,
-                       control_url, data_url);
+       ret = network_location_set_from_uri_strings(
+               &descriptor->output.network, control_url, data_url);
        if (ret) {
                goto error;
        }
        return descriptor;
 error:
        lttng_session_descriptor_destroy(descriptor);
-       return NULL;
+       return nullptr;
 }
 
-static
-struct lttng_session_descriptor_snapshot *
+static struct lttng_session_descriptor_snapshot *
 _lttng_session_descriptor_snapshot_create(const char *name)
 {
        struct lttng_session_descriptor_snapshot *descriptor;
@@ -344,23 +327,19 @@ _lttng_session_descriptor_snapshot_create(const char *name)
        }
 
        descriptor->base.type = LTTNG_SESSION_DESCRIPTOR_TYPE_SNAPSHOT;
-       descriptor->base.output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
-       if (lttng_session_descriptor_set_session_name(&descriptor->base,
-                       name)) {
+       descriptor->base.output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
+       if (lttng_session_descriptor_set_session_name(&descriptor->base, name)) {
                goto error;
        }
        return descriptor;
 error:
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
 /* Ownership of control and data is transferred. */
-static
-struct lttng_session_descriptor_snapshot *
-_lttng_session_descriptor_snapshot_network_create(const char *name,
-               struct lttng_uri *control, struct lttng_uri *data)
+static struct lttng_session_descriptor_snapshot *_lttng_session_descriptor_snapshot_network_create(
+       const char *name, struct lttng_uri *control, struct lttng_uri *data)
 {
        int ret;
        struct lttng_session_descriptor_snapshot *descriptor;
@@ -370,14 +349,11 @@ _lttng_session_descriptor_snapshot_network_create(const char *name,
                goto error;
        }
 
-       descriptor->base.output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK;
+       descriptor->base.output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK;
        /* Ownership of control and data is transferred. */
-       ret = network_location_set_from_lttng_uris(
-                       &descriptor->base.output.network,
-                       control, data);
-       control = NULL;
-       data = NULL;
+       ret = network_location_set_from_lttng_uris(&descriptor->base.output.network, control, data);
+       control = nullptr;
+       data = nullptr;
        if (ret) {
                goto error;
        }
@@ -385,49 +361,43 @@ _lttng_session_descriptor_snapshot_network_create(const char *name,
 error:
        free(control);
        free(data);
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_create(const char *name)
+struct lttng_session_descriptor *lttng_session_descriptor_snapshot_create(const char *name)
 {
        struct lttng_session_descriptor_snapshot *descriptor;
 
        descriptor = _lttng_session_descriptor_snapshot_create(name);
-       return descriptor ? &descriptor->base : NULL;
+       return descriptor ? &descriptor->base : nullptr;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_network_create(const char *name,
-               const char *control_url, const char *data_url)
+struct lttng_session_descriptor *lttng_session_descriptor_snapshot_network_create(
+       const char *name, const char *control_url, const char *data_url)
 {
        int ret;
        struct lttng_session_descriptor_snapshot *descriptor;
 
-       descriptor = _lttng_session_descriptor_snapshot_network_create(name,
-                       NULL, NULL);
+       descriptor = _lttng_session_descriptor_snapshot_network_create(name, nullptr, nullptr);
        if (!descriptor) {
                goto error;
        }
 
        ret = network_location_set_from_uri_strings(
-                       &descriptor->base.output.network,
-                       control_url, data_url);
+               &descriptor->base.output.network, control_url, data_url);
        if (ret) {
                goto error;
        }
        return &descriptor->base;
 error:
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
 /* Ownership of uri is transferred. */
-static
-struct lttng_session_descriptor_snapshot *
-_lttng_session_descriptor_snapshot_local_create(const char *name,
-               struct lttng_uri *uri)
+static struct lttng_session_descriptor_snapshot *
+_lttng_session_descriptor_snapshot_local_create(const char *name, struct lttng_uri *uri)
 {
        struct lttng_session_descriptor_snapshot *descriptor;
 
@@ -435,27 +405,25 @@ _lttng_session_descriptor_snapshot_local_create(const char *name,
        if (!descriptor) {
                goto error;
        }
-       descriptor->base.output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL;
+       descriptor->base.output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL;
        if (uri) {
                if (uri->dtype != LTTNG_DST_PATH) {
                        goto error;
                }
                descriptor->base.output.local = uri;
-               uri = NULL;
+               uri = nullptr;
        }
        return descriptor;
 error:
        free(uri);
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
-struct lttng_session_descriptor *
-lttng_session_descriptor_snapshot_local_create(const char *name,
-               const char *path)
+struct lttng_session_descriptor *lttng_session_descriptor_snapshot_local_create(const char *name,
+                                                                               const char *path)
 {
-       struct lttng_uri *path_uri = NULL;
+       struct lttng_uri *path_uri = nullptr;
        struct lttng_session_descriptor_snapshot *descriptor;
 
        if (path) {
@@ -464,19 +432,16 @@ lttng_session_descriptor_snapshot_local_create(const char *name,
                        goto error;
                }
        }
-       descriptor = _lttng_session_descriptor_snapshot_local_create(name,
-                       path_uri);
-       return descriptor ? &descriptor->base : NULL;
+       descriptor = _lttng_session_descriptor_snapshot_local_create(name, path_uri);
+       return descriptor ? &descriptor->base : nullptr;
 error:
-       return NULL;
+       return nullptr;
 }
 
-static
-struct lttng_session_descriptor_live *
-_lttng_session_descriptor_live_create(const char *name,
-               unsigned long long live_timer_interval_us)
+static struct lttng_session_descriptor_live *
+_lttng_session_descriptor_live_create(const char *name, unsigned long long live_timer_interval_us)
 {
-       struct lttng_session_descriptor_live *descriptor = NULL;
+       struct lttng_session_descriptor_live *descriptor = nullptr;
 
        if (live_timer_interval_us == 0) {
                goto error;
@@ -487,46 +452,39 @@ _lttng_session_descriptor_live_create(const char *name,
        }
 
        descriptor->base.type = LTTNG_SESSION_DESCRIPTOR_TYPE_LIVE;
-       descriptor->base.output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
+       descriptor->base.output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE;
        descriptor->live_timer_us = live_timer_interval_us;
-       if (lttng_session_descriptor_set_session_name(&descriptor->base,
-                       name)) {
+       if (lttng_session_descriptor_set_session_name(&descriptor->base, name)) {
                goto error;
        }
 
        return descriptor;
 error:
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
 /* Ownership of control and data is transferred. */
-static
-struct lttng_session_descriptor_live *
-_lttng_session_descriptor_live_network_create(
-               const char *name,
-               struct lttng_uri *control, struct lttng_uri *data,
-               unsigned long long live_timer_interval_us)
+static struct lttng_session_descriptor_live *
+_lttng_session_descriptor_live_network_create(const char *name,
+                                             struct lttng_uri *control,
+                                             struct lttng_uri *data,
+                                             unsigned long long live_timer_interval_us)
 {
        int ret;
        struct lttng_session_descriptor_live *descriptor;
 
-       descriptor = _lttng_session_descriptor_live_create(name,
-                       live_timer_interval_us);
+       descriptor = _lttng_session_descriptor_live_create(name, live_timer_interval_us);
        if (!descriptor) {
                goto error;
        }
 
-       descriptor->base.output_type =
-                       LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK;
+       descriptor->base.output_type = LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK;
 
        /* Ownerwhip of control and data is transferred. */
-       ret = network_location_set_from_lttng_uris(
-                       &descriptor->base.output.network,
-                       control, data);
-       control = NULL;
-       data = NULL;
+       ret = network_location_set_from_lttng_uris(&descriptor->base.output.network, control, data);
+       control = nullptr;
+       data = nullptr;
        if (ret) {
                goto error;
        }
@@ -534,51 +492,47 @@ _lttng_session_descriptor_live_network_create(
 error:
        free(control);
        free(data);
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
 struct lttng_session_descriptor *
-lttng_session_descriptor_live_create(
-               const char *name,
-               unsigned long long live_timer_us)
+lttng_session_descriptor_live_create(const char *name, unsigned long long live_timer_us)
 {
        struct lttng_session_descriptor_live *descriptor;
 
        descriptor = _lttng_session_descriptor_live_create(name, live_timer_us);
 
-       return descriptor ? &descriptor->base : NULL;
+       return descriptor ? &descriptor->base : nullptr;
 }
 
 struct lttng_session_descriptor *
-lttng_session_descriptor_live_network_create(
-               const char *name,
-               const char *control_url, const char *data_url,
-               unsigned long long live_timer_us)
+lttng_session_descriptor_live_network_create(const char *name,
+                                            const char *control_url,
+                                            const char *data_url,
+                                            unsigned long long live_timer_us)
 {
        int ret;
        struct lttng_session_descriptor_live *descriptor;
 
-       descriptor = _lttng_session_descriptor_live_network_create(name,
-                       NULL, NULL, live_timer_us);
+       descriptor = _lttng_session_descriptor_live_network_create(
+               name, nullptr, nullptr, live_timer_us);
        if (!descriptor) {
                goto error;
        }
 
        ret = network_location_set_from_uri_strings(
-                       &descriptor->base.output.network,
-                       control_url, data_url);
+               &descriptor->base.output.network, control_url, data_url);
        if (ret) {
                goto error;
        }
        return &descriptor->base;
 error:
-       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : NULL);
-       return NULL;
+       lttng_session_descriptor_destroy(descriptor ? &descriptor->base : nullptr);
+       return nullptr;
 }
 
-void lttng_session_descriptor_destroy(
-               struct lttng_session_descriptor *descriptor)
+void lttng_session_descriptor_destroy(struct lttng_session_descriptor *descriptor)
 {
        if (!descriptor) {
                return;
@@ -601,14 +555,13 @@ void lttng_session_descriptor_destroy(
        free(descriptor);
 }
 
-ssize_t lttng_session_descriptor_create_from_buffer(
-               const struct lttng_buffer_view *payload,
-               struct lttng_session_descriptor **descriptor)
+ssize_t lttng_session_descriptor_create_from_buffer(const struct lttng_buffer_view *payload,
+                                                   struct lttng_session_descriptor **descriptor)
 {
        int i;
        ssize_t offset = 0, ret;
        struct lttng_buffer_view current_view;
-       const char *name = NULL;
+       const char *name = nullptr;
        const struct lttng_session_descriptor_comm *base_header;
        size_t max_expected_uri_count;
        uint64_t live_timer_us = 0;
@@ -616,8 +569,7 @@ ssize_t lttng_session_descriptor_create_from_buffer(
        enum lttng_session_descriptor_type type;
        enum lttng_session_descriptor_output_type output_type;
 
-       current_view = lttng_buffer_view_from_view(payload, offset,
-                       sizeof(*base_header));
+       current_view = lttng_buffer_view_from_view(payload, offset, sizeof(*base_header));
        if (!lttng_buffer_view_is_valid(&current_view)) {
                ret = -1;
                goto end;
@@ -632,8 +584,7 @@ ssize_t lttng_session_descriptor_create_from_buffer(
        {
                const struct lttng_session_descriptor_live_comm *live_header;
 
-               current_view = lttng_buffer_view_from_view(payload, offset,
-                               sizeof(*live_header));
+               current_view = lttng_buffer_view_from_view(payload, offset, sizeof(*live_header));
                if (!lttng_buffer_view_is_valid(&current_view)) {
                        ret = -1;
                        goto end;
@@ -674,17 +625,15 @@ ssize_t lttng_session_descriptor_create_from_buffer(
        }
 
        /* Map the name. */
-       current_view = lttng_buffer_view_from_view(payload, offset,
-                       base_header->name_len);
+       current_view = lttng_buffer_view_from_view(payload, offset, base_header->name_len);
        if (!lttng_buffer_view_is_valid(&current_view)) {
                ret = -1;
                goto end;
        }
 
        name = current_view.data;
-       if (base_header->name_len == 1 ||
-                       name[base_header->name_len - 1] ||
-                       strlen(name) != base_header->name_len - 1) {
+       if (base_header->name_len == 1 || name[base_header->name_len - 1] ||
+           strlen(name) != base_header->name_len - 1) {
                /*
                 * Check that the name is not NULL, is NULL-terminated, and
                 * does not contain a NULL before the last byte.
@@ -705,8 +654,7 @@ skip_name:
                struct lttng_uri *uri;
 
                /* Map a URI. */
-               current_view = lttng_buffer_view_from_view(payload,
-                               offset, sizeof(*uri));
+               current_view = lttng_buffer_view_from_view(payload, offset, sizeof(*uri));
                if (!lttng_buffer_view_is_valid(&current_view)) {
                        ret = -1;
                        goto end;
@@ -729,12 +677,11 @@ skip_name:
                        *descriptor = lttng_session_descriptor_create(name);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL:
-                       *descriptor = _lttng_session_descriptor_local_create(
-                                       name, uris[0]);
+                       *descriptor = _lttng_session_descriptor_local_create(name, uris[0]);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
-                       *descriptor = _lttng_session_descriptor_network_create(
-                                       name, uris[0], uris[1]);
+                       *descriptor =
+                               _lttng_session_descriptor_network_create(name, uris[0], uris[1]);
                        break;
                default:
                        /* Already checked. */
@@ -746,22 +693,20 @@ skip_name:
                struct lttng_session_descriptor_snapshot *snapshot;
                switch (output_type) {
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
-                       snapshot = _lttng_session_descriptor_snapshot_create(
-                                       name);
+                       snapshot = _lttng_session_descriptor_snapshot_create(name);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL:
-                       snapshot = _lttng_session_descriptor_snapshot_local_create(
-                                       name, uris[0]);
+                       snapshot = _lttng_session_descriptor_snapshot_local_create(name, uris[0]);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
                        snapshot = _lttng_session_descriptor_snapshot_network_create(
-                                       name, uris[0], uris[1]);
+                               name, uris[0], uris[1]);
                        break;
                default:
                        /* Already checked. */
                        abort();
                }
-               *descriptor = snapshot ? &snapshot->base : NULL;
+               *descriptor = snapshot ? &snapshot->base : nullptr;
                break;
        }
        case LTTNG_SESSION_DESCRIPTOR_TYPE_LIVE:
@@ -770,13 +715,11 @@ skip_name:
 
                switch (output_type) {
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
-                       live = _lttng_session_descriptor_live_create(
-                                       name, live_timer_us);
+                       live = _lttng_session_descriptor_live_create(name, live_timer_us);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
                        live = _lttng_session_descriptor_live_network_create(
-                                       name, uris[0], uris[1],
-                                       live_timer_us);
+                               name, uris[0], uris[1], live_timer_us);
                        break;
                case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_LOCAL:
                        ret = -1;
@@ -785,7 +728,7 @@ skip_name:
                        /* Already checked. */
                        abort();
                }
-               *descriptor = live ? &live->base : NULL;
+               *descriptor = live ? &live->base : nullptr;
                break;
        }
        default:
@@ -805,9 +748,8 @@ end:
        return ret;
 }
 
-int lttng_session_descriptor_serialize(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_dynamic_buffer *buffer)
+int lttng_session_descriptor_serialize(const struct lttng_session_descriptor *descriptor,
+                                      struct lttng_dynamic_buffer *buffer)
 {
        int ret, i;
        /* There are, at most, two URIs to serialize. */
@@ -825,7 +767,7 @@ int lttng_session_descriptor_serialize(
                .live_timer_us = 0,
 
        };
-       const void *header_ptr = NULL;
+       const void *header_ptr = nullptr;
        size_t header_size;
 
        switch (descriptor->output_type) {
@@ -848,7 +790,7 @@ int lttng_session_descriptor_serialize(
        header.base.uri_count = uri_count;
        if (descriptor->type == LTTNG_SESSION_DESCRIPTOR_TYPE_LIVE) {
                const struct lttng_session_descriptor_live *live = lttng::utils::container_of(
-                               descriptor, &lttng_session_descriptor_live::base);
+                       descriptor, &lttng_session_descriptor_live::base);
 
                header.live_timer_us = live->live_timer_us;
                header_ptr = &header;
@@ -863,16 +805,14 @@ int lttng_session_descriptor_serialize(
                goto end;
        }
        if (header.base.name_len) {
-               ret = lttng_dynamic_buffer_append(buffer, descriptor->name,
-                               header.base.name_len);
+               ret = lttng_dynamic_buffer_append(buffer, descriptor->name, header.base.name_len);
                if (ret) {
                        goto end;
                }
        }
 
        for (i = 0; i < uri_count; i++) {
-               ret = lttng_dynamic_buffer_append(buffer, uris[i],
-                               sizeof(struct lttng_uri));
+               ret = lttng_dynamic_buffer_append(buffer, uris[i], sizeof(struct lttng_uri));
                if (ret) {
                        goto end;
                }
@@ -882,38 +822,34 @@ end:
 }
 
 enum lttng_session_descriptor_type
-lttng_session_descriptor_get_type(
-               const struct lttng_session_descriptor *descriptor)
+lttng_session_descriptor_get_type(const struct lttng_session_descriptor *descriptor)
 {
        return descriptor->type;
 }
 
 enum lttng_session_descriptor_output_type
-lttng_session_descriptor_get_output_type(
-               const struct lttng_session_descriptor *descriptor)
+lttng_session_descriptor_get_output_type(const struct lttng_session_descriptor *descriptor)
 {
        return descriptor->output_type;
 }
 
 void lttng_session_descriptor_get_local_output_uri(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_uri *local_uri)
+       const struct lttng_session_descriptor *descriptor, struct lttng_uri *local_uri)
 {
        memcpy(local_uri, descriptor->output.local, sizeof(*local_uri));
 }
 
 void lttng_session_descriptor_get_network_output_uris(
-               const struct lttng_session_descriptor *descriptor,
-               struct lttng_uri *control,
-               struct lttng_uri *data)
+       const struct lttng_session_descriptor *descriptor,
+       struct lttng_uri *control,
+       struct lttng_uri *data)
 {
        memcpy(control, descriptor->output.network.control, sizeof(*control));
        memcpy(data, descriptor->output.network.data, sizeof(*data));
 }
 
 unsigned long long
-lttng_session_descriptor_live_get_timer_interval(
-               const struct lttng_session_descriptor *descriptor)
+lttng_session_descriptor_live_get_timer_interval(const struct lttng_session_descriptor *descriptor)
 {
        struct lttng_session_descriptor_live *live;
 
@@ -922,9 +858,8 @@ lttng_session_descriptor_live_get_timer_interval(
 }
 
 enum lttng_session_descriptor_status
-lttng_session_descriptor_get_session_name(
-               const struct lttng_session_descriptor *descriptor,
-               const char **session_name)
+lttng_session_descriptor_get_session_name(const struct lttng_session_descriptor *descriptor,
+                                         const char **session_name)
 {
        enum lttng_session_descriptor_status status;
 
@@ -934,16 +869,14 @@ lttng_session_descriptor_get_session_name(
        }
 
        *session_name = descriptor->name;
-       status = descriptor->name ?
-                       LTTNG_SESSION_DESCRIPTOR_STATUS_OK :
-                       LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET;
+       status = descriptor->name ? LTTNG_SESSION_DESCRIPTOR_STATUS_OK :
+                                   LTTNG_SESSION_DESCRIPTOR_STATUS_UNSET;
 end:
        return status;
 }
 
-int lttng_session_descriptor_set_session_name(
-               struct lttng_session_descriptor *descriptor,
-               const char *name)
+int lttng_session_descriptor_set_session_name(struct lttng_session_descriptor *descriptor,
+                                             const char *name)
 {
        int ret = 0;
        char *new_name;
@@ -967,7 +900,7 @@ end:
 }
 
 bool lttng_session_descriptor_is_output_destination_initialized(
-               const struct lttng_session_descriptor *descriptor)
+       const struct lttng_session_descriptor *descriptor)
 {
        switch (descriptor->output_type) {
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
@@ -981,8 +914,7 @@ bool lttng_session_descriptor_is_output_destination_initialized(
        }
 }
 
-bool lttng_session_descriptor_has_output_directory(
-               const struct lttng_session_descriptor *descriptor)
+bool lttng_session_descriptor_has_output_directory(const struct lttng_session_descriptor *descriptor)
 {
        switch (descriptor->output_type) {
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
@@ -1003,13 +935,13 @@ bool lttng_session_descriptor_has_output_directory(
        return false;
 }
 
-enum lttng_error_code lttng_session_descriptor_set_default_output(
-               struct lttng_session_descriptor *descriptor,
-               time_t *session_creation_time,
-               const char *absolute_home_path)
+enum lttng_error_code
+lttng_session_descriptor_set_default_output(struct lttng_session_descriptor *descriptor,
+                                           time_t *session_creation_time,
+                                           const char *absolute_home_path)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
 
        switch (descriptor->output_type) {
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
@@ -1031,8 +963,9 @@ enum lttng_error_code lttng_session_descriptor_set_default_output(
                                goto end;
                        }
                        strftime_ret = strftime(creation_datetime_suffix,
-                                       sizeof(creation_datetime_suffix),
-                                       "-%Y%m%d-%H%M%S", timeinfo);
+                                               sizeof(creation_datetime_suffix),
+                                               "-%Y%m%d-%H%M%S",
+                                               timeinfo);
                        if (strftime_ret == 0) {
                                ERR("Failed to format session creation timestamp while setting default local output destination");
                                ret_code = LTTNG_ERR_FATAL;
@@ -1040,11 +973,13 @@ enum lttng_error_code lttng_session_descriptor_set_default_output(
                        }
                }
                LTTNG_ASSERT(descriptor->name);
-               ret = snprintf(local_uri, sizeof(local_uri),
-                               "file://%s/%s/%s%s",
-                               absolute_home_path,
-                               DEFAULT_TRACE_DIR_NAME, descriptor->name,
-                               creation_datetime_suffix);
+               ret = snprintf(local_uri,
+                              sizeof(local_uri),
+                              "file://%s/%s/%s%s",
+                              absolute_home_path,
+                              DEFAULT_TRACE_DIR_NAME,
+                              descriptor->name,
+                              creation_datetime_suffix);
                if (ret >= sizeof(local_uri)) {
                        ERR("Truncation occurred while setting default local output destination");
                        ret_code = LTTNG_ERR_SET_URL;
@@ -1062,16 +997,16 @@ enum lttng_error_code lttng_session_descriptor_set_default_output(
                }
                free(descriptor->output.local);
                descriptor->output.local = &uris[0];
-               uris = NULL;
+               uris = nullptr;
                break;
        }
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
        {
                int ret;
                ssize_t uri_ret;
-               struct lttng_uri *control = NULL, *data = NULL;
+               struct lttng_uri *control = nullptr, *data = nullptr;
 
-               uri_ret = uri_parse_str_urls("net://127.0.0.1", NULL, &uris);
+               uri_ret = uri_parse_str_urls("net://127.0.0.1", nullptr, &uris);
                if (uri_ret != 2) {
                        ret_code = LTTNG_ERR_SET_URL;
                        goto end;
@@ -1088,8 +1023,7 @@ enum lttng_error_code lttng_session_descriptor_set_default_output(
 
                /* Ownership of uris is transferred. */
                ret = network_location_set_from_lttng_uris(
-                               &descriptor->output.network,
-                               control, data);
+                       &descriptor->output.network, control, data);
                if (ret) {
                        abort();
                        ret_code = LTTNG_ERR_SET_URL;
@@ -1109,9 +1043,8 @@ end:
  * Note that only properties that can be populated by the session daemon
  * (output destination and name) are assigned.
  */
-int lttng_session_descriptor_assign(
-               struct lttng_session_descriptor *dst,
-               const struct lttng_session_descriptor *src)
+int lttng_session_descriptor_assign(struct lttng_session_descriptor *dst,
+                                   const struct lttng_session_descriptor *src)
 {
        int ret = 0;
 
@@ -1138,7 +1071,7 @@ int lttng_session_descriptor_assign(
                break;
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NETWORK:
        {
-               struct lttng_uri *control_copy = NULL, *data_copy = NULL;
+               struct lttng_uri *control_copy = nullptr, *data_copy = nullptr;
 
                control_copy = uri_copy(dst->output.network.control);
                if (!control_copy && dst->output.network.control) {
@@ -1151,8 +1084,8 @@ int lttng_session_descriptor_assign(
                        ret = -1;
                        goto end;
                }
-               ret = network_location_set_from_lttng_uris(&dst->output.network,
-                               control_copy, data_copy);
+               ret = network_location_set_from_lttng_uris(
+                       &dst->output.network, control_copy, data_copy);
                break;
        }
        case LTTNG_SESSION_DESCRIPTOR_OUTPUT_TYPE_NONE:
index 9fcb1f34956be67f4a5329e4a8c5cd9d2158a10f..2d2d0fa4a50f98734c653de30b4e20bf89839451 100644 (file)
@@ -9,21 +9,23 @@
 #ifndef AGENT_COMM
 #define AGENT_COMM
 
-#include <stdint.h>
-
+#include <common/compiler.hpp>
 #include <common/macros.hpp>
+
 #include <lttng/lttng.h>
 
+#include <stdint.h>
+
 /*
  * Command value passed in the header.
  */
 enum lttcomm_agent_command {
-       AGENT_CMD_LIST                  = 1,
-       AGENT_CMD_ENABLE                = 2,
-       AGENT_CMD_DISABLE               = 3,
-       AGENT_CMD_REG_DONE              = 4,    /* End registration process. */
-       AGENT_CMD_APP_CTX_ENABLE        = 5,
-       AGENT_CMD_APP_CTX_DISABLE       = 6,
+       AGENT_CMD_LIST = 1,
+       AGENT_CMD_ENABLE = 2,
+       AGENT_CMD_DISABLE = 3,
+       AGENT_CMD_REG_DONE = 4, /* End registration process. */
+       AGENT_CMD_APP_CTX_ENABLE = 5,
+       AGENT_CMD_APP_CTX_DISABLE = 6,
 };
 
 /*
@@ -31,11 +33,11 @@ enum lttcomm_agent_command {
  */
 enum lttcomm_agent_ret_code {
        /* Success, assumed to be the first entry */
-       AGENT_RET_CODE_SUCCESS          = 1,
+       AGENT_RET_CODE_SUCCESS = 1,
        /* Invalid command */
-       AGENT_RET_CODE_INVALID          = 2,
+       AGENT_RET_CODE_INVALID = 2,
        /* Unknown logger name */
-       AGENT_RET_CODE_UNKNOWN_NAME     = 3,
+       AGENT_RET_CODE_UNKNOWN_NAME = 3,
        AGENT_RET_CODE_NR,
 };
 
@@ -43,9 +45,9 @@ enum lttcomm_agent_ret_code {
  * Agent application communication header.
  */
 struct lttcomm_agent_hdr {
-       uint64_t data_size;             /* data size following this header */
-       uint32_t cmd;                   /* Enum of agent command. */
-       uint32_t cmd_version;   /* command version */
+       uint64_t data_size; /* data size following this header */
+       uint32_t cmd; /* Enum of agent command. */
+       uint32_t cmd_version; /* command version */
 } LTTNG_PACKED;
 
 /*
@@ -87,7 +89,7 @@ struct lttcomm_agent_list_reply_hdr {
 struct lttcomm_agent_list_reply {
        uint32_t nb_event;
        /* List of event name each of them ending by a NULL byte. */
-       char payload[];
+       char payload[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
-#endif /* AGENT_COMM */
+#endif /* AGENT_COMM */
index 30aa8c6134a42903f2df14cd6e0e69c103d2173a..633685799aad448f352adfac358c5214269dfa05 100644 (file)
@@ -6,25 +6,25 @@
  */
 
 #define _LGPL_SOURCE
+#include "inet.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/compat/time.hpp>
+#include <common/time.hpp>
+
 #include <algorithm>
+#include <fcntl.h>
 #include <limits.h>
+#include <poll.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <fcntl.h>
-#include <common/compat/time.hpp>
-#include <poll.h>
-
-#include <common/common.hpp>
-#include <common/time.hpp>
-#include <common/compat/errno.hpp>
-
-#include "inet.hpp"
 
-#define RECONNECT_DELAY        200     /* ms */
+#define RECONNECT_DELAY 200 /* ms */
 
 /*
  * INET protocol operations.
@@ -93,16 +93,14 @@ int lttcomm_bind_inet_sock(struct lttcomm_sock *sock)
        return bind(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
 }
 
-static
-int connect_no_timeout(struct lttcomm_sock *sock)
+static int connect_no_timeout(struct lttcomm_sock *sock)
 {
        struct sockaddr_in sockaddr = sock->sockaddr.addr.sin;
 
        return connect(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
 }
 
-static
-int connect_with_timeout(struct lttcomm_sock *sock)
+static int connect_with_timeout(struct lttcomm_sock *sock)
 {
        unsigned long timeout = lttcomm_get_network_timeout();
        int ret, flags, connect_ret;
@@ -132,8 +130,7 @@ int connect_with_timeout(struct lttcomm_sock *sock)
 
        sockaddr = sock->sockaddr.addr.sin;
        connect_ret = connect(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
-       if (connect_ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK &&
-                       errno != EINPROGRESS) {
+       if (connect_ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINPROGRESS) {
                goto error;
        } else if (!connect_ret) {
                /* Connect succeeded */
@@ -141,7 +138,9 @@ int connect_with_timeout(struct lttcomm_sock *sock)
        }
 
        DBG("Asynchronous connect for sock %d, performing polling with"
-                       " timeout: %lums", sock->fd, timeout);
+           " timeout: %lums",
+           sock->fd,
+           timeout);
        /*
         * Perform poll loop following EINPROGRESS recommendation from
         * connect(2) man page.
@@ -165,8 +164,7 @@ int connect_with_timeout(struct lttcomm_sock *sock)
                                goto error;
                        }
                        /* got something */
-                       ret = getsockopt(sock->fd, SOL_SOCKET,
-                               SO_ERROR, &optval, &optval_len);
+                       ret = getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, &optval, &optval_len);
                        if (ret) {
                                PERROR("getsockopt");
                                goto error;
@@ -258,7 +256,7 @@ struct lttcomm_sock *lttcomm_accept_inet_sock(struct lttcomm_sock *sock)
        }
 
        new_sock = lttcomm_alloc_sock(sock->proto);
-       if (new_sock == NULL) {
+       if (new_sock == nullptr) {
                goto error;
        }
 
@@ -298,7 +296,7 @@ error_close:
 
 error:
        free(new_sock);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -334,8 +332,7 @@ end:
  *
  * Return the size of received data.
  */
-ssize_t lttcomm_recvmsg_inet_sock(struct lttcomm_sock *sock, void *buf,
-               size_t len, int flags)
+ssize_t lttcomm_recvmsg_inet_sock(struct lttcomm_sock *sock, void *buf, size_t len, int flags)
 {
        struct msghdr msg;
        struct iovec iov[1];
@@ -390,8 +387,7 @@ end:
  *
  * Return the size of sent data.
  */
-ssize_t lttcomm_sendmsg_inet_sock(struct lttcomm_sock *sock, const void *buf,
-               size_t len, int flags)
+ssize_t lttcomm_sendmsg_inet_sock(struct lttcomm_sock *sock, const void *buf, size_t len, int flags)
 {
        struct msghdr msg;
        struct iovec iov[1];
@@ -484,7 +480,7 @@ static unsigned long read_proc_value(const char *path)
        buf[size_ret] = '\0';
 
        errno = 0;
-       r_val = strtol(buf, NULL, 10);
+       r_val = strtol(buf, nullptr, 10);
        if (errno != 0 || r_val < -1L) {
                val = 0;
                goto error_close;
@@ -503,7 +499,7 @@ error:
        return val;
 }
 
-void lttcomm_inet_init(void)
+void lttcomm_inet_init()
 {
        unsigned long syn_retries, fin_timeout, syn_timeout, env;
 
@@ -525,8 +521,8 @@ void lttcomm_inet_init(void)
         * Get the maximum between the two possible timeout value and use that to
         * get the maximum with the default timeout.
         */
-       lttcomm_inet_tcp_timeout = std::max(std::max(syn_timeout, fin_timeout),
-                       lttcomm_inet_tcp_timeout);
+       lttcomm_inet_tcp_timeout =
+               std::max(std::max(syn_timeout, fin_timeout), lttcomm_inet_tcp_timeout);
 
 end:
        DBG("TCP inet operation timeout set to %lu sec", lttcomm_inet_tcp_timeout);
index dca1cc154c1c80ea2fef6e6ae3bd41ffa91a88ee..f1fc4c069704fd4f241db5bd58ed37bb5c07acea 100644 (file)
@@ -8,10 +8,13 @@
 #ifndef _LTTCOMM_INET_H
 #define _LTTCOMM_INET_H
 
-#include <limits.h>
-
 #include "sessiond-comm.hpp"
 
+#include <lttng/lttng-export.h>
+
+#include <limits.h>
+#include <sys/types.h>
+
 /* See man tcp(7) for more detail about this value. */
 #define LTTCOMM_INET_PROC_SYN_RETRIES_PATH "/proc/sys/net/ipv4/tcp_syn_retries"
 #define LTTCOMM_INET_PROC_FIN_TIMEOUT_PATH "/proc/sys/net/ipv4/tcp_fin_timeout"
@@ -24,7 +27,7 @@
  * (180/5) by considering that it grows linearly. This is of course uncertain
  * but this is the best approximation we can do at runtime.
  */
-#define LTTCOMM_INET_SYN_TIMEOUT_FACTOR                36
+#define LTTCOMM_INET_SYN_TIMEOUT_FACTOR 36
 
 /*
  * Maximum timeout value in seconds of a TCP connection for both send/recv and
@@ -36,8 +39,7 @@ LTTNG_EXPORT extern unsigned long lttcomm_inet_tcp_timeout;
 struct lttcomm_sock;
 
 /* Net family callback */
-extern int lttcomm_create_inet_sock(struct lttcomm_sock *sock, int type,
-               int proto);
+extern int lttcomm_create_inet_sock(struct lttcomm_sock *sock, int type, int proto);
 
 extern struct lttcomm_sock *lttcomm_accept_inet_sock(struct lttcomm_sock *sock);
 extern int lttcomm_bind_inet_sock(struct lttcomm_sock *sock);
@@ -45,12 +47,12 @@ extern int lttcomm_close_inet_sock(struct lttcomm_sock *sock);
 extern int lttcomm_connect_inet_sock(struct lttcomm_sock *sock);
 extern int lttcomm_listen_inet_sock(struct lttcomm_sock *sock, int backlog);
 
-extern ssize_t lttcomm_recvmsg_inet_sock(struct lttcomm_sock *sock, void *buf,
-               size_t len, int flags);
-extern ssize_t lttcomm_sendmsg_inet_sock(struct lttcomm_sock *sock,
-               const void *buf, size_t len, int flags);
+extern ssize_t
+lttcomm_recvmsg_inet_sock(struct lttcomm_sock *sock, void *buf, size_t len, int flags);
+extern ssize_t
+lttcomm_sendmsg_inet_sock(struct lttcomm_sock *sock, const void *buf, size_t len, int flags);
 
 /* Initialize inet communication layer. */
-extern void lttcomm_inet_init(void);
+extern void lttcomm_inet_init();
 
-#endif /* _LTTCOMM_INET_H */
+#endif /* _LTTCOMM_INET_H */
index caa4d7eb3906b691d1762b6e0fd41268b0ff53ed..289e19e98df67b3192095da8d4df50c4197b99cb 100644 (file)
@@ -6,24 +6,24 @@
  */
 
 #define _LGPL_SOURCE
+#include "inet6.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/compat/time.hpp>
+#include <common/time.hpp>
+
+#include <fcntl.h>
 #include <limits.h>
+#include <poll.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <fcntl.h>
-#include <common/compat/time.hpp>
-#include <poll.h>
-
-#include <common/common.hpp>
-#include <common/time.hpp>
-#include <common/compat/errno.hpp>
-
-#include "inet6.hpp"
 
-#define RECONNECT_DELAY        200     /* ms */
+#define RECONNECT_DELAY 200 /* ms */
 
 /*
  * INET protocol operations.
@@ -89,15 +89,13 @@ int lttcomm_bind_inet6_sock(struct lttcomm_sock *sock)
        return bind(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
 }
 
-static
-int connect_no_timeout(struct lttcomm_sock *sock)
+static int connect_no_timeout(struct lttcomm_sock *sock)
 {
        struct sockaddr_in6 sockaddr = sock->sockaddr.addr.sin6;
        return connect(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
 }
 
-static
-int connect_with_timeout(struct lttcomm_sock *sock)
+static int connect_with_timeout(struct lttcomm_sock *sock)
 {
        unsigned long timeout = lttcomm_get_network_timeout();
        int ret, flags, connect_ret;
@@ -127,8 +125,7 @@ int connect_with_timeout(struct lttcomm_sock *sock)
 
        sockaddr = sock->sockaddr.addr.sin6;
        connect_ret = connect(sock->fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
-       if (connect_ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK &&
-                       errno != EINPROGRESS) {
+       if (connect_ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINPROGRESS) {
                goto error;
        } else if (!connect_ret) {
                /* Connect succeeded */
@@ -136,7 +133,9 @@ int connect_with_timeout(struct lttcomm_sock *sock)
        }
 
        DBG("Asynchronous connect for sock %d, performing polling with"
-                       " timeout: %lums", sock->fd, timeout);
+           " timeout: %lums",
+           sock->fd,
+           timeout);
 
        /*
         * Perform poll loop following EINPROGRESS recommendation from
@@ -161,8 +160,7 @@ int connect_with_timeout(struct lttcomm_sock *sock)
                                goto error;
                        }
                        /* got something */
-                       ret = getsockopt(sock->fd, SOL_SOCKET,
-                               SO_ERROR, &optval, &optval_len);
+                       ret = getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, &optval, &optval_len);
                        if (ret) {
                                PERROR("getsockopt");
                                goto error;
@@ -253,7 +251,7 @@ struct lttcomm_sock *lttcomm_accept_inet6_sock(struct lttcomm_sock *sock)
        }
 
        new_sock = lttcomm_alloc_sock(sock->proto);
-       if (new_sock == NULL) {
+       if (new_sock == nullptr) {
                goto error;
        }
 
@@ -274,7 +272,7 @@ end:
 
 error:
        free(new_sock);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -310,8 +308,7 @@ end:
  *
  * Return the size of received data.
  */
-ssize_t lttcomm_recvmsg_inet6_sock(struct lttcomm_sock *sock, void *buf,
-               size_t len, int flags)
+ssize_t lttcomm_recvmsg_inet6_sock(struct lttcomm_sock *sock, void *buf, size_t len, int flags)
 {
        struct msghdr msg;
        struct iovec iov[1];
@@ -356,8 +353,8 @@ end:
  *
  * Return the size of sent data.
  */
-ssize_t lttcomm_sendmsg_inet6_sock(struct lttcomm_sock *sock, const void *buf,
-               size_t len, int flags)
+ssize_t
+lttcomm_sendmsg_inet6_sock(struct lttcomm_sock *sock, const void *buf, size_t len, int flags)
 {
        struct msghdr msg;
        struct iovec iov[1];
index d6122fdfae0363558904ad7946ec13259bc78a74..674751e552e3ce2890fa591b319547d2bb70a333 100644 (file)
@@ -8,27 +8,26 @@
 #ifndef _LTTCOMM_INET6_H
 #define _LTTCOMM_INET6_H
 
-#include <limits.h>
-
 #include "sessiond-comm.hpp"
 
+#include <limits.h>
+#include <sys/types.h>
+
 /* Stub */
 struct lttcomm_sock;
 
 /* Net family callback */
-extern int lttcomm_create_inet6_sock(struct lttcomm_sock *sock, int type,
-               int proto);
+extern int lttcomm_create_inet6_sock(struct lttcomm_sock *sock, int type, int proto);
 
-extern struct lttcomm_sock *lttcomm_accept_inet6_sock(
-               struct lttcomm_sock *sock);
+extern struct lttcomm_sock *lttcomm_accept_inet6_sock(struct lttcomm_sock *sock);
 extern int lttcomm_bind_inet6_sock(struct lttcomm_sock *sock);
 extern int lttcomm_close_inet6_sock(struct lttcomm_sock *sock);
 extern int lttcomm_connect_inet6_sock(struct lttcomm_sock *sock);
 extern int lttcomm_listen_inet6_sock(struct lttcomm_sock *sock, int backlog);
 
-extern ssize_t lttcomm_recvmsg_inet6_sock(struct lttcomm_sock *sock, void *buf,
-               size_t len, int flags);
-extern ssize_t lttcomm_sendmsg_inet6_sock(struct lttcomm_sock *sock,
-               const void *buf, size_t len, int flags);
+extern ssize_t
+lttcomm_recvmsg_inet6_sock(struct lttcomm_sock *sock, void *buf, size_t len, int flags);
+extern ssize_t
+lttcomm_sendmsg_inet6_sock(struct lttcomm_sock *sock, const void *buf, size_t len, int flags);
 
-#endif /* _LTTCOMM_INET6_H */
+#endif /* _LTTCOMM_INET6_H */
index 0f5adaa94bba32443286bcefe1d99c9f445e96a8..6a0a79201ca356e0b79a382f951ab4cbf55da109 100644 (file)
@@ -9,23 +9,25 @@
 #ifndef _RELAYD_COMM
 #define _RELAYD_COMM
 
-#include <limits.h>
-#include <stdint.h>
-
-#include <lttng/lttng.h>
+#include <common/compiler.hpp>
 #include <common/defaults.hpp>
 #include <common/index/ctf-index.hpp>
 #include <common/macros.hpp>
-#include <common/uuid.hpp>
 #include <common/optional.hpp>
+#include <common/uuid.hpp>
 
-#define RELAYD_VERSION_COMM_MAJOR             VERSION_MAJOR
-#define RELAYD_VERSION_COMM_MINOR             VERSION_MINOR
+#include <lttng/lttng.h>
+
+#include <limits.h>
+#include <stdint.h>
+
+#define RELAYD_VERSION_COMM_MAJOR VERSION_MAJOR
+#define RELAYD_VERSION_COMM_MINOR VERSION_MINOR
 
-#define RELAYD_COMM_LTTNG_HOST_NAME_MAX_2_4    64
-#define RELAYD_COMM_LTTNG_NAME_MAX_2_4 255
-#define RELAYD_COMM_LTTNG_PATH_MAX     4096
-#define RELAYD_COMM_DEFAULT_STREAM_NAME_LEN    264 /* 256 + 8 */
+#define RELAYD_COMM_LTTNG_HOST_NAME_MAX_2_4 64
+#define RELAYD_COMM_LTTNG_NAME_MAX_2_4     255
+#define RELAYD_COMM_LTTNG_PATH_MAX         4096
+#define RELAYD_COMM_DEFAULT_STREAM_NAME_LEN 264 /* 256 + 8 */
 
 /*
  * lttng-relayd communication header.
@@ -33,9 +35,9 @@
 struct lttcomm_relayd_hdr {
        /* Circuit ID not used for now so always ignored */
        uint64_t circuit_id;
-       uint64_t data_size;             /* data size following this header */
-       uint32_t cmd;                   /* enum lttcomm_relayd_command */
-       uint32_t cmd_version;   /* command version */
+       uint64_t data_size; /* data size following this header */
+       uint32_t cmd; /* enum lttcomm_relayd_command */
+       uint32_t cmd_version; /* command version */
 } LTTNG_PACKED;
 
 /*
@@ -44,10 +46,10 @@ struct lttcomm_relayd_hdr {
 struct lttcomm_relayd_data_hdr {
        /* Circuit ID not used for now so always ignored */
        uint64_t circuit_id;
-       uint64_t stream_id;     /* Stream ID known by the relayd */
-       uint64_t net_seq_num;   /* Network sequence number, per stream. */
-       uint32_t data_size;     /* data size following this header */
-       uint32_t padding_size;  /* Size of 0 padding the data */
+       uint64_t stream_id; /* Stream ID known by the relayd */
+       uint64_t net_seq_num; /* Network sequence number, per stream. */
+       uint32_t data_size; /* data size following this header */
+       uint32_t padding_size; /* Size of 0 padding the data */
 } LTTNG_PACKED;
 
 /*
@@ -83,7 +85,7 @@ struct lttcomm_relayd_add_stream_2_11 {
        uint64_t tracefile_size;
        uint64_t tracefile_count;
        uint64_t trace_chunk_id;
-       char names[];
+       char names[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 /*
@@ -123,7 +125,7 @@ struct lttcomm_relayd_metadata_payload {
  */
 struct lttcomm_relayd_close_stream {
        uint64_t stream_id;
-       uint64_t last_net_seq_num;      /* sequence number of last packet */
+       uint64_t last_net_seq_num; /* sequence number of last packet */
 } LTTNG_PACKED;
 
 /*
@@ -169,13 +171,11 @@ static inline size_t lttcomm_relayd_index_len(uint32_t major, uint32_t minor)
        if (major == 1) {
                switch (minor) {
                case 0:
-                       return offsetof(struct lttcomm_relayd_index, stream_id)
-                               + member_sizeof(struct lttcomm_relayd_index,
-                                               stream_id);
+                       return offsetof(struct lttcomm_relayd_index, stream_id) +
+                               member_sizeof(struct lttcomm_relayd_index, stream_id);
                case 1:
-                       return offsetof(struct lttcomm_relayd_index, packet_seq_num)
-                               + member_sizeof(struct lttcomm_relayd_index,
-                                               packet_seq_num);
+                       return offsetof(struct lttcomm_relayd_index, packet_seq_num) +
+                               member_sizeof(struct lttcomm_relayd_index, packet_seq_num);
                default:
                        abort();
                }
@@ -209,14 +209,14 @@ struct lttcomm_relayd_create_session_2_11 {
        uint64_t creation_time;
        LTTNG_OPTIONAL_COMM(uint64_t) LTTNG_PACKED current_chunk_id;
        /* Contains the session_name, hostname, base_path. */
-       char names[];
+       char names[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 struct lttcomm_relayd_create_session_reply_2_11 {
        struct lttcomm_relayd_status_session generic;
        /* Includes the '\0' terminator. */
        uint32_t output_path_length;
-       char output_path[];
+       char output_path[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 /*
@@ -309,7 +309,7 @@ struct lttcomm_relayd_create_trace_chunk {
        uint64_t creation_timestamp;
        /* Includes trailing NULL. */
        uint32_t override_name_length;
-       char override_name[];
+       char override_name[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 struct lttcomm_relayd_close_trace_chunk {
@@ -324,7 +324,7 @@ struct lttcomm_relayd_close_trace_chunk_reply {
        struct lttcomm_relayd_generic_reply generic;
        /* Includes trailing NULL. */
        uint32_t path_length;
-       char path[];
+       char path[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
 struct lttcomm_relayd_trace_chunk_exists {
@@ -354,7 +354,7 @@ struct lttcomm_relayd_get_configuration_reply {
        /* Set of lttcomm_relayd_configuration_flag. */
        uint64_t relayd_configuration_flags;
        /* Optional variable-length payload. */
-       char payload[];
+       char payload[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 } LTTNG_PACKED;
 
-#endif /* _RELAYD_COMM */
+#endif /* _RELAYD_COMM */
index ed14a9e63ec7af3f721a80d4ee7b1d53d7429eaa..593ab265ccc25f6a1d7e06d098c31c0568529b27 100644 (file)
@@ -8,6 +8,12 @@
 
 #include <sys/socket.h>
 #define _LGPL_SOURCE
+#include "sessiond-comm.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+
+#include <inttypes.h>
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-
-#include <common/common.hpp>
-#include <common/compat/errno.hpp>
-
-#include "sessiond-comm.hpp"
 
 /* For Unix socket */
 #include <common/unix.hpp>
@@ -29,7 +29,7 @@
 /* For Inet6 socket */
 #include "inet6.hpp"
 
-#define NETWORK_TIMEOUT_ENV    "LTTNG_NETWORK_SOCKET_TIMEOUT"
+#define NETWORK_TIMEOUT_ENV "LTTNG_NETWORK_SOCKET_TIMEOUT"
 
 static struct lttcomm_net_family net_families[] = {
        { LTTCOMM_INET, lttcomm_create_inet_sock },
@@ -39,8 +39,8 @@ static struct lttcomm_net_family net_families[] = {
 /*
  * Human readable error message.
  */
-static
-const char *lttcomm_return_code_str(lttcomm_return_code code) {
+static const char *lttcomm_return_code_str(lttcomm_return_code code)
+{
        switch (code) {
        case LTTCOMM_CONSUMERD_SUCCESS:
                return "consumerd success";
@@ -126,7 +126,7 @@ const char *lttcomm_get_readable_code(enum lttcomm_return_code code)
        code = (lttcomm_return_code) -code;
 
        if (code != LTTCOMM_CONSUMERD_SUCCESS &&
-                       !(code >= LTTCOMM_CONSUMERD_COMMAND_SOCK_READY && code < LTTCOMM_NR)) {
+           !(code >= LTTCOMM_CONSUMERD_COMMAND_SOCK_READY && code < LTTCOMM_NR)) {
                code = LTTCOMM_CONSUMERD_UNKNOWN_ERROR;
        }
 
@@ -180,7 +180,7 @@ struct lttcomm_sock *lttcomm_alloc_sock(enum lttcomm_sock_proto proto)
 {
        struct lttcomm_sock *sock = zmalloc<lttcomm_sock>();
 
-       if (sock == NULL) {
+       if (sock == nullptr) {
                PERROR("zmalloc create sock");
                goto end;
        }
@@ -207,7 +207,7 @@ struct lttcomm_sock *lttcomm_alloc_copy_sock(struct lttcomm_sock *src)
        LTTNG_ASSERT(src);
 
        sock = lttcomm_alloc_sock(src->proto);
-       if (sock == NULL) {
+       if (sock == nullptr) {
                goto alloc_error;
        }
 
@@ -239,8 +239,7 @@ void lttcomm_copy_sock(struct lttcomm_sock *dst, struct lttcomm_sock *src)
 /*
  * Init IPv4 sockaddr structure.
  */
-int lttcomm_init_inet_sockaddr(struct lttcomm_sockaddr *sockaddr,
-               const char *ip, unsigned int port)
+int lttcomm_init_inet_sockaddr(struct lttcomm_sockaddr *sockaddr, const char *ip, unsigned int port)
 {
        int ret;
 
@@ -253,8 +252,7 @@ int lttcomm_init_inet_sockaddr(struct lttcomm_sockaddr *sockaddr,
        sockaddr->type = LTTCOMM_INET;
        sockaddr->addr.sin.sin_family = AF_INET;
        sockaddr->addr.sin.sin_port = htons(port);
-       ret = inet_pton(sockaddr->addr.sin.sin_family, ip,
-                       &sockaddr->addr.sin.sin_addr);
+       ret = inet_pton(sockaddr->addr.sin.sin_family, ip, &sockaddr->addr.sin.sin_addr);
        if (ret < 1) {
                ret = -1;
                ERR("%s with port %d: unrecognized IPv4 address", ip, port);
@@ -270,7 +268,8 @@ error:
  * Init IPv6 sockaddr structure.
  */
 int lttcomm_init_inet6_sockaddr(struct lttcomm_sockaddr *sockaddr,
-               const char *ip, unsigned int port)
+                               const char *ip,
+                               unsigned int port)
 {
        int ret;
 
@@ -283,8 +282,7 @@ int lttcomm_init_inet6_sockaddr(struct lttcomm_sockaddr *sockaddr,
        sockaddr->type = LTTCOMM_INET6;
        sockaddr->addr.sin6.sin6_family = AF_INET6;
        sockaddr->addr.sin6.sin6_port = htons(port);
-       ret = inet_pton(sockaddr->addr.sin6.sin6_family, ip,
-                       &sockaddr->addr.sin6.sin6_addr);
+       ret = inet_pton(sockaddr->addr.sin6.sin6_family, ip, &sockaddr->addr.sin6.sin6_addr);
        if (ret < 1) {
                ret = -1;
                goto error;
@@ -301,7 +299,7 @@ struct lttcomm_sock *lttcomm_alloc_sock_from_uri(struct lttng_uri *uri)
 {
        int ret;
        int _sock_proto;
-       struct lttcomm_sock *sock = NULL;
+       struct lttcomm_sock *sock = nullptr;
 
        /* Safety net */
        LTTNG_ASSERT(uri);
@@ -315,20 +313,18 @@ struct lttcomm_sock *lttcomm_alloc_sock_from_uri(struct lttng_uri *uri)
        }
 
        sock = lttcomm_alloc_sock((lttcomm_sock_proto) _sock_proto);
-       if (sock == NULL) {
+       if (sock == nullptr) {
                goto alloc_error;
        }
 
        /* Check destination type */
        if (uri->dtype == LTTNG_DST_IPV4) {
-               ret = lttcomm_init_inet_sockaddr(&sock->sockaddr, uri->dst.ipv4,
-                               uri->port);
+               ret = lttcomm_init_inet_sockaddr(&sock->sockaddr, uri->dst.ipv4, uri->port);
                if (ret < 0) {
                        goto error;
                }
        } else if (uri->dtype == LTTNG_DST_IPV6) {
-               ret = lttcomm_init_inet6_sockaddr(&sock->sockaddr, uri->dst.ipv6,
-                               uri->port);
+               ret = lttcomm_init_inet6_sockaddr(&sock->sockaddr, uri->dst.ipv6, uri->port);
                if (ret < 0) {
                        goto error;
                }
@@ -343,7 +339,7 @@ struct lttcomm_sock *lttcomm_alloc_sock_from_uri(struct lttng_uri *uri)
 error:
        lttcomm_destroy_sock(sock);
 alloc_error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -360,11 +356,11 @@ void lttcomm_destroy_sock(struct lttcomm_sock *sock)
  *
  * On error, NULL is returned.
  */
-struct lttcomm_relayd_sock *lttcomm_alloc_relayd_sock(struct lttng_uri *uri,
-               uint32_t major, uint32_t minor)
+struct lttcomm_relayd_sock *
+lttcomm_alloc_relayd_sock(struct lttng_uri *uri, uint32_t major, uint32_t minor)
 {
        int ret;
-       struct lttcomm_sock *tmp_sock = NULL;
+       struct lttcomm_sock *tmp_sock = nullptr;
        struct lttcomm_relayd_sock *rsock = zmalloc<lttcomm_relayd_sock>();
 
        LTTNG_ASSERT(uri);
@@ -376,7 +372,7 @@ struct lttcomm_relayd_sock *lttcomm_alloc_relayd_sock(struct lttng_uri *uri,
 
        /* Allocate socket object from URI */
        tmp_sock = lttcomm_alloc_sock_from_uri(uri);
-       if (tmp_sock == NULL) {
+       if (tmp_sock == nullptr) {
                goto error_free;
        }
 
@@ -400,7 +396,7 @@ struct lttcomm_relayd_sock *lttcomm_alloc_relayd_sock(struct lttng_uri *uri,
 error_free:
        free(rsock);
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -445,10 +441,8 @@ int lttcomm_sock_get_port(const struct lttcomm_sock *sock, uint16_t *port)
 {
        LTTNG_ASSERT(sock);
        LTTNG_ASSERT(port);
-       LTTNG_ASSERT(sock->sockaddr.type == LTTCOMM_INET ||
-                       sock->sockaddr.type == LTTCOMM_INET6);
-       LTTNG_ASSERT(sock->proto == LTTCOMM_SOCK_TCP ||
-                       sock->proto == LTTCOMM_SOCK_UDP);
+       LTTNG_ASSERT(sock->sockaddr.type == LTTCOMM_INET || sock->sockaddr.type == LTTCOMM_INET6);
+       LTTNG_ASSERT(sock->proto == LTTCOMM_SOCK_TCP || sock->proto == LTTCOMM_SOCK_UDP);
 
        switch (sock->sockaddr.type) {
        case LTTCOMM_INET:
@@ -467,10 +461,8 @@ int lttcomm_sock_get_port(const struct lttcomm_sock *sock, uint16_t *port)
 int lttcomm_sock_set_port(struct lttcomm_sock *sock, uint16_t port)
 {
        LTTNG_ASSERT(sock);
-       LTTNG_ASSERT(sock->sockaddr.type == LTTCOMM_INET ||
-                       sock->sockaddr.type == LTTCOMM_INET6);
-       LTTNG_ASSERT(sock->proto == LTTCOMM_SOCK_TCP ||
-                       sock->proto == LTTCOMM_SOCK_UDP);
+       LTTNG_ASSERT(sock->sockaddr.type == LTTCOMM_INET || sock->sockaddr.type == LTTCOMM_INET6);
+       LTTNG_ASSERT(sock->proto == LTTCOMM_SOCK_TCP || sock->proto == LTTCOMM_SOCK_UDP);
 
        switch (sock->sockaddr.type) {
        case LTTCOMM_INET:
@@ -486,7 +478,7 @@ int lttcomm_sock_set_port(struct lttcomm_sock *sock, uint16_t port)
        return 0;
 }
 
-void lttcomm_init(void)
+void lttcomm_init()
 {
        const char *env;
 
@@ -495,7 +487,7 @@ void lttcomm_init(void)
                long timeout;
 
                errno = 0;
-               timeout = strtol(env, NULL, 0);
+               timeout = strtol(env, nullptr, 0);
                if (errno != 0 || timeout < -1L) {
                        PERROR("Network timeout");
                } else {
@@ -506,7 +498,7 @@ void lttcomm_init(void)
        }
 }
 
-unsigned long lttcomm_get_network_timeout(void)
+unsigned long lttcomm_get_network_timeout()
 {
        return network_timeout;
 }
@@ -515,10 +507,9 @@ unsigned long lttcomm_get_network_timeout(void)
  * Only valid for an ipv4 and ipv6 bound socket that is already connected to its
  * peer.
  */
-int lttcomm_populate_sock_from_open_socket(
-               struct lttcomm_sock *sock,
-               int fd,
-               enum lttcomm_sock_proto protocol)
+int lttcomm_populate_sock_from_open_socket(struct lttcomm_sock *sock,
+                                          int fd,
+                                          enum lttcomm_sock_proto protocol)
 {
        int ret = 0;
        socklen_t storage_len;
@@ -530,11 +521,9 @@ int lttcomm_populate_sock_from_open_socket(
        sock->proto = protocol;
 
        storage_len = sizeof(storage);
-       ret = getpeername(fd, (struct sockaddr *) &storage,
-                       &storage_len);
+       ret = getpeername(fd, (struct sockaddr *) &storage, &storage_len);
        if (ret) {
-               ERR("Failed to get peer info for socket %d (errno: %d)", fd,
-                               errno);
+               ERR("Failed to get peer info for socket %d (errno: %d)", fd, errno);
                ret = -1;
                goto end;
        }
@@ -548,13 +537,11 @@ int lttcomm_populate_sock_from_open_socket(
        switch (storage.ss_family) {
        case AF_INET:
                sock->sockaddr.type = LTTCOMM_INET;
-               memcpy(&sock->sockaddr.addr, &storage,
-                               sizeof(struct sockaddr_in));
+               memcpy(&sock->sockaddr.addr, &storage, sizeof(struct sockaddr_in));
                break;
        case AF_INET6:
                sock->sockaddr.type = LTTCOMM_INET6;
-               memcpy(&sock->sockaddr.addr, &storage,
-                               sizeof(struct sockaddr_in6));
+               memcpy(&sock->sockaddr.addr, &storage, sizeof(struct sockaddr_in6));
                break;
        default:
                abort();
index 4bcc77bbbb3035ab08e7d2313e42a8538165f995..c8ac0cf41e60318b4634bf2ee4f25b1637ae6680 100644 (file)
 #ifndef _LTTNG_SESSIOND_COMM_H
 #define _LTTNG_SESSIOND_COMM_H
 
-#include <limits.h>
-#include <lttng/lttng.h>
-#include <lttng/snapshot-internal.hpp>
-#include <lttng/save-internal.hpp>
-#include <lttng/channel-internal.hpp>
-#include <lttng/trigger/trigger-internal.hpp>
-#include <lttng/rotate-internal.hpp>
+#include "inet.hpp"
+#include "inet6.hpp"
+
 #include <common/compat/socket.hpp>
-#include <common/uri.hpp>
+#include <common/compiler.hpp>
 #include <common/defaults.hpp>
-#include <common/uuid.hpp>
 #include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/unix.hpp>
+#include <common/uri.hpp>
+#include <common/uuid.hpp>
+
+#include <lttng/channel-internal.hpp>
+#include <lttng/lttng.h>
+#include <lttng/rotate-internal.hpp>
+#include <lttng/save-internal.hpp>
+#include <lttng/snapshot-internal.hpp>
+#include <lttng/trigger/trigger-internal.hpp>
 
 #include <arpa/inet.h>
+#include <limits.h>
 #include <netinet/in.h>
 #include <stdint.h>
 #include <sys/un.h>
 
-#include "inet.hpp"
-#include "inet6.hpp"
-#include <common/unix.hpp>
-
 /* Queue size of listen(2) */
 #define LTTNG_SESSIOND_COMM_MAX_LISTEN 64
 
 /* Maximum number of FDs that can be sent over a Unix socket */
 #if defined(__linux__)
 /* Based on the kernel's SCM_MAX_FD which is 253 since 2.6.38 (255 before) */
-#define LTTCOMM_MAX_SEND_FDS           253
+#define LTTCOMM_MAX_SEND_FDS 253
 #else
-#define LTTCOMM_MAX_SEND_FDS           16
+#define LTTCOMM_MAX_SEND_FDS 16
 #endif
 
 enum lttcomm_sessiond_command {
-       /* Tracer command */
-       LTTNG_ADD_CONTEXT                               = 0,
-       /* LTTNG_CALIBRATE used to be here */
-       LTTNG_DISABLE_CHANNEL                           = 2,
-       LTTNG_DISABLE_EVENT                             = 3,
-       LTTNG_LIST_SYSCALLS                             = 4,
-       LTTNG_ENABLE_CHANNEL                            = 5,
-       LTTNG_ENABLE_EVENT                              = 6,
-       /* 7 */
-       /* Session daemon command */
-       /* 8 */
-       LTTNG_DESTROY_SESSION                           = 9,
-       LTTNG_LIST_CHANNELS                             = 10,
-       LTTNG_LIST_DOMAINS                              = 11,
-       LTTNG_LIST_EVENTS                               = 12,
-       LTTNG_LIST_SESSIONS                             = 13,
-       LTTNG_LIST_TRACEPOINTS                          = 14,
-       LTTNG_REGISTER_CONSUMER                         = 15,
-       LTTNG_START_TRACE                               = 16,
-       LTTNG_STOP_TRACE                                = 17,
-       LTTNG_LIST_TRACEPOINT_FIELDS                    = 18,
-
-       /* Consumer */
-       LTTNG_DISABLE_CONSUMER                          = 19,
-       LTTNG_ENABLE_CONSUMER                           = 20,
-       LTTNG_SET_CONSUMER_URI                          = 21,
-       /* 22 */
-       /* 23 */
-       LTTNG_DATA_PENDING                              = 24,
-       LTTNG_SNAPSHOT_ADD_OUTPUT                       = 25,
-       LTTNG_SNAPSHOT_DEL_OUTPUT                       = 26,
-       LTTNG_SNAPSHOT_LIST_OUTPUT                      = 27,
-       LTTNG_SNAPSHOT_RECORD                           = 28,
-       /* 29 */
-       /* 30 */
-       LTTNG_SAVE_SESSION                              = 31,
-       LTTNG_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE    = 32,
-       LTTNG_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE = 33,
-       LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY           = 34,
-       LTTNG_PROCESS_ATTR_TRACKER_SET_POLICY           = 35,
-       LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET     = 36,
-       LTTNG_SET_SESSION_SHM_PATH                      = 40,
-       LTTNG_REGENERATE_METADATA                       = 41,
-       LTTNG_REGENERATE_STATEDUMP                      = 42,
-       LTTNG_REGISTER_TRIGGER                          = 43,
-       LTTNG_UNREGISTER_TRIGGER                        = 44,
-       LTTNG_ROTATE_SESSION                            = 45,
-       LTTNG_ROTATION_GET_INFO                         = 46,
-       LTTNG_ROTATION_SET_SCHEDULE                     = 47,
-       LTTNG_SESSION_LIST_ROTATION_SCHEDULES           = 48,
-       LTTNG_CREATE_SESSION_EXT                        = 49,
-       LTTNG_CLEAR_SESSION                             = 50,
-       LTTNG_LIST_TRIGGERS                             = 51,
-       LTTNG_EXECUTE_ERROR_QUERY                       = 52,
+       LTTCOMM_SESSIOND_COMMAND_MIN,
+       LTTCOMM_SESSIOND_COMMAND_ADD_CONTEXT,
+       LTTCOMM_SESSIOND_COMMAND_DISABLE_CHANNEL,
+       LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT,
+       LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS,
+       LTTCOMM_SESSIOND_COMMAND_ENABLE_CHANNEL,
+       LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT,
+       LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION,
+       LTTCOMM_SESSIOND_COMMAND_LIST_CHANNELS,
+       LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS,
+       LTTCOMM_SESSIOND_COMMAND_LIST_EVENTS,
+       LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS,
+       LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS,
+       LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER,
+       LTTCOMM_SESSIOND_COMMAND_START_TRACE,
+       LTTCOMM_SESSIOND_COMMAND_STOP_TRACE,
+       LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS,
+       LTTCOMM_SESSIOND_COMMAND_DISABLE_CONSUMER,
+       LTTCOMM_SESSIOND_COMMAND_ENABLE_CONSUMER,
+       LTTCOMM_SESSIOND_COMMAND_SET_CONSUMER_URI,
+       LTTCOMM_SESSIOND_COMMAND_DATA_PENDING,
+       LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_ADD_OUTPUT,
+       LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_DEL_OUTPUT,
+       LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_LIST_OUTPUT,
+       LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_RECORD,
+       LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION,
+       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE,
+       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE,
+       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_POLICY,
+       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_SET_POLICY,
+       LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET,
+       LTTCOMM_SESSIOND_COMMAND_SET_SESSION_SHM_PATH,
+       LTTCOMM_SESSIOND_COMMAND_REGENERATE_METADATA,
+       LTTCOMM_SESSIOND_COMMAND_REGENERATE_STATEDUMP,
+       LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER,
+       LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER,
+       LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION,
+       LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO,
+       LTTCOMM_SESSIOND_COMMAND_ROTATION_SET_SCHEDULE,
+       LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES,
+       LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT,
+       LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION,
+       LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS,
+       LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY,
+       LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS,
+       LTTCOMM_SESSIOND_COMMAND_MAX,
 };
 
-static inline
-const char *lttcomm_sessiond_command_str(enum lttcomm_sessiond_command cmd)
+static inline bool lttcomm_sessiond_command_is_valid(enum lttcomm_sessiond_command cmd)
+{
+       return cmd > LTTCOMM_SESSIOND_COMMAND_MIN && cmd < LTTCOMM_SESSIOND_COMMAND_MAX;
+}
+
+static inline const char *lttcomm_sessiond_command_str(enum lttcomm_sessiond_command cmd)
 {
        switch (cmd) {
-       case LTTNG_ADD_CONTEXT:
-               return "LTTNG_ADD_CONTEXT";
-       case LTTNG_DISABLE_CHANNEL:
-               return "LTTNG_DISABLE_CHANNEL";
-       case LTTNG_DISABLE_EVENT:
-               return "LTTNG_DISABLE_EVENT";
-       case LTTNG_LIST_SYSCALLS:
-               return "LTTNG_LIST_SYSCALLS";
-       case LTTNG_ENABLE_CHANNEL:
-               return "LTTNG_ENABLE_CHANNEL";
-       case LTTNG_ENABLE_EVENT:
-               return "LTTNG_ENABLE_EVENT";
-       case LTTNG_DESTROY_SESSION:
-               return "LTTNG_DESTROY_SESSION";
-       case LTTNG_LIST_CHANNELS:
-               return "LTTNG_LIST_CHANNELS";
-       case LTTNG_LIST_DOMAINS:
-               return "LTTNG_LIST_DOMAINS";
-       case LTTNG_LIST_EVENTS:
-               return "LTTNG_LIST_EVENTS";
-       case LTTNG_LIST_SESSIONS:
-               return "LTTNG_LIST_SESSIONS";
-       case LTTNG_LIST_TRACEPOINTS:
-               return "LTTNG_LIST_TRACEPOINTS";
-       case LTTNG_REGISTER_CONSUMER:
-               return "LTTNG_REGISTER_CONSUMER";
-       case LTTNG_START_TRACE:
-               return "LTTNG_START_TRACE";
-       case LTTNG_STOP_TRACE:
-               return "LTTNG_STOP_TRACE";
-       case LTTNG_LIST_TRACEPOINT_FIELDS:
-               return "LTTNG_LIST_TRACEPOINT_FIELDS";
-       case LTTNG_DISABLE_CONSUMER:
-               return "LTTNG_DISABLE_CONSUMER";
-       case LTTNG_ENABLE_CONSUMER:
-               return "LTTNG_ENABLE_CONSUMER";
-       case LTTNG_SET_CONSUMER_URI:
-               return "LTTNG_SET_CONSUMER_URI";
-       case LTTNG_DATA_PENDING:
-               return "LTTNG_DATA_PENDING";
-       case LTTNG_SNAPSHOT_ADD_OUTPUT:
-               return "LTTNG_SNAPSHOT_ADD_OUTPUT";
-       case LTTNG_SNAPSHOT_DEL_OUTPUT:
-               return "LTTNG_SNAPSHOT_DEL_OUTPUT";
-       case LTTNG_SNAPSHOT_LIST_OUTPUT:
-               return "LTTNG_SNAPSHOT_LIST_OUTPUT";
-       case LTTNG_SNAPSHOT_RECORD:
-               return "LTTNG_SNAPSHOT_RECORD";
-       case LTTNG_SAVE_SESSION:
-               return "LTTNG_SAVE_SESSION";
-       case LTTNG_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE:
-               return "LTTNG_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE";
-       case LTTNG_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE:
-               return "LTTNG_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE";
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY:
-               return "LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY";
-       case LTTNG_PROCESS_ATTR_TRACKER_SET_POLICY:
-               return "LTTNG_PROCESS_ATTR_TRACKER_SET_POLICY";
-       case LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
-               return "LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET";
-       case LTTNG_SET_SESSION_SHM_PATH:
-               return "LTTNG_SET_SESSION_SHM_PATH";
-       case LTTNG_REGENERATE_METADATA:
-               return "LTTNG_REGENERATE_METADATA";
-       case LTTNG_REGENERATE_STATEDUMP:
-               return "LTTNG_REGENERATE_STATEDUMP";
-       case LTTNG_REGISTER_TRIGGER:
-               return "LTTNG_REGISTER_TRIGGER";
-       case LTTNG_UNREGISTER_TRIGGER:
-               return "LTTNG_UNREGISTER_TRIGGER";
-       case LTTNG_ROTATE_SESSION:
-               return "LTTNG_ROTATE_SESSION";
-       case LTTNG_ROTATION_GET_INFO:
-               return "LTTNG_ROTATION_GET_INFO";
-       case LTTNG_ROTATION_SET_SCHEDULE:
-               return "LTTNG_ROTATION_SET_SCHEDULE";
-       case LTTNG_SESSION_LIST_ROTATION_SCHEDULES:
-               return "LTTNG_SESSION_LIST_ROTATION_SCHEDULES";
-       case LTTNG_CREATE_SESSION_EXT:
-               return "LTTNG_CREATE_SESSION_EXT";
-       case LTTNG_CLEAR_SESSION:
-               return "LTTNG_CLEAR_SESSION";
-       case LTTNG_LIST_TRIGGERS:
-               return "LTTNG_LIST_TRIGGERS";
-       case LTTNG_EXECUTE_ERROR_QUERY:
-               return "LTTNG_EXECUTE_ERROR_QUERY";
+       case LTTCOMM_SESSIOND_COMMAND_ADD_CONTEXT:
+               return "ADD_CONTEXT";
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_CHANNEL:
+               return "DISABLE_CHANNEL";
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT:
+               return "DISABLE_EVENT";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS:
+               return "LIST_SYSCALLS";
+       case LTTCOMM_SESSIOND_COMMAND_ENABLE_CHANNEL:
+               return "ENABLE_CHANNEL";
+       case LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT:
+               return "ENABLE_EVENT";
+       case LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION:
+               return "DESTROY_SESSION";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_CHANNELS:
+               return "LIST_CHANNELS";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS:
+               return "LIST_DOMAINS";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_EVENTS:
+               return "LIST_EVENTS";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS:
+               return "LIST_SESSIONS";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS:
+               return "LIST_TRACEPOINTS";
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER:
+               return "REGISTER_CONSUMER";
+       case LTTCOMM_SESSIOND_COMMAND_START_TRACE:
+               return "START_TRACE";
+       case LTTCOMM_SESSIOND_COMMAND_STOP_TRACE:
+               return "STOP_TRACE";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS:
+               return "LIST_TRACEPOINT_FIELDS";
+       case LTTCOMM_SESSIOND_COMMAND_DISABLE_CONSUMER:
+               return "DISABLE_CONSUMER";
+       case LTTCOMM_SESSIOND_COMMAND_ENABLE_CONSUMER:
+               return "ENABLE_CONSUMER";
+       case LTTCOMM_SESSIOND_COMMAND_SET_CONSUMER_URI:
+               return "SET_CONSUMER_URI";
+       case LTTCOMM_SESSIOND_COMMAND_DATA_PENDING:
+               return "DATA_PENDING";
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_ADD_OUTPUT:
+               return "SNAPSHOT_ADD_OUTPUT";
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_DEL_OUTPUT:
+               return "SNAPSHOT_DEL_OUTPUT";
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_LIST_OUTPUT:
+               return "SNAPSHOT_LIST_OUTPUT";
+       case LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_RECORD:
+               return "SNAPSHOT_RECORD";
+       case LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION:
+               return "SAVE_SESSION";
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE:
+               return "PROCESS_ATTR_TRACKER_ADD_INCLUDE_VALUE";
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE:
+               return "PROCESS_ATTR_TRACKER_REMOVE_INCLUDE_VALUE";
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_POLICY:
+               return "PROCESS_ATTR_TRACKER_GET_POLICY";
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_SET_POLICY:
+               return "PROCESS_ATTR_TRACKER_SET_POLICY";
+       case LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET:
+               return "PROCESS_ATTR_TRACKER_GET_INCLUSION_SET";
+       case LTTCOMM_SESSIOND_COMMAND_SET_SESSION_SHM_PATH:
+               return "SET_SESSION_SHM_PATH";
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_METADATA:
+               return "REGENERATE_METADATA";
+       case LTTCOMM_SESSIOND_COMMAND_REGENERATE_STATEDUMP:
+               return "REGENERATE_STATEDUMP";
+       case LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER:
+               return "REGISTER_TRIGGER";
+       case LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER:
+               return "UNREGISTER_TRIGGER";
+       case LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION:
+               return "ROTATE_SESSION";
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO:
+               return "ROTATION_GET_INFO";
+       case LTTCOMM_SESSIOND_COMMAND_ROTATION_SET_SCHEDULE:
+               return "ROTATION_SET_SCHEDULE";
+       case LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES:
+               return "SESSION_LIST_ROTATION_SCHEDULES";
+       case LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT:
+               return "CREATE_SESSION_EXT";
+       case LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION:
+               return "CLEAR_SESSION";
+       case LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS:
+               return "LIST_TRIGGERS";
+       case LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY:
+               return "EXECUTE_ERROR_QUERY";
+       case LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS:
+               return "KERNEL_TRACER_STATUS";
        default:
                abort();
        }
 }
 
 enum lttcomm_relayd_command {
-       RELAYD_ADD_STREAM                   = 1,
-       RELAYD_CREATE_SESSION               = 2,
-       RELAYD_START_DATA                   = 3,
-       RELAYD_UPDATE_SYNC_INFO             = 4,
-       RELAYD_VERSION                      = 5,
-       RELAYD_SEND_METADATA                = 6,
-       RELAYD_CLOSE_STREAM                 = 7,
-       RELAYD_DATA_PENDING                 = 8,
-       RELAYD_QUIESCENT_CONTROL            = 9,
-       RELAYD_BEGIN_DATA_PENDING           = 10,
-       RELAYD_END_DATA_PENDING             = 11,
-       RELAYD_ADD_INDEX                    = 12,
-       RELAYD_SEND_INDEX                   = 13,
-       RELAYD_CLOSE_INDEX                  = 14,
+       RELAYD_ADD_STREAM = 1,
+       RELAYD_CREATE_SESSION = 2,
+       RELAYD_START_DATA = 3,
+       RELAYD_UPDATE_SYNC_INFO = 4,
+       RELAYD_VERSION = 5,
+       RELAYD_SEND_METADATA = 6,
+       RELAYD_CLOSE_STREAM = 7,
+       RELAYD_DATA_PENDING = 8,
+       RELAYD_QUIESCENT_CONTROL = 9,
+       RELAYD_BEGIN_DATA_PENDING = 10,
+       RELAYD_END_DATA_PENDING = 11,
+       RELAYD_ADD_INDEX = 12,
+       RELAYD_SEND_INDEX = 13,
+       RELAYD_CLOSE_INDEX = 14,
        /* Live-reading commands (2.4+). */
-       RELAYD_LIST_SESSIONS                = 15,
+       RELAYD_LIST_SESSIONS = 15,
        /* All streams of the channel have been sent to the relayd (2.4+). */
-       RELAYD_STREAMS_SENT                 = 16,
+       RELAYD_STREAMS_SENT = 16,
        /* Ask the relay to reset the metadata trace file (2.8+) */
-       RELAYD_RESET_METADATA               = 17,
+       RELAYD_RESET_METADATA = 17,
        /* Ask the relay to rotate a set of stream files (2.11+) */
-       RELAYD_ROTATE_STREAMS                = 18,
+       RELAYD_ROTATE_STREAMS = 18,
        /* Ask the relay to create a trace chunk (2.11+) */
-       RELAYD_CREATE_TRACE_CHUNK           = 19,
+       RELAYD_CREATE_TRACE_CHUNK = 19,
        /* Ask the relay to close a trace chunk (2.11+) */
-       RELAYD_CLOSE_TRACE_CHUNK            = 20,
+       RELAYD_CLOSE_TRACE_CHUNK = 20,
        /* Ask the relay whether a trace chunk exists (2.11+) */
-       RELAYD_TRACE_CHUNK_EXISTS           = 21,
+       RELAYD_TRACE_CHUNK_EXISTS = 21,
        /* Get the current configuration of a relayd peer (2.12+) */
-       RELAYD_GET_CONFIGURATION            = 22,
+       RELAYD_GET_CONFIGURATION = 22,
 
        /* Feature branch specific commands start at 10000. */
 };
 
-static inline
-const char *lttcomm_relayd_command_str(lttcomm_relayd_command cmd)
+static inline const char *lttcomm_relayd_command_str(lttcomm_relayd_command cmd)
 {
        switch (cmd) {
        case RELAYD_ADD_STREAM:
@@ -292,7 +291,7 @@ const char *lttcomm_relayd_command_str(lttcomm_relayd_command cmd)
  * lttcomm error code.
  */
 enum lttcomm_return_code {
-       LTTCOMM_CONSUMERD_SUCCESS            = 0,   /* Everything went fine. */
+       LTTCOMM_CONSUMERD_SUCCESS = 0, /* Everything went fine. */
        /*
         * Some code paths use -1 to express an error, others
         * negate this consumer return code. Starting codes at
@@ -300,39 +299,39 @@ enum lttcomm_return_code {
         * and legitimate status codes.
         */
        LTTCOMM_CONSUMERD_COMMAND_SOCK_READY = 100, /* Command socket ready */
-       LTTCOMM_CONSUMERD_SUCCESS_RECV_FD,          /* Success on receiving fds */
-       LTTCOMM_CONSUMERD_ERROR_RECV_FD,            /* Error on receiving fds */
-       LTTCOMM_CONSUMERD_ERROR_RECV_CMD,           /* Error on receiving command */
-       LTTCOMM_CONSUMERD_POLL_ERROR,               /* Error in polling thread */
-       LTTCOMM_CONSUMERD_POLL_NVAL,                /* Poll on closed fd */
-       LTTCOMM_CONSUMERD_POLL_HUP,                 /* All fds have hungup */
-       LTTCOMM_CONSUMERD_EXIT_SUCCESS,             /* Consumerd exiting normally */
-       LTTCOMM_CONSUMERD_EXIT_FAILURE,             /* Consumerd exiting on error */
-       LTTCOMM_CONSUMERD_OUTFD_ERROR,              /* Error opening the tracefile */
-       LTTCOMM_CONSUMERD_SPLICE_EBADF,             /* EBADF from splice(2) */
-       LTTCOMM_CONSUMERD_SPLICE_EINVAL,            /* EINVAL from splice(2) */
-       LTTCOMM_CONSUMERD_SPLICE_ENOMEM,            /* ENOMEM from splice(2) */
-       LTTCOMM_CONSUMERD_SPLICE_ESPIPE,            /* ESPIPE from splice(2) */
-       LTTCOMM_CONSUMERD_ENOMEM,                   /* Consumer is out of memory */
-       LTTCOMM_CONSUMERD_ERROR_METADATA,           /* Error with metadata. */
-       LTTCOMM_CONSUMERD_FATAL,                    /* Fatal error. */
-       LTTCOMM_CONSUMERD_RELAYD_FAIL,              /* Error on remote relayd */
-       LTTCOMM_CONSUMERD_CHANNEL_FAIL,             /* Channel creation failed. */
-       LTTCOMM_CONSUMERD_CHAN_NOT_FOUND,           /* Channel not found. */
-       LTTCOMM_CONSUMERD_ALREADY_SET,              /* Resource already set. */
-       LTTCOMM_CONSUMERD_ROTATION_FAIL,            /* Rotation has failed. */
-       LTTCOMM_CONSUMERD_SNAPSHOT_FAILED,          /* snapshot has failed. */
-       LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED,/* Trace chunk creation failed. */
+       LTTCOMM_CONSUMERD_SUCCESS_RECV_FD, /* Success on receiving fds */
+       LTTCOMM_CONSUMERD_ERROR_RECV_FD, /* Error on receiving fds */
+       LTTCOMM_CONSUMERD_ERROR_RECV_CMD, /* Error on receiving command */
+       LTTCOMM_CONSUMERD_POLL_ERROR, /* Error in polling thread */
+       LTTCOMM_CONSUMERD_POLL_NVAL, /* Poll on closed fd */
+       LTTCOMM_CONSUMERD_POLL_HUP, /* All fds have hungup */
+       LTTCOMM_CONSUMERD_EXIT_SUCCESS, /* Consumerd exiting normally */
+       LTTCOMM_CONSUMERD_EXIT_FAILURE, /* Consumerd exiting on error */
+       LTTCOMM_CONSUMERD_OUTFD_ERROR, /* Error opening the tracefile */
+       LTTCOMM_CONSUMERD_SPLICE_EBADF, /* EBADF from splice(2) */
+       LTTCOMM_CONSUMERD_SPLICE_EINVAL, /* EINVAL from splice(2) */
+       LTTCOMM_CONSUMERD_SPLICE_ENOMEM, /* ENOMEM from splice(2) */
+       LTTCOMM_CONSUMERD_SPLICE_ESPIPE, /* ESPIPE from splice(2) */
+       LTTCOMM_CONSUMERD_ENOMEM, /* Consumer is out of memory */
+       LTTCOMM_CONSUMERD_ERROR_METADATA, /* Error with metadata. */
+       LTTCOMM_CONSUMERD_FATAL, /* Fatal error. */
+       LTTCOMM_CONSUMERD_RELAYD_FAIL, /* Error on remote relayd */
+       LTTCOMM_CONSUMERD_CHANNEL_FAIL, /* Channel creation failed. */
+       LTTCOMM_CONSUMERD_CHAN_NOT_FOUND, /* Channel not found. */
+       LTTCOMM_CONSUMERD_ALREADY_SET, /* Resource already set. */
+       LTTCOMM_CONSUMERD_ROTATION_FAIL, /* Rotation has failed. */
+       LTTCOMM_CONSUMERD_SNAPSHOT_FAILED, /* snapshot has failed. */
+       LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED, /* Trace chunk creation failed. */
        LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED, /* Trace chunk close failed. */
-       LTTCOMM_CONSUMERD_INVALID_PARAMETERS,       /* Invalid parameters. */
+       LTTCOMM_CONSUMERD_INVALID_PARAMETERS, /* Invalid parameters. */
        LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_LOCAL, /* Trace chunk exists on consumer daemon. */
-       LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE,/* Trace chunk exists on relay daemon. */
-       LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK,      /* Unknown trace chunk. */
-       LTTCOMM_CONSUMERD_RELAYD_CLEAR_DISALLOWED,  /* Relayd does not accept clear command. */
-       LTTCOMM_CONSUMERD_UNKNOWN_ERROR,            /* Unknown error. */
+       LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE, /* Trace chunk exists on relay daemon. */
+       LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK, /* Unknown trace chunk. */
+       LTTCOMM_CONSUMERD_RELAYD_CLEAR_DISALLOWED, /* Relayd does not accept clear command. */
+       LTTCOMM_CONSUMERD_UNKNOWN_ERROR, /* Unknown error. */
 
        /* MUST be last element */
-       LTTCOMM_NR,                                             /* Last element */
+       LTTCOMM_NR, /* Last element */
 };
 
 /* lttng socket protocol. */
@@ -345,8 +344,8 @@ enum lttcomm_sock_proto {
  * Index in the net_families array below. Please keep in sync!
  */
 enum lttcomm_sock_domain {
-       LTTCOMM_INET      = 0,
-       LTTCOMM_INET6     = 1,
+       LTTCOMM_INET = 0,
+       LTTCOMM_INET6 = 1,
 };
 
 enum lttcomm_metadata_command {
@@ -395,19 +394,17 @@ struct lttcomm_relayd_sock {
 
 struct lttcomm_net_family {
        int family;
-       int (*create) (struct lttcomm_sock *sock, int type, int proto);
+       int (*create)(struct lttcomm_sock *sock, int type, int proto);
 };
 
 struct lttcomm_proto_ops {
-       int (*bind) (struct lttcomm_sock *sock);
-       int (*close) (struct lttcomm_sock *sock);
-       int (*connect) (struct lttcomm_sock *sock);
-       struct lttcomm_sock *(*accept) (struct lttcomm_sock *sock);
-       int (*listen) (struct lttcomm_sock *sock, int backlog);
-       ssize_t (*recvmsg) (struct lttcomm_sock *sock, void *buf, size_t len,
-                       int flags);
-       ssize_t (*sendmsg) (struct lttcomm_sock *sock, const void *buf,
-                       size_t len, int flags);
+       int (*bind)(struct lttcomm_sock *sock);
+       int (*close)(struct lttcomm_sock *sock);
+       int (*connect)(struct lttcomm_sock *sock);
+       struct lttcomm_sock *(*accept)(struct lttcomm_sock *sock);
+       int (*listen)(struct lttcomm_sock *sock, int backlog);
+       ssize_t (*recvmsg)(struct lttcomm_sock *sock, void *buf, size_t len, int flags);
+       ssize_t (*sendmsg)(struct lttcomm_sock *sock, const void *buf, size_t len, int flags);
 };
 
 struct process_attr_integral_value_comm {
@@ -421,7 +418,7 @@ struct process_attr_integral_value_comm {
  * Data structure received from lttng client to session daemon.
  */
 struct lttcomm_session_msg {
-       uint32_t cmd_type;      /* enum lttcomm_sessiond_command */
+       uint32_t cmd_type; /* enum lttcomm_sessiond_command */
        struct lttng_session session;
        struct lttng_domain domain;
        union {
@@ -466,7 +463,7 @@ struct lttcomm_session_msg {
                } LTTNG_PACKED snapshot_record;
                struct {
                        uint32_t nb_uri;
-                       unsigned int timer_interval;    /* usec */
+                       unsigned int timer_interval; /* usec */
                } LTTNG_PACKED session_live;
                struct {
                        struct lttng_save_session_attr attr;
@@ -540,17 +537,17 @@ struct lttcomm_session_msg {
        uint32_t fd_count;
 } LTTNG_PACKED;
 
-#define LTTNG_FILTER_MAX_LEN   65536
-#define LTTNG_SESSION_DESCRIPTOR_MAX_LEN       65536
+#define LTTNG_FILTER_MAX_LEN            65536
+#define LTTNG_SESSION_DESCRIPTOR_MAX_LEN 65536
 
 /*
  * Filter bytecode data. The reloc table is located at the end of the
  * bytecode. It is made of tuples: (uint16_t, var. len. string). It
  * starts at reloc_table_offset.
  */
-#define LTTNG_FILTER_PADDING   32
+#define LTTNG_FILTER_PADDING 32
 struct lttng_bytecode {
-       uint32_t len;   /* len of data */
+       uint32_t len; /* len of data */
        uint32_t reloc_table_offset;
        uint64_t seqnum;
        char padding[LTTNG_FILTER_PADDING];
@@ -562,15 +559,14 @@ struct lttng_bytecode {
  * by zero or more names, where the actual number of names is given by
  * the 'count' item of the structure.
  */
-#define LTTNG_EVENT_EXCLUSION_PADDING  32
+#define LTTNG_EVENT_EXCLUSION_PADDING 32
 struct lttng_event_exclusion {
        uint32_t count;
        char padding[LTTNG_EVENT_EXCLUSION_PADDING];
-       char names[][LTTNG_SYMBOL_NAME_LEN];
+       char names[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH][LTTNG_SYMBOL_NAME_LEN];
 } LTTNG_PACKED;
 
-#define LTTNG_EVENT_EXCLUSION_NAME_AT(_exclusion, _i) \
-       ((_exclusion)->names[_i])
+#define LTTNG_EVENT_EXCLUSION_NAME_AT(_exclusion, _i) ((_exclusion)->names[_i])
 
 /*
  * Listing command header.
@@ -606,7 +602,7 @@ struct lttcomm_event_extended_header {
 } LTTNG_PACKED;
 
 /*
- * Command header of the reply to an LTTNG_DESTROY_SESSION command.
+ * Command header of the reply to an LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION command.
  */
 struct lttcomm_session_destroy_command_header {
        /* enum lttng_session */
@@ -624,9 +620,9 @@ struct lttcomm_tracker_command_header {
  * Data structure for the response from sessiond to the lttng client.
  */
 struct lttcomm_lttng_msg {
-       uint32_t cmd_type;      /* enum lttcomm_sessiond_command */
-       uint32_t ret_code;      /* enum lttcomm_return_code */
-       uint32_t pid;           /* pid_t */
+       uint32_t cmd_type; /* enum lttcomm_sessiond_command */
+       uint32_t ret_code; /* enum lttcomm_return_code */
+       uint32_t pid; /* pid_t */
        uint32_t cmd_header_size;
        uint32_t data_size;
        uint32_t fd_count;
@@ -642,7 +638,7 @@ struct lttcomm_lttng_output_id {
  * operation.
  */
 struct lttcomm_consumer_msg {
-       uint32_t cmd_type;      /* enum lttng_consumer_command */
+       uint32_t cmd_type; /* enum lttng_consumer_command */
        union {
                struct {
                        uint64_t channel_key;
@@ -671,10 +667,10 @@ struct lttcomm_consumer_msg {
                struct {
                        uint64_t stream_key;
                        uint64_t channel_key;
-                       int32_t cpu;    /* On which CPU this stream is assigned. */
+                       int32_t cpu; /* On which CPU this stream is assigned. */
                        /* Tells the consumer if the stream should be or not monitored. */
                        uint32_t no_monitor;
-               } LTTNG_PACKED stream;  /* Only used by Kernel. */
+               } LTTNG_PACKED stream; /* Only used by Kernel. */
                struct {
                        uint64_t net_index;
                        enum lttng_stream_type type;
@@ -693,33 +689,33 @@ struct lttcomm_consumer_msg {
                        uint64_t session_id;
                } LTTNG_PACKED data_pending;
                struct {
-                       uint64_t subbuf_size;                   /* bytes */
-                       uint64_t num_subbuf;                    /* power of 2 */
-                       int32_t overwrite;                      /* 1: overwrite, 0: discard */
-                       uint32_t switch_timer_interval;         /* usec */
-                       uint32_t read_timer_interval;           /* usec */
-                       unsigned int live_timer_interval;       /* usec */
-                       uint8_t is_live;                        /* is part of a live session */
-                       uint32_t monitor_timer_interval;        /* usec */
-                       int32_t output;                         /* splice, mmap */
-                       int32_t type;                           /* metadata or per_cpu */
-                       uint64_t session_id;                    /* Tracing session id */
-                       char pathname[PATH_MAX];                /* Channel file path. */
-                       char name[LTTNG_SYMBOL_NAME_LEN];       /* Channel name. */
+                       uint64_t subbuf_size; /* bytes */
+                       uint64_t num_subbuf; /* power of 2 */
+                       int32_t overwrite; /* 1: overwrite, 0: discard */
+                       uint32_t switch_timer_interval; /* usec */
+                       uint32_t read_timer_interval; /* usec */
+                       unsigned int live_timer_interval; /* usec */
+                       uint8_t is_live; /* is part of a live session */
+                       uint32_t monitor_timer_interval; /* usec */
+                       int32_t output; /* splice, mmap */
+                       int32_t type; /* metadata or per_cpu */
+                       uint64_t session_id; /* Tracing session id */
+                       char pathname[PATH_MAX]; /* Channel file path. */
+                       char name[LTTNG_SYMBOL_NAME_LEN]; /* Channel name. */
                        /* Credentials used to open the UST buffer shared mappings. */
                        struct {
                                uint32_t uid;
                                uint32_t gid;
                        } LTTNG_PACKED buffer_credentials;
-                       uint64_t relayd_id;                     /* Relayd id if apply. */
-                       uint64_t key;                           /* Unique channel key. */
+                       uint64_t relayd_id; /* Relayd id if apply. */
+                       uint64_t key; /* Unique channel key. */
                        /* ID of the session's current trace chunk. */
                        LTTNG_OPTIONAL_COMM(uint64_t) LTTNG_PACKED chunk_id;
-                       unsigned char uuid[LTTNG_UUID_LEN];     /* uuid for ust tracer. */
-                       uint32_t chan_id;                       /* Channel ID on the tracer side. */
-                       uint64_t tracefile_size;        /* bytes */
-                       uint32_t tracefile_count;       /* number of tracefiles */
-                       uint64_t session_id_per_pid;    /* Per-pid session ID. */
+                       unsigned char uuid[LTTNG_UUID_LEN]; /* uuid for ust tracer. */
+                       uint32_t chan_id; /* Channel ID on the tracer side. */
+                       uint64_t tracefile_size; /* bytes */
+                       uint32_t tracefile_count; /* number of tracefiles */
+                       uint64_t session_id_per_pid; /* Per-pid session ID. */
                        /* Tells the consumer if the stream should be or not monitored. */
                        uint32_t monitor;
                        /*
@@ -740,29 +736,29 @@ struct lttcomm_consumer_msg {
                        uint64_t key;
                } LTTNG_PACKED destroy_channel;
                struct {
-                       uint64_t key;   /* Metadata channel key. */
-                       uint64_t target_offset; /* Offset in the consumer */
-                       uint64_t len;   /* Length of metadata to be received. */
+                       uint64_t key; /* Metadata channel key. */
+                       uint64_t target_offset; /* Offset in the consumer */
+                       uint64_t len; /* Length of metadata to be received. */
                        uint64_t version; /* Version of the metadata. */
                } LTTNG_PACKED push_metadata;
                struct {
-                       uint64_t key;   /* Metadata channel key. */
+                       uint64_t key; /* Metadata channel key. */
                } LTTNG_PACKED close_metadata;
                struct {
-                       uint64_t key;   /* Metadata channel key. */
+                       uint64_t key; /* Metadata channel key. */
                } LTTNG_PACKED setup_metadata;
                struct {
-                       uint64_t key;   /* Channel key. */
+                       uint64_t key; /* Channel key. */
                } LTTNG_PACKED flush_channel;
                struct {
-                       uint64_t key;   /* Channel key. */
+                       uint64_t key; /* Channel key. */
                } LTTNG_PACKED clear_quiescent_channel;
                struct {
                        char pathname[PATH_MAX];
                        /* Indicate if the snapshot goes on the relayd or locally. */
                        uint32_t use_relayd;
-                       uint32_t metadata;              /* This a metadata snapshot. */
-                       uint64_t relayd_id;             /* Relayd id if apply. */
+                       uint32_t metadata; /* This a metadata snapshot. */
+                       uint64_t relayd_id; /* Relayd id if apply. */
                        uint64_t key;
                        uint64_t nb_packets_per_stream;
                } LTTNG_PACKED snapshot_channel;
@@ -814,7 +810,8 @@ struct lttcomm_consumer_msg {
                        LTTNG_OPTIONAL_COMM(struct {
                                uint32_t uid;
                                uint32_t gid;
-                       } LTTNG_PACKED ) LTTNG_PACKED credentials;
+                       } LTTNG_PACKED)
+                       LTTNG_PACKED credentials;
                } LTTNG_PACKED create_trace_chunk;
                struct {
                        LTTNG_OPTIONAL_COMM(uint64_t) LTTNG_PACKED relayd_id;
@@ -905,8 +902,8 @@ struct lttcomm_ust_msg {
 struct lttcomm_ust_reply {
        uint32_t handle;
        uint32_t cmd;
-       uint32_t ret_code;      /* enum lttcomm_return_code */
-       uint32_t ret_val;       /* return value */
+       uint32_t ret_code; /* enum lttcomm_return_code */
+       uint32_t ret_val; /* return value */
        union {
                struct {
                        uint64_t memory_map_size;
@@ -923,38 +920,38 @@ struct lttcomm_ust_reply {
 const char *lttcomm_get_readable_code(enum lttcomm_return_code code);
 
 int lttcomm_init_inet_sockaddr(struct lttcomm_sockaddr *sockaddr,
-               const char *ip, unsigned int port);
+                              const char *ip,
+                              unsigned int port);
 int lttcomm_init_inet6_sockaddr(struct lttcomm_sockaddr *sockaddr,
-               const char *ip, unsigned int port);
+                               const char *ip,
+                               unsigned int port);
 
 struct lttcomm_sock *lttcomm_alloc_sock(enum lttcomm_sock_proto proto);
 int lttcomm_populate_sock_from_open_socket(struct lttcomm_sock *sock,
-               int fd,
-               enum lttcomm_sock_proto protocol);
+                                          int fd,
+                                          enum lttcomm_sock_proto protocol);
 int lttcomm_create_sock(struct lttcomm_sock *sock);
 struct lttcomm_sock *lttcomm_alloc_sock_from_uri(struct lttng_uri *uri);
 void lttcomm_destroy_sock(struct lttcomm_sock *sock);
 struct lttcomm_sock *lttcomm_alloc_copy_sock(struct lttcomm_sock *src);
-void lttcomm_copy_sock(struct lttcomm_sock *dst,
-               struct lttcomm_sock *src);
+void lttcomm_copy_sock(struct lttcomm_sock *dst, struct lttcomm_sock *src);
 
 /* Relayd socket object. */
-struct lttcomm_relayd_sock *lttcomm_alloc_relayd_sock(
-               struct lttng_uri *uri, uint32_t major, uint32_t minor);
+struct lttcomm_relayd_sock *
+lttcomm_alloc_relayd_sock(struct lttng_uri *uri, uint32_t major, uint32_t minor);
 
 int lttcomm_setsockopt_rcv_timeout(int sock, unsigned int msec);
 int lttcomm_setsockopt_snd_timeout(int sock, unsigned int msec);
 
-int lttcomm_sock_get_port(const struct lttcomm_sock *sock,
-               uint16_t *port);
+int lttcomm_sock_get_port(const struct lttcomm_sock *sock, uint16_t *port);
 /*
  * Set a port to an lttcomm_sock. This will have no effect is the socket is
  * already bound.
  */
 int lttcomm_sock_set_port(struct lttcomm_sock *sock, uint16_t port);
 
-void lttcomm_init(void);
+void lttcomm_init();
 /* Get network timeout, in milliseconds */
-unsigned long lttcomm_get_network_timeout(void);
+unsigned long lttcomm_get_network_timeout();
 
-#endif /* _LTTNG_SESSIOND_COMM_H */
+#endif /* _LTTNG_SESSIOND_COMM_H */
index 300ffe357e98cafdfabb02146ab8736bc8474104..deaf715a651cd62ba156dbf2f173da0d5526fcec 100644 (file)
@@ -7,6 +7,10 @@
  */
 
 #define _LGPL_SOURCE
+#include "shm.hpp"
+
+#include <common/error.hpp>
+
 #include <fcntl.h>
 #include <limits.h>
 #include <sys/mman.h>
 #include <unistd.h>
 #include <urcu.h>
 
-#include <common/error.hpp>
-
-#include "shm.hpp"
-
 /*
  * We deal with the shm_open vs ftruncate race (happening when the sessiond owns
  * the shm and does not let everybody modify it, to ensure safety against
@@ -84,13 +84,15 @@ static int get_wait_shm(char *shm_path, size_t mmap_size, int global)
                if (errno == EACCES) {
                        /* Work around sysctl fs.protected_regular. */
                        DBG("shm_open of %s returned EACCES, this may be caused "
-                                       "by the fs.protected_regular sysctl. "
-                                       "Attempting to open the shm without "
-                                       "creating it.", shm_path);
+                           "by the fs.protected_regular sysctl. "
+                           "Attempting to open the shm without "
+                           "creating it.",
+                           shm_path);
                        wait_shm_fd = shm_open(shm_path, O_RDWR, mode);
                }
                if (wait_shm_fd < 0) {
-                       PERROR("Failed to open \"wait\" shared memory object: path = '%s'", shm_path);
+                       PERROR("Failed to open \"wait\" shared memory object: path = '%s'",
+                              shm_path);
                        goto error;
                }
        }
@@ -98,7 +100,8 @@ static int get_wait_shm(char *shm_path, size_t mmap_size, int global)
        ret = ftruncate(wait_shm_fd, mmap_size);
        if (ret < 0) {
                PERROR("Failed to truncate \"wait\" shared memory object: fd = %d, size = %zu",
-                               wait_shm_fd, mmap_size);
+                      wait_shm_fd,
+                      mmap_size);
                goto error;
        }
 
@@ -106,7 +109,7 @@ static int get_wait_shm(char *shm_path, size_t mmap_size, int global)
                ret = fchown(wait_shm_fd, 0, 0);
                if (ret < 0) {
                        PERROR("Failed to set ownership of \"wait\" shared memory object: fd = %d, owner = 0, group = 0",
-                                       wait_shm_fd);
+                              wait_shm_fd);
                        goto error;
                }
                /*
@@ -118,21 +121,26 @@ static int get_wait_shm(char *shm_path, size_t mmap_size, int global)
                ret = fchmod(wait_shm_fd, mode);
                if (ret < 0) {
                        PERROR("Failed to set the mode of the \"wait\" shared memory object: fd = %d, mode = %d",
-                                       wait_shm_fd, mode);
+                              wait_shm_fd,
+                              mode);
                        goto error;
                }
        } else {
                ret = fchown(wait_shm_fd, getuid(), getgid());
                if (ret < 0) {
                        PERROR("Failed to set ownership of \"wait\" shared memory object: fd = %d, owner = %d, group = %d",
-                                       wait_shm_fd, getuid(), getgid());
+                              wait_shm_fd,
+                              getuid(),
+                              getgid());
                        goto error;
                }
        }
 
        DBG("Wait shared memory file descriptor created successfully: path = '%s', mmap_size = %zu, global = %s, fd = %d",
-                       shm_path, mmap_size, global ? "true" : "false",
-                       wait_shm_fd);
+           shm_path,
+           mmap_size,
+           global ? "true" : "false",
+           wait_shm_fd);
 
 end:
        (void) umask(old_mode);
@@ -179,26 +187,27 @@ char *shm_ust_get_mmap(char *shm_path, int global)
                goto error;
        }
 
-       wait_shm_mmap = (char *) mmap(NULL, mmap_size, PROT_WRITE | PROT_READ,
-                       MAP_SHARED, wait_shm_fd, 0);
+       wait_shm_mmap = (char *) mmap(
+               nullptr, mmap_size, PROT_WRITE | PROT_READ, MAP_SHARED, wait_shm_fd, 0);
 
        /* close shm fd immediately after taking the mmap reference */
        ret = close(wait_shm_fd);
        if (ret) {
                PERROR("Failed to close \"wait\" shared memory object file descriptor: fd = %d",
-                               wait_shm_fd);
+                      wait_shm_fd);
        }
 
        if (wait_shm_mmap == MAP_FAILED) {
                DBG("Failed to mmap the \"wait\" shareed memory object (can be caused by race with ust): path = '%s', global = %s",
-                               shm_path, global ? "true" : "false");
+                   shm_path,
+                   global ? "true" : "false");
                goto error;
        }
 
        return wait_shm_mmap;
 
 error:
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -212,7 +221,8 @@ int shm_create_anonymous(const char *owner_name)
        ret = snprintf(tmp_name, NAME_MAX, "/shm-%s-%d", owner_name, getpid());
        if (ret < 0) {
                PERROR("Failed to format shm path: owner_name = '%s', pid = %d",
-                               owner_name, getpid());
+                      owner_name,
+                      getpid());
                return -1;
        }
 
@@ -228,8 +238,7 @@ int shm_create_anonymous(const char *owner_name)
 
        ret = shm_unlink(tmp_name);
        if (ret < 0 && errno != ENOENT) {
-               PERROR("Failed to unlink shared memory object: path = '%s'",
-                               tmp_name);
+               PERROR("Failed to unlink shared memory object: path = '%s'", tmp_name);
                goto error_shm_release;
        }
 
@@ -239,7 +248,8 @@ error_shm_release:
        ret = close(shmfd);
        if (ret) {
                PERROR("Failed to close shared memory object file descriptor: fd = %d, path = '%s'",
-                               shmfd, tmp_name);
+                      shmfd,
+                      tmp_name);
        }
 error_shm_open:
        return -1;
index 191f484c255b0d5a9669737b07e6fff8b3c535cb..765c11cb4d60efab0fbd84de372dd68f0c571f1f 100644 (file)
@@ -10,6 +10,7 @@
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
 #include <common/snapshot.hpp>
+
 #include <lttng/snapshot-internal.hpp>
 #include <lttng/snapshot.h>
 
@@ -46,9 +47,8 @@ end:
        return valid;
 }
 
-bool lttng_snapshot_output_is_equal(
-               const struct lttng_snapshot_output *a,
-               const struct lttng_snapshot_output *b)
+bool lttng_snapshot_output_is_equal(const struct lttng_snapshot_output *a,
+                                   const struct lttng_snapshot_output *b)
 {
        bool equal = false;
 
@@ -90,9 +90,8 @@ struct lttng_snapshot_output_comm {
 } LTTNG_PACKED;
 } /* namespace */
 
-int lttng_snapshot_output_serialize(
-               const struct lttng_snapshot_output *output,
-               struct lttng_payload *payload)
+int lttng_snapshot_output_serialize(const struct lttng_snapshot_output *output,
+                                   struct lttng_payload *payload)
 {
        struct lttng_snapshot_output_comm comm;
        int ret;
@@ -105,20 +104,17 @@ int lttng_snapshot_output_serialize(
                goto end;
        }
 
-       ret = lttng_strncpy(
-                       comm.ctrl_url, output->ctrl_url, sizeof(comm.ctrl_url));
+       ret = lttng_strncpy(comm.ctrl_url, output->ctrl_url, sizeof(comm.ctrl_url));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_strncpy(
-                       comm.data_url, output->data_url, sizeof(comm.data_url));
+       ret = lttng_strncpy(comm.data_url, output->data_url, sizeof(comm.data_url));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, &comm, sizeof(comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &comm, sizeof(comm));
        if (ret) {
                goto end;
        }
@@ -127,12 +123,11 @@ end:
        return ret;
 }
 
-ssize_t lttng_snapshot_output_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_snapshot_output **output_p)
+ssize_t lttng_snapshot_output_create_from_payload(struct lttng_payload_view *view,
+                                                 struct lttng_snapshot_output **output_p)
 {
        const struct lttng_snapshot_output_comm *comm;
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
        int ret;
 
        if (view->buffer.size != sizeof(*comm)) {
@@ -156,20 +151,18 @@ ssize_t lttng_snapshot_output_create_from_payload(
                goto end;
        }
 
-       ret = lttng_strncpy(output->ctrl_url, comm->ctrl_url,
-                       sizeof(output->ctrl_url));
+       ret = lttng_strncpy(output->ctrl_url, comm->ctrl_url, sizeof(output->ctrl_url));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_strncpy(output->data_url, comm->data_url,
-                       sizeof(output->data_url));
+       ret = lttng_strncpy(output->data_url, comm->data_url, sizeof(output->data_url));
        if (ret) {
                goto end;
        }
 
        *output_p = output;
-       output = NULL;
+       output = nullptr;
        ret = sizeof(*comm);
 
 end:
@@ -177,9 +170,8 @@ end:
        return ret;
 }
 
-enum lttng_error_code lttng_snapshot_output_mi_serialize(
-               const struct lttng_snapshot_output *output,
-               struct mi_writer *writer)
+enum lttng_error_code lttng_snapshot_output_mi_serialize(const struct lttng_snapshot_output *output,
+                                                        struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -188,8 +180,7 @@ enum lttng_error_code lttng_snapshot_output_mi_serialize(
        LTTNG_ASSERT(writer);
 
        /* Open output element. */
-       ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_action_snapshot_session_output);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_action_snapshot_session_output);
        if (ret) {
                goto mi_error;
        }
@@ -197,24 +188,23 @@ enum lttng_error_code lttng_snapshot_output_mi_serialize(
        /* Name. */
        if (strnlen(output->name, LTTNG_NAME_MAX) != 0) {
                ret = mi_lttng_writer_write_element_string(
-                               writer, config_element_name, output->name);
+                       writer, config_element_name, output->name);
                if (ret) {
                        goto mi_error;
                }
        }
 
        /* Control url (always present). */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_snapshot_ctrl_url, output->ctrl_url);
        if (ret) {
                goto mi_error;
        }
 
        /* Data url (optional). */
        if (strnlen(output->data_url, PATH_MAX) != 0) {
-               ret = mi_lttng_writer_write_element_string(writer,
-                               mi_lttng_element_snapshot_data_url,
-                               output->data_url);
+               ret = mi_lttng_writer_write_element_string(
+                       writer, mi_lttng_element_snapshot_data_url, output->data_url);
                if (ret) {
                        goto mi_error;
                }
@@ -230,9 +220,8 @@ enum lttng_error_code lttng_snapshot_output_mi_serialize(
         */
        if (output->max_size > 0 && output->max_size != UINT64_MAX) {
                /* Total size of all stream combined. */
-               ret = mi_lttng_writer_write_element_unsigned_int(writer,
-                               mi_lttng_element_snapshot_max_size,
-                               output->max_size);
+               ret = mi_lttng_writer_write_element_unsigned_int(
+                       writer, mi_lttng_element_snapshot_max_size, output->max_size);
                if (ret) {
                        goto mi_error;
                }
index d7442152f16af428d433330c646d52d1db9d72b5..1465fbd4d1a6fd5d9a9da6a52db5f7e34d08ddfa 100644 (file)
@@ -8,6 +8,7 @@
 #ifndef COMMON_SNAPSHOT_H
 #define COMMON_SNAPSHOT_H
 
+#include <common/error.hpp>
 #include <common/macros.hpp>
 
 #include <stdbool.h>
@@ -20,20 +21,16 @@ struct mi_writer;
 
 bool lttng_snapshot_output_validate(const struct lttng_snapshot_output *output);
 
-bool lttng_snapshot_output_is_equal(
-               const struct lttng_snapshot_output *a,
-               const struct lttng_snapshot_output *b);
+bool lttng_snapshot_output_is_equal(const struct lttng_snapshot_output *a,
+                                   const struct lttng_snapshot_output *b);
 
-int lttng_snapshot_output_serialize(
-               const struct lttng_snapshot_output *output,
-               struct lttng_payload *payload);
+int lttng_snapshot_output_serialize(const struct lttng_snapshot_output *output,
+                                   struct lttng_payload *payload);
 
-ssize_t lttng_snapshot_output_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_snapshot_output **output_p);
+ssize_t lttng_snapshot_output_create_from_payload(struct lttng_payload_view *view,
+                                                 struct lttng_snapshot_output **output_p);
 
-enum lttng_error_code lttng_snapshot_output_mi_serialize(
-               const struct lttng_snapshot_output *output,
-               struct mi_writer *writer);
+enum lttng_error_code lttng_snapshot_output_mi_serialize(const struct lttng_snapshot_output *output,
+                                                        struct mi_writer *writer);
 
 #endif /* COMMON_SNAPSHOT_H */
index 0b605a6442a797ad0822e7d034e016d8abd84e5d..150fa4e94bafe948ba3d4f96cb59f1365adddb22 100644 (file)
@@ -7,26 +7,27 @@
  *
  */
 
+#include "error.hpp"
+#include "macros.hpp"
+#include "spawn-viewer.hpp"
+
+#include <common/compat/errno.hpp>
+
+#include <lttng/constant.h>
+
 #include <stdbool.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <lttng/constant.h>
-
-#include <common/compat/errno.hpp>
-#include "error.hpp"
-#include "macros.hpp"
-#include "spawn-viewer.hpp"
-
 /*
  * Type is also use as the index in the viewers array. So please, make sure
  * your enum value is in the right order in the array below.
  */
 enum viewer_type {
-       VIEWER_BABELTRACE    = 0,
-       VIEWER_BABELTRACE2   = 1,
-       VIEWER_USER_DEFINED  = 2,
+       VIEWER_BABELTRACE = 0,
+       VIEWER_BABELTRACE2 = 1,
+       VIEWER_USER_DEFINED = 2,
 };
 
 namespace {
@@ -45,13 +46,13 @@ const struct viewer {
 } viewers[] = {
        { "babeltrace", VIEWER_BABELTRACE },
        { "babeltrace2", VIEWER_BABELTRACE2 },
-       { NULL, VIEWER_USER_DEFINED },
+       { nullptr, VIEWER_USER_DEFINED },
 };
 } /* namespace */
 
 static const struct viewer *parse_viewer_option(const char *opt_viewer)
 {
-       if (opt_viewer == NULL) {
+       if (opt_viewer == nullptr) {
                /* Default is babeltrace2 */
                return &(viewers[VIEWER_BABELTRACE2]);
        }
@@ -69,7 +70,7 @@ static char **alloc_argv_from_user_opts(char *opts, const char *trace_path)
 {
        int i = 0, ignore_space = 0;
        unsigned int num_opts = 1;
-       char **argv, *token = opts, *saveptr = NULL;
+       char **argv, *token = opts, *saveptr = nullptr;
 
        /* Count number of arguments. */
        do {
@@ -87,22 +88,22 @@ static char **alloc_argv_from_user_opts(char *opts, const char *trace_path)
 
        /* Add two here for the NULL terminating element and trace path */
        argv = calloc<char *>(num_opts + 2);
-       if (argv == NULL) {
+       if (argv == nullptr) {
                goto error;
        }
 
        token = strtok_r(opts, " ", &saveptr);
-       while (token != NULL) {
+       while (token != nullptr) {
                argv[i] = strdup(token);
-               if (argv[i] == NULL) {
+               if (argv[i] == nullptr) {
                        goto error;
                }
-               token = strtok_r(NULL, " ", &saveptr);
+               token = strtok_r(nullptr, " ", &saveptr);
                i++;
        }
 
        argv[num_opts] = (char *) trace_path;
-       argv[num_opts + 1] = NULL;
+       argv[num_opts + 1] = nullptr;
 
        return argv;
 
@@ -114,7 +115,7 @@ error:
                free(argv);
        }
 
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -123,8 +124,10 @@ error:
  *
  * The returning pointer is ready to be passed to execvp().
  */
-static char **alloc_argv_from_local_opts(const char **opts, size_t opts_len,
-               const char *trace_path, bool opt_live_mode)
+static char **alloc_argv_from_local_opts(const char **opts,
+                                        size_t opts_len,
+                                        const char *trace_path,
+                                        bool opt_live_mode)
 {
        char **argv;
        size_t mem_len;
@@ -140,7 +143,7 @@ static char **alloc_argv_from_local_opts(const char **opts, size_t opts_len,
        }
 
        argv = calloc<char *>(mem_len);
-       if (argv == NULL) {
+       if (argv == nullptr) {
                goto error;
        }
 
@@ -150,17 +153,16 @@ static char **alloc_argv_from_local_opts(const char **opts, size_t opts_len,
                argv[opts_len] = (char *) "-i";
                argv[opts_len + 1] = (char *) "lttng-live";
                argv[opts_len + 2] = (char *) trace_path;
-               argv[opts_len + 3] = NULL;
+               argv[opts_len + 3] = nullptr;
        } else {
                argv[opts_len] = (char *) trace_path;
-               argv[opts_len + 1] = NULL;
+               argv[opts_len + 1] = nullptr;
        }
 
 error:
        return argv;
 }
 
-
 /*
  * Spawn viewer with the trace directory path.
  */
@@ -168,13 +170,13 @@ int spawn_viewer(const char *trace_path, char *opt_viewer, bool opt_live_mode)
 {
        int ret = 0;
        struct stat status;
-       const char *viewer_bin = NULL;
+       const char *viewer_bin = nullptr;
        const struct viewer *viewer;
-       char **argv = NULL;
+       char **argv = nullptr;
 
        /* Check for --viewer option. */
        viewer = parse_viewer_option(opt_viewer);
-       if (viewer == NULL) {
+       if (viewer == nullptr) {
                ret = -1;
                goto error;
        }
@@ -187,9 +189,8 @@ retry_viewer:
                } else {
                        viewer_bin = viewer->exec_name;
                }
-               argv = alloc_argv_from_local_opts(babeltrace2_opts,
-                               ARRAY_SIZE(babeltrace2_opts), trace_path,
-                               opt_live_mode);
+               argv = alloc_argv_from_local_opts(
+                       babeltrace2_opts, ARRAY_SIZE(babeltrace2_opts), trace_path, opt_live_mode);
                break;
        case VIEWER_BABELTRACE:
                if (stat(babeltrace_bin, &status) == 0) {
@@ -197,9 +198,8 @@ retry_viewer:
                } else {
                        viewer_bin = viewer->exec_name;
                }
-               argv = alloc_argv_from_local_opts(babeltrace_opts,
-                               ARRAY_SIZE(babeltrace_opts), trace_path,
-                               opt_live_mode);
+               argv = alloc_argv_from_local_opts(
+                       babeltrace_opts, ARRAY_SIZE(babeltrace_opts), trace_path, opt_live_mode);
                break;
        case VIEWER_USER_DEFINED:
                argv = alloc_argv_from_user_opts(opt_viewer, trace_path);
@@ -211,7 +211,7 @@ retry_viewer:
                abort();
        }
 
-       if (argv == NULL || !viewer_bin) {
+       if (argv == nullptr || !viewer_bin) {
                ret = -1;
                goto error;
        }
@@ -224,16 +224,16 @@ retry_viewer:
                        if (viewer->type == VIEWER_BABELTRACE2) {
                                /* Fallback to legacy babeltrace. */
                                DBG("Default viewer \"%s\" not installed on the system, falling back to \"%s\"",
-                                               viewers[VIEWER_BABELTRACE2].exec_name,
-                                               viewers[VIEWER_BABELTRACE].exec_name);
+                                   viewers[VIEWER_BABELTRACE2].exec_name,
+                                   viewers[VIEWER_BABELTRACE].exec_name);
                                viewer = &viewers[VIEWER_BABELTRACE];
                                free(argv);
-                               argv = NULL;
+                               argv = nullptr;
                                goto retry_viewer;
                        } else {
                                ERR("Default viewer \"%s\" (and fallback \"%s\") not found on the system",
-                                               viewers[VIEWER_BABELTRACE2].exec_name,
-                                               viewers[VIEWER_BABELTRACE].exec_name);
+                                   viewers[VIEWER_BABELTRACE2].exec_name,
+                                   viewers[VIEWER_BABELTRACE].exec_name);
                        }
                } else {
                        PERROR("Failed to launch \"%s\" viewer", viewer_bin);
index 4c2fe0252824b30afcfa3404cf30534c8eb6d851..f7c7a82b5fde0ea2e4c98c62ba191cec8e24d126 100644 (file)
@@ -9,6 +9,7 @@
  */
 
 #include <lttng/lttng-export.h>
+
 #include <stdbool.h>
 
 /*
@@ -21,7 +22,7 @@
  * This symbol was mistakenly made public before the 2.12 release. It can't
  * be removed (but it can be stubbed-out if necessary).
  */
-extern "C" LTTNG_EXPORT
-int spawn_viewer(const char *trace_path, char *opt_viewer, bool opt_live_mode);
+extern "C" LTTNG_EXPORT int
+spawn_viewer(const char *trace_path, char *opt_viewer, bool opt_live_mode);
 
 #endif /* ifndef LTTNG_SPAWN_VIEWER_H */
index 244652332f1eee0d60a541baef9e53739b82b8b3..2cc9ed66ef2cd7c303166150b2bcd364b2a19b69 100644 (file)
@@ -16,6 +16,6 @@
  * assumes that no grouping/locale-aware formatting is performed (i.e. using
  * the `'` specifier in POSIX formatting functions).
  */
-#define MAX_INT_DEC_LEN(val)       ((3 * sizeof(val)) + 2)
+#define MAX_INT_DEC_LEN(val) ((3 * sizeof(val)) + 2)
 
 #endif /* _STRING_UTILS_FORMAT_H */
index d172aeb4b0fd69aaf3284e00283c2cdcab9cd5ce..4f727e2e8ed0fe9f407249e538a4dfe1b80d7f85 100644 (file)
@@ -6,17 +6,17 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdbool.h>
-#include <type_traits>
+#include "../macros.hpp"
+#include "string-utils.hpp"
+
 #include <assert.h>
 #include <errno.h>
 #include <stdarg.h>
-
-#include "string-utils.hpp"
-#include "../macros.hpp"
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <type_traits>
 
 enum star_glob_pattern_type_flags {
        STAR_GLOB_PATTERN_TYPE_FLAG_NONE = 0,
@@ -24,13 +24,11 @@ enum star_glob_pattern_type_flags {
        STAR_GLOB_PATTERN_TYPE_FLAG_END_ONLY = 2,
 };
 
-static
-star_glob_pattern_type_flags &operator|=(star_glob_pattern_type_flags &l,
-               star_glob_pattern_type_flags r)
+static star_glob_pattern_type_flags& operator|=(star_glob_pattern_type_flags& l,
+                                               star_glob_pattern_type_flags r)
 {
        using T = std::underlying_type<star_glob_pattern_type_flags>::type;
-       l = static_cast<star_glob_pattern_type_flags> (
-               static_cast<T> (l) | static_cast<T> (r));
+       l = static_cast<star_glob_pattern_type_flags>(static_cast<T>(l) | static_cast<T>(r));
        return l;
 }
 
@@ -81,11 +79,9 @@ end:
        *np = '\0';
 }
 
-static
-enum star_glob_pattern_type_flags strutils_test_glob_pattern(const char *pattern)
+static enum star_glob_pattern_type_flags strutils_test_glob_pattern(const char *pattern)
 {
-       enum star_glob_pattern_type_flags ret =
-               STAR_GLOB_PATTERN_TYPE_FLAG_NONE;
+       enum star_glob_pattern_type_flags ret = STAR_GLOB_PATTERN_TYPE_FLAG_NONE;
        const char *p;
 
        LTTNG_ASSERT(pattern);
@@ -122,8 +118,7 @@ end:
  */
 bool strutils_is_star_glob_pattern(const char *pattern)
 {
-       return strutils_test_glob_pattern(pattern) &
-               STAR_GLOB_PATTERN_TYPE_FLAG_PATTERN;
+       return strutils_test_glob_pattern(pattern) & STAR_GLOB_PATTERN_TYPE_FLAG_PATTERN;
 }
 
 /*
@@ -132,8 +127,7 @@ bool strutils_is_star_glob_pattern(const char *pattern)
  */
 bool strutils_is_star_at_the_end_only_glob_pattern(const char *pattern)
 {
-       return strutils_test_glob_pattern(pattern) &
-               STAR_GLOB_PATTERN_TYPE_FLAG_END_ONLY;
+       return strutils_test_glob_pattern(pattern) & STAR_GLOB_PATTERN_TYPE_FLAG_END_ONLY;
 }
 
 /*
@@ -251,9 +245,9 @@ void strutils_free_null_terminated_array_of_strings(char **array)
  * Returns -1 if there's an error.
  */
 int strutils_split(const char *input,
-               char delim,
-               bool escape_delim,
-               struct lttng_dynamic_pointer_array *out_strings)
+                  char delim,
+                  bool escape_delim,
+                  struct lttng_dynamic_pointer_array *out_strings)
 {
        int ret;
        size_t at;
@@ -305,8 +299,7 @@ int strutils_split(const char *input,
                        goto error;
                }
 
-               ret = lttng_dynamic_pointer_array_add_pointer(
-                               out_strings, substring);
+               ret = lttng_dynamic_pointer_array_add_pointer(out_strings, substring);
                if (ret) {
                        free(substring);
                        goto error;
@@ -364,9 +357,9 @@ end:
        return ret;
 }
 
-size_t strutils_array_of_strings_len(char * const *array)
+size_t strutils_array_of_strings_len(char *const *array)
 {
-       char * const *item;
+       char *const *item;
        size_t count = 0;
 
        LTTNG_ASSERT(array);
@@ -382,7 +375,7 @@ int strutils_append_str(char **s, const char *append)
 {
        char *old = *s;
        char *new_str;
-       size_t oldlen = (old == NULL) ? 0 : strlen(old);
+       size_t oldlen = (old == nullptr) ? 0 : strlen(old);
        size_t appendlen = strlen(append);
 
        new_str = zmalloc<char>(oldlen + appendlen + 1);
@@ -402,12 +395,13 @@ int strutils_appendf(char **s, const char *fmt, ...)
 {
        char *new_str;
        size_t oldlen = (*s) ? strlen(*s) : 0;
+       size_t addlen = 0;
        int ret;
        va_list args;
 
        /* Compute length of formatted string we append. */
        va_start(args, fmt);
-       ret = vsnprintf(NULL, 0, fmt, args);
+       ret = vsnprintf(nullptr, 0, fmt, args);
        va_end(args);
 
        if (ret == -1) {
@@ -415,7 +409,8 @@ int strutils_appendf(char **s, const char *fmt, ...)
        }
 
        /* Allocate space for old string + new string + \0. */
-       new_str = zmalloc<char>(oldlen + ret + 1);
+       addlen = ret + 1;
+       new_str = zmalloc<char>(oldlen + addlen);
        if (!new_str) {
                ret = -ENOMEM;
                goto end;
@@ -428,7 +423,7 @@ int strutils_appendf(char **s, const char *fmt, ...)
 
        /* Format new string in-place. */
        va_start(args, fmt);
-       ret = vsprintf(&new_str[oldlen], fmt, args); 
+       ret = vsnprintf(&new_str[oldlen], addlen, fmt, args);
        va_end(args);
 
        if (ret == -1) {
@@ -438,7 +433,7 @@ int strutils_appendf(char **s, const char *fmt, ...)
 
        free(*s);
        *s = new_str;
-       new_str = NULL;
+       new_str = nullptr;
 
 end:
        return ret;
index 4be165f9c9508e38638c431f6a31d79ec97f79f3..f6c9b8f828360adc4b08437477f81c3d578f552b 100644 (file)
@@ -8,9 +8,10 @@
 #ifndef _STRING_UTILS_H
 #define _STRING_UTILS_H
 
-#include <stdbool.h>
-#include <common/macros.hpp>
 #include <common/dynamic-array.hpp>
+#include <common/macros.hpp>
+
+#include <stdbool.h>
 
 void strutils_normalize_star_glob_pattern(char *pattern);
 
@@ -20,12 +21,14 @@ bool strutils_is_star_at_the_end_only_glob_pattern(const char *pattern);
 
 char *strutils_unescape_string(const char *input, char only_char);
 
-int strutils_split(const char *input, char delim, bool escape_delim,
-               struct lttng_dynamic_pointer_array *out_strings);
+int strutils_split(const char *input,
+                  char delim,
+                  bool escape_delim,
+                  struct lttng_dynamic_pointer_array *out_strings);
 
 void strutils_free_null_terminated_array_of_strings(char **array);
 
-size_t strutils_array_of_strings_len(char * const *array);
+size_t strutils_array_of_strings_len(char *const *array);
 
 /*
  * Append `append` to the malloc-end string `str`.
@@ -41,7 +44,6 @@ C_LINKAGE int strutils_append_str(char **str, const char *append);
  * Like `strutils_append_str`, but the appended string is formatted using
  * `fmt` and the following arguments.
  */
-C_LINKAGE ATTR_FORMAT_PRINTF(2, 3)
-int strutils_appendf(char **s, const char *fmt, ...);
+C_LINKAGE ATTR_FORMAT_PRINTF(2, 3) int strutils_appendf(char **s, const char *fmt, ...);
 
 #endif /* _STRING_UTILS_H */
index 4dfeadd81eb9aad643d31b5200f0d59e38e5e921..7d41fae5fa381d5299012a400799ccc940fd9d36 100644 (file)
@@ -8,12 +8,12 @@
 #ifndef NTESTPOINT
 
 #define _LGPL_SOURCE
-#include <dlfcn.h>  /* for dlsym   */
+#include "testpoint.hpp"
+
+#include <dlfcn.h> /* for dlsym   */
 #include <stdlib.h> /* for getenv  */
 #include <string.h> /* for strncmp */
 
-#include "testpoint.hpp"
-
 /* Environment variable used to enable the testpoints facilities. */
 static const char *lttng_testpoint_env_var = "LTTNG_TESTPOINT_ENABLE";
 
@@ -23,13 +23,12 @@ int lttng_testpoint_activated;
 /*
  * Toggle the support for testpoints on the application startup.
  */
-static void __attribute__((constructor)) lttng_testpoint_check(void)
+static void __attribute__((constructor)) lttng_testpoint_check()
 {
-       char *testpoint_env_val = NULL;
+       char *testpoint_env_val = nullptr;
 
        testpoint_env_val = getenv(lttng_testpoint_env_var);
-       if (testpoint_env_val != NULL
-                       && (strncmp(testpoint_env_val, "1", 1) == 0)) {
+       if (testpoint_env_val != nullptr && (strncmp(testpoint_env_val, "1", 1) == 0)) {
                lttng_testpoint_activated = 1;
        }
 }
@@ -43,7 +42,7 @@ static void __attribute__((constructor)) lttng_testpoint_check(void)
 void *lttng_testpoint_lookup(const char *name)
 {
        if (!name) {
-               return NULL;
+               return nullptr;
        }
 
        return dlsym(RTLD_DEFAULT, name);
index 33cb9aa340cc71e64939be17844aaea3e42fa26c..3682493eae4202750b083275dfae34dd82c9a621 100644 (file)
@@ -23,40 +23,38 @@ void *lttng_testpoint_lookup(const char *name);
  * set.
  * Return a non-zero error code to indicate failure.
  */
-#define testpoint(name)                                \
-       ((caa_unlikely(lttng_testpoint_activated))      \
-       ? __testpoint_##name##_wrapper() : 0)
+#define testpoint(name) \
+       ((caa_unlikely(lttng_testpoint_activated)) ? __testpoint_##name##_wrapper() : 0)
 
 /*
  * One wrapper per testpoint is generated. This is to keep track of the symbol
  * lookup status and the corresponding function pointer, if any.
  */
-#define _TESTPOINT_DECL(_name)                                         \
-       static inline int __testpoint_##_name##_wrapper(void)           \
-       {                                                               \
-               int ret = 0;                                            \
-               static int (*tp)(void);                                 \
-               static int found;                                       \
-               const char *tp_name = "__testpoint_" #_name;            \
-                                                                       \
-               if (tp) {                                               \
-                       ret = tp();                                     \
-               } else {                                                \
-                       if (!found) {                                   \
-                               tp = (int (*)(void)) lttng_testpoint_lookup(tp_name);   \
-                               if (tp) {                               \
-                                       found = 1;                      \
-                                       ret = tp();                     \
-                               } else {                                \
-                                       found = -1;                     \
-                               }                                       \
-                       }                                               \
-               }                                                       \
-               return ret;                                             \
+#define _TESTPOINT_DECL(_name)                                                        \
+       static inline int __testpoint_##_name##_wrapper(void)                         \
+       {                                                                             \
+               int ret = 0;                                                          \
+               static int (*tp)(void);                                               \
+               static int found;                                                     \
+               const char *tp_name = "__testpoint_" #_name;                          \
+                                                                                      \
+               if (tp) {                                                             \
+                       ret = tp();                                                   \
+               } else {                                                              \
+                       if (!found) {                                                 \
+                               tp = (int (*)(void)) lttng_testpoint_lookup(tp_name); \
+                               if (tp) {                                             \
+                                       found = 1;                                    \
+                                       ret = tp();                                   \
+                               } else {                                              \
+                                       found = -1;                                   \
+                               }                                                     \
+                       }                                                             \
+               }                                                                     \
+               return ret;                                                           \
        }
 
 /* Testpoint declaration */
-#define TESTPOINT_DECL(name)   \
-       _TESTPOINT_DECL(name)
+#define TESTPOINT_DECL(name) _TESTPOINT_DECL(name)
 
 #endif /* NTESTPOINT */
index fecc0064dbca83358dd65dfb559a1d8cca2e16bf..b46a55852a5f015485856e9a41228506372036df 100644 (file)
@@ -5,11 +5,11 @@
  *
  */
 
-#include <string.h>
+#include "thread.hpp"
 
 #include <common/compat/pthread.hpp>
-#include "thread.hpp"
 
+#include <string.h>
 
 int lttng_thread_setname(const char *name)
 {
@@ -27,4 +27,3 @@ int lttng_thread_setname(const char *name)
 
        return ret;
 }
-
index a60fcf23cfabf4c53edc3085084ca88a77996c76..ca29b2d61891efad38919300ee6771cc70f7008d 100644 (file)
@@ -21,7 +21,7 @@
 
 static bool utf8_output_supported;
 
-bool locale_supports_utf8(void)
+bool locale_supports_utf8()
 {
        return utf8_output_supported;
 }
@@ -32,13 +32,13 @@ int timespec_to_ms(struct timespec ts, unsigned long *ms)
 
        if (ts.tv_sec > ULONG_MAX / MSEC_PER_SEC) {
                errno = EOVERFLOW;
-               return -1;      /* multiplication overflow */
+               return -1; /* multiplication overflow */
        }
        res = ts.tv_sec * MSEC_PER_SEC;
        remain_ms = ULONG_MAX - res;
        if (ts.tv_nsec / NSEC_PER_MSEC > remain_ms) {
                errno = EOVERFLOW;
-               return -1;      /* addition overflow */
+               return -1; /* addition overflow */
        }
        res += ts.tv_nsec / NSEC_PER_MSEC;
        *ms = res;
@@ -47,10 +47,8 @@ int timespec_to_ms(struct timespec ts, unsigned long *ms)
 
 struct timespec timespec_abs_diff(struct timespec t1, struct timespec t2)
 {
-       uint64_t ts1 = (uint64_t) t1.tv_sec * (uint64_t) NSEC_PER_SEC +
-                       (uint64_t) t1.tv_nsec;
-       uint64_t ts2 = (uint64_t) t2.tv_sec * (uint64_t) NSEC_PER_SEC +
-                       (uint64_t) t2.tv_nsec;
+       uint64_t ts1 = (uint64_t) t1.tv_sec * (uint64_t) NSEC_PER_SEC + (uint64_t) t1.tv_nsec;
+       uint64_t ts2 = (uint64_t) t2.tv_sec * (uint64_t) NSEC_PER_SEC + (uint64_t) t2.tv_nsec;
        uint64_t diff = std::max(ts1, ts2) - std::min(ts1, ts2);
        struct timespec res;
 
@@ -59,10 +57,9 @@ struct timespec timespec_abs_diff(struct timespec t1, struct timespec t2)
        return res;
 }
 
-static
-void __attribute__((constructor)) init_locale_utf8_support(void)
+static void __attribute__((constructor)) init_locale_utf8_support()
 {
-       const char *program_locale = setlocale(LC_ALL, NULL);
+       const char *program_locale = setlocale(LC_ALL, nullptr);
        const char *lang = getenv("LANG");
 
        if (program_locale && strstr(program_locale, "utf8")) {
@@ -81,7 +78,8 @@ int time_to_iso8601_str(time_t time, char *str, size_t len)
 
        if (len < ISO8601_STR_LEN) {
                ERR("Buffer too short to format ISO 8601 timestamp: %zu bytes provided when at least %zu are needed",
-                               len, ISO8601_STR_LEN);
+                   len,
+                   ISO8601_STR_LEN);
                ret = -1;
                goto end;
        }
@@ -112,7 +110,8 @@ int time_to_datetime_str(time_t time, char *str, size_t len)
 
        if (len < DATETIME_STR_LEN) {
                ERR("Buffer too short to format to datetime: %zu bytes provided when at least %zu are needed",
-                               len, DATETIME_STR_LEN);
+                   len,
+                   DATETIME_STR_LEN);
                ret = -1;
                goto end;
        }
index 34c41a08adbd9837018489546c4dcc2a7894bd36..d07152c18a1dfd0167f368e0ca9272132571b07a 100644 (file)
@@ -8,38 +8,38 @@
 #ifndef LTTNG_TIME_H
 #define LTTNG_TIME_H
 
-#include <time.h>
+#include <common/compat/time.hpp>
+#include <common/macros.hpp>
+
 #include <ctime>
 #include <stdbool.h>
 #include <string>
+#include <time.h>
 
-#include <common/macros.hpp>
-#include <common/compat/time.hpp>
-
-#define MSEC_PER_SEC    1000ULL
-#define NSEC_PER_SEC    1000000000ULL
-#define NSEC_PER_MSEC   1000000ULL
-#define NSEC_PER_USEC   1000ULL
-#define USEC_PER_SEC    1000000ULL
-#define USEC_PER_MSEC   1000ULL
+#define MSEC_PER_SEC  1000ULL
+#define NSEC_PER_SEC  1000000000ULL
+#define NSEC_PER_MSEC 1000000ULL
+#define NSEC_PER_USEC 1000ULL
+#define USEC_PER_SEC  1000000ULL
+#define USEC_PER_MSEC 1000ULL
 
-#define SEC_PER_MINUTE  60ULL
+#define SEC_PER_MINUTE 60ULL
 #define MINUTE_PER_HOUR 60ULL
 
 #define USEC_PER_MINUTE (USEC_PER_SEC * SEC_PER_MINUTE)
-#define USEC_PER_HOURS  (USEC_PER_MINUTE * MINUTE_PER_HOUR)
+#define USEC_PER_HOURS (USEC_PER_MINUTE * MINUTE_PER_HOUR)
 
-#define ISO8601_STR_LEN sizeof("YYYYmmddTHHMMSS+HHMM")
+#define ISO8601_STR_LEN         sizeof("YYYYmmddTHHMMSS+HHMM")
 #define DATETIME_STR_LEN sizeof("YYYYmmdd-HHMMSS")
 
-bool locale_supports_utf8(void);
+bool locale_supports_utf8();
 
-#define NSEC_UNIT       "ns"
-#define USEC_UNIT       (locale_supports_utf8() ? "µs" : "us")
-#define MSEC_UNIT       "ms"
-#define SEC_UNIT        "s"
-#define MIN_UNIT        "m"
-#define HR_UNIT         "h"
+#define NSEC_UNIT "ns"
+#define USEC_UNIT (locale_supports_utf8() ? "µs" : "us")
+#define MSEC_UNIT "ms"
+#define SEC_UNIT  "s"
+#define MIN_UNIT  "m"
+#define HR_UNIT          "h"
 
 /*
  * timespec_to_ms: Convert timespec to milliseconds.
index e634e71e8163b67b283185f2f9788013185bc220..89125ca5033fd9e094593e3e412b4789238f6878 100644 (file)
@@ -8,12 +8,13 @@
 #ifndef LTTNG_TRACE_CHUNK_REGISTRY_H
 #define LTTNG_TRACE_CHUNK_REGISTRY_H
 
-#include <stddef.h>
-#include <stdint.h>
-#include <stdbool.h>
 #include <common/macros.hpp>
 #include <common/trace-chunk.hpp>
 
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
 struct lttng_trace_chunk_registry;
 
 /*
@@ -31,15 +32,14 @@ struct lttng_trace_chunk_registry;
  *
  * Note that a trace chunk registry may only be accessed by an RCU thread.
  */
-struct lttng_trace_chunk_registry *lttng_trace_chunk_registry_create(void);
+struct lttng_trace_chunk_registry *lttng_trace_chunk_registry_create();
 
 /*
  * Destroy an lttng trace chunk registry. The registry must be emptied
  * (i.e. all references to the trace chunks it contains must be released) before
  * it is destroyed.
  */
-void lttng_trace_chunk_registry_destroy(
-               struct lttng_trace_chunk_registry *registry);
+void lttng_trace_chunk_registry_destroy(struct lttng_trace_chunk_registry *registry);
 
 /*
  * Publish a trace chunk for a given session id.
@@ -54,13 +54,14 @@ void lttng_trace_chunk_registry_destroy(
  *
  * Returns an lttng_trace_chunk on success, NULL on error.
  */
-struct lttng_trace_chunk *lttng_trace_chunk_registry_publish_chunk(
-               struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, struct lttng_trace_chunk *chunk);
+struct lttng_trace_chunk *
+lttng_trace_chunk_registry_publish_chunk(struct lttng_trace_chunk_registry *registry,
+                                        uint64_t session_id,
+                                        struct lttng_trace_chunk *chunk);
 /*
  * Adds the `previously_published` parameter which allows the caller
  * to know if a trace chunk equivalent to `chunk` was previously published.
- * 
+ *
  * The registry holds a reference to the published trace chunks it contains.
  * Trace chunks automatically unpublish themselves from their registry on
  * destruction.
@@ -68,7 +69,7 @@ struct lttng_trace_chunk *lttng_trace_chunk_registry_publish_chunk(
  * This information is necessary to drop the reference of newly published
  * chunks when a user doesn't wish to explicitly maintain all references
  * to a given trace chunk.
- * 
+ *
  * For instance, the relay daemon doesn't need the registry to hold a
  * reference since it controls the lifetime of its trace chunks.
  * Conversely, the consumer daemons rely on the session daemon to inform
@@ -76,10 +77,11 @@ struct lttng_trace_chunk *lttng_trace_chunk_registry_publish_chunk(
  * belong to a specific top-level object: they are always retrieved from
  * the registry by `id`.
  */
-struct lttng_trace_chunk *lttng_trace_chunk_registry_publish_chunk(
-               struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, struct lttng_trace_chunk *chunk,
-               bool *previously_published);
+struct lttng_trace_chunk *
+lttng_trace_chunk_registry_publish_chunk(struct lttng_trace_chunk_registry *registry,
+                                        uint64_t session_id,
+                                        struct lttng_trace_chunk *chunk,
+                                        bool *previously_published);
 
 /*
  * Look-up a trace chunk by session_id and chunk_id.
@@ -87,19 +89,18 @@ struct lttng_trace_chunk *lttng_trace_chunk_registry_publish_chunk(
  *
  * Returns an lttng_trace_chunk on success, NULL if the chunk does not exist.
  */
-struct lttng_trace_chunk *
-lttng_trace_chunk_registry_find_chunk(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, uint64_t chunk_id);
+struct lttng_trace_chunk *lttng_trace_chunk_registry_find_chunk(
+       const struct lttng_trace_chunk_registry *registry, uint64_t session_id, uint64_t chunk_id);
 
 /*
  * Query the existence of a trace chunk by session_id and chunk_id.
  *
  * Returns 0 on success, a negative value on error.
  */
-int lttng_trace_chunk_registry_chunk_exists(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, uint64_t chunk_id, bool *chunk_exists);
+int lttng_trace_chunk_registry_chunk_exists(const struct lttng_trace_chunk_registry *registry,
+                                           uint64_t session_id,
+                                           uint64_t chunk_id,
+                                           bool *chunk_exists);
 
 /*
  * Look-up an anonymous trace chunk by session_id.
@@ -108,11 +109,10 @@ int lttng_trace_chunk_registry_chunk_exists(
  * Returns an lttng_trace_chunk on success, NULL if the chunk does not exist.
  */
 struct lttng_trace_chunk *
-lttng_trace_chunk_registry_find_anonymous_chunk(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id);
+lttng_trace_chunk_registry_find_anonymous_chunk(const struct lttng_trace_chunk_registry *registry,
+                                               uint64_t session_id);
 
-unsigned int lttng_trace_chunk_registry_put_each_chunk(
-               const struct lttng_trace_chunk_registry *registry);
+unsigned int
+lttng_trace_chunk_registry_put_each_chunk(const struct lttng_trace_chunk_registry *registry);
 
 #endif /* LTTNG_TRACE_CHUNK_REGISTRY_H */
index 488d0814620f32e4351913231d7596abff0fbdae..5da16a6134ac7027365a022abb27410bec2edf1f 100644 (file)
@@ -12,8 +12,8 @@
 #include <common/error.hpp>
 #include <common/fd-tracker/fd-tracker.hpp>
 #include <common/fd-tracker/utils.hpp>
-#include <common/fs-handle.hpp>
 #include <common/fs-handle-internal.hpp>
+#include <common/fs-handle.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/optional.hpp>
@@ -21,7 +21,9 @@
 #include <common/time.hpp>
 #include <common/trace-chunk-registry.hpp>
 #include <common/trace-chunk.hpp>
+#include <common/urcu.hpp>
 #include <common/utils.hpp>
+
 #include <lttng/constant.h>
 
 #include <inttypes.h>
@@ -36,7 +38,7 @@
  * index, i.e. <start-iso-8601>-<end-iso-8601>-<id-uint64_t>.
  */
 #define GENERATED_CHUNK_NAME_LEN (2 * sizeof("YYYYmmddTHHMMSS+HHMM") + MAX_INT_DEC_LEN(uint64_t))
-#define DIR_CREATION_MODE (S_IRWXU | S_IRWXG)
+#define DIR_CREATION_MODE       (S_IRWXU | S_IRWXG)
 
 enum trace_chunk_mode {
        TRACE_CHUNK_MODE_USER,
@@ -49,20 +51,16 @@ enum trace_chunk_mode {
  * since only one thread may access a chunk during its destruction (the last
  * to release its reference to the chunk).
  */
-typedef int (*chunk_command)(struct lttng_trace_chunk *trace_chunk);
+using chunk_command = int (*)(struct lttng_trace_chunk *);
 
 /* Move a completed trace chunk to the 'completed' trace archive folder. */
-static
-int lttng_trace_chunk_move_to_completed_post_release(struct lttng_trace_chunk *trace_chunk);
+static int lttng_trace_chunk_move_to_completed_post_release(struct lttng_trace_chunk *trace_chunk);
 /* Empty callback. */
-static
-int lttng_trace_chunk_no_operation(struct lttng_trace_chunk *trace_chunk);
+static int lttng_trace_chunk_no_operation(struct lttng_trace_chunk *trace_chunk);
 /* Unlink old chunk files. */
-static
-int lttng_trace_chunk_delete_post_release(struct lttng_trace_chunk *trace_chunk);
-static
-enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
-               struct lttng_trace_chunk *chunk, const char *path);
+static int lttng_trace_chunk_delete_post_release(struct lttng_trace_chunk *trace_chunk);
+static enum lttng_trace_chunk_status
+lttng_trace_chunk_rename_path_no_lock(struct lttng_trace_chunk *chunk, const char *path);
 
 namespace {
 struct chunk_credentials {
@@ -150,18 +148,13 @@ struct fs_handle_untracked {
 };
 } /* namespace */
 
-static
-int fs_handle_untracked_get_fd(struct fs_handle *handle);
-static
-void fs_handle_untracked_put_fd(struct fs_handle *handle);
-static
-int fs_handle_untracked_unlink(struct fs_handle *handle);
-static
-int fs_handle_untracked_close(struct fs_handle *handle);
-
-static
-const char *lttng_trace_chunk_command_type_str(
-               lttng_trace_chunk_command_type type) {
+static int fs_handle_untracked_get_fd(struct fs_handle *handle);
+static void fs_handle_untracked_put_fd(struct fs_handle *handle);
+static int fs_handle_untracked_unlink(struct fs_handle *handle);
+static int fs_handle_untracked_close(struct fs_handle *handle);
+
+static const char *lttng_trace_chunk_command_type_str(lttng_trace_chunk_command_type type)
+{
        switch (type) {
        case LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED:
                return "move to completed chunk folder";
@@ -176,9 +169,8 @@ const char *lttng_trace_chunk_command_type_str(
        abort();
 };
 
-static
-chunk_command close_command_get_post_release_func(
-               lttng_trace_chunk_command_type type) {
+static chunk_command close_command_get_post_release_func(lttng_trace_chunk_command_type type)
+{
        switch (type) {
        case LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED:
                return lttng_trace_chunk_move_to_completed_post_release;
@@ -193,13 +185,11 @@ chunk_command close_command_get_post_release_func(
        abort();
 };
 
-static
-struct fs_handle *fs_handle_untracked_create(
-               struct lttng_directory_handle *directory_handle,
-               const char *path,
-               int fd)
+static struct fs_handle *fs_handle_untracked_create(struct lttng_directory_handle *directory_handle,
+                                                   const char *path,
+                                                   int fd)
 {
-       struct fs_handle_untracked *handle = NULL;
+       struct fs_handle_untracked *handle = nullptr;
        bool reference_acquired;
        char *path_copy = strdup(path);
 
@@ -215,7 +205,7 @@ struct fs_handle *fs_handle_untracked_create(
                goto end;
        }
 
-       handle->parent = (typeof(handle->parent)) {
+       handle->parent = (typeof(handle->parent)){
                .get_fd = fs_handle_untracked_get_fd,
                .put_fd = fs_handle_untracked_put_fd,
                .unlink = fs_handle_untracked_unlink,
@@ -228,61 +218,54 @@ struct fs_handle *fs_handle_untracked_create(
        handle->location.directory_handle = directory_handle;
        /* Ownership is transferred. */
        handle->location.path = path_copy;
-       path_copy = NULL;
+       path_copy = nullptr;
 end:
        free(path_copy);
-       return handle ? &handle->parent : NULL;
+       return handle ? &handle->parent : nullptr;
 }
 
-static
-int fs_handle_untracked_get_fd(struct fs_handle *_handle)
+static int fs_handle_untracked_get_fd(struct fs_handle *_handle)
 {
-       struct fs_handle_untracked *handle = lttng::utils::container_of(
-                       _handle, &fs_handle_untracked::parent);
+       struct fs_handle_untracked *handle =
+               lttng::utils::container_of(_handle, &fs_handle_untracked::parent);
 
        return handle->fd;
 }
 
-static
-void fs_handle_untracked_put_fd(struct fs_handle *_handle __attribute__((unused)))
+static void fs_handle_untracked_put_fd(struct fs_handle *_handle __attribute__((unused)))
 {
        /* no-op. */
 }
 
-static
-int fs_handle_untracked_unlink(struct fs_handle *_handle)
+static int fs_handle_untracked_unlink(struct fs_handle *_handle)
 {
-       struct fs_handle_untracked *handle = lttng::utils::container_of(
-                       _handle, &fs_handle_untracked::parent);
+       struct fs_handle_untracked *handle =
+               lttng::utils::container_of(_handle, &fs_handle_untracked::parent);
 
-       return lttng_directory_handle_unlink_file(
-                       handle->location.directory_handle,
-                       handle->location.path);
+       return lttng_directory_handle_unlink_file(handle->location.directory_handle,
+                                                 handle->location.path);
 }
 
-static
-void fs_handle_untracked_destroy(struct fs_handle_untracked *handle)
+static void fs_handle_untracked_destroy(struct fs_handle_untracked *handle)
 {
        lttng_directory_handle_put(handle->location.directory_handle);
        free(handle->location.path);
        free(handle);
 }
 
-static
-int fs_handle_untracked_close(struct fs_handle *_handle)
+static int fs_handle_untracked_close(struct fs_handle *_handle)
 {
-       struct fs_handle_untracked *handle = lttng::utils::container_of(
-                       _handle, &fs_handle_untracked::parent);
+       struct fs_handle_untracked *handle =
+               lttng::utils::container_of(_handle, &fs_handle_untracked::parent);
        int ret = close(handle->fd);
 
        fs_handle_untracked_destroy(handle);
        return ret;
 }
 
-static
-bool lttng_trace_chunk_registry_element_equals(
-               const struct lttng_trace_chunk_registry_element *a,
-               const struct lttng_trace_chunk_registry_element *b)
+static bool
+lttng_trace_chunk_registry_element_equals(const struct lttng_trace_chunk_registry_element *a,
+                                         const struct lttng_trace_chunk_registry_element *b)
 {
        if (a->session_id != b->session_id) {
                goto not_equal;
@@ -298,24 +281,19 @@ not_equal:
        return false;
 }
 
-static
-int lttng_trace_chunk_registry_element_match(struct cds_lfht_node *node,
-               const void *key)
+static int lttng_trace_chunk_registry_element_match(struct cds_lfht_node *node, const void *key)
 {
        const struct lttng_trace_chunk_registry_element *element_a, *element_b;
 
        element_a = (const struct lttng_trace_chunk_registry_element *) key;
-       element_b = caa_container_of(node, typeof(*element_b),
-                       trace_chunk_registry_ht_node);
+       element_b = caa_container_of(node, typeof(*element_b), trace_chunk_registry_ht_node);
        return lttng_trace_chunk_registry_element_equals(element_a, element_b);
 }
 
-static
-unsigned long lttng_trace_chunk_registry_element_hash(
-               const struct lttng_trace_chunk_registry_element *element)
+static unsigned long
+lttng_trace_chunk_registry_element_hash(const struct lttng_trace_chunk_registry_element *element)
 {
-       unsigned long hash = hash_key_u64(&element->session_id,
-                       lttng_ht_seed);
+       unsigned long hash = hash_key_u64(&element->session_id, lttng_ht_seed);
 
        if (element->chunk.id.is_set) {
                hash ^= hash_key_u64(&element->chunk.id.value, lttng_ht_seed);
@@ -324,19 +302,16 @@ unsigned long lttng_trace_chunk_registry_element_hash(
        return hash;
 }
 
-static
-char *generate_chunk_name(uint64_t chunk_id, time_t creation_timestamp,
-               const time_t *close_timestamp)
+static char *
+generate_chunk_name(uint64_t chunk_id, time_t creation_timestamp, const time_t *close_timestamp)
 {
        int ret = 0;
-       char *new_name= NULL;
+       char *new_name = nullptr;
        char start_datetime[ISO8601_STR_LEN] = {};
        /* Add 1 for a '-' prefix. */
        char end_datetime_suffix[ISO8601_STR_LEN + 1] = {};
 
-       ret = time_to_iso8601_str(
-                       creation_timestamp,
-                       start_datetime, sizeof(start_datetime));
+       ret = time_to_iso8601_str(creation_timestamp, start_datetime, sizeof(start_datetime));
        if (ret) {
                ERR("Failed to format trace chunk start date time");
                goto error;
@@ -344,9 +319,7 @@ char *generate_chunk_name(uint64_t chunk_id, time_t creation_timestamp,
        if (close_timestamp) {
                *end_datetime_suffix = '-';
                ret = time_to_iso8601_str(
-                               *close_timestamp,
-                               end_datetime_suffix + 1,
-                               sizeof(end_datetime_suffix) - 1);
+                       *close_timestamp, end_datetime_suffix + 1, sizeof(end_datetime_suffix) - 1);
                if (ret) {
                        ERR("Failed to format trace chunk end date time");
                        goto error;
@@ -357,8 +330,12 @@ char *generate_chunk_name(uint64_t chunk_id, time_t creation_timestamp,
                ERR("Failed to allocate buffer for automatically-generated trace chunk name");
                goto error;
        }
-       ret = snprintf(new_name, GENERATED_CHUNK_NAME_LEN, "%s%s-%" PRIu64,
-                       start_datetime, end_datetime_suffix, chunk_id);
+       ret = snprintf(new_name,
+                      GENERATED_CHUNK_NAME_LEN,
+                      "%s%s-%" PRIu64,
+                      start_datetime,
+                      end_datetime_suffix,
+                      chunk_id);
        if (ret >= GENERATED_CHUNK_NAME_LEN || ret == -1) {
                ERR("Failed to format trace chunk name");
                goto error;
@@ -367,43 +344,39 @@ char *generate_chunk_name(uint64_t chunk_id, time_t creation_timestamp,
        return new_name;
 error:
        free(new_name);
-       return NULL;
+       return nullptr;
 }
 
-static
-void lttng_trace_chunk_init(struct lttng_trace_chunk *chunk)
+static void lttng_trace_chunk_init(struct lttng_trace_chunk *chunk)
 {
        urcu_ref_init(&chunk->ref);
-       pthread_mutex_init(&chunk->lock, NULL);
+       pthread_mutex_init(&chunk->lock, nullptr);
        lttng_dynamic_pointer_array_init(&chunk->top_level_directories, free);
        lttng_dynamic_pointer_array_init(&chunk->files, free);
 }
 
-static
-void lttng_trace_chunk_fini(struct lttng_trace_chunk *chunk)
+static void lttng_trace_chunk_fini(struct lttng_trace_chunk *chunk)
 {
        if (chunk->session_output_directory) {
-               lttng_directory_handle_put(
-                               chunk->session_output_directory);
-               chunk->session_output_directory = NULL;
+               lttng_directory_handle_put(chunk->session_output_directory);
+               chunk->session_output_directory = nullptr;
        }
        if (chunk->chunk_directory) {
                lttng_directory_handle_put(chunk->chunk_directory);
-               chunk->chunk_directory = NULL;
+               chunk->chunk_directory = nullptr;
        }
        free(chunk->name);
-       chunk->name = NULL;
+       chunk->name = nullptr;
        free(chunk->path);
-       chunk->path = NULL;
+       chunk->path = nullptr;
        lttng_dynamic_pointer_array_reset(&chunk->top_level_directories);
        lttng_dynamic_pointer_array_reset(&chunk->files);
        pthread_mutex_destroy(&chunk->lock);
 }
 
-static
-struct lttng_trace_chunk *lttng_trace_chunk_allocate(void)
+static struct lttng_trace_chunk *lttng_trace_chunk_allocate()
 {
-       struct lttng_trace_chunk *chunk = NULL;
+       struct lttng_trace_chunk *chunk = nullptr;
 
        chunk = zmalloc<lttng_trace_chunk>();
        if (!chunk) {
@@ -415,14 +388,14 @@ end:
        return chunk;
 }
 
-struct lttng_trace_chunk *lttng_trace_chunk_create_anonymous(void)
+struct lttng_trace_chunk *lttng_trace_chunk_create_anonymous()
 {
        DBG("Creating anonymous trace chunk");
        return lttng_trace_chunk_allocate();
 }
 
-struct lttng_trace_chunk *lttng_trace_chunk_create(
-               uint64_t chunk_id, time_t chunk_creation_time, const char *path)
+struct lttng_trace_chunk *
+lttng_trace_chunk_create(uint64_t chunk_id, time_t chunk_creation_time, const char *path)
 {
        struct lttng_trace_chunk *chunk;
        char chunk_creation_datetime_buf[16] = {};
@@ -435,16 +408,17 @@ struct lttng_trace_chunk *lttng_trace_chunk_create(
 
                /* Don't fail because of this; it is only used for logging. */
                strftime_ret = strftime(chunk_creation_datetime_buf,
-                               sizeof(chunk_creation_datetime_buf),
-                               "%Y%m%d-%H%M%S", timeinfo);
+                                       sizeof(chunk_creation_datetime_buf),
+                                       "%Y%m%d-%H%M%S",
+                                       timeinfo);
                if (strftime_ret) {
-                       chunk_creation_datetime_str =
-                                       chunk_creation_datetime_buf;
+                       chunk_creation_datetime_str = chunk_creation_datetime_buf;
                }
        }
 
        DBG("Creating trace chunk: chunk_id = %" PRIu64 ", creation time = %s",
-                       chunk_id, chunk_creation_datetime_str);
+           chunk_id,
+           chunk_creation_datetime_str);
        chunk = lttng_trace_chunk_allocate();
        if (!chunk) {
                goto end;
@@ -453,8 +427,7 @@ struct lttng_trace_chunk *lttng_trace_chunk_create(
        LTTNG_OPTIONAL_SET(&chunk->id, chunk_id);
        LTTNG_OPTIONAL_SET(&chunk->timestamp_creation, chunk_creation_time);
        if (chunk_id != 0) {
-               chunk->name = generate_chunk_name(chunk_id,
-                               chunk_creation_time, NULL);
+               chunk->name = generate_chunk_name(chunk_id, chunk_creation_time, nullptr);
                if (!chunk->name) {
                        ERR("Failed to allocate trace chunk name storage");
                        goto error;
@@ -474,16 +447,16 @@ struct lttng_trace_chunk *lttng_trace_chunk_create(
                }
        }
 
-       DBG("Chunk name set to \"%s\"", chunk->name ? : "(none)");
+       DBG("Chunk name set to \"%s\"", chunk->name ?: "(none)");
 end:
        return chunk;
 error:
        lttng_trace_chunk_put(chunk);
-       return NULL;
+       return nullptr;
 }
 
 void lttng_trace_chunk_set_fd_tracker(struct lttng_trace_chunk *chunk,
-               struct fd_tracker *fd_tracker)
+                                     struct fd_tracker *fd_tracker)
 {
        LTTNG_ASSERT(!chunk->session_output_directory);
        LTTNG_ASSERT(!chunk->chunk_directory);
@@ -491,8 +464,7 @@ void lttng_trace_chunk_set_fd_tracker(struct lttng_trace_chunk *chunk,
        chunk->fd_tracker = fd_tracker;
 }
 
-struct lttng_trace_chunk *lttng_trace_chunk_copy(
-               struct lttng_trace_chunk *source_chunk)
+struct lttng_trace_chunk *lttng_trace_chunk_copy(struct lttng_trace_chunk *source_chunk)
 {
        struct lttng_trace_chunk *new_chunk = lttng_trace_chunk_allocate();
 
@@ -505,7 +477,7 @@ struct lttng_trace_chunk *lttng_trace_chunk_copy(
         * A new chunk is always a user; it shall create no new trace
         * subdirectories.
         */
-       new_chunk->mode = (typeof(new_chunk->mode)) {
+       new_chunk->mode = (typeof(new_chunk->mode)){
                .is_set = true,
                .value = TRACE_CHUNK_MODE_USER,
        };
@@ -519,16 +491,14 @@ struct lttng_trace_chunk *lttng_trace_chunk_copy(
        if (source_chunk->name) {
                new_chunk->name = strdup(source_chunk->name);
                if (!new_chunk->name) {
-                       ERR("Failed to copy source trace chunk name in %s()",
-                                       __FUNCTION__);
+                       ERR("Failed to copy source trace chunk name in %s()", __FUNCTION__);
                        goto error_unlock;
                }
        }
        if (source_chunk->path) {
                new_chunk->path = strdup(source_chunk->path);
                if (!new_chunk->path) {
-                       ERR("Failed to copy source trace chunk path in %s()",
-                                       __FUNCTION__);
+                       ERR("Failed to copy source trace chunk path in %s()", __FUNCTION__);
                }
        }
        new_chunk->id = source_chunk->id;
@@ -536,16 +506,15 @@ struct lttng_trace_chunk *lttng_trace_chunk_copy(
        new_chunk->timestamp_close = source_chunk->timestamp_close;
        new_chunk->credentials = source_chunk->credentials;
        if (source_chunk->session_output_directory) {
-               const bool reference_acquired = lttng_directory_handle_get(
-                               source_chunk->session_output_directory);
+               const bool reference_acquired =
+                       lttng_directory_handle_get(source_chunk->session_output_directory);
 
                LTTNG_ASSERT(reference_acquired);
-               new_chunk->session_output_directory =
-                               source_chunk->session_output_directory;
+               new_chunk->session_output_directory = source_chunk->session_output_directory;
        }
        if (source_chunk->chunk_directory) {
-               const bool reference_acquired = lttng_directory_handle_get(
-                               source_chunk->chunk_directory);
+               const bool reference_acquired =
+                       lttng_directory_handle_get(source_chunk->chunk_directory);
 
                LTTNG_ASSERT(reference_acquired);
                new_chunk->chunk_directory = source_chunk->chunk_directory;
@@ -558,11 +527,11 @@ end:
 error_unlock:
        pthread_mutex_unlock(&source_chunk->lock);
        lttng_trace_chunk_put(new_chunk);
-       return NULL;
+       return nullptr;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_id(
-               struct lttng_trace_chunk *chunk, uint64_t *id)
+enum lttng_trace_chunk_status lttng_trace_chunk_get_id(struct lttng_trace_chunk *chunk,
+                                                      uint64_t *id)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -576,8 +545,8 @@ enum lttng_trace_chunk_status lttng_trace_chunk_get_id(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_creation_timestamp(
-               struct lttng_trace_chunk *chunk, time_t *creation_ts)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_creation_timestamp(struct lttng_trace_chunk *chunk, time_t *creation_ts)
 
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -592,8 +561,8 @@ enum lttng_trace_chunk_status lttng_trace_chunk_get_creation_timestamp(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_close_timestamp(
-               struct lttng_trace_chunk *chunk, time_t *close_ts)
+enum lttng_trace_chunk_status lttng_trace_chunk_get_close_timestamp(struct lttng_trace_chunk *chunk,
+                                                                   time_t *close_ts)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -607,8 +576,8 @@ enum lttng_trace_chunk_status lttng_trace_chunk_get_close_timestamp(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_close_timestamp(
-               struct lttng_trace_chunk *chunk, time_t close_ts)
+enum lttng_trace_chunk_status lttng_trace_chunk_set_close_timestamp(struct lttng_trace_chunk *chunk,
+                                                                   time_t close_ts)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -629,15 +598,16 @@ enum lttng_trace_chunk_status lttng_trace_chunk_set_close_timestamp(
         */
        if (chunk->timestamp_creation.value > close_ts) {
                WARN("Set trace chunk close timestamp: close timestamp is before creation timestamp, begin : %ld, close : %ld",
-                               chunk->timestamp_creation.value, close_ts);
+                    chunk->timestamp_creation.value,
+                    close_ts);
        }
 
        LTTNG_OPTIONAL_SET(&chunk->timestamp_close, close_ts);
        if (!chunk->name_overridden) {
                free(chunk->name);
                chunk->name = generate_chunk_name(LTTNG_OPTIONAL_GET(chunk->id),
-                               LTTNG_OPTIONAL_GET(chunk->timestamp_creation),
-                               &close_ts);
+                                                 LTTNG_OPTIONAL_GET(chunk->timestamp_creation),
+                                                 &close_ts);
                if (!chunk->name) {
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                }
@@ -647,9 +617,9 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_name(
-               struct lttng_trace_chunk *chunk, const char **name,
-               bool *name_overridden)
+enum lttng_trace_chunk_status lttng_trace_chunk_get_name(struct lttng_trace_chunk *chunk,
+                                                        const char **name,
+                                                        bool *name_overridden)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -677,8 +647,7 @@ bool lttng_trace_chunk_get_name_overridden(struct lttng_trace_chunk *chunk)
        return name_overridden;
 }
 
-static
-bool is_valid_chunk_name(const char *name)
+static bool is_valid_chunk_name(const char *name)
 {
        size_t len;
 
@@ -698,8 +667,8 @@ bool is_valid_chunk_name(const char *name)
        return true;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_override_name(
-               struct lttng_trace_chunk *chunk, const char *name)
+enum lttng_trace_chunk_status lttng_trace_chunk_override_name(struct lttng_trace_chunk *chunk,
+                                                             const char *name)
 
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -707,8 +676,7 @@ enum lttng_trace_chunk_status lttng_trace_chunk_override_name(
 
        DBG("Override trace chunk name from %s to %s", chunk->name, name);
        if (!is_valid_chunk_name(name)) {
-               ERR("Attempted to set an invalid name on a trace chunk: name = %s",
-                               name ? : "NULL");
+               ERR("Attempted to set an invalid name on a trace chunk: name = %s", name ?: "NULL");
                status = LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT;
                goto end;
        }
@@ -716,7 +684,7 @@ enum lttng_trace_chunk_status lttng_trace_chunk_override_name(
        pthread_mutex_lock(&chunk->lock);
        if (!chunk->id.is_set) {
                ERR("Attempted to set an override name on an anonymous trace chunk: name = %s",
-                               name);
+                   name);
                status = LTTNG_TRACE_CHUNK_STATUS_INVALID_OPERATION;
                goto end_unlock;
        }
@@ -746,13 +714,12 @@ end:
        return status;
 }
 
-static
-enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
-               struct lttng_trace_chunk *chunk, const char *path)
+static enum lttng_trace_chunk_status
+lttng_trace_chunk_rename_path_no_lock(struct lttng_trace_chunk *chunk, const char *path)
 
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
-       struct lttng_directory_handle *rename_directory = NULL;
+       struct lttng_directory_handle *rename_directory = nullptr;
        char *new_path, *old_path;
        int ret;
 
@@ -764,8 +731,7 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
        old_path = chunk->path;
        DBG("lttng_trace_chunk_rename_path from %s to %s", old_path, path);
 
-       if ((!old_path && !path) ||
-                       (old_path && path && !strcmp(old_path, path)))  {
+       if ((!old_path && !path) || (old_path && path && !strcmp(old_path, path))) {
                goto end;
        }
        /*
@@ -786,8 +752,7 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
         * is not set (yet), or the session_output_directory is not set
         * (interacting with a relay daemon), there is no rename to perform.
         */
-       if (!chunk->chunk_directory ||
-                       !chunk->session_output_directory) {
+       if (!chunk->chunk_directory || !chunk->session_output_directory) {
                goto skip_move;
        }
 
@@ -799,22 +764,20 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                        chunk->session_output_directory,
                        path,
                        LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
-                               NULL :
+                               nullptr :
                                &chunk->credentials.value.user);
                if (ret) {
                        PERROR("Failed to move trace chunk directory \"%s\" to \"%s\"",
-                                       old_path, path);
+                              old_path,
+                              path);
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                        goto end;
                }
                rename_directory = chunk->fd_tracker ?
-                               fd_tracker_create_directory_handle_from_handle(
-                                               chunk->fd_tracker,
-                                               chunk->session_output_directory,
-                                               path) :
-                               lttng_directory_handle_create_from_handle(
-                                               path,
-                                               chunk->session_output_directory);
+                       fd_tracker_create_directory_handle_from_handle(
+                               chunk->fd_tracker, chunk->session_output_directory, path) :
+                       lttng_directory_handle_create_from_handle(path,
+                                                                 chunk->session_output_directory);
                if (!rename_directory) {
                        ERR("Failed to get handle to trace chunk rename directory");
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
@@ -828,27 +791,27 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                 * handle.
                 */
                chunk->chunk_directory = rename_directory;
-               rename_directory = NULL;
+               rename_directory = nullptr;
        } else if (old_path && old_path[0] == '\0') {
-               size_t i, count = lttng_dynamic_pointer_array_get_count(
+               size_t i,
+                       count = lttng_dynamic_pointer_array_get_count(
                                &chunk->top_level_directories);
 
                ret = lttng_directory_handle_create_subdirectory_as_user(
-                               chunk->session_output_directory,
-                               path,
-                               DIR_CREATION_MODE,
-                               LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
-                                       NULL :
-                                       &chunk->credentials.value.user);
+                       chunk->session_output_directory,
+                       path,
+                       DIR_CREATION_MODE,
+                       LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
+                               nullptr :
+                               &chunk->credentials.value.user);
                if (ret) {
-                       PERROR("Failed to create trace chunk rename directory \"%s\"",
-                                       path);
+                       PERROR("Failed to create trace chunk rename directory \"%s\"", path);
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                        goto end;
                }
 
                rename_directory = lttng_directory_handle_create_from_handle(
-                               path, chunk->session_output_directory);
+                       path, chunk->session_output_directory);
                if (!rename_directory) {
                        ERR("Failed to get handle to trace chunk rename directory");
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
@@ -862,16 +825,16 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                                        &chunk->top_level_directories, i);
 
                        ret = lttng_directory_handle_rename_as_user(
-                                       chunk->chunk_directory,
-                                       top_level_name,
-                                       rename_directory,
-                                       top_level_name,
-                                       LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
-                                               NULL :
-                                               &chunk->credentials.value.user);
+                               chunk->chunk_directory,
+                               top_level_name,
+                               rename_directory,
+                               top_level_name,
+                               LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
+                                       nullptr :
+                                       &chunk->credentials.value.user);
                        if (ret) {
                                PERROR("Failed to move \"%s\" to trace chunk rename directory",
-                                               top_level_name);
+                                      top_level_name);
                                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                                goto end;
                        }
@@ -883,12 +846,13 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                 * handle.
                 */
                chunk->chunk_directory = rename_directory;
-               rename_directory = NULL;
+               rename_directory = nullptr;
        } else if (old_path) {
-               size_t i, count = lttng_dynamic_pointer_array_get_count(
+               size_t i,
+                       count = lttng_dynamic_pointer_array_get_count(
                                &chunk->top_level_directories);
-               const bool reference_acquired = lttng_directory_handle_get(
-                               chunk->session_output_directory);
+               const bool reference_acquired =
+                       lttng_directory_handle_get(chunk->session_output_directory);
 
                LTTNG_ASSERT(reference_acquired);
                rename_directory = chunk->session_output_directory;
@@ -900,16 +864,16 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                                        &chunk->top_level_directories, i);
 
                        ret = lttng_directory_handle_rename_as_user(
-                                       chunk->chunk_directory,
-                                       top_level_name,
-                                       rename_directory,
-                                       top_level_name,
-                                       LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
-                                               NULL :
-                                               &chunk->credentials.value.user);
+                               chunk->chunk_directory,
+                               top_level_name,
+                               rename_directory,
+                               top_level_name,
+                               LTTNG_OPTIONAL_GET(chunk->credentials).use_current_user ?
+                                       nullptr :
+                                       &chunk->credentials.value.user);
                        if (ret) {
                                PERROR("Failed to move \"%s\" to trace chunk rename directory",
-                                               top_level_name);
+                                      top_level_name);
                                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                                goto end;
                        }
@@ -921,15 +885,13 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path_no_lock(
                 * handle.
                 */
                chunk->chunk_directory = rename_directory;
-               rename_directory = NULL;
+               rename_directory = nullptr;
 
                /* Remove old directory. */
                status = (lttng_trace_chunk_status) lttng_directory_handle_remove_subdirectory(
-                               chunk->session_output_directory,
-                               old_path);
+                       chunk->session_output_directory, old_path);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
-                       ERR("Error removing subdirectory '%s' file when deleting chunk",
-                               old_path);
+                       ERR("Error removing subdirectory '%s' file when deleting chunk", old_path);
                        goto end;
                }
        } else {
@@ -952,8 +914,8 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_rename_path(
-               struct lttng_trace_chunk *chunk, const char *path)
+enum lttng_trace_chunk_status lttng_trace_chunk_rename_path(struct lttng_trace_chunk *chunk,
+                                                           const char *path)
 
 {
        enum lttng_trace_chunk_status status;
@@ -965,9 +927,9 @@ enum lttng_trace_chunk_status lttng_trace_chunk_rename_path(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_credentials(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_credentials *credentials)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_credentials(struct lttng_trace_chunk *chunk,
+                                 struct lttng_credentials *credentials)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -986,9 +948,9 @@ enum lttng_trace_chunk_status lttng_trace_chunk_get_credentials(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_credentials(
-               struct lttng_trace_chunk *chunk,
-               const struct lttng_credentials *user_credentials)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_credentials(struct lttng_trace_chunk *chunk,
+                                 const struct lttng_credentials *user_credentials)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
        const struct chunk_credentials credentials = {
@@ -1007,8 +969,8 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_credentials_current_user(
-               struct lttng_trace_chunk *chunk)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_credentials_current_user(struct lttng_trace_chunk *chunk)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
        const struct chunk_credentials credentials = {
@@ -1027,14 +989,13 @@ end:
        return status;
 }
 
-
-enum lttng_trace_chunk_status lttng_trace_chunk_set_as_owner(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle *session_output_directory)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_as_owner(struct lttng_trace_chunk *chunk,
+                              struct lttng_directory_handle *session_output_directory)
 {
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
-       struct lttng_directory_handle *chunk_directory_handle = NULL;
+       struct lttng_directory_handle *chunk_directory_handle = nullptr;
        bool reference_acquired;
 
        pthread_mutex_lock(&chunk->lock);
@@ -1053,26 +1014,22 @@ enum lttng_trace_chunk_status lttng_trace_chunk_set_as_owner(
        }
        if (chunk->path && chunk->path[0] != '\0') {
                ret = lttng_directory_handle_create_subdirectory_as_user(
-                               session_output_directory,
-                               chunk->path,
-                               DIR_CREATION_MODE,
-                               !chunk->credentials.value.use_current_user ?
-                                       &chunk->credentials.value.user : NULL);
+                       session_output_directory,
+                       chunk->path,
+                       DIR_CREATION_MODE,
+                       !chunk->credentials.value.use_current_user ?
+                               &chunk->credentials.value.user :
+                               nullptr);
                if (ret) {
-                       PERROR("Failed to create chunk output directory \"%s\"",
-                               chunk->path);
+                       PERROR("Failed to create chunk output directory \"%s\"", chunk->path);
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                        goto end;
                }
-               chunk_directory_handle =
-                               chunk->fd_tracker ?
-                                       fd_tracker_create_directory_handle_from_handle(
-                                                       chunk->fd_tracker,
-                                                       session_output_directory,
-                                                       chunk->path) :
-                                       lttng_directory_handle_create_from_handle(
-                                                       chunk->path,
-                                                       session_output_directory);
+               chunk_directory_handle = chunk->fd_tracker ?
+                       fd_tracker_create_directory_handle_from_handle(
+                               chunk->fd_tracker, session_output_directory, chunk->path) :
+                       lttng_directory_handle_create_from_handle(chunk->path,
+                                                                 session_output_directory);
                if (!chunk_directory_handle) {
                        /* The function already logs on all error paths. */
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
@@ -1083,16 +1040,14 @@ enum lttng_trace_chunk_status lttng_trace_chunk_set_as_owner(
                 * A nameless chunk does not need its own output directory.
                 * The session's output directory will be used.
                 */
-               reference_acquired = lttng_directory_handle_get(
-                               session_output_directory);
+               reference_acquired = lttng_directory_handle_get(session_output_directory);
 
                LTTNG_ASSERT(reference_acquired);
                chunk_directory_handle = session_output_directory;
        }
        chunk->chunk_directory = chunk_directory_handle;
-       chunk_directory_handle = NULL;
-       reference_acquired = lttng_directory_handle_get(
-                       session_output_directory);
+       chunk_directory_handle = nullptr;
+       reference_acquired = lttng_directory_handle_get(session_output_directory);
        LTTNG_ASSERT(reference_acquired);
        chunk->session_output_directory = session_output_directory;
        LTTNG_OPTIONAL_SET(&chunk->mode, TRACE_CHUNK_MODE_OWNER);
@@ -1101,9 +1056,9 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_as_user(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle *chunk_directory)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_as_user(struct lttng_trace_chunk *chunk,
+                             struct lttng_directory_handle *chunk_directory)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
        bool reference_acquired;
@@ -1128,20 +1083,19 @@ end:
 }
 
 enum lttng_trace_chunk_status
-lttng_trace_chunk_get_session_output_directory_handle(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle **handle)
+lttng_trace_chunk_get_session_output_directory_handle(struct lttng_trace_chunk *chunk,
+                                                     struct lttng_directory_handle **handle)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
        pthread_mutex_lock(&chunk->lock);
        if (!chunk->session_output_directory) {
                status = LTTNG_TRACE_CHUNK_STATUS_NONE;
-               *handle = NULL;
+               *handle = nullptr;
                goto end;
        } else {
-               const bool reference_acquired = lttng_directory_handle_get(
-                               chunk->session_output_directory);
+               const bool reference_acquired =
+                       lttng_directory_handle_get(chunk->session_output_directory);
 
                LTTNG_ASSERT(reference_acquired);
                *handle = chunk->session_output_directory;
@@ -1151,9 +1105,9 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_borrow_chunk_directory_handle(
-               struct lttng_trace_chunk *chunk,
-               const struct lttng_directory_handle **handle)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_borrow_chunk_directory_handle(struct lttng_trace_chunk *chunk,
+                                               const struct lttng_directory_handle **handle)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -1170,21 +1124,18 @@ end:
 }
 
 /* Add a top-level directory to the trace chunk if it was previously unknown. */
-static
-int add_top_level_directory_unique(struct lttng_trace_chunk *chunk,
-               const char *new_path)
+static int add_top_level_directory_unique(struct lttng_trace_chunk *chunk, const char *new_path)
 {
        int ret = 0;
        bool found = false;
-       size_t i, count = lttng_dynamic_pointer_array_get_count(
-                       &chunk->top_level_directories);
+       size_t i, count = lttng_dynamic_pointer_array_get_count(&chunk->top_level_directories);
        const char *new_path_separator_pos = strchr(new_path, '/');
-       const ptrdiff_t new_path_top_level_len = new_path_separator_pos ?
-                       new_path_separator_pos - new_path : strlen(new_path);
+       const ptrdiff_t new_path_top_level_len =
+               new_path_separator_pos ? new_path_separator_pos - new_path : strlen(new_path);
 
        for (i = 0; i < count; i++) {
                const char *path = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               &chunk->top_level_directories, i);
+                       &chunk->top_level_directories, i);
                const ptrdiff_t path_top_level_len = strlen(path);
 
                if (path_top_level_len != new_path_top_level_len) {
@@ -1200,14 +1151,14 @@ int add_top_level_directory_unique(struct lttng_trace_chunk *chunk,
                char *copy = lttng_strndup(new_path, new_path_top_level_len);
 
                DBG("Adding new top-level directory \"%s\" to trace chunk \"%s\"",
-                               new_path, chunk->name ? : "(unnamed)");
+                   new_path,
+                   chunk->name ?: "(unnamed)");
                if (!copy) {
                        PERROR("Failed to copy path");
                        ret = -1;
                        goto end;
                }
-               ret = lttng_dynamic_pointer_array_add_pointer(
-                               &chunk->top_level_directories, copy);
+               ret = lttng_dynamic_pointer_array_add_pointer(&chunk->top_level_directories, copy);
                if (ret) {
                        ERR("Allocation failure while adding top-level directory entry to a trace chunk");
                        free(copy);
@@ -1218,9 +1169,8 @@ end:
        return ret;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_create_subdirectory(
-               struct lttng_trace_chunk *chunk,
-               const char *path)
+enum lttng_trace_chunk_status lttng_trace_chunk_create_subdirectory(struct lttng_trace_chunk *chunk,
+                                                                   const char *path)
 {
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -1233,37 +1183,35 @@ enum lttng_trace_chunk_status lttng_trace_chunk_create_subdirectory(
                 * directory is created.
                 */
                ERR("Credentials of trace chunk are unset: refusing to create subdirectory \"%s\"",
-                               path);
+                   path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
-       if (!chunk->mode.is_set ||
-                       chunk->mode.value != TRACE_CHUNK_MODE_OWNER) {
+       if (!chunk->mode.is_set || chunk->mode.value != TRACE_CHUNK_MODE_OWNER) {
                ERR("Attempted to create trace chunk subdirectory \"%s\" through a non-owner chunk",
-                               path);
+                   path);
                status = LTTNG_TRACE_CHUNK_STATUS_INVALID_OPERATION;
                goto end;
        }
        if (!chunk->chunk_directory) {
                ERR("Attempted to create trace chunk subdirectory \"%s\" before setting the chunk output directory",
-                               path);
+                   path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
        if (*path == '/') {
-               ERR("Refusing to create absolute trace chunk directory \"%s\"",
-                               path);
+               ERR("Refusing to create absolute trace chunk directory \"%s\"", path);
                status = LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT;
                goto end;
        }
        ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
-                       chunk->chunk_directory, path,
-                       DIR_CREATION_MODE,
-                       chunk->credentials.value.use_current_user ?
-                                       NULL : &chunk->credentials.value.user);
+               chunk->chunk_directory,
+               path,
+               DIR_CREATION_MODE,
+               chunk->credentials.value.use_current_user ? nullptr :
+                                                           &chunk->credentials.value.user);
        if (ret) {
-               PERROR("Failed to create trace chunk subdirectory \"%s\"",
-                               path);
+               PERROR("Failed to create trace chunk subdirectory \"%s\"", path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
@@ -1280,17 +1228,15 @@ end:
 /*
  * TODO: Implement O(1) lookup.
  */
-static
-bool lttng_trace_chunk_find_file(struct lttng_trace_chunk *chunk,
-               const char *path, size_t *index)
+static bool
+lttng_trace_chunk_find_file(struct lttng_trace_chunk *chunk, const char *path, size_t *index)
 {
        size_t i, count;
 
        count = lttng_dynamic_pointer_array_get_count(&chunk->files);
        for (i = 0; i < count; i++) {
                const char *iter_path =
-                       (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               &chunk->files, i);
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(&chunk->files, i);
                if (!strcmp(iter_path, path)) {
                        if (index) {
                                *index = i;
@@ -1301,28 +1247,24 @@ bool lttng_trace_chunk_find_file(struct lttng_trace_chunk *chunk,
        return false;
 }
 
-static
-enum lttng_trace_chunk_status lttng_trace_chunk_add_file(
-               struct lttng_trace_chunk *chunk,
-               const char *path)
+static enum lttng_trace_chunk_status lttng_trace_chunk_add_file(struct lttng_trace_chunk *chunk,
+                                                               const char *path)
 {
        char *copy;
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
-       if (lttng_trace_chunk_find_file(chunk, path, NULL)) {
+       if (lttng_trace_chunk_find_file(chunk, path, nullptr)) {
                return LTTNG_TRACE_CHUNK_STATUS_OK;
        }
-       DBG("Adding new file \"%s\" to trace chunk \"%s\"",
-                       path, chunk->name ? : "(unnamed)");
+       DBG("Adding new file \"%s\" to trace chunk \"%s\"", path, chunk->name ?: "(unnamed)");
        copy = strdup(path);
        if (!copy) {
                PERROR("Failed to copy path");
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
-       ret = lttng_dynamic_pointer_array_add_pointer(
-                       &chunk->files, copy);
+       ret = lttng_dynamic_pointer_array_add_pointer(&chunk->files, copy);
        if (ret) {
                ERR("Allocation failure while adding file to a trace chunk");
                free(copy);
@@ -1333,10 +1275,7 @@ end:
        return status;
 }
 
-static
-void lttng_trace_chunk_remove_file(
-               struct lttng_trace_chunk *chunk,
-               const char *path)
+static void lttng_trace_chunk_remove_file(struct lttng_trace_chunk *chunk, const char *path)
 {
        size_t index;
        bool found;
@@ -1346,19 +1285,17 @@ void lttng_trace_chunk_remove_file(
        if (!found) {
                return;
        }
-       ret = lttng_dynamic_pointer_array_remove_pointer(
-                       &chunk->files, index);
+       ret = lttng_dynamic_pointer_array_remove_pointer(&chunk->files, index);
        LTTNG_ASSERT(!ret);
 }
 
-static
-enum lttng_trace_chunk_status _lttng_trace_chunk_open_fs_handle_locked(
-               struct lttng_trace_chunk *chunk,
-               const char *file_path,
-               int flags,
-               mode_t mode,
-               struct fs_handle **out_handle,
-               bool expect_no_file)
+static enum lttng_trace_chunk_status
+_lttng_trace_chunk_open_fs_handle_locked(struct lttng_trace_chunk *chunk,
+                                        const char *file_path,
+                                        int flags,
+                                        mode_t mode,
+                                        struct fs_handle **out_handle,
+                                        bool expect_no_file)
 {
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -1370,13 +1307,13 @@ enum lttng_trace_chunk_status _lttng_trace_chunk_open_fs_handle_locked(
                 * file is created.
                 */
                ERR("Credentials of trace chunk are unset: refusing to open file \"%s\"",
-                               file_path);
+                   file_path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
        if (!chunk->chunk_directory) {
                ERR("Attempted to open trace chunk file \"%s\" before setting the chunk output directory",
-                               file_path);
+                   file_path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
@@ -1386,18 +1323,20 @@ enum lttng_trace_chunk_status _lttng_trace_chunk_open_fs_handle_locked(
        }
        if (chunk->fd_tracker) {
                LTTNG_ASSERT(chunk->credentials.value.use_current_user);
-               *out_handle = fd_tracker_open_fs_handle(chunk->fd_tracker,
-                               chunk->chunk_directory, file_path, flags, &mode);
+               *out_handle = fd_tracker_open_fs_handle(
+                       chunk->fd_tracker, chunk->chunk_directory, file_path, flags, &mode);
                ret = *out_handle ? 0 : -1;
        } else {
                ret = lttng_directory_handle_open_file_as_user(
-                               chunk->chunk_directory, file_path, flags, mode,
-                               chunk->credentials.value.use_current_user ?
-                                               NULL :
-                                               &chunk->credentials.value.user);
+                       chunk->chunk_directory,
+                       file_path,
+                       flags,
+                       mode,
+                       chunk->credentials.value.use_current_user ? nullptr :
+                                                                   &chunk->credentials.value.user);
                if (ret >= 0) {
-                       *out_handle = fs_handle_untracked_create(
-                                       chunk->chunk_directory, file_path, ret);
+                       *out_handle =
+                               fs_handle_untracked_create(chunk->chunk_directory, file_path, ret);
                        if (!*out_handle) {
                                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                                goto end;
@@ -1409,7 +1348,9 @@ enum lttng_trace_chunk_status _lttng_trace_chunk_open_fs_handle_locked(
                        status = LTTNG_TRACE_CHUNK_STATUS_NO_FILE;
                } else {
                        PERROR("Failed to open file relative to trace chunk file_path = \"%s\", flags = %d, mode = %d",
-                               file_path, flags, (int) mode);
+                              file_path,
+                              flags,
+                              (int) mode);
                        status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                }
                lttng_trace_chunk_remove_file(chunk, file_path);
@@ -1419,30 +1360,28 @@ end:
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_open_fs_handle(
-               struct lttng_trace_chunk *chunk,
-               const char *file_path,
-               int flags,
-               mode_t mode,
-               struct fs_handle **out_handle,
-               bool expect_no_file)
+enum lttng_trace_chunk_status lttng_trace_chunk_open_fs_handle(struct lttng_trace_chunk *chunk,
+                                                              const char *file_path,
+                                                              int flags,
+                                                              mode_t mode,
+                                                              struct fs_handle **out_handle,
+                                                              bool expect_no_file)
 {
        enum lttng_trace_chunk_status status;
 
        pthread_mutex_lock(&chunk->lock);
-       status = _lttng_trace_chunk_open_fs_handle_locked(chunk, file_path,
-                       flags, mode, out_handle, expect_no_file);
+       status = _lttng_trace_chunk_open_fs_handle_locked(
+               chunk, file_path, flags, mode, out_handle, expect_no_file);
        pthread_mutex_unlock(&chunk->lock);
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_open_file(
-               struct lttng_trace_chunk *chunk,
-               const char *file_path,
-               int flags,
-               mode_t mode,
-               int *out_fd,
-               bool expect_no_file)
+enum lttng_trace_chunk_status lttng_trace_chunk_open_file(struct lttng_trace_chunk *chunk,
+                                                         const char *file_path,
+                                                         int flags,
+                                                         mode_t mode,
+                                                         int *out_fd,
+                                                         bool expect_no_file)
 {
        enum lttng_trace_chunk_status status;
        struct fs_handle *fs_handle;
@@ -1453,8 +1392,8 @@ enum lttng_trace_chunk_status lttng_trace_chunk_open_file(
         * used since the resulting file descriptor would not be tracked.
         */
        LTTNG_ASSERT(!chunk->fd_tracker);
-       status = _lttng_trace_chunk_open_fs_handle_locked(chunk, file_path,
-                       flags, mode, &fs_handle, expect_no_file);
+       status = _lttng_trace_chunk_open_fs_handle_locked(
+               chunk, file_path, flags, mode, &fs_handle, expect_no_file);
        pthread_mutex_unlock(&chunk->lock);
 
        if (status == LTTNG_TRACE_CHUNK_STATUS_OK) {
@@ -1462,15 +1401,14 @@ enum lttng_trace_chunk_status lttng_trace_chunk_open_file(
                /*
                 * Does not close the fd; we just "unbox" it from the fs_handle.
                 */
-               fs_handle_untracked_destroy(lttng::utils::container_of(
-                               fs_handle, &fs_handle_untracked::parent));
+               fs_handle_untracked_destroy(
+                       lttng::utils::container_of(fs_handle, &fs_handle_untracked::parent));
        }
 
        return status;
 }
 
-int lttng_trace_chunk_unlink_file(struct lttng_trace_chunk *chunk,
-               const char *file_path)
+int lttng_trace_chunk_unlink_file(struct lttng_trace_chunk *chunk, const char *file_path)
 {
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -1483,20 +1421,21 @@ int lttng_trace_chunk_unlink_file(struct lttng_trace_chunk *chunk,
                 * file is unlinked.
                 */
                ERR("Credentials of trace chunk are unset: refusing to unlink file \"%s\"",
-                               file_path);
+                   file_path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
        if (!chunk->chunk_directory) {
                ERR("Attempted to unlink trace chunk file \"%s\" before setting the chunk output directory",
-                               file_path);
+                   file_path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
-       ret = lttng_directory_handle_unlink_file_as_user(
-                       chunk->chunk_directory, file_path,
-                       chunk->credentials.value.use_current_user ?
-                                       NULL : &chunk->credentials.value.user);
+       ret = lttng_directory_handle_unlink_file_as_user(chunk->chunk_directory,
+                                                        file_path,
+                                                        chunk->credentials.value.use_current_user ?
+                                                                nullptr :
+                                                                &chunk->credentials.value.user);
        if (ret < 0) {
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
@@ -1507,9 +1446,8 @@ end:
        return status;
 }
 
-static
-int lttng_trace_chunk_remove_subdirectory_recursive(struct lttng_trace_chunk *chunk,
-               const char *path)
+static int lttng_trace_chunk_remove_subdirectory_recursive(struct lttng_trace_chunk *chunk,
+                                                          const char *path)
 {
        int ret;
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
@@ -1522,21 +1460,22 @@ int lttng_trace_chunk_remove_subdirectory_recursive(struct lttng_trace_chunk *ch
                 * directory is removed.
                 */
                ERR("Credentials of trace chunk are unset: refusing to recursively remove directory \"%s\"",
-                               path);
+                   path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
        if (!chunk->chunk_directory) {
                ERR("Attempted to recursively remove trace chunk directory \"%s\" before setting the chunk output directory",
-                               path);
+                   path);
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
        }
        ret = lttng_directory_handle_remove_subdirectory_recursive_as_user(
-                       chunk->chunk_directory, path,
-                       chunk->credentials.value.use_current_user ?
-                                       NULL : &chunk->credentials.value.user,
-                       LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+               chunk->chunk_directory,
+               path,
+               chunk->credentials.value.use_current_user ? nullptr :
+                                                           &chunk->credentials.value.user,
+               LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
        if (ret < 0) {
                status = LTTNG_TRACE_CHUNK_STATUS_ERROR;
                goto end;
@@ -1546,23 +1485,18 @@ end:
        return status;
 }
 
-static
-int lttng_trace_chunk_move_to_completed_post_release(
-               struct lttng_trace_chunk *trace_chunk)
+static int lttng_trace_chunk_move_to_completed_post_release(struct lttng_trace_chunk *trace_chunk)
 {
        int ret = 0;
-       char *archived_chunk_name = NULL;
+       char *archived_chunk_name = nullptr;
        const uint64_t chunk_id = LTTNG_OPTIONAL_GET(trace_chunk->id);
-       const time_t creation_timestamp =
-                       LTTNG_OPTIONAL_GET(trace_chunk->timestamp_creation);
-       const time_t close_timestamp =
-                       LTTNG_OPTIONAL_GET(trace_chunk->timestamp_close);
-       struct lttng_directory_handle *archived_chunks_directory = NULL;
+       const time_t creation_timestamp = LTTNG_OPTIONAL_GET(trace_chunk->timestamp_creation);
+       const time_t close_timestamp = LTTNG_OPTIONAL_GET(trace_chunk->timestamp_close);
+       struct lttng_directory_handle *archived_chunks_directory = nullptr;
        enum lttng_trace_chunk_status status;
 
-       if (!trace_chunk->mode.is_set ||
-                       trace_chunk->mode.value != TRACE_CHUNK_MODE_OWNER ||
-                       !trace_chunk->session_output_directory) {
+       if (!trace_chunk->mode.is_set || trace_chunk->mode.value != TRACE_CHUNK_MODE_OWNER ||
+           !trace_chunk->session_output_directory) {
                /*
                 * This command doesn't need to run if the output is remote
                 * or if the trace chunk is not owned by this process.
@@ -1574,8 +1508,7 @@ int lttng_trace_chunk_move_to_completed_post_release(
        LTTNG_ASSERT(!trace_chunk->name_overridden);
        LTTNG_ASSERT(trace_chunk->path);
 
-       archived_chunk_name = generate_chunk_name(chunk_id, creation_timestamp,
-                       &close_timestamp);
+       archived_chunk_name = generate_chunk_name(chunk_id, creation_timestamp, &close_timestamp);
        if (!archived_chunk_name) {
                ERR("Failed to generate archived trace chunk name while renaming trace chunk");
                ret = -1;
@@ -1583,26 +1516,25 @@ int lttng_trace_chunk_move_to_completed_post_release(
        }
 
        ret = lttng_directory_handle_create_subdirectory_as_user(
-                       trace_chunk->session_output_directory,
-                       DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY,
-                       DIR_CREATION_MODE,
-                       !trace_chunk->credentials.value.use_current_user ?
-                                       &trace_chunk->credentials.value.user :
-                                       NULL);
+               trace_chunk->session_output_directory,
+               DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY,
+               DIR_CREATION_MODE,
+               !trace_chunk->credentials.value.use_current_user ?
+                       &trace_chunk->credentials.value.user :
+                       nullptr);
        if (ret) {
                PERROR("Failed to create \"" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
-                               "\" directory for archived trace chunks");
+                      "\" directory for archived trace chunks");
                goto end;
        }
 
        archived_chunks_directory = trace_chunk->fd_tracker ?
-                       fd_tracker_create_directory_handle_from_handle(
-                                       trace_chunk->fd_tracker,
-                                       trace_chunk->session_output_directory,
-                                       DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY) :
-                       lttng_directory_handle_create_from_handle(
-                                       DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY,
-                                       trace_chunk->session_output_directory);
+               fd_tracker_create_directory_handle_from_handle(
+                       trace_chunk->fd_tracker,
+                       trace_chunk->session_output_directory,
+                       DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY) :
+               lttng_directory_handle_create_from_handle(DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY,
+                                                         trace_chunk->session_output_directory);
        if (!archived_chunks_directory) {
                PERROR("Failed to get handle to archived trace chunks directory");
                ret = -1;
@@ -1614,10 +1546,9 @@ int lttng_trace_chunk_move_to_completed_post_release(
         * the creation of the next chunk. This happens if a rotation is
         * performed while tracing is stopped.
         */
-       if (!trace_chunk->path || strcmp(trace_chunk->path,
-                       DEFAULT_CHUNK_TMP_OLD_DIRECTORY)) {
+       if (!trace_chunk->path || strcmp(trace_chunk->path, DEFAULT_CHUNK_TMP_OLD_DIRECTORY) != 0) {
                status = lttng_trace_chunk_rename_path_no_lock(trace_chunk,
-                               DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
+                                                              DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Failed to rename chunk to %s", DEFAULT_CHUNK_TMP_OLD_DIRECTORY);
                        ret = -1;
@@ -1626,17 +1557,17 @@ int lttng_trace_chunk_move_to_completed_post_release(
        }
 
        ret = lttng_directory_handle_rename_as_user(
-                       trace_chunk->session_output_directory,
-                       trace_chunk->path,
-                       archived_chunks_directory,
-                       archived_chunk_name,
-                       LTTNG_OPTIONAL_GET(trace_chunk->credentials).use_current_user ?
-                               NULL :
-                               &trace_chunk->credentials.value.user);
+               trace_chunk->session_output_directory,
+               trace_chunk->path,
+               archived_chunks_directory,
+               archived_chunk_name,
+               LTTNG_OPTIONAL_GET(trace_chunk->credentials).use_current_user ?
+                       nullptr :
+                       &trace_chunk->credentials.value.user);
        if (ret) {
                PERROR("Failed to rename folder \"%s\" to \"%s\"",
-                               trace_chunk->path,
-                               archived_chunk_name);
+                      trace_chunk->path,
+                      archived_chunk_name);
        }
 
 end:
@@ -1645,15 +1576,13 @@ end:
        return ret;
 }
 
-static
-int lttng_trace_chunk_no_operation(struct lttng_trace_chunk *trace_chunk __attribute__((unused)))
+static int lttng_trace_chunk_no_operation(struct lttng_trace_chunk *trace_chunk
+                                         __attribute__((unused)))
 {
        return 0;
 }
 
-static
-int lttng_trace_chunk_delete_post_release_user(
-               struct lttng_trace_chunk *trace_chunk)
+static int lttng_trace_chunk_delete_post_release_user(struct lttng_trace_chunk *trace_chunk)
 {
        int ret = 0;
 
@@ -1665,10 +1594,11 @@ int lttng_trace_chunk_delete_post_release_user(
                const char *path;
 
                /* Remove first. */
-               path = (const char *) lttng_dynamic_pointer_array_get_pointer(
-                       &trace_chunk->files, 0);
+               path = (const char *) lttng_dynamic_pointer_array_get_pointer(&trace_chunk->files,
+                                                                             0);
                DBG("Unlink file: %s", path);
-               status = (lttng_trace_chunk_status) lttng_trace_chunk_unlink_file(trace_chunk, path);
+               status =
+                       (lttng_trace_chunk_status) lttng_trace_chunk_unlink_file(trace_chunk, path);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Error unlinking file '%s' when deleting chunk", path);
                        ret = -1;
@@ -1679,9 +1609,7 @@ end:
        return ret;
 }
 
-static
-int lttng_trace_chunk_delete_post_release_owner(
-               struct lttng_trace_chunk *trace_chunk)
+static int lttng_trace_chunk_delete_post_release_owner(struct lttng_trace_chunk *trace_chunk)
 {
        enum lttng_trace_chunk_status status;
        size_t i, count;
@@ -1698,39 +1626,38 @@ int lttng_trace_chunk_delete_post_release_owner(
        LTTNG_ASSERT(trace_chunk->chunk_directory);
 
        /* Remove empty directories. */
-       count = lttng_dynamic_pointer_array_get_count(
-                       &trace_chunk->top_level_directories);
+       count = lttng_dynamic_pointer_array_get_count(&trace_chunk->top_level_directories);
 
        for (i = 0; i < count; i++) {
-               const char *top_level_name =
-                       (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               &trace_chunk->top_level_directories, i);
+               const char *top_level_name = (const char *) lttng_dynamic_pointer_array_get_pointer(
+                       &trace_chunk->top_level_directories, i);
 
-               status = (lttng_trace_chunk_status) lttng_trace_chunk_remove_subdirectory_recursive(trace_chunk, top_level_name);
+               status = (lttng_trace_chunk_status) lttng_trace_chunk_remove_subdirectory_recursive(
+                       trace_chunk, top_level_name);
                if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                        ERR("Error recursively removing subdirectory '%s' file when deleting chunk",
-                                       top_level_name);
+                           top_level_name);
                        ret = -1;
                        break;
                }
        }
        if (!ret) {
                lttng_directory_handle_put(trace_chunk->chunk_directory);
-               trace_chunk->chunk_directory = NULL;
+               trace_chunk->chunk_directory = nullptr;
 
                if (trace_chunk->path && trace_chunk->path[0] != '\0') {
-                       status = (lttng_trace_chunk_status) lttng_directory_handle_remove_subdirectory(
-                                       trace_chunk->session_output_directory,
-                                       trace_chunk->path);
+                       status = (lttng_trace_chunk_status)
+                               lttng_directory_handle_remove_subdirectory(
+                                       trace_chunk->session_output_directory, trace_chunk->path);
                        if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
                                ERR("Error removing subdirectory '%s' file when deleting chunk",
-                                       trace_chunk->path);
+                                   trace_chunk->path);
                                ret = -1;
                        }
                }
        }
        free(trace_chunk->path);
-       trace_chunk->path = NULL;
+       trace_chunk->path = nullptr;
 end:
        return ret;
 }
@@ -1741,9 +1668,7 @@ end:
  * session daemon is the owner of the chunk. Unlink all files owned by each
  * consumer daemon.
  */
-static
-int lttng_trace_chunk_delete_post_release(
-               struct lttng_trace_chunk *trace_chunk)
+static int lttng_trace_chunk_delete_post_release(struct lttng_trace_chunk *trace_chunk)
 {
        if (!trace_chunk->chunk_directory) {
                return 0;
@@ -1756,9 +1681,9 @@ int lttng_trace_chunk_delete_post_release(
        }
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_close_command(
-               struct lttng_trace_chunk *chunk,
-               enum lttng_trace_chunk_command_type *command_type)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_close_command(struct lttng_trace_chunk *chunk,
+                                   enum lttng_trace_chunk_command_type *command_type)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
@@ -1773,14 +1698,14 @@ enum lttng_trace_chunk_status lttng_trace_chunk_get_close_command(
        return status;
 }
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_close_command(
-               struct lttng_trace_chunk *chunk,
-               enum lttng_trace_chunk_command_type close_command)
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_close_command(struct lttng_trace_chunk *chunk,
+                                   enum lttng_trace_chunk_command_type close_command)
 {
        enum lttng_trace_chunk_status status = LTTNG_TRACE_CHUNK_STATUS_OK;
 
        if (close_command < LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED ||
-                       close_command >= LTTNG_TRACE_CHUNK_COMMAND_TYPE_MAX) {
+           close_command >= LTTNG_TRACE_CHUNK_COMMAND_TYPE_MAX) {
                status = LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT;
                goto end;
        }
@@ -1788,11 +1713,11 @@ enum lttng_trace_chunk_status lttng_trace_chunk_set_close_command(
        pthread_mutex_lock(&chunk->lock);
        if (chunk->close_command.is_set) {
                DBG("Overriding trace chunk close command from \"%s\" to \"%s\"",
-                               lttng_trace_chunk_command_type_str(chunk->close_command.value),
-                               lttng_trace_chunk_command_type_str(close_command));
+                   lttng_trace_chunk_command_type_str(chunk->close_command.value),
+                   lttng_trace_chunk_command_type_str(close_command));
        } else {
                DBG("Setting trace chunk close command to \"%s\"",
-                               lttng_trace_chunk_command_type_str(close_command));
+                   lttng_trace_chunk_command_type_str(close_command));
        }
        /*
         * Unset close command for no-op for backward compatibility with relayd
@@ -1808,8 +1733,7 @@ end:
        return status;
 }
 
-const char *lttng_trace_chunk_command_type_get_name(
-               enum lttng_trace_chunk_command_type command)
+const char *lttng_trace_chunk_command_type_get_name(enum lttng_trace_chunk_command_type command)
 {
        switch (command) {
        case LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED:
@@ -1824,7 +1748,7 @@ const char *lttng_trace_chunk_command_type_get_name(
 }
 
 bool lttng_trace_chunk_ids_equal(const struct lttng_trace_chunk *chunk_a,
-               const struct lttng_trace_chunk *chunk_b)
+                                const struct lttng_trace_chunk *chunk_b)
 {
        bool equal = false;
 
@@ -1858,26 +1782,25 @@ bool lttng_trace_chunk_get(struct lttng_trace_chunk *chunk)
        return urcu_ref_get_unless_zero(&chunk->ref);
 }
 
-static
-void free_lttng_trace_chunk_registry_element(struct rcu_head *node)
+static void free_lttng_trace_chunk_registry_element(struct rcu_head *node)
 {
-       struct lttng_trace_chunk_registry_element *element = lttng::utils::container_of(
-                       node, &lttng_trace_chunk_registry_element::rcu_node);
+       struct lttng_trace_chunk_registry_element *element =
+               lttng::utils::container_of(node, &lttng_trace_chunk_registry_element::rcu_node);
 
        free(element);
 }
 
-static
-void lttng_trace_chunk_release(struct urcu_ref *ref)
+static void lttng_trace_chunk_release(struct urcu_ref *ref)
 {
        struct lttng_trace_chunk *chunk = lttng::utils::container_of(ref, &lttng_trace_chunk::ref);
 
        if (chunk->close_command.is_set) {
-               chunk_command func = close_command_get_post_release_func(chunk->close_command.value);
+               chunk_command func =
+                       close_command_get_post_release_func(chunk->close_command.value);
 
                if (func(chunk)) {
                        ERR("Trace chunk post-release command %s has failed.",
-                                       lttng_trace_chunk_command_type_str(chunk->close_command.value));
+                           lttng_trace_chunk_command_type_str(chunk->close_command.value));
                }
        }
 
@@ -1902,19 +1825,15 @@ void lttng_trace_chunk_release(struct urcu_ref *ref)
                 */
                lttng_trace_chunk_fini(chunk);
 
-               element = lttng::utils::container_of(
-                               chunk, &lttng_trace_chunk_registry_element::chunk);
+               element = lttng::utils::container_of(chunk,
+                                                    &lttng_trace_chunk_registry_element::chunk);
                if (element->registry) {
-                       rcu_read_lock();
-                       cds_lfht_del(element->registry->ht,
-                                       &element->trace_chunk_registry_ht_node);
-                       rcu_read_unlock();
-                       call_rcu(&element->rcu_node,
-                                       free_lttng_trace_chunk_registry_element);
+                       lttng::urcu::read_lock_guard read_lock;
+                       cds_lfht_del(element->registry->ht, &element->trace_chunk_registry_ht_node);
+                       call_rcu(&element->rcu_node, free_lttng_trace_chunk_registry_element);
                } else {
                        /* Never published, can be free'd immediately. */
-                       free_lttng_trace_chunk_registry_element(
-                                       &element->rcu_node);
+                       free_lttng_trace_chunk_registry_element(&element->rcu_node);
                }
        } else {
                /* Not RCU-protected, free immediately. */
@@ -1932,7 +1851,7 @@ void lttng_trace_chunk_put(struct lttng_trace_chunk *chunk)
        urcu_ref_put(&chunk->ref, lttng_trace_chunk_release);
 }
 
-struct lttng_trace_chunk_registry *lttng_trace_chunk_registry_create(void)
+struct lttng_trace_chunk_registry *lttng_trace_chunk_registry_create()
 {
        struct lttng_trace_chunk_registry *registry;
 
@@ -1941,8 +1860,8 @@ struct lttng_trace_chunk_registry *lttng_trace_chunk_registry_create(void)
                goto end;
        }
 
-       registry->ht = cds_lfht_new(DEFAULT_HT_SIZE, 1, 0,
-                       CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, NULL);
+       registry->ht = cds_lfht_new(
+               DEFAULT_HT_SIZE, 1, 0, CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING, nullptr);
        if (!registry->ht) {
                goto error;
        }
@@ -1950,26 +1869,24 @@ end:
        return registry;
 error:
        lttng_trace_chunk_registry_destroy(registry);
-       return NULL;
+       return nullptr;
 }
 
-void lttng_trace_chunk_registry_destroy(
-               struct lttng_trace_chunk_registry *registry)
+void lttng_trace_chunk_registry_destroy(struct lttng_trace_chunk_registry *registry)
 {
        if (!registry) {
                return;
        }
        if (registry->ht) {
-               int ret = cds_lfht_destroy(registry->ht, NULL);
+               int ret = cds_lfht_destroy(registry->ht, nullptr);
                LTTNG_ASSERT(!ret);
        }
        free(registry);
 }
 
-static
-struct lttng_trace_chunk_registry_element *
-lttng_trace_chunk_registry_element_create_from_chunk(
-               struct lttng_trace_chunk *chunk, uint64_t session_id)
+static struct lttng_trace_chunk_registry_element *
+lttng_trace_chunk_registry_element_create_from_chunk(struct lttng_trace_chunk *chunk,
+                                                    uint64_t session_id)
 {
        struct lttng_trace_chunk_registry_element *element =
                zmalloc<lttng_trace_chunk_registry_element>();
@@ -1984,21 +1901,20 @@ lttng_trace_chunk_registry_element_create_from_chunk(
        lttng_trace_chunk_init(&element->chunk);
        if (chunk->session_output_directory) {
                /* Transferred ownership. */
-               element->chunk.session_output_directory =
-                               chunk->session_output_directory;
-               chunk->session_output_directory = NULL;
+               element->chunk.session_output_directory = chunk->session_output_directory;
+               chunk->session_output_directory = nullptr;
        }
        if (chunk->chunk_directory) {
                /* Transferred ownership. */
                element->chunk.chunk_directory = chunk->chunk_directory;
-               chunk->chunk_directory = NULL;
+               chunk->chunk_directory = nullptr;
        }
        /*
         * The original chunk becomes invalid; the name and path attributes are
         * transferred to the new chunk instance.
         */
-       chunk->name = NULL;
-       chunk->path = NULL;
+       chunk->name = nullptr;
+       chunk->path = nullptr;
        element->chunk.fd_tracker = chunk->fd_tracker;
        element->chunk.in_registry_element = true;
 end:
@@ -2006,30 +1922,29 @@ end:
 }
 
 struct lttng_trace_chunk *
-lttng_trace_chunk_registry_publish_chunk(
-               struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id,
-               struct lttng_trace_chunk *chunk)
+lttng_trace_chunk_registry_publish_chunk(struct lttng_trace_chunk_registry *registry,
+                                        uint64_t session_id,
+                                        struct lttng_trace_chunk *chunk)
 {
        bool unused;
 
-       return lttng_trace_chunk_registry_publish_chunk(
-                       registry, session_id, chunk, &unused);
+       return lttng_trace_chunk_registry_publish_chunk(registry, session_id, chunk, &unused);
 }
 
 struct lttng_trace_chunk *
-lttng_trace_chunk_registry_publish_chunk(
-               struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, struct lttng_trace_chunk *chunk,
-               bool *previously_published)
+lttng_trace_chunk_registry_publish_chunk(struct lttng_trace_chunk_registry *registry,
+                                        uint64_t session_id,
+                                        struct lttng_trace_chunk *chunk,
+                                        bool *previously_published)
 {
        struct lttng_trace_chunk_registry_element *element;
        unsigned long element_hash;
 
        pthread_mutex_lock(&chunk->lock);
-       element = lttng_trace_chunk_registry_element_create_from_chunk(chunk,
-                       session_id);
+       element = lttng_trace_chunk_registry_element_create_from_chunk(chunk, session_id);
        pthread_mutex_unlock(&chunk->lock);
+
+       lttng::urcu::read_lock_guard read_lock;
        if (!element) {
                goto end;
        }
@@ -2037,20 +1952,19 @@ lttng_trace_chunk_registry_publish_chunk(
         * chunk is now invalid, the only valid operation is a 'put' from the
         * caller.
         */
-       chunk = NULL;
+       chunk = nullptr;
        element_hash = lttng_trace_chunk_registry_element_hash(element);
 
-       rcu_read_lock();
-       while (1) {
+       while (true) {
                struct cds_lfht_node *published_node;
                struct lttng_trace_chunk *published_chunk;
                struct lttng_trace_chunk_registry_element *published_element;
 
                published_node = cds_lfht_add_unique(registry->ht,
-                               element_hash,
-                               lttng_trace_chunk_registry_element_match,
-                               element,
-                               &element->trace_chunk_registry_ht_node);
+                                                    element_hash,
+                                                    lttng_trace_chunk_registry_element_match,
+                                                    element,
+                                                    &element->trace_chunk_registry_ht_node);
                if (published_node == &element->trace_chunk_registry_ht_node) {
                        /* Successfully published the new element. */
                        element->registry = registry;
@@ -2076,8 +1990,9 @@ lttng_trace_chunk_registry_publish_chunk(
                 * already published and release the reference to the copy we
                 * created if successful.
                 */
-               published_element = lttng::utils::container_of(published_node,
-                               &lttng_trace_chunk_registry_element::trace_chunk_registry_ht_node);
+               published_element = lttng::utils::container_of(
+                       published_node,
+                       &lttng_trace_chunk_registry_element::trace_chunk_registry_ht_node);
                published_chunk = &published_element->chunk;
                if (lttng_trace_chunk_get(published_chunk)) {
                        lttng_trace_chunk_put(&element->chunk);
@@ -2091,9 +2006,8 @@ lttng_trace_chunk_registry_publish_chunk(
                 * chunk.
                 */
        }
-       rcu_read_unlock();
 end:
-       return element ? &element->chunk : NULL;
+       return element ? &element->chunk : nullptr;
 }
 
 /*
@@ -2105,26 +2019,22 @@ end:
  * IOW, holding a reference guarantees the existence of the object for the
  * caller.
  */
-static
-struct lttng_trace_chunk *_lttng_trace_chunk_registry_find_chunk(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, uint64_t *chunk_id)
+static struct lttng_trace_chunk *_lttng_trace_chunk_registry_find_chunk(
+       const struct lttng_trace_chunk_registry *registry, uint64_t session_id, uint64_t *chunk_id)
 {
-       lttng_trace_chunk_registry_element target_element {};
+       lttng_trace_chunk_registry_element target_element{};
 
        target_element.chunk.id.is_set = !!chunk_id;
        target_element.chunk.id.value = chunk_id ? *chunk_id : 0;
        target_element.session_id = session_id;
 
-       const unsigned long element_hash =
-                       lttng_trace_chunk_registry_element_hash(
-                               &target_element);
+       const unsigned long element_hash = lttng_trace_chunk_registry_element_hash(&target_element);
        struct cds_lfht_node *published_node;
        struct lttng_trace_chunk_registry_element *published_element;
-       struct lttng_trace_chunk *published_chunk = NULL;
+       struct lttng_trace_chunk *published_chunk = nullptr;
        struct cds_lfht_iter iter;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(registry->ht,
                        element_hash,
                        lttng_trace_chunk_registry_element_match,
@@ -2135,28 +2045,25 @@ struct lttng_trace_chunk *_lttng_trace_chunk_registry_find_chunk(
                goto end;
        }
 
-       published_element = lttng::utils::container_of(published_node,
-                       &lttng_trace_chunk_registry_element::trace_chunk_registry_ht_node);
+       published_element = lttng::utils::container_of(
+               published_node, &lttng_trace_chunk_registry_element::trace_chunk_registry_ht_node);
        if (lttng_trace_chunk_get(&published_element->chunk)) {
                published_chunk = &published_element->chunk;
        }
 end:
-       rcu_read_unlock();
        return published_chunk;
 }
 
-struct lttng_trace_chunk *
-lttng_trace_chunk_registry_find_chunk(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, uint64_t chunk_id)
+struct lttng_trace_chunk *lttng_trace_chunk_registry_find_chunk(
+       const struct lttng_trace_chunk_registry *registry, uint64_t session_id, uint64_t chunk_id)
 {
-       return _lttng_trace_chunk_registry_find_chunk(registry,
-                       session_id, &chunk_id);
+       return _lttng_trace_chunk_registry_find_chunk(registry, session_id, &chunk_id);
 }
 
-int lttng_trace_chunk_registry_chunk_exists(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id, uint64_t chunk_id, bool *chunk_exists)
+int lttng_trace_chunk_registry_chunk_exists(const struct lttng_trace_chunk_registry *registry,
+                                           uint64_t session_id,
+                                           uint64_t chunk_id,
+                                           bool *chunk_exists)
 {
        int ret = 0;
        lttng_trace_chunk_registry_element target_element;
@@ -2165,13 +2072,11 @@ int lttng_trace_chunk_registry_chunk_exists(
        target_element.chunk.id.value = chunk_id;
        target_element.session_id = session_id;
 
-       const unsigned long element_hash =
-                       lttng_trace_chunk_registry_element_hash(
-                               &target_element);
+       const unsigned long element_hash = lttng_trace_chunk_registry_element_hash(&target_element);
        struct cds_lfht_node *published_node;
        struct cds_lfht_iter iter;
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        cds_lfht_lookup(registry->ht,
                        element_hash,
                        lttng_trace_chunk_registry_element_match,
@@ -2185,61 +2090,61 @@ int lttng_trace_chunk_registry_chunk_exists(
 
        *chunk_exists = !cds_lfht_is_node_deleted(published_node);
 end:
-       rcu_read_unlock();
        return ret;
 }
 
 struct lttng_trace_chunk *
-lttng_trace_chunk_registry_find_anonymous_chunk(
-               const struct lttng_trace_chunk_registry *registry,
-               uint64_t session_id)
+lttng_trace_chunk_registry_find_anonymous_chunk(const struct lttng_trace_chunk_registry *registry,
+                                               uint64_t session_id)
 {
-       return _lttng_trace_chunk_registry_find_chunk(registry,
-                       session_id, NULL);
+       return _lttng_trace_chunk_registry_find_chunk(registry, session_id, nullptr);
 }
 
-unsigned int lttng_trace_chunk_registry_put_each_chunk(
-               const struct lttng_trace_chunk_registry *registry)
+unsigned int
+lttng_trace_chunk_registry_put_each_chunk(const struct lttng_trace_chunk_registry *registry)
 {
        struct cds_lfht_iter iter;
        struct lttng_trace_chunk_registry_element *chunk_element;
        unsigned int trace_chunks_left = 0;
 
        DBG("Releasing trace chunk registry to all trace chunks");
-       rcu_read_lock();
-       cds_lfht_for_each_entry(registry->ht,
-                       &iter, chunk_element, trace_chunk_registry_ht_node) {
-               const char *chunk_id_str = "none";
-               char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
-
-               pthread_mutex_lock(&chunk_element->chunk.lock);
-               if (chunk_element->chunk.id.is_set) {
-                       int fmt_ret;
-
-                       fmt_ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf),
-                                       "%" PRIu64,
-                                       chunk_element->chunk.id.value);
-                       if (fmt_ret < 0 || fmt_ret >= sizeof(chunk_id_buf)) {
-                               chunk_id_str = "formatting error";
-                       } else {
-                               chunk_id_str = chunk_id_buf;
+
+       {
+               lttng::urcu::read_lock_guard read_lock;
+
+               cds_lfht_for_each_entry (
+                       registry->ht, &iter, chunk_element, trace_chunk_registry_ht_node) {
+                       const char *chunk_id_str = "none";
+                       char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
+
+                       pthread_mutex_lock(&chunk_element->chunk.lock);
+                       if (chunk_element->chunk.id.is_set) {
+                               int fmt_ret;
+
+                               fmt_ret = snprintf(chunk_id_buf,
+                                                  sizeof(chunk_id_buf),
+                                                  "%" PRIu64,
+                                                  chunk_element->chunk.id.value);
+                               if (fmt_ret < 0 || fmt_ret >= sizeof(chunk_id_buf)) {
+                                       chunk_id_str = "formatting error";
+                               } else {
+                                       chunk_id_str = chunk_id_buf;
+                               }
                        }
+
+                       DBG("Releasing reference to trace chunk: session_id = %" PRIu64
+                           "chunk_id = %s, name = \"%s\", status = %s",
+                           chunk_element->session_id,
+                           chunk_id_str,
+                           chunk_element->chunk.name ?: "none",
+                           chunk_element->chunk.close_command.is_set ? "open" : "closed");
+                       pthread_mutex_unlock(&chunk_element->chunk.lock);
+                       lttng_trace_chunk_put(&chunk_element->chunk);
+                       trace_chunks_left++;
                }
+       }
 
-               DBG("Releasing reference to trace chunk: session_id = %" PRIu64
-                               "chunk_id = %s, name = \"%s\", status = %s",
-                               chunk_element->session_id,
-                               chunk_id_str,
-                               chunk_element->chunk.name ? : "none",
-                               chunk_element->chunk.close_command.is_set ?
-                                               "open" : "closed");
-               pthread_mutex_unlock(&chunk_element->chunk.lock);
-               lttng_trace_chunk_put(&chunk_element->chunk);
-               trace_chunks_left++;
-       }
-       rcu_read_unlock();
-       DBG("Released reference to %u trace chunks in %s()", trace_chunks_left,
-                       __FUNCTION__);
+       DBG("Released reference to %u trace chunks in %s()", trace_chunks_left, __FUNCTION__);
 
        return trace_chunks_left;
 }
index cf038b9512401c9d6ddce0420e8939249444f9fe..5364f5cd6b93518264502cb01a0336607545bab1 100644 (file)
@@ -12,6 +12,7 @@
 #include <common/credentials.hpp>
 #include <common/fd-tracker/fd-tracker.hpp>
 #include <common/macros.hpp>
+
 #include <stdbool.h>
 #include <stddef.h>
 #include <stdint.h>
@@ -70,112 +71,103 @@ enum lttng_trace_chunk_command_type {
        LTTNG_TRACE_CHUNK_COMMAND_TYPE_MAX,
 };
 
-struct lttng_trace_chunk *lttng_trace_chunk_create_anonymous(void);
+struct lttng_trace_chunk *lttng_trace_chunk_create_anonymous();
 
-struct lttng_trace_chunk *lttng_trace_chunk_create(
-               uint64_t chunk_id,
-               time_t chunk_creation_time,
-               const char *path);
+struct lttng_trace_chunk *
+lttng_trace_chunk_create(uint64_t chunk_id, time_t chunk_creation_time, const char *path);
 
 void lttng_trace_chunk_set_fd_tracker(struct lttng_trace_chunk *chunk,
-               struct fd_tracker *fd_tracker);
+                                     struct fd_tracker *fd_tracker);
 
 /*
  * Copy a trace chunk. The copy that is returned is always a _user_
  * mode chunk even if the source chunk was an _owner_ as there can never be
  * two _owners_ of the same trace output.
  */
-struct lttng_trace_chunk *lttng_trace_chunk_copy(
-               struct lttng_trace_chunk *source_chunk);
+struct lttng_trace_chunk *lttng_trace_chunk_copy(struct lttng_trace_chunk *source_chunk);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_id(
-               struct lttng_trace_chunk *chunk, uint64_t *id);
+enum lttng_trace_chunk_status lttng_trace_chunk_get_id(struct lttng_trace_chunk *chunk,
+                                                      uint64_t *id);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_creation_timestamp(
-               struct lttng_trace_chunk *chunk, time_t *creation_ts);
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_creation_timestamp(struct lttng_trace_chunk *chunk, time_t *creation_ts);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_close_timestamp(
-               struct lttng_trace_chunk *chunk, time_t *close_ts);
+enum lttng_trace_chunk_status lttng_trace_chunk_get_close_timestamp(struct lttng_trace_chunk *chunk,
+                                                                   time_t *close_ts);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_close_timestamp(
-               struct lttng_trace_chunk *chunk, time_t close_ts);
+enum lttng_trace_chunk_status lttng_trace_chunk_set_close_timestamp(struct lttng_trace_chunk *chunk,
+                                                                   time_t close_ts);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_name(
-               struct lttng_trace_chunk *chunk, const char **name,
-               bool *name_overridden);
+enum lttng_trace_chunk_status lttng_trace_chunk_get_name(struct lttng_trace_chunk *chunk,
+                                                        const char **name,
+                                                        bool *name_overridden);
 
 bool lttng_trace_chunk_get_name_overridden(struct lttng_trace_chunk *chunk);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_override_name(
-               struct lttng_trace_chunk *chunk, const char *name);
+enum lttng_trace_chunk_status lttng_trace_chunk_override_name(struct lttng_trace_chunk *chunk,
+                                                             const char *name);
+
+enum lttng_trace_chunk_status lttng_trace_chunk_rename_path(struct lttng_trace_chunk *chunk,
+                                                           const char *path);
+
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_credentials(struct lttng_trace_chunk *chunk,
+                                 struct lttng_credentials *credentials);
+
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_credentials(struct lttng_trace_chunk *chunk,
+                                 const struct lttng_credentials *credentials);
+
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_credentials_current_user(struct lttng_trace_chunk *chunk);
+
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_as_owner(struct lttng_trace_chunk *chunk,
+                              struct lttng_directory_handle *session_output_directory);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_rename_path(
-               struct lttng_trace_chunk *chunk, const char *path);
+enum lttng_trace_chunk_status
+lttng_trace_chunk_set_as_user(struct lttng_trace_chunk *chunk,
+                             struct lttng_directory_handle *chunk_directory);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_get_credentials(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_credentials *credentials);
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_session_output_directory_handle(struct lttng_trace_chunk *chunk,
+                                                     struct lttng_directory_handle **handle);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_credentials(
-               struct lttng_trace_chunk *chunk,
-               const struct lttng_credentials *credentials);
+enum lttng_trace_chunk_status
+lttng_trace_chunk_borrow_chunk_directory_handle(struct lttng_trace_chunk *chunk,
+                                               const struct lttng_directory_handle **handle);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_credentials_current_user(
-               struct lttng_trace_chunk *chunk);
+enum lttng_trace_chunk_status lttng_trace_chunk_create_subdirectory(struct lttng_trace_chunk *chunk,
+                                                                   const char *subdirectory_path);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_as_owner(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle *session_output_directory);
+enum lttng_trace_chunk_status lttng_trace_chunk_open_file(struct lttng_trace_chunk *chunk,
+                                                         const char *filename,
+                                                         int flags,
+                                                         mode_t mode,
+                                                         int *out_fd,
+                                                         bool expect_no_file);
 
-enum lttng_trace_chunk_status lttng_trace_chunk_set_as_user(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle *chunk_directory);
+enum lttng_trace_chunk_status lttng_trace_chunk_open_fs_handle(struct lttng_trace_chunk *chunk,
+                                                              const char *filename,
+                                                              int flags,
+                                                              mode_t mode,
+                                                              struct fs_handle **out_handle,
+                                                              bool expect_no_file);
+
+int lttng_trace_chunk_unlink_file(struct lttng_trace_chunk *chunk, const char *filename);
+
+enum lttng_trace_chunk_status
+lttng_trace_chunk_get_close_command(struct lttng_trace_chunk *chunk,
+                                   enum lttng_trace_chunk_command_type *command_type);
 
 enum lttng_trace_chunk_status
-lttng_trace_chunk_get_session_output_directory_handle(
-               struct lttng_trace_chunk *chunk,
-               struct lttng_directory_handle **handle);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_borrow_chunk_directory_handle(
-               struct lttng_trace_chunk *chunk,
-               const struct lttng_directory_handle **handle);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_create_subdirectory(
-               struct lttng_trace_chunk *chunk,
-               const char *subdirectory_path);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_open_file(
-               struct lttng_trace_chunk *chunk,
-               const char *filename,
-               int flags,
-               mode_t mode,
-               int *out_fd,
-               bool expect_no_file);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_open_fs_handle(
-               struct lttng_trace_chunk *chunk,
-               const char *filename,
-               int flags,
-               mode_t mode,
-               struct fs_handle **out_handle,
-               bool expect_no_file);
-
-int lttng_trace_chunk_unlink_file(struct lttng_trace_chunk *chunk,
-               const char *filename);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_get_close_command(
-               struct lttng_trace_chunk *chunk,
-               enum lttng_trace_chunk_command_type *command_type);
-
-enum lttng_trace_chunk_status lttng_trace_chunk_set_close_command(
-               struct lttng_trace_chunk *chunk,
-               enum lttng_trace_chunk_command_type command_type);
-
-const char *lttng_trace_chunk_command_type_get_name(
-               enum lttng_trace_chunk_command_type command);
+lttng_trace_chunk_set_close_command(struct lttng_trace_chunk *chunk,
+                                   enum lttng_trace_chunk_command_type command_type);
+
+const char *lttng_trace_chunk_command_type_get_name(enum lttng_trace_chunk_command_type command);
 
 bool lttng_trace_chunk_ids_equal(const struct lttng_trace_chunk *chunk_a,
-               const struct lttng_trace_chunk *chunk_b);
+                                const struct lttng_trace_chunk *chunk_b);
 
 /* Returns true on success. */
 bool lttng_trace_chunk_get(struct lttng_trace_chunk *chunk);
index e988599bae9a27a0c4859e6a577b191a5ff57094..dba84293dc216f1d28e3f44239149032326ac8f3 100644 (file)
@@ -6,18 +6,17 @@
  *
  */
 
-#include <lttng/domain.h>
-#include <lttng/lttng-error.h>
-#include <lttng/tracker.h>
-
 #include <common/dynamic-array.hpp>
 #include <common/error.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/tracker.hpp>
 
-#include <stdbool.h>
+#include <lttng/domain.h>
+#include <lttng/lttng-error.h>
+#include <lttng/tracker.h>
 
+#include <stdbool.h>
 #include <type_traits>
 
 namespace {
@@ -36,42 +35,39 @@ struct process_attr_tracker_value_comm {
 } LTTNG_PACKED;
 } /* namespace */
 
-#define GET_INTEGRAL_COMM_VALUE(value_ptr, as_type)              \
-       ((as_type)(std::is_signed<as_type>::value ? (value_ptr)->u._signed : \
-                                       (value_ptr)->u._unsigned))
-
-#define SET_INTEGRAL_COMM_VALUE(comm_value, val)                         \
-       if (std::is_signed<typeof(val)>::value) {                                    \
-               (comm_value)->u._signed =                                  \
-                               (typeof((comm_value)->u._signed)) val;   \
-       } else {                                                           \
-               (comm_value)->u._unsigned =                                \
-                               (typeof((comm_value)->u._unsigned)) val; \
+#define GET_INTEGRAL_COMM_VALUE(value_ptr, as_type)                           \
+       ((as_type) (std::is_signed<as_type>::value ? (value_ptr)->u._signed : \
+                                                    (value_ptr)->u._unsigned))
+
+#define SET_INTEGRAL_COMM_VALUE(comm_value, val)                                       \
+       if (std::is_signed<typeof(val)>::value) {                                      \
+               (comm_value)->u._signed = (typeof((comm_value)->u._signed)) (val);     \
+       } else {                                                                       \
+               (comm_value)->u._unsigned = (typeof((comm_value)->u._unsigned)) (val); \
        }
 
 static inline bool is_virtual_process_attr(enum lttng_process_attr process_attr)
 {
        return process_attr == LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID ||
-              process_attr == LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID ||
-              process_attr == LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID;
+               process_attr == LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID ||
+               process_attr == LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID;
 }
 
-static inline bool is_value_type_name(
-               enum lttng_process_attr_value_type value_type)
+static inline bool is_value_type_name(enum lttng_process_attr_value_type value_type)
 {
        return value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ||
-              value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME;
+               value_type == LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME;
 }
 
-enum lttng_error_code process_attr_value_from_comm(
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_process_attr_value_type value_type,
-               const struct process_attr_integral_value_comm *integral_value,
-               const struct lttng_buffer_view *value_view,
-               struct process_attr_value **_value)
+enum lttng_error_code
+process_attr_value_from_comm(enum lttng_domain_type domain,
+                            enum lttng_process_attr process_attr,
+                            enum lttng_process_attr_value_type value_type,
+                            const struct process_attr_integral_value_comm *integral_value,
+                            const struct lttng_buffer_view *value_view,
+                            struct process_attr_value **_value)
 {
-       char *name = NULL;
+       char *name = nullptr;
        enum lttng_error_code ret = LTTNG_OK;
        struct process_attr_value *value = zmalloc<process_attr_value>();
 
@@ -98,20 +94,17 @@ enum lttng_error_code process_attr_value_from_comm(
                goto error;
        }
 
-       if (!is_virtual_process_attr(process_attr) &&
-                       domain != LTTNG_DOMAIN_KERNEL) {
+       if (!is_virtual_process_attr(process_attr) && domain != LTTNG_DOMAIN_KERNEL) {
                ERR("Non-virtual process attributes can only be used in the kernel domain");
                ret = LTTNG_ERR_UNSUPPORTED_DOMAIN;
                goto error;
        }
 
        /* Only expect a payload for name value types. */
-       if (is_value_type_name(value_type) &&
-                       (!value_view || value_view->size == 0)) {
+       if (is_value_type_name(value_type) && (!value_view || value_view->size == 0)) {
                ret = LTTNG_ERR_INVALID_PROTOCOL;
                goto error;
-       } else if (!is_value_type_name(value_type) && value_view &&
-                       value_view->size != 0) {
+       } else if (!is_value_type_name(value_type) && value_view && value_view->size != 0) {
                ret = LTTNG_ERR_INVALID_PROTOCOL;
                goto error;
        }
@@ -125,15 +118,13 @@ enum lttng_error_code process_attr_value_from_comm(
                        ret = LTTNG_ERR_INVALID;
                        goto error;
                }
-               value->value.pid =
-                               GET_INTEGRAL_COMM_VALUE(integral_value, pid_t);
+               value->value.pid = GET_INTEGRAL_COMM_VALUE(integral_value, pid_t);
                break;
        case LTTNG_PROCESS_ATTR_USER_ID:
        case LTTNG_PROCESS_ATTR_VIRTUAL_USER_ID:
                switch (value_type) {
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_UID:
-                       value->value.uid = GET_INTEGRAL_COMM_VALUE(
-                                       integral_value, uid_t);
+                       value->value.uid = GET_INTEGRAL_COMM_VALUE(integral_value, uid_t);
                        break;
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME:
                        if (!name) {
@@ -142,7 +133,7 @@ enum lttng_error_code process_attr_value_from_comm(
                        }
 
                        value->value.user_name = name;
-                       name = NULL;
+                       name = nullptr;
                        break;
                default:
                        ERR("Invalid value type used for user ID process attribute");
@@ -154,8 +145,7 @@ enum lttng_error_code process_attr_value_from_comm(
        case LTTNG_PROCESS_ATTR_VIRTUAL_GROUP_ID:
                switch (value_type) {
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_GID:
-                       value->value.gid = GET_INTEGRAL_COMM_VALUE(
-                                       integral_value, gid_t);
+                       value->value.gid = GET_INTEGRAL_COMM_VALUE(integral_value, gid_t);
                        break;
                case LTTNG_PROCESS_ATTR_VALUE_TYPE_GROUP_NAME:
                        if (!name) {
@@ -164,7 +154,7 @@ enum lttng_error_code process_attr_value_from_comm(
                        }
 
                        value->value.group_name = name;
-                       name = NULL;
+                       name = nullptr;
                        break;
                default:
                        ERR("Invalid value type used for group ID process attribute");
@@ -178,7 +168,7 @@ enum lttng_error_code process_attr_value_from_comm(
        }
 
        *_value = value;
-       value = NULL;
+       value = nullptr;
        free(name);
        return LTTNG_OK;
 error:
@@ -214,7 +204,7 @@ static void process_attr_tracker_value_destructor(void *ptr)
        process_attr_value_destroy(value);
 }
 
-struct lttng_process_attr_values *lttng_process_attr_values_create(void)
+struct lttng_process_attr_values *lttng_process_attr_values_create()
 {
        struct lttng_process_attr_values *values = zmalloc<lttng_process_attr_values>();
 
@@ -222,49 +212,43 @@ struct lttng_process_attr_values *lttng_process_attr_values_create(void)
                goto end;
        }
 
-       lttng_dynamic_pointer_array_init(
-                       &values->array, process_attr_tracker_value_destructor);
+       lttng_dynamic_pointer_array_init(&values->array, process_attr_tracker_value_destructor);
 end:
        return values;
 }
 
-unsigned int _lttng_process_attr_values_get_count(
-               const struct lttng_process_attr_values *values)
+unsigned int _lttng_process_attr_values_get_count(const struct lttng_process_attr_values *values)
 {
-       return (unsigned int) lttng_dynamic_pointer_array_get_count(
-                       &values->array);
+       return (unsigned int) lttng_dynamic_pointer_array_get_count(&values->array);
 }
 
-const struct process_attr_value *lttng_process_attr_tracker_values_get_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index)
+const struct process_attr_value *
+lttng_process_attr_tracker_values_get_at_index(const struct lttng_process_attr_values *values,
+                                              unsigned int index)
 {
-       return (process_attr_value *) lttng_dynamic_pointer_array_get_pointer(&values->array, index);
+       return (process_attr_value *) lttng_dynamic_pointer_array_get_pointer(&values->array,
+                                                                             index);
 }
 
-static
-int process_attr_tracker_value_serialize(const struct process_attr_value *value,
-               struct lttng_dynamic_buffer *buffer)
+static int process_attr_tracker_value_serialize(const struct process_attr_value *value,
+                                               struct lttng_dynamic_buffer *buffer)
 {
        int ret;
        struct process_attr_tracker_value_comm value_comm = {
-                       .type = (int32_t) value->type,
-                       .value = {},
+               .type = (int32_t) value->type,
+               .value = {},
        };
-       const char *name = NULL;
+       const char *name = nullptr;
 
        switch (value->type) {
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_PID:
-               SET_INTEGRAL_COMM_VALUE(
-                               &value_comm.value.integral, value->value.pid);
+               SET_INTEGRAL_COMM_VALUE(&value_comm.value.integral, value->value.pid);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_UID:
-               SET_INTEGRAL_COMM_VALUE(
-                               &value_comm.value.integral, value->value.uid);
+               SET_INTEGRAL_COMM_VALUE(&value_comm.value.integral, value->value.uid);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_GID:
-               SET_INTEGRAL_COMM_VALUE(
-                               &value_comm.value.integral, value->value.gid);
+               SET_INTEGRAL_COMM_VALUE(&value_comm.value.integral, value->value.gid);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME:
                name = value->value.user_name;
@@ -280,23 +264,20 @@ int process_attr_tracker_value_serialize(const struct process_attr_value *value,
                value_comm.value.name_len = strlen(name) + 1;
        }
 
-       ret = lttng_dynamic_buffer_append(
-                       buffer, &value_comm, sizeof(value_comm));
+       ret = lttng_dynamic_buffer_append(buffer, &value_comm, sizeof(value_comm));
        if (ret) {
                goto end;
        }
 
        if (name) {
-               ret = lttng_dynamic_buffer_append(
-                               buffer, name, value_comm.value.name_len);
+               ret = lttng_dynamic_buffer_append(buffer, name, value_comm.value.name_len);
        }
 end:
        return ret;
 }
 
-int lttng_process_attr_values_serialize(
-               const struct lttng_process_attr_values *values,
-               struct lttng_dynamic_buffer *buffer)
+int lttng_process_attr_values_serialize(const struct lttng_process_attr_values *values,
+                                       struct lttng_dynamic_buffer *buffer)
 {
        int ret;
        unsigned int count, i;
@@ -312,8 +293,7 @@ int lttng_process_attr_values_serialize(
 
        for (i = 0; i < count; i++) {
                const struct process_attr_value *value =
-                               lttng_process_attr_tracker_values_get_at_index(
-                                               values, i);
+                       lttng_process_attr_tracker_values_get_at_index(values, i);
 
                ret = process_attr_tracker_value_serialize(value, buffer);
                if (ret) {
@@ -324,11 +304,10 @@ end:
        return ret;
 }
 
-ssize_t lttng_process_attr_values_create_from_buffer(
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct lttng_buffer_view *buffer_view,
-               struct lttng_process_attr_values **_values)
+ssize_t lttng_process_attr_values_create_from_buffer(enum lttng_domain_type domain,
+                                                    enum lttng_process_attr process_attr,
+                                                    const struct lttng_buffer_view *buffer_view,
+                                                    struct lttng_process_attr_values **_values)
 {
        ssize_t offset;
        unsigned int i;
@@ -341,8 +320,7 @@ ssize_t lttng_process_attr_values_create_from_buffer(
                goto error;
        }
 
-       header_view = lttng_buffer_view_from_view(
-                       buffer_view, 0, sizeof(*header));
+       header_view = lttng_buffer_view_from_view(buffer_view, 0, sizeof(*header));
        if (!lttng_buffer_view_is_valid(&header_view)) {
                goto error;
        }
@@ -354,8 +332,7 @@ ssize_t lttng_process_attr_values_create_from_buffer(
         * Check that the number of values is not absurdly large with respect to
         * the received buffer's size.
         */
-       if (buffer_view->size <
-                       header->count * sizeof(struct process_attr_tracker_value_comm)) {
+       if (buffer_view->size < header->count * sizeof(struct process_attr_tracker_value_comm)) {
                goto error;
        }
        for (i = 0; i < (unsigned int) header->count; i++) {
@@ -367,8 +344,7 @@ ssize_t lttng_process_attr_values_create_from_buffer(
                struct lttng_buffer_view value_view;
                struct lttng_buffer_view value_name_view = {};
 
-               value_view = lttng_buffer_view_from_view(
-                               buffer_view, offset, sizeof(*value_comm));
+               value_view = lttng_buffer_view_from_view(buffer_view, offset, sizeof(*value_comm));
                if (!lttng_buffer_view_is_valid(&value_view)) {
                        goto error;
                }
@@ -379,8 +355,7 @@ ssize_t lttng_process_attr_values_create_from_buffer(
 
                if (is_value_type_name(type)) {
                        value_name_view = lttng_buffer_view_from_view(
-                                       buffer_view, offset,
-                                       value_comm->value.name_len);
+                               buffer_view, offset, value_comm->value.name_len);
                        if (!lttng_buffer_view_is_valid(&value_name_view)) {
                                goto error;
                        }
@@ -388,15 +363,17 @@ ssize_t lttng_process_attr_values_create_from_buffer(
                        offset += value_name_view.size;
                }
 
-               ret_code = process_attr_value_from_comm(domain, process_attr,
-                               type, &value_comm->value.integral,
-                               &value_name_view, &value);
+               ret_code = process_attr_value_from_comm(domain,
+                                                       process_attr,
+                                                       type,
+                                                       &value_comm->value.integral,
+                                                       &value_name_view,
+                                                       &value);
                if (ret_code != LTTNG_OK) {
                        goto error;
                }
 
-               ret = lttng_dynamic_pointer_array_add_pointer(
-                               &values->array, value);
+               ret = lttng_dynamic_pointer_array_add_pointer(&values->array, value);
                if (ret) {
                        process_attr_value_destroy(value);
                        goto error;
@@ -419,10 +396,9 @@ void lttng_process_attr_values_destroy(struct lttng_process_attr_values *values)
        free(values);
 }
 
-struct process_attr_value *process_attr_value_copy(
-               const struct process_attr_value *value)
+struct process_attr_value *process_attr_value_copy(const struct process_attr_value *value)
 {
-       struct process_attr_value *new_value = NULL;
+       struct process_attr_value *new_value = nullptr;
 
        if (!value) {
                goto end;
@@ -433,13 +409,12 @@ struct process_attr_value *process_attr_value_copy(
                goto end;
        }
        if (is_value_type_name(value->type)) {
-               const char *src =
-                               value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ?
-                                               value->value.user_name :
-                                               value->value.group_name;
+               const char *src = value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ?
+                       value->value.user_name :
+                       value->value.group_name;
                char **dst = value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ?
-                                            &new_value->value.user_name :
-                                            &new_value->value.group_name;
+                       &new_value->value.user_name :
+                       &new_value->value.group_name;
 
                new_value->type = value->type;
                *dst = strdup(src);
@@ -453,7 +428,7 @@ end:
        return new_value;
 error:
        free(new_value);
-       return NULL;
+       return nullptr;
 }
 
 unsigned long process_attr_value_hash(const struct process_attr_value *a)
@@ -462,16 +437,13 @@ unsigned long process_attr_value_hash(const struct process_attr_value *a)
 
        switch (a->type) {
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_PID:
-               hash ^= hash_key_ulong((void *) (unsigned long) a->value.pid,
-                               lttng_ht_seed);
+               hash ^= hash_key_ulong((void *) (unsigned long) a->value.pid, lttng_ht_seed);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_UID:
-               hash ^= hash_key_ulong((void *) (unsigned long) a->value.uid,
-                               lttng_ht_seed);
+               hash ^= hash_key_ulong((void *) (unsigned long) a->value.uid, lttng_ht_seed);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_GID:
-               hash ^= hash_key_ulong((void *) (unsigned long) a->value.gid,
-                               lttng_ht_seed);
+               hash ^= hash_key_ulong((void *) (unsigned long) a->value.gid, lttng_ht_seed);
                break;
        case LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME:
                hash ^= hash_key_str(a->value.user_name, lttng_ht_seed);
@@ -487,7 +459,7 @@ unsigned long process_attr_value_hash(const struct process_attr_value *a)
 }
 
 bool process_attr_tracker_value_equal(const struct process_attr_value *a,
-               const struct process_attr_value *b)
+                                     const struct process_attr_value *b)
 {
        if (a->type != b->type) {
                return false;
@@ -515,8 +487,8 @@ void process_attr_value_destroy(struct process_attr_value *value)
        }
        if (is_value_type_name(value->type)) {
                free(value->type == LTTNG_PROCESS_ATTR_VALUE_TYPE_USER_NAME ?
-                                               value->value.user_name :
-                                               value->value.group_name);
+                            value->value.user_name :
+                            value->value.group_name);
        }
        free(value);
 }
index 7f4702a7d262204e215cba063221f3772d1149d9..3d6c20c3f47a74841042f74e0ad500d444302c8a 100644 (file)
@@ -9,14 +9,14 @@
 #ifndef LTTNG_COMMON_TRACKER_H
 #define LTTNG_COMMON_TRACKER_H
 
-#include <lttng/lttng-error.h>
-#include <lttng/tracker.h>
-
 #include <common/buffer-view.hpp>
 #include <common/dynamic-array.hpp>
 #include <common/macros.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
 
+#include <lttng/lttng-error.h>
+#include <lttng/tracker.h>
+
 struct process_attr_value {
        enum lttng_process_attr_value_type type;
        union value {
@@ -35,45 +35,40 @@ struct lttng_process_attr_values {
 
 const char *lttng_process_attr_to_string(enum lttng_process_attr process_attr);
 
-struct lttng_process_attr_values *lttng_process_attr_values_create(void);
+struct lttng_process_attr_values *lttng_process_attr_values_create();
 
 /* Prefixed with '_' since the name conflicts with a public API. */
-unsigned int _lttng_process_attr_values_get_count(
-               const struct lttng_process_attr_values *values);
+unsigned int _lttng_process_attr_values_get_count(const struct lttng_process_attr_values *values);
 
-const struct process_attr_value *lttng_process_attr_tracker_values_get_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index);
+const struct process_attr_value *
+lttng_process_attr_tracker_values_get_at_index(const struct lttng_process_attr_values *values,
+                                              unsigned int index);
 
-int lttng_process_attr_values_serialize(
-               const struct lttng_process_attr_values *values,
-               struct lttng_dynamic_buffer *buffer);
+int lttng_process_attr_values_serialize(const struct lttng_process_attr_values *values,
+                                       struct lttng_dynamic_buffer *buffer);
 
-ssize_t lttng_process_attr_values_create_from_buffer(
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               const struct lttng_buffer_view *buffer_view,
-               struct lttng_process_attr_values **_values);
+ssize_t lttng_process_attr_values_create_from_buffer(enum lttng_domain_type domain,
+                                                    enum lttng_process_attr process_attr,
+                                                    const struct lttng_buffer_view *buffer_view,
+                                                    struct lttng_process_attr_values **_values);
 
-void lttng_process_attr_values_destroy(
-               struct lttng_process_attr_values *values);
+void lttng_process_attr_values_destroy(struct lttng_process_attr_values *values);
 
-struct process_attr_value *process_attr_value_copy(
-               const struct process_attr_value *value);
+struct process_attr_value *process_attr_value_copy(const struct process_attr_value *value);
 
 unsigned long process_attr_value_hash(const struct process_attr_value *a);
 
 bool process_attr_tracker_value_equal(const struct process_attr_value *a,
-               const struct process_attr_value *b);
+                                     const struct process_attr_value *b);
 
 void process_attr_value_destroy(struct process_attr_value *value);
 
-enum lttng_error_code process_attr_value_from_comm(
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               enum lttng_process_attr_value_type value_type,
-               const struct process_attr_integral_value_comm *integral_value,
-               const struct lttng_buffer_view *value_view,
-               struct process_attr_value **value);
+enum lttng_error_code
+process_attr_value_from_comm(enum lttng_domain_type domain,
+                            enum lttng_process_attr process_attr,
+                            enum lttng_process_attr_value_type value_type,
+                            const struct process_attr_integral_value_comm *integral_value,
+                            const struct lttng_buffer_view *value_view,
+                            struct process_attr_value **value);
 
 #endif /* LTTNG_COMMON_TRACKER_H */
index bceeab534ae14a8113233537060fcc59b3fd92be..75892542cd090d82be20c9d53692102873e4fbaf 100644 (file)
@@ -12,7 +12,7 @@
 #include <common/optional.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
-#include <inttypes.h>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/condition/buffer-usage.h>
 #include <lttng/condition/condition-internal.hpp>
@@ -23,6 +23,8 @@
 #include <lttng/event-expr-internal.hpp>
 #include <lttng/event-rule/event-rule-internal.hpp>
 #include <lttng/trigger/trigger-internal.hpp>
+
+#include <inttypes.h>
 #include <pthread.h>
 
 bool lttng_trigger_validate(const struct lttng_trigger *trigger)
@@ -40,16 +42,15 @@ bool lttng_trigger_validate(const struct lttng_trigger *trigger)
        }
 
        valid = lttng_condition_validate(trigger->condition) &&
-                       lttng_action_validate(trigger->action);
+               lttng_action_validate(trigger->action);
 end:
        return valid;
 }
 
-struct lttng_trigger *lttng_trigger_create(
-               struct lttng_condition *condition,
-               struct lttng_action *action)
+struct lttng_trigger *lttng_trigger_create(struct lttng_condition *condition,
+                                          struct lttng_action *action)
 {
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_trigger *trigger = nullptr;
 
        if (!condition || !action) {
                goto end;
@@ -68,7 +69,7 @@ struct lttng_trigger *lttng_trigger_create(
        lttng_action_get(action);
        trigger->action = action;
 
-       pthread_mutex_init(&trigger->lock, NULL);
+       pthread_mutex_init(&trigger->lock, nullptr);
        trigger->registered = false;
 
 end:
@@ -80,16 +81,14 @@ end:
  * This API was exposed as such in 2.11. The client is not expected to call
  * lttng_condition_destroy on the returned object.
  */
-struct lttng_condition *lttng_trigger_get_condition(
-               struct lttng_trigger *trigger)
+struct lttng_condition *lttng_trigger_get_condition(struct lttng_trigger *trigger)
 {
-       return trigger ? trigger->condition : NULL;
+       return trigger ? trigger->condition : nullptr;
 }
 
-const struct lttng_condition *lttng_trigger_get_const_condition(
-               const struct lttng_trigger *trigger)
+const struct lttng_condition *lttng_trigger_get_const_condition(const struct lttng_trigger *trigger)
 {
-       return trigger ? trigger->condition : NULL;
+       return trigger ? trigger->condition : nullptr;
 }
 
 /*
@@ -97,25 +96,21 @@ const struct lttng_condition *lttng_trigger_get_const_condition(
  * This API was exposed as such in 2.11. The client is not expected to call
  * lttng_action_destroy on the returned object.
  */
-struct lttng_action *lttng_trigger_get_action(
-               struct lttng_trigger *trigger)
+struct lttng_action *lttng_trigger_get_action(struct lttng_trigger *trigger)
 {
-       return trigger ? trigger->action : NULL;
+       return trigger ? trigger->action : nullptr;
 }
 
-const struct lttng_action *lttng_trigger_get_const_action(
-               const struct lttng_trigger *trigger)
+const struct lttng_action *lttng_trigger_get_const_action(const struct lttng_trigger *trigger)
 {
-       return trigger ? trigger->action : NULL;
+       return trigger ? trigger->action : nullptr;
 }
 
 static void trigger_destroy_ref(struct urcu_ref *ref)
 {
-       struct lttng_trigger *trigger =
-                       lttng::utils::container_of(ref, &lttng_trigger::ref);
+       struct lttng_trigger *trigger = lttng::utils::container_of(ref, &lttng_trigger::ref);
        struct lttng_action *action = lttng_trigger_get_action(trigger);
-       struct lttng_condition *condition =
-                       lttng_trigger_get_condition(trigger);
+       struct lttng_condition *condition = lttng_trigger_get_condition(trigger);
 
        LTTNG_ASSERT(action);
        LTTNG_ASSERT(condition);
@@ -135,23 +130,21 @@ void lttng_trigger_destroy(struct lttng_trigger *trigger)
        lttng_trigger_put(trigger);
 }
 
-ssize_t lttng_trigger_create_from_payload(
-               struct lttng_payload_view *src_view,
-               struct lttng_trigger **_trigger)
+ssize_t lttng_trigger_create_from_payload(struct lttng_payload_view *src_view,
+                                         struct lttng_trigger **_trigger)
 {
        ssize_t ret, offset = 0, condition_size, action_size, name_size = 0;
-       struct lttng_condition *condition = NULL;
-       struct lttng_action *action = NULL;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_action *action = nullptr;
        const struct lttng_trigger_comm *trigger_comm;
-       const char *name = NULL;
+       const char *name = nullptr;
        struct lttng_credentials creds = {
                .uid = LTTNG_OPTIONAL_INIT_UNSET,
                .gid = LTTNG_OPTIONAL_INIT_UNSET,
        };
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_trigger *trigger = nullptr;
        const struct lttng_payload_view trigger_comm_view =
-                       lttng_payload_view_from_view(
-                                       src_view, 0, sizeof(*trigger_comm));
+               lttng_payload_view_from_view(src_view, 0, sizeof(*trigger_comm));
 
        if (!src_view || !_trigger) {
                ret = -1;
@@ -181,9 +174,7 @@ ssize_t lttng_trigger_create_from_payload(
        if (trigger_comm->name_length != 0) {
                /* Name. */
                const struct lttng_payload_view name_view =
-                               lttng_payload_view_from_view(
-                                               src_view, offset,
-                                               trigger_comm->name_length);
+                       lttng_payload_view_from_view(src_view, offset, trigger_comm->name_length);
 
                if (!lttng_payload_view_is_valid(&name_view)) {
                        ret = -1;
@@ -191,8 +182,8 @@ ssize_t lttng_trigger_create_from_payload(
                }
 
                name = name_view.buffer.data;
-               if (!lttng_buffer_view_contains_string(&name_view.buffer, name,
-                                   trigger_comm->name_length)) {
+               if (!lttng_buffer_view_contains_string(
+                           &name_view.buffer, name, trigger_comm->name_length)) {
                        ret = -1;
                        goto end;
                }
@@ -204,11 +195,9 @@ ssize_t lttng_trigger_create_from_payload(
        {
                /* struct lttng_condition */
                struct lttng_payload_view condition_view =
-                               lttng_payload_view_from_view(
-                                               src_view, offset, -1);
+                       lttng_payload_view_from_view(src_view, offset, -1);
 
-               condition_size = lttng_condition_create_from_payload(&condition_view,
-                               &condition);
+               condition_size = lttng_condition_create_from_payload(&condition_view, &condition);
        }
 
        if (condition_size < 0) {
@@ -220,8 +209,7 @@ ssize_t lttng_trigger_create_from_payload(
        {
                /* struct lttng_action */
                struct lttng_payload_view action_view =
-                               lttng_payload_view_from_view(
-                                       src_view, offset, -1);
+                       lttng_payload_view_from_view(src_view, offset, -1);
 
                action_size = lttng_action_create_from_payload(&action_view, &action);
        }
@@ -251,14 +239,13 @@ ssize_t lttng_trigger_create_from_payload(
         * objects.
         */
        lttng_condition_put(condition);
-       condition = NULL;
+       condition = nullptr;
 
        lttng_action_put(action);
-       action = NULL;
+       action = nullptr;
 
        if (name) {
-               const enum lttng_trigger_status status =
-                               lttng_trigger_set_name(trigger, name);
+               const enum lttng_trigger_status status = lttng_trigger_set_name(trigger, name);
 
                if (status != LTTNG_TRIGGER_STATUS_OK) {
                        ret = -1;
@@ -289,21 +276,20 @@ end:
  * Both elements are stored contiguously, see their "*_comm" structure
  * for the detailed format.
  */
-int lttng_trigger_serialize(const struct lttng_trigger *trigger,
-               struct lttng_payload *payload)
+int lttng_trigger_serialize(const struct lttng_trigger *trigger, struct lttng_payload *payload)
 {
        int ret;
        size_t header_offset, size_before_payload, size_name;
        struct lttng_trigger_comm trigger_comm = {};
        struct lttng_trigger_comm *header;
-       const struct lttng_credentials *creds = NULL;
+       const struct lttng_credentials *creds = nullptr;
 
        creds = lttng_trigger_get_credentials(trigger);
        LTTNG_ASSERT(creds);
 
        trigger_comm.uid = LTTNG_OPTIONAL_GET(creds->uid);
 
-       if (trigger->name != NULL) {
+       if (trigger->name != nullptr) {
                size_name = strlen(trigger->name) + 1;
        } else {
                size_name = 0;
@@ -314,8 +300,7 @@ int lttng_trigger_serialize(const struct lttng_trigger *trigger,
        trigger_comm.is_hidden = lttng_trigger_is_hidden(trigger);
 
        header_offset = payload->buffer.size;
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &trigger_comm,
-                       sizeof(trigger_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &trigger_comm, sizeof(trigger_comm));
        if (ret) {
                goto end;
        }
@@ -323,8 +308,7 @@ int lttng_trigger_serialize(const struct lttng_trigger *trigger,
        size_before_payload = payload->buffer.size;
 
        /* Trigger name. */
-       ret = lttng_dynamic_buffer_append(
-                       &payload->buffer, trigger->name, size_name);
+       ret = lttng_dynamic_buffer_append(&payload->buffer, trigger->name, size_name);
        if (ret) {
                goto end;
        }
@@ -346,8 +330,7 @@ end:
        return ret;
 }
 
-bool lttng_trigger_is_equal(
-               const struct lttng_trigger *a, const struct lttng_trigger *b)
+bool lttng_trigger_is_equal(const struct lttng_trigger *a, const struct lttng_trigger *b)
 {
        if (!!a->name != !!b->name) {
                /* Both must be either anonymous or named. */
@@ -367,7 +350,7 @@ bool lttng_trigger_is_equal(
        }
 
        if (!lttng_credentials_is_equal(lttng_trigger_get_credentials(a),
-                       lttng_trigger_get_credentials(b))) {
+                                       lttng_trigger_get_credentials(b))) {
                return false;
        }
 
@@ -390,10 +373,9 @@ void lttng_trigger_set_hidden(struct lttng_trigger *trigger)
        trigger->is_hidden = true;
 }
 
-enum lttng_trigger_status lttng_trigger_set_name(struct lttng_trigger *trigger,
-               const char* name)
+enum lttng_trigger_status lttng_trigger_set_name(struct lttng_trigger *trigger, const char *name)
 {
-       char *name_copy = NULL;
+       char *name_copy = nullptr;
        enum lttng_trigger_status status = LTTNG_TRIGGER_STATUS_OK;
 
        if (!trigger) {
@@ -412,13 +394,13 @@ enum lttng_trigger_status lttng_trigger_set_name(struct lttng_trigger *trigger,
        free(trigger->name);
 
        trigger->name = name_copy;
-       name_copy = NULL;
+       name_copy = nullptr;
 end:
        return status;
 }
 
-enum lttng_trigger_status lttng_trigger_get_name(
-               const struct lttng_trigger *trigger, const char **name)
+enum lttng_trigger_status lttng_trigger_get_name(const struct lttng_trigger *trigger,
+                                                const char **name)
 {
        enum lttng_trigger_status status = LTTNG_TRIGGER_STATUS_OK;
 
@@ -436,8 +418,7 @@ end:
        return status;
 }
 
-int lttng_trigger_assign_name(struct lttng_trigger *dst,
-               const struct lttng_trigger *src)
+int lttng_trigger_assign_name(struct lttng_trigger *dst, const struct lttng_trigger *src)
 {
        int ret = 0;
        enum lttng_trigger_status status;
@@ -452,8 +433,7 @@ end:
        return ret;
 }
 
-void lttng_trigger_set_tracer_token(struct lttng_trigger *trigger,
-               uint64_t token)
+void lttng_trigger_set_tracer_token(struct lttng_trigger *trigger, uint64_t token)
 {
        LTTNG_ASSERT(trigger);
        LTTNG_OPTIONAL_SET(&trigger->tracer_token, token);
@@ -466,11 +446,10 @@ uint64_t lttng_trigger_get_tracer_token(const struct lttng_trigger *trigger)
        return LTTNG_OPTIONAL_GET(trigger->tracer_token);
 }
 
-int lttng_trigger_generate_name(struct lttng_trigger *trigger,
-               uint64_t unique_id)
+int lttng_trigger_generate_name(struct lttng_trigger *trigger, uint64_t unique_id)
 {
        int ret = 0;
-       char *generated_name = NULL;
+       char *generated_name = nullptr;
 
        ret = asprintf(&generated_name, "trigger%" PRIu64 "", unique_id);
        if (ret < 0) {
@@ -497,7 +476,7 @@ void lttng_trigger_put(struct lttng_trigger *trigger)
                return;
        }
 
-       urcu_ref_put(&trigger->ref , trigger_destroy_ref);
+       urcu_ref_put(&trigger->ref, trigger_destroy_ref);
 }
 
 static void delete_trigger_array_element(void *ptr)
@@ -507,9 +486,9 @@ static void delete_trigger_array_element(void *ptr)
        lttng_trigger_put(trigger);
 }
 
-struct lttng_triggers *lttng_triggers_create(void)
+struct lttng_triggers *lttng_triggers_create()
 {
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
 
        triggers = zmalloc<lttng_triggers>();
        if (!triggers) {
@@ -522,25 +501,23 @@ end:
        return triggers;
 }
 
-struct lttng_trigger *lttng_triggers_borrow_mutable_at_index(
-               const struct lttng_triggers *triggers, unsigned int index)
+struct lttng_trigger *lttng_triggers_borrow_mutable_at_index(const struct lttng_triggers *triggers,
+                                                            unsigned int index)
 {
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_trigger *trigger = nullptr;
 
        LTTNG_ASSERT(triggers);
        if (index >= lttng_dynamic_pointer_array_get_count(&triggers->array)) {
                goto end;
        }
 
-       trigger = (struct lttng_trigger *)
-                       lttng_dynamic_pointer_array_get_pointer(
-                                       &triggers->array, index);
+       trigger = (struct lttng_trigger *) lttng_dynamic_pointer_array_get_pointer(&triggers->array,
+                                                                                  index);
 end:
        return trigger;
 }
 
-int lttng_triggers_add(
-               struct lttng_triggers *triggers, struct lttng_trigger *trigger)
+int lttng_triggers_add(struct lttng_triggers *triggers, struct lttng_trigger *trigger)
 {
        int ret;
 
@@ -569,12 +546,10 @@ int lttng_triggers_remove_hidden_triggers(struct lttng_triggers *triggers)
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        while (i < trigger_count) {
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
 
                if (lttng_trigger_is_hidden(trigger)) {
-                       ret = lttng_dynamic_pointer_array_remove_pointer(
-                                       &triggers->array, i);
+                       ret = lttng_dynamic_pointer_array_remove_pointer(&triggers->array, i);
                        if (ret) {
                                goto end;
                        }
@@ -590,13 +565,14 @@ end:
        return ret;
 }
 
-const struct lttng_trigger *lttng_triggers_get_at_index(
-               const struct lttng_triggers *triggers, unsigned int index)
+const struct lttng_trigger *lttng_triggers_get_at_index(const struct lttng_triggers *triggers,
+                                                       unsigned int index)
 {
        return lttng_triggers_borrow_mutable_at_index(triggers, index);
 }
 
-enum lttng_trigger_status lttng_triggers_get_count(const struct lttng_triggers *triggers, unsigned int *count)
+enum lttng_trigger_status lttng_triggers_get_count(const struct lttng_triggers *triggers,
+                                                  unsigned int *count)
 {
        enum lttng_trigger_status status = LTTNG_TRIGGER_STATUS_OK;
 
@@ -620,8 +596,7 @@ void lttng_triggers_destroy(struct lttng_triggers *triggers)
        free(triggers);
 }
 
-int lttng_triggers_serialize(const struct lttng_triggers *triggers,
-               struct lttng_payload *payload)
+int lttng_triggers_serialize(const struct lttng_triggers *triggers, struct lttng_payload *payload)
 {
        int ret;
        unsigned int i, count;
@@ -640,8 +615,7 @@ int lttng_triggers_serialize(const struct lttng_triggers *triggers,
        triggers_comm.count = count;
 
        /* Placeholder header; updated at the end. */
-       ret = lttng_dynamic_buffer_append(&payload->buffer, &triggers_comm,
-                       sizeof(triggers_comm));
+       ret = lttng_dynamic_buffer_append(&payload->buffer, &triggers_comm, sizeof(triggers_comm));
        if (ret) {
                goto end;
        }
@@ -649,8 +623,7 @@ int lttng_triggers_serialize(const struct lttng_triggers *triggers,
        size_before_payload = payload->buffer.size;
 
        for (i = 0; i < count; i++) {
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
 
                LTTNG_ASSERT(trigger);
 
@@ -667,14 +640,13 @@ end:
        return ret;
 }
 
-ssize_t lttng_triggers_create_from_payload(
-               struct lttng_payload_view *src_view,
-               struct lttng_triggers **triggers)
+ssize_t lttng_triggers_create_from_payload(struct lttng_payload_view *src_view,
+                                          struct lttng_triggers **triggers)
 {
        ssize_t ret, offset = 0, triggers_size = 0;
        unsigned int i;
        const struct lttng_triggers_comm *triggers_comm;
-       struct lttng_triggers *local_triggers = NULL;
+       struct lttng_triggers *local_triggers = nullptr;
 
        if (!src_view || !triggers) {
                ret = -1;
@@ -692,13 +664,12 @@ ssize_t lttng_triggers_create_from_payload(
        }
 
        for (i = 0; i < triggers_comm->count; i++) {
-               struct lttng_trigger *trigger = NULL;
+               struct lttng_trigger *trigger = nullptr;
                struct lttng_payload_view trigger_view =
-                               lttng_payload_view_from_view(src_view, offset, -1);
+                       lttng_payload_view_from_view(src_view, offset, -1);
                ssize_t trigger_size;
 
-               trigger_size = lttng_trigger_create_from_payload(
-                               &trigger_view, &trigger);
+               trigger_size = lttng_trigger_create_from_payload(&trigger_view, &trigger);
                if (trigger_size < 0) {
                        ret = trigger_size;
                        goto error;
@@ -724,7 +695,7 @@ ssize_t lttng_triggers_create_from_payload(
 
        /* Pass ownership to caller. */
        *triggers = local_triggers;
-       local_triggers = NULL;
+       local_triggers = nullptr;
 
        ret = offset;
 error:
@@ -733,14 +704,13 @@ error:
        return ret;
 }
 
-const struct lttng_credentials *lttng_trigger_get_credentials(
-               const struct lttng_trigger *trigger)
+const struct lttng_credentials *lttng_trigger_get_credentials(const struct lttng_trigger *trigger)
 {
        return &trigger->creds;
 }
 
 void lttng_trigger_set_credentials(struct lttng_trigger *trigger,
-               const struct lttng_credentials *creds)
+                                  const struct lttng_credentials *creds)
 {
        /* Triggers do not use the group id to authenticate the user. */
        LTTNG_ASSERT(creds);
@@ -748,8 +718,7 @@ void lttng_trigger_set_credentials(struct lttng_trigger *trigger,
        LTTNG_OPTIONAL_UNSET(&trigger->creds.gid);
 }
 
-enum lttng_trigger_status lttng_trigger_set_owner_uid(
-               struct lttng_trigger *trigger, uid_t uid)
+enum lttng_trigger_status lttng_trigger_set_owner_uid(struct lttng_trigger *trigger, uid_t uid)
 {
        enum lttng_trigger_status ret = LTTNG_TRIGGER_STATUS_OK;
        const uid_t euid = geteuid();
@@ -775,18 +744,18 @@ end:
        return ret;
 }
 
-enum lttng_trigger_status lttng_trigger_get_owner_uid(
-               const struct lttng_trigger *trigger, uid_t *uid)
+enum lttng_trigger_status lttng_trigger_get_owner_uid(const struct lttng_trigger *trigger,
+                                                     uid_t *uid)
 {
        enum lttng_trigger_status ret = LTTNG_TRIGGER_STATUS_OK;
-       const struct lttng_credentials *creds = NULL;
+       const struct lttng_credentials *creds = nullptr;
 
-       if (!trigger || !uid ) {
+       if (!trigger || !uid) {
                ret = LTTNG_TRIGGER_STATUS_INVALID;
                goto end;
        }
 
-       if (!trigger->creds.uid.is_set ) {
+       if (!trigger->creds.uid.is_set) {
                ret = LTTNG_TRIGGER_STATUS_UNSET;
                goto end;
        }
@@ -798,8 +767,8 @@ end:
        return ret;
 }
 
-enum lttng_domain_type lttng_trigger_get_underlying_domain_type_restriction(
-               const struct lttng_trigger *trigger)
+enum lttng_domain_type
+lttng_trigger_get_underlying_domain_type_restriction(const struct lttng_trigger *trigger)
 {
        enum lttng_domain_type type = LTTNG_DOMAIN_NONE;
        const struct lttng_event_rule *event_rule;
@@ -810,7 +779,7 @@ enum lttng_domain_type lttng_trigger_get_underlying_domain_type_restriction(
        LTTNG_ASSERT(trigger->condition);
 
        c_type = lttng_condition_get_type(trigger->condition);
-       assert (c_type != LTTNG_CONDITION_TYPE_UNKNOWN);
+       assert(c_type != LTTNG_CONDITION_TYPE_UNKNOWN);
 
        switch (c_type) {
        case LTTNG_CONDITION_TYPE_SESSION_CONSUMED_SIZE:
@@ -821,16 +790,15 @@ enum lttng_domain_type lttng_trigger_get_underlying_domain_type_restriction(
                break;
        case LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES:
                /* Return the domain of the event rule. */
-               c_status = lttng_condition_event_rule_matches_get_rule(
-                               trigger->condition, &event_rule);
+               c_status = lttng_condition_event_rule_matches_get_rule(trigger->condition,
+                                                                      &event_rule);
                LTTNG_ASSERT(c_status == LTTNG_CONDITION_STATUS_OK);
                type = lttng_event_rule_get_domain_type(event_rule);
                break;
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH:
        case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
                /* Return the domain of the channel being monitored. */
-               c_status = lttng_condition_buffer_usage_get_domain_type(
-                               trigger->condition, &type);
+               c_status = lttng_condition_buffer_usage_get_domain_type(trigger->condition, &type);
                LTTNG_ASSERT(c_status == LTTNG_CONDITION_STATUS_OK);
                break;
        default:
@@ -844,12 +812,11 @@ enum lttng_domain_type lttng_trigger_get_underlying_domain_type_restriction(
  * Generate bytecode related to the trigger.
  * On success LTTNG_OK. On error, returns lttng_error code.
  */
-enum lttng_error_code lttng_trigger_generate_bytecode(
-               struct lttng_trigger *trigger,
-               const struct lttng_credentials *creds)
+enum lttng_error_code lttng_trigger_generate_bytecode(struct lttng_trigger *trigger,
+                                                     const struct lttng_credentials *creds)
 {
        enum lttng_error_code ret;
-       struct lttng_condition *condition = NULL;
+       struct lttng_condition *condition = nullptr;
 
        condition = lttng_trigger_get_condition(trigger);
        if (!condition) {
@@ -862,21 +829,20 @@ enum lttng_error_code lttng_trigger_generate_bytecode(
        {
                struct lttng_event_rule *event_rule;
                const enum lttng_condition_status condition_status =
-                               lttng_condition_event_rule_matches_borrow_rule_mutable(
-                                               condition, &event_rule);
+                       lttng_condition_event_rule_matches_borrow_rule_mutable(condition,
+                                                                              &event_rule);
 
                LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
                /* Generate the filter bytecode. */
-               ret = lttng_event_rule_generate_filter_bytecode(
-                               event_rule, creds);
+               ret = lttng_event_rule_generate_filter_bytecode(event_rule, creds);
                if (ret != LTTNG_OK) {
                        goto end;
                }
 
                /* Generate the capture bytecode. */
                ret = lttng_condition_event_rule_matches_generate_capture_descriptor_bytecode(
-                               condition);
+                       condition);
                if (ret != LTTNG_OK) {
                        goto end;
                }
@@ -896,9 +862,9 @@ struct lttng_trigger *lttng_trigger_copy(const struct lttng_trigger *trigger)
 {
        int ret;
        struct lttng_payload copy_buffer;
-       struct lttng_condition *condition_copy = NULL;
-       struct lttng_action *action_copy = NULL;
-       struct lttng_trigger *copy = NULL;
+       struct lttng_condition *condition_copy = nullptr;
+       struct lttng_action *action_copy = nullptr;
+       struct lttng_trigger *copy = nullptr;
        enum lttng_trigger_status trigger_status;
        const char *trigger_name;
        uid_t trigger_owner_uid;
@@ -912,11 +878,9 @@ struct lttng_trigger *lttng_trigger_copy(const struct lttng_trigger *trigger)
 
        {
                struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &copy_buffer, 0, -1);
+                       lttng_payload_view_from_payload(&copy_buffer, 0, -1);
 
-               ret = lttng_condition_create_from_payload(
-                               &view, &condition_copy);
+               ret = lttng_condition_create_from_payload(&view, &condition_copy);
                if (ret < 0) {
                        goto end;
                }
@@ -931,11 +895,9 @@ struct lttng_trigger *lttng_trigger_copy(const struct lttng_trigger *trigger)
 
        {
                struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &copy_buffer, 0, -1);
+                       lttng_payload_view_from_payload(&copy_buffer, 0, -1);
 
-               ret = lttng_action_create_from_payload(
-                               &view, &action_copy);
+               ret = lttng_action_create_from_payload(&view, &action_copy);
                if (ret < 0) {
                        goto end;
                }
@@ -963,8 +925,7 @@ struct lttng_trigger *lttng_trigger_copy(const struct lttng_trigger *trigger)
                goto error_cleanup_trigger;
        }
 
-       trigger_status = lttng_trigger_get_owner_uid(
-                       trigger, &trigger_owner_uid);
+       trigger_status = lttng_trigger_get_owner_uid(trigger, &trigger_owner_uid);
        switch (trigger_status) {
        case LTTNG_TRIGGER_STATUS_OK:
                LTTNG_OPTIONAL_SET(&copy->creds.uid, trigger_owner_uid);
@@ -983,7 +944,7 @@ struct lttng_trigger *lttng_trigger_copy(const struct lttng_trigger *trigger)
 
 error_cleanup_trigger:
        lttng_trigger_destroy(copy);
-       copy = NULL;
+       copy = nullptr;
 end:
        lttng_condition_put(condition_copy);
        lttng_action_put(action_copy);
@@ -994,8 +955,7 @@ end:
 bool lttng_trigger_needs_tracer_notifier(const struct lttng_trigger *trigger)
 {
        bool needs_tracer_notifier = false;
-       const struct lttng_condition *condition =
-                       lttng_trigger_get_const_condition(trigger);
+       const struct lttng_condition *condition = lttng_trigger_get_const_condition(trigger);
 
        switch (lttng_condition_get_type(condition)) {
        case LTTNG_CONDITION_TYPE_EVENT_RULE_MATCHES:
@@ -1052,23 +1012,23 @@ void lttng_trigger_unlock(struct lttng_trigger *trigger)
        pthread_mutex_unlock(&trigger->lock);
 }
 
-enum lttng_error_code lttng_trigger_mi_serialize(const struct lttng_trigger *trigger,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks)
+enum lttng_error_code
+lttng_trigger_mi_serialize(const struct lttng_trigger *trigger,
+                          struct mi_writer *writer,
+                          const struct mi_lttng_error_query_callbacks *error_query_callbacks)
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_trigger_status trigger_status;
-       const struct lttng_condition *condition = NULL;
-       const struct lttng_action *action = NULL;
+       const struct lttng_condition *condition = nullptr;
+       const struct lttng_action *action = nullptr;
        struct lttng_dynamic_array action_path_indexes;
        uid_t owner_uid;
 
        LTTNG_ASSERT(trigger);
        LTTNG_ASSERT(writer);
 
-       lttng_dynamic_array_init(&action_path_indexes, sizeof(uint64_t), NULL);
+       lttng_dynamic_array_init(&action_path_indexes, sizeof(uint64_t), nullptr);
 
        /* Open trigger element. */
        ret = mi_lttng_writer_open_element(writer, mi_lttng_element_trigger);
@@ -1080,16 +1040,14 @@ enum lttng_error_code lttng_trigger_mi_serialize(const struct lttng_trigger *tri
        LTTNG_ASSERT(trigger_status == LTTNG_TRIGGER_STATUS_OK);
 
        /* Name. */
-       ret = mi_lttng_writer_write_element_string(
-                       writer, config_element_name, trigger->name);
+       ret = mi_lttng_writer_write_element_string(writer, config_element_name, trigger->name);
        if (ret) {
                goto mi_error;
        }
 
        /* Owner uid. */
-       ret = mi_lttng_writer_write_element_signed_int(writer,
-                       mi_lttng_element_trigger_owner_uid,
-                       (int64_t) owner_uid);
+       ret = mi_lttng_writer_write_element_signed_int(
+               writer, mi_lttng_element_trigger_owner_uid, (int64_t) owner_uid);
        if (ret) {
                goto mi_error;
        }
@@ -1097,8 +1055,7 @@ enum lttng_error_code lttng_trigger_mi_serialize(const struct lttng_trigger *tri
        /* Condition. */
        condition = lttng_trigger_get_const_condition(trigger);
        LTTNG_ASSERT(condition);
-       ret_code = lttng_condition_mi_serialize(
-                       trigger, condition, writer, error_query_callbacks);
+       ret_code = lttng_condition_mi_serialize(trigger, condition, writer, error_query_callbacks);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
@@ -1106,22 +1063,21 @@ enum lttng_error_code lttng_trigger_mi_serialize(const struct lttng_trigger *tri
        /* Action. */
        action = lttng_trigger_get_const_action(trigger);
        LTTNG_ASSERT(action);
-       ret_code = lttng_action_mi_serialize(trigger, action, writer,
-                       error_query_callbacks, &action_path_indexes);
+       ret_code = lttng_action_mi_serialize(
+               trigger, action, writer, error_query_callbacks, &action_path_indexes);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        if (error_query_callbacks && error_query_callbacks->trigger_cb) {
-               struct lttng_error_query_results *results = NULL;
+               struct lttng_error_query_results *results = nullptr;
 
                ret_code = error_query_callbacks->trigger_cb(trigger, &results);
                if (ret_code != LTTNG_OK) {
                        goto end;
                }
 
-               ret_code = lttng_error_query_results_mi_serialize(
-                               results, writer);
+               ret_code = lttng_error_query_results_mi_serialize(results, writer);
                lttng_error_query_results_destroy(results);
                if (ret_code != LTTNG_OK) {
                        goto end;
@@ -1147,10 +1103,8 @@ end:
 /* Used by qsort, which expects the semantics of strcmp(). */
 static int compare_triggers_by_name(const void *a, const void *b)
 {
-       const struct lttng_trigger *trigger_a =
-                       *((const struct lttng_trigger **) a);
-       const struct lttng_trigger *trigger_b =
-                       *((const struct lttng_trigger **) b);
+       const struct lttng_trigger *trigger_a = *((const struct lttng_trigger **) a);
+       const struct lttng_trigger *trigger_b = *((const struct lttng_trigger **) b);
        const char *name_a, *name_b;
        enum lttng_trigger_status trigger_status;
 
@@ -1164,10 +1118,10 @@ static int compare_triggers_by_name(const void *a, const void *b)
        return strcmp(name_a, name_b);
 }
 
-enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *triggers,
-               struct mi_writer *writer,
-               const struct mi_lttng_error_query_callbacks
-                               *error_query_callbacks)
+enum lttng_error_code
+lttng_triggers_mi_serialize(const struct lttng_triggers *triggers,
+                           struct mi_writer *writer,
+                           const struct mi_lttng_error_query_callbacks *error_query_callbacks)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -1182,7 +1136,7 @@ enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *t
         * Sort trigger by name to ensure an order at the MI level and ignore
         * any anonymous trigger present.
         */
-       lttng_dynamic_pointer_array_init(&sorted_triggers, NULL);
+       lttng_dynamic_pointer_array_init(&sorted_triggers, nullptr);
 
        status = lttng_triggers_get_count(triggers, &count);
        LTTNG_ASSERT(status == LTTNG_TRIGGER_STATUS_OK);
@@ -1190,8 +1144,7 @@ enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *t
        for (i = 0; i < count; i++) {
                int add_ret;
                const char *unused_name;
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
 
                status = lttng_trigger_get_name(trigger, &unused_name);
                switch (status) {
@@ -1204,8 +1157,8 @@ enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *t
                        abort();
                }
 
-               add_ret = lttng_dynamic_pointer_array_add_pointer(
-                               &sorted_triggers, (void *) trigger);
+               add_ret =
+                       lttng_dynamic_pointer_array_add_pointer(&sorted_triggers, (void *) trigger);
 
                if (add_ret) {
                        ERR("Failed to lttng_trigger to sorting array.");
@@ -1214,9 +1167,10 @@ enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *t
                }
        }
 
-       qsort(sorted_triggers.array.buffer.data, count,
-                       sizeof(struct lttng_trigger *),
-                       compare_triggers_by_name);
+       qsort(sorted_triggers.array.buffer.data,
+             count,
+             sizeof(struct lttng_trigger *),
+             compare_triggers_by_name);
 
        /* Open triggers element. */
        ret = mi_lttng_writer_open_element(writer, mi_lttng_element_triggers);
@@ -1227,9 +1181,8 @@ enum lttng_error_code lttng_triggers_mi_serialize(const struct lttng_triggers *t
 
        for (i = 0; i < lttng_dynamic_pointer_array_get_count(&sorted_triggers); i++) {
                const struct lttng_trigger *trigger =
-                               (const struct lttng_trigger *)
-                               lttng_dynamic_pointer_array_get_pointer(
-                                               &sorted_triggers, i);
+                       (const struct lttng_trigger *) lttng_dynamic_pointer_array_get_pointer(
+                               &sorted_triggers, i);
 
                lttng_trigger_mi_serialize(trigger, writer, error_query_callbacks);
        }
index 0a1b1a5a54354beb1b759a7a95d6b6953d340ed2..11ab18a98567cddcf6ca2cb3513f61009150e6cf 100644 (file)
@@ -7,6 +7,13 @@
  */
 
 #define _LGPL_SOURCE
+#include "unix.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/fd-handle.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/common.hpp>
-#include <common/compat/errno.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/fd-handle.hpp>
-
-#include "unix.hpp"
-
 /*
  * Connect to unix socket using the path name.
  */
@@ -32,8 +32,9 @@ int lttcomm_connect_unix_sock(const char *pathname)
 
        if (strlen(pathname) >= sizeof(s_un.sun_path)) {
                ERR("unix socket address (\"%s\") is longer than the platform's limit (%zu > %zu).",
-                               pathname, strlen(pathname) + 1,
-                               sizeof(s_un.sun_path));
+                   pathname,
+                   strlen(pathname) + 1,
+                   sizeof(s_un.sun_path));
                ret = -ENAMETOOLONG;
                goto error;
        }
@@ -110,8 +111,9 @@ int lttcomm_create_unix_sock(const char *pathname)
 
        if (strlen(pathname) >= sizeof(s_un.sun_path)) {
                ERR("unix socket address (\"%s\") is longer than the platform's limit (%zu > %zu).",
-                               pathname, strlen(pathname) + 1,
-                               sizeof(s_un.sun_path));
+                   pathname,
+                   strlen(pathname) + 1,
+                   sizeof(s_un.sun_path));
                ret = -ENAMETOOLONG;
                goto error;
        }
@@ -241,9 +243,8 @@ retry:
                         */
                        DIAGNOSTIC_PUSH
                        DIAGNOSTIC_IGNORE_LOGICAL_OP
-                       if (errno == EAGAIN || errno == EWOULDBLOCK ||
-                                       errno == EPIPE) {
-                       DIAGNOSTIC_POP
+                       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EPIPE) {
+                               DIAGNOSTIC_POP
                                /*
                                 * Nothing was recv.
                                 */
@@ -348,9 +349,8 @@ retry:
                         */
                        DIAGNOSTIC_PUSH
                        DIAGNOSTIC_IGNORE_LOGICAL_OP
-                       if (errno == EAGAIN || errno == EWOULDBLOCK ||
-                                       errno == EPIPE) {
-                       DIAGNOSTIC_POP
+                       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EPIPE) {
+                               DIAGNOSTIC_POP
                                /*
                                 * This can happen in non blocking mode.
                                 * Nothing was sent.
@@ -379,7 +379,16 @@ int lttcomm_close_unix_sock(int sock)
        /* Shutdown receptions and transmissions */
        ret = shutdown(sock, SHUT_RDWR);
        if (ret < 0) {
-               PERROR("shutdown");
+               /*
+                * The socket is already disconnected, don't error out.
+                * This doesn't happen on Linux, but it does on FreeBSD, see:
+                * https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=227259
+                */
+               if (errno == ENOTCONN) {
+                       ret = 0;
+               } else {
+                       PERROR("shutdown");
+               }
        }
 
        closeret = close(sock);
@@ -415,7 +424,7 @@ ssize_t lttcomm_send_fds_unix_sock(int sock, const int *fds, size_t nb_fd)
        if (nb_fd > LTTCOMM_MAX_SEND_FDS)
                return -EINVAL;
 
-       msg.msg_control = (caddr_t)tmp;
+       msg.msg_control = (caddr_t) tmp;
        msg.msg_controllen = CMSG_LEN(sizeof_fds);
 
        cmptr = CMSG_FIRSTHDR(&msg);
@@ -455,17 +464,15 @@ ssize_t lttcomm_send_fds_unix_sock(int sock, const int *fds, size_t nb_fd)
  *
  * Returns the size of data sent, or negative error value.
  */
-static
-ssize_t _lttcomm_send_payload_view_fds_unix_sock(int sock,
-               struct lttng_payload_view *view,
-               bool blocking)
+static ssize_t
+_lttcomm_send_payload_view_fds_unix_sock(int sock, struct lttng_payload_view *view, bool blocking)
 {
        int i;
        ssize_t ret;
        struct lttng_dynamic_array raw_fds;
        const int fd_count = lttng_payload_view_get_fd_handle_count(view);
 
-       lttng_dynamic_array_init(&raw_fds, sizeof(int), NULL);
+       lttng_dynamic_array_init(&raw_fds, sizeof(int), nullptr);
 
        if (fd_count < 0) {
                ret = -LTTNG_ERR_INVALID;
@@ -482,11 +489,9 @@ ssize_t _lttcomm_send_payload_view_fds_unix_sock(int sock,
         * owns a reference to the fd_handles.
         */
        for (i = 0; i < fd_count; i++) {
-               struct fd_handle *handle =
-                               lttng_payload_view_pop_fd_handle(view);
+               struct fd_handle *handle = lttng_payload_view_pop_fd_handle(view);
                const int raw_fd = fd_handle_get_fd(handle);
-               const int add_ret = lttng_dynamic_array_add_element(
-                               &raw_fds, &raw_fd);
+               const int add_ret = lttng_dynamic_array_add_element(&raw_fds, &raw_fd);
 
                fd_handle_put(handle);
                if (add_ret) {
@@ -496,11 +501,10 @@ ssize_t _lttcomm_send_payload_view_fds_unix_sock(int sock,
        }
 
        if (blocking) {
-               ret = lttcomm_send_fds_unix_sock(sock,
-                               (const int *) raw_fds.buffer.data, fd_count);
+               ret = lttcomm_send_fds_unix_sock(sock, (const int *) raw_fds.buffer.data, fd_count);
        } else {
-               ret = lttcomm_send_fds_unix_sock_non_block(sock,
-                               (const int *) raw_fds.buffer.data, fd_count);
+               ret = lttcomm_send_fds_unix_sock_non_block(
+                       sock, (const int *) raw_fds.buffer.data, fd_count);
        }
 
 end:
@@ -508,14 +512,12 @@ end:
        return ret;
 }
 
-ssize_t lttcomm_send_payload_view_fds_unix_sock(int sock,
-               struct lttng_payload_view *view)
+ssize_t lttcomm_send_payload_view_fds_unix_sock(int sock, struct lttng_payload_view *view)
 {
        return _lttcomm_send_payload_view_fds_unix_sock(sock, view, true);
 }
 
-ssize_t lttcomm_send_payload_view_fds_unix_sock_non_block(int sock,
-               struct lttng_payload_view *view)
+ssize_t lttcomm_send_payload_view_fds_unix_sock_non_block(int sock, struct lttng_payload_view *view)
 {
        return _lttcomm_send_payload_view_fds_unix_sock(sock, view, false);
 }
@@ -546,7 +548,7 @@ ssize_t lttcomm_send_fds_unix_sock_non_block(int sock, const int *fds, size_t nb
        if (nb_fd > LTTCOMM_MAX_SEND_FDS)
                return -EINVAL;
 
-       msg.msg_control = (caddr_t)tmp;
+       msg.msg_control = (caddr_t) tmp;
        msg.msg_controllen = CMSG_LEN(sizeof_fds);
 
        cmptr = CMSG_FIRSTHDR(&msg);
@@ -578,7 +580,7 @@ retry:
                        DIAGNOSTIC_PUSH
                        DIAGNOSTIC_IGNORE_LOGICAL_OP
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
-                       DIAGNOSTIC_POP
+                               DIAGNOSTIC_POP
                                /*
                                 * This can happen in non blocking mode.
                                 * Nothing was sent.
@@ -659,8 +661,7 @@ retry:
                        goto retry;
                } else {
                        /* We consider EPIPE and EAGAIN as expected. */
-                       if (!lttng_opt_quiet &&
-                                       (errno != EPIPE && errno != EAGAIN)) {
+                       if (!lttng_opt_quiet && (errno != EPIPE && errno != EAGAIN)) {
                                PERROR("recvmsg");
                        }
                        goto end;
@@ -668,8 +669,7 @@ retry:
        }
 
        if (ret != 1) {
-               fprintf(stderr, "Error: Received %zd bytes, expected %d\n",
-                               ret, 1);
+               fprintf(stderr, "Error: Received %zd bytes, expected %d\n", ret, 1);
                goto end;
        }
 
@@ -685,7 +685,7 @@ retry:
         * need to expect a cmsg of the SCM_CREDENTIALS as the first control
         * message.
         */
-       for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+       for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
                if (cmsg->cmsg_level != SOL_SOCKET) {
                        fprintf(stderr, "Error: The socket needs to be of type SOL_SOCKET\n");
                        ret = -1;
@@ -697,7 +697,8 @@ retry:
                         * now copy the fds to the fds ptr and return success.
                         */
                        if (cmsg->cmsg_len != CMSG_LEN(sizeof_fds)) {
-                               fprintf(stderr, "Error: Received %zu bytes of"
+                               fprintf(stderr,
+                                       "Error: Received %zu bytes of"
                                        "ancillary data for FDs, expected %zu\n",
                                        (size_t) cmsg->cmsg_len,
                                        (size_t) CMSG_LEN(sizeof_fds));
@@ -723,8 +724,7 @@ end:
        return ret;
 }
 
-static
-void close_raw_fd(void *ptr)
+static void close_raw_fd(void *ptr)
 {
        const int raw_fd = *((const int *) ptr);
 
@@ -737,9 +737,8 @@ void close_raw_fd(void *ptr)
        }
 }
 
-static
-enum lttng_error_code add_fds_to_payload(struct lttng_dynamic_array *raw_fds,
-               struct lttng_payload *payload)
+static enum lttng_error_code add_fds_to_payload(struct lttng_dynamic_array *raw_fds,
+                                               struct lttng_payload *payload)
 {
        int i;
        enum lttng_error_code ret_code = LTTNG_OK;
@@ -748,8 +747,7 @@ enum lttng_error_code add_fds_to_payload(struct lttng_dynamic_array *raw_fds,
        for (i = 0; i < fd_count; i++) {
                int ret;
                struct fd_handle *handle;
-               int *raw_fd = (int *) lttng_dynamic_array_get_element(
-                       raw_fds, i);
+               int *raw_fd = (int *) lttng_dynamic_array_get_element(raw_fds, i);
 
                LTTNG_ASSERT(*raw_fd != -1);
 
@@ -774,9 +772,10 @@ end:
        return ret_code;
 }
 
-static
-ssize_t _lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd,
-               struct lttng_payload *payload, bool blocking)
+static ssize_t _lttcomm_recv_payload_fds_unix_sock(int sock,
+                                                  size_t nb_fd,
+                                                  struct lttng_payload *payload,
+                                                  bool blocking)
 {
        int i = 0;
        enum lttng_error_code add_ret;
@@ -798,11 +797,10 @@ ssize_t _lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd,
        }
 
        if (blocking) {
-               ret = lttcomm_recv_fds_unix_sock(
-                               sock, (int *) raw_fds.buffer.data, nb_fd);
+               ret = lttcomm_recv_fds_unix_sock(sock, (int *) raw_fds.buffer.data, nb_fd);
        } else {
                ret = lttcomm_recv_fds_unix_sock_non_block(
-                               sock, (int *) raw_fds.buffer.data, nb_fd);
+                       sock, (int *) raw_fds.buffer.data, nb_fd);
        }
 
        if (ret <= 0) {
@@ -811,7 +809,7 @@ ssize_t _lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd,
 
        add_ret = add_fds_to_payload(&raw_fds, payload);
        if (add_ret != LTTNG_OK) {
-               ret = - (int) add_ret;
+               ret = -(int) add_ret;
                goto end;
        }
 
@@ -820,14 +818,13 @@ end:
        return ret;
 }
 
-ssize_t lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd,
-                          struct lttng_payload *payload)
+ssize_t lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd, struct lttng_payload *payload)
 {
        return _lttcomm_recv_payload_fds_unix_sock(sock, nb_fd, payload, true);
 }
 
-ssize_t lttcomm_recv_payload_fds_unix_sock_non_block(int sock, size_t nb_fd,
-                          struct lttng_payload *payload)
+ssize_t
+lttcomm_recv_payload_fds_unix_sock_non_block(int sock, size_t nb_fd, struct lttng_payload *payload)
 {
        return _lttcomm_recv_payload_fds_unix_sock(sock, nb_fd, payload, false);
 }
@@ -895,7 +892,7 @@ retry:
                        DIAGNOSTIC_PUSH
                        DIAGNOSTIC_IGNORE_LOGICAL_OP
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
-                       DIAGNOSTIC_POP
+                               DIAGNOSTIC_POP
                                /*
                                 * This can happen in non blocking mode.
                                 * Nothing was recv.
@@ -919,8 +916,7 @@ retry:
        }
 
        if (ret != 1) {
-               fprintf(stderr, "Error: Received %zd bytes, expected %d\n",
-                               ret, 1);
+               fprintf(stderr, "Error: Received %zd bytes, expected %d\n", ret, 1);
                goto end;
        }
 
@@ -936,7 +932,7 @@ retry:
         * need to expect a cmsg of the SCM_CREDENTIALS as the first control
         * message.
         */
-       for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+       for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
                if (cmsg->cmsg_level != SOL_SOCKET) {
                        fprintf(stderr, "Error: The socket needs to be of type SOL_SOCKET\n");
                        ret = -1;
@@ -948,7 +944,8 @@ retry:
                         * now copy the fds to the fds ptr and return success.
                         */
                        if (cmsg->cmsg_len != CMSG_LEN(sizeof_fds)) {
-                               fprintf(stderr, "Error: Received %zu bytes of"
+                               fprintf(stderr,
+                                       "Error: Received %zu bytes of"
                                        "ancillary data for FDs, expected %zu\n",
                                        (size_t) cmsg->cmsg_len,
                                        (size_t) CMSG_LEN(sizeof_fds));
@@ -1016,7 +1013,7 @@ ssize_t lttcomm_send_creds_unix_sock(int sock, const void *buf, size_t len)
        cmptr->cmsg_type = LTTNG_SOCK_CREDS;
        cmptr->cmsg_len = CMSG_LEN(sizeof_cred);
 
-       creds = (lttng_sock_cred*) CMSG_DATA(cmptr);
+       creds = (lttng_sock_cred *) CMSG_DATA(cmptr);
 
        LTTNG_SOCK_SET_UID_CRED(creds, geteuid());
        LTTNG_SOCK_SET_GID_CRED(creds, getegid());
@@ -1043,8 +1040,7 @@ ssize_t lttcomm_send_creds_unix_sock(int sock, const void *buf, size_t len)
  *
  * Returns the size of received data, or negative error value.
  */
-ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len,
-               lttng_sock_cred *creds)
+ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len, lttng_sock_cred *creds)
 {
        struct msghdr msg;
        struct iovec iov[1];
@@ -1054,7 +1050,7 @@ ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len,
        struct cmsghdr *cmptr;
        size_t sizeof_cred = sizeof(lttng_sock_cred);
        char anc_buf[CMSG_SPACE(sizeof_cred)];
-#endif /* __linux__, __CYGWIN__ */
+#endif /* __linux__, __CYGWIN__ */
 
        LTTNG_ASSERT(sock);
        LTTNG_ASSERT(buf);
@@ -1099,22 +1095,23 @@ ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len,
        }
 
        cmptr = CMSG_FIRSTHDR(&msg);
-       if (cmptr == NULL) {
+       if (cmptr == nullptr) {
                fprintf(stderr, "Error: Invalid control message header\n");
                ret = -1;
                goto end;
        }
 
-       if (cmptr->cmsg_level != SOL_SOCKET ||
-                       cmptr->cmsg_type != LTTNG_SOCK_CREDS) {
+       if (cmptr->cmsg_level != SOL_SOCKET || cmptr->cmsg_type != LTTNG_SOCK_CREDS) {
                fprintf(stderr, "Didn't received any credentials\n");
                ret = -1;
                goto end;
        }
 
        if (cmptr->cmsg_len != CMSG_LEN(sizeof_cred)) {
-               fprintf(stderr, "Error: Received %zu bytes of ancillary data, expected %zu\n",
-                               (size_t) cmptr->cmsg_len, (size_t) CMSG_LEN(sizeof_cred));
+               fprintf(stderr,
+                       "Error: Received %zu bytes of ancillary data, expected %zu\n",
+                       (size_t) cmptr->cmsg_len,
+                       (size_t) CMSG_LEN(sizeof_cred));
                ret = -1;
                goto end;
        }
@@ -1128,7 +1125,7 @@ ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len,
        }
 #else
 #error "Please implement credential support for your OS."
-#endif /* __linux__, __CYGWIN__ */
+#endif /* __linux__, __CYGWIN__ */
 
 end:
        return ret;
index 22ddf2edb0a177b37f676de579ee286b2cc055d6..5a4984b716b6aea960c6bd3ecc6182fd08e196df 100644 (file)
@@ -8,13 +8,13 @@
 #ifndef _LTTCOMM_UNIX_H
 #define _LTTCOMM_UNIX_H
 
-#include <limits.h>
-#include <sys/un.h>
-
 #include <common/compat/socket.hpp>
 #include <common/macros.hpp>
-#include <common/payload.hpp>
 #include <common/payload-view.hpp>
+#include <common/payload.hpp>
+
+#include <limits.h>
+#include <sys/un.h>
 
 int lttcomm_create_unix_sock(const char *pathname);
 int lttcomm_create_anon_unix_socketpair(int *fds);
@@ -25,20 +25,17 @@ int lttcomm_close_unix_sock(int sock);
 
 /* Send a message accompanied by fd(s) over a unix socket. */
 ssize_t lttcomm_send_fds_unix_sock(int sock, const int *fds, size_t nb_fd);
-ssize_t lttcomm_send_payload_view_fds_unix_sock(int sock,
-               struct lttng_payload_view *view);
-ssize_t lttcomm_send_fds_unix_sock_non_block(
-               int sock, const int *fds, size_t nb_fd);
+ssize_t lttcomm_send_payload_view_fds_unix_sock(int sock, struct lttng_payload_view *view);
+ssize_t lttcomm_send_fds_unix_sock_non_block(int sock, const int *fds, size_t nb_fd);
 ssize_t lttcomm_send_payload_view_fds_unix_sock_non_block(int sock,
-               struct lttng_payload_view *view);
+                                                         struct lttng_payload_view *view);
 
 /* Recv a message accompanied by fd(s) from a unix socket */
 ssize_t lttcomm_recv_fds_unix_sock(int sock, int *fds, size_t nb_fd);
-ssize_t lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd,
-               struct lttng_payload *payload);
+ssize_t lttcomm_recv_payload_fds_unix_sock(int sock, size_t nb_fd, struct lttng_payload *payload);
 ssize_t lttcomm_recv_fds_unix_sock_non_block(int sock, int *fds, size_t nb_fd);
-ssize_t lttcomm_recv_payload_fds_unix_sock_non_block(int sock, size_t nb_fd,
-               struct lttng_payload *payload);
+ssize_t
+lttcomm_recv_payload_fds_unix_sock_non_block(int sock, size_t nb_fd, struct lttng_payload *payload);
 
 ssize_t lttcomm_recv_unix_sock(int sock, void *buf, size_t len);
 ssize_t lttcomm_recv_unix_sock_non_block(int sock, void *buf, size_t len);
@@ -46,9 +43,8 @@ ssize_t lttcomm_send_unix_sock(int sock, const void *buf, size_t len);
 ssize_t lttcomm_send_unix_sock_non_block(int sock, const void *buf, size_t len);
 
 ssize_t lttcomm_send_creds_unix_sock(int sock, const void *buf, size_t len);
-ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len,
-               lttng_sock_cred *creds);
+ssize_t lttcomm_recv_creds_unix_sock(int sock, void *buf, size_t len, lttng_sock_cred *creds);
 
 int lttcomm_setsockopt_creds_unix_sock(int sock);
 
-#endif /* _LTTCOMM_UNIX_H */
+#endif /* _LTTCOMM_UNIX_H */
index d121ecd9f6799b62e1236a56b17d4d9f4110ba85..35bb2905c9e44cfeaf14b6e065d39696861ce8a6 100644 (file)
@@ -9,8 +9,8 @@
 #define LTTNG_URCU_H
 
 #define _LGPL_SOURCE
-#include <urcu.h>
 #include <mutex>
+#include <urcu.h>
 
 namespace lttng {
 namespace urcu {
@@ -27,10 +27,13 @@ namespace details {
 class read_lock {
 public:
        read_lock() = default;
+       ~read_lock() = default;
 
        /* "Not copyable" and "not moveable" Mutex requirements. */
-       read_lock(read_lock const &) = delete;
-       read_lock &operator=(read_lock const &) = delete;
+       read_lock(read_lock const&) = delete;
+       read_lock(read_lock&&) = delete;
+       read_lock& operator=(read_lock&&) = delete;
+       read_lock& operator=(const read_lock&) = delete;
 
        void lock()
        {
@@ -57,15 +60,17 @@ public:
  */
 class read_lock_guard {
 public:
-       read_lock_guard() : _guard(_lock)
-       {
-       }
+       read_lock_guard() = default;
+       ~read_lock_guard() = default;
 
-       read_lock_guard(const read_lock_guard &) = delete;
+       read_lock_guard(const read_lock_guard&) = delete;
+       read_lock_guard(read_lock_guard&&) = delete;
+       read_lock_guard& operator=(read_lock_guard&&) = delete;
+       read_lock_guard& operator=(const read_lock_guard&) = delete;
 
 private:
        details::read_lock _lock;
-       std::lock_guard<details::read_lock> _guard;
+       std::lock_guard<details::read_lock> _guard{ _lock };
 };
 
 using unique_read_lock = std::unique_lock<details::read_lock>;
index 3b74928b401cc469a9b2dca2f8f205b3746a1d71..af78bd35585e2ee1cb1b23f241eaf4ab31506960 100644 (file)
@@ -6,23 +6,27 @@
  */
 
 #define _LGPL_SOURCE
-#include <arpa/inet.h>
-#include <common/compat/netdb.hpp>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
+#include "uri.hpp"
 
 #include <common/common.hpp>
+#include <common/compat/netdb.hpp>
 #include <common/defaults.hpp>
 #include <common/utils.hpp>
 
-#include "uri.hpp"
+#include <arpa/inet.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
 
 #define LOOPBACK_ADDR_IPV4 "127.0.0.1"
 #define LOOPBACK_ADDR_IPV6 "::1"
 
 enum uri_proto_code {
-       P_NET, P_NET6, P_FILE, P_TCP, P_TCP6,
+       P_NET,
+       P_NET6,
+       P_FILE,
+       P_TCP,
+       P_TCP6,
 };
 
 namespace {
@@ -35,17 +39,43 @@ struct uri_proto {
 };
 
 /* Supported protocols */
-const struct uri_proto proto_uri[] = {
-       { .name = "file", .leading_string = "file://", .code = P_FILE, .type = LTTNG_PROTO_TYPE_NONE, .dtype = LTTNG_DST_PATH },
-       { .name = "net", .leading_string = "net://", .code = P_NET, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV4 },
-       { .name = "net4", .leading_string = "net4://", .code = P_NET, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV4 },
-       { .name = "net6", .leading_string = "net6://", .code = P_NET6, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV6 },
-       { .name = "tcp", .leading_string = "tcp://", .code = P_TCP, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV4 },
-       { .name = "tcp4", .leading_string = "tcp4://", .code = P_TCP, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV4 },
-       { .name = "tcp6", .leading_string = "tcp6://", .code = P_TCP6, .type = LTTNG_TCP, .dtype = LTTNG_DST_IPV6 },
-       /* Invalid proto marking the end of the array. */
-       {}
-};
+const struct uri_proto proto_uri[] = { { .name = "file",
+                                        .leading_string = "file://",
+                                        .code = P_FILE,
+                                        .type = LTTNG_PROTO_TYPE_NONE,
+                                        .dtype = LTTNG_DST_PATH },
+                                      { .name = "net",
+                                        .leading_string = "net://",
+                                        .code = P_NET,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV4 },
+                                      { .name = "net4",
+                                        .leading_string = "net4://",
+                                        .code = P_NET,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV4 },
+                                      { .name = "net6",
+                                        .leading_string = "net6://",
+                                        .code = P_NET6,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV6 },
+                                      { .name = "tcp",
+                                        .leading_string = "tcp://",
+                                        .code = P_TCP,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV4 },
+                                      { .name = "tcp4",
+                                        .leading_string = "tcp4://",
+                                        .code = P_TCP,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV4 },
+                                      { .name = "tcp6",
+                                        .leading_string = "tcp6://",
+                                        .code = P_TCP6,
+                                        .type = LTTNG_TCP,
+                                        .dtype = LTTNG_DST_IPV6 },
+                                      /* Invalid proto marking the end of the array. */
+                                      {} };
 } /* namespace */
 
 /*
@@ -55,7 +85,7 @@ const struct uri_proto proto_uri[] = {
 static inline const char *strpbrk_or_eos(const char *s, const char *accept)
 {
        char *p = (char *) strpbrk(s, accept);
-       if (p == NULL) {
+       if (p == nullptr) {
                p = (char *) strchr(s, '\0');
        }
 
@@ -67,23 +97,23 @@ static inline const char *strpbrk_or_eos(const char *s, const char *accept)
  */
 static const struct uri_proto *get_uri_proto(const char *uri_str)
 {
-       const struct uri_proto *supported = NULL;
+       const struct uri_proto *supported = nullptr;
 
        /* Safety net */
-       if (uri_str == NULL) {
+       if (uri_str == nullptr) {
                goto end;
        }
 
-       for (supported = &proto_uri[0];
-                       supported->leading_string != NULL; ++supported) {
-               if (strncasecmp(uri_str, supported->leading_string,
-                                       strlen(supported->leading_string)) == 0) {
+       for (supported = &proto_uri[0]; supported->leading_string != nullptr; ++supported) {
+               if (strncasecmp(uri_str,
+                               supported->leading_string,
+                               strlen(supported->leading_string)) == 0) {
                        goto end;
                }
        }
 
        /* Proto not found */
-       return NULL;
+       return nullptr;
 
 end:
        return supported;
@@ -115,8 +145,7 @@ static int set_ip_address(const char *addr, int af, char *dst, size_t size)
                                PERROR("inet_ntop");
                                goto error;
                        }
-               } else if (!strcmp(addr, "localhost") &&
-                               (af == AF_INET || af == AF_INET6)) {
+               } else if (!strcmp(addr, "localhost") && (af == AF_INET || af == AF_INET6)) {
                        /*
                         * Some systems may not have "localhost" defined in
                         * accordance with IETF RFC 6761. According to this RFC,
@@ -130,11 +159,11 @@ static int set_ip_address(const char *addr, int af, char *dst, size_t size)
                         * done to accommodates systems which may want to start
                         * tracing before their network configured.
                         */
-                       const char *loopback_addr = af == AF_INET ?
-                                       LOOPBACK_ADDR_IPV4 : LOOPBACK_ADDR_IPV6;
+                       const char *loopback_addr = af == AF_INET ? LOOPBACK_ADDR_IPV4 :
+                                                                   LOOPBACK_ADDR_IPV6;
                        const size_t loopback_addr_len = af == AF_INET ?
-                                       sizeof(LOOPBACK_ADDR_IPV4) :
-                                       sizeof(LOOPBACK_ADDR_IPV6);
+                               sizeof(LOOPBACK_ADDR_IPV4) :
+                               sizeof(LOOPBACK_ADDR_IPV6);
 
                        DBG2("Could not resolve localhost address, using fallback");
                        if (loopback_addr_len > size) {
@@ -165,13 +194,12 @@ error:
  * Set default URI attribute which is basically the given stream type and the
  * default port if none is set in the URI.
  */
-static void set_default_uri_attr(struct lttng_uri *uri,
-               enum lttng_stream_type stype)
+static void set_default_uri_attr(struct lttng_uri *uri, enum lttng_stream_type stype)
 {
        uri->stype = stype;
        if (uri->dtype != LTTNG_DST_PATH && uri->port == 0) {
-               uri->port = (stype == LTTNG_STREAM_CONTROL) ?
-                       DEFAULT_NETWORK_CONTROL_PORT : DEFAULT_NETWORK_DATA_PORT;
+               uri->port = (stype == LTTNG_STREAM_CONTROL) ? DEFAULT_NETWORK_CONTROL_PORT :
+                                                             DEFAULT_NETWORK_DATA_PORT;
        }
 }
 
@@ -221,14 +249,20 @@ int uri_to_str_url(struct lttng_uri *uri, char *dst, size_t size)
                (void) snprintf(port, sizeof(port), "%s", "");
        } else {
                ipver = (uri->dtype == LTTNG_DST_IPV4) ? 4 : 6;
-               addr = (ipver == 4) ?  uri->dst.ipv4 : uri->dst.ipv6;
+               addr = (ipver == 4) ? uri->dst.ipv4 : uri->dst.ipv6;
                (void) snprintf(proto, sizeof(proto), "tcp%d", ipver);
                (void) snprintf(port, sizeof(port), ":%d", uri->port);
        }
 
-       ret = snprintf(dst, size, "%s://%s%s%s%s/%s", proto,
-                       (ipver == 6) ? "[" : "", addr, (ipver == 6) ? "]" : "",
-                       port, uri->subdir);
+       ret = snprintf(dst,
+                      size,
+                      "%s://%s%s%s%s/%s",
+                      proto,
+                      (ipver == 6) ? "[" : "",
+                      addr,
+                      (ipver == 6) ? "]" : "",
+                      port,
+                      uri->subdir);
        if (ret < 0) {
                PERROR("snprintf uri to url");
        }
@@ -279,9 +313,9 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
        unsigned int ctrl_port = 0;
        unsigned int data_port = 0;
        struct lttng_uri *tmp_uris;
-       char *addr_f = NULL;
+       char *addr_f = nullptr;
        const struct uri_proto *proto;
-       const char *purl, *addr_e, *addr_b, *subdir_b = NULL;
+       const char *purl, *addr_e, *addr_b, *subdir_b = nullptr;
        const char *seps = ":/\0";
 
        /*
@@ -295,7 +329,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
        DBG3("URI string: %s", str_uri);
 
        proto = get_uri_proto(str_uri);
-       if (proto == NULL) {
+       if (proto == nullptr) {
                ERR("URI parse unknown protocol %s", str_uri);
                goto error;
        }
@@ -309,7 +343,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
 
        /* Allocate URI array */
        tmp_uris = calloc<lttng_uri>(size);
-       if (tmp_uris == NULL) {
+       if (tmp_uris == nullptr) {
                PERROR("zmalloc uri");
                goto error;
        }
@@ -348,7 +382,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                /* Address begins after '[' */
                addr_b = purl + 1;
                addr_e = strchr(addr_b, ']');
-               if (addr_e == NULL || addr_b == addr_e) {
+               if (addr_e == nullptr || addr_b == addr_e) {
                        ERR("Broken IPv6 address %s", addr_b);
                        goto free_error;
                }
@@ -359,7 +393,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                /*
                 * The closing bracket must be followed by a seperator or NULL char.
                 */
-               if (strchr(seps, *purl) == NULL) {
+               if (strchr(seps, *purl) == nullptr) {
                        ERR("Unknown symbol after IPv6 address: %s", purl);
                        goto free_error;
                }
@@ -375,7 +409,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
        }
 
        addr_f = utils_strdupdelim(addr_b, addr_e);
-       if (addr_f == NULL) {
+       if (addr_f == nullptr) {
                goto free_error;
        }
 
@@ -394,8 +428,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                 * Maximum of two ports is possible if P_NET/NET6. Bigger than that,
                 * two much stuff.
                 */
-               if ((i == 2 && (proto->code != P_NET && proto->code != P_NET6))
-                               || i > 2) {
+               if ((i == 2 && (proto->code != P_NET && proto->code != P_NET6)) || i > 2) {
                        break;
                }
 
@@ -413,7 +446,7 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                        int port;
 
                        port_f = utils_strdupdelim(port_b, port_e);
-                       if (port_f == NULL) {
+                       if (port_f == nullptr) {
                                goto free_error;
                        }
 
@@ -460,8 +493,8 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
 
        switch (proto->code) {
        case P_NET:
-               ret = set_ip_address(addr_f, AF_INET, tmp_uris[0].dst.ipv4,
-                               sizeof(tmp_uris[0].dst.ipv4));
+               ret = set_ip_address(
+                       addr_f, AF_INET, tmp_uris[0].dst.ipv4, sizeof(tmp_uris[0].dst.ipv4));
                if (ret < 0) {
                        goto free_error;
                }
@@ -473,8 +506,8 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                tmp_uris[1].port = data_port;
                break;
        case P_NET6:
-               ret = set_ip_address(addr_f, AF_INET6, tmp_uris[0].dst.ipv6,
-                               sizeof(tmp_uris[0].dst.ipv6));
+               ret = set_ip_address(
+                       addr_f, AF_INET6, tmp_uris[0].dst.ipv6, sizeof(tmp_uris[0].dst.ipv6));
                if (ret < 0) {
                        goto free_error;
                }
@@ -486,15 +519,15 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
                tmp_uris[1].port = data_port;
                break;
        case P_TCP:
-               ret = set_ip_address(addr_f, AF_INET, tmp_uris[0].dst.ipv4,
-                               sizeof(tmp_uris[0].dst.ipv4));
+               ret = set_ip_address(
+                       addr_f, AF_INET, tmp_uris[0].dst.ipv4, sizeof(tmp_uris[0].dst.ipv4));
                if (ret < 0) {
                        goto free_error;
                }
                break;
        case P_TCP6:
-               ret = set_ip_address(addr_f, AF_INET6, tmp_uris[0].dst.ipv6,
-                               sizeof(tmp_uris[0].dst.ipv6));
+               ret = set_ip_address(
+                       addr_f, AF_INET6, tmp_uris[0].dst.ipv6, sizeof(tmp_uris[0].dst.ipv6));
                if (ret < 0) {
                        goto free_error;
                }
@@ -505,8 +538,12 @@ ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris)
 
 end:
        DBG3("URI dtype: %d, proto: %d, host: %s, subdir: %s, ctrl: %d, data: %d",
-                       proto->dtype, proto->type, (addr_f == NULL) ? "" : addr_f,
-                       (subdir_b == NULL) ? "" : subdir_b, ctrl_port, data_port);
+            proto->dtype,
+            proto->type,
+            (addr_f == NULL) ? "" : addr_f,
+            (subdir_b == NULL) ? "" : subdir_b,
+            ctrl_port,
+            data_port);
 
        free(addr_f);
 
@@ -525,18 +562,17 @@ error:
  * Parse a string URL and creates URI(s) returning the size of the populated
  * array.
  */
-ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
-               struct lttng_uri **uris)
+ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url, struct lttng_uri **uris)
 {
        unsigned int equal = 1, idx = 0;
        /* Add the "file://" size to the URL maximum size */
        char url[PATH_MAX + 7];
        ssize_t ctrl_uri_count = 0, data_uri_count = 0, uri_count;
-       struct lttng_uri *ctrl_uris = NULL, *data_uris = NULL;
-       struct lttng_uri *tmp_uris = NULL;
+       struct lttng_uri *ctrl_uris = nullptr, *data_uris = nullptr;
+       struct lttng_uri *tmp_uris = nullptr;
 
        /* No URL(s) is allowed. This means that the consumer will be disabled. */
-       if (ctrl_url == NULL && data_url == NULL) {
+       if (ctrl_url == nullptr && data_url == nullptr) {
                return 0;
        }
 
@@ -561,7 +597,6 @@ ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
                } else if (ret >= sizeof(url)) {
                        PERROR("snprintf file url is too long");
                        goto parse_error;
-
                }
                ctrl_url = url;
        }
@@ -580,8 +615,7 @@ ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
                /* At this point, we know there is at least one URI in the array */
                set_default_uri_attr(&ctrl_uris[0], LTTNG_STREAM_CONTROL);
 
-               if (ctrl_uris[0].dtype == LTTNG_DST_PATH &&
-                               (data_url && *data_url != '\0')) {
+               if (ctrl_uris[0].dtype == LTTNG_DST_PATH && (data_url && *data_url != '\0')) {
                        ERR("Cannot have a data URL when destination is file://");
                        goto error;
                }
@@ -590,7 +624,7 @@ ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
                if (ctrl_uri_count == 2) {
                        if (!equal) {
                                ERR("Control URL uses the net:// protocol and the data URL is "
-                                               "different. Not allowed.");
+                                   "different. Not allowed.");
                                goto error;
                        } else {
                                set_default_uri_attr(&ctrl_uris[1], LTTNG_STREAM_DATA);
@@ -598,7 +632,7 @@ ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
                                 * The data_url and ctrl_url are equal and the ctrl_url
                                 * contains a net:// protocol so we just skip the data part.
                                 */
-                               data_url = NULL;
+                               data_url = nullptr;
                        }
                }
        }
@@ -637,7 +671,7 @@ ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
        }
 
        tmp_uris = calloc<lttng_uri>(uri_count);
-       if (tmp_uris == NULL) {
+       if (tmp_uris == nullptr) {
                PERROR("zmalloc uris");
                goto error;
        }
index fe5c02afd2b7efbf554e71175678732c99e4fecc..7cc352943fa0f2dded7ea6a77fca49bb5c45de1b 100644 (file)
@@ -8,20 +8,22 @@
 #ifndef URI_H
 #define URI_H
 
-#include <netinet/in.h>
-#include <lttng/lttng.h>
 #include <common/macros.hpp>
 
+#include <lttng/lttng.h>
+
+#include <netinet/in.h>
+
 /* Destination type of lttng URI */
 enum lttng_dst_type {
-       LTTNG_DST_IPV4                        = 1,
-       LTTNG_DST_IPV6                        = 2,
-       LTTNG_DST_PATH                        = 3,
+       LTTNG_DST_IPV4 = 1,
+       LTTNG_DST_IPV6 = 2,
+       LTTNG_DST_PATH = 3,
 };
 
 /* Type of lttng URI where it is a final destination or a hop */
 enum lttng_uri_type {
-       LTTNG_URI_DST,  /* The URI is a final destination */
+       LTTNG_URI_DST, /* The URI is a final destination */
        /*
         * Hops are not supported yet but planned for a future release.
         *
@@ -40,8 +42,8 @@ enum lttng_stream_type {
  * should be ignored.
  */
 enum lttng_proto_type {
-       LTTNG_PROTO_TYPE_NONE                 = 0,
-       LTTNG_TCP                             = 1,
+       LTTNG_PROTO_TYPE_NONE = 0,
+       LTTNG_TCP = 1,
        /*
         * UDP protocol is not supported for now.
         *
@@ -69,8 +71,7 @@ struct lttng_uri {
 int uri_compare(struct lttng_uri *uri1, struct lttng_uri *uri2);
 void uri_free(struct lttng_uri *uri);
 ssize_t uri_parse(const char *str_uri, struct lttng_uri **uris);
-ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url,
-               struct lttng_uri **uris);
+ssize_t uri_parse_str_urls(const char *ctrl_url, const char *data_url, struct lttng_uri **uris);
 int uri_to_str_url(struct lttng_uri *uri, char *dst, size_t size);
 
 #endif /* _LTT_URI_H */
index 9798b12c46236b56f2879f53db888c22748e0015..4a9c31812b75909769121c12edcf60e1571d6f6f 100644 (file)
@@ -6,8 +6,9 @@
  */
 
 #include "lttng/lttng-error.h"
-#include <common/compat/string.hpp>
+
 #include <common/align.hpp>
+#include <common/compat/string.hpp>
 #include <common/error.hpp>
 #include <common/hashtable/hashtable.hpp>
 #include <common/hashtable/utils.hpp>
 #include <common/mi-lttng.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
-#include <fcntl.h>
+
 #include <lttng/constant.h>
 #include <lttng/userspace-probe-internal.hpp>
+
+#include <fcntl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-static
-int lttng_userspace_probe_location_function_set_binary_fd_handle(
-               struct lttng_userspace_probe_location *location,
-               struct fd_handle *binary_fd_handle);
+static int lttng_userspace_probe_location_function_set_binary_fd_handle(
+       struct lttng_userspace_probe_location *location, struct fd_handle *binary_fd_handle);
 
-static
-int lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
-               struct lttng_userspace_probe_location *location,
-               struct fd_handle *binary_fd_handle);
+static int lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
+       struct lttng_userspace_probe_location *location, struct fd_handle *binary_fd_handle);
 
-static
-enum lttng_error_code lttng_userspace_probe_location_lookup_method_mi_serialize(
-               const struct lttng_userspace_probe_location_lookup_method
-                               *method,
-               struct mi_writer *writer);
+static enum lttng_error_code lttng_userspace_probe_location_lookup_method_mi_serialize(
+       const struct lttng_userspace_probe_location_lookup_method *method,
+       struct mi_writer *writer);
 
-static
-enum lttng_error_code lttng_userspace_probe_location_tracepoint_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer);
+static enum lttng_error_code lttng_userspace_probe_location_tracepoint_mi_serialize(
+       const struct lttng_userspace_probe_location *location, struct mi_writer *writer);
 
-static
-enum lttng_error_code lttng_userspace_probe_location_function_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer);
+static enum lttng_error_code lttng_userspace_probe_location_function_mi_serialize(
+       const struct lttng_userspace_probe_location *location, struct mi_writer *writer);
 
 enum lttng_userspace_probe_location_lookup_method_type
 lttng_userspace_probe_location_lookup_method_get_type(
-               const struct lttng_userspace_probe_location_lookup_method *lookup_method)
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
        return lookup_method ? lookup_method->type :
-               LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_UNKNOWN;
+                              LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_UNKNOWN;
 }
 
 void lttng_userspace_probe_location_lookup_method_destroy(
-               struct lttng_userspace_probe_location_lookup_method *lookup_method)
+       struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
-       if (!lookup_method){
+       if (!lookup_method) {
                return;
        }
 
@@ -69,7 +62,7 @@ void lttng_userspace_probe_location_lookup_method_destroy(
 struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_lookup_method_function_elf_create(void)
 {
-       struct lttng_userspace_probe_location_lookup_method *ret = NULL;
+       struct lttng_userspace_probe_location_lookup_method *ret = nullptr;
        struct lttng_userspace_probe_location_lookup_method_elf *elf_method;
 
        elf_method = zmalloc<lttng_userspace_probe_location_lookup_method_elf>();
@@ -87,7 +80,7 @@ end:
 struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_lookup_method_tracepoint_sdt_create(void)
 {
-       struct lttng_userspace_probe_location_lookup_method *ret = NULL;
+       struct lttng_userspace_probe_location_lookup_method *ret = nullptr;
        struct lttng_userspace_probe_location_lookup_method_sdt *sdt_method;
 
        sdt_method = zmalloc<lttng_userspace_probe_location_lookup_method_sdt>();
@@ -102,23 +95,21 @@ end:
        return ret;
 }
 
-enum lttng_userspace_probe_location_type lttng_userspace_probe_location_get_type(
-               const struct lttng_userspace_probe_location *location)
+enum lttng_userspace_probe_location_type
+lttng_userspace_probe_location_get_type(const struct lttng_userspace_probe_location *location)
 {
-       return location ? location->type :
-               LTTNG_USERSPACE_PROBE_LOCATION_TYPE_UNKNOWN;
+       return location ? location->type : LTTNG_USERSPACE_PROBE_LOCATION_TYPE_UNKNOWN;
 }
 
-static
-void lttng_userspace_probe_location_function_destroy(
-               struct lttng_userspace_probe_location *location)
+static void
+lttng_userspace_probe_location_function_destroy(struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location_function *location_function = NULL;
+       struct lttng_userspace_probe_location_function *location_function = nullptr;
 
        LTTNG_ASSERT(location);
 
-       location_function = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_function::parent);
+       location_function = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
 
        LTTNG_ASSERT(location_function);
 
@@ -128,16 +119,15 @@ void lttng_userspace_probe_location_function_destroy(
        free(location);
 }
 
-static
-void lttng_userspace_probe_location_tracepoint_destroy(
-               struct lttng_userspace_probe_location *location)
+static void
+lttng_userspace_probe_location_tracepoint_destroy(struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location_tracepoint *location_tracepoint = NULL;
+       struct lttng_userspace_probe_location_tracepoint *location_tracepoint = nullptr;
 
        LTTNG_ASSERT(location);
 
-       location_tracepoint = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_tracepoint::parent);
+       location_tracepoint = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
 
        LTTNG_ASSERT(location_tracepoint);
 
@@ -148,15 +138,13 @@ void lttng_userspace_probe_location_tracepoint_destroy(
        free(location);
 }
 
-void lttng_userspace_probe_location_destroy(
-               struct lttng_userspace_probe_location *location)
+void lttng_userspace_probe_location_destroy(struct lttng_userspace_probe_location *location)
 {
        if (!location) {
                return;
        }
 
-       lttng_userspace_probe_location_lookup_method_destroy(
-                       location->lookup_method);
+       lttng_userspace_probe_location_lookup_method_destroy(location->lookup_method);
 
        switch (location->type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
@@ -198,34 +186,30 @@ static bool fd_is_equal(int a, int b)
        /* Both are valid file descriptors. */
        ret = fstat(a, &a_stat);
        if (ret) {
-               PERROR("Failed to fstat userspace probe location binary fd %d",
-                               a);
+               PERROR("Failed to fstat userspace probe location binary fd %d", a);
                goto end;
        }
 
        ret = fstat(b, &b_stat);
        if (ret) {
-               PERROR("Failed to fstat userspace probe location binary fd %d",
-                               b);
+               PERROR("Failed to fstat userspace probe location binary fd %d", b);
                goto end;
        }
 
-       is_equal = (a_stat.st_ino == b_stat.st_ino) &&
-                       (a_stat.st_dev == b_stat.st_dev);
+       is_equal = (a_stat.st_ino == b_stat.st_ino) && (a_stat.st_dev == b_stat.st_dev);
 
 end:
        return is_equal;
 }
 
-static unsigned long lttng_userspace_probe_location_function_hash(
-               const struct lttng_userspace_probe_location *location)
+static unsigned long
+lttng_userspace_probe_location_function_hash(const struct lttng_userspace_probe_location *location)
 {
-       unsigned long hash = hash_key_ulong(
-                       (void *) LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION,
-                       lttng_ht_seed);
+       unsigned long hash = hash_key_ulong((void *) LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION,
+                                           lttng_ht_seed);
        struct lttng_userspace_probe_location_function *function_location =
-                       lttng::utils::container_of(
-                                       location, &lttng_userspace_probe_location_function::parent);
+               lttng::utils::container_of(location,
+                                          &lttng_userspace_probe_location_function::parent);
 
        hash ^= hash_key_str(function_location->function_name, lttng_ht_seed);
        hash ^= hash_key_str(function_location->binary_path, lttng_ht_seed);
@@ -236,17 +220,15 @@ static unsigned long lttng_userspace_probe_location_function_hash(
        return hash;
 }
 
-static bool lttng_userspace_probe_location_function_is_equal(
-               const struct lttng_userspace_probe_location *_a,
-               const struct lttng_userspace_probe_location *_b)
+static bool
+lttng_userspace_probe_location_function_is_equal(const struct lttng_userspace_probe_location *_a,
+                                                const struct lttng_userspace_probe_location *_b)
 {
        bool is_equal = false;
        struct lttng_userspace_probe_location_function *a, *b;
 
-       a = lttng::utils::container_of(_a,
-                       &lttng_userspace_probe_location_function::parent);
-       b = lttng::utils::container_of(_b,
-                       &lttng_userspace_probe_location_function::parent);
+       a = lttng::utils::container_of(_a, &lttng_userspace_probe_location_function::parent);
+       b = lttng::utils::container_of(_b, &lttng_userspace_probe_location_function::parent);
 
        if (a->instrumentation_type != b->instrumentation_type) {
                goto end;
@@ -254,32 +236,33 @@ static bool lttng_userspace_probe_location_function_is_equal(
 
        LTTNG_ASSERT(a->function_name);
        LTTNG_ASSERT(b->function_name);
-       if (strcmp(a->function_name, b->function_name)) {
+       if (strcmp(a->function_name, b->function_name) != 0) {
                goto end;
        }
 
        LTTNG_ASSERT(a->binary_path);
        LTTNG_ASSERT(b->binary_path);
-       if (strcmp(a->binary_path, b->binary_path)) {
+       if (strcmp(a->binary_path, b->binary_path) != 0) {
                goto end;
        }
 
        is_equal = fd_is_equal(a->binary_fd_handle ? fd_handle_get_fd(a->binary_fd_handle) : -1,
-                       b->binary_fd_handle ? fd_handle_get_fd(b->binary_fd_handle) : -1);
+                              b->binary_fd_handle ? fd_handle_get_fd(b->binary_fd_handle) : -1);
 end:
        return is_equal;
 }
 
 static struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_function_create_no_check(const char *binary_path,
-               const char *function_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method,
-               bool open_binary)
+lttng_userspace_probe_location_function_create_no_check(
+       const char *binary_path,
+       const char *function_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method,
+       bool open_binary)
 {
        int binary_fd = -1;
-       struct fd_handle *binary_fd_handle = NULL;
-       char *function_name_copy = NULL, *binary_path_copy = NULL;
-       struct lttng_userspace_probe_location *ret = NULL;
+       struct fd_handle *binary_fd_handle = nullptr;
+       char *function_name_copy = nullptr, *binary_path_copy = nullptr;
+       struct lttng_userspace_probe_location *ret = nullptr;
        struct lttng_userspace_probe_location_function *location;
 
        if (open_binary) {
@@ -319,9 +302,9 @@ lttng_userspace_probe_location_function_create_no_check(const char *binary_path,
        location->function_name = function_name_copy;
        location->binary_path = binary_path_copy;
        location->binary_fd_handle = binary_fd_handle;
-       binary_fd_handle = NULL;
+       binary_fd_handle = nullptr;
        location->instrumentation_type =
-                       LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY;
+               LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY;
 
        ret = &location->parent;
        ret->lookup_method = lookup_method;
@@ -344,13 +327,12 @@ end:
 }
 
 static unsigned long lttng_userspace_probe_location_tracepoint_hash(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       unsigned long hash = hash_key_ulong(
-                       (void *) LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT,
-                       lttng_ht_seed);
+       unsigned long hash = hash_key_ulong((void *) LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT,
+                                           lttng_ht_seed);
        struct lttng_userspace_probe_location_tracepoint *tp_location = lttng::utils::container_of(
-                       location, &lttng_userspace_probe_location_tracepoint::parent);
+               location, &lttng_userspace_probe_location_tracepoint::parent);
 
        hash ^= hash_key_str(tp_location->probe_name, lttng_ht_seed);
        hash ^= hash_key_str(tp_location->provider_name, lttng_ht_seed);
@@ -362,55 +344,55 @@ static unsigned long lttng_userspace_probe_location_tracepoint_hash(
        return hash;
 }
 
-static bool lttng_userspace_probe_location_tracepoint_is_equal(
-               const struct lttng_userspace_probe_location *_a,
-               const struct lttng_userspace_probe_location *_b)
+static bool
+lttng_userspace_probe_location_tracepoint_is_equal(const struct lttng_userspace_probe_location *_a,
+                                                  const struct lttng_userspace_probe_location *_b)
 {
        bool is_equal = false;
        struct lttng_userspace_probe_location_tracepoint *a, *b;
 
-       a = lttng::utils::container_of(_a,
-                       &lttng_userspace_probe_location_tracepoint::parent);
-       b = lttng::utils::container_of(_b,
-                       &lttng_userspace_probe_location_tracepoint::parent);
+       a = lttng::utils::container_of(_a, &lttng_userspace_probe_location_tracepoint::parent);
+       b = lttng::utils::container_of(_b, &lttng_userspace_probe_location_tracepoint::parent);
 
        LTTNG_ASSERT(a->probe_name);
        LTTNG_ASSERT(b->probe_name);
-       if (strcmp(a->probe_name, b->probe_name)) {
+       if (strcmp(a->probe_name, b->probe_name) != 0) {
                goto end;
        }
 
        LTTNG_ASSERT(a->provider_name);
        LTTNG_ASSERT(b->provider_name);
-       if (strcmp(a->provider_name, b->provider_name)) {
+       if (strcmp(a->provider_name, b->provider_name) != 0) {
                goto end;
        }
 
        LTTNG_ASSERT(a->binary_path);
        LTTNG_ASSERT(b->binary_path);
-       if (strcmp(a->binary_path, b->binary_path)) {
+       if (strcmp(a->binary_path, b->binary_path) != 0) {
                goto end;
        }
 
        is_equal = fd_is_equal(a->binary_fd_handle ? fd_handle_get_fd(a->binary_fd_handle) : -1,
-                       b->binary_fd_handle ? fd_handle_get_fd(b->binary_fd_handle) : -1);
+                              b->binary_fd_handle ? fd_handle_get_fd(b->binary_fd_handle) : -1);
 
 end:
        return is_equal;
 }
 
 static struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_tracepoint_create_no_check(const char *binary_path,
-               const char *provider_name, const char *probe_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method,
-               bool open_binary)
+lttng_userspace_probe_location_tracepoint_create_no_check(
+       const char *binary_path,
+       const char *provider_name,
+       const char *probe_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method,
+       bool open_binary)
 {
        int binary_fd = -1;
-       struct fd_handle *binary_fd_handle = NULL;
-       char *probe_name_copy = NULL;
-       char *provider_name_copy = NULL;
-       char *binary_path_copy = NULL;
-       struct lttng_userspace_probe_location *ret = NULL;
+       struct fd_handle *binary_fd_handle = nullptr;
+       char *probe_name_copy = nullptr;
+       char *provider_name_copy = nullptr;
+       char *binary_path_copy = nullptr;
+       struct lttng_userspace_probe_location *ret = nullptr;
        struct lttng_userspace_probe_location_tracepoint *location;
 
        if (open_binary) {
@@ -457,7 +439,7 @@ lttng_userspace_probe_location_tracepoint_create_no_check(const char *binary_pat
        location->provider_name = provider_name_copy;
        location->binary_path = binary_path_copy;
        location->binary_fd_handle = binary_fd_handle;
-       binary_fd_handle = NULL;
+       binary_fd_handle = nullptr;
 
        ret = &location->parent;
        ret->lookup_method = lookup_method;
@@ -480,20 +462,19 @@ end:
        return ret;
 }
 
-struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_function_create(const char *binary_path,
-               const char *function_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method)
+struct lttng_userspace_probe_location *lttng_userspace_probe_location_function_create(
+       const char *binary_path,
+       const char *function_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
-       struct lttng_userspace_probe_location *ret = NULL;
+       struct lttng_userspace_probe_location *ret = nullptr;
 
        if (!binary_path || !function_name) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       switch (lttng_userspace_probe_location_lookup_method_get_type(
-                       lookup_method)) {
+       switch (lttng_userspace_probe_location_lookup_method_get_type(lookup_method)) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT:
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
                break;
@@ -503,25 +484,25 @@ lttng_userspace_probe_location_function_create(const char *binary_path,
        }
 
        ret = lttng_userspace_probe_location_function_create_no_check(
-                       binary_path, function_name, lookup_method, true);
+               binary_path, function_name, lookup_method, true);
 end:
        return ret;
 }
 
-struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_tracepoint_create(const char *binary_path,
-               const char *provider_name, const char *probe_name,
-               struct lttng_userspace_probe_location_lookup_method *lookup_method)
+struct lttng_userspace_probe_location *lttng_userspace_probe_location_tracepoint_create(
+       const char *binary_path,
+       const char *provider_name,
+       const char *probe_name,
+       struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
-       struct lttng_userspace_probe_location *ret = NULL;
+       struct lttng_userspace_probe_location *ret = nullptr;
 
        if (!binary_path || !probe_name || !provider_name) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       switch (lttng_userspace_probe_location_lookup_method_get_type(
-                       lookup_method)) {
+       switch (lttng_userspace_probe_location_lookup_method_get_type(lookup_method)) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                break;
        default:
@@ -530,21 +511,21 @@ lttng_userspace_probe_location_tracepoint_create(const char *binary_path,
        }
 
        ret = lttng_userspace_probe_location_tracepoint_create_no_check(
-                       binary_path, provider_name, probe_name, lookup_method, true);
+               binary_path, provider_name, probe_name, lookup_method, true);
 end:
        return ret;
 }
 
 static struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_lookup_method_function_elf_copy(
-               const struct lttng_userspace_probe_location_lookup_method *lookup_method)
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
-       struct lttng_userspace_probe_location_lookup_method *parent = NULL;
+       struct lttng_userspace_probe_location_lookup_method *parent = nullptr;
        struct lttng_userspace_probe_location_lookup_method_elf *elf_method;
 
        LTTNG_ASSERT(lookup_method);
        LTTNG_ASSERT(lookup_method->type ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF);
+                    LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF);
 
        elf_method = zmalloc<lttng_userspace_probe_location_lookup_method_elf>();
        if (!elf_method) {
@@ -557,21 +538,21 @@ lttng_userspace_probe_location_lookup_method_function_elf_copy(
 
        goto end;
 error:
-       parent = NULL;
+       parent = nullptr;
 end:
        return parent;
 }
 
 static struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_lookup_method_tracepoint_sdt_copy(
-               struct lttng_userspace_probe_location_lookup_method *lookup_method)
+       struct lttng_userspace_probe_location_lookup_method *lookup_method)
 {
-       struct lttng_userspace_probe_location_lookup_method *parent = NULL;
+       struct lttng_userspace_probe_location_lookup_method *parent = nullptr;
        struct lttng_userspace_probe_location_lookup_method_sdt *sdt_method;
 
        LTTNG_ASSERT(lookup_method);
        LTTNG_ASSERT(lookup_method->type ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT);
+                    LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT);
 
        sdt_method = zmalloc<lttng_userspace_probe_location_lookup_method_sdt>();
        if (!sdt_method) {
@@ -585,26 +566,25 @@ lttng_userspace_probe_location_lookup_method_tracepoint_sdt_copy(
        goto end;
 
 error:
-       parent = NULL;
+       parent = nullptr;
 end:
        return parent;
 }
 
 static struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_function_copy(
-               const struct lttng_userspace_probe_location *location)
+lttng_userspace_probe_location_function_copy(const struct lttng_userspace_probe_location *location)
 {
        enum lttng_userspace_probe_location_lookup_method_type lookup_type;
-       struct lttng_userspace_probe_location *new_location = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
-       const char *binary_path = NULL;
-       const char *function_name = NULL;
+       struct lttng_userspace_probe_location *new_location = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
+       const char *binary_path = nullptr;
+       const char *function_name = nullptr;
        struct lttng_userspace_probe_location_function *function_location;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(location->type == LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
        function_location = lttng::utils::container_of(
-                       location, &lttng_userspace_probe_location_function::parent);
+               location, &lttng_userspace_probe_location_function::parent);
 
        /* Get probe location fields */
        binary_path = lttng_userspace_probe_location_function_get_binary_path(location);
@@ -622,13 +602,12 @@ lttng_userspace_probe_location_function_copy(
        /*
         * Duplicate probe location method fields
         */
-       lookup_type = lttng_userspace_probe_location_lookup_method_get_type(
-                       location->lookup_method);
+       lookup_type =
+               lttng_userspace_probe_location_lookup_method_get_type(location->lookup_method);
        switch (lookup_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
-               lookup_method =
-                       lttng_userspace_probe_location_lookup_method_function_elf_copy(
-                                       location->lookup_method);
+               lookup_method = lttng_userspace_probe_location_lookup_method_function_elf_copy(
+                       location->lookup_method);
                if (!lookup_method) {
                        goto error;
                }
@@ -640,14 +619,14 @@ lttng_userspace_probe_location_function_copy(
 
        /* Create the probe_location */
        new_location = lttng_userspace_probe_location_function_create_no_check(
-                       binary_path, function_name, lookup_method, false);
+               binary_path, function_name, lookup_method, false);
        if (!new_location) {
                goto destroy_lookup_method;
        }
 
        /* Set the duplicated fd to the new probe_location */
-       if (lttng_userspace_probe_location_function_set_binary_fd_handle(new_location,
-                       function_location->binary_fd_handle) < 0) {
+       if (lttng_userspace_probe_location_function_set_binary_fd_handle(
+                   new_location, function_location->binary_fd_handle) < 0) {
                goto destroy_probe_location;
        }
 
@@ -658,27 +637,26 @@ destroy_probe_location:
 destroy_lookup_method:
        lttng_userspace_probe_location_lookup_method_destroy(lookup_method);
 error:
-       new_location = NULL;
+       new_location = nullptr;
 end:
        return new_location;
 }
 
-static struct lttng_userspace_probe_location *
-lttng_userspace_probe_location_tracepoint_copy(
-               const struct lttng_userspace_probe_location *location)
+static struct lttng_userspace_probe_location *lttng_userspace_probe_location_tracepoint_copy(
+       const struct lttng_userspace_probe_location *location)
 {
        enum lttng_userspace_probe_location_lookup_method_type lookup_type;
-       struct lttng_userspace_probe_location *new_location = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method = NULL;
-       const char *binary_path = NULL;
-       const char *probe_name = NULL;
-       const char *provider_name = NULL;
+       struct lttng_userspace_probe_location *new_location = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
+       const char *binary_path = nullptr;
+       const char *probe_name = nullptr;
+       const char *provider_name = nullptr;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(location->type == LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
        tracepoint_location = lttng::utils::container_of(
-                       location, &lttng_userspace_probe_location_tracepoint::parent);
+               location, &lttng_userspace_probe_location_tracepoint::parent);
 
        /* Get probe location fields */
        binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(location);
@@ -702,13 +680,12 @@ lttng_userspace_probe_location_tracepoint_copy(
        /*
         * Duplicate probe location method fields
         */
-       lookup_type = lttng_userspace_probe_location_lookup_method_get_type(
-                       location->lookup_method);
+       lookup_type =
+               lttng_userspace_probe_location_lookup_method_get_type(location->lookup_method);
        switch (lookup_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
-               lookup_method =
-                       lttng_userspace_probe_location_lookup_method_tracepoint_sdt_copy(
-                                       location->lookup_method);
+               lookup_method = lttng_userspace_probe_location_lookup_method_tracepoint_sdt_copy(
+                       location->lookup_method);
                if (!lookup_method) {
                        goto error;
                }
@@ -720,14 +697,14 @@ lttng_userspace_probe_location_tracepoint_copy(
 
        /* Create the probe_location */
        new_location = lttng_userspace_probe_location_tracepoint_create_no_check(
-                       binary_path, provider_name, probe_name, lookup_method, false);
+               binary_path, provider_name, probe_name, lookup_method, false);
        if (!new_location) {
                goto destroy_lookup_method;
        }
 
        /* Set the duplicated fd to the new probe_location */
-       if (lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(new_location,
-                       tracepoint_location->binary_fd_handle) < 0) {
+       if (lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
+                   new_location, tracepoint_location->binary_fd_handle) < 0) {
                goto destroy_probe_location;
        }
 
@@ -738,142 +715,150 @@ destroy_probe_location:
 destroy_lookup_method:
        lttng_userspace_probe_location_lookup_method_destroy(lookup_method);
 error:
-       new_location = NULL;
+       new_location = nullptr;
 end:
        return new_location;
 }
 
 const char *lttng_userspace_probe_location_function_get_binary_path(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_userspace_probe_location_function *function_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       function_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        ret = function_location->binary_path;
 end:
        return ret;
 }
 
 const char *lttng_userspace_probe_location_tracepoint_get_binary_path(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       tracepoint_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_tracepoint::parent);
+       tracepoint_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        ret = tracepoint_location->binary_path;
 end:
        return ret;
 }
 
 const char *lttng_userspace_probe_location_function_get_function_name(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_userspace_probe_location_function *function_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       function_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        ret = function_location->function_name;
 end:
        return ret;
 }
 
 const char *lttng_userspace_probe_location_tracepoint_get_probe_name(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       tracepoint_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_tracepoint::parent);
+       tracepoint_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        ret = tracepoint_location->probe_name;
 end:
        return ret;
 }
 
 const char *lttng_userspace_probe_location_tracepoint_get_provider_name(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       tracepoint_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_tracepoint::parent);
+       tracepoint_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        ret = tracepoint_location->provider_name;
 end:
        return ret;
 }
 
 int lttng_userspace_probe_location_function_get_binary_fd(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
        int ret = -1;
        struct lttng_userspace_probe_location_function *function_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       function_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        ret = function_location->binary_fd_handle ?
-                       fd_handle_get_fd(function_location->binary_fd_handle) : -1;
+               fd_handle_get_fd(function_location->binary_fd_handle) :
+               -1;
 end:
        return ret;
 }
 
 enum lttng_userspace_probe_location_function_instrumentation_type
 lttng_userspace_probe_location_function_get_instrumentation_type(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
        enum lttng_userspace_probe_location_function_instrumentation_type type;
        struct lttng_userspace_probe_location_function *function_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                type = LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_UNKNOWN;
                goto end;
        }
 
-       function_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        type = function_location->instrumentation_type;
 end:
        return type;
@@ -881,57 +866,61 @@ end:
 
 enum lttng_userspace_probe_location_status
 lttng_userspace_probe_location_function_set_instrumentation_type(
-               const struct lttng_userspace_probe_location *location,
-               enum lttng_userspace_probe_location_function_instrumentation_type instrumentation_type)
+       const struct lttng_userspace_probe_location *location,
+       enum lttng_userspace_probe_location_function_instrumentation_type instrumentation_type)
 {
        enum lttng_userspace_probe_location_status status =
-                       LTTNG_USERSPACE_PROBE_LOCATION_STATUS_OK;
+               LTTNG_USERSPACE_PROBE_LOCATION_STATUS_OK;
        struct lttng_userspace_probe_location_function *function_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION ||
-                       instrumentation_type !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION ||
+           instrumentation_type !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                status = LTTNG_USERSPACE_PROBE_LOCATION_STATUS_INVALID;
                goto end;
        }
 
-       function_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        function_location->instrumentation_type = instrumentation_type;
 end:
        return status;
 }
 
 int lttng_userspace_probe_location_tracepoint_get_binary_fd(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
        int ret = -1;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
 
-       tracepoint_location = lttng::utils::container_of(location,
-               &lttng_userspace_probe_location_tracepoint::parent);
+       tracepoint_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        ret = tracepoint_location->binary_fd_handle ?
-                       fd_handle_get_fd(tracepoint_location->binary_fd_handle) : -1;
+               fd_handle_get_fd(tracepoint_location->binary_fd_handle) :
+               -1;
 end:
        return ret;
 }
 
 static struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_function_get_lookup_method(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location_lookup_method *ret = NULL;
+       struct lttng_userspace_probe_location_lookup_method *ret = nullptr;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
@@ -943,12 +932,13 @@ end:
 
 static struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_tracepoint_get_lookup_method(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location_lookup_method *ret = NULL;
+       struct lttng_userspace_probe_location_lookup_method *ret = nullptr;
 
-       if (!location || lttng_userspace_probe_location_get_type(location) !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
+       if (!location ||
+           lttng_userspace_probe_location_get_type(location) !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT) {
                ERR("Invalid argument(s) passed to '%s'", __FUNCTION__);
                goto end;
        }
@@ -960,19 +950,17 @@ end:
 
 const struct lttng_userspace_probe_location_lookup_method *
 lttng_userspace_probe_location_get_lookup_method(
-               const struct lttng_userspace_probe_location *location)
+       const struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location_lookup_method *ret = NULL;
+       struct lttng_userspace_probe_location_lookup_method *ret = nullptr;
 
        LTTNG_ASSERT(location);
        switch (location->type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
-       ret = lttng_userspace_probe_location_function_get_lookup_method(
-                       location);
+               ret = lttng_userspace_probe_location_function_get_lookup_method(location);
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT:
-       ret = lttng_userspace_probe_location_tracepoint_get_lookup_method(
-                       location);
+               ret = lttng_userspace_probe_location_tracepoint_get_lookup_method(location);
                break;
        default:
                ERR("Unknowned lookup method.");
@@ -981,20 +969,19 @@ lttng_userspace_probe_location_get_lookup_method(
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_lookup_method_serialize(
-               struct lttng_userspace_probe_location_lookup_method *method,
-               struct lttng_payload *payload)
+static int lttng_userspace_probe_location_lookup_method_serialize(
+       struct lttng_userspace_probe_location_lookup_method *method, struct lttng_payload *payload)
 {
        int ret;
-       struct lttng_userspace_probe_location_lookup_method_comm
-                       lookup_method_comm;
+       struct lttng_userspace_probe_location_lookup_method_comm lookup_method_comm;
 
-       lookup_method_comm.type = (int8_t) (method ? method->type :
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT);
+       lookup_method_comm.type =
+               (int8_t) (method ?
+                                 method->type :
+                                 LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT);
        if (payload) {
-               ret = lttng_dynamic_buffer_append(&payload->buffer, &lookup_method_comm,
-                               sizeof(lookup_method_comm));
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, &lookup_method_comm, sizeof(lookup_method_comm));
                if (ret) {
                        goto end;
                }
@@ -1004,10 +991,8 @@ end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_function_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_payload *payload)
+static int lttng_userspace_probe_location_function_serialize(
+       const struct lttng_userspace_probe_location *location, struct lttng_payload *payload)
 {
        int ret;
        size_t function_name_len, binary_path_len;
@@ -1016,10 +1001,10 @@ int lttng_userspace_probe_location_function_serialize(
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(lttng_userspace_probe_location_get_type(location) ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
+                    LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
 
-       location_function = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_function::parent);
+       location_function = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        if (!location_function->function_name || !location_function->binary_path) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -1045,45 +1030,40 @@ int lttng_userspace_probe_location_function_serialize(
        location_function_comm.binary_path_len = binary_path_len + 1;
 
        if (payload) {
-               ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               &location_function_comm,
-                               sizeof(location_function_comm));
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, &location_function_comm, sizeof(location_function_comm));
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               location_function->function_name,
-                               location_function_comm.function_name_len);
+                                                 location_function->function_name,
+                                                 location_function_comm.function_name_len);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               location_function->binary_path,
-                               location_function_comm.binary_path_len);
+                                                 location_function->binary_path,
+                                                 location_function_comm.binary_path_len);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
-               ret = lttng_payload_push_fd_handle(
-                               payload, location_function->binary_fd_handle);
+               ret = lttng_payload_push_fd_handle(payload, location_function->binary_fd_handle);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
        }
-       ret = sizeof(location_function_comm) +
-                       location_function_comm.function_name_len +
-                       location_function_comm.binary_path_len;
+       ret = sizeof(location_function_comm) + location_function_comm.function_name_len +
+               location_function_comm.binary_path_len;
 end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_tracepoint_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_payload *payload)
+static int lttng_userspace_probe_location_tracepoint_serialize(
+       const struct lttng_userspace_probe_location *location, struct lttng_payload *payload)
 {
        int ret;
        size_t probe_name_len, provider_name_len, binary_path_len;
@@ -1092,13 +1072,12 @@ int lttng_userspace_probe_location_tracepoint_serialize(
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(lttng_userspace_probe_location_get_type(location) ==
-                       LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
+                    LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
 
-       location_tracepoint = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_tracepoint::parent);
-       if (!location_tracepoint->probe_name ||
-                       !location_tracepoint->provider_name ||
-                       !location_tracepoint->binary_path) {
+       location_tracepoint = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
+       if (!location_tracepoint->probe_name || !location_tracepoint->provider_name ||
+           !location_tracepoint->binary_path) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -1132,52 +1111,49 @@ int lttng_userspace_probe_location_tracepoint_serialize(
 
        if (payload) {
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               &location_tracepoint_comm,
-                               sizeof(location_tracepoint_comm));
+                                                 &location_tracepoint_comm,
+                                                 sizeof(location_tracepoint_comm));
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               location_tracepoint->probe_name,
-                               location_tracepoint_comm.probe_name_len);
+                                                 location_tracepoint->probe_name,
+                                                 location_tracepoint_comm.probe_name_len);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               location_tracepoint->provider_name,
-                               location_tracepoint_comm.provider_name_len);
+                                                 location_tracepoint->provider_name,
+                                                 location_tracepoint_comm.provider_name_len);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
                ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               location_tracepoint->binary_path,
-                               location_tracepoint_comm.binary_path_len);
+                                                 location_tracepoint->binary_path,
+                                                 location_tracepoint_comm.binary_path_len);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
-               ret = lttng_payload_push_fd_handle(
-                               payload, location_tracepoint->binary_fd_handle);
+               ret = lttng_payload_push_fd_handle(payload, location_tracepoint->binary_fd_handle);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
        }
 
-       ret = sizeof(location_tracepoint_comm) +
-                       location_tracepoint_comm.probe_name_len +
-                       location_tracepoint_comm.provider_name_len +
-                       location_tracepoint_comm.binary_path_len;
+       ret = sizeof(location_tracepoint_comm) + location_tracepoint_comm.probe_name_len +
+               location_tracepoint_comm.provider_name_len +
+               location_tracepoint_comm.binary_path_len;
 end:
        return ret;
 }
 
-int lttng_userspace_probe_location_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_payload *payload)
+int lttng_userspace_probe_location_serialize(const struct lttng_userspace_probe_location *location,
+                                            struct lttng_payload *payload)
 {
        int ret, buffer_use = 0;
        struct lttng_userspace_probe_location_comm location_generic_comm;
@@ -1192,9 +1168,8 @@ int lttng_userspace_probe_location_serialize(
 
        location_generic_comm.type = (int8_t) location->type;
        if (payload) {
-               ret = lttng_dynamic_buffer_append(&payload->buffer,
-                               &location_generic_comm,
-                               sizeof(location_generic_comm));
+               ret = lttng_dynamic_buffer_append(
+                       &payload->buffer, &location_generic_comm, sizeof(location_generic_comm));
                if (ret) {
                        goto end;
                }
@@ -1203,12 +1178,10 @@ int lttng_userspace_probe_location_serialize(
 
        switch (lttng_userspace_probe_location_get_type(location)) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
-               ret = lttng_userspace_probe_location_function_serialize(
-                               location, payload);
+               ret = lttng_userspace_probe_location_function_serialize(location, payload);
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT:
-               ret = lttng_userspace_probe_location_tracepoint_serialize(
-                               location, payload);
+               ret = lttng_userspace_probe_location_tracepoint_serialize(location, payload);
                break;
        default:
                ERR("Unsupported probe location type");
@@ -1220,8 +1193,8 @@ int lttng_userspace_probe_location_serialize(
        }
        buffer_use += ret;
 
-       ret = lttng_userspace_probe_location_lookup_method_serialize(
-                       location->lookup_method, payload);
+       ret = lttng_userspace_probe_location_lookup_method_serialize(location->lookup_method,
+                                                                    payload);
        if (ret < 0) {
                goto end;
        }
@@ -1230,14 +1203,12 @@ end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_function_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_userspace_probe_location **location)
+static int lttng_userspace_probe_location_function_create_from_payload(
+       struct lttng_payload_view *view, struct lttng_userspace_probe_location **location)
 {
        struct lttng_userspace_probe_location_function_comm *location_function_comm;
        const char *function_name_src, *binary_path_src;
-       char *function_name = NULL, *binary_path = NULL;
+       char *function_name = nullptr, *binary_path = nullptr;
        int ret = 0;
        size_t expected_size;
        struct fd_handle *binary_fd_handle = lttng_payload_view_pop_fd_handle(view);
@@ -1249,12 +1220,10 @@ int lttng_userspace_probe_location_function_create_from_payload(
                goto end;
        }
 
-       location_function_comm =
-                       (typeof(location_function_comm)) view->buffer.data;
+       location_function_comm = (typeof(location_function_comm)) view->buffer.data;
 
        expected_size = sizeof(*location_function_comm) +
-                       location_function_comm->function_name_len +
-                       location_function_comm->binary_path_len;
+               location_function_comm->function_name_len + location_function_comm->binary_path_len;
 
        if (view->buffer.size < expected_size) {
                ret = -LTTNG_ERR_INVALID;
@@ -1262,17 +1231,16 @@ int lttng_userspace_probe_location_function_create_from_payload(
        }
 
        function_name_src = view->buffer.data + sizeof(*location_function_comm);
-       binary_path_src = function_name_src +
-                       location_function_comm->function_name_len;
+       binary_path_src = function_name_src + location_function_comm->function_name_len;
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, function_name_src,
-                           location_function_comm->function_name_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, function_name_src, location_function_comm->function_name_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, binary_path_src,
-                           location_function_comm->binary_path_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, binary_path_src, location_function_comm->binary_path_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -1292,14 +1260,14 @@ int lttng_userspace_probe_location_function_create_from_payload(
        }
 
        *location = lttng_userspace_probe_location_function_create_no_check(
-                       binary_path, function_name, NULL, false);
+               binary_path, function_name, nullptr, false);
        if (!(*location)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_userspace_probe_location_function_set_binary_fd_handle(
-                       *location, binary_fd_handle);
+       ret = lttng_userspace_probe_location_function_set_binary_fd_handle(*location,
+                                                                          binary_fd_handle);
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -1313,14 +1281,12 @@ end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_tracepoint_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_userspace_probe_location **location)
+static int lttng_userspace_probe_location_tracepoint_create_from_payload(
+       struct lttng_payload_view *view, struct lttng_userspace_probe_location **location)
 {
        struct lttng_userspace_probe_location_tracepoint_comm *location_tracepoint_comm;
        const char *probe_name_src, *provider_name_src, *binary_path_src;
-       char *probe_name = NULL, *provider_name = NULL, *binary_path = NULL;
+       char *probe_name = nullptr, *provider_name = nullptr, *binary_path = nullptr;
        int ret = 0;
        size_t expected_size;
        struct fd_handle *binary_fd_handle = lttng_payload_view_pop_fd_handle(view);
@@ -1337,13 +1303,12 @@ int lttng_userspace_probe_location_tracepoint_create_from_payload(
                goto end;
        }
 
-       location_tracepoint_comm =
-                       (typeof(location_tracepoint_comm)) view->buffer.data;
+       location_tracepoint_comm = (typeof(location_tracepoint_comm)) view->buffer.data;
 
        expected_size = sizeof(*location_tracepoint_comm) +
-                       location_tracepoint_comm->probe_name_len +
-                       location_tracepoint_comm->provider_name_len +
-                       location_tracepoint_comm->binary_path_len;
+               location_tracepoint_comm->probe_name_len +
+               location_tracepoint_comm->provider_name_len +
+               location_tracepoint_comm->binary_path_len;
 
        if (view->buffer.size < expected_size) {
                ret = -LTTNG_ERR_INVALID;
@@ -1351,25 +1316,24 @@ int lttng_userspace_probe_location_tracepoint_create_from_payload(
        }
 
        probe_name_src = view->buffer.data + sizeof(*location_tracepoint_comm);
-       provider_name_src = probe_name_src +
-                       location_tracepoint_comm->probe_name_len;
-       binary_path_src = provider_name_src +
-                       location_tracepoint_comm->provider_name_len;
+       provider_name_src = probe_name_src + location_tracepoint_comm->probe_name_len;
+       binary_path_src = provider_name_src + location_tracepoint_comm->provider_name_len;
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, probe_name_src,
-                           location_tracepoint_comm->probe_name_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, probe_name_src, location_tracepoint_comm->probe_name_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, provider_name_src,
-                           location_tracepoint_comm->provider_name_len)) {
+       if (!lttng_buffer_view_contains_string(&view->buffer,
+                                              provider_name_src,
+                                              location_tracepoint_comm->provider_name_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (!lttng_buffer_view_contains_string(&view->buffer, binary_path_src,
-                           location_tracepoint_comm->binary_path_len)) {
+       if (!lttng_buffer_view_contains_string(
+                   &view->buffer, binary_path_src, location_tracepoint_comm->binary_path_len)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -1395,14 +1359,14 @@ int lttng_userspace_probe_location_tracepoint_create_from_payload(
        }
 
        *location = lttng_userspace_probe_location_tracepoint_create_no_check(
-                       binary_path, provider_name, probe_name, NULL, false);
+               binary_path, provider_name, probe_name, nullptr, false);
        if (!(*location)) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
-                       *location, binary_fd_handle);
+       ret = lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(*location,
+                                                                            binary_fd_handle);
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -1417,10 +1381,9 @@ end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_lookup_method_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_userspace_probe_location_lookup_method **lookup_method)
+static int lttng_userspace_probe_location_lookup_method_create_from_payload(
+       struct lttng_payload_view *view,
+       struct lttng_userspace_probe_location_lookup_method **lookup_method)
 {
        int ret;
        struct lttng_userspace_probe_location_lookup_method_comm *lookup_comm;
@@ -1435,15 +1398,13 @@ int lttng_userspace_probe_location_lookup_method_create_from_payload(
        }
 
        lookup_comm = (typeof(lookup_comm)) view->buffer.data;
-       type = (enum lttng_userspace_probe_location_lookup_method_type)
-                       lookup_comm->type;
+       type = (enum lttng_userspace_probe_location_lookup_method_type) lookup_comm->type;
        switch (type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT:
-               *lookup_method = NULL;
+               *lookup_method = nullptr;
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
-               *lookup_method =
-                       lttng_userspace_probe_location_lookup_method_function_elf_create();
+               *lookup_method = lttng_userspace_probe_location_lookup_method_function_elf_create();
                if (!(*lookup_method)) {
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
@@ -1468,8 +1429,7 @@ end:
 }
 
 int lttng_userspace_probe_location_create_from_payload(
-               struct lttng_payload_view *view,
-               struct lttng_userspace_probe_location **location)
+       struct lttng_payload_view *view, struct lttng_userspace_probe_location **location)
 {
        struct lttng_userspace_probe_location_lookup_method *lookup_method;
        enum lttng_userspace_probe_location_type type;
@@ -1477,13 +1437,12 @@ int lttng_userspace_probe_location_create_from_payload(
        int ret;
        struct lttng_userspace_probe_location_comm *probe_location_comm;
        struct lttng_payload_view probe_location_comm_view =
-                       lttng_payload_view_from_view(
-                                       view, 0, sizeof(*probe_location_comm));
+               lttng_payload_view_from_view(view, 0, sizeof(*probe_location_comm));
 
        LTTNG_ASSERT(view);
        LTTNG_ASSERT(location);
 
-       lookup_method = NULL;
+       lookup_method = nullptr;
 
        if (!lttng_payload_view_is_valid(&probe_location_comm_view)) {
                ret = -LTTNG_ERR_INVALID;
@@ -1498,11 +1457,10 @@ int lttng_userspace_probe_location_create_from_payload(
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
        {
                struct lttng_payload_view location_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
-               ret = lttng_userspace_probe_location_function_create_from_payload(
-                               &location_view, location);
+               ret = lttng_userspace_probe_location_function_create_from_payload(&location_view,
+                                                                                 location);
                if (ret < 0) {
                        goto end;
                }
@@ -1511,10 +1469,10 @@ int lttng_userspace_probe_location_create_from_payload(
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT:
        {
                struct lttng_payload_view location_view =
-                               lttng_payload_view_from_view(view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
-               ret = lttng_userspace_probe_location_tracepoint_create_from_payload(
-                               &location_view, location);
+               ret = lttng_userspace_probe_location_tracepoint_create_from_payload(&location_view,
+                                                                                   location);
                if (ret < 0) {
                        goto end;
                }
@@ -1533,11 +1491,10 @@ int lttng_userspace_probe_location_create_from_payload(
 
        {
                struct lttng_payload_view lookup_method_view =
-                               lttng_payload_view_from_view(
-                                               view, consumed, -1);
+                       lttng_payload_view_from_view(view, consumed, -1);
 
                ret = lttng_userspace_probe_location_lookup_method_create_from_payload(
-                               &lookup_method_view, &lookup_method);
+                       &lookup_method_view, &lookup_method);
        }
        if (ret < 0) {
                ret = -LTTNG_ERR_INVALID;
@@ -1546,16 +1503,14 @@ int lttng_userspace_probe_location_create_from_payload(
 
        LTTNG_ASSERT(lookup_method);
        (*location)->lookup_method = lookup_method;
-       lookup_method = NULL;
+       lookup_method = nullptr;
        ret += consumed;
 end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_function_set_binary_fd_handle(
-               struct lttng_userspace_probe_location *location,
-               struct fd_handle *binary_fd)
+static int lttng_userspace_probe_location_function_set_binary_fd_handle(
+       struct lttng_userspace_probe_location *location, struct fd_handle *binary_fd)
 {
        int ret = 0;
        struct lttng_userspace_probe_location_function *function_location;
@@ -1563,18 +1518,16 @@ int lttng_userspace_probe_location_function_set_binary_fd_handle(
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(location->type == LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION);
 
-       function_location = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_function::parent);
+       function_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        fd_handle_put(function_location->binary_fd_handle);
        fd_handle_get(binary_fd);
        function_location->binary_fd_handle = binary_fd;
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
-               struct lttng_userspace_probe_location *location,
-               struct fd_handle *binary_fd)
+static int lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
+       struct lttng_userspace_probe_location *location, struct fd_handle *binary_fd)
 {
        int ret = 0;
        struct lttng_userspace_probe_location_tracepoint *tracepoint_location;
@@ -1582,18 +1535,16 @@ int lttng_userspace_probe_location_tracepoint_set_binary_fd_handle(
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(location->type == LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT);
 
-       tracepoint_location = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_tracepoint::parent);
+       tracepoint_location = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        fd_handle_put(tracepoint_location->binary_fd_handle);
        fd_handle_get(binary_fd);
        tracepoint_location->binary_fd_handle = binary_fd;
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_function_flatten(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_dynamic_buffer *buffer)
+static int lttng_userspace_probe_location_function_flatten(
+       const struct lttng_userspace_probe_location *location, struct lttng_dynamic_buffer *buffer)
 {
        struct lttng_userspace_probe_location_lookup_method_elf flat_lookup_method;
        struct lttng_userspace_probe_location_function *probe_function;
@@ -1606,19 +1557,19 @@ int lttng_userspace_probe_location_function_flatten(
 
        LTTNG_ASSERT(location);
 
-       if (location->lookup_method && location->lookup_method->type !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF) {
+       if (location->lookup_method &&
+           location->lookup_method->type !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       probe_function = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_function::parent);
+       probe_function = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_function::parent);
        LTTNG_ASSERT(probe_function->function_name);
        LTTNG_ASSERT(probe_function->binary_path);
 
-       storage_needed +=
-                       sizeof(struct lttng_userspace_probe_location_function);
+       storage_needed += sizeof(struct lttng_userspace_probe_location_function);
        function_name_len = strlen(probe_function->function_name) + 1;
        binary_path_len = strlen(probe_function->binary_path) + 1;
        storage_needed += function_name_len + binary_path_len;
@@ -1643,8 +1594,7 @@ int lttng_userspace_probe_location_function_flatten(
        }
 
        if (lttng_dynamic_buffer_get_capacity_left(buffer) < storage_needed) {
-               ret = lttng_dynamic_buffer_set_capacity(buffer,
-                               buffer->size + storage_needed);
+               ret = lttng_dynamic_buffer_set_capacity(buffer, buffer->size + storage_needed);
                if (ret) {
                        goto end;
                }
@@ -1660,36 +1610,32 @@ int lttng_userspace_probe_location_function_flatten(
         */
        if (location->lookup_method) {
                flat_probe.parent.lookup_method =
-                               (struct lttng_userspace_probe_location_lookup_method *)
-                                       (flat_probe_start + sizeof(flat_probe) +
-                                       function_name_len + binary_path_len + padding_needed);
+                       (struct lttng_userspace_probe_location_lookup_method
+                                *) (flat_probe_start + sizeof(flat_probe) + function_name_len +
+                                    binary_path_len + padding_needed);
        } else {
-               flat_probe.parent.lookup_method = NULL;
+               flat_probe.parent.lookup_method = nullptr;
        }
 
        flat_probe.function_name = flat_probe_start + sizeof(flat_probe);
        flat_probe.binary_path = flat_probe.function_name + function_name_len;
-       flat_probe.binary_fd_handle = NULL;
-       ret = lttng_dynamic_buffer_append(buffer, &flat_probe,
-                       sizeof(flat_probe));
+       flat_probe.binary_fd_handle = nullptr;
+       ret = lttng_dynamic_buffer_append(buffer, &flat_probe, sizeof(flat_probe));
        if (ret) {
                goto end;
        }
 
-       ret = lttng_dynamic_buffer_append(buffer,
-                       probe_function->function_name, function_name_len);
+       ret = lttng_dynamic_buffer_append(buffer, probe_function->function_name, function_name_len);
        if (ret) {
                goto end;
        }
-       ret = lttng_dynamic_buffer_append(buffer,
-                       probe_function->binary_path, binary_path_len);
+       ret = lttng_dynamic_buffer_append(buffer, probe_function->binary_path, binary_path_len);
        if (ret) {
                goto end;
        }
 
        /* Insert padding before the lookup method. */
-       ret = lttng_dynamic_buffer_set_size(buffer,
-                       buffer->size + padding_needed);
+       ret = lttng_dynamic_buffer_set_size(buffer, buffer->size + padding_needed);
        if (ret) {
                goto end;
        }
@@ -1702,9 +1648,8 @@ int lttng_userspace_probe_location_function_flatten(
 
        memset(&flat_lookup_method, 0, sizeof(flat_lookup_method));
        flat_lookup_method.parent.type =
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF;
-       ret = lttng_dynamic_buffer_append(buffer,
-                       &flat_lookup_method, sizeof(flat_lookup_method));
+               LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF;
+       ret = lttng_dynamic_buffer_append(buffer, &flat_lookup_method, sizeof(flat_lookup_method));
        if (ret) {
                goto end;
        }
@@ -1713,10 +1658,8 @@ end:
        return ret;
 }
 
-static
-int lttng_userspace_probe_location_tracepoint_flatten(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_dynamic_buffer *buffer)
+static int lttng_userspace_probe_location_tracepoint_flatten(
+       const struct lttng_userspace_probe_location *location, struct lttng_dynamic_buffer *buffer)
 {
        struct lttng_userspace_probe_location_lookup_method_sdt flat_lookup_method;
        struct lttng_userspace_probe_location_tracepoint *probe_tracepoint;
@@ -1730,13 +1673,14 @@ int lttng_userspace_probe_location_tracepoint_flatten(
        LTTNG_ASSERT(location);
 
        /* Only SDT tracepoints are supported at the moment */
-       if (location->lookup_method && location->lookup_method->type !=
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT) {
+       if (location->lookup_method &&
+           location->lookup_method->type !=
+                   LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
-       probe_tracepoint = lttng::utils::container_of(location,
-                       &lttng_userspace_probe_location_tracepoint::parent);
+       probe_tracepoint = lttng::utils::container_of(
+               location, &lttng_userspace_probe_location_tracepoint::parent);
        LTTNG_ASSERT(probe_tracepoint->probe_name);
        LTTNG_ASSERT(probe_tracepoint->provider_name);
        LTTNG_ASSERT(probe_tracepoint->binary_path);
@@ -1761,8 +1705,7 @@ int lttng_userspace_probe_location_tracepoint_flatten(
 
        if (location->lookup_method) {
                /* NOTE: elf look-up method is assumed here. */
-               storage_needed +=
-                       sizeof(struct lttng_userspace_probe_location_lookup_method_elf);
+               storage_needed += sizeof(struct lttng_userspace_probe_location_lookup_method_elf);
        }
 
        /*
@@ -1774,8 +1717,7 @@ int lttng_userspace_probe_location_tracepoint_flatten(
        }
 
        if (lttng_dynamic_buffer_get_capacity_left(buffer) < storage_needed) {
-               ret = lttng_dynamic_buffer_set_capacity(buffer,
-                               buffer->size + storage_needed);
+               ret = lttng_dynamic_buffer_set_capacity(buffer, buffer->size + storage_needed);
                if (ret) {
                        goto end;
                }
@@ -1792,36 +1734,33 @@ int lttng_userspace_probe_location_tracepoint_flatten(
         */
        if (location->lookup_method) {
                flat_probe.parent.lookup_method =
-                               (struct lttng_userspace_probe_location_lookup_method *)
-                                       (flat_probe_start + sizeof(flat_probe) +
-                                       probe_name_len + provider_name_len +
-                                       binary_path_len + padding_needed);
+                       (struct lttng_userspace_probe_location_lookup_method
+                                *) (flat_probe_start + sizeof(flat_probe) + probe_name_len +
+                                    provider_name_len + binary_path_len + padding_needed);
        } else {
-               flat_probe.parent.lookup_method = NULL;
+               flat_probe.parent.lookup_method = nullptr;
        }
 
        flat_probe.probe_name = flat_probe_start + sizeof(flat_probe);
        flat_probe.provider_name = flat_probe.probe_name + probe_name_len;
        flat_probe.binary_path = flat_probe.provider_name + provider_name_len;
-       flat_probe.binary_fd_handle = NULL;
+       flat_probe.binary_fd_handle = nullptr;
        ret = lttng_dynamic_buffer_append(buffer, &flat_probe, sizeof(flat_probe));
        if (ret) {
                goto end;
        }
 
        /* Append all the fields to the buffer */
-       ret = lttng_dynamic_buffer_append(buffer,
-                       probe_tracepoint->probe_name, probe_name_len);
+       ret = lttng_dynamic_buffer_append(buffer, probe_tracepoint->probe_name, probe_name_len);
        if (ret) {
                goto end;
        }
-       ret = lttng_dynamic_buffer_append(buffer,
-                       probe_tracepoint->provider_name, provider_name_len);
+       ret = lttng_dynamic_buffer_append(
+               buffer, probe_tracepoint->provider_name, provider_name_len);
        if (ret) {
                goto end;
        }
-       ret = lttng_dynamic_buffer_append(buffer,
-                       probe_tracepoint->binary_path, binary_path_len);
+       ret = lttng_dynamic_buffer_append(buffer, probe_tracepoint->binary_path, binary_path_len);
        if (ret) {
                goto end;
        }
@@ -1841,9 +1780,8 @@ int lttng_userspace_probe_location_tracepoint_flatten(
        memset(&flat_lookup_method, 0, sizeof(flat_lookup_method));
 
        flat_lookup_method.parent.type =
-                       LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT;
-       ret = lttng_dynamic_buffer_append(buffer,
-                       &flat_lookup_method, sizeof(flat_lookup_method));
+               LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT;
+       ret = lttng_dynamic_buffer_append(buffer, &flat_lookup_method, sizeof(flat_lookup_method));
        if (ret) {
                goto end;
        }
@@ -1852,9 +1790,8 @@ end:
        return ret;
 }
 
-int lttng_userspace_probe_location_flatten(
-               const struct lttng_userspace_probe_location *location,
-               struct lttng_dynamic_buffer *buffer)
+int lttng_userspace_probe_location_flatten(const struct lttng_userspace_probe_location *location,
+                                          struct lttng_dynamic_buffer *buffer)
 {
        int ret;
        if (!location) {
@@ -1879,10 +1816,10 @@ end:
        return ret;
 }
 
-struct lttng_userspace_probe_location *lttng_userspace_probe_location_copy(
-               const struct lttng_userspace_probe_location *location)
+struct lttng_userspace_probe_location *
+lttng_userspace_probe_location_copy(const struct lttng_userspace_probe_location *location)
 {
-       struct lttng_userspace_probe_location *new_location = NULL;
+       struct lttng_userspace_probe_location *new_location = nullptr;
        enum lttng_userspace_probe_location_type type;
 
        if (!location) {
@@ -1892,21 +1829,19 @@ struct lttng_userspace_probe_location *lttng_userspace_probe_location_copy(
        type = lttng_userspace_probe_location_get_type(location);
        switch (type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION:
-               new_location =
-                       lttng_userspace_probe_location_function_copy(location);
+               new_location = lttng_userspace_probe_location_function_copy(location);
                if (!new_location) {
                        goto err;
                }
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT:
-               new_location =
-                       lttng_userspace_probe_location_tracepoint_copy(location);
+               new_location = lttng_userspace_probe_location_tracepoint_copy(location);
                if (!new_location) {
                        goto err;
                }
                break;
        default:
-               new_location = NULL;
+               new_location = nullptr;
                goto err;
        }
 err:
@@ -1914,8 +1849,8 @@ err:
 }
 
 bool lttng_userspace_probe_location_lookup_method_is_equal(
-               const struct lttng_userspace_probe_location_lookup_method *a,
-               const struct lttng_userspace_probe_location_lookup_method *b)
+       const struct lttng_userspace_probe_location_lookup_method *a,
+       const struct lttng_userspace_probe_location_lookup_method *b)
 {
        bool is_equal = false;
 
@@ -1937,9 +1872,8 @@ end:
        return is_equal;
 }
 
-bool lttng_userspace_probe_location_is_equal(
-               const struct lttng_userspace_probe_location *a,
-               const struct lttng_userspace_probe_location *b)
+bool lttng_userspace_probe_location_is_equal(const struct lttng_userspace_probe_location *a,
+                                            const struct lttng_userspace_probe_location *b)
 {
        bool is_equal = false;
 
@@ -1952,8 +1886,8 @@ bool lttng_userspace_probe_location_is_equal(
                goto end;
        }
 
-       if (!lttng_userspace_probe_location_lookup_method_is_equal(
-                           a->lookup_method, b->lookup_method)) {
+       if (!lttng_userspace_probe_location_lookup_method_is_equal(a->lookup_method,
+                                                                  b->lookup_method)) {
                goto end;
        }
 
@@ -1966,23 +1900,22 @@ end:
        return is_equal;
 }
 
-unsigned long lttng_userspace_probe_location_hash(
-               const struct lttng_userspace_probe_location *location)
+unsigned long
+lttng_userspace_probe_location_hash(const struct lttng_userspace_probe_location *location)
 {
        return location->hash(location);
 }
 
-enum lttng_error_code lttng_userspace_probe_location_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer)
+enum lttng_error_code
+lttng_userspace_probe_location_mi_serialize(const struct lttng_userspace_probe_location *location,
+                                           struct mi_writer *writer)
 {
-       typedef enum lttng_error_code (*mi_fp)(
-                       const struct lttng_userspace_probe_location *,
-                       struct mi_writer *);
+       using mi_fp = enum lttng_error_code (*)(const struct lttng_userspace_probe_location *,
+                                               struct mi_writer *);
 
        int ret;
        enum lttng_error_code ret_code;
-       mi_fp mi_function = NULL;
+       mi_fp mi_function = nullptr;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(writer);
@@ -2000,8 +1933,7 @@ enum lttng_error_code lttng_userspace_probe_location_mi_serialize(
        }
 
        /* Open userspace probe location element. */
-       ret = mi_lttng_writer_open_element(
-                       writer, mi_lttng_element_userspace_probe_location);
+       ret = mi_lttng_writer_open_element(writer, mi_lttng_element_userspace_probe_location);
        if (ret) {
                goto mi_error;
        }
@@ -2028,9 +1960,7 @@ end:
 }
 
 enum lttng_error_code lttng_userspace_probe_location_lookup_method_mi_serialize(
-               const struct lttng_userspace_probe_location_lookup_method
-                               *method,
-               struct mi_writer *writer)
+       const struct lttng_userspace_probe_location_lookup_method *method, struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -2042,15 +1972,15 @@ enum lttng_error_code lttng_userspace_probe_location_lookup_method_mi_serialize(
        switch (lttng_userspace_probe_location_lookup_method_get_type(method)) {
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_DEFAULT:
                type_element_str =
-                               mi_lttng_element_userspace_probe_location_lookup_method_function_default;
+                       mi_lttng_element_userspace_probe_location_lookup_method_function_default;
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_FUNCTION_ELF:
                type_element_str =
-                               mi_lttng_element_userspace_probe_location_lookup_method_function_elf;
+                       mi_lttng_element_userspace_probe_location_lookup_method_function_elf;
                break;
        case LTTNG_USERSPACE_PROBE_LOCATION_LOOKUP_METHOD_TYPE_TRACEPOINT_SDT:
                type_element_str =
-                               mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt;
+                       mi_lttng_element_userspace_probe_location_lookup_method_tracepoint_sdt;
                break;
        default:
                abort();
@@ -2059,7 +1989,7 @@ enum lttng_error_code lttng_userspace_probe_location_lookup_method_mi_serialize(
 
        /* Open userspace probe location lookup method element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_userspace_probe_location_lookup_method);
+                                          mi_lttng_element_userspace_probe_location_lookup_method);
        if (ret) {
                goto mi_error;
        }
@@ -2086,63 +2016,57 @@ end:
 }
 
 static enum lttng_error_code lttng_userspace_probe_location_tracepoint_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer)
+       const struct lttng_userspace_probe_location *location, struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const char *probe_name = NULL;
-       const char *provider_name = NULL;
-       const char *binary_path = NULL;
-       const struct lttng_userspace_probe_location_lookup_method
-                       *lookup_method = NULL;
+       const char *probe_name = nullptr;
+       const char *provider_name = nullptr;
+       const char *binary_path = nullptr;
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(writer);
 
-       probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(
-                       location);
-       provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(
-                       location);
-       binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(
-                       location);
-       lookup_method = lttng_userspace_probe_location_tracepoint_get_lookup_method(
-                       location);
+       probe_name = lttng_userspace_probe_location_tracepoint_get_probe_name(location);
+       provider_name = lttng_userspace_probe_location_tracepoint_get_provider_name(location);
+       binary_path = lttng_userspace_probe_location_tracepoint_get_binary_path(location);
+       lookup_method = lttng_userspace_probe_location_tracepoint_get_lookup_method(location);
 
        /* Open userspace probe location tracepoint element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_userspace_probe_location_tracepoint);
+                                          mi_lttng_element_userspace_probe_location_tracepoint);
        if (ret) {
                goto mi_error;
        }
 
        /* Probe name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_tracepoint_probe_name,
-                       probe_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer,
+               mi_lttng_element_userspace_probe_location_tracepoint_probe_name,
+               probe_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Provider name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_tracepoint_provider_name,
-                       provider_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer,
+               mi_lttng_element_userspace_probe_location_tracepoint_provider_name,
+               provider_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Binary path. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_binary_path,
-                       binary_path);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_userspace_probe_location_binary_path, binary_path);
        if (ret) {
                goto mi_error;
        }
 
        /* The lookup method. */
-       ret_code = lttng_userspace_probe_location_lookup_method_mi_serialize(
-                       lookup_method, writer);
+       ret_code = lttng_userspace_probe_location_lookup_method_mi_serialize(lookup_method, writer);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
@@ -2163,36 +2087,29 @@ end:
 }
 
 static enum lttng_error_code lttng_userspace_probe_location_function_mi_serialize(
-               const struct lttng_userspace_probe_location *location,
-               struct mi_writer *writer)
+       const struct lttng_userspace_probe_location *location, struct mi_writer *writer)
 {
        int ret;
        enum lttng_error_code ret_code;
-       const char *function_name = NULL;
-       const char *binary_path = NULL;
-       const char *instrumentation_type_str = NULL;
-       enum lttng_userspace_probe_location_function_instrumentation_type
-                       instrumentation_type;
-       const struct lttng_userspace_probe_location_lookup_method
-                       *lookup_method = NULL;
+       const char *function_name = nullptr;
+       const char *binary_path = nullptr;
+       const char *instrumentation_type_str = nullptr;
+       enum lttng_userspace_probe_location_function_instrumentation_type instrumentation_type;
+       const struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
 
        LTTNG_ASSERT(location);
        LTTNG_ASSERT(writer);
 
-       function_name = lttng_userspace_probe_location_function_get_function_name(
-                       location);
-       binary_path = lttng_userspace_probe_location_function_get_binary_path(
-                       location);
+       function_name = lttng_userspace_probe_location_function_get_function_name(location);
+       binary_path = lttng_userspace_probe_location_function_get_binary_path(location);
        instrumentation_type =
-                       lttng_userspace_probe_location_function_get_instrumentation_type(
-                                       location);
-       lookup_method = lttng_userspace_probe_location_function_get_lookup_method(
-                       location);
+               lttng_userspace_probe_location_function_get_instrumentation_type(location);
+       lookup_method = lttng_userspace_probe_location_function_get_lookup_method(location);
 
        switch (instrumentation_type) {
        case LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY:
                instrumentation_type_str =
-                               mi_lttng_userspace_probe_location_function_instrumentation_type_entry;
+                       mi_lttng_userspace_probe_location_function_instrumentation_type_entry;
                break;
        default:
                abort();
@@ -2201,38 +2118,36 @@ static enum lttng_error_code lttng_userspace_probe_location_function_mi_serializ
 
        /* Open userspace probe location function element. */
        ret = mi_lttng_writer_open_element(writer,
-                       mi_lttng_element_userspace_probe_location_function);
+                                          mi_lttng_element_userspace_probe_location_function);
        if (ret) {
                goto mi_error;
        }
 
        /* Function name. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_function_name,
-                       function_name);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_userspace_probe_location_function_name, function_name);
        if (ret) {
                goto mi_error;
        }
 
        /* Binary path. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_binary_path,
-                       binary_path);
+       ret = mi_lttng_writer_write_element_string(
+               writer, mi_lttng_element_userspace_probe_location_binary_path, binary_path);
        if (ret) {
                goto mi_error;
        }
 
        /* Instrumentation type. */
-       ret = mi_lttng_writer_write_element_string(writer,
-                       mi_lttng_element_userspace_probe_location_function_instrumentation_type,
-                       instrumentation_type_str);
+       ret = mi_lttng_writer_write_element_string(
+               writer,
+               mi_lttng_element_userspace_probe_location_function_instrumentation_type,
+               instrumentation_type_str);
        if (ret) {
                goto mi_error;
        }
 
        /* The lookup method. */
-       ret_code = lttng_userspace_probe_location_lookup_method_mi_serialize(
-                       lookup_method, writer);
+       ret_code = lttng_userspace_probe_location_lookup_method_mi_serialize(lookup_method, writer);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
index 30d1f102142781289be72a965a9b8bfe719486ff..3f40d03ed3d846cb8fa95788c94bf555be5fb28f 100644 (file)
@@ -8,41 +8,43 @@
  */
 
 #define _LGPL_SOURCE
+#include "ust-consumer.hpp"
+
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/consumer/consumer-metadata-cache.hpp>
+#include <common/consumer/consumer-stream.hpp>
+#include <common/consumer/consumer-timer.hpp>
+#include <common/consumer/consumer.hpp>
+#include <common/index/index.hpp>
+#include <common/optional.hpp>
+#include <common/relayd/relayd.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/shm.hpp>
+#include <common/urcu.hpp>
+#include <common/utils.hpp>
+
 #include <lttng/ust-ctl.h>
 #include <lttng/ust-sigbus.h>
+
+#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <fcntl.h>
+#include <inttypes.h>
 #include <poll.h>
 #include <pthread.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/mman.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <inttypes.h>
 #include <unistd.h>
 #include <urcu/list.h>
-#include <signal.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <bin/lttng-consumerd/health-consumerd.hpp>
-#include <common/common.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/relayd/relayd.hpp>
-#include <common/compat/fcntl.hpp>
-#include <common/compat/endian.hpp>
-#include <common/consumer/consumer-metadata-cache.hpp>
-#include <common/consumer/consumer-stream.hpp>
-#include <common/consumer/consumer-timer.hpp>
-#include <common/utils.hpp>
-#include <common/index/index.hpp>
-#include <common/consumer/consumer.hpp>
-#include <common/shm.hpp>
-#include <common/optional.hpp>
 
-#include "ust-consumer.hpp"
-
-#define INT_MAX_STR_LEN 12     /* includes \0 */
+#define INT_MAX_STR_LEN 12 /* includes \0 */
 
 extern struct lttng_consumer_global_data the_consumer_data;
 extern int consumer_poll_timeout;
@@ -55,14 +57,14 @@ LTTNG_EXPORT DEFINE_LTTNG_UST_SIGBUS_STATE();
  * Returns 0 on success or else a negative value.
  */
 static int add_channel(struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx)
+                      struct lttng_consumer_local_data *ctx)
 {
        int ret = 0;
 
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(ctx);
 
-       if (ctx->on_recv_channel != NULL) {
+       if (ctx->on_recv_channel != nullptr) {
                ret = ctx->on_recv_channel(channel);
                if (ret == 0) {
                        ret = consumer_add_channel(channel, ctx);
@@ -87,29 +89,30 @@ error:
  *
  * Return NULL on error else the newly allocated stream object.
  */
-static struct lttng_consumer_stream *allocate_stream(int cpu, int key,
-               struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx, int *_alloc_ret)
+static struct lttng_consumer_stream *allocate_stream(int cpu,
+                                                    int key,
+                                                    struct lttng_consumer_channel *channel,
+                                                    struct lttng_consumer_local_data *ctx,
+                                                    int *_alloc_ret)
 {
        int alloc_ret;
-       struct lttng_consumer_stream *stream = NULL;
+       struct lttng_consumer_stream *stream = nullptr;
 
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(ctx);
 
-       stream = consumer_stream_create(
-                       channel,
-                       channel->key,
-                       key,
-                       channel->name,
-                       channel->relayd_id,
-                       channel->session_id,
-                       channel->trace_chunk,
-                       cpu,
-                       &alloc_ret,
-                       channel->type,
-                       channel->monitor);
-       if (stream == NULL) {
+       stream = consumer_stream_create(channel,
+                                       channel->key,
+                                       key,
+                                       channel->name,
+                                       channel->relayd_id,
+                                       channel->session_id,
+                                       channel->trace_chunk,
+                                       cpu,
+                                       &alloc_ret,
+                                       channel->type,
+                                       channel->monitor);
+       if (stream == nullptr) {
                switch (alloc_ret) {
                case -ENOENT:
                        /*
@@ -142,7 +145,7 @@ error:
  * Returns 0 on success else a negative value.
  */
 static int send_stream_to_thread(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx)
+                                struct lttng_consumer_local_data *ctx)
 {
        int ret;
        struct lttng_pipe *stream_pipe;
@@ -165,11 +168,12 @@ static int send_stream_to_thread(struct lttng_consumer_stream *stream,
        stream->globally_visible = 1;
        cds_list_del_init(&stream->send_node);
 
-       ret = lttng_pipe_write(stream_pipe, &stream, sizeof(stream));
+       ret = lttng_pipe_write(stream_pipe, &stream, sizeof(stream)); /* NOLINT sizeof used on a
+                                                                        pointer. */
        if (ret < 0) {
                ERR("Consumer write %s stream to pipe %d",
-                               stream->metadata_flag ? "metadata" : "data",
-                               lttng_pipe_get_writefd(stream_pipe));
+                   stream->metadata_flag ? "metadata" : "data",
+                   lttng_pipe_get_writefd(stream_pipe));
                if (stream->metadata_flag) {
                        consumer_del_stream_for_metadata(stream);
                } else {
@@ -182,10 +186,9 @@ error:
        return ret;
 }
 
-static
-int get_stream_shm_path(char *stream_shm_path, const char *shm_path, int cpu)
+static int get_stream_shm_path(char *stream_shm_path, const char *shm_path, int cpu)
 {
-       char cpu_nr[INT_MAX_STR_LEN];  /* int max len */
+       char cpu_nr[INT_MAX_STR_LEN]; /* int max len */
        int ret;
 
        strncpy(stream_shm_path, shm_path, PATH_MAX);
@@ -195,8 +198,7 @@ int get_stream_shm_path(char *stream_shm_path, const char *shm_path, int cpu)
                PERROR("snprintf");
                goto end;
        }
-       strncat(stream_shm_path, cpu_nr,
-               PATH_MAX - strlen(stream_shm_path) - 1);
+       strncat(stream_shm_path, cpu_nr, PATH_MAX - strlen(stream_shm_path) - 1);
        ret = 0;
 end:
        return ret;
@@ -209,12 +211,12 @@ end:
  * Return 0 on success else a negative value.
  */
 static int create_ust_streams(struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx)
+                             struct lttng_consumer_local_data *ctx)
 {
        int ret, cpu = 0;
        struct lttng_ust_ctl_consumer_stream *ustream;
        struct lttng_consumer_stream *stream;
-       pthread_mutex_t *current_stream_lock = NULL;
+       pthread_mutex_t *current_stream_lock = nullptr;
 
        LTTNG_ASSERT(channel);
        LTTNG_ASSERT(ctx);
@@ -269,11 +271,9 @@ static int create_ust_streams(struct lttng_consumer_channel *channel,
                 */
                cds_list_add_tail(&stream->send_node, &channel->streams.head);
 
-               ret = lttng_ust_ctl_get_max_subbuf_size(stream->ustream,
-                               &stream->max_sb_size);
+               ret = lttng_ust_ctl_get_max_subbuf_size(stream->ustream, &stream->max_sb_size);
                if (ret < 0) {
-                       ERR("lttng_ust_ctl_get_max_subbuf_size failed for stream %s",
-                                       stream->name);
+                       ERR("lttng_ust_ctl_get_max_subbuf_size failed for stream %s", stream->name);
                        goto error;
                }
 
@@ -286,7 +286,9 @@ static int create_ust_streams(struct lttng_consumer_channel *channel,
                }
 
                DBG("UST consumer add stream %s (key: %" PRIu64 ") with relayd id %" PRIu64,
-                               stream->name, stream->key, stream->relayd_stream_id);
+                   stream->name,
+                   stream->key,
+                   stream->relayd_stream_id);
 
                /* Set next CPU stream. */
                channel->streams.count = ++cpu;
@@ -297,12 +299,12 @@ static int create_ust_streams(struct lttng_consumer_channel *channel,
                        if (channel->monitor) {
                                /* Set metadata poll pipe if we created one */
                                memcpy(stream->ust_metadata_poll_pipe,
-                                               ust_metadata_pipe,
-                                               sizeof(ust_metadata_pipe));
+                                      ust_metadata_pipe,
+                                      sizeof(ust_metadata_pipe));
                        }
                }
                pthread_mutex_unlock(&stream->lock);
-               current_stream_lock = NULL;
+               current_stream_lock = nullptr;
        }
 
        return 0;
@@ -315,8 +317,9 @@ error_alloc:
        return ret;
 }
 
-static int open_ust_stream_fd(struct lttng_consumer_channel *channel, int cpu,
-               const struct lttng_credentials *session_credentials)
+static int open_ust_stream_fd(struct lttng_consumer_channel *channel,
+                             int cpu,
+                             const struct lttng_credentials *session_credentials)
 {
        char shm_path[PATH_MAX];
        int ret;
@@ -329,9 +332,10 @@ static int open_ust_stream_fd(struct lttng_consumer_channel *channel, int cpu,
                goto error_shm_path;
        }
        return run_as_open(shm_path,
-               O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR,
-               lttng_credentials_get_uid(session_credentials),
-               lttng_credentials_get_gid(session_credentials));
+                          O_RDWR | O_CREAT | O_EXCL,
+                          S_IRUSR | S_IWUSR,
+                          lttng_credentials_get_uid(session_credentials),
+                          lttng_credentials_get_gid(session_credentials));
 
 error_shm_path:
        return -1;
@@ -344,8 +348,8 @@ error_shm_path:
  * Return 0 on success or else a negative value.
  */
 static int create_ust_channel(struct lttng_consumer_channel *channel,
-               struct lttng_ust_ctl_consumer_channel_attr *attr,
-               struct lttng_ust_ctl_consumer_channel **ust_chanp)
+                             struct lttng_ust_ctl_consumer_channel_attr *attr,
+                             struct lttng_ust_ctl_consumer_channel **ust_chanp)
 {
        int ret, nr_stream_fds, i, j;
        int *stream_fds;
@@ -357,11 +361,16 @@ static int create_ust_channel(struct lttng_consumer_channel *channel,
        LTTNG_ASSERT(channel->buffer_credentials.is_set);
 
        DBG3("Creating channel to ustctl with attr: [overwrite: %d, "
-                       "subbuf_size: %" PRIu64 ", num_subbuf: %" PRIu64 ", "
-                       "switch_timer_interval: %u, read_timer_interval: %u, "
-                       "output: %d, type: %d", attr->overwrite, attr->subbuf_size,
-                       attr->num_subbuf, attr->switch_timer_interval,
-                       attr->read_timer_interval, attr->output, attr->type);
+            "subbuf_size: %" PRIu64 ", num_subbuf: %" PRIu64 ", "
+            "switch_timer_interval: %u, read_timer_interval: %u, "
+            "output: %d, type: %d",
+            attr->overwrite,
+            attr->subbuf_size,
+            attr->num_subbuf,
+            attr->switch_timer_interval,
+            attr->read_timer_interval,
+            attr->output,
+            attr->type);
 
        if (channel->type == CONSUMER_CHANNEL_TYPE_METADATA)
                nr_stream_fds = 1;
@@ -373,8 +382,7 @@ static int create_ust_channel(struct lttng_consumer_channel *channel,
                goto error_alloc;
        }
        for (i = 0; i < nr_stream_fds; i++) {
-               stream_fds[i] = open_ust_stream_fd(channel, i,
-                               &channel->buffer_credentials.value);
+               stream_fds[i] = open_ust_stream_fd(channel, i, &channel->buffer_credentials.value);
                if (stream_fds[i] < 0) {
                        ret = -1;
                        goto error_open;
@@ -403,16 +411,15 @@ error_open:
                if (channel->shm_path[0]) {
                        char shm_path[PATH_MAX];
 
-                       closeret = get_stream_shm_path(shm_path,
-                                       channel->shm_path, j);
+                       closeret = get_stream_shm_path(shm_path, channel->shm_path, j);
                        if (closeret) {
                                ERR("Cannot get stream shm path");
                        }
                        closeret = run_as_unlink(shm_path,
-                                       lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
-                                                       channel->buffer_credentials)),
-                                       lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
-                                                       channel->buffer_credentials)));
+                                                lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
+                                                        channel->buffer_credentials)),
+                                                lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
+                                                        channel->buffer_credentials)));
                        if (closeret) {
                                PERROR("unlink %s", shm_path);
                        }
@@ -421,11 +428,11 @@ error_open:
        /* Try to rmdir all directories under shm_path root. */
        if (channel->root_shm_path[0]) {
                (void) run_as_rmdir_recursive(channel->root_shm_path,
-                               lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
-                                               channel->buffer_credentials)),
-                               lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
-                                               channel->buffer_credentials)),
-                               LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+                                             lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
+                                                     channel->buffer_credentials)),
+                                             lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
+                                                     channel->buffer_credentials)),
+                                             LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
        }
        free(stream_fds);
 error_alloc:
@@ -462,8 +469,9 @@ error:
  * Return 0 on success or else a negative value.
  */
 static int send_channel_to_sessiond_and_relayd(int sock,
-               struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx, int *relayd_error)
+                                              struct lttng_consumer_channel *channel,
+                                              struct lttng_consumer_local_data *ctx,
+                                              int *relayd_error)
 {
        int ret, ret_code = LTTCOMM_CONSUMERD_SUCCESS;
        struct lttng_consumer_stream *stream;
@@ -476,13 +484,13 @@ static int send_channel_to_sessiond_and_relayd(int sock,
        DBG("UST consumer sending channel %s to sessiond", channel->name);
 
        if (channel->relayd_id != (uint64_t) -1ULL) {
-               cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
-
+               cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
                        health_code_update();
 
                        /* Try to send the stream to the relayd if one is available. */
                        DBG("Sending stream %" PRIu64 " of channel \"%s\" to relayd",
-                                       stream->key, channel->name);
+                           stream->key,
+                           channel->name);
                        ret = consumer_send_relayd_stream(stream, stream->chan->pathname);
                        if (ret < 0) {
                                /*
@@ -522,8 +530,7 @@ static int send_channel_to_sessiond_and_relayd(int sock,
        }
 
        /* The channel was sent successfully to the sessiond at this point. */
-       cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
-
+       cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
                health_code_update();
 
                /* Send stream to session daemon. */
@@ -534,7 +541,7 @@ static int send_channel_to_sessiond_and_relayd(int sock,
        }
 
        /* Tell sessiond there is no more stream. */
-       ret = lttng_ust_ctl_send_stream_to_sessiond(sock, NULL);
+       ret = lttng_ust_ctl_send_stream_to_sessiond(sock, nullptr);
        if (ret < 0) {
                goto error;
        }
@@ -559,8 +566,8 @@ error:
  * MUST be destroyed by consumer_del_channel().
  */
 static int ask_channel(struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_channel *channel,
-               struct lttng_ust_ctl_consumer_channel_attr *attr)
+                      struct lttng_consumer_channel *channel,
+                      struct lttng_ust_ctl_consumer_channel_attr *attr)
 {
        int ret;
 
@@ -618,7 +625,7 @@ end:
  * On error, return a negative value else 0 on success.
  */
 static int send_streams_to_thread(struct lttng_consumer_channel *channel,
-               struct lttng_consumer_local_data *ctx)
+                                 struct lttng_consumer_local_data *ctx)
 {
        int ret = 0;
        struct lttng_consumer_stream *stream, *stmp;
@@ -627,9 +634,7 @@ static int send_streams_to_thread(struct lttng_consumer_channel *channel,
        LTTNG_ASSERT(ctx);
 
        /* Send streams to the corresponding thread. */
-       cds_list_for_each_entry_safe(stream, stmp, &channel->streams.head,
-                       send_node) {
-
+       cds_list_for_each_entry_safe (stream, stmp, &channel->streams.head, send_node) {
                health_code_update();
 
                /* Sending the stream to the thread. */
@@ -662,7 +667,7 @@ static int flush_channel(uint64_t chan_key)
 
        DBG("UST consumer flush channel key %" PRIu64, chan_key);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        channel = consumer_find_channel(chan_key);
        if (!channel) {
                ERR("UST consumer flush channel %" PRIu64 " not found", chan_key);
@@ -674,9 +679,13 @@ static int flush_channel(uint64_t chan_key)
 
        /* For each stream of the channel id, flush it. */
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed), ht->match_fct,
-                       &channel->key, &iter.iter, stream, node_channel_id.node) {
-
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                health_code_update();
 
                pthread_mutex_lock(&stream->lock);
@@ -691,15 +700,17 @@ static int flush_channel(uint64_t chan_key)
                if (!stream->quiescent) {
                        ret = lttng_ust_ctl_flush_buffer(stream->ustream, 0);
                        if (ret) {
-                               ERR("Failed to flush buffer while flushing channel: channel key = %" PRIu64 ", channel name = '%s'",
-                                               chan_key, channel->name);
+                               ERR("Failed to flush buffer while flushing channel: channel key = %" PRIu64
+                                   ", channel name = '%s'",
+                                   chan_key,
+                                   channel->name);
                                ret = LTTNG_ERR_BUFFER_FLUSH_FAILED;
                                pthread_mutex_unlock(&stream->lock);
                                goto error;
                        }
                        stream->quiescent = true;
                }
-next:
+       next:
                pthread_mutex_unlock(&stream->lock);
        }
 
@@ -711,7 +722,6 @@ next:
         */
        sample_and_send_channel_buffer_stats(channel);
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -731,7 +741,7 @@ static int clear_quiescent_channel(uint64_t chan_key)
 
        DBG("UST consumer clear quiescent channel key %" PRIu64, chan_key);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
        channel = consumer_find_channel(chan_key);
        if (!channel) {
                ERR("UST consumer clear quiescent channel %" PRIu64 " not found", chan_key);
@@ -743,9 +753,13 @@ static int clear_quiescent_channel(uint64_t chan_key)
 
        /* For each stream of the channel id, clear quiescent state. */
        cds_lfht_for_each_entry_duplicate(ht->ht,
-                       ht->hash_fct(&channel->key, lttng_ht_seed), ht->match_fct,
-                       &channel->key, &iter.iter, stream, node_channel_id.node) {
-
+                                         ht->hash_fct(&channel->key, lttng_ht_seed),
+                                         ht->match_fct,
+                                         &channel->key,
+                                         &iter.iter,
+                                         stream,
+                                         node_channel_id.node)
+       {
                health_code_update();
 
                pthread_mutex_lock(&stream->lock);
@@ -753,7 +767,6 @@ static int clear_quiescent_channel(uint64_t chan_key)
                pthread_mutex_unlock(&stream->lock);
        }
 error:
-       rcu_read_unlock();
        return ret;
 }
 
@@ -877,14 +890,12 @@ static int setup_metadata(struct lttng_consumer_local_data *ctx, uint64_t key)
 
        /* Send metadata stream to relayd if needed. */
        if (metadata->metadata_stream->net_seq_idx != (uint64_t) -1ULL) {
-               ret = consumer_send_relayd_stream(metadata->metadata_stream,
-                               metadata->pathname);
+               ret = consumer_send_relayd_stream(metadata->metadata_stream, metadata->pathname);
                if (ret < 0) {
                        ret = LTTCOMM_CONSUMERD_ERROR_METADATA;
                        goto error;
                }
-               ret = consumer_send_relayd_streams_sent(
-                               metadata->metadata_stream->net_seq_idx);
+               ret = consumer_send_relayd_streams_sent(metadata->metadata_stream->net_seq_idx);
                if (ret < 0) {
                        ret = LTTCOMM_CONSUMERD_RELAYD_FAIL;
                        goto error;
@@ -917,8 +928,10 @@ error:
         * the stream is still in the local stream list of the channel. This call
         * will make sure to clean that list.
         */
-       consumer_stream_destroy(metadata->metadata_stream, NULL);
-       metadata->metadata_stream = NULL;
+       consumer_stream_destroy(metadata->metadata_stream, nullptr);
+       metadata->metadata_stream = nullptr;
+       metadata->metadata_pushed_wait_queue.wake_all();
+
 send_streams_error:
 error_no_stream:
 end:
@@ -932,8 +945,10 @@ end:
  * Returns 0 on success, < 0 on error
  */
 static int snapshot_metadata(struct lttng_consumer_channel *metadata_channel,
-               uint64_t key, char *path, uint64_t relayd_id,
-               struct lttng_consumer_local_data *ctx)
+                            uint64_t key,
+                            char *path,
+                            uint64_t relayd_id,
+                            struct lttng_consumer_local_data *ctx)
 {
        int ret = 0;
        struct lttng_consumer_stream *metadata_stream;
@@ -942,10 +957,9 @@ static int snapshot_metadata(struct lttng_consumer_channel *metadata_channel,
        LTTNG_ASSERT(ctx);
        ASSERT_RCU_READ_LOCKED();
 
-       DBG("UST consumer snapshot metadata with key %" PRIu64 " at path %s",
-                       key, path);
+       DBG("UST consumer snapshot metadata with key %" PRIu64 " at path %s", key, path);
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        LTTNG_ASSERT(!metadata_channel->monitor);
 
@@ -955,7 +969,7 @@ static int snapshot_metadata(struct lttng_consumer_channel *metadata_channel,
         * Ask the sessiond if we have new metadata waiting and update the
         * consumer metadata cache.
         */
-       ret = lttng_ustconsumer_request_metadata(ctx, metadata_channel, 0, 1);
+       ret = lttng_ustconsumer_request_metadata(ctx, metadata_channel, false, 1);
        if (ret < 0) {
                goto error;
        }
@@ -979,8 +993,7 @@ static int snapshot_metadata(struct lttng_consumer_channel *metadata_channel,
                metadata_stream->net_seq_idx = relayd_id;
                ret = consumer_send_relayd_stream(metadata_stream, path);
        } else {
-               ret = consumer_stream_create_output_files(metadata_stream,
-                               false);
+               ret = consumer_stream_create_output_files(metadata_stream, false);
        }
        if (ret < 0) {
                goto error_stream;
@@ -1000,17 +1013,15 @@ error_stream:
         * Clean up the stream completely because the next snapshot will use a
         * new metadata stream.
         */
-       consumer_stream_destroy(metadata_stream, NULL);
-       metadata_channel->metadata_stream = NULL;
+       consumer_stream_destroy(metadata_stream, nullptr);
+       metadata_channel->metadata_stream = nullptr;
+       metadata_channel->metadata_pushed_wait_queue.wake_all();
 
 error:
-       rcu_read_unlock();
        return ret;
 }
 
-static
-int get_current_subbuf_addr(struct lttng_consumer_stream *stream,
-               const char **addr)
+static int get_current_subbuf_addr(struct lttng_consumer_stream *stream, const char **addr)
 {
        int ret;
        unsigned long mmap_offset;
@@ -1018,8 +1029,7 @@ int get_current_subbuf_addr(struct lttng_consumer_stream *stream,
 
        mmap_base = (const char *) lttng_ust_ctl_get_mmap_base(stream->ustream);
        if (!mmap_base) {
-               ERR("Failed to get mmap base for stream `%s`",
-                               stream->name);
+               ERR("Failed to get mmap base for stream `%s`", stream->name);
                ret = -EPERM;
                goto error;
        }
@@ -1034,7 +1044,6 @@ int get_current_subbuf_addr(struct lttng_consumer_stream *stream,
        *addr = mmap_base + mmap_offset;
 error:
        return ret;
-
 }
 
 /*
@@ -1044,9 +1053,11 @@ error:
  * Returns 0 on success, < 0 on error
  */
 static int snapshot_channel(struct lttng_consumer_channel *channel,
-               uint64_t key, char *path, uint64_t relayd_id,
-               uint64_t nb_packets_per_stream,
-               struct lttng_consumer_local_data *ctx)
+                           uint64_t key,
+                           char *path,
+                           uint64_t relayd_id,
+                           uint64_t nb_packets_per_stream,
+                           struct lttng_consumer_local_data *ctx)
 {
        int ret;
        unsigned use_relayd = 0;
@@ -1057,7 +1068,7 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
        LTTNG_ASSERT(ctx);
        ASSERT_RCU_READ_LOCKED();
 
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        if (relayd_id != (uint64_t) -1ULL) {
                use_relayd = 1;
@@ -1066,7 +1077,7 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
        LTTNG_ASSERT(!channel->monitor);
        DBG("UST consumer snapshot channel %" PRIu64, key);
 
-       cds_list_for_each_entry(stream, &channel->streams.head, send_node) {
+       cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
                health_code_update();
 
                /* Lock stream because we are about to change its state. */
@@ -1089,16 +1100,14 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                if (use_relayd) {
                        ret = consumer_send_relayd_stream(stream, path);
                        if (ret < 0) {
-                               goto error_unlock;
+                               goto error_close_stream;
                        }
                } else {
-                       ret = consumer_stream_create_output_files(stream,
-                                       false);
+                       ret = consumer_stream_create_output_files(stream, false);
                        if (ret < 0) {
-                               goto error_unlock;
+                               goto error_close_stream;
                        }
-                       DBG("UST consumer snapshot stream (%" PRIu64 ")",
-                                       stream->key);
+                       DBG("UST consumer snapshot stream (%" PRIu64 ")", stream->key);
                }
 
                /*
@@ -1108,8 +1117,10 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                if (!stream->quiescent) {
                        ret = lttng_ust_ctl_flush_buffer(stream->ustream, 0);
                        if (ret < 0) {
-                               ERR("Failed to flush buffer during snapshot of channel: channel key = %" PRIu64 ", channel name = '%s'",
-                                               channel->key, channel->name);
+                               ERR("Failed to flush buffer during snapshot of channel: channel key = %" PRIu64
+                                   ", channel name = '%s'",
+                                   channel->key,
+                                   channel->name);
                                goto error_unlock;
                        }
                }
@@ -1117,19 +1128,19 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                ret = lttng_ustconsumer_take_snapshot(stream);
                if (ret < 0) {
                        ERR("Taking UST snapshot");
-                       goto error_unlock;
+                       goto error_close_stream;
                }
 
                ret = lttng_ustconsumer_get_produced_snapshot(stream, &produced_pos);
                if (ret < 0) {
                        ERR("Produced UST snapshot position");
-                       goto error_unlock;
+                       goto error_close_stream;
                }
 
                ret = lttng_ustconsumer_get_consumed_snapshot(stream, &consumed_pos);
                if (ret < 0) {
                        ERR("Consumerd UST snapshot position");
-                       goto error_unlock;
+                       goto error_close_stream;
                }
 
                /*
@@ -1138,9 +1149,8 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                 * daemon should never send a maximum stream size that is lower than
                 * subbuffer size.
                 */
-               consumed_pos = consumer_get_consume_start_pos(consumed_pos,
-                               produced_pos, nb_packets_per_stream,
-                               stream->max_sb_size);
+               consumed_pos = consumer_get_consume_start_pos(
+                       consumed_pos, produced_pos, nb_packets_per_stream, stream->max_sb_size);
 
                while ((long) (consumed_pos - produced_pos) < 0) {
                        ssize_t read_len;
@@ -1181,10 +1191,9 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                                goto error_put_subbuf;
                        }
 
-                       subbuf_view = lttng_buffer_view_init(
-                                       subbuf_addr, 0, padded_len);
+                       subbuf_view = lttng_buffer_view_init(subbuf_addr, 0, padded_len);
                        read_len = lttng_consumer_on_read_subbuffer_mmap(
-                                       stream, &subbuf_view, padded_len - len);
+                               stream, &subbuf_view, padded_len - len);
                        if (use_relayd) {
                                if (read_len != len) {
                                        ret = -EPERM;
@@ -1206,11 +1215,10 @@ static int snapshot_channel(struct lttng_consumer_channel *channel,
                }
 
                /* Simply close the stream so we can use it on the next snapshot. */
-               consumer_stream_close(stream);
+               consumer_stream_close_output(stream);
                pthread_mutex_unlock(&stream->lock);
        }
 
-       rcu_read_unlock();
        return 0;
 
 error_put_subbuf:
@@ -1218,21 +1226,17 @@ error_put_subbuf:
                ERR("Snapshot lttng_ust_ctl_put_subbuf");
        }
 error_close_stream:
-       consumer_stream_close(stream);
+       consumer_stream_close_output(stream);
 error_unlock:
        pthread_mutex_unlock(&stream->lock);
-       rcu_read_unlock();
        return ret;
 }
 
-static
-void metadata_stream_reset_cache_consumed_position(
-               struct lttng_consumer_stream *stream)
+static void metadata_stream_reset_cache_consumed_position(struct lttng_consumer_stream *stream)
 {
        ASSERT_LOCKED(stream->lock);
 
-       DBG("Reset metadata cache of session %" PRIu64,
-                       stream->chan->session_id);
+       DBG("Reset metadata cache of session %" PRIu64, stream->chan->session_id);
        stream->ust_metadata_pushed = 0;
 }
 
@@ -1244,9 +1248,14 @@ void metadata_stream_reset_cache_consumed_position(
  * the metadata cache flush to concurrently progress in order to
  * complete.
  */
-int lttng_ustconsumer_recv_metadata(int sock, uint64_t key, uint64_t offset,
-               uint64_t len, uint64_t version,
-               struct lttng_consumer_channel *channel, int timer, int wait)
+int lttng_ustconsumer_recv_metadata(int sock,
+                                   uint64_t key,
+                                   uint64_t offset,
+                                   uint64_t len,
+                                   uint64_t version,
+                                   struct lttng_consumer_channel *channel,
+                                   bool invoked_by_timer,
+                                   int wait)
 {
        int ret, ret_code = LTTCOMM_CONSUMERD_SUCCESS;
        char *metadata_str;
@@ -1275,8 +1284,7 @@ int lttng_ustconsumer_recv_metadata(int sock, uint64_t key, uint64_t offset,
 
        pthread_mutex_lock(&channel->metadata_cache->lock);
        cache_write_status = consumer_metadata_cache_write(
-                       channel->metadata_cache, offset, len, version,
-                       metadata_str);
+               channel->metadata_cache, offset, len, version, metadata_str);
        pthread_mutex_unlock(&channel->metadata_cache->lock);
        switch (cache_write_status) {
        case CONSUMER_METADATA_CACHE_WRITE_STATUS_NO_CHANGE:
@@ -1298,10 +1306,9 @@ int lttng_ustconsumer_recv_metadata(int sock, uint64_t key, uint64_t offset,
                 * channel is under a snapshot session type. No need to update
                 * the stream position in that scenario.
                 */
-               if (channel->metadata_stream != NULL) {
+               if (channel->metadata_stream != nullptr) {
                        pthread_mutex_lock(&channel->metadata_stream->lock);
-                       metadata_stream_reset_cache_consumed_position(
-                                       channel->metadata_stream);
+                       metadata_stream_reset_cache_consumed_position(channel->metadata_stream);
                        pthread_mutex_unlock(&channel->metadata_stream->lock);
                } else {
                        /* Validate we are in snapshot mode. */
@@ -1335,13 +1342,8 @@ int lttng_ustconsumer_recv_metadata(int sock, uint64_t key, uint64_t offset,
        if (!wait) {
                goto end_free;
        }
-       while (consumer_metadata_cache_flushed(channel, offset + len, timer)) {
-               DBG("Waiting for metadata to be flushed");
-
-               health_code_update();
 
-               usleep(DEFAULT_METADATA_AVAILABILITY_WAIT_TIME);
-       }
+       consumer_wait_metadata_cache_flushed(channel, offset + len, invoked_by_timer);
 
 end_free:
        free(metadata_str);
@@ -1355,12 +1357,13 @@ end:
  * Return 1 on success else a negative value or 0.
  */
 int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll)
+                              int sock,
+                              struct pollfd *consumer_sockpoll)
 {
        int ret_func;
        enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
        struct lttcomm_consumer_msg msg;
-       struct lttng_consumer_channel *channel = NULL;
+       struct lttng_consumer_channel *channel = nullptr;
 
        health_code_update();
 
@@ -1370,14 +1373,14 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                ret_recv = lttcomm_recv_unix_sock(sock, &msg, sizeof(msg));
                if (ret_recv != sizeof(msg)) {
                        DBG("Consumer received unexpected message size %zd (expects %zu)",
-                                       ret_recv, sizeof(msg));
+                           ret_recv,
+                           sizeof(msg));
                        /*
                         * The ret value might 0 meaning an orderly shutdown but this is ok
                         * since the caller handles this.
                         */
                        if (ret_recv > 0) {
-                               lttng_consumer_send_error(ctx,
-                                               LTTCOMM_CONSUMERD_ERROR_RECV_CMD);
+                               lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_CMD);
                                ret_recv = -1;
                        }
                        return ret_recv;
@@ -1392,7 +1395,7 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
        health_code_update();
 
        /* relayd needs RCU read-side lock */
-       rcu_read_lock();
+       lttng::urcu::read_lock_guard read_lock;
 
        switch (msg.cmd_type) {
        case LTTNG_CONSUMER_ADD_RELAYD_SOCKET:
@@ -1400,15 +1403,19 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                uint32_t major = msg.u.relayd_sock.major;
                uint32_t minor = msg.u.relayd_sock.minor;
                enum lttcomm_sock_proto protocol =
-                               (enum lttcomm_sock_proto) msg.u.relayd_sock
-                                               .relayd_socket_protocol;
+                       (enum lttcomm_sock_proto) msg.u.relayd_sock.relayd_socket_protocol;
 
                /* Session daemon status message are handled in the following call. */
                consumer_add_relayd_socket(msg.u.relayd_sock.net_index,
-                               msg.u.relayd_sock.type, ctx, sock,
-                               consumer_sockpoll, msg.u.relayd_sock.session_id,
-                               msg.u.relayd_sock.relayd_session_id, major,
-                               minor, protocol);
+                                          msg.u.relayd_sock.type,
+                                          ctx,
+                                          sock,
+                                          consumer_sockpoll,
+                                          msg.u.relayd_sock.session_id,
+                                          msg.u.relayd_sock.relayd_session_id,
+                                          major,
+                                          minor,
+                                          protocol);
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_DESTROY_RELAYD:
@@ -1420,7 +1427,7 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                /* Get relayd reference if exists. */
                relayd = consumer_find_relayd(index);
-               if (relayd == NULL) {
+               if (relayd == nullptr) {
                        DBG("Unable to find relayd %" PRIu64, index);
                        ret_code = LTTCOMM_CONSUMERD_RELAYD_FAIL;
                }
@@ -1443,7 +1450,6 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
        }
        case LTTNG_CONSUMER_UPDATE_STREAM:
        {
-               rcu_read_unlock();
                return -ENOSYS;
        }
        case LTTNG_CONSUMER_DATA_PENDING:
@@ -1457,11 +1463,9 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                is_data_pending = consumer_data_pending(id);
 
                /* Send back returned value to session daemon */
-               ret_send = lttcomm_send_unix_sock(sock, &is_data_pending,
-                               sizeof(is_data_pending));
+               ret_send = lttcomm_send_unix_sock(sock, &is_data_pending, sizeof(is_data_pending));
                if (ret_send < 0) {
-                       DBG("Error when sending the data pending ret code: %zd",
-                                       ret_send);
+                       DBG("Error when sending the data pending ret code: %zd", ret_send);
                        goto error_fatal;
                }
 
@@ -1483,28 +1487,26 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
 
                /* Create a plain object and reserve a channel key. */
                channel = consumer_allocate_channel(
-                               msg.u.ask_channel.key,
-                               msg.u.ask_channel.session_id,
-                               msg.u.ask_channel.chunk_id.is_set ?
-                                               &chunk_id : NULL,
-                               msg.u.ask_channel.pathname,
-                               msg.u.ask_channel.name,
-                               msg.u.ask_channel.relayd_id,
-                               (enum lttng_event_output) msg.u.ask_channel.output,
-                               msg.u.ask_channel.tracefile_size,
-                               msg.u.ask_channel.tracefile_count,
-                               msg.u.ask_channel.session_id_per_pid,
-                               msg.u.ask_channel.monitor,
-                               msg.u.ask_channel.live_timer_interval,
-                               msg.u.ask_channel.is_live,
-                               msg.u.ask_channel.root_shm_path,
-                               msg.u.ask_channel.shm_path);
+                       msg.u.ask_channel.key,
+                       msg.u.ask_channel.session_id,
+                       msg.u.ask_channel.chunk_id.is_set ? &chunk_id : nullptr,
+                       msg.u.ask_channel.pathname,
+                       msg.u.ask_channel.name,
+                       msg.u.ask_channel.relayd_id,
+                       (enum lttng_event_output) msg.u.ask_channel.output,
+                       msg.u.ask_channel.tracefile_size,
+                       msg.u.ask_channel.tracefile_count,
+                       msg.u.ask_channel.session_id_per_pid,
+                       msg.u.ask_channel.monitor,
+                       msg.u.ask_channel.live_timer_interval,
+                       msg.u.ask_channel.is_live,
+                       msg.u.ask_channel.root_shm_path,
+                       msg.u.ask_channel.shm_path);
                if (!channel) {
                        goto end_channel_error;
                }
 
-               LTTNG_OPTIONAL_SET(&channel->buffer_credentials,
-                               buffer_credentials);
+               LTTNG_OPTIONAL_SET(&channel->buffer_credentials, buffer_credentials);
 
                /*
                 * Assign UST application UID to the channel. This value is ignored for
@@ -1521,7 +1523,7 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                attr.read_timer_interval = msg.u.ask_channel.read_timer_interval;
                attr.chan_id = msg.u.ask_channel.chan_id;
                memcpy(attr.uuid, msg.u.ask_channel.uuid, sizeof(attr.uuid));
-               attr.blocking_timeout= msg.u.ask_channel.blocking_timeout;
+               attr.blocking_timeout = msg.u.ask_channel.blocking_timeout;
 
                /* Match channel buffer type to the UST abi. */
                switch (msg.u.ask_channel.output) {
@@ -1562,8 +1564,7 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                if (msg.u.ask_channel.type == LTTNG_UST_ABI_CHAN_METADATA) {
                        int ret_allocate;
 
-                       ret_allocate = consumer_metadata_cache_allocate(
-                                       channel);
+                       ret_allocate = consumer_metadata_cache_allocate(channel);
                        if (ret_allocate < 0) {
                                ERR("Allocating metadata cache");
                                goto end_channel_error;
@@ -1573,11 +1574,9 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                } else {
                        int monitor_start_ret;
 
-                       consumer_timer_live_start(channel,
-                                       msg.u.ask_channel.live_timer_interval);
+                       consumer_timer_live_start(channel, msg.u.ask_channel.live_timer_interval);
                        monitor_start_ret = consumer_timer_monitor_start(
-                                       channel,
-                                       msg.u.ask_channel.monitor_timer_interval);
+                               channel, msg.u.ask_channel.monitor_timer_interval);
                        if (monitor_start_ret < 0) {
                                ERR("Starting channel monitoring timer failed");
                                goto end_channel_error;
@@ -1643,8 +1642,7 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                health_code_update();
 
                /* Send the channel to sessiond (and relayd, if applicable). */
-               ret = send_channel_to_sessiond_and_relayd(
-                               sock, found_channel, ctx, &relayd_err);
+               ret = send_channel_to_sessiond_and_relayd(sock, found_channel, ctx, &relayd_err);
                if (ret < 0) {
                        if (relayd_err) {
                                /*
@@ -1682,11 +1680,11 @@ int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
                }
                /* List MUST be empty after or else it could be reused. */
                LTTNG_ASSERT(cds_list_empty(&found_channel->streams.head));
-end_get_channel:
+       end_get_channel:
                goto end_msg_sessiond;
-error_get_channel_fatal:
+       error_get_channel_fatal:
                goto error_fatal;
-end_get_channel_nosignal:
+       end_get_channel_nosignal:
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_DESTROY_CHANNEL:
@@ -1727,8 +1725,7 @@ end_get_channel_nosignal:
        {
                int ret;
 
-               ret = clear_quiescent_channel(
-                               msg.u.clear_quiescent_channel.key);
+               ret = clear_quiescent_channel(msg.u.clear_quiescent_channel.key);
                if (ret != 0) {
                        ret_code = (lttcomm_return_code) ret;
                }
@@ -1744,8 +1741,7 @@ end_get_channel_nosignal:
                uint64_t version = msg.u.push_metadata.version;
                struct lttng_consumer_channel *found_channel;
 
-               DBG("UST consumer push metadata key %" PRIu64 " of len %" PRIu64, key,
-                               len);
+               DBG("UST consumer push metadata key %" PRIu64 " of len %" PRIu64, key, len);
 
                found_channel = consumer_find_channel(key);
                if (!found_channel) {
@@ -1791,8 +1787,8 @@ end_get_channel_nosignal:
 
                health_code_update();
 
-               ret = lttng_ustconsumer_recv_metadata(sock, key, offset, len,
-                               version, found_channel, 0, 1);
+               ret = lttng_ustconsumer_recv_metadata(
+                       sock, key, offset, len, version, found_channel, false, 1);
                if (ret < 0) {
                        /* error receiving from sessiond */
                        goto error_push_metadata_fatal;
@@ -1800,9 +1796,9 @@ end_get_channel_nosignal:
                        ret_code = (lttcomm_return_code) ret;
                        goto end_push_metadata_msg_sessiond;
                }
-end_push_metadata_msg_sessiond:
+       end_push_metadata_msg_sessiond:
                goto end_msg_sessiond;
-error_push_metadata_fatal:
+       error_push_metadata_fatal:
                goto error_fatal;
        }
        case LTTNG_CONSUMER_SETUP_METADATA:
@@ -1830,10 +1826,10 @@ error_push_metadata_fatal:
                                int ret_snapshot;
 
                                ret_snapshot = snapshot_metadata(found_channel,
-                                               key,
-                                               msg.u.snapshot_channel.pathname,
-                                               msg.u.snapshot_channel.relayd_id,
-                                               ctx);
+                                                                key,
+                                                                msg.u.snapshot_channel.pathname,
+                                                                msg.u.snapshot_channel.relayd_id,
+                                                                ctx);
                                if (ret_snapshot < 0) {
                                        ERR("Snapshot metadata failed");
                                        ret_code = LTTCOMM_CONSUMERD_SNAPSHOT_FAILED;
@@ -1841,13 +1837,13 @@ error_push_metadata_fatal:
                        } else {
                                int ret_snapshot;
 
-                               ret_snapshot = snapshot_channel(found_channel,
-                                               key,
-                                               msg.u.snapshot_channel.pathname,
-                                               msg.u.snapshot_channel.relayd_id,
-                                               msg.u.snapshot_channel
-                                                               .nb_packets_per_stream,
-                                               ctx);
+                               ret_snapshot = snapshot_channel(
+                                       found_channel,
+                                       key,
+                                       msg.u.snapshot_channel.pathname,
+                                       msg.u.snapshot_channel.relayd_id,
+                                       msg.u.snapshot_channel.nb_packets_per_stream,
+                                       ctx);
                                if (ret_snapshot < 0) {
                                        ERR("Snapshot channel failed");
                                        ret_code = LTTCOMM_CONSUMERD_SNAPSHOT_FAILED;
@@ -1873,9 +1869,7 @@ error_push_metadata_fatal:
                uint64_t id = msg.u.discarded_events.session_id;
                uint64_t key = msg.u.discarded_events.channel_key;
 
-               DBG("UST consumer discarded events command for session id %"
-                               PRIu64, id);
-               rcu_read_lock();
+               DBG("UST consumer discarded events command for session id %" PRIu64, id);
                pthread_mutex_lock(&the_consumer_data.lock);
 
                ht = the_consumer_data.stream_list_ht;
@@ -1889,19 +1883,24 @@ error_push_metadata_fatal:
                 */
                discarded_events = 0;
                cds_lfht_for_each_entry_duplicate(ht->ht,
-                               ht->hash_fct(&id, lttng_ht_seed),
-                               ht->match_fct, &id,
-                               &iter.iter, stream, node_session_id.node) {
+                                                 ht->hash_fct(&id, lttng_ht_seed),
+                                                 ht->match_fct,
+                                                 &id,
+                                                 &iter.iter,
+                                                 stream,
+                                                 node_session_id.node)
+               {
                        if (stream->chan->key == key) {
                                discarded_events = stream->chan->discarded_events;
                                break;
                        }
                }
                pthread_mutex_unlock(&the_consumer_data.lock);
-               rcu_read_unlock();
 
-               DBG("UST consumer discarded events command for session id %"
-                               PRIu64 ", channel key %" PRIu64, id, key);
+               DBG("UST consumer discarded events command for session id %" PRIu64
+                   ", channel key %" PRIu64,
+                   id,
+                   key);
 
                health_code_update();
 
@@ -1916,7 +1915,7 @@ error_push_metadata_fatal:
        }
        case LTTNG_CONSUMER_LOST_PACKETS:
        {
-               int ret;
+               int ret;
                uint64_t lost_packets;
                struct lttng_ht_iter iter;
                struct lttng_ht *ht;
@@ -1924,9 +1923,7 @@ error_push_metadata_fatal:
                uint64_t id = msg.u.lost_packets.session_id;
                uint64_t key = msg.u.lost_packets.channel_key;
 
-               DBG("UST consumer lost packets command for session id %"
-                               PRIu64, id);
-               rcu_read_lock();
+               DBG("UST consumer lost packets command for session id %" PRIu64, id);
                pthread_mutex_lock(&the_consumer_data.lock);
 
                ht = the_consumer_data.stream_list_ht;
@@ -1937,27 +1934,31 @@ error_push_metadata_fatal:
                 * to extract the information we need, we default to 0 if not
                 * found (no packets lost if the channel is not yet in use).
                 */
-               lost_packets = 0;
+               lost_packets = 0;
                cds_lfht_for_each_entry_duplicate(ht->ht,
-                               ht->hash_fct(&id, lttng_ht_seed),
-                               ht->match_fct, &id,
-                               &iter.iter, stream, node_session_id.node) {
+                                                 ht->hash_fct(&id, lttng_ht_seed),
+                                                 ht->match_fct,
+                                                 &id,
+                                                 &iter.iter,
+                                                 stream,
+                                                 node_session_id.node)
+               {
                        if (stream->chan->key == key) {
-                               lost_packets = stream->chan->lost_packets;
+                               lost_packets = stream->chan->lost_packets;
                                break;
                        }
                }
                pthread_mutex_unlock(&the_consumer_data.lock);
-               rcu_read_unlock();
 
-               DBG("UST consumer lost packets command for session id %"
-                               PRIu64 ", channel key %" PRIu64, id, key);
+               DBG("UST consumer lost packets command for session id %" PRIu64
+                   ", channel key %" PRIu64,
+                   id,
+                   key);
 
                health_code_update();
 
                /* Send back returned value to session daemon */
-               ret = lttcomm_send_unix_sock(sock, &lost_packets,
-                               sizeof(lost_packets));
+               ret = lttcomm_send_unix_sock(sock, &lost_packets, sizeof(lost_packets));
                if (ret < 0) {
                        PERROR("send lost packets");
                        goto error_fatal;
@@ -1967,8 +1968,7 @@ error_push_metadata_fatal:
        }
        case LTTNG_CONSUMER_SET_CHANNEL_MONITOR_PIPE:
        {
-               int channel_monitor_pipe, ret_send,
-                               ret_set_channel_monitor_pipe;
+               int channel_monitor_pipe, ret_send, ret_set_channel_monitor_pipe;
                ssize_t ret_recv;
 
                ret_code = LTTCOMM_CONSUMERD_SUCCESS;
@@ -1978,8 +1978,7 @@ error_push_metadata_fatal:
                        goto error_fatal;
                }
 
-               ret_recv = lttcomm_recv_fds_unix_sock(
-                               sock, &channel_monitor_pipe, 1);
+               ret_recv = lttcomm_recv_fds_unix_sock(sock, &channel_monitor_pipe, 1);
                if (ret_recv != sizeof(channel_monitor_pipe)) {
                        ERR("Failed to receive channel monitor pipe");
                        goto error_fatal;
@@ -1987,8 +1986,7 @@ error_push_metadata_fatal:
 
                DBG("Received channel monitor pipe (%d)", channel_monitor_pipe);
                ret_set_channel_monitor_pipe =
-                               consumer_timer_thread_set_channel_monitor_pipe(
-                                               channel_monitor_pipe);
+                       consumer_timer_thread_set_channel_monitor_pipe(channel_monitor_pipe);
                if (!ret_set_channel_monitor_pipe) {
                        int flags;
                        int ret_fcntl;
@@ -2002,8 +2000,7 @@ error_push_metadata_fatal:
                        }
                        flags = ret_fcntl;
 
-                       ret_fcntl = fcntl(channel_monitor_pipe, F_SETFL,
-                                       flags | O_NONBLOCK);
+                       ret_fcntl = fcntl(channel_monitor_pipe, F_SETFL, flags | O_NONBLOCK);
                        if (ret_fcntl == -1) {
                                PERROR("fcntl set O_NONBLOCK flag of the channel monitoring pipe");
                                goto error_fatal;
@@ -2032,8 +2029,7 @@ error_push_metadata_fatal:
                         * this channel.
                         */
                        rotate_channel = lttng_consumer_rotate_channel(
-                                       found_channel, key,
-                                       msg.u.rotate_channel.relayd_id);
+                               found_channel, key, msg.u.rotate_channel.relayd_id);
                        if (rotate_channel < 0) {
                                ERR("Rotate channel failed");
                                ret_code = LTTCOMM_CONSUMERD_ROTATION_FAIL;
@@ -2059,14 +2055,13 @@ error_push_metadata_fatal:
                        int ret_rotate_read_streams;
 
                        ret_rotate_read_streams =
-                                       lttng_consumer_rotate_ready_streams(
-                                                       found_channel, key);
+                               lttng_consumer_rotate_ready_streams(found_channel, key);
                        if (ret_rotate_read_streams < 0) {
                                ERR("Rotate channel failed");
                        }
                }
                break;
-end_rotate_channel_nosignal:
+       end_rotate_channel_nosignal:
                goto end_nosignal;
        }
        case LTTNG_CONSUMER_CLEAR_CHANNEL:
@@ -2082,8 +2077,7 @@ end_rotate_channel_nosignal:
                } else {
                        int ret_clear_channel;
 
-                       ret_clear_channel = lttng_consumer_clear_channel(
-                                       found_channel);
+                       ret_clear_channel = lttng_consumer_clear_channel(found_channel);
                        if (ret_clear_channel) {
                                ERR("Clear channel failed key %" PRIu64, key);
                                ret_code = (lttcomm_return_code) ret_clear_channel;
@@ -2103,8 +2097,9 @@ end_rotate_channel_nosignal:
                int ret_send_status;
                lttng_uuid sessiond_uuid;
 
-               std::copy(std::begin(msg.u.init.sessiond_uuid), std::end(msg.u.init.sessiond_uuid),
-                               sessiond_uuid.begin());
+               std::copy(std::begin(msg.u.init.sessiond_uuid),
+                         std::end(msg.u.init.sessiond_uuid),
+                         sessiond_uuid.begin());
                ret_code = lttng_consumer_init_command(ctx, sessiond_uuid);
                health_code_update();
                ret_send_status = consumer_send_status_msg(sock, ret_code);
@@ -2117,18 +2112,17 @@ end_rotate_channel_nosignal:
        case LTTNG_CONSUMER_CREATE_TRACE_CHUNK:
        {
                const struct lttng_credentials credentials = {
-                       .uid = LTTNG_OPTIONAL_INIT_VALUE(msg.u.create_trace_chunk.credentials.value.uid),
-                       .gid = LTTNG_OPTIONAL_INIT_VALUE(msg.u.create_trace_chunk.credentials.value.gid),
+                       .uid = LTTNG_OPTIONAL_INIT_VALUE(
+                               msg.u.create_trace_chunk.credentials.value.uid),
+                       .gid = LTTNG_OPTIONAL_INIT_VALUE(
+                               msg.u.create_trace_chunk.credentials.value.gid),
                };
-               const bool is_local_trace =
-                               !msg.u.create_trace_chunk.relayd_id.is_set;
-               const uint64_t relayd_id =
-                               msg.u.create_trace_chunk.relayd_id.value;
-               const char *chunk_override_name =
-                               *msg.u.create_trace_chunk.override_name ?
-                                       msg.u.create_trace_chunk.override_name :
-                                       NULL;
-               struct lttng_directory_handle *chunk_directory_handle = NULL;
+               const bool is_local_trace = !msg.u.create_trace_chunk.relayd_id.is_set;
+               const uint64_t relayd_id = msg.u.create_trace_chunk.relayd_id.value;
+               const char *chunk_override_name = *msg.u.create_trace_chunk.override_name ?
+                       msg.u.create_trace_chunk.override_name :
+                       nullptr;
+               struct lttng_directory_handle *chunk_directory_handle = nullptr;
 
                /*
                 * The session daemon will only provide a chunk directory file
@@ -2140,8 +2134,7 @@ end_rotate_channel_nosignal:
                        ssize_t ret_recv;
 
                        /* Acnowledge the reception of the command. */
-                       ret_send_status = consumer_send_status_msg(
-                                       sock, LTTCOMM_CONSUMERD_SUCCESS);
+                       ret_send_status = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
                        if (ret_send_status < 0) {
                                /* Somehow, the session daemon is not responding anymore. */
                                goto end_nosignal;
@@ -2150,17 +2143,15 @@ end_rotate_channel_nosignal:
                        /*
                         * Receive trace chunk domain dirfd.
                         */
-                       ret_recv = lttcomm_recv_fds_unix_sock(
-                                       sock, &chunk_dirfd, 1);
+                       ret_recv = lttcomm_recv_fds_unix_sock(sock, &chunk_dirfd, 1);
                        if (ret_recv != sizeof(chunk_dirfd)) {
                                ERR("Failed to receive trace chunk domain directory file descriptor");
                                goto error_fatal;
                        }
 
-                       DBG("Received trace chunk domain directory fd (%d)",
-                                       chunk_dirfd);
-                       chunk_directory_handle = lttng_directory_handle_create_from_dirfd(
-                                       chunk_dirfd);
+                       DBG("Received trace chunk domain directory fd (%d)", chunk_dirfd);
+                       chunk_directory_handle =
+                               lttng_directory_handle_create_from_dirfd(chunk_dirfd);
                        if (!chunk_directory_handle) {
                                ERR("Failed to initialize chunk domain directory handle from directory file descriptor");
                                if (close(chunk_dirfd)) {
@@ -2171,48 +2162,39 @@ end_rotate_channel_nosignal:
                }
 
                ret_code = lttng_consumer_create_trace_chunk(
-                               !is_local_trace ? &relayd_id : NULL,
-                               msg.u.create_trace_chunk.session_id,
-                               msg.u.create_trace_chunk.chunk_id,
-                               (time_t) msg.u.create_trace_chunk
-                                               .creation_timestamp,
-                               chunk_override_name,
-                               msg.u.create_trace_chunk.credentials.is_set ?
-                                               &credentials :
-                                               NULL,
-                               chunk_directory_handle);
+                       !is_local_trace ? &relayd_id : nullptr,
+                       msg.u.create_trace_chunk.session_id,
+                       msg.u.create_trace_chunk.chunk_id,
+                       (time_t) msg.u.create_trace_chunk.creation_timestamp,
+                       chunk_override_name,
+                       msg.u.create_trace_chunk.credentials.is_set ? &credentials : nullptr,
+                       chunk_directory_handle);
                lttng_directory_handle_put(chunk_directory_handle);
                goto end_msg_sessiond;
        }
        case LTTNG_CONSUMER_CLOSE_TRACE_CHUNK:
        {
                enum lttng_trace_chunk_command_type close_command =
-                       (lttng_trace_chunk_command_type)
-                               msg.u.close_trace_chunk.close_command.value;
-               const uint64_t relayd_id =
-                               msg.u.close_trace_chunk.relayd_id.value;
+                       (lttng_trace_chunk_command_type) msg.u.close_trace_chunk.close_command.value;
+               const uint64_t relayd_id = msg.u.close_trace_chunk.relayd_id.value;
                struct lttcomm_consumer_close_trace_chunk_reply reply;
                char closed_trace_chunk_path[LTTNG_PATH_MAX] = {};
                int ret;
 
                ret_code = lttng_consumer_close_trace_chunk(
-                               msg.u.close_trace_chunk.relayd_id.is_set ?
-                                               &relayd_id :
-                                               NULL,
-                               msg.u.close_trace_chunk.session_id,
-                               msg.u.close_trace_chunk.chunk_id,
-                               (time_t) msg.u.close_trace_chunk.close_timestamp,
-                               msg.u.close_trace_chunk.close_command.is_set ?
-                                               &close_command :
-                                               NULL, closed_trace_chunk_path);
+                       msg.u.close_trace_chunk.relayd_id.is_set ? &relayd_id : nullptr,
+                       msg.u.close_trace_chunk.session_id,
+                       msg.u.close_trace_chunk.chunk_id,
+                       (time_t) msg.u.close_trace_chunk.close_timestamp,
+                       msg.u.close_trace_chunk.close_command.is_set ? &close_command : nullptr,
+                       closed_trace_chunk_path);
                reply.ret_code = ret_code;
                reply.path_length = strlen(closed_trace_chunk_path) + 1;
                ret = lttcomm_send_unix_sock(sock, &reply, sizeof(reply));
                if (ret != sizeof(reply)) {
                        goto error_fatal;
                }
-               ret = lttcomm_send_unix_sock(sock, closed_trace_chunk_path,
-                               reply.path_length);
+               ret = lttcomm_send_unix_sock(sock, closed_trace_chunk_path, reply.path_length);
                if (ret != reply.path_length) {
                        goto error_fatal;
                }
@@ -2220,26 +2202,22 @@ end_rotate_channel_nosignal:
        }
        case LTTNG_CONSUMER_TRACE_CHUNK_EXISTS:
        {
-               const uint64_t relayd_id =
-                               msg.u.trace_chunk_exists.relayd_id.value;
+               const uint64_t relayd_id = msg.u.trace_chunk_exists.relayd_id.value;
 
                ret_code = lttng_consumer_trace_chunk_exists(
-                               msg.u.trace_chunk_exists.relayd_id.is_set ?
-                                               &relayd_id : NULL,
-                               msg.u.trace_chunk_exists.session_id,
-                               msg.u.trace_chunk_exists.chunk_id);
+                       msg.u.trace_chunk_exists.relayd_id.is_set ? &relayd_id : nullptr,
+                       msg.u.trace_chunk_exists.session_id,
+                       msg.u.trace_chunk_exists.chunk_id);
                goto end_msg_sessiond;
        }
        case LTTNG_CONSUMER_OPEN_CHANNEL_PACKETS:
        {
                const uint64_t key = msg.u.open_channel_packets.key;
-               struct lttng_consumer_channel *found_channel =
-                               consumer_find_channel(key);
+               struct lttng_consumer_channel *found_channel = consumer_find_channel(key);
 
                if (found_channel) {
                        pthread_mutex_lock(&found_channel->lock);
-                       ret_code = lttng_consumer_open_channel_packets(
-                                       found_channel);
+                       ret_code = lttng_consumer_open_channel_packets(found_channel);
                        pthread_mutex_unlock(&found_channel->lock);
                } else {
                        /*
@@ -2291,7 +2269,7 @@ end_channel_error:
        {
                int ret_send_status;
 
-               ret_send_status = consumer_send_status_channel(sock, NULL);
+               ret_send_status = consumer_send_status_channel(sock, nullptr);
                if (ret_send_status < 0) {
                        /* Stop everything if session daemon can not be notified. */
                        goto error_fatal;
@@ -2307,13 +2285,11 @@ error_fatal:
        goto end;
 
 end:
-       rcu_read_unlock();
        health_code_update();
        return ret_func;
 }
 
-int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream,
-               int producer_active)
+int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream, int producer_active)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2339,8 +2315,7 @@ int lttng_ustconsumer_take_snapshot(struct lttng_consumer_stream *stream)
  *
  * Returns 0 on success, < 0 on error.
  */
-int lttng_ustconsumer_sample_snapshot_positions(
-               struct lttng_consumer_stream *stream)
+int lttng_ustconsumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2353,8 +2328,8 @@ int lttng_ustconsumer_sample_snapshot_positions(
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_ustconsumer_get_produced_snapshot(
-               struct lttng_consumer_stream *stream, unsigned long *pos)
+int lttng_ustconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
+                                           unsigned long *pos)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2368,8 +2343,8 @@ int lttng_ustconsumer_get_produced_snapshot(
  *
  * Returns 0 on success, < 0 on error
  */
-int lttng_ustconsumer_get_consumed_snapshot(
-               struct lttng_consumer_stream *stream, unsigned long *pos)
+int lttng_ustconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
+                                           unsigned long *pos)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2378,8 +2353,7 @@ int lttng_ustconsumer_get_consumed_snapshot(
        return lttng_ust_ctl_snapshot_get_consumed(stream->ustream, pos);
 }
 
-int lttng_ustconsumer_flush_buffer(struct lttng_consumer_stream *stream,
-               int producer)
+int lttng_ustconsumer_flush_buffer(struct lttng_consumer_stream *stream, int producer)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2395,8 +2369,7 @@ int lttng_ustconsumer_clear_buffer(struct lttng_consumer_stream *stream)
        return lttng_ust_ctl_clear_buffer(stream->ustream);
 }
 
-int lttng_ustconsumer_get_current_timestamp(
-               struct lttng_consumer_stream *stream, uint64_t *ts)
+int lttng_ustconsumer_get_current_timestamp(struct lttng_consumer_stream *stream, uint64_t *ts)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2405,8 +2378,7 @@ int lttng_ustconsumer_get_current_timestamp(
        return lttng_ust_ctl_get_current_timestamp(stream->ustream, ts);
 }
 
-int lttng_ustconsumer_get_sequence_number(
-               struct lttng_consumer_stream *stream, uint64_t *seq)
+int lttng_ustconsumer_get_sequence_number(struct lttng_consumer_stream *stream, uint64_t *seq)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream->ustream);
@@ -2462,10 +2434,10 @@ void lttng_ustconsumer_del_channel(struct lttng_consumer_channel *chan)
                                ERR("Cannot get stream shm path");
                        }
                        ret = run_as_unlink(shm_path,
-                                       lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
-                                                       chan->buffer_credentials)),
-                                       lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
-                                                       chan->buffer_credentials)));
+                                           lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
+                                                   chan->buffer_credentials)),
+                                           lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
+                                                   chan->buffer_credentials)));
                        if (ret) {
                                PERROR("unlink %s", shm_path);
                        }
@@ -2483,12 +2455,11 @@ void lttng_ustconsumer_free_channel(struct lttng_consumer_channel *chan)
        lttng_ust_ctl_destroy_channel(chan->uchan);
        /* Try to rmdir all directories under shm_path root. */
        if (chan->root_shm_path[0]) {
-               (void) run_as_rmdir_recursive(chan->root_shm_path,
-                               lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(
-                                               chan->buffer_credentials)),
-                               lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(
-                                               chan->buffer_credentials)),
-                               LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+               (void) run_as_rmdir_recursive(
+                       chan->root_shm_path,
+                       lttng_credentials_get_uid(LTTNG_OPTIONAL_GET_PTR(chan->buffer_credentials)),
+                       lttng_credentials_get_gid(LTTNG_OPTIONAL_GET_PTR(chan->buffer_credentials)),
+                       LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
        }
        free(chan->stream_fds);
 }
@@ -2526,15 +2497,13 @@ int lttng_ustconsumer_close_wakeup_fd(struct lttng_consumer_stream *stream)
  * Returns the number of bytes pushed from the cache into the ring buffer, or a
  * negative value on error.
  */
-static
-int commit_one_metadata_packet(struct lttng_consumer_stream *stream)
+static int commit_one_metadata_packet(struct lttng_consumer_stream *stream)
 {
        ssize_t write_len;
        int ret;
 
        pthread_mutex_lock(&stream->chan->metadata_cache->lock);
-       if (stream->chan->metadata_cache->contents.size ==
-                       stream->ust_metadata_pushed) {
+       if (stream->chan->metadata_cache->contents.size == stream->ust_metadata_pushed) {
                /*
                 * In the context of a user space metadata channel, a
                 * change in version can be detected in two ways:
@@ -2559,31 +2528,31 @@ int commit_one_metadata_packet(struct lttng_consumer_stream *stream)
                 * occur as part of the pre-consume) until the metadata size
                 * exceeded the cache size.
                 */
-               if (stream->metadata_version !=
-                               stream->chan->metadata_cache->version) {
+               if (stream->metadata_version != stream->chan->metadata_cache->version) {
                        metadata_stream_reset_cache_consumed_position(stream);
                        consumer_stream_metadata_set_version(stream,
-                                       stream->chan->metadata_cache->version);
+                                                            stream->chan->metadata_cache->version);
                } else {
                        ret = 0;
                        goto end;
                }
        }
 
-       write_len = lttng_ust_ctl_write_one_packet_to_channel(stream->chan->uchan,
-                       &stream->chan->metadata_cache->contents.data[stream->ust_metadata_pushed],
-                       stream->chan->metadata_cache->contents.size -
-                                       stream->ust_metadata_pushed);
+       write_len = lttng_ust_ctl_write_one_packet_to_channel(
+               stream->chan->uchan,
+               &stream->chan->metadata_cache->contents.data[stream->ust_metadata_pushed],
+               stream->chan->metadata_cache->contents.size - stream->ust_metadata_pushed);
        LTTNG_ASSERT(write_len != 0);
        if (write_len < 0) {
                ERR("Writing one metadata packet");
                ret = write_len;
                goto end;
        }
+
        stream->ust_metadata_pushed += write_len;
+       stream->chan->metadata_pushed_wait_queue.wake_all();
 
-       LTTNG_ASSERT(stream->chan->metadata_cache->contents.size >=
-                       stream->ust_metadata_pushed);
+       LTTNG_ASSERT(stream->chan->metadata_cache->contents.size >= stream->ust_metadata_pushed);
        ret = write_len;
 
        /*
@@ -2602,7 +2571,6 @@ end:
        return ret;
 }
 
-
 /*
  * Sync metadata meaning request them to the session daemon and snapshot to the
  * metadata thread can consumer them.
@@ -2613,9 +2581,9 @@ end:
  *
  * The RCU read side lock must be held by the caller.
  */
-enum sync_metadata_status lttng_ustconsumer_sync_metadata(
-               struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_stream *metadata_stream)
+enum sync_metadata_status
+lttng_ustconsumer_sync_metadata(struct lttng_consumer_local_data *ctx,
+                               struct lttng_consumer_stream *metadata_stream)
 {
        int ret;
        enum sync_metadata_status status;
@@ -2631,7 +2599,7 @@ enum sync_metadata_status lttng_ustconsumer_sync_metadata(
         * Request metadata from the sessiond, but don't wait for the flush
         * because we locked the metadata thread.
         */
-       ret = lttng_ustconsumer_request_metadata(ctx, metadata_channel, 0, 0);
+       ret = lttng_ustconsumer_request_metadata(ctx, metadata_channel, false, 0);
        pthread_mutex_lock(&metadata_stream->lock);
        if (ret < 0) {
                status = SYNC_METADATA_STATUS_ERROR;
@@ -2651,7 +2619,7 @@ enum sync_metadata_status lttng_ustconsumer_sync_metadata(
         */
        if (consumer_stream_is_deleted(metadata_stream)) {
                DBG("Metadata stream %" PRIu64 " was deleted during the metadata synchronization",
-                               metadata_stream->key);
+                   metadata_stream->key);
                status = SYNC_METADATA_STATUS_NO_DATA;
                goto end;
        }
@@ -2669,7 +2637,8 @@ enum sync_metadata_status lttng_ustconsumer_sync_metadata(
 
        ret = lttng_ust_ctl_snapshot(metadata_stream->ustream);
        if (ret < 0) {
-               ERR("Failed to take a snapshot of the metadata ring-buffer positions, ret = %d", ret);
+               ERR("Failed to take a snapshot of the metadata ring-buffer positions, ret = %d",
+                   ret);
                status = SYNC_METADATA_STATUS_ERROR;
                goto end;
        }
@@ -2682,7 +2651,7 @@ end:
  * Return 0 on success else a negative value.
  */
 static int notify_if_more_data(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx)
+                              struct lttng_consumer_local_data *ctx)
 {
        int ret;
        struct lttng_ust_ctl_consumer_stream *ustream;
@@ -2758,18 +2727,17 @@ static int consumer_stream_ust_on_wake_up(struct lttng_consumer_stream *stream)
 }
 
 static int extract_common_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+                                        struct stream_subbuffer *subbuf)
 {
        int ret;
 
-       ret = lttng_ust_ctl_get_subbuf_size(
-                       stream->ustream, &subbuf->info.data.subbuf_size);
+       ret = lttng_ust_ctl_get_subbuf_size(stream->ustream, &subbuf->info.data.subbuf_size);
        if (ret) {
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_padded_subbuf_size(
-                       stream->ustream, &subbuf->info.data.padded_subbuf_size);
+       ret = lttng_ust_ctl_get_padded_subbuf_size(stream->ustream,
+                                                  &subbuf->info.data.padded_subbuf_size);
        if (ret) {
                goto end;
        }
@@ -2779,7 +2747,7 @@ end:
 }
 
 static int extract_metadata_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+                                          struct stream_subbuffer *subbuf)
 {
        int ret;
 
@@ -2795,7 +2763,7 @@ end:
 }
 
 static int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuf)
+                                      struct stream_subbuffer *subbuf)
 {
        int ret;
 
@@ -2804,43 +2772,40 @@ static int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_packet_size(
-                       stream->ustream, &subbuf->info.data.packet_size);
+       ret = lttng_ust_ctl_get_packet_size(stream->ustream, &subbuf->info.data.packet_size);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer packet size");
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_content_size(
-                       stream->ustream, &subbuf->info.data.content_size);
+       ret = lttng_ust_ctl_get_content_size(stream->ustream, &subbuf->info.data.content_size);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer content size");
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_timestamp_begin(
-                       stream->ustream, &subbuf->info.data.timestamp_begin);
+       ret = lttng_ust_ctl_get_timestamp_begin(stream->ustream,
+                                               &subbuf->info.data.timestamp_begin);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer begin timestamp");
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_timestamp_end(
-                       stream->ustream, &subbuf->info.data.timestamp_end);
+       ret = lttng_ust_ctl_get_timestamp_end(stream->ustream, &subbuf->info.data.timestamp_end);
        if (ret < 0) {
                PERROR("Failed to get sub-buffer end timestamp");
                goto end;
        }
 
-       ret = lttng_ust_ctl_get_events_discarded(
-                       stream->ustream, &subbuf->info.data.events_discarded);
+       ret = lttng_ust_ctl_get_events_discarded(stream->ustream,
+                                                &subbuf->info.data.events_discarded);
        if (ret) {
                PERROR("Failed to get sub-buffer events discarded count");
                goto end;
        }
 
        ret = lttng_ust_ctl_get_sequence_number(stream->ustream,
-                       &subbuf->info.data.sequence_number.value);
+                                               &subbuf->info.data.sequence_number.value);
        if (ret) {
                /* May not be supported by older LTTng-modules. */
                if (ret != -ENOTTY) {
@@ -2851,15 +2816,14 @@ static int extract_data_subbuffer_info(struct lttng_consumer_stream *stream,
                subbuf->info.data.sequence_number.is_set = true;
        }
 
-       ret = lttng_ust_ctl_get_stream_id(
-                       stream->ustream, &subbuf->info.data.stream_id);
+       ret = lttng_ust_ctl_get_stream_id(stream->ustream, &subbuf->info.data.stream_id);
        if (ret < 0) {
                PERROR("Failed to get stream id");
                goto end;
        }
 
        ret = lttng_ust_ctl_get_instance_id(stream->ustream,
-                       &subbuf->info.data.stream_instance_id.value);
+                                           &subbuf->info.data.stream_instance_id.value);
        if (ret) {
                /* May not be supported by older LTTng-modules. */
                if (ret != -ENOTTY) {
@@ -2874,13 +2838,12 @@ end:
 }
 
 static int get_next_subbuffer_common(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+                                    struct stream_subbuffer *subbuffer)
 {
        int ret;
        const char *addr;
 
-       ret = stream->read_subbuffer_ops.extract_subbuffer_info(
-                       stream, subbuffer);
+       ret = stream->read_subbuffer_ops.extract_subbuffer_info(stream, subbuffer);
        if (ret) {
                goto end;
        }
@@ -2890,16 +2853,15 @@ static int get_next_subbuffer_common(struct lttng_consumer_stream *stream,
                goto end;
        }
 
-       subbuffer->buffer.buffer = lttng_buffer_view_init(
-                       addr, 0, subbuffer->info.data.padded_subbuf_size);
-       LTTNG_ASSERT(subbuffer->buffer.buffer.data != NULL);
+       subbuffer->buffer.buffer =
+               lttng_buffer_view_init(addr, 0, subbuffer->info.data.padded_subbuf_size);
+       LTTNG_ASSERT(subbuffer->buffer.buffer.data != nullptr);
 end:
        return ret;
 }
 
-static enum get_next_subbuffer_status get_next_subbuffer(
-               struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status get_next_subbuffer(struct lttng_consumer_stream *stream,
+                                                        struct stream_subbuffer *subbuffer)
 {
        int ret;
        enum get_next_subbuffer_status status;
@@ -2910,7 +2872,7 @@ static enum get_next_subbuffer_status get_next_subbuffer(
                status = GET_NEXT_SUBBUFFER_STATUS_OK;
                break;
        case -ENODATA:
-               case -EAGAIN:
+       case -EAGAIN:
                /*
                 * The caller only expects -ENODATA when there is no data to
                 * read, but the kernel tracer returns -EAGAIN when there is
@@ -2934,9 +2896,9 @@ end:
        return status;
 }
 
-static enum get_next_subbuffer_status get_next_subbuffer_metadata(
-               struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer)
+static enum get_next_subbuffer_status
+get_next_subbuffer_metadata(struct lttng_consumer_stream *stream,
+                           struct stream_subbuffer *subbuffer)
 {
        int ret;
        bool cache_empty;
@@ -2979,7 +2941,7 @@ static enum get_next_subbuffer_status get_next_subbuffer_metadata(
                } else {
                        pthread_mutex_lock(&stream->chan->metadata_cache->lock);
                        cache_empty = stream->chan->metadata_cache->contents.size ==
-                                       stream->ust_metadata_pushed;
+                               stream->ust_metadata_pushed;
                        pthread_mutex_unlock(&stream->chan->metadata_cache->lock);
                }
        } while (!got_subbuffer);
@@ -3034,7 +2996,7 @@ end:
 }
 
 static int put_next_subbuffer(struct lttng_consumer_stream *stream,
-               struct stream_subbuffer *subbuffer __attribute__((unused)))
+                             struct stream_subbuffer *subbuffer __attribute__((unused)))
 {
        const int ret = lttng_ust_ctl_put_next_subbuf(stream->ustream);
 
@@ -3043,42 +3005,35 @@ static int put_next_subbuffer(struct lttng_consumer_stream *stream,
 }
 
 static int signal_metadata(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx __attribute__((unused)))
+                          struct lttng_consumer_local_data *ctx __attribute__((unused)))
 {
        ASSERT_LOCKED(stream->metadata_rdv_lock);
        return pthread_cond_broadcast(&stream->metadata_rdv) ? -errno : 0;
 }
 
-static int lttng_ustconsumer_set_stream_ops(
-               struct lttng_consumer_stream *stream)
+static int lttng_ustconsumer_set_stream_ops(struct lttng_consumer_stream *stream)
 {
        int ret = 0;
 
        stream->read_subbuffer_ops.on_wake_up = consumer_stream_ust_on_wake_up;
        if (stream->metadata_flag) {
-               stream->read_subbuffer_ops.get_next_subbuffer =
-                               get_next_subbuffer_metadata;
-               stream->read_subbuffer_ops.extract_subbuffer_info =
-                               extract_metadata_subbuffer_info;
+               stream->read_subbuffer_ops.get_next_subbuffer = get_next_subbuffer_metadata;
+               stream->read_subbuffer_ops.extract_subbuffer_info = extract_metadata_subbuffer_info;
                stream->read_subbuffer_ops.reset_metadata =
-                               metadata_stream_reset_cache_consumed_position;
+                       metadata_stream_reset_cache_consumed_position;
                if (stream->chan->is_live) {
                        stream->read_subbuffer_ops.on_sleep = signal_metadata;
-                       ret = consumer_stream_enable_metadata_bucketization(
-                                       stream);
+                       ret = consumer_stream_enable_metadata_bucketization(stream);
                        if (ret) {
                                goto end;
                        }
                }
        } else {
-               stream->read_subbuffer_ops.get_next_subbuffer =
-                               get_next_subbuffer;
-               stream->read_subbuffer_ops.extract_subbuffer_info =
-                               extract_data_subbuffer_info;
+               stream->read_subbuffer_ops.get_next_subbuffer = get_next_subbuffer;
+               stream->read_subbuffer_ops.extract_subbuffer_info = extract_data_subbuffer_info;
                stream->read_subbuffer_ops.on_sleep = notify_if_more_data;
                if (stream->chan->is_live) {
-                       stream->read_subbuffer_ops.send_live_beacon =
-                                       consumer_flush_ust_index;
+                       stream->read_subbuffer_ops.send_live_beacon = consumer_flush_ust_index;
                }
        }
 
@@ -3103,7 +3058,7 @@ int lttng_ustconsumer_on_recv_stream(struct lttng_consumer_stream *stream)
         * no current trace chunk on the parent channel.
         */
        if (stream->net_seq_idx == (uint64_t) -1ULL && stream->chan->monitor &&
-                       stream->chan->trace_chunk) {
+           stream->chan->trace_chunk) {
                ret = consumer_stream_create_output_files(stream, true);
                if (ret) {
                        goto error;
@@ -3159,12 +3114,14 @@ int lttng_ustconsumer_data_pending(struct lttng_consumer_stream *stream)
                 * whetnever ust_metadata_pushed is incremented, the associated
                 * metadata has been consumed from the metadata stream.
                 */
-               DBG("UST consumer metadata pending check: contiguous %" PRIu64 " vs pushed %" PRIu64,
-                               contiguous, pushed);
+               DBG("UST consumer metadata pending check: contiguous %" PRIu64
+                   " vs pushed %" PRIu64,
+                   contiguous,
+                   pushed);
                LTTNG_ASSERT(((int64_t) (contiguous - pushed)) >= 0);
                if ((contiguous != pushed) ||
-                               (((int64_t) contiguous - pushed) > 0 || contiguous == 0)) {
-                       ret = 1;        /* Data is pending */
+                   (((int64_t) contiguous - pushed) > 0 || contiguous == 0)) {
+                       ret = 1; /* Data is pending */
                        goto end;
                }
        } else {
@@ -3176,7 +3133,7 @@ int lttng_ustconsumer_data_pending(struct lttng_consumer_stream *stream)
                         */
                        ret = lttng_ust_ctl_put_subbuf(stream->ustream);
                        LTTNG_ASSERT(ret == 0);
-                       ret = 1;        /* Data is pending */
+                       ret = 1; /* Data is pending */
                        goto end;
                }
        }
@@ -3246,18 +3203,17 @@ void lttng_ustconsumer_close_all_metadata(struct lttng_ht *metadata_ht)
 
        DBG("UST consumer closing all metadata streams");
 
-       rcu_read_lock();
-       cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream,
-                       node.node) {
-
-               health_code_update();
+       {
+               lttng::urcu::read_lock_guard read_lock;
 
-               pthread_mutex_lock(&stream->chan->lock);
-               lttng_ustconsumer_close_metadata(stream->chan);
-               pthread_mutex_unlock(&stream->chan->lock);
+               cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
+                       health_code_update();
 
+                       pthread_mutex_lock(&stream->chan->lock);
+                       lttng_ustconsumer_close_metadata(stream->chan);
+                       pthread_mutex_unlock(&stream->chan->lock);
+               }
        }
-       rcu_read_unlock();
 }
 
 void lttng_ustconsumer_close_stream_wakeup(struct lttng_consumer_stream *stream)
@@ -3281,7 +3237,9 @@ void lttng_ustconsumer_close_stream_wakeup(struct lttng_consumer_stream *stream)
  * pushed out due to concurrent interaction with the session daemon.
  */
 int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_channel *channel, int timer, int wait)
+                                      struct lttng_consumer_channel *channel,
+                                      bool invoked_by_timer,
+                                      int wait)
 {
        struct lttcomm_metadata_request_msg request;
        struct lttcomm_consumer_msg msg;
@@ -3317,17 +3275,18 @@ int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
        request.uid = channel->ust_app_uid;
        request.key = channel->key;
 
-       DBG("Sending metadata request to sessiond, session id %" PRIu64
-                       ", per-pid %" PRIu64 ", app UID %u and channel key %" PRIu64,
-                       request.session_id, request.session_id_per_pid, request.uid,
-                       request.key);
+       DBG("Sending metadata request to sessiond, session id %" PRIu64 ", per-pid %" PRIu64
+           ", app UID %u and channel key %" PRIu64,
+           request.session_id,
+           request.session_id_per_pid,
+           request.uid,
+           request.key);
 
        pthread_mutex_lock(&ctx->metadata_socket_lock);
 
        health_code_update();
 
-       ret = lttcomm_send_unix_sock(ctx->consumer_metadata_socket, &request,
-                       sizeof(request));
+       ret = lttcomm_send_unix_sock(ctx->consumer_metadata_socket, &request, sizeof(request));
        if (ret < 0) {
                ERR("Asking metadata to sessiond");
                goto end;
@@ -3336,11 +3295,9 @@ int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
        health_code_update();
 
        /* Receive the metadata from sessiond */
-       ret = lttcomm_recv_unix_sock(ctx->consumer_metadata_socket, &msg,
-                       sizeof(msg));
+       ret = lttcomm_recv_unix_sock(ctx->consumer_metadata_socket, &msg, sizeof(msg));
        if (ret != sizeof(msg)) {
-               DBG("Consumer received unexpected message size %d (expects %zu)",
-                       ret, sizeof(msg));
+               DBG("Consumer received unexpected message size %d (expects %zu)", ret, sizeof(msg));
                lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_CMD);
                /*
                 * The ret value might 0 meaning an orderly shutdown but this is ok
@@ -3353,8 +3310,7 @@ int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
 
        if (msg.cmd_type == LTTNG_ERR_UND) {
                /* No registry found */
-               (void) consumer_send_status_msg(ctx->consumer_metadata_socket,
-                               ret_code);
+               (void) consumer_send_status_msg(ctx->consumer_metadata_socket, ret_code);
                ret = 0;
                goto end;
        } else if (msg.cmd_type != LTTNG_CONSUMER_PUSH_METADATA) {
@@ -3376,8 +3332,7 @@ int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
        health_code_update();
 
        /* Tell session daemon we are ready to receive the metadata. */
-       ret = consumer_send_status_msg(ctx->consumer_metadata_socket,
-                       LTTCOMM_CONSUMERD_SUCCESS);
+       ret = consumer_send_status_msg(ctx->consumer_metadata_socket, LTTCOMM_CONSUMERD_SUCCESS);
        if (ret < 0 || len == 0) {
                /*
                 * Somehow, the session daemon is not responding anymore or there is
@@ -3389,7 +3344,13 @@ int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
        health_code_update();
 
        ret = lttng_ustconsumer_recv_metadata(ctx->consumer_metadata_socket,
-                       key, offset, len, version, channel, timer, wait);
+                                             key,
+                                             offset,
+                                             len,
+                                             version,
+                                             channel,
+                                             invoked_by_timer,
+                                             wait);
        if (ret >= 0) {
                /*
                 * Only send the status msg if the sessiond is alive meaning a positive
@@ -3409,8 +3370,7 @@ end:
 /*
  * Return the ustctl call for the get stream id.
  */
-int lttng_ustconsumer_get_stream_id(struct lttng_consumer_stream *stream,
-               uint64_t *stream_id)
+int lttng_ustconsumer_get_stream_id(struct lttng_consumer_stream *stream, uint64_t *stream_id)
 {
        LTTNG_ASSERT(stream);
        LTTNG_ASSERT(stream_id);
index 6fc0dedcb6a2183d87d32faaf370b55ea96e4497..13de36f1ff5340c31d416c5f7ab735662e20c042 100644 (file)
 
 #include <common/compat/errno.hpp>
 #include <common/consumer/consumer.hpp>
+
 #include <stdbool.h>
 
 #ifdef HAVE_LIBLTTNG_UST_CTL
 
 int lttng_ustconsumer_take_snapshot(struct lttng_consumer_stream *stream);
-int lttng_ustconsumer_sample_snapshot_positions(
-               struct lttng_consumer_stream *stream);
+int lttng_ustconsumer_sample_snapshot_positions(struct lttng_consumer_stream *stream);
 
-int lttng_ustconsumer_get_produced_snapshot(
-               struct lttng_consumer_stream *stream, unsigned long *pos);
-int lttng_ustconsumer_get_consumed_snapshot(
-               struct lttng_consumer_stream *stream, unsigned long *pos);
+int lttng_ustconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
+                                           unsigned long *pos);
+int lttng_ustconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
+                                           unsigned long *pos);
 
 int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx,
-               int sock, struct pollfd *consumer_sockpoll);
+                              int sock,
+                              struct pollfd *consumer_sockpoll);
 
-extern int lttng_ustconsumer_allocate_channel(struct lttng_consumer_channel *chan);
 extern void lttng_ustconsumer_del_channel(struct lttng_consumer_channel *chan);
 extern void lttng_ustconsumer_free_channel(struct lttng_consumer_channel *chan);
 extern int lttng_ustconsumer_add_stream(struct lttng_consumer_stream *stream);
 extern void lttng_ustconsumer_del_stream(struct lttng_consumer_stream *stream);
 
 int lttng_ustconsumer_read_subbuffer(struct lttng_consumer_stream *stream,
-               struct lttng_consumer_local_data *ctx);
+                                    struct lttng_consumer_local_data *ctx);
 int lttng_ustconsumer_on_recv_stream(struct lttng_consumer_stream *stream);
 
 void lttng_ustconsumer_on_stream_hangup(struct lttng_consumer_stream *stream);
 
-int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream,
-               int producer_active);
-int lttng_ustconsumer_get_stream_id(struct lttng_consumer_stream *stream,
-               uint64_t *stream_id);
+int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream, int producer_active);
+int lttng_ustconsumer_get_stream_id(struct lttng_consumer_stream *stream, uint64_t *stream_id);
 int lttng_ustconsumer_data_pending(struct lttng_consumer_stream *stream);
 void lttng_ustconsumer_close_all_metadata(struct lttng_ht *ht);
 void lttng_ustconsumer_close_metadata(struct lttng_consumer_channel *metadata);
 void lttng_ustconsumer_close_stream_wakeup(struct lttng_consumer_stream *stream);
-int lttng_ustconsumer_recv_metadata(int sock, uint64_t key, uint64_t offset,
-               uint64_t len, uint64_t version,
-               struct lttng_consumer_channel *channel, int timer, int wait);
+int lttng_ustconsumer_recv_metadata(int sock,
+                                   uint64_t key,
+                                   uint64_t offset,
+                                   uint64_t len,
+                                   uint64_t version,
+                                   struct lttng_consumer_channel *channel,
+                                   bool invoked_by_timer,
+                                   int wait);
 int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_channel *channel, int timer, int wait);
-enum sync_metadata_status lttng_ustconsumer_sync_metadata(
-               struct lttng_consumer_local_data *ctx,
-               struct lttng_consumer_stream *metadata);
-int lttng_ustconsumer_flush_buffer(struct lttng_consumer_stream *stream,
-               int producer);
+                                      struct lttng_consumer_channel *channel,
+                                      bool invoked_by_timer,
+                                      int wait);
+enum sync_metadata_status lttng_ustconsumer_sync_metadata(struct lttng_consumer_local_data *ctx,
+                                                         struct lttng_consumer_stream *metadata);
+int lttng_ustconsumer_flush_buffer(struct lttng_consumer_stream *stream, int producer);
 int lttng_ustconsumer_clear_buffer(struct lttng_consumer_stream *stream);
-int lttng_ustconsumer_get_current_timestamp(
-               struct lttng_consumer_stream *stream, uint64_t *ts);
-int lttng_ustconsumer_get_sequence_number(
-               struct lttng_consumer_stream *stream, uint64_t *seq);
+int lttng_ustconsumer_get_current_timestamp(struct lttng_consumer_stream *stream, uint64_t *ts);
+int lttng_ustconsumer_get_sequence_number(struct lttng_consumer_stream *stream, uint64_t *seq);
 void lttng_ustconsumer_sigbus_handle(void *addr);
 
 #else /* HAVE_LIBLTTNG_UST_CTL */
 
-static inline
-ssize_t lttng_ustconsumer_on_read_subbuffer_mmap(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               unsigned long len __attribute__((unused)),
-               unsigned long padding __attribute__((unused)))
-{
-       return -ENOSYS;
-}
-
-static inline
-ssize_t lttng_ustconsumer_on_read_subbuffer_splice(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               struct lttng_consumer_stream *uststream __attribute__((unused)),
-               unsigned long len __attribute__((unused)),
-               unsigned long padding __attribute__((unused)))
+static inline ssize_t lttng_ustconsumer_on_read_subbuffer_mmap(
+       struct lttng_consumer_local_data *ctx __attribute__((unused)),
+       struct lttng_consumer_stream *stream __attribute__((unused)),
+       unsigned long len __attribute__((unused)),
+       unsigned long padding __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_take_snapshot(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline ssize_t lttng_ustconsumer_on_read_subbuffer_splice(
+       struct lttng_consumer_local_data *ctx __attribute__((unused)),
+       struct lttng_consumer_stream *uststream __attribute__((unused)),
+       unsigned long len __attribute__((unused)),
+       unsigned long padding __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_sample_snapshot_positions(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline int lttng_ustconsumer_take_snapshot(struct lttng_consumer_stream *stream
+                                                 __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_get_produced_snapshot(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               unsigned long *pos __attribute__((unused)))
+static inline int lttng_ustconsumer_sample_snapshot_positions(struct lttng_consumer_stream *stream
+                                                             __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_get_consumed_snapshot(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               unsigned long *pos __attribute__((unused)))
+static inline int lttng_ustconsumer_get_produced_snapshot(struct lttng_consumer_stream *stream
+                                                         __attribute__((unused)),
+                                                         unsigned long *pos
+                                                         __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_recv_cmd(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               int sock __attribute__((unused)),
-               struct pollfd *consumer_sockpoll __attribute__((unused)))
+static inline int lttng_ustconsumer_get_consumed_snapshot(struct lttng_consumer_stream *stream
+                                                         __attribute__((unused)),
+                                                         unsigned long *pos
+                                                         __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_allocate_channel(
-               struct lttng_consumer_channel *chan __attribute__((unused)))
+static inline int lttng_ustconsumer_recv_cmd(struct lttng_consumer_local_data *ctx
+                                            __attribute__((unused)),
+                                            int sock __attribute__((unused)),
+                                            struct pollfd *consumer_sockpoll
+                                            __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void lttng_ustconsumer_del_channel(
-               struct lttng_consumer_channel *chan __attribute__((unused)))
+static inline void lttng_ustconsumer_del_channel(struct lttng_consumer_channel *chan
+                                                __attribute__((unused)))
 {
 }
 
-static inline
-void lttng_ustconsumer_free_channel(
-               struct lttng_consumer_channel *chan __attribute__((unused)))
+static inline void lttng_ustconsumer_free_channel(struct lttng_consumer_channel *chan
+                                                 __attribute__((unused)))
 {
 }
 
-static inline
-int lttng_ustconsumer_add_stream(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline int lttng_ustconsumer_add_stream(struct lttng_consumer_stream *stream
+                                              __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void lttng_ustconsumer_del_stream(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline void lttng_ustconsumer_del_stream(struct lttng_consumer_stream *stream
+                                               __attribute__((unused)))
 {
 }
 
-static inline
-int lttng_ustconsumer_read_subbuffer(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               struct lttng_consumer_local_data *ctx __attribute__((unused)))
+static inline int lttng_ustconsumer_read_subbuffer(struct lttng_consumer_stream *stream
+                                                  __attribute__((unused)),
+                                                  struct lttng_consumer_local_data *ctx
+                                                  __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_on_recv_stream(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline int lttng_ustconsumer_on_recv_stream(struct lttng_consumer_stream *stream
+                                                  __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void lttng_ustconsumer_on_stream_hangup(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline void lttng_ustconsumer_on_stream_hangup(struct lttng_consumer_stream *stream
+                                                     __attribute__((unused)))
 {
 }
 
-static inline
-int lttng_ustconsumer_data_pending(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline int lttng_ustconsumer_data_pending(struct lttng_consumer_stream *stream
+                                                __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream __attribute__((unused)),
-               int producer_active __attribute__((unused)))
+static inline int lttng_ust_flush_buffer(struct lttng_consumer_stream *stream
+                                        __attribute__((unused)),
+                                        int producer_active __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void lttng_ustconsumer_close_all_metadata(
-               struct lttng_ht *ht __attribute__((unused)))
+static inline void lttng_ustconsumer_close_all_metadata(struct lttng_ht *ht __attribute__((unused)))
 {
 }
 
-static inline
-void lttng_ustconsumer_close_metadata(
-               struct lttng_consumer_channel *metadata __attribute__((unused)))
+static inline void lttng_ustconsumer_close_metadata(struct lttng_consumer_channel *metadata
+                                                   __attribute__((unused)))
 {
 }
-static inline
-void lttng_ustconsumer_close_stream_wakeup(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline void lttng_ustconsumer_close_stream_wakeup(struct lttng_consumer_stream *stream
+                                                        __attribute__((unused)))
 {
 }
 
-static inline
-int lttng_ustconsumer_recv_metadata(int sock __attribute__((unused)),
-               uint64_t key __attribute__((unused)),
-               uint64_t offset __attribute__((unused)),
-               uint64_t len __attribute__((unused)),
-               uint64_t version __attribute__((unused)),
-               struct lttng_consumer_channel *channel __attribute__((unused)),
-               int timer __attribute__((unused)))
+static inline int lttng_ustconsumer_recv_metadata(int sock __attribute__((unused)),
+                                                 uint64_t key __attribute__((unused)),
+                                                 uint64_t offset __attribute__((unused)),
+                                                 uint64_t len __attribute__((unused)),
+                                                 uint64_t version __attribute__((unused)),
+                                                 struct lttng_consumer_channel *channel
+                                                 __attribute__((unused)),
+                                                 bool invoked_by_timer __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_request_metadata(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               struct lttng_consumer_channel *channel __attribute__((unused)),
-               int timer __attribute__((unused)),
-               int wait __attribute__((unused)))
+static inline int lttng_ustconsumer_request_metadata(struct lttng_consumer_local_data *ctx
+                                                    __attribute__((unused)),
+                                                    struct lttng_consumer_channel *channel
+                                                    __attribute__((unused)),
+                                                    bool invoked_by_timer __attribute__((unused)),
+                                                    int wait __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-enum sync_metadata_status lttng_ustconsumer_sync_metadata(
-               struct lttng_consumer_local_data *ctx __attribute__((unused)),
-               struct lttng_consumer_stream *metadata __attribute__((unused)))
+static inline enum sync_metadata_status
+lttng_ustconsumer_sync_metadata(struct lttng_consumer_local_data *ctx __attribute__((unused)),
+                               struct lttng_consumer_stream *metadata __attribute__((unused)))
 {
        return SYNC_METADATA_STATUS_ERROR;
 }
 
-static inline
-int lttng_ustconsumer_flush_buffer(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               int producer __attribute__((unused)))
+static inline int lttng_ustconsumer_flush_buffer(struct lttng_consumer_stream *stream
+                                                __attribute__((unused)),
+                                                int producer __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_clear_buffer(
-               struct lttng_consumer_stream *stream __attribute__((unused)))
+static inline int lttng_ustconsumer_clear_buffer(struct lttng_consumer_stream *stream
+                                                __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_get_current_timestamp(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               uint64_t *ts __attribute__((unused)))
+static inline int lttng_ustconsumer_get_current_timestamp(struct lttng_consumer_stream *stream
+                                                         __attribute__((unused)),
+                                                         uint64_t *ts __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_get_sequence_number(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               uint64_t *seq __attribute__((unused)))
+static inline int lttng_ustconsumer_get_sequence_number(struct lttng_consumer_stream *stream
+                                                       __attribute__((unused)),
+                                                       uint64_t *seq __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-int lttng_ustconsumer_get_stream_id(
-               struct lttng_consumer_stream *stream __attribute__((unused)),
-               uint64_t *stream_id __attribute__((unused)))
+static inline int lttng_ustconsumer_get_stream_id(struct lttng_consumer_stream *stream
+                                                 __attribute__((unused)),
+                                                 uint64_t *stream_id __attribute__((unused)))
 {
        return -ENOSYS;
 }
 
-static inline
-void lttng_ustconsumer_sigbus_handle(
-               void *addr __attribute__((unused)))
+static inline void lttng_ustconsumer_sigbus_handle(void *addr __attribute__((unused)))
 {
 }
 #endif /* HAVE_LIBLTTNG_UST_CTL */
index 89ef0e54fd01714ea866c05dd2424cd1f21c26e5..62c9c22d52686e442edad15ce3a4a17a8edb0a75 100644 (file)
@@ -7,17 +7,9 @@
  */
 
 #define _LGPL_SOURCE
-#include <ctype.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <pwd.h>
-#include <stdlib.h>
-#include <sys/file.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
+#include "defaults.hpp"
+#include "time.hpp"
+#include "utils.hpp"
 
 #include <common/common.hpp>
 #include <common/compat/directory-handle.hpp>
 #include <common/readwrite.hpp>
 #include <common/runas.hpp>
 #include <common/string-utils/format.hpp>
+
 #include <lttng/constant.h>
 
-#include "defaults.hpp"
-#include "time.hpp"
-#include "utils.hpp"
+#include <ctype.h>
+#include <fcntl.h>
+#include <grp.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
-#define PROC_MEMINFO_PATH               "/proc/meminfo"
-#define PROC_MEMINFO_MEMAVAILABLE_LINE  "MemAvailable:"
-#define PROC_MEMINFO_MEMTOTAL_LINE      "MemTotal:"
+#define PROC_MEMINFO_PATH             "/proc/meminfo"
+#define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
+#define PROC_MEMINFO_MEMTOTAL_LINE     "MemTotal:"
 
-/* The length of the longest field of `/proc/meminfo`. */
-#define PROC_MEMINFO_FIELD_MAX_NAME_LEN        20
+/* The lnullptrh of the longest field of `/proc/meminfo`. */
+#define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
 
 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
@@ -47,7 +48,7 @@
 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
 #endif
 
-#define FALLBACK_USER_BUFLEN 16384
+#define FALLBACK_USER_BUFLEN  16384
 #define FALLBACK_GROUP_BUFLEN 16384
 
 /*
@@ -57,7 +58,7 @@ int utils_create_pipe(int *dst)
 {
        int ret;
 
-       if (dst == NULL) {
+       if (dst == nullptr) {
                return -1;
        }
 
@@ -79,7 +80,7 @@ int utils_create_pipe_cloexec(int *dst)
 {
        int ret, i;
 
-       if (dst == NULL) {
+       if (dst == nullptr) {
                return -1;
        }
 
@@ -111,7 +112,7 @@ int utils_create_pipe_cloexec_nonblock(int *dst)
 {
        int ret, i;
 
-       if (dst == NULL) {
+       if (dst == nullptr) {
                return -1;
        }
 
@@ -148,7 +149,7 @@ void utils_close_pipe(int *src)
 {
        int i, ret;
 
-       if (src == NULL) {
+       if (src == nullptr) {
                return;
        }
 
@@ -173,7 +174,7 @@ char *utils_strdupdelim(const char *begin, const char *end)
 {
        char *str = zmalloc<char>(end - begin + 1);
 
-       if (str == NULL) {
+       if (str == nullptr) {
                PERROR("zmalloc strdupdelim");
                goto error;
        }
@@ -213,11 +214,11 @@ end:
 int utils_create_pid_file(pid_t pid, const char *filepath)
 {
        int ret, fd = -1;
-       FILE *fp = NULL;
+       FILE *fp = nullptr;
 
        LTTNG_ASSERT(filepath);
 
-       fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR |S_IWUSR | S_IRGRP | S_IROTH);
+       fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
        if (fd < 0) {
                PERROR("open file %s", filepath);
                ret = -1;
@@ -225,11 +226,12 @@ int utils_create_pid_file(pid_t pid, const char *filepath)
        }
 
        fp = fdopen(fd, "w");
-       if (fp == NULL) {
+       if (fp == nullptr) {
                PERROR("fdopen file %s", filepath);
                ret = -1;
                if (close(fd)) {
-                       PERROR("Failed to close `%s` file descriptor while handling fdopen error", filepath);
+                       PERROR("Failed to close `%s` file descriptor while handling fdopen error",
+                              filepath);
                }
 
                goto error;
@@ -252,51 +254,6 @@ error:
        return ret;
 }
 
-/*
- * Create lock file to the given path and filename.
- * Returns the associated file descriptor, -1 on error.
- */
-int utils_create_lock_file(const char *filepath)
-{
-       int ret;
-       int fd;
-       struct flock lock;
-
-       LTTNG_ASSERT(filepath);
-
-       memset(&lock, 0, sizeof(lock));
-       fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
-               S_IRGRP | S_IWGRP);
-       if (fd < 0) {
-               PERROR("open lock file %s", filepath);
-               fd = -1;
-               goto error;
-       }
-
-       /*
-        * Attempt to lock the file. If this fails, there is
-        * already a process using the same lock file running
-        * and we should exit.
-        */
-       lock.l_whence = SEEK_SET;
-       lock.l_type = F_WRLCK;
-
-       ret = fcntl(fd, F_SETLK, &lock);
-       if (ret == -1) {
-               PERROR("fcntl lock file");
-               ERR("Could not get lock file %s, another instance is running.",
-                       filepath);
-               if (close(fd)) {
-                       PERROR("close lock file");
-               }
-               fd = ret;
-               goto error;
-       }
-
-error:
-       return fd;
-}
-
 /*
  * Create directory using the given path and mode.
  *
@@ -311,14 +268,13 @@ int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
                .gid = LTTNG_OPTIONAL_INIT_VALUE((gid_t) gid),
        };
 
-       handle = lttng_directory_handle_create(NULL);
+       handle = lttng_directory_handle_create(nullptr);
        if (!handle) {
                ret = -1;
                goto end;
        }
        ret = lttng_directory_handle_create_subdirectory_as_user(
-                       handle, path, mode,
-                       (uid >= 0 || gid >= 0) ? &creds : NULL);
+               handle, path, mode, (uid >= 0 || gid >= 0) ? &creds : nullptr);
 end:
        lttng_directory_handle_put(handle);
        return ret;
@@ -339,14 +295,13 @@ int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
                .gid = LTTNG_OPTIONAL_INIT_VALUE((gid_t) gid),
        };
 
-       handle = lttng_directory_handle_create(NULL);
+       handle = lttng_directory_handle_create(nullptr);
        if (!handle) {
                ret = -1;
                goto end;
        }
        ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
-                       handle, path, mode,
-                       (uid >= 0 || gid >= 0) ? &creds : NULL);
+               handle, path, mode, (uid >= 0 || gid >= 0) ? &creds : nullptr);
 end:
        lttng_directory_handle_put(handle);
        return ret;
@@ -357,32 +312,39 @@ end:
  *
  * Return 0 on success or else a negative value.
  */
-int utils_stream_file_path(const char *path_name, const char *file_name,
-               uint64_t size, uint64_t count, const char *suffix,
-               char *out_stream_path, size_t stream_path_len)
+int utils_stream_file_path(const char *path_name,
+                          const char *file_name,
+                          uint64_t size,
+                          uint64_t count,
+                          const char *suffix,
+                          char *out_stream_path,
+                          size_t stream_path_len)
 {
        int ret;
        char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
        const char *path_separator;
 
-       if (path_name && (path_name[0] == '\0' ||
-                       path_name[strlen(path_name) - 1] == '/')) {
+       if (path_name && (path_name[0] == '\0' || path_name[strlen(path_name) - 1] == '/')) {
                path_separator = "";
        } else {
                path_separator = "/";
        }
 
-       path_name = path_name ? : "";
-       suffix = suffix ? : "";
+       path_name = path_name ?: "";
+       suffix = suffix ?: "";
        if (size > 0) {
-               ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
-                               count);
+               ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64, count);
                LTTNG_ASSERT(ret > 0 && ret < sizeof(count_str));
        }
 
-       ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
-                       path_name, path_separator, file_name, count_str,
-                       suffix);
+       ret = snprintf(out_stream_path,
+                      stream_path_len,
+                      "%s%s%s%s%s",
+                      path_name,
+                      path_separator,
+                      file_name,
+                      count_str,
+                      suffix);
        if (ret < 0 || ret >= stream_path_len) {
                ERR("Truncation occurred while formatting stream path");
                ret = -1;
@@ -407,7 +369,7 @@ int utils_stream_file_path(const char *path_name, const char *file_name,
  *
  * @return 0 on success, -1 on failure.
  */
-int utils_parse_size_suffix(const char * const str, uint64_t * const size)
+int utils_parse_size_suffix(const char *const str, uint64_t *const size)
 {
        int ret;
        uint64_t base_size;
@@ -422,7 +384,7 @@ int utils_parse_size_suffix(const char * const str, uint64_t * const size)
        }
 
        /* strtoull will accept a negative number, but we don't want to. */
-       if (strchr(str, '-') != NULL) {
+       if (strchr(str, '-') != nullptr) {
                DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
                ret = -1;
                goto end;
@@ -513,7 +475,7 @@ end:
  *
  * @return 0 on success, -1 on failure.
  */
-int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
+int utils_parse_time_suffix(char const *const str, uint64_t *const time_us)
 {
        int ret;
        uint64_t base_time;
@@ -528,7 +490,7 @@ int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
        }
 
        /* strtoull will accept a negative number, but we don't want to. */
-       if (strchr(str, '-') != NULL) {
+       if (strchr(str, '-') != nullptr) {
                DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
                ret = -1;
                goto end;
@@ -627,18 +589,18 @@ static inline unsigned int fls_u32(uint32_t x)
        int r;
 
        asm("bsrl %1,%0\n\t"
-               "jnz 1f\n\t"
-               "movl $-1,%0\n\t"
-               "1:\n\t"
-               : "=r" (r) : "rm" (x));
+           "jnz 1f\n\t"
+           "movl $-1,%0\n\t"
+           "1:\n\t"
+           : "=r"(r)
+           : "rm"(x));
        return r + 1;
 }
 #define HAS_FLS_U32
 #endif
 
 #if defined(__x86_64) && defined(__LP64__)
-static inline
-unsigned int fls_u64(uint64_t x)
+static inline unsigned int fls_u64(uint64_t x)
 {
        long r;
 
@@ -646,15 +608,15 @@ unsigned int fls_u64(uint64_t x)
            "jnz 1f\n\t"
            "movq $-1,%0\n\t"
            "1:\n\t"
-           : "=r" (r) : "rm" (x));
+           : "=r"(r)
+           : "rm"(x));
        return r + 1;
 }
 #define HAS_FLS_U64
 #endif
 
 #ifndef HAS_FLS_U64
-static __attribute__((unused))
-unsigned int fls_u64(uint64_t x)
+static __attribute__((unused)) unsigned int fls_u64(uint64_t x)
 {
        unsigned int r = 64;
 
@@ -751,17 +713,17 @@ int utils_get_count_order_u64(uint64_t x)
  * Obtain the value of LTTNG_HOME environment variable, if exists.
  * Otherwise returns the value of HOME.
  */
-const char *utils_get_home_dir(void)
+const char *utils_get_home_dir()
 {
-       char *val = NULL;
+       char *val = nullptr;
        struct passwd *pwd;
 
        val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
-       if (val != NULL) {
+       if (val != nullptr) {
                goto end;
        }
        val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
-       if (val != NULL) {
+       if (val != nullptr) {
                goto end;
        }
 
@@ -786,8 +748,8 @@ char *utils_get_user_home_dir(uid_t uid)
 {
        struct passwd pwd;
        struct passwd *result;
-       char *home_dir = NULL;
-       char *buf = NULL;
+       char *home_dir = nullptr;
+       char *buf = nullptr;
        long buflen;
        int ret;
 
@@ -839,8 +801,7 @@ size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
        ret = strftime(dst, len, format, timeinfo);
        DIAGNOSTIC_POP
        if (ret == 0) {
-               ERR("Unable to strftime with format %s at dst %p of len %zu", format,
-                               dst, len);
+               ERR("Unable to strftime with format %s at dst %p of len %zu", format, dst, len);
        }
 
        return ret;
@@ -888,19 +849,16 @@ int utils_get_group_id(const char *name, bool warn, gid_t *gid)
 
                ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
                if (ret) {
-                       ERR("Failed to grow group info buffer to %zu bytes",
-                                       new_len);
+                       ERR("Failed to grow group info buffer to %zu bytes", new_len);
                        ret = -1;
                        goto error;
                }
        }
        if (ret) {
                if (ret == ESRCH) {
-                       DBG("Could not find group file entry for group name '%s'",
-                                       name);
+                       DBG("Could not find group file entry for group name '%s'", name);
                } else {
-                       PERROR("Failed to get group file entry for group name '%s'",
-                                       name);
+                       PERROR("Failed to get group file entry for group name '%s'", name);
                }
 
                ret = -1;
@@ -931,8 +889,7 @@ error:
  * of elements in the long_options array. Returns NULL if the string's
  * allocation fails.
  */
-char *utils_generate_optstring(const struct option *long_options,
-               size_t opt_count)
+char *utils_generate_optstring(const struct option *long_options, size_t opt_count)
 {
        int i;
        size_t string_len = opt_count, str_pos = 0;
@@ -978,7 +935,7 @@ int utils_recursive_rmdir(const char *path)
        int ret;
        struct lttng_directory_handle *handle;
 
-       handle = lttng_directory_handle_create(NULL);
+       handle = lttng_directory_handle_create(nullptr);
        if (!handle) {
                ret = -1;
                goto end;
@@ -1009,7 +966,7 @@ end:
        return ret;
 }
 
-static const char *get_man_bin_path(void)
+static const char *get_man_bin_path()
 {
        char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
 
@@ -1020,11 +977,23 @@ static const char *get_man_bin_path(void)
        return DEFAULT_MAN_BIN_PATH;
 }
 
-int utils_show_help(int section, const char *page_name,
-               const char *help_msg)
+static const char *get_manpath()
+{
+       char *manpath = lttng_secure_getenv(DEFAULT_MANPATH);
+
+       if (manpath) {
+               return manpath;
+       }
+
+       /* As defined during configuration. */
+       return MANPATH;
+}
+
+int utils_show_help(int section, const char *page_name, const char *help_msg)
 {
        char section_string[8];
        const char *man_bin_path = get_man_bin_path();
+       const char *manpath = get_manpath();
        int ret = 0;
 
        if (help_msg) {
@@ -1033,7 +1002,7 @@ int utils_show_help(int section, const char *page_name,
        }
 
        /* Section integer -> section string */
-       ret = sprintf(section_string, "%d", section);
+       ret = snprintf(section_string, sizeof(section_string), "%d", section);
        LTTNG_ASSERT(ret > 0 && ret < 8);
 
        /*
@@ -1043,15 +1012,13 @@ int utils_show_help(int section, const char *page_name,
         * be installed outside /usr, in which case its man pages are
         * not located in the default /usr/share/man directory.
         */
-       ret = execlp(man_bin_path, "man", "-M", MANPATH,
-               section_string, page_name, NULL);
+       ret = execlp(man_bin_path, "man", "-M", manpath, section_string, page_name, NULL);
 
 end:
        return ret;
 }
 
-static
-int read_proc_meminfo_field(const char *field, uint64_t *value)
+static int read_proc_meminfo_field(const char *field, uint64_t *value)
 {
        int ret;
        FILE *proc_meminfo;
@@ -1062,7 +1029,7 @@ int read_proc_meminfo_field(const char *field, uint64_t *value)
                PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
                ret = -1;
                goto fopen_error;
-        }
+       }
 
        /*
         * Read the contents of /proc/meminfo line by line to find the right
@@ -1072,8 +1039,9 @@ int read_proc_meminfo_field(const char *field, uint64_t *value)
                uint64_t value_kb;
 
                ret = fscanf(proc_meminfo,
-                               "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %" SCNu64 " kB\n",
-                               name, &value_kb);
+                            "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %" SCNu64 " kB\n",
+                            name,
+                            &value_kb);
                if (ret == EOF) {
                        /*
                         * fscanf() returning EOF can indicate EOF or an error.
@@ -1149,8 +1117,7 @@ int utils_change_working_directory(const char *path)
                         */
                        DBG("Working directory \"%s\" is not writable", path);
                } else {
-                       PERROR("Failed to check if working directory \"%s\" is writable",
-                                       path);
+                       PERROR("Failed to check if working directory \"%s\" is writable", path);
                }
        }
 
@@ -1163,7 +1130,7 @@ enum lttng_error_code utils_user_id_from_name(const char *user_name, uid_t *uid)
        struct passwd p, *pres;
        int ret;
        enum lttng_error_code ret_val = LTTNG_OK;
-       char *buf = NULL;
+       char *buf = nullptr;
        ssize_t buflen;
 
        buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
@@ -1199,12 +1166,13 @@ end_loop:
 
        switch (ret) {
        case 0:
-               if (pres == NULL) {
+               if (pres == nullptr) {
                        ret_val = LTTNG_ERR_USER_NOT_FOUND;
                } else {
                        *uid = p.pw_uid;
                        DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64,
-                                       user_name, (int64_t) *uid);
+                           user_name,
+                           (int64_t) *uid);
                        ret_val = LTTNG_OK;
                }
                break;
@@ -1222,13 +1190,12 @@ end:
        return ret_val;
 }
 
-enum lttng_error_code utils_group_id_from_name(
-               const char *group_name, gid_t *gid)
+enum lttng_error_code utils_group_id_from_name(const char *group_name, gid_t *gid)
 {
        struct group g, *gres;
        int ret;
        enum lttng_error_code ret_val = LTTNG_OK;
-       char *buf = NULL;
+       char *buf = nullptr;
        ssize_t buflen;
 
        buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
@@ -1264,12 +1231,13 @@ end_loop:
 
        switch (ret) {
        case 0:
-               if (gres == NULL) {
+               if (gres == nullptr) {
                        ret_val = LTTNG_ERR_GROUP_NOT_FOUND;
                } else {
                        *gid = g.gr_gid;
                        DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64,
-                                       group_name, (int64_t) *gid);
+                           group_name,
+                           (int64_t) *gid);
                        ret_val = LTTNG_OK;
                }
                break;
@@ -1287,8 +1255,7 @@ end:
        return ret_val;
 }
 
-int utils_parse_unsigned_long_long(const char *str,
-               unsigned long long *value)
+int utils_parse_unsigned_long_long(const char *str, unsigned long long *value)
 {
        int ret;
        char *endptr;
@@ -1303,15 +1270,15 @@ int utils_parse_unsigned_long_long(const char *str,
        if (errno != 0) {
                /* Don't print an error; allow the caller to log a better error. */
                DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
-                               str, errno);
+                   str,
+                   errno);
                ret = -1;
                goto end;
        }
 
        /* Not the end of the string or empty string. */
        if (*endptr || endptr == str) {
-               DBG("Failed to parse string as unsigned long long number: string = '%s'",
-                               str);
+               DBG("Failed to parse string as unsigned long long number: string = '%s'", str);
                ret = -1;
                goto end;
        }
index 0c60a234a93cf5b2bfa60b0fed1b9231f980a7dd..850c29ba88bf9ca3fe96b071861a7d67847c1b73 100644 (file)
@@ -8,15 +8,16 @@
 #ifndef _COMMON_UTILS_H
 #define _COMMON_UTILS_H
 
-#include <getopt.h>
+#include <common/compat/directory-handle.hpp>
+
 #include <lttng/lttng-error.h>
+
+#include <getopt.h>
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/compat/directory-handle.hpp>
-
 #define KIBI_LOG2 10
 #define MEBI_LOG2 20
 #define GIBI_LOG2 30
@@ -30,33 +31,33 @@ int utils_set_fd_cloexec(int fd);
 int utils_create_pid_file(pid_t pid, const char *filepath);
 int utils_mkdir(const char *path, mode_t mode, int uid, int gid);
 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid);
-int utils_stream_file_path(const char *path_name, const char *file_name,
-               uint64_t size, uint64_t count, const char *suffix,
-               char *out_stream_path, size_t stream_path_len);
-int utils_parse_size_suffix(char const * const str, uint64_t * const size);
-int utils_parse_time_suffix(char const * const str, uint64_t * const time_us);
+int utils_stream_file_path(const char *path_name,
+                          const char *file_name,
+                          uint64_t size,
+                          uint64_t count,
+                          const char *suffix,
+                          char *out_stream_path,
+                          size_t stream_path_len);
+int utils_parse_size_suffix(char const *const str, uint64_t *const size);
+int utils_parse_time_suffix(char const *const str, uint64_t *const time_us);
 int utils_get_count_order_u32(uint32_t x);
 int utils_get_count_order_u64(uint64_t x);
-const char *utils_get_home_dir(void);
+const char *utils_get_home_dir();
 char *utils_get_user_home_dir(uid_t uid);
 
 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
        ATTR_FORMAT_STRFTIME(1);
 
 int utils_get_group_id(const char *name, bool warn, gid_t *gid);
-char *utils_generate_optstring(const struct option *long_options,
-               size_t opt_count);
-int utils_create_lock_file(const char *filepath);
+char *utils_generate_optstring(const struct option *long_options, size_t opt_count);
 int utils_recursive_rmdir(const char *path);
 int utils_truncate_stream_file(int fd, off_t length);
 int utils_show_help(int section, const char *page_name, const char *help_msg);
 int utils_get_memory_available(uint64_t *value);
 int utils_get_memory_total(uint64_t *value);
 int utils_change_working_directory(const char *path);
-enum lttng_error_code utils_user_id_from_name(
-               const char *user_name, uid_t *user_id);
-enum lttng_error_code utils_group_id_from_name(
-               const char *group_name, gid_t *group_id);
+enum lttng_error_code utils_user_id_from_name(const char *user_name, uid_t *user_id);
+enum lttng_error_code utils_group_id_from_name(const char *group_name, gid_t *group_id);
 
 /*
  * Parse `str` as an unsigned long long value.
@@ -66,7 +67,6 @@ enum lttng_error_code utils_group_id_from_name(
  * - `str` is zero length
  * - `str` contains invalid
  */
-int utils_parse_unsigned_long_long(const char *str,
-               unsigned long long *value);
+int utils_parse_unsigned_long_long(const char *str, unsigned long long *value);
 
 #endif /* _COMMON_UTILS_H */
index dd59edc31c79e532f6b14bb8caa84d731fa430ef..4c64c08acedafe03de2e3d32b168146b97271134 100644 (file)
@@ -6,7 +6,13 @@
  *
  */
 
+#include "uuid.hpp"
+
 #include <common/compat/string.hpp>
+#include <common/error.hpp>
+#include <common/format.hpp>
+#include <common/random.hpp>
+
 #include <stddef.h>
 #include <stdint.h>
 #include <stdio.h>
@@ -14,8 +20,6 @@
 #include <string.h>
 #include <time.h>
 
-#include "uuid.hpp"
-
 namespace {
 const lttng_uuid nil_uuid = {};
 bool lttng_uuid_is_init;
@@ -23,7 +27,7 @@ bool lttng_uuid_is_init;
 
 void lttng_uuid_to_str(const lttng_uuid& uuid, char *uuid_str)
 {
-       sprintf(uuid_str, LTTNG_UUID_FMT, LTTNG_UUID_FMT_VALUES(uuid));
+       snprintf(uuid_str, LTTNG_UUID_STR_LEN, LTTNG_UUID_FMT, LTTNG_UUID_FMT_VALUES(uuid));
 }
 
 std::string lttng::utils::uuid_to_str(const lttng_uuid& uuid)
@@ -41,7 +45,7 @@ std::string lttng::utils::uuid_to_str(const lttng_uuid& uuid)
 int lttng_uuid_from_str(const char *str_in, lttng_uuid& uuid_out)
 {
        int ret = 0;
-       lttng_uuid uuid_scan;
+       lttng_uuid uuid_scan = {};
 
        if (str_in == nullptr) {
                ret = -1;
@@ -54,8 +58,7 @@ int lttng_uuid_from_str(const char *str_in, lttng_uuid& uuid_out)
        }
 
        /* Scan to a temporary location in case of a partial match. */
-       if (sscanf(str_in, LTTNG_UUID_FMT, LTTNG_UUID_SCAN_VALUES(uuid_scan)) !=
-                       LTTNG_UUID_LEN) {
+       if (sscanf(str_in, LTTNG_UUID_FMT, LTTNG_UUID_SCAN_VALUES(uuid_scan)) != LTTNG_UUID_LEN) {
                ret = -1;
                goto end;
        }
@@ -78,18 +81,15 @@ int lttng_uuid_generate(lttng_uuid& uuid_out)
        int i, ret = 0;
 
        if (!lttng_uuid_is_init) {
-               /*
-                * We don't need cryptographic quality randomness to
-                * generate UUIDs, seed rand with the epoch.
-                */
-               const time_t epoch = time(NULL);
-
-               if (epoch == (time_t) -1) {
+               try {
+                       srand(lttng::random::produce_best_effort_random_seed());
+               } catch (const std::exception& e) {
+                       ERR("Failed to initialize random seed during generation of UUID: %s",
+                           e.what());
                        ret = -1;
                        goto end;
                }
 
-               srand(epoch);
                lttng_uuid_is_init = true;
        }
 
index 586c2ad67c06fcdaac63c39759dee0e95ae8a7d6..9bec2d55ae08f8fe50ae73c726bdaa5bbd31de15 100644 (file)
@@ -9,34 +9,34 @@
 #define LTTNG_UUID_H
 
 #include <common/macros.hpp>
+
+#include <array>
+#include <inttypes.h>
 #include <stdbool.h>
 #include <stdint.h>
-#include <inttypes.h>
-#include <array>
 #include <string>
 
 /*
  * Includes final \0.
  */
-#define LTTNG_UUID_STR_LEN     37
-#define LTTNG_UUID_LEN         16
-#define LTTNG_UUID_VER         4
+#define LTTNG_UUID_STR_LEN 37
+#define LTTNG_UUID_LEN    16
+#define LTTNG_UUID_VER    4
 
-#define LTTNG_UUID_FMT \
-       "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 \
-       "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 \
-       "-%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 \
-       "%02" SCNx8
+#define LTTNG_UUID_FMT                                                                        \
+       "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 \
+       "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 \
+       "%02" SCNx8 "%02" SCNx8
 
-#define LTTNG_UUID_FMT_VALUES(uuid) \
-       (uuid)[0], (uuid)[1], (uuid)[2], (uuid)[3], (uuid)[4], (uuid)[5], \
-       (uuid)[6], (uuid)[7], (uuid)[8], (uuid)[9], (uuid)[10], (uuid)[11], \
-       (uuid)[12], (uuid)[13], (uuid)[14], (uuid)[15]
+#define LTTNG_UUID_FMT_VALUES(uuid)                                                               \
+       (uuid)[0], (uuid)[1], (uuid)[2], (uuid)[3], (uuid)[4], (uuid)[5], (uuid)[6], (uuid)[7],   \
+               (uuid)[8], (uuid)[9], (uuid)[10], (uuid)[11], (uuid)[12], (uuid)[13], (uuid)[14], \
+               (uuid)[15]
 
-#define LTTNG_UUID_SCAN_VALUES(uuid) \
-       &(uuid)[0], &(uuid)[1], &(uuid)[2], &(uuid)[3], &(uuid)[4], &(uuid)[5], \
-       &(uuid)[6], &(uuid)[7], &(uuid)[8], &(uuid)[9], &(uuid)[10], &(uuid)[11], \
-       &(uuid)[12], &(uuid)[13], &(uuid)[14], &(uuid)[15]
+#define LTTNG_UUID_SCAN_VALUES(uuid)                                                        \
+       &(uuid)[0], &(uuid)[1], &(uuid)[2], &(uuid)[3], &(uuid)[4], &(uuid)[5], &(uuid)[6], \
+               &(uuid)[7], &(uuid)[8], &(uuid)[9], &(uuid)[10], &(uuid)[11], &(uuid)[12],  \
+               &(uuid)[13], &(uuid)[14], &(uuid)[15]
 
 using lttng_uuid = std::array<uint8_t, LTTNG_UUID_LEN>;
 
index 3ddb68feb7c76dd91f09bec9d7664c02224627a2..8d2ba4d696ec228a5f886bc79ef10fa29f34c36e 100644 (file)
@@ -6,58 +6,77 @@
  *
  */
 
-#include "waiter.hpp"
-#include <urcu/uatomic.h>
-#include <urcu/futex.h>
 #include "error.hpp"
+#include "macros.hpp"
+#include "waiter.hpp"
+
 #include <poll.h>
+#include <urcu/futex.h>
+#include <urcu/uatomic.h>
 
-/*
- * Number of busy-loop attempts before waiting on futex.
- */
-#define WAIT_ATTEMPTS 1000
+namespace {
+/* Number of busy-loop attempts before waiting on futex. */
+constexpr auto wait_attempt_count = 1000;
 
 enum waiter_state {
        /* WAITER_WAITING is compared directly (futex compares it). */
-       WAITER_WAITING =        0,
+       WAITER_WAITING = 0,
        /* non-zero are used as masks. */
-       WAITER_WOKEN_UP =       (1 << 0),
-       WAITER_RUNNING =        (1 << 1),
-       WAITER_TEARDOWN =       (1 << 2),
+       WAITER_WOKEN_UP = (1 << 0),
+       WAITER_RUNNING = (1 << 1),
+       WAITER_TEARDOWN = (1 << 2),
 };
+} /* namespace */
+
+lttng::synchro::waiter::waiter()
+{
+       arm();
+}
 
-void lttng_waiter_init(struct lttng_waiter *waiter)
+void lttng::synchro::waiter::arm() noexcept
 {
-       cds_wfs_node_init(&waiter->wait_queue_node);
-       uatomic_set(&waiter->state, WAITER_WAITING);
+       cds_wfs_node_init(&_wait_queue_node);
+       uatomic_set(&_state, WAITER_WAITING);
        cmm_smp_mb();
 }
 
 /*
- * User must init "waiter" before passing its memory to waker thread.
+ * User must arm "waiter" before passing its memory to waker thread.
  */
-void lttng_waiter_wait(struct lttng_waiter *waiter)
+void lttng::synchro::waiter::wait()
 {
-       unsigned int i;
+       DBG("Beginning of waiter \"wait\" period");
 
-       DBG("Beginning of waiter wait period");
-       /* Load and test condition before read state */
+       /* Load and test condition before read state. */
        cmm_smp_rmb();
-       for (i = 0; i < WAIT_ATTEMPTS; i++) {
-               if (uatomic_read(&waiter->state) != WAITER_WAITING) {
+       for (unsigned int i = 0; i < wait_attempt_count; i++) {
+               if (uatomic_read(&_state) != WAITER_WAITING) {
                        goto skip_futex_wait;
                }
+
                caa_cpu_relax();
        }
-       while (futex_noasync(&waiter->state, FUTEX_WAIT, WAITER_WAITING,
-                       NULL, NULL, 0)) {
+
+       while (uatomic_read(&_state) == WAITER_WAITING) {
+               if (!futex_noasync(&_state, FUTEX_WAIT, WAITER_WAITING, nullptr, nullptr, 0)) {
+                       /*
+                        * Prior queued wakeups queued by unrelated code
+                        * using the same address can cause futex wait to
+                        * return 0 even through the futex value is still
+                        * WAITER_WAITING (spurious wakeups). Check
+                        * the value again in user-space to validate
+                        * whether it really differs from WAITER_WAITING.
+                        */
+                       continue;
+               }
+
                switch (errno) {
-               case EWOULDBLOCK:
+               case EAGAIN:
                        /* Value already changed. */
                        goto skip_futex_wait;
                case EINTR:
                        /* Retry if interrupted by signal. */
-                       break;  /* Get out of switch. */
+                       break; /* Get out of switch. Check again. */
                default:
                        /* Unexpected error. */
                        PERROR("futex_noasync");
@@ -67,23 +86,31 @@ void lttng_waiter_wait(struct lttng_waiter *waiter)
 skip_futex_wait:
 
        /* Tell waker thread than we are running. */
-       uatomic_or(&waiter->state, WAITER_RUNNING);
+       uatomic_or(&_state, WAITER_RUNNING);
 
        /*
         * Wait until waker thread lets us know it's ok to tear down
         * memory allocated for struct lttng_waiter.
         */
-       for (i = 0; i < WAIT_ATTEMPTS; i++) {
-               if (uatomic_read(&waiter->state) & WAITER_TEARDOWN) {
+       for (unsigned int i = 0; i < wait_attempt_count; i++) {
+               if (uatomic_read(&_state) & WAITER_TEARDOWN) {
                        break;
                }
+
                caa_cpu_relax();
        }
-       while (!(uatomic_read(&waiter->state) & WAITER_TEARDOWN)) {
-               poll(NULL, 0, 10);
+
+       while (!(uatomic_read(&_state) & WAITER_TEARDOWN)) {
+               poll(nullptr, 0, 10);
        }
-       LTTNG_ASSERT(uatomic_read(&waiter->state) & WAITER_TEARDOWN);
-       DBG("End of waiter wait period");
+
+       LTTNG_ASSERT(uatomic_read(&_state) & WAITER_TEARDOWN);
+       DBG("End of waiter \"wait\" period");
+}
+
+lttng::synchro::waker lttng::synchro::waiter::get_waker()
+{
+       return lttng::synchro::waker(_state);
 }
 
 /*
@@ -91,18 +118,50 @@ skip_futex_wait:
  * execution. In this scheme, the waiter owns the node memory, and we only allow
  * it to free this memory when it sees the WAITER_TEARDOWN flag.
  */
-void lttng_waiter_wake_up(struct lttng_waiter *waiter)
+void lttng::synchro::waker::wake()
 {
        cmm_smp_mb();
-       LTTNG_ASSERT(uatomic_read(&waiter->state) == WAITER_WAITING);
-       uatomic_set(&waiter->state, WAITER_WOKEN_UP);
-       if (!(uatomic_read(&waiter->state) & WAITER_RUNNING)) {
-               if (futex_noasync(&waiter->state, FUTEX_WAKE, 1,
-                               NULL, NULL, 0) < 0) {
+
+       LTTNG_ASSERT(uatomic_read(&_state.get()) == WAITER_WAITING);
+
+       uatomic_set(&_state.get(), WAITER_WOKEN_UP);
+       if (!(uatomic_read(&_state.get()) & WAITER_RUNNING)) {
+               if (futex_noasync(&_state.get(), FUTEX_WAKE, 1, nullptr, nullptr, 0) < 0) {
                        PERROR("futex_noasync");
                        abort();
                }
        }
+
        /* Allow teardown of struct urcu_wait memory. */
-       uatomic_or(&waiter->state, WAITER_TEARDOWN);
+       uatomic_or(&_state.get(), WAITER_TEARDOWN);
+}
+
+lttng::synchro::wait_queue::wait_queue()
+{
+       cds_wfs_init(&_stack);
+}
+
+void lttng::synchro::wait_queue::add(waiter& waiter) noexcept
+{
+       (void) cds_wfs_push(&_stack, &waiter._wait_queue_node);
+}
+
+void lttng::synchro::wait_queue::wake_all()
+{
+       /* Move all waiters from the queue to our local stack. */
+       auto *waiters = __cds_wfs_pop_all(&_stack);
+
+       /* Wake all waiters in our stack head. */
+       cds_wfs_node *iter, *iter_n;
+       cds_wfs_for_each_blocking_safe (waiters, iter, iter_n) {
+               auto& waiter = *lttng::utils::container_of(
+                       iter, &lttng::synchro::waiter::_wait_queue_node);
+
+               /* Don't wake already running threads. */
+               if (waiter._state & WAITER_RUNNING) {
+                       continue;
+               }
+
+               waiter.get_waker().wake();
+       }
 }
index 75c9ac447da2ce1320c9bf6c26d5a1b458abc7c1..cdd0913cc13e7f1957d4b493c4c0d9e3bb3265fc 100644 (file)
 
 #define _LGPL_SOURCE
 
+#include "macros.hpp"
+
+#include <functional>
 #include <stdint.h>
 #include <urcu/wfstack.h>
-#include <stdbool.h>
-#include "macros.hpp"
 
-struct lttng_waiter {
-       struct cds_wfs_node wait_queue_node;
-       int32_t state;
+namespace lttng {
+namespace synchro {
+class waiter;
+class wait_queue;
+
+class waker final {
+       friend waiter;
+
+public:
+       waker(const waker&) noexcept = default;
+       waker(waker&&) noexcept = default;
+       waker& operator=(const waker& other) noexcept = default;
+       waker& operator=(waker&& other) noexcept = default;
+
+       void wake();
+
+       ~waker() = default;
+
+private:
+       explicit waker(int32_t& state) noexcept : _state{ state }
+       {
+       }
+
+       std::reference_wrapper<int32_t> _state;
 };
 
-void lttng_waiter_init(struct lttng_waiter *waiter);
+class waiter final {
+       friend wait_queue;
 
-void lttng_waiter_wait(struct lttng_waiter *waiter);
+public:
+       waiter();
 
-/*
- * lttng_waiter_wake_up must only be called by a single waker.
- * It is invalid for multiple "wake" operations to be invoked
- * on a single waiter without re-initializing it before.
- */
-void lttng_waiter_wake_up(struct lttng_waiter *waiter);
+       /* Deactivate copy and assignment. */
+       waiter(const waiter&) = delete;
+       waiter(waiter&&) = delete;
+       waiter& operator=(const waiter&) = delete;
+       waiter& operator=(waiter&&) = delete;
+       ~waiter() = default;
+
+       void arm() noexcept;
+       void wait();
+
+       waker get_waker();
+
+private:
+       cds_wfs_node _wait_queue_node;
+       int32_t _state;
+};
+
+class wait_queue final {
+public:
+       wait_queue();
+
+       /* Deactivate copy and assignment. */
+       wait_queue(const wait_queue&) = delete;
+       wait_queue(wait_queue&&) = delete;
+       wait_queue& operator=(const wait_queue&) = delete;
+       wait_queue& operator=(wait_queue&&) = delete;
+       ~wait_queue() = default;
+
+       /*
+        * Atomically add a waiter to a wait queue.
+        * A full memory barrier is issued before being added to the wait queue.
+        */
+       void add(waiter& waiter) noexcept;
+       /*
+        * Wake every waiter present in the wait queue and remove them from
+        * the queue.
+        */
+       void wake_all();
+
+private:
+       cds_wfs_stack _stack;
+};
+} /* namespace synchro */
+} /* namespace lttng */
 
 #endif /* LTTNG_WAITER_H */
index 3613f1b1cde5e1912edead013894811660d4c5a7..a5ad2843cee1054c22504acc1db8e1205b1d3265 100644 (file)
@@ -5,30 +5,29 @@
  *
  */
 
-#include <lttng/notification/notification-internal.hpp>
-#include <lttng/notification/channel-internal.hpp>
-#include <lttng/condition/condition-internal.hpp>
-#include <lttng/endpoint.h>
+#include "lttng-ctl-helper.hpp"
+
+#include <common/compat/poll.hpp>
 #include <common/defaults.hpp>
-#include <common/error.hpp>
 #include <common/dynamic-buffer.hpp>
-#include <common/utils.hpp>
-#include <common/defaults.hpp>
-#include <common/payload.hpp>
+#include <common/error.hpp>
 #include <common/payload-view.hpp>
+#include <common/payload.hpp>
 #include <common/unix.hpp>
-#include "lttng-ctl-helper.hpp"
-#include <common/compat/poll.hpp>
+#include <common/utils.hpp>
 
-static
-int handshake(struct lttng_notification_channel *channel);
+#include <lttng/condition/condition-internal.hpp>
+#include <lttng/endpoint.h>
+#include <lttng/notification/channel-internal.hpp>
+#include <lttng/notification/notification-internal.hpp>
+
+static int handshake(struct lttng_notification_channel *channel);
 
 /*
  * Populates the reception buffer with the next complete message.
  * The caller must acquire the channel's lock.
  */
-static
-int receive_message(struct lttng_notification_channel *channel)
+static int receive_message(struct lttng_notification_channel *channel)
 {
        ssize_t ret;
        struct lttng_notification_channel_message msg;
@@ -47,8 +46,7 @@ int receive_message(struct lttng_notification_channel *channel)
        }
 
        /* Add message header at buffer's start. */
-       ret = lttng_dynamic_buffer_append(&channel->reception_payload.buffer, &msg,
-                       sizeof(msg));
+       ret = lttng_dynamic_buffer_append(&channel->reception_payload.buffer, &msg, sizeof(msg));
        if (ret) {
                goto error;
        }
@@ -59,14 +57,14 @@ int receive_message(struct lttng_notification_channel *channel)
 
        /* Reserve space for the payload. */
        ret = lttng_dynamic_buffer_set_size(&channel->reception_payload.buffer,
-                       channel->reception_payload.buffer.size + msg.size);
+                                           channel->reception_payload.buffer.size + msg.size);
        if (ret) {
                goto error;
        }
 
        /* Receive message payload. */
-       ret = lttcomm_recv_unix_sock(channel->socket,
-                       channel->reception_payload.buffer.data + sizeof(msg), msg.size);
+       ret = lttcomm_recv_unix_sock(
+               channel->socket, channel->reception_payload.buffer.data + sizeof(msg), msg.size);
        if (ret < (ssize_t) msg.size) {
                ret = -1;
                goto error;
@@ -75,8 +73,8 @@ int receive_message(struct lttng_notification_channel *channel)
 skip_payload:
        /* Receive message fds. */
        if (msg.fds != 0) {
-               ret = lttcomm_recv_payload_fds_unix_sock(channel->socket,
-                               msg.fds, &channel->reception_payload);
+               ret = lttcomm_recv_payload_fds_unix_sock(
+                       channel->socket, msg.fds, &channel->reception_payload);
                if (ret < sizeof(int) * msg.fds) {
                        ret = -1;
                        goto error;
@@ -90,61 +88,57 @@ error:
        goto end;
 }
 
-static
-enum lttng_notification_channel_message_type get_current_message_type(
-               struct lttng_notification_channel *channel)
+static enum lttng_notification_channel_message_type
+get_current_message_type(struct lttng_notification_channel *channel)
 {
        struct lttng_notification_channel_message *msg;
 
        LTTNG_ASSERT(channel->reception_payload.buffer.size >= sizeof(*msg));
 
-       msg = (struct lttng_notification_channel_message *)
-                       channel->reception_payload.buffer.data;
+       msg = (struct lttng_notification_channel_message *) channel->reception_payload.buffer.data;
        return (enum lttng_notification_channel_message_type) msg->type;
 }
 
-static
-struct lttng_notification *create_notification_from_current_message(
-               struct lttng_notification_channel *channel)
+static struct lttng_notification *
+create_notification_from_current_message(struct lttng_notification_channel *channel)
 {
        ssize_t ret;
-       struct lttng_notification *notification = NULL;
+       struct lttng_notification *notification = nullptr;
 
        if (channel->reception_payload.buffer.size <=
-                       sizeof(struct lttng_notification_channel_message)) {
+           sizeof(struct lttng_notification_channel_message)) {
                goto end;
        }
 
        {
                struct lttng_payload_view view = lttng_payload_view_from_payload(
-                               &channel->reception_payload,
-                               sizeof(struct lttng_notification_channel_message),
-                               -1);
+                       &channel->reception_payload,
+                       sizeof(struct lttng_notification_channel_message),
+                       -1);
 
-               ret = lttng_notification_create_from_payload(
-                               &view, &notification);
+               ret = lttng_notification_create_from_payload(&view, &notification);
        }
 
-       if (ret != channel->reception_payload.buffer.size -
-                       sizeof(struct lttng_notification_channel_message)) {
+       if (ret !=
+           channel->reception_payload.buffer.size -
+                   sizeof(struct lttng_notification_channel_message)) {
                lttng_notification_destroy(notification);
-               notification = NULL;
+               notification = nullptr;
                goto end;
        }
 end:
        return notification;
 }
 
-struct lttng_notification_channel *lttng_notification_channel_create(
-               struct lttng_endpoint *endpoint)
+struct lttng_notification_channel *
+lttng_notification_channel_create(struct lttng_endpoint *endpoint)
 {
        int fd, ret;
        bool is_in_tracing_group = false, is_root = false;
-       char *sock_path = NULL;
-       struct lttng_notification_channel *channel = NULL;
+       char *sock_path = nullptr;
+       struct lttng_notification_channel *channel = nullptr;
 
-       if (!endpoint ||
-                       endpoint != lttng_session_daemon_notification_endpoint) {
+       if (!endpoint || endpoint != lttng_session_daemon_notification_endpoint) {
                goto end;
        }
 
@@ -158,7 +152,7 @@ struct lttng_notification_channel *lttng_notification_channel_create(
                goto end;
        }
        channel->socket = -1;
-       pthread_mutex_init(&channel->lock, NULL);
+       pthread_mutex_init(&channel->lock, nullptr);
        lttng_payload_init(&channel->reception_payload);
        CDS_INIT_LIST_HEAD(&channel->pending_notifications.list);
 
@@ -168,9 +162,8 @@ struct lttng_notification_channel *lttng_notification_channel_create(
        }
 
        if (is_root || is_in_tracing_group) {
-               ret = lttng_strncpy(sock_path,
-                               DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK,
-                               LTTNG_PATH_MAX);
+               ret = lttng_strncpy(
+                       sock_path, DEFAULT_GLOBAL_NOTIFICATION_CHANNEL_UNIX_SOCK, LTTNG_PATH_MAX);
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto error;
@@ -184,9 +177,10 @@ struct lttng_notification_channel *lttng_notification_channel_create(
        }
 
        /* Fallback to local session daemon. */
-       ret = snprintf(sock_path, LTTNG_PATH_MAX,
-                       DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK,
-                       utils_get_home_dir());
+       ret = snprintf(sock_path,
+                      LTTNG_PATH_MAX,
+                      DEFAULT_HOME_NOTIFICATION_CHANNEL_UNIX_SOCK,
+                      utils_get_home_dir());
        if (ret < 0 || ret >= LTTNG_PATH_MAX) {
                goto error;
        }
@@ -209,19 +203,17 @@ end:
        return channel;
 error:
        lttng_notification_channel_destroy(channel);
-       channel = NULL;
+       channel = nullptr;
        goto end;
 }
 
 enum lttng_notification_channel_status
-lttng_notification_channel_get_next_notification(
-               struct lttng_notification_channel *channel,
-               struct lttng_notification **_notification)
+lttng_notification_channel_get_next_notification(struct lttng_notification_channel *channel,
+                                                struct lttng_notification **_notification)
 {
        int ret;
-       struct lttng_notification *notification = NULL;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       struct lttng_notification *notification = nullptr;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        struct lttng_poll_event events;
 
        if (!channel || !_notification) {
@@ -238,9 +230,7 @@ lttng_notification_channel_get_next_notification(
 
                /* Deliver one of the pending notifications. */
                pending_notification = cds_list_first_entry(
-                               &channel->pending_notifications.list,
-                               struct pending_notification,
-                               node);
+                       &channel->pending_notifications.list, struct pending_notification, node);
                notification = pending_notification->notification;
                if (!notification) {
                        status = LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED;
@@ -268,7 +258,7 @@ lttng_notification_channel_get_next_notification(
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                goto end_unlock;
        }
-       ret = lttng_poll_add(&events, channel->socket, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, channel->socket, LPOLLIN);
        if (ret < 0) {
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                goto end_clean_poll;
@@ -289,8 +279,7 @@ lttng_notification_channel_get_next_notification(
 
        switch (get_current_message_type(channel)) {
        case LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_NOTIFICATION:
-               notification = create_notification_from_current_message(
-                               channel);
+               notification = create_notification_from_current_message(channel);
                if (!notification) {
                        status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                        goto end_clean_poll;
@@ -315,17 +304,13 @@ end:
        return status;
 }
 
-static
-int enqueue_dropped_notification(
-               struct lttng_notification_channel *channel)
+static int enqueue_dropped_notification(struct lttng_notification_channel *channel)
 {
        int ret = 0;
        struct pending_notification *pending_notification;
-       struct cds_list_head *last_element =
-                       channel->pending_notifications.list.prev;
+       struct cds_list_head *last_element = channel->pending_notifications.list.prev;
 
-       pending_notification = caa_container_of(last_element,
-                       struct pending_notification, node);
+       pending_notification = caa_container_of(last_element, struct pending_notification, node);
        if (!pending_notification->notification) {
                /*
                 * The last enqueued notification indicates dropped
@@ -335,16 +320,14 @@ int enqueue_dropped_notification(
                goto end;
        }
 
-       if (channel->pending_notifications.count >=
-                       DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT &&
-                       pending_notification->notification) {
+       if (channel->pending_notifications.count >= DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT &&
+           pending_notification->notification) {
                /*
                 * Discard the last enqueued notification to indicate
                 * that notifications were dropped at this point.
                 */
-               lttng_notification_destroy(
-                               pending_notification->notification);
-               pending_notification->notification = NULL;
+               lttng_notification_destroy(pending_notification->notification);
+               pending_notification->notification = nullptr;
                goto end;
        }
 
@@ -354,23 +337,19 @@ int enqueue_dropped_notification(
                goto end;
        }
        CDS_INIT_LIST_HEAD(&pending_notification->node);
-       cds_list_add(&pending_notification->node,
-                       &channel->pending_notifications.list);
+       cds_list_add(&pending_notification->node, &channel->pending_notifications.list);
        channel->pending_notifications.count++;
 end:
        return ret;
 }
 
-static
-int enqueue_notification_from_current_message(
-               struct lttng_notification_channel *channel)
+static int enqueue_notification_from_current_message(struct lttng_notification_channel *channel)
 {
        int ret = 0;
        struct lttng_notification *notification;
        struct pending_notification *pending_notification;
 
-       if (channel->pending_notifications.count >=
-                       DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT) {
+       if (channel->pending_notifications.count >= DEFAULT_CLIENT_MAX_QUEUED_NOTIFICATIONS_COUNT) {
                /* Drop the notification. */
                ret = enqueue_dropped_notification(channel);
                goto end;
@@ -390,8 +369,7 @@ int enqueue_notification_from_current_message(
        }
 
        pending_notification->notification = notification;
-       cds_list_add(&pending_notification->node,
-                       &channel->pending_notifications.list);
+       cds_list_add(&pending_notification->node, &channel->pending_notifications.list);
        channel->pending_notifications.count++;
 end:
        return ret;
@@ -401,13 +379,11 @@ error:
 }
 
 enum lttng_notification_channel_status
-lttng_notification_channel_has_pending_notification(
-               struct lttng_notification_channel *channel,
-               bool *_notification_pending)
+lttng_notification_channel_has_pending_notification(struct lttng_notification_channel *channel,
+                                                   bool *_notification_pending)
 {
        int ret;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        struct lttng_poll_event events;
 
        if (!channel || !_notification_pending) {
@@ -448,7 +424,7 @@ lttng_notification_channel_has_pending_notification(
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                goto end_unlock;
        }
-       ret = lttng_poll_add(&events, channel->socket, LPOLLIN | LPOLLERR);
+       ret = lttng_poll_add(&events, channel->socket, LPOLLIN);
        if (ret < 0) {
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                goto end_clean_poll;
@@ -500,9 +476,8 @@ end:
        return status;
 }
 
-static
-int receive_command_reply(struct lttng_notification_channel *channel,
-               enum lttng_notification_channel_status *status)
+static int receive_command_reply(struct lttng_notification_channel *channel,
+                                enum lttng_notification_channel_status *status)
 {
        int ret;
        struct lttng_notification_channel_command_reply *reply;
@@ -520,8 +495,7 @@ int receive_command_reply(struct lttng_notification_channel *channel,
                case LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_COMMAND_REPLY:
                        goto exit_loop;
                case LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_NOTIFICATION:
-                       ret = enqueue_notification_from_current_message(
-                                       channel);
+                       ret = enqueue_notification_from_current_message(channel);
                        if (ret) {
                                goto end;
                        }
@@ -536,9 +510,9 @@ int receive_command_reply(struct lttng_notification_channel *channel,
                {
                        struct lttng_notification_channel_command_handshake *handshake;
 
-                       handshake = (struct lttng_notification_channel_command_handshake *)
-                                       (channel->reception_payload.buffer.data +
-                                       sizeof(struct lttng_notification_channel_message));
+                       handshake = (struct lttng_notification_channel_command_handshake
+                                            *) (channel->reception_payload.buffer.data +
+                                                sizeof(struct lttng_notification_channel_message));
                        channel->version.major = handshake->major;
                        channel->version.minor = handshake->minor;
                        channel->version.set = true;
@@ -552,27 +526,24 @@ int receive_command_reply(struct lttng_notification_channel *channel,
 
 exit_loop:
        if (channel->reception_payload.buffer.size <
-                       (sizeof(struct lttng_notification_channel_message) +
-                       sizeof(*reply))) {
+           (sizeof(struct lttng_notification_channel_message) + sizeof(*reply))) {
                /* Invalid message received. */
                ret = -1;
                goto end;
        }
 
-       reply = (struct lttng_notification_channel_command_reply *)
-                       (channel->reception_payload.buffer.data +
-                       sizeof(struct lttng_notification_channel_message));
+       reply = (struct lttng_notification_channel_command_reply
+                        *) (channel->reception_payload.buffer.data +
+                            sizeof(struct lttng_notification_channel_message));
        *status = (enum lttng_notification_channel_status) reply->status;
 end:
        return ret;
 }
 
-static
-int handshake(struct lttng_notification_channel *channel)
+static int handshake(struct lttng_notification_channel *channel)
 {
        ssize_t ret;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        struct lttng_notification_channel_command_handshake handshake = {
                .major = LTTNG_NOTIFICATION_CHANNEL_VERSION_MAJOR,
                .minor = LTTNG_NOTIFICATION_CHANNEL_VERSION_MINOR,
@@ -589,8 +560,7 @@ int handshake(struct lttng_notification_channel *channel)
 
        pthread_mutex_lock(&channel->lock);
 
-       ret = lttcomm_send_creds_unix_sock(channel->socket, send_buffer,
-                       sizeof(send_buffer));
+       ret = lttcomm_send_creds_unix_sock(channel->socket, send_buffer, sizeof(send_buffer));
        if (ret < 0) {
                goto end_unlock;
        }
@@ -616,16 +586,14 @@ end_unlock:
        return ret;
 }
 
-static
-enum lttng_notification_channel_status send_condition_command(
-               struct lttng_notification_channel *channel,
-               enum lttng_notification_channel_message_type type,
-               const struct lttng_condition *condition)
+static enum lttng_notification_channel_status
+send_condition_command(struct lttng_notification_channel *channel,
+                      enum lttng_notification_channel_message_type type,
+                      const struct lttng_condition *condition)
 {
        int socket;
        ssize_t ret;
-       enum lttng_notification_channel_status status =
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
+       enum lttng_notification_channel_status status = LTTNG_NOTIFICATION_CHANNEL_STATUS_OK;
        struct lttng_payload payload;
        struct lttng_notification_channel_message cmd_header;
 
@@ -641,7 +609,7 @@ enum lttng_notification_channel_status send_condition_command(
        }
 
        LTTNG_ASSERT(type == LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_SUBSCRIBE ||
-               type == LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNSUBSCRIBE);
+                    type == LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNSUBSCRIBE);
 
        pthread_mutex_lock(&channel->lock);
        socket = channel->socket;
@@ -651,8 +619,7 @@ enum lttng_notification_channel_status send_condition_command(
                goto end_unlock;
        }
 
-       ret = lttng_dynamic_buffer_append(&payload.buffer, &cmd_header,
-                       sizeof(cmd_header));
+       ret = lttng_dynamic_buffer_append(&payload.buffer, &cmd_header, sizeof(cmd_header));
        if (ret) {
                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                goto end_unlock;
@@ -666,21 +633,17 @@ enum lttng_notification_channel_status send_condition_command(
 
        /* Update payload length. */
        ((struct lttng_notification_channel_message *) payload.buffer.data)->size =
-                       (uint32_t) (payload.buffer.size - sizeof(cmd_header));
+               (uint32_t) (payload.buffer.size - sizeof(cmd_header));
 
        {
-               struct lttng_payload_view pv =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               const int fd_count =
-                               lttng_payload_view_get_fd_handle_count(&pv);
+               struct lttng_payload_view pv = lttng_payload_view_from_payload(&payload, 0, -1);
+               const int fd_count = lttng_payload_view_get_fd_handle_count(&pv);
 
                /* Update fd count. */
                ((struct lttng_notification_channel_message *) payload.buffer.data)->fds =
                        (uint32_t) fd_count;
 
-               ret = lttcomm_send_unix_sock(
-                       socket, pv.buffer.data, pv.buffer.size);
+               ret = lttcomm_send_unix_sock(socket, pv.buffer.data, pv.buffer.size);
                if (ret < 0) {
                        status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                        goto end_unlock;
@@ -688,8 +651,7 @@ enum lttng_notification_channel_status send_condition_command(
 
                /* Pass fds if present. */
                if (fd_count > 0) {
-                       ret = lttcomm_send_payload_view_fds_unix_sock(socket,
-                                       &pv);
+                       ret = lttcomm_send_payload_view_fds_unix_sock(socket, &pv);
                        if (ret < 0) {
                                status = LTTNG_NOTIFICATION_CHANNEL_STATUS_ERROR;
                                goto end_unlock;
@@ -709,26 +671,23 @@ end:
        return status;
 }
 
-enum lttng_notification_channel_status lttng_notification_channel_subscribe(
-               struct lttng_notification_channel *channel,
-               const struct lttng_condition *condition)
+enum lttng_notification_channel_status
+lttng_notification_channel_subscribe(struct lttng_notification_channel *channel,
+                                    const struct lttng_condition *condition)
 {
-       return send_condition_command(channel,
-                       LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_SUBSCRIBE,
-                       condition);
+       return send_condition_command(
+               channel, LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_SUBSCRIBE, condition);
 }
 
-enum lttng_notification_channel_status lttng_notification_channel_unsubscribe(
-               struct lttng_notification_channel *channel,
-               const struct lttng_condition *condition)
+enum lttng_notification_channel_status
+lttng_notification_channel_unsubscribe(struct lttng_notification_channel *channel,
+                                      const struct lttng_condition *condition)
 {
-       return send_condition_command(channel,
-                       LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNSUBSCRIBE,
-                       condition);
+       return send_condition_command(
+               channel, LTTNG_NOTIFICATION_CHANNEL_MESSAGE_TYPE_UNSUBSCRIBE, condition);
 }
 
-void lttng_notification_channel_destroy(
-               struct lttng_notification_channel *channel)
+void lttng_notification_channel_destroy(struct lttng_notification_channel *channel)
 {
        if (!channel) {
                return;
index b7a312be583e6750df64d2872f379c4fce4cfd52..61b2e5041f7bb44f5ee19f28bbb864a329c1d218 100644 (file)
@@ -7,20 +7,21 @@
  */
 
 #define _LGPL_SOURCE
-#include <algorithm>
-#include <string.h>
+#include "lttng-ctl-helper.hpp"
 
-#include <lttng/lttng-error.h>
-#include <lttng/clear.h>
-#include <lttng/clear-handle.h>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/macros.hpp>
+#include <common/buffer-view.hpp>
 #include <common/compat/poll.hpp>
 #include <common/dynamic-buffer.hpp>
-#include <common/buffer-view.hpp>
+#include <common/macros.hpp>
 #include <common/optional.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
 
-#include "lttng-ctl-helper.hpp"
+#include <lttng/clear-handle.h>
+#include <lttng/clear.h>
+#include <lttng/lttng-error.h>
+
+#include <algorithm>
+#include <string.h>
 
 enum communication_state {
        COMMUNICATION_STATE_RECEIVE_LTTNG_MSG,
@@ -60,8 +61,7 @@ void lttng_clear_handle_destroy(struct lttng_clear_handle *handle)
        free(handle);
 }
 
-static
-struct lttng_clear_handle *lttng_clear_handle_create(int sessiond_socket)
+static struct lttng_clear_handle *lttng_clear_handle_create(int sessiond_socket)
 {
        int ret;
        struct lttng_clear_handle *handle = zmalloc<lttng_clear_handle>();
@@ -76,24 +76,21 @@ struct lttng_clear_handle *lttng_clear_handle_create(int sessiond_socket)
                goto error;
        }
 
-       ret = lttng_poll_add(&handle->communication.events, sessiond_socket,
-                       LPOLLIN | LPOLLHUP | LPOLLRDHUP | LPOLLERR);
+       ret = lttng_poll_add(&handle->communication.events, sessiond_socket, LPOLLIN | LPOLLRDHUP);
        if (ret) {
                goto error;
        }
 
-       handle->communication.bytes_left_to_receive =
-                       sizeof(struct lttcomm_lttng_msg);
+       handle->communication.bytes_left_to_receive = sizeof(struct lttcomm_lttng_msg);
        handle->communication.state = COMMUNICATION_STATE_RECEIVE_LTTNG_MSG;
 end:
        return handle;
 error:
        lttng_clear_handle_destroy(handle);
-       return NULL;
+       return nullptr;
 }
 
-static
-int handle_state_transition(struct lttng_clear_handle *handle)
+static int handle_state_transition(struct lttng_clear_handle *handle)
 {
        int ret = 0;
 
@@ -103,10 +100,10 @@ int handle_state_transition(struct lttng_clear_handle *handle)
        case COMMUNICATION_STATE_RECEIVE_LTTNG_MSG:
        {
                const struct lttcomm_lttng_msg *msg =
-                               (typeof(msg)) handle->communication.buffer.data;
+                       (typeof(msg)) handle->communication.buffer.data;
 
                LTTNG_OPTIONAL_SET(&handle->clear_return_code,
-                               (enum lttng_error_code) msg->ret_code);
+                                  (enum lttng_error_code) msg->ret_code);
                if (handle->clear_return_code.value != LTTNG_OK) {
                        handle->communication.state = COMMUNICATION_STATE_END;
                        break;
@@ -119,8 +116,7 @@ int handle_state_transition(struct lttng_clear_handle *handle)
                handle->communication.state = COMMUNICATION_STATE_END;
                handle->communication.bytes_left_to_receive = 0;
                LTTNG_OPTIONAL_SET(&handle->communication.data_size, 0);
-               ret = lttng_dynamic_buffer_set_size(
-                               &handle->communication.buffer, 0);
+               ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer, 0);
                LTTNG_ASSERT(!ret);
                break;
        }
@@ -135,8 +131,7 @@ int handle_state_transition(struct lttng_clear_handle *handle)
        return ret;
 }
 
-static
-int handle_incoming_data(struct lttng_clear_handle *handle)
+static int handle_incoming_data(struct lttng_clear_handle *handle)
 {
        int ret;
        ssize_t comm_ret;
@@ -144,14 +139,15 @@ int handle_incoming_data(struct lttng_clear_handle *handle)
 
        /* Reserve space for reception. */
        ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer,
-                       original_buffer_size + handle->communication.bytes_left_to_receive);
+                                           original_buffer_size +
+                                                   handle->communication.bytes_left_to_receive);
        if (ret) {
                goto end;
        }
 
        comm_ret = lttcomm_recv_unix_sock(handle->communication.socket,
-                       handle->communication.buffer.data + original_buffer_size,
-                       handle->communication.bytes_left_to_receive);
+                                         handle->communication.buffer.data + original_buffer_size,
+                                         handle->communication.bytes_left_to_receive);
        if (comm_ret <= 0) {
                ret = -1;
                goto end;
@@ -161,17 +157,15 @@ int handle_incoming_data(struct lttng_clear_handle *handle)
        if (handle->communication.bytes_left_to_receive == 0) {
                ret = handle_state_transition(handle);
        } else {
-               ret = lttng_dynamic_buffer_set_size(
-                               &handle->communication.buffer,
-                               original_buffer_size + comm_ret);
+               ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer,
+                                                   original_buffer_size + comm_ret);
        }
 end:
        return ret;
 }
 
 extern enum lttng_clear_handle_status
-       lttng_clear_handle_wait_for_completion(
-               struct lttng_clear_handle *handle, int timeout_ms)
+lttng_clear_handle_wait_for_completion(struct lttng_clear_handle *handle, int timeout_ms)
 {
        enum lttng_clear_handle_status status;
        unsigned long time_left_ms = 0;
@@ -195,14 +189,14 @@ extern enum lttng_clear_handle_status
        }
 
        while (handle->communication.state != COMMUNICATION_STATE_END &&
-                       (time_left_ms || !has_timeout)) {
+              (time_left_ms || !has_timeout)) {
                int ret;
                uint32_t revents;
                struct timespec current_time, diff;
                unsigned long diff_ms;
 
                ret = lttng_poll_wait(&handle->communication.events,
-                               has_timeout ? time_left_ms : -1);
+                                     has_timeout ? time_left_ms : -1);
                if (ret == 0) {
                        /* timeout */
                        break;
@@ -216,8 +210,7 @@ extern enum lttng_clear_handle_status
                if (revents & LPOLLIN) {
                        ret = handle_incoming_data(handle);
                        if (ret) {
-                               handle->communication.state =
-                                               COMMUNICATION_STATE_ERROR;
+                               handle->communication.state = COMMUNICATION_STATE_ERROR;
                                status = LTTNG_CLEAR_HANDLE_STATUS_ERROR;
                                goto end;
                        }
@@ -242,27 +235,24 @@ extern enum lttng_clear_handle_status
                        status = LTTNG_CLEAR_HANDLE_STATUS_ERROR;
                        goto end;
                }
-               DBG("%lums elapsed while waiting for session clear completion",
-                               diff_ms);
+               DBG("%lums elapsed while waiting for session clear completion", diff_ms);
                diff_ms = std::max(diff_ms, 1UL);
                diff_ms = std::min(diff_ms, time_left_ms);
                time_left_ms -= diff_ms;
        }
 
        status = handle->communication.state == COMMUNICATION_STATE_END ?
-                       LTTNG_CLEAR_HANDLE_STATUS_COMPLETED :
-                       LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT;
+               LTTNG_CLEAR_HANDLE_STATUS_COMPLETED :
+               LTTNG_CLEAR_HANDLE_STATUS_TIMEOUT;
 end:
        return status;
 }
 
 extern enum lttng_clear_handle_status
-       lttng_clear_handle_get_result(
-               const struct lttng_clear_handle *handle,
-               enum lttng_error_code *result)
+lttng_clear_handle_get_result(const struct lttng_clear_handle *handle,
+                             enum lttng_error_code *result)
 {
-       enum lttng_clear_handle_status status =
-                       LTTNG_CLEAR_HANDLE_STATUS_OK;
+       enum lttng_clear_handle_status status = LTTNG_CLEAR_HANDLE_STATUS_OK;
 
        if (!handle->clear_return_code.is_set) {
                status = LTTNG_CLEAR_HANDLE_STATUS_INVALID;
@@ -277,12 +267,12 @@ end:
  * Clear the session
  */
 enum lttng_error_code lttng_clear_session(const char *session_name,
-               struct lttng_clear_handle **_handle)
+                                         struct lttng_clear_handle **_handle)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
-       struct lttng_clear_handle *handle = NULL;
+       struct lttng_clear_handle *handle = nullptr;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_CLEAR_SESSION,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_CLEAR_SESSION,
                .session = {},
                .domain = {},
                .u = {},
@@ -292,12 +282,11 @@ enum lttng_error_code lttng_clear_session(const char *session_name,
        ssize_t comm_ret;
        int ret;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
@@ -325,7 +314,7 @@ error:
        /* Transfer the handle to the caller. */
        if (_handle) {
                *_handle = handle;
-               handle = NULL;
+               handle = nullptr;
        }
        if (sessiond_socket >= 0) {
                ret = close(sessiond_socket);
index 0eaf507c29da390968111391c87827472716f483..00d76a4b8b72cbccdfc89115e6fc0aa0f629e8c7 100644 (file)
@@ -6,6 +6,7 @@
  */
 
 #include <lttng/lttng-export.h>
+
 #include <stddef.h>
 
 /*
index 3882a587e830e12e61926b38c852ff7d08b9fb8d..34f58f7e01187afc2ae5ab1ad326326197abf009 100644 (file)
@@ -5,19 +5,19 @@
  *
  */
 
-#include <lttng/destruction-handle.h>
-#include <lttng/rotation.h>
+#include "lttng-ctl-helper.hpp"
 
-#include <common/optional.hpp>
+#include <common/buffer-view.hpp>
 #include <common/compat/poll.hpp>
 #include <common/compat/time.hpp>
-#include <common/macros.hpp>
-#include <common/compat/poll.hpp>
 #include <common/dynamic-buffer.hpp>
-#include <common/buffer-view.hpp>
+#include <common/macros.hpp>
+#include <common/optional.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
+#include <lttng/destruction-handle.h>
 #include <lttng/location-internal.hpp>
-#include "lttng-ctl-helper.hpp"
+#include <lttng/rotation.h>
 
 #include <algorithm>
 #include <stdbool.h>
@@ -64,9 +64,7 @@ void lttng_destruction_handle_destroy(struct lttng_destruction_handle *handle)
        free(handle);
 }
 
-static
-struct lttng_destruction_handle *lttng_destruction_handle_create(
-               int sessiond_socket)
+static struct lttng_destruction_handle *lttng_destruction_handle_create(int sessiond_socket)
 {
        int ret;
        struct lttng_destruction_handle *handle = zmalloc<lttng_destruction_handle>();
@@ -81,24 +79,21 @@ struct lttng_destruction_handle *lttng_destruction_handle_create(
                goto error;
        }
 
-       ret = lttng_poll_add(&handle->communication.events, sessiond_socket,
-                       LPOLLIN | LPOLLHUP | LPOLLRDHUP | LPOLLERR);
+       ret = lttng_poll_add(&handle->communication.events, sessiond_socket, LPOLLIN | LPOLLRDHUP);
        if (ret) {
                goto error;
        }
 
-       handle->communication.bytes_left_to_receive =
-                       sizeof(struct lttcomm_lttng_msg);
+       handle->communication.bytes_left_to_receive = sizeof(struct lttcomm_lttng_msg);
        handle->communication.state = COMMUNICATION_STATE_RECEIVE_LTTNG_MSG;
 end:
        return handle;
 error:
        lttng_destruction_handle_destroy(handle);
-       return NULL;
+       return nullptr;
 }
 
-static
-int handle_state_transition(struct lttng_destruction_handle *handle)
+static int handle_state_transition(struct lttng_destruction_handle *handle)
 {
        int ret = 0;
 
@@ -108,44 +103,40 @@ int handle_state_transition(struct lttng_destruction_handle *handle)
        case COMMUNICATION_STATE_RECEIVE_LTTNG_MSG:
        {
                const struct lttcomm_lttng_msg *msg =
-                               (typeof(msg)) handle->communication.buffer.data;
+                       (typeof(msg)) handle->communication.buffer.data;
 
                LTTNG_OPTIONAL_SET(&handle->destruction_return_code,
-                               (enum lttng_error_code) msg->ret_code);
+                                  (enum lttng_error_code) msg->ret_code);
                if (handle->destruction_return_code.value != LTTNG_OK) {
                        handle->communication.state = COMMUNICATION_STATE_END;
                        break;
-               } else if (msg->cmd_header_size != sizeof(struct lttcomm_session_destroy_command_header) ||
-                               msg->data_size > DEFAULT_MAX_TRACE_ARCHIVE_LOCATION_PAYLOAD_SIZE) {
+               } else if (msg->cmd_header_size !=
+                                  sizeof(struct lttcomm_session_destroy_command_header) ||
+                          msg->data_size > DEFAULT_MAX_TRACE_ARCHIVE_LOCATION_PAYLOAD_SIZE) {
                        handle->communication.state = COMMUNICATION_STATE_ERROR;
                        ret = -1;
                        break;
                }
 
-               handle->communication.state =
-                               COMMUNICATION_STATE_RECEIVE_COMMAND_HEADER;
-               handle->communication.bytes_left_to_receive =
-                               msg->cmd_header_size;
-               LTTNG_OPTIONAL_SET(&handle->communication.data_size,
-                               msg->data_size);
-               ret = lttng_dynamic_buffer_set_size(
-                               &handle->communication.buffer, 0);
+               handle->communication.state = COMMUNICATION_STATE_RECEIVE_COMMAND_HEADER;
+               handle->communication.bytes_left_to_receive = msg->cmd_header_size;
+               LTTNG_OPTIONAL_SET(&handle->communication.data_size, msg->data_size);
+               ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer, 0);
                LTTNG_ASSERT(!ret);
                break;
        }
        case COMMUNICATION_STATE_RECEIVE_COMMAND_HEADER:
        {
                const struct lttcomm_session_destroy_command_header *hdr =
-                               (typeof(hdr)) handle->communication.buffer.data;
+                       (typeof(hdr)) handle->communication.buffer.data;
 
                LTTNG_OPTIONAL_SET(&handle->rotation_state,
-                               (enum lttng_rotation_state) hdr->rotation_state);
+                                  (enum lttng_rotation_state) hdr->rotation_state);
                switch (handle->rotation_state.value) {
                case LTTNG_ROTATION_STATE_COMPLETED:
-                       handle->communication.state =
-                                       COMMUNICATION_STATE_RECEIVE_PAYLOAD;
+                       handle->communication.state = COMMUNICATION_STATE_RECEIVE_PAYLOAD;
                        handle->communication.bytes_left_to_receive =
-                                       LTTNG_OPTIONAL_GET(handle->communication.data_size);
+                               LTTNG_OPTIONAL_GET(handle->communication.data_size);
                        break;
                case LTTNG_ROTATION_STATE_ERROR:
                case LTTNG_ROTATION_STATE_NO_ROTATION:
@@ -163,11 +154,9 @@ int handle_state_transition(struct lttng_destruction_handle *handle)
                ssize_t location_ret;
                struct lttng_trace_archive_location *location;
                const struct lttng_buffer_view view =
-                               lttng_buffer_view_from_dynamic_buffer(
-                                       &handle->communication.buffer, 0, -1);
+                       lttng_buffer_view_from_dynamic_buffer(&handle->communication.buffer, 0, -1);
 
-               location_ret = lttng_trace_archive_location_create_from_buffer(
-                               &view, &location);
+               location_ret = lttng_trace_archive_location_create_from_buffer(&view, &location);
                if (location_ret < 0) {
                        ERR("Failed to deserialize trace archive location");
                        handle->communication.state = COMMUNICATION_STATE_ERROR;
@@ -191,8 +180,7 @@ int handle_state_transition(struct lttng_destruction_handle *handle)
        return ret;
 }
 
-static
-int handle_incoming_data(struct lttng_destruction_handle *handle)
+static int handle_incoming_data(struct lttng_destruction_handle *handle)
 {
        int ret;
        ssize_t comm_ret;
@@ -200,14 +188,15 @@ int handle_incoming_data(struct lttng_destruction_handle *handle)
 
        /* Reserve space for reception. */
        ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer,
-                       original_buffer_size + handle->communication.bytes_left_to_receive);
+                                           original_buffer_size +
+                                                   handle->communication.bytes_left_to_receive);
        if (ret) {
                goto end;
        }
 
        comm_ret = lttcomm_recv_unix_sock(handle->communication.socket,
-                       handle->communication.buffer.data + original_buffer_size,
-                       handle->communication.bytes_left_to_receive);
+                                         handle->communication.buffer.data + original_buffer_size,
+                                         handle->communication.bytes_left_to_receive);
        if (comm_ret <= 0) {
                ret = -1;
                goto end;
@@ -217,17 +206,16 @@ int handle_incoming_data(struct lttng_destruction_handle *handle)
        if (handle->communication.bytes_left_to_receive == 0) {
                ret = handle_state_transition(handle);
        } else {
-               ret = lttng_dynamic_buffer_set_size(
-                               &handle->communication.buffer,
-                               original_buffer_size + comm_ret);
+               ret = lttng_dynamic_buffer_set_size(&handle->communication.buffer,
+                                                   original_buffer_size + comm_ret);
        }
 end:
        return ret;
 }
 
 enum lttng_destruction_handle_status
-lttng_destruction_handle_wait_for_completion(
-               struct lttng_destruction_handle *handle, int timeout_ms)
+lttng_destruction_handle_wait_for_completion(struct lttng_destruction_handle *handle,
+                                            int timeout_ms)
 {
        enum lttng_destruction_handle_status status;
        unsigned long time_left_ms = 0;
@@ -256,14 +244,14 @@ lttng_destruction_handle_wait_for_completion(
        }
 
        while (handle->communication.state != COMMUNICATION_STATE_END &&
-                       (time_left_ms || !has_timeout)) {
+              (time_left_ms || !has_timeout)) {
                int ret;
                uint32_t revents;
                struct timespec current_time, diff;
                unsigned long diff_ms;
 
                ret = lttng_poll_wait(&handle->communication.events,
-                               has_timeout ? time_left_ms : -1);
+                                     has_timeout ? time_left_ms : -1);
                if (ret == 0) {
                        /* timeout */
                        break;
@@ -277,8 +265,7 @@ lttng_destruction_handle_wait_for_completion(
                if (revents & LPOLLIN) {
                        ret = handle_incoming_data(handle);
                        if (ret) {
-                               handle->communication.state =
-                                               COMMUNICATION_STATE_ERROR;
+                               handle->communication.state = COMMUNICATION_STATE_ERROR;
                                status = LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR;
                                goto end;
                        }
@@ -303,27 +290,24 @@ lttng_destruction_handle_wait_for_completion(
                        status = LTTNG_DESTRUCTION_HANDLE_STATUS_ERROR;
                        goto end;
                }
-               DBG("%lums elapsed while waiting for session destruction completion",
-                               diff_ms);
+               DBG("%lums elapsed while waiting for session destruction completion", diff_ms);
                diff_ms = std::max(diff_ms, 1UL);
                diff_ms = std::min(diff_ms, time_left_ms);
                time_left_ms -= diff_ms;
        }
 
        status = handle->communication.state == COMMUNICATION_STATE_END ?
-                       LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED :
-                       LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT;
+               LTTNG_DESTRUCTION_HANDLE_STATUS_COMPLETED :
+               LTTNG_DESTRUCTION_HANDLE_STATUS_TIMEOUT;
 end:
        return status;
 }
 
 enum lttng_destruction_handle_status
-lttng_destruction_handle_get_rotation_state(
-               const struct lttng_destruction_handle *handle,
-               enum lttng_rotation_state *rotation_state)
+lttng_destruction_handle_get_rotation_state(const struct lttng_destruction_handle *handle,
+                                           enum lttng_rotation_state *rotation_state)
 {
-       enum lttng_destruction_handle_status status =
-                       LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
+       enum lttng_destruction_handle_status status = LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
 
        if (!handle || !rotation_state) {
                status = LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID;
@@ -340,12 +324,10 @@ end:
 }
 
 enum lttng_destruction_handle_status
-lttng_destruction_handle_get_archive_location(
-               const struct lttng_destruction_handle *handle,
-               const struct lttng_trace_archive_location **location)
+lttng_destruction_handle_get_archive_location(const struct lttng_destruction_handle *handle,
+                                             const struct lttng_trace_archive_location **location)
 {
-       enum lttng_destruction_handle_status status =
-                       LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
+       enum lttng_destruction_handle_status status = LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
 
        if (!handle || !location) {
                status = LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID;
@@ -362,12 +344,10 @@ end:
 }
 
 enum lttng_destruction_handle_status
-lttng_destruction_handle_get_result(
-               const struct lttng_destruction_handle *handle,
-               enum lttng_error_code *result)
+lttng_destruction_handle_get_result(const struct lttng_destruction_handle *handle,
+                                   enum lttng_error_code *result)
 {
-       enum lttng_destruction_handle_status status =
-                       LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
+       enum lttng_destruction_handle_status status = LTTNG_DESTRUCTION_HANDLE_STATUS_OK;
 
        if (!handle || !result) {
                status = LTTNG_DESTRUCTION_HANDLE_STATUS_INVALID;
@@ -384,28 +364,27 @@ end:
 }
 
 enum lttng_error_code lttng_destroy_session_ext(const char *session_name,
-               struct lttng_destruction_handle **_handle)
+                                               struct lttng_destruction_handle **_handle)
 {
        int ret;
        ssize_t comm_ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_DESTROY_SESSION,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_DESTROY_SESSION,
                .session = {},
                .domain = {},
                .u = {},
                .fd_count = 0,
        };
        int sessiond_socket = -1;
-       struct lttng_destruction_handle *handle = NULL;
+       struct lttng_destruction_handle *handle = nullptr;
 
        if (!session_name) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
        }
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret_code = LTTNG_ERR_INVALID;
                goto error;
@@ -435,7 +414,7 @@ enum lttng_error_code lttng_destroy_session_ext(const char *session_name,
        /* Transfer the handle to the caller. */
        if (_handle) {
                *_handle = handle;
-               handle = NULL;
+               handle = nullptr;
        }
 error:
        if (sessiond_socket >= 0) {
index c33adf1197e15485469921417f5654c3958028b5..b136640dfce031a557cec8a01c98e1d754c17c3c 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <stddef.h>
-
 #include <common/error.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <lttng/event-internal.hpp>
 #include <lttng/event.h>
 #include <lttng/lttng-error.h>
 #include <lttng/userspace-probe-internal.hpp>
 
+#include <stddef.h>
+
 struct lttng_event *lttng_event_create(void)
 {
        struct lttng_event *event;
@@ -40,7 +41,7 @@ end:
        return event;
 error:
        free(event);
-       event = NULL;
+       event = nullptr;
        goto end;
 }
 
@@ -56,16 +57,14 @@ void lttng_event_destroy(struct lttng_event *event)
 
        if (event_extended) {
                if (event_extended->probe_location) {
-                       lttng_userspace_probe_location_destroy(
-                               event_extended->probe_location);
+                       lttng_userspace_probe_location_destroy(event_extended->probe_location);
                }
                free(event_extended);
        }
        free(event);
 }
 
-int lttng_event_get_filter_expression(struct lttng_event *event,
-       const char **filter_expression)
+int lttng_event_get_filter_expression(struct lttng_event *event, const char **filter_expression)
 {
        int ret = 0;
        struct lttng_event_extended *event_extended;
@@ -81,7 +80,7 @@ int lttng_event_get_filter_expression(struct lttng_event *event,
                 * This can happen since the lttng_event structure is
                 * used for other tasks where this pointer is never set.
                 */
-               *filter_expression = NULL;
+               *filter_expression = nullptr;
                goto end;
        }
 
@@ -119,7 +118,8 @@ end:
 }
 
 int lttng_event_get_exclusion_name(struct lttng_event *event,
-               size_t index, const char **exclusion_name)
+                                  size_t index,
+                                  const char **exclusion_name)
 {
        int ret = 0;
        struct lttng_event_extended *event_extended;
@@ -149,8 +149,7 @@ int lttng_event_get_exclusion_name(struct lttng_event *event,
                goto end;
        }
 
-       *exclusion_name = event_extended->exclusions.strings +
-               (index * LTTNG_SYMBOL_NAME_LEN);
+       *exclusion_name = event_extended->exclusions.strings + (index * LTTNG_SYMBOL_NAME_LEN);
 end:
        return ret;
 }
@@ -158,7 +157,7 @@ end:
 const struct lttng_userspace_probe_location *
 lttng_event_get_userspace_probe_location(const struct lttng_event *event)
 {
-       struct lttng_userspace_probe_location *probe_location = NULL;
+       struct lttng_userspace_probe_location *probe_location = nullptr;
        struct lttng_event_extended *event_extended;
 
        if (!event) {
@@ -175,7 +174,7 @@ end:
 }
 
 int lttng_event_set_userspace_probe_location(struct lttng_event *event,
-               struct lttng_userspace_probe_location *probe_location)
+                                            struct lttng_userspace_probe_location *probe_location)
 {
        int ret = 0;
        struct lttng_event_extended *event_extended;
@@ -188,8 +187,7 @@ int lttng_event_set_userspace_probe_location(struct lttng_event *event,
        event_extended = (struct lttng_event_extended *) event->extended.ptr;
        LTTNG_ASSERT(event_extended);
        if (event_extended->probe_location) {
-               lttng_userspace_probe_location_destroy(
-                       event_extended->probe_location);
+               lttng_userspace_probe_location_destroy(event_extended->probe_location);
        }
        event_extended->probe_location = probe_location;
 end:
index b69e78df9cb8b45d66eb4c20a12837a99c742ceb..3bd9efb76cc2c64f895d1205ae4c29b0005fb899 100644 (file)
@@ -311,6 +311,7 @@ lttng_event_rule_user_tracepoint_set_filter
 lttng_event_rule_user_tracepoint_set_log_level_rule
 lttng_event_rule_user_tracepoint_set_name_pattern
 lttng_event_set_userspace_probe_location
+lttng_get_kernel_tracer_status
 lttng_health_create_consumerd
 lttng_health_create_relayd
 lttng_health_create_sessiond
index 02e2a6ff901a1e4d2fba83f426e644767cae41f8..4c04a71f3d99e9787e69173aabd8013c8b77ff8e 100644 (file)
@@ -6,27 +6,27 @@
  */
 
 #define _LGPL_SOURCE
-#include <string.h>
-#include <limits.h>
+#include "lttng-ctl-helper.hpp"
 
-#include <lttng/lttng-error.h>
-#include <lttng/load.h>
-#include <lttng/load-internal.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/compat/string.hpp>
 #include <common/config/session-config.hpp>
-#include <common/uri.hpp>
 #include <common/macros.hpp>
-#include <common/compat/string.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <common/uri.hpp>
 
-#include "lttng-ctl-helper.hpp"
+#include <lttng/load-internal.hpp>
+#include <lttng/load.h>
+#include <lttng/lttng-error.h>
+
+#include <limits.h>
+#include <string.h>
 
 struct lttng_load_session_attr *lttng_load_session_attr_create(void)
 {
        return zmalloc<lttng_load_session_attr>();
 }
 
-static
-void reset_load_session_attr_urls(struct lttng_load_session_attr *attr)
+static void reset_load_session_attr_urls(struct lttng_load_session_attr *attr)
 {
        free(attr->raw_override_url);
        free(attr->raw_override_path_url);
@@ -66,8 +66,7 @@ static int validate_attr(const struct lttng_load_session_attr *attr)
         * Refuse override name if the objective is to load multiple session
         * since this operation is ambiguous while loading multiple session.
         */
-       if (attr->override_attr->session_name
-                       && attr->session_name[0] == '\0') {
+       if (attr->override_attr->session_name && attr->session_name[0] == '\0') {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -75,10 +74,9 @@ end:
        return ret;
 }
 
-const char *lttng_load_session_attr_get_session_name(
-       struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_session_name(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (attr && attr->session_name[0]) {
                ret = attr->session_name;
@@ -87,10 +85,9 @@ const char *lttng_load_session_attr_get_session_name(
        return ret;
 }
 
-const char *lttng_load_session_attr_get_input_url(
-       struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_input_url(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (attr && attr->input_url[0]) {
                ret = attr->input_url;
@@ -99,16 +96,14 @@ const char *lttng_load_session_attr_get_input_url(
        return ret;
 }
 
-int lttng_load_session_attr_get_overwrite(
-       struct lttng_load_session_attr *attr)
+int lttng_load_session_attr_get_overwrite(struct lttng_load_session_attr *attr)
 {
        return attr ? attr->overwrite : -LTTNG_ERR_INVALID;
 }
 
-const char *lttng_load_session_attr_get_override_ctrl_url(
-       struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_override_ctrl_url(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!attr || !attr->override_attr) {
                goto end;
@@ -119,10 +114,9 @@ end:
        return ret;
 }
 
-const char *lttng_load_session_attr_get_override_data_url(
-       struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_override_data_url(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!attr || !attr->override_attr) {
                goto end;
@@ -133,28 +127,25 @@ end:
        return ret;
 }
 
-const char *lttng_load_session_attr_get_override_url(
-               struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_override_url(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!attr || !attr->override_attr) {
                goto end;
        }
 
        if ((attr->override_attr->path_url ||
-               (attr->override_attr->ctrl_url &&
-                attr->override_attr->data_url))) {
+            (attr->override_attr->ctrl_url && attr->override_attr->data_url))) {
                ret = attr->raw_override_url;
        }
 end:
        return ret;
 }
 
-const char *lttng_load_session_attr_get_override_session_name(
-               struct lttng_load_session_attr *attr)
+const char *lttng_load_session_attr_get_override_session_name(struct lttng_load_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (!attr || !attr->override_attr) {
                goto end;
@@ -165,8 +156,8 @@ end:
        return ret;
 }
 
-int lttng_load_session_attr_set_session_name(
-       struct lttng_load_session_attr *attr, const char *session_name)
+int lttng_load_session_attr_set_session_name(struct lttng_load_session_attr *attr,
+                                            const char *session_name)
 {
        int ret = 0;
 
@@ -184,8 +175,7 @@ int lttng_load_session_attr_set_session_name(
                        goto error;
                }
 
-               ret = lttng_strncpy(attr->session_name, session_name,
-                               sizeof(attr->session_name));
+               ret = lttng_strncpy(attr->session_name, session_name, sizeof(attr->session_name));
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto error;
@@ -197,13 +187,12 @@ error:
        return ret;
 }
 
-int lttng_load_session_attr_set_input_url(
-       struct lttng_load_session_attr *attr, const char *url)
+int lttng_load_session_attr_set_input_url(struct lttng_load_session_attr *attr, const char *url)
 {
        int ret = 0;
        size_t len;
        ssize_t size;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
 
        if (!attr) {
                ret = -LTTNG_ERR_INVALID;
@@ -222,15 +211,14 @@ int lttng_load_session_attr_set_input_url(
                goto error;
        }
 
-       size = uri_parse_str_urls(url, NULL, &uris);
+       size = uri_parse_str_urls(url, nullptr, &uris);
        if (size <= 0 || uris[0].dtype != LTTNG_DST_PATH) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        /* Copy string plus the NULL terminated byte. */
-       ret = lttng_strncpy(attr->input_url, uris[0].dst.path,
-                       sizeof(attr->input_url));
+       ret = lttng_strncpy(attr->input_url, uris[0].dst.path, sizeof(attr->input_url));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -242,8 +230,7 @@ error:
        return ret;
 }
 
-int lttng_load_session_attr_set_overwrite(
-       struct lttng_load_session_attr *attr, int overwrite)
+int lttng_load_session_attr_set_overwrite(struct lttng_load_session_attr *attr, int overwrite)
 {
        int ret = 0;
 
@@ -257,14 +244,14 @@ end:
        return ret;
 }
 
-int lttng_load_session_attr_set_override_ctrl_url(
-       struct lttng_load_session_attr *attr, const char *url)
+int lttng_load_session_attr_set_override_ctrl_url(struct lttng_load_session_attr *attr,
+                                                 const char *url)
 {
        int ret = 0;
        ssize_t ret_size;
-       struct lttng_uri *uri = NULL;
-       char *url_str = NULL;
-       char *raw_str = NULL;
+       struct lttng_uri *uri = nullptr;
+       char *url_str = nullptr;
+       char *raw_str = nullptr;
 
        if (!attr) {
                ret = -LTTNG_ERR_INVALID;
@@ -331,8 +318,8 @@ int lttng_load_session_attr_set_override_ctrl_url(
        attr->raw_override_ctrl_url = raw_str;
 
        /* Ownership passed to attr. */
-       url_str = NULL;
-       raw_str = NULL;
+       url_str = nullptr;
+       raw_str = nullptr;
 
 end:
        free(raw_str);
@@ -341,14 +328,14 @@ end:
        return ret;
 }
 
-int lttng_load_session_attr_set_override_data_url(
-       struct lttng_load_session_attr *attr, const char *url)
+int lttng_load_session_attr_set_override_data_url(struct lttng_load_session_attr *attr,
+                                                 const char *url)
 {
        int ret = 0;
        ssize_t ret_size;
-       struct lttng_uri *uri = NULL;
-       char *url_str = NULL;
-       char *raw_str = NULL;
+       struct lttng_uri *uri = nullptr;
+       char *url_str = nullptr;
+       char *raw_str = nullptr;
 
        if (!attr) {
                ret = -LTTNG_ERR_INVALID;
@@ -414,8 +401,8 @@ int lttng_load_session_attr_set_override_data_url(
        attr->raw_override_data_url = raw_str;
 
        /* Ownership passed to attr. */
-       url_str = NULL;
-       raw_str = NULL;
+       url_str = nullptr;
+       raw_str = nullptr;
 end:
        free(raw_str);
        free(url_str);
@@ -423,19 +410,18 @@ end:
        return ret;
 }
 
-int lttng_load_session_attr_set_override_url(
-               struct lttng_load_session_attr *attr, const char *url)
+int lttng_load_session_attr_set_override_url(struct lttng_load_session_attr *attr, const char *url)
 {
        int ret = 0;
        ssize_t ret_size;
-       struct lttng_uri *uri = NULL;
-       char *raw_url_str = NULL;
-       char *raw_path_str = NULL;
-       char *path_str = NULL;
-       char *raw_ctrl_str = NULL;
-       char *ctrl_str = NULL;
-       char *raw_data_str = NULL;
-       char *data_str = NULL;
+       struct lttng_uri *uri = nullptr;
+       char *raw_url_str = nullptr;
+       char *raw_path_str = nullptr;
+       char *path_str = nullptr;
+       char *raw_ctrl_str = nullptr;
+       char *ctrl_str = nullptr;
+       char *raw_data_str = nullptr;
+       char *data_str = nullptr;
        char buffer[PATH_MAX];
 
        if (!attr || !url || strlen(url) >= PATH_MAX) {
@@ -456,7 +442,7 @@ int lttng_load_session_attr_set_override_url(
         * type to validate "url". For now only check the parsing goes through;
         * it will fail later on.
         */
-       ret_size = uri_parse_str_urls(url, NULL, &uri);
+       ret_size = uri_parse_str_urls(url, nullptr, &uri);
        if (ret_size < 0 || ret_size > 2) {
                /* Unexpected URL format. */
                ret = -LTTNG_ERR_INVALID;
@@ -485,7 +471,7 @@ int lttng_load_session_attr_set_override_url(
                        goto end;
                }
 
-               path_str = lttng_strndup(raw_path_str, PATH_MAX);
+               path_str = lttng_strndup(uri[0].dst.path, PATH_MAX);
                if (!path_str) {
                        ret = -LTTNG_ERR_NOMEM;
                        goto end;
@@ -548,13 +534,13 @@ int lttng_load_session_attr_set_override_url(
        attr->raw_override_data_url = raw_data_str;
 
        /* Pass data ownership to attr. */
-       raw_url_str = NULL;
-       raw_path_str = NULL;
-       path_str = NULL;
-       raw_ctrl_str = NULL;
-       ctrl_str = NULL;
-       raw_data_str = NULL;
-       data_str = NULL;
+       raw_url_str = nullptr;
+       raw_path_str = nullptr;
+       path_str = nullptr;
+       raw_ctrl_str = nullptr;
+       ctrl_str = nullptr;
+       raw_data_str = nullptr;
+       data_str = nullptr;
 
 end:
        free(raw_path_str);
@@ -568,13 +554,13 @@ end:
        return ret;
 }
 
-int lttng_load_session_attr_set_override_session_name(
-       struct lttng_load_session_attr *attr, const char *session_name)
+int lttng_load_session_attr_set_override_session_name(struct lttng_load_session_attr *attr,
+                                                     const char *session_name)
 {
        int ret = 0;
        size_t len;
 
-       if (!attr ||!session_name) {
+       if (!attr || !session_name) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -593,8 +579,7 @@ int lttng_load_session_attr_set_override_session_name(
                goto end;
        }
 
-       attr->override_attr->session_name = lttng_strndup(session_name,
-               len);
+       attr->override_attr->session_name = lttng_strndup(session_name, len);
        if (!attr->override_attr->session_name) {
                ret = -LTTNG_ERR_NOMEM;
                goto end;
@@ -618,12 +603,10 @@ int lttng_load_session(struct lttng_load_session_attr *attr)
                goto end;
        }
 
-       url = attr->input_url[0] != '\0' ? attr->input_url : NULL;
-       session_name = attr->session_name[0] != '\0' ?
-                       attr->session_name : NULL;
+       url = attr->input_url[0] != '\0' ? attr->input_url : nullptr;
+       session_name = attr->session_name[0] != '\0' ? attr->session_name : nullptr;
 
-       ret = config_load_session(url, session_name, attr->overwrite, 0,
-                       attr->override_attr);
+       ret = config_load_session(url, session_name, attr->overwrite, 0, attr->override_attr);
 
 end:
        return ret;
index e3234d5d4e3ef75a70761ea20420cf500f356b8a..c490f8993c0c1ca55b31613dbad82d1142bce47b 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <unistd.h>
-#include <sys/types.h>
-#include <stdint.h>
-#include <limits.h>
-#include <string.h>
-#include <lttng/health-internal.hpp>
+#include "lttng-ctl-helper.hpp"
 
-#include <bin/lttng-sessiond/health-sessiond.hpp>
-#include <bin/lttng-consumerd/health-consumerd.hpp>
-#include <bin/lttng-relayd/health-relayd.hpp>
+#include <common/compat/errno.hpp>
+#include <common/compiler.hpp>
 #include <common/defaults.hpp>
 #include <common/utils.hpp>
-#include <common/compat/errno.hpp>
 
-#include "lttng-ctl-helper.hpp"
+#include <lttng/health-internal.hpp>
+
+#include <bin/lttng-consumerd/health-consumerd.hpp>
+#include <bin/lttng-relayd/health-relayd.hpp>
+#include <bin/lttng-sessiond/health-sessiond.hpp>
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 enum health_component {
        HEALTH_COMPONENT_SESSIOND,
@@ -47,13 +49,12 @@ struct lttng_health {
        char health_sock_path[PATH_MAX];
        /* For consumer health only */
        enum lttng_health_consumerd consumerd_type;
-       struct lttng_health_thread thread[];
+       struct lttng_health_thread thread[LTTNG_FLEXIBLE_ARRAY_MEMBER_LENGTH];
 };
 
-static
-const char *get_sessiond_thread_name(health_type_sessiond type) {
-       switch (type)
-       {
+static const char *get_sessiond_thread_name(health_type_sessiond type)
+{
+       switch (type) {
        case HEALTH_SESSIOND_TYPE_CMD:
                return "Session daemon command";
        case HEALTH_SESSIOND_TYPE_APP_MANAGE:
@@ -83,8 +84,8 @@ const char *get_sessiond_thread_name(health_type_sessiond type) {
        abort();
 };
 
-static
-const char *get_consumerd_thread_name(health_type_consumerd type) {
+static const char *get_consumerd_thread_name(health_type_consumerd type)
+{
        switch (type) {
        case HEALTH_CONSUMERD_TYPE_CHANNEL:
                return "Consumer daemon channel";
@@ -103,8 +104,7 @@ const char *get_consumerd_thread_name(health_type_consumerd type) {
        abort();
 };
 
-static
-const char *get_relayd_thread_name(health_type_relayd type)
+static const char *get_relayd_thread_name(health_type_relayd type)
 {
        switch (type) {
        case HEALTH_RELAYD_TYPE_DISPATCHER:
@@ -126,8 +126,7 @@ const char *get_relayd_thread_name(health_type_relayd type)
        abort();
 }
 
-static
-const char *get_thread_name(int comp, int nr)
+static const char *get_thread_name(int comp, int nr)
 {
        switch (comp) {
        case HEALTH_COMPONENT_SESSIOND:
@@ -148,9 +147,7 @@ const char *get_thread_name(int comp, int nr)
  *
  * Returns 0 on success or a negative errno.
  */
-static
-int set_health_socket_path(struct lttng_health *lh,
-               int tracing_group)
+static int set_health_socket_path(struct lttng_health *lh, int tracing_group)
 {
        uid_t uid;
        const char *home;
@@ -187,7 +184,7 @@ int set_health_socket_path(struct lttng_health *lh,
                } else {
                        return 0;
                }
-               break;  /* Unreached */
+               break; /* Unreached */
        default:
                return -EINVAL;
        }
@@ -195,9 +192,7 @@ int set_health_socket_path(struct lttng_health *lh,
        uid = getuid();
 
        if (uid == 0 || tracing_group) {
-               ret = lttng_strncpy(lh->health_sock_path,
-                               global_str,
-                               sizeof(lh->health_sock_path));
+               ret = lttng_strncpy(lh->health_sock_path, global_str, sizeof(lh->health_sock_path));
                return ret == 0 ? 0 : -EINVAL;
        }
 
@@ -207,15 +202,14 @@ int set_health_socket_path(struct lttng_health *lh,
         * required size (excluding closing null).
         */
        home = utils_get_home_dir();
-       if (home == NULL) {
+       if (home == nullptr) {
                /* Fallback in /tmp */
                home = "/tmp";
        }
 
        DIAGNOSTIC_PUSH
        DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
-       ret = snprintf(lh->health_sock_path, sizeof(lh->health_sock_path),
-                       home_str, home);
+       ret = snprintf(lh->health_sock_path, sizeof(lh->health_sock_path), home_str, home);
        DIAGNOSTIC_POP
        if ((ret < 0) || (ret >= sizeof(lh->health_sock_path))) {
                return -ENOMEM;
@@ -224,20 +218,18 @@ int set_health_socket_path(struct lttng_health *lh,
        return 0;
 }
 
-static
-struct lttng_health *lttng_health_create(enum health_component hc,
-               unsigned int nr_threads)
+static struct lttng_health *lttng_health_create(enum health_component hc, unsigned int nr_threads)
 {
        struct lttng_health *lh;
        int i;
 
        lh = zmalloc<lttng_health>(sizeof(*lh) + sizeof(lh->thread[0]) * nr_threads);
        if (!lh) {
-               return NULL;
+               return nullptr;
        }
 
        lh->component = hc;
-       lh->state = UINT64_MAX;         /* All bits in error initially */
+       lh->state = UINT64_MAX; /* All bits in error initially */
        lh->nr_threads = nr_threads;
        for (i = 0; i < nr_threads; i++) {
                lh->thread[i].p = lh;
@@ -249,23 +241,20 @@ struct lttng_health *lttng_health_create_sessiond(void)
 {
        struct lttng_health *lh;
 
-       lh = lttng_health_create(HEALTH_COMPONENT_SESSIOND,
-                       NR_HEALTH_SESSIOND_TYPES);
+       lh = lttng_health_create(HEALTH_COMPONENT_SESSIOND, NR_HEALTH_SESSIOND_TYPES);
        if (!lh) {
-               return NULL;
+               return nullptr;
        }
        return lh;
 }
 
-struct lttng_health *
-       lttng_health_create_consumerd(enum lttng_health_consumerd consumerd)
+struct lttng_health *lttng_health_create_consumerd(enum lttng_health_consumerd consumerd)
 {
        struct lttng_health *lh;
 
-       lh = lttng_health_create(HEALTH_COMPONENT_CONSUMERD,
-                       NR_HEALTH_CONSUMERD_TYPES);
+       lh = lttng_health_create(HEALTH_COMPONENT_CONSUMERD, NR_HEALTH_CONSUMERD_TYPES);
        if (!lh) {
-               return NULL;
+               return nullptr;
        }
        lh->consumerd_type = consumerd;
        return lh;
@@ -274,20 +263,18 @@ struct lttng_health *
 struct lttng_health *lttng_health_create_relayd(const char *path)
 {
        int ret;
-       struct lttng_health *lh = NULL;
+       struct lttng_health *lh = nullptr;
 
        if (!path) {
                goto error;
        }
 
-       lh = lttng_health_create(HEALTH_COMPONENT_RELAYD,
-                       NR_HEALTH_RELAYD_TYPES);
+       lh = lttng_health_create(HEALTH_COMPONENT_RELAYD, NR_HEALTH_RELAYD_TYPES);
        if (!lh) {
                goto error;
        }
 
-       ret = lttng_strncpy(lh->health_sock_path, path,
-                       sizeof(lh->health_sock_path));
+       ret = lttng_strncpy(lh->health_sock_path, path, sizeof(lh->health_sock_path));
        if (ret) {
                goto error;
        }
@@ -296,7 +283,7 @@ struct lttng_health *lttng_health_create_relayd(const char *path)
 
 error:
        free(lh);
-       return NULL;
+       return nullptr;
 }
 
 void lttng_health_destroy(struct lttng_health *lh)
@@ -335,13 +322,13 @@ retry:
        memset(&msg, 0, sizeof(msg));
        msg.cmd = HEALTH_CMD_CHECK;
 
-       ret = lttcomm_send_unix_sock(sock, (void *)&msg, sizeof(msg));
+       ret = lttcomm_send_unix_sock(sock, (void *) &msg, sizeof(msg));
        if (ret < 0) {
                ret = -1;
                goto close_error;
        }
 
-       ret = lttcomm_recv_unix_sock(sock, (void *)&reply, sizeof(reply));
+       ret = lttcomm_recv_unix_sock(sock, (void *) &reply, sizeof(reply));
        if (ret < 0) {
                ret = -1;
                goto close_error;
@@ -357,12 +344,12 @@ retry:
        }
 
 close_error:
-       {
-               int closeret;
+{
+       int closeret;
 
-               closeret = close(sock);
-               LTTNG_ASSERT(!closeret);
-       }
+       closeret = close(sock);
+       LTTNG_ASSERT(!closeret);
+}
 
 error:
        if (ret >= 0)
@@ -391,12 +378,11 @@ int lttng_health_get_nr_threads(const struct lttng_health *health)
        return health->nr_threads;
 }
 
-const struct lttng_health_thread *
-       lttng_health_get_thread(const struct lttng_health *health,
-               unsigned int nth_thread)
+const struct lttng_health_thread *lttng_health_get_thread(const struct lttng_health *health,
+                                                         unsigned int nth_thread)
 {
        if (!health || nth_thread >= health->nr_threads) {
-               return NULL;
+               return nullptr;
        }
        return &health->thread[nth_thread];
 }
@@ -414,8 +400,8 @@ const char *lttng_health_thread_name(const struct lttng_health_thread *thread)
        unsigned int nr;
 
        if (!thread) {
-               return NULL;
+               return nullptr;
        }
        nr = thread - &thread->p->thread[0];
-       return get_thread_name (thread->p->component, nr);
+       return get_thread_name(thread->p->component, nr);
 }
index 4b025a4e268d753543b7929e59c2dc15e63a1d9b..b725dd06fc29a609e9fd1ccf3fbccac895cee786 100644 (file)
@@ -8,14 +8,14 @@
 #ifndef LTTNG_CTL_HELPER_H
 #define LTTNG_CTL_HELPER_H
 
-#include <stdio.h>
-
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <lttng/lttng.h>
 
+#include <stdio.h>
+
 /* Copy helper functions. */
-void lttng_ctl_copy_lttng_domain(struct lttng_domain *dst,
-               struct lttng_domain *src);
+void lttng_ctl_copy_lttng_domain(struct lttng_domain *dst, struct lttng_domain *src);
 
 /*
  * Sends the lttcomm message to the session daemon and fills buf if the
@@ -25,10 +25,13 @@ void lttng_ctl_copy_lttng_domain(struct lttng_domain *dst,
  * error code. If buf is NULL, 0 is returned on success.
  */
 int lttng_ctl_ask_sessiond_fds_varlen(struct lttcomm_session_msg *lsm,
-               const int *fds, size_t nb_fd,
-               const void *vardata, size_t vardata_len,
-               void **user_payload_buf, void **user_cmd_header_buf,
-               size_t *user_cmd_header_len);
+                                     const int *fds,
+                                     size_t nb_fd,
+                                     const void *vardata,
+                                     size_t vardata_len,
+                                     void **user_payload_buf,
+                                     void **user_cmd_header_buf,
+                                     size_t *user_cmd_header_len);
 
 /*
  * Sends the lttcomm message to the session daemon and fills the reply payload.
@@ -36,43 +39,41 @@ int lttng_ctl_ask_sessiond_fds_varlen(struct lttcomm_session_msg *lsm,
  * Return the size of the received data on success or else a negative lttng
  * error code.
  */
-int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message,
-               struct lttng_payload *reply);
+int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message, struct lttng_payload *reply);
 
 /*
  * Calls lttng_ctl_ask_sessiond_fds_varlen() with no expected command header.
  */
-static inline int lttng_ctl_ask_sessiond_varlen_no_cmd_header(
-               struct lttcomm_session_msg *lsm,
-               const void *vardata,
-               size_t vardata_len,
-               void **user_payload_buf)
+static inline int lttng_ctl_ask_sessiond_varlen_no_cmd_header(struct lttcomm_session_msg *lsm,
+                                                             const void *vardata,
+                                                             size_t vardata_len,
+                                                             void **user_payload_buf)
 {
-       return lttng_ctl_ask_sessiond_fds_varlen(lsm, NULL, 0, vardata,
-               vardata_len, user_payload_buf, NULL, NULL);
+       return lttng_ctl_ask_sessiond_fds_varlen(
+               lsm, nullptr, 0, vardata, vardata_len, user_payload_buf, nullptr, nullptr);
 }
 
 /*
  * Calls lttng_ctl_ask_sessiond_fds_varlen() with fds and no expected command header.
  */
-static inline
-int lttng_ctl_ask_sessiond_fds_no_cmd_header(struct lttcomm_session_msg *lsm,
-               const int *fds, size_t nb_fd, void **buf __attribute__((unused)))
+static inline int lttng_ctl_ask_sessiond_fds_no_cmd_header(struct lttcomm_session_msg *lsm,
+                                                          const int *fds,
+                                                          size_t nb_fd,
+                                                          void **buf __attribute__((unused)))
 {
-       return lttng_ctl_ask_sessiond_fds_varlen(lsm, fds, nb_fd, NULL,
-               0, NULL, NULL, NULL);
+       return lttng_ctl_ask_sessiond_fds_varlen(
+               lsm, fds, nb_fd, nullptr, 0, nullptr, nullptr, nullptr);
 }
 /*
  * Use this if no variable length data needs to be sent.
  */
-static inline
-int lttng_ctl_ask_sessiond(struct lttcomm_session_msg *lsm, void **buf)
+static inline int lttng_ctl_ask_sessiond(struct lttcomm_session_msg *lsm, void **buf)
 {
-       return lttng_ctl_ask_sessiond_varlen_no_cmd_header(lsm, NULL, 0, buf);
+       return lttng_ctl_ask_sessiond_varlen_no_cmd_header(lsm, nullptr, 0, buf);
 }
 
-int lttng_check_tracing_group(void);
+int lttng_check_tracing_group();
 
-int connect_sessiond(void);
+int connect_sessiond();
 
 #endif /* LTTNG_CTL_HELPER_H */
index 3d0c8b412cc7297914051a3417831d417857bf28..bbc94828e6c828e7b7a9acbe90080654d714202a 100644 (file)
  */
 
 #define _LGPL_SOURCE
-#include <grp.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <unistd.h>
+#include "lttng-ctl-helper.hpp"
 
-#include <common/bytecode/bytecode.hpp>
 #include <common/align.hpp>
+#include <common/bytecode/bytecode.hpp>
 #include <common/common.hpp>
 #include <common/compat/errno.hpp>
 #include <common/compat/string.hpp>
 #include <common/defaults.hpp>
 #include <common/dynamic-array.hpp>
 #include <common/dynamic-buffer.hpp>
+#include <common/filter/filter-ast.hpp>
+#include <common/filter/filter-parser.hpp>
+#include <common/filter/memstream.hpp>
+#include <common/make-unique-wrapper.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
 #include <common/sessiond-comm/sessiond-comm.hpp>
@@ -33,6 +32,7 @@
 #include <common/unix.hpp>
 #include <common/uri.hpp>
 #include <common/utils.hpp>
+
 #include <lttng/channel-internal.hpp>
 #include <lttng/destruction-handle.h>
 #include <lttng/endpoint.h>
 #include <lttng/trigger/trigger-internal.hpp>
 #include <lttng/userspace-probe-internal.hpp>
 
-#include "lttng-ctl-helper.hpp"
-#include <common/filter/filter-ast.hpp>
-#include <common/filter/filter-parser.hpp>
-#include <common/filter/memstream.hpp>
+#include <grp.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
 
-#define COPY_DOMAIN_PACKED(dst, src)                           \
-do {                                                           \
-       struct lttng_domain _tmp_domain;                        \
-                                                               \
-       lttng_ctl_copy_lttng_domain(&_tmp_domain, &src);        \
-       dst = _tmp_domain;                                      \
-} while (0)
+#define COPY_DOMAIN_PACKED(dst, src)                               \
+       do {                                                       \
+               struct lttng_domain _tmp_domain;                   \
+                                                                   \
+               lttng_ctl_copy_lttng_domain(&_tmp_domain, &(src)); \
+               (dst) = _tmp_domain;                               \
+       } while (0)
 
 /* Socket to session daemon for communication */
 static int sessiond_socket = -1;
@@ -83,8 +85,7 @@ LTTNG_EXPORT int lttng_opt_mi;
  *
  * If domain is unknown, default domain will be the kernel.
  */
-void lttng_ctl_copy_lttng_domain(struct lttng_domain *dst,
-               struct lttng_domain *src)
+void lttng_ctl_copy_lttng_domain(struct lttng_domain *dst, struct lttng_domain *src)
 {
        if (src && dst) {
                switch (src->type) {
@@ -117,11 +118,12 @@ static int send_session_msg(struct lttcomm_session_msg *lsm)
                goto end;
        }
 
-       DBG("LSM cmd type: '%s' (%d)", lttcomm_sessiond_command_str((lttcomm_sessiond_command) lsm->cmd_type),
-                       lsm->cmd_type);
+       DBG("LSM cmd type: '%s' (%d)",
+           lttcomm_sessiond_command_str((lttcomm_sessiond_command) lsm->cmd_type),
+           lsm->cmd_type);
 
-       ret = lttcomm_send_creds_unix_sock(sessiond_socket, lsm,
-                       sizeof(struct lttcomm_session_msg));
+       ret = lttcomm_send_creds_unix_sock(
+               sessiond_socket, lsm, sizeof(struct lttcomm_session_msg));
        if (ret < 0) {
                ret = -LTTNG_ERR_FATAL;
        }
@@ -227,15 +229,13 @@ static int recv_payload_sessiond(struct lttng_payload *payload, size_t len)
        int ret;
        const size_t original_payload_size = payload->buffer.size;
 
-       ret = lttng_dynamic_buffer_set_size(
-                       &payload->buffer, payload->buffer.size + len);
+       ret = lttng_dynamic_buffer_set_size(&payload->buffer, payload->buffer.size + len);
        if (ret) {
                ret = -LTTNG_ERR_NOMEM;
                goto end;
        }
 
-       ret = recv_data_sessiond(
-                       payload->buffer.data + original_payload_size, len);
+       ret = recv_data_sessiond(payload->buffer.data + original_payload_size, len);
 end:
        return ret;
 }
@@ -245,7 +245,7 @@ end:
  *
  * If yes return 1, else return -1.
  */
-int lttng_check_tracing_group(void)
+int lttng_check_tracing_group()
 {
        gid_t *grp_list, tracing_gid;
        int grp_list_size, grp_id, i;
@@ -259,7 +259,7 @@ int lttng_check_tracing_group(void)
        }
 
        /* Get number of supplementary group IDs */
-       grp_list_size = getgroups(0, NULL);
+       grp_list_size = getgroups(0, nullptr);
        if (grp_list_size < 0) {
                PERROR("getgroups");
                goto end;
@@ -291,8 +291,7 @@ end:
        return ret;
 }
 
-static enum lttng_error_code check_enough_available_memory(
-               uint64_t num_bytes_requested_per_cpu)
+static enum lttng_error_code check_enough_available_memory(uint64_t num_bytes_requested_per_cpu)
 {
        int ret;
        enum lttng_error_code ret_code;
@@ -316,8 +315,7 @@ static enum lttng_error_code check_enough_available_memory(
                goto end;
        }
 
-       num_bytes_requested_total =
-                       num_bytes_requested_per_cpu * (uint64_t) num_cpu;
+       num_bytes_requested_total = num_bytes_requested_per_cpu * (uint64_t) num_cpu;
 
        /*
         * Try to get the `MemAvail` field of `/proc/meminfo`. This is the most
@@ -393,9 +391,9 @@ error:
  * Returns 0 on success, negative value on failure (the sessiond socket path
  * is somehow too long or ENOMEM).
  */
-static int set_session_daemon_path(void)
+static int set_session_daemon_path()
 {
-       int in_tgroup = 0;      /* In tracing group. */
+       int in_tgroup = 0; /* In tracing group. */
        uid_t uid;
 
        uid = getuid();
@@ -407,8 +405,8 @@ static int set_session_daemon_path(void)
 
        if ((uid == 0) || in_tgroup == 1) {
                const int ret = lttng_strncpy(sessiond_sock_path,
-                               DEFAULT_GLOBAL_CLIENT_UNIX_SOCK,
-                               sizeof(sessiond_sock_path));
+                                             DEFAULT_GLOBAL_CLIENT_UNIX_SOCK,
+                                             sizeof(sessiond_sock_path));
 
                if (ret) {
                        goto error;
@@ -434,8 +432,10 @@ static int set_session_daemon_path(void)
                 * With GNU C >= 2.1, snprintf returns the required size
                 * (excluding closing null)
                 */
-               ret = snprintf(sessiond_sock_path, sizeof(sessiond_sock_path),
-                               DEFAULT_HOME_CLIENT_UNIX_SOCK, utils_get_home_dir());
+               ret = snprintf(sessiond_sock_path,
+                              sizeof(sessiond_sock_path),
+                              DEFAULT_HOME_CLIENT_UNIX_SOCK,
+                              utils_get_home_dir());
                if ((ret < 0) || (ret >= sizeof(sessiond_sock_path))) {
                        goto error;
                }
@@ -452,7 +452,7 @@ error:
  *
  * On success, return the socket's file descriptor. On error, return -1.
  */
-int connect_sessiond(void)
+int connect_sessiond()
 {
        int ret;
 
@@ -473,7 +473,7 @@ error:
        return -1;
 }
 
-static void reset_global_sessiond_connection_state(void)
+static void reset_global_sessiond_connection_state()
 {
        sessiond_socket = -1;
        connected = 0;
@@ -484,7 +484,7 @@ static void reset_global_sessiond_connection_state(void)
  *
  *  On success, return 0. On error, return -1.
  */
-static int disconnect_sessiond(void)
+static int disconnect_sessiond()
 {
        int ret = 0;
 
@@ -496,11 +496,10 @@ static int disconnect_sessiond(void)
        return ret;
 }
 
-static int recv_sessiond_optional_data(size_t len, void **user_buf,
-       size_t *user_len)
+static int recv_sessiond_optional_data(size_t len, void **user_buf, size_t *user_len)
 {
        int ret = 0;
-       char *buf = NULL;
+       char *buf = nullptr;
 
        if (len) {
                if (!user_len) {
@@ -526,7 +525,7 @@ static int recv_sessiond_optional_data(size_t len, void **user_buf,
 
                /* Move ownership of command header buffer to user. */
                *user_buf = buf;
-               buf = NULL;
+               buf = nullptr;
                *user_len = len;
        } else {
                /* No command header. */
@@ -535,7 +534,7 @@ static int recv_sessiond_optional_data(size_t len, void **user_buf,
                }
 
                if (user_buf) {
-                       *user_buf = NULL;
+                       *user_buf = nullptr;
                }
        }
 
@@ -552,9 +551,13 @@ end:
  * Return size of data (only payload, not header) or a negative error code.
  */
 int lttng_ctl_ask_sessiond_fds_varlen(struct lttcomm_session_msg *lsm,
-               const int *fds, size_t nb_fd, const void *vardata,
-               size_t vardata_len, void **user_payload_buf,
-               void **user_cmd_header_buf, size_t *user_cmd_header_len)
+                                     const int *fds,
+                                     size_t nb_fd,
+                                     const void *vardata,
+                                     size_t vardata_len,
+                                     void **user_payload_buf,
+                                     void **user_cmd_header_buf,
+                                     size_t *user_cmd_header_len)
 {
        int ret;
        size_t payload_len;
@@ -602,15 +605,14 @@ int lttng_ctl_ask_sessiond_fds_varlen(struct lttcomm_session_msg *lsm,
        }
 
        /* Get command header from data transmission */
-       ret = recv_sessiond_optional_data(llm.cmd_header_size,
-               user_cmd_header_buf, user_cmd_header_len);
+       ret = recv_sessiond_optional_data(
+               llm.cmd_header_size, user_cmd_header_buf, user_cmd_header_len);
        if (ret < 0) {
                goto end;
        }
 
        /* Get payload from data transmission */
-       ret = recv_sessiond_optional_data(llm.data_size, user_payload_buf,
-               &payload_len);
+       ret = recv_sessiond_optional_data(llm.data_size, user_payload_buf, &payload_len);
        if (ret < 0) {
                goto end;
        }
@@ -622,8 +624,7 @@ end:
        return ret;
 }
 
-int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message,
-       struct lttng_payload *reply)
+int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message, struct lttng_payload *reply)
 {
        int ret;
        struct lttcomm_lttng_msg llm;
@@ -642,16 +643,15 @@ int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message,
        }
 
        /* Send command to session daemon */
-       ret = lttcomm_send_creds_unix_sock(sessiond_socket, message->buffer.data,
-                       message->buffer.size);
+       ret = lttcomm_send_creds_unix_sock(
+               sessiond_socket, message->buffer.data, message->buffer.size);
        if (ret < 0) {
                ret = -LTTNG_ERR_FATAL;
                goto end;
        }
 
        if (fd_count > 0) {
-               ret = lttcomm_send_payload_view_fds_unix_sock(sessiond_socket,
-                               message);
+               ret = lttcomm_send_payload_view_fds_unix_sock(sessiond_socket, message);
                if (ret < 0) {
                        ret = -LTTNG_ERR_FATAL;
                        goto end;
@@ -694,18 +694,17 @@ int lttng_ctl_ask_sessiond_payload(struct lttng_payload_view *message,
        }
 
        if (llm.fd_count > 0) {
-               ret = lttcomm_recv_payload_fds_unix_sock(
-                               sessiond_socket, llm.fd_count, reply);
+               ret = lttcomm_recv_payload_fds_unix_sock(sessiond_socket, llm.fd_count, reply);
                if (ret < 0) {
                        goto end;
                }
        }
 
        /* Don't return the llm header to the caller. */
-       memmove(reply->buffer.data, reply->buffer.data + sizeof(llm),
-                       reply->buffer.size - sizeof(llm));
-       ret = lttng_dynamic_buffer_set_size(
-                       &reply->buffer, reply->buffer.size - sizeof(llm));
+       memmove(reply->buffer.data,
+               reply->buffer.data + sizeof(llm),
+               reply->buffer.size - sizeof(llm));
+       ret = lttng_dynamic_buffer_set_size(&reply->buffer, reply->buffer.size - sizeof(llm));
        if (ret) {
                /* Can't happen as size is reduced. */
                abort();
@@ -723,21 +722,19 @@ end:
  *
  * The returned pointer will be NULL in case of malloc() error.
  */
-struct lttng_handle *lttng_create_handle(const char *session_name,
-               struct lttng_domain *domain)
+struct lttng_handle *lttng_create_handle(const char *session_name, struct lttng_domain *domain)
 {
        int ret;
-       struct lttng_handle *handle = NULL;
+       struct lttng_handle *handle = nullptr;
 
        handle = zmalloc<lttng_handle>();
-       if (handle == NULL) {
+       if (handle == nullptr) {
                PERROR("malloc handle");
                goto end;
        }
 
        /* Copy session name */
-       ret = lttng_strncpy(handle->session_name, session_name ? : "",
-                           sizeof(handle->session_name));
+       ret = lttng_strncpy(handle->session_name, session_name ?: "", sizeof(handle->session_name));
        if (ret) {
                goto error;
        }
@@ -751,7 +748,7 @@ end:
        return handle;
 error:
        free(handle);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -767,21 +764,19 @@ void lttng_destroy_handle(struct lttng_handle *handle)
  *
  * Returns size of returned session payload data or a negative error code.
  */
-int lttng_register_consumer(struct lttng_handle *handle,
-               const char *socket_path)
+int lttng_register_consumer(struct lttng_handle *handle, const char *socket_path)
 {
        int ret;
        struct lttcomm_session_msg lsm;
 
-       if (handle == NULL || socket_path == NULL) {
+       if (handle == nullptr || socket_path == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_REGISTER_CONSUMER;
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_REGISTER_CONSUMER;
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -789,14 +784,13 @@ int lttng_register_consumer(struct lttng_handle *handle,
 
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
-       ret = lttng_strncpy(lsm.u.reg.path, socket_path,
-                           sizeof(lsm.u.reg.path));
+       ret = lttng_strncpy(lsm.u.reg.path, socket_path, sizeof(lsm.u.reg.path));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -811,22 +805,21 @@ int lttng_start_tracing(const char *session_name)
        int ret;
        struct lttcomm_session_msg lsm;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_START_TRACE;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_START_TRACE;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -839,22 +832,21 @@ static int _lttng_stop_tracing(const char *session_name, int wait)
        int ret, data_ret;
        struct lttcomm_session_msg lsm;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_STOP_TRACE;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_STOP_TRACE;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
        if (ret < 0 && ret != -LTTNG_ERR_TRACE_ALREADY_STOPPED) {
                goto error;
        }
@@ -911,13 +903,13 @@ int lttng_stop_tracing_no_wait(const char *session_name)
  * Returns the size of the returned payload data or a negative error code.
  */
 int lttng_add_context(struct lttng_handle *handle,
-               struct lttng_event_context *ctx,
-               const char *event_name __attribute__((unused)),
-               const char *channel_name)
+                     struct lttng_event_context *ctx,
+                     const char *event_name __attribute__((unused)),
+                     const char *channel_name)
 {
        int ret;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_ADD_CONTEXT,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_ADD_CONTEXT,
                .session = {},
                .domain = {},
                .u = {},
@@ -928,7 +920,7 @@ int lttng_add_context(struct lttng_handle *handle,
        lttng_payload_init(&payload);
 
        /* Safety check. Both are mandatory. */
-       if (handle == NULL || ctx == NULL) {
+       if (handle == nullptr || ctx == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -940,16 +932,15 @@ int lttng_add_context(struct lttng_handle *handle,
        }
 
        /* If no channel name, send empty string. */
-       ret = lttng_strncpy(lsm.u.context.channel_name, channel_name ?: "",
-                       sizeof(lsm.u.context.channel_name));
+       ret = lttng_strncpy(
+               lsm.u.context.channel_name, channel_name ?: "", sizeof(lsm.u.context.channel_name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -969,8 +960,7 @@ int lttng_add_context(struct lttng_handle *handle,
        {
                struct lttng_payload reply;
                struct lttng_payload_view payload_view =
-                               lttng_payload_view_from_payload(&payload, 0,
-                               -1);
+                       lttng_payload_view_from_payload(&payload, 0, -1);
 
                lttng_payload_init(&reply);
                ret = lttng_ctl_ask_sessiond_payload(&payload_view, &reply);
@@ -994,10 +984,10 @@ end:
  * Returns size of returned session payload data or a negative error code.
  */
 int lttng_enable_event(struct lttng_handle *handle,
-               struct lttng_event *ev, const char *channel_name)
+                      struct lttng_event *ev,
+                      const char *channel_name)
 {
-       return lttng_enable_event_with_exclusions(handle, ev, channel_name,
-                       NULL, 0, NULL);
+       return lttng_enable_event_with_exclusions(handle, ev, channel_name, nullptr, 0, nullptr);
 }
 
 /*
@@ -1007,11 +997,12 @@ int lttng_enable_event(struct lttng_handle *handle,
  * Return size of returned session payload data if OK.
  */
 int lttng_enable_event_with_filter(struct lttng_handle *handle,
-               struct lttng_event *event, const char *channel_name,
-               const char *filter_expression)
+                                  struct lttng_event *event,
+                                  const char *channel_name,
+                                  const char *filter_expression)
 {
-       return lttng_enable_event_with_exclusions(handle, event, channel_name,
-                       filter_expression, 0, NULL);
+       return lttng_enable_event_with_exclusions(
+               handle, event, channel_name, filter_expression, 0, nullptr);
 }
 
 /*
@@ -1023,15 +1014,15 @@ int lttng_enable_event_with_filter(struct lttng_handle *handle,
 static char *set_agent_filter(const char *filter, struct lttng_event *ev)
 {
        int err;
-       char *agent_filter = NULL;
+       char *agent_filter = nullptr;
 
        LTTNG_ASSERT(ev);
 
        /* Don't add filter for the '*' event. */
        if (strcmp(ev->name, "*") != 0) {
                if (filter) {
-                       err = asprintf(&agent_filter, "(%s) && (logger_name == \"%s\")", filter,
-                                       ev->name);
+                       err = asprintf(
+                               &agent_filter, "(%s) && (logger_name == \"%s\")", filter, ev->name);
                } else {
                        err = asprintf(&agent_filter, "logger_name == \"%s\"", ev->name);
                }
@@ -1054,16 +1045,17 @@ static char *set_agent_filter(const char *filter, struct lttng_event *ev)
                if (filter || agent_filter) {
                        char *new_filter;
 
-                       err = asprintf(&new_filter, "(%s) && (int_loglevel %s %d)",
-                                       agent_filter ? agent_filter : filter, op,
-                                       ev->loglevel);
+                       err = asprintf(&new_filter,
+                                      "(%s) && (int_loglevel %s %d)",
+                                      agent_filter ? agent_filter : filter,
+                                      op,
+                                      ev->loglevel);
                        if (agent_filter) {
                                free(agent_filter);
                        }
                        agent_filter = new_filter;
                } else {
-                       err = asprintf(&agent_filter, "int_loglevel %s %d", op,
-                                       ev->loglevel);
+                       err = asprintf(&agent_filter, "int_loglevel %s %d", op, ev->loglevel);
                }
                if (err < 0) {
                        PERROR("asprintf");
@@ -1074,7 +1066,7 @@ static char *set_agent_filter(const char *filter, struct lttng_event *ev)
        return agent_filter;
 error:
        free(agent_filter);
-       return NULL;
+       return nullptr;
 }
 
 /*
@@ -1086,12 +1078,14 @@ error:
  * Returns size of returned session payload data or a negative error code.
  */
 int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
-               struct lttng_event *ev, const char *channel_name,
-               const char *original_filter_expression,
-               int exclusion_count, char **exclusion_list)
+                                      struct lttng_event *ev,
+                                      const char *channel_name,
+                                      const char *original_filter_expression,
+                                      int exclusion_count,
+                                      char **exclusion_list)
 {
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_ENABLE_EVENT,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_ENABLE_EVENT,
                .session = {},
                .domain = {},
                .u = {},
@@ -1100,7 +1094,7 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
        struct lttng_payload payload;
        int ret = 0;
        unsigned int free_filter_expression = 0;
-       struct filter_parser_ctx *ctx = NULL;
+       struct filter_parser_ctx *ctx = nullptr;
        size_t bytecode_len = 0;
 
        /*
@@ -1116,7 +1110,7 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
         */
        char *filter_expression = (char *) original_filter_expression;
 
-       if (handle == NULL || ev == NULL) {
+       if (handle == nullptr || ev == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
@@ -1138,12 +1132,12 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
        }
 
        /* Parse filter expression. */
-       if (filter_expression != NULL || handle->domain.type == LTTNG_DOMAIN_JUL
-                       || handle->domain.type == LTTNG_DOMAIN_LOG4J
-                       || handle->domain.type == LTTNG_DOMAIN_PYTHON) {
+       if (filter_expression != nullptr || handle->domain.type == LTTNG_DOMAIN_JUL ||
+           handle->domain.type == LTTNG_DOMAIN_LOG4J ||
+           handle->domain.type == LTTNG_DOMAIN_PYTHON) {
                if (handle->domain.type == LTTNG_DOMAIN_JUL ||
-                               handle->domain.type == LTTNG_DOMAIN_LOG4J ||
-                               handle->domain.type == LTTNG_DOMAIN_PYTHON) {
+                   handle->domain.type == LTTNG_DOMAIN_LOG4J ||
+                   handle->domain.type == LTTNG_DOMAIN_PYTHON) {
                        char *agent_filter;
 
                        /* Setup agent filter if needed. */
@@ -1167,8 +1161,7 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
                        }
                }
 
-               if (strnlen(filter_expression, LTTNG_FILTER_MAX_LEN) ==
-                               LTTNG_FILTER_MAX_LEN) {
+               if (strnlen(filter_expression, LTTNG_FILTER_MAX_LEN) == LTTNG_FILTER_MAX_LEN) {
                        ret = -LTTNG_ERR_FILTER_INVAL;
                        goto error;
                }
@@ -1178,8 +1171,7 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
                        goto error;
                }
 
-               bytecode_len = bytecode_get_len(&ctx->bytecode->b) +
-                               sizeof(ctx->bytecode->b);
+               bytecode_len = bytecode_get_len(&ctx->bytecode->b) + sizeof(ctx->bytecode->b);
                if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
                        ret = -LTTNG_ERR_FILTER_INVAL;
                        goto error;
@@ -1187,18 +1179,21 @@ int lttng_enable_event_with_exclusions(struct lttng_handle *handle,
        }
 
 serialize:
-       ret = lttng_event_serialize(ev, exclusion_count, exclusion_list,
-                       filter_expression, bytecode_len,
-                       (ctx && bytecode_len) ? &ctx->bytecode->b : NULL,
-                       &payload);
+       ret = lttng_event_serialize(ev,
+                                   exclusion_count,
+                                   exclusion_list,
+                                   filter_expression,
+                                   bytecode_len,
+                                   (ctx && bytecode_len) ? &ctx->bytecode->b : nullptr,
+                                   &payload);
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        /* If no channel name, send empty string. */
-       ret = lttng_strncpy(lsm.u.enable.channel_name, channel_name ?: "",
-                       sizeof(lsm.u.enable.channel_name));
+       ret = lttng_strncpy(
+               lsm.u.enable.channel_name, channel_name ?: "", sizeof(lsm.u.enable.channel_name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -1208,8 +1203,7 @@ serialize:
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
        /* Session name */
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -1219,8 +1213,7 @@ serialize:
        lsm.u.enable.length = (uint32_t) payload.buffer.size;
 
        {
-               struct lttng_payload_view view = lttng_payload_view_from_payload(
-                       &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
                int fd_count = lttng_payload_view_get_fd_handle_count(&view);
                int fd_to_send;
 
@@ -1230,8 +1223,7 @@ serialize:
 
                LTTNG_ASSERT(fd_count == 0 || fd_count == 1);
                if (fd_count == 1) {
-                       struct fd_handle *h =
-                                       lttng_payload_view_pop_fd_handle(&view);
+                       struct fd_handle *h = lttng_payload_view_pop_fd_handle(&view);
 
                        if (!h) {
                                goto error;
@@ -1244,9 +1236,14 @@ serialize:
                lsm.fd_count = fd_count;
 
                ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm,
-                               fd_count ? &fd_to_send : NULL, fd_count,
-                               view.buffer.size ? view.buffer.data : NULL,
-                               view.buffer.size, NULL, NULL, 0);
+                                                       fd_count ? &fd_to_send : nullptr,
+                                                       fd_count,
+                                                       view.buffer.size ? view.buffer.data :
+                                                                          nullptr,
+                                                       view.buffer.size,
+                                                       nullptr,
+                                                       nullptr,
+                                                       nullptr);
        }
 
 error:
@@ -1272,11 +1269,12 @@ error:
 }
 
 int lttng_disable_event_ext(struct lttng_handle *handle,
-               struct lttng_event *ev, const char *channel_name,
-               const char *original_filter_expression)
+                           struct lttng_event *ev,
+                           const char *channel_name,
+                           const char *original_filter_expression)
 {
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_DISABLE_EVENT,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_DISABLE_EVENT,
                .session = {},
                .domain = {},
                .u = {},
@@ -1285,7 +1283,7 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
        struct lttng_payload payload;
        int ret = 0;
        unsigned int free_filter_expression = 0;
-       struct filter_parser_ctx *ctx = NULL;
+       struct filter_parser_ctx *ctx = nullptr;
        size_t bytecode_len = 0;
 
        /*
@@ -1301,7 +1299,7 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
         */
        char *filter_expression = (char *) original_filter_expression;
 
-       if (handle == NULL || ev == NULL) {
+       if (handle == nullptr || ev == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
@@ -1317,12 +1315,12 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
        }
 
        /* Parse filter expression. */
-       if (filter_expression != NULL || handle->domain.type == LTTNG_DOMAIN_JUL
-                       || handle->domain.type == LTTNG_DOMAIN_LOG4J
-                       || handle->domain.type == LTTNG_DOMAIN_PYTHON) {
+       if (filter_expression != nullptr || handle->domain.type == LTTNG_DOMAIN_JUL ||
+           handle->domain.type == LTTNG_DOMAIN_LOG4J ||
+           handle->domain.type == LTTNG_DOMAIN_PYTHON) {
                if (handle->domain.type == LTTNG_DOMAIN_JUL ||
-                               handle->domain.type == LTTNG_DOMAIN_LOG4J ||
-                               handle->domain.type == LTTNG_DOMAIN_PYTHON) {
+                   handle->domain.type == LTTNG_DOMAIN_LOG4J ||
+                   handle->domain.type == LTTNG_DOMAIN_PYTHON) {
                        char *agent_filter;
 
                        /* Setup agent filter if needed. */
@@ -1346,8 +1344,7 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
                        }
                }
 
-               if (strnlen(filter_expression, LTTNG_FILTER_MAX_LEN) ==
-                               LTTNG_FILTER_MAX_LEN) {
+               if (strnlen(filter_expression, LTTNG_FILTER_MAX_LEN) == LTTNG_FILTER_MAX_LEN) {
                        ret = -LTTNG_ERR_FILTER_INVAL;
                        goto error;
                }
@@ -1357,8 +1354,7 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
                        goto error;
                }
 
-               bytecode_len = bytecode_get_len(&ctx->bytecode->b) +
-                               sizeof(ctx->bytecode->b);
+               bytecode_len = bytecode_get_len(&ctx->bytecode->b) + sizeof(ctx->bytecode->b);
                if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
                        ret = -LTTNG_ERR_FILTER_INVAL;
                        goto error;
@@ -1366,18 +1362,21 @@ int lttng_disable_event_ext(struct lttng_handle *handle,
        }
 
 serialize:
-       ret = lttng_event_serialize(ev, 0, NULL,
-                       filter_expression, bytecode_len,
-                       (ctx && bytecode_len) ? &ctx->bytecode->b : NULL,
-                       &payload);
+       ret = lttng_event_serialize(ev,
+                                   0,
+                                   nullptr,
+                                   filter_expression,
+                                   bytecode_len,
+                                   (ctx && bytecode_len) ? &ctx->bytecode->b : nullptr,
+                                   &payload);
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        /* If no channel name, send empty string. */
-       ret = lttng_strncpy(lsm.u.disable.channel_name, channel_name ?: "",
-                       sizeof(lsm.u.disable.channel_name));
+       ret = lttng_strncpy(
+               lsm.u.disable.channel_name, channel_name ?: "", sizeof(lsm.u.disable.channel_name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -1387,8 +1386,7 @@ serialize:
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
        /* Session name */
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -1398,8 +1396,7 @@ serialize:
        lsm.u.disable.length = (uint32_t) payload.buffer.size;
 
        {
-               struct lttng_payload_view view = lttng_payload_view_from_payload(
-                       &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
                int fd_count = lttng_payload_view_get_fd_handle_count(&view);
                int fd_to_send;
 
@@ -1409,8 +1406,7 @@ serialize:
 
                LTTNG_ASSERT(fd_count == 0 || fd_count == 1);
                if (fd_count == 1) {
-                       struct fd_handle *h =
-                                       lttng_payload_view_pop_fd_handle(&view);
+                       struct fd_handle *h = lttng_payload_view_pop_fd_handle(&view);
 
                        if (!h) {
                                goto error;
@@ -1421,9 +1417,14 @@ serialize:
                }
 
                ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm,
-                               fd_count ? &fd_to_send : NULL, fd_count,
-                               view.buffer.size ? view.buffer.data : NULL,
-                               view.buffer.size, NULL, NULL, 0);
+                                                       fd_count ? &fd_to_send : nullptr,
+                                                       fd_count,
+                                                       view.buffer.size ? view.buffer.data :
+                                                                          nullptr,
+                                                       view.buffer.size,
+                                                       nullptr,
+                                                       nullptr,
+                                                       nullptr);
        }
 
 error:
@@ -1454,8 +1455,7 @@ error:
  * If no channel name is specified, the default 'channel0' is used.
  * Returns size of returned session payload data or a negative error code.
  */
-int lttng_disable_event(struct lttng_handle *handle, const char *name,
-               const char *channel_name)
+int lttng_disable_event(struct lttng_handle *handle, const char *name, const char *channel_name)
 {
        int ret;
        struct lttng_event ev;
@@ -1469,14 +1469,14 @@ int lttng_disable_event(struct lttng_handle *handle, const char *name,
                goto end;
        }
 
-       ret = lttng_disable_event_ext(handle, &ev, channel_name, NULL);
+       ret = lttng_disable_event_ext(handle, &ev, channel_name, nullptr);
 end:
        return ret;
 }
 
 struct lttng_channel *lttng_channel_create(struct lttng_domain *domain)
 {
-       struct lttng_channel *channel = NULL;
+       struct lttng_channel *channel = nullptr;
 
        if (!domain) {
                goto end;
@@ -1528,20 +1528,19 @@ void lttng_channel_destroy(struct lttng_channel *channel)
  * Enable channel per domain
  * Returns size of returned session payload data or a negative error code.
  */
-int lttng_enable_channel(struct lttng_handle *handle,
-               struct lttng_channel *in_chan)
+int lttng_enable_channel(struct lttng_handle *handle, struct lttng_channel *in_chan)
 {
        enum lttng_error_code ret_code;
        int ret;
        struct lttng_dynamic_buffer buffer;
        struct lttcomm_session_msg lsm;
        uint64_t total_buffer_size_needed_per_cpu = 0;
-       struct lttng_channel *channel = NULL;
+       struct lttng_channel *channel = nullptr;
 
        lttng_dynamic_buffer_init(&buffer);
 
        /* NULL arguments are forbidden. No default values. */
-       if (handle == NULL || in_chan == NULL) {
+       if (handle == nullptr || in_chan == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -1550,17 +1549,14 @@ int lttng_enable_channel(struct lttng_handle *handle,
         * Verify that the amount of memory required to create the requested
         * buffer is available on the system at the moment.
         */
-       if (in_chan->attr.num_subbuf >
-                       UINT64_MAX / in_chan->attr.subbuf_size) {
+       if (in_chan->attr.num_subbuf > UINT64_MAX / in_chan->attr.subbuf_size) {
                /* Overflow */
                ret = -LTTNG_ERR_OVERFLOW;
                goto end;
        }
 
-       total_buffer_size_needed_per_cpu =
-                       in_chan->attr.num_subbuf * in_chan->attr.subbuf_size;
-       ret_code = check_enough_available_memory(
-                       total_buffer_size_needed_per_cpu);
+       total_buffer_size_needed_per_cpu = in_chan->attr.num_subbuf * in_chan->attr.subbuf_size;
+       ret_code = check_enough_available_memory(total_buffer_size_needed_per_cpu);
        if (ret_code != LTTNG_OK) {
                ret = -ret_code;
                goto end;
@@ -1575,27 +1571,24 @@ int lttng_enable_channel(struct lttng_handle *handle,
 
        /* Populate the channel extended attribute if necessary. */
        if (!channel->attr.extended.ptr) {
-               struct lttng_channel_extended *extended =
-                               zmalloc<lttng_channel_extended>();
+               struct lttng_channel_extended *extended = zmalloc<lttng_channel_extended>();
 
                if (!extended) {
                        ret = -LTTNG_ERR_NOMEM;
                        goto end;
                }
 
-               lttng_channel_set_default_extended_attr(
-                               &handle->domain, extended);
+               lttng_channel_set_default_extended_attr(&handle->domain, extended);
                channel->attr.extended.ptr = extended;
        }
 
        /* Prepare the payload */
        memset(&lsm, 0, sizeof(lsm));
 
-       lsm.cmd_type = LTTNG_ENABLE_CHANNEL;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_ENABLE_CHANNEL;
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                                   sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -1609,8 +1602,7 @@ int lttng_enable_channel(struct lttng_handle *handle,
 
        lsm.u.channel.length = buffer.size;
 
-       ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(
-                       &lsm, buffer.data, buffer.size, NULL);
+       ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, buffer.data, buffer.size, nullptr);
 end:
        lttng_channel_destroy(channel);
        lttng_dynamic_buffer_reset(&buffer);
@@ -1627,16 +1619,15 @@ int lttng_disable_channel(struct lttng_handle *handle, const char *name)
        struct lttcomm_session_msg lsm;
 
        /* Safety check. Both are mandatory. */
-       if (handle == NULL || name == NULL) {
+       if (handle == nullptr || name == nullptr) {
                return -LTTNG_ERR_INVALID;
        }
 
        memset(&lsm, 0, sizeof(lsm));
 
-       lsm.cmd_type = LTTNG_DISABLE_CHANNEL;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_DISABLE_CHANNEL;
 
-       ret = lttng_strncpy(lsm.u.disable.channel_name, name,
-                       sizeof(lsm.u.disable.channel_name));
+       ret = lttng_strncpy(lsm.u.disable.channel_name, name, sizeof(lsm.u.disable.channel_name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -1644,14 +1635,13 @@ int lttng_disable_channel(struct lttng_handle *handle, const char *name)
 
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -1662,61 +1652,63 @@ end:
  * Returns the number of lttng_event entries in events;
  * on error, returns a negative value.
  */
-int lttng_list_tracepoints(struct lttng_handle *handle,
-               struct lttng_event **events)
-{
-        enum lttng_error_code ret_code;
-        int ret, total_payload_received;
-        char *reception_buffer = NULL;
-        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_LIST_TRACEPOINTS,
+int lttng_list_tracepoints(struct lttng_handle *handle, struct lttng_event **events)
+{
+       enum lttng_error_code ret_code;
+       int ret, total_payload_received;
+       char *reception_buffer = nullptr;
+       struct lttcomm_session_msg lsm = {
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINTS,
                .session = {},
                .domain = {},
                .u = {},
                .fd_count = 0,
        };
-        struct lttcomm_list_command_header *cmd_header = NULL;
-        size_t cmd_header_len;
-        unsigned int nb_events = 0;
+       struct lttcomm_list_command_header *cmd_header = nullptr;
+       size_t cmd_header_len;
+       unsigned int nb_events = 0;
 
-        if (handle == NULL) {
-                ret = -LTTNG_ERR_INVALID;
-                goto end;
-        }
+       if (handle == nullptr) {
+               ret = -LTTNG_ERR_INVALID;
+               goto end;
+       }
 
-        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
+       COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
-        ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm, NULL, 0, NULL, 0,
-                        (void **) &reception_buffer, (void **) &cmd_header,
-                        &cmd_header_len);
-        if (ret < 0) {
-                goto end;
-        }
+       ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm,
+                                               nullptr,
+                                               0,
+                                               nullptr,
+                                               0,
+                                               (void **) &reception_buffer,
+                                               (void **) &cmd_header,
+                                               &cmd_header_len);
+       if (ret < 0) {
+               goto end;
+       }
 
-        total_payload_received = ret;
+       total_payload_received = ret;
 
-        if (!cmd_header) {
-                ret = -LTTNG_ERR_UNK;
-                goto end;
-        }
+       if (!cmd_header) {
+               ret = -LTTNG_ERR_UNK;
+               goto end;
+       }
 
-        if (cmd_header->count > INT_MAX) {
-                ret = -LTTNG_ERR_OVERFLOW;
-                goto end;
-        }
+       if (cmd_header->count > INT_MAX) {
+               ret = -LTTNG_ERR_OVERFLOW;
+               goto end;
+       }
 
-        nb_events = (unsigned int) cmd_header->count;
+       nb_events = (unsigned int) cmd_header->count;
 
        {
                struct lttng_buffer_view events_view =
-                               lttng_buffer_view_init(reception_buffer, 0,
-                                               total_payload_received);
+                       lttng_buffer_view_init(reception_buffer, 0, total_payload_received);
                struct lttng_payload_view events_payload_view =
-                               lttng_payload_view_from_buffer_view(
-                                               &events_view, 0, -1);
+                       lttng_payload_view_from_buffer_view(&events_view, 0, -1);
 
                ret_code = lttng_events_create_and_flatten_from_payload(
-                               &events_payload_view, nb_events, events);
+                       &events_payload_view, nb_events, events);
                if (ret_code != LTTNG_OK) {
                        ret = -ret_code;
                        goto end;
@@ -1726,9 +1718,9 @@ int lttng_list_tracepoints(struct lttng_handle *handle,
        ret = (int) nb_events;
 
 end:
-        free(cmd_header);
-        free(reception_buffer);
-        return ret;
+       free(cmd_header);
+       free(reception_buffer);
+       return ret;
 }
 
 /*
@@ -1737,32 +1729,29 @@ end:
  * Returns the number of lttng_event_field entries in events;
  * on error, returns a negative value.
  */
-int lttng_list_tracepoint_fields(struct lttng_handle *handle,
-               struct lttng_event_field **fields)
+int lttng_list_tracepoint_fields(struct lttng_handle *handle, struct lttng_event_field **fields)
 {
        enum lttng_error_code ret_code;
        int ret;
        struct lttcomm_session_msg lsm;
-       const struct lttcomm_list_command_header *cmd_header = NULL;
+       const struct lttcomm_list_command_header *cmd_header = nullptr;
        unsigned int nb_event_fields = 0;
        struct lttng_payload reply;
 
        lttng_payload_init(&reply);
 
-       if (handle == NULL) {
+       if (handle == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_LIST_TRACEPOINT_FIELDS;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_TRACEPOINT_FIELDS;
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
        {
                lttng_payload_view message_view =
-                               lttng_payload_view_init_from_buffer(
-                                       (const char *) &lsm, 0,
-                                       sizeof(lsm));
+                       lttng_payload_view_init_from_buffer((const char *) &lsm, 0, sizeof(lsm));
 
                ret = lttng_ctl_ask_sessiond_payload(&message_view, &reply);
                if (ret < 0) {
@@ -1771,17 +1760,15 @@ int lttng_list_tracepoint_fields(struct lttng_handle *handle,
        }
 
        {
-               const lttng_buffer_view cmd_header_view =
-                               lttng_buffer_view_from_dynamic_buffer(
-                                       &reply.buffer, 0, sizeof(*cmd_header));
+               const lttng_buffer_view cmd_header_view = lttng_buffer_view_from_dynamic_buffer(
+                       &reply.buffer, 0, sizeof(*cmd_header));
 
                if (!lttng_buffer_view_is_valid(&cmd_header_view)) {
                        ret = -LTTNG_ERR_INVALID_PROTOCOL;
                        goto end;
                }
 
-               cmd_header = (struct lttcomm_list_command_header *)
-                               cmd_header_view.data;
+               cmd_header = (struct lttcomm_list_command_header *) cmd_header_view.data;
        }
 
        if (cmd_header->count > INT_MAX) {
@@ -1793,11 +1780,10 @@ int lttng_list_tracepoint_fields(struct lttng_handle *handle,
 
        {
                lttng_payload_view reply_view =
-                               lttng_payload_view_from_payload(&reply,
-                               sizeof(*cmd_header), -1);
+                       lttng_payload_view_from_payload(&reply, sizeof(*cmd_header), -1);
 
                ret_code = lttng_event_fields_create_and_flatten_from_payload(
-                               &reply_view, nb_event_fields, fields);
+                       &reply_view, nb_event_fields, fields);
                if (ret_code != LTTNG_OK) {
                        ret = -ret_code;
                        goto end;
@@ -1820,65 +1806,68 @@ end:
  */
 int lttng_list_syscalls(struct lttng_event **events)
 {
-        enum lttng_error_code ret_code;
-        int ret, total_payload_received;
-        char *reception_buffer = NULL;
-        struct lttcomm_session_msg lsm = {};
-        struct lttcomm_list_command_header *cmd_header = NULL;
-        size_t cmd_header_len;
-        uint32_t nb_events = 0;
-
-        if (!events) {
-                ret = -LTTNG_ERR_INVALID;
-                goto end;
-        }
-
-        lsm.cmd_type = LTTNG_LIST_SYSCALLS;
-        /* Force kernel domain for system calls. */
-        lsm.domain.type = LTTNG_DOMAIN_KERNEL;
-
-        ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm, NULL, 0, NULL, 0,
-                        (void **) &reception_buffer, (void **) &cmd_header,
-                        &cmd_header_len);
-        if (ret < 0) {
-                goto end;
-        }
-        total_payload_received = ret;
-
-        if (!cmd_header) {
-                ret = -LTTNG_ERR_UNK;
-                goto end;
-        }
-
-        if (cmd_header->count > INT_MAX) {
-                ret = -LTTNG_ERR_OVERFLOW;
-                goto end;
-        }
-
-        nb_events = (unsigned int) cmd_header->count;
-
-        {
-                const struct lttng_buffer_view events_view =
-                                lttng_buffer_view_init(reception_buffer, 0,
-                                                total_payload_received);
+       enum lttng_error_code ret_code;
+       int ret, total_payload_received;
+       char *reception_buffer = nullptr;
+       struct lttcomm_session_msg lsm = {};
+       struct lttcomm_list_command_header *cmd_header = nullptr;
+       size_t cmd_header_len;
+       uint32_t nb_events = 0;
+
+       if (!events) {
+               ret = -LTTNG_ERR_INVALID;
+               goto end;
+       }
+
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_SYSCALLS;
+       /* Force kernel domain for system calls. */
+       lsm.domain.type = LTTNG_DOMAIN_KERNEL;
+
+       ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm,
+                                               nullptr,
+                                               0,
+                                               nullptr,
+                                               0,
+                                               (void **) &reception_buffer,
+                                               (void **) &cmd_header,
+                                               &cmd_header_len);
+       if (ret < 0) {
+               goto end;
+       }
+       total_payload_received = ret;
+
+       if (!cmd_header) {
+               ret = -LTTNG_ERR_UNK;
+               goto end;
+       }
+
+       if (cmd_header->count > INT_MAX) {
+               ret = -LTTNG_ERR_OVERFLOW;
+               goto end;
+       }
+
+       nb_events = (unsigned int) cmd_header->count;
+
+       {
+               const struct lttng_buffer_view events_view =
+                       lttng_buffer_view_init(reception_buffer, 0, total_payload_received);
                struct lttng_payload_view events_payload_view =
-                               lttng_payload_view_from_buffer_view(
-                                               &events_view, 0, -1);
+                       lttng_payload_view_from_buffer_view(&events_view, 0, -1);
 
-                ret_code = lttng_events_create_and_flatten_from_payload(
-                                &events_payload_view, nb_events, events);
-                if (ret_code != LTTNG_OK) {
-                        ret = -ret_code;
-                        goto end;
-                }
-        }
+               ret_code = lttng_events_create_and_flatten_from_payload(
+                       &events_payload_view, nb_events, events);
+               if (ret_code != LTTNG_OK) {
+                       ret = -ret_code;
+                       goto end;
+               }
+       }
 
-        ret = (int) nb_events;
+       ret = (int) nb_events;
 
 end:
-        free(reception_buffer);
-        free(cmd_header);
-        return ret;
+       free(reception_buffer);
+       free(cmd_header);
+       return ret;
 }
 
 /*
@@ -1894,25 +1883,24 @@ const char *lttng_strerror(int code)
        return error_get_str(code);
 }
 
-enum lttng_error_code lttng_create_session_ext(
-               struct lttng_session_descriptor *session_descriptor)
+enum lttng_error_code lttng_create_session_ext(struct lttng_session_descriptor *session_descriptor)
 {
        enum lttng_error_code ret_code;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_CREATE_SESSION_EXT,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_CREATE_SESSION_EXT,
                .session = {},
                .domain = {},
                .u = {},
                .fd_count = 0,
        };
-       void *reply = NULL;
+       void *reply = nullptr;
        struct lttng_buffer_view reply_view;
        int reply_ret;
        bool sessiond_must_generate_ouput;
        struct lttng_dynamic_buffer payload;
        int ret;
        size_t descriptor_size;
-       struct lttng_session_descriptor *descriptor_reply = NULL;
+       struct lttng_session_descriptor *descriptor_reply = nullptr;
 
        lttng_dynamic_buffer_init(&payload);
        if (!session_descriptor) {
@@ -1921,8 +1909,7 @@ enum lttng_error_code lttng_create_session_ext(
        }
 
        sessiond_must_generate_ouput =
-                       !lttng_session_descriptor_is_output_destination_initialized(
-                               session_descriptor);
+               !lttng_session_descriptor_is_output_destination_initialized(session_descriptor);
        if (sessiond_must_generate_ouput) {
                const char *home_dir = utils_get_home_dir();
                size_t home_dir_len = home_dir ? strlen(home_dir) + 1 : 0;
@@ -1933,8 +1920,7 @@ enum lttng_error_code lttng_create_session_ext(
                }
 
                lsm.u.create_session.home_dir_size = (uint16_t) home_dir_len;
-               ret = lttng_dynamic_buffer_append(&payload, home_dir,
-                               home_dir_len);
+               ret = lttng_dynamic_buffer_append(&payload, home_dir, home_dir_len);
                if (ret) {
                        ret_code = LTTNG_ERR_NOMEM;
                        goto end;
@@ -1942,8 +1928,7 @@ enum lttng_error_code lttng_create_session_ext(
        }
 
        descriptor_size = payload.size;
-       ret = lttng_session_descriptor_serialize(session_descriptor,
-                       &payload);
+       ret = lttng_session_descriptor_serialize(session_descriptor, &payload);
        if (ret) {
                ret_code = LTTNG_ERR_INVALID;
                goto end;
@@ -1952,8 +1937,8 @@ enum lttng_error_code lttng_create_session_ext(
        lsm.u.create_session.session_descriptor_size = descriptor_size;
 
        /* Command returns a session descriptor on success. */
-       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, payload.data,
-                       payload.size, &reply);
+       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(
+               &lsm, payload.data, payload.size, &reply);
        if (reply_ret < 0) {
                ret_code = (lttng_error_code) -reply_ret;
                goto end;
@@ -1964,8 +1949,7 @@ enum lttng_error_code lttng_create_session_ext(
        }
 
        reply_view = lttng_buffer_view_init((const char *) reply, 0, reply_ret);
-       ret = lttng_session_descriptor_create_from_buffer(&reply_view,
-                       &descriptor_reply);
+       ret = lttng_session_descriptor_create_from_buffer(&reply_view, &descriptor_reply);
        if (ret < 0) {
                ret_code = LTTNG_ERR_FATAL;
                goto end;
@@ -1988,8 +1972,8 @@ int lttng_create_session(const char *name, const char *url)
 {
        int ret;
        ssize_t size;
-       struct lttng_uri *uris = NULL;
-       struct lttng_session_descriptor *descriptor = NULL;
+       struct lttng_uri *uris = nullptr;
+       struct lttng_session_descriptor *descriptor = nullptr;
        enum lttng_error_code ret_code;
 
        if (!name) {
@@ -1997,7 +1981,7 @@ int lttng_create_session(const char *name, const char *url)
                goto end;
        }
 
-       size = uri_parse_str_urls(url, NULL, &uris);
+       size = uri_parse_str_urls(url, nullptr, &uris);
        if (size < 0) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -2011,12 +1995,10 @@ int lttng_create_session(const char *name, const char *url)
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
-               descriptor = lttng_session_descriptor_local_create(name,
-                               uris[0].dst.path);
+               descriptor = lttng_session_descriptor_local_create(name, uris[0].dst.path);
                break;
        case 2:
-               descriptor = lttng_session_descriptor_network_create(name, url,
-                               NULL);
+               descriptor = lttng_session_descriptor_network_create(name, url, nullptr);
                break;
        default:
                ret = -LTTNG_ERR_INVALID;
@@ -2044,15 +2026,15 @@ int lttng_create_session_snapshot(const char *name, const char *snapshot_url)
        int ret;
        enum lttng_error_code ret_code;
        ssize_t size;
-       struct lttng_uri *uris = NULL;
-       struct lttng_session_descriptor *descriptor = NULL;
+       struct lttng_uri *uris = nullptr;
+       struct lttng_session_descriptor *descriptor = nullptr;
 
        if (!name) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       size = uri_parse_str_urls(snapshot_url, NULL, &uris);
+       size = uri_parse_str_urls(snapshot_url, nullptr, &uris);
        if (size < 0) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -2060,10 +2042,8 @@ int lttng_create_session_snapshot(const char *name, const char *snapshot_url)
        /*
         * If the user does not specify a custom subdir, use the session name.
         */
-       if (size > 0 && uris[0].dtype != LTTNG_DST_PATH &&
-                       strlen(uris[0].subdir) == 0) {
-               ret = snprintf(uris[0].subdir, sizeof(uris[0].subdir), "%s",
-                               name);
+       if (size > 0 && uris[0].dtype != LTTNG_DST_PATH && strlen(uris[0].subdir) == 0) {
+               ret = snprintf(uris[0].subdir, sizeof(uris[0].subdir), "%s", name);
                if (ret < 0) {
                        PERROR("Failed to set session name as network destination sub-directory");
                        ret = -LTTNG_ERR_FATAL;
@@ -2084,15 +2064,11 @@ int lttng_create_session_snapshot(const char *name, const char *snapshot_url)
                        ret = -LTTNG_ERR_INVALID;
                        goto end;
                }
-               descriptor = lttng_session_descriptor_snapshot_local_create(
-                               name,
-                               uris[0].dst.path);
+               descriptor = lttng_session_descriptor_snapshot_local_create(name, uris[0].dst.path);
                break;
        case 2:
                descriptor = lttng_session_descriptor_snapshot_network_create(
-                               name,
-                               snapshot_url,
-                               NULL);
+                       name, snapshot_url, nullptr);
                break;
        default:
                ret = -LTTNG_ERR_INVALID;
@@ -2115,12 +2091,11 @@ end:
  *
  * Return 0 on success else a negative LTTng error code.
  */
-int lttng_create_session_live(const char *name, const char *url,
-               unsigned int timer_interval)
+int lttng_create_session_live(const char *name, const char *url, unsigned int timer_interval)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct lttng_session_descriptor *descriptor = NULL;
+       struct lttng_session_descriptor *descriptor = nullptr;
 
        if (!name) {
                ret = -LTTNG_ERR_INVALID;
@@ -2129,10 +2104,9 @@ int lttng_create_session_live(const char *name, const char *url,
 
        if (url) {
                descriptor = lttng_session_descriptor_live_network_create(
-                               name, url, NULL, timer_interval);
+                       name, url, nullptr, timer_interval);
        } else {
-               descriptor = lttng_session_descriptor_live_create(
-                               name, timer_interval);
+               descriptor = lttng_session_descriptor_live_create(name, timer_interval);
        }
        if (!descriptor) {
                ret = -LTTNG_ERR_INVALID;
@@ -2155,7 +2129,7 @@ int lttng_destroy_session(const char *session_name)
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_destruction_handle_status status;
-       struct lttng_destruction_handle *handle = NULL;
+       struct lttng_destruction_handle *handle = nullptr;
 
        /*
         * Stop the tracing and wait for the data to be
@@ -2198,7 +2172,7 @@ int lttng_destroy_session_no_wait(const char *session_name)
 {
        enum lttng_error_code ret_code;
 
-       ret_code = lttng_destroy_session_ext(session_name, NULL);
+       ret_code = lttng_destroy_session_ext(session_name, nullptr);
        return ret_code == LTTNG_OK ? 0 : -ret_code;
 }
 
@@ -2212,21 +2186,21 @@ int lttng_list_sessions(struct lttng_session **out_sessions)
 {
        int ret;
        struct lttcomm_session_msg lsm;
-       const size_t session_size = sizeof(struct lttng_session) +
-                       sizeof(struct lttng_session_extended);
+       const size_t session_size =
+               sizeof(struct lttng_session) + sizeof(struct lttng_session_extended);
        size_t session_count, i;
        struct lttng_session_extended *sessions_extended_begin;
-       struct lttng_session *sessions = NULL;
+       struct lttng_session *sessions = nullptr;
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_LIST_SESSIONS;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_SESSIONS;
        /*
         * Initialize out_sessions to NULL so it is initialized when
         * lttng_list_sessions returns 0, thus allowing *out_sessions to
         * be subsequently freed.
         */
-       *out_sessions = NULL;
-       ret = lttng_ctl_ask_sessiond(&lsm, (void**) &sessions);
+       *out_sessions = nullptr;
+       ret = lttng_ctl_ask_sessiond(&lsm, (void **) &sessions);
        if (ret <= 0) {
                goto end;
        }
@@ -2241,14 +2215,12 @@ int lttng_list_sessions(struct lttng_session **out_sessions)
                goto end;
        }
        session_count = (size_t) ret / session_size;
-       sessions_extended_begin = (struct lttng_session_extended *)
-                       (&sessions[session_count]);
+       sessions_extended_begin = (struct lttng_session_extended *) (&sessions[session_count]);
 
        /* Set extended session info pointers. */
        for (i = 0; i < session_count; i++) {
                struct lttng_session *session = &sessions[i];
-               struct lttng_session_extended *extended =
-                               &(sessions_extended_begin[i]);
+               struct lttng_session_extended *extended = &(sessions_extended_begin[i]);
 
                session->extended.ptr = extended;
        }
@@ -2259,8 +2231,8 @@ end:
        return ret;
 }
 
-enum lttng_error_code lttng_session_get_creation_time(
-               const struct lttng_session *session, uint64_t *creation_time)
+enum lttng_error_code lttng_session_get_creation_time(const struct lttng_session *session,
+                                                     uint64_t *creation_time)
 {
        enum lttng_error_code ret = LTTNG_OK;
        struct lttng_session_extended *extended;
@@ -2281,34 +2253,32 @@ end:
        return ret;
 }
 
-int lttng_set_session_shm_path(const char *session_name,
-               const char *shm_path)
+int lttng_set_session_shm_path(const char *session_name, const char *shm_path)
 {
        int ret;
        struct lttcomm_session_msg lsm;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                return -LTTNG_ERR_INVALID;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SET_SESSION_SHM_PATH;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SET_SESSION_SHM_PATH;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_strncpy(lsm.u.set_shm_path.shm_path, shm_path ?: "",
-                       sizeof(lsm.u.set_shm_path.shm_path));
+       ret = lttng_strncpy(
+               lsm.u.set_shm_path.shm_path, shm_path ?: "", sizeof(lsm.u.set_shm_path.shm_path));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -2319,28 +2289,26 @@ end:
  * Returns the number of lttng_domain entries in domains;
  * on error, returns a negative value.
  */
-int lttng_list_domains(const char *session_name,
-               struct lttng_domain **domains)
+int lttng_list_domains(const char *session_name, struct lttng_domain **domains)
 {
        int ret;
        struct lttcomm_session_msg lsm;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_LIST_DOMAINS;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_DOMAINS;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, (void**) domains);
+       ret = lttng_ctl_ask_sessiond(&lsm, (void **) domains);
        if (ret < 0) {
                goto error;
        }
@@ -2356,27 +2324,25 @@ error:
  * Returns the number of lttng_channel entries in channels;
  * on error, returns a negative value.
  */
-int lttng_list_channels(struct lttng_handle *handle,
-               struct lttng_channel **channels)
+int lttng_list_channels(struct lttng_handle *handle, struct lttng_channel **channels)
 {
        int ret, total_payload_received;
        struct lttcomm_session_msg lsm;
-       char *reception_buffer = NULL;
+       char *reception_buffer = nullptr;
        size_t cmd_header_len = 0;
-       struct lttcomm_list_command_header *cmd_header = NULL;
+       struct lttcomm_list_command_header *cmd_header = nullptr;
        struct lttng_dynamic_buffer tmp_buffer;
 
        lttng_dynamic_buffer_init(&tmp_buffer);
 
-       if (handle == NULL) {
+       if (handle == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_LIST_CHANNELS;
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_CHANNELS;
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -2384,9 +2350,14 @@ int lttng_list_channels(struct lttng_handle *handle,
 
        COPY_DOMAIN_PACKED(lsm.domain, handle->domain);
 
-       ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm, NULL, 0, NULL, 0,
-                       (void **) &reception_buffer, (void **) &cmd_header,
-                       &cmd_header_len);
+       ret = lttng_ctl_ask_sessiond_fds_varlen(&lsm,
+                                               nullptr,
+                                               0,
+                                               nullptr,
+                                               0,
+                                               (void **) &reception_buffer,
+                                               (void **) &cmd_header,
+                                               &cmd_header_len);
        if (ret < 0) {
                goto end;
        }
@@ -2411,11 +2382,10 @@ int lttng_list_channels(struct lttng_handle *handle,
        {
                enum lttng_error_code ret_code;
                const struct lttng_buffer_view events_view =
-                               lttng_buffer_view_init(reception_buffer, 0,
-                                               total_payload_received);
+                       lttng_buffer_view_init(reception_buffer, 0, total_payload_received);
 
                ret_code = lttng_channels_create_and_flatten_from_buffer(
-                               &events_view, cmd_header->count, channels);
+                       &events_view, cmd_header->count, channels);
                if (ret_code != LTTNG_OK) {
                        ret = -ret_code;
                        goto end;
@@ -2436,35 +2406,33 @@ end:
  * on error, returns a negative value.
  */
 int lttng_list_events(struct lttng_handle *handle,
-               const char *channel_name, struct lttng_event **events)
+                     const char *channel_name,
+                     struct lttng_event **events)
 {
        int ret;
        struct lttcomm_session_msg lsm = {};
        struct lttng_payload reply;
        struct lttng_payload_view lsm_view =
-                       lttng_payload_view_init_from_buffer(
-                               (const char *) &lsm, 0, sizeof(lsm));
+               lttng_payload_view_init_from_buffer((const char *) &lsm, 0, sizeof(lsm));
        unsigned int nb_events = 0;
 
        lttng_payload_init(&reply);
 
        /* Safety check. An handle and channel name are mandatory. */
-       if (handle == NULL || channel_name == NULL) {
+       if (handle == nullptr || channel_name == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
        /* Initialize command parameters. */
-       lsm.cmd_type = LTTNG_LIST_EVENTS;
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_EVENTS;
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_strncpy(lsm.u.list.channel_name, channel_name,
-                       sizeof(lsm.u.list.channel_name));
+       ret = lttng_strncpy(lsm.u.list.channel_name, channel_name, sizeof(lsm.u.list.channel_name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -2479,11 +2447,9 @@ int lttng_list_events(struct lttng_handle *handle,
        }
 
        {
-               const struct lttcomm_list_command_header *cmd_reply_header =
-                               NULL;
+               const struct lttcomm_list_command_header *cmd_reply_header = nullptr;
                const lttng_payload_view cmd_reply_header_view =
-                               lttng_payload_view_from_payload(&reply, 0,
-                                               sizeof(*cmd_reply_header));
+                       lttng_payload_view_from_payload(&reply, 0, sizeof(*cmd_reply_header));
 
                if (!lttng_payload_view_is_valid(&cmd_reply_header_view)) {
                        ret = -LTTNG_ERR_INVALID_PROTOCOL;
@@ -2491,8 +2457,7 @@ int lttng_list_events(struct lttng_handle *handle,
                }
 
                cmd_reply_header = (const struct lttcomm_list_command_header *)
-                                                  cmd_reply_header_view.buffer
-                                                                  .data;
+                                          cmd_reply_header_view.buffer.data;
                if (cmd_reply_header->count > INT_MAX) {
                        ret = -LTTNG_ERR_OVERFLOW;
                        goto end;
@@ -2504,11 +2469,10 @@ int lttng_list_events(struct lttng_handle *handle,
        {
                enum lttng_error_code ret_code;
                lttng_payload_view cmd_reply_payload = lttng_payload_view_from_payload(
-                               &reply,
-                               sizeof(struct lttcomm_list_command_header), -1);
+                       &reply, sizeof(struct lttcomm_list_command_header), -1);
 
                ret_code = lttng_events_create_and_flatten_from_payload(
-                               &cmd_reply_payload, nb_events, events);
+                       &cmd_reply_payload, nb_events, events);
                if (ret_code != LTTNG_OK) {
                        ret = -((int) ret_code);
                        goto end;
@@ -2531,7 +2495,7 @@ int lttng_set_tracing_group(const char *name)
        int ret = 0;
        char *new_group;
 
-       if (name == NULL) {
+       if (name == nullptr) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -2544,14 +2508,14 @@ int lttng_set_tracing_group(const char *name)
 
        free(tracing_group);
        tracing_group = new_group;
-       new_group = NULL;
+       new_group = nullptr;
 
 end:
        return ret;
 }
 
 int lttng_calibrate(struct lttng_handle *handle __attribute__((unused)),
-               struct lttng_calibrate *calibrate __attribute__((unused)))
+                   struct lttng_calibrate *calibrate __attribute__((unused)))
 {
        /*
         * This command was removed in LTTng 2.9.
@@ -2563,13 +2527,12 @@ int lttng_calibrate(struct lttng_handle *handle __attribute__((unused)),
  * Set default channel attributes.
  * If either or both of the arguments are null, attr content is zeroe'd.
  */
-void lttng_channel_set_default_attr(struct lttng_domain *domain,
-               struct lttng_channel_attr *attr)
+void lttng_channel_set_default_attr(struct lttng_domain *domain, struct lttng_channel_attr *attr)
 {
        struct lttng_channel_extended *extended;
 
        /* Safety check */
-       if (attr == NULL || domain == NULL) {
+       if (attr == nullptr || domain == nullptr) {
                return;
        }
 
@@ -2584,8 +2547,7 @@ void lttng_channel_set_default_attr(struct lttng_domain *domain,
 
        switch (domain->type) {
        case LTTNG_DOMAIN_KERNEL:
-               attr->switch_timer_interval =
-                               DEFAULT_KERNEL_CHANNEL_SWITCH_TIMER;
+               attr->switch_timer_interval = DEFAULT_KERNEL_CHANNEL_SWITCH_TIMER;
                attr->read_timer_interval = DEFAULT_KERNEL_CHANNEL_READ_TIMER;
                attr->subbuf_size = default_get_kernel_channel_subbuf_size();
                attr->num_subbuf = DEFAULT_KERNEL_CHANNEL_SUBBUF_NUM;
@@ -2597,20 +2559,16 @@ void lttng_channel_set_default_attr(struct lttng_domain *domain,
                        attr->subbuf_size = default_get_ust_uid_channel_subbuf_size();
                        attr->num_subbuf = DEFAULT_UST_UID_CHANNEL_SUBBUF_NUM;
                        attr->output = DEFAULT_UST_UID_CHANNEL_OUTPUT;
-                       attr->switch_timer_interval =
-                                       DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER;
-                       attr->read_timer_interval =
-                                       DEFAULT_UST_UID_CHANNEL_READ_TIMER;
+                       attr->switch_timer_interval = DEFAULT_UST_UID_CHANNEL_SWITCH_TIMER;
+                       attr->read_timer_interval = DEFAULT_UST_UID_CHANNEL_READ_TIMER;
                        break;
                case LTTNG_BUFFER_PER_PID:
                default:
                        attr->subbuf_size = default_get_ust_pid_channel_subbuf_size();
                        attr->num_subbuf = DEFAULT_UST_PID_CHANNEL_SUBBUF_NUM;
                        attr->output = DEFAULT_UST_PID_CHANNEL_OUTPUT;
-                       attr->switch_timer_interval =
-                                       DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER;
-                       attr->read_timer_interval =
-                                       DEFAULT_UST_PID_CHANNEL_READ_TIMER;
+                       attr->switch_timer_interval = DEFAULT_UST_PID_CHANNEL_SWITCH_TIMER;
+                       attr->read_timer_interval = DEFAULT_UST_PID_CHANNEL_READ_TIMER;
                        break;
                }
        default:
@@ -2627,7 +2585,7 @@ void lttng_channel_set_default_attr(struct lttng_domain *domain,
 }
 
 int lttng_channel_get_discarded_event_count(struct lttng_channel *channel,
-               uint64_t *discarded_events)
+                                           uint64_t *discarded_events)
 {
        int ret = 0;
        struct lttng_channel_extended *chan_ext;
@@ -2652,8 +2610,7 @@ end:
        return ret;
 }
 
-int lttng_channel_get_lost_packet_count(struct lttng_channel *channel,
-               uint64_t *lost_packets)
+int lttng_channel_get_lost_packet_count(struct lttng_channel *channel, uint64_t *lost_packets)
 {
        int ret = 0;
        struct lttng_channel_extended *chan_ext;
@@ -2679,7 +2636,7 @@ end:
 }
 
 int lttng_channel_get_monitor_timer_interval(struct lttng_channel *chan,
-               uint64_t *monitor_timer_interval)
+                                            uint64_t *monitor_timer_interval)
 {
        int ret = 0;
 
@@ -2693,14 +2650,14 @@ int lttng_channel_get_monitor_timer_interval(struct lttng_channel *chan,
                goto end;
        }
 
-       *monitor_timer_interval = ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->monitor_timer_interval;
+       *monitor_timer_interval =
+               ((struct lttng_channel_extended *) chan->attr.extended.ptr)->monitor_timer_interval;
 end:
        return ret;
 }
 
 int lttng_channel_set_monitor_timer_interval(struct lttng_channel *chan,
-               uint64_t monitor_timer_interval)
+                                            uint64_t monitor_timer_interval)
 {
        int ret = 0;
 
@@ -2709,15 +2666,13 @@ int lttng_channel_set_monitor_timer_interval(struct lttng_channel *chan,
                goto end;
        }
 
-       ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->monitor_timer_interval =
-                       monitor_timer_interval;
+       ((struct lttng_channel_extended *) chan->attr.extended.ptr)->monitor_timer_interval =
+               monitor_timer_interval;
 end:
        return ret;
 }
 
-int lttng_channel_get_blocking_timeout(struct lttng_channel *chan,
-               int64_t *blocking_timeout)
+int lttng_channel_get_blocking_timeout(struct lttng_channel *chan, int64_t *blocking_timeout)
 {
        int ret = 0;
 
@@ -2731,14 +2686,13 @@ int lttng_channel_get_blocking_timeout(struct lttng_channel *chan,
                goto end;
        }
 
-       *blocking_timeout = ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->blocking_timeout;
+       *blocking_timeout =
+               ((struct lttng_channel_extended *) chan->attr.extended.ptr)->blocking_timeout;
 end:
        return ret;
 }
 
-int lttng_channel_set_blocking_timeout(struct lttng_channel *chan,
-               int64_t blocking_timeout)
+int lttng_channel_set_blocking_timeout(struct lttng_channel *chan, int64_t blocking_timeout)
 {
        int ret = 0;
        int64_t msec_timeout;
@@ -2764,9 +2718,8 @@ int lttng_channel_set_blocking_timeout(struct lttng_channel *chan,
                goto end;
        }
 
-       ((struct lttng_channel_extended *)
-                       chan->attr.extended.ptr)->blocking_timeout =
-                       blocking_timeout;
+       ((struct lttng_channel_extended *) chan->attr.extended.ptr)->blocking_timeout =
+               blocking_timeout;
 end:
        return ret;
 }
@@ -2811,24 +2764,24 @@ int lttng_session_daemon_alive(void)
  * Return 0 on success, else a negative value.
  */
 int lttng_set_consumer_url(struct lttng_handle *handle,
-               const char *control_url, const char *data_url)
+                          const char *control_url,
+                          const char *data_url)
 {
        int ret;
        ssize_t size;
        struct lttcomm_session_msg lsm;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
 
-       if (handle == NULL || (control_url == NULL && data_url == NULL)) {
+       if (handle == nullptr || (control_url == nullptr && data_url == nullptr)) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        memset(&lsm, 0, sizeof(lsm));
 
-       lsm.cmd_type = LTTNG_SET_CONSUMER_URI;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SET_CONSUMER_URI;
 
-       ret = lttng_strncpy(lsm.session.name, handle->session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -2844,8 +2797,8 @@ int lttng_set_consumer_url(struct lttng_handle *handle,
 
        lsm.u.uri.size = size;
 
-       ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, uris,
-                       sizeof(struct lttng_uri) * size, NULL);
+       ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(
+               &lsm, uris, sizeof(struct lttng_uri) * size, nullptr);
 
        free(uris);
 error:
@@ -2855,8 +2808,7 @@ error:
 /*
  * [OBSOLETE]
  */
-extern "C"
-LTTNG_EXPORT int lttng_enable_consumer(struct lttng_handle *handle);
+extern "C" LTTNG_EXPORT int lttng_enable_consumer(struct lttng_handle *handle);
 int lttng_enable_consumer(struct lttng_handle *handle __attribute__((unused)))
 {
        return -ENOSYS;
@@ -2865,8 +2817,7 @@ int lttng_enable_consumer(struct lttng_handle *handle __attribute__((unused)))
 /*
  * [OBSOLETE]
  */
-extern "C"
-LTTNG_EXPORT int lttng_disable_consumer(struct lttng_handle *handle);
+extern "C" LTTNG_EXPORT int lttng_disable_consumer(struct lttng_handle *handle);
 int lttng_disable_consumer(struct lttng_handle *handle __attribute__((unused)))
 {
        return -ENOSYS;
@@ -2875,12 +2826,11 @@ int lttng_disable_consumer(struct lttng_handle *handle __attribute__((unused)))
 /*
  * [OBSOLETE]
  */
-extern "C"
-LTTNG_EXPORT int _lttng_create_session_ext(const char *name, const char *url,
-               const char *datetime);
+extern "C" LTTNG_EXPORT int
+_lttng_create_session_ext(const char *name, const char *url, const char *datetime);
 int _lttng_create_session_ext(const char *name __attribute__((unused)),
-               const char *url __attribute__((unused)),
-               const char *datetime __attribute__((unused)))
+                             const char *url __attribute__((unused)),
+                             const char *datetime __attribute__((unused)))
 {
        return -ENOSYS;
 }
@@ -2894,17 +2844,16 @@ int lttng_data_pending(const char *session_name)
 {
        int ret;
        struct lttcomm_session_msg lsm;
-       uint8_t *pending = NULL;
+       uint8_t *pending = nullptr;
 
-       if (session_name == NULL) {
+       if (session_name == nullptr) {
                return -LTTNG_ERR_INVALID;
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_DATA_PENDING;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_DATA_PENDING;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -2929,6 +2878,34 @@ end:
        return ret;
 }
 
+/*
+ * Get the status of the kernel tracer
+ *
+ * Sets the value of the argument
+ */
+enum lttng_error_code lttng_get_kernel_tracer_status(enum lttng_kernel_tracer_status *out_status)
+{
+       if (out_status == nullptr) {
+               return LTTNG_ERR_INVALID;
+       }
+
+       struct lttcomm_session_msg lsm = {};
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_KERNEL_TRACER_STATUS;
+
+       uint32_t *raw_tracer_status = nullptr;
+       const auto ask_ret = lttng_ctl_ask_sessiond(&lsm, (void **) &raw_tracer_status);
+
+       const auto tracer_status =
+               lttng::make_unique_wrapper<uint32_t, lttng::memory::free>(raw_tracer_status);
+
+       if (ask_ret != 4) {
+               return LTTNG_ERR_INVALID;
+       }
+
+       *out_status = (enum lttng_kernel_tracer_status) * tracer_status;
+       return LTTNG_OK;
+}
+
 /*
  * Regenerate the metadata for a session.
  * Return 0 on success, a negative error code on error.
@@ -2944,16 +2921,15 @@ int lttng_regenerate_metadata(const char *session_name)
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_REGENERATE_METADATA;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_REGENERATE_METADATA;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
        if (ret < 0) {
                goto end;
        }
@@ -2986,16 +2962,15 @@ int lttng_regenerate_statedump(const char *session_name)
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_REGENERATE_STATEDUMP;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_REGENERATE_STATEDUMP;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
        if (ret < 0) {
                goto end;
        }
@@ -3005,13 +2980,12 @@ end:
        return ret;
 }
 
-static
-int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
-               bool generate_name)
+static int
+_lttng_register_trigger(struct lttng_trigger *trigger, const char *name, bool generate_name)
 {
        int ret;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_REGISTER_TRIGGER,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_REGISTER_TRIGGER,
                .session = {},
                .domain = {},
                .u = {},
@@ -3021,13 +2995,13 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
        struct lttcomm_session_msg *message_lsm;
        struct lttng_payload message;
        struct lttng_payload reply;
-       struct lttng_trigger *reply_trigger = NULL;
+       struct lttng_trigger *reply_trigger = nullptr;
        enum lttng_domain_type domain_type;
        const struct lttng_credentials user_creds = {
                .uid = LTTNG_OPTIONAL_INIT_VALUE(geteuid()),
                .gid = LTTNG_OPTIONAL_INIT_UNSET,
        };
-       const char *unused_trigger_name = NULL;
+       const char *unused_trigger_name = nullptr;
        enum lttng_trigger_status trigger_status;
 
        lttng_payload_init(&message);
@@ -3068,7 +3042,7 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
                 * "safety" checks.
                 */
                const struct lttng_credentials *trigger_creds =
-                               lttng_trigger_get_credentials(trigger);
+                       lttng_trigger_get_credentials(trigger);
 
                if (!lttng_credentials_is_equal_uid(trigger_creds, &user_creds)) {
                        if (lttng_credentials_get_uid(&user_creds) != 0) {
@@ -3083,8 +3057,7 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
                goto end_unset_name;
        }
 
-       domain_type = lttng_trigger_get_underlying_domain_type_restriction(
-                       trigger);
+       domain_type = lttng_trigger_get_underlying_domain_type_restriction(trigger);
 
        lsm.domain.type = domain_type;
 
@@ -3110,11 +3083,9 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
 
        {
                struct lttng_payload_view message_view =
-                               lttng_payload_view_from_payload(
-                                               &message, 0, -1);
+                       lttng_payload_view_from_payload(&message, 0, -1);
 
-               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(
-                               &message_view);
+               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(&message_view);
                ret = lttng_ctl_ask_sessiond_payload(&message_view, &reply);
                if (ret < 0) {
                        goto end_unset_name;
@@ -3123,11 +3094,9 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
 
        {
                struct lttng_payload_view reply_view =
-                               lttng_payload_view_from_payload(
-                                               &reply, 0, reply.buffer.size);
+                       lttng_payload_view_from_payload(&reply, 0, reply.buffer.size);
 
-               ret = lttng_trigger_create_from_payload(
-                               &reply_view, &reply_trigger);
+               ret = lttng_trigger_create_from_payload(&reply_view, &reply_trigger);
                if (ret < 0) {
                        ret = -LTTNG_ERR_INVALID_PROTOCOL;
                        goto end_unset_name;
@@ -3146,7 +3115,7 @@ int _lttng_register_trigger(struct lttng_trigger *trigger, const char *name,
        goto end;
 
 end_unset_name:
-       trigger_status = lttng_trigger_set_name(trigger, NULL);
+       trigger_status = lttng_trigger_set_name(trigger, nullptr);
        if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
                ret = -LTTNG_ERR_UNK;
        }
@@ -3160,34 +3129,32 @@ end:
 int lttng_register_trigger(struct lttng_trigger *trigger)
 {
        /* Register an anonymous trigger. */
-       return _lttng_register_trigger(trigger, NULL, false);
+       return _lttng_register_trigger(trigger, nullptr, false);
 }
 
-enum lttng_error_code lttng_register_trigger_with_name(
-               struct lttng_trigger *trigger, const char *name)
+enum lttng_error_code lttng_register_trigger_with_name(struct lttng_trigger *trigger,
+                                                      const char *name)
 {
        const int ret = _lttng_register_trigger(trigger, name, false);
 
-       return ret == 0 ? LTTNG_OK : (enum lttng_error_code) -ret;
+       return ret == 0 ? LTTNG_OK : (enum lttng_error_code) - ret;
 }
 
-enum lttng_error_code lttng_register_trigger_with_automatic_name(
-               struct lttng_trigger *trigger)
+enum lttng_error_code lttng_register_trigger_with_automatic_name(struct lttng_trigger *trigger)
 {
-       const int ret =  _lttng_register_trigger(trigger, nullptr, true);
+       const int ret = _lttng_register_trigger(trigger, nullptr, true);
 
-       return ret == 0 ? LTTNG_OK : (enum lttng_error_code) -ret;
+       return ret == 0 ? LTTNG_OK : (enum lttng_error_code) - ret;
 }
 
-enum lttng_error_code lttng_error_query_execute(
-               const struct lttng_error_query *query,
-               const struct lttng_endpoint *endpoint,
-               struct lttng_error_query_results **results)
+enum lttng_error_code lttng_error_query_execute(const struct lttng_error_query *query,
+                                               const struct lttng_endpoint *endpoint,
+                                               struct lttng_error_query_results **results)
 {
        int ret;
        enum lttng_error_code ret_code;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_EXECUTE_ERROR_QUERY,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_EXECUTE_ERROR_QUERY,
                .session = {},
                .domain = {},
                .u = {},
@@ -3223,19 +3190,16 @@ enum lttng_error_code lttng_error_query_execute(
        }
 
        message_lsm = (struct lttcomm_session_msg *) message.buffer.data;
-       message_lsm->u.error_query.length =
-                       (uint32_t) message.buffer.size - sizeof(lsm);
+       message_lsm->u.error_query.length = (uint32_t) message.buffer.size - sizeof(lsm);
 
        {
                struct lttng_payload_view message_view =
-                               lttng_payload_view_from_payload(
-                                               &message, 0, -1);
+                       lttng_payload_view_from_payload(&message, 0, -1);
 
-               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(
-                               &message_view);
+               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(&message_view);
                ret = lttng_ctl_ask_sessiond_payload(&message_view, &reply);
                if (ret < 0) {
-                       ret_code =(lttng_error_code) -ret;
+                       ret_code = (lttng_error_code) -ret;
                        goto end;
                }
        }
@@ -3243,11 +3207,10 @@ enum lttng_error_code lttng_error_query_execute(
        {
                ssize_t reply_create_ret;
                struct lttng_payload_view reply_view =
-                               lttng_payload_view_from_payload(
-                                               &reply, 0, reply.buffer.size);
+                       lttng_payload_view_from_payload(&reply, 0, reply.buffer.size);
 
-               reply_create_ret = lttng_error_query_results_create_from_payload(
-                               &reply_view, results);
+               reply_create_ret =
+                       lttng_error_query_results_create_from_payload(&reply_view, results);
                if (reply_create_ret < 0) {
                        ret_code = LTTNG_ERR_INVALID_PROTOCOL;
                        goto end;
@@ -3268,7 +3231,7 @@ int lttng_unregister_trigger(const struct lttng_trigger *trigger)
        struct lttcomm_session_msg *message_lsm;
        struct lttng_payload message;
        struct lttng_payload reply;
-       struct lttng_trigger *copy = NULL;
+       struct lttng_trigger *copy = nullptr;
        const struct lttng_credentials user_creds = {
                .uid = LTTNG_OPTIONAL_INIT_VALUE(geteuid()),
                .gid = LTTNG_OPTIONAL_INIT_UNSET,
@@ -3302,8 +3265,7 @@ int lttng_unregister_trigger(const struct lttng_trigger *trigger)
                 * credentials passed on the socket. These check are all
                 * "safety" checks.
                 */
-               const struct lttng_credentials *trigger_creds =
-                               lttng_trigger_get_credentials(copy);
+               const struct lttng_credentials *trigger_creds = lttng_trigger_get_credentials(copy);
                if (!lttng_credentials_is_equal_uid(trigger_creds, &user_creds)) {
                        if (lttng_credentials_get_uid(&user_creds) != 0) {
                                ret = -LTTNG_ERR_EPERM;
@@ -3318,7 +3280,7 @@ int lttng_unregister_trigger(const struct lttng_trigger *trigger)
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_UNREGISTER_TRIGGER;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_UNREGISTER_TRIGGER;
 
        ret = lttng_dynamic_buffer_append(&message.buffer, &lsm, sizeof(lsm));
        if (ret) {
@@ -3335,22 +3297,20 @@ int lttng_unregister_trigger(const struct lttng_trigger *trigger)
        /*
         * This is needed to populate the trigger object size for the command
         * header and number of fds sent.
-       */
+        */
        message_lsm = (struct lttcomm_session_msg *) message.buffer.data;
 
        message_lsm->u.trigger.length = (uint32_t) message.buffer.size - sizeof(lsm);
 
        {
                struct lttng_payload_view message_view =
-                               lttng_payload_view_from_payload(
-                                               &message, 0, -1);
+                       lttng_payload_view_from_payload(&message, 0, -1);
 
                /*
                 * Update the message header with the number of fd that will be
                 * sent.
                 */
-               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(
-                               &message_view);
+               message_lsm->fd_count = lttng_payload_view_get_fd_handle_count(&message_view);
 
                ret = lttng_ctl_ask_sessiond_payload(&message_view, &reply);
                if (ret < 0) {
@@ -3377,33 +3337,30 @@ enum lttng_error_code lttng_list_triggers(struct lttng_triggers **triggers)
        int ret;
        enum lttng_error_code ret_code = LTTNG_OK;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_LIST_TRIGGERS,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_LIST_TRIGGERS,
                .session = {},
                .domain = {},
                .u = {},
                .fd_count = 0,
        };
-       struct lttng_triggers *local_triggers = NULL;
+       struct lttng_triggers *local_triggers = nullptr;
        struct lttng_payload reply;
        struct lttng_payload_view lsm_view =
-                       lttng_payload_view_init_from_buffer(
-                               (const char *) &lsm, 0, sizeof(lsm));
+               lttng_payload_view_init_from_buffer((const char *) &lsm, 0, sizeof(lsm));
 
        lttng_payload_init(&reply);
 
        ret = lttng_ctl_ask_sessiond_payload(&lsm_view, &reply);
        if (ret < 0) {
-               ret_code = (enum lttng_error_code) -ret;
+               ret_code = (enum lttng_error_code) - ret;
                goto end;
        }
 
        {
                struct lttng_payload_view reply_view =
-                               lttng_payload_view_from_payload(
-                                               &reply, 0, reply.buffer.size);
+                       lttng_payload_view_from_payload(&reply, 0, reply.buffer.size);
 
-               ret = lttng_triggers_create_from_payload(
-                               &reply_view, &local_triggers);
+               ret = lttng_triggers_create_from_payload(&reply_view, &local_triggers);
                if (ret < 0) {
                        ret_code = LTTNG_ERR_FATAL;
                        goto end;
@@ -3411,7 +3368,7 @@ enum lttng_error_code lttng_list_triggers(struct lttng_triggers **triggers)
        }
 
        *triggers = local_triggers;
-       local_triggers = NULL;
+       local_triggers = nullptr;
 end:
        lttng_payload_reset(&reply);
        lttng_triggers_destroy(local_triggers);
@@ -3421,7 +3378,7 @@ end:
 /*
  * lib constructor.
  */
-static void __attribute__((constructor)) init(void)
+static void __attribute__((constructor)) init()
 {
        /* Set default session group */
        lttng_set_tracing_group(DEFAULT_TRACING_GROUP);
@@ -3430,7 +3387,7 @@ static void __attribute__((constructor)) init(void)
 /*
  * lib destructor.
  */
-static void __attribute__((destructor)) lttng_ctl_exit(void)
+static void __attribute__((destructor)) lttng_ctl_exit()
 {
        free(tracing_group);
 }
index 3f1848a809c051d03a4571401cca436c8216b583..60ac8669d9defc07a19169a2409496437f1b30f6 100644 (file)
@@ -6,21 +6,20 @@
  */
 
 #define _LGPL_SOURCE
-#include <string.h>
+#include "lttng-ctl-helper.hpp"
+
+#include <common/macros.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
 
-#include <lttng/lttng-error.h>
-#include <lttng/rotation.h>
 #include <lttng/location-internal.hpp>
+#include <lttng/lttng-error.h>
 #include <lttng/rotate-internal.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/macros.hpp>
+#include <lttng/rotation.h>
 
-#include "lttng-ctl-helper.hpp"
+#include <string.h>
 
-static
-enum lttng_rotation_status ask_rotation_info(
-               struct lttng_rotation_handle *rotation_handle,
-               struct lttng_rotation_get_info_return **info)
+static enum lttng_rotation_status ask_rotation_info(struct lttng_rotation_handle *rotation_handle,
+                                                   struct lttng_rotation_get_info_return **info)
 {
        /* lsm.get_rotation_state.rotation_id */
        struct lttcomm_session_msg lsm;
@@ -33,11 +32,11 @@ enum lttng_rotation_status ask_rotation_info(
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_ROTATION_GET_INFO;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_ROTATION_GET_INFO;
        lsm.u.get_rotation_info.rotation_id = rotation_handle->rotation_id;
 
-       ret = lttng_strncpy(lsm.session.name, rotation_handle->session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(
+               lsm.session.name, rotation_handle->session_name, sizeof(lsm.session.name));
        if (ret) {
                status = LTTNG_ROTATION_STATUS_INVALID;
                goto end;
@@ -50,42 +49,40 @@ enum lttng_rotation_status ask_rotation_info(
        }
 end:
        return status;
-
 }
 
-static
-struct lttng_trace_archive_location *
-create_trace_archive_location_from_get_info(
-               const struct lttng_rotation_get_info_return *info)
+static struct lttng_trace_archive_location *
+create_trace_archive_location_from_get_info(const struct lttng_rotation_get_info_return *info)
 {
        struct lttng_trace_archive_location *location;
 
        switch (info->location_type) {
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL:
                location = lttng_trace_archive_location_local_create(
-                               info->location.local.absolute_path);
+                       info->location.local.absolute_path);
                break;
        case LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_RELAY:
                location = lttng_trace_archive_location_relay_create(
-                               info->location.relay.host,
-                               (lttng_trace_archive_location_relay_protocol_type) info->location.relay.protocol,
-                               info->location.relay.ports.control,
-                               info->location.relay.ports.data,
-                               info->location.relay.relative_path);
+                       info->location.relay.host,
+                       (lttng_trace_archive_location_relay_protocol_type)
+                               info->location.relay.protocol,
+                       info->location.relay.ports.control,
+                       info->location.relay.ports.data,
+                       info->location.relay.relative_path);
                break;
        default:
-               location = NULL;
+               location = nullptr;
                break;
        }
        return location;
 }
 
-enum lttng_rotation_status lttng_rotation_handle_get_state(
-               struct lttng_rotation_handle *rotation_handle,
-               enum lttng_rotation_state *state)
+enum lttng_rotation_status
+lttng_rotation_handle_get_state(struct lttng_rotation_handle *rotation_handle,
+                               enum lttng_rotation_state *state)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
-       struct lttng_rotation_get_info_return *info = NULL;
+       struct lttng_rotation_get_info_return *info = nullptr;
 
        if (!rotation_handle || !state) {
                status = LTTNG_ROTATION_STATUS_INVALID;
@@ -98,8 +95,7 @@ enum lttng_rotation_status lttng_rotation_handle_get_state(
        }
 
        *state = (enum lttng_rotation_state) info->status;
-       if (rotation_handle->archive_location ||
-                       *state != LTTNG_ROTATION_STATE_COMPLETED) {
+       if (rotation_handle->archive_location || *state != LTTNG_ROTATION_STATE_COMPLETED) {
                /*
                 * The path is only provided by the sessiond once
                 * the session rotation is completed, but not expired.
@@ -111,8 +107,7 @@ enum lttng_rotation_status lttng_rotation_handle_get_state(
         * Cache the location since the rotation may expire before the user
         * has a chance to query it.
         */
-       rotation_handle->archive_location =
-                       create_trace_archive_location_from_get_info(info);
+       rotation_handle->archive_location = create_trace_archive_location_from_get_info(info);
        if (!rotation_handle->archive_location) {
                status = LTTNG_ROTATION_STATUS_ERROR;
                goto end;
@@ -122,12 +117,12 @@ end:
        return status;
 }
 
-enum lttng_rotation_status lttng_rotation_handle_get_archive_location(
-               struct lttng_rotation_handle *rotation_handle,
-               const struct lttng_trace_archive_location **location)
+enum lttng_rotation_status
+lttng_rotation_handle_get_archive_location(struct lttng_rotation_handle *rotation_handle,
+                                          const struct lttng_trace_archive_location **location)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
-       struct lttng_rotation_get_info_return *info = NULL;
+       struct lttng_rotation_get_info_return *info = nullptr;
 
        if (!rotation_handle || !location) {
                status = LTTNG_ROTATION_STATUS_INVALID;
@@ -145,14 +140,12 @@ enum lttng_rotation_status lttng_rotation_handle_get_archive_location(
                goto end;
        }
 
-       if ((enum lttng_rotation_state) info->status !=
-                       LTTNG_ROTATION_STATE_COMPLETED) {
+       if ((enum lttng_rotation_state) info->status != LTTNG_ROTATION_STATE_COMPLETED) {
                status = LTTNG_ROTATION_STATUS_UNAVAILABLE;
                goto end;
        }
 
-       rotation_handle->archive_location =
-                       create_trace_archive_location_from_get_info(info);
+       rotation_handle->archive_location = create_trace_archive_location_from_get_info(info);
        if (!rotation_handle->archive_location) {
                status = LTTNG_ROTATION_STATUS_ERROR;
                goto end;
@@ -162,8 +155,7 @@ end:
        return status;
 }
 
-void lttng_rotation_handle_destroy(
-               struct lttng_rotation_handle *rotation_handle)
+void lttng_rotation_handle_destroy(struct lttng_rotation_handle *rotation_handle)
 {
        if (!rotation_handle) {
                return;
@@ -172,15 +164,14 @@ void lttng_rotation_handle_destroy(
        free(rotation_handle);
 }
 
-static
-int init_rotation_handle(struct lttng_rotation_handle *rotation_handle,
-               const char *session_name,
-               struct lttng_rotate_session_return *rotate_return)
+static int init_rotation_handle(struct lttng_rotation_handle *rotation_handle,
+                               const char *session_name,
+                               struct lttng_rotate_session_return *rotate_return)
 {
        int ret;
 
-       ret = lttng_strncpy(rotation_handle->session_name, session_name,
-                       sizeof(rotation_handle->session_name));
+       ret = lttng_strncpy(
+               rotation_handle->session_name, session_name, sizeof(rotation_handle->session_name));
        if (ret) {
                goto end;
        }
@@ -196,11 +187,12 @@ end:
  * Return 0 on success else a negative LTTng error code.
  */
 int lttng_rotate_session(const char *session_name,
-               struct lttng_rotation_immediate_descriptor *descriptor __attribute__((unused)),
-               struct lttng_rotation_handle **rotation_handle)
+                        struct lttng_rotation_immediate_descriptor *descriptor
+                        __attribute__((unused)),
+                        struct lttng_rotation_handle **rotation_handle)
 {
        struct lttcomm_session_msg lsm;
-       struct lttng_rotate_session_return *rotate_return = NULL;
+       struct lttng_rotate_session_return *rotate_return = nullptr;
        int ret;
        size_t session_name_len;
 
@@ -217,16 +209,15 @@ int lttng_rotate_session(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_ROTATE_SESSION;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_ROTATE_SESSION;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        /* Source length already validated. */
        LTTNG_ASSERT(ret == 0);
 
        ret = lttng_ctl_ask_sessiond(&lsm, (void **) &rotate_return);
        if (ret <= 0) {
-               *rotation_handle = NULL;
+               *rotation_handle = nullptr;
                goto end;
        }
 
@@ -262,11 +253,8 @@ end:
  * just its type) must be passed so that the session daemon can
  * validate that is exists before clearing it.
  */
-static
-enum lttng_rotation_status lttng_rotation_update_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedule *schedule,
-               bool add)
+static enum lttng_rotation_status lttng_rotation_update_schedule(
+       const char *session_name, const struct lttng_rotation_schedule *schedule, bool add)
 {
        struct lttcomm_session_msg lsm;
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
@@ -283,9 +271,8 @@ enum lttng_rotation_status lttng_rotation_update_schedule(
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_ROTATION_SET_SCHEDULE;
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_ROTATION_SET_SCHEDULE;
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        /* Source length already validated. */
        LTTNG_ASSERT(ret == 0);
 
@@ -295,8 +282,7 @@ enum lttng_rotation_status lttng_rotation_update_schedule(
        {
                uint64_t threshold;
 
-               status = lttng_rotation_schedule_size_threshold_get_threshold(
-                               schedule, &threshold);
+               status = lttng_rotation_schedule_size_threshold_get_threshold(schedule, &threshold);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        if (status == LTTNG_ROTATION_STATUS_UNAVAILABLE) {
                                status = LTTNG_ROTATION_STATUS_INVALID;
@@ -311,8 +297,7 @@ enum lttng_rotation_status lttng_rotation_update_schedule(
        {
                uint64_t period;
 
-               status = lttng_rotation_schedule_periodic_get_period(
-                               schedule, &period);
+               status = lttng_rotation_schedule_periodic_get_period(schedule, &period);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        if (status == LTTNG_ROTATION_STATUS_UNAVAILABLE) {
                                status = LTTNG_ROTATION_STATUS_INVALID;
@@ -328,7 +313,7 @@ enum lttng_rotation_status lttng_rotation_update_schedule(
                goto end;
        }
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
        if (ret >= 0) {
                goto end;
        }
@@ -347,28 +332,24 @@ end:
        return status;
 }
 
-static
-struct lttng_rotation_schedules *lttng_rotation_schedules_create(void)
+static struct lttng_rotation_schedules *lttng_rotation_schedules_create()
 {
        return zmalloc<lttng_rotation_schedules>();
 }
 
-static
-void lttng_schedules_add(struct lttng_rotation_schedules *schedules,
-               struct lttng_rotation_schedule *schedule)
+static void lttng_schedules_add(struct lttng_rotation_schedules *schedules,
+                               struct lttng_rotation_schedule *schedule)
 {
        schedules->schedules[schedules->count++] = schedule;
 }
 
-static
-int get_schedules(const char *session_name,
-               struct lttng_rotation_schedules **_schedules)
+static int get_schedules(const char *session_name, struct lttng_rotation_schedules **_schedules)
 {
        int ret;
        struct lttcomm_session_msg lsm;
-       struct lttng_session_list_schedules_return *schedules_comm = NULL;
-       struct lttng_rotation_schedules *schedules = NULL;
-       struct lttng_rotation_schedule *periodic = NULL, *size = NULL;
+       struct lttng_session_list_schedules_return *schedules_comm = nullptr;
+       struct lttng_rotation_schedules *schedules = nullptr;
+       struct lttng_rotation_schedule *periodic = nullptr, *size = nullptr;
 
        if (!session_name) {
                ret = -LTTNG_ERR_INVALID;
@@ -376,9 +357,8 @@ int get_schedules(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SESSION_LIST_ROTATION_SCHEDULES;
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SESSION_LIST_ROTATION_SCHEDULES;
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -405,7 +385,7 @@ int get_schedules(const char *session_name,
                }
 
                status = lttng_rotation_schedule_periodic_set_period(
-                               periodic, schedules_comm->periodic.value);
+                       periodic, schedules_comm->periodic.value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        /*
                         * This would imply that the session daemon returned
@@ -416,7 +396,7 @@ int get_schedules(const char *session_name,
                }
 
                lttng_schedules_add(schedules, periodic);
-               periodic = NULL;
+               periodic = nullptr;
        }
 
        if (schedules_comm->size.set == 1) {
@@ -429,7 +409,7 @@ int get_schedules(const char *session_name,
                }
 
                status = lttng_rotation_schedule_size_threshold_set_threshold(
-                               size, schedules_comm->size.value);
+                       size, schedules_comm->size.value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        /*
                         * This would imply that the session daemon returned
@@ -440,7 +420,7 @@ int get_schedules(const char *session_name,
                }
 
                lttng_schedules_add(schedules, size);
-               size = NULL;
+               size = nullptr;
        }
 
        ret = LTTNG_OK;
@@ -452,14 +432,13 @@ end:
        return ret;
 }
 
-enum lttng_rotation_schedule_type lttng_rotation_schedule_get_type(
-               const struct lttng_rotation_schedule *schedule)
+enum lttng_rotation_schedule_type
+lttng_rotation_schedule_get_type(const struct lttng_rotation_schedule *schedule)
 {
        return schedule ? schedule->type : LTTNG_ROTATION_SCHEDULE_TYPE_UNKNOWN;
 }
 
-struct lttng_rotation_schedule *
-lttng_rotation_schedule_size_threshold_create(void)
+struct lttng_rotation_schedule *lttng_rotation_schedule_size_threshold_create(void)
 {
        struct lttng_rotation_schedule_size_threshold *schedule;
 
@@ -474,21 +453,20 @@ end:
 }
 
 enum lttng_rotation_status
-lttng_rotation_schedule_size_threshold_get_threshold(
-               const struct lttng_rotation_schedule *schedule,
-               uint64_t *size_threshold_bytes)
+lttng_rotation_schedule_size_threshold_get_threshold(const struct lttng_rotation_schedule *schedule,
+                                                    uint64_t *size_threshold_bytes)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
        struct lttng_rotation_schedule_size_threshold *size_schedule;
 
        if (!schedule || !size_threshold_bytes ||
-                       schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD) {
+           schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD) {
                status = LTTNG_ROTATION_STATUS_INVALID;
                goto end;
        }
 
        size_schedule = lttng::utils::container_of(schedule,
-                       &lttng_rotation_schedule_size_threshold::parent);
+                                                  &lttng_rotation_schedule_size_threshold::parent);
        if (size_schedule->size.set) {
                *size_threshold_bytes = size_schedule->size.bytes;
        } else {
@@ -500,30 +478,27 @@ end:
 }
 
 enum lttng_rotation_status
-lttng_rotation_schedule_size_threshold_set_threshold(
-               struct lttng_rotation_schedule *schedule,
-               uint64_t size_threshold_bytes)
+lttng_rotation_schedule_size_threshold_set_threshold(struct lttng_rotation_schedule *schedule,
+                                                    uint64_t size_threshold_bytes)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
        struct lttng_rotation_schedule_size_threshold *size_schedule;
 
-       if (!schedule || size_threshold_bytes == 0 ||
-                       size_threshold_bytes == -1ULL ||
-                       schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD) {
+       if (!schedule || size_threshold_bytes == 0 || size_threshold_bytes == -1ULL ||
+           schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD) {
                status = LTTNG_ROTATION_STATUS_INVALID;
                goto end;
        }
 
        size_schedule = lttng::utils::container_of(schedule,
-                       &lttng_rotation_schedule_size_threshold::parent);
+                                                  &lttng_rotation_schedule_size_threshold::parent);
        size_schedule->size.bytes = size_threshold_bytes;
        size_schedule->size.set = true;
 end:
        return status;
 }
 
-struct lttng_rotation_schedule *
-lttng_rotation_schedule_periodic_create(void)
+struct lttng_rotation_schedule *lttng_rotation_schedule_periodic_create(void)
 {
        struct lttng_rotation_schedule_periodic *schedule;
 
@@ -538,21 +513,19 @@ end:
 }
 
 enum lttng_rotation_status
-lttng_rotation_schedule_periodic_get_period(
-               const struct lttng_rotation_schedule *schedule,
-               uint64_t *period_us)
+lttng_rotation_schedule_periodic_get_period(const struct lttng_rotation_schedule *schedule,
+                                           uint64_t *period_us)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
        struct lttng_rotation_schedule_periodic *periodic_schedule;
 
-       if (!schedule || !period_us ||
-                       schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC) {
+       if (!schedule || !period_us || schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC) {
                status = LTTNG_ROTATION_STATUS_INVALID;
                goto end;
        }
 
-       periodic_schedule = lttng::utils::container_of(schedule,
-                       &lttng_rotation_schedule_periodic::parent);
+       periodic_schedule =
+               lttng::utils::container_of(schedule, &lttng_rotation_schedule_periodic::parent);
        if (periodic_schedule->period.set) {
                *period_us = periodic_schedule->period.us;
        } else {
@@ -564,21 +537,20 @@ end:
 }
 
 enum lttng_rotation_status
-lttng_rotation_schedule_periodic_set_period(
-               struct lttng_rotation_schedule *schedule,
-               uint64_t period_us)
+lttng_rotation_schedule_periodic_set_period(struct lttng_rotation_schedule *schedule,
+                                           uint64_t period_us)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
        struct lttng_rotation_schedule_periodic *periodic_schedule;
 
        if (!schedule || period_us == 0 || period_us == -1ULL ||
-                       schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC) {
+           schedule->type != LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC) {
                status = LTTNG_ROTATION_STATUS_INVALID;
                goto end;
        }
 
-       periodic_schedule = lttng::utils::container_of(schedule,
-                       &lttng_rotation_schedule_periodic::parent);
+       periodic_schedule =
+               lttng::utils::container_of(schedule, &lttng_rotation_schedule_periodic::parent);
        periodic_schedule->period.us = period_us;
        periodic_schedule->period.set = true;
 end:
@@ -593,8 +565,7 @@ void lttng_rotation_schedule_destroy(struct lttng_rotation_schedule *schedule)
        free(schedule);
 }
 
-void lttng_rotation_schedules_destroy(
-               struct lttng_rotation_schedules *schedules)
+void lttng_rotation_schedules_destroy(struct lttng_rotation_schedules *schedules)
 {
        unsigned int i;
 
@@ -608,10 +579,9 @@ void lttng_rotation_schedules_destroy(
        free(schedules);
 }
 
-
-enum lttng_rotation_status lttng_rotation_schedules_get_count(
-               const struct lttng_rotation_schedules *schedules,
-               unsigned int *count)
+enum lttng_rotation_status
+lttng_rotation_schedules_get_count(const struct lttng_rotation_schedules *schedules,
+                                  unsigned int *count)
 {
        enum lttng_rotation_status status = LTTNG_ROTATION_STATUS_OK;
 
@@ -625,11 +595,11 @@ end:
        return status;
 }
 
-const struct lttng_rotation_schedule *lttng_rotation_schedules_get_at_index(
-               const struct lttng_rotation_schedules *schedules,
-               unsigned int index)
+const struct lttng_rotation_schedule *
+lttng_rotation_schedules_get_at_index(const struct lttng_rotation_schedules *schedules,
+                                     unsigned int index)
 {
-       const struct lttng_rotation_schedule *schedule = NULL;
+       const struct lttng_rotation_schedule *schedule = nullptr;
 
        if (!schedules || index >= schedules->count) {
                goto end;
@@ -640,23 +610,22 @@ end:
        return schedule;
 }
 
-enum lttng_rotation_status lttng_session_add_rotation_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedule *schedule)
+enum lttng_rotation_status
+lttng_session_add_rotation_schedule(const char *session_name,
+                                   const struct lttng_rotation_schedule *schedule)
 {
        return lttng_rotation_update_schedule(session_name, schedule, true);
 }
 
-enum lttng_rotation_status lttng_session_remove_rotation_schedule(
-               const char *session_name,
-               const struct lttng_rotation_schedule *schedule)
+enum lttng_rotation_status
+lttng_session_remove_rotation_schedule(const char *session_name,
+                                      const struct lttng_rotation_schedule *schedule)
 {
        return lttng_rotation_update_schedule(session_name, schedule, false);
 }
 
-int lttng_session_list_rotation_schedules(
-               const char *session_name,
-               struct lttng_rotation_schedules **schedules)
+int lttng_session_list_rotation_schedules(const char *session_name,
+                                         struct lttng_rotation_schedules **schedules)
 {
        return get_schedules(session_name, schedules);
 }
index 32fcb1c2d772d968252e4a4706f15f468916784c..4cc2f8014ccc6c219e1a930ba126152823e079d3 100644 (file)
@@ -6,14 +6,15 @@
  */
 
 #define _LGPL_SOURCE
-#include <string.h>
+#include "lttng-ctl-helper.hpp"
+
+#include <common/sessiond-comm/sessiond-comm.hpp>
 
 #include <lttng/lttng-error.h>
-#include <lttng/save.h>
 #include <lttng/save-internal.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
+#include <lttng/save.h>
 
-#include "lttng-ctl-helper.hpp"
+#include <string.h>
 
 struct lttng_save_session_attr *lttng_save_session_attr_create(void)
 {
@@ -27,10 +28,9 @@ void lttng_save_session_attr_destroy(struct lttng_save_session_attr *output)
        }
 }
 
-const char *lttng_save_session_attr_get_session_name(
-       struct lttng_save_session_attr *attr)
+const char *lttng_save_session_attr_get_session_name(struct lttng_save_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (attr && attr->session_name[0]) {
                ret = attr->session_name;
@@ -39,10 +39,9 @@ const char *lttng_save_session_attr_get_session_name(
        return ret;
 }
 
-const char *lttng_save_session_attr_get_output_url(
-       struct lttng_save_session_attr *attr)
+const char *lttng_save_session_attr_get_output_url(struct lttng_save_session_attr *attr)
 {
-       const char *ret = NULL;
+       const char *ret = nullptr;
 
        if (attr && attr->configuration_url[0]) {
                ret = attr->configuration_url;
@@ -51,26 +50,23 @@ const char *lttng_save_session_attr_get_output_url(
        return ret;
 }
 
-int lttng_save_session_attr_get_overwrite(
-       struct lttng_save_session_attr *attr)
+int lttng_save_session_attr_get_overwrite(struct lttng_save_session_attr *attr)
 {
        return attr ? attr->overwrite : -LTTNG_ERR_INVALID;
 }
 
-int lttng_save_session_attr_get_omit_name(
-       struct lttng_save_session_attr *attr)
+int lttng_save_session_attr_get_omit_name(struct lttng_save_session_attr *attr)
 {
        return attr ? attr->omit_name : -LTTNG_ERR_INVALID;
 }
 
-int lttng_save_session_attr_get_omit_output(
-       struct lttng_save_session_attr *attr)
+int lttng_save_session_attr_get_omit_output(struct lttng_save_session_attr *attr)
 {
        return attr ? attr->omit_output : -LTTNG_ERR_INVALID;
 }
 
-int lttng_save_session_attr_set_session_name(
-       struct lttng_save_session_attr *attr, const char *session_name)
+int lttng_save_session_attr_set_session_name(struct lttng_save_session_attr *attr,
+                                            const char *session_name)
 {
        int ret = 0;
 
@@ -88,8 +84,7 @@ int lttng_save_session_attr_set_session_name(
                        goto error;
                }
 
-               ret = lttng_strncpy(attr->session_name, session_name,
-                               sizeof(attr->session_name));
+               ret = lttng_strncpy(attr->session_name, session_name, sizeof(attr->session_name));
                if (ret) {
                        ret = -LTTNG_ERR_INVALID;
                        goto error;
@@ -101,13 +96,12 @@ error:
        return ret;
 }
 
-int lttng_save_session_attr_set_output_url(
-       struct lttng_save_session_attr *attr, const char *url)
+int lttng_save_session_attr_set_output_url(struct lttng_save_session_attr *attr, const char *url)
 {
        int ret = 0;
        size_t len;
        ssize_t size;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
 
        if (!attr) {
                ret = -LTTNG_ERR_INVALID;
@@ -126,15 +120,15 @@ int lttng_save_session_attr_set_output_url(
                goto error;
        }
 
-       size = uri_parse_str_urls(url, NULL, &uris);
+       size = uri_parse_str_urls(url, nullptr, &uris);
        if (size <= 0 || uris[0].dtype != LTTNG_DST_PATH) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
        }
 
        /* Copy string plus the NULL terminated byte. */
-       ret = lttng_strncpy(attr->configuration_url, uris[0].dst.path,
-                           sizeof(attr->configuration_url));
+       ret = lttng_strncpy(
+               attr->configuration_url, uris[0].dst.path, sizeof(attr->configuration_url));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -146,8 +140,7 @@ error:
        return ret;
 }
 
-int lttng_save_session_attr_set_overwrite(
-       struct lttng_save_session_attr *attr, int overwrite)
+int lttng_save_session_attr_set_overwrite(struct lttng_save_session_attr *attr, int overwrite)
 {
        int ret = 0;
 
@@ -161,8 +154,7 @@ end:
        return ret;
 }
 
-int lttng_save_session_attr_set_omit_name(
-       struct lttng_save_session_attr *attr, int omit_name)
+int lttng_save_session_attr_set_omit_name(struct lttng_save_session_attr *attr, int omit_name)
 {
        int ret = 0;
 
@@ -176,8 +168,7 @@ end:
        return ret;
 }
 
-int lttng_save_session_attr_set_omit_output(
-       struct lttng_save_session_attr *attr, int omit_output)
+int lttng_save_session_attr_set_omit_output(struct lttng_save_session_attr *attr, int omit_output)
 {
        int ret = 0;
 
@@ -207,11 +198,10 @@ int lttng_save_session(struct lttng_save_session_attr *attr)
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SAVE_SESSION;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SAVE_SESSION;
 
-       memcpy(&lsm.u.save_session.attr, attr,
-               sizeof(struct lttng_save_session_attr));
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       memcpy(&lsm.u.save_session.attr, attr, sizeof(struct lttng_save_session_attr));
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
index baec7357f6b8c3becf5a90df7937ed63aba64810..4e7df2db39c60888c03b86529f1b0351f9093080 100644 (file)
@@ -6,22 +6,22 @@
  */
 
 #define _LGPL_SOURCE
-#include <string.h>
+#include "lttng-ctl-helper.hpp"
 
 #include <common/sessiond-comm/sessiond-comm.hpp>
+
 #include <lttng/lttng-error.h>
-#include <lttng/snapshot.h>
 #include <lttng/snapshot-internal.hpp>
+#include <lttng/snapshot.h>
 
-#include "lttng-ctl-helper.hpp"
+#include <string.h>
 
 /*
  * Add an output object to a session identified by name.
  *
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
-int lttng_snapshot_add_output(const char *session_name,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_add_output(const char *session_name, struct lttng_snapshot_output *output)
 {
        int ret;
        struct lttcomm_session_msg lsm;
@@ -33,17 +33,15 @@ int lttng_snapshot_add_output(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SNAPSHOT_ADD_OUTPUT;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_ADD_OUTPUT;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       memcpy(&lsm.u.snapshot_output.output, output,
-                       sizeof(lsm.u.snapshot_output.output));
+       memcpy(&lsm.u.snapshot_output.output, output, sizeof(lsm.u.snapshot_output.output));
 
        ret = lttng_ctl_ask_sessiond(&lsm, (void **) &reply);
        if (ret < 0) {
@@ -62,8 +60,7 @@ end:
  *
  * Return 0 on success or else a negative LTTNG_ERR code.
  */
-int lttng_snapshot_del_output(const char *session_name,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_del_output(const char *session_name, struct lttng_snapshot_output *output)
 {
        int ret;
        struct lttcomm_session_msg lsm;
@@ -74,19 +71,17 @@ int lttng_snapshot_del_output(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SNAPSHOT_DEL_OUTPUT;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_DEL_OUTPUT;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       memcpy(&lsm.u.snapshot_output.output, output,
-                       sizeof(lsm.u.snapshot_output.output));
+       memcpy(&lsm.u.snapshot_output.output, output, sizeof(lsm.u.snapshot_output.output));
 
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -98,12 +93,11 @@ end:
  * Return 0 on success or else a negative LTTNG_ERR code and the list pointer
  * is untouched.
  */
-int lttng_snapshot_list_output(const char *session_name,
-               struct lttng_snapshot_output_list **list)
+int lttng_snapshot_list_output(const char *session_name, struct lttng_snapshot_output_list **list)
 {
        int ret;
        struct lttcomm_session_msg lsm;
-       struct lttng_snapshot_output_list *new_list = NULL;
+       struct lttng_snapshot_output_list *new_list = nullptr;
 
        if (!session_name || !list) {
                ret = -LTTNG_ERR_INVALID;
@@ -111,10 +105,9 @@ int lttng_snapshot_list_output(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SNAPSHOT_LIST_OUTPUT;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_LIST_OUTPUT;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                           sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto error;
@@ -148,10 +141,10 @@ error:
  * Return the next object on success or else NULL indicating the end of the
  * list.
  */
-struct lttng_snapshot_output *lttng_snapshot_output_list_get_next(
-               struct lttng_snapshot_output_list *list)
+struct lttng_snapshot_output *
+lttng_snapshot_output_list_get_next(struct lttng_snapshot_output_list *list)
 {
-       struct lttng_snapshot_output *output = NULL;
+       struct lttng_snapshot_output *output = nullptr;
 
        if (!list) {
                goto error;
@@ -196,8 +189,8 @@ void lttng_snapshot_output_list_destroy(struct lttng_snapshot_output_list *list)
  * Return 0 on success or else a negative LTTNG_ERR value.
  */
 int lttng_snapshot_record(const char *session_name,
-               struct lttng_snapshot_output *output,
-               int wait __attribute__((unused)))
+                         struct lttng_snapshot_output *output,
+                         int wait __attribute__((unused)))
 {
        int ret;
        struct lttcomm_session_msg lsm;
@@ -208,10 +201,9 @@ int lttng_snapshot_record(const char *session_name,
        }
 
        memset(&lsm, 0, sizeof(lsm));
-       lsm.cmd_type = LTTNG_SNAPSHOT_RECORD;
+       lsm.cmd_type = LTTCOMM_SESSIOND_COMMAND_SNAPSHOT_RECORD;
 
-       ret = lttng_strncpy(lsm.session.name, session_name,
-                       sizeof(lsm.session.name));
+       ret = lttng_strncpy(lsm.session.name, session_name, sizeof(lsm.session.name));
        if (ret) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -223,12 +215,11 @@ int lttng_snapshot_record(const char *session_name,
         * record.
         */
        if (output) {
-               memcpy(&lsm.u.snapshot_record.output, output,
-                               sizeof(lsm.u.snapshot_record.output));
+               memcpy(&lsm.u.snapshot_record.output, output, sizeof(lsm.u.snapshot_record.output));
        }
 
        /* The wait param is ignored. */
-       ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
 end:
        return ret;
 }
@@ -270,8 +261,7 @@ uint32_t lttng_snapshot_output_get_id(const struct lttng_snapshot_output *output
        return output->id;
 }
 
-const char *lttng_snapshot_output_get_name(
-               const struct lttng_snapshot_output *output)
+const char *lttng_snapshot_output_get_name(const struct lttng_snapshot_output *output)
 {
        return output->name;
 }
@@ -286,8 +276,7 @@ const char *lttng_snapshot_output_get_ctrl_url(const struct lttng_snapshot_outpu
        return output->ctrl_url;
 }
 
-uint64_t lttng_snapshot_output_get_maxsize(
-               const struct lttng_snapshot_output *output)
+uint64_t lttng_snapshot_output_get_maxsize(const struct lttng_snapshot_output *output)
 {
        return output->max_size;
 }
@@ -296,8 +285,7 @@ uint64_t lttng_snapshot_output_get_maxsize(
  * Setter family functions for snapshot output.
  */
 
-int lttng_snapshot_output_set_id(uint32_t id,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_id(uint32_t id, struct lttng_snapshot_output *output)
 {
        if (!output || id == 0) {
                return -LTTNG_ERR_INVALID;
@@ -307,8 +295,7 @@ int lttng_snapshot_output_set_id(uint32_t id,
        return 0;
 }
 
-int lttng_snapshot_output_set_size(uint64_t size,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_size(uint64_t size, struct lttng_snapshot_output *output)
 {
        if (!output) {
                return -LTTNG_ERR_INVALID;
@@ -318,8 +305,7 @@ int lttng_snapshot_output_set_size(uint64_t size,
        return 0;
 }
 
-int lttng_snapshot_output_set_name(const char *name,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_name(const char *name, struct lttng_snapshot_output *output)
 {
        int ret;
 
@@ -338,8 +324,7 @@ end:
        return ret;
 }
 
-int lttng_snapshot_output_set_ctrl_url(const char *url,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_ctrl_url(const char *url, struct lttng_snapshot_output *output)
 {
        int ret;
 
@@ -358,8 +343,7 @@ end:
        return ret;
 }
 
-int lttng_snapshot_output_set_data_url(const char *url,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_data_url(const char *url, struct lttng_snapshot_output *output)
 {
        int ret;
 
@@ -378,11 +362,10 @@ end:
        return ret;
 }
 
-int lttng_snapshot_output_set_local_path(const char *path,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_local_path(const char *path, struct lttng_snapshot_output *output)
 {
        int ret;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
        ssize_t num_uris;
 
        if (!path || !output) {
@@ -390,7 +373,7 @@ int lttng_snapshot_output_set_local_path(const char *path,
                goto end;
        }
 
-       num_uris = uri_parse_str_urls(path, NULL, &uris);
+       num_uris = uri_parse_str_urls(path, nullptr, &uris);
        if (num_uris != 1) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
@@ -412,11 +395,10 @@ end:
        return ret;
 }
 
-int lttng_snapshot_output_set_network_url(const char *url,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_network_url(const char *url, struct lttng_snapshot_output *output)
 {
        int ret;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
        ssize_t num_uris;
 
        if (!url || !output) {
@@ -424,20 +406,18 @@ int lttng_snapshot_output_set_network_url(const char *url,
                goto end;
        }
 
-       num_uris = uri_parse_str_urls(url, NULL, &uris);
+       num_uris = uri_parse_str_urls(url, nullptr, &uris);
        if (num_uris != 2) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (uris[0].dtype != LTTNG_DST_IPV4 &&
-                       uris[0].dtype != LTTNG_DST_IPV6) {
+       if (uris[0].dtype != LTTNG_DST_IPV4 && uris[0].dtype != LTTNG_DST_IPV6) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (uris[1].dtype != LTTNG_DST_IPV4 &&
-                       uris[1].dtype != LTTNG_DST_IPV6) {
+       if (uris[1].dtype != LTTNG_DST_IPV4 && uris[1].dtype != LTTNG_DST_IPV6) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
@@ -453,12 +433,12 @@ end:
        return ret;
 }
 
-int lttng_snapshot_output_set_network_urls(
-               const char *ctrl_url, const char *data_url,
-               struct lttng_snapshot_output *output)
+int lttng_snapshot_output_set_network_urls(const char *ctrl_url,
+                                          const char *data_url,
+                                          struct lttng_snapshot_output *output)
 {
        int ret;
-       struct lttng_uri *uris = NULL;
+       struct lttng_uri *uris = nullptr;
        ssize_t num_uris;
 
        if (!ctrl_url || !data_url || !output) {
@@ -472,14 +452,12 @@ int lttng_snapshot_output_set_network_urls(
                goto end;
        }
 
-       if (uris[0].dtype != LTTNG_DST_IPV4 &&
-                       uris[0].dtype != LTTNG_DST_IPV6) {
+       if (uris[0].dtype != LTTNG_DST_IPV4 && uris[0].dtype != LTTNG_DST_IPV6) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
 
-       if (uris[1].dtype != LTTNG_DST_IPV4 &&
-                       uris[1].dtype != LTTNG_DST_IPV6) {
+       if (uris[1].dtype != LTTNG_DST_IPV4 && uris[1].dtype != LTTNG_DST_IPV6) {
                ret = -LTTNG_ERR_INVALID;
                goto end;
        }
index 4930e94ce57610469f9fcc9558425556b31d3cfd..a31b5a1893643abe67cda41de44c1fd2ebc82816 100644 (file)
@@ -5,13 +5,15 @@
  *
  */
 
-#include <lttng/domain.h>
-#include <lttng/lttng-error.h>
-
 #include "lttng-ctl-helper.hpp"
+
 #include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/tracker.hpp>
+
+#include <lttng/domain.h>
+#include <lttng/lttng-error.h>
 #include <lttng/tracker.h>
+
 #include <type_traits>
 
 struct lttng_process_attr_tracker_handle {
@@ -21,8 +23,7 @@ struct lttng_process_attr_tracker_handle {
        struct lttng_process_attr_values *inclusion_set;
 };
 
-void lttng_process_attr_tracker_handle_destroy(
-               struct lttng_process_attr_tracker_handle *tracker)
+void lttng_process_attr_tracker_handle_destroy(struct lttng_process_attr_tracker_handle *tracker)
 {
        if (!tracker) {
                return;
@@ -33,13 +34,14 @@ void lttng_process_attr_tracker_handle_destroy(
        free(tracker);
 }
 
-enum lttng_error_code lttng_session_get_tracker_handle(const char *session_name,
-               enum lttng_domain_type domain,
-               enum lttng_process_attr process_attr,
-               struct lttng_process_attr_tracker_handle **out_tracker_handle)
+enum lttng_error_code
+lttng_session_get_tracker_handle(const char *session_name,
+                                enum lttng_domain_type domain,
+                                enum lttng_process_attr process_attr,
+                                struct lttng_process_attr_tracker_handle **out_tracker_handle)
 {
        enum lttng_error_code ret_code = LTTNG_OK;
-       struct lttng_process_attr_tracker_handle *handle = NULL;
+       struct lttng_process_attr_tracker_handle *handle = nullptr;
        enum lttng_process_attr_tracker_handle_status status;
        enum lttng_tracking_policy policy;
 
@@ -72,8 +74,7 @@ enum lttng_error_code lttng_session_get_tracker_handle(const char *session_name,
         * Use the `get_tracking_policy` command to validate the tracker's
         * existence.
         */
-       status = lttng_process_attr_tracker_handle_get_tracking_policy(
-                       handle, &policy);
+       status = lttng_process_attr_tracker_handle_get_tracking_policy(handle, &policy);
        switch (status) {
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK:
                break;
@@ -92,17 +93,15 @@ error:
        return ret_code;
 }
 
-enum lttng_process_attr_tracker_handle_status
-lttng_process_attr_tracker_handle_get_tracking_policy(
-               const struct lttng_process_attr_tracker_handle *tracker,
-               enum lttng_tracking_policy *policy)
+enum lttng_process_attr_tracker_handle_status lttng_process_attr_tracker_handle_get_tracking_policy(
+       const struct lttng_process_attr_tracker_handle *tracker, enum lttng_tracking_policy *policy)
 {
-       void *reply = NULL;
+       void *reply = nullptr;
        int reply_ret, copy_ret;
        enum lttng_process_attr_tracker_handle_status status =
-                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
+               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_PROCESS_ATTR_TRACKER_GET_POLICY,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_POLICY,
                .session = {},
                .domain = {},
                .u = {},
@@ -114,8 +113,7 @@ lttng_process_attr_tracker_handle_get_tracking_policy(
                goto end;
        }
 
-       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name,
-                       sizeof(lsm.session.name));
+       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name, sizeof(lsm.session.name));
        if (copy_ret) {
                status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;
                goto end;
@@ -123,14 +121,13 @@ lttng_process_attr_tracker_handle_get_tracking_policy(
 
        lsm.domain.type = tracker->domain;
        lsm.u.process_attr_tracker_get_tracking_policy.process_attr =
-                       (int32_t) tracker->process_attr;
+               (int32_t) tracker->process_attr;
 
        /* Command returns a session descriptor on success. */
-       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(
-                       &lsm, NULL, 0, &reply);
+       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, nullptr, 0, &reply);
        if (reply_ret != sizeof(uint32_t)) {
                if (reply_ret == -LTTNG_ERR_SESSION_NOT_EXIST ||
-                               reply_ret == -LTTNG_ERR_SESS_NOT_FOUND) {
+                   reply_ret == -LTTNG_ERR_SESS_NOT_FOUND) {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST;
                } else {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;
@@ -144,16 +141,14 @@ end:
        return status;
 }
 
-enum lttng_process_attr_tracker_handle_status
-lttng_process_attr_tracker_handle_set_tracking_policy(
-               const struct lttng_process_attr_tracker_handle *tracker,
-               enum lttng_tracking_policy policy)
+enum lttng_process_attr_tracker_handle_status lttng_process_attr_tracker_handle_set_tracking_policy(
+       const struct lttng_process_attr_tracker_handle *tracker, enum lttng_tracking_policy policy)
 {
        int reply_ret, copy_ret;
        enum lttng_process_attr_tracker_handle_status status =
-                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
+               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_PROCESS_ATTR_TRACKER_SET_POLICY,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_SET_POLICY,
                .session = {},
                .domain = {},
                .u = {},
@@ -165,8 +160,7 @@ lttng_process_attr_tracker_handle_set_tracking_policy(
                goto end;
        }
 
-       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name,
-                                sizeof(lsm.session.name));
+       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name, sizeof(lsm.session.name));
        if (copy_ret) {
                status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;
                goto end;
@@ -174,12 +168,11 @@ lttng_process_attr_tracker_handle_set_tracking_policy(
 
        lsm.domain.type = tracker->domain;
        lsm.u.process_attr_tracker_set_tracking_policy.process_attr =
-                       (int32_t) tracker->process_attr;
-       lsm.u.process_attr_tracker_set_tracking_policy.tracking_policy =
-                       (int32_t) policy;
+               (int32_t) tracker->process_attr;
+       lsm.u.process_attr_tracker_set_tracking_policy.tracking_policy = (int32_t) policy;
 
        /* Command returns a session descriptor on success. */
-       reply_ret = lttng_ctl_ask_sessiond(&lsm, NULL);
+       reply_ret = lttng_ctl_ask_sessiond(&lsm, nullptr);
        if (reply_ret < 0) {
                if (reply_ret == -LTTNG_ERR_SESSION_NOT_EXIST) {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST;
@@ -192,207 +185,185 @@ end:
        return status;
 }
 
-#define DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(command_upper,                                                 \
-               command_lower, process_attr_name, value_type_name,                                                   \
-               value_type_c, value_type_enum)                                                                       \
-       enum lttng_process_attr_tracker_handle_status                                                                \
-                       lttng_process_attr_##process_attr_name##_tracker_handle_##command_lower##_##value_type_name( \
-                                       const struct lttng_process_attr_tracker_handle                               \
-                                                       *tracker,                                                    \
-                                       value_type_c value)                                                          \
-       {                                                                                                            \
-               int ret;                                                                                             \
-               enum lttng_process_attr_tracker_handle_status status =                                               \
-                               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;                                         \
-               struct lttcomm_session_msg lsm = {                                                                   \
-                       .cmd_type = LTTNG_PROCESS_ATTR_TRACKER_##command_upper##_INCLUDE_VALUE,                      \
-                       .session = {},                                                                               \
-                       .domain = {},                                                                                \
-                       .u = {},                                                                                     \
-                       .fd_count = 0,                                                                               \
-               };                                                                                                   \
-                                                                                                                     \
-               if (!tracker) {                                                                                      \
-                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                                   \
-                       goto end;                                                                                    \
-               }                                                                                                    \
-                                                                                                                     \
-               ret = lttng_strncpy(lsm.session.name, tracker->session_name,                                         \
-                               sizeof(lsm.session.name));                                                           \
-               if (ret) {                                                                                           \
-                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                                   \
-                       goto end;                                                                                    \
-               }                                                                                                    \
-                                                                                                                     \
-               lsm.domain.type = tracker->domain;                                                                   \
-               lsm.u.process_attr_tracker_add_remove_include_value                                                  \
-                               .process_attr =                                                                      \
-                               (int32_t) tracker->process_attr;                                                     \
-               lsm.u.process_attr_tracker_add_remove_include_value                                                  \
-                               .value_type = (uint32_t)                                                             \
-                               LTTNG_PROCESS_ATTR_VALUE_TYPE_##value_type_enum;                                     \
-                                                                                                                     \
-               if (std::is_signed<value_type_c>::value) {                                                                       \
-                       lsm.u.process_attr_tracker_add_remove_include_value                                          \
-                                       .integral_value.u._signed = value;                                           \
-               } else {                                                                                             \
-                       lsm.u.process_attr_tracker_add_remove_include_value                                          \
-                                       .integral_value.u._unsigned = value;                                         \
-               }                                                                                                    \
-                                                                                                                     \
-               ret = lttng_ctl_ask_sessiond(&lsm, NULL);                                                            \
-               if (ret < 0) {                                                                                       \
-                       switch (-ret) {                                                                              \
-                       case LTTNG_ERR_PROCESS_ATTR_EXISTS:                                                          \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_EXISTS;                            \
-                               break;                                                                               \
-                       case LTTNG_ERR_PROCESS_ATTR_MISSING:                                                         \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_MISSING;                           \
-                               break;                                                                               \
-                       case LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY:                                 \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY;           \
-                               break;                                                                               \
-                       default:                                                                                     \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;                             \
-                       }                                                                                            \
-               }                                                                                                    \
-       end:                                                                                                         \
-               return status;                                                                                       \
-       }
-
-#define DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(command_upper,                                                   \
-               command_lower, process_attr_name, value_type_name,                                                   \
-               value_type_enum)                                                                                     \
-       enum lttng_process_attr_tracker_handle_status                                                                \
-                       lttng_process_attr_##process_attr_name##_tracker_handle_##command_lower##_##value_type_name( \
-                                       const struct lttng_process_attr_tracker_handle                               \
-                                                       *tracker,                                                    \
-                                       const char *value)                                                           \
-       {                                                                                                            \
-               int ret;                                                                                             \
-               enum lttng_process_attr_tracker_handle_status status =                                               \
-                               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;                                         \
-               struct lttcomm_session_msg lsm = {                                                                   \
-                       .cmd_type = LTTNG_PROCESS_ATTR_TRACKER_##command_upper##_INCLUDE_VALUE,                      \
-                       .session = {},                                                                               \
-                       .domain = {},                                                                                \
-                       .u = {},                                                                                     \
-                       .fd_count = 0,                                                                               \
-               };                                                                                                   \
-               const size_t len = value ? strlen(value) + 1 : 0;                                                    \
-                                                                                                                     \
-               if (!tracker || !value) {                                                                            \
-                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                                   \
-                       goto end;                                                                                    \
-               }                                                                                                    \
-                                                                                                                     \
-               ret = lttng_strncpy(lsm.session.name, tracker->session_name,                                         \
-                               sizeof(lsm.session.name));                                                           \
-               if (ret) {                                                                                           \
-                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                                   \
-                       goto end;                                                                                    \
-               }                                                                                                    \
-                                                                                                                     \
-               lsm.domain.type = tracker->domain;                                                                   \
-               lsm.u.process_attr_tracker_add_remove_include_value                                                  \
-                               .process_attr =                                                                      \
-                               (int32_t) tracker->process_attr;                                                     \
-               lsm.u.process_attr_tracker_add_remove_include_value.name_len =                                       \
-                               (uint32_t) len;                                                                      \
-               lsm.u.process_attr_tracker_add_remove_include_value                                                  \
-                               .value_type = (uint32_t)                                                             \
-                               LTTNG_PROCESS_ATTR_VALUE_TYPE_##value_type_enum;                                     \
-                                                                                                                     \
-               ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(                                                   \
-                               &lsm, value, len, NULL);                                                             \
-               if (ret < 0) {                                                                                       \
-                       switch (-ret) {                                                                              \
-                       case LTTNG_ERR_PROCESS_ATTR_EXISTS:                                                          \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_EXISTS;                            \
-                               break;                                                                               \
-                       case LTTNG_ERR_PROCESS_ATTR_MISSING:                                                         \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_MISSING;                           \
-                               break;                                                                               \
-                       case LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY:                                 \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY;           \
-                               break;                                                                               \
-                       case LTTNG_ERR_USER_NOT_FOUND:                                                               \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_USER_NOT_FOUND;                    \
-                               break;                                                                               \
-                       case LTTNG_ERR_GROUP_NOT_FOUND:                                                              \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_GROUP_NOT_FOUND;                   \
-                               break;                                                                               \
-                       default:                                                                                     \
-                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;                             \
-                       }                                                                                            \
-               }                                                                                                    \
-       end:                                                                                                         \
-               return status;                                                                                       \
+#define DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(command_upper,                                           \
+                                                     command_lower,                                           \
+                                                     process_attr_name,                                       \
+                                                     value_type_name,                                         \
+                                                     value_type_c,                                            \
+                                                     value_type_enum)                                         \
+       enum lttng_process_attr_tracker_handle_status                                                          \
+               lttng_process_attr_##process_attr_name##_tracker_handle_##command_lower##_##value_type_name(   \
+                       const struct lttng_process_attr_tracker_handle *tracker,                               \
+                       value_type_c value)                                                                    \
+       {                                                                                                      \
+               int ret;                                                                                       \
+               enum lttng_process_attr_tracker_handle_status status =                                         \
+                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;                                           \
+               struct lttcomm_session_msg lsm = {                                                             \
+                       .cmd_type =                                                                            \
+                               LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_##command_upper##_INCLUDE_VALUE, \
+                       .session = {},                                                                         \
+                       .domain = {},                                                                          \
+                       .u = {},                                                                               \
+                       .fd_count = 0,                                                                         \
+               };                                                                                             \
+                                                                                                               \
+               if (!tracker) {                                                                                \
+                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                             \
+                       goto end;                                                                              \
+               }                                                                                              \
+                                                                                                               \
+               ret = lttng_strncpy(                                                                           \
+                       lsm.session.name, tracker->session_name, sizeof(lsm.session.name));                    \
+               if (ret) {                                                                                     \
+                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                             \
+                       goto end;                                                                              \
+               }                                                                                              \
+                                                                                                               \
+               lsm.domain.type = tracker->domain;                                                             \
+               lsm.u.process_attr_tracker_add_remove_include_value.process_attr =                             \
+                       (int32_t) tracker->process_attr;                                                       \
+               lsm.u.process_attr_tracker_add_remove_include_value.value_type =                               \
+                       (uint32_t) LTTNG_PROCESS_ATTR_VALUE_TYPE_##value_type_enum;                            \
+                                                                                                               \
+               if (std::is_signed<value_type_c>::value) {                                                     \
+                       lsm.u.process_attr_tracker_add_remove_include_value.integral_value.u                   \
+                               ._signed = value;                                                              \
+               } else {                                                                                       \
+                       lsm.u.process_attr_tracker_add_remove_include_value.integral_value.u                   \
+                               ._unsigned = value;                                                            \
+               }                                                                                              \
+                                                                                                               \
+               ret = lttng_ctl_ask_sessiond(&lsm, NULL);                                                      \
+               if (ret < 0) {                                                                                 \
+                       switch (-ret) {                                                                        \
+                       case LTTNG_ERR_PROCESS_ATTR_EXISTS:                                                    \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_EXISTS;                      \
+                               break;                                                                         \
+                       case LTTNG_ERR_PROCESS_ATTR_MISSING:                                                   \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_MISSING;                     \
+                               break;                                                                         \
+                       case LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY:                           \
+                               status =                                                                       \
+                                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY;      \
+                               break;                                                                         \
+                       default:                                                                               \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;                       \
+                       }                                                                                      \
+               }                                                                                              \
+       end:                                                                                                   \
+               return status;                                                                                 \
+       }
+
+#define DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(                                                           \
+       command_upper, command_lower, process_attr_name, value_type_name, value_type_enum)                     \
+       enum lttng_process_attr_tracker_handle_status                                                          \
+               lttng_process_attr_##process_attr_name##_tracker_handle_##command_lower##_##value_type_name(   \
+                       const struct lttng_process_attr_tracker_handle *tracker,                               \
+                       const char *value)                                                                     \
+       {                                                                                                      \
+               int ret;                                                                                       \
+               enum lttng_process_attr_tracker_handle_status status =                                         \
+                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;                                           \
+               struct lttcomm_session_msg lsm = {                                                             \
+                       .cmd_type =                                                                            \
+                               LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_##command_upper##_INCLUDE_VALUE, \
+                       .session = {},                                                                         \
+                       .domain = {},                                                                          \
+                       .u = {},                                                                               \
+                       .fd_count = 0,                                                                         \
+               };                                                                                             \
+               const size_t len = value ? strlen(value) + 1 : 0;                                              \
+                                                                                                               \
+               if (!tracker || !value) {                                                                      \
+                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                             \
+                       goto end;                                                                              \
+               }                                                                                              \
+                                                                                                               \
+               ret = lttng_strncpy(                                                                           \
+                       lsm.session.name, tracker->session_name, sizeof(lsm.session.name));                    \
+               if (ret) {                                                                                     \
+                       status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;                             \
+                       goto end;                                                                              \
+               }                                                                                              \
+                                                                                                               \
+               lsm.domain.type = tracker->domain;                                                             \
+               lsm.u.process_attr_tracker_add_remove_include_value.process_attr =                             \
+                       (int32_t) tracker->process_attr;                                                       \
+               lsm.u.process_attr_tracker_add_remove_include_value.name_len = (uint32_t) len;                 \
+               lsm.u.process_attr_tracker_add_remove_include_value.value_type =                               \
+                       (uint32_t) LTTNG_PROCESS_ATTR_VALUE_TYPE_##value_type_enum;                            \
+                                                                                                               \
+               ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, value, len, NULL);                     \
+               if (ret < 0) {                                                                                 \
+                       switch (-ret) {                                                                        \
+                       case LTTNG_ERR_PROCESS_ATTR_EXISTS:                                                    \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_EXISTS;                      \
+                               break;                                                                         \
+                       case LTTNG_ERR_PROCESS_ATTR_MISSING:                                                   \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_MISSING;                     \
+                               break;                                                                         \
+                       case LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY:                           \
+                               status =                                                                       \
+                                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY;      \
+                               break;                                                                         \
+                       case LTTNG_ERR_USER_NOT_FOUND:                                                         \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_USER_NOT_FOUND;              \
+                               break;                                                                         \
+                       case LTTNG_ERR_GROUP_NOT_FOUND:                                                        \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_GROUP_NOT_FOUND;             \
+                               break;                                                                         \
+                       default:                                                                               \
+                               status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;                       \
+                       }                                                                                      \
+               }                                                                                              \
+       end:                                                                                                   \
+               return status;                                                                                 \
        }
 
 /* PID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, process_id, pid, pid_t, PID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, process_id, pid, pid_t, PID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, process_id, pid, pid_t, PID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, process_id, pid, pid_t, PID);
 
 /* VPID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, virtual_process_id, pid, pid_t, PID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, virtual_process_id, pid, pid_t, PID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, virtual_process_id, pid, pid_t, PID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, virtual_process_id, pid, pid_t, PID);
 
 /* UID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, user_id, uid, uid_t, UID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, user_id, uid, uid_t, UID);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               ADD, add, user_id, user_name, USER_NAME);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               REMOVE, remove, user_id, user_name, USER_NAME);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, user_id, uid, uid_t, UID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, user_id, uid, uid_t, UID);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(ADD, add, user_id, user_name, USER_NAME);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(REMOVE, remove, user_id, user_name, USER_NAME);
 
 /* VUID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, virtual_user_id, uid, uid_t, UID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, virtual_user_id, uid, uid_t, UID);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               ADD, add, virtual_user_id, user_name, USER_NAME);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               REMOVE, remove, virtual_user_id, user_name, USER_NAME);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, virtual_user_id, uid, uid_t, UID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, virtual_user_id, uid, uid_t, UID);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(ADD, add, virtual_user_id, user_name, USER_NAME);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(REMOVE, remove, virtual_user_id, user_name, USER_NAME);
 
 /* GID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, group_id, gid, gid_t, GID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, group_id, gid, gid_t, GID);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               ADD, add, group_id, group_name, GROUP_NAME);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               REMOVE, remove, group_id, group_name, GROUP_NAME);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, group_id, gid, gid_t, GID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, group_id, gid, gid_t, GID);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(ADD, add, group_id, group_name, GROUP_NAME);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(REMOVE, remove, group_id, group_name, GROUP_NAME);
 
 /* VGID */
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               ADD, add, virtual_group_id, gid, gid_t, GID);
-DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(
-               REMOVE, remove, virtual_group_id, gid, gid_t, GID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(ADD, add, virtual_group_id, gid, gid_t, GID);
+DEFINE_TRACKER_ADD_REMOVE_INTEGRAL_VALUE_FUNC(REMOVE, remove, virtual_group_id, gid, gid_t, GID);
+DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(ADD, add, virtual_group_id, group_name, GROUP_NAME);
 DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               ADD, add, virtual_group_id, group_name, GROUP_NAME);
-DEFINE_TRACKER_ADD_REMOVE_STRING_VALUE_FUNC(
-               REMOVE, remove, virtual_group_id, group_name, GROUP_NAME);
+       REMOVE, remove, virtual_group_id, group_name, GROUP_NAME);
 
-enum lttng_process_attr_tracker_handle_status
-lttng_process_attr_tracker_handle_get_inclusion_set(
-               struct lttng_process_attr_tracker_handle *tracker,
-               const struct lttng_process_attr_values **values)
+enum lttng_process_attr_tracker_handle_status lttng_process_attr_tracker_handle_get_inclusion_set(
+       struct lttng_process_attr_tracker_handle *tracker,
+       const struct lttng_process_attr_values **values)
 {
-       char *reply = NULL;
+       char *reply = nullptr;
        int reply_ret, copy_ret;
        enum lttng_process_attr_tracker_handle_status status =
-                       LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
+               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK;
        struct lttcomm_session_msg lsm = {
-               .cmd_type = LTTNG_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET,
+               .cmd_type = LTTCOMM_SESSIOND_COMMAND_PROCESS_ATTR_TRACKER_GET_INCLUSION_SET,
                .session = {},
                .domain = {},
                .u = {},
@@ -407,10 +378,9 @@ lttng_process_attr_tracker_handle_get_inclusion_set(
        }
 
        lttng_process_attr_values_destroy(tracker->inclusion_set);
-       tracker->inclusion_set = NULL;
+       tracker->inclusion_set = nullptr;
 
-       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name,
-                       sizeof(lsm.session.name));
+       copy_ret = lttng_strncpy(lsm.session.name, tracker->session_name, sizeof(lsm.session.name));
        if (copy_ret) {
                status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID;
                goto end;
@@ -418,16 +388,14 @@ lttng_process_attr_tracker_handle_get_inclusion_set(
 
        lsm.domain.type = tracker->domain;
        lsm.u.process_attr_tracker_get_tracking_policy.process_attr =
-                       (int32_t) tracker->process_attr;
+               (int32_t) tracker->process_attr;
 
        /* Command returns a session descriptor on success. */
-       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(
-                       &lsm, NULL, 0, (void **) &reply);
+       reply_ret = lttng_ctl_ask_sessiond_varlen_no_cmd_header(&lsm, nullptr, 0, (void **) &reply);
        if (reply_ret < 0) {
                if (reply_ret == -LTTNG_ERR_SESSION_NOT_EXIST) {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_SESSION_DOES_NOT_EXIST;
-               } else if (reply_ret ==
-                               -LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY) {
+               } else if (reply_ret == -LTTNG_ERR_PROCESS_ATTR_TRACKER_INVALID_TRACKING_POLICY) {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY;
                } else {
                        status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_ERROR;
@@ -444,9 +412,10 @@ lttng_process_attr_tracker_handle_get_inclusion_set(
                goto end;
        }
 
-       inclusion_set_ret = lttng_process_attr_values_create_from_buffer(
-                       tracker->domain, tracker->process_attr,
-                       &inclusion_set_view, &tracker->inclusion_set);
+       inclusion_set_ret = lttng_process_attr_values_create_from_buffer(tracker->domain,
+                                                                        tracker->process_attr,
+                                                                        &inclusion_set_view,
+                                                                        &tracker->inclusion_set);
        if (inclusion_set_ret < 0) {
                status = LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_COMMUNICATION_ERROR;
                goto end;
@@ -457,12 +426,11 @@ end:
        return status;
 }
 
-enum lttng_process_attr_values_status lttng_process_attr_values_get_count(
-               const struct lttng_process_attr_values *values,
-               unsigned int *count)
+enum lttng_process_attr_values_status
+lttng_process_attr_values_get_count(const struct lttng_process_attr_values *values,
+                                   unsigned int *count)
 {
-       enum lttng_process_attr_values_status status =
-                       LTTNG_PROCESS_ATTR_VALUES_STATUS_OK;
+       enum lttng_process_attr_values_status status = LTTNG_PROCESS_ATTR_VALUES_STATUS_OK;
 
        if (!values || !count) {
                status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID;
@@ -474,9 +442,9 @@ end:
        return status;
 }
 
-enum lttng_process_attr_value_type lttng_process_attr_values_get_type_at_index(
-               const struct lttng_process_attr_values *values,
-               unsigned int index)
+enum lttng_process_attr_value_type
+lttng_process_attr_values_get_type_at_index(const struct lttng_process_attr_values *values,
+                                           unsigned int index)
 {
        enum lttng_process_attr_value_type type;
        const struct process_attr_value *value;
@@ -497,39 +465,36 @@ end:
        return type;
 }
 
-#define DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(                                       \
-               value_type_name, value_type, expected_value_type)                      \
-       enum lttng_process_attr_values_status                                          \
-                       lttng_process_attr_values_get_##value_type_name##_at_index(    \
-                                       const struct lttng_process_attr_values         \
-                                                       *values,                       \
-                                       unsigned int index,                            \
-                                       value_type *out_value)                         \
-       {                                                                              \
-               enum lttng_process_attr_values_status status =                         \
-                               LTTNG_PROCESS_ATTR_VALUES_STATUS_OK;                   \
-               const struct process_attr_value *value;                                \
-                                                                                       \
-               if (!values) {                                                         \
-                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID;             \
-                       goto end;                                                      \
-               }                                                                      \
-                                                                                       \
-               if (_lttng_process_attr_values_get_count(values) <= index) {           \
-                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID;             \
-                       goto end;                                                      \
-               }                                                                      \
-                                                                                       \
-               value = lttng_process_attr_tracker_values_get_at_index(                \
-                               values, index);                                        \
-               if (value->type !=                                                     \
-                               LTTNG_PROCESS_ATTR_VALUE_TYPE_##expected_value_type) { \
-                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID_TYPE;        \
-                       goto end;                                                      \
-               }                                                                      \
-               *out_value = value->value.value_type_name;                             \
-       end:                                                                           \
-               return status;                                                         \
+#define DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(value_type_name, value_type, expected_value_type)  \
+       enum lttng_process_attr_values_status                                                      \
+               lttng_process_attr_values_get_##value_type_name##_at_index(                        \
+                       const struct lttng_process_attr_values *values,                            \
+                       unsigned int index,                                                        \
+                       value_type *out_value) /* NOLINT clang-tidy sees value_type as a value and \
+                                                 adds parentheses */                              \
+       {                                                                                          \
+               enum lttng_process_attr_values_status status =                                     \
+                       LTTNG_PROCESS_ATTR_VALUES_STATUS_OK;                                       \
+               const struct process_attr_value *value;                                            \
+                                                                                                   \
+               if (!values) {                                                                     \
+                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID;                         \
+                       goto end;                                                                  \
+               }                                                                                  \
+                                                                                                   \
+               if (_lttng_process_attr_values_get_count(values) <= index) {                       \
+                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID;                         \
+                       goto end;                                                                  \
+               }                                                                                  \
+                                                                                                   \
+               value = lttng_process_attr_tracker_values_get_at_index(values, index);             \
+               if (value->type != LTTNG_PROCESS_ATTR_VALUE_TYPE_##expected_value_type) {          \
+                       status = LTTNG_PROCESS_ATTR_VALUES_STATUS_INVALID_TYPE;                    \
+                       goto end;                                                                  \
+               }                                                                                  \
+               *out_value = value->value.value_type_name;                                         \
+       end:                                                                                       \
+               return status;                                                                     \
        }
 
 DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(pid, pid_t, PID);
@@ -538,8 +503,8 @@ DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(gid, gid_t, GID);
 DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(user_name, const char *, USER_NAME);
 DEFINE_LTTNG_PROCESS_ATTR_VALUES_GETTER(group_name, const char *, GROUP_NAME);
 
-static enum lttng_error_code handle_status_to_error_code(
-               enum lttng_process_attr_tracker_handle_status handle_status)
+static enum lttng_error_code
+handle_status_to_error_code(enum lttng_process_attr_tracker_handle_status handle_status)
 {
        switch (handle_status) {
        case LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY:
@@ -568,7 +533,7 @@ static enum lttng_error_code handle_status_to_error_code(
 int lttng_track_pid(struct lttng_handle *handle, int pid)
 {
        enum lttng_error_code ret_code;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
        enum lttng_process_attr_tracker_handle_status handle_status;
        enum lttng_tracking_policy policy;
        enum lttng_process_attr process_attr;
@@ -579,26 +544,24 @@ int lttng_track_pid(struct lttng_handle *handle, int pid)
        }
 
        process_attr = handle->domain.type == LTTNG_DOMAIN_KERNEL ?
-                                      LTTNG_PROCESS_ATTR_PROCESS_ID :
-                                      LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID;
+               LTTNG_PROCESS_ATTR_PROCESS_ID :
+               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID;
 
-       ret_code = lttng_session_get_tracker_handle(handle->session_name,
-                       handle->domain.type,
-                       process_attr, &tracker_handle);
+       ret_code = lttng_session_get_tracker_handle(
+               handle->session_name, handle->domain.type, process_attr, &tracker_handle);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        if (pid == -1) {
                handle_status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                               tracker_handle,
-                               LTTNG_TRACKING_POLICY_INCLUDE_ALL);
+                       tracker_handle, LTTNG_TRACKING_POLICY_INCLUDE_ALL);
                ret_code = handle_status_to_error_code(handle_status);
                goto end;
        }
 
-       handle_status = lttng_process_attr_tracker_handle_get_tracking_policy(
-               tracker_handle, &policy);
+       handle_status =
+               lttng_process_attr_tracker_handle_get_tracking_policy(tracker_handle, &policy);
        if (handle_status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                ret_code = handle_status_to_error_code(handle_status);
                goto end;
@@ -606,8 +569,7 @@ int lttng_track_pid(struct lttng_handle *handle, int pid)
 
        if (policy != LTTNG_TRACKING_POLICY_INCLUDE_SET) {
                handle_status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                       tracker_handle,
-                       LTTNG_TRACKING_POLICY_INCLUDE_SET);
+                       tracker_handle, LTTNG_TRACKING_POLICY_INCLUDE_SET);
                if (handle_status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                        ret_code = handle_status_to_error_code(handle_status);
                        goto end;
@@ -615,12 +577,9 @@ int lttng_track_pid(struct lttng_handle *handle, int pid)
        }
 
        handle_status = process_attr == LTTNG_PROCESS_ATTR_PROCESS_ID ?
-                                       lttng_process_attr_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) pid) :
-                                       lttng_process_attr_virtual_process_id_tracker_handle_add_pid(
-                                                       tracker_handle,
-                                                       (pid_t) pid);
+               lttng_process_attr_process_id_tracker_handle_add_pid(tracker_handle, (pid_t) pid) :
+               lttng_process_attr_virtual_process_id_tracker_handle_add_pid(tracker_handle,
+                                                                            (pid_t) pid);
        ret_code = handle_status_to_error_code(handle_status);
 end:
        lttng_process_attr_tracker_handle_destroy(tracker_handle);
@@ -634,7 +593,7 @@ end:
 int lttng_untrack_pid(struct lttng_handle *handle, int pid)
 {
        enum lttng_error_code ret_code;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
        enum lttng_process_attr_tracker_handle_status handle_status;
        enum lttng_tracking_policy policy;
        enum lttng_process_attr process_attr;
@@ -645,24 +604,23 @@ int lttng_untrack_pid(struct lttng_handle *handle, int pid)
        }
 
        process_attr = handle->domain.type == LTTNG_DOMAIN_KERNEL ?
-                                      LTTNG_PROCESS_ATTR_PROCESS_ID :
-                                      LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID;
-       ret_code = lttng_session_get_tracker_handle(handle->session_name,
-                       handle->domain.type, process_attr, &tracker_handle);
+               LTTNG_PROCESS_ATTR_PROCESS_ID :
+               LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID;
+       ret_code = lttng_session_get_tracker_handle(
+               handle->session_name, handle->domain.type, process_attr, &tracker_handle);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        if (pid == -1) {
                handle_status = lttng_process_attr_tracker_handle_set_tracking_policy(
-                               tracker_handle,
-                               LTTNG_TRACKING_POLICY_EXCLUDE_ALL);
+                       tracker_handle, LTTNG_TRACKING_POLICY_EXCLUDE_ALL);
                ret_code = handle_status_to_error_code(handle_status);
                goto end;
        }
 
-       handle_status = lttng_process_attr_tracker_handle_get_tracking_policy(
-               tracker_handle, &policy);
+       handle_status =
+               lttng_process_attr_tracker_handle_get_tracking_policy(tracker_handle, &policy);
        if (handle_status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                ret_code = handle_status_to_error_code(handle_status);
                goto end;
@@ -677,12 +635,10 @@ int lttng_untrack_pid(struct lttng_handle *handle, int pid)
        }
 
        handle_status = process_attr == LTTNG_PROCESS_ATTR_PROCESS_ID ?
-                                       lttng_process_attr_process_id_tracker_handle_remove_pid(
-                                                       tracker_handle,
-                                                       (pid_t) pid) :
-                                       lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(
-                                                       tracker_handle,
-                                                       (pid_t) pid);
+               lttng_process_attr_process_id_tracker_handle_remove_pid(tracker_handle,
+                                                                       (pid_t) pid) :
+               lttng_process_attr_virtual_process_id_tracker_handle_remove_pid(tracker_handle,
+                                                                               (pid_t) pid);
        if (handle_status == LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY) {
                ret_code = LTTNG_ERR_PID_NOT_TRACKED;
        }
@@ -702,17 +658,17 @@ end:
  * Returns 0 on success, else a negative LTTng error code.
  */
 int lttng_list_tracker_pids(struct lttng_handle *handle,
-               int *_enabled,
-               int32_t **_pids,
-               size_t *_nr_pids)
+                           int *_enabled,
+                           int32_t **_pids,
+                           size_t *_nr_pids)
 {
        enum lttng_error_code ret_code;
-       struct lttng_process_attr_tracker_handle *tracker_handle = NULL;
+       struct lttng_process_attr_tracker_handle *tracker_handle = nullptr;
        enum lttng_process_attr_tracker_handle_status handle_status;
        const struct lttng_process_attr_values *values;
        enum lttng_tracking_policy policy;
        unsigned int pid_count, i;
-       int32_t *pid_array = NULL;
+       int32_t *pid_array = nullptr;
 
        if (!handle || !_enabled || !_pids || !_nr_pids) {
                ret_code = LTTNG_ERR_INVALID;
@@ -720,29 +676,28 @@ int lttng_list_tracker_pids(struct lttng_handle *handle,
        }
 
        ret_code = lttng_session_get_tracker_handle(handle->session_name,
-                       handle->domain.type,
-                       LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID, &tracker_handle);
+                                                   handle->domain.type,
+                                                   LTTNG_PROCESS_ATTR_VIRTUAL_PROCESS_ID,
+                                                   &tracker_handle);
        if (ret_code != LTTNG_OK) {
                goto end;
        }
 
        while (true) {
-               handle_status = lttng_process_attr_tracker_handle_get_inclusion_set(
-                               tracker_handle, &values);
-               if (handle_status ==
-                               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
+               handle_status = lttng_process_attr_tracker_handle_get_inclusion_set(tracker_handle,
+                                                                                   &values);
+               if (handle_status == LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                        policy = LTTNG_TRACKING_POLICY_INCLUDE_SET;
                        break;
                } else if (handle_status !=
-                               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY) {
+                          LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_INVALID_TRACKING_POLICY) {
                        ret_code = handle_status_to_error_code(handle_status);
                        goto end;
                }
 
                handle_status = lttng_process_attr_tracker_handle_get_tracking_policy(
-                               tracker_handle, &policy);
-               if (handle_status !=
-                               LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
+                       tracker_handle, &policy);
+               if (handle_status != LTTNG_PROCESS_ATTR_TRACKER_HANDLE_STATUS_OK) {
                        ret_code = handle_status_to_error_code(handle_status);
                        goto end;
                }
@@ -765,8 +720,7 @@ int lttng_list_tracker_pids(struct lttng_handle *handle,
        case LTTNG_TRACKING_POLICY_INCLUDE_SET:
        {
                const enum lttng_process_attr_values_status values_status =
-                               lttng_process_attr_values_get_count(
-                                               values, &pid_count);
+                       lttng_process_attr_values_get_count(values, &pid_count);
 
                if (values_status != LTTNG_PROCESS_ATTR_VALUES_STATUS_OK) {
                        ret_code = LTTNG_ERR_UNK;
@@ -789,8 +743,7 @@ int lttng_list_tracker_pids(struct lttng_handle *handle,
        for (i = 0; i < pid_count; i++) {
                pid_t pid;
                const enum lttng_process_attr_values_status values_status =
-                               lttng_process_attr_values_get_pid_at_index(
-                                               values, i, &pid);
+                       lttng_process_attr_values_get_pid_at_index(values, i, &pid);
 
                if (values_status != LTTNG_PROCESS_ATTR_VALUES_STATUS_OK) {
                        ret_code = LTTNG_ERR_UNK;
@@ -800,7 +753,7 @@ int lttng_list_tracker_pids(struct lttng_handle *handle,
        }
        *_nr_pids = (size_t) pid_count;
        *_pids = pid_array;
-       pid_array = NULL;
+       pid_array = nullptr;
 end:
        lttng_process_attr_tracker_handle_destroy(tracker_handle);
        free(pid_array);
diff --git a/src/vendor/.clang-tidy b/src/vendor/.clang-tidy
new file mode 100644 (file)
index 0000000..b298fbc
--- /dev/null
@@ -0,0 +1,8 @@
+# clang-tidy uses the closest .clang-tidy in a parent directory
+# to override settings.
+#
+# Add a dummy check since we can't disable them all without
+# clang-tidy complaining. This ensures that generated code
+# is not flagged.
+
+Checks: '-*,llvm-twine-local'
index 93cf91d1b584513d334c2a5934215c9afba59704..e8b7a8159917f41acf6f4615f7ba6552958745d4 100644 (file)
@@ -2,4 +2,4 @@
 
 SUBDIRS = msgpack
 
-EXTRA_DIST = optional.hpp fmt
+EXTRA_DIST = optional.hpp fmt nlohmann
index 9a8e4ed2cebb84c65b32633fcf82eb7cc6f92990..a3966d1407198da8f3058b086ed403addb556b2e 100644 (file)
@@ -95,10 +95,10 @@ class dynamic_format_arg_store
   };
 
   template <typename T>
-  using stored_type = conditional_t<detail::is_string<T>::value &&
-                                        !has_formatter<T, Context>::value &&
-                                        !detail::is_reference_wrapper<T>::value,
-                                    std::basic_string<char_type>, T>;
+  using stored_type = conditional_t<
+      std::is_convertible<T, std::basic_string<char_type>>::value &&
+          !detail::is_reference_wrapper<T>::value,
+      std::basic_string<char_type>, T>;
 
   // Storage of basic_format_arg must be contiguous.
   std::vector<basic_format_arg<Context>> data_;
index 682efd8d21b1464dd40a641ba8096f8f2c915197..b112f76e991c32d59e36b1c4586bbd26aa23bc79 100644 (file)
@@ -10,6 +10,8 @@
 
 #include <algorithm>
 #include <chrono>
+#include <cmath>    // std::isfinite
+#include <cstring>  // std::memcpy
 #include <ctime>
 #include <iterator>
 #include <locale>
@@ -201,7 +203,7 @@ To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
     }
     const auto min1 =
         (std::numeric_limits<IntermediateRep>::min)() / Factor::num;
-    if (count < min1) {
+    if (!std::is_unsigned<IntermediateRep>::value && count < min1) {
       ec = 1;
       return {};
     }
@@ -321,14 +323,13 @@ constexpr const size_t codecvt_result<CodeUnit>::max_size;
 template <typename CodeUnit>
 void write_codecvt(codecvt_result<CodeUnit>& out, string_view in_buf,
                    const std::locale& loc) {
-  using codecvt = std::codecvt<CodeUnit, char, std::mbstate_t>;
 #if FMT_CLANG_VERSION
 #  pragma clang diagnostic push
 #  pragma clang diagnostic ignored "-Wdeprecated"
-  auto& f = std::use_facet<codecvt>(loc);
+  auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
 #  pragma clang diagnostic pop
 #else
-  auto& f = std::use_facet<codecvt>(loc);
+  auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
 #endif
   auto mb = std::mbstate_t();
   const char* from_next = nullptr;
@@ -344,7 +345,7 @@ auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)
   if (detail::is_utf8() && loc != get_classic_locale()) {
     // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
     // gcc-4.
-#if FMT_MSC_VER != 0 || \
+#if FMT_MSC_VERSION != 0 || \
     (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI))
     // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
     // and newer.
@@ -468,7 +469,7 @@ inline std::tm localtime(std::time_t time) {
 
     bool fallback(int res) { return res == 0; }
 
-#if !FMT_MSC_VER
+#if !FMT_MSC_VERSION
     bool fallback(detail::null<>) {
       using namespace fmt::detail;
       std::tm* tm = std::localtime(&time_);
@@ -514,7 +515,7 @@ inline std::tm gmtime(std::time_t time) {
 
     bool fallback(int res) { return res == 0; }
 
-#if !FMT_MSC_VER
+#if !FMT_MSC_VERSION
     bool fallback(detail::null<>) {
       std::tm* tm = std::gmtime(&time_);
       if (tm) tm_ = *tm;
@@ -562,10 +563,10 @@ inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
   constexpr const size_t len = 8;
   if (const_check(is_big_endian())) {
     char tmp[len];
-    memcpy(tmp, &digits, len);
+    std::memcpy(tmp, &digits, len);
     std::reverse_copy(tmp, tmp + len, buf);
   } else {
-    memcpy(buf, &digits, len);
+    std::memcpy(buf, &digits, len);
   }
 }
 
@@ -1214,7 +1215,7 @@ template <typename OutputIt, typename Char> class tm_writer {
     char buf[10];
     size_t offset = 0;
     if (year >= 0 && year < 10000) {
-      copy2(buf, digits2(to_unsigned(year / 100)));
+      copy2(buf, digits2(static_cast<size_t>(year / 100)));
     } else {
       offset = 4;
       write_year_extended(year);
@@ -1387,15 +1388,6 @@ struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
   FMT_CONSTEXPR void on_duration_unit() {}
 };
 
-template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
-inline bool isnan(T) {
-  return false;
-}
-template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
-inline bool isnan(T value) {
-  return std::isnan(value);
-}
-
 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
 inline bool isfinite(T) {
   return true;
@@ -1404,7 +1396,8 @@ inline bool isfinite(T) {
 // Converts value to Int and checks that it's in the range [0, upper).
 template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
 inline Int to_nonnegative_int(T value, Int upper) {
-  FMT_ASSERT(value >= 0 && to_unsigned(value) <= to_unsigned(upper),
+  FMT_ASSERT(std::is_unsigned<Int>::value ||
+             (value >= 0 && to_unsigned(value) <= to_unsigned(upper)),
              "invalid value");
   (void)upper;
   return static_cast<Int>(value);
@@ -1470,14 +1463,22 @@ inline std::chrono::duration<Rep, std::milli> get_milliseconds(
 #endif
 }
 
-// Returns the number of fractional digits in the range [0, 18] according to the
+// Counts the number of fractional digits in the range [0, 18] according to the
 // C++20 spec. If more than 18 fractional digits are required then returns 6 for
 // microseconds precision.
-constexpr int count_fractional_digits(long long num, long long den, int n = 0) {
-  return num % den == 0
-             ? n
-             : (n > 18 ? 6 : count_fractional_digits(num * 10, den, n + 1));
-}
+template <long long Num, long long Den, int N = 0,
+          bool Enabled = (N < 19) && (Num <= max_value<long long>() / 10)>
+struct count_fractional_digits {
+  static constexpr int value =
+      Num % Den == 0 ? N : count_fractional_digits<Num * 10, Den, N + 1>::value;
+};
+
+// Base case that doesn't instantiate any more templates
+// in order to avoid overflow.
+template <long long Num, long long Den, int N>
+struct count_fractional_digits<Num, Den, N, false> {
+  static constexpr int value = (Num % Den == 0) ? N : 6;
+};
 
 constexpr long long pow10(std::uint32_t n) {
   return n == 0 ? 1 : 10 * pow10(n - 1);
@@ -1663,9 +1664,11 @@ struct chrono_formatter {
     out = format_decimal<char_type>(out, n, num_digits).end;
   }
 
-  template <class Duration> void write_fractional_seconds(Duration d) {
+  template <typename Duration> void write_fractional_seconds(Duration d) {
+    FMT_ASSERT(!std::is_floating_point<typename Duration::rep>::value, "");
     constexpr auto num_fractional_digits =
-        count_fractional_digits(Duration::period::num, Duration::period::den);
+        count_fractional_digits<Duration::period::num,
+                                Duration::period::den>::value;
 
     using subsecond_precision = std::chrono::duration<
         typename std::common_type<typename Duration::rep,
@@ -1674,12 +1677,9 @@ struct chrono_formatter {
     if (std::ratio_less<typename subsecond_precision::period,
                         std::chrono::seconds::period>::value) {
       *out++ = '.';
-      // Don't convert long double to integer seconds to avoid overflow.
-      using sec = conditional_t<
-          std::is_same<typename Duration::rep, long double>::value,
-          std::chrono::duration<long double>, std::chrono::seconds>;
-      auto fractional = detail::abs(d) - std::chrono::duration_cast<sec>(d);
-      const auto subseconds =
+      auto fractional =
+          detail::abs(d) - std::chrono::duration_cast<std::chrono::seconds>(d);
+      auto subseconds =
           std::chrono::treat_as_floating_point<
               typename subsecond_precision::rep>::value
               ? fractional.count()
@@ -1770,8 +1770,22 @@ struct chrono_formatter {
     if (handle_nan_inf()) return;
 
     if (ns == numeric_system::standard) {
-      write(second(), 2);
-      write_fractional_seconds(std::chrono::duration<rep, Period>{val});
+      if (std::is_floating_point<rep>::value) {
+        constexpr auto num_fractional_digits =
+            count_fractional_digits<Period::num, Period::den>::value;
+        auto buf = memory_buffer();
+        format_to(std::back_inserter(buf), runtime("{:.{}f}"),
+                  std::fmod(val * static_cast<rep>(Period::num) /
+                                static_cast<rep>(Period::den),
+                            static_cast<rep>(60)),
+                  num_fractional_digits);
+        if (negative) *out++ = '-';
+        if (buf.size() < 2 || buf[1] == '.') *out++ = '0';
+        out = std::copy(buf.begin(), buf.end(), out);
+      } else {
+        write(second(), 2);
+        write_fractional_seconds(std::chrono::duration<rep, Period>(val));
+      }
       return;
     }
     auto time = tm();
@@ -1988,13 +2002,9 @@ template <typename Char, typename Duration>
 struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
                  Char> : formatter<std::tm, Char> {
   FMT_CONSTEXPR formatter() {
-    this->do_parse(default_specs,
-                   default_specs + sizeof(default_specs) / sizeof(Char));
-  }
-
-  template <typename ParseContext>
-  FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
-    return this->do_parse(ctx.begin(), ctx.end(), true);
+    basic_string_view<Char> default_specs =
+        detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>{};
+    this->do_parse(default_specs.begin(), default_specs.end());
   }
 
   template <typename FormatContext>
@@ -2002,15 +2012,8 @@ struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
               FormatContext& ctx) const -> decltype(ctx.out()) {
     return formatter<std::tm, Char>::format(localtime(val), ctx);
   }
-
-  static constexpr const Char default_specs[] = {'%', 'F', ' ', '%', 'T'};
 };
 
-template <typename Char, typename Duration>
-constexpr const Char
-    formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
-              Char>::default_specs[];
-
 template <typename Char> struct formatter<std::tm, Char> {
  private:
   enum class spec {
@@ -2022,13 +2025,18 @@ template <typename Char> struct formatter<std::tm, Char> {
   basic_string_view<Char> specs;
 
  protected:
-  template <typename It>
-  FMT_CONSTEXPR auto do_parse(It begin, It end, bool with_default = false)
-      -> It {
+  template <typename It> FMT_CONSTEXPR auto do_parse(It begin, It end) -> It {
     if (begin != end && *begin == ':') ++begin;
     end = detail::parse_chrono_format(begin, end, detail::tm_format_checker());
-    if (!with_default || end != begin)
-      specs = {begin, detail::to_unsigned(end - begin)};
+    // Replace default spec only if the new spec is not empty.
+    if (end != begin) specs = {begin, detail::to_unsigned(end - begin)};
+    return end;
+  }
+
+ public:
+  FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
+      -> decltype(ctx.begin()) {
+    auto end = this->do_parse(ctx.begin(), ctx.end());
     // basic_string_view<>::compare isn't constexpr before C++17.
     if (specs.size() == 2 && specs[0] == Char('%')) {
       if (specs[1] == Char('F'))
@@ -2039,12 +2047,6 @@ template <typename Char> struct formatter<std::tm, Char> {
     return end;
   }
 
- public:
-  template <typename ParseContext>
-  FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
-    return this->do_parse(ctx.begin(), ctx.end());
-  }
-
   template <typename FormatContext>
   auto format(const std::tm& tm, FormatContext& ctx) const
       -> decltype(ctx.out()) {
index dfbe482938e7e655af996ecfb293af6959114044..4c163277ef1882075491efb0079f0bf08aa45c33 100644 (file)
 
 #include "format.h"
 
-// __declspec(deprecated) is broken in some MSVC versions.
-#if FMT_MSC_VER
-#  define FMT_DEPRECATED_NONMSVC
-#else
-#  define FMT_DEPRECATED_NONMSVC FMT_DEPRECATED
-#endif
-
 FMT_BEGIN_NAMESPACE
 FMT_MODULE_EXPORT_BEGIN
 
@@ -214,17 +207,16 @@ FMT_BEGIN_DETAIL_NAMESPACE
 
 // color is a struct of either a rgb color or a terminal color.
 struct color_type {
-  FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
-  FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
-                                                           value{} {
+  FMT_CONSTEXPR color_type() noexcept : is_rgb(), value{} {}
+  FMT_CONSTEXPR color_type(color rgb_color) noexcept : is_rgb(true), value{} {
     value.rgb_color = static_cast<uint32_t>(rgb_color);
   }
-  FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
+  FMT_CONSTEXPR color_type(rgb rgb_color) noexcept : is_rgb(true), value{} {
     value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
                       (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
   }
-  FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
-                                                                     value{} {
+  FMT_CONSTEXPR color_type(terminal_color term_color) noexcept
+      : is_rgb(), value{} {
     value.term_color = static_cast<uint8_t>(term_color);
   }
   bool is_rgb;
@@ -239,10 +231,8 @@ FMT_END_DETAIL_NAMESPACE
 /** A text style consisting of foreground and background colors and emphasis. */
 class text_style {
  public:
-  FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT
-      : set_foreground_color(),
-        set_background_color(),
-        ems(em) {}
+  FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept
+      : set_foreground_color(), set_background_color(), ems(em) {}
 
   FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) {
     if (!set_foreground_color) {
@@ -273,44 +263,32 @@ class text_style {
     return lhs |= rhs;
   }
 
-  FMT_DEPRECATED_NONMSVC FMT_CONSTEXPR text_style& operator&=(
-      const text_style& rhs) {
-    return and_assign(rhs);
-  }
-
-  FMT_DEPRECATED_NONMSVC friend FMT_CONSTEXPR text_style
-  operator&(text_style lhs, const text_style& rhs) {
-    return lhs.and_assign(rhs);
-  }
-
-  FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR bool has_foreground() const noexcept {
     return set_foreground_color;
   }
-  FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR bool has_background() const noexcept {
     return set_background_color;
   }
-  FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR bool has_emphasis() const noexcept {
     return static_cast<uint8_t>(ems) != 0;
   }
-  FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR detail::color_type get_foreground() const noexcept {
     FMT_ASSERT(has_foreground(), "no foreground specified for this style");
     return foreground_color;
   }
-  FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR detail::color_type get_background() const noexcept {
     FMT_ASSERT(has_background(), "no background specified for this style");
     return background_color;
   }
-  FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR emphasis get_emphasis() const noexcept {
     FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
     return ems;
   }
 
  private:
   FMT_CONSTEXPR text_style(bool is_foreground,
-                           detail::color_type text_color) FMT_NOEXCEPT
-      : set_foreground_color(),
-        set_background_color(),
-        ems() {
+                           detail::color_type text_color) noexcept
+      : set_foreground_color(), set_background_color(), ems() {
     if (is_foreground) {
       foreground_color = text_color;
       set_foreground_color = true;
@@ -320,36 +298,9 @@ class text_style {
     }
   }
 
-  // DEPRECATED!
-  FMT_CONSTEXPR text_style& and_assign(const text_style& rhs) {
-    if (!set_foreground_color) {
-      set_foreground_color = rhs.set_foreground_color;
-      foreground_color = rhs.foreground_color;
-    } else if (rhs.set_foreground_color) {
-      if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
-        FMT_THROW(format_error("can't AND a terminal color"));
-      foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color;
-    }
-
-    if (!set_background_color) {
-      set_background_color = rhs.set_background_color;
-      background_color = rhs.background_color;
-    } else if (rhs.set_background_color) {
-      if (!background_color.is_rgb || !rhs.background_color.is_rgb)
-        FMT_THROW(format_error("can't AND a terminal color"));
-      background_color.value.rgb_color &= rhs.background_color.value.rgb_color;
-    }
-
-    ems = static_cast<emphasis>(static_cast<uint8_t>(ems) &
-                                static_cast<uint8_t>(rhs.ems));
-    return *this;
-  }
-
-  friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground)
-      FMT_NOEXCEPT;
+  friend FMT_CONSTEXPR text_style fg(detail::color_type foreground) noexcept;
 
-  friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background)
-      FMT_NOEXCEPT;
+  friend FMT_CONSTEXPR text_style bg(detail::color_type background) noexcept;
 
   detail::color_type foreground_color;
   detail::color_type background_color;
@@ -359,17 +310,16 @@ class text_style {
 };
 
 /** Creates a text style from the foreground (text) color. */
-FMT_CONSTEXPR inline text_style fg(detail::color_type foreground) FMT_NOEXCEPT {
+FMT_CONSTEXPR inline text_style fg(detail::color_type foreground) noexcept {
   return text_style(true, foreground);
 }
 
 /** Creates a text style from the background color. */
-FMT_CONSTEXPR inline text_style bg(detail::color_type background) FMT_NOEXCEPT {
+FMT_CONSTEXPR inline text_style bg(detail::color_type background) noexcept {
   return text_style(false, background);
 }
 
-FMT_CONSTEXPR inline text_style operator|(emphasis lhs,
-                                          emphasis rhs) FMT_NOEXCEPT {
+FMT_CONSTEXPR inline text_style operator|(emphasis lhs, emphasis rhs) noexcept {
   return text_style(lhs) | rhs;
 }
 
@@ -377,7 +327,7 @@ FMT_BEGIN_DETAIL_NAMESPACE
 
 template <typename Char> struct ansi_color_escape {
   FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color,
-                                  const char* esc) FMT_NOEXCEPT {
+                                  const char* esc) noexcept {
     // If we have a terminal color, we need to output another escape code
     // sequence.
     if (!text_color.is_rgb) {
@@ -412,7 +362,7 @@ template <typename Char> struct ansi_color_escape {
     to_esc(color.b, buffer + 15, 'm');
     buffer[19] = static_cast<Char>(0);
   }
-  FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
+  FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept {
     uint8_t em_codes[num_emphases] = {};
     if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1;
     if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2;
@@ -433,10 +383,10 @@ template <typename Char> struct ansi_color_escape {
     }
     buffer[index++] = static_cast<Char>(0);
   }
-  FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
+  FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; }
 
-  FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
-  FMT_CONSTEXPR_CHAR_TRAITS const Char* end() const FMT_NOEXCEPT {
+  FMT_CONSTEXPR const Char* begin() const noexcept { return buffer; }
+  FMT_CONSTEXPR_CHAR_TRAITS const Char* end() const noexcept {
     return buffer + std::char_traits<Char>::length(buffer);
   }
 
@@ -445,59 +395,64 @@ template <typename Char> struct ansi_color_escape {
   Char buffer[7u + 3u * num_emphases + 1u];
 
   static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
-                                   char delimiter) FMT_NOEXCEPT {
+                                   char delimiter) noexcept {
     out[0] = static_cast<Char>('0' + c / 100);
     out[1] = static_cast<Char>('0' + c / 10 % 10);
     out[2] = static_cast<Char>('0' + c % 10);
     out[3] = static_cast<Char>(delimiter);
   }
-  static FMT_CONSTEXPR bool has_emphasis(emphasis em,
-                                         emphasis mask) FMT_NOEXCEPT {
+  static FMT_CONSTEXPR bool has_emphasis(emphasis em, emphasis mask) noexcept {
     return static_cast<uint8_t>(em) & static_cast<uint8_t>(mask);
   }
 };
 
 template <typename Char>
 FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
-    detail::color_type foreground) FMT_NOEXCEPT {
+    detail::color_type foreground) noexcept {
   return ansi_color_escape<Char>(foreground, "\x1b[38;2;");
 }
 
 template <typename Char>
 FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
-    detail::color_type background) FMT_NOEXCEPT {
+    detail::color_type background) noexcept {
   return ansi_color_escape<Char>(background, "\x1b[48;2;");
 }
 
 template <typename Char>
-FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
+FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) noexcept {
   return ansi_color_escape<Char>(em);
 }
 
-template <typename Char>
-inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
-  std::fputs(chars, stream);
+template <typename Char> inline void fputs(const Char* chars, FILE* stream) {
+  int result = std::fputs(chars, stream);
+  if (result < 0)
+    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
 }
 
-template <>
-inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
-  std::fputws(chars, stream);
+template <> inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) {
+  int result = std::fputws(chars, stream);
+  if (result < 0)
+    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
 }
 
-template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
+template <typename Char> inline void reset_color(FILE* stream) {
   fputs("\x1b[0m", stream);
 }
 
-template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
+template <> inline void reset_color<wchar_t>(FILE* stream) {
   fputs(L"\x1b[0m", stream);
 }
 
-template <typename Char>
-inline void reset_color(buffer<Char>& buffer) FMT_NOEXCEPT {
+template <typename Char> inline void reset_color(buffer<Char>& buffer) {
   auto reset_color = string_view("\x1b[0m");
   buffer.append(reset_color.begin(), reset_color.end());
 }
 
+template <typename T> struct styled_arg {
+  const T& value;
+  text_style style;
+};
+
 template <typename Char>
 void vformat_to(buffer<Char>& buf, const text_style& ts,
                 basic_string_view<Char> format_str,
@@ -528,9 +483,13 @@ template <typename S, typename Char = char_t<S>>
 void vprint(std::FILE* f, const text_style& ts, const S& format,
             basic_format_args<buffer_context<type_identity_t<Char>>> args) {
   basic_memory_buffer<Char> buf;
-  detail::vformat_to(buf, ts, to_string_view(format), args);
-  buf.push_back(Char(0));
-  detail::fputs(buf.data(), f);
+  detail::vformat_to(buf, ts, detail::to_string_view(format), args);
+  if (detail::is_utf8()) {
+    detail::print(f, basic_string_view<Char>(buf.begin(), buf.size()));
+  } else {
+    buf.push_back(Char(0));
+    detail::fputs(buf.data(), f);
+  }
 }
 
 /**
@@ -549,7 +508,7 @@ template <typename S, typename... Args,
 void print(std::FILE* f, const text_style& ts, const S& format_str,
            const Args&... args) {
   vprint(f, ts, format_str,
-         fmt::make_args_checked<Args...>(format_str, args...));
+         fmt::make_format_args<buffer_context<char_t<S>>>(args...));
 }
 
 /**
@@ -574,7 +533,7 @@ inline std::basic_string<Char> vformat(
     const text_style& ts, const S& format_str,
     basic_format_args<buffer_context<type_identity_t<Char>>> args) {
   basic_memory_buffer<Char> buf;
-  detail::vformat_to(buf, ts, to_string_view(format_str), args);
+  detail::vformat_to(buf, ts, detail::to_string_view(format_str), args);
   return fmt::to_string(buf);
 }
 
@@ -593,8 +552,8 @@ inline std::basic_string<Char> vformat(
 template <typename S, typename... Args, typename Char = char_t<S>>
 inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
                                       const Args&... args) {
-  return fmt::vformat(ts, to_string_view(format_str),
-                      fmt::make_args_checked<Args...>(format_str, args...));
+  return fmt::vformat(ts, detail::to_string_view(format_str),
+                      fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 /**
@@ -628,8 +587,62 @@ template <typename OutputIt, typename S, typename... Args,
 inline auto format_to(OutputIt out, const text_style& ts, const S& format_str,
                       Args&&... args) ->
     typename std::enable_if<enable, OutputIt>::type {
-  return vformat_to(out, ts, to_string_view(format_str),
-                    fmt::make_args_checked<Args...>(format_str, args...));
+  return vformat_to(out, ts, detail::to_string_view(format_str),
+                    fmt::make_format_args<buffer_context<char_t<S>>>(args...));
+}
+
+template <typename T, typename Char>
+struct formatter<detail::styled_arg<T>, Char> : formatter<T, Char> {
+  template <typename FormatContext>
+  auto format(const detail::styled_arg<T>& arg, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    const auto& ts = arg.style;
+    const auto& value = arg.value;
+    auto out = ctx.out();
+
+    bool has_style = false;
+    if (ts.has_emphasis()) {
+      has_style = true;
+      auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());
+      out = std::copy(emphasis.begin(), emphasis.end(), out);
+    }
+    if (ts.has_foreground()) {
+      has_style = true;
+      auto foreground =
+          detail::make_foreground_color<Char>(ts.get_foreground());
+      out = std::copy(foreground.begin(), foreground.end(), out);
+    }
+    if (ts.has_background()) {
+      has_style = true;
+      auto background =
+          detail::make_background_color<Char>(ts.get_background());
+      out = std::copy(background.begin(), background.end(), out);
+    }
+    out = formatter<T, Char>::format(value, ctx);
+    if (has_style) {
+      auto reset_color = string_view("\x1b[0m");
+      out = std::copy(reset_color.begin(), reset_color.end(), out);
+    }
+    return out;
+  }
+};
+
+/**
+  \rst
+  Returns an argument that will be formatted using ANSI escape sequences,
+  to be used in a formatting function.
+
+  **Example**::
+
+    fmt::print("Elapsed time: {0:.2f} seconds",
+               fmt::styled(1.23, fmt::fg(fmt::color::green) |
+                                 fmt::bg(fmt::color::blue)));
+  \endrst
+ */
+template <typename T>
+FMT_CONSTEXPR auto styled(const T& value, text_style ts)
+    -> detail::styled_arg<remove_cvref_t<T>> {
+  return detail::styled_arg<remove_cvref_t<T>>{value, ts};
 }
 
 FMT_MODULE_EXPORT_END
index 1dba3ddb5222b15aaef2bcc41eaef8bc0a4647a5..933668c41c3e839df937cd6c67a2f8fffc9f8d87 100644 (file)
 FMT_BEGIN_NAMESPACE
 namespace detail {
 
-// An output iterator that counts the number of objects written to it and
-// discards them.
-class counting_iterator {
- private:
-  size_t count_;
-
- public:
-  using iterator_category = std::output_iterator_tag;
-  using difference_type = std::ptrdiff_t;
-  using pointer = void;
-  using reference = void;
-  using _Unchecked_type = counting_iterator;  // Mark iterator as checked.
-
-  struct value_type {
-    template <typename T> void operator=(const T&) {}
-  };
-
-  counting_iterator() : count_(0) {}
-
-  size_t count() const { return count_; }
-
-  counting_iterator& operator++() {
-    ++count_;
-    return *this;
-  }
-  counting_iterator operator++(int) {
-    auto it = *this;
-    ++*this;
-    return it;
-  }
-
-  friend counting_iterator operator+(counting_iterator it, difference_type n) {
-    it.count_ += static_cast<size_t>(n);
-    return it;
-  }
-
-  value_type operator*() const { return {}; }
-};
-
 template <typename Char, typename InputIt>
-inline counting_iterator copy_str(InputIt begin, InputIt end,
-                                  counting_iterator it) {
+FMT_CONSTEXPR inline counting_iterator copy_str(InputIt begin, InputIt end,
+                                                counting_iterator it) {
   return it + (end - begin);
 }
 
@@ -75,8 +36,7 @@ template <typename OutputIt> class truncating_iterator_base {
   using difference_type = std::ptrdiff_t;
   using pointer = void;
   using reference = void;
-  using _Unchecked_type =
-      truncating_iterator_base;  // Mark iterator as checked.
+  FMT_UNCHECKED_ITERATOR(truncating_iterator_base);
 
   OutputIt base() const { return out_; }
   size_t count() const { return count_; }
@@ -163,12 +123,12 @@ struct is_compiled_string : std::is_base_of<compiled_string, S> {};
 #  define FMT_COMPILE(s) FMT_STRING(s)
 #endif
 
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
 template <typename Char, size_t N,
           fmt::detail_exported::fixed_string<Char, N> Str>
 struct udl_compiled_string : compiled_string {
   using char_type = Char;
-  constexpr operator basic_string_view<char_type>() const {
+  explicit constexpr operator basic_string_view<char_type>() const {
     return {Str.data, N - 1};
   }
 };
@@ -377,10 +337,11 @@ template <typename T, typename Char>
 constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
                                                   size_t pos, int next_arg_id) {
   str.remove_prefix(pos);
-  auto ctx = basic_format_parse_context<Char>(str, {}, next_arg_id);
+  auto ctx = compile_parse_context<Char>(str, max_value<int>(), nullptr, {},
+                                         next_arg_id);
   auto f = formatter<T, Char>();
   auto end = f.parse(ctx);
-  return {f, pos + fmt::detail::to_unsigned(end - str.data()) + 1,
+  return {f, pos + fmt::detail::to_unsigned(end - str.data()),
           next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
 }
 
@@ -436,13 +397,20 @@ constexpr auto parse_replacement_field_then_tail(S format_str) {
     return parse_tail<Args, END_POS + 1, NEXT_ID>(
         field<char_type, typename field_type<T>::type, ARG_INDEX>(),
         format_str);
-  } else if constexpr (c == ':') {
+  } else if constexpr (c != ':') {
+    FMT_THROW(format_error("expected ':'"));
+  } else {
     constexpr auto result = parse_specs<typename field_type<T>::type>(
         str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
-    return parse_tail<Args, result.end, result.next_arg_id>(
-        spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
-            result.fmt},
-        format_str);
+    if constexpr (result.end >= str.size() || str[result.end] != '}') {
+      FMT_THROW(format_error("expected '}'"));
+      return 0;
+    } else {
+      return parse_tail<Args, result.end + 1, result.next_arg_id>(
+          spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
+              result.fmt},
+          format_str);
+    }
   }
 }
 
@@ -573,10 +541,11 @@ FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
   constexpr auto compiled = detail::compile<Args...>(S());
   if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
                              detail::unknown_format>()) {
-    return format(static_cast<basic_string_view<typename S::char_type>>(S()),
-                  std::forward<Args>(args)...);
+    return fmt::format(
+        static_cast<basic_string_view<typename S::char_type>>(S()),
+        std::forward<Args>(args)...);
   } else {
-    return format(compiled, std::forward<Args>(args)...);
+    return fmt::format(compiled, std::forward<Args>(args)...);
   }
 }
 
@@ -586,11 +555,11 @@ FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
   constexpr auto compiled = detail::compile<Args...>(S());
   if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
                              detail::unknown_format>()) {
-    return format_to(out,
-                     static_cast<basic_string_view<typename S::char_type>>(S()),
-                     std::forward<Args>(args)...);
+    return fmt::format_to(
+        out, static_cast<basic_string_view<typename S::char_type>>(S()),
+        std::forward<Args>(args)...);
   } else {
-    return format_to(out, compiled, std::forward<Args>(args)...);
+    return fmt::format_to(out, compiled, std::forward<Args>(args)...);
   }
 }
 #endif
@@ -599,22 +568,24 @@ template <typename OutputIt, typename S, typename... Args,
           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
 format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n,
                                          const S& format_str, Args&&... args) {
-  auto it = format_to(detail::truncating_iterator<OutputIt>(out, n), format_str,
-                      std::forward<Args>(args)...);
+  auto it = fmt::format_to(detail::truncating_iterator<OutputIt>(out, n),
+                           format_str, std::forward<Args>(args)...);
   return {it.base(), it.count()};
 }
 
 template <typename S, typename... Args,
           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
-size_t formatted_size(const S& format_str, const Args&... args) {
-  return format_to(detail::counting_iterator(), format_str, args...).count();
+FMT_CONSTEXPR20 size_t formatted_size(const S& format_str,
+                                      const Args&... args) {
+  return fmt::format_to(detail::counting_iterator(), format_str, args...)
+      .count();
 }
 
 template <typename S, typename... Args,
           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
 void print(std::FILE* f, const S& format_str, const Args&... args) {
   memory_buffer buffer;
-  format_to(std::back_inserter(buffer), format_str, args...);
+  fmt::format_to(std::back_inserter(buffer), format_str, args...);
   detail::print(f, {buffer.data(), buffer.size()});
 }
 
@@ -624,14 +595,12 @@ void print(const S& format_str, const Args&... args) {
   print(stdout, format_str, args...);
 }
 
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
 inline namespace literals {
-template <detail_exported::fixed_string Str>
-constexpr detail::udl_compiled_string<
-    remove_cvref_t<decltype(Str.data[0])>,
-    sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str>
-operator""_cf() {
-  return {};
+template <detail_exported::fixed_string Str> constexpr auto operator""_cf() {
+  using char_t = remove_cvref_t<decltype(Str.data[0])>;
+  return detail::udl_compiled_string<char_t, sizeof(Str.data) / sizeof(char_t),
+                                     Str>();
 }
 }  // namespace literals
 #endif
index 92a7aa1df69ba84553c987c591a1bac1ec187c88..2eff064cd363756bc63e5018fdc73f75da04f0a4 100644 (file)
 
 #include <cstddef>  // std::byte
 #include <cstdio>   // std::FILE
-#include <cstring>
+#include <cstring>  // std::strlen
 #include <iterator>
 #include <limits>
 #include <string>
 #include <type_traits>
 
 // The fmt library version in the form major * 10000 + minor * 100 + patch.
-#define FMT_VERSION 80101
+#define FMT_VERSION 90100
 
 #if defined(__clang__) && !defined(__ibmxl__)
 #  define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
 #  define FMT_ICC_VERSION 0
 #endif
 
-#ifdef __NVCC__
-#  define FMT_NVCC __NVCC__
-#else
-#  define FMT_NVCC 0
-#endif
-
 #ifdef _MSC_VER
-#  define FMT_MSC_VER _MSC_VER
+#  define FMT_MSC_VERSION _MSC_VER
 #  define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
 #else
-#  define FMT_MSC_VER 0
+#  define FMT_MSC_VERSION 0
 #  define FMT_MSC_WARNING(...)
 #endif
 
+#ifdef _MSVC_LANG
+#  define FMT_CPLUSPLUS _MSVC_LANG
+#else
+#  define FMT_CPLUSPLUS __cplusplus
+#endif
+
 #ifdef __has_feature
 #  define FMT_HAS_FEATURE(x) __has_feature(x)
 #else
 #  define FMT_HAS_FEATURE(x) 0
 #endif
 
-#if defined(__has_include) &&                             \
-    (!defined(__INTELLISENSE__) || FMT_MSC_VER > 1900) && \
-    (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600)
+#if (defined(__has_include) || FMT_ICC_VERSION >= 1600 || \
+     FMT_MSC_VERSION > 1900) &&                           \
+    !defined(__INTELLISENSE__)
 #  define FMT_HAS_INCLUDE(x) __has_include(x)
 #else
 #  define FMT_HAS_INCLUDE(x) 0
 #  define FMT_HAS_CPP_ATTRIBUTE(x) 0
 #endif
 
-#ifdef _MSVC_LANG
-#  define FMT_CPLUSPLUS _MSVC_LANG
-#else
-#  define FMT_CPLUSPLUS __cplusplus
-#endif
-
 #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
   (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
 
 // Check if relaxed C++14 constexpr is supported.
 // GCC doesn't allow throw in constexpr until version 6 (bug 67371).
 #ifndef FMT_USE_CONSTEXPR
-#  define FMT_USE_CONSTEXPR                                           \
-    (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1912 || \
-     (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) &&           \
-        !FMT_NVCC && !FMT_ICC_VERSION
+#  if (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 || \
+       (FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L)) &&             \
+      !FMT_ICC_VERSION && !defined(__NVCC__)
+#    define FMT_USE_CONSTEXPR 1
+#  else
+#    define FMT_USE_CONSTEXPR 0
+#  endif
 #endif
 #if FMT_USE_CONSTEXPR
 #  define FMT_CONSTEXPR constexpr
-#  define FMT_CONSTEXPR_DECL constexpr
 #else
 #  define FMT_CONSTEXPR
-#  define FMT_CONSTEXPR_DECL
 #endif
 
-#if ((__cplusplus >= 202002L) &&                              \
+#if ((FMT_CPLUSPLUS >= 202002L) &&                            \
      (!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE > 9)) || \
-    (__cplusplus >= 201709L && FMT_GCC_VERSION >= 1002)
+    (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)
 #  define FMT_CONSTEXPR20 constexpr
 #else
 #  define FMT_CONSTEXPR20
 #endif
 
-// Check if constexpr std::char_traits<>::compare,length is supported.
+// Check if constexpr std::char_traits<>::{compare,length} are supported.
 #if defined(__GLIBCXX__)
-#  if __cplusplus >= 201703L && defined(_GLIBCXX_RELEASE) && \
+#  if FMT_CPLUSPLUS >= 201703L && defined(_GLIBCXX_RELEASE) && \
       _GLIBCXX_RELEASE >= 7  // GCC 7+ libstdc++ has _GLIBCXX_RELEASE.
 #    define FMT_CONSTEXPR_CHAR_TRAITS constexpr
 #  endif
-#elif defined(_LIBCPP_VERSION) && __cplusplus >= 201703L && \
+#elif defined(_LIBCPP_VERSION) && FMT_CPLUSPLUS >= 201703L && \
     _LIBCPP_VERSION >= 4000
 #  define FMT_CONSTEXPR_CHAR_TRAITS constexpr
-#elif FMT_MSC_VER >= 1914 && _MSVC_LANG >= 201703L
+#elif FMT_MSC_VERSION >= 1914 && FMT_CPLUSPLUS >= 201703L
 #  define FMT_CONSTEXPR_CHAR_TRAITS constexpr
 #endif
 #ifndef FMT_CONSTEXPR_CHAR_TRAITS
 // Check if exceptions are disabled.
 #ifndef FMT_EXCEPTIONS
 #  if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
-      FMT_MSC_VER && !_HAS_EXCEPTIONS
+      (FMT_MSC_VERSION && !_HAS_EXCEPTIONS)
 #    define FMT_EXCEPTIONS 0
 #  else
 #    define FMT_EXCEPTIONS 1
 #  endif
 #endif
 
-// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
-#ifndef FMT_USE_NOEXCEPT
-#  define FMT_USE_NOEXCEPT 0
-#endif
-
-#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
-    FMT_GCC_VERSION >= 408 || FMT_MSC_VER >= 1900
-#  define FMT_DETECTED_NOEXCEPT noexcept
-#  define FMT_HAS_CXX11_NOEXCEPT 1
-#else
-#  define FMT_DETECTED_NOEXCEPT throw()
-#  define FMT_HAS_CXX11_NOEXCEPT 0
-#endif
-
-#ifndef FMT_NOEXCEPT
-#  if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
-#    define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
+#ifndef FMT_DEPRECATED
+#  if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VERSION >= 1900
+#    define FMT_DEPRECATED [[deprecated]]
 #  else
-#    define FMT_NOEXCEPT
+#    if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
+#      define FMT_DEPRECATED __attribute__((deprecated))
+#    elif FMT_MSC_VERSION
+#      define FMT_DEPRECATED __declspec(deprecated)
+#    else
+#      define FMT_DEPRECATED /* deprecated */
+#    endif
 #  endif
 #endif
 
 // [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
 // warnings.
-#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \
-    !FMT_NVCC
+#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \
+    !defined(__NVCC__)
 #  define FMT_NORETURN [[noreturn]]
 #else
 #  define FMT_NORETURN
 #endif
 
-#if __cplusplus == 201103L || __cplusplus == 201402L
-#  if defined(__INTEL_COMPILER) || defined(__PGI)
-#    define FMT_FALLTHROUGH
-#  elif defined(__clang__)
-#    define FMT_FALLTHROUGH [[clang::fallthrough]]
-#  elif FMT_GCC_VERSION >= 700 && \
-      (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
-#    define FMT_FALLTHROUGH [[gnu::fallthrough]]
-#  else
-#    define FMT_FALLTHROUGH
-#  endif
-#elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
+#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
 #  define FMT_FALLTHROUGH [[fallthrough]]
+#elif defined(__clang__)
+#  define FMT_FALLTHROUGH [[clang::fallthrough]]
+#elif FMT_GCC_VERSION >= 700 && \
+    (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
+#  define FMT_FALLTHROUGH [[gnu::fallthrough]]
 #else
 #  define FMT_FALLTHROUGH
 #endif
 #  endif
 #endif
 
-#ifndef FMT_DEPRECATED
-#  if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900
-#    define FMT_DEPRECATED [[deprecated]]
-#  else
-#    if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
-#      define FMT_DEPRECATED __attribute__((deprecated))
-#    elif FMT_MSC_VER
-#      define FMT_DEPRECATED __declspec(deprecated)
-#    else
-#      define FMT_DEPRECATED /* deprecated */
-#    endif
-#  endif
+// An inline std::forward replacement.
+#define FMT_FORWARD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
+
+#ifdef _MSC_VER
+#  define FMT_UNCHECKED_ITERATOR(It) \
+    using _Unchecked_type = It  // Mark iterator as checked.
+#else
+#  define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It
 #endif
 
 #ifndef FMT_BEGIN_NAMESPACE
 #  define FMT_BEGIN_NAMESPACE \
     namespace fmt {           \
-    inline namespace v8 {
+    inline namespace v9 {
 #  define FMT_END_NAMESPACE \
     }                       \
     }
 #endif
 
 // libc++ supports string_view in pre-c++17.
-#if (FMT_HAS_INCLUDE(<string_view>) &&                       \
-     (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
-    (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
+#if FMT_HAS_INCLUDE(<string_view>) && \
+    (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))
 #  include <string_view>
 #  define FMT_USE_STRING_VIEW
-#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
+#elif FMT_HAS_INCLUDE("experimental/string_view") && FMT_CPLUSPLUS >= 201402L
 #  include <experimental/string_view>
 #  define FMT_USE_EXPERIMENTAL_STRING_VIEW
 #endif
 
 #ifndef FMT_UNICODE
-#  define FMT_UNICODE !FMT_MSC_VER
+#  define FMT_UNICODE !FMT_MSC_VERSION
 #endif
 
 #ifndef FMT_CONSTEVAL
-#  if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) &&      \
-       __cplusplus > 201703L && !defined(__apple_build_version__)) || \
-      (defined(__cpp_consteval) &&                                    \
-       (!FMT_MSC_VER || _MSC_FULL_VER >= 193030704))
+#  if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) &&         \
+       FMT_CPLUSPLUS >= 202002L && !defined(__apple_build_version__)) || \
+      (defined(__cpp_consteval) &&                                       \
+       (!FMT_MSC_VERSION || _MSC_FULL_VER >= 193030704))
 // consteval is broken in MSVC before VS2022 and Apple clang 13.
 #    define FMT_CONSTEVAL consteval
 #    define FMT_HAS_CONSTEVAL
 #  endif
 #endif
 
-#ifndef FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
-#  if defined(__cpp_nontype_template_args) &&                \
-      ((FMT_GCC_VERSION >= 903 && __cplusplus >= 201709L) || \
-       __cpp_nontype_template_args >= 201911L)
-#    define FMT_USE_NONTYPE_TEMPLATE_PARAMETERS 1
+#ifndef FMT_USE_NONTYPE_TEMPLATE_ARGS
+#  if defined(__cpp_nontype_template_args) &&                  \
+      ((FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L) || \
+       __cpp_nontype_template_args >= 201911L) &&              \
+      !defined(__NVCOMPILER)
+#    define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
 #  else
-#    define FMT_USE_NONTYPE_TEMPLATE_PARAMETERS 0
+#    define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
 #  endif
 #endif
 
 // Enable minimal optimizations for more compact code in debug mode.
 FMT_GCC_PRAGMA("GCC push_options")
-#ifndef __OPTIMIZE__
+#if !defined(__OPTIMIZE__) && !defined(__NVCOMPILER)
 FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
 #endif
 
@@ -330,6 +307,20 @@ template <typename T>
 using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
 template <typename T> struct type_identity { using type = T; };
 template <typename T> using type_identity_t = typename type_identity<T>::type;
+template <typename T>
+using underlying_t = typename std::underlying_type<T>::type;
+
+template <typename...> struct disjunction : std::false_type {};
+template <typename P> struct disjunction<P> : P {};
+template <typename P1, typename... Pn>
+struct disjunction<P1, Pn...>
+    : conditional_t<bool(P1::value), P1, disjunction<Pn...>> {};
+
+template <typename...> struct conjunction : std::true_type {};
+template <typename P> struct conjunction<P> : P {};
+template <typename P1, typename... Pn>
+struct conjunction<P1, Pn...>
+    : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};
 
 struct monostate {
   constexpr monostate() {}
@@ -346,13 +337,13 @@ struct monostate {
 
 FMT_BEGIN_DETAIL_NAMESPACE
 
-// Suppress "unused variable" warnings with the method described in
+// Suppresses "unused variable" warnings with the method described in
 // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
 // (void)var does not work on many Intel compilers.
 template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
 
-constexpr FMT_INLINE auto is_constant_evaluated(bool default_value = false)
-    FMT_NOEXCEPT -> bool {
+constexpr FMT_INLINE auto is_constant_evaluated(
+    bool default_value = false) noexcept -> bool {
 #ifdef __cpp_lib_is_constant_evaluated
   ignore_unused(default_value);
   return std::is_constant_evaluated();
@@ -361,7 +352,7 @@ constexpr FMT_INLINE auto is_constant_evaluated(bool default_value = false)
 #endif
 }
 
-// A function to suppress "conditional expression is constant" warnings.
+// Suppresses "conditional expression is constant" warnings.
 template <typename T> constexpr FMT_INLINE auto const_check(T value) -> T {
   return value;
 }
@@ -371,7 +362,7 @@ FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
 
 #ifndef FMT_ASSERT
 #  ifdef NDEBUG
-// FMT_ASSERT is not empty to avoid -Werror=empty-body.
+// FMT_ASSERT is not empty to avoid -Wempty-body.
 #    define FMT_ASSERT(condition, message) \
       ::fmt::detail::ignore_unused((condition), (message))
 #  else
@@ -382,12 +373,6 @@ FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
 #  endif
 #endif
 
-#ifdef __cpp_lib_byte
-using byte = std::byte;
-#else
-enum class byte : unsigned char {};
-#endif
-
 #if defined(FMT_USE_STRING_VIEW)
 template <typename Char> using std_string_view = std::basic_string_view<Char>;
 #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
@@ -399,11 +384,11 @@ template <typename T> struct std_string_view {};
 
 #ifdef FMT_USE_INT128
 // Do nothing.
-#elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \
-    !(FMT_CLANG_VERSION && FMT_MSC_VER)
+#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
+    !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
 #  define FMT_USE_INT128 1
-using int128_t = __int128_t;
-using uint128_t = __uint128_t;
+using int128_opt = __int128_t;  // An optional native 128-bit integer.
+using uint128_opt = __uint128_t;
 template <typename T> inline auto convert_for_visit(T value) -> T {
   return value;
 }
@@ -411,27 +396,24 @@ template <typename T> inline auto convert_for_visit(T value) -> T {
 #  define FMT_USE_INT128 0
 #endif
 #if !FMT_USE_INT128
-enum class int128_t {};
-enum class uint128_t {};
+enum class int128_opt {};
+enum class uint128_opt {};
 // Reduce template instantiations.
-template <typename T> inline auto convert_for_visit(T) -> monostate {
-  return {};
-}
+template <typename T> auto convert_for_visit(T) -> monostate { return {}; }
 #endif
 
 // Casts a nonnegative integer to unsigned.
 template <typename Int>
 FMT_CONSTEXPR auto to_unsigned(Int value) ->
     typename std::make_unsigned<Int>::type {
-  FMT_ASSERT(value >= 0, "negative value");
+  FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
   return static_cast<typename std::make_unsigned<Int>::type>(value);
 }
 
 FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char micro[] = "\u00B5";
 
 constexpr auto is_utf8() -> bool {
-  // Avoid buggy sign extensions in MSVC's constant evaluation mode.
-  // https://developercommunity.visualstudio.com/t/C-difference-in-behavior-for-unsigned/1233612
+  // Avoid buggy sign extensions in MSVC's constant evaluation mode (#2297).
   using uchar = unsigned char;
   return FMT_UNICODE || (sizeof(micro) == 3 && uchar(micro[0]) == 0xC2 &&
                          uchar(micro[1]) == 0xB5);
@@ -454,12 +436,11 @@ template <typename Char> class basic_string_view {
   using value_type = Char;
   using iterator = const Char*;
 
-  constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {}
+  constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
 
   /** Constructs a string reference object from a C string and a size. */
-  constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
-      : data_(s),
-        size_(count) {}
+  constexpr basic_string_view(const Char* s, size_t count) noexcept
+      : data_(s), size_(count) {}
 
   /**
     \rst
@@ -479,29 +460,28 @@ template <typename Char> class basic_string_view {
   /** Constructs a string reference from a ``std::basic_string`` object. */
   template <typename Traits, typename Alloc>
   FMT_CONSTEXPR basic_string_view(
-      const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT
-      : data_(s.data()),
-        size_(s.size()) {}
+      const std::basic_string<Char, Traits, Alloc>& s) noexcept
+      : data_(s.data()), size_(s.size()) {}
 
   template <typename S, FMT_ENABLE_IF(std::is_same<
                                       S, detail::std_string_view<Char>>::value)>
-  FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
-                                                      size_(s.size()) {}
+  FMT_CONSTEXPR basic_string_view(S s) noexcept
+      : data_(s.data()), size_(s.size()) {}
 
   /** Returns a pointer to the string data. */
-  constexpr auto data() const FMT_NOEXCEPT -> const Char* { return data_; }
+  constexpr auto data() const noexcept -> const Char* { return data_; }
 
   /** Returns the string size. */
-  constexpr auto size() const FMT_NOEXCEPT -> size_t { return size_; }
+  constexpr auto size() const noexcept -> size_t { return size_; }
 
-  constexpr auto begin() const FMT_NOEXCEPT -> iterator { return data_; }
-  constexpr auto end() const FMT_NOEXCEPT -> iterator { return data_ + size_; }
+  constexpr auto begin() const noexcept -> iterator { return data_; }
+  constexpr auto end() const noexcept -> iterator { return data_ + size_; }
 
-  constexpr auto operator[](size_t pos) const FMT_NOEXCEPT -> const Char& {
+  constexpr auto operator[](size_t pos) const noexcept -> const Char& {
     return data_[pos];
   }
 
-  FMT_CONSTEXPR void remove_prefix(size_t n) FMT_NOEXCEPT {
+  FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
     data_ += n;
     size_ -= n;
   }
@@ -543,6 +523,14 @@ using string_view = basic_string_view<char>;
 template <typename T> struct is_char : std::false_type {};
 template <> struct is_char<char> : std::true_type {};
 
+FMT_BEGIN_DETAIL_NAMESPACE
+
+// A base class for compile-time strings.
+struct compile_string {};
+
+template <typename S>
+struct is_compile_string : std::is_base_of<compile_string, S> {};
+
 // Returns a string view of `s`.
 template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
 FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view<Char> {
@@ -559,33 +547,21 @@ constexpr auto to_string_view(basic_string_view<Char> s)
   return s;
 }
 template <typename Char,
-          FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)>
-inline auto to_string_view(detail::std_string_view<Char> s)
-    -> basic_string_view<Char> {
+          FMT_ENABLE_IF(!std::is_empty<std_string_view<Char>>::value)>
+inline auto to_string_view(std_string_view<Char> s) -> basic_string_view<Char> {
   return s;
 }
-
-// A base class for compile-time strings. It is defined in the fmt namespace to
-// make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42).
-struct compile_string {};
-
-template <typename S>
-struct is_compile_string : std::is_base_of<compile_string, S> {};
-
 template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
 constexpr auto to_string_view(const S& s)
     -> basic_string_view<typename S::char_type> {
   return basic_string_view<typename S::char_type>(s);
 }
-
-FMT_BEGIN_DETAIL_NAMESPACE
-
 void to_string_view(...);
-using fmt::to_string_view;
 
 // Specifies whether S is a string type convertible to fmt::basic_string_view.
 // It should be a constexpr function but MSVC 2017 fails to compile it in
 // enable_if and MSVC 2015 fails to compile it as an alias template.
+// ADL invocation of to_string_view is DEPRECATED!
 template <typename S>
 struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
 };
@@ -596,17 +572,60 @@ template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
   using type = typename result::value_type;
 };
 
-// Reports a compile-time error if S is not a valid format string.
-template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
-FMT_INLINE void check_format_string(const S&) {
-#ifdef FMT_ENFORCE_COMPILE_STRING
-  static_assert(is_compile_string<S>::value,
-                "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
-                "FMT_STRING.");
-#endif
+enum class type {
+  none_type,
+  // Integer types should go first,
+  int_type,
+  uint_type,
+  long_long_type,
+  ulong_long_type,
+  int128_type,
+  uint128_type,
+  bool_type,
+  char_type,
+  last_integer_type = char_type,
+  // followed by floating-point types.
+  float_type,
+  double_type,
+  long_double_type,
+  last_numeric_type = long_double_type,
+  cstring_type,
+  string_type,
+  pointer_type,
+  custom_type
+};
+
+// Maps core type T to the corresponding type enum constant.
+template <typename T, typename Char>
+struct type_constant : std::integral_constant<type, type::custom_type> {};
+
+#define FMT_TYPE_CONSTANT(Type, constant) \
+  template <typename Char>                \
+  struct type_constant<Type, Char>        \
+      : std::integral_constant<type, type::constant> {}
+
+FMT_TYPE_CONSTANT(int, int_type);
+FMT_TYPE_CONSTANT(unsigned, uint_type);
+FMT_TYPE_CONSTANT(long long, long_long_type);
+FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
+FMT_TYPE_CONSTANT(int128_opt, int128_type);
+FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
+FMT_TYPE_CONSTANT(bool, bool_type);
+FMT_TYPE_CONSTANT(Char, char_type);
+FMT_TYPE_CONSTANT(float, float_type);
+FMT_TYPE_CONSTANT(double, double_type);
+FMT_TYPE_CONSTANT(long double, long_double_type);
+FMT_TYPE_CONSTANT(const Char*, cstring_type);
+FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
+FMT_TYPE_CONSTANT(const void*, pointer_type);
+
+constexpr bool is_integral_type(type t) {
+  return t > type::none_type && t <= type::last_integer_type;
+}
+
+constexpr bool is_arithmetic_type(type t) {
+  return t > type::none_type && t <= type::last_numeric_type;
 }
-template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
-void check_format_string(S);
 
 FMT_NORETURN FMT_API void throw_format_error(const char* message);
 
@@ -615,7 +634,9 @@ struct error_handler {
   constexpr error_handler(const error_handler&) = default;
 
   // This function is intentionally not constexpr to give a compile-time error.
-  FMT_NORETURN FMT_API void on_error(const char* message);
+  FMT_NORETURN void on_error(const char* message) {
+    throw_format_error(message);
+  }
 };
 FMT_END_DETAIL_NAMESPACE
 
@@ -635,6 +656,8 @@ class basic_format_parse_context : private ErrorHandler {
   basic_string_view<Char> format_str_;
   int next_arg_id_;
 
+  FMT_CONSTEXPR void do_check_arg_id(int id);
+
  public:
   using char_type = Char;
   using iterator = typename basic_string_view<Char>::iterator;
@@ -648,16 +671,14 @@ class basic_format_parse_context : private ErrorHandler {
     Returns an iterator to the beginning of the format string range being
     parsed.
    */
-  constexpr auto begin() const FMT_NOEXCEPT -> iterator {
+  constexpr auto begin() const noexcept -> iterator {
     return format_str_.begin();
   }
 
   /**
     Returns an iterator past the end of the format string range being parsed.
    */
-  constexpr auto end() const FMT_NOEXCEPT -> iterator {
-    return format_str_.end();
-  }
+  constexpr auto end() const noexcept -> iterator { return format_str_.end(); }
 
   /** Advances the begin iterator to ``it``. */
   FMT_CONSTEXPR void advance_to(iterator it) {
@@ -669,25 +690,29 @@ class basic_format_parse_context : private ErrorHandler {
     the next argument index and switches to the automatic indexing.
    */
   FMT_CONSTEXPR auto next_arg_id() -> int {
-    // Don't check if the argument id is valid to avoid overhead and because it
-    // will be checked during formatting anyway.
-    if (next_arg_id_ >= 0) return next_arg_id_++;
-    on_error("cannot switch from manual to automatic argument indexing");
-    return 0;
+    if (next_arg_id_ < 0) {
+      on_error("cannot switch from manual to automatic argument indexing");
+      return 0;
+    }
+    int id = next_arg_id_++;
+    do_check_arg_id(id);
+    return id;
   }
 
   /**
     Reports an error if using the automatic argument indexing; otherwise
     switches to the manual indexing.
    */
-  FMT_CONSTEXPR void check_arg_id(int) {
-    if (next_arg_id_ > 0)
+  FMT_CONSTEXPR void check_arg_id(int id) {
+    if (next_arg_id_ > 0) {
       on_error("cannot switch from automatic to manual argument indexing");
-    else
-      next_arg_id_ = -1;
+      return;
+    }
+    next_arg_id_ = -1;
+    do_check_arg_id(id);
   }
-
   FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
+  FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
 
   FMT_CONSTEXPR void on_error(const char* message) {
     ErrorHandler::on_error(message);
@@ -698,6 +723,65 @@ class basic_format_parse_context : private ErrorHandler {
 
 using format_parse_context = basic_format_parse_context<char>;
 
+FMT_BEGIN_DETAIL_NAMESPACE
+// A parse context with extra data used only in compile-time checks.
+template <typename Char, typename ErrorHandler = detail::error_handler>
+class compile_parse_context
+    : public basic_format_parse_context<Char, ErrorHandler> {
+ private:
+  int num_args_;
+  const type* types_;
+  using base = basic_format_parse_context<Char, ErrorHandler>;
+
+ public:
+  explicit FMT_CONSTEXPR compile_parse_context(
+      basic_string_view<Char> format_str, int num_args, const type* types,
+      ErrorHandler eh = {}, int next_arg_id = 0)
+      : base(format_str, eh, next_arg_id), num_args_(num_args), types_(types) {}
+
+  constexpr auto num_args() const -> int { return num_args_; }
+  constexpr auto arg_type(int id) const -> type { return types_[id]; }
+
+  FMT_CONSTEXPR auto next_arg_id() -> int {
+    int id = base::next_arg_id();
+    if (id >= num_args_) this->on_error("argument not found");
+    return id;
+  }
+
+  FMT_CONSTEXPR void check_arg_id(int id) {
+    base::check_arg_id(id);
+    if (id >= num_args_) this->on_error("argument not found");
+  }
+  using base::check_arg_id;
+
+  FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
+    if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
+      this->on_error("width/precision is not integer");
+  }
+};
+FMT_END_DETAIL_NAMESPACE
+
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void
+basic_format_parse_context<Char, ErrorHandler>::do_check_arg_id(int id) {
+  // Argument id is only checked at compile-time during parsing because
+  // formatting has its own validation.
+  if (detail::is_constant_evaluated() && FMT_GCC_VERSION >= 1200) {
+    using context = detail::compile_parse_context<Char, ErrorHandler>;
+    if (id >= static_cast<context*>(this)->num_args())
+      on_error("argument not found");
+  }
+}
+
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void
+basic_format_parse_context<Char, ErrorHandler>::check_dynamic_spec(int arg_id) {
+  if (detail::is_constant_evaluated()) {
+    using context = detail::compile_parse_context<Char, ErrorHandler>;
+    static_cast<context*>(this)->check_dynamic_spec(arg_id);
+  }
+}
+
 template <typename Context> class basic_format_arg;
 template <typename Context> class basic_format_args;
 template <typename Context> class dynamic_format_arg_store;
@@ -744,10 +828,10 @@ constexpr auto has_const_formatter() -> bool {
 template <typename Container>
 inline auto get_container(std::back_insert_iterator<Container> it)
     -> Container& {
-  using bi_iterator = std::back_insert_iterator<Container>;
-  struct accessor : bi_iterator {
-    accessor(bi_iterator iter) : bi_iterator(iter) {}
-    using bi_iterator::container;
+  using base = std::back_insert_iterator<Container>;
+  struct accessor : base {
+    accessor(base b) : base(b) {}
+    using base::container;
   };
   return *accessor(it).container;
 }
@@ -784,18 +868,16 @@ template <typename T> class buffer {
  protected:
   // Don't initialize ptr_ since it is not accessed to save a few cycles.
   FMT_MSC_WARNING(suppress : 26495)
-  buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
+  buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {}
 
-  FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0,
-                         size_t cap = 0) FMT_NOEXCEPT : ptr_(p),
-                                                        size_(sz),
-                                                        capacity_(cap) {}
+  FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept
+      : ptr_(p), size_(sz), capacity_(cap) {}
 
   FMT_CONSTEXPR20 ~buffer() = default;
   buffer(buffer&&) = default;
 
   /** Sets the buffer data and capacity. */
-  FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT {
+  FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
     ptr_ = buf_data;
     capacity_ = buf_capacity;
   }
@@ -810,23 +892,23 @@ template <typename T> class buffer {
   buffer(const buffer&) = delete;
   void operator=(const buffer&) = delete;
 
-  auto begin() FMT_NOEXCEPT -> T* { return ptr_; }
-  auto end() FMT_NOEXCEPT -> T* { return ptr_ + size_; }
+  auto begin() noexcept -> T* { return ptr_; }
+  auto end() noexcept -> T* { return ptr_ + size_; }
 
-  auto begin() const FMT_NOEXCEPT -> const T* { return ptr_; }
-  auto end() const FMT_NOEXCEPT -> const T* { return ptr_ + size_; }
+  auto begin() const noexcept -> const T* { return ptr_; }
+  auto end() const noexcept -> const T* { return ptr_ + size_; }
 
   /** Returns the size of this buffer. */
-  constexpr auto size() const FMT_NOEXCEPT -> size_t { return size_; }
+  constexpr auto size() const noexcept -> size_t { return size_; }
 
   /** Returns the capacity of this buffer. */
-  constexpr auto capacity() const FMT_NOEXCEPT -> size_t { return capacity_; }
+  constexpr auto capacity() const noexcept -> size_t { return capacity_; }
 
   /** Returns a pointer to the buffer data. */
-  FMT_CONSTEXPR auto data() FMT_NOEXCEPT -> T* { return ptr_; }
+  FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
 
   /** Returns a pointer to the buffer data. */
-  FMT_CONSTEXPR auto data() const FMT_NOEXCEPT -> const T* { return ptr_; }
+  FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
 
   /** Clears this buffer. */
   void clear() { size_ = 0; }
@@ -854,11 +936,11 @@ template <typename T> class buffer {
   /** Appends data to the end of the buffer. */
   template <typename U> void append(const U* begin, const U* end);
 
-  template <typename I> FMT_CONSTEXPR auto operator[](I index) -> T& {
+  template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
     return ptr_[index];
   }
-  template <typename I>
-  FMT_CONSTEXPR auto operator[](I index) const -> const T& {
+  template <typename Idx>
+  FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
     return ptr_[index];
   }
 };
@@ -993,6 +1075,7 @@ class iterator_buffer<std::back_insert_iterator<Container>,
       : buffer<typename Container::value_type>(c.size()), container_(c) {}
   explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
       : iterator_buffer(get_container(out)) {}
+
   auto out() -> std::back_insert_iterator<Container> {
     return std::back_inserter(container_);
   }
@@ -1044,7 +1127,11 @@ struct fallback_formatter {
 // Specifies if T has an enabled fallback_formatter specialization.
 template <typename T, typename Char>
 using has_fallback_formatter =
+#ifdef FMT_DEPRECATED_OSTREAM
     std::is_constructible<fallback_formatter<T, Char>>;
+#else
+    std::false_type;
+#endif
 
 struct view {};
 
@@ -1128,61 +1215,6 @@ constexpr auto count_statically_named_args() -> size_t {
   return count<is_statically_named_arg<Args>::value...>();
 }
 
-enum class type {
-  none_type,
-  // Integer types should go first,
-  int_type,
-  uint_type,
-  long_long_type,
-  ulong_long_type,
-  int128_type,
-  uint128_type,
-  bool_type,
-  char_type,
-  last_integer_type = char_type,
-  // followed by floating-point types.
-  float_type,
-  double_type,
-  long_double_type,
-  last_numeric_type = long_double_type,
-  cstring_type,
-  string_type,
-  pointer_type,
-  custom_type
-};
-
-// Maps core type T to the corresponding type enum constant.
-template <typename T, typename Char>
-struct type_constant : std::integral_constant<type, type::custom_type> {};
-
-#define FMT_TYPE_CONSTANT(Type, constant) \
-  template <typename Char>                \
-  struct type_constant<Type, Char>        \
-      : std::integral_constant<type, type::constant> {}
-
-FMT_TYPE_CONSTANT(int, int_type);
-FMT_TYPE_CONSTANT(unsigned, uint_type);
-FMT_TYPE_CONSTANT(long long, long_long_type);
-FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
-FMT_TYPE_CONSTANT(int128_t, int128_type);
-FMT_TYPE_CONSTANT(uint128_t, uint128_type);
-FMT_TYPE_CONSTANT(bool, bool_type);
-FMT_TYPE_CONSTANT(Char, char_type);
-FMT_TYPE_CONSTANT(float, float_type);
-FMT_TYPE_CONSTANT(double, double_type);
-FMT_TYPE_CONSTANT(long double, long_double_type);
-FMT_TYPE_CONSTANT(const Char*, cstring_type);
-FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
-FMT_TYPE_CONSTANT(const void*, pointer_type);
-
-constexpr bool is_integral_type(type t) {
-  return t > type::none_type && t <= type::last_integer_type;
-}
-
-constexpr bool is_arithmetic_type(type t) {
-  return t > type::none_type && t <= type::last_numeric_type;
-}
-
 struct unformattable {};
 struct unformattable_char : unformattable {};
 struct unformattable_const : unformattable {};
@@ -1215,8 +1247,8 @@ template <typename Context> class value {
     unsigned uint_value;
     long long long_long_value;
     unsigned long long ulong_long_value;
-    int128_t int128_value;
-    uint128_t uint128_value;
+    int128_opt int128_value;
+    uint128_opt uint128_value;
     bool bool_value;
     char_type char_value;
     float float_value;
@@ -1233,8 +1265,8 @@ template <typename Context> class value {
   constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
   constexpr FMT_INLINE value(long long val) : long_long_value(val) {}
   constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
-  FMT_INLINE value(int128_t val) : int128_value(val) {}
-  FMT_INLINE value(uint128_t val) : uint128_value(val) {}
+  FMT_INLINE value(int128_opt val) : int128_value(val) {}
+  FMT_INLINE value(uint128_opt val) : uint128_value(val) {}
   constexpr FMT_INLINE value(float val) : float_value(val) {}
   constexpr FMT_INLINE value(double val) : double_value(val) {}
   FMT_INLINE value(long double val) : long_double_value(val) {}
@@ -1284,7 +1316,7 @@ template <typename Context> class value {
 };
 
 template <typename Context, typename T>
-FMT_CONSTEXPR auto make_arg(const T& value) -> basic_format_arg<Context>;
+FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context>;
 
 // To minimize the number of types we need to deal with, long is translated
 // either to int or to long long depending on its size.
@@ -1292,6 +1324,21 @@ enum { long_short = sizeof(long) == sizeof(int) };
 using long_type = conditional_t<long_short, int, long long>;
 using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
 
+#ifdef __cpp_lib_byte
+inline auto format_as(std::byte b) -> unsigned char {
+  return static_cast<unsigned char>(b);
+}
+#endif
+
+template <typename T> struct has_format_as {
+  template <typename U, typename V = decltype(format_as(U())),
+            FMT_ENABLE_IF(std::is_enum<U>::value&& std::is_integral<V>::value)>
+  static auto check(U*) -> std::true_type;
+  static auto check(...) -> std::false_type;
+
+  enum { value = decltype(check(static_cast<T*>(nullptr)))::value };
+};
+
 // Maps formatting arguments to core types.
 // arg_mapper reports errors by returning unformattable instead of using
 // static_assert because it's used in the is_formattable trait.
@@ -1317,8 +1364,12 @@ template <typename Context> struct arg_mapper {
       -> unsigned long long {
     return val;
   }
-  FMT_CONSTEXPR FMT_INLINE auto map(int128_t val) -> int128_t { return val; }
-  FMT_CONSTEXPR FMT_INLINE auto map(uint128_t val) -> uint128_t { return val; }
+  FMT_CONSTEXPR FMT_INLINE auto map(int128_opt val) -> int128_opt {
+    return val;
+  }
+  FMT_CONSTEXPR FMT_INLINE auto map(uint128_opt val) -> uint128_opt {
+    return val;
+  }
   FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; }
 
   template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
@@ -1365,45 +1416,24 @@ template <typename Context> struct arg_mapper {
   }
   template <typename T,
             FMT_ENABLE_IF(
-                std::is_constructible<basic_string_view<char_type>, T>::value &&
+                std::is_convertible<T, basic_string_view<char_type>>::value &&
                 !is_string<T>::value && !has_formatter<T, Context>::value &&
                 !has_fallback_formatter<T, char_type>::value)>
   FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
       -> basic_string_view<char_type> {
     return basic_string_view<char_type>(val);
   }
-  template <
-      typename T,
-      FMT_ENABLE_IF(
-          std::is_constructible<std_string_view<char_type>, T>::value &&
-          !std::is_constructible<basic_string_view<char_type>, T>::value &&
-          !is_string<T>::value && !has_formatter<T, Context>::value &&
-          !has_fallback_formatter<T, char_type>::value)>
+  template <typename T,
+            FMT_ENABLE_IF(
+                std::is_convertible<T, std_string_view<char_type>>::value &&
+                !std::is_convertible<T, basic_string_view<char_type>>::value &&
+                !is_string<T>::value && !has_formatter<T, Context>::value &&
+                !has_fallback_formatter<T, char_type>::value)>
   FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
       -> basic_string_view<char_type> {
     return std_string_view<char_type>(val);
   }
 
-  using cstring_result = conditional_t<std::is_same<char_type, char>::value,
-                                       const char*, unformattable_pointer>;
-
-  FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const signed char* val)
-      -> cstring_result {
-    return map(reinterpret_cast<const char*>(val));
-  }
-  FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const unsigned char* val)
-      -> cstring_result {
-    return map(reinterpret_cast<const char*>(val));
-  }
-  FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(signed char* val)
-      -> cstring_result {
-    return map(reinterpret_cast<const char*>(val));
-  }
-  FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(unsigned char* val)
-      -> cstring_result {
-    return map(reinterpret_cast<const char*>(val));
-  }
-
   FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; }
   FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* {
     return val;
@@ -1417,10 +1447,11 @@ template <typename Context> struct arg_mapper {
   template <
       typename T,
       FMT_ENABLE_IF(
-          std::is_member_pointer<T>::value ||
+          std::is_pointer<T>::value || std::is_member_pointer<T>::value ||
           std::is_function<typename std::remove_pointer<T>::type>::value ||
           (std::is_convertible<const T&, const void*>::value &&
-           !std::is_convertible<const T&, const char_type*>::value))>
+           !std::is_convertible<const T&, const char_type*>::value &&
+           !has_formatter<T, Context>::value))>
   FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
     return {};
   }
@@ -1434,16 +1465,19 @@ template <typename Context> struct arg_mapper {
   template <typename T,
             FMT_ENABLE_IF(
                 std::is_enum<T>::value&& std::is_convertible<T, int>::value &&
-                !has_formatter<T, Context>::value &&
+                !has_format_as<T>::value && !has_formatter<T, Context>::value &&
                 !has_fallback_formatter<T, char_type>::value)>
-  FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
+  FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
       -> decltype(std::declval<arg_mapper>().map(
-          static_cast<typename std::underlying_type<T>::type>(val))) {
-    return map(static_cast<typename std::underlying_type<T>::type>(val));
+          static_cast<underlying_t<T>>(val))) {
+    return map(static_cast<underlying_t<T>>(val));
   }
 
-  FMT_CONSTEXPR FMT_INLINE auto map(detail::byte val) -> unsigned {
-    return map(static_cast<unsigned char>(val));
+  template <typename T, FMT_ENABLE_IF(has_format_as<T>::value &&
+                                      !has_formatter<T, Context>::value)>
+  FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
+      -> decltype(std::declval<arg_mapper>().map(format_as(T()))) {
+    return map(format_as(val));
   }
 
   template <typename T, typename U = remove_cvref_t<T>>
@@ -1452,8 +1486,9 @@ template <typename Context> struct arg_mapper {
                       !std::is_const<remove_reference_t<T>>::value ||
                       has_fallback_formatter<U, char_type>::value> {};
 
-#if FMT_MSC_VER != 0 && FMT_MSC_VER < 1910
-  // Workaround a bug in MSVC.
+#if (FMT_MSC_VERSION != 0 && FMT_MSC_VERSION < 1910) || \
+    FMT_ICC_VERSION != 0 || defined(__NVCC__)
+  // Workaround a bug in MSVC and Intel (Issue 2746).
   template <typename T> FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
     return val;
   }
@@ -1471,6 +1506,8 @@ template <typename Context> struct arg_mapper {
   template <typename T, typename U = remove_cvref_t<T>,
             FMT_ENABLE_IF(!is_string<U>::value && !is_char<U>::value &&
                           !std::is_array<U>::value &&
+                          !std::is_pointer<U>::value &&
+                          !has_format_as<U>::value &&
                           (has_formatter<U, Context>::value ||
                            has_fallback_formatter<U, char_type>::value))>
   FMT_CONSTEXPR FMT_INLINE auto map(T&& val)
@@ -1513,12 +1550,11 @@ class appender : public std::back_insert_iterator<detail::buffer<char>> {
 
  public:
   using std::back_insert_iterator<detail::buffer<char>>::back_insert_iterator;
-  appender(base it) FMT_NOEXCEPT : base(it) {}
-  using _Unchecked_type = appender;  // Mark iterator as checked.
-
-  auto operator++() FMT_NOEXCEPT -> appender& { return *this; }
+  appender(base it) noexcept : base(it) {}
+  FMT_UNCHECKED_ITERATOR(appender);
 
-  auto operator++(int) FMT_NOEXCEPT -> appender { return *this; }
+  auto operator++() noexcept -> appender& { return *this; }
+  auto operator++(int) noexcept -> appender { return *this; }
 };
 
 // A formatting argument. It is a trivially copyable/constructible type to
@@ -1529,7 +1565,7 @@ template <typename Context> class basic_format_arg {
   detail::type type_;
 
   template <typename ContextType, typename T>
-  friend FMT_CONSTEXPR auto detail::make_arg(const T& value)
+  friend FMT_CONSTEXPR auto detail::make_arg(T&& value)
       -> basic_format_arg<ContextType>;
 
   template <typename Visitor, typename Ctx>
@@ -1564,7 +1600,7 @@ template <typename Context> class basic_format_arg {
 
   constexpr basic_format_arg() : type_(detail::type::none_type) {}
 
-  constexpr explicit operator bool() const FMT_NOEXCEPT {
+  constexpr explicit operator bool() const noexcept {
     return type_ != detail::type::none_type;
   }
 
@@ -1632,6 +1668,11 @@ auto copy_str(InputIt begin, InputIt end, appender out) -> appender {
   return out;
 }
 
+template <typename Char, typename R, typename OutputIt>
+FMT_CONSTEXPR auto copy_str(R&& rng, OutputIt out) -> OutputIt {
+  return detail::copy_str<Char>(rng.begin(), rng.end(), out);
+}
+
 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
 // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
 template <typename... Ts> struct void_t_impl { using type = void; };
@@ -1665,7 +1706,7 @@ struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
 template <>
 struct is_contiguous_back_insert_iterator<appender> : std::true_type {};
 
-// A type-erased reference to an std::locale to avoid heavy <locale> include.
+// A type-erased reference to an std::locale to avoid heavy <locale> include.
 class locale_ref {
  private:
   const void* locale_;  // A type-erased pointer to std::locale.
@@ -1674,7 +1715,7 @@ class locale_ref {
   constexpr locale_ref() : locale_(nullptr) {}
   template <typename Locale> explicit locale_ref(const Locale& loc);
 
-  explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; }
+  explicit operator bool() const noexcept { return locale_ != nullptr; }
 
   template <typename Locale> auto get() const -> Locale;
 };
@@ -1690,50 +1731,50 @@ constexpr auto encode_types() -> unsigned long long {
 }
 
 template <typename Context, typename T>
-FMT_CONSTEXPR auto make_arg(const T& value) -> basic_format_arg<Context> {
-  basic_format_arg<Context> arg;
-  arg.type_ = mapped_type_constant<T, Context>::value;
-  arg.value_ = arg_mapper<Context>().map(value);
-  return arg;
-}
-
-// The type template parameter is there to avoid an ODR violation when using
-// a fallback formatter in one translation unit and an implicit conversion in
-// another (not recommended).
-template <bool IS_PACKED, typename Context, type, typename T,
-          FMT_ENABLE_IF(IS_PACKED)>
-FMT_CONSTEXPR FMT_INLINE auto make_arg(T&& val) -> value<Context> {
-  const auto& arg = arg_mapper<Context>().map(std::forward<T>(val));
+FMT_CONSTEXPR FMT_INLINE auto make_value(T&& val) -> value<Context> {
+  using arg_type = remove_cvref_t<decltype(arg_mapper<Context>().map(val))>;
 
   constexpr bool formattable_char =
-      !std::is_same<decltype(arg), const unformattable_char&>::value;
+          !std::is_same<arg_type, unformattable_char>::value;
   static_assert(formattable_char, "Mixing character types is disallowed.");
 
-  constexpr bool formattable_const =
-      !std::is_same<decltype(arg), const unformattable_const&>::value;
-  static_assert(formattable_const, "Cannot format a const argument.");
-
   // Formatting of arbitrary pointers is disallowed. If you want to output
   // a pointer cast it to "void *" or "const void *". In particular, this
   // forbids formatting of "[const] volatile char *" which is printed as bool
   // by iostreams.
   constexpr bool formattable_pointer =
-      !std::is_same<decltype(arg), const unformattable_pointer&>::value;
+    !std::is_same<arg_type, unformattable_pointer>::value;
   static_assert(formattable_pointer,
                 "Formatting of non-void pointers is disallowed.");
 
-  constexpr bool formattable =
-      !std::is_same<decltype(arg), const unformattable&>::value;
+  constexpr bool formattable = !std::is_same<arg_type, unformattable>::value;
   static_assert(
       formattable,
       "Cannot format an argument. To make type T formattable provide a "
       "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
-  return {arg};
+  return {arg_mapper<Context>().map(val)};
+}
+
+template <typename Context, typename T>
+FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context> {
+  basic_format_arg<Context> arg;
+  arg.type_ = mapped_type_constant<T, Context>::value;
+  arg.value_ = make_value<Context>(value);
+  return arg;
+}
+
+// The type template parameter is there to avoid an ODR violation when using
+// a fallback formatter in one translation unit and an implicit conversion in
+// another (not recommended).
+template <bool IS_PACKED, typename Context, type, typename T,
+          FMT_ENABLE_IF(IS_PACKED)>
+FMT_CONSTEXPR FMT_INLINE auto make_arg(T&& val) -> value<Context> {
+  return make_value<Context>(val);
 }
 
 template <bool IS_PACKED, typename Context, type, typename T,
           FMT_ENABLE_IF(!IS_PACKED)>
-inline auto make_arg(const T& value) -> basic_format_arg<Context> {
+FMT_CONSTEXPR inline auto make_arg(T&& value) -> basic_format_arg<Context> {
   return make_arg<Context>(value);
 }
 FMT_END_DETAIL_NAMESPACE
@@ -1853,7 +1894,7 @@ class format_arg_store
         data_{detail::make_arg<
             is_packed, Context,
             detail::mapped_type_constant<remove_cvref_t<T>, Context>::value>(
-            std::forward<T>(args))...} {
+            FMT_FORWARD(args))...} {
     detail::init_named_args(data_.named_args(), 0, 0, args...);
   }
 };
@@ -1869,7 +1910,7 @@ class format_arg_store
 template <typename Context = format_context, typename... Args>
 constexpr auto make_format_args(Args&&... args)
     -> format_arg_store<Context, remove_cvref_t<Args>...> {
-  return {std::forward<Args>(args)...};
+  return {FMT_FORWARD(args)...};
 }
 
 /**
@@ -2015,14 +2056,22 @@ template <typename Context> class basic_format_args {
 // between clang and gcc on ARM (#1919).
 using format_args = basic_format_args<format_context>;
 
-// We cannot use enum classes as bit fields because of a gcc bug
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414.
+// We cannot use enum classes as bit fields because of a gcc bug, so we put them
+// in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414).
+// Additionally, if an underlying type is specified, older gcc incorrectly warns
+// that the type is too small. Both bugs are fixed in gcc 9.3.
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 903
+#  define FMT_ENUM_UNDERLYING_TYPE(type)
+#else
+#  define FMT_ENUM_UNDERLYING_TYPE(type) : type
+#endif
 namespace align {
-enum type { none, left, right, center, numeric };
+enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center,
+                                                  numeric};
 }
 using align_t = align::type;
 namespace sign {
-enum type { none, minus, plus, space };
+enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space};
 }
 using sign_t = sign::type;
 
@@ -2072,7 +2121,8 @@ enum class presentation_type : unsigned char {
   general_upper,   // 'G'
   chr,             // 'c'
   string,          // 's'
-  pointer          // 'p'
+  pointer,         // 'p'
+  debug            // '?'
 };
 
 // Format specifiers for built-in and string types.
@@ -2209,11 +2259,14 @@ class dynamic_specs_handler
 
   FMT_CONSTEXPR auto make_arg_ref(int arg_id) -> arg_ref_type {
     context_.check_arg_id(arg_id);
+    context_.check_dynamic_spec(arg_id);
     return arg_ref_type(arg_id);
   }
 
   FMT_CONSTEXPR auto make_arg_ref(auto_id) -> arg_ref_type {
-    return arg_ref_type(context_.next_arg_id());
+    int arg_id = context_.next_arg_id();
+    context_.check_dynamic_spec(arg_id);
+    return arg_ref_type(arg_id);
   }
 
   FMT_CONSTEXPR auto make_arg_ref(basic_string_view<char_type> arg_id)
@@ -2231,21 +2284,23 @@ template <typename Char> constexpr bool is_ascii_letter(Char c) {
 
 // Converts a character to ASCII. Returns a number > 127 on conversion failure.
 template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
-constexpr auto to_ascii(Char value) -> Char {
-  return value;
+constexpr auto to_ascii(Char c) -> Char {
+  return c;
 }
 template <typename Char, FMT_ENABLE_IF(std::is_enum<Char>::value)>
-constexpr auto to_ascii(Char value) ->
-    typename std::underlying_type<Char>::type {
-  return value;
+constexpr auto to_ascii(Char c) -> underlying_t<Char> {
+  return c;
+}
+
+FMT_CONSTEXPR inline auto code_point_length_impl(char c) -> int {
+  return "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4"
+      [static_cast<unsigned char>(c) >> 3];
 }
 
 template <typename Char>
 FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
   if (const_check(sizeof(Char) != 1)) return 1;
-  auto lengths =
-      "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4";
-  int len = lengths[static_cast<unsigned char>(*begin) >> 3];
+  int len = code_point_length_impl(static_cast<char>(*begin));
 
   // Compute the pointer to the next character early so that the next
   // iteration can start working on the next character. Neither Clang
@@ -2302,7 +2357,7 @@ FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
   FMT_ASSERT(begin != end, "");
   auto align = align::none;
   auto p = begin + code_point_length(begin);
-  if (p >= end) p = begin;
+  if (end - p <= 0) p = begin;
   for (;;) {
     switch (to_ascii(*p)) {
     case '<':
@@ -2488,6 +2543,8 @@ FMT_CONSTEXPR auto parse_presentation_type(Char type) -> presentation_type {
     return presentation_type::string;
   case 'p':
     return presentation_type::pointer;
+  case '?':
+    return presentation_type::debug;
   default:
     return presentation_type::none;
   }
@@ -2634,22 +2691,22 @@ FMT_CONSTEXPR FMT_INLINE void parse_format_string(
     handler.on_text(begin, end);
     return;
   }
-  struct writer {
-    FMT_CONSTEXPR void operator()(const Char* pbegin, const Char* pend) {
-      if (pbegin == pend) return;
+  struct pfs_writer {
+    FMT_CONSTEXPR void operator()(const Char* from, const Char* to) {
+      if (from == to) return;
       for (;;) {
         const Char* p = nullptr;
-        if (!find<IS_CONSTEXPR>(pbegin, pend, Char('}'), p))
-          return handler_.on_text(pbegin, pend);
+        if (!find<IS_CONSTEXPR>(from, to, Char('}'), p))
+          return handler_.on_text(from, to);
         ++p;
-        if (p == pend || *p != '}')
+        if (p == to || *p != '}')
           return handler_.on_error("unmatched '}' in format string");
-        handler_.on_text(pbegin, p);
-        pbegin = p + 1;
+        handler_.on_text(from, p);
+        from = p + 1;
       }
     }
     Handler& handler_;
-  } write{handler};
+  } write = {handler};
   while (begin != end) {
     // Doing two passes with memchr (one for '{' and another for '}') is up to
     // 2.5x faster than the naive one-pass implementation on big format strings.
@@ -2661,50 +2718,29 @@ FMT_CONSTEXPR FMT_INLINE void parse_format_string(
   }
 }
 
+template <typename T, bool = is_named_arg<T>::value> struct strip_named_arg {
+  using type = T;
+};
+template <typename T> struct strip_named_arg<T, true> {
+  using type = remove_cvref_t<decltype(T::value)>;
+};
+
 template <typename T, typename ParseContext>
 FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
     -> decltype(ctx.begin()) {
   using char_type = typename ParseContext::char_type;
   using context = buffer_context<char_type>;
+  using stripped_type = typename strip_named_arg<T>::type;
   using mapped_type = conditional_t<
       mapped_type_constant<T, context>::value != type::custom_type,
-      decltype(arg_mapper<context>().map(std::declval<const T&>())), T>;
+      decltype(arg_mapper<context>().map(std::declval<const T&>())),
+      stripped_type>;
   auto f = conditional_t<has_formatter<mapped_type, context>::value,
                          formatter<mapped_type, char_type>,
-                         fallback_formatter<T, char_type>>();
+                         fallback_formatter<stripped_type, char_type>>();
   return f.parse(ctx);
 }
 
-// A parse context with extra argument id checks. It is only used at compile
-// time because adding checks at runtime would introduce substantial overhead
-// and would be redundant since argument ids are checked when arguments are
-// retrieved anyway.
-template <typename Char, typename ErrorHandler = error_handler>
-class compile_parse_context
-    : public basic_format_parse_context<Char, ErrorHandler> {
- private:
-  int num_args_;
-  using base = basic_format_parse_context<Char, ErrorHandler>;
-
- public:
-  explicit FMT_CONSTEXPR compile_parse_context(
-      basic_string_view<Char> format_str,
-      int num_args = (std::numeric_limits<int>::max)(), ErrorHandler eh = {})
-      : base(format_str, eh), num_args_(num_args) {}
-
-  FMT_CONSTEXPR auto next_arg_id() -> int {
-    int id = base::next_arg_id();
-    if (id >= num_args_) this->on_error("argument not found");
-    return id;
-  }
-
-  FMT_CONSTEXPR void check_arg_id(int id) {
-    base::check_arg_id(id);
-    if (id >= num_args_) this->on_error("argument not found");
-  }
-  using base::check_arg_id;
-};
-
 template <typename ErrorHandler>
 FMT_CONSTEXPR void check_int_type_spec(presentation_type type,
                                        ErrorHandler&& eh) {
@@ -2717,7 +2753,8 @@ template <typename Char, typename ErrorHandler = error_handler>
 FMT_CONSTEXPR auto check_char_specs(const basic_format_specs<Char>& specs,
                                     ErrorHandler&& eh = {}) -> bool {
   if (specs.type != presentation_type::none &&
-      specs.type != presentation_type::chr) {
+      specs.type != presentation_type::chr &&
+      specs.type != presentation_type::debug) {
     check_int_type_spec(specs.type, eh);
     return false;
   }
@@ -2741,7 +2778,6 @@ struct float_specs {
   bool upper : 1;
   bool locale : 1;
   bool binary32 : 1;
-  bool fallback : 1;
   bool showpoint : 1;
 };
 
@@ -2792,7 +2828,8 @@ FMT_CONSTEXPR auto parse_float_type_spec(const basic_format_specs<Char>& specs,
 template <typename ErrorHandler = error_handler>
 FMT_CONSTEXPR auto check_cstring_type_spec(presentation_type type,
                                            ErrorHandler&& eh = {}) -> bool {
-  if (type == presentation_type::none || type == presentation_type::string)
+  if (type == presentation_type::none || type == presentation_type::string ||
+      type == presentation_type::debug)
     return true;
   if (type != presentation_type::pointer) eh.on_error("invalid type specifier");
   return false;
@@ -2801,7 +2838,8 @@ FMT_CONSTEXPR auto check_cstring_type_spec(presentation_type type,
 template <typename ErrorHandler = error_handler>
 FMT_CONSTEXPR void check_string_type_spec(presentation_type type,
                                           ErrorHandler&& eh = {}) {
-  if (type != presentation_type::none && type != presentation_type::string)
+  if (type != presentation_type::none && type != presentation_type::string &&
+      type != presentation_type::debug)
     eh.on_error("invalid type specifier");
 }
 
@@ -2835,7 +2873,8 @@ template <typename Handler> class specs_checker : public Handler {
   FMT_CONSTEXPR void on_sign(sign_t s) {
     require_numeric_argument();
     if (is_integral_type(arg_type_) && arg_type_ != type::int_type &&
-        arg_type_ != type::long_long_type && arg_type_ != type::char_type) {
+        arg_type_ != type::long_long_type && arg_type_ != type::int128_type &&
+        arg_type_ != type::char_type) {
       this->on_error("format specifier requires signed argument");
     }
     Handler::on_sign(s);
@@ -2864,7 +2903,7 @@ template <typename Handler> class specs_checker : public Handler {
 
 constexpr int invalid_arg_index = -1;
 
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
 template <int N, typename T, typename... Args, typename Char>
 constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
   if constexpr (detail::is_statically_named_arg<T>()) {
@@ -2879,7 +2918,7 @@ constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
 
 template <typename... Args, typename Char>
 FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
   if constexpr (sizeof...(Args) > 0)
     return get_arg_index_by_name<0, Args...>(name);
 #endif
@@ -2890,20 +2929,28 @@ FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
 template <typename Char, typename ErrorHandler, typename... Args>
 class format_string_checker {
  private:
+  // In the future basic_format_parse_context will replace compile_parse_context
+  // here and will use is_constant_evaluated and downcasting to access the data
+  // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1.
   using parse_context_type = compile_parse_context<Char, ErrorHandler>;
-  enum { num_args = sizeof...(Args) };
+  static constexpr int num_args = sizeof...(Args);
 
   // Format specifier parsing function.
   using parse_func = const Char* (*)(parse_context_type&);
 
   parse_context_type context_;
-  parse_func parse_funcs_[num_args > 0 ? num_args : 1];
+  parse_func parse_funcs_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
+  type types_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
 
  public:
   explicit FMT_CONSTEXPR format_string_checker(
       basic_string_view<Char> format_str, ErrorHandler eh)
-      : context_(format_str, num_args, eh),
-        parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
+      : context_(format_str, num_args, types_, eh),
+        parse_funcs_{&parse_format_specs<Args, parse_context_type>...},
+        types_{
+            mapped_type_constant<Args,
+                                 basic_format_context<Char*, Char>>::value...} {
+  }
 
   FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
 
@@ -2912,7 +2959,7 @@ class format_string_checker {
     return context_.check_arg_id(id), id;
   }
   FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
     auto index = get_arg_index_by_name<Args...>(id);
     if (index == invalid_arg_index) on_error("named argument is not found");
     return context_.check_arg_id(index), index;
@@ -2937,10 +2984,19 @@ class format_string_checker {
   }
 };
 
+// Reports a compile-time error if S is not a valid format string.
+template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
+FMT_INLINE void check_format_string(const S&) {
+#ifdef FMT_ENFORCE_COMPILE_STRING
+  static_assert(is_compile_string<S>::value,
+                "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
+                "FMT_STRING.");
+#endif
+}
 template <typename... Args, typename S,
-          enable_if_t<(is_compile_string<S>::value), int>>
+          FMT_ENABLE_IF(is_compile_string<S>::value)>
 void check_format_string(S format_str) {
-  FMT_CONSTEXPR auto s = to_string_view(format_str);
+  FMT_CONSTEXPR auto s = basic_string_view<typename S::char_type>(format_str);
   using checker = format_string_checker<typename S::char_type, error_handler,
                                         remove_cvref_t<Args>...>;
   FMT_CONSTEXPR bool invalid_format =
@@ -3038,11 +3094,41 @@ struct formatter<T, Char,
     return it;
   }
 
+  template <detail::type U = detail::type_constant<T, Char>::value,
+            enable_if_t<(U == detail::type::string_type ||
+                         U == detail::type::cstring_type ||
+                         U == detail::type::char_type),
+                        int> = 0>
+  FMT_CONSTEXPR void set_debug_format() {
+    specs_.type = presentation_type::debug;
+  }
+
   template <typename FormatContext>
   FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
       -> decltype(ctx.out());
 };
 
+#define FMT_FORMAT_AS(Type, Base)                                        \
+  template <typename Char>                                               \
+  struct formatter<Type, Char> : formatter<Base, Char> {                 \
+    template <typename FormatContext>                                    \
+    auto format(Type const& val, FormatContext& ctx) const               \
+        -> decltype(ctx.out()) {                                         \
+      return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
+    }                                                                    \
+  }
+
+FMT_FORMAT_AS(signed char, int);
+FMT_FORMAT_AS(unsigned char, unsigned);
+FMT_FORMAT_AS(short, int);
+FMT_FORMAT_AS(unsigned short, unsigned);
+FMT_FORMAT_AS(long, long long);
+FMT_FORMAT_AS(unsigned long, unsigned long long);
+FMT_FORMAT_AS(Char*, const Char*);
+FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
+FMT_FORMAT_AS(std::nullptr_t, const void*);
+FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
+
 template <typename Char> struct basic_runtime { basic_string_view<Char> str; };
 
 /** A compile-time format string. */
@@ -3078,10 +3164,8 @@ template <typename Char, typename... Args> class basic_format_string {
 
 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
 // Workaround broken conversion on older gcc.
-template <typename... Args> using format_string = string_view;
-template <typename S> auto runtime(const S& s) -> basic_string_view<char_t<S>> {
-  return s;
-}
+template <typename...> using format_string = string_view;
+inline auto runtime(string_view s) -> string_view { return s; }
 #else
 template <typename... Args>
 using format_string = basic_format_string<char, type_identity_t<Args>...>;
@@ -3095,9 +3179,7 @@ using format_string = basic_format_string<char, type_identity_t<Args>...>;
     fmt::print(fmt::runtime("{:d}"), "I am not a number");
   \endrst
  */
-template <typename S> auto runtime(const S& s) -> basic_runtime<char_t<S>> {
-  return {{s}};
-}
+inline auto runtime(string_view s) -> basic_runtime<char> { return {{s}}; }
 #endif
 
 FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
index 2c51c50aeb2007706b56d8cba05a0785645dd642..22b1ec8df0eb14b3f7f21797a19586b50b8423fd 100644 (file)
@@ -44,21 +44,8 @@ FMT_FUNC void throw_format_error(const char* message) {
   FMT_THROW(format_error(message));
 }
 
-#ifndef _MSC_VER
-#  define FMT_SNPRINTF snprintf
-#else  // _MSC_VER
-inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
-  va_list args;
-  va_start(args, format);
-  int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
-  va_end(args);
-  return result;
-}
-#  define FMT_SNPRINTF fmt_snprintf
-#endif  // _MSC_VER
-
 FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
-                                string_view message) FMT_NOEXCEPT {
+                                string_view message) noexcept {
   // Report error code making sure that the output fits into
   // inline_buffer_size to avoid dynamic memory allocation and potential
   // bad_alloc.
@@ -81,7 +68,7 @@ FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
 }
 
 FMT_FUNC void report_error(format_func func, int error_code,
-                           const char* message) FMT_NOEXCEPT {
+                           const char* message) noexcept {
   memory_buffer full_message;
   func(full_message, error_code, message);
   // Don't use fwrite_fully because the latter may throw.
@@ -93,7 +80,8 @@ FMT_FUNC void report_error(format_func func, int error_code,
 inline void fwrite_fully(const void* ptr, size_t size, size_t count,
                          FILE* stream) {
   size_t written = std::fwrite(ptr, size, count, stream);
-  if (written < count) FMT_THROW(system_error(errno, "cannot write to file"));
+  if (written < count)
+    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
 }
 
 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
@@ -129,8 +117,8 @@ template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref) {
 #endif
 }  // namespace detail
 
-#if !FMT_MSC_VER
-FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default;
+#if !FMT_MSC_VERSION
+FMT_API FMT_FUNC format_error::~format_error() noexcept = default;
 #endif
 
 FMT_FUNC std::system_error vsystem_error(int error_code, string_view format_str,
@@ -141,710 +129,31 @@ FMT_FUNC std::system_error vsystem_error(int error_code, string_view format_str,
 
 namespace detail {
 
-template <> FMT_FUNC int count_digits<4>(detail::fallback_uintptr n) {
-  // fallback_uintptr is always stored in little endian.
-  int i = static_cast<int>(sizeof(void*)) - 1;
-  while (i > 0 && n.value[i] == 0) --i;
-  auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
-  return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1;
-}
-
-// log10(2) = 0x0.4d104d427de7fbcc...
-static constexpr uint64_t log10_2_significand = 0x4d104d427de7fbcc;
-
-template <typename T = void> struct basic_impl_data {
-  // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
-  // These are generated by support/compute-powers.py.
-  static constexpr uint64_t pow10_significands[87] = {
-      0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
-      0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
-      0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
-      0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
-      0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
-      0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
-      0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
-      0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
-      0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
-      0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
-      0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
-      0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
-      0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
-      0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
-      0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
-      0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
-      0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
-      0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
-      0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
-      0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
-      0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
-      0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
-      0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
-      0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
-      0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
-      0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
-      0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
-      0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
-      0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
-  };
-
-#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
-#  pragma GCC diagnostic push
-#  pragma GCC diagnostic ignored "-Wnarrowing"
-#endif
-  // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
-  // to significands above.
-  static constexpr int16_t pow10_exponents[87] = {
-      -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
-      -927,  -901,  -874,  -847,  -821,  -794,  -768,  -741,  -715,  -688, -661,
-      -635,  -608,  -582,  -555,  -529,  -502,  -475,  -449,  -422,  -396, -369,
-      -343,  -316,  -289,  -263,  -236,  -210,  -183,  -157,  -130,  -103, -77,
-      -50,   -24,   3,     30,    56,    83,    109,   136,   162,   189,  216,
-      242,   269,   295,   322,   348,   375,   402,   428,   455,   481,  508,
-      534,   561,   588,   614,   641,   667,   694,   720,   747,   774,  800,
-      827,   853,   880,   907,   933,   960,   986,   1013,  1039,  1066};
-#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
-#  pragma GCC diagnostic pop
-#endif
-
-  static constexpr uint64_t power_of_10_64[20] = {
-      1, FMT_POWERS_OF_10(1ULL), FMT_POWERS_OF_10(1000000000ULL),
-      10000000000000000000ULL};
-};
-
-// This is a struct rather than an alias to avoid shadowing warnings in gcc.
-struct impl_data : basic_impl_data<> {};
-
-#if __cplusplus < 201703L
-template <typename T>
-constexpr uint64_t basic_impl_data<T>::pow10_significands[];
-template <typename T> constexpr int16_t basic_impl_data<T>::pow10_exponents[];
-template <typename T> constexpr uint64_t basic_impl_data<T>::power_of_10_64[];
-#endif
-
-template <typename T> struct bits {
-  static FMT_CONSTEXPR_DECL const int value =
-      static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits);
-};
-
-// Returns the number of significand bits in Float excluding the implicit bit.
-template <typename Float> constexpr int num_significand_bits() {
-  // Subtract 1 to account for an implicit most significant bit in the
-  // normalized form.
-  return std::numeric_limits<Float>::digits - 1;
-}
-
-// A floating-point number f * pow(2, e).
-struct fp {
-  uint64_t f;
-  int e;
-
-  static constexpr const int num_significand_bits = bits<decltype(f)>::value;
-
-  constexpr fp() : f(0), e(0) {}
-  constexpr fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
-
-  // Constructs fp from an IEEE754 floating-point number. It is a template to
-  // prevent compile errors on systems where n is not IEEE754.
-  template <typename Float> explicit FMT_CONSTEXPR fp(Float n) { assign(n); }
-
-  template <typename Float>
-  using is_supported = bool_constant<sizeof(Float) == sizeof(uint64_t) ||
-                                     sizeof(Float) == sizeof(uint32_t)>;
-
-  // Assigns d to this and return true iff predecessor is closer than successor.
-  template <typename Float, FMT_ENABLE_IF(is_supported<Float>::value)>
-  FMT_CONSTEXPR bool assign(Float n) {
-    // Assume float is in the format [sign][exponent][significand].
-    const int num_float_significand_bits =
-        detail::num_significand_bits<Float>();
-    const uint64_t implicit_bit = 1ULL << num_float_significand_bits;
-    const uint64_t significand_mask = implicit_bit - 1;
-    constexpr bool is_double = sizeof(Float) == sizeof(uint64_t);
-    auto u = bit_cast<conditional_t<is_double, uint64_t, uint32_t>>(n);
-    f = u & significand_mask;
-    const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask;
-    int biased_e =
-        static_cast<int>((u & exponent_mask) >> num_float_significand_bits);
-    // The predecessor is closer if n is a normalized power of 2 (f == 0) other
-    // than the smallest normalized number (biased_e > 1).
-    bool is_predecessor_closer = f == 0 && biased_e > 1;
-    if (biased_e != 0)
-      f += implicit_bit;
-    else
-      biased_e = 1;  // Subnormals use biased exponent 1 (min exponent).
-    const int exponent_bias = std::numeric_limits<Float>::max_exponent - 1;
-    e = biased_e - exponent_bias - num_float_significand_bits;
-    return is_predecessor_closer;
-  }
-
-  template <typename Float, FMT_ENABLE_IF(!is_supported<Float>::value)>
-  bool assign(Float) {
-    FMT_ASSERT(false, "");
-    return false;
-  }
-};
-
-// Normalizes the value converted from double and multiplied by (1 << SHIFT).
-template <int SHIFT = 0> FMT_CONSTEXPR fp normalize(fp value) {
-  // Handle subnormals.
-  const uint64_t implicit_bit = 1ULL << num_significand_bits<double>();
-  const auto shifted_implicit_bit = implicit_bit << SHIFT;
-  while ((value.f & shifted_implicit_bit) == 0) {
-    value.f <<= 1;
-    --value.e;
-  }
-  // Subtract 1 to account for hidden bit.
-  const auto offset =
-      fp::num_significand_bits - num_significand_bits<double>() - SHIFT - 1;
-  value.f <<= offset;
-  value.e -= offset;
-  return value;
-}
-
-inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; }
-
-// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
-FMT_CONSTEXPR inline uint64_t multiply(uint64_t lhs, uint64_t rhs) {
-#if FMT_USE_INT128
-  auto product = static_cast<__uint128_t>(lhs) * rhs;
-  auto f = static_cast<uint64_t>(product >> 64);
-  return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
-#else
-  // Multiply 32-bit parts of significands.
-  uint64_t mask = (1ULL << 32) - 1;
-  uint64_t a = lhs >> 32, b = lhs & mask;
-  uint64_t c = rhs >> 32, d = rhs & mask;
-  uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
-  // Compute mid 64-bit of result and round.
-  uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
-  return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
-#endif
-}
-
-FMT_CONSTEXPR inline fp operator*(fp x, fp y) {
-  return {multiply(x.f, y.f), x.e + y.e + 64};
-}
-
-// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its
-// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`.
-FMT_CONSTEXPR inline fp get_cached_power(int min_exponent,
-                                         int& pow10_exponent) {
-  const int shift = 32;
-  const auto significand = static_cast<int64_t>(log10_2_significand);
-  int index = static_cast<int>(
-      ((min_exponent + fp::num_significand_bits - 1) * (significand >> shift) +
-       ((int64_t(1) << shift) - 1))  // ceil
-      >> 32                          // arithmetic shift
-  );
-  // Decimal exponent of the first (smallest) cached power of 10.
-  const int first_dec_exp = -348;
-  // Difference between 2 consecutive decimal exponents in cached powers of 10.
-  const int dec_exp_step = 8;
-  index = (index - first_dec_exp - 1) / dec_exp_step + 1;
-  pow10_exponent = first_dec_exp + index * dec_exp_step;
-  return {impl_data::pow10_significands[index],
-          impl_data::pow10_exponents[index]};
-}
-
-// A simple accumulator to hold the sums of terms in bigint::square if uint128_t
-// is not available.
-struct accumulator {
-  uint64_t lower;
-  uint64_t upper;
-
-  constexpr accumulator() : lower(0), upper(0) {}
-  constexpr explicit operator uint32_t() const {
-    return static_cast<uint32_t>(lower);
-  }
-
-  FMT_CONSTEXPR void operator+=(uint64_t n) {
-    lower += n;
-    if (lower < n) ++upper;
-  }
-  FMT_CONSTEXPR void operator>>=(int shift) {
-    FMT_ASSERT(shift == 32, "");
-    (void)shift;
-    lower = (upper << 32) | (lower >> 32);
-    upper >>= 32;
-  }
-};
-
-class bigint {
- private:
-  // A bigint is stored as an array of bigits (big digits), with bigit at index
-  // 0 being the least significant one.
-  using bigit = uint32_t;
-  using double_bigit = uint64_t;
-  enum { bigits_capacity = 32 };
-  basic_memory_buffer<bigit, bigits_capacity> bigits_;
-  int exp_;
-
-  FMT_CONSTEXPR20 bigit operator[](int index) const {
-    return bigits_[to_unsigned(index)];
-  }
-  FMT_CONSTEXPR20 bigit& operator[](int index) {
-    return bigits_[to_unsigned(index)];
-  }
-
-  static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value;
-
-  friend struct formatter<bigint>;
-
-  FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) {
-    auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
-    (*this)[index] = static_cast<bigit>(result);
-    borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
-  }
-
-  FMT_CONSTEXPR20 void remove_leading_zeros() {
-    int num_bigits = static_cast<int>(bigits_.size()) - 1;
-    while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
-    bigits_.resize(to_unsigned(num_bigits + 1));
-  }
-
-  // Computes *this -= other assuming aligned bigints and *this >= other.
-  FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) {
-    FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
-    FMT_ASSERT(compare(*this, other) >= 0, "");
-    bigit borrow = 0;
-    int i = other.exp_ - exp_;
-    for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
-      subtract_bigits(i, other.bigits_[j], borrow);
-    while (borrow > 0) subtract_bigits(i, 0, borrow);
-    remove_leading_zeros();
-  }
-
-  FMT_CONSTEXPR20 void multiply(uint32_t value) {
-    const double_bigit wide_value = value;
-    bigit carry = 0;
-    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
-      double_bigit result = bigits_[i] * wide_value + carry;
-      bigits_[i] = static_cast<bigit>(result);
-      carry = static_cast<bigit>(result >> bigit_bits);
-    }
-    if (carry != 0) bigits_.push_back(carry);
-  }
-
-  FMT_CONSTEXPR20 void multiply(uint64_t value) {
-    const bigit mask = ~bigit(0);
-    const double_bigit lower = value & mask;
-    const double_bigit upper = value >> bigit_bits;
-    double_bigit carry = 0;
-    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
-      double_bigit result = bigits_[i] * lower + (carry & mask);
-      carry =
-          bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits);
-      bigits_[i] = static_cast<bigit>(result);
-    }
-    while (carry != 0) {
-      bigits_.push_back(carry & mask);
-      carry >>= bigit_bits;
-    }
-  }
-
- public:
-  FMT_CONSTEXPR20 bigint() : exp_(0) {}
-  explicit bigint(uint64_t n) { assign(n); }
-  FMT_CONSTEXPR20 ~bigint() {
-    FMT_ASSERT(bigits_.capacity() <= bigits_capacity, "");
-  }
-
-  bigint(const bigint&) = delete;
-  void operator=(const bigint&) = delete;
-
-  FMT_CONSTEXPR20 void assign(const bigint& other) {
-    auto size = other.bigits_.size();
-    bigits_.resize(size);
-    auto data = other.bigits_.data();
-    std::copy(data, data + size, make_checked(bigits_.data(), size));
-    exp_ = other.exp_;
-  }
-
-  FMT_CONSTEXPR20 void assign(uint64_t n) {
-    size_t num_bigits = 0;
-    do {
-      bigits_[num_bigits++] = n & ~bigit(0);
-      n >>= bigit_bits;
-    } while (n != 0);
-    bigits_.resize(num_bigits);
-    exp_ = 0;
-  }
-
-  FMT_CONSTEXPR20 int num_bigits() const {
-    return static_cast<int>(bigits_.size()) + exp_;
-  }
-
-  FMT_NOINLINE FMT_CONSTEXPR20 bigint& operator<<=(int shift) {
-    FMT_ASSERT(shift >= 0, "");
-    exp_ += shift / bigit_bits;
-    shift %= bigit_bits;
-    if (shift == 0) return *this;
-    bigit carry = 0;
-    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
-      bigit c = bigits_[i] >> (bigit_bits - shift);
-      bigits_[i] = (bigits_[i] << shift) + carry;
-      carry = c;
-    }
-    if (carry != 0) bigits_.push_back(carry);
-    return *this;
-  }
-
-  template <typename Int> FMT_CONSTEXPR20 bigint& operator*=(Int value) {
-    FMT_ASSERT(value > 0, "");
-    multiply(uint32_or_64_or_128_t<Int>(value));
-    return *this;
-  }
-
-  friend FMT_CONSTEXPR20 int compare(const bigint& lhs, const bigint& rhs) {
-    int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
-    if (num_lhs_bigits != num_rhs_bigits)
-      return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
-    int i = static_cast<int>(lhs.bigits_.size()) - 1;
-    int j = static_cast<int>(rhs.bigits_.size()) - 1;
-    int end = i - j;
-    if (end < 0) end = 0;
-    for (; i >= end; --i, --j) {
-      bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
-      if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
-    }
-    if (i != j) return i > j ? 1 : -1;
-    return 0;
-  }
-
-  // Returns compare(lhs1 + lhs2, rhs).
-  friend FMT_CONSTEXPR20 int add_compare(const bigint& lhs1, const bigint& lhs2,
-                                         const bigint& rhs) {
-    int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits());
-    int num_rhs_bigits = rhs.num_bigits();
-    if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
-    if (max_lhs_bigits > num_rhs_bigits) return 1;
-    auto get_bigit = [](const bigint& n, int i) -> bigit {
-      return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
-    };
-    double_bigit borrow = 0;
-    int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_);
-    for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
-      double_bigit sum =
-          static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
-      bigit rhs_bigit = get_bigit(rhs, i);
-      if (sum > rhs_bigit + borrow) return 1;
-      borrow = rhs_bigit + borrow - sum;
-      if (borrow > 1) return -1;
-      borrow <<= bigit_bits;
-    }
-    return borrow != 0 ? -1 : 0;
-  }
-
-  // Assigns pow(10, exp) to this bigint.
-  FMT_CONSTEXPR20 void assign_pow10(int exp) {
-    FMT_ASSERT(exp >= 0, "");
-    if (exp == 0) return assign(1);
-    // Find the top bit.
-    int bitmask = 1;
-    while (exp >= bitmask) bitmask <<= 1;
-    bitmask >>= 1;
-    // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
-    // repeated squaring and multiplication.
-    assign(5);
-    bitmask >>= 1;
-    while (bitmask != 0) {
-      square();
-      if ((exp & bitmask) != 0) *this *= 5;
-      bitmask >>= 1;
-    }
-    *this <<= exp;  // Multiply by pow(2, exp) by shifting.
-  }
-
-  FMT_CONSTEXPR20 void square() {
-    int num_bigits = static_cast<int>(bigits_.size());
-    int num_result_bigits = 2 * num_bigits;
-    basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
-    bigits_.resize(to_unsigned(num_result_bigits));
-    using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>;
-    auto sum = accumulator_t();
-    for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
-      // Compute bigit at position bigit_index of the result by adding
-      // cross-product terms n[i] * n[j] such that i + j == bigit_index.
-      for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
-        // Most terms are multiplied twice which can be optimized in the future.
-        sum += static_cast<double_bigit>(n[i]) * n[j];
-      }
-      (*this)[bigit_index] = static_cast<bigit>(sum);
-      sum >>= bits<bigit>::value;  // Compute the carry.
-    }
-    // Do the same for the top half.
-    for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
-         ++bigit_index) {
-      for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
-        sum += static_cast<double_bigit>(n[i++]) * n[j--];
-      (*this)[bigit_index] = static_cast<bigit>(sum);
-      sum >>= bits<bigit>::value;
-    }
-    remove_leading_zeros();
-    exp_ *= 2;
-  }
-
-  // If this bigint has a bigger exponent than other, adds trailing zero to make
-  // exponents equal. This simplifies some operations such as subtraction.
-  FMT_CONSTEXPR20 void align(const bigint& other) {
-    int exp_difference = exp_ - other.exp_;
-    if (exp_difference <= 0) return;
-    int num_bigits = static_cast<int>(bigits_.size());
-    bigits_.resize(to_unsigned(num_bigits + exp_difference));
-    for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
-      bigits_[j] = bigits_[i];
-    std::uninitialized_fill_n(bigits_.data(), exp_difference, 0);
-    exp_ -= exp_difference;
-  }
-
-  // Divides this bignum by divisor, assigning the remainder to this and
-  // returning the quotient.
-  FMT_CONSTEXPR20 int divmod_assign(const bigint& divisor) {
-    FMT_ASSERT(this != &divisor, "");
-    if (compare(*this, divisor) < 0) return 0;
-    FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
-    align(divisor);
-    int quotient = 0;
-    do {
-      subtract_aligned(divisor);
-      ++quotient;
-    } while (compare(*this, divisor) >= 0);
-    return quotient;
-  }
-};
-
-enum class round_direction { unknown, up, down };
-
-// Given the divisor (normally a power of 10), the remainder = v % divisor for
-// some number v and the error, returns whether v should be rounded up, down, or
-// whether the rounding direction can't be determined due to error.
-// error should be less than divisor / 2.
-FMT_CONSTEXPR inline round_direction get_round_direction(uint64_t divisor,
-                                                         uint64_t remainder,
-                                                         uint64_t error) {
-  FMT_ASSERT(remainder < divisor, "");  // divisor - remainder won't overflow.
-  FMT_ASSERT(error < divisor, "");      // divisor - error won't overflow.
-  FMT_ASSERT(error < divisor - error, "");  // error * 2 won't overflow.
-  // Round down if (remainder + error) * 2 <= divisor.
-  if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
-    return round_direction::down;
-  // Round up if (remainder - error) * 2 >= divisor.
-  if (remainder >= error &&
-      remainder - error >= divisor - (remainder - error)) {
-    return round_direction::up;
-  }
-  return round_direction::unknown;
+template <typename F> inline bool operator==(basic_fp<F> x, basic_fp<F> y) {
+  return x.f == y.f && x.e == y.e;
 }
 
-namespace digits {
-enum result {
-  more,  // Generate more digits.
-  done,  // Done generating digits.
-  error  // Digit generation cancelled due to an error.
-};
+// Compilers should be able to optimize this into the ror instruction.
+FMT_CONSTEXPR inline uint32_t rotr(uint32_t n, uint32_t r) noexcept {
+  r &= 31;
+  return (n >> r) | (n << (32 - r));
 }
-
-struct gen_digits_handler {
-  char* buf;
-  int size;
-  int precision;
-  int exp10;
-  bool fixed;
-
-  FMT_CONSTEXPR digits::result on_digit(char digit, uint64_t divisor,
-                                        uint64_t remainder, uint64_t error,
-                                        bool integral) {
-    FMT_ASSERT(remainder < divisor, "");
-    buf[size++] = digit;
-    if (!integral && error >= remainder) return digits::error;
-    if (size < precision) return digits::more;
-    if (!integral) {
-      // Check if error * 2 < divisor with overflow prevention.
-      // The check is not needed for the integral part because error = 1
-      // and divisor > (1 << 32) there.
-      if (error >= divisor || error >= divisor - error) return digits::error;
-    } else {
-      FMT_ASSERT(error == 1 && divisor > 2, "");
-    }
-    auto dir = get_round_direction(divisor, remainder, error);
-    if (dir != round_direction::up)
-      return dir == round_direction::down ? digits::done : digits::error;
-    ++buf[size - 1];
-    for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
-      buf[i] = '0';
-      ++buf[i - 1];
-    }
-    if (buf[0] > '9') {
-      buf[0] = '1';
-      if (fixed)
-        buf[size++] = '0';
-      else
-        ++exp10;
-    }
-    return digits::done;
-  }
-};
-
-// Generates output using the Grisu digit-gen algorithm.
-// error: the size of the region (lower, upper) outside of which numbers
-// definitely do not round to value (Delta in Grisu3).
-FMT_INLINE FMT_CONSTEXPR20 digits::result grisu_gen_digits(
-    fp value, uint64_t error, int& exp, gen_digits_handler& handler) {
-  const fp one(1ULL << -value.e, value.e);
-  // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
-  // zero because it contains a product of two 64-bit numbers with MSB set (due
-  // to normalization) - 1, shifted right by at most 60 bits.
-  auto integral = static_cast<uint32_t>(value.f >> -one.e);
-  FMT_ASSERT(integral != 0, "");
-  FMT_ASSERT(integral == value.f >> -one.e, "");
-  // The fractional part of scaled value (p2 in Grisu) c = value % one.
-  uint64_t fractional = value.f & (one.f - 1);
-  exp = count_digits(integral);  // kappa in Grisu.
-  // Non-fixed formats require at least one digit and no precision adjustment.
-  if (handler.fixed) {
-    // Adjust fixed precision by exponent because it is relative to decimal
-    // point.
-    int precision_offset = exp + handler.exp10;
-    if (precision_offset > 0 &&
-        handler.precision > max_value<int>() - precision_offset) {
-      FMT_THROW(format_error("number is too big"));
-    }
-    handler.precision += precision_offset;
-    // Check if precision is satisfied just by leading zeros, e.g.
-    // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
-    if (handler.precision <= 0) {
-      if (handler.precision < 0) return digits::done;
-      // Divide by 10 to prevent overflow.
-      uint64_t divisor = impl_data::power_of_10_64[exp - 1] << -one.e;
-      auto dir = get_round_direction(divisor, value.f / 10, error * 10);
-      if (dir == round_direction::unknown) return digits::error;
-      handler.buf[handler.size++] = dir == round_direction::up ? '1' : '0';
-      return digits::done;
-    }
-  }
-  // Generate digits for the integral part. This can produce up to 10 digits.
-  do {
-    uint32_t digit = 0;
-    auto divmod_integral = [&](uint32_t divisor) {
-      digit = integral / divisor;
-      integral %= divisor;
-    };
-    // This optimization by Milo Yip reduces the number of integer divisions by
-    // one per iteration.
-    switch (exp) {
-    case 10:
-      divmod_integral(1000000000);
-      break;
-    case 9:
-      divmod_integral(100000000);
-      break;
-    case 8:
-      divmod_integral(10000000);
-      break;
-    case 7:
-      divmod_integral(1000000);
-      break;
-    case 6:
-      divmod_integral(100000);
-      break;
-    case 5:
-      divmod_integral(10000);
-      break;
-    case 4:
-      divmod_integral(1000);
-      break;
-    case 3:
-      divmod_integral(100);
-      break;
-    case 2:
-      divmod_integral(10);
-      break;
-    case 1:
-      digit = integral;
-      integral = 0;
-      break;
-    default:
-      FMT_ASSERT(false, "invalid number of digits");
-    }
-    --exp;
-    auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional;
-    auto result = handler.on_digit(static_cast<char>('0' + digit),
-                                   impl_data::power_of_10_64[exp] << -one.e,
-                                   remainder, error, true);
-    if (result != digits::more) return result;
-  } while (exp > 0);
-  // Generate digits for the fractional part.
-  for (;;) {
-    fractional *= 10;
-    error *= 10;
-    char digit = static_cast<char>('0' + (fractional >> -one.e));
-    fractional &= one.f - 1;
-    --exp;
-    auto result = handler.on_digit(digit, one.f, fractional, error, false);
-    if (result != digits::more) return result;
-  }
+FMT_CONSTEXPR inline uint64_t rotr(uint64_t n, uint32_t r) noexcept {
+  r &= 63;
+  return (n >> r) | (n << (64 - r));
 }
 
-// A 128-bit integer type used internally,
-struct uint128_wrapper {
-  uint128_wrapper() = default;
-
-#if FMT_USE_INT128
-  uint128_t internal_;
-
-  constexpr uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT
-      : internal_{static_cast<uint128_t>(low) |
-                  (static_cast<uint128_t>(high) << 64)} {}
-
-  constexpr uint128_wrapper(uint128_t u) : internal_{u} {}
-
-  constexpr uint64_t high() const FMT_NOEXCEPT {
-    return uint64_t(internal_ >> 64);
-  }
-  constexpr uint64_t low() const FMT_NOEXCEPT { return uint64_t(internal_); }
-
-  uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
-    internal_ += n;
-    return *this;
-  }
-#else
-  uint64_t high_;
-  uint64_t low_;
-
-  constexpr uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT
-      : high_{high},
-        low_{low} {}
-
-  constexpr uint64_t high() const FMT_NOEXCEPT { return high_; }
-  constexpr uint64_t low() const FMT_NOEXCEPT { return low_; }
-
-  uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
-#  if defined(_MSC_VER) && defined(_M_X64)
-    unsigned char carry = _addcarry_u64(0, low_, n, &low_);
-    _addcarry_u64(carry, high_, 0, &high_);
-    return *this;
-#  else
-    uint64_t sum = low_ + n;
-    high_ += (sum < low_ ? 1 : 0);
-    low_ = sum;
-    return *this;
-#  endif
-  }
-#endif
-};
-
-// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.
-namespace dragonbox {
 // Computes 128-bit result of multiplication of two 64-bit unsigned integers.
-inline uint128_wrapper umul128(uint64_t x, uint64_t y) FMT_NOEXCEPT {
+inline uint128_fallback umul128(uint64_t x, uint64_t y) noexcept {
 #if FMT_USE_INT128
-  return static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
+  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
+  return {static_cast<uint64_t>(p >> 64), static_cast<uint64_t>(p)};
 #elif defined(_MSC_VER) && defined(_M_X64)
-  uint128_wrapper result;
-  result.low_ = _umul128(x, y, &result.high_);
+  auto result = uint128_fallback();
+  result.lo_ = _umul128(x, y, &result.hi_);
   return result;
 #else
-  const uint64_t mask = (uint64_t(1) << 32) - uint64_t(1);
+  const uint64_t mask = static_cast<uint64_t>(max_value<uint32_t>());
 
   uint64_t a = x >> 32;
   uint64_t b = x & mask;
@@ -863,10 +172,12 @@ inline uint128_wrapper umul128(uint64_t x, uint64_t y) FMT_NOEXCEPT {
 #endif
 }
 
+// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.
+namespace dragonbox {
 // Computes upper 64 bits of multiplication of two 64-bit unsigned integers.
-inline uint64_t umul128_upper64(uint64_t x, uint64_t y) FMT_NOEXCEPT {
+inline uint64_t umul128_upper64(uint64_t x, uint64_t y) noexcept {
 #if FMT_USE_INT128
-  auto p = static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
+  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
   return static_cast<uint64_t>(p >> 64);
 #elif defined(_MSC_VER) && defined(_M_X64)
   return __umulh(x, y);
@@ -875,170 +186,105 @@ inline uint64_t umul128_upper64(uint64_t x, uint64_t y) FMT_NOEXCEPT {
 #endif
 }
 
-// Computes upper 64 bits of multiplication of a 64-bit unsigned integer and a
+// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a
 // 128-bit unsigned integer.
-inline uint64_t umul192_upper64(uint64_t x, uint128_wrapper y) FMT_NOEXCEPT {
-  uint128_wrapper g0 = umul128(x, y.high());
-  g0 += umul128_upper64(x, y.low());
-  return g0.high();
+inline uint128_fallback umul192_upper128(uint64_t x,
+                                         uint128_fallback y) noexcept {
+  uint128_fallback r = umul128(x, y.high());
+  r += umul128_upper64(x, y.low());
+  return r;
 }
 
-// Computes upper 32 bits of multiplication of a 32-bit unsigned integer and a
+// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a
 // 64-bit unsigned integer.
-inline uint32_t umul96_upper32(uint32_t x, uint64_t y) FMT_NOEXCEPT {
-  return static_cast<uint32_t>(umul128_upper64(x, y));
+inline uint64_t umul96_upper64(uint32_t x, uint64_t y) noexcept {
+  return umul128_upper64(static_cast<uint64_t>(x) << 32, y);
 }
 
-// Computes middle 64 bits of multiplication of a 64-bit unsigned integer and a
+// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a
 // 128-bit unsigned integer.
-inline uint64_t umul192_middle64(uint64_t x, uint128_wrapper y) FMT_NOEXCEPT {
-  uint64_t g01 = x * y.high();
-  uint64_t g10 = umul128_upper64(x, y.low());
-  return g01 + g10;
+inline uint128_fallback umul192_lower128(uint64_t x,
+                                         uint128_fallback y) noexcept {
+  uint64_t high = x * y.high();
+  uint128_fallback high_low = umul128(x, y.low());
+  return {high + high_low.high(), high_low.low()};
 }
 
 // Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a
 // 64-bit unsigned integer.
-inline uint64_t umul96_lower64(uint32_t x, uint64_t y) FMT_NOEXCEPT {
+inline uint64_t umul96_lower64(uint32_t x, uint64_t y) noexcept {
   return x * y;
 }
 
-// Computes floor(log10(pow(2, e))) for e in [-1700, 1700] using the method from
-// https://fmt.dev/papers/Grisu-Exact.pdf#page=5, section 3.4.
-inline int floor_log10_pow2(int e) FMT_NOEXCEPT {
-  FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
-  const int shift = 22;
-  return (e * static_cast<int>(log10_2_significand >> (64 - shift))) >> shift;
+// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from
+// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1.
+inline int floor_log10_pow2(int e) noexcept {
+  FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent");
+  static_assert((-1 >> 1) == -1, "right shift is not arithmetic");
+  return (e * 315653) >> 20;
 }
 
 // Various fast log computations.
-inline int floor_log2_pow10(int e) FMT_NOEXCEPT {
+inline int floor_log2_pow10(int e) noexcept {
   FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent");
-  const uint64_t log2_10_integer_part = 3;
-  const uint64_t log2_10_fractional_digits = 0x5269e12f346e2bf9;
-  const int shift_amount = 19;
-  return (e * static_cast<int>(
-                  (log2_10_integer_part << shift_amount) |
-                  (log2_10_fractional_digits >> (64 - shift_amount)))) >>
-         shift_amount;
+  return (e * 1741647) >> 19;
 }
-inline int floor_log10_pow2_minus_log10_4_over_3(int e) FMT_NOEXCEPT {
-  FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
-  const uint64_t log10_4_over_3_fractional_digits = 0x1ffbfc2bbc780375;
-  const int shift_amount = 22;
-  return (e * static_cast<int>(log10_2_significand >> (64 - shift_amount)) -
-          static_cast<int>(log10_4_over_3_fractional_digits >>
-                           (64 - shift_amount))) >>
-         shift_amount;
+inline int floor_log10_pow2_minus_log10_4_over_3(int e) noexcept {
+  FMT_ASSERT(e <= 2936 && e >= -2985, "too large exponent");
+  return (e * 631305 - 261663) >> 21;
 }
 
-// Returns true iff x is divisible by pow(2, exp).
-inline bool divisible_by_power_of_2(uint32_t x, int exp) FMT_NOEXCEPT {
-  FMT_ASSERT(exp >= 1, "");
-  FMT_ASSERT(x != 0, "");
-#ifdef FMT_BUILTIN_CTZ
-  return FMT_BUILTIN_CTZ(x) >= exp;
-#else
-  return exp < num_bits<uint32_t>() && x == ((x >> exp) << exp);
-#endif
-}
-inline bool divisible_by_power_of_2(uint64_t x, int exp) FMT_NOEXCEPT {
-  FMT_ASSERT(exp >= 1, "");
-  FMT_ASSERT(x != 0, "");
-#ifdef FMT_BUILTIN_CTZLL
-  return FMT_BUILTIN_CTZLL(x) >= exp;
-#else
-  return exp < num_bits<uint64_t>() && x == ((x >> exp) << exp);
-#endif
-}
-
-// Table entry type for divisibility test.
-template <typename T> struct divtest_table_entry {
-  T mod_inv;
-  T max_quotient;
-};
-
-// Returns true iff x is divisible by pow(5, exp).
-inline bool divisible_by_power_of_5(uint32_t x, int exp) FMT_NOEXCEPT {
-  FMT_ASSERT(exp <= 10, "too large exponent");
-  static constexpr const divtest_table_entry<uint32_t> divtest_table[] = {
-      {0x00000001, 0xffffffff}, {0xcccccccd, 0x33333333},
-      {0xc28f5c29, 0x0a3d70a3}, {0x26e978d5, 0x020c49ba},
-      {0x3afb7e91, 0x0068db8b}, {0x0bcbe61d, 0x0014f8b5},
-      {0x68c26139, 0x000431bd}, {0xae8d46a5, 0x0000d6bf},
-      {0x22e90e21, 0x00002af3}, {0x3a2e9c6d, 0x00000897},
-      {0x3ed61f49, 0x000001b7}};
-  return x * divtest_table[exp].mod_inv <= divtest_table[exp].max_quotient;
-}
-inline bool divisible_by_power_of_5(uint64_t x, int exp) FMT_NOEXCEPT {
-  FMT_ASSERT(exp <= 23, "too large exponent");
-  static constexpr const divtest_table_entry<uint64_t> divtest_table[] = {
-      {0x0000000000000001, 0xffffffffffffffff},
-      {0xcccccccccccccccd, 0x3333333333333333},
-      {0x8f5c28f5c28f5c29, 0x0a3d70a3d70a3d70},
-      {0x1cac083126e978d5, 0x020c49ba5e353f7c},
-      {0xd288ce703afb7e91, 0x0068db8bac710cb2},
-      {0x5d4e8fb00bcbe61d, 0x0014f8b588e368f0},
-      {0x790fb65668c26139, 0x000431bde82d7b63},
-      {0xe5032477ae8d46a5, 0x0000d6bf94d5e57a},
-      {0xc767074b22e90e21, 0x00002af31dc46118},
-      {0x8e47ce423a2e9c6d, 0x0000089705f4136b},
-      {0x4fa7f60d3ed61f49, 0x000001b7cdfd9d7b},
-      {0x0fee64690c913975, 0x00000057f5ff85e5},
-      {0x3662e0e1cf503eb1, 0x000000119799812d},
-      {0xa47a2cf9f6433fbd, 0x0000000384b84d09},
-      {0x54186f653140a659, 0x00000000b424dc35},
-      {0x7738164770402145, 0x0000000024075f3d},
-      {0xe4a4d1417cd9a041, 0x000000000734aca5},
-      {0xc75429d9e5c5200d, 0x000000000170ef54},
-      {0xc1773b91fac10669, 0x000000000049c977},
-      {0x26b172506559ce15, 0x00000000000ec1e4},
-      {0xd489e3a9addec2d1, 0x000000000002f394},
-      {0x90e860bb892c8d5d, 0x000000000000971d},
-      {0x502e79bf1b6f4f79, 0x0000000000001e39},
-      {0xdcd618596be30fe5, 0x000000000000060b}};
-  return x * divtest_table[exp].mod_inv <= divtest_table[exp].max_quotient;
-}
+static constexpr struct {
+  uint32_t divisor;
+  int shift_amount;
+} div_small_pow10_infos[] = {{10, 16}, {100, 16}};
 
-// Replaces n by floor(n / pow(5, N)) returning true if and only if n is
-// divisible by pow(5, N).
-// Precondition: n <= 2 * pow(5, N + 1).
+// Replaces n by floor(n / pow(10, N)) returning true if and only if n is
+// divisible by pow(10, N).
+// Precondition: n <= pow(10, N + 1).
 template <int N>
-bool check_divisibility_and_divide_by_pow5(uint32_t& n) FMT_NOEXCEPT {
-  static constexpr struct {
-    uint32_t magic_number;
-    int bits_for_comparison;
-    uint32_t threshold;
-    int shift_amount;
-  } infos[] = {{0xcccd, 16, 0x3333, 18}, {0xa429, 8, 0x0a, 20}};
-  constexpr auto info = infos[N - 1];
-  n *= info.magic_number;
-  const uint32_t comparison_mask = (1u << info.bits_for_comparison) - 1;
-  bool result = (n & comparison_mask) <= info.threshold;
+bool check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept {
+  // The numbers below are chosen such that:
+  //   1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100,
+  //   2. nm mod 2^k < m if and only if n is divisible by d,
+  // where m is magic_number, k is shift_amount
+  // and d is divisor.
+  //
+  // Item 1 is a common technique of replacing division by a constant with
+  // multiplication, see e.g. "Division by Invariant Integers Using
+  // Multiplication" by Granlund and Montgomery (1994). magic_number (m) is set
+  // to ceil(2^k/d) for large enough k.
+  // The idea for item 2 originates from Schubfach.
+  constexpr auto info = div_small_pow10_infos[N - 1];
+  FMT_ASSERT(n <= info.divisor * 10, "n is too large");
+  constexpr uint32_t magic_number =
+      (1u << info.shift_amount) / info.divisor + 1;
+  n *= magic_number;
+  const uint32_t comparison_mask = (1u << info.shift_amount) - 1;
+  bool result = (n & comparison_mask) < magic_number;
   n >>= info.shift_amount;
   return result;
 }
 
 // Computes floor(n / pow(10, N)) for small n and N.
 // Precondition: n <= pow(10, N + 1).
-template <int N> uint32_t small_division_by_pow10(uint32_t n) FMT_NOEXCEPT {
-  static constexpr struct {
-    uint32_t magic_number;
-    int shift_amount;
-    uint32_t divisor_times_10;
-  } infos[] = {{0xcccd, 19, 100}, {0xa3d8, 22, 1000}};
-  constexpr auto info = infos[N - 1];
-  FMT_ASSERT(n <= info.divisor_times_10, "n is too large");
-  return n * info.magic_number >> info.shift_amount;
+template <int N> uint32_t small_division_by_pow10(uint32_t n) noexcept {
+  constexpr auto info = div_small_pow10_infos[N - 1];
+  FMT_ASSERT(n <= info.divisor * 10, "n is too large");
+  constexpr uint32_t magic_number =
+      (1u << info.shift_amount) / info.divisor + 1;
+  return (n * magic_number) >> info.shift_amount;
 }
 
 // Computes floor(n / 10^(kappa + 1)) (float)
-inline uint32_t divide_by_10_to_kappa_plus_1(uint32_t n) FMT_NOEXCEPT {
-  return n / float_info<float>::big_divisor;
+inline uint32_t divide_by_10_to_kappa_plus_1(uint32_t n) noexcept {
+  // 1374389535 = ceil(2^37/100)
+  return static_cast<uint32_t>((static_cast<uint64_t>(n) * 1374389535) >> 37);
 }
 // Computes floor(n / 10^(kappa + 1)) (double)
-inline uint64_t divide_by_10_to_kappa_plus_1(uint64_t n) FMT_NOEXCEPT {
-  return umul128_upper64(n, 0x83126e978d4fdf3c) >> 9;
+inline uint64_t divide_by_10_to_kappa_plus_1(uint64_t n) noexcept {
+  // 2361183241434822607 = ceil(2^(64+7)/1000)
+  return umul128_upper64(n, 2361183241434822607ull) >> 7;
 }
 
 // Various subroutines using pow10 cache
@@ -1048,7 +294,7 @@ template <> struct cache_accessor<float> {
   using carrier_uint = float_info<float>::carrier_uint;
   using cache_entry_type = uint64_t;
 
-  static uint64_t get_cached_power(int k) FMT_NOEXCEPT {
+  static uint64_t get_cached_power(int k) noexcept {
     FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,
                "k is out of range");
     static constexpr const uint64_t pow10_significands[] = {
@@ -1071,54 +317,65 @@ template <> struct cache_accessor<float> {
         0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,
         0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,
         0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,
-        0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984,
-        0xa18f07d736b90be5, 0xc9f2c9cd04674ede, 0xfc6f7c4045812296,
-        0x9dc5ada82b70b59d, 0xc5371912364ce305, 0xf684df56c3e01bc6,
-        0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20,
-        0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd,
-        0x92efd1b8d0cf37be, 0xb7abc627050305ad, 0xe596b7b0c643c719,
-        0x8f7e32ce7bea5c6f, 0xb35dbf821ae4f38b, 0xe0352f62a19e306e};
+        0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940985,
+        0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297,
+        0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7,
+        0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21,
+        0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe,
+        0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a,
+        0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f};
     return pow10_significands[k - float_info<float>::min_k];
   }
 
-  static carrier_uint compute_mul(carrier_uint u,
-                                  const cache_entry_type& cache) FMT_NOEXCEPT {
-    return umul96_upper32(u, cache);
+  struct compute_mul_result {
+    carrier_uint result;
+    bool is_integer;
+  };
+  struct compute_mul_parity_result {
+    bool parity;
+    bool is_integer;
+  };
+
+  static compute_mul_result compute_mul(
+      carrier_uint u, const cache_entry_type& cache) noexcept {
+    auto r = umul96_upper64(u, cache);
+    return {static_cast<carrier_uint>(r >> 32),
+            static_cast<carrier_uint>(r) == 0};
   }
 
   static uint32_t compute_delta(const cache_entry_type& cache,
-                                int beta_minus_1) FMT_NOEXCEPT {
-    return static_cast<uint32_t>(cache >> (64 - 1 - beta_minus_1));
+                                int beta) noexcept {
+    return static_cast<uint32_t>(cache >> (64 - 1 - beta));
   }
 
-  static bool compute_mul_parity(carrier_uint two_f,
-                                 const cache_entry_type& cache,
-                                 int beta_minus_1) FMT_NOEXCEPT {
-    FMT_ASSERT(beta_minus_1 >= 1, "");
-    FMT_ASSERT(beta_minus_1 < 64, "");
+  static compute_mul_parity_result compute_mul_parity(
+      carrier_uint two_f, const cache_entry_type& cache, int beta) noexcept {
+    FMT_ASSERT(beta >= 1, "");
+    FMT_ASSERT(beta < 64, "");
 
-    return ((umul96_lower64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
+    auto r = umul96_lower64(two_f, cache);
+    return {((r >> (64 - beta)) & 1) != 0,
+            static_cast<uint32_t>(r >> (32 - beta)) == 0};
   }
 
   static carrier_uint compute_left_endpoint_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+      const cache_entry_type& cache, int beta) noexcept {
     return static_cast<carrier_uint>(
-        (cache - (cache >> (float_info<float>::significand_bits + 2))) >>
-        (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
+        (cache - (cache >> (num_significand_bits<float>() + 2))) >>
+        (64 - num_significand_bits<float>() - 1 - beta));
   }
 
   static carrier_uint compute_right_endpoint_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+      const cache_entry_type& cache, int beta) noexcept {
     return static_cast<carrier_uint>(
-        (cache + (cache >> (float_info<float>::significand_bits + 1))) >>
-        (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
+        (cache + (cache >> (num_significand_bits<float>() + 1))) >>
+        (64 - num_significand_bits<float>() - 1 - beta));
   }
 
   static carrier_uint compute_round_up_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+      const cache_entry_type& cache, int beta) noexcept {
     return (static_cast<carrier_uint>(
-                cache >>
-                (64 - float_info<float>::significand_bits - 2 - beta_minus_1)) +
+                cache >> (64 - num_significand_bits<float>() - 2 - beta)) +
             1) /
            2;
   }
@@ -1126,13 +383,13 @@ template <> struct cache_accessor<float> {
 
 template <> struct cache_accessor<double> {
   using carrier_uint = float_info<double>::carrier_uint;
-  using cache_entry_type = uint128_wrapper;
+  using cache_entry_type = uint128_fallback;
 
-  static uint128_wrapper get_cached_power(int k) FMT_NOEXCEPT {
+  static uint128_fallback get_cached_power(int k) noexcept {
     FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,
                "k is out of range");
 
-    static constexpr const uint128_wrapper pow10_significands[] = {
+    static constexpr const uint128_fallback pow10_significands[] = {
 #if FMT_USE_FULL_CACHE_DRAGONBOX
       {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
       {0x9faacf3df73609b1, 0x77b191618c54e9ad},
@@ -1482,278 +739,278 @@ template <> struct cache_accessor<double> {
       {0x85a36366eb71f041, 0x47a6da2b7f864750},
       {0xa70c3c40a64e6c51, 0x999090b65f67d924},
       {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d},
-      {0x82818f1281ed449f, 0xbff8f10e7a8921a4},
-      {0xa321f2d7226895c7, 0xaff72d52192b6a0d},
-      {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490},
-      {0xfee50b7025c36a08, 0x02f236d04753d5b4},
-      {0x9f4f2726179a2245, 0x01d762422c946590},
-      {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5},
-      {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2},
-      {0x9b934c3b330c8577, 0x63cc55f49f88eb2f},
-      {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb},
-      {0xf316271c7fc3908a, 0x8bef464e3945ef7a},
-      {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac},
-      {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317},
-      {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd},
-      {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a},
-      {0xb975d6b6ee39e436, 0xb3e2fd538e122b44},
-      {0xe7d34c64a9c85d44, 0x60dbbca87196b616},
-      {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd},
-      {0xb51d13aea4a488dd, 0x6babab6398bdbe41},
-      {0xe264589a4dcdab14, 0xc696963c7eed2dd1},
-      {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2},
-      {0xb0de65388cc8ada8, 0x3b25a55f43294bcb},
-      {0xdd15fe86affad912, 0x49ef0eb713f39ebe},
-      {0x8a2dbf142dfcc7ab, 0x6e3569326c784337},
-      {0xacb92ed9397bf996, 0x49c2c37f07965404},
-      {0xd7e77a8f87daf7fb, 0xdc33745ec97be906},
-      {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3},
-      {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c},
-      {0xd2d80db02aabd62b, 0xf50a3fa490c30190},
-      {0x83c7088e1aab65db, 0x792667c6da79e0fa},
-      {0xa4b8cab1a1563f52, 0x577001b891185938},
-      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
-      {0x80b05e5ac60b6178, 0x544f8158315b05b4},
-      {0xa0dc75f1778e39d6, 0x696361ae3db1c721},
-      {0xc913936dd571c84c, 0x03bc3a19cd1e38e9},
-      {0xfb5878494ace3a5f, 0x04ab48a04065c723},
-      {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76},
-      {0xc45d1df942711d9a, 0x3ba5d0bd324f8394},
-      {0xf5746577930d6500, 0xca8f44ec7ee36479},
-      {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb},
-      {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e},
-      {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e},
-      {0x95d04aee3b80ece5, 0xbba1f1d158724a12},
-      {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97},
-      {0xea1575143cf97226, 0xf52d09d71a3293bd},
-      {0x924d692ca61be758, 0x593c2626705f9c56},
-      {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c},
-      {0xe498f455c38b997a, 0x0b6dfb9c0f956447},
-      {0x8edf98b59a373fec, 0x4724bd4189bd5eac},
-      {0xb2977ee300c50fe7, 0x58edec91ec2cb657},
-      {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed},
-      {0x8b865b215899f46c, 0xbd79e0d20082ee74},
-      {0xae67f1e9aec07187, 0xecd8590680a3aa11},
-      {0xda01ee641a708de9, 0xe80e6f4820cc9495},
-      {0x884134fe908658b2, 0x3109058d147fdcdd},
-      {0xaa51823e34a7eede, 0xbd4b46f0599fd415},
-      {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a},
-      {0x850fadc09923329e, 0x03e2cf6bc604ddb0},
-      {0xa6539930bf6bff45, 0x84db8346b786151c},
-      {0xcfe87f7cef46ff16, 0xe612641865679a63},
-      {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e},
-      {0xa26da3999aef7749, 0xe3be5e330f38f09d},
-      {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5},
-      {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6},
-      {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa},
-      {0xc646d63501a1511d, 0xb281e1fd541501b8},
-      {0xf7d88bc24209a565, 0x1f225a7ca91a4226},
-      {0x9ae757596946075f, 0x3375788de9b06958},
-      {0xc1a12d2fc3978937, 0x0052d6b1641c83ae},
-      {0xf209787bb47d6b84, 0xc0678c5dbd23a49a},
-      {0x9745eb4d50ce6332, 0xf840b7ba963646e0},
-      {0xbd176620a501fbff, 0xb650e5a93bc3d898},
-      {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe},
-      {0x93ba47c980e98cdf, 0xc66f336c36b10137},
-      {0xb8a8d9bbe123f017, 0xb80b0047445d4184},
-      {0xe6d3102ad96cec1d, 0xa60dc059157491e5},
-      {0x9043ea1ac7e41392, 0x87c89837ad68db2f},
-      {0xb454e4a179dd1877, 0x29babe4598c311fb},
-      {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a},
-      {0x8ce2529e2734bb1d, 0x1899e4a65f58660c},
-      {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f},
-      {0xdc21a1171d42645d, 0x76707543f4fa1f73},
-      {0x899504ae72497eba, 0x6a06494a791c53a8},
-      {0xabfa45da0edbde69, 0x0487db9d17636892},
-      {0xd6f8d7509292d603, 0x45a9d2845d3c42b6},
-      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
-      {0xa7f26836f282b732, 0x8e6cac7768d7141e},
-      {0xd1ef0244af2364ff, 0x3207d795430cd926},
-      {0x8335616aed761f1f, 0x7f44e6bd49e807b8},
-      {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6},
-      {0xcd036837130890a1, 0x36dba887c37a8c0f},
-      {0x802221226be55a64, 0xc2494954da2c9789},
-      {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c},
-      {0xc83553c5c8965d3d, 0x6f92829494e5acc7},
-      {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9},
-      {0x9c69a97284b578d7, 0xff2a760414536efb},
-      {0xc38413cf25e2d70d, 0xfef5138519684aba},
-      {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69},
-      {0x98bf2f79d5993802, 0xef2f773ffbd97a61},
-      {0xbeeefb584aff8603, 0xaafb550ffacfd8fa},
-      {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38},
-      {0x952ab45cfa97a0b2, 0xdd945a747bf26183},
-      {0xba756174393d88df, 0x94f971119aeef9e4},
-      {0xe912b9d1478ceb17, 0x7a37cd5601aab85d},
-      {0x91abb422ccb812ee, 0xac62e055c10ab33a},
-      {0xb616a12b7fe617aa, 0x577b986b314d6009},
-      {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b},
-      {0x8e41ade9fbebc27d, 0x14588f13be847307},
-      {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8},
-      {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb},
-      {0x8aec23d680043bee, 0x25de7bb9480d5854},
-      {0xada72ccc20054ae9, 0xaf561aa79a10ae6a},
-      {0xd910f7ff28069da4, 0x1b2ba1518094da04},
-      {0x87aa9aff79042286, 0x90fb44d2f05d0842},
-      {0xa99541bf57452b28, 0x353a1607ac744a53},
-      {0xd3fa922f2d1675f2, 0x42889b8997915ce8},
-      {0x847c9b5d7c2e09b7, 0x69956135febada11},
-      {0xa59bc234db398c25, 0x43fab9837e699095},
-      {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb},
-      {0x8161afb94b44f57d, 0x1d1be0eebac278f5},
-      {0xa1ba1ba79e1632dc, 0x6462d92a69731732},
-      {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe},
-      {0xfcb2cb35e702af78, 0x5cda735244c3d43e},
-      {0x9defbf01b061adab, 0x3a0888136afa64a7},
-      {0xc56baec21c7a1916, 0x088aaa1845b8fdd0},
-      {0xf6c69a72a3989f5b, 0x8aad549e57273d45},
-      {0x9a3c2087a63f6399, 0x36ac54e2f678864b},
-      {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd},
-      {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5},
-      {0x969eb7c47859e743, 0x9f644ae5a4b1b325},
-      {0xbc4665b596706114, 0x873d5d9f0dde1fee},
-      {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea},
-      {0x9316ff75dd87cbd8, 0x09a7f12442d588f2},
-      {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f},
-      {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa},
-      {0x8fa475791a569d10, 0xf96e017d694487bc},
-      {0xb38d92d760ec4455, 0x37c981dcc395a9ac},
-      {0xe070f78d3927556a, 0x85bbe253f47b1417},
-      {0x8c469ab843b89562, 0x93956d7478ccec8e},
-      {0xaf58416654a6babb, 0x387ac8d1970027b2},
-      {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e},
-      {0x88fcf317f22241e2, 0x441fece3bdf81f03},
-      {0xab3c2fddeeaad25a, 0xd527e81cad7626c3},
-      {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074},
-      {0x85c7056562757456, 0xf6872d5667844e49},
-      {0xa738c6bebb12d16c, 0xb428f8ac016561db},
-      {0xd106f86e69d785c7, 0xe13336d701beba52},
-      {0x82a45b450226b39c, 0xecc0024661173473},
-      {0xa34d721642b06084, 0x27f002d7f95d0190},
-      {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4},
-      {0xff290242c83396ce, 0x7e67047175a15271},
-      {0x9f79a169bd203e41, 0x0f0062c6e984d386},
-      {0xc75809c42c684dd1, 0x52c07b78a3e60868},
-      {0xf92e0c3537826145, 0xa7709a56ccdf8a82},
-      {0x9bbcc7a142b17ccb, 0x88a66076400bb691},
-      {0xc2abf989935ddbfe, 0x6acff893d00ea435},
-      {0xf356f7ebf83552fe, 0x0583f6b8c4124d43},
-      {0x98165af37b2153de, 0xc3727a337a8b704a},
-      {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c},
-      {0xeda2ee1c7064130c, 0x1162def06f79df73},
-      {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8},
-      {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692},
-      {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437},
-      {0x910ab1d4db9914a0, 0x1d9c9892400a22a2},
-      {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b},
-      {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d},
-      {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
-      {0xb10d8e1456105dad, 0x7425a83e872c5f47},
-      {0xdd50f1996b947518, 0xd12f124e28f77719},
-      {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f},
-      {0xace73cbfdc0bfb7b, 0x636cc64d1001550b},
-      {0xd8210befd30efa5a, 0x3c47f7e05401aa4e},
-      {0x8714a775e3e95c78, 0x65acfaec34810a71},
-      {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d},
-      {0xd31045a8341ca07c, 0x1ede48111209a050},
-      {0x83ea2b892091e44d, 0x934aed0aab460432},
-      {0xa4e4b66b68b65d60, 0xf81da84d5617853f},
-      {0xce1de40642e3f4b9, 0x36251260ab9d668e},
-      {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019},
-      {0xa1075a24e4421730, 0xb24cf65b8612f81f},
-      {0xc94930ae1d529cfc, 0xdee033f26797b627},
-      {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1},
-      {0x9d412e0806e88aa5, 0x8e1f289560ee864e},
-      {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2},
-      {0xf5b5d7ec8acb58a2, 0xae10af696774b1db},
-      {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29},
-      {0xbff610b0cc6edd3f, 0x17fd090a58d32af3},
-      {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0},
-      {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e},
-      {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1},
-      {0xea53df5fd18d5513, 0x84c86189216dc5ed},
-      {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4},
-      {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1},
-      {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
-      {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e},
-      {0xb2c71d5bca9023f8, 0x743e20e9ef511012},
-      {0xdf78e4b2bd342cf6, 0x914da9246b255416},
-      {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e},
-      {0xae9672aba3d0c320, 0xa184ac2473b529b1},
-      {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e},
-      {0x8865899617fb1871, 0x7e2fa67c7a658892},
-      {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7},
-      {0xd51ea6fa85785631, 0x552a74227f3ea565},
-      {0x8533285c936b35de, 0xd53a88958f87275f},
-      {0xa67ff273b8460356, 0x8a892abaf368f137},
-      {0xd01fef10a657842c, 0x2d2b7569b0432d85},
-      {0x8213f56a67f6b29b, 0x9c3b29620e29fc73},
-      {0xa298f2c501f45f42, 0x8349f3ba91b47b8f},
-      {0xcb3f2f7642717713, 0x241c70a936219a73},
-      {0xfe0efb53d30dd4d7, 0xed238cd383aa0110},
-      {0x9ec95d1463e8a506, 0xf4363804324a40aa},
-      {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5},
-      {0xf81aa16fdc1b81da, 0xdd94b7868e94050a},
-      {0x9b10a4e5e9913128, 0xca7cf2b4191c8326},
-      {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0},
-      {0xf24a01a73cf2dccf, 0xbc633b39673c8cec},
-      {0x976e41088617ca01, 0xd5be0503e085d813},
-      {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18},
-      {0xec9c459d51852ba2, 0xddf8e7d60ed1219e},
-      {0x93e1ab8252f33b45, 0xcabb90e5c942b503},
-      {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
-      {0xe7109bfba19c0c9d, 0x0cc512670a783ad4},
-      {0x906a617d450187e2, 0x27fb2b80668b24c5},
-      {0xb484f9dc9641e9da, 0xb1f9f660802dedf6},
-      {0xe1a63853bbd26451, 0x5e7873f8a0396973},
-      {0x8d07e33455637eb2, 0xdb0b487b6423e1e8},
-      {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62},
-      {0xdc5c5301c56b75f7, 0x7641a140cc7810fb},
-      {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d},
-      {0xac2820d9623bf429, 0x546345fa9fbdcd44},
-      {0xd732290fbacaf133, 0xa97c177947ad4095},
-      {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d},
-      {0xa81f301449ee8c70, 0x5c68f256bfff5a74},
-      {0xd226fc195c6a2f8c, 0x73832eec6fff3111},
-      {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab},
-      {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55},
-      {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb},
-      {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3},
-      {0xa0555e361951c366, 0xd7e105bcc332621f},
-      {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7},
-      {0xfa856334878fc150, 0xb14f98f6f0feb951},
-      {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3},
-      {0xc3b8358109e84f07, 0x0a862f80ec4700c8},
-      {0xf4a642e14c6262c8, 0xcd27bb612758c0fa},
-      {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c},
-      {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3},
-      {0xeeea5d5004981478, 0x1858ccfce06cac74},
-      {0x95527a5202df0ccb, 0x0f37801e0c43ebc8},
-      {0xbaa718e68396cffd, 0xd30560258f54e6ba},
-      {0xe950df20247c83fd, 0x47c6b82ef32a2069},
-      {0x91d28b7416cdd27e, 0x4cdc331d57fa5441},
-      {0xb6472e511c81471d, 0xe0133fe4adf8e952},
-      {0xe3d8f9e563a198e5, 0x58180fddd97723a6},
-      {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648},
-      {0xb201833b35d63f73, 0x2cd2cc6551e513da},
-      {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1},
-      {0x8b112e86420f6191, 0xfb04afaf27faf782},
-      {0xadd57a27d29339f6, 0x79c5db9af1f9b563},
-      {0xd94ad8b1c7380874, 0x18375281ae7822bc},
-      {0x87cec76f1c830548, 0x8f2293910d0b15b5},
-      {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22},
-      {0xd433179d9c8cb841, 0x5fa60692a46151eb},
-      {0x849feec281d7f328, 0xdbc7c41ba6bcd333},
-      {0xa5c7ea73224deff3, 0x12b9b522906c0800},
-      {0xcf39e50feae16bef, 0xd768226b34870a00},
-      {0x81842f29f2cce375, 0xe6a1158300d46640},
-      {0xa1e53af46f801c53, 0x60495ae3c1097fd0},
-      {0xca5e89b18b602368, 0x385bb19cb14bdfc4},
-      {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5},
-      {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d1},
-      {0xc5a05277621be293, 0xc7098b7305241885},
+      {0x82818f1281ed449f, 0xbff8f10e7a8921a5},
+      {0xa321f2d7226895c7, 0xaff72d52192b6a0e},
+      {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491},
+      {0xfee50b7025c36a08, 0x02f236d04753d5b5},
+      {0x9f4f2726179a2245, 0x01d762422c946591},
+      {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6},
+      {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3},
+      {0x9b934c3b330c8577, 0x63cc55f49f88eb30},
+      {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc},
+      {0xf316271c7fc3908a, 0x8bef464e3945ef7b},
+      {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad},
+      {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318},
+      {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde},
+      {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b},
+      {0xb975d6b6ee39e436, 0xb3e2fd538e122b45},
+      {0xe7d34c64a9c85d44, 0x60dbbca87196b617},
+      {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce},
+      {0xb51d13aea4a488dd, 0x6babab6398bdbe42},
+      {0xe264589a4dcdab14, 0xc696963c7eed2dd2},
+      {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3},
+      {0xb0de65388cc8ada8, 0x3b25a55f43294bcc},
+      {0xdd15fe86affad912, 0x49ef0eb713f39ebf},
+      {0x8a2dbf142dfcc7ab, 0x6e3569326c784338},
+      {0xacb92ed9397bf996, 0x49c2c37f07965405},
+      {0xd7e77a8f87daf7fb, 0xdc33745ec97be907},
+      {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4},
+      {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d},
+      {0xd2d80db02aabd62b, 0xf50a3fa490c30191},
+      {0x83c7088e1aab65db, 0x792667c6da79e0fb},
+      {0xa4b8cab1a1563f52, 0x577001b891185939},
+      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},
+      {0x80b05e5ac60b6178, 0x544f8158315b05b5},
+      {0xa0dc75f1778e39d6, 0x696361ae3db1c722},
+      {0xc913936dd571c84c, 0x03bc3a19cd1e38ea},
+      {0xfb5878494ace3a5f, 0x04ab48a04065c724},
+      {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77},
+      {0xc45d1df942711d9a, 0x3ba5d0bd324f8395},
+      {0xf5746577930d6500, 0xca8f44ec7ee3647a},
+      {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc},
+      {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f},
+      {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f},
+      {0x95d04aee3b80ece5, 0xbba1f1d158724a13},
+      {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98},
+      {0xea1575143cf97226, 0xf52d09d71a3293be},
+      {0x924d692ca61be758, 0x593c2626705f9c57},
+      {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d},
+      {0xe498f455c38b997a, 0x0b6dfb9c0f956448},
+      {0x8edf98b59a373fec, 0x4724bd4189bd5ead},
+      {0xb2977ee300c50fe7, 0x58edec91ec2cb658},
+      {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee},
+      {0x8b865b215899f46c, 0xbd79e0d20082ee75},
+      {0xae67f1e9aec07187, 0xecd8590680a3aa12},
+      {0xda01ee641a708de9, 0xe80e6f4820cc9496},
+      {0x884134fe908658b2, 0x3109058d147fdcde},
+      {0xaa51823e34a7eede, 0xbd4b46f0599fd416},
+      {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b},
+      {0x850fadc09923329e, 0x03e2cf6bc604ddb1},
+      {0xa6539930bf6bff45, 0x84db8346b786151d},
+      {0xcfe87f7cef46ff16, 0xe612641865679a64},
+      {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f},
+      {0xa26da3999aef7749, 0xe3be5e330f38f09e},
+      {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6},
+      {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7},
+      {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb},
+      {0xc646d63501a1511d, 0xb281e1fd541501b9},
+      {0xf7d88bc24209a565, 0x1f225a7ca91a4227},
+      {0x9ae757596946075f, 0x3375788de9b06959},
+      {0xc1a12d2fc3978937, 0x0052d6b1641c83af},
+      {0xf209787bb47d6b84, 0xc0678c5dbd23a49b},
+      {0x9745eb4d50ce6332, 0xf840b7ba963646e1},
+      {0xbd176620a501fbff, 0xb650e5a93bc3d899},
+      {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf},
+      {0x93ba47c980e98cdf, 0xc66f336c36b10138},
+      {0xb8a8d9bbe123f017, 0xb80b0047445d4185},
+      {0xe6d3102ad96cec1d, 0xa60dc059157491e6},
+      {0x9043ea1ac7e41392, 0x87c89837ad68db30},
+      {0xb454e4a179dd1877, 0x29babe4598c311fc},
+      {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b},
+      {0x8ce2529e2734bb1d, 0x1899e4a65f58660d},
+      {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90},
+      {0xdc21a1171d42645d, 0x76707543f4fa1f74},
+      {0x899504ae72497eba, 0x6a06494a791c53a9},
+      {0xabfa45da0edbde69, 0x0487db9d17636893},
+      {0xd6f8d7509292d603, 0x45a9d2845d3c42b7},
+      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},
+      {0xa7f26836f282b732, 0x8e6cac7768d7141f},
+      {0xd1ef0244af2364ff, 0x3207d795430cd927},
+      {0x8335616aed761f1f, 0x7f44e6bd49e807b9},
+      {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7},
+      {0xcd036837130890a1, 0x36dba887c37a8c10},
+      {0x802221226be55a64, 0xc2494954da2c978a},
+      {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d},
+      {0xc83553c5c8965d3d, 0x6f92829494e5acc8},
+      {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa},
+      {0x9c69a97284b578d7, 0xff2a760414536efc},
+      {0xc38413cf25e2d70d, 0xfef5138519684abb},
+      {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a},
+      {0x98bf2f79d5993802, 0xef2f773ffbd97a62},
+      {0xbeeefb584aff8603, 0xaafb550ffacfd8fb},
+      {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39},
+      {0x952ab45cfa97a0b2, 0xdd945a747bf26184},
+      {0xba756174393d88df, 0x94f971119aeef9e5},
+      {0xe912b9d1478ceb17, 0x7a37cd5601aab85e},
+      {0x91abb422ccb812ee, 0xac62e055c10ab33b},
+      {0xb616a12b7fe617aa, 0x577b986b314d600a},
+      {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c},
+      {0x8e41ade9fbebc27d, 0x14588f13be847308},
+      {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9},
+      {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc},
+      {0x8aec23d680043bee, 0x25de7bb9480d5855},
+      {0xada72ccc20054ae9, 0xaf561aa79a10ae6b},
+      {0xd910f7ff28069da4, 0x1b2ba1518094da05},
+      {0x87aa9aff79042286, 0x90fb44d2f05d0843},
+      {0xa99541bf57452b28, 0x353a1607ac744a54},
+      {0xd3fa922f2d1675f2, 0x42889b8997915ce9},
+      {0x847c9b5d7c2e09b7, 0x69956135febada12},
+      {0xa59bc234db398c25, 0x43fab9837e699096},
+      {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc},
+      {0x8161afb94b44f57d, 0x1d1be0eebac278f6},
+      {0xa1ba1ba79e1632dc, 0x6462d92a69731733},
+      {0xca28a291859bbf93, 0x7d7b8f7503cfdcff},
+      {0xfcb2cb35e702af78, 0x5cda735244c3d43f},
+      {0x9defbf01b061adab, 0x3a0888136afa64a8},
+      {0xc56baec21c7a1916, 0x088aaa1845b8fdd1},
+      {0xf6c69a72a3989f5b, 0x8aad549e57273d46},
+      {0x9a3c2087a63f6399, 0x36ac54e2f678864c},
+      {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de},
+      {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6},
+      {0x969eb7c47859e743, 0x9f644ae5a4b1b326},
+      {0xbc4665b596706114, 0x873d5d9f0dde1fef},
+      {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb},
+      {0x9316ff75dd87cbd8, 0x09a7f12442d588f3},
+      {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30},
+      {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb},
+      {0x8fa475791a569d10, 0xf96e017d694487bd},
+      {0xb38d92d760ec4455, 0x37c981dcc395a9ad},
+      {0xe070f78d3927556a, 0x85bbe253f47b1418},
+      {0x8c469ab843b89562, 0x93956d7478ccec8f},
+      {0xaf58416654a6babb, 0x387ac8d1970027b3},
+      {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f},
+      {0x88fcf317f22241e2, 0x441fece3bdf81f04},
+      {0xab3c2fddeeaad25a, 0xd527e81cad7626c4},
+      {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075},
+      {0x85c7056562757456, 0xf6872d5667844e4a},
+      {0xa738c6bebb12d16c, 0xb428f8ac016561dc},
+      {0xd106f86e69d785c7, 0xe13336d701beba53},
+      {0x82a45b450226b39c, 0xecc0024661173474},
+      {0xa34d721642b06084, 0x27f002d7f95d0191},
+      {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5},
+      {0xff290242c83396ce, 0x7e67047175a15272},
+      {0x9f79a169bd203e41, 0x0f0062c6e984d387},
+      {0xc75809c42c684dd1, 0x52c07b78a3e60869},
+      {0xf92e0c3537826145, 0xa7709a56ccdf8a83},
+      {0x9bbcc7a142b17ccb, 0x88a66076400bb692},
+      {0xc2abf989935ddbfe, 0x6acff893d00ea436},
+      {0xf356f7ebf83552fe, 0x0583f6b8c4124d44},
+      {0x98165af37b2153de, 0xc3727a337a8b704b},
+      {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d},
+      {0xeda2ee1c7064130c, 0x1162def06f79df74},
+      {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9},
+      {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693},
+      {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438},
+      {0x910ab1d4db9914a0, 0x1d9c9892400a22a3},
+      {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c},
+      {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e},
+      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},
+      {0xb10d8e1456105dad, 0x7425a83e872c5f48},
+      {0xdd50f1996b947518, 0xd12f124e28f7771a},
+      {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70},
+      {0xace73cbfdc0bfb7b, 0x636cc64d1001550c},
+      {0xd8210befd30efa5a, 0x3c47f7e05401aa4f},
+      {0x8714a775e3e95c78, 0x65acfaec34810a72},
+      {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e},
+      {0xd31045a8341ca07c, 0x1ede48111209a051},
+      {0x83ea2b892091e44d, 0x934aed0aab460433},
+      {0xa4e4b66b68b65d60, 0xf81da84d56178540},
+      {0xce1de40642e3f4b9, 0x36251260ab9d668f},
+      {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a},
+      {0xa1075a24e4421730, 0xb24cf65b8612f820},
+      {0xc94930ae1d529cfc, 0xdee033f26797b628},
+      {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2},
+      {0x9d412e0806e88aa5, 0x8e1f289560ee864f},
+      {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3},
+      {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc},
+      {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a},
+      {0xbff610b0cc6edd3f, 0x17fd090a58d32af4},
+      {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1},
+      {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f},
+      {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2},
+      {0xea53df5fd18d5513, 0x84c86189216dc5ee},
+      {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5},
+      {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2},
+      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},
+      {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f},
+      {0xb2c71d5bca9023f8, 0x743e20e9ef511013},
+      {0xdf78e4b2bd342cf6, 0x914da9246b255417},
+      {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f},
+      {0xae9672aba3d0c320, 0xa184ac2473b529b2},
+      {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f},
+      {0x8865899617fb1871, 0x7e2fa67c7a658893},
+      {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8},
+      {0xd51ea6fa85785631, 0x552a74227f3ea566},
+      {0x8533285c936b35de, 0xd53a88958f872760},
+      {0xa67ff273b8460356, 0x8a892abaf368f138},
+      {0xd01fef10a657842c, 0x2d2b7569b0432d86},
+      {0x8213f56a67f6b29b, 0x9c3b29620e29fc74},
+      {0xa298f2c501f45f42, 0x8349f3ba91b47b90},
+      {0xcb3f2f7642717713, 0x241c70a936219a74},
+      {0xfe0efb53d30dd4d7, 0xed238cd383aa0111},
+      {0x9ec95d1463e8a506, 0xf4363804324a40ab},
+      {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6},
+      {0xf81aa16fdc1b81da, 0xdd94b7868e94050b},
+      {0x9b10a4e5e9913128, 0xca7cf2b4191c8327},
+      {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1},
+      {0xf24a01a73cf2dccf, 0xbc633b39673c8ced},
+      {0x976e41088617ca01, 0xd5be0503e085d814},
+      {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19},
+      {0xec9c459d51852ba2, 0xddf8e7d60ed1219f},
+      {0x93e1ab8252f33b45, 0xcabb90e5c942b504},
+      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},
+      {0xe7109bfba19c0c9d, 0x0cc512670a783ad5},
+      {0x906a617d450187e2, 0x27fb2b80668b24c6},
+      {0xb484f9dc9641e9da, 0xb1f9f660802dedf7},
+      {0xe1a63853bbd26451, 0x5e7873f8a0396974},
+      {0x8d07e33455637eb2, 0xdb0b487b6423e1e9},
+      {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63},
+      {0xdc5c5301c56b75f7, 0x7641a140cc7810fc},
+      {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e},
+      {0xac2820d9623bf429, 0x546345fa9fbdcd45},
+      {0xd732290fbacaf133, 0xa97c177947ad4096},
+      {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e},
+      {0xa81f301449ee8c70, 0x5c68f256bfff5a75},
+      {0xd226fc195c6a2f8c, 0x73832eec6fff3112},
+      {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac},
+      {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56},
+      {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec},
+      {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4},
+      {0xa0555e361951c366, 0xd7e105bcc3326220},
+      {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8},
+      {0xfa856334878fc150, 0xb14f98f6f0feb952},
+      {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4},
+      {0xc3b8358109e84f07, 0x0a862f80ec4700c9},
+      {0xf4a642e14c6262c8, 0xcd27bb612758c0fb},
+      {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d},
+      {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4},
+      {0xeeea5d5004981478, 0x1858ccfce06cac75},
+      {0x95527a5202df0ccb, 0x0f37801e0c43ebc9},
+      {0xbaa718e68396cffd, 0xd30560258f54e6bb},
+      {0xe950df20247c83fd, 0x47c6b82ef32a206a},
+      {0x91d28b7416cdd27e, 0x4cdc331d57fa5442},
+      {0xb6472e511c81471d, 0xe0133fe4adf8e953},
+      {0xe3d8f9e563a198e5, 0x58180fddd97723a7},
+      {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649},
+      {0xb201833b35d63f73, 0x2cd2cc6551e513db},
+      {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2},
+      {0x8b112e86420f6191, 0xfb04afaf27faf783},
+      {0xadd57a27d29339f6, 0x79c5db9af1f9b564},
+      {0xd94ad8b1c7380874, 0x18375281ae7822bd},
+      {0x87cec76f1c830548, 0x8f2293910d0b15b6},
+      {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23},
+      {0xd433179d9c8cb841, 0x5fa60692a46151ec},
+      {0x849feec281d7f328, 0xdbc7c41ba6bcd334},
+      {0xa5c7ea73224deff3, 0x12b9b522906c0801},
+      {0xcf39e50feae16bef, 0xd768226b34870a01},
+      {0x81842f29f2cce375, 0xe6a1158300d46641},
+      {0xa1e53af46f801c53, 0x60495ae3c1097fd1},
+      {0xca5e89b18b602368, 0x385bb19cb14bdfc5},
+      {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6},
+      {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2},
+      {0xc5a05277621be293, 0xc7098b7305241886},
       { 0xf70867153aa2db38,
-        0xb8cbee4fc66d1ea7 }
+        0xb8cbee4fc66d1ea8 }
 #else
       {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
       {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
@@ -1768,17 +1025,17 @@ template <> struct cache_accessor<double> {
       {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
       {0xc350000000000000, 0x0000000000000000},
       {0x9dc5ada82b70b59d, 0xf020000000000000},
-      {0xfee50b7025c36a08, 0x02f236d04753d5b4},
-      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
-      {0xa6539930bf6bff45, 0x84db8346b786151c},
-      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
-      {0xd910f7ff28069da4, 0x1b2ba1518094da04},
-      {0xaf58416654a6babb, 0x387ac8d1970027b2},
-      {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
-      {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
-      {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
+      {0xfee50b7025c36a08, 0x02f236d04753d5b5},
+      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},
+      {0xa6539930bf6bff45, 0x84db8346b786151d},
+      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},
+      {0xd910f7ff28069da4, 0x1b2ba1518094da05},
+      {0xaf58416654a6babb, 0x387ac8d1970027b3},
+      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},
+      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},
+      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},
       { 0x95527a5202df0ccb,
-        0x0f37801e0c43ebc8 }
+        0x0f37801e0c43ebc9 }
 #endif
     };
 
@@ -1796,15 +1053,6 @@ template <> struct cache_accessor<double> {
         0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed,
         0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9};
 
-    static constexpr const uint32_t pow10_recovery_errors[] = {
-        0x50001400, 0x54044100, 0x54014555, 0x55954415, 0x54115555, 0x00000001,
-        0x50000000, 0x00104000, 0x54010004, 0x05004001, 0x55555544, 0x41545555,
-        0x54040551, 0x15445545, 0x51555514, 0x10000015, 0x00101100, 0x01100015,
-        0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04450514, 0x45414110,
-        0x55555145, 0x50544050, 0x15040155, 0x11054140, 0x50111514, 0x11451454,
-        0x00400541, 0x00000000, 0x55555450, 0x10056551, 0x10054011, 0x55551014,
-        0x69514555, 0x05151109, 0x00155555};
-
     static const int compression_ratio = 27;
 
     // Compute base index.
@@ -1813,7 +1061,7 @@ template <> struct cache_accessor<double> {
     int offset = k - kb;
 
     // Get base cache.
-    uint128_wrapper base_cache = pow10_significands[cache_index];
+    uint128_fallback base_cache = pow10_significands[cache_index];
     if (offset == 0) return base_cache;
 
     // Compute the required amount of bit-shift.
@@ -1822,9 +1070,8 @@ template <> struct cache_accessor<double> {
 
     // Try to recover the real cache.
     uint64_t pow5 = powers_of_5_64[offset];
-    uint128_wrapper recovered_cache = umul128(base_cache.high(), pow5);
-    uint128_wrapper middle_low =
-        umul128(base_cache.low() - (kb < 0 ? 1u : 0u), pow5);
+    uint128_fallback recovered_cache = umul128(base_cache.high(), pow5);
+    uint128_fallback middle_low = umul128(base_cache.low(), pow5);
 
     recovered_cache += middle_low.high();
 
@@ -1832,60 +1079,60 @@ template <> struct cache_accessor<double> {
     uint64_t middle_to_low = recovered_cache.low() << (64 - alpha);
 
     recovered_cache =
-        uint128_wrapper{(recovered_cache.low() >> alpha) | high_to_middle,
-                        ((middle_low.low() >> alpha) | middle_to_low)};
-
-    if (kb < 0) recovered_cache += 1;
-
-    // Get error.
-    int error_idx = (k - float_info<double>::min_k) / 16;
-    uint32_t error = (pow10_recovery_errors[error_idx] >>
-                      ((k - float_info<double>::min_k) % 16) * 2) &
-                     0x3;
-
-    // Add the error back.
-    FMT_ASSERT(recovered_cache.low() + error >= recovered_cache.low(), "");
-    return {recovered_cache.high(), recovered_cache.low() + error};
+        uint128_fallback{(recovered_cache.low() >> alpha) | high_to_middle,
+                         ((middle_low.low() >> alpha) | middle_to_low)};
+    FMT_ASSERT(recovered_cache.low() + 1 != 0, "");
+    return {recovered_cache.high(), recovered_cache.low() + 1};
 #endif
   }
 
-  static carrier_uint compute_mul(carrier_uint u,
-                                  const cache_entry_type& cache) FMT_NOEXCEPT {
-    return umul192_upper64(u, cache);
+  struct compute_mul_result {
+    carrier_uint result;
+    bool is_integer;
+  };
+  struct compute_mul_parity_result {
+    bool parity;
+    bool is_integer;
+  };
+
+  static compute_mul_result compute_mul(
+      carrier_uint u, const cache_entry_type& cache) noexcept {
+    auto r = umul192_upper128(u, cache);
+    return {r.high(), r.low() == 0};
   }
 
   static uint32_t compute_delta(cache_entry_type const& cache,
-                                int beta_minus_1) FMT_NOEXCEPT {
-    return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta_minus_1));
+                                int beta) noexcept {
+    return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta));
   }
 
-  static bool compute_mul_parity(carrier_uint two_f,
-                                 const cache_entry_type& cache,
-                                 int beta_minus_1) FMT_NOEXCEPT {
-    FMT_ASSERT(beta_minus_1 >= 1, "");
-    FMT_ASSERT(beta_minus_1 < 64, "");
+  static compute_mul_parity_result compute_mul_parity(
+      carrier_uint two_f, const cache_entry_type& cache, int beta) noexcept {
+    FMT_ASSERT(beta >= 1, "");
+    FMT_ASSERT(beta < 64, "");
 
-    return ((umul192_middle64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
+    auto r = umul192_lower128(two_f, cache);
+    return {((r.high() >> (64 - beta)) & 1) != 0,
+            ((r.high() << beta) | (r.low() >> (64 - beta))) == 0};
   }
 
   static carrier_uint compute_left_endpoint_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+      const cache_entry_type& cache, int beta) noexcept {
     return (cache.high() -
-            (cache.high() >> (float_info<double>::significand_bits + 2))) >>
-           (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
+            (cache.high() >> (num_significand_bits<double>() + 2))) >>
+           (64 - num_significand_bits<double>() - 1 - beta);
   }
 
   static carrier_uint compute_right_endpoint_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+      const cache_entry_type& cache, int beta) noexcept {
     return (cache.high() +
-            (cache.high() >> (float_info<double>::significand_bits + 1))) >>
-           (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
+            (cache.high() >> (num_significand_bits<double>() + 1))) >>
+           (64 - num_significand_bits<double>() - 1 - beta);
   }
 
   static carrier_uint compute_round_up_for_shorter_interval_case(
-      const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
-    return ((cache.high() >>
-             (64 - float_info<double>::significand_bits - 2 - beta_minus_1)) +
+      const cache_entry_type& cache, int beta) noexcept {
+    return ((cache.high() >> (64 - num_significand_bits<double>() - 2 - beta)) +
             1) /
            2;
   }
@@ -1893,166 +1140,104 @@ template <> struct cache_accessor<double> {
 
 // Various integer checks
 template <class T>
-bool is_left_endpoint_integer_shorter_interval(int exponent) FMT_NOEXCEPT {
-  return exponent >=
-             float_info<
-                 T>::case_shorter_interval_left_endpoint_lower_threshold &&
-         exponent <=
-             float_info<T>::case_shorter_interval_left_endpoint_upper_threshold;
-}
-template <class T>
-bool is_endpoint_integer(typename float_info<T>::carrier_uint two_f,
-                         int exponent, int minus_k) FMT_NOEXCEPT {
-  if (exponent < float_info<T>::case_fc_pm_half_lower_threshold) return false;
-  // For k >= 0.
-  if (exponent <= float_info<T>::case_fc_pm_half_upper_threshold) return true;
-  // For k < 0.
-  if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
-  return divisible_by_power_of_5(two_f, minus_k);
-}
-
-template <class T>
-bool is_center_integer(typename float_info<T>::carrier_uint two_f, int exponent,
-                       int minus_k) FMT_NOEXCEPT {
-  // Exponent for 5 is negative.
-  if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
-  if (exponent > float_info<T>::case_fc_upper_threshold)
-    return divisible_by_power_of_5(two_f, minus_k);
-  // Both exponents are nonnegative.
-  if (exponent >= float_info<T>::case_fc_lower_threshold) return true;
-  // Exponent for 2 is negative.
-  return divisible_by_power_of_2(two_f, minus_k - exponent + 1);
+bool is_left_endpoint_integer_shorter_interval(int exponent) noexcept {
+  const int case_shorter_interval_left_endpoint_lower_threshold = 2;
+  const int case_shorter_interval_left_endpoint_upper_threshold = 3;
+  return exponent >= case_shorter_interval_left_endpoint_lower_threshold &&
+         exponent <= case_shorter_interval_left_endpoint_upper_threshold;
 }
 
 // Remove trailing zeros from n and return the number of zeros removed (float)
-FMT_INLINE int remove_trailing_zeros(uint32_t& n) FMT_NOEXCEPT {
-#ifdef FMT_BUILTIN_CTZ
-  int t = FMT_BUILTIN_CTZ(n);
-#else
-  int t = ctz(n);
-#endif
-  if (t > float_info<float>::max_trailing_zeros)
-    t = float_info<float>::max_trailing_zeros;
-
-  const uint32_t mod_inv1 = 0xcccccccd;
-  const uint32_t max_quotient1 = 0x33333333;
-  const uint32_t mod_inv2 = 0xc28f5c29;
-  const uint32_t max_quotient2 = 0x0a3d70a3;
+FMT_INLINE int remove_trailing_zeros(uint32_t& n) noexcept {
+  FMT_ASSERT(n != 0, "");
+  const uint32_t mod_inv_5 = 0xcccccccd;
+  const uint32_t mod_inv_25 = mod_inv_5 * mod_inv_5;
 
   int s = 0;
-  for (; s < t - 1; s += 2) {
-    if (n * mod_inv2 > max_quotient2) break;
-    n *= mod_inv2;
+  while (true) {
+    auto q = rotr(n * mod_inv_25, 2);
+    if (q > max_value<uint32_t>() / 100) break;
+    n = q;
+    s += 2;
   }
-  if (s < t && n * mod_inv1 <= max_quotient1) {
-    n *= mod_inv1;
-    ++s;
+  auto q = rotr(n * mod_inv_5, 1);
+  if (q <= max_value<uint32_t>() / 10) {
+    n = q;
+    s |= 1;
   }
-  n >>= s;
+
   return s;
 }
 
 // Removes trailing zeros and returns the number of zeros removed (double)
-FMT_INLINE int remove_trailing_zeros(uint64_t& n) FMT_NOEXCEPT {
-#ifdef FMT_BUILTIN_CTZLL
-  int t = FMT_BUILTIN_CTZLL(n);
-#else
-  int t = ctzll(n);
-#endif
-  if (t > float_info<double>::max_trailing_zeros)
-    t = float_info<double>::max_trailing_zeros;
-  // Divide by 10^8 and reduce to 32-bits
-  // Since ret_value.significand <= (2^64 - 1) / 1000 < 10^17,
-  // both of the quotient and the r should fit in 32-bits
-
-  const uint32_t mod_inv1 = 0xcccccccd;
-  const uint32_t max_quotient1 = 0x33333333;
-  const uint64_t mod_inv8 = 0xc767074b22e90e21;
-  const uint64_t max_quotient8 = 0x00002af31dc46118;
-
-  // If the number is divisible by 1'0000'0000, work with the quotient
-  if (t >= 8) {
-    auto quotient_candidate = n * mod_inv8;
-
-    if (quotient_candidate <= max_quotient8) {
-      auto quotient = static_cast<uint32_t>(quotient_candidate >> 8);
-
-      int s = 8;
-      for (; s < t; ++s) {
-        if (quotient * mod_inv1 > max_quotient1) break;
-        quotient *= mod_inv1;
-      }
-      quotient >>= (s - 8);
-      n = quotient;
-      return s;
+FMT_INLINE int remove_trailing_zeros(uint64_t& n) noexcept {
+  FMT_ASSERT(n != 0, "");
+
+  // This magic number is ceil(2^90 / 10^8).
+  constexpr uint64_t magic_number = 12379400392853802749ull;
+  auto nm = umul128(n, magic_number);
+
+  // Is n is divisible by 10^8?
+  if ((nm.high() & ((1ull << (90 - 64)) - 1)) == 0 && nm.low() < magic_number) {
+    // If yes, work with the quotient.
+    auto n32 = static_cast<uint32_t>(nm.high() >> (90 - 64));
+
+    const uint32_t mod_inv_5 = 0xcccccccd;
+    const uint32_t mod_inv_25 = mod_inv_5 * mod_inv_5;
+
+    int s = 8;
+    while (true) {
+      auto q = rotr(n32 * mod_inv_25, 2);
+      if (q > max_value<uint32_t>() / 100) break;
+      n32 = q;
+      s += 2;
+    }
+    auto q = rotr(n32 * mod_inv_5, 1);
+    if (q <= max_value<uint32_t>() / 10) {
+      n32 = q;
+      s |= 1;
     }
-  }
-
-  // Otherwise, work with the remainder
-  auto quotient = static_cast<uint32_t>(n / 100000000);
-  auto remainder = static_cast<uint32_t>(n - 100000000 * quotient);
-
-  if (t == 0 || remainder * mod_inv1 > max_quotient1) {
-    return 0;
-  }
-  remainder *= mod_inv1;
-
-  if (t == 1 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 1) + quotient * 10000000ull;
-    return 1;
-  }
-  remainder *= mod_inv1;
-
-  if (t == 2 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 2) + quotient * 1000000ull;
-    return 2;
-  }
-  remainder *= mod_inv1;
 
-  if (t == 3 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 3) + quotient * 100000ull;
-    return 3;
+    n = n32;
+    return s;
   }
-  remainder *= mod_inv1;
 
-  if (t == 4 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 4) + quotient * 10000ull;
-    return 4;
-  }
-  remainder *= mod_inv1;
+  // If n is not divisible by 10^8, work with n itself.
+  const uint64_t mod_inv_5 = 0xcccccccccccccccd;
+  const uint64_t mod_inv_25 = mod_inv_5 * mod_inv_5;
 
-  if (t == 5 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 5) + quotient * 1000ull;
-    return 5;
+  int s = 0;
+  while (true) {
+    auto q = rotr(n * mod_inv_25, 2);
+    if (q > max_value<uint64_t>() / 100) break;
+    n = q;
+    s += 2;
   }
-  remainder *= mod_inv1;
-
-  if (t == 6 || remainder * mod_inv1 > max_quotient1) {
-    n = (remainder >> 6) + quotient * 100ull;
-    return 6;
+  auto q = rotr(n * mod_inv_5, 1);
+  if (q <= max_value<uint64_t>() / 10) {
+    n = q;
+    s |= 1;
   }
-  remainder *= mod_inv1;
 
-  n = (remainder >> 7) + quotient * 10ull;
-  return 7;
+  return s;
 }
 
 // The main algorithm for shorter interval case
 template <class T>
-FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) FMT_NOEXCEPT {
+FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) noexcept {
   decimal_fp<T> ret_value;
   // Compute k and beta
   const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);
-  const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
+  const int beta = exponent + floor_log2_pow10(-minus_k);
 
   // Compute xi and zi
   using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
   const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
 
   auto xi = cache_accessor<T>::compute_left_endpoint_for_shorter_interval_case(
-      cache, beta_minus_1);
+      cache, beta);
   auto zi = cache_accessor<T>::compute_right_endpoint_for_shorter_interval_case(
-      cache, beta_minus_1);
+      cache, beta);
 
   // If the left endpoint is not an integer, increase it
   if (!is_left_endpoint_integer_shorter_interval<T>(exponent)) ++xi;
@@ -2069,8 +1254,8 @@ FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) FMT_NOEXCEPT {
 
   // Otherwise, compute the round-up of y
   ret_value.significand =
-      cache_accessor<T>::compute_round_up_for_shorter_interval_case(
-          cache, beta_minus_1);
+      cache_accessor<T>::compute_round_up_for_shorter_interval_case(cache,
+                                                                    beta);
   ret_value.exponent = minus_k;
 
   // When tie occurs, choose one of them according to the rule
@@ -2085,7 +1270,7 @@ FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) FMT_NOEXCEPT {
   return ret_value;
 }
 
-template <typename T> decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT {
+template <typename T> decimal_fp<T> to_decimal(T x) noexcept {
   // Step 1: integer promotion & Schubfach multiplier calculation.
 
   using carrier_uint = typename float_info<T>::carrier_uint;
@@ -2094,23 +1279,25 @@ template <typename T> decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT {
 
   // Extract significand bits and exponent bits.
   const carrier_uint significand_mask =
-      (static_cast<carrier_uint>(1) << float_info<T>::significand_bits) - 1;
+      (static_cast<carrier_uint>(1) << num_significand_bits<T>()) - 1;
   carrier_uint significand = (br & significand_mask);
-  int exponent = static_cast<int>((br & exponent_mask<T>()) >>
-                                  float_info<T>::significand_bits);
+  int exponent =
+      static_cast<int>((br & exponent_mask<T>()) >> num_significand_bits<T>());
 
   if (exponent != 0) {  // Check if normal.
-    exponent += float_info<T>::exponent_bias - float_info<T>::significand_bits;
+    exponent -= exponent_bias<T>() + num_significand_bits<T>();
 
     // Shorter interval case; proceed like Schubfach.
+    // In fact, when exponent == 1 and significand == 0, the interval is
+    // regular. However, it can be shown that the end-results are anyway same.
     if (significand == 0) return shorter_interval_case<T>(exponent);
 
-    significand |=
-        (static_cast<carrier_uint>(1) << float_info<T>::significand_bits);
+    significand |= (static_cast<carrier_uint>(1) << num_significand_bits<T>());
   } else {
     // Subnormal case; the interval is always regular.
     if (significand == 0) return {0, 0};
-    exponent = float_info<T>::min_exponent - float_info<T>::significand_bits;
+    exponent =
+        std::numeric_limits<T>::min_exponent - num_significand_bits<T>() - 1;
   }
 
   const bool include_left_endpoint = (significand % 2 == 0);
@@ -2119,413 +1306,116 @@ template <typename T> decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT {
   // Compute k and beta.
   const int minus_k = floor_log10_pow2(exponent) - float_info<T>::kappa;
   const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
-  const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
+  const int beta = exponent + floor_log2_pow10(-minus_k);
 
-  // Compute zi and deltai
+  // Compute zi and deltai.
   // 10^kappa <= deltai < 10^(kappa + 1)
-  const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta_minus_1);
+  const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta);
   const carrier_uint two_fc = significand << 1;
-  const carrier_uint two_fr = two_fc | 1;
-  const carrier_uint zi =
-      cache_accessor<T>::compute_mul(two_fr << beta_minus_1, cache);
 
-  // Step 2: Try larger divisor; remove trailing zeros if necessary
+  // For the case of binary32, the result of integer check is not correct for
+  // 29711844 * 2^-82
+  // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18
+  // and 29711844 * 2^-81
+  // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17,
+  // and they are the unique counterexamples. However, since 29711844 is even,
+  // this does not cause any problem for the endpoints calculations; it can only
+  // cause a problem when we need to perform integer check for the center.
+  // Fortunately, with these inputs, that branch is never executed, so we are
+  // fine.
+  const typename cache_accessor<T>::compute_mul_result z_mul =
+      cache_accessor<T>::compute_mul((two_fc | 1) << beta, cache);
+
+  // Step 2: Try larger divisor; remove trailing zeros if necessary.
 
   // Using an upper bound on zi, we might be able to optimize the division
-  // better than the compiler; we are computing zi / big_divisor here
+  // better than the compiler; we are computing zi / big_divisor here.
   decimal_fp<T> ret_value;
-  ret_value.significand = divide_by_10_to_kappa_plus_1(zi);
-  uint32_t r = static_cast<uint32_t>(zi - float_info<T>::big_divisor *
-                                              ret_value.significand);
+  ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result);
+  uint32_t r = static_cast<uint32_t>(z_mul.result - float_info<T>::big_divisor *
+                                                        ret_value.significand);
 
-  if (r > deltai) {
-    goto small_divisor_case_label;
-  } else if (r < deltai) {
-    // Exclude the right endpoint if necessary
-    if (r == 0 && !include_right_endpoint &&
-        is_endpoint_integer<T>(two_fr, exponent, minus_k)) {
+  if (r < deltai) {
+    // Exclude the right endpoint if necessary.
+    if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) {
       --ret_value.significand;
       r = float_info<T>::big_divisor;
       goto small_divisor_case_label;
     }
+  } else if (r > deltai) {
+    goto small_divisor_case_label;
   } else {
-    // r == deltai; compare fractional parts
-    // Check conditions in the order different from the paper
-    // to take advantage of short-circuiting
-    const carrier_uint two_fl = two_fc - 1;
-    if ((!include_left_endpoint ||
-         !is_endpoint_integer<T>(two_fl, exponent, minus_k)) &&
-        !cache_accessor<T>::compute_mul_parity(two_fl, cache, beta_minus_1)) {
+    // r == deltai; compare fractional parts.
+    const typename cache_accessor<T>::compute_mul_parity_result x_mul =
+        cache_accessor<T>::compute_mul_parity(two_fc - 1, cache, beta);
+
+    if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint)))
       goto small_divisor_case_label;
-    }
   }
   ret_value.exponent = minus_k + float_info<T>::kappa + 1;
 
-  // We may need to remove trailing zeros
+  // We may need to remove trailing zeros.
   ret_value.exponent += remove_trailing_zeros(ret_value.significand);
   return ret_value;
 
-  // Step 3: Find the significand with the smaller divisor
+  // Step 3: Find the significand with the smaller divisor.
 
 small_divisor_case_label:
   ret_value.significand *= 10;
   ret_value.exponent = minus_k + float_info<T>::kappa;
 
-  const uint32_t mask = (1u << float_info<T>::kappa) - 1;
-  auto dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);
-
-  // Is dist divisible by 2^kappa?
-  if ((dist & mask) == 0) {
-    const bool approx_y_parity =
-        ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;
-    dist >>= float_info<T>::kappa;
-
-    // Is dist divisible by 5^kappa?
-    if (check_divisibility_and_divide_by_pow5<float_info<T>::kappa>(dist)) {
-      ret_value.significand += dist;
-
-      // Check z^(f) >= epsilon^(f)
-      // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,
-      // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f)
-      // Since there are only 2 possibilities, we only need to care about the
-      // parity. Also, zi and r should have the same parity since the divisor
-      // is an even number
-      if (cache_accessor<T>::compute_mul_parity(two_fc, cache, beta_minus_1) !=
-          approx_y_parity) {
-        --ret_value.significand;
-      } else {
-        // If z^(f) >= epsilon^(f), we might have a tie
-        // when z^(f) == epsilon^(f), or equivalently, when y is an integer
-        if (is_center_integer<T>(two_fc, exponent, minus_k)) {
-          ret_value.significand = ret_value.significand % 2 == 0
-                                      ? ret_value.significand
-                                      : ret_value.significand - 1;
-        }
-      }
-    }
-    // Is dist not divisible by 5^kappa?
-    else {
-      ret_value.significand += dist;
-    }
-  }
-  // Is dist not divisible by 2^kappa?
-  else {
-    // Since we know dist is small, we might be able to optimize the division
-    // better than the compiler; we are computing dist / small_divisor here
-    ret_value.significand +=
-        small_division_by_pow10<float_info<T>::kappa>(dist);
-  }
+  uint32_t dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);
+  const bool approx_y_parity =
+      ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;
+
+  // Is dist divisible by 10^kappa?
+  const bool divisible_by_small_divisor =
+      check_divisibility_and_divide_by_pow10<float_info<T>::kappa>(dist);
+
+  // Add dist / 10^kappa to the significand.
+  ret_value.significand += dist;
+
+  if (!divisible_by_small_divisor) return ret_value;
+
+  // Check z^(f) >= epsilon^(f).
+  // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,
+  // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f).
+  // Since there are only 2 possibilities, we only need to care about the
+  // parity. Also, zi and r should have the same parity since the divisor
+  // is an even number.
+  const auto y_mul = cache_accessor<T>::compute_mul_parity(two_fc, cache, beta);
+
+  // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f),
+  // or equivalently, when y is an integer.
+  if (y_mul.parity != approx_y_parity)
+    --ret_value.significand;
+  else if (y_mul.is_integer & (ret_value.significand % 2 != 0))
+    --ret_value.significand;
   return ret_value;
 }
 }  // namespace dragonbox
 
-// Formats a floating-point number using a variation of the Fixed-Precision
-// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
-// https://fmt.dev/papers/p372-steele.pdf.
-FMT_CONSTEXPR20 inline void format_dragon(fp value, bool is_predecessor_closer,
-                                          int num_digits, buffer<char>& buf,
-                                          int& exp10) {
-  bigint numerator;    // 2 * R in (FPP)^2.
-  bigint denominator;  // 2 * S in (FPP)^2.
-  // lower and upper are differences between value and corresponding boundaries.
-  bigint lower;             // (M^- in (FPP)^2).
-  bigint upper_store;       // upper's value if different from lower.
-  bigint* upper = nullptr;  // (M^+ in (FPP)^2).
-  // Shift numerator and denominator by an extra bit or two (if lower boundary
-  // is closer) to make lower and upper integers. This eliminates multiplication
-  // by 2 during later computations.
-  int shift = is_predecessor_closer ? 2 : 1;
-  uint64_t significand = value.f << shift;
-  if (value.e >= 0) {
-    numerator.assign(significand);
-    numerator <<= value.e;
-    lower.assign(1);
-    lower <<= value.e;
-    if (shift != 1) {
-      upper_store.assign(1);
-      upper_store <<= value.e + 1;
-      upper = &upper_store;
-    }
-    denominator.assign_pow10(exp10);
-    denominator <<= shift;
-  } else if (exp10 < 0) {
-    numerator.assign_pow10(-exp10);
-    lower.assign(numerator);
-    if (shift != 1) {
-      upper_store.assign(numerator);
-      upper_store <<= 1;
-      upper = &upper_store;
-    }
-    numerator *= significand;
-    denominator.assign(1);
-    denominator <<= shift - value.e;
-  } else {
-    numerator.assign(significand);
-    denominator.assign_pow10(exp10);
-    denominator <<= shift - value.e;
-    lower.assign(1);
-    if (shift != 1) {
-      upper_store.assign(1ULL << 1);
-      upper = &upper_store;
-    }
-  }
-  // Invariant: value == (numerator / denominator) * pow(10, exp10).
-  if (num_digits < 0) {
-    // Generate the shortest representation.
-    if (!upper) upper = &lower;
-    bool even = (value.f & 1) == 0;
-    num_digits = 0;
-    char* data = buf.data();
-    for (;;) {
-      int digit = numerator.divmod_assign(denominator);
-      bool low = compare(numerator, lower) - even < 0;  // numerator <[=] lower.
-      // numerator + upper >[=] pow10:
-      bool high = add_compare(numerator, *upper, denominator) + even > 0;
-      data[num_digits++] = static_cast<char>('0' + digit);
-      if (low || high) {
-        if (!low) {
-          ++data[num_digits - 1];
-        } else if (high) {
-          int result = add_compare(numerator, numerator, denominator);
-          // Round half to even.
-          if (result > 0 || (result == 0 && (digit % 2) != 0))
-            ++data[num_digits - 1];
-        }
-        buf.try_resize(to_unsigned(num_digits));
-        exp10 -= num_digits - 1;
-        return;
-      }
-      numerator *= 10;
-      lower *= 10;
-      if (upper != &lower) *upper *= 10;
-    }
-  }
-  // Generate the given number of digits.
-  exp10 -= num_digits - 1;
-  if (num_digits == 0) {
-    denominator *= 10;
-    auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
-    buf.push_back(digit);
-    return;
-  }
-  buf.try_resize(to_unsigned(num_digits));
-  for (int i = 0; i < num_digits - 1; ++i) {
-    int digit = numerator.divmod_assign(denominator);
-    buf[i] = static_cast<char>('0' + digit);
-    numerator *= 10;
-  }
-  int digit = numerator.divmod_assign(denominator);
-  auto result = add_compare(numerator, numerator, denominator);
-  if (result > 0 || (result == 0 && (digit % 2) != 0)) {
-    if (digit == 9) {
-      const auto overflow = '0' + 10;
-      buf[num_digits - 1] = overflow;
-      // Propagate the carry.
-      for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
-        buf[i] = '0';
-        ++buf[i - 1];
-      }
-      if (buf[0] == overflow) {
-        buf[0] = '1';
-        ++exp10;
-      }
-      return;
-    }
-    ++digit;
-  }
-  buf[num_digits - 1] = static_cast<char>('0' + digit);
-}
-
-template <typename Float>
-FMT_HEADER_ONLY_CONSTEXPR20 int format_float(Float value, int precision,
-                                             float_specs specs,
-                                             buffer<char>& buf) {
-  // float is passed as double to reduce the number of instantiations.
-  static_assert(!std::is_same<Float, float>::value, "");
-  FMT_ASSERT(value >= 0, "value is negative");
-
-  const bool fixed = specs.format == float_format::fixed;
-  if (value <= 0) {  // <= instead of == to silence a warning.
-    if (precision <= 0 || !fixed) {
-      buf.push_back('0');
-      return 0;
-    }
-    buf.try_resize(to_unsigned(precision));
-    fill_n(buf.data(), precision, '0');
-    return -precision;
-  }
-
-  if (specs.fallback) return snprintf_float(value, precision, specs, buf);
-
-  if (!is_constant_evaluated() && precision < 0) {
-    // Use Dragonbox for the shortest format.
-    if (specs.binary32) {
-      auto dec = dragonbox::to_decimal(static_cast<float>(value));
-      write<char>(buffer_appender<char>(buf), dec.significand);
-      return dec.exponent;
-    }
-    auto dec = dragonbox::to_decimal(static_cast<double>(value));
-    write<char>(buffer_appender<char>(buf), dec.significand);
-    return dec.exponent;
-  }
-
-  int exp = 0;
-  bool use_dragon = true;
-  if (is_fast_float<Float>()) {
-    // Use Grisu + Dragon4 for the given precision:
-    // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf.
-    const int min_exp = -60;  // alpha in Grisu.
-    int cached_exp10 = 0;     // K in Grisu.
-    fp normalized = normalize(fp(value));
-    const auto cached_pow = get_cached_power(
-        min_exp - (normalized.e + fp::num_significand_bits), cached_exp10);
-    normalized = normalized * cached_pow;
-    gen_digits_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
-    if (grisu_gen_digits(normalized, 1, exp, handler) != digits::error &&
-        !is_constant_evaluated()) {
-      exp += handler.exp10;
-      buf.try_resize(to_unsigned(handler.size));
-      use_dragon = false;
-    } else {
-      exp += handler.size - cached_exp10 - 1;
-      precision = handler.precision;
-    }
-  }
-  if (use_dragon) {
-    auto f = fp();
-    bool is_predecessor_closer =
-        specs.binary32 ? f.assign(static_cast<float>(value)) : f.assign(value);
-    // Limit precision to the maximum possible number of significant digits in
-    // an IEEE754 double because we don't need to generate zeros.
-    const int max_double_digits = 767;
-    if (precision > max_double_digits) precision = max_double_digits;
-    format_dragon(f, is_predecessor_closer, precision, buf, exp);
-  }
-  if (!fixed && !specs.showpoint) {
-    // Remove trailing zeros.
-    auto num_digits = buf.size();
-    while (num_digits > 0 && buf[num_digits - 1] == '0') {
-      --num_digits;
-      ++exp;
-    }
-    buf.try_resize(num_digits);
-  }
-  return exp;
+#ifdef _MSC_VER
+FMT_FUNC auto fmt_snprintf(char* buf, size_t size, const char* fmt, ...)
+    -> int {
+  auto args = va_list();
+  va_start(args, fmt);
+  int result = vsnprintf_s(buf, size, _TRUNCATE, fmt, args);
+  va_end(args);
+  return result;
 }
-
-template <typename T>
-int snprintf_float(T value, int precision, float_specs specs,
-                   buffer<char>& buf) {
-  // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
-  FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer");
-  static_assert(!std::is_same<T, float>::value, "");
-
-  // Subtract 1 to account for the difference in precision since we use %e for
-  // both general and exponent format.
-  if (specs.format == float_format::general ||
-      specs.format == float_format::exp)
-    precision = (precision >= 0 ? precision : 6) - 1;
-
-  // Build the format string.
-  enum { max_format_size = 7 };  // The longest format is "%#.*Le".
-  char format[max_format_size];
-  char* format_ptr = format;
-  *format_ptr++ = '%';
-  if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#';
-  if (precision >= 0) {
-    *format_ptr++ = '.';
-    *format_ptr++ = '*';
-  }
-  if (std::is_same<T, long double>()) *format_ptr++ = 'L';
-  *format_ptr++ = specs.format != float_format::hex
-                      ? (specs.format == float_format::fixed ? 'f' : 'e')
-                      : (specs.upper ? 'A' : 'a');
-  *format_ptr = '\0';
-
-  // Format using snprintf.
-  auto offset = buf.size();
-  for (;;) {
-    auto begin = buf.data() + offset;
-    auto capacity = buf.capacity() - offset;
-#ifdef FMT_FUZZ
-    if (precision > 100000)
-      throw std::runtime_error(
-          "fuzz mode - avoid large allocation inside snprintf");
 #endif
-    // Suppress the warning about a nonliteral format string.
-    // Cannot use auto because of a bug in MinGW (#1532).
-    int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
-    int result = precision >= 0
-                     ? snprintf_ptr(begin, capacity, format, precision, value)
-                     : snprintf_ptr(begin, capacity, format, value);
-    if (result < 0) {
-      // The buffer will grow exponentially.
-      buf.try_reserve(buf.capacity() + 1);
-      continue;
-    }
-    auto size = to_unsigned(result);
-    // Size equal to capacity means that the last character was truncated.
-    if (size >= capacity) {
-      buf.try_reserve(size + offset + 1);  // Add 1 for the terminating '\0'.
-      continue;
-    }
-    auto is_digit = [](char c) { return c >= '0' && c <= '9'; };
-    if (specs.format == float_format::fixed) {
-      if (precision == 0) {
-        buf.try_resize(size);
-        return 0;
-      }
-      // Find and remove the decimal point.
-      auto end = begin + size, p = end;
-      do {
-        --p;
-      } while (is_digit(*p));
-      int fraction_size = static_cast<int>(end - p - 1);
-      std::memmove(p, p + 1, to_unsigned(fraction_size));
-      buf.try_resize(size - 1);
-      return -fraction_size;
-    }
-    if (specs.format == float_format::hex) {
-      buf.try_resize(size + offset);
-      return 0;
-    }
-    // Find and parse the exponent.
-    auto end = begin + size, exp_pos = end;
-    do {
-      --exp_pos;
-    } while (*exp_pos != 'e');
-    char sign = exp_pos[1];
-    FMT_ASSERT(sign == '+' || sign == '-', "");
-    int exp = 0;
-    auto p = exp_pos + 2;  // Skip 'e' and sign.
-    do {
-      FMT_ASSERT(is_digit(*p), "");
-      exp = exp * 10 + (*p++ - '0');
-    } while (p != end);
-    if (sign == '-') exp = -exp;
-    int fraction_size = 0;
-    if (exp_pos != begin + 1) {
-      // Remove trailing zeros.
-      auto fraction_end = exp_pos - 1;
-      while (*fraction_end == '0') --fraction_end;
-      // Move the fractional part left to get rid of the decimal point.
-      fraction_size = static_cast<int>(fraction_end - begin - 1);
-      std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size));
-    }
-    buf.try_resize(to_unsigned(fraction_size) + offset + 1);
-    return exp - fraction_size;
-  }
-}
 }  // namespace detail
 
 template <> struct formatter<detail::bigint> {
-  FMT_CONSTEXPR format_parse_context::iterator parse(
-      format_parse_context& ctx) {
+  FMT_CONSTEXPR auto parse(format_parse_context& ctx)
+      -> format_parse_context::iterator {
     return ctx.begin();
   }
 
-  format_context::iterator format(const detail::bigint& n,
-                                  format_context& ctx) {
+  template <typename FormatContext>
+  auto format(const detail::bigint& n, FormatContext& ctx) const ->
+      typename FormatContext::iterator {
     auto out = ctx.out();
     bool first = true;
     for (auto i = n.bigits_.size(); i > 0; --i) {
@@ -2560,7 +1450,7 @@ FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) {
 }
 
 FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,
-                                  const char* message) FMT_NOEXCEPT {
+                                  const char* message) noexcept {
   FMT_TRY {
     auto ec = std::error_code(error_code, std::generic_category());
     write(std::back_inserter(out), std::system_error(ec, message).what());
@@ -2571,16 +1461,10 @@ FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,
 }
 
 FMT_FUNC void report_system_error(int error_code,
-                                  const char* message) FMT_NOEXCEPT {
+                                  const char* message) noexcept {
   report_error(format_system_error, error_code, message);
 }
 
-// DEPRECATED!
-// This function is defined here and not inline for ABI compatiblity.
-FMT_FUNC void detail::error_handler::on_error(const char* message) {
-  throw_format_error(message);
-}
-
 FMT_FUNC std::string vformat(string_view fmt, format_args args) {
   // Don't optimize the "{}" case to keep the binary size small and because it
   // can be better optimized in fmt::format anyway.
@@ -2589,17 +1473,13 @@ FMT_FUNC std::string vformat(string_view fmt, format_args args) {
   return to_string(buffer);
 }
 
-#ifdef _WIN32
 namespace detail {
+#ifdef _WIN32
 using dword = conditional_t<sizeof(long) == 4, unsigned long, unsigned>;
 extern "C" __declspec(dllimport) int __stdcall WriteConsoleW(  //
     void*, const void*, dword, dword*, void*);
-}  // namespace detail
-#endif
 
-namespace detail {
-FMT_FUNC void print(std::FILE* f, string_view text) {
-#ifdef _WIN32
+FMT_FUNC bool write_console(std::FILE* f, string_view text) {
   auto fd = _fileno(f);
   if (_isatty(fd)) {
     detail::utf8_to_utf16 u16(string_view(text.data(), text.size()));
@@ -2607,11 +1487,20 @@ FMT_FUNC void print(std::FILE* f, string_view text) {
     if (detail::WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)),
                               u16.c_str(), static_cast<uint32_t>(u16.size()),
                               &written, nullptr)) {
-      return;
+      return true;
     }
-    // Fallback to fwrite on failure. It can happen if the output has been
-    // redirected to NUL.
   }
+  // We return false if the file descriptor was not TTY, or it was but
+  // SetConsoleW failed which can happen if the output has been redirected to
+  // NUL. In both cases when we return false, we should attempt to do regular
+  // write via fwrite or std::ostream::write.
+  return false;
+}
+#endif
+
+FMT_FUNC void print(std::FILE* f, string_view text) {
+#ifdef _WIN32
+  if (write_console(f, text)) return;
 #endif
   detail::fwrite_fully(text.data(), 1, text.size(), f);
 }
@@ -2638,6 +1527,197 @@ FMT_FUNC void vprint(string_view format_str, format_args args) {
   vprint(stdout, format_str, args);
 }
 
+namespace detail {
+
+struct singleton {
+  unsigned char upper;
+  unsigned char lower_count;
+};
+
+inline auto is_printable(uint16_t x, const singleton* singletons,
+                         size_t singletons_size,
+                         const unsigned char* singleton_lowers,
+                         const unsigned char* normal, size_t normal_size)
+    -> bool {
+  auto upper = x >> 8;
+  auto lower_start = 0;
+  for (size_t i = 0; i < singletons_size; ++i) {
+    auto s = singletons[i];
+    auto lower_end = lower_start + s.lower_count;
+    if (upper < s.upper) break;
+    if (upper == s.upper) {
+      for (auto j = lower_start; j < lower_end; ++j) {
+        if (singleton_lowers[j] == (x & 0xff)) return false;
+      }
+    }
+    lower_start = lower_end;
+  }
+
+  auto xsigned = static_cast<int>(x);
+  auto current = true;
+  for (size_t i = 0; i < normal_size; ++i) {
+    auto v = static_cast<int>(normal[i]);
+    auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v;
+    xsigned -= len;
+    if (xsigned < 0) break;
+    current = !current;
+  }
+  return current;
+}
+
+// This code is generated by support/printable.py.
+FMT_FUNC auto is_printable(uint32_t cp) -> bool {
+  static constexpr singleton singletons0[] = {
+      {0x00, 1},  {0x03, 5},  {0x05, 6},  {0x06, 3},  {0x07, 6},  {0x08, 8},
+      {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13},
+      {0x0f, 4},  {0x10, 3},  {0x12, 18}, {0x13, 9},  {0x16, 1},  {0x17, 5},
+      {0x18, 2},  {0x19, 3},  {0x1a, 7},  {0x1c, 2},  {0x1d, 1},  {0x1f, 22},
+      {0x20, 3},  {0x2b, 3},  {0x2c, 2},  {0x2d, 11}, {0x2e, 1},  {0x30, 3},
+      {0x31, 2},  {0x32, 1},  {0xa7, 2},  {0xa9, 2},  {0xaa, 4},  {0xab, 8},
+      {0xfa, 2},  {0xfb, 5},  {0xfd, 4},  {0xfe, 3},  {0xff, 9},
+  };
+  static constexpr unsigned char singletons0_lower[] = {
+      0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90,
+      0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f,
+      0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1,
+      0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04,
+      0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d,
+      0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf,
+      0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
+      0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d,
+      0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d,
+      0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d,
+      0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5,
+      0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7,
+      0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49,
+      0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7,
+      0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7,
+      0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e,
+      0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16,
+      0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e,
+      0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f,
+      0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf,
+      0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0,
+      0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27,
+      0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91,
+      0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7,
+      0xfe, 0xff,
+  };
+  static constexpr singleton singletons1[] = {
+      {0x00, 6},  {0x01, 1}, {0x03, 1},  {0x04, 2}, {0x08, 8},  {0x09, 2},
+      {0x0a, 5},  {0x0b, 2}, {0x0e, 4},  {0x10, 1}, {0x11, 2},  {0x12, 5},
+      {0x13, 17}, {0x14, 1}, {0x15, 2},  {0x17, 2}, {0x19, 13}, {0x1c, 5},
+      {0x1d, 8},  {0x24, 1}, {0x6a, 3},  {0x6b, 2}, {0xbc, 2},  {0xd1, 2},
+      {0xd4, 12}, {0xd5, 9}, {0xd6, 2},  {0xd7, 2}, {0xda, 1},  {0xe0, 5},
+      {0xe1, 2},  {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2},  {0xf9, 2},
+      {0xfa, 2},  {0xfb, 1},
+  };
+  static constexpr unsigned char singletons1_lower[] = {
+      0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07,
+      0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36,
+      0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87,
+      0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
+      0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b,
+      0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9,
+      0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66,
+      0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27,
+      0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc,
+      0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7,
+      0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6,
+      0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c,
+      0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66,
+      0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0,
+      0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93,
+  };
+  static constexpr unsigned char normal0[] = {
+      0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04,
+      0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0,
+      0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01,
+      0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03,
+      0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03,
+      0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a,
+      0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15,
+      0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f,
+      0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80,
+      0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07,
+      0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06,
+      0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04,
+      0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac,
+      0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c,
+      0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11,
+      0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c,
+      0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b,
+      0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6,
+      0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03,
+      0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80,
+      0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06,
+      0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c,
+      0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17,
+      0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80,
+      0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80,
+      0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d,
+  };
+  static constexpr unsigned char normal1[] = {
+      0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f,
+      0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e,
+      0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04,
+      0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09,
+      0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16,
+      0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f,
+      0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36,
+      0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33,
+      0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08,
+      0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e,
+      0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41,
+      0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03,
+      0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22,
+      0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04,
+      0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45,
+      0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03,
+      0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81,
+      0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75,
+      0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1,
+      0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a,
+      0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11,
+      0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09,
+      0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89,
+      0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6,
+      0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09,
+      0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50,
+      0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05,
+      0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83,
+      0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05,
+      0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80,
+      0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80,
+      0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07,
+      0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e,
+      0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07,
+      0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06,
+  };
+  auto lower = static_cast<uint16_t>(cp);
+  if (cp < 0x10000) {
+    return is_printable(lower, singletons0,
+                        sizeof(singletons0) / sizeof(*singletons0),
+                        singletons0_lower, normal0, sizeof(normal0));
+  }
+  if (cp < 0x20000) {
+    return is_printable(lower, singletons1,
+                        sizeof(singletons1) / sizeof(*singletons1),
+                        singletons1_lower, normal1, sizeof(normal1));
+  }
+  if (0x2a6de <= cp && cp < 0x2a700) return false;
+  if (0x2b735 <= cp && cp < 0x2b740) return false;
+  if (0x2b81e <= cp && cp < 0x2b820) return false;
+  if (0x2cea2 <= cp && cp < 0x2ceb0) return false;
+  if (0x2ebe1 <= cp && cp < 0x2f800) return false;
+  if (0x2fa1e <= cp && cp < 0x30000) return false;
+  if (0x3134b <= cp && cp < 0xe0100) return false;
+  if (0xe01f0 <= cp && cp < 0x110000) return false;
+  return cp < 0x110000;
+}
+
+}  // namespace detail
+
 FMT_END_NAMESPACE
 
 #endif  // FMT_FORMAT_INL_H_
index ee69651ca54fef5b30945992c36b5b291515a462..7c607dbd30421b5bc57aaafc1edabeafdf2a3ea0 100644 (file)
@@ -1,33 +1,33 @@
 /*
- Formatting library for C++
-
- Copyright (c) 2012 - present, Victor Zverovich
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- "Software"), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- --- Optional exception to the license ---
-
- As an exception, if, as a result of your compiling your source code, portions
- of this Software are embedded into a machine-executable object form of such
- source code, you may redistribute such embedded portions in such object form
- without including the above copyright and permission notices.
 Formatting library for C++
+
 Copyright (c) 2012 - present, Victor Zverovich
+
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:
+
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
+
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
 --- Optional exception to the license ---
+
 As an exception, if, as a result of your compiling your source code, portions
 of this Software are embedded into a machine-executable object form of such
 source code, you may redistribute such embedded portions in such object form
 without including the above copyright and permission notices.
  */
 
 #ifndef FMT_FORMAT_H_
 
 #include <cmath>         // std::signbit
 #include <cstdint>       // uint32_t
+#include <cstring>       // std::memcpy
 #include <limits>        // std::numeric_limits
 #include <memory>        // std::uninitialized_copy
 #include <stdexcept>     // std::runtime_error
 #include <system_error>  // std::system_error
-#include <utility>       // std::swap
 
 #ifdef __cpp_lib_bit_cast
 #  include <bit>  // std::bitcast
@@ -71,7 +71,7 @@
 #  define FMT_NOINLINE
 #endif
 
-#if FMT_MSC_VER
+#if FMT_MSC_VERSION
 #  define FMT_MSC_DEFAULT = default
 #else
 #  define FMT_MSC_DEFAULT
@@ -79,7 +79,7 @@
 
 #ifndef FMT_THROW
 #  if FMT_EXCEPTIONS
-#    if FMT_MSC_VER || FMT_NVCC
+#    if FMT_MSC_VERSION || defined(__NVCC__)
 FMT_BEGIN_NAMESPACE
 namespace detail {
 template <typename Exception> inline void do_throw(const Exception& x) {
@@ -118,17 +118,10 @@ FMT_END_NAMESPACE
 #  endif
 #endif
 
-// Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
-#if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
-#  define FMT_DEPRECATED_ALIAS
-#else
-#  define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
-#endif
-
 #ifndef FMT_USE_USER_DEFINED_LITERALS
 // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
 #  if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
-       FMT_MSC_VER >= 1900) &&                                         \
+       FMT_MSC_VERSION >= 1900) &&                                     \
       (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
 #    define FMT_USE_USER_DEFINED_LITERALS 1
 #  else
@@ -146,7 +139,7 @@ FMT_END_NAMESPACE
 
 // __builtin_clz is broken in clang with Microsoft CodeGen:
 // https://github.com/fmtlib/fmt/issues/519.
-#if !FMT_MSC_VER
+#if !FMT_MSC_VERSION
 #  if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
 #    define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
 #  endif
@@ -158,22 +151,25 @@ FMT_END_NAMESPACE
 // __builtin_ctz is broken in Intel Compiler Classic on Windows:
 // https://github.com/fmtlib/fmt/issues/2510.
 #ifndef __ICL
-#  if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION
+#  if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION || \
+      defined(__NVCOMPILER)
 #    define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
 #  endif
-#  if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
+#  if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || \
+      FMT_ICC_VERSION || defined(__NVCOMPILER)
 #    define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
 #  endif
 #endif
 
-#if FMT_MSC_VER
+#if FMT_MSC_VERSION
 #  include <intrin.h>  // _BitScanReverse[64], _BitScanForward[64], _umul128
 #endif
 
 // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
 // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
 // MSVC intrinsics if the clz and clzll builtins are not available.
-#if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(FMT_BUILTIN_CTZLL)
+#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) && \
+    !defined(FMT_BUILTIN_CTZLL)
 FMT_BEGIN_NAMESPACE
 namespace detail {
 // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
@@ -243,15 +239,28 @@ inline auto ctzll(uint64_t x) -> int {
 FMT_END_NAMESPACE
 #endif
 
-#ifdef FMT_HEADER_ONLY
-#  define FMT_HEADER_ONLY_CONSTEXPR20 FMT_CONSTEXPR20
-#else
-#  define FMT_HEADER_ONLY_CONSTEXPR20
-#endif
-
 FMT_BEGIN_NAMESPACE
 namespace detail {
 
+FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) {
+  ignore_unused(condition);
+#ifdef FMT_FUZZ
+  if (condition) throw std::runtime_error("fuzzing limit reached");
+#endif
+}
+
+template <typename CharT, CharT... C> struct string_literal {
+  static constexpr CharT value[sizeof...(C)] = {C...};
+  constexpr operator basic_string_view<CharT>() const {
+    return {value, sizeof...(C)};
+  }
+};
+
+#if FMT_CPLUSPLUS < 201703L
+template <typename CharT, CharT... C>
+constexpr CharT string_literal<CharT, C...>::value[sizeof...(C)];
+#endif
+
 template <typename Streambuf> class formatbuf : public Streambuf {
  private:
   using char_type = typename Streambuf::char_type;
@@ -284,14 +293,14 @@ template <typename Streambuf> class formatbuf : public Streambuf {
 };
 
 // Implementation of std::bit_cast for pre-C++20.
-template <typename To, typename From>
+template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) == sizeof(From))>
 FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
-  static_assert(sizeof(To) == sizeof(From), "size mismatch");
 #ifdef __cpp_lib_bit_cast
   if (is_constant_evaluated()) return std::bit_cast<To>(from);
 #endif
   auto to = To();
-  std::memcpy(&to, &from, sizeof(to));
+  // The cast suppresses a bogus -Wclass-memaccess on GCC.
+  std::memcpy(static_cast<void*>(&to), &from, sizeof(to));
   return to;
 }
 
@@ -310,29 +319,117 @@ inline auto is_big_endian() -> bool {
 #endif
 }
 
-// A fallback implementation of uintptr_t for systems that lack it.
-struct fallback_uintptr {
-  unsigned char value[sizeof(void*)];
+class uint128_fallback {
+ private:
+  uint64_t lo_, hi_;
+
+  friend uint128_fallback umul128(uint64_t x, uint64_t y) noexcept;
+
+ public:
+  constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {}
+  constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {}
+
+  constexpr uint64_t high() const noexcept { return hi_; }
+  constexpr uint64_t low() const noexcept { return lo_; }
+
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  constexpr explicit operator T() const {
+    return static_cast<T>(lo_);
+  }
+
+  friend constexpr auto operator==(const uint128_fallback& lhs,
+                                   const uint128_fallback& rhs) -> bool {
+    return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_;
+  }
+  friend constexpr auto operator!=(const uint128_fallback& lhs,
+                                   const uint128_fallback& rhs) -> bool {
+    return !(lhs == rhs);
+  }
+  friend constexpr auto operator>(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs) -> bool {
+    return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_;
+  }
+  friend constexpr auto operator|(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_};
+  }
+  friend constexpr auto operator&(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_};
+  }
+  friend auto operator+(const uint128_fallback& lhs,
+                        const uint128_fallback& rhs) -> uint128_fallback {
+    auto result = uint128_fallback(lhs);
+    result += rhs;
+    return result;
+  }
+  friend auto operator*(const uint128_fallback& lhs, uint32_t rhs)
+      -> uint128_fallback {
+    FMT_ASSERT(lhs.hi_ == 0, "");
+    uint64_t hi = (lhs.lo_ >> 32) * rhs;
+    uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs;
+    uint64_t new_lo = (hi << 32) + lo;
+    return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo};
+  }
+  friend auto operator-(const uint128_fallback& lhs, uint64_t rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs};
+  }
+  FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback {
+    if (shift == 64) return {0, hi_};
+    if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64);
+    return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)};
+  }
+  FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback {
+    if (shift == 64) return {lo_, 0};
+    if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64);
+    return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)};
+  }
+  FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& {
+    return *this = *this >> shift;
+  }
+  FMT_CONSTEXPR void operator+=(uint128_fallback n) {
+    uint64_t new_lo = lo_ + n.lo_;
+    uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0);
+    FMT_ASSERT(new_hi >= hi_, "");
+    lo_ = new_lo;
+    hi_ = new_hi;
+  }
 
-  fallback_uintptr() = default;
-  explicit fallback_uintptr(const void* p) {
-    *this = bit_cast<fallback_uintptr>(p);
-    if (const_check(is_big_endian())) {
-      for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j)
-        std::swap(value[i], value[j]);
+  FMT_CONSTEXPR20 uint128_fallback& operator+=(uint64_t n) noexcept {
+    if (is_constant_evaluated()) {
+      lo_ += n;
+      hi_ += (lo_ < n ? 1 : 0);
+      return *this;
     }
+#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__)
+    unsigned long long carry;
+    lo_ = __builtin_addcll(lo_, n, 0, &carry);
+    hi_ += carry;
+#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__)
+    unsigned long long result;
+    auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result);
+    lo_ = result;
+    hi_ += carry;
+#elif defined(_MSC_VER) && defined(_M_X64)
+    auto carry = _addcarry_u64(0, lo_, n, &lo_);
+    _addcarry_u64(carry, hi_, 0, &hi_);
+#else
+    lo_ += n;
+    hi_ += (lo_ < n ? 1 : 0);
+#endif
+    return *this;
   }
 };
+
+using uint128_t = conditional_t<FMT_USE_INT128, uint128_opt, uint128_fallback>;
+
 #ifdef UINTPTR_MAX
 using uintptr_t = ::uintptr_t;
-inline auto to_uintptr(const void* p) -> uintptr_t {
-  return bit_cast<uintptr_t>(p);
-}
 #else
-using uintptr_t = fallback_uintptr;
-inline auto to_uintptr(const void* p) -> fallback_uintptr {
-  return fallback_uintptr(p);
-}
+using uintptr_t = uint128_t;
 #endif
 
 // Returns the largest possible value for type T. Same as
@@ -344,16 +441,31 @@ template <typename T> constexpr auto num_bits() -> int {
   return std::numeric_limits<T>::digits;
 }
 // std::numeric_limits<T>::digits may return 0 for 128-bit ints.
-template <> constexpr auto num_bits<int128_t>() -> int { return 128; }
+template <> constexpr auto num_bits<int128_opt>() -> int { return 128; }
 template <> constexpr auto num_bits<uint128_t>() -> int { return 128; }
-template <> constexpr auto num_bits<fallback_uintptr>() -> int {
-  return static_cast<int>(sizeof(void*) *
-                          std::numeric_limits<unsigned char>::digits);
+
+// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t
+// and 128-bit pointers to uint128_fallback.
+template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) > sizeof(From))>
+inline auto bit_cast(const From& from) -> To {
+  constexpr auto size = static_cast<int>(sizeof(From) / sizeof(unsigned));
+  struct data_t {
+    unsigned value[static_cast<unsigned>(size)];
+  } data = bit_cast<data_t>(from);
+  auto result = To();
+  if (const_check(is_big_endian())) {
+    for (int i = 0; i < size; ++i)
+      result = (result << num_bits<unsigned>()) | data.value[i];
+  } else {
+    for (int i = size - 1; i >= 0; --i)
+      result = (result << num_bits<unsigned>()) | data.value[i];
+  }
+  return result;
 }
 
 FMT_INLINE void assume(bool condition) {
   (void)condition;
-#if FMT_HAS_BUILTIN(__builtin_assume)
+#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION
   __builtin_assume(condition);
 #endif
 }
@@ -495,19 +607,23 @@ FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
   constexpr const int shiftc[] = {0, 18, 12, 6, 0};
   constexpr const int shifte[] = {0, 6, 4, 2, 0};
 
-  int len = code_point_length(s);
-  const char* next = s + len;
+  int len = code_point_length_impl(*s);
+  // Compute the pointer to the next character early so that the next
+  // iteration can start working on the next character. Neither Clang
+  // nor GCC figure out this reordering on their own.
+  const char* next = s + len + !len;
+
+  using uchar = unsigned char;
 
   // Assume a four-byte character and load four bytes. Unused bits are
   // shifted out.
-  *c = uint32_t(s[0] & masks[len]) << 18;
-  *c |= uint32_t(s[1] & 0x3f) << 12;
-  *c |= uint32_t(s[2] & 0x3f) << 6;
-  *c |= uint32_t(s[3] & 0x3f) << 0;
+  *c = uint32_t(uchar(s[0]) & masks[len]) << 18;
+  *c |= uint32_t(uchar(s[1]) & 0x3f) << 12;
+  *c |= uint32_t(uchar(s[2]) & 0x3f) << 6;
+  *c |= uint32_t(uchar(s[3]) & 0x3f) << 0;
   *c >>= shiftc[len];
 
   // Accumulate the various error conditions.
-  using uchar = unsigned char;
   *e = (*c < mins[len]) << 6;       // non-canonical encoding
   *e |= ((*c >> 11) == 0x1b) << 7;  // surrogate half?
   *e |= (*c > 0x10FFFF) << 8;       // out of range?
@@ -531,8 +647,8 @@ FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
     auto error = 0;
     auto end = utf8_decode(buf_ptr, &cp, &error);
     bool result = f(error ? invalid_code_point : cp,
-                    string_view(ptr, to_unsigned(end - buf_ptr)));
-    return result ? end : nullptr;
+                    string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr)));
+    return result ? (error ? buf_ptr + 1 : end) : nullptr;
   };
   auto p = s.data();
   const size_t block_size = 4;  // utf8_decode always reads blocks of 4 chars.
@@ -595,8 +711,8 @@ FMT_CONSTEXPR inline size_t compute_width(string_view s) {
 }
 
 inline auto compute_width(basic_string_view<char8_type> s) -> size_t {
-  return compute_width(basic_string_view<char>(
-      reinterpret_cast<const char*>(s.data()), s.size()));
+  return compute_width(
+      string_view(reinterpret_cast<const char*>(s.data()), s.size()));
 }
 
 template <typename Char>
@@ -606,9 +722,8 @@ inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
 }
 
 // Calculates the index of the nth code point in a UTF-8 string.
-inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
-    -> size_t {
-  const char8_type* data = s.data();
+inline auto code_point_index(string_view s, size_t n) -> size_t {
+  const char* data = s.data();
   size_t num_code_points = 0;
   for (size_t i = 0, size = s.size(); i != size; ++i) {
     if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) return i;
@@ -616,11 +731,38 @@ inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
   return s.size();
 }
 
+inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
+    -> size_t {
+  return code_point_index(
+      string_view(reinterpret_cast<const char*>(s.data()), s.size()), n);
+}
+
+#ifndef FMT_USE_FLOAT128
+#  ifdef __SIZEOF_FLOAT128__
+#    define FMT_USE_FLOAT128 1
+#  else
+#    define FMT_USE_FLOAT128 0
+#  endif
+#endif
+#if FMT_USE_FLOAT128
+using float128 = __float128;
+#else
+using float128 = void;
+#endif
+template <typename T> using is_float128 = std::is_same<T, float128>;
+
+template <typename T>
+using is_floating_point =
+    bool_constant<std::is_floating_point<T>::value || is_float128<T>::value>;
+
 template <typename T, bool = std::is_floating_point<T>::value>
 struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
                                      sizeof(T) <= sizeof(double)> {};
 template <typename T> struct is_fast_float<T, false> : std::false_type {};
 
+template <typename T>
+using is_double_double = bool_constant<std::numeric_limits<T>::digits == 106>;
+
 #ifndef FMT_USE_FULL_CACHE_DRAGONBOX
 #  define FMT_USE_FULL_CACHE_DRAGONBOX 0
 #endif
@@ -698,9 +840,7 @@ class basic_memory_buffer final : public detail::buffer<T> {
       const Allocator& alloc = Allocator())
       : alloc_(alloc) {
     this->set(store_, SIZE);
-    if (detail::is_constant_evaluated()) {
-      detail::fill_n(store_, SIZE, T{});
-    }
+    if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T());
   }
   FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
 
@@ -712,18 +852,14 @@ class basic_memory_buffer final : public detail::buffer<T> {
     size_t size = other.size(), capacity = other.capacity();
     if (data == other.store_) {
       this->set(store_, capacity);
-      if (detail::is_constant_evaluated()) {
-        detail::copy_str<T>(other.store_, other.store_ + size,
-                            detail::make_checked(store_, capacity));
-      } else {
-        std::uninitialized_copy(other.store_, other.store_ + size,
-                                detail::make_checked(store_, capacity));
-      }
+      detail::copy_str<T>(other.store_, other.store_ + size,
+                          detail::make_checked(store_, capacity));
     } else {
       this->set(data, capacity);
       // Set pointer to the inline array so that delete is not called
       // when deallocating.
       other.set(other.store_, 0);
+      other.clear();
     }
     this->resize(size);
   }
@@ -735,8 +871,7 @@ class basic_memory_buffer final : public detail::buffer<T> {
     of the other object to it.
     \endrst
    */
-  FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other)
-      FMT_NOEXCEPT {
+  FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept {
     move(other);
   }
 
@@ -745,8 +880,7 @@ class basic_memory_buffer final : public detail::buffer<T> {
     Moves the content of the other ``basic_memory_buffer`` object to this one.
     \endrst
    */
-  auto operator=(basic_memory_buffer&& other) FMT_NOEXCEPT
-      -> basic_memory_buffer& {
+  auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& {
     FMT_ASSERT(this != &other, "");
     deallocate();
     move(other);
@@ -776,9 +910,7 @@ class basic_memory_buffer final : public detail::buffer<T> {
 template <typename T, size_t SIZE, typename Allocator>
 FMT_CONSTEXPR20 void basic_memory_buffer<T, SIZE, Allocator>::grow(
     size_t size) {
-#ifdef FMT_FUZZ
-  if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much");
-#endif
+  detail::abort_fuzzing_if(size > 5000);
   const size_t max_size = std::allocator_traits<Allocator>::max_size(alloc_);
   size_t old_capacity = this->capacity();
   size_t new_capacity = old_capacity + old_capacity / 2;
@@ -806,8 +938,11 @@ struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
 };
 
 namespace detail {
+#ifdef _WIN32
+FMT_API bool write_console(std::FILE* f, string_view text);
+#endif
 FMT_API void print(std::FILE*, string_view);
-}
+}  // namespace detail
 
 /** A formatting error such as invalid format string. */
 FMT_CLASS_API
@@ -820,39 +955,17 @@ class FMT_API format_error : public std::runtime_error {
   format_error& operator=(const format_error&) = default;
   format_error(format_error&&) = default;
   format_error& operator=(format_error&&) = default;
-  ~format_error() FMT_NOEXCEPT override FMT_MSC_DEFAULT;
+  ~format_error() noexcept override FMT_MSC_DEFAULT;
 };
 
-/**
-  \rst
-  Constructs a `~fmt::format_arg_store` object that contains references
-  to arguments and can be implicitly converted to `~fmt::format_args`.
-  If ``fmt`` is a compile-time string then `make_args_checked` checks
-  its validity at compile time.
-  \endrst
- */
-template <typename... Args, typename S, typename Char = char_t<S>>
-FMT_INLINE auto make_args_checked(const S& fmt,
-                                  const remove_reference_t<Args>&... args)
-    -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
-  static_assert(
-      detail::count<(
-              std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
-              std::is_reference<Args>::value)...>() == 0,
-      "passing views as lvalues is disallowed");
-  detail::check_format_string<Args...>(fmt);
-  return {args...};
-}
-
-// compile-time support
 namespace detail_exported {
-#if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
 template <typename Char, size_t N> struct fixed_string {
   constexpr fixed_string(const Char (&str)[N]) {
     detail::copy_str<Char, const Char*, Char*>(static_cast<const Char*>(str),
                                                str + N, data);
   }
-  Char data[N]{};
+  Char data[N] = {};
 };
 #endif
 
@@ -874,30 +987,31 @@ constexpr auto compile_string_to_view(detail::std_string_view<Char> s)
 FMT_BEGIN_DETAIL_NAMESPACE
 
 template <typename T> struct is_integral : std::is_integral<T> {};
-template <> struct is_integral<int128_t> : std::true_type {};
+template <> struct is_integral<int128_opt> : std::true_type {};
 template <> struct is_integral<uint128_t> : std::true_type {};
 
 template <typename T>
 using is_signed =
     std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
-                                     std::is_same<T, int128_t>::value>;
+                                     std::is_same<T, int128_opt>::value>;
 
 // Returns true if value is negative, false otherwise.
 // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
 template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
-FMT_CONSTEXPR auto is_negative(T value) -> bool {
+constexpr auto is_negative(T value) -> bool {
   return value < 0;
 }
 template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
-FMT_CONSTEXPR auto is_negative(T) -> bool {
+constexpr auto is_negative(T) -> bool {
   return false;
 }
 
-template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
-FMT_CONSTEXPR auto is_supported_floating_point(T) -> uint16_t {
-  return (std::is_same<T, float>::value && FMT_USE_FLOAT) ||
-         (std::is_same<T, double>::value && FMT_USE_DOUBLE) ||
-         (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE);
+template <typename T>
+FMT_CONSTEXPR auto is_supported_floating_point(T) -> bool {
+  if (std::is_same<T, float>()) return FMT_USE_FLOAT;
+  if (std::is_same<T, double>()) return FMT_USE_DOUBLE;
+  if (std::is_same<T, long double>()) return FMT_USE_LONG_DOUBLE;
+  return true;
 }
 
 // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
@@ -948,7 +1062,7 @@ template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
   }
 }
 #if FMT_USE_INT128
-FMT_CONSTEXPR inline auto count_digits(uint128_t n) -> int {
+FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int {
   return count_digits_fallback(n);
 }
 #endif
@@ -989,7 +1103,7 @@ FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
 template <int BITS, typename UInt>
 FMT_CONSTEXPR auto count_digits(UInt n) -> int {
 #ifdef FMT_BUILTIN_CLZ
-  if (num_bits<UInt>() == 32)
+  if (!is_constant_evaluated() && num_bits<UInt>() == 32)
     return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
 #endif
   // Lambda avoids unreachable code warnings from NVHPC.
@@ -1002,8 +1116,6 @@ FMT_CONSTEXPR auto count_digits(UInt n) -> int {
   }(n);
 }
 
-template <> auto count_digits<4>(detail::fallback_uintptr n) -> int;
-
 #ifdef FMT_BUILTIN_CLZ
 // It is a separate function rather than a part of count_digits to workaround
 // the lack of static constexpr in constexpr functions.
@@ -1039,15 +1151,11 @@ FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
   return count_digits_fallback(n);
 }
 
-template <typename Int> constexpr auto digits10() FMT_NOEXCEPT -> int {
+template <typename Int> constexpr auto digits10() noexcept -> int {
   return std::numeric_limits<Int>::digits10;
 }
-template <> constexpr auto digits10<int128_t>() FMT_NOEXCEPT -> int {
-  return 38;
-}
-template <> constexpr auto digits10<uint128_t>() FMT_NOEXCEPT -> int {
-  return 38;
-}
+template <> constexpr auto digits10<int128_opt>() noexcept -> int { return 38; }
+template <> constexpr auto digits10<uint128_t>() noexcept -> int { return 38; }
 
 template <typename Char> struct thousands_sep_result {
   std::string grouping;
@@ -1127,7 +1235,7 @@ FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
 
 template <typename Char, typename UInt, typename Iterator,
           FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
-inline auto format_decimal(Iterator out, UInt value, int size)
+FMT_CONSTEXPR inline auto format_decimal(Iterator out, UInt value, int size)
     -> format_decimal_result<Iterator> {
   // Buffer is large enough to hold all digits (digits10 + 1).
   Char buffer[digits10<UInt>() + 1];
@@ -1142,35 +1250,13 @@ FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits,
   Char* end = buffer;
   do {
     const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
-    unsigned digit = (value & ((1 << BASE_BITS) - 1));
+    unsigned digit = static_cast<unsigned>(value & ((1 << BASE_BITS) - 1));
     *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
                                                 : digits[digit]);
   } while ((value >>= BASE_BITS) != 0);
   return end;
 }
 
-template <unsigned BASE_BITS, typename Char>
-auto format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits,
-                 bool = false) -> Char* {
-  auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
-  int start = (num_digits + char_digits - 1) / char_digits - 1;
-  if (int start_digits = num_digits % char_digits) {
-    unsigned value = n.value[start--];
-    buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
-  }
-  for (; start >= 0; --start) {
-    unsigned value = n.value[start];
-    buffer += char_digits;
-    auto p = buffer;
-    for (int i = 0; i < char_digits; ++i) {
-      unsigned digit = (value & ((1 << BASE_BITS) - 1));
-      *--p = static_cast<Char>("0123456789abcdef"[digit]);
-      value >>= BASE_BITS;
-    }
-  }
-  return buffer;
-}
-
 template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
 inline auto format_uint(It out, UInt value, int num_digits, bool upper = false)
     -> It {
@@ -1200,58 +1286,45 @@ class utf8_to_utf16 {
 namespace dragonbox {
 
 // Type-specific information that Dragonbox uses.
-template <class T> struct float_info;
+template <typename T, typename Enable = void> struct float_info;
 
 template <> struct float_info<float> {
   using carrier_uint = uint32_t;
-  static const int significand_bits = 23;
   static const int exponent_bits = 8;
-  static const int min_exponent = -126;
-  static const int max_exponent = 127;
-  static const int exponent_bias = -127;
-  static const int decimal_digits = 9;
   static const int kappa = 1;
   static const int big_divisor = 100;
   static const int small_divisor = 10;
   static const int min_k = -31;
   static const int max_k = 46;
-  static const int cache_bits = 64;
-  static const int divisibility_check_by_5_threshold = 39;
-  static const int case_fc_pm_half_lower_threshold = -1;
-  static const int case_fc_pm_half_upper_threshold = 6;
-  static const int case_fc_lower_threshold = -2;
-  static const int case_fc_upper_threshold = 6;
-  static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
-  static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
   static const int shorter_interval_tie_lower_threshold = -35;
   static const int shorter_interval_tie_upper_threshold = -35;
-  static const int max_trailing_zeros = 7;
 };
 
 template <> struct float_info<double> {
   using carrier_uint = uint64_t;
-  static const int significand_bits = 52;
   static const int exponent_bits = 11;
-  static const int min_exponent = -1022;
-  static const int max_exponent = 1023;
-  static const int exponent_bias = -1023;
-  static const int decimal_digits = 17;
   static const int kappa = 2;
   static const int big_divisor = 1000;
   static const int small_divisor = 100;
   static const int min_k = -292;
   static const int max_k = 326;
-  static const int cache_bits = 128;
-  static const int divisibility_check_by_5_threshold = 86;
-  static const int case_fc_pm_half_lower_threshold = -2;
-  static const int case_fc_pm_half_upper_threshold = 9;
-  static const int case_fc_lower_threshold = -4;
-  static const int case_fc_upper_threshold = 9;
-  static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
-  static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
   static const int shorter_interval_tie_lower_threshold = -77;
   static const int shorter_interval_tie_upper_threshold = -77;
-  static const int max_trailing_zeros = 16;
+};
+
+// An 80- or 128-bit floating point number.
+template <typename T>
+struct float_info<T, enable_if_t<std::numeric_limits<T>::digits == 64 ||
+                                 std::numeric_limits<T>::digits == 113 ||
+                                 is_float128<T>::value>> {
+  using carrier_uint = detail::uint128_t;
+  static const int exponent_bits = 15;
+};
+
+// A double-double floating point number.
+template <typename T>
+struct float_info<T, enable_if_t<is_double_double<T>::value>> {
+  using carrier_uint = detail::uint128_t;
 };
 
 template <typename T> struct decimal_fp {
@@ -1260,16 +1333,35 @@ template <typename T> struct decimal_fp {
   int exponent;
 };
 
-template <typename T>
-FMT_API auto to_decimal(T x) FMT_NOEXCEPT -> decimal_fp<T>;
+template <typename T> FMT_API auto to_decimal(T x) noexcept -> decimal_fp<T>;
 }  // namespace dragonbox
 
-template <typename T>
+// Returns true iff Float has the implicit bit which is not stored.
+template <typename Float> constexpr bool has_implicit_bit() {
+  // An 80-bit FP number has a 64-bit significand an no implicit bit.
+  return std::numeric_limits<Float>::digits != 64;
+}
+
+// Returns the number of significand bits stored in Float. The implicit bit is
+// not counted since it is not stored.
+template <typename Float> constexpr int num_significand_bits() {
+  // std::numeric_limits may not support __float128.
+  return is_float128<Float>() ? 112
+                              : (std::numeric_limits<Float>::digits -
+                                 (has_implicit_bit<Float>() ? 1 : 0));
+}
+
+template <typename Float>
 constexpr auto exponent_mask() ->
-    typename dragonbox::float_info<T>::carrier_uint {
-  using uint = typename dragonbox::float_info<T>::carrier_uint;
-  return ((uint(1) << dragonbox::float_info<T>::exponent_bits) - 1)
-         << dragonbox::float_info<T>::significand_bits;
+    typename dragonbox::float_info<Float>::carrier_uint {
+  using uint = typename dragonbox::float_info<Float>::carrier_uint;
+  return ((uint(1) << dragonbox::float_info<Float>::exponent_bits) - 1)
+         << num_significand_bits<Float>();
+}
+template <typename Float> constexpr auto exponent_bias() -> int {
+  // std::numeric_limits may not support __float128.
+  return is_float128<Float>() ? 16383
+                              : std::numeric_limits<Float>::max_exponent - 1;
 }
 
 // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
@@ -1294,21 +1386,251 @@ FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It {
   return it;
 }
 
-template <typename T>
-FMT_HEADER_ONLY_CONSTEXPR20 auto format_float(T value, int precision,
-                                              float_specs specs,
-                                              buffer<char>& buf) -> int;
+// A floating-point number f * pow(2, e) where F is an unsigned type.
+template <typename F> struct basic_fp {
+  F f;
+  int e;
+
+  static constexpr const int num_significand_bits =
+      static_cast<int>(sizeof(F) * num_bits<unsigned char>());
+
+  constexpr basic_fp() : f(0), e(0) {}
+  constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
+
+  // Constructs fp from an IEEE754 floating-point number.
+  template <typename Float> FMT_CONSTEXPR basic_fp(Float n) { assign(n); }
+
+  // Assigns n to this and return true iff predecessor is closer than successor.
+  template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
+  FMT_CONSTEXPR auto assign(Float n) -> bool {
+    static_assert(std::numeric_limits<Float>::digits <= 113, "unsupported FP");
+    // Assume Float is in the format [sign][exponent][significand].
+    using carrier_uint = typename dragonbox::float_info<Float>::carrier_uint;
+    const auto num_float_significand_bits =
+        detail::num_significand_bits<Float>();
+    const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
+    const auto significand_mask = implicit_bit - 1;
+    auto u = bit_cast<carrier_uint>(n);
+    f = static_cast<F>(u & significand_mask);
+    auto biased_e = static_cast<int>((u & exponent_mask<Float>()) >>
+                                     num_float_significand_bits);
+    // The predecessor is closer if n is a normalized power of 2 (f == 0)
+    // other than the smallest normalized number (biased_e > 1).
+    auto is_predecessor_closer = f == 0 && biased_e > 1;
+    if (biased_e == 0)
+      biased_e = 1;  // Subnormals use biased exponent 1 (min exponent).
+    else if (has_implicit_bit<Float>())
+      f += static_cast<F>(implicit_bit);
+    e = biased_e - exponent_bias<Float>() - num_float_significand_bits;
+    if (!has_implicit_bit<Float>()) ++e;
+    return is_predecessor_closer;
+  }
 
-// Formats a floating-point number with snprintf.
+  template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
+  FMT_CONSTEXPR auto assign(Float n) -> bool {
+    static_assert(std::numeric_limits<double>::is_iec559, "unsupported FP");
+    return assign(static_cast<double>(n));
+  }
+};
+
+using fp = basic_fp<unsigned long long>;
+
+// Normalizes the value converted from double and multiplied by (1 << SHIFT).
+template <int SHIFT = 0, typename F>
+FMT_CONSTEXPR basic_fp<F> normalize(basic_fp<F> value) {
+  // Handle subnormals.
+  const auto implicit_bit = F(1) << num_significand_bits<double>();
+  const auto shifted_implicit_bit = implicit_bit << SHIFT;
+  while ((value.f & shifted_implicit_bit) == 0) {
+    value.f <<= 1;
+    --value.e;
+  }
+  // Subtract 1 to account for hidden bit.
+  const auto offset = basic_fp<F>::num_significand_bits -
+                      num_significand_bits<double>() - SHIFT - 1;
+  value.f <<= offset;
+  value.e -= offset;
+  return value;
+}
+
+// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
+FMT_CONSTEXPR inline uint64_t multiply(uint64_t lhs, uint64_t rhs) {
+#if FMT_USE_INT128
+  auto product = static_cast<__uint128_t>(lhs) * rhs;
+  auto f = static_cast<uint64_t>(product >> 64);
+  return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
+#else
+  // Multiply 32-bit parts of significands.
+  uint64_t mask = (1ULL << 32) - 1;
+  uint64_t a = lhs >> 32, b = lhs & mask;
+  uint64_t c = rhs >> 32, d = rhs & mask;
+  uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
+  // Compute mid 64-bit of result and round.
+  uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
+  return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
+#endif
+}
+
+FMT_CONSTEXPR inline fp operator*(fp x, fp y) {
+  return {multiply(x.f, y.f), x.e + y.e + 64};
+}
+
+template <typename T = void> struct basic_data {
+  // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
+  // These are generated by support/compute-powers.py.
+  static constexpr uint64_t pow10_significands[87] = {
+      0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
+      0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
+      0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
+      0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
+      0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
+      0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
+      0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
+      0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
+      0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
+      0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
+      0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
+      0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
+      0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
+      0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
+      0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
+      0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
+      0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
+      0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
+      0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
+      0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
+      0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
+      0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
+      0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
+      0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
+      0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
+      0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
+      0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
+      0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
+      0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
+  };
+
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
+#  pragma GCC diagnostic push
+#  pragma GCC diagnostic ignored "-Wnarrowing"
+#endif
+  // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
+  // to significands above.
+  static constexpr int16_t pow10_exponents[87] = {
+      -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
+      -927,  -901,  -874,  -847,  -821,  -794,  -768,  -741,  -715,  -688, -661,
+      -635,  -608,  -582,  -555,  -529,  -502,  -475,  -449,  -422,  -396, -369,
+      -343,  -316,  -289,  -263,  -236,  -210,  -183,  -157,  -130,  -103, -77,
+      -50,   -24,   3,     30,    56,    83,    109,   136,   162,   189,  216,
+      242,   269,   295,   322,   348,   375,   402,   428,   455,   481,  508,
+      534,   561,   588,   614,   641,   667,   694,   720,   747,   774,  800,
+      827,   853,   880,   907,   933,   960,   986,   1013,  1039,  1066};
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
+#  pragma GCC diagnostic pop
+#endif
+
+  static constexpr uint64_t power_of_10_64[20] = {
+      1, FMT_POWERS_OF_10(1ULL), FMT_POWERS_OF_10(1000000000ULL),
+      10000000000000000000ULL};
+};
+
+#if FMT_CPLUSPLUS < 201703L
+template <typename T> constexpr uint64_t basic_data<T>::pow10_significands[];
+template <typename T> constexpr int16_t basic_data<T>::pow10_exponents[];
+template <typename T> constexpr uint64_t basic_data<T>::power_of_10_64[];
+#endif
+
+// This is a struct rather than an alias to avoid shadowing warnings in gcc.
+struct data : basic_data<> {};
+
+// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its
+// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`.
+FMT_CONSTEXPR inline fp get_cached_power(int min_exponent,
+                                         int& pow10_exponent) {
+  const int shift = 32;
+  // log10(2) = 0x0.4d104d427de7fbcc...
+  const int64_t significand = 0x4d104d427de7fbcc;
+  int index = static_cast<int>(
+      ((min_exponent + fp::num_significand_bits - 1) * (significand >> shift) +
+       ((int64_t(1) << shift) - 1))  // ceil
+      >> 32                          // arithmetic shift
+  );
+  // Decimal exponent of the first (smallest) cached power of 10.
+  const int first_dec_exp = -348;
+  // Difference between 2 consecutive decimal exponents in cached powers of 10.
+  const int dec_exp_step = 8;
+  index = (index - first_dec_exp - 1) / dec_exp_step + 1;
+  pow10_exponent = first_dec_exp + index * dec_exp_step;
+  // Using *(x + index) instead of x[index] avoids an issue with some compilers
+  // using the EDG frontend (e.g. nvhpc/22.3 in C++17 mode).
+  return {*(data::pow10_significands + index),
+          *(data::pow10_exponents + index)};
+}
+
+#ifndef _MSC_VER
+#  define FMT_SNPRINTF snprintf
+#else
+FMT_API auto fmt_snprintf(char* buf, size_t size, const char* fmt, ...) -> int;
+#  define FMT_SNPRINTF fmt_snprintf
+#endif  // _MSC_VER
+
+// Formats a floating-point number with snprintf using the hexfloat format.
 template <typename T>
 auto snprintf_float(T value, int precision, float_specs specs,
-                    buffer<char>& buf) -> int;
+                    buffer<char>& buf) -> int {
+  // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
+  FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer");
+  FMT_ASSERT(specs.format == float_format::hex, "");
+  static_assert(!std::is_same<T, float>::value, "");
+
+  // Build the format string.
+  char format[7];  // The longest format is "%#.*Le".
+  char* format_ptr = format;
+  *format_ptr++ = '%';
+  if (specs.showpoint) *format_ptr++ = '#';
+  if (precision >= 0) {
+    *format_ptr++ = '.';
+    *format_ptr++ = '*';
+  }
+  if (std::is_same<T, long double>()) *format_ptr++ = 'L';
+  *format_ptr++ = specs.upper ? 'A' : 'a';
+  *format_ptr = '\0';
 
-template <typename T> constexpr auto promote_float(T value) -> T {
-  return value;
+  // Format using snprintf.
+  auto offset = buf.size();
+  for (;;) {
+    auto begin = buf.data() + offset;
+    auto capacity = buf.capacity() - offset;
+    abort_fuzzing_if(precision > 100000);
+    // Suppress the warning about a nonliteral format string.
+    // Cannot use auto because of a bug in MinGW (#1532).
+    int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
+    int result = precision >= 0
+                     ? snprintf_ptr(begin, capacity, format, precision, value)
+                     : snprintf_ptr(begin, capacity, format, value);
+    if (result < 0) {
+      // The buffer will grow exponentially.
+      buf.try_reserve(buf.capacity() + 1);
+      continue;
+    }
+    auto size = to_unsigned(result);
+    // Size equal to capacity means that the last character was truncated.
+    if (size < capacity) {
+      buf.try_resize(size + offset);
+      return 0;
+    }
+    buf.try_reserve(size + offset + 1);  // Add 1 for the terminating '\0'.
+  }
 }
-constexpr auto promote_float(float value) -> double {
-  return static_cast<double>(value);
+
+template <typename T>
+using convert_float_result =
+    conditional_t<std::is_same<T, float>::value || sizeof(T) == sizeof(double),
+                  double, T>;
+
+template <typename T>
+constexpr auto convert_float(T value) -> convert_float_result<T> {
+  return static_cast<convert_float_result<T>>(value);
 }
 
 template <typename OutputIt, typename Char>
@@ -1377,11 +1699,172 @@ auto write_ptr(OutputIt out, UIntPtr value,
                : base_iterator(out, write(reserve(out, size)));
 }
 
+// Returns true iff the code point cp is printable.
+FMT_API auto is_printable(uint32_t cp) -> bool;
+
+inline auto needs_escape(uint32_t cp) -> bool {
+  return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' ||
+         !is_printable(cp);
+}
+
+template <typename Char> struct find_escape_result {
+  const Char* begin;
+  const Char* end;
+  uint32_t cp;
+};
+
+template <typename Char>
+using make_unsigned_char =
+    typename conditional_t<std::is_integral<Char>::value,
+                           std::make_unsigned<Char>,
+                           type_identity<uint32_t>>::type;
+
+template <typename Char>
+auto find_escape(const Char* begin, const Char* end)
+    -> find_escape_result<Char> {
+  for (; begin != end; ++begin) {
+    uint32_t cp = static_cast<make_unsigned_char<Char>>(*begin);
+    if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue;
+    if (needs_escape(cp)) return {begin, begin + 1, cp};
+  }
+  return {begin, nullptr, 0};
+}
+
+inline auto find_escape(const char* begin, const char* end)
+    -> find_escape_result<char> {
+  if (!is_utf8()) return find_escape<char>(begin, end);
+  auto result = find_escape_result<char>{end, nullptr, 0};
+  for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
+                     [&](uint32_t cp, string_view sv) {
+                       if (needs_escape(cp)) {
+                         result = {sv.begin(), sv.end(), cp};
+                         return false;
+                       }
+                       return true;
+                     });
+  return result;
+}
+
+#define FMT_STRING_IMPL(s, base, explicit)                                    \
+  [] {                                                                        \
+    /* Use the hidden visibility as a workaround for a GCC bug (#1973). */    \
+    /* Use a macro-like name to avoid shadowing warnings. */                  \
+    struct FMT_GCC_VISIBILITY_HIDDEN FMT_COMPILE_STRING : base {              \
+      using char_type FMT_MAYBE_UNUSED = fmt::remove_cvref_t<decltype(s[0])>; \
+      FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit                                 \
+      operator fmt::basic_string_view<char_type>() const {                    \
+        return fmt::detail_exported::compile_string_to_view<char_type>(s);    \
+      }                                                                       \
+    };                                                                        \
+    return FMT_COMPILE_STRING();                                              \
+  }()
+
+/**
+  \rst
+  Constructs a compile-time format string from a string literal *s*.
+
+  **Example**::
+
+    // A compile-time error because 'd' is an invalid specifier for strings.
+    std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
+  \endrst
+ */
+#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string, )
+
+template <size_t width, typename Char, typename OutputIt>
+auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt {
+  *out++ = static_cast<Char>('\\');
+  *out++ = static_cast<Char>(prefix);
+  Char buf[width];
+  fill_n(buf, width, static_cast<Char>('0'));
+  format_uint<4>(buf, cp, width);
+  return copy_str<Char>(buf, buf + width, out);
+}
+
+template <typename OutputIt, typename Char>
+auto write_escaped_cp(OutputIt out, const find_escape_result<Char>& escape)
+    -> OutputIt {
+  auto c = static_cast<Char>(escape.cp);
+  switch (escape.cp) {
+  case '\n':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('n');
+    break;
+  case '\r':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('r');
+    break;
+  case '\t':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('t');
+    break;
+  case '"':
+    FMT_FALLTHROUGH;
+  case '\'':
+    FMT_FALLTHROUGH;
+  case '\\':
+    *out++ = static_cast<Char>('\\');
+    break;
+  default:
+    if (is_utf8()) {
+      if (escape.cp < 0x100) {
+        return write_codepoint<2, Char>(out, 'x', escape.cp);
+      }
+      if (escape.cp < 0x10000) {
+        return write_codepoint<4, Char>(out, 'u', escape.cp);
+      }
+      if (escape.cp < 0x110000) {
+        return write_codepoint<8, Char>(out, 'U', escape.cp);
+      }
+    }
+    for (Char escape_char : basic_string_view<Char>(
+             escape.begin, to_unsigned(escape.end - escape.begin))) {
+      out = write_codepoint<2, Char>(out, 'x',
+                                     static_cast<uint32_t>(escape_char) & 0xFF);
+    }
+    return out;
+  }
+  *out++ = c;
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+auto write_escaped_string(OutputIt out, basic_string_view<Char> str)
+    -> OutputIt {
+  *out++ = static_cast<Char>('"');
+  auto begin = str.begin(), end = str.end();
+  do {
+    auto escape = find_escape(begin, end);
+    out = copy_str<Char>(begin, escape.begin, out);
+    begin = escape.end;
+    if (!begin) break;
+    out = write_escaped_cp<OutputIt, Char>(out, escape);
+  } while (begin != end);
+  *out++ = static_cast<Char>('"');
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+auto write_escaped_char(OutputIt out, Char v) -> OutputIt {
+  *out++ = static_cast<Char>('\'');
+  if ((needs_escape(static_cast<uint32_t>(v)) && v != static_cast<Char>('"')) ||
+      v == static_cast<Char>('\'')) {
+    out = write_escaped_cp(
+        out, find_escape_result<Char>{&v, &v + 1, static_cast<uint32_t>(v)});
+  } else {
+    *out++ = v;
+  }
+  *out++ = static_cast<Char>('\'');
+  return out;
+}
+
 template <typename Char, typename OutputIt>
 FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
                               const basic_format_specs<Char>& specs)
     -> OutputIt {
+  bool is_debug = specs.type == presentation_type::debug;
   return write_padded(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
+    if (is_debug) return write_escaped_char(it, value);
     *it++ = value;
     return it;
   });
@@ -1519,7 +2002,10 @@ auto write_int_localized(OutputIt out, UInt value, unsigned prefix,
                               grouping.count_separators(num_digits));
   return write_padded<align::right>(
       out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
-        if (prefix != 0) *it++ = static_cast<Char>(prefix);
+        if (prefix != 0) {
+          char sign = static_cast<char>(prefix);
+          *it++ = static_cast<Char>(sign);
+        }
         return grouping.apply(it, string_view(digits, to_unsigned(num_digits)));
       });
 }
@@ -1647,6 +2133,46 @@ FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
   return write_int(out, make_write_int_arg(value, specs.sign), specs, loc);
 }
 
+// An output iterator that counts the number of objects written to it and
+// discards them.
+class counting_iterator {
+ private:
+  size_t count_;
+
+ public:
+  using iterator_category = std::output_iterator_tag;
+  using difference_type = std::ptrdiff_t;
+  using pointer = void;
+  using reference = void;
+  FMT_UNCHECKED_ITERATOR(counting_iterator);
+
+  struct value_type {
+    template <typename T> FMT_CONSTEXPR void operator=(const T&) {}
+  };
+
+  FMT_CONSTEXPR counting_iterator() : count_(0) {}
+
+  FMT_CONSTEXPR size_t count() const { return count_; }
+
+  FMT_CONSTEXPR counting_iterator& operator++() {
+    ++count_;
+    return *this;
+  }
+  FMT_CONSTEXPR counting_iterator operator++(int) {
+    auto it = *this;
+    ++*this;
+    return it;
+  }
+
+  FMT_CONSTEXPR friend counting_iterator operator+(counting_iterator it,
+                                                   difference_type n) {
+    it.count_ += static_cast<size_t>(n);
+    return it;
+  }
+
+  FMT_CONSTEXPR value_type operator*() const { return {}; }
+};
+
 template <typename Char, typename OutputIt>
 FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
                          const basic_format_specs<Char>& specs) -> OutputIt {
@@ -1654,10 +2180,17 @@ FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
   auto size = s.size();
   if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
     size = code_point_index(s, to_unsigned(specs.precision));
-  auto width =
-      specs.width != 0 ? compute_width(basic_string_view<Char>(data, size)) : 0;
+  bool is_debug = specs.type == presentation_type::debug;
+  size_t width = 0;
+  if (specs.width != 0) {
+    if (is_debug)
+      width = write_escaped_string(counting_iterator{}, s).count();
+    else
+      width = compute_width(basic_string_view<Char>(data, size));
+  }
   return write_padded(out, specs, size, width,
                       [=](reserve_iterator<OutputIt> it) {
+                        if (is_debug) return write_escaped_string(it, s);
                         return copy_str<Char>(data, data + size, it);
                       });
 }
@@ -1675,15 +2208,37 @@ FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
     -> OutputIt {
   return check_cstring_type_spec(specs.type)
              ? write(out, basic_string_view<Char>(s), specs, {})
-             : write_ptr<Char>(out, to_uintptr(s), &specs);
+             : write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_integral<T>::value &&
+                        !std::is_same<T, bool>::value &&
+                        !std::is_same<T, Char>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
+  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
+  bool negative = is_negative(value);
+  // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
+  if (negative) abs_value = ~abs_value + 1;
+  int num_digits = count_digits(abs_value);
+  auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
+  auto it = reserve(out, size);
+  if (auto ptr = to_pointer<Char>(it, size)) {
+    if (negative) *ptr++ = static_cast<Char>('-');
+    format_decimal<Char>(ptr, abs_value, num_digits);
+    return out;
+  }
+  if (negative) *it++ = static_cast<Char>('-');
+  it = format_decimal<Char>(it, abs_value, num_digits).end;
+  return base_iterator(out, it);
 }
 
 template <typename Char, typename OutputIt>
-FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isinf,
+FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan,
                                      basic_format_specs<Char> specs,
                                      const float_specs& fspecs) -> OutputIt {
   auto str =
-      isinf ? (fspecs.upper ? "INF" : "inf") : (fspecs.upper ? "NAN" : "nan");
+      isnan ? (fspecs.upper ? "NAN" : "nan") : (fspecs.upper ? "INF" : "inf");
   constexpr size_t str_size = 3;
   auto sign = fspecs.sign;
   auto size = str_size + (sign ? 1 : 0);
@@ -1704,12 +2259,12 @@ struct big_decimal_fp {
   int exponent;
 };
 
-constexpr auto get_significand_size(const big_decimal_fp& fp) -> int {
-  return fp.significand_size;
+constexpr auto get_significand_size(const big_decimal_fp& f) -> int {
+  return f.significand_size;
 }
 template <typename T>
-inline auto get_significand_size(const dragonbox::decimal_fp<T>& fp) -> int {
-  return count_digits(fp.significand);
+inline auto get_significand_size(const dragonbox::decimal_fp<T>& f) -> int {
+  return count_digits(f.significand);
 }
 
 template <typename Char, typename OutputIt>
@@ -1747,7 +2302,7 @@ inline auto write_significand(Char* out, UInt significand, int significand_size,
   int floating_size = significand_size - integral_size;
   for (int i = floating_size / 2; i > 0; --i) {
     out -= 2;
-    copy2(out, digits2(significand % 100));
+    copy2(out, digits2(static_cast<std::size_t>(significand % 100)));
     significand /= 100;
   }
   if (floating_size % 2 != 0) {
@@ -1803,13 +2358,13 @@ FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
 
 template <typename OutputIt, typename DecimalFP, typename Char,
           typename Grouping = digit_grouping<Char>>
-FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& fp,
+FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f,
                                     const basic_format_specs<Char>& specs,
                                     float_specs fspecs, locale_ref loc)
     -> OutputIt {
-  auto significand = fp.significand;
-  int significand_size = get_significand_size(fp);
-  constexpr Char zero = static_cast<Char>('0');
+  auto significand = f.significand;
+  int significand_size = get_significand_size(f);
+  const Char zero = static_cast<Char>('0');
   auto sign = fspecs.sign;
   size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
   using iterator = reserve_iterator<OutputIt>;
@@ -1817,7 +2372,7 @@ FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& fp,
   Char decimal_point =
       fspecs.locale ? detail::decimal_point<Char>(loc) : static_cast<Char>('.');
 
-  int output_exp = fp.exponent + significand_size - 1;
+  int output_exp = f.exponent + significand_size - 1;
   auto use_exp_format = [=]() {
     if (fspecs.format == float_format::exp) return true;
     if (fspecs.format != float_format::general) return false;
@@ -1855,25 +2410,23 @@ FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& fp,
                            : base_iterator(out, write(reserve(out, size)));
   }
 
-  int exp = fp.exponent + significand_size;
-  if (fp.exponent >= 0) {
+  int exp = f.exponent + significand_size;
+  if (f.exponent >= 0) {
     // 1234e5 -> 123400000[.0+]
-    size += to_unsigned(fp.exponent);
+    size += to_unsigned(f.exponent);
     int num_zeros = fspecs.precision - exp;
-#ifdef FMT_FUZZ
-    if (num_zeros > 5000)
-      throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
-#endif
+    abort_fuzzing_if(num_zeros > 5000);
     if (fspecs.showpoint) {
+      ++size;
       if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1;
-      if (num_zeros > 0) size += to_unsigned(num_zeros) + 1;
+      if (num_zeros > 0) size += to_unsigned(num_zeros);
     }
     auto grouping = Grouping(loc, fspecs.locale);
-    size += to_unsigned(grouping.count_separators(significand_size));
+    size += to_unsigned(grouping.count_separators(exp));
     return write_padded<align::right>(out, specs, size, [&](iterator it) {
       if (sign) *it++ = detail::sign<Char>(sign);
       it = write_significand<Char>(it, significand, significand_size,
-                                   fp.exponent, grouping);
+                                   f.exponent, grouping);
       if (!fspecs.showpoint) return it;
       *it++ = decimal_point;
       return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
@@ -1924,63 +2477,713 @@ template <typename Char> class fallback_digit_grouping {
 };
 
 template <typename OutputIt, typename DecimalFP, typename Char>
-FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& fp,
+FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,
                                  const basic_format_specs<Char>& specs,
                                  float_specs fspecs, locale_ref loc)
     -> OutputIt {
   if (is_constant_evaluated()) {
     return do_write_float<OutputIt, DecimalFP, Char,
-                          fallback_digit_grouping<Char>>(out, fp, specs, fspecs,
+                          fallback_digit_grouping<Char>>(out, f, specs, fspecs,
                                                          loc);
   } else {
-    return do_write_float(out, fp, specs, fspecs, loc);
+    return do_write_float(out, f, specs, fspecs, loc);
   }
 }
 
-template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
-FMT_CONSTEXPR20 bool isinf(T value) {
-  if (is_constant_evaluated()) {
-#if defined(__cpp_if_constexpr)
-    if constexpr (std::numeric_limits<double>::is_iec559) {
-      auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
-      constexpr auto significand_bits =
-          dragonbox::float_info<double>::significand_bits;
-      return (bits & exponent_mask<double>()) &&
-             !(bits & ((uint64_t(1) << significand_bits) - 1));
-    }
-#endif
-  }
-  return std::isinf(value);
+template <typename T> constexpr bool isnan(T value) {
+  return !(value >= value);  // std::isnan doesn't support __float128.
 }
 
-template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+template <typename T, typename Enable = void>
+struct has_isfinite : std::false_type {};
+
+template <typename T>
+struct has_isfinite<T, enable_if_t<sizeof(std::isfinite(T())) != 0>>
+    : std::true_type {};
+
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value&&
+                                        has_isfinite<T>::value)>
 FMT_CONSTEXPR20 bool isfinite(T value) {
-  if (is_constant_evaluated()) {
-#if defined(__cpp_if_constexpr)
-    if constexpr (std::numeric_limits<double>::is_iec559) {
-      auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
-      return (bits & exponent_mask<double>()) != exponent_mask<double>();
-    }
-#endif
-  }
+  constexpr T inf = T(std::numeric_limits<double>::infinity());
+  if (is_constant_evaluated())
+    return !detail::isnan(value) && value != inf && value != -inf;
   return std::isfinite(value);
 }
+template <typename T, FMT_ENABLE_IF(!has_isfinite<T>::value)>
+FMT_CONSTEXPR bool isfinite(T value) {
+  T inf = T(std::numeric_limits<double>::infinity());
+  // std::isfinite doesn't support __float128.
+  return !detail::isnan(value) && value != inf && value != -inf;
+}
 
-template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+template <typename T, FMT_ENABLE_IF(is_floating_point<T>::value)>
 FMT_INLINE FMT_CONSTEXPR bool signbit(T value) {
   if (is_constant_evaluated()) {
 #ifdef __cpp_if_constexpr
     if constexpr (std::numeric_limits<double>::is_iec559) {
       auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
-      return (bits & (uint64_t(1) << (num_bits<uint64_t>() - 1))) != 0;
+      return (bits >> (num_bits<uint64_t>() - 1)) != 0;
     }
 #endif
   }
-  return std::signbit(value);
+  return std::signbit(static_cast<double>(value));
+}
+
+enum class round_direction { unknown, up, down };
+
+// Given the divisor (normally a power of 10), the remainder = v % divisor for
+// some number v and the error, returns whether v should be rounded up, down, or
+// whether the rounding direction can't be determined due to error.
+// error should be less than divisor / 2.
+FMT_CONSTEXPR inline round_direction get_round_direction(uint64_t divisor,
+                                                         uint64_t remainder,
+                                                         uint64_t error) {
+  FMT_ASSERT(remainder < divisor, "");  // divisor - remainder won't overflow.
+  FMT_ASSERT(error < divisor, "");      // divisor - error won't overflow.
+  FMT_ASSERT(error < divisor - error, "");  // error * 2 won't overflow.
+  // Round down if (remainder + error) * 2 <= divisor.
+  if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
+    return round_direction::down;
+  // Round up if (remainder - error) * 2 >= divisor.
+  if (remainder >= error &&
+      remainder - error >= divisor - (remainder - error)) {
+    return round_direction::up;
+  }
+  return round_direction::unknown;
+}
+
+namespace digits {
+enum result {
+  more,  // Generate more digits.
+  done,  // Done generating digits.
+  error  // Digit generation cancelled due to an error.
+};
+}
+
+struct gen_digits_handler {
+  char* buf;
+  int size;
+  int precision;
+  int exp10;
+  bool fixed;
+
+  FMT_CONSTEXPR digits::result on_digit(char digit, uint64_t divisor,
+                                        uint64_t remainder, uint64_t error,
+                                        bool integral) {
+    FMT_ASSERT(remainder < divisor, "");
+    buf[size++] = digit;
+    if (!integral && error >= remainder) return digits::error;
+    if (size < precision) return digits::more;
+    if (!integral) {
+      // Check if error * 2 < divisor with overflow prevention.
+      // The check is not needed for the integral part because error = 1
+      // and divisor > (1 << 32) there.
+      if (error >= divisor || error >= divisor - error) return digits::error;
+    } else {
+      FMT_ASSERT(error == 1 && divisor > 2, "");
+    }
+    auto dir = get_round_direction(divisor, remainder, error);
+    if (dir != round_direction::up)
+      return dir == round_direction::down ? digits::done : digits::error;
+    ++buf[size - 1];
+    for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
+      buf[i] = '0';
+      ++buf[i - 1];
+    }
+    if (buf[0] > '9') {
+      buf[0] = '1';
+      if (fixed)
+        buf[size++] = '0';
+      else
+        ++exp10;
+    }
+    return digits::done;
+  }
+};
+
+inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) {
+  // Adjust fixed precision by exponent because it is relative to decimal
+  // point.
+  if (exp10 > 0 && precision > max_value<int>() - exp10)
+    FMT_THROW(format_error("number is too big"));
+  precision += exp10;
+}
+
+// Generates output using the Grisu digit-gen algorithm.
+// error: the size of the region (lower, upper) outside of which numbers
+// definitely do not round to value (Delta in Grisu3).
+FMT_INLINE FMT_CONSTEXPR20 auto grisu_gen_digits(fp value, uint64_t error,
+                                                 int& exp,
+                                                 gen_digits_handler& handler)
+    -> digits::result {
+  const fp one(1ULL << -value.e, value.e);
+  // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
+  // zero because it contains a product of two 64-bit numbers with MSB set (due
+  // to normalization) - 1, shifted right by at most 60 bits.
+  auto integral = static_cast<uint32_t>(value.f >> -one.e);
+  FMT_ASSERT(integral != 0, "");
+  FMT_ASSERT(integral == value.f >> -one.e, "");
+  // The fractional part of scaled value (p2 in Grisu) c = value % one.
+  uint64_t fractional = value.f & (one.f - 1);
+  exp = count_digits(integral);  // kappa in Grisu.
+  // Non-fixed formats require at least one digit and no precision adjustment.
+  if (handler.fixed) {
+    adjust_precision(handler.precision, exp + handler.exp10);
+    // Check if precision is satisfied just by leading zeros, e.g.
+    // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
+    if (handler.precision <= 0) {
+      if (handler.precision < 0) return digits::done;
+      // Divide by 10 to prevent overflow.
+      uint64_t divisor = data::power_of_10_64[exp - 1] << -one.e;
+      auto dir = get_round_direction(divisor, value.f / 10, error * 10);
+      if (dir == round_direction::unknown) return digits::error;
+      handler.buf[handler.size++] = dir == round_direction::up ? '1' : '0';
+      return digits::done;
+    }
+  }
+  // Generate digits for the integral part. This can produce up to 10 digits.
+  do {
+    uint32_t digit = 0;
+    auto divmod_integral = [&](uint32_t divisor) {
+      digit = integral / divisor;
+      integral %= divisor;
+    };
+    // This optimization by Milo Yip reduces the number of integer divisions by
+    // one per iteration.
+    switch (exp) {
+    case 10:
+      divmod_integral(1000000000);
+      break;
+    case 9:
+      divmod_integral(100000000);
+      break;
+    case 8:
+      divmod_integral(10000000);
+      break;
+    case 7:
+      divmod_integral(1000000);
+      break;
+    case 6:
+      divmod_integral(100000);
+      break;
+    case 5:
+      divmod_integral(10000);
+      break;
+    case 4:
+      divmod_integral(1000);
+      break;
+    case 3:
+      divmod_integral(100);
+      break;
+    case 2:
+      divmod_integral(10);
+      break;
+    case 1:
+      digit = integral;
+      integral = 0;
+      break;
+    default:
+      FMT_ASSERT(false, "invalid number of digits");
+    }
+    --exp;
+    auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional;
+    auto result = handler.on_digit(static_cast<char>('0' + digit),
+                                   data::power_of_10_64[exp] << -one.e,
+                                   remainder, error, true);
+    if (result != digits::more) return result;
+  } while (exp > 0);
+  // Generate digits for the fractional part.
+  for (;;) {
+    fractional *= 10;
+    error *= 10;
+    char digit = static_cast<char>('0' + (fractional >> -one.e));
+    fractional &= one.f - 1;
+    --exp;
+    auto result = handler.on_digit(digit, one.f, fractional, error, false);
+    if (result != digits::more) return result;
+  }
+}
+
+class bigint {
+ private:
+  // A bigint is stored as an array of bigits (big digits), with bigit at index
+  // 0 being the least significant one.
+  using bigit = uint32_t;
+  using double_bigit = uint64_t;
+  enum { bigits_capacity = 32 };
+  basic_memory_buffer<bigit, bigits_capacity> bigits_;
+  int exp_;
+
+  FMT_CONSTEXPR20 bigit operator[](int index) const {
+    return bigits_[to_unsigned(index)];
+  }
+  FMT_CONSTEXPR20 bigit& operator[](int index) {
+    return bigits_[to_unsigned(index)];
+  }
+
+  static constexpr const int bigit_bits = num_bits<bigit>();
+
+  friend struct formatter<bigint>;
+
+  FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) {
+    auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
+    (*this)[index] = static_cast<bigit>(result);
+    borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
+  }
+
+  FMT_CONSTEXPR20 void remove_leading_zeros() {
+    int num_bigits = static_cast<int>(bigits_.size()) - 1;
+    while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
+    bigits_.resize(to_unsigned(num_bigits + 1));
+  }
+
+  // Computes *this -= other assuming aligned bigints and *this >= other.
+  FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) {
+    FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
+    FMT_ASSERT(compare(*this, other) >= 0, "");
+    bigit borrow = 0;
+    int i = other.exp_ - exp_;
+    for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
+      subtract_bigits(i, other.bigits_[j], borrow);
+    while (borrow > 0) subtract_bigits(i, 0, borrow);
+    remove_leading_zeros();
+  }
+
+  FMT_CONSTEXPR20 void multiply(uint32_t value) {
+    const double_bigit wide_value = value;
+    bigit carry = 0;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      double_bigit result = bigits_[i] * wide_value + carry;
+      bigits_[i] = static_cast<bigit>(result);
+      carry = static_cast<bigit>(result >> bigit_bits);
+    }
+    if (carry != 0) bigits_.push_back(carry);
+  }
+
+  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
+                                         std::is_same<UInt, uint128_t>::value)>
+  FMT_CONSTEXPR20 void multiply(UInt value) {
+    using half_uint =
+        conditional_t<std::is_same<UInt, uint128_t>::value, uint64_t, uint32_t>;
+    const int shift = num_bits<half_uint>() - bigit_bits;
+    const UInt lower = static_cast<half_uint>(value);
+    const UInt upper = value >> num_bits<half_uint>();
+    UInt carry = 0;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      UInt result = lower * bigits_[i] + static_cast<bigit>(carry);
+      carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) +
+              (carry >> bigit_bits);
+      bigits_[i] = static_cast<bigit>(result);
+    }
+    while (carry != 0) {
+      bigits_.push_back(static_cast<bigit>(carry));
+      carry >>= bigit_bits;
+    }
+  }
+
+  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
+                                         std::is_same<UInt, uint128_t>::value)>
+  FMT_CONSTEXPR20 void assign(UInt n) {
+    size_t num_bigits = 0;
+    do {
+      bigits_[num_bigits++] = static_cast<bigit>(n);
+      n >>= bigit_bits;
+    } while (n != 0);
+    bigits_.resize(num_bigits);
+    exp_ = 0;
+  }
+
+ public:
+  FMT_CONSTEXPR20 bigint() : exp_(0) {}
+  explicit bigint(uint64_t n) { assign(n); }
+
+  bigint(const bigint&) = delete;
+  void operator=(const bigint&) = delete;
+
+  FMT_CONSTEXPR20 void assign(const bigint& other) {
+    auto size = other.bigits_.size();
+    bigits_.resize(size);
+    auto data = other.bigits_.data();
+    std::copy(data, data + size, make_checked(bigits_.data(), size));
+    exp_ = other.exp_;
+  }
+
+  template <typename Int> FMT_CONSTEXPR20 void operator=(Int n) {
+    FMT_ASSERT(n > 0, "");
+    assign(uint64_or_128_t<Int>(n));
+  }
+
+  FMT_CONSTEXPR20 int num_bigits() const {
+    return static_cast<int>(bigits_.size()) + exp_;
+  }
+
+  FMT_NOINLINE FMT_CONSTEXPR20 bigint& operator<<=(int shift) {
+    FMT_ASSERT(shift >= 0, "");
+    exp_ += shift / bigit_bits;
+    shift %= bigit_bits;
+    if (shift == 0) return *this;
+    bigit carry = 0;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      bigit c = bigits_[i] >> (bigit_bits - shift);
+      bigits_[i] = (bigits_[i] << shift) + carry;
+      carry = c;
+    }
+    if (carry != 0) bigits_.push_back(carry);
+    return *this;
+  }
+
+  template <typename Int> FMT_CONSTEXPR20 bigint& operator*=(Int value) {
+    FMT_ASSERT(value > 0, "");
+    multiply(uint32_or_64_or_128_t<Int>(value));
+    return *this;
+  }
+
+  friend FMT_CONSTEXPR20 int compare(const bigint& lhs, const bigint& rhs) {
+    int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
+    if (num_lhs_bigits != num_rhs_bigits)
+      return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
+    int i = static_cast<int>(lhs.bigits_.size()) - 1;
+    int j = static_cast<int>(rhs.bigits_.size()) - 1;
+    int end = i - j;
+    if (end < 0) end = 0;
+    for (; i >= end; --i, --j) {
+      bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
+      if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
+    }
+    if (i != j) return i > j ? 1 : -1;
+    return 0;
+  }
+
+  // Returns compare(lhs1 + lhs2, rhs).
+  friend FMT_CONSTEXPR20 int add_compare(const bigint& lhs1, const bigint& lhs2,
+                                         const bigint& rhs) {
+    auto minimum = [](int a, int b) { return a < b ? a : b; };
+    auto maximum = [](int a, int b) { return a > b ? a : b; };
+    int max_lhs_bigits = maximum(lhs1.num_bigits(), lhs2.num_bigits());
+    int num_rhs_bigits = rhs.num_bigits();
+    if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
+    if (max_lhs_bigits > num_rhs_bigits) return 1;
+    auto get_bigit = [](const bigint& n, int i) -> bigit {
+      return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
+    };
+    double_bigit borrow = 0;
+    int min_exp = minimum(minimum(lhs1.exp_, lhs2.exp_), rhs.exp_);
+    for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
+      double_bigit sum =
+          static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
+      bigit rhs_bigit = get_bigit(rhs, i);
+      if (sum > rhs_bigit + borrow) return 1;
+      borrow = rhs_bigit + borrow - sum;
+      if (borrow > 1) return -1;
+      borrow <<= bigit_bits;
+    }
+    return borrow != 0 ? -1 : 0;
+  }
+
+  // Assigns pow(10, exp) to this bigint.
+  FMT_CONSTEXPR20 void assign_pow10(int exp) {
+    FMT_ASSERT(exp >= 0, "");
+    if (exp == 0) return *this = 1;
+    // Find the top bit.
+    int bitmask = 1;
+    while (exp >= bitmask) bitmask <<= 1;
+    bitmask >>= 1;
+    // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
+    // repeated squaring and multiplication.
+    *this = 5;
+    bitmask >>= 1;
+    while (bitmask != 0) {
+      square();
+      if ((exp & bitmask) != 0) *this *= 5;
+      bitmask >>= 1;
+    }
+    *this <<= exp;  // Multiply by pow(2, exp) by shifting.
+  }
+
+  FMT_CONSTEXPR20 void square() {
+    int num_bigits = static_cast<int>(bigits_.size());
+    int num_result_bigits = 2 * num_bigits;
+    basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
+    bigits_.resize(to_unsigned(num_result_bigits));
+    auto sum = uint128_t();
+    for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
+      // Compute bigit at position bigit_index of the result by adding
+      // cross-product terms n[i] * n[j] such that i + j == bigit_index.
+      for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
+        // Most terms are multiplied twice which can be optimized in the future.
+        sum += static_cast<double_bigit>(n[i]) * n[j];
+      }
+      (*this)[bigit_index] = static_cast<bigit>(sum);
+      sum >>= num_bits<bigit>();  // Compute the carry.
+    }
+    // Do the same for the top half.
+    for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
+         ++bigit_index) {
+      for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
+        sum += static_cast<double_bigit>(n[i++]) * n[j--];
+      (*this)[bigit_index] = static_cast<bigit>(sum);
+      sum >>= num_bits<bigit>();
+    }
+    remove_leading_zeros();
+    exp_ *= 2;
+  }
+
+  // If this bigint has a bigger exponent than other, adds trailing zero to make
+  // exponents equal. This simplifies some operations such as subtraction.
+  FMT_CONSTEXPR20 void align(const bigint& other) {
+    int exp_difference = exp_ - other.exp_;
+    if (exp_difference <= 0) return;
+    int num_bigits = static_cast<int>(bigits_.size());
+    bigits_.resize(to_unsigned(num_bigits + exp_difference));
+    for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
+      bigits_[j] = bigits_[i];
+    std::uninitialized_fill_n(bigits_.data(), exp_difference, 0);
+    exp_ -= exp_difference;
+  }
+
+  // Divides this bignum by divisor, assigning the remainder to this and
+  // returning the quotient.
+  FMT_CONSTEXPR20 int divmod_assign(const bigint& divisor) {
+    FMT_ASSERT(this != &divisor, "");
+    if (compare(*this, divisor) < 0) return 0;
+    FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
+    align(divisor);
+    int quotient = 0;
+    do {
+      subtract_aligned(divisor);
+      ++quotient;
+    } while (compare(*this, divisor) >= 0);
+    return quotient;
+  }
+};
+
+// format_dragon flags.
+enum dragon {
+  predecessor_closer = 1,
+  fixup = 2,  // Run fixup to correct exp10 which can be off by one.
+  fixed = 4,
+};
+
+// Formats a floating-point number using a variation of the Fixed-Precision
+// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
+// https://fmt.dev/papers/p372-steele.pdf.
+FMT_CONSTEXPR20 inline void format_dragon(basic_fp<uint128_t> value,
+                                          unsigned flags, int num_digits,
+                                          buffer<char>& buf, int& exp10) {
+  bigint numerator;    // 2 * R in (FPP)^2.
+  bigint denominator;  // 2 * S in (FPP)^2.
+  // lower and upper are differences between value and corresponding boundaries.
+  bigint lower;             // (M^- in (FPP)^2).
+  bigint upper_store;       // upper's value if different from lower.
+  bigint* upper = nullptr;  // (M^+ in (FPP)^2).
+  // Shift numerator and denominator by an extra bit or two (if lower boundary
+  // is closer) to make lower and upper integers. This eliminates multiplication
+  // by 2 during later computations.
+  bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0;
+  int shift = is_predecessor_closer ? 2 : 1;
+  if (value.e >= 0) {
+    numerator = value.f;
+    numerator <<= value.e + shift;
+    lower = 1;
+    lower <<= value.e;
+    if (is_predecessor_closer) {
+      upper_store = 1;
+      upper_store <<= value.e + 1;
+      upper = &upper_store;
+    }
+    denominator.assign_pow10(exp10);
+    denominator <<= shift;
+  } else if (exp10 < 0) {
+    numerator.assign_pow10(-exp10);
+    lower.assign(numerator);
+    if (is_predecessor_closer) {
+      upper_store.assign(numerator);
+      upper_store <<= 1;
+      upper = &upper_store;
+    }
+    numerator *= value.f;
+    numerator <<= shift;
+    denominator = 1;
+    denominator <<= shift - value.e;
+  } else {
+    numerator = value.f;
+    numerator <<= shift;
+    denominator.assign_pow10(exp10);
+    denominator <<= shift - value.e;
+    lower = 1;
+    if (is_predecessor_closer) {
+      upper_store = 1ULL << 1;
+      upper = &upper_store;
+    }
+  }
+  int even = static_cast<int>((value.f & 1) == 0);
+  if (!upper) upper = &lower;
+  if ((flags & dragon::fixup) != 0) {
+    if (add_compare(numerator, *upper, denominator) + even <= 0) {
+      --exp10;
+      numerator *= 10;
+      if (num_digits < 0) {
+        lower *= 10;
+        if (upper != &lower) *upper *= 10;
+      }
+    }
+    if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1);
+  }
+  // Invariant: value == (numerator / denominator) * pow(10, exp10).
+  if (num_digits < 0) {
+    // Generate the shortest representation.
+    num_digits = 0;
+    char* data = buf.data();
+    for (;;) {
+      int digit = numerator.divmod_assign(denominator);
+      bool low = compare(numerator, lower) - even < 0;  // numerator <[=] lower.
+      // numerator + upper >[=] pow10:
+      bool high = add_compare(numerator, *upper, denominator) + even > 0;
+      data[num_digits++] = static_cast<char>('0' + digit);
+      if (low || high) {
+        if (!low) {
+          ++data[num_digits - 1];
+        } else if (high) {
+          int result = add_compare(numerator, numerator, denominator);
+          // Round half to even.
+          if (result > 0 || (result == 0 && (digit % 2) != 0))
+            ++data[num_digits - 1];
+        }
+        buf.try_resize(to_unsigned(num_digits));
+        exp10 -= num_digits - 1;
+        return;
+      }
+      numerator *= 10;
+      lower *= 10;
+      if (upper != &lower) *upper *= 10;
+    }
+  }
+  // Generate the given number of digits.
+  exp10 -= num_digits - 1;
+  if (num_digits == 0) {
+    denominator *= 10;
+    auto digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
+    buf.push_back(digit);
+    return;
+  }
+  buf.try_resize(to_unsigned(num_digits));
+  for (int i = 0; i < num_digits - 1; ++i) {
+    int digit = numerator.divmod_assign(denominator);
+    buf[i] = static_cast<char>('0' + digit);
+    numerator *= 10;
+  }
+  int digit = numerator.divmod_assign(denominator);
+  auto result = add_compare(numerator, numerator, denominator);
+  if (result > 0 || (result == 0 && (digit % 2) != 0)) {
+    if (digit == 9) {
+      const auto overflow = '0' + 10;
+      buf[num_digits - 1] = overflow;
+      // Propagate the carry.
+      for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
+        buf[i] = '0';
+        ++buf[i - 1];
+      }
+      if (buf[0] == overflow) {
+        buf[0] = '1';
+        ++exp10;
+      }
+      return;
+    }
+    ++digit;
+  }
+  buf[num_digits - 1] = static_cast<char>('0' + digit);
+}
+
+template <typename Float>
+FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs,
+                                  buffer<char>& buf) -> int {
+  // float is passed as double to reduce the number of instantiations.
+  static_assert(!std::is_same<Float, float>::value, "");
+  FMT_ASSERT(value >= 0, "value is negative");
+  auto converted_value = convert_float(value);
+
+  const bool fixed = specs.format == float_format::fixed;
+  if (value <= 0) {  // <= instead of == to silence a warning.
+    if (precision <= 0 || !fixed) {
+      buf.push_back('0');
+      return 0;
+    }
+    buf.try_resize(to_unsigned(precision));
+    fill_n(buf.data(), precision, '0');
+    return -precision;
+  }
+
+  int exp = 0;
+  bool use_dragon = true;
+  unsigned dragon_flags = 0;
+  if (!is_fast_float<Float>()) {
+    const auto inv_log2_10 = 0.3010299956639812;  // 1 / log2(10)
+    using info = dragonbox::float_info<decltype(converted_value)>;
+    const auto f = basic_fp<typename info::carrier_uint>(converted_value);
+    // Compute exp, an approximate power of 10, such that
+    //   10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1).
+    // This is based on log10(value) == log2(value) / log2(10) and approximation
+    // of log2(value) by e + num_fraction_bits idea from double-conversion.
+    exp = static_cast<int>(
+        std::ceil((f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10));
+    dragon_flags = dragon::fixup;
+  } else if (!is_constant_evaluated() && precision < 0) {
+    // Use Dragonbox for the shortest format.
+    if (specs.binary32) {
+      auto dec = dragonbox::to_decimal(static_cast<float>(value));
+      write<char>(buffer_appender<char>(buf), dec.significand);
+      return dec.exponent;
+    }
+    auto dec = dragonbox::to_decimal(static_cast<double>(value));
+    write<char>(buffer_appender<char>(buf), dec.significand);
+    return dec.exponent;
+  } else {
+    // Use Grisu + Dragon4 for the given precision:
+    // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf.
+    const int min_exp = -60;  // alpha in Grisu.
+    int cached_exp10 = 0;     // K in Grisu.
+    fp normalized = normalize(fp(converted_value));
+    const auto cached_pow = get_cached_power(
+        min_exp - (normalized.e + fp::num_significand_bits), cached_exp10);
+    normalized = normalized * cached_pow;
+    gen_digits_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
+    if (grisu_gen_digits(normalized, 1, exp, handler) != digits::error &&
+        !is_constant_evaluated()) {
+      exp += handler.exp10;
+      buf.try_resize(to_unsigned(handler.size));
+      use_dragon = false;
+    } else {
+      exp += handler.size - cached_exp10 - 1;
+      precision = handler.precision;
+    }
+  }
+  if (use_dragon) {
+    auto f = basic_fp<uint128_t>();
+    bool is_predecessor_closer = specs.binary32
+                                     ? f.assign(static_cast<float>(value))
+                                     : f.assign(converted_value);
+    if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer;
+    if (fixed) dragon_flags |= dragon::fixed;
+    // Limit precision to the maximum possible number of significant digits in
+    // an IEEE754 double because we don't need to generate zeros.
+    const int max_double_digits = 767;
+    if (precision > max_double_digits) precision = max_double_digits;
+    format_dragon(f, dragon_flags, precision, buf, exp);
+  }
+  if (!fixed && !specs.showpoint) {
+    // Remove trailing zeros.
+    auto num_digits = buf.size();
+    while (num_digits > 0 && buf[num_digits - 1] == '0') {
+      --num_digits;
+      ++exp;
+    }
+    buf.try_resize(num_digits);
+  }
+  return exp;
 }
 
 template <typename Char, typename OutputIt, typename T,
-          FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+          FMT_ENABLE_IF(is_floating_point<T>::value)>
 FMT_CONSTEXPR20 auto write(OutputIt out, T value,
                            basic_format_specs<Char> specs, locale_ref loc = {})
     -> OutputIt {
@@ -1995,7 +3198,7 @@ FMT_CONSTEXPR20 auto write(OutputIt out, T value,
   }
 
   if (!detail::isfinite(value))
-    return write_nonfinite(out, detail::isinf(value), specs, fspecs);
+    return write_nonfinite(out, detail::isnan(value), specs, fspecs);
 
   if (specs.align == align::numeric && fspecs.sign) {
     auto it = reserve(out, 1);
@@ -2008,7 +3211,7 @@ FMT_CONSTEXPR20 auto write(OutputIt out, T value,
   memory_buffer buffer;
   if (fspecs.format == float_format::hex) {
     if (fspecs.sign) buffer.push_back(detail::sign<char>(fspecs.sign));
-    snprintf_float(promote_float(value), specs.precision, fspecs, buffer);
+    snprintf_float(convert_float(value), specs.precision, fspecs, buffer);
     return write_bytes<align::right>(out, {buffer.data(), buffer.size()},
                                      specs);
   }
@@ -2020,28 +3223,23 @@ FMT_CONSTEXPR20 auto write(OutputIt out, T value,
       throw_format_error("number is too big");
     else
       ++precision;
+  } else if (fspecs.format != float_format::fixed && precision == 0) {
+    precision = 1;
   }
   if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
-  if (!is_fast_float<T>()) fspecs.fallback = true;
-  int exp = format_float(promote_float(value), precision, fspecs, buffer);
+  int exp = format_float(convert_float(value), precision, fspecs, buffer);
   fspecs.precision = precision;
-  auto fp = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
-  return write_float(out, fp, specs, fspecs, loc);
+  auto f = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
+  return write_float(out, f, specs, fspecs, loc);
 }
 
 template <typename Char, typename OutputIt, typename T,
           FMT_ENABLE_IF(is_fast_float<T>::value)>
 FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
-  if (is_constant_evaluated()) {
+  if (is_constant_evaluated())
     return write(out, value, basic_format_specs<Char>());
-  }
-
   if (const_check(!is_supported_floating_point(value))) return out;
 
-  using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
-  using uint = typename dragonbox::float_info<floaty>::carrier_uint;
-  auto bits = bit_cast<uint>(value);
-
   auto fspecs = float_specs();
   if (detail::signbit(value)) {
     fspecs.sign = sign::minus;
@@ -2049,16 +3247,18 @@ FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
   }
 
   constexpr auto specs = basic_format_specs<Char>();
+  using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
+  using uint = typename dragonbox::float_info<floaty>::carrier_uint;
   uint mask = exponent_mask<floaty>();
-  if ((bits & mask) == mask)
-    return write_nonfinite(out, std::isinf(value), specs, fspecs);
+  if ((bit_cast<uint>(value) & mask) == mask)
+    return write_nonfinite(out, std::isnan(value), specs, fspecs);
 
   auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
   return write_float(out, dec, specs, fspecs, {});
 }
 
 template <typename Char, typename OutputIt, typename T,
-          FMT_ENABLE_IF(std::is_floating_point<T>::value &&
+          FMT_ENABLE_IF(is_floating_point<T>::value &&
                         !is_fast_float<T>::value)>
 inline auto write(OutputIt out, T value) -> OutputIt {
   return write(out, value, basic_format_specs<Char>());
@@ -2085,28 +3285,6 @@ constexpr auto write(OutputIt out, const T& value) -> OutputIt {
   return write<Char>(out, to_string_view(value));
 }
 
-template <typename Char, typename OutputIt, typename T,
-          FMT_ENABLE_IF(is_integral<T>::value &&
-                        !std::is_same<T, bool>::value &&
-                        !std::is_same<T, Char>::value)>
-FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
-  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
-  bool negative = is_negative(value);
-  // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
-  if (negative) abs_value = ~abs_value + 1;
-  int num_digits = count_digits(abs_value);
-  auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
-  auto it = reserve(out, size);
-  if (auto ptr = to_pointer<Char>(it, size)) {
-    if (negative) *ptr++ = static_cast<Char>('-');
-    format_decimal<Char>(ptr, abs_value, num_digits);
-    return out;
-  }
-  if (negative) *it++ = static_cast<Char>('-');
-  it = format_decimal<Char>(it, abs_value, num_digits).end;
-  return base_iterator(out, it);
-}
-
 // FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
 template <
     typename Char, typename OutputIt, typename T,
@@ -2116,8 +3294,7 @@ template <
             type::custom_type,
     FMT_ENABLE_IF(check)>
 FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
-  return write<Char>(
-      out, static_cast<typename std::underlying_type<T>::type>(value));
+  return write<Char>(out, static_cast<underlying_t<T>>(value));
 }
 
 template <typename Char, typename OutputIt, typename T,
@@ -2155,7 +3332,7 @@ auto write(OutputIt out, const T* value,
            const basic_format_specs<Char>& specs = {}, locale_ref = {})
     -> OutputIt {
   check_pointer_type_spec(specs.type, error_handler());
-  return write_ptr<Char>(out, to_uintptr(value), &specs);
+  return write_ptr<Char>(out, bit_cast<uintptr_t>(value), &specs);
 }
 
 // A write overload that handles implicit conversions.
@@ -2163,7 +3340,7 @@ template <typename Char, typename OutputIt, typename T,
           typename Context = basic_format_context<OutputIt, Char>>
 FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t<
     std::is_class<T>::value && !is_string<T>::value &&
-        !std::is_same<T, Char>::value &&
+        !is_floating_point<T>::value && !std::is_same<T, Char>::value &&
         !std::is_same<const T&,
                       decltype(arg_mapper<Context>().map(value))>::value,
     OutputIt> {
@@ -2356,43 +3533,17 @@ FMT_CONSTEXPR void handle_dynamic_spec(int& value,
   }
 }
 
-#define FMT_STRING_IMPL(s, base, explicit)                                 \
-  [] {                                                                     \
-    /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
-    /* Use a macro-like name to avoid shadowing warnings. */               \
-    struct FMT_GCC_VISIBILITY_HIDDEN FMT_COMPILE_STRING : base {           \
-      using char_type = fmt::remove_cvref_t<decltype(s[0])>;               \
-      FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit                              \
-      operator fmt::basic_string_view<char_type>() const {                 \
-        return fmt::detail_exported::compile_string_to_view<char_type>(s); \
-      }                                                                    \
-    };                                                                     \
-    return FMT_COMPILE_STRING();                                           \
-  }()
-
-/**
-  \rst
-  Constructs a compile-time format string from a string literal *s*.
-
-  **Example**::
-
-    // A compile-time error because 'd' is an invalid specifier for strings.
-    std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
-  \endrst
- */
-#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::compile_string, )
-
 #if FMT_USE_USER_DEFINED_LITERALS
 template <typename Char> struct udl_formatter {
   basic_string_view<Char> str;
 
   template <typename... T>
   auto operator()(T&&... args) const -> std::basic_string<Char> {
-    return vformat(str, fmt::make_args_checked<T...>(str, args...));
+    return vformat(str, fmt::make_format_args<buffer_context<Char>>(args...));
   }
 };
 
-#  if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#  if FMT_USE_NONTYPE_TEMPLATE_ARGS
 template <typename T, typename Char, size_t N,
           fmt::detail_exported::fixed_string<Char, N> Str>
 struct statically_named_arg : view {
@@ -2441,10 +3592,10 @@ auto vformat(const Locale& loc, basic_string_view<Char> format_str,
 using format_func = void (*)(detail::buffer<char>&, int, const char*);
 
 FMT_API void format_error_code(buffer<char>& out, int error_code,
-                               string_view message) FMT_NOEXCEPT;
+                               string_view message) noexcept;
 
 FMT_API void report_error(format_func func, int error_code,
-                          const char* message) FMT_NOEXCEPT;
+                          const char* message) noexcept;
 FMT_END_DETAIL_NAMESPACE
 
 FMT_API auto vsystem_error(int error_code, string_view format_str,
@@ -2490,12 +3641,11 @@ auto system_error(int error_code, format_string<T...> fmt, T&&... args)
   \endrst
  */
 FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
-                                 const char* message) FMT_NOEXCEPT;
+                                 const char* message) noexcept;
 
 // Reports a system error without throwing an exception.
 // Can be used to report errors from destructors.
-FMT_API void report_system_error(int error_code,
-                                 const char* message) FMT_NOEXCEPT;
+FMT_API void report_system_error(int error_code, const char* message) noexcept;
 
 /** Fast integer formatter. */
 class format_int {
@@ -2577,28 +3727,6 @@ formatter<T, Char,
   return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
 }
 
-#define FMT_FORMAT_AS(Type, Base)                                        \
-  template <typename Char>                                               \
-  struct formatter<Type, Char> : formatter<Base, Char> {                 \
-    template <typename FormatContext>                                    \
-    auto format(Type const& val, FormatContext& ctx) const               \
-        -> decltype(ctx.out()) {                                         \
-      return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
-    }                                                                    \
-  }
-
-FMT_FORMAT_AS(signed char, int);
-FMT_FORMAT_AS(unsigned char, unsigned);
-FMT_FORMAT_AS(short, int);
-FMT_FORMAT_AS(unsigned short, unsigned);
-FMT_FORMAT_AS(long, long long);
-FMT_FORMAT_AS(unsigned long, unsigned long long);
-FMT_FORMAT_AS(Char*, const Char*);
-FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
-FMT_FORMAT_AS(std::nullptr_t, const void*);
-FMT_FORMAT_AS(detail::byte, unsigned char);
-FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
-
 template <typename Char>
 struct formatter<void*, Char> : formatter<const void*, Char> {
   template <typename FormatContext>
@@ -2688,6 +3816,28 @@ template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
   return p.get();
 }
 
+/**
+  \rst
+  Converts ``e`` to the underlying type.
+
+  **Example**::
+
+    enum class color { red, green, blue };
+    auto s = fmt::format("{}", fmt::underlying(color::red));
+  \endrst
+ */
+template <typename Enum>
+constexpr auto underlying(Enum e) noexcept -> underlying_t<Enum> {
+  return static_cast<underlying_t<Enum>>(e);
+}
+
+namespace enums {
+template <typename Enum, FMT_ENABLE_IF(std::is_enum<Enum>::value)>
+constexpr auto format_as(Enum e) noexcept -> underlying_t<Enum> {
+  return static_cast<underlying_t<Enum>>(e);
+}
+}  // namespace enums
+
 class bytes {
  private:
   string_view data_;
@@ -2778,9 +3928,6 @@ struct join_view : detail::view {
       : begin(b), end(e), sep(s) {}
 };
 
-template <typename It, typename Sentinel, typename Char>
-using arg_join FMT_DEPRECATED_ALIAS = join_view<It, Sentinel, Char>;
-
 template <typename It, typename Sentinel, typename Char>
 struct formatter<join_view<It, Sentinel, Char>, Char> {
  private:
@@ -2818,8 +3965,8 @@ struct formatter<join_view<It, Sentinel, Char>, Char> {
   }
 
   template <typename FormatContext>
-  auto format(const join_view<It, Sentinel, Char>& value, FormatContext& ctx)
-      -> decltype(ctx.out()) {
+  auto format(const join_view<It, Sentinel, Char>& value,
+              FormatContext& ctx) const -> decltype(ctx.out()) {
     auto it = value.begin;
     auto out = ctx.out();
     if (it != value.end) {
@@ -2936,9 +4083,10 @@ void vformat_to(
     basic_format_parse_context<Char> parse_context;
     buffer_context<Char> context;
 
-    format_handler(buffer_appender<Char> out, basic_string_view<Char> str,
-                   basic_format_args<buffer_context<Char>> args, locale_ref loc)
-        : parse_context(str), context(out, args, loc) {}
+    format_handler(buffer_appender<Char> p_out, basic_string_view<Char> str,
+                   basic_format_args<buffer_context<Char>> p_args,
+                   locale_ref p_loc)
+        : parse_context(str), context(p_out, p_args, p_loc) {}
 
     void on_text(const Char* begin, const Char* end) {
       auto text = basic_string_view<Char>(begin, to_unsigned(end - begin));
@@ -2995,20 +4143,6 @@ extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
     -> thousands_sep_result<wchar_t>;
 extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
 extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
-extern template auto format_float<double>(double value, int precision,
-                                          float_specs specs, buffer<char>& buf)
-    -> int;
-extern template auto format_float<long double>(long double value, int precision,
-                                               float_specs specs,
-                                               buffer<char>& buf) -> int;
-void snprintf_float(float, int, float_specs, buffer<char>&) = delete;
-extern template auto snprintf_float<double>(double value, int precision,
-                                            float_specs specs,
-                                            buffer<char>& buf) -> int;
-extern template auto snprintf_float<long double>(long double value,
-                                                 int precision,
-                                                 float_specs specs,
-                                                 buffer<char>& buf) -> int;
 #endif  // FMT_HEADER_ONLY
 
 FMT_END_DETAIL_NAMESPACE
@@ -3025,25 +4159,16 @@ inline namespace literals {
     fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
   \endrst
  */
-#  if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
-template <detail_exported::fixed_string Str>
-constexpr auto operator""_a()
-    -> detail::udl_arg<remove_cvref_t<decltype(Str.data[0])>,
-                       sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str> {
-  return {};
+#  if FMT_USE_NONTYPE_TEMPLATE_ARGS
+template <detail_exported::fixed_string Str> constexpr auto operator""_a() {
+  using char_t = remove_cvref_t<decltype(Str.data[0])>;
+  return detail::udl_arg<char_t, sizeof(Str.data) / sizeof(char_t), Str>();
 }
 #  else
 constexpr auto operator"" _a(const char* s, size_t) -> detail::udl_arg<char> {
   return {s};
 }
 #  endif
-
-// DEPRECATED!
-// User-defined literal equivalent of fmt::format.
-FMT_DEPRECATED constexpr auto operator"" _format(const char* s, size_t n)
-    -> detail::udl_formatter<char> {
-  return {{s, n}};
-}
 }  // namespace literals
 #endif  // FMT_USE_USER_DEFINED_LITERALS
 
@@ -3060,14 +4185,6 @@ inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
   return vformat(loc, string_view(fmt), fmt::make_format_args(args...));
 }
 
-template <typename... T, size_t SIZE, typename Allocator>
-FMT_DEPRECATED auto format_to(basic_memory_buffer<char, SIZE, Allocator>& buf,
-                              format_string<T...> fmt, T&&... args)
-    -> appender {
-  detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...));
-  return appender(buf);
-}
-
 template <typename OutputIt, typename Locale,
           FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
                             detail::is_locale<Locale>::value)>
@@ -3090,10 +4207,6 @@ FMT_INLINE auto format_to(OutputIt out, const Locale& loc,
 FMT_MODULE_EXPORT_END
 FMT_END_NAMESPACE
 
-#ifdef FMT_DEPRECATED_INCLUDE_XCHAR
-#  include "xchar.h"
-#endif
-
 #ifdef FMT_HEADER_ONLY
 #  define FMT_FUNC inline
 #  include "format-inl.h"
diff --git a/src/vendor/fmt/locale.h b/src/vendor/fmt/locale.h
deleted file mode 100644 (file)
index 7571b52..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-#include "xchar.h"
-#warning fmt/locale.h is deprecated, include fmt/format.h or fmt/xchar.h instead
index b64f8bbfa57ac3fd97c849fd303a2f28d002e5e1..d82be1125a4bc64adbd32c8e4ba017f912d22013 100644 (file)
@@ -9,10 +9,8 @@
 #define FMT_OS_H_
 
 #include <cerrno>
-#include <clocale>  // locale_t
 #include <cstddef>
 #include <cstdio>
-#include <cstdlib>       // strtod_l
 #include <system_error>  // std::system_error
 
 #if defined __APPLE__ || defined(__FreeBSD__)
@@ -141,7 +139,7 @@ template <typename Char> struct formatter<std::error_code, Char> {
 };
 
 #ifdef _WIN32
-FMT_API const std::error_category& system_category() FMT_NOEXCEPT;
+FMT_API const std::error_category& system_category() noexcept;
 
 FMT_BEGIN_DETAIL_NAMESPACE
 // A converter from UTF-16 to UTF-8.
@@ -165,7 +163,7 @@ class utf16_to_utf8 {
 };
 
 FMT_API void format_windows_error(buffer<char>& out, int error_code,
-                                  const char* message) FMT_NOEXCEPT;
+                                  const char* message) noexcept;
 FMT_END_DETAIL_NAMESPACE
 
 FMT_API std::system_error vwindows_error(int error_code, string_view format_str,
@@ -207,10 +205,9 @@ std::system_error windows_error(int error_code, string_view message,
 
 // Reports a Windows error without throwing an exception.
 // Can be used to report errors from destructors.
-FMT_API void report_windows_error(int error_code,
-                                  const char* message) FMT_NOEXCEPT;
+FMT_API void report_windows_error(int error_code, const char* message) noexcept;
 #else
-inline const std::error_category& system_category() FMT_NOEXCEPT {
+inline const std::error_category& system_category() noexcept {
   return std::system_category();
 }
 #endif  // _WIN32
@@ -237,13 +234,13 @@ class buffered_file {
   void operator=(const buffered_file&) = delete;
 
   // Constructs a buffered_file object which doesn't represent any file.
-  buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
+  buffered_file() noexcept : file_(nullptr) {}
 
   // Destroys the object closing the file it represents if any.
-  FMT_API ~buffered_file() FMT_NOEXCEPT;
+  FMT_API ~buffered_file() noexcept;
 
  public:
-  buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
+  buffered_file(buffered_file&& other) noexcept : file_(other.file_) {
     other.file_ = nullptr;
   }
 
@@ -261,11 +258,9 @@ class buffered_file {
   FMT_API void close();
 
   // Returns the pointer to a FILE object representing this file.
-  FILE* get() const FMT_NOEXCEPT { return file_; }
+  FILE* get() const noexcept { return file_; }
 
-  // We place parentheses around fileno to workaround a bug in some versions
-  // of MinGW that define fileno as a macro.
-  FMT_API int(fileno)() const;
+  FMT_API int descriptor() const;
 
   void vprint(string_view format_str, format_args args) {
     fmt::vprint(file_, format_str, args);
@@ -279,12 +274,12 @@ class buffered_file {
 
 #if FMT_USE_FCNTL
 // A file. Closed file is represented by a file object with descriptor -1.
-// Methods that are not declared with FMT_NOEXCEPT may throw
+// Methods that are not declared with noexcept may throw
 // fmt::system_error in case of failure. Note that some errors such as
 // closing the file multiple times will cause a crash on Windows rather
 // than an exception. You can get standard behavior by overriding the
 // invalid parameter handler with _set_invalid_parameter_handler.
-class file {
+class FMT_API file {
  private:
   int fd_;  // File descriptor.
 
@@ -303,16 +298,16 @@ class file {
   };
 
   // Constructs a file object which doesn't represent any file.
-  file() FMT_NOEXCEPT : fd_(-1) {}
+  file() noexcept : fd_(-1) {}
 
   // Opens a file and constructs a file object representing this file.
-  FMT_API file(cstring_view path, int oflag);
+  file(cstring_view path, int oflag);
 
  public:
   file(const file&) = delete;
   void operator=(const file&) = delete;
 
-  file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
+  file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }
 
   // Move assignment is not noexcept because close may throw.
   file& operator=(file&& other) {
@@ -323,43 +318,43 @@ class file {
   }
 
   // Destroys the object closing the file it represents if any.
-  FMT_API ~file() FMT_NOEXCEPT;
+  ~file() noexcept;
 
   // Returns the file descriptor.
-  int descriptor() const FMT_NOEXCEPT { return fd_; }
+  int descriptor() const noexcept { return fd_; }
 
   // Closes the file.
-  FMT_API void close();
+  void close();
 
   // Returns the file size. The size has signed type for consistency with
   // stat::st_size.
-  FMT_API long long size() const;
+  long long size() const;
 
   // Attempts to read count bytes from the file into the specified buffer.
-  FMT_API size_t read(void* buffer, size_t count);
+  size_t read(void* buffer, size_t count);
 
   // Attempts to write count bytes from the specified buffer to the file.
-  FMT_API size_t write(const void* buffer, size_t count);
+  size_t write(const void* buffer, size_t count);
 
   // Duplicates a file descriptor with the dup function and returns
   // the duplicate as a file object.
-  FMT_API static file dup(int fd);
+  static file dup(int fd);
 
   // Makes fd be the copy of this file descriptor, closing fd first if
   // necessary.
-  FMT_API void dup2(int fd);
+  void dup2(int fd);
 
   // Makes fd be the copy of this file descriptor, closing fd first if
   // necessary.
-  FMT_API void dup2(int fd, std::error_code& ec) FMT_NOEXCEPT;
+  void dup2(int fd, std::error_code& ec) noexcept;
 
   // Creates a pipe setting up read_end and write_end file objects for reading
   // and writing respectively.
-  FMT_API static void pipe(file& read_end, file& write_end);
+  static void pipe(file& read_end, file& write_end);
 
   // Creates a buffered_file object associated with this file and detaches
   // this file object from the file.
-  FMT_API buffered_file fdopen(const char* mode);
+  buffered_file fdopen(const char* mode);
 };
 
 // Returns the memory page size.
@@ -462,7 +457,7 @@ class FMT_API ostream final : private detail::buffer<char> {
 
   * ``<integer>``: Flags passed to `open
     <https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
-    (``file::WRONLY | file::CREATE`` by default)
+    (``file::WRONLY | file::CREATE | file::TRUNC`` by default)
   * ``buffer_size=<integer>``: Output buffer size
 
   **Example**::
@@ -477,50 +472,6 @@ inline ostream output_file(cstring_view path, T... params) {
 }
 #endif  // FMT_USE_FCNTL
 
-#ifdef FMT_LOCALE
-// A "C" numeric locale.
-class locale {
- private:
-#  ifdef _WIN32
-  using locale_t = _locale_t;
-
-  static void freelocale(locale_t loc) { _free_locale(loc); }
-
-  static double strtod_l(const char* nptr, char** endptr, _locale_t loc) {
-    return _strtod_l(nptr, endptr, loc);
-  }
-#  endif
-
-  locale_t locale_;
-
- public:
-  using type = locale_t;
-  locale(const locale&) = delete;
-  void operator=(const locale&) = delete;
-
-  locale() {
-#  ifndef _WIN32
-    locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr));
-#  else
-    locale_ = _create_locale(LC_NUMERIC, "C");
-#  endif
-    if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
-  }
-  ~locale() { freelocale(locale_); }
-
-  type get() const { return locale_; }
-
-  // Converts string to floating-point number and advances str past the end
-  // of the parsed input.
-  FMT_DEPRECATED double strtod(const char*& str) const {
-    char* end = nullptr;
-    double result = strtod_l(str, &end, locale_);
-    str = end;
-    return result;
-  }
-};
-using Locale FMT_DEPRECATED_ALIAS = locale;
-#endif  // FMT_LOCALE
 FMT_MODULE_EXPORT_END
 FMT_END_NAMESPACE
 
index 3d716ece84d00c3ee05298c79b5504e72d433402..c3cdd4a61b2cdd25b9abdd171dfae04eabc90b03 100644 (file)
@@ -8,7 +8,14 @@
 #ifndef FMT_OSTREAM_H_
 #define FMT_OSTREAM_H_
 
+#include <fstream>
 #include <ostream>
+#if defined(_WIN32) && defined(__GLIBCXX__)
+#  include <ext/stdio_filebuf.h>
+#  include <ext/stdio_sync_filebuf.h>
+#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
+#  include <__std_stream>
+#endif
 
 #include "format.h"
 
@@ -45,11 +52,58 @@ struct is_streamable<
     enable_if_t<
         std::is_arithmetic<T>::value || std::is_array<T>::value ||
         std::is_pointer<T>::value || std::is_same<T, char8_type>::value ||
-        std::is_same<T, std::basic_string<Char>>::value ||
+        std::is_convertible<T, fmt::basic_string_view<Char>>::value ||
         std::is_same<T, std_string_view<Char>>::value ||
         (std::is_convertible<T, int>::value && !std::is_enum<T>::value)>>
     : std::false_type {};
 
+// Generate a unique explicit instantion in every translation unit using a tag
+// type in an anonymous namespace.
+namespace {
+struct file_access_tag {};
+}  // namespace
+template <class Tag, class BufType, FILE* BufType::*FileMemberPtr>
+class file_access {
+  friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; }
+};
+
+#if FMT_MSC_VERSION
+template class file_access<file_access_tag, std::filebuf,
+                           &std::filebuf::_Myfile>;
+auto get_file(std::filebuf&) -> FILE*;
+#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
+template class file_access<file_access_tag, std::__stdoutbuf<char>,
+                           &std::__stdoutbuf<char>::__file_>;
+auto get_file(std::__stdoutbuf<char>&) -> FILE*;
+#endif
+
+inline bool write_ostream_unicode(std::ostream& os, fmt::string_view data) {
+#if FMT_MSC_VERSION
+  if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf()))
+    if (FILE* f = get_file(*buf)) return write_console(f, data);
+#elif defined(_WIN32) && defined(__GLIBCXX__)
+  auto* rdbuf = os.rdbuf();
+  FILE* c_file;
+  if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf))
+    c_file = fbuf->file();
+  else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf))
+    c_file = fbuf->file();
+  else
+    return false;
+  if (c_file) return write_console(c_file, data);
+#elif defined(_WIN32) && defined(_LIBCPP_VERSION)
+  if (auto* buf = dynamic_cast<std::__stdoutbuf<char>*>(os.rdbuf()))
+    if (FILE* f = get_file(*buf)) return write_console(f, data);
+#else
+  ignore_unused(os, data);
+#endif
+  return false;
+}
+inline bool write_ostream_unicode(std::wostream&,
+                                  fmt::basic_string_view<wchar_t>) {
+  return false;
+}
+
 // Write the content of buf to os.
 // It is a separate function rather than a part of vprint to simplify testing.
 template <typename Char>
@@ -76,41 +130,79 @@ void format_value(buffer<Char>& buf, const T& value,
 #endif
   output << value;
   output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
-  buf.try_resize(buf.size());
 }
 
+template <typename T> struct streamed_view { const T& value; };
+
+}  // namespace detail
+
 // Formats an object of type T that has an overloaded ostream operator<<.
-template <typename T, typename Char>
-struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
-    : private formatter<basic_string_view<Char>, Char> {
-  using formatter<basic_string_view<Char>, Char>::parse;
+template <typename Char>
+struct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> {
+  void set_debug_format() = delete;
 
-  template <typename OutputIt>
-  auto format(const T& value, basic_format_context<OutputIt, Char>& ctx)
+  template <typename T, typename OutputIt>
+  auto format(const T& value, basic_format_context<OutputIt, Char>& ctx) const
       -> OutputIt {
     auto buffer = basic_memory_buffer<Char>();
     format_value(buffer, value, ctx.locale());
     return formatter<basic_string_view<Char>, Char>::format(
         {buffer.data(), buffer.size()}, ctx);
   }
+};
+
+using ostream_formatter = basic_ostream_formatter<char>;
 
-  // DEPRECATED!
+template <typename T, typename Char>
+struct formatter<detail::streamed_view<T>, Char>
+    : basic_ostream_formatter<Char> {
   template <typename OutputIt>
-  auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx)
-      -> OutputIt {
-    auto buffer = basic_memory_buffer<Char>();
-    format_value(buffer, value, ctx.locale());
-    return std::copy(buffer.begin(), buffer.end(), ctx.out());
+  auto format(detail::streamed_view<T> view,
+              basic_format_context<OutputIt, Char>& ctx) const -> OutputIt {
+    return basic_ostream_formatter<Char>::format(view.value, ctx);
   }
 };
+
+/**
+  \rst
+  Returns a view that formats `value` via an ostream ``operator<<``.
+
+  **Example**::
+
+    fmt::print("Current thread id: {}\n",
+               fmt::streamed(std::this_thread::get_id()));
+  \endrst
+ */
+template <typename T>
+auto streamed(const T& value) -> detail::streamed_view<T> {
+  return {value};
+}
+
+namespace detail {
+
+// Formats an object of type T that has an overloaded ostream operator<<.
+template <typename T, typename Char>
+struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
+    : basic_ostream_formatter<Char> {
+  using basic_ostream_formatter<Char>::format;
+};
+
+inline void vprint_directly(std::ostream& os, string_view format_str,
+                            format_args args) {
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, format_str, args);
+  detail::write_buffer(os, buffer);
+}
+
 }  // namespace detail
 
-FMT_MODULE_EXPORT
-template <typename Char>
-void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
+FMT_MODULE_EXPORT template <typename Char>
+void vprint(std::basic_ostream<Char>& os,
+            basic_string_view<type_identity_t<Char>> format_str,
             basic_format_args<buffer_context<type_identity_t<Char>>> args) {
   auto buffer = basic_memory_buffer<Char>();
   detail::vformat_to(buffer, format_str, args);
+  if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return;
   detail::write_buffer(os, buffer);
 }
 
@@ -123,13 +215,23 @@ void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
     fmt::print(cerr, "Don't {}!", "panic");
   \endrst
  */
+FMT_MODULE_EXPORT template <typename... T>
+void print(std::ostream& os, format_string<T...> fmt, T&&... args) {
+  const auto& vargs = fmt::make_format_args(args...);
+  if (detail::is_utf8())
+    vprint(os, fmt, vargs);
+  else
+    detail::vprint_directly(os, fmt, vargs);
+}
+
 FMT_MODULE_EXPORT
-template <typename S, typename... Args,
-          typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
-void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
-  vprint(os, to_string_view(format_str),
-         fmt::make_args_checked<Args...>(format_str, args...));
+template <typename... Args>
+void print(std::wostream& os,
+           basic_format_string<wchar_t, type_identity_t<Args>...> fmt,
+           Args&&... args) {
+  vprint(os, fmt, fmt::make_format_args<buffer_context<wchar_t>>(args...));
 }
+
 FMT_END_NAMESPACE
 
 #endif  // FMT_OSTREAM_H_
index 19d550f6cf5393a3fb9cc8a92369f2908ab48a89..70a592dc26dd9c38f61aeeaaa63656694aa7e505 100644 (file)
@@ -10,7 +10,6 @@
 
 #include <algorithm>  // std::max
 #include <limits>     // std::numeric_limits
-#include <ostream>
 
 #include "format.h"
 
@@ -561,7 +560,7 @@ inline auto vsprintf(
     basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
     -> std::basic_string<Char> {
   basic_memory_buffer<Char> buffer;
-  vprintf(buffer, to_string_view(fmt), args);
+  vprintf(buffer, detail::to_string_view(fmt), args);
   return to_string(buffer);
 }
 
@@ -578,7 +577,8 @@ template <typename S, typename... T,
           typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
 inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string<Char> {
   using context = basic_printf_context_t<Char>;
-  return vsprintf(to_string_view(fmt), fmt::make_format_args<context>(args...));
+  return vsprintf(detail::to_string_view(fmt),
+                  fmt::make_format_args<context>(args...));
 }
 
 template <typename S, typename Char = char_t<S>>
@@ -587,7 +587,7 @@ inline auto vfprintf(
     basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
     -> int {
   basic_memory_buffer<Char> buffer;
-  vprintf(buffer, to_string_view(fmt), args);
+  vprintf(buffer, detail::to_string_view(fmt), args);
   size_t size = buffer.size();
   return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
              ? -1
@@ -606,7 +606,7 @@ inline auto vfprintf(
 template <typename S, typename... T, typename Char = char_t<S>>
 inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int {
   using context = basic_printf_context_t<Char>;
-  return vfprintf(f, to_string_view(fmt),
+  return vfprintf(f, detail::to_string_view(fmt),
                   fmt::make_format_args<context>(args...));
 }
 
@@ -615,7 +615,7 @@ inline auto vprintf(
     const S& fmt,
     basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
     -> int {
-  return vfprintf(stdout, to_string_view(fmt), args);
+  return vfprintf(stdout, detail::to_string_view(fmt), args);
 }
 
 /**
@@ -630,27 +630,10 @@ inline auto vprintf(
 template <typename S, typename... T, FMT_ENABLE_IF(detail::is_string<S>::value)>
 inline auto printf(const S& fmt, const T&... args) -> int {
   return vprintf(
-      to_string_view(fmt),
+      detail::to_string_view(fmt),
       fmt::make_format_args<basic_printf_context_t<char_t<S>>>(args...));
 }
 
-template <typename S, typename Char = char_t<S>>
-FMT_DEPRECATED auto vfprintf(
-    std::basic_ostream<Char>& os, const S& fmt,
-    basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args)
-    -> int {
-  basic_memory_buffer<Char> buffer;
-  vprintf(buffer, to_string_view(fmt), args);
-  os.write(buffer.data(), static_cast<std::streamsize>(buffer.size()));
-  return static_cast<int>(buffer.size());
-}
-template <typename S, typename... T, typename Char = char_t<S>>
-FMT_DEPRECATED auto fprintf(std::basic_ostream<Char>& os, const S& fmt,
-                            const T&... args) -> int {
-  return vfprintf(os, to_string_view(fmt),
-                  fmt::make_format_args<basic_printf_context_t<Char>>(args...));
-}
-
 FMT_MODULE_EXPORT_END
 FMT_END_NAMESPACE
 
index eb9fb8a92d6a0f8f0bcda12301349ac5c74b8cc2..dea7d60dd6bb01daff808f48ed86c06cc2a3cacc 100644 (file)
@@ -55,7 +55,7 @@ template <typename T> class is_std_string_like {
   template <typename> static void check(...);
 
  public:
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       is_string<T>::value ||
       std::is_convertible<T, std_string_view<char>>::value ||
       !std::is_void<decltype(check<T>(nullptr))>::value;
@@ -70,9 +70,9 @@ template <typename T> class is_map {
 
  public:
 #ifdef FMT_FORMAT_MAP_AS_LIST
-  static FMT_CONSTEXPR_DECL const bool value = false;
+  static constexpr const bool value = false;
 #else
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       !std::is_void<decltype(check<T>(nullptr))>::value;
 #endif
 };
@@ -83,9 +83,9 @@ template <typename T> class is_set {
 
  public:
 #ifdef FMT_FORMAT_SET_AS_LIST
-  static FMT_CONSTEXPR_DECL const bool value = false;
+  static constexpr const bool value = false;
 #else
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       !std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;
 #endif
 };
@@ -94,7 +94,7 @@ template <typename... Ts> struct conditional_helper {};
 
 template <typename T, typename _ = void> struct is_range_ : std::false_type {};
 
-#if !FMT_MSC_VER || FMT_MSC_VER > 1800
+#if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1800
 
 #  define FMT_DECLTYPE_RETURN(val)  \
     ->decltype(val) { return val; } \
@@ -174,12 +174,12 @@ template <typename T> class is_tuple_like_ {
   template <typename> static void check(...);
 
  public:
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       !std::is_void<decltype(check<T>(nullptr))>::value;
 };
 
 // Check for integer_sequence
-#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
+#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900
 template <typename T, T... N>
 using integer_sequence = std::integer_sequence<T, N...>;
 template <size_t... N> using index_sequence = std::index_sequence<N...>;
@@ -202,8 +202,33 @@ template <size_t N>
 using make_index_sequence = make_integer_sequence<size_t, N>;
 #endif
 
+template <typename T>
+using tuple_index_sequence = make_index_sequence<std::tuple_size<T>::value>;
+
+template <typename T, typename C, bool = is_tuple_like_<T>::value>
+class is_tuple_formattable_ {
+ public:
+  static constexpr const bool value = false;
+};
+template <typename T, typename C> class is_tuple_formattable_<T, C, true> {
+  template <std::size_t... I>
+  static std::true_type check2(index_sequence<I...>,
+                               integer_sequence<bool, (I == I)...>);
+  static std::false_type check2(...);
+  template <std::size_t... I>
+  static decltype(check2(
+      index_sequence<I...>{},
+      integer_sequence<
+          bool, (is_formattable<typename std::tuple_element<I, T>::type,
+                                C>::value)...>{})) check(index_sequence<I...>);
+
+ public:
+  static constexpr const bool value =
+      decltype(check(tuple_index_sequence<T>{}))::value;
+};
+
 template <class Tuple, class F, size_t... Is>
-void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
+void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) noexcept {
   using std::get;
   // using free function get<I>(T) now.
   const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
@@ -221,296 +246,46 @@ template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
   for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
 }
 
-template <typename Range>
-using value_type =
-    remove_cvref_t<decltype(*detail::range_begin(std::declval<Range>()))>;
-
-template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
-  *out++ = ',';
-  *out++ = ' ';
-  return out;
-}
-
-struct singleton {
-  unsigned char upper;
-  unsigned char lower_count;
+#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920
+// Older MSVC doesn't get the reference type correctly for arrays.
+template <typename R> struct range_reference_type_impl {
+  using type = decltype(*detail::range_begin(std::declval<R&>()));
 };
 
-inline auto is_printable(uint16_t x, const singleton* singletons,
-                         size_t singletons_size,
-                         const unsigned char* singleton_lowers,
-                         const unsigned char* normal, size_t normal_size)
-    -> bool {
-  auto upper = x >> 8;
-  auto lower_start = 0;
-  for (size_t i = 0; i < singletons_size; ++i) {
-    auto s = singletons[i];
-    auto lower_end = lower_start + s.lower_count;
-    if (upper < s.upper) break;
-    if (upper == s.upper) {
-      for (auto j = lower_start; j < lower_end; ++j) {
-        if (singleton_lowers[j] == (x & 0xff)) return false;
-      }
-    }
-    lower_start = lower_end;
-  }
-
-  auto xsigned = static_cast<int>(x);
-  auto current = true;
-  for (size_t i = 0; i < normal_size; ++i) {
-    auto v = static_cast<int>(normal[i]);
-    auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v;
-    xsigned -= len;
-    if (xsigned < 0) break;
-    current = !current;
-  }
-  return current;
-}
+template <typename T, std::size_t N> struct range_reference_type_impl<T[N]> {
+  using type = T&;
+};
 
-// Returns true iff the code point cp is printable.
-// This code is generated by support/printable.py.
-inline auto is_printable(uint32_t cp) -> bool {
-  static constexpr singleton singletons0[] = {
-      {0x00, 1},  {0x03, 5},  {0x05, 6},  {0x06, 3},  {0x07, 6},  {0x08, 8},
-      {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13},
-      {0x0f, 4},  {0x10, 3},  {0x12, 18}, {0x13, 9},  {0x16, 1},  {0x17, 5},
-      {0x18, 2},  {0x19, 3},  {0x1a, 7},  {0x1c, 2},  {0x1d, 1},  {0x1f, 22},
-      {0x20, 3},  {0x2b, 3},  {0x2c, 2},  {0x2d, 11}, {0x2e, 1},  {0x30, 3},
-      {0x31, 2},  {0x32, 1},  {0xa7, 2},  {0xa9, 2},  {0xaa, 4},  {0xab, 8},
-      {0xfa, 2},  {0xfb, 5},  {0xfd, 4},  {0xfe, 3},  {0xff, 9},
-  };
-  static constexpr unsigned char singletons0_lower[] = {
-      0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90,
-      0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f,
-      0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1,
-      0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04,
-      0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d,
-      0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf,
-      0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
-      0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d,
-      0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d,
-      0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d,
-      0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5,
-      0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7,
-      0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49,
-      0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7,
-      0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7,
-      0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e,
-      0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16,
-      0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e,
-      0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f,
-      0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf,
-      0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0,
-      0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27,
-      0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91,
-      0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7,
-      0xfe, 0xff,
-  };
-  static constexpr singleton singletons1[] = {
-      {0x00, 6},  {0x01, 1}, {0x03, 1},  {0x04, 2}, {0x08, 8},  {0x09, 2},
-      {0x0a, 5},  {0x0b, 2}, {0x0e, 4},  {0x10, 1}, {0x11, 2},  {0x12, 5},
-      {0x13, 17}, {0x14, 1}, {0x15, 2},  {0x17, 2}, {0x19, 13}, {0x1c, 5},
-      {0x1d, 8},  {0x24, 1}, {0x6a, 3},  {0x6b, 2}, {0xbc, 2},  {0xd1, 2},
-      {0xd4, 12}, {0xd5, 9}, {0xd6, 2},  {0xd7, 2}, {0xda, 1},  {0xe0, 5},
-      {0xe1, 2},  {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2},  {0xf9, 2},
-      {0xfa, 2},  {0xfb, 1},
-  };
-  static constexpr unsigned char singletons1_lower[] = {
-      0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07,
-      0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36,
-      0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87,
-      0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
-      0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b,
-      0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9,
-      0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66,
-      0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27,
-      0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc,
-      0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7,
-      0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6,
-      0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c,
-      0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66,
-      0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0,
-      0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93,
-  };
-  static constexpr unsigned char normal0[] = {
-      0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04,
-      0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0,
-      0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01,
-      0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03,
-      0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03,
-      0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a,
-      0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15,
-      0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f,
-      0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80,
-      0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07,
-      0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06,
-      0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04,
-      0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac,
-      0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c,
-      0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11,
-      0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c,
-      0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b,
-      0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6,
-      0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03,
-      0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80,
-      0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06,
-      0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c,
-      0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17,
-      0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80,
-      0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80,
-      0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d,
-  };
-  static constexpr unsigned char normal1[] = {
-      0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f,
-      0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e,
-      0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04,
-      0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09,
-      0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16,
-      0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f,
-      0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36,
-      0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33,
-      0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08,
-      0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e,
-      0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41,
-      0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03,
-      0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22,
-      0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04,
-      0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45,
-      0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03,
-      0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81,
-      0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75,
-      0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1,
-      0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a,
-      0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11,
-      0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09,
-      0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89,
-      0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6,
-      0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09,
-      0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50,
-      0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05,
-      0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83,
-      0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05,
-      0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80,
-      0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80,
-      0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07,
-      0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e,
-      0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07,
-      0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06,
-  };
-  auto lower = static_cast<uint16_t>(cp);
-  if (cp < 0x10000) {
-    return is_printable(lower, singletons0,
-                        sizeof(singletons0) / sizeof(*singletons0),
-                        singletons0_lower, normal0, sizeof(normal0));
-  }
-  if (cp < 0x20000) {
-    return is_printable(lower, singletons1,
-                        sizeof(singletons1) / sizeof(*singletons1),
-                        singletons1_lower, normal1, sizeof(normal1));
-  }
-  if (0x2a6de <= cp && cp < 0x2a700) return false;
-  if (0x2b735 <= cp && cp < 0x2b740) return false;
-  if (0x2b81e <= cp && cp < 0x2b820) return false;
-  if (0x2cea2 <= cp && cp < 0x2ceb0) return false;
-  if (0x2ebe1 <= cp && cp < 0x2f800) return false;
-  if (0x2fa1e <= cp && cp < 0x30000) return false;
-  if (0x3134b <= cp && cp < 0xe0100) return false;
-  if (0xe01f0 <= cp && cp < 0x110000) return false;
-  return cp < 0x110000;
-}
+template <typename T>
+using range_reference_type = typename range_reference_type_impl<T>::type;
+#else
+template <typename Range>
+using range_reference_type =
+    decltype(*detail::range_begin(std::declval<Range&>()));
+#endif
 
-inline auto needs_escape(uint32_t cp) -> bool {
-  return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' ||
-         !is_printable(cp);
-}
+// We don't use the Range's value_type for anything, but we do need the Range's
+// reference type, with cv-ref stripped.
+template <typename Range>
+using uncvref_type = remove_cvref_t<range_reference_type<Range>>;
 
-template <typename Char> struct find_escape_result {
-  const Char* begin;
-  const Char* end;
-  uint32_t cp;
-};
+template <typename Range>
+using uncvref_first_type =
+    remove_cvref_t<decltype(std::declval<range_reference_type<Range>>().first)>;
 
-template <typename Char>
-auto find_escape(const Char* begin, const Char* end)
-    -> find_escape_result<Char> {
-  for (; begin != end; ++begin) {
-    auto cp = static_cast<typename std::make_unsigned<Char>::type>(*begin);
-    if (sizeof(Char) == 1 && cp >= 0x80) continue;
-    if (needs_escape(cp)) return {begin, begin + 1, cp};
-  }
-  return {begin, nullptr, 0};
-}
+template <typename Range>
+using uncvref_second_type = remove_cvref_t<
+    decltype(std::declval<range_reference_type<Range>>().second)>;
 
-inline auto find_escape(const char* begin, const char* end)
-    -> find_escape_result<char> {
-  if (!is_utf8()) return find_escape<char>(begin, end);
-  auto result = find_escape_result<char>{end, nullptr, 0};
-  for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
-                     [&](uint32_t cp, string_view sv) {
-                       if (needs_escape(cp)) {
-                         result = {sv.begin(), sv.end(), cp};
-                         return false;
-                       }
-                       return true;
-                     });
-  return result;
+template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
+  *out++ = ',';
+  *out++ = ' ';
+  return out;
 }
 
 template <typename Char, typename OutputIt>
 auto write_range_entry(OutputIt out, basic_string_view<Char> str) -> OutputIt {
-  *out++ = '"';
-  auto begin = str.begin(), end = str.end();
-  do {
-    auto escape = find_escape(begin, end);
-    out = copy_str<Char>(begin, escape.begin, out);
-    begin = escape.end;
-    if (!begin) break;
-    auto c = static_cast<Char>(escape.cp);
-    switch (escape.cp) {
-    case '\n':
-      *out++ = '\\';
-      c = 'n';
-      break;
-    case '\r':
-      *out++ = '\\';
-      c = 'r';
-      break;
-    case '\t':
-      *out++ = '\\';
-      c = 't';
-      break;
-    case '"':
-      FMT_FALLTHROUGH;
-    case '\\':
-      *out++ = '\\';
-      break;
-    default:
-      if (is_utf8()) {
-        if (escape.cp < 0x100) {
-          out = format_to(out, "\\x{:02x}", escape.cp);
-          continue;
-        }
-        if (escape.cp < 0x10000) {
-          out = format_to(out, "\\u{:04x}", escape.cp);
-          continue;
-        }
-        if (escape.cp < 0x110000) {
-          out = format_to(out, "\\U{:08x}", escape.cp);
-          continue;
-        }
-      }
-      for (Char escape_char : basic_string_view<Char>(
-               escape.begin, to_unsigned(escape.end - escape.begin))) {
-        out = format_to(
-            out, "\\x{:02x}",
-            static_cast<typename std::make_unsigned<Char>::type>(escape_char));
-      }
-      continue;
-    }
-    *out++ = c;
-  } while (begin != end);
-  *out++ = '"';
-  return out;
+  return write_escaped_string(out, str);
 }
 
 template <typename Char, typename OutputIt, typename T,
@@ -523,10 +298,7 @@ inline auto write_range_entry(OutputIt out, const T& str) -> OutputIt {
 template <typename Char, typename OutputIt, typename Arg,
           FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
 OutputIt write_range_entry(OutputIt out, const Arg v) {
-  *out++ = '\'';
-  *out++ = v;
-  *out++ = '\'';
-  return out;
+  return write_escaped_char(out, v);
 }
 
 template <
@@ -540,129 +312,286 @@ OutputIt write_range_entry(OutputIt out, const Arg& v) {
 }  // namespace detail
 
 template <typename T> struct is_tuple_like {
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
 };
 
+template <typename T, typename C> struct is_tuple_formattable {
+  static constexpr const bool value =
+      detail::is_tuple_formattable_<T, C>::value;
+};
+
 template <typename TupleT, typename Char>
-struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
+struct formatter<TupleT, Char,
+                 enable_if_t<fmt::is_tuple_like<TupleT>::value &&
+                             fmt::is_tuple_formattable<TupleT, Char>::value>> {
  private:
+  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
+  basic_string_view<Char> opening_bracket_ =
+      detail::string_literal<Char, '('>{};
+  basic_string_view<Char> closing_bracket_ =
+      detail::string_literal<Char, ')'>{};
+
   // C++11 generic lambda for format().
   template <typename FormatContext> struct format_each {
     template <typename T> void operator()(const T& v) {
-      if (i > 0) out = detail::write_delimiter(out);
+      if (i > 0) out = detail::copy_str<Char>(separator, out);
       out = detail::write_range_entry<Char>(out, v);
       ++i;
     }
     int i;
     typename FormatContext::iterator& out;
+    basic_string_view<Char> separator;
   };
 
  public:
+  FMT_CONSTEXPR formatter() {}
+
+  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
+    separator_ = sep;
+  }
+
+  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
+                                  basic_string_view<Char> close) {
+    opening_bracket_ = open;
+    closing_bracket_ = close;
+  }
+
   template <typename ParseContext>
   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
     return ctx.begin();
   }
 
   template <typename FormatContext = format_context>
-  auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
+  auto format(const TupleT& values, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
     auto out = ctx.out();
-    *out++ = '(';
-    detail::for_each(values, format_each<FormatContext>{0, out});
-    *out++ = ')';
+    out = detail::copy_str<Char>(opening_bracket_, out);
+    detail::for_each(values, format_each<FormatContext>{0, out, separator_});
+    out = detail::copy_str<Char>(closing_bracket_, out);
     return out;
   }
 };
 
 template <typename T, typename Char> struct is_range {
-  static FMT_CONSTEXPR_DECL const bool value =
+  static constexpr const bool value =
       detail::is_range_<T>::value && !detail::is_std_string_like<T>::value &&
-      !detail::is_map<T>::value &&
       !std::is_convertible<T, std::basic_string<Char>>::value &&
-      !std::is_constructible<detail::std_string_view<Char>, T>::value;
+      !std::is_convertible<T, detail::std_string_view<Char>>::value;
+};
+
+namespace detail {
+template <typename Context> struct range_mapper {
+  using mapper = arg_mapper<Context>;
+
+  template <typename T,
+            FMT_ENABLE_IF(has_formatter<remove_cvref_t<T>, Context>::value)>
+  static auto map(T&& value) -> T&& {
+    return static_cast<T&&>(value);
+  }
+  template <typename T,
+            FMT_ENABLE_IF(!has_formatter<remove_cvref_t<T>, Context>::value)>
+  static auto map(T&& value)
+      -> decltype(mapper().map(static_cast<T&&>(value))) {
+    return mapper().map(static_cast<T&&>(value));
+  }
 };
 
+template <typename Char, typename Element>
+using range_formatter_type = conditional_t<
+    is_formattable<Element, Char>::value,
+    formatter<remove_cvref_t<decltype(range_mapper<buffer_context<Char>>{}.map(
+                  std::declval<Element>()))>,
+              Char>,
+    fallback_formatter<Element, Char>>;
+
+template <typename R>
+using maybe_const_range =
+    conditional_t<has_const_begin_end<R>::value, const R, R>;
+
+// Workaround a bug in MSVC 2015 and earlier.
+#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910
+template <typename R, typename Char>
+struct is_formattable_delayed
+    : disjunction<
+          is_formattable<uncvref_type<maybe_const_range<R>>, Char>,
+          has_fallback_formatter<uncvref_type<maybe_const_range<R>>, Char>> {};
+#endif
+
+}  // namespace detail
+
+template <typename T, typename Char, typename Enable = void>
+struct range_formatter;
+
 template <typename T, typename Char>
-struct formatter<
+struct range_formatter<
     T, Char,
-    enable_if_t<
-        fmt::is_range<T, Char>::value
-// Workaround a bug in MSVC 2019 and earlier.
-#if !FMT_MSC_VER
-        && (is_formattable<detail::value_type<T>, Char>::value ||
-            detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
-#endif
-        >> {
+    enable_if_t<conjunction<
+        std::is_same<T, remove_cvref_t<T>>,
+        disjunction<is_formattable<T, Char>,
+                    detail::has_fallback_formatter<T, Char>>>::value>> {
+ private:
+  detail::range_formatter_type<Char, T> underlying_;
+  bool custom_specs_ = false;
+  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
+  basic_string_view<Char> opening_bracket_ =
+      detail::string_literal<Char, '['>{};
+  basic_string_view<Char> closing_bracket_ =
+      detail::string_literal<Char, ']'>{};
+
+  template <class U>
+  FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, int)
+      -> decltype(u.set_debug_format()) {
+    u.set_debug_format();
+  }
+
+  template <class U>
+  FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}
+
+  FMT_CONSTEXPR void maybe_set_debug_format() {
+    maybe_set_debug_format(underlying_, 0);
+  }
+
+ public:
+  FMT_CONSTEXPR range_formatter() {}
+
+  FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type<Char, T>& {
+    return underlying_;
+  }
+
+  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
+    separator_ = sep;
+  }
+
+  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
+                                  basic_string_view<Char> close) {
+    opening_bracket_ = open;
+    closing_bracket_ = close;
+  }
+
   template <typename ParseContext>
   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
-    return ctx.begin();
+    auto it = ctx.begin();
+    auto end = ctx.end();
+    if (it == end || *it == '}') {
+      maybe_set_debug_format();
+      return it;
+    }
+
+    if (*it == 'n') {
+      set_brackets({}, {});
+      ++it;
+    }
+
+    if (*it == '}') {
+      maybe_set_debug_format();
+      return it;
+    }
+
+    if (*it != ':')
+      FMT_THROW(format_error("no other top-level range formatters supported"));
+
+    custom_specs_ = true;
+    ++it;
+    ctx.advance_to(it);
+    return underlying_.parse(ctx);
   }
 
-  template <
-      typename FormatContext, typename U,
-      FMT_ENABLE_IF(
-          std::is_same<U, conditional_t<detail::has_const_begin_end<T>::value,
-                                        const T, T>>::value)>
-  auto format(U& range, FormatContext& ctx) -> decltype(ctx.out()) {
-#ifdef FMT_DEPRECATED_BRACED_RANGES
-    Char prefix = '{';
-    Char postfix = '}';
-#else
-    Char prefix = detail::is_set<T>::value ? '{' : '[';
-    Char postfix = detail::is_set<T>::value ? '}' : ']';
-#endif
+  template <typename R, class FormatContext>
+  auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) {
+    detail::range_mapper<buffer_context<Char>> mapper;
     auto out = ctx.out();
-    *out++ = prefix;
+    out = detail::copy_str<Char>(opening_bracket_, out);
     int i = 0;
-    auto it = std::begin(range);
-    auto end = std::end(range);
+    auto it = detail::range_begin(range);
+    auto end = detail::range_end(range);
     for (; it != end; ++it) {
-      if (i > 0) out = detail::write_delimiter(out);
-      out = detail::write_range_entry<Char>(out, *it);
+      if (i > 0) out = detail::copy_str<Char>(separator_, out);
+      ;
+      ctx.advance_to(out);
+      out = underlying_.format(mapper.map(*it), ctx);
       ++i;
     }
-    *out++ = postfix;
+    out = detail::copy_str<Char>(closing_bracket_, out);
     return out;
   }
 };
 
-template <typename T, typename Char>
-struct formatter<
-    T, Char,
-    enable_if_t<
-        detail::is_map<T>::value
-// Workaround a bug in MSVC 2019 and earlier.
-#if !FMT_MSC_VER
-        && (is_formattable<detail::value_type<T>, Char>::value ||
-            detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
-#endif
-        >> {
+enum class range_format { disabled, map, set, sequence, string, debug_string };
+
+namespace detail {
+template <typename T> struct range_format_kind_ {
+  static constexpr auto value = std::is_same<range_reference_type<T>, T>::value
+                                    ? range_format::disabled
+                                : is_map<T>::value ? range_format::map
+                                : is_set<T>::value ? range_format::set
+                                                   : range_format::sequence;
+};
+
+template <range_format K, typename R, typename Char, typename Enable = void>
+struct range_default_formatter;
+
+template <range_format K>
+using range_format_constant = std::integral_constant<range_format, K>;
+
+template <range_format K, typename R, typename Char>
+struct range_default_formatter<
+    K, R, Char,
+    enable_if_t<(K == range_format::sequence || K == range_format::map ||
+                 K == range_format::set)>> {
+  using range_type = detail::maybe_const_range<R>;
+  range_formatter<detail::uncvref_type<range_type>, Char> underlying_;
+
+  FMT_CONSTEXPR range_default_formatter() { init(range_format_constant<K>()); }
+
+  FMT_CONSTEXPR void init(range_format_constant<range_format::set>) {
+    underlying_.set_brackets(detail::string_literal<Char, '{'>{},
+                             detail::string_literal<Char, '}'>{});
+  }
+
+  FMT_CONSTEXPR void init(range_format_constant<range_format::map>) {
+    underlying_.set_brackets(detail::string_literal<Char, '{'>{},
+                             detail::string_literal<Char, '}'>{});
+    underlying_.underlying().set_brackets({}, {});
+    underlying_.underlying().set_separator(
+        detail::string_literal<Char, ':', ' '>{});
+  }
+
+  FMT_CONSTEXPR void init(range_format_constant<range_format::sequence>) {}
+
   template <typename ParseContext>
   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
-    return ctx.begin();
+    return underlying_.parse(ctx);
   }
 
-  template <
-      typename FormatContext, typename U,
-      FMT_ENABLE_IF(
-          std::is_same<U, conditional_t<detail::has_const_begin_end<T>::value,
-                                        const T, T>>::value)>
-  auto format(U& map, FormatContext& ctx) -> decltype(ctx.out()) {
-    auto out = ctx.out();
-    *out++ = '{';
-    int i = 0;
-    for (const auto& item : map) {
-      if (i > 0) out = detail::write_delimiter(out);
-      out = detail::write_range_entry<Char>(out, item.first);
-      *out++ = ':';
-      *out++ = ' ';
-      out = detail::write_range_entry<Char>(out, item.second);
-      ++i;
-    }
-    *out++ = '}';
-    return out;
+  template <typename FormatContext>
+  auto format(range_type& range, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return underlying_.format(range, ctx);
   }
 };
+}  // namespace detail
+
+template <typename T, typename Char, typename Enable = void>
+struct range_format_kind
+    : conditional_t<
+          is_range<T, Char>::value, detail::range_format_kind_<T>,
+          std::integral_constant<range_format, range_format::disabled>> {};
+
+template <typename R, typename Char>
+struct formatter<
+    R, Char,
+    enable_if_t<conjunction<bool_constant<range_format_kind<R, Char>::value !=
+                                          range_format::disabled>
+// Workaround a bug in MSVC 2015 and earlier.
+#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1910
+                            ,
+                            detail::is_formattable_delayed<R, Char>
+#endif
+                            >::value>>
+    : detail::range_default_formatter<range_format_kind<R, Char>::value, R,
+                                      Char> {
+};
 
 template <typename Char, typename... T> struct tuple_join_view : detail::view {
   const std::tuple<T...>& tuple;
diff --git a/src/vendor/fmt/std.h b/src/vendor/fmt/std.h
new file mode 100644 (file)
index 0000000..41d2b28
--- /dev/null
@@ -0,0 +1,171 @@
+// Formatting library for C++ - formatters for standard library types
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_STD_H_
+#define FMT_STD_H_
+
+#include <thread>
+#include <type_traits>
+#include <utility>
+
+#include "ostream.h"
+
+#if FMT_HAS_INCLUDE(<version>)
+#  include <version>
+#endif
+// Checking FMT_CPLUSPLUS for warning suppression in MSVC.
+#if FMT_CPLUSPLUS >= 201703L
+#  if FMT_HAS_INCLUDE(<filesystem>)
+#    include <filesystem>
+#  endif
+#  if FMT_HAS_INCLUDE(<variant>)
+#    include <variant>
+#  endif
+#endif
+
+#ifdef __cpp_lib_filesystem
+FMT_BEGIN_NAMESPACE
+
+namespace detail {
+
+template <typename Char>
+void write_escaped_path(basic_memory_buffer<Char>& quoted,
+                        const std::filesystem::path& p) {
+  write_escaped_string<Char>(std::back_inserter(quoted), p.string<Char>());
+}
+#  ifdef _WIN32
+template <>
+inline void write_escaped_path<char>(basic_memory_buffer<char>& quoted,
+                                     const std::filesystem::path& p) {
+  auto s = p.u8string();
+  write_escaped_string<char>(
+      std::back_inserter(quoted),
+      string_view(reinterpret_cast<const char*>(s.c_str()), s.size()));
+}
+#  endif
+template <>
+inline void write_escaped_path<std::filesystem::path::value_type>(
+    basic_memory_buffer<std::filesystem::path::value_type>& quoted,
+    const std::filesystem::path& p) {
+  write_escaped_string<std::filesystem::path::value_type>(
+      std::back_inserter(quoted), p.native());
+}
+
+}  // namespace detail
+
+template <typename Char>
+struct formatter<std::filesystem::path, Char>
+    : formatter<basic_string_view<Char>> {
+  template <typename FormatContext>
+  auto format(const std::filesystem::path& p, FormatContext& ctx) const ->
+      typename FormatContext::iterator {
+    basic_memory_buffer<Char> quoted;
+    detail::write_escaped_path(quoted, p);
+    return formatter<basic_string_view<Char>>::format(
+        basic_string_view<Char>(quoted.data(), quoted.size()), ctx);
+  }
+};
+FMT_END_NAMESPACE
+#endif
+
+FMT_BEGIN_NAMESPACE
+template <typename Char>
+struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};
+FMT_END_NAMESPACE
+
+#ifdef __cpp_lib_variant
+FMT_BEGIN_NAMESPACE
+template <typename Char> struct formatter<std::monostate, Char> {
+  template <typename ParseContext>
+  FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+    return ctx.begin();
+  }
+
+  template <typename FormatContext>
+  auto format(const std::monostate&, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+    out = detail::write<Char>(out, "monostate");
+    return out;
+  }
+};
+
+namespace detail {
+
+template <typename T>
+using variant_index_sequence =
+    std::make_index_sequence<std::variant_size<T>::value>;
+
+// variant_size and variant_alternative check.
+template <typename T, typename U = void>
+struct is_variant_like_ : std::false_type {};
+template <typename T>
+struct is_variant_like_<T, std::void_t<decltype(std::variant_size<T>::value)>>
+    : std::true_type {};
+
+// formattable element check
+template <typename T, typename C> class is_variant_formattable_ {
+  template <std::size_t... I>
+  static std::conjunction<
+      is_formattable<std::variant_alternative_t<I, T>, C>...>
+      check(std::index_sequence<I...>);
+
+ public:
+  static constexpr const bool value =
+      decltype(check(variant_index_sequence<T>{}))::value;
+};
+
+template <typename Char, typename OutputIt, typename T>
+auto write_variant_alternative(OutputIt out, const T& v) -> OutputIt {
+  if constexpr (is_string<T>::value)
+    return write_escaped_string<Char>(out, detail::to_string_view(v));
+  else if constexpr (std::is_same_v<T, Char>)
+    return write_escaped_char(out, v);
+  else
+    return write<Char>(out, v);
+}
+
+}  // namespace detail
+
+template <typename T> struct is_variant_like {
+  static constexpr const bool value = detail::is_variant_like_<T>::value;
+};
+
+template <typename T, typename C> struct is_variant_formattable {
+  static constexpr const bool value =
+      detail::is_variant_formattable_<T, C>::value;
+};
+
+template <typename Variant, typename Char>
+struct formatter<
+    Variant, Char,
+    std::enable_if_t<std::conjunction_v<
+        is_variant_like<Variant>, is_variant_formattable<Variant, Char>>>> {
+  template <typename ParseContext>
+  FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+    return ctx.begin();
+  }
+
+  template <typename FormatContext>
+  auto format(const Variant& value, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+
+    out = detail::write<Char>(out, "variant(");
+    std::visit(
+        [&](const auto& v) {
+          out = detail::write_variant_alternative<Char>(out, v);
+        },
+        value);
+    *out++ = ')';
+    return out;
+  }
+};
+FMT_END_NAMESPACE
+#endif
+
+#endif  // FMT_STD_H_
index 55825077f8ed21d386661f089efd0bbcf200b861..3b5bc15ca0a1d92d721611ddc70e80f098fb79ae 100644 (file)
@@ -9,7 +9,6 @@
 #define FMT_XCHAR_H_
 
 #include <cwchar>
-#include <tuple>
 
 #include "format.h"
 
@@ -30,9 +29,11 @@ using wmemory_buffer = basic_memory_buffer<wchar_t>;
 #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
 // Workaround broken conversion on older gcc.
 template <typename... Args> using wformat_string = wstring_view;
+inline auto runtime(wstring_view s) -> wstring_view { return s; }
 #else
 template <typename... Args>
 using wformat_string = basic_format_string<wchar_t, type_identity_t<Args>...>;
+inline auto runtime(wstring_view s) -> basic_runtime<wchar_t> { return {{s}}; }
 #endif
 
 template <> struct is_char<wchar_t> : std::true_type {};
@@ -47,12 +48,7 @@ constexpr format_arg_store<wformat_context, Args...> make_wformat_args(
 }
 
 inline namespace literals {
-constexpr auto operator"" _format(const wchar_t* s, size_t n)
-    -> detail::udl_formatter<wchar_t> {
-  return {{s, n}};
-}
-
-#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
+#if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_ARGS
 constexpr detail::udl_arg<wchar_t> operator"" _a(const wchar_t* s, size_t) {
   return {s};
 }
@@ -87,13 +83,19 @@ auto vformat(basic_string_view<Char> format_str,
   return to_string(buffer);
 }
 
+template <typename... T>
+auto format(wformat_string<T...> fmt, T&&... args) -> std::wstring {
+  return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...));
+}
+
 // Pass char_t as a default template parameter instead of using
 // std::basic_string<char_t<S>> to reduce the symbol size.
 template <typename S, typename... Args, typename Char = char_t<S>,
-          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+          FMT_ENABLE_IF(!std::is_same<Char, char>::value &&
+                        !std::is_same<Char, wchar_t>::value)>
 auto format(const S& format_str, Args&&... args) -> std::basic_string<Char> {
-  const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
-  return vformat(to_string_view(format_str), vargs);
+  return vformat(detail::to_string_view(format_str),
+                 fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 template <typename Locale, typename S, typename Char = char_t<S>,
@@ -103,7 +105,7 @@ inline auto vformat(
     const Locale& loc, const S& format_str,
     basic_format_args<buffer_context<type_identity_t<Char>>> args)
     -> std::basic_string<Char> {
-  return detail::vformat(loc, to_string_view(format_str), args);
+  return detail::vformat(loc, detail::to_string_view(format_str), args);
 }
 
 template <typename Locale, typename S, typename... Args,
@@ -112,8 +114,8 @@ template <typename Locale, typename S, typename... Args,
                             detail::is_exotic_char<Char>::value)>
 inline auto format(const Locale& loc, const S& format_str, Args&&... args)
     -> std::basic_string<Char> {
-  return detail::vformat(loc, to_string_view(format_str),
-                         fmt::make_args_checked<Args...>(format_str, args...));
+  return detail::vformat(loc, detail::to_string_view(format_str),
+                         fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 template <typename OutputIt, typename S, typename Char = char_t<S>,
@@ -123,7 +125,7 @@ auto vformat_to(OutputIt out, const S& format_str,
                 basic_format_args<buffer_context<type_identity_t<Char>>> args)
     -> OutputIt {
   auto&& buf = detail::get_buffer<Char>(out);
-  detail::vformat_to(buf, to_string_view(format_str), args);
+  detail::vformat_to(buf, detail::to_string_view(format_str), args);
   return detail::get_iterator(buf);
 }
 
@@ -132,18 +134,8 @@ template <typename OutputIt, typename S, typename... Args,
           FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
                             detail::is_exotic_char<Char>::value)>
 inline auto format_to(OutputIt out, const S& fmt, Args&&... args) -> OutputIt {
-  const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
-  return vformat_to(out, to_string_view(fmt), vargs);
-}
-
-template <typename S, typename... Args, typename Char, size_t SIZE,
-          typename Allocator, FMT_ENABLE_IF(detail::is_string<S>::value)>
-FMT_DEPRECATED auto format_to(basic_memory_buffer<Char, SIZE, Allocator>& buf,
-                              const S& format_str, Args&&... args) ->
-    typename buffer_context<Char>::iterator {
-  const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
-  detail::vformat_to(buf, to_string_view(format_str), vargs, {});
-  return detail::buffer_appender<Char>(buf);
+  return vformat_to(out, detail::to_string_view(fmt),
+                    fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 template <typename Locale, typename S, typename OutputIt, typename... Args,
@@ -155,7 +147,8 @@ inline auto vformat_to(
     OutputIt out, const Locale& loc, const S& format_str,
     basic_format_args<buffer_context<type_identity_t<Char>>> args) -> OutputIt {
   auto&& buf = detail::get_buffer<Char>(out);
-  vformat_to(buf, to_string_view(format_str), args, detail::locale_ref(loc));
+  vformat_to(buf, detail::to_string_view(format_str), args,
+             detail::locale_ref(loc));
   return detail::get_iterator(buf);
 }
 
@@ -167,8 +160,8 @@ template <
 inline auto format_to(OutputIt out, const Locale& loc, const S& format_str,
                       Args&&... args) ->
     typename std::enable_if<enable, OutputIt>::type {
-  const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
-  return vformat_to(out, loc, to_string_view(format_str), vargs);
+  return vformat_to(out, loc, to_string_view(format_str),
+                    fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 template <typename OutputIt, typename Char, typename... Args,
@@ -190,16 +183,16 @@ template <typename OutputIt, typename S, typename... Args,
                             detail::is_exotic_char<Char>::value)>
 inline auto format_to_n(OutputIt out, size_t n, const S& fmt,
                         const Args&... args) -> format_to_n_result<OutputIt> {
-  const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
-  return vformat_to_n(out, n, to_string_view(fmt), vargs);
+  return vformat_to_n(out, n, detail::to_string_view(fmt),
+                      fmt::make_format_args<buffer_context<Char>>(args...));
 }
 
 template <typename S, typename... Args, typename Char = char_t<S>,
           FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
 inline auto formatted_size(const S& fmt, Args&&... args) -> size_t {
   detail::counting_buffer<Char> buf;
-  const auto& vargs = fmt::make_args_checked<Args...>(fmt, args...);
-  detail::vformat_to(buf, to_string_view(fmt), vargs);
+  detail::vformat_to(buf, detail::to_string_view(fmt),
+                     fmt::make_format_args<buffer_context<Char>>(args...));
   return buf.count();
 }
 
diff --git a/src/vendor/nlohmann/json.hpp b/src/vendor/nlohmann/json.hpp
new file mode 100644 (file)
index 0000000..cb27e05
--- /dev/null
@@ -0,0 +1,22091 @@
+/*
+    __ _____ _____ _____
+ __|  |   __|     |   | |  JSON for Modern C++
+|  |  |__   |  |  | | | |  version 3.10.5
+|_____|_____|_____|_|___|  https://github.com/nlohmann/json
+
+Licensed under the MIT License <http://opensource.org/licenses/MIT>.
+SPDX-License-Identifier: MIT
+Copyright (c) 2013-2022 Niels Lohmann <http://nlohmann.me>.
+
+Permission is hereby  granted, free of charge, to any  person obtaining a copy
+of this software and associated  documentation files (the "Software"), to deal
+in the Software  without restriction, including without  limitation the rights
+to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
+copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
+IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
+FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
+AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
+LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/****************************************************************************\
+ * Note on documentation: The source files contain links to the online      *
+ * documentation of the public API at https://json.nlohmann.me. This URL    *
+ * contains the most recent documentation and should also be applicable to  *
+ * previous versions; documentation for deprecated functions is not         *
+ * removed, but marked deprecated. See "Generate documentation" section in  *
+ * file doc/README.md.                                                      *
+\****************************************************************************/
+
+#ifndef INCLUDE_NLOHMANN_JSON_HPP_
+#define INCLUDE_NLOHMANN_JSON_HPP_
+
+#define NLOHMANN_JSON_VERSION_MAJOR 3
+#define NLOHMANN_JSON_VERSION_MINOR 10
+#define NLOHMANN_JSON_VERSION_PATCH 5
+
+#include <algorithm> // all_of, find, for_each
+#include <cstddef> // nullptr_t, ptrdiff_t, size_t
+#include <functional> // hash, less
+#include <initializer_list> // initializer_list
+#ifndef JSON_NO_IO
+    #include <iosfwd> // istream, ostream
+#endif  // JSON_NO_IO
+#include <iterator> // random_access_iterator_tag
+#include <memory> // unique_ptr
+#include <numeric> // accumulate
+#include <string> // string, stoi, to_string
+#include <utility> // declval, forward, move, pair, swap
+#include <vector> // vector
+
+// #include <nlohmann/adl_serializer.hpp>
+
+
+#include <type_traits>
+#include <utility>
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+
+
+#include <algorithm> // transform
+#include <array> // array
+#include <forward_list> // forward_list
+#include <iterator> // inserter, front_inserter, end
+#include <map> // map
+#include <string> // string
+#include <tuple> // tuple, make_tuple
+#include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
+#include <unordered_map> // unordered_map
+#include <utility> // pair, declval
+#include <valarray> // valarray
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+
+#include <exception> // exception
+#include <stdexcept> // runtime_error
+#include <string> // to_string
+#include <vector> // vector
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+#include <array> // array
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t
+#include <string> // string
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////////////
+// JSON type enumeration //
+///////////////////////////
+
+/*!
+@brief the JSON type enumeration
+
+This enumeration collects the different JSON types. It is internally used to
+distinguish the stored values, and the functions @ref basic_json::is_null(),
+@ref basic_json::is_object(), @ref basic_json::is_array(),
+@ref basic_json::is_string(), @ref basic_json::is_boolean(),
+@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
+@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
+@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
+@ref basic_json::is_structured() rely on it.
+
+@note There are three enumeration entries (number_integer, number_unsigned, and
+number_float), because the library distinguishes these three types for numbers:
+@ref basic_json::number_unsigned_t is used for unsigned integers,
+@ref basic_json::number_integer_t is used for signed integers, and
+@ref basic_json::number_float_t is used for floating-point numbers or to
+approximate integers which do not fit in the limits of their respective type.
+
+@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON
+value with the default value for a given type
+
+@since version 1.0.0
+*/
+enum class value_t : std::uint8_t
+{
+    null,             ///< null value
+    object,           ///< object (unordered set of name/value pairs)
+    array,            ///< array (ordered collection of values)
+    string,           ///< string value
+    boolean,          ///< boolean value
+    number_integer,   ///< number value (signed integer)
+    number_unsigned,  ///< number value (unsigned integer)
+    number_float,     ///< number value (floating-point)
+    binary,           ///< binary array (ordered collection of bytes)
+    discarded         ///< discarded by the parser callback function
+};
+
+/*!
+@brief comparison operator for JSON types
+
+Returns an ordering that is similar to Python:
+- order: null < boolean < number < object < array < string < binary
+- furthermore, each type is not smaller than itself
+- discarded values are not comparable
+- binary is represented as a b"" string in python and directly comparable to a
+  string; however, making a binary array directly comparable with a string would
+  be surprising behavior in a JSON file.
+
+@since version 1.0.0
+*/
+inline bool operator<(const value_t lhs, const value_t rhs) noexcept
+{
+    static constexpr std::array<std::uint8_t, 9> order = {{
+            0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
+            1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
+            6 /* binary */
+        }
+    };
+
+    const auto l_index = static_cast<std::size_t>(lhs);
+    const auto r_index = static_cast<std::size_t>(rhs);
+    return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
+}
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/string_escape.hpp>
+
+
+#include <string>
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+#include <utility> // declval, pair
+// #include <nlohmann/thirdparty/hedley/hedley.hpp>
+
+
+/* Hedley - https://nemequ.github.io/hedley
+ * Created by Evan Nemerson <evan@nemerson.com>
+ *
+ * To the extent possible under law, the author(s) have dedicated all
+ * copyright and related and neighboring rights to this software to
+ * the public domain worldwide. This software is distributed without
+ * any warranty.
+ *
+ * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
+ * SPDX-License-Identifier: CC0-1.0
+ */
+
+#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15)
+#if defined(JSON_HEDLEY_VERSION)
+    #undef JSON_HEDLEY_VERSION
+#endif
+#define JSON_HEDLEY_VERSION 15
+
+#if defined(JSON_HEDLEY_STRINGIFY_EX)
+    #undef JSON_HEDLEY_STRINGIFY_EX
+#endif
+#define JSON_HEDLEY_STRINGIFY_EX(x) #x
+
+#if defined(JSON_HEDLEY_STRINGIFY)
+    #undef JSON_HEDLEY_STRINGIFY
+#endif
+#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
+
+#if defined(JSON_HEDLEY_CONCAT_EX)
+    #undef JSON_HEDLEY_CONCAT_EX
+#endif
+#define JSON_HEDLEY_CONCAT_EX(a,b) a##b
+
+#if defined(JSON_HEDLEY_CONCAT)
+    #undef JSON_HEDLEY_CONCAT
+#endif
+#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
+
+#if defined(JSON_HEDLEY_CONCAT3_EX)
+    #undef JSON_HEDLEY_CONCAT3_EX
+#endif
+#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
+
+#if defined(JSON_HEDLEY_CONCAT3)
+    #undef JSON_HEDLEY_CONCAT3
+#endif
+#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
+
+#if defined(JSON_HEDLEY_VERSION_ENCODE)
+    #undef JSON_HEDLEY_VERSION_ENCODE
+#endif
+#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
+    #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
+    #undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
+
+#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
+    #undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#endif
+#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
+
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+    #undef JSON_HEDLEY_GNUC_VERSION
+#endif
+#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
+    #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
+#elif defined(__GNUC__)
+    #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
+    #undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GNUC_VERSION)
+    #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION)
+    #undef JSON_HEDLEY_MSVC_VERSION
+#endif
+#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
+#elif defined(_MSC_FULL_VER) && !defined(__ICL)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
+#elif defined(_MSC_VER) && !defined(__ICL)
+    #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
+    #undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#endif
+#if !defined(JSON_HEDLEY_MSVC_VERSION)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
+#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
+#elif defined(_MSC_VER) && (_MSC_VER >= 1200)
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
+#else
+    #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+    #undef JSON_HEDLEY_INTEL_VERSION
+#endif
+#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL)
+    #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
+#elif defined(__INTEL_COMPILER) && !defined(__ICL)
+    #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
+    #undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_INTEL_VERSION)
+    #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION)
+    #undef JSON_HEDLEY_INTEL_CL_VERSION
+#endif
+#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL)
+    #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0)
+#endif
+
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK)
+    #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_INTEL_CL_VERSION)
+    #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION)
+    #undef JSON_HEDLEY_PGI_VERSION
+#endif
+#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
+    #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
+#endif
+
+#if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
+    #undef JSON_HEDLEY_PGI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PGI_VERSION)
+    #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+    #undef JSON_HEDLEY_SUNPRO_VERSION
+#endif
+#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10)
+#elif defined(__SUNPRO_C)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
+#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10)
+#elif defined(__SUNPRO_CC)
+    #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
+    #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_SUNPRO_VERSION)
+    #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+    #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#endif
+#if defined(__EMSCRIPTEN__)
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
+#endif
+
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
+    #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION)
+    #undef JSON_HEDLEY_ARM_VERSION
+#endif
+#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
+#elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
+#endif
+
+#if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
+    #undef JSON_HEDLEY_ARM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_ARM_VERSION)
+    #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION)
+    #undef JSON_HEDLEY_IBM_VERSION
+#endif
+#if defined(__ibmxl__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
+#elif defined(__xlC__) && defined(__xlC_ver__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
+#elif defined(__xlC__)
+    #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
+#endif
+
+#if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
+    #undef JSON_HEDLEY_IBM_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IBM_VERSION)
+    #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION)
+    #undef JSON_HEDLEY_TI_VERSION
+#endif
+#if \
+    defined(__TI_COMPILER_VERSION__) && \
+    ( \
+      defined(__TMS470__) || defined(__TI_ARM__) || \
+      defined(__MSP430__) || \
+      defined(__TMS320C2000__) \
+    )
+#if (__TI_COMPILER_VERSION__ >= 16000000)
+    #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+#endif
+
+#if defined(JSON_HEDLEY_TI_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_VERSION)
+    #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION)
+    #undef JSON_HEDLEY_TI_CL2000_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
+    #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL2000_VERSION)
+    #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL430_VERSION)
+    #undef JSON_HEDLEY_TI_CL430_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
+    #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL430_VERSION)
+    #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
+    #undef JSON_HEDLEY_TI_ARMCL_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
+    #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
+    #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION)
+    #undef JSON_HEDLEY_TI_CL6X_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
+    #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL6X_VERSION)
+    #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION)
+    #undef JSON_HEDLEY_TI_CL7X_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
+    #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CL7X_VERSION)
+    #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
+    #undef JSON_HEDLEY_TI_CLPRU_VERSION
+#endif
+#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
+    #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
+#endif
+
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
+    #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
+    #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+    #undef JSON_HEDLEY_CRAY_VERSION
+#endif
+#if defined(_CRAYC)
+    #if defined(_RELEASE_PATCHLEVEL)
+        #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
+    #else
+        #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
+    #endif
+#endif
+
+#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
+    #undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_CRAY_VERSION)
+    #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION)
+    #undef JSON_HEDLEY_IAR_VERSION
+#endif
+#if defined(__IAR_SYSTEMS_ICC__)
+    #if __VER__ > 1000
+        #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
+    #else
+        #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0)
+    #endif
+#endif
+
+#if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
+    #undef JSON_HEDLEY_IAR_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_IAR_VERSION)
+    #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+    #undef JSON_HEDLEY_TINYC_VERSION
+#endif
+#if defined(__TINYC__)
+    #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
+    #undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_TINYC_VERSION)
+    #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION)
+    #undef JSON_HEDLEY_DMC_VERSION
+#endif
+#if defined(__DMC__)
+    #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
+#endif
+
+#if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
+    #undef JSON_HEDLEY_DMC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_DMC_VERSION)
+    #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+    #undef JSON_HEDLEY_COMPCERT_VERSION
+#endif
+#if defined(__COMPCERT_VERSION__)
+    #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
+#endif
+
+#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
+    #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_COMPCERT_VERSION)
+    #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+    #undef JSON_HEDLEY_PELLES_VERSION
+#endif
+#if defined(__POCC__)
+    #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
+#endif
+
+#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
+    #undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_PELLES_VERSION)
+    #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION)
+    #undef JSON_HEDLEY_MCST_LCC_VERSION
+#endif
+#if defined(__LCC__) && defined(__LCC_MINOR__)
+    #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__)
+#endif
+
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK)
+    #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_MCST_LCC_VERSION)
+    #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION)
+    #undef JSON_HEDLEY_GCC_VERSION
+#endif
+#if \
+    defined(JSON_HEDLEY_GNUC_VERSION) && \
+    !defined(__clang__) && \
+    !defined(JSON_HEDLEY_INTEL_VERSION) && \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    !defined(JSON_HEDLEY_ARM_VERSION) && \
+    !defined(JSON_HEDLEY_CRAY_VERSION) && \
+    !defined(JSON_HEDLEY_TI_VERSION) && \
+    !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
+    !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
+    !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
+    !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
+    !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
+    !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
+    !defined(__COMPCERT__) && \
+    !defined(JSON_HEDLEY_MCST_LCC_VERSION)
+    #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
+#endif
+
+#if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
+    #undef JSON_HEDLEY_GCC_VERSION_CHECK
+#endif
+#if defined(JSON_HEDLEY_GCC_VERSION)
+    #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
+#else
+    #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_ATTRIBUTE
+#endif
+#if \
+  defined(__has_attribute) && \
+  ( \
+    (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \
+  )
+#  define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
+#else
+#  define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+    #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#endif
+#if defined(__has_attribute)
+    #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#endif
+#if \
+    defined(__has_cpp_attribute) && \
+    defined(__cplusplus) && \
+    (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
+    #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#endif
+#if !defined(__cplusplus) || !defined(__has_cpp_attribute)
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
+#elif \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    !defined(JSON_HEDLEY_IAR_VERSION) && \
+    (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
+    (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
+#else
+    #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+    #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#endif
+#if defined(__has_cpp_attribute) && defined(__cplusplus)
+    #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_BUILTIN)
+    #undef JSON_HEDLEY_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
+    #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
+    #undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#endif
+#if defined(__has_builtin)
+    #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
+#else
+    #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_FEATURE)
+    #undef JSON_HEDLEY_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
+    #undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
+    #undef JSON_HEDLEY_GCC_HAS_FEATURE
+#endif
+#if defined(__has_feature)
+    #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
+#else
+    #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_EXTENSION)
+    #undef JSON_HEDLEY_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
+    #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
+    #undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#endif
+#if defined(__has_extension)
+    #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
+#else
+    #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#endif
+#if defined(__has_declspec_attribute)
+    #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
+#else
+    #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_HAS_WARNING)
+    #undef JSON_HEDLEY_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_HAS_WARNING(warning) (0)
+#endif
+
+#if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
+    #undef JSON_HEDLEY_GNUC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_GCC_HAS_WARNING)
+    #undef JSON_HEDLEY_GCC_HAS_WARNING
+#endif
+#if defined(__has_warning)
+    #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
+#else
+    #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if \
+    (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
+    defined(__clang__) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
+    JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
+    (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
+    #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
+#else
+    #define JSON_HEDLEY_PRAGMA(value)
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
+    #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#endif
+#if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
+    #undef JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+#if defined(__clang__)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
+    #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
+#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
+#elif \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
+    #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_PUSH
+    #define JSON_HEDLEY_DIAGNOSTIC_POP
+#endif
+
+/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
+   HEDLEY INTERNAL USE ONLY.  API subject to change without notice. */
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#endif
+#if defined(__cplusplus)
+#  if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
+#    if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
+#      if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions")
+#        define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
+    _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
+    _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \
+    xpr \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#      else
+#        define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
+    _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
+    xpr \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#      endif
+#    else
+#      define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
+    xpr \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#    endif
+#  endif
+#endif
+#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
+#endif
+
+#if defined(JSON_HEDLEY_CONST_CAST)
+    #undef JSON_HEDLEY_CONST_CAST
+#endif
+#if defined(__cplusplus)
+#  define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
+#elif \
+  JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+#  define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
+        JSON_HEDLEY_DIAGNOSTIC_PUSH \
+        JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
+        ((T) (expr)); \
+        JSON_HEDLEY_DIAGNOSTIC_POP \
+    }))
+#else
+#  define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
+#endif
+
+#if defined(JSON_HEDLEY_REINTERPRET_CAST)
+    #undef JSON_HEDLEY_REINTERPRET_CAST
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
+#else
+    #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_CAST)
+    #undef JSON_HEDLEY_STATIC_CAST
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
+#else
+    #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
+#endif
+
+#if defined(JSON_HEDLEY_CPP_CAST)
+    #undef JSON_HEDLEY_CPP_CAST
+#endif
+#if defined(__cplusplus)
+#  if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
+#    define JSON_HEDLEY_CPP_CAST(T, expr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
+    ((T) (expr)) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#  elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
+#    define JSON_HEDLEY_CPP_CAST(T, expr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("diag_suppress=Pe137") \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#  else
+#    define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
+#  endif
+#else
+#  define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
+#elif \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
+#elif \
+    JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
+#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292))
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098")
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
+#elif \
+    JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
+#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#endif
+
+#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION)
+    #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunused-function")
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"")
+#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
+#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505))
+#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142")
+#else
+    #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#endif
+
+#if defined(JSON_HEDLEY_DEPRECATED)
+    #undef JSON_HEDLEY_DEPRECATED
+#endif
+#if defined(JSON_HEDLEY_DEPRECATED_FOR)
+    #undef JSON_HEDLEY_DEPRECATED_FOR
+#endif
+#if \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
+#elif \
+    (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
+#elif defined(__cplusplus) && (__cplusplus >= 201402L)
+    #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
+#else
+    #define JSON_HEDLEY_DEPRECATED(since)
+    #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
+#endif
+
+#if defined(JSON_HEDLEY_UNAVAILABLE)
+    #undef JSON_HEDLEY_UNAVAILABLE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
+#else
+    #define JSON_HEDLEY_UNAVAILABLE(available_since)
+#endif
+
+#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
+    #undef JSON_HEDLEY_WARN_UNUSED_RESULT
+#endif
+#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
+    #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
+#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
+#elif defined(_Check_return_) /* SAL */
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
+#else
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT
+    #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
+#endif
+
+#if defined(JSON_HEDLEY_SENTINEL)
+    #undef JSON_HEDLEY_SENTINEL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
+#else
+    #define JSON_HEDLEY_SENTINEL(position)
+#endif
+
+#if defined(JSON_HEDLEY_NO_RETURN)
+    #undef JSON_HEDLEY_NO_RETURN
+#endif
+#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_NO_RETURN __noreturn
+#elif \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+    #define JSON_HEDLEY_NO_RETURN _Noreturn
+#elif defined(__cplusplus) && (__cplusplus >= 201103L)
+    #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
+    #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
+    #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
+    #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
+#else
+    #define JSON_HEDLEY_NO_RETURN
+#endif
+
+#if defined(JSON_HEDLEY_NO_ESCAPE)
+    #undef JSON_HEDLEY_NO_ESCAPE
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
+    #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
+#else
+    #define JSON_HEDLEY_NO_ESCAPE
+#endif
+
+#if defined(JSON_HEDLEY_UNREACHABLE)
+    #undef JSON_HEDLEY_UNREACHABLE
+#endif
+#if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
+    #undef JSON_HEDLEY_UNREACHABLE_RETURN
+#endif
+#if defined(JSON_HEDLEY_ASSUME)
+    #undef JSON_HEDLEY_ASSUME
+#endif
+#if \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
+#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
+    #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
+#elif \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
+    #if defined(__cplusplus)
+        #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
+    #else
+        #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
+    #endif
+#endif
+#if \
+    (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \
+    JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
+#elif defined(JSON_HEDLEY_ASSUME)
+    #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
+#endif
+#if !defined(JSON_HEDLEY_ASSUME)
+    #if defined(JSON_HEDLEY_UNREACHABLE)
+        #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
+    #else
+        #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
+    #endif
+#endif
+#if defined(JSON_HEDLEY_UNREACHABLE)
+    #if  \
+        JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
+        JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
+        #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
+    #else
+        #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
+    #endif
+#else
+    #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
+#endif
+#if !defined(JSON_HEDLEY_UNREACHABLE)
+    #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
+#endif
+
+JSON_HEDLEY_DIAGNOSTIC_PUSH
+#if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
+    #pragma clang diagnostic ignored "-Wpedantic"
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
+    #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
+#endif
+#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
+    #if defined(__clang__)
+        #pragma clang diagnostic ignored "-Wvariadic-macros"
+    #elif defined(JSON_HEDLEY_GCC_VERSION)
+        #pragma GCC diagnostic ignored "-Wvariadic-macros"
+    #endif
+#endif
+#if defined(JSON_HEDLEY_NON_NULL)
+    #undef JSON_HEDLEY_NON_NULL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
+    #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
+#else
+    #define JSON_HEDLEY_NON_NULL(...)
+#endif
+JSON_HEDLEY_DIAGNOSTIC_POP
+
+#if defined(JSON_HEDLEY_PRINTF_FORMAT)
+    #undef JSON_HEDLEY_PRINTF_FORMAT
+#endif
+#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
+#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
+#elif \
+    JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
+#else
+    #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
+#endif
+
+#if defined(JSON_HEDLEY_CONSTEXPR)
+    #undef JSON_HEDLEY_CONSTEXPR
+#endif
+#if defined(__cplusplus)
+    #if __cplusplus >= 201103L
+        #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
+    #endif
+#endif
+#if !defined(JSON_HEDLEY_CONSTEXPR)
+    #define JSON_HEDLEY_CONSTEXPR
+#endif
+
+#if defined(JSON_HEDLEY_PREDICT)
+    #undef JSON_HEDLEY_PREDICT
+#endif
+#if defined(JSON_HEDLEY_LIKELY)
+    #undef JSON_HEDLEY_LIKELY
+#endif
+#if defined(JSON_HEDLEY_UNLIKELY)
+    #undef JSON_HEDLEY_UNLIKELY
+#endif
+#if defined(JSON_HEDLEY_UNPREDICTABLE)
+    #undef JSON_HEDLEY_UNPREDICTABLE
+#endif
+#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
+    #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
+#endif
+#if \
+  (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \
+  JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+#  define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(  (expr), (value), (probability))
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability)   __builtin_expect_with_probability(!!(expr),    1   , (probability))
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability)  __builtin_expect_with_probability(!!(expr),    0   , (probability))
+#  define JSON_HEDLEY_LIKELY(expr)                      __builtin_expect                 (!!(expr),    1                  )
+#  define JSON_HEDLEY_UNLIKELY(expr)                    __builtin_expect                 (!!(expr),    0                  )
+#elif \
+  (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+  (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
+  JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+  JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+  JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+  JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
+  JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
+  JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
+  JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
+  JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+  JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+  JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
+  JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
+  JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+#  define JSON_HEDLEY_PREDICT(expr, expected, probability) \
+    (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
+    (__extension__ ({ \
+        double hedley_probability_ = (probability); \
+        ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
+    }))
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
+    (__extension__ ({ \
+        double hedley_probability_ = (probability); \
+        ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
+    }))
+#  define JSON_HEDLEY_LIKELY(expr)   __builtin_expect(!!(expr), 1)
+#  define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
+#else
+#  define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
+#  define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
+#  define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
+#  define JSON_HEDLEY_LIKELY(expr) (!!(expr))
+#  define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
+#endif
+#if !defined(JSON_HEDLEY_UNPREDICTABLE)
+    #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
+#endif
+
+#if defined(JSON_HEDLEY_MALLOC)
+    #undef JSON_HEDLEY_MALLOC
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_MALLOC __declspec(restrict)
+#else
+    #define JSON_HEDLEY_MALLOC
+#endif
+
+#if defined(JSON_HEDLEY_PURE)
+    #undef JSON_HEDLEY_PURE
+#endif
+#if \
+  JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+  JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+  JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+  JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+  JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+  (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+  (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+  (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+  (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+  JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+  JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+  JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+  JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+#  define JSON_HEDLEY_PURE __attribute__((__pure__))
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+#  define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
+#elif defined(__cplusplus) && \
+    ( \
+      JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
+      JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
+      JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
+    )
+#  define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
+#else
+#  define JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_CONST)
+    #undef JSON_HEDLEY_CONST
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_CONST __attribute__((__const__))
+#elif \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
+    #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
+#else
+    #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
+#endif
+
+#if defined(JSON_HEDLEY_RESTRICT)
+    #undef JSON_HEDLEY_RESTRICT
+#endif
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
+    #define JSON_HEDLEY_RESTRICT restrict
+#elif \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
+    defined(__clang__) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_RESTRICT __restrict
+#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
+    #define JSON_HEDLEY_RESTRICT _Restrict
+#else
+    #define JSON_HEDLEY_RESTRICT
+#endif
+
+#if defined(JSON_HEDLEY_INLINE)
+    #undef JSON_HEDLEY_INLINE
+#endif
+#if \
+    (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
+    (defined(__cplusplus) && (__cplusplus >= 199711L))
+    #define JSON_HEDLEY_INLINE inline
+#elif \
+    defined(JSON_HEDLEY_GCC_VERSION) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
+    #define JSON_HEDLEY_INLINE __inline__
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_INLINE __inline
+#else
+    #define JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_ALWAYS_INLINE)
+    #undef JSON_HEDLEY_ALWAYS_INLINE
+#endif
+#if \
+  JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+  JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+  JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+  JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+  JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+  (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+  (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+  (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+  (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+  JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+  JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+  JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+  JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
+  JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
+#  define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
+#elif \
+  JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
+  JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+#  define JSON_HEDLEY_ALWAYS_INLINE __forceinline
+#elif defined(__cplusplus) && \
+    ( \
+      JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+      JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+      JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+      JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
+      JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+      JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
+    )
+#  define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+#  define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
+#else
+#  define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_NEVER_INLINE)
+    #undef JSON_HEDLEY_NEVER_INLINE
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
+    JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
+    (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
+    (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
+    (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
+    (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
+    JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
+    JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \
+    JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0)
+    #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
+#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+    #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
+#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
+    #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
+    #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
+#else
+    #define JSON_HEDLEY_NEVER_INLINE
+#endif
+
+#if defined(JSON_HEDLEY_PRIVATE)
+    #undef JSON_HEDLEY_PRIVATE
+#endif
+#if defined(JSON_HEDLEY_PUBLIC)
+    #undef JSON_HEDLEY_PUBLIC
+#endif
+#if defined(JSON_HEDLEY_IMPORT)
+    #undef JSON_HEDLEY_IMPORT
+#endif
+#if defined(_WIN32) || defined(__CYGWIN__)
+#  define JSON_HEDLEY_PRIVATE
+#  define JSON_HEDLEY_PUBLIC   __declspec(dllexport)
+#  define JSON_HEDLEY_IMPORT   __declspec(dllimport)
+#else
+#  if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+    JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+    ( \
+      defined(__TI_EABI__) && \
+      ( \
+        (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
+        JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
+      ) \
+    ) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+#    define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
+#    define JSON_HEDLEY_PUBLIC  __attribute__((__visibility__("default")))
+#  else
+#    define JSON_HEDLEY_PRIVATE
+#    define JSON_HEDLEY_PUBLIC
+#  endif
+#  define JSON_HEDLEY_IMPORT    extern
+#endif
+
+#if defined(JSON_HEDLEY_NO_THROW)
+    #undef JSON_HEDLEY_NO_THROW
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
+#elif \
+    JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
+    #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
+#else
+    #define JSON_HEDLEY_NO_THROW
+#endif
+
+#if defined(JSON_HEDLEY_FALL_THROUGH)
+    #undef JSON_HEDLEY_FALL_THROUGH
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
+    #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
+#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
+    #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
+#elif defined(__fallthrough) /* SAL */
+    #define JSON_HEDLEY_FALL_THROUGH __fallthrough
+#else
+    #define JSON_HEDLEY_FALL_THROUGH
+#endif
+
+#if defined(JSON_HEDLEY_RETURNS_NON_NULL)
+    #undef JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+#if \
+    JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
+#elif defined(_Ret_notnull_) /* SAL */
+    #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
+#else
+    #define JSON_HEDLEY_RETURNS_NON_NULL
+#endif
+
+#if defined(JSON_HEDLEY_ARRAY_PARAM)
+    #undef JSON_HEDLEY_ARRAY_PARAM
+#endif
+#if \
+    defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
+    !defined(__STDC_NO_VLA__) && \
+    !defined(__cplusplus) && \
+    !defined(JSON_HEDLEY_PGI_VERSION) && \
+    !defined(JSON_HEDLEY_TINYC_VERSION)
+    #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
+#else
+    #define JSON_HEDLEY_ARRAY_PARAM(name)
+#endif
+
+#if defined(JSON_HEDLEY_IS_CONSTANT)
+    #undef JSON_HEDLEY_IS_CONSTANT
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
+    #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#endif
+/* JSON_HEDLEY_IS_CONSTEXPR_ is for
+   HEDLEY INTERNAL USE ONLY.  API subject to change without notice. */
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+    #undef JSON_HEDLEY_IS_CONSTEXPR_
+#endif
+#if \
+    JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
+    JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+    JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+    JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
+    JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
+    JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+    JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
+    (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
+    JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
+    JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10)
+    #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
+#endif
+#if !defined(__cplusplus)
+#  if \
+       JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
+       JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
+       JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+       JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
+       JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
+       JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
+       JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
+#if defined(__INTPTR_TYPE__)
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
+#else
+    #include <stdint.h>
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
+#endif
+#  elif \
+       ( \
+          defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
+          !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
+          !defined(JSON_HEDLEY_PGI_VERSION) && \
+          !defined(JSON_HEDLEY_IAR_VERSION)) || \
+       (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \
+       JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
+       JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
+       JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
+       JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
+#if defined(__INTPTR_TYPE__)
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
+#else
+    #include <stdint.h>
+    #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
+#endif
+#  elif \
+       defined(JSON_HEDLEY_GCC_VERSION) || \
+       defined(JSON_HEDLEY_INTEL_VERSION) || \
+       defined(JSON_HEDLEY_TINYC_VERSION) || \
+       defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
+       JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
+       defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
+       defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
+       defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
+       defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
+       defined(__clang__)
+#    define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
+        sizeof(void) != \
+        sizeof(*( \
+                  1 ? \
+                  ((void*) ((expr) * 0L) ) : \
+((struct { char v[sizeof(void) * 2]; } *) 1) \
+                ) \
+              ) \
+                                            )
+#  endif
+#endif
+#if defined(JSON_HEDLEY_IS_CONSTEXPR_)
+    #if !defined(JSON_HEDLEY_IS_CONSTANT)
+        #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
+    #endif
+    #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
+#else
+    #if !defined(JSON_HEDLEY_IS_CONSTANT)
+        #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
+    #endif
+    #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
+#endif
+
+#if defined(JSON_HEDLEY_BEGIN_C_DECLS)
+    #undef JSON_HEDLEY_BEGIN_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_END_C_DECLS)
+    #undef JSON_HEDLEY_END_C_DECLS
+#endif
+#if defined(JSON_HEDLEY_C_DECL)
+    #undef JSON_HEDLEY_C_DECL
+#endif
+#if defined(__cplusplus)
+    #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
+    #define JSON_HEDLEY_END_C_DECLS }
+    #define JSON_HEDLEY_C_DECL extern "C"
+#else
+    #define JSON_HEDLEY_BEGIN_C_DECLS
+    #define JSON_HEDLEY_END_C_DECLS
+    #define JSON_HEDLEY_C_DECL
+#endif
+
+#if defined(JSON_HEDLEY_STATIC_ASSERT)
+    #undef JSON_HEDLEY_STATIC_ASSERT
+#endif
+#if \
+  !defined(__cplusplus) && ( \
+      (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
+      (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \
+      JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
+      JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
+      defined(_Static_assert) \
+    )
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
+#elif \
+  (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
+  JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
+  JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
+#else
+#  define JSON_HEDLEY_STATIC_ASSERT(expr, message)
+#endif
+
+#if defined(JSON_HEDLEY_NULL)
+    #undef JSON_HEDLEY_NULL
+#endif
+#if defined(__cplusplus)
+    #if __cplusplus >= 201103L
+        #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
+    #elif defined(NULL)
+        #define JSON_HEDLEY_NULL NULL
+    #else
+        #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
+    #endif
+#elif defined(NULL)
+    #define JSON_HEDLEY_NULL NULL
+#else
+    #define JSON_HEDLEY_NULL ((void*) 0)
+#endif
+
+#if defined(JSON_HEDLEY_MESSAGE)
+    #undef JSON_HEDLEY_MESSAGE
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#  define JSON_HEDLEY_MESSAGE(msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+    JSON_HEDLEY_PRAGMA(message msg) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#elif \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
+#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
+#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
+#  define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#  define JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_WARNING)
+    #undef JSON_HEDLEY_WARNING
+#endif
+#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
+#  define JSON_HEDLEY_WARNING(msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
+    JSON_HEDLEY_PRAGMA(clang warning msg) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#elif \
+  JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
+  JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
+  JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
+#elif \
+  JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \
+  JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
+#else
+#  define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
+#endif
+
+#if defined(JSON_HEDLEY_REQUIRE)
+    #undef JSON_HEDLEY_REQUIRE
+#endif
+#if defined(JSON_HEDLEY_REQUIRE_MSG)
+    #undef JSON_HEDLEY_REQUIRE_MSG
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
+#  if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
+#    define JSON_HEDLEY_REQUIRE(expr) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+    __attribute__((diagnose_if(!(expr), #expr, "error"))) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#    define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
+    JSON_HEDLEY_DIAGNOSTIC_PUSH \
+    _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
+    __attribute__((diagnose_if(!(expr), msg, "error"))) \
+    JSON_HEDLEY_DIAGNOSTIC_POP
+#  else
+#    define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
+#    define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
+#  endif
+#else
+#  define JSON_HEDLEY_REQUIRE(expr)
+#  define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS)
+    #undef JSON_HEDLEY_FLAGS
+#endif
+#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion"))
+    #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
+#else
+    #define JSON_HEDLEY_FLAGS
+#endif
+
+#if defined(JSON_HEDLEY_FLAGS_CAST)
+    #undef JSON_HEDLEY_FLAGS_CAST
+#endif
+#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
+#  define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
+        JSON_HEDLEY_DIAGNOSTIC_PUSH \
+        _Pragma("warning(disable:188)") \
+        ((T) (expr)); \
+        JSON_HEDLEY_DIAGNOSTIC_POP \
+    }))
+#else
+#  define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
+#endif
+
+#if defined(JSON_HEDLEY_EMPTY_BASES)
+    #undef JSON_HEDLEY_EMPTY_BASES
+#endif
+#if \
+    (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \
+    JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0)
+    #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
+#else
+    #define JSON_HEDLEY_EMPTY_BASES
+#endif
+
+/* Remaining macros are deprecated. */
+
+#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
+    #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#endif
+#if defined(__clang__)
+    #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
+#else
+    #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
+#endif
+
+#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
+    #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#endif
+#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
+    #undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
+    #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#endif
+#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
+    #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#endif
+#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
+
+#if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
+    #undef JSON_HEDLEY_CLANG_HAS_WARNING
+#endif
+#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
+
+#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+
+#include <type_traits>
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename ...Ts> struct make_void
+{
+    using type = void;
+};
+template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
+} // namespace detail
+}  // namespace nlohmann
+
+
+// https://en.cppreference.com/w/cpp/experimental/is_detected
+namespace nlohmann
+{
+namespace detail
+{
+struct nonesuch
+{
+    nonesuch() = delete;
+    ~nonesuch() = delete;
+    nonesuch(nonesuch const&) = delete;
+    nonesuch(nonesuch const&&) = delete;
+    void operator=(nonesuch const&) = delete;
+    void operator=(nonesuch&&) = delete;
+};
+
+template<class Default,
+         class AlwaysVoid,
+         template<class...> class Op,
+         class... Args>
+struct detector
+{
+    using value_t = std::false_type;
+    using type = Default;
+};
+
+template<class Default, template<class...> class Op, class... Args>
+struct detector<Default, void_t<Op<Args...>>, Op, Args...>
+{
+    using value_t = std::true_type;
+    using type = Op<Args...>;
+};
+
+template<template<class...> class Op, class... Args>
+using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
+
+template<template<class...> class Op, class... Args>
+struct is_detected_lazy : is_detected<Op, Args...> { };
+
+template<template<class...> class Op, class... Args>
+using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
+
+template<class Default, template<class...> class Op, class... Args>
+using detected_or = detector<Default, void, Op, Args...>;
+
+template<class Default, template<class...> class Op, class... Args>
+using detected_or_t = typename detected_or<Default, Op, Args...>::type;
+
+template<class Expected, template<class...> class Op, class... Args>
+using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
+
+template<class To, template<class...> class Op, class... Args>
+using is_detected_convertible =
+    std::is_convertible<detected_t<Op, Args...>, To>;
+}  // namespace detail
+}  // namespace nlohmann
+
+
+// This file contains all internal macro definitions
+// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
+
+// exclude unsupported compilers
+#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
+    #if defined(__clang__)
+        #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
+            #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
+        #endif
+    #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
+        #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
+            #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
+        #endif
+    #endif
+#endif
+
+// C++ language standard detection
+// if the user manually specified the used c++ version this is skipped
+#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11)
+    #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
+        #define JSON_HAS_CPP_20
+        #define JSON_HAS_CPP_17
+        #define JSON_HAS_CPP_14
+    #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
+        #define JSON_HAS_CPP_17
+        #define JSON_HAS_CPP_14
+    #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
+        #define JSON_HAS_CPP_14
+    #endif
+    // the cpp 11 flag is always specified because it is the minimal required version
+    #define JSON_HAS_CPP_11
+#endif
+
+#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM)
+    #ifdef JSON_HAS_CPP_17
+        #if defined(__cpp_lib_filesystem)
+            #define JSON_HAS_FILESYSTEM 1
+        #elif defined(__cpp_lib_experimental_filesystem)
+            #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+        #elif !defined(__has_include)
+            #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+        #elif __has_include(<filesystem>)
+            #define JSON_HAS_FILESYSTEM 1
+        #elif __has_include(<experimental/filesystem>)
+            #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
+        #endif
+
+        // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/
+        #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+
+        // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support
+        #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+
+        // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support
+        #if defined(__clang_major__) && __clang_major__ < 7
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+
+        // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support
+        #if defined(_MSC_VER) && _MSC_VER < 1940
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+
+        // no filesystem support before iOS 13
+        #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+
+        // no filesystem support before macOS Catalina
+        #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
+            #undef JSON_HAS_FILESYSTEM
+            #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+        #endif
+    #endif
+#endif
+
+#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+    #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0
+#endif
+
+#ifndef JSON_HAS_FILESYSTEM
+    #define JSON_HAS_FILESYSTEM 0
+#endif
+
+// disable documentation warnings on clang
+#if defined(__clang__)
+    #pragma clang diagnostic push
+    #pragma clang diagnostic ignored "-Wdocumentation"
+    #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
+#endif
+
+// allow disabling exceptions
+#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
+    #define JSON_THROW(exception) throw exception
+    #define JSON_TRY try
+    #define JSON_CATCH(exception) catch(exception)
+    #define JSON_INTERNAL_CATCH(exception) catch(exception)
+#else
+    #include <cstdlib>
+    #define JSON_THROW(exception) std::abort()
+    #define JSON_TRY if(true)
+    #define JSON_CATCH(exception) if(false)
+    #define JSON_INTERNAL_CATCH(exception) if(false)
+#endif
+
+// override exception macros
+#if defined(JSON_THROW_USER)
+    #undef JSON_THROW
+    #define JSON_THROW JSON_THROW_USER
+#endif
+#if defined(JSON_TRY_USER)
+    #undef JSON_TRY
+    #define JSON_TRY JSON_TRY_USER
+#endif
+#if defined(JSON_CATCH_USER)
+    #undef JSON_CATCH
+    #define JSON_CATCH JSON_CATCH_USER
+    #undef JSON_INTERNAL_CATCH
+    #define JSON_INTERNAL_CATCH JSON_CATCH_USER
+#endif
+#if defined(JSON_INTERNAL_CATCH_USER)
+    #undef JSON_INTERNAL_CATCH
+    #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
+#endif
+
+// allow overriding assert
+#if !defined(JSON_ASSERT)
+    #include <cassert> // assert
+    #define JSON_ASSERT(x) assert(x)
+#endif
+
+// allow to access some private functions (needed by the test suite)
+#if defined(JSON_TESTS_PRIVATE)
+    #define JSON_PRIVATE_UNLESS_TESTED public
+#else
+    #define JSON_PRIVATE_UNLESS_TESTED private
+#endif
+
+/*!
+@brief macro to briefly define a mapping between an enum and JSON
+@def NLOHMANN_JSON_SERIALIZE_ENUM
+@since version 3.4.0
+*/
+#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...)                                            \
+    template<typename BasicJsonType>                                                            \
+    inline void to_json(BasicJsonType& j, const ENUM_TYPE& e)                                   \
+    {                                                                                           \
+        static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!");          \
+        static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__;                     \
+        auto it = std::find_if(std::begin(m), std::end(m),                                      \
+                               [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool  \
+        {                                                                                       \
+            return ej_pair.first == e;                                                          \
+        });                                                                                     \
+        j = ((it != std::end(m)) ? it : std::begin(m))->second;                                 \
+    }                                                                                           \
+    template<typename BasicJsonType>                                                            \
+    inline void from_json(const BasicJsonType& j, ENUM_TYPE& e)                                 \
+    {                                                                                           \
+        static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!");          \
+        static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__;                     \
+        auto it = std::find_if(std::begin(m), std::end(m),                                      \
+                               [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
+        {                                                                                       \
+            return ej_pair.second == j;                                                         \
+        });                                                                                     \
+        e = ((it != std::end(m)) ? it : std::begin(m))->first;                                  \
+    }
+
+// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
+// may be removed in the future once the class is split.
+
+#define NLOHMANN_BASIC_JSON_TPL_DECLARATION                                \
+    template<template<typename, typename, typename...> class ObjectType,   \
+             template<typename, typename...> class ArrayType,              \
+             class StringType, class BooleanType, class NumberIntegerType, \
+             class NumberUnsignedType, class NumberFloatType,              \
+             template<typename> class AllocatorType,                       \
+             template<typename, typename = void> class JSONSerializer,     \
+             class BinaryType>
+
+#define NLOHMANN_BASIC_JSON_TPL                                            \
+    basic_json<ObjectType, ArrayType, StringType, BooleanType,             \
+    NumberIntegerType, NumberUnsignedType, NumberFloatType,                \
+    AllocatorType, JSONSerializer, BinaryType>
+
+// Macros to simplify conversion from/to types
+
+#define NLOHMANN_JSON_EXPAND( x ) x
+#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME
+#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \
+        NLOHMANN_JSON_PASTE64, \
+        NLOHMANN_JSON_PASTE63, \
+        NLOHMANN_JSON_PASTE62, \
+        NLOHMANN_JSON_PASTE61, \
+        NLOHMANN_JSON_PASTE60, \
+        NLOHMANN_JSON_PASTE59, \
+        NLOHMANN_JSON_PASTE58, \
+        NLOHMANN_JSON_PASTE57, \
+        NLOHMANN_JSON_PASTE56, \
+        NLOHMANN_JSON_PASTE55, \
+        NLOHMANN_JSON_PASTE54, \
+        NLOHMANN_JSON_PASTE53, \
+        NLOHMANN_JSON_PASTE52, \
+        NLOHMANN_JSON_PASTE51, \
+        NLOHMANN_JSON_PASTE50, \
+        NLOHMANN_JSON_PASTE49, \
+        NLOHMANN_JSON_PASTE48, \
+        NLOHMANN_JSON_PASTE47, \
+        NLOHMANN_JSON_PASTE46, \
+        NLOHMANN_JSON_PASTE45, \
+        NLOHMANN_JSON_PASTE44, \
+        NLOHMANN_JSON_PASTE43, \
+        NLOHMANN_JSON_PASTE42, \
+        NLOHMANN_JSON_PASTE41, \
+        NLOHMANN_JSON_PASTE40, \
+        NLOHMANN_JSON_PASTE39, \
+        NLOHMANN_JSON_PASTE38, \
+        NLOHMANN_JSON_PASTE37, \
+        NLOHMANN_JSON_PASTE36, \
+        NLOHMANN_JSON_PASTE35, \
+        NLOHMANN_JSON_PASTE34, \
+        NLOHMANN_JSON_PASTE33, \
+        NLOHMANN_JSON_PASTE32, \
+        NLOHMANN_JSON_PASTE31, \
+        NLOHMANN_JSON_PASTE30, \
+        NLOHMANN_JSON_PASTE29, \
+        NLOHMANN_JSON_PASTE28, \
+        NLOHMANN_JSON_PASTE27, \
+        NLOHMANN_JSON_PASTE26, \
+        NLOHMANN_JSON_PASTE25, \
+        NLOHMANN_JSON_PASTE24, \
+        NLOHMANN_JSON_PASTE23, \
+        NLOHMANN_JSON_PASTE22, \
+        NLOHMANN_JSON_PASTE21, \
+        NLOHMANN_JSON_PASTE20, \
+        NLOHMANN_JSON_PASTE19, \
+        NLOHMANN_JSON_PASTE18, \
+        NLOHMANN_JSON_PASTE17, \
+        NLOHMANN_JSON_PASTE16, \
+        NLOHMANN_JSON_PASTE15, \
+        NLOHMANN_JSON_PASTE14, \
+        NLOHMANN_JSON_PASTE13, \
+        NLOHMANN_JSON_PASTE12, \
+        NLOHMANN_JSON_PASTE11, \
+        NLOHMANN_JSON_PASTE10, \
+        NLOHMANN_JSON_PASTE9, \
+        NLOHMANN_JSON_PASTE8, \
+        NLOHMANN_JSON_PASTE7, \
+        NLOHMANN_JSON_PASTE6, \
+        NLOHMANN_JSON_PASTE5, \
+        NLOHMANN_JSON_PASTE4, \
+        NLOHMANN_JSON_PASTE3, \
+        NLOHMANN_JSON_PASTE2, \
+        NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
+#define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
+#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
+#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
+#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
+#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
+#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6)
+#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7)
+#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8)
+#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9)
+#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10)
+#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11)
+#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12)
+#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13)
+#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14)
+#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)
+#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16)
+#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17)
+#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18)
+#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19)
+#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20)
+#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21)
+#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22)
+#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23)
+#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24)
+#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25)
+#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26)
+#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27)
+#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28)
+#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29)
+#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30)
+#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31)
+#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32)
+#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33)
+#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34)
+#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35)
+#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36)
+#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37)
+#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38)
+#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39)
+#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40)
+#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41)
+#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42)
+#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43)
+#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44)
+#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45)
+#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46)
+#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47)
+#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48)
+#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49)
+#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50)
+#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51)
+#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52)
+#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53)
+#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54)
+#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55)
+#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56)
+#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57)
+#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58)
+#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59)
+#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60)
+#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61)
+#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62)
+#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63)
+
+#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1;
+#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
+
+/*!
+@brief macro
+@def NLOHMANN_DEFINE_TYPE_INTRUSIVE
+@since version 3.9.0
+*/
+#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...)  \
+    friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
+    friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
+
+/*!
+@brief macro
+@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
+@since version 3.9.0
+*/
+#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...)  \
+    inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
+    inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
+
+
+// inspired from https://stackoverflow.com/a/26745591
+// allows to call any std function as if (e.g. with begin):
+// using std::begin; begin(x);
+//
+// it allows using the detected idiom to retrieve the return type
+// of such an expression
+#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name)                                 \
+    namespace detail {                                                            \
+    using std::std_name;                                                          \
+    \
+    template<typename... T>                                                       \
+    using result_of_##std_name = decltype(std_name(std::declval<T>()...));        \
+    }                                                                             \
+    \
+    namespace detail2 {                                                           \
+    struct std_name##_tag                                                         \
+    {                                                                             \
+    };                                                                            \
+    \
+    template<typename... T>                                                       \
+    std_name##_tag std_name(T&&...);                                              \
+    \
+    template<typename... T>                                                       \
+    using result_of_##std_name = decltype(std_name(std::declval<T>()...));        \
+    \
+    template<typename... T>                                                       \
+    struct would_call_std_##std_name                                              \
+    {                                                                             \
+        static constexpr auto const value = ::nlohmann::detail::                  \
+                                            is_detected_exact<std_name##_tag, result_of_##std_name, T...>::value; \
+    };                                                                            \
+    } /* namespace detail2 */ \
+    \
+    template<typename... T>                                                       \
+    struct would_call_std_##std_name : detail2::would_call_std_##std_name<T...>   \
+    {                                                                             \
+    }
+
+#ifndef JSON_USE_IMPLICIT_CONVERSIONS
+    #define JSON_USE_IMPLICIT_CONVERSIONS 1
+#endif
+
+#if JSON_USE_IMPLICIT_CONVERSIONS
+    #define JSON_EXPLICIT
+#else
+    #define JSON_EXPLICIT explicit
+#endif
+
+#ifndef JSON_DIAGNOSTICS
+    #define JSON_DIAGNOSTICS 0
+#endif
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+/*!
+@brief replace all occurrences of a substring by another string
+
+@param[in,out] s  the string to manipulate; changed so that all
+               occurrences of @a f are replaced with @a t
+@param[in]     f  the substring to replace with @a t
+@param[in]     t  the string to replace @a f
+
+@pre The search string @a f must not be empty. **This precondition is
+enforced with an assertion.**
+
+@since version 2.0.0
+*/
+inline void replace_substring(std::string& s, const std::string& f,
+                              const std::string& t)
+{
+    JSON_ASSERT(!f.empty());
+    for (auto pos = s.find(f);                // find first occurrence of f
+            pos != std::string::npos;         // make sure f was found
+            s.replace(pos, f.size(), t),      // replace with t, and
+            pos = s.find(f, pos + t.size()))  // find next occurrence of f
+    {}
+}
+
+/*!
+ * @brief string escaping as described in RFC 6901 (Sect. 4)
+ * @param[in] s string to escape
+ * @return    escaped string
+ *
+ * Note the order of escaping "~" to "~0" and "/" to "~1" is important.
+ */
+inline std::string escape(std::string s)
+{
+    replace_substring(s, "~", "~0");
+    replace_substring(s, "/", "~1");
+    return s;
+}
+
+/*!
+ * @brief string unescaping as described in RFC 6901 (Sect. 4)
+ * @param[in] s string to unescape
+ * @return    unescaped string
+ *
+ * Note the order of escaping "~1" to "/" and "~0" to "~" is important.
+ */
+static void unescape(std::string& s)
+{
+    replace_substring(s, "~1", "/");
+    replace_substring(s, "~0", "~");
+}
+
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/input/position_t.hpp>
+
+
+#include <cstddef> // size_t
+
+namespace nlohmann
+{
+namespace detail
+{
+/// struct to capture the start position of the current token
+struct position_t
+{
+    /// the total number of characters read
+    std::size_t chars_read_total = 0;
+    /// the number of characters read in the current line
+    std::size_t chars_read_current_line = 0;
+    /// the number of lines read
+    std::size_t lines_read = 0;
+
+    /// conversion to size_t to preserve SAX interface
+    constexpr operator size_t() const
+    {
+        return chars_read_total;
+    }
+};
+
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+////////////////
+// exceptions //
+////////////////
+
+/// @brief general exception of the @ref basic_json class
+/// @sa https://json.nlohmann.me/api/basic_json/exception/
+class exception : public std::exception
+{
+  public:
+    /// returns the explanatory string
+    const char* what() const noexcept override
+    {
+        return m.what();
+    }
+
+    /// the id of the exception
+    const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
+
+  protected:
+    JSON_HEDLEY_NON_NULL(3)
+    exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing)
+
+    static std::string name(const std::string& ename, int id_)
+    {
+        return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
+    }
+
+    template<typename BasicJsonType>
+    static std::string diagnostics(const BasicJsonType& leaf_element)
+    {
+#if JSON_DIAGNOSTICS
+        std::vector<std::string> tokens;
+        for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent)
+        {
+            switch (current->m_parent->type())
+            {
+                case value_t::array:
+                {
+                    for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i)
+                    {
+                        if (&current->m_parent->m_value.array->operator[](i) == current)
+                        {
+                            tokens.emplace_back(std::to_string(i));
+                            break;
+                        }
+                    }
+                    break;
+                }
+
+                case value_t::object:
+                {
+                    for (const auto& element : *current->m_parent->m_value.object)
+                    {
+                        if (&element.second == current)
+                        {
+                            tokens.emplace_back(element.first.c_str());
+                            break;
+                        }
+                    }
+                    break;
+                }
+
+                case value_t::null: // LCOV_EXCL_LINE
+                case value_t::string: // LCOV_EXCL_LINE
+                case value_t::boolean: // LCOV_EXCL_LINE
+                case value_t::number_integer: // LCOV_EXCL_LINE
+                case value_t::number_unsigned: // LCOV_EXCL_LINE
+                case value_t::number_float: // LCOV_EXCL_LINE
+                case value_t::binary: // LCOV_EXCL_LINE
+                case value_t::discarded: // LCOV_EXCL_LINE
+                default:   // LCOV_EXCL_LINE
+                    break; // LCOV_EXCL_LINE
+            }
+        }
+
+        if (tokens.empty())
+        {
+            return "";
+        }
+
+        return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},
+                                     [](const std::string & a, const std::string & b)
+        {
+            return a + "/" + detail::escape(b);
+        }) + ") ";
+#else
+        static_cast<void>(leaf_element);
+        return "";
+#endif
+    }
+
+  private:
+    /// an exception object as storage for error messages
+    std::runtime_error m;
+};
+
+/// @brief exception indicating a parse error
+/// @sa https://json.nlohmann.me/api/basic_json/parse_error/
+class parse_error : public exception
+{
+  public:
+    /*!
+    @brief create a parse error exception
+    @param[in] id_       the id of the exception
+    @param[in] pos       the position where the error occurred (or with
+                         chars_read_total=0 if the position cannot be
+                         determined)
+    @param[in] what_arg  the explanatory string
+    @return parse_error object
+    */
+    template<typename BasicJsonType>
+    static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("parse_error", id_) + "parse error" +
+                        position_string(pos) + ": " + exception::diagnostics(context) + what_arg;
+        return {id_, pos.chars_read_total, w.c_str()};
+    }
+
+    template<typename BasicJsonType>
+    static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("parse_error", id_) + "parse error" +
+                        (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
+                        ": " + exception::diagnostics(context) + what_arg;
+        return {id_, byte_, w.c_str()};
+    }
+
+    /*!
+    @brief byte index of the parse error
+
+    The byte index of the last read character in the input file.
+
+    @note For an input with n bytes, 1 is the index of the first character and
+          n+1 is the index of the terminating null byte or the end of file.
+          This also holds true when reading a byte vector (CBOR or MessagePack).
+    */
+    const std::size_t byte;
+
+  private:
+    parse_error(int id_, std::size_t byte_, const char* what_arg)
+        : exception(id_, what_arg), byte(byte_) {}
+
+    static std::string position_string(const position_t& pos)
+    {
+        return " at line " + std::to_string(pos.lines_read + 1) +
+               ", column " + std::to_string(pos.chars_read_current_line);
+    }
+};
+
+/// @brief exception indicating errors with iterators
+/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/
+class invalid_iterator : public exception
+{
+  public:
+    template<typename BasicJsonType>
+    static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg;
+        return {id_, w.c_str()};
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    invalid_iterator(int id_, const char* what_arg)
+        : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating executing a member function with a wrong type
+/// @sa https://json.nlohmann.me/api/basic_json/type_error/
+class type_error : public exception
+{
+  public:
+    template<typename BasicJsonType>
+    static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg;
+        return {id_, w.c_str()};
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating access out of the defined range
+/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/
+class out_of_range : public exception
+{
+  public:
+    template<typename BasicJsonType>
+    static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg;
+        return {id_, w.c_str()};
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+/// @brief exception indicating other library errors
+/// @sa https://json.nlohmann.me/api/basic_json/other_error/
+class other_error : public exception
+{
+  public:
+    template<typename BasicJsonType>
+    static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
+    {
+        std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg;
+        return {id_, w.c_str()};
+    }
+
+  private:
+    JSON_HEDLEY_NON_NULL(3)
+    other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
+};
+
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+
+#include <cstddef> // size_t
+#include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
+#include <utility> // index_sequence, make_index_sequence, index_sequence_for
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+template<typename T>
+using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
+
+#ifdef JSON_HAS_CPP_14
+
+// the following utilities are natively available in C++14
+using std::enable_if_t;
+using std::index_sequence;
+using std::make_index_sequence;
+using std::index_sequence_for;
+
+#else
+
+// alias templates to reduce boilerplate
+template<bool B, typename T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+
+// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h
+// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0.
+
+//// START OF CODE FROM GOOGLE ABSEIL
+
+// integer_sequence
+//
+// Class template representing a compile-time integer sequence. An instantiation
+// of `integer_sequence<T, Ints...>` has a sequence of integers encoded in its
+// type through its template arguments (which is a common need when
+// working with C++11 variadic templates). `absl::integer_sequence` is designed
+// to be a drop-in replacement for C++14's `std::integer_sequence`.
+//
+// Example:
+//
+//   template< class T, T... Ints >
+//   void user_function(integer_sequence<T, Ints...>);
+//
+//   int main()
+//   {
+//     // user_function's `T` will be deduced to `int` and `Ints...`
+//     // will be deduced to `0, 1, 2, 3, 4`.
+//     user_function(make_integer_sequence<int, 5>());
+//   }
+template <typename T, T... Ints>
+struct integer_sequence
+{
+    using value_type = T;
+    static constexpr std::size_t size() noexcept
+    {
+        return sizeof...(Ints);
+    }
+};
+
+// index_sequence
+//
+// A helper template for an `integer_sequence` of `size_t`,
+// `absl::index_sequence` is designed to be a drop-in replacement for C++14's
+// `std::index_sequence`.
+template <size_t... Ints>
+using index_sequence = integer_sequence<size_t, Ints...>;
+
+namespace utility_internal
+{
+
+template <typename Seq, size_t SeqSize, size_t Rem>
+struct Extend;
+
+// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency.
+template <typename T, T... Ints, size_t SeqSize>
+struct Extend<integer_sequence<T, Ints...>, SeqSize, 0>
+{
+    using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >;
+};
+
+template <typename T, T... Ints, size_t SeqSize>
+struct Extend<integer_sequence<T, Ints...>, SeqSize, 1>
+{
+    using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >;
+};
+
+// Recursion helper for 'make_integer_sequence<T, N>'.
+// 'Gen<T, N>::type' is an alias for 'integer_sequence<T, 0, 1, ... N-1>'.
+template <typename T, size_t N>
+struct Gen
+{
+    using type =
+        typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type;
+};
+
+template <typename T>
+struct Gen<T, 0>
+{
+    using type = integer_sequence<T>;
+};
+
+}  // namespace utility_internal
+
+// Compile-time sequences of integers
+
+// make_integer_sequence
+//
+// This template alias is equivalent to
+// `integer_sequence<int, 0, 1, ..., N-1>`, and is designed to be a drop-in
+// replacement for C++14's `std::make_integer_sequence`.
+template <typename T, T N>
+using make_integer_sequence = typename utility_internal::Gen<T, N>::type;
+
+// make_index_sequence
+//
+// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`,
+// and is designed to be a drop-in replacement for C++14's
+// `std::make_index_sequence`.
+template <size_t N>
+using make_index_sequence = make_integer_sequence<size_t, N>;
+
+// index_sequence_for
+//
+// Converts a typename pack into an index sequence of the same length, and
+// is designed to be a drop-in replacement for C++14's
+// `std::index_sequence_for()`
+template <typename... Ts>
+using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
+
+//// END OF CODE FROM GOOGLE ABSEIL
+
+#endif
+
+// dispatch utility (taken from ranges-v3)
+template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
+template<> struct priority_tag<0> {};
+
+// taken from ranges-v3
+template<typename T>
+struct static_const
+{
+    static constexpr T value{};
+};
+
+template<typename T>
+constexpr T static_const<T>::value; // NOLINT(readability-redundant-declaration)
+
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/identity_tag.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+// dispatching helper struct
+template <class T> struct identity_tag {};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+#include <limits> // numeric_limits
+#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
+#include <utility> // declval
+#include <tuple> // tuple
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+
+
+#include <iterator> // random_access_iterator_tag
+
+// #include <nlohmann/detail/meta/void_t.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename It, typename = void>
+struct iterator_types {};
+
+template<typename It>
+struct iterator_types <
+    It,
+    void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
+    typename It::reference, typename It::iterator_category >>
+{
+    using difference_type = typename It::difference_type;
+    using value_type = typename It::value_type;
+    using pointer = typename It::pointer;
+    using reference = typename It::reference;
+    using iterator_category = typename It::iterator_category;
+};
+
+// This is required as some compilers implement std::iterator_traits in a way that
+// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
+template<typename T, typename = void>
+struct iterator_traits
+{
+};
+
+template<typename T>
+struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
+            : iterator_types<T>
+{
+};
+
+template<typename T>
+struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
+{
+    using iterator_category = std::random_access_iterator_tag;
+    using value_type = T;
+    using difference_type = ptrdiff_t;
+    using pointer = T*;
+    using reference = T&;
+};
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/meta/call_std/begin.hpp>
+
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin);
+} // namespace nlohmann
+
+// #include <nlohmann/detail/meta/call_std/end.hpp>
+
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end);
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+// #include <nlohmann/json_fwd.hpp>
+#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
+#define INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+#include <cstdint> // int64_t, uint64_t
+#include <map> // map
+#include <memory> // allocator
+#include <string> // string
+#include <vector> // vector
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+namespace nlohmann
+{
+/*!
+@brief default JSONSerializer template argument
+
+This serializer ignores the template arguments and uses ADL
+([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
+for serialization.
+*/
+template<typename T = void, typename SFINAE = void>
+struct adl_serializer;
+
+/// a class to store JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/
+template<template<typename U, typename V, typename... Args> class ObjectType =
+         std::map,
+         template<typename U, typename... Args> class ArrayType = std::vector,
+         class StringType = std::string, class BooleanType = bool,
+         class NumberIntegerType = std::int64_t,
+         class NumberUnsignedType = std::uint64_t,
+         class NumberFloatType = double,
+         template<typename U> class AllocatorType = std::allocator,
+         template<typename T, typename SFINAE = void> class JSONSerializer =
+         adl_serializer,
+         class BinaryType = std::vector<std::uint8_t>>
+class basic_json;
+
+/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
+/// @sa https://json.nlohmann.me/api/json_pointer/
+template<typename BasicJsonType>
+class json_pointer;
+
+/*!
+@brief default specialization
+@sa https://json.nlohmann.me/api/json/
+*/
+using json = basic_json<>;
+
+/// @brief a minimal map-like container that preserves insertion order
+/// @sa https://json.nlohmann.me/api/ordered_map/
+template<class Key, class T, class IgnoredLess, class Allocator>
+struct ordered_map;
+
+/// @brief specialization that maintains the insertion order of object keys
+/// @sa https://json.nlohmann.me/api/ordered_json/
+using ordered_json = basic_json<nlohmann::ordered_map>;
+
+}  // namespace nlohmann
+
+#endif  // INCLUDE_NLOHMANN_JSON_FWD_HPP_
+
+
+namespace nlohmann
+{
+/*!
+@brief detail namespace with internal helper functions
+
+This namespace collects functions that should not be exposed,
+implementations of some @ref basic_json methods, and meta-programming helpers.
+
+@since version 2.1.0
+*/
+namespace detail
+{
+/////////////
+// helpers //
+/////////////
+
+// Note to maintainers:
+//
+// Every trait in this file expects a non CV-qualified type.
+// The only exceptions are in the 'aliases for detected' section
+// (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
+//
+// In this case, T has to be properly CV-qualified to constraint the function arguments
+// (e.g. to_json(BasicJsonType&, const T&))
+
+template<typename> struct is_basic_json : std::false_type {};
+
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
+
+//////////////////////
+// json_ref helpers //
+//////////////////////
+
+template<typename>
+class json_ref;
+
+template<typename>
+struct is_json_ref : std::false_type {};
+
+template<typename T>
+struct is_json_ref<json_ref<T>> : std::true_type {};
+
+//////////////////////////
+// aliases for detected //
+//////////////////////////
+
+template<typename T>
+using mapped_type_t = typename T::mapped_type;
+
+template<typename T>
+using key_type_t = typename T::key_type;
+
+template<typename T>
+using value_type_t = typename T::value_type;
+
+template<typename T>
+using difference_type_t = typename T::difference_type;
+
+template<typename T>
+using pointer_t = typename T::pointer;
+
+template<typename T>
+using reference_t = typename T::reference;
+
+template<typename T>
+using iterator_category_t = typename T::iterator_category;
+
+template<typename T, typename... Args>
+using to_json_function = decltype(T::to_json(std::declval<Args>()...));
+
+template<typename T, typename... Args>
+using from_json_function = decltype(T::from_json(std::declval<Args>()...));
+
+template<typename T, typename U>
+using get_template_function = decltype(std::declval<T>().template get<U>());
+
+// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
+template<typename BasicJsonType, typename T, typename = void>
+struct has_from_json : std::false_type {};
+
+// trait checking if j.get<T> is valid
+// use this trait instead of std::is_constructible or std::is_convertible,
+// both rely on, or make use of implicit conversions, and thus fail when T
+// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958)
+template <typename BasicJsonType, typename T>
+struct is_getable
+{
+    static constexpr bool value = is_detected<get_template_function, const BasicJsonType&, T>::value;
+};
+
+template<typename BasicJsonType, typename T>
+struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<void, from_json_function, serializer,
+        const BasicJsonType&, T&>::value;
+};
+
+// This trait checks if JSONSerializer<T>::from_json(json const&) exists
+// this overload is used for non-default-constructible user-defined-types
+template<typename BasicJsonType, typename T, typename = void>
+struct has_non_default_from_json : std::false_type {};
+
+template<typename BasicJsonType, typename T>
+struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<T, from_json_function, serializer,
+        const BasicJsonType&>::value;
+};
+
+// This trait checks if BasicJsonType::json_serializer<T>::to_json exists
+// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
+template<typename BasicJsonType, typename T, typename = void>
+struct has_to_json : std::false_type {};
+
+template<typename BasicJsonType, typename T>
+struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
+{
+    using serializer = typename BasicJsonType::template json_serializer<T, void>;
+
+    static constexpr bool value =
+        is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
+        T>::value;
+};
+
+
+///////////////////
+// is_ functions //
+///////////////////
+
+// https://en.cppreference.com/w/cpp/types/conjunction
+template<class...> struct conjunction : std::true_type { };
+template<class B1> struct conjunction<B1> : B1 { };
+template<class B1, class... Bn>
+struct conjunction<B1, Bn...>
+: std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
+
+// https://en.cppreference.com/w/cpp/types/negation
+template<class B> struct negation : std::integral_constant < bool, !B::value > { };
+
+// Reimplementation of is_constructible and is_default_constructible, due to them being broken for
+// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367).
+// This causes compile errors in e.g. clang 3.5 or gcc 4.9.
+template <typename T>
+struct is_default_constructible : std::is_default_constructible<T> {};
+
+template <typename T1, typename T2>
+struct is_default_constructible<std::pair<T1, T2>>
+            : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
+
+template <typename T1, typename T2>
+struct is_default_constructible<const std::pair<T1, T2>>
+            : conjunction<is_default_constructible<T1>, is_default_constructible<T2>> {};
+
+template <typename... Ts>
+struct is_default_constructible<std::tuple<Ts...>>
+            : conjunction<is_default_constructible<Ts>...> {};
+
+template <typename... Ts>
+struct is_default_constructible<const std::tuple<Ts...>>
+            : conjunction<is_default_constructible<Ts>...> {};
+
+
+template <typename T, typename... Args>
+struct is_constructible : std::is_constructible<T, Args...> {};
+
+template <typename T1, typename T2>
+struct is_constructible<std::pair<T1, T2>> : is_default_constructible<std::pair<T1, T2>> {};
+
+template <typename T1, typename T2>
+struct is_constructible<const std::pair<T1, T2>> : is_default_constructible<const std::pair<T1, T2>> {};
+
+template <typename... Ts>
+struct is_constructible<std::tuple<Ts...>> : is_default_constructible<std::tuple<Ts...>> {};
+
+template <typename... Ts>
+struct is_constructible<const std::tuple<Ts...>> : is_default_constructible<const std::tuple<Ts...>> {};
+
+
+template<typename T, typename = void>
+struct is_iterator_traits : std::false_type {};
+
+template<typename T>
+struct is_iterator_traits<iterator_traits<T>>
+{
+  private:
+    using traits = iterator_traits<T>;
+
+  public:
+    static constexpr auto value =
+        is_detected<value_type_t, traits>::value &&
+        is_detected<difference_type_t, traits>::value &&
+        is_detected<pointer_t, traits>::value &&
+        is_detected<iterator_category_t, traits>::value &&
+        is_detected<reference_t, traits>::value;
+};
+
+template<typename T>
+struct is_range
+{
+  private:
+    using t_ref = typename std::add_lvalue_reference<T>::type;
+
+    using iterator = detected_t<result_of_begin, t_ref>;
+    using sentinel = detected_t<result_of_end, t_ref>;
+
+    // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator
+    // and https://en.cppreference.com/w/cpp/iterator/sentinel_for
+    // but reimplementing these would be too much work, as a lot of other concepts are used underneath
+    static constexpr auto is_iterator_begin =
+        is_iterator_traits<iterator_traits<iterator>>::value;
+
+  public:
+    static constexpr bool value = !std::is_same<iterator, nonesuch>::value && !std::is_same<sentinel, nonesuch>::value && is_iterator_begin;
+};
+
+template<typename R>
+using iterator_t = enable_if_t<is_range<R>::value, result_of_begin<decltype(std::declval<R&>())>>;
+
+template<typename T>
+using range_value_t = value_type_t<iterator_traits<iterator_t<T>>>;
+
+// The following implementation of is_complete_type is taken from
+// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/
+// and is written by Xiang Fan who agreed to using it in this library.
+
+template<typename T, typename = void>
+struct is_complete_type : std::false_type {};
+
+template<typename T>
+struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
+
+template<typename BasicJsonType, typename CompatibleObjectType,
+         typename = void>
+struct is_compatible_object_type_impl : std::false_type {};
+
+template<typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type_impl <
+    BasicJsonType, CompatibleObjectType,
+    enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
+    is_detected<key_type_t, CompatibleObjectType>::value >>
+{
+    using object_t = typename BasicJsonType::object_t;
+
+    // macOS's is_constructible does not play well with nonesuch...
+    static constexpr bool value =
+        is_constructible<typename object_t::key_type,
+        typename CompatibleObjectType::key_type>::value &&
+        is_constructible<typename object_t::mapped_type,
+        typename CompatibleObjectType::mapped_type>::value;
+};
+
+template<typename BasicJsonType, typename CompatibleObjectType>
+struct is_compatible_object_type
+    : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
+
+template<typename BasicJsonType, typename ConstructibleObjectType,
+         typename = void>
+struct is_constructible_object_type_impl : std::false_type {};
+
+template<typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type_impl <
+    BasicJsonType, ConstructibleObjectType,
+    enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
+    is_detected<key_type_t, ConstructibleObjectType>::value >>
+{
+    using object_t = typename BasicJsonType::object_t;
+
+    static constexpr bool value =
+        (is_default_constructible<ConstructibleObjectType>::value &&
+         (std::is_move_assignable<ConstructibleObjectType>::value ||
+          std::is_copy_assignable<ConstructibleObjectType>::value) &&
+         (is_constructible<typename ConstructibleObjectType::key_type,
+          typename object_t::key_type>::value &&
+          std::is_same <
+          typename object_t::mapped_type,
+          typename ConstructibleObjectType::mapped_type >::value)) ||
+        (has_from_json<BasicJsonType,
+         typename ConstructibleObjectType::mapped_type>::value ||
+         has_non_default_from_json <
+         BasicJsonType,
+         typename ConstructibleObjectType::mapped_type >::value);
+};
+
+template<typename BasicJsonType, typename ConstructibleObjectType>
+struct is_constructible_object_type
+    : is_constructible_object_type_impl<BasicJsonType,
+      ConstructibleObjectType> {};
+
+template<typename BasicJsonType, typename CompatibleStringType>
+struct is_compatible_string_type
+{
+    static constexpr auto value =
+        is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
+};
+
+template<typename BasicJsonType, typename ConstructibleStringType>
+struct is_constructible_string_type
+{
+    static constexpr auto value =
+        is_constructible<ConstructibleStringType,
+        typename BasicJsonType::string_t>::value;
+};
+
+template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
+struct is_compatible_array_type_impl : std::false_type {};
+
+template<typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type_impl <
+    BasicJsonType, CompatibleArrayType,
+    enable_if_t <
+    is_detected<iterator_t, CompatibleArrayType>::value&&
+    is_iterator_traits<iterator_traits<detected_t<iterator_t, CompatibleArrayType>>>::value&&
+// special case for types like std::filesystem::path whose iterator's value_type are themselves
+// c.f. https://github.com/nlohmann/json/pull/3073
+    !std::is_same<CompatibleArrayType, detected_t<range_value_t, CompatibleArrayType>>::value >>
+{
+    static constexpr bool value =
+        is_constructible<BasicJsonType,
+        range_value_t<CompatibleArrayType>>::value;
+};
+
+template<typename BasicJsonType, typename CompatibleArrayType>
+struct is_compatible_array_type
+    : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
+
+template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
+struct is_constructible_array_type_impl : std::false_type {};
+
+template<typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl <
+    BasicJsonType, ConstructibleArrayType,
+    enable_if_t<std::is_same<ConstructibleArrayType,
+    typename BasicJsonType::value_type>::value >>
+            : std::true_type {};
+
+template<typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type_impl <
+    BasicJsonType, ConstructibleArrayType,
+    enable_if_t < !std::is_same<ConstructibleArrayType,
+    typename BasicJsonType::value_type>::value&&
+    !is_compatible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
+    is_default_constructible<ConstructibleArrayType>::value&&
+(std::is_move_assignable<ConstructibleArrayType>::value ||
+ std::is_copy_assignable<ConstructibleArrayType>::value)&&
+is_detected<iterator_t, ConstructibleArrayType>::value&&
+is_iterator_traits<iterator_traits<detected_t<iterator_t, ConstructibleArrayType>>>::value&&
+is_detected<range_value_t, ConstructibleArrayType>::value&&
+// special case for types like std::filesystem::path whose iterator's value_type are themselves
+// c.f. https://github.com/nlohmann/json/pull/3073
+!std::is_same<ConstructibleArrayType, detected_t<range_value_t, ConstructibleArrayType>>::value&&
+        is_complete_type <
+        detected_t<range_value_t, ConstructibleArrayType >>::value >>
+{
+    using value_type = range_value_t<ConstructibleArrayType>;
+
+    static constexpr bool value =
+        std::is_same<value_type,
+        typename BasicJsonType::array_t::value_type>::value ||
+        has_from_json<BasicJsonType,
+        value_type>::value ||
+        has_non_default_from_json <
+        BasicJsonType,
+        value_type >::value;
+};
+
+template<typename BasicJsonType, typename ConstructibleArrayType>
+struct is_constructible_array_type
+    : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
+
+template<typename RealIntegerType, typename CompatibleNumberIntegerType,
+         typename = void>
+struct is_compatible_integer_type_impl : std::false_type {};
+
+template<typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type_impl <
+    RealIntegerType, CompatibleNumberIntegerType,
+    enable_if_t < std::is_integral<RealIntegerType>::value&&
+    std::is_integral<CompatibleNumberIntegerType>::value&&
+    !std::is_same<bool, CompatibleNumberIntegerType>::value >>
+{
+    // is there an assert somewhere on overflows?
+    using RealLimits = std::numeric_limits<RealIntegerType>;
+    using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
+
+    static constexpr auto value =
+        is_constructible<RealIntegerType,
+        CompatibleNumberIntegerType>::value &&
+        CompatibleLimits::is_integer &&
+        RealLimits::is_signed == CompatibleLimits::is_signed;
+};
+
+template<typename RealIntegerType, typename CompatibleNumberIntegerType>
+struct is_compatible_integer_type
+    : is_compatible_integer_type_impl<RealIntegerType,
+      CompatibleNumberIntegerType> {};
+
+template<typename BasicJsonType, typename CompatibleType, typename = void>
+struct is_compatible_type_impl: std::false_type {};
+
+template<typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type_impl <
+    BasicJsonType, CompatibleType,
+    enable_if_t<is_complete_type<CompatibleType>::value >>
+{
+    static constexpr bool value =
+        has_to_json<BasicJsonType, CompatibleType>::value;
+};
+
+template<typename BasicJsonType, typename CompatibleType>
+struct is_compatible_type
+    : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
+
+template<typename T1, typename T2>
+struct is_constructible_tuple : std::false_type {};
+
+template<typename T1, typename... Args>
+struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<is_constructible<T1, Args>...> {};
+
+// a naive helper to check if a type is an ordered_map (exploits the fact that
+// ordered_map inherits capacity() from std::vector)
+template <typename T>
+struct is_ordered_map
+{
+    using one = char;
+
+    struct two
+    {
+        char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+    };
+
+    template <typename C> static one test( decltype(&C::capacity) ) ;
+    template <typename C> static two test(...);
+
+    enum { value = sizeof(test<T>(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+};
+
+// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
+template < typename T, typename U, enable_if_t < !std::is_same<T, U>::value, int > = 0 >
+T conditional_static_cast(U value)
+{
+    return static_cast<T>(value);
+}
+
+template<typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
+T conditional_static_cast(U value)
+{
+    return value;
+}
+
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+#if JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#include <experimental/filesystem>
+namespace nlohmann::detail
+{
+namespace std_fs = std::experimental::filesystem;
+} // namespace nlohmann::detail
+#elif JSON_HAS_FILESYSTEM
+#include <filesystem>
+namespace nlohmann::detail
+{
+namespace std_fs = std::filesystem;
+} // namespace nlohmann::detail
+#endif
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
+    {
+        JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j));
+    }
+    n = nullptr;
+}
+
+// overloads for basic_json template parameters
+template < typename BasicJsonType, typename ArithmeticType,
+           enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
+                         !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+                         int > = 0 >
+void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
+{
+    switch (static_cast<value_t>(j))
+    {
+        case value_t::number_unsigned:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+            break;
+        }
+        case value_t::number_integer:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+            break;
+        }
+        case value_t::number_float:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+            break;
+        }
+
+        case value_t::null:
+        case value_t::object:
+        case value_t::array:
+        case value_t::string:
+        case value_t::boolean:
+        case value_t::binary:
+        case value_t::discarded:
+        default:
+            JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
+    }
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
+    {
+        JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j));
+    }
+    b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
+    {
+        JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
+    }
+    s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template <
+    typename BasicJsonType, typename ConstructibleStringType,
+    enable_if_t <
+        is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
+        !std::is_same<typename BasicJsonType::string_t,
+                      ConstructibleStringType>::value,
+        int > = 0 >
+void from_json(const BasicJsonType& j, ConstructibleStringType& s)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
+    {
+        JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
+    }
+
+    s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
+{
+    get_arithmetic_value(j, val);
+}
+
+template<typename BasicJsonType, typename EnumType,
+         enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+void from_json(const BasicJsonType& j, EnumType& e)
+{
+    typename std::underlying_type<EnumType>::type val;
+    get_arithmetic_value(j, val);
+    e = static_cast<EnumType>(val);
+}
+
+// forward_list doesn't have an insert method
+template<typename BasicJsonType, typename T, typename Allocator,
+         enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
+void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+    l.clear();
+    std::transform(j.rbegin(), j.rend(),
+                   std::front_inserter(l), [](const BasicJsonType & i)
+    {
+        return i.template get<T>();
+    });
+}
+
+// valarray doesn't have an insert method
+template<typename BasicJsonType, typename T,
+         enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
+void from_json(const BasicJsonType& j, std::valarray<T>& l)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+    l.resize(j.size());
+    std::transform(j.begin(), j.end(), std::begin(l),
+                   [](const BasicJsonType & elem)
+    {
+        return elem.template get<T>();
+    });
+}
+
+template<typename BasicJsonType, typename T, std::size_t N>
+auto from_json(const BasicJsonType& j, T (&arr)[N])  // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+-> decltype(j.template get<T>(), void())
+{
+    for (std::size_t i = 0; i < N; ++i)
+    {
+        arr[i] = j.at(i).template get<T>();
+    }
+}
+
+template<typename BasicJsonType>
+void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
+{
+    arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
+}
+
+template<typename BasicJsonType, typename T, std::size_t N>
+auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
+                          priority_tag<2> /*unused*/)
+-> decltype(j.template get<T>(), void())
+{
+    for (std::size_t i = 0; i < N; ++i)
+    {
+        arr[i] = j.at(i).template get<T>();
+    }
+}
+
+template<typename BasicJsonType, typename ConstructibleArrayType,
+         enable_if_t<
+             std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
+             int> = 0>
+auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
+-> decltype(
+    arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
+    j.template get<typename ConstructibleArrayType::value_type>(),
+    void())
+{
+    using std::end;
+
+    ConstructibleArrayType ret;
+    ret.reserve(j.size());
+    std::transform(j.begin(), j.end(),
+                   std::inserter(ret, end(ret)), [](const BasicJsonType & i)
+    {
+        // get<BasicJsonType>() returns *this, this won't call a from_json
+        // method when value_type is BasicJsonType
+        return i.template get<typename ConstructibleArrayType::value_type>();
+    });
+    arr = std::move(ret);
+}
+
+template<typename BasicJsonType, typename ConstructibleArrayType,
+         enable_if_t<
+             std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
+             int> = 0>
+void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
+                          priority_tag<0> /*unused*/)
+{
+    using std::end;
+
+    ConstructibleArrayType ret;
+    std::transform(
+        j.begin(), j.end(), std::inserter(ret, end(ret)),
+        [](const BasicJsonType & i)
+    {
+        // get<BasicJsonType>() returns *this, this won't call a from_json
+        // method when value_type is BasicJsonType
+        return i.template get<typename ConstructibleArrayType::value_type>();
+    });
+    arr = std::move(ret);
+}
+
+template < typename BasicJsonType, typename ConstructibleArrayType,
+           enable_if_t <
+               is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
+               !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
+               !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
+               !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
+               !is_basic_json<ConstructibleArrayType>::value,
+               int > = 0 >
+auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
+-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
+j.template get<typename ConstructibleArrayType::value_type>(),
+void())
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+
+    from_json_array_impl(j, arr, priority_tag<3> {});
+}
+
+template < typename BasicJsonType, typename T, std::size_t... Idx >
+std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(BasicJsonType&& j,
+        identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
+{
+    return { { std::forward<BasicJsonType>(j).at(Idx).template get<T>()... } };
+}
+
+template < typename BasicJsonType, typename T, std::size_t N >
+auto from_json(BasicJsonType&& j, identity_tag<std::array<T, N>> tag)
+-> decltype(from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {}))
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+
+    return from_json_inplace_array_impl(std::forward<BasicJsonType>(j), tag, make_index_sequence<N> {});
+}
+
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
+    {
+        JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j));
+    }
+
+    bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
+}
+
+template<typename BasicJsonType, typename ConstructibleObjectType,
+         enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
+void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
+    {
+        JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j));
+    }
+
+    ConstructibleObjectType ret;
+    const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
+    using value_type = typename ConstructibleObjectType::value_type;
+    std::transform(
+        inner_object->begin(), inner_object->end(),
+        std::inserter(ret, ret.begin()),
+        [](typename BasicJsonType::object_t::value_type const & p)
+    {
+        return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
+    });
+    obj = std::move(ret);
+}
+
+// overload for arithmetic types, not chosen for basic_json template arguments
+// (BooleanType, etc..); note: Is it really necessary to provide explicit
+// overloads for boolean_t etc. in case of a custom BooleanType which is not
+// an arithmetic type?
+template < typename BasicJsonType, typename ArithmeticType,
+           enable_if_t <
+               std::is_arithmetic<ArithmeticType>::value&&
+               !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
+               !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
+               !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
+               !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
+               int > = 0 >
+void from_json(const BasicJsonType& j, ArithmeticType& val)
+{
+    switch (static_cast<value_t>(j))
+    {
+        case value_t::number_unsigned:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
+            break;
+        }
+        case value_t::number_integer:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
+            break;
+        }
+        case value_t::number_float:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
+            break;
+        }
+        case value_t::boolean:
+        {
+            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
+            break;
+        }
+
+        case value_t::null:
+        case value_t::object:
+        case value_t::array:
+        case value_t::string:
+        case value_t::binary:
+        case value_t::discarded:
+        default:
+            JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j));
+    }
+}
+
+template<typename BasicJsonType, typename... Args, std::size_t... Idx>
+std::tuple<Args...> from_json_tuple_impl_base(BasicJsonType&& j, index_sequence<Idx...> /*unused*/)
+{
+    return std::make_tuple(std::forward<BasicJsonType>(j).at(Idx).template get<Args>()...);
+}
+
+template < typename BasicJsonType, class A1, class A2 >
+std::pair<A1, A2> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
+{
+    return {std::forward<BasicJsonType>(j).at(0).template get<A1>(),
+            std::forward<BasicJsonType>(j).at(1).template get<A2>()};
+}
+
+template<typename BasicJsonType, typename A1, typename A2>
+void from_json_tuple_impl(BasicJsonType&& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
+{
+    p = from_json_tuple_impl(std::forward<BasicJsonType>(j), identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
+}
+
+template<typename BasicJsonType, typename... Args>
+std::tuple<Args...> from_json_tuple_impl(BasicJsonType&& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
+{
+    return from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
+}
+
+template<typename BasicJsonType, typename... Args>
+void from_json_tuple_impl(BasicJsonType&& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
+{
+    t = from_json_tuple_impl_base<BasicJsonType, Args...>(std::forward<BasicJsonType>(j), index_sequence_for<Args...> {});
+}
+
+template<typename BasicJsonType, typename TupleRelated>
+auto from_json(BasicJsonType&& j, TupleRelated&& t)
+-> decltype(from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {}))
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+
+    return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
+}
+
+template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
+           typename = enable_if_t < !std::is_constructible <
+                                        typename BasicJsonType::string_t, Key >::value >>
+void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+    m.clear();
+    for (const auto& p : j)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
+        {
+            JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
+        }
+        m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+    }
+}
+
+template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
+           typename = enable_if_t < !std::is_constructible <
+                                        typename BasicJsonType::string_t, Key >::value >>
+void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
+    {
+        JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j));
+    }
+    m.clear();
+    for (const auto& p : j)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
+        {
+            JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j));
+        }
+        m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
+    }
+}
+
+#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
+template<typename BasicJsonType>
+void from_json(const BasicJsonType& j, std_fs::path& p)
+{
+    if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
+    {
+        JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j));
+    }
+    p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
+}
+#endif
+
+struct from_json_fn
+{
+    template<typename BasicJsonType, typename T>
+    auto operator()(const BasicJsonType& j, T&& val) const
+    noexcept(noexcept(from_json(j, std::forward<T>(val))))
+    -> decltype(from_json(j, std::forward<T>(val)))
+    {
+        return from_json(j, std::forward<T>(val));
+    }
+};
+}  // namespace detail
+
+/// namespace to hold default `from_json` function
+/// to see why this is required:
+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
+namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
+{
+constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; // NOLINT(misc-definitions-in-headers)
+} // namespace
+} // namespace nlohmann
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+
+
+#include <algorithm> // copy
+#include <iterator> // begin, end
+#include <string> // string
+#include <tuple> // tuple, get
+#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
+#include <utility> // move, forward, declval, pair
+#include <valarray> // valarray
+#include <vector> // vector
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+
+
+#include <cstddef> // size_t
+#include <iterator> // input_iterator_tag
+#include <string> // string, to_string
+#include <tuple> // tuple_size, get, tuple_element
+#include <utility> // move
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename string_type>
+void int_to_string( string_type& target, std::size_t value )
+{
+    // For ADL
+    using std::to_string;
+    target = to_string(value);
+}
+template<typename IteratorType> class iteration_proxy_value
+{
+  public:
+    using difference_type = std::ptrdiff_t;
+    using value_type = iteration_proxy_value;
+    using pointer = value_type * ;
+    using reference = value_type & ;
+    using iterator_category = std::input_iterator_tag;
+    using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
+
+  private:
+    /// the iterator
+    IteratorType anchor;
+    /// an index for arrays (used to create key names)
+    std::size_t array_index = 0;
+    /// last stringified array index
+    mutable std::size_t array_index_last = 0;
+    /// a string representation of the array index
+    mutable string_type array_index_str = "0";
+    /// an empty string (to return a reference for primitive values)
+    const string_type empty_str{};
+
+  public:
+    explicit iteration_proxy_value(IteratorType it) noexcept
+        : anchor(std::move(it))
+    {}
+
+    /// dereference operator (needed for range-based for)
+    iteration_proxy_value& operator*()
+    {
+        return *this;
+    }
+
+    /// increment operator (needed for range-based for)
+    iteration_proxy_value& operator++()
+    {
+        ++anchor;
+        ++array_index;
+
+        return *this;
+    }
+
+    /// equality operator (needed for InputIterator)
+    bool operator==(const iteration_proxy_value& o) const
+    {
+        return anchor == o.anchor;
+    }
+
+    /// inequality operator (needed for range-based for)
+    bool operator!=(const iteration_proxy_value& o) const
+    {
+        return anchor != o.anchor;
+    }
+
+    /// return key of the iterator
+    const string_type& key() const
+    {
+        JSON_ASSERT(anchor.m_object != nullptr);
+
+        switch (anchor.m_object->type())
+        {
+            // use integer array index as key
+            case value_t::array:
+            {
+                if (array_index != array_index_last)
+                {
+                    int_to_string( array_index_str, array_index );
+                    array_index_last = array_index;
+                }
+                return array_index_str;
+            }
+
+            // use key from the object
+            case value_t::object:
+                return anchor.key();
+
+            // use an empty key for all primitive types
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                return empty_str;
+        }
+    }
+
+    /// return value of the iterator
+    typename IteratorType::reference value() const
+    {
+        return anchor.value();
+    }
+};
+
+/// proxy class for the items() function
+template<typename IteratorType> class iteration_proxy
+{
+  private:
+    /// the container to iterate
+    typename IteratorType::reference container;
+
+  public:
+    /// construct iteration proxy from a container
+    explicit iteration_proxy(typename IteratorType::reference cont) noexcept
+        : container(cont) {}
+
+    /// return iterator begin (needed for range-based for)
+    iteration_proxy_value<IteratorType> begin() noexcept
+    {
+        return iteration_proxy_value<IteratorType>(container.begin());
+    }
+
+    /// return iterator end (needed for range-based for)
+    iteration_proxy_value<IteratorType> end() noexcept
+    {
+        return iteration_proxy_value<IteratorType>(container.end());
+    }
+};
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
+auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
+{
+    return i.key();
+}
+// Structured Bindings Support
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
+auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
+{
+    return i.value();
+}
+}  // namespace detail
+}  // namespace nlohmann
+
+// The Addition to the STD Namespace is required to add
+// Structured Bindings Support to the iteration_proxy_value class
+// For further reference see https://blog.tartanllama.xyz/structured-bindings/
+// And see https://github.com/nlohmann/json/pull/1391
+namespace std
+{
+#if defined(__clang__)
+    // Fix: https://github.com/nlohmann/json/issues/1401
+    #pragma clang diagnostic push
+    #pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template<typename IteratorType>
+class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
+            : public std::integral_constant<std::size_t, 2> {};
+
+template<std::size_t N, typename IteratorType>
+class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
+{
+  public:
+    using type = decltype(
+                     get<N>(std::declval <
+                            ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
+};
+#if defined(__clang__)
+    #pragma clang diagnostic pop
+#endif
+} // namespace std
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+#if JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#include <experimental/filesystem>
+namespace nlohmann::detail
+{
+namespace std_fs = std::experimental::filesystem;
+} // namespace nlohmann::detail
+#elif JSON_HAS_FILESYSTEM
+#include <filesystem>
+namespace nlohmann::detail
+{
+namespace std_fs = std::filesystem;
+} // namespace nlohmann::detail
+#endif
+
+namespace nlohmann
+{
+namespace detail
+{
+//////////////////
+// constructors //
+//////////////////
+
+/*
+ * Note all external_constructor<>::construct functions need to call
+ * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an
+ * allocated value (e.g., a string). See bug issue
+ * https://github.com/nlohmann/json/issues/2865 for more information.
+ */
+
+template<value_t> struct external_constructor;
+
+template<>
+struct external_constructor<value_t::boolean>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::boolean;
+        j.m_value = b;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::string>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::string;
+        j.m_value = s;
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::string;
+        j.m_value = std::move(s);
+        j.assert_invariant();
+    }
+
+    template < typename BasicJsonType, typename CompatibleStringType,
+               enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
+                             int > = 0 >
+    static void construct(BasicJsonType& j, const CompatibleStringType& str)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::string;
+        j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::binary>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::binary;
+        j.m_value = typename BasicJsonType::binary_t(b);
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::binary;
+        j.m_value = typename BasicJsonType::binary_t(std::move(b));
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_float>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::number_float;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_unsigned>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::number_unsigned;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::number_integer>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::number_integer;
+        j.m_value = val;
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::array>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::array;
+        j.m_value = arr;
+        j.set_parents();
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::array;
+        j.m_value = std::move(arr);
+        j.set_parents();
+        j.assert_invariant();
+    }
+
+    template < typename BasicJsonType, typename CompatibleArrayType,
+               enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
+                             int > = 0 >
+    static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
+    {
+        using std::begin;
+        using std::end;
+
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::array;
+        j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
+        j.set_parents();
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const std::vector<bool>& arr)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::array;
+        j.m_value = value_t::array;
+        j.m_value.array->reserve(arr.size());
+        for (const bool x : arr)
+        {
+            j.m_value.array->push_back(x);
+            j.set_parent(j.m_value.array->back());
+        }
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType, typename T,
+             enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+    static void construct(BasicJsonType& j, const std::valarray<T>& arr)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::array;
+        j.m_value = value_t::array;
+        j.m_value.array->resize(arr.size());
+        if (arr.size() > 0)
+        {
+            std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
+        }
+        j.set_parents();
+        j.assert_invariant();
+    }
+};
+
+template<>
+struct external_constructor<value_t::object>
+{
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::object;
+        j.m_value = obj;
+        j.set_parents();
+        j.assert_invariant();
+    }
+
+    template<typename BasicJsonType>
+    static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
+    {
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::object;
+        j.m_value = std::move(obj);
+        j.set_parents();
+        j.assert_invariant();
+    }
+
+    template < typename BasicJsonType, typename CompatibleObjectType,
+               enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
+    static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
+    {
+        using std::begin;
+        using std::end;
+
+        j.m_value.destroy(j.m_type);
+        j.m_type = value_t::object;
+        j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
+        j.set_parents();
+        j.assert_invariant();
+    }
+};
+
+/////////////
+// to_json //
+/////////////
+
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
+void to_json(BasicJsonType& j, T b) noexcept
+{
+    external_constructor<value_t::boolean>::construct(j, b);
+}
+
+template<typename BasicJsonType, typename CompatibleString,
+         enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
+void to_json(BasicJsonType& j, const CompatibleString& s)
+{
+    external_constructor<value_t::string>::construct(j, s);
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
+{
+    external_constructor<value_t::string>::construct(j, std::move(s));
+}
+
+template<typename BasicJsonType, typename FloatType,
+         enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
+void to_json(BasicJsonType& j, FloatType val) noexcept
+{
+    external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
+}
+
+template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
+         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
+void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
+{
+    external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
+}
+
+template<typename BasicJsonType, typename CompatibleNumberIntegerType,
+         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
+void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
+{
+    external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
+}
+
+template<typename BasicJsonType, typename EnumType,
+         enable_if_t<std::is_enum<EnumType>::value, int> = 0>
+void to_json(BasicJsonType& j, EnumType e) noexcept
+{
+    using underlying_type = typename std::underlying_type<EnumType>::type;
+    external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, const std::vector<bool>& e)
+{
+    external_constructor<value_t::array>::construct(j, e);
+}
+
+template < typename BasicJsonType, typename CompatibleArrayType,
+           enable_if_t < is_compatible_array_type<BasicJsonType,
+                         CompatibleArrayType>::value&&
+                         !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
+                         !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
+                         !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
+                         !is_basic_json<CompatibleArrayType>::value,
+                         int > = 0 >
+void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
+{
+    external_constructor<value_t::array>::construct(j, arr);
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
+{
+    external_constructor<value_t::binary>::construct(j, bin);
+}
+
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
+void to_json(BasicJsonType& j, const std::valarray<T>& arr)
+{
+    external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
+{
+    external_constructor<value_t::array>::construct(j, std::move(arr));
+}
+
+template < typename BasicJsonType, typename CompatibleObjectType,
+           enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
+void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
+{
+    external_constructor<value_t::object>::construct(j, obj);
+}
+
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
+{
+    external_constructor<value_t::object>::construct(j, std::move(obj));
+}
+
+template <
+    typename BasicJsonType, typename T, std::size_t N,
+    enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
+                  const T(&)[N]>::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+                  int > = 0 >
+void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+{
+    external_constructor<value_t::array>::construct(j, arr);
+}
+
+template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
+void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
+{
+    j = { p.first, p.second };
+}
+
+// for https://github.com/nlohmann/json/pull/1134
+template<typename BasicJsonType, typename T,
+         enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
+void to_json(BasicJsonType& j, const T& b)
+{
+    j = { {b.key(), b.value()} };
+}
+
+template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
+void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
+{
+    j = { std::get<Idx>(t)... };
+}
+
+template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
+void to_json(BasicJsonType& j, const T& t)
+{
+    to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
+}
+
+#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
+template<typename BasicJsonType>
+void to_json(BasicJsonType& j, const std_fs::path& p)
+{
+    j = p.string();
+}
+#endif
+
+struct to_json_fn
+{
+    template<typename BasicJsonType, typename T>
+    auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
+    -> decltype(to_json(j, std::forward<T>(val)), void())
+    {
+        return to_json(j, std::forward<T>(val));
+    }
+};
+}  // namespace detail
+
+/// namespace to hold default `to_json` function
+/// to see why this is required:
+/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
+namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces)
+{
+constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; // NOLINT(misc-definitions-in-headers)
+} // namespace
+} // namespace nlohmann
+
+// #include <nlohmann/detail/meta/identity_tag.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+namespace nlohmann
+{
+
+/// @sa https://json.nlohmann.me/api/adl_serializer/
+template<typename ValueType, typename>
+struct adl_serializer
+{
+    /// @brief convert a JSON value to any value type
+    /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
+    template<typename BasicJsonType, typename TargetType = ValueType>
+    static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
+        noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
+    -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
+    {
+        ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
+    }
+
+    /// @brief convert a JSON value to any value type
+    /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/
+    template<typename BasicJsonType, typename TargetType = ValueType>
+    static auto from_json(BasicJsonType && j) noexcept(
+    noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
+    -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
+    {
+        return ::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {});
+    }
+
+    /// @brief convert any value type to a JSON value
+    /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/
+    template<typename BasicJsonType, typename TargetType = ValueType>
+    static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
+        noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
+    -> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
+    {
+        ::nlohmann::to_json(j, std::forward<TargetType>(val));
+    }
+};
+}  // namespace nlohmann
+
+// #include <nlohmann/byte_container_with_subtype.hpp>
+
+
+#include <cstdint> // uint8_t, uint64_t
+#include <tuple> // tie
+#include <utility> // move
+
+namespace nlohmann
+{
+
+/// @brief an internal type for a backed binary type
+/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/
+template<typename BinaryType>
+class byte_container_with_subtype : public BinaryType
+{
+  public:
+    using container_type = BinaryType;
+    using subtype_type = std::uint64_t;
+
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+    byte_container_with_subtype() noexcept(noexcept(container_type()))
+        : container_type()
+    {}
+
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+    byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
+        : container_type(b)
+    {}
+
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+    byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
+        : container_type(std::move(b))
+    {}
+
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+    byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b)))
+        : container_type(b)
+        , m_subtype(subtype_)
+        , m_has_subtype(true)
+    {}
+
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/
+    byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b))))
+        : container_type(std::move(b))
+        , m_subtype(subtype_)
+        , m_has_subtype(true)
+    {}
+
+    bool operator==(const byte_container_with_subtype& rhs) const
+    {
+        return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
+               std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
+    }
+
+    bool operator!=(const byte_container_with_subtype& rhs) const
+    {
+        return !(rhs == *this);
+    }
+
+    /// @brief sets the binary subtype
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/
+    void set_subtype(subtype_type subtype_) noexcept
+    {
+        m_subtype = subtype_;
+        m_has_subtype = true;
+    }
+
+    /// @brief return the binary subtype
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/
+    constexpr subtype_type subtype() const noexcept
+    {
+        return m_has_subtype ? m_subtype : static_cast<subtype_type>(-1);
+    }
+
+    /// @brief return whether the value has a subtype
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/
+    constexpr bool has_subtype() const noexcept
+    {
+        return m_has_subtype;
+    }
+
+    /// @brief clears the binary subtype
+    /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/
+    void clear_subtype() noexcept
+    {
+        m_subtype = 0;
+        m_has_subtype = false;
+    }
+
+  private:
+    subtype_type m_subtype = 0;
+    bool m_has_subtype = false;
+};
+
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/conversions/from_json.hpp>
+
+// #include <nlohmann/detail/conversions/to_json.hpp>
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/hash.hpp>
+
+
+#include <cstdint> // uint8_t
+#include <cstddef> // size_t
+#include <functional> // hash
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+// boost::hash_combine
+inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
+{
+    seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
+    return seed;
+}
+
+/*!
+@brief hash a JSON value
+
+The hash function tries to rely on std::hash where possible. Furthermore, the
+type of the JSON value is taken into account to have different hash values for
+null, 0, 0U, and false, etc.
+
+@tparam BasicJsonType basic_json specialization
+@param j JSON value to hash
+@return hash value of j
+*/
+template<typename BasicJsonType>
+std::size_t hash(const BasicJsonType& j)
+{
+    using string_t = typename BasicJsonType::string_t;
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+
+    const auto type = static_cast<std::size_t>(j.type());
+    switch (j.type())
+    {
+        case BasicJsonType::value_t::null:
+        case BasicJsonType::value_t::discarded:
+        {
+            return combine(type, 0);
+        }
+
+        case BasicJsonType::value_t::object:
+        {
+            auto seed = combine(type, j.size());
+            for (const auto& element : j.items())
+            {
+                const auto h = std::hash<string_t> {}(element.key());
+                seed = combine(seed, h);
+                seed = combine(seed, hash(element.value()));
+            }
+            return seed;
+        }
+
+        case BasicJsonType::value_t::array:
+        {
+            auto seed = combine(type, j.size());
+            for (const auto& element : j)
+            {
+                seed = combine(seed, hash(element));
+            }
+            return seed;
+        }
+
+        case BasicJsonType::value_t::string:
+        {
+            const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
+            return combine(type, h);
+        }
+
+        case BasicJsonType::value_t::boolean:
+        {
+            const auto h = std::hash<bool> {}(j.template get<bool>());
+            return combine(type, h);
+        }
+
+        case BasicJsonType::value_t::number_integer:
+        {
+            const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
+            return combine(type, h);
+        }
+
+        case BasicJsonType::value_t::number_unsigned:
+        {
+            const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
+            return combine(type, h);
+        }
+
+        case BasicJsonType::value_t::number_float:
+        {
+            const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
+            return combine(type, h);
+        }
+
+        case BasicJsonType::value_t::binary:
+        {
+            auto seed = combine(type, j.get_binary().size());
+            const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
+            seed = combine(seed, h);
+            seed = combine(seed, static_cast<std::size_t>(j.get_binary().subtype()));
+            for (const auto byte : j.get_binary())
+            {
+                seed = combine(seed, std::hash<std::uint8_t> {}(byte));
+            }
+            return seed;
+        }
+
+        default:                   // LCOV_EXCL_LINE
+            JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+            return 0;              // LCOV_EXCL_LINE
+    }
+}
+
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+
+
+#include <algorithm> // generate_n
+#include <array> // array
+#include <cmath> // ldexp
+#include <cstddef> // size_t
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstdio> // snprintf
+#include <cstring> // memcpy
+#include <iterator> // back_inserter
+#include <limits> // numeric_limits
+#include <string> // char_traits, string
+#include <utility> // make_pair, move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+
+#include <array> // array
+#include <cstddef> // size_t
+#include <cstring> // strlen
+#include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
+#include <memory> // shared_ptr, make_shared, addressof
+#include <numeric> // accumulate
+#include <string> // string, char_traits
+#include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
+#include <utility> // pair, declval
+
+#ifndef JSON_NO_IO
+    #include <cstdio>   // FILE *
+    #include <istream>  // istream
+#endif                  // JSON_NO_IO
+
+// #include <nlohmann/detail/iterators/iterator_traits.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/// the supported input formats
+enum class input_format_t { json, cbor, msgpack, ubjson, bson };
+
+////////////////////
+// input adapters //
+////////////////////
+
+#ifndef JSON_NO_IO
+/*!
+Input adapter for stdio file access. This adapter read only 1 byte and do not use any
+ buffer. This adapter is a very low level adapter.
+*/
+class file_input_adapter
+{
+  public:
+    using char_type = char;
+
+    JSON_HEDLEY_NON_NULL(2)
+    explicit file_input_adapter(std::FILE* f) noexcept
+        : m_file(f)
+    {}
+
+    // make class move-only
+    file_input_adapter(const file_input_adapter&) = delete;
+    file_input_adapter(file_input_adapter&&) noexcept = default;
+    file_input_adapter& operator=(const file_input_adapter&) = delete;
+    file_input_adapter& operator=(file_input_adapter&&) = delete;
+    ~file_input_adapter() = default;
+
+    std::char_traits<char>::int_type get_character() noexcept
+    {
+        return std::fgetc(m_file);
+    }
+
+  private:
+    /// the file pointer to read from
+    std::FILE* m_file;
+};
+
+
+/*!
+Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
+beginning of input. Does not support changing the underlying std::streambuf
+in mid-input. Maintains underlying std::istream and std::streambuf to support
+subsequent use of standard std::istream operations to process any input
+characters following those used in parsing the JSON input.  Clears the
+std::istream flags; any input errors (e.g., EOF) will be detected by the first
+subsequent call for input from the std::istream.
+*/
+class input_stream_adapter
+{
+  public:
+    using char_type = char;
+
+    ~input_stream_adapter()
+    {
+        // clear stream flags; we use underlying streambuf I/O, do not
+        // maintain ifstream flags, except eof
+        if (is != nullptr)
+        {
+            is->clear(is->rdstate() & std::ios::eofbit);
+        }
+    }
+
+    explicit input_stream_adapter(std::istream& i)
+        : is(&i), sb(i.rdbuf())
+    {}
+
+    // delete because of pointer members
+    input_stream_adapter(const input_stream_adapter&) = delete;
+    input_stream_adapter& operator=(input_stream_adapter&) = delete;
+    input_stream_adapter& operator=(input_stream_adapter&&) = delete;
+
+    input_stream_adapter(input_stream_adapter&& rhs) noexcept
+        : is(rhs.is), sb(rhs.sb)
+    {
+        rhs.is = nullptr;
+        rhs.sb = nullptr;
+    }
+
+    // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
+    // ensure that std::char_traits<char>::eof() and the character 0xFF do not
+    // end up as the same value, e.g. 0xFFFFFFFF.
+    std::char_traits<char>::int_type get_character()
+    {
+        auto res = sb->sbumpc();
+        // set eof manually, as we don't use the istream interface.
+        if (JSON_HEDLEY_UNLIKELY(res == std::char_traits<char>::eof()))
+        {
+            is->clear(is->rdstate() | std::ios::eofbit);
+        }
+        return res;
+    }
+
+  private:
+    /// the associated input stream
+    std::istream* is = nullptr;
+    std::streambuf* sb = nullptr;
+};
+#endif  // JSON_NO_IO
+
+// General-purpose iterator-based adapter. It might not be as fast as
+// theoretically possible for some containers, but it is extremely versatile.
+template<typename IteratorType>
+class iterator_input_adapter
+{
+  public:
+    using char_type = typename std::iterator_traits<IteratorType>::value_type;
+
+    iterator_input_adapter(IteratorType first, IteratorType last)
+        : current(std::move(first)), end(std::move(last))
+    {}
+
+    typename std::char_traits<char_type>::int_type get_character()
+    {
+        if (JSON_HEDLEY_LIKELY(current != end))
+        {
+            auto result = std::char_traits<char_type>::to_int_type(*current);
+            std::advance(current, 1);
+            return result;
+        }
+
+        return std::char_traits<char_type>::eof();
+    }
+
+  private:
+    IteratorType current;
+    IteratorType end;
+
+    template<typename BaseInputAdapter, size_t T>
+    friend struct wide_string_input_helper;
+
+    bool empty() const
+    {
+        return current == end;
+    }
+};
+
+
+template<typename BaseInputAdapter, size_t T>
+struct wide_string_input_helper;
+
+template<typename BaseInputAdapter>
+struct wide_string_input_helper<BaseInputAdapter, 4>
+{
+    // UTF-32
+    static void fill_buffer(BaseInputAdapter& input,
+                            std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+                            size_t& utf8_bytes_index,
+                            size_t& utf8_bytes_filled)
+    {
+        utf8_bytes_index = 0;
+
+        if (JSON_HEDLEY_UNLIKELY(input.empty()))
+        {
+            utf8_bytes[0] = std::char_traits<char>::eof();
+            utf8_bytes_filled = 1;
+        }
+        else
+        {
+            // get the current character
+            const auto wc = input.get_character();
+
+            // UTF-32 to UTF-8 encoding
+            if (wc < 0x80)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+            else if (wc <= 0x7FF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+                utf8_bytes_filled = 2;
+            }
+            else if (wc <= 0xFFFF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+                utf8_bytes_filled = 3;
+            }
+            else if (wc <= 0x10FFFF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+                utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+                utf8_bytes_filled = 4;
+            }
+            else
+            {
+                // unknown character
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+        }
+    }
+};
+
+template<typename BaseInputAdapter>
+struct wide_string_input_helper<BaseInputAdapter, 2>
+{
+    // UTF-16
+    static void fill_buffer(BaseInputAdapter& input,
+                            std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
+                            size_t& utf8_bytes_index,
+                            size_t& utf8_bytes_filled)
+    {
+        utf8_bytes_index = 0;
+
+        if (JSON_HEDLEY_UNLIKELY(input.empty()))
+        {
+            utf8_bytes[0] = std::char_traits<char>::eof();
+            utf8_bytes_filled = 1;
+        }
+        else
+        {
+            // get the current character
+            const auto wc = input.get_character();
+
+            // UTF-16 to UTF-8 encoding
+            if (wc < 0x80)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                utf8_bytes_filled = 1;
+            }
+            else if (wc <= 0x7FF)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+                utf8_bytes_filled = 2;
+            }
+            else if (0xD800 > wc || wc >= 0xE000)
+            {
+                utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
+                utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
+                utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
+                utf8_bytes_filled = 3;
+            }
+            else
+            {
+                if (JSON_HEDLEY_UNLIKELY(!input.empty()))
+                {
+                    const auto wc2 = static_cast<unsigned int>(input.get_character());
+                    const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
+                    utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
+                    utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
+                    utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
+                    utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
+                    utf8_bytes_filled = 4;
+                }
+                else
+                {
+                    utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
+                    utf8_bytes_filled = 1;
+                }
+            }
+        }
+    }
+};
+
+// Wraps another input apdater to convert wide character types into individual bytes.
+template<typename BaseInputAdapter, typename WideCharType>
+class wide_string_input_adapter
+{
+  public:
+    using char_type = char;
+
+    wide_string_input_adapter(BaseInputAdapter base)
+        : base_adapter(base) {}
+
+    typename std::char_traits<char>::int_type get_character() noexcept
+    {
+        // check if buffer needs to be filled
+        if (utf8_bytes_index == utf8_bytes_filled)
+        {
+            fill_buffer<sizeof(WideCharType)>();
+
+            JSON_ASSERT(utf8_bytes_filled > 0);
+            JSON_ASSERT(utf8_bytes_index == 0);
+        }
+
+        // use buffer
+        JSON_ASSERT(utf8_bytes_filled > 0);
+        JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
+        return utf8_bytes[utf8_bytes_index++];
+    }
+
+  private:
+    BaseInputAdapter base_adapter;
+
+    template<size_t T>
+    void fill_buffer()
+    {
+        wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
+    }
+
+    /// a buffer for UTF-8 bytes
+    std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
+
+    /// index to the utf8_codes array for the next valid byte
+    std::size_t utf8_bytes_index = 0;
+    /// number of valid bytes in the utf8_codes array
+    std::size_t utf8_bytes_filled = 0;
+};
+
+
+template<typename IteratorType, typename Enable = void>
+struct iterator_input_adapter_factory
+{
+    using iterator_type = IteratorType;
+    using char_type = typename std::iterator_traits<iterator_type>::value_type;
+    using adapter_type = iterator_input_adapter<iterator_type>;
+
+    static adapter_type create(IteratorType first, IteratorType last)
+    {
+        return adapter_type(std::move(first), std::move(last));
+    }
+};
+
+template<typename T>
+struct is_iterator_of_multibyte
+{
+    using value_type = typename std::iterator_traits<T>::value_type;
+    enum
+    {
+        value = sizeof(value_type) > 1
+    };
+};
+
+template<typename IteratorType>
+struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
+{
+    using iterator_type = IteratorType;
+    using char_type = typename std::iterator_traits<iterator_type>::value_type;
+    using base_adapter_type = iterator_input_adapter<iterator_type>;
+    using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
+
+    static adapter_type create(IteratorType first, IteratorType last)
+    {
+        return adapter_type(base_adapter_type(std::move(first), std::move(last)));
+    }
+};
+
+// General purpose iterator-based input
+template<typename IteratorType>
+typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
+{
+    using factory_type = iterator_input_adapter_factory<IteratorType>;
+    return factory_type::create(first, last);
+}
+
+// Convenience shorthand from container to iterator
+// Enables ADL on begin(container) and end(container)
+// Encloses the using declarations in namespace for not to leak them to outside scope
+
+namespace container_input_adapter_factory_impl
+{
+
+using std::begin;
+using std::end;
+
+template<typename ContainerType, typename Enable = void>
+struct container_input_adapter_factory {};
+
+template<typename ContainerType>
+struct container_input_adapter_factory< ContainerType,
+       void_t<decltype(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>()))>>
+       {
+           using adapter_type = decltype(input_adapter(begin(std::declval<ContainerType>()), end(std::declval<ContainerType>())));
+
+           static adapter_type create(const ContainerType& container)
+{
+    return input_adapter(begin(container), end(container));
+}
+       };
+
+} // namespace container_input_adapter_factory_impl
+
+template<typename ContainerType>
+typename container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::adapter_type input_adapter(const ContainerType& container)
+{
+    return container_input_adapter_factory_impl::container_input_adapter_factory<ContainerType>::create(container);
+}
+
+#ifndef JSON_NO_IO
+// Special cases with fast paths
+inline file_input_adapter input_adapter(std::FILE* file)
+{
+    return file_input_adapter(file);
+}
+
+inline input_stream_adapter input_adapter(std::istream& stream)
+{
+    return input_stream_adapter(stream);
+}
+
+inline input_stream_adapter input_adapter(std::istream&& stream)
+{
+    return input_stream_adapter(stream);
+}
+#endif  // JSON_NO_IO
+
+using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
+
+// Null-delimited strings, and the like.
+template < typename CharT,
+           typename std::enable_if <
+               std::is_pointer<CharT>::value&&
+               !std::is_array<CharT>::value&&
+               std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
+               sizeof(typename std::remove_pointer<CharT>::type) == 1,
+               int >::type = 0 >
+contiguous_bytes_input_adapter input_adapter(CharT b)
+{
+    auto length = std::strlen(reinterpret_cast<const char*>(b));
+    const auto* ptr = reinterpret_cast<const char*>(b);
+    return input_adapter(ptr, ptr + length);
+}
+
+template<typename T, std::size_t N>
+auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+{
+    return input_adapter(array, array + N);
+}
+
+// This class only handles inputs of input_buffer_adapter type.
+// It's required so that expressions like {ptr, len} can be implicitly cast
+// to the correct adapter.
+class span_input_adapter
+{
+  public:
+    template < typename CharT,
+               typename std::enable_if <
+                   std::is_pointer<CharT>::value&&
+                   std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
+                   sizeof(typename std::remove_pointer<CharT>::type) == 1,
+                   int >::type = 0 >
+    span_input_adapter(CharT b, std::size_t l)
+        : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
+
+    template<class IteratorType,
+             typename std::enable_if<
+                 std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
+                 int>::type = 0>
+    span_input_adapter(IteratorType first, IteratorType last)
+        : ia(input_adapter(first, last)) {}
+
+    contiguous_bytes_input_adapter&& get()
+    {
+        return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg)
+    }
+
+  private:
+    contiguous_bytes_input_adapter ia;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+
+
+#include <cstddef>
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+
+/*!
+@brief SAX interface
+
+This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
+Each function is called in different situations while the input is parsed. The
+boolean return value informs the parser whether to continue processing the
+input.
+*/
+template<typename BasicJsonType>
+struct json_sax
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+
+    /*!
+    @brief a null value was read
+    @return whether parsing should proceed
+    */
+    virtual bool null() = 0;
+
+    /*!
+    @brief a boolean value was read
+    @param[in] val  boolean value
+    @return whether parsing should proceed
+    */
+    virtual bool boolean(bool val) = 0;
+
+    /*!
+    @brief an integer number was read
+    @param[in] val  integer value
+    @return whether parsing should proceed
+    */
+    virtual bool number_integer(number_integer_t val) = 0;
+
+    /*!
+    @brief an unsigned integer number was read
+    @param[in] val  unsigned integer value
+    @return whether parsing should proceed
+    */
+    virtual bool number_unsigned(number_unsigned_t val) = 0;
+
+    /*!
+    @brief a floating-point number was read
+    @param[in] val  floating-point value
+    @param[in] s    raw token value
+    @return whether parsing should proceed
+    */
+    virtual bool number_float(number_float_t val, const string_t& s) = 0;
+
+    /*!
+    @brief a string value was read
+    @param[in] val  string value
+    @return whether parsing should proceed
+    @note It is safe to move the passed string value.
+    */
+    virtual bool string(string_t& val) = 0;
+
+    /*!
+    @brief a binary value was read
+    @param[in] val  binary value
+    @return whether parsing should proceed
+    @note It is safe to move the passed binary value.
+    */
+    virtual bool binary(binary_t& val) = 0;
+
+    /*!
+    @brief the beginning of an object was read
+    @param[in] elements  number of object elements or -1 if unknown
+    @return whether parsing should proceed
+    @note binary formats may report the number of elements
+    */
+    virtual bool start_object(std::size_t elements) = 0;
+
+    /*!
+    @brief an object key was read
+    @param[in] val  object key
+    @return whether parsing should proceed
+    @note It is safe to move the passed string.
+    */
+    virtual bool key(string_t& val) = 0;
+
+    /*!
+    @brief the end of an object was read
+    @return whether parsing should proceed
+    */
+    virtual bool end_object() = 0;
+
+    /*!
+    @brief the beginning of an array was read
+    @param[in] elements  number of array elements or -1 if unknown
+    @return whether parsing should proceed
+    @note binary formats may report the number of elements
+    */
+    virtual bool start_array(std::size_t elements) = 0;
+
+    /*!
+    @brief the end of an array was read
+    @return whether parsing should proceed
+    */
+    virtual bool end_array() = 0;
+
+    /*!
+    @brief a parse error occurred
+    @param[in] position    the position in the input where the error occurs
+    @param[in] last_token  the last read token
+    @param[in] ex          an exception object describing the error
+    @return whether parsing should proceed (must return false)
+    */
+    virtual bool parse_error(std::size_t position,
+                             const std::string& last_token,
+                             const detail::exception& ex) = 0;
+
+    json_sax() = default;
+    json_sax(const json_sax&) = default;
+    json_sax(json_sax&&) noexcept = default;
+    json_sax& operator=(const json_sax&) = default;
+    json_sax& operator=(json_sax&&) noexcept = default;
+    virtual ~json_sax() = default;
+};
+
+
+namespace detail
+{
+/*!
+@brief SAX implementation to create a JSON value from SAX events
+
+This class implements the @ref json_sax interface and processes the SAX events
+to create a JSON value which makes it basically a DOM parser. The structure or
+hierarchy of the JSON value is managed by the stack `ref_stack` which contains
+a pointer to the respective array or object for each recursion depth.
+
+After successful parsing, the value that is passed by reference to the
+constructor contains the parsed value.
+
+@tparam BasicJsonType  the JSON type
+*/
+template<typename BasicJsonType>
+class json_sax_dom_parser
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+
+    /*!
+    @param[in,out] r  reference to a JSON value that is manipulated while
+                       parsing
+    @param[in] allow_exceptions_  whether parse errors yield exceptions
+    */
+    explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
+        : root(r), allow_exceptions(allow_exceptions_)
+    {}
+
+    // make class move-only
+    json_sax_dom_parser(const json_sax_dom_parser&) = delete;
+    json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
+    json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    ~json_sax_dom_parser() = default;
+
+    bool null()
+    {
+        handle_value(nullptr);
+        return true;
+    }
+
+    bool boolean(bool val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_integer(number_integer_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_float(number_float_t val, const string_t& /*unused*/)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool string(string_t& val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool binary(binary_t& val)
+    {
+        handle_value(std::move(val));
+        return true;
+    }
+
+    bool start_object(std::size_t len)
+    {
+        ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
+
+        if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
+        }
+
+        return true;
+    }
+
+    bool key(string_t& val)
+    {
+        // add null at given key and store the reference for later
+        object_element = &(ref_stack.back()->m_value.object->operator[](val));
+        return true;
+    }
+
+    bool end_object()
+    {
+        ref_stack.back()->set_parents();
+        ref_stack.pop_back();
+        return true;
+    }
+
+    bool start_array(std::size_t len)
+    {
+        ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
+
+        if (JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
+        }
+
+        return true;
+    }
+
+    bool end_array()
+    {
+        ref_stack.back()->set_parents();
+        ref_stack.pop_back();
+        return true;
+    }
+
+    template<class Exception>
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
+                     const Exception& ex)
+    {
+        errored = true;
+        static_cast<void>(ex);
+        if (allow_exceptions)
+        {
+            JSON_THROW(ex);
+        }
+        return false;
+    }
+
+    constexpr bool is_errored() const
+    {
+        return errored;
+    }
+
+  private:
+    /*!
+    @invariant If the ref stack is empty, then the passed value will be the new
+               root.
+    @invariant If the ref stack contains a value, then it is an array or an
+               object to which we can add elements
+    */
+    template<typename Value>
+    JSON_HEDLEY_RETURNS_NON_NULL
+    BasicJsonType* handle_value(Value&& v)
+    {
+        if (ref_stack.empty())
+        {
+            root = BasicJsonType(std::forward<Value>(v));
+            return &root;
+        }
+
+        JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
+
+        if (ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
+            return &(ref_stack.back()->m_value.array->back());
+        }
+
+        JSON_ASSERT(ref_stack.back()->is_object());
+        JSON_ASSERT(object_element);
+        *object_element = BasicJsonType(std::forward<Value>(v));
+        return object_element;
+    }
+
+    /// the parsed JSON value
+    BasicJsonType& root;
+    /// stack to model hierarchy of values
+    std::vector<BasicJsonType*> ref_stack {};
+    /// helper to hold the reference for the next object element
+    BasicJsonType* object_element = nullptr;
+    /// whether a syntax error occurred
+    bool errored = false;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+};
+
+template<typename BasicJsonType>
+class json_sax_dom_callback_parser
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+    using parser_callback_t = typename BasicJsonType::parser_callback_t;
+    using parse_event_t = typename BasicJsonType::parse_event_t;
+
+    json_sax_dom_callback_parser(BasicJsonType& r,
+                                 const parser_callback_t cb,
+                                 const bool allow_exceptions_ = true)
+        : root(r), callback(cb), allow_exceptions(allow_exceptions_)
+    {
+        keep_stack.push_back(true);
+    }
+
+    // make class move-only
+    json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
+    json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
+    json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    ~json_sax_dom_callback_parser() = default;
+
+    bool null()
+    {
+        handle_value(nullptr);
+        return true;
+    }
+
+    bool boolean(bool val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_integer(number_integer_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool number_float(number_float_t val, const string_t& /*unused*/)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool string(string_t& val)
+    {
+        handle_value(val);
+        return true;
+    }
+
+    bool binary(binary_t& val)
+    {
+        handle_value(std::move(val));
+        return true;
+    }
+
+    bool start_object(std::size_t len)
+    {
+        // check callback for object start
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
+        keep_stack.push_back(keep);
+
+        auto val = handle_value(BasicJsonType::value_t::object, true);
+        ref_stack.push_back(val.second);
+
+        // check object limit
+        if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back()));
+        }
+
+        return true;
+    }
+
+    bool key(string_t& val)
+    {
+        BasicJsonType k = BasicJsonType(val);
+
+        // check callback for key
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
+        key_keep_stack.push_back(keep);
+
+        // add discarded value at given key and store the reference for later
+        if (keep && ref_stack.back())
+        {
+            object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
+        }
+
+        return true;
+    }
+
+    bool end_object()
+    {
+        if (ref_stack.back())
+        {
+            if (!callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
+            {
+                // discard object
+                *ref_stack.back() = discarded;
+            }
+            else
+            {
+                ref_stack.back()->set_parents();
+            }
+        }
+
+        JSON_ASSERT(!ref_stack.empty());
+        JSON_ASSERT(!keep_stack.empty());
+        ref_stack.pop_back();
+        keep_stack.pop_back();
+
+        if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
+        {
+            // remove discarded value
+            for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
+            {
+                if (it->is_discarded())
+                {
+                    ref_stack.back()->erase(it);
+                    break;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    bool start_array(std::size_t len)
+    {
+        const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
+        keep_stack.push_back(keep);
+
+        auto val = handle_value(BasicJsonType::value_t::array, true);
+        ref_stack.push_back(val.second);
+
+        // check array limit
+        if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast<std::size_t>(-1) && len > ref_stack.back()->max_size()))
+        {
+            JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back()));
+        }
+
+        return true;
+    }
+
+    bool end_array()
+    {
+        bool keep = true;
+
+        if (ref_stack.back())
+        {
+            keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
+            if (keep)
+            {
+                ref_stack.back()->set_parents();
+            }
+            else
+            {
+                // discard array
+                *ref_stack.back() = discarded;
+            }
+        }
+
+        JSON_ASSERT(!ref_stack.empty());
+        JSON_ASSERT(!keep_stack.empty());
+        ref_stack.pop_back();
+        keep_stack.pop_back();
+
+        // remove discarded value
+        if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->pop_back();
+        }
+
+        return true;
+    }
+
+    template<class Exception>
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
+                     const Exception& ex)
+    {
+        errored = true;
+        static_cast<void>(ex);
+        if (allow_exceptions)
+        {
+            JSON_THROW(ex);
+        }
+        return false;
+    }
+
+    constexpr bool is_errored() const
+    {
+        return errored;
+    }
+
+  private:
+    /*!
+    @param[in] v  value to add to the JSON value we build during parsing
+    @param[in] skip_callback  whether we should skip calling the callback
+               function; this is required after start_array() and
+               start_object() SAX events, because otherwise we would call the
+               callback function with an empty array or object, respectively.
+
+    @invariant If the ref stack is empty, then the passed value will be the new
+               root.
+    @invariant If the ref stack contains a value, then it is an array or an
+               object to which we can add elements
+
+    @return pair of boolean (whether value should be kept) and pointer (to the
+            passed value in the ref_stack hierarchy; nullptr if not kept)
+    */
+    template<typename Value>
+    std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
+    {
+        JSON_ASSERT(!keep_stack.empty());
+
+        // do not handle this value if we know it would be added to a discarded
+        // container
+        if (!keep_stack.back())
+        {
+            return {false, nullptr};
+        }
+
+        // create value
+        auto value = BasicJsonType(std::forward<Value>(v));
+
+        // check callback
+        const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
+
+        // do not handle this value if we just learnt it shall be discarded
+        if (!keep)
+        {
+            return {false, nullptr};
+        }
+
+        if (ref_stack.empty())
+        {
+            root = std::move(value);
+            return {true, &root};
+        }
+
+        // skip this value if we already decided to skip the parent
+        // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
+        if (!ref_stack.back())
+        {
+            return {false, nullptr};
+        }
+
+        // we now only expect arrays and objects
+        JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
+
+        // array
+        if (ref_stack.back()->is_array())
+        {
+            ref_stack.back()->m_value.array->emplace_back(std::move(value));
+            return {true, &(ref_stack.back()->m_value.array->back())};
+        }
+
+        // object
+        JSON_ASSERT(ref_stack.back()->is_object());
+        // check if we should store an element for the current key
+        JSON_ASSERT(!key_keep_stack.empty());
+        const bool store_element = key_keep_stack.back();
+        key_keep_stack.pop_back();
+
+        if (!store_element)
+        {
+            return {false, nullptr};
+        }
+
+        JSON_ASSERT(object_element);
+        *object_element = std::move(value);
+        return {true, object_element};
+    }
+
+    /// the parsed JSON value
+    BasicJsonType& root;
+    /// stack to model hierarchy of values
+    std::vector<BasicJsonType*> ref_stack {};
+    /// stack to manage which values to keep
+    std::vector<bool> keep_stack {};
+    /// stack to manage which object keys to keep
+    std::vector<bool> key_keep_stack {};
+    /// helper to hold the reference for the next object element
+    BasicJsonType* object_element = nullptr;
+    /// whether a syntax error occurred
+    bool errored = false;
+    /// callback function
+    const parser_callback_t callback = nullptr;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+    /// a discarded value for the callback
+    BasicJsonType discarded = BasicJsonType::value_t::discarded;
+};
+
+template<typename BasicJsonType>
+class json_sax_acceptor
+{
+  public:
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+
+    bool null()
+    {
+        return true;
+    }
+
+    bool boolean(bool /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_integer(number_integer_t /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_unsigned(number_unsigned_t /*unused*/)
+    {
+        return true;
+    }
+
+    bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool string(string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool binary(binary_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool start_object(std::size_t /*unused*/ = static_cast<std::size_t>(-1))
+    {
+        return true;
+    }
+
+    bool key(string_t& /*unused*/)
+    {
+        return true;
+    }
+
+    bool end_object()
+    {
+        return true;
+    }
+
+    bool start_array(std::size_t /*unused*/ = static_cast<std::size_t>(-1))
+    {
+        return true;
+    }
+
+    bool end_array()
+    {
+        return true;
+    }
+
+    bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
+    {
+        return false;
+    }
+};
+}  // namespace detail
+
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+
+#include <array> // array
+#include <clocale> // localeconv
+#include <cstddef> // size_t
+#include <cstdio> // snprintf
+#include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
+#include <initializer_list> // initializer_list
+#include <string> // char_traits, string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/position_t.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////
+// lexer //
+///////////
+
+template<typename BasicJsonType>
+class lexer_base
+{
+  public:
+    /// token types for the parser
+    enum class token_type
+    {
+        uninitialized,    ///< indicating the scanner is uninitialized
+        literal_true,     ///< the `true` literal
+        literal_false,    ///< the `false` literal
+        literal_null,     ///< the `null` literal
+        value_string,     ///< a string -- use get_string() for actual value
+        value_unsigned,   ///< an unsigned integer -- use get_number_unsigned() for actual value
+        value_integer,    ///< a signed integer -- use get_number_integer() for actual value
+        value_float,      ///< an floating point number -- use get_number_float() for actual value
+        begin_array,      ///< the character for array begin `[`
+        begin_object,     ///< the character for object begin `{`
+        end_array,        ///< the character for array end `]`
+        end_object,       ///< the character for object end `}`
+        name_separator,   ///< the name separator `:`
+        value_separator,  ///< the value separator `,`
+        parse_error,      ///< indicating a parse error
+        end_of_input,     ///< indicating the end of the input buffer
+        literal_or_value  ///< a literal or the begin of a value (only for diagnostics)
+    };
+
+    /// return name of values of type token_type (only used for errors)
+    JSON_HEDLEY_RETURNS_NON_NULL
+    JSON_HEDLEY_CONST
+    static const char* token_type_name(const token_type t) noexcept
+    {
+        switch (t)
+        {
+            case token_type::uninitialized:
+                return "<uninitialized>";
+            case token_type::literal_true:
+                return "true literal";
+            case token_type::literal_false:
+                return "false literal";
+            case token_type::literal_null:
+                return "null literal";
+            case token_type::value_string:
+                return "string literal";
+            case token_type::value_unsigned:
+            case token_type::value_integer:
+            case token_type::value_float:
+                return "number literal";
+            case token_type::begin_array:
+                return "'['";
+            case token_type::begin_object:
+                return "'{'";
+            case token_type::end_array:
+                return "']'";
+            case token_type::end_object:
+                return "'}'";
+            case token_type::name_separator:
+                return "':'";
+            case token_type::value_separator:
+                return "','";
+            case token_type::parse_error:
+                return "<parse error>";
+            case token_type::end_of_input:
+                return "end of input";
+            case token_type::literal_or_value:
+                return "'[', '{', or a literal";
+            // LCOV_EXCL_START
+            default: // catch non-enum values
+                return "unknown token";
+                // LCOV_EXCL_STOP
+        }
+    }
+};
+/*!
+@brief lexical analysis
+
+This class organizes the lexical analysis during JSON deserialization.
+*/
+template<typename BasicJsonType, typename InputAdapterType>
+class lexer : public lexer_base<BasicJsonType>
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using char_type = typename InputAdapterType::char_type;
+    using char_int_type = typename std::char_traits<char_type>::int_type;
+
+  public:
+    using token_type = typename lexer_base<BasicJsonType>::token_type;
+
+    explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept
+        : ia(std::move(adapter))
+        , ignore_comments(ignore_comments_)
+        , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
+    {}
+
+    // delete because of pointer members
+    lexer(const lexer&) = delete;
+    lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    lexer& operator=(lexer&) = delete;
+    lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    ~lexer() = default;
+
+  private:
+    /////////////////////
+    // locales
+    /////////////////////
+
+    /// return the locale-dependent decimal point
+    JSON_HEDLEY_PURE
+    static char get_decimal_point() noexcept
+    {
+        const auto* loc = localeconv();
+        JSON_ASSERT(loc != nullptr);
+        return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
+    }
+
+    /////////////////////
+    // scan functions
+    /////////////////////
+
+    /*!
+    @brief get codepoint from 4 hex characters following `\u`
+
+    For input "\u c1 c2 c3 c4" the codepoint is:
+      (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
+    = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
+
+    Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
+    must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
+    conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
+    between the ASCII value of the character and the desired integer value.
+
+    @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
+            non-hex character)
+    */
+    int get_codepoint()
+    {
+        // this function only makes sense after reading `\u`
+        JSON_ASSERT(current == 'u');
+        int codepoint = 0;
+
+        const auto factors = { 12u, 8u, 4u, 0u };
+        for (const auto factor : factors)
+        {
+            get();
+
+            if (current >= '0' && current <= '9')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
+            }
+            else if (current >= 'A' && current <= 'F')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
+            }
+            else if (current >= 'a' && current <= 'f')
+            {
+                codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
+            }
+            else
+            {
+                return -1;
+            }
+        }
+
+        JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
+        return codepoint;
+    }
+
+    /*!
+    @brief check if the next byte(s) are inside a given range
+
+    Adds the current byte and, for each passed range, reads a new byte and
+    checks if it is inside the range. If a violation was detected, set up an
+    error message and return false. Otherwise, return true.
+
+    @param[in] ranges  list of integers; interpreted as list of pairs of
+                       inclusive lower and upper bound, respectively
+
+    @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
+         1, 2, or 3 pairs. This precondition is enforced by an assertion.
+
+    @return true if and only if no range violation was detected
+    */
+    bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
+    {
+        JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
+        add(current);
+
+        for (auto range = ranges.begin(); range != ranges.end(); ++range)
+        {
+            get();
+            if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
+            {
+                add(current);
+            }
+            else
+            {
+                error_message = "invalid string: ill-formed UTF-8 byte";
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /*!
+    @brief scan a string literal
+
+    This function scans a string according to Sect. 7 of RFC 8259. While
+    scanning, bytes are escaped and copied into buffer token_buffer. Then the
+    function returns successfully, token_buffer is *not* null-terminated (as it
+    may contain \0 bytes), and token_buffer.size() is the number of bytes in the
+    string.
+
+    @return token_type::value_string if string could be successfully scanned,
+            token_type::parse_error otherwise
+
+    @note In case of errors, variable error_message contains a textual
+          description.
+    */
+    token_type scan_string()
+    {
+        // reset token_buffer (ignore opening quote)
+        reset();
+
+        // we entered the function by reading an open quote
+        JSON_ASSERT(current == '\"');
+
+        while (true)
+        {
+            // get next character
+            switch (get())
+            {
+                // end of file while parsing string
+                case std::char_traits<char_type>::eof():
+                {
+                    error_message = "invalid string: missing closing quote";
+                    return token_type::parse_error;
+                }
+
+                // closing quote
+                case '\"':
+                {
+                    return token_type::value_string;
+                }
+
+                // escapes
+                case '\\':
+                {
+                    switch (get())
+                    {
+                        // quotation mark
+                        case '\"':
+                            add('\"');
+                            break;
+                        // reverse solidus
+                        case '\\':
+                            add('\\');
+                            break;
+                        // solidus
+                        case '/':
+                            add('/');
+                            break;
+                        // backspace
+                        case 'b':
+                            add('\b');
+                            break;
+                        // form feed
+                        case 'f':
+                            add('\f');
+                            break;
+                        // line feed
+                        case 'n':
+                            add('\n');
+                            break;
+                        // carriage return
+                        case 'r':
+                            add('\r');
+                            break;
+                        // tab
+                        case 't':
+                            add('\t');
+                            break;
+
+                        // unicode escapes
+                        case 'u':
+                        {
+                            const int codepoint1 = get_codepoint();
+                            int codepoint = codepoint1; // start with codepoint1
+
+                            if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
+                            {
+                                error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+                                return token_type::parse_error;
+                            }
+
+                            // check if code point is a high surrogate
+                            if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
+                            {
+                                // expect next \uxxxx entry
+                                if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
+                                {
+                                    const int codepoint2 = get_codepoint();
+
+                                    if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
+                                    {
+                                        error_message = "invalid string: '\\u' must be followed by 4 hex digits";
+                                        return token_type::parse_error;
+                                    }
+
+                                    // check if codepoint2 is a low surrogate
+                                    if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
+                                    {
+                                        // overwrite codepoint
+                                        codepoint = static_cast<int>(
+                                                        // high surrogate occupies the most significant 22 bits
+                                                        (static_cast<unsigned int>(codepoint1) << 10u)
+                                                        // low surrogate occupies the least significant 15 bits
+                                                        + static_cast<unsigned int>(codepoint2)
+                                                        // there is still the 0xD800, 0xDC00 and 0x10000 noise
+                                                        // in the result, so we have to subtract with:
+                                                        // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
+                                                        - 0x35FDC00u);
+                                    }
+                                    else
+                                    {
+                                        error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
+                                        return token_type::parse_error;
+                                    }
+                                }
+                                else
+                                {
+                                    error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
+                                    return token_type::parse_error;
+                                }
+                            }
+                            else
+                            {
+                                if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
+                                {
+                                    error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
+                                    return token_type::parse_error;
+                                }
+                            }
+
+                            // result of the above calculation yields a proper codepoint
+                            JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
+
+                            // translate codepoint into bytes
+                            if (codepoint < 0x80)
+                            {
+                                // 1-byte characters: 0xxxxxxx (ASCII)
+                                add(static_cast<char_int_type>(codepoint));
+                            }
+                            else if (codepoint <= 0x7FF)
+                            {
+                                // 2-byte characters: 110xxxxx 10xxxxxx
+                                add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
+                                add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+                            else if (codepoint <= 0xFFFF)
+                            {
+                                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
+                                add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
+                                add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+                                add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+                            else
+                            {
+                                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+                                add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
+                                add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
+                                add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
+                                add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
+                            }
+
+                            break;
+                        }
+
+                        // other characters after escape
+                        default:
+                            error_message = "invalid string: forbidden character after backslash";
+                            return token_type::parse_error;
+                    }
+
+                    break;
+                }
+
+                // invalid control characters
+                case 0x00:
+                {
+                    error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
+                    return token_type::parse_error;
+                }
+
+                case 0x01:
+                {
+                    error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
+                    return token_type::parse_error;
+                }
+
+                case 0x02:
+                {
+                    error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
+                    return token_type::parse_error;
+                }
+
+                case 0x03:
+                {
+                    error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
+                    return token_type::parse_error;
+                }
+
+                case 0x04:
+                {
+                    error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
+                    return token_type::parse_error;
+                }
+
+                case 0x05:
+                {
+                    error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
+                    return token_type::parse_error;
+                }
+
+                case 0x06:
+                {
+                    error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
+                    return token_type::parse_error;
+                }
+
+                case 0x07:
+                {
+                    error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
+                    return token_type::parse_error;
+                }
+
+                case 0x08:
+                {
+                    error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
+                    return token_type::parse_error;
+                }
+
+                case 0x09:
+                {
+                    error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
+                    return token_type::parse_error;
+                }
+
+                case 0x0A:
+                {
+                    error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
+                    return token_type::parse_error;
+                }
+
+                case 0x0B:
+                {
+                    error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
+                    return token_type::parse_error;
+                }
+
+                case 0x0C:
+                {
+                    error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
+                    return token_type::parse_error;
+                }
+
+                case 0x0D:
+                {
+                    error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
+                    return token_type::parse_error;
+                }
+
+                case 0x0E:
+                {
+                    error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
+                    return token_type::parse_error;
+                }
+
+                case 0x0F:
+                {
+                    error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
+                    return token_type::parse_error;
+                }
+
+                case 0x10:
+                {
+                    error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
+                    return token_type::parse_error;
+                }
+
+                case 0x11:
+                {
+                    error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
+                    return token_type::parse_error;
+                }
+
+                case 0x12:
+                {
+                    error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
+                    return token_type::parse_error;
+                }
+
+                case 0x13:
+                {
+                    error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
+                    return token_type::parse_error;
+                }
+
+                case 0x14:
+                {
+                    error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
+                    return token_type::parse_error;
+                }
+
+                case 0x15:
+                {
+                    error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
+                    return token_type::parse_error;
+                }
+
+                case 0x16:
+                {
+                    error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
+                    return token_type::parse_error;
+                }
+
+                case 0x17:
+                {
+                    error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
+                    return token_type::parse_error;
+                }
+
+                case 0x18:
+                {
+                    error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
+                    return token_type::parse_error;
+                }
+
+                case 0x19:
+                {
+                    error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
+                    return token_type::parse_error;
+                }
+
+                case 0x1A:
+                {
+                    error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
+                    return token_type::parse_error;
+                }
+
+                case 0x1B:
+                {
+                    error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
+                    return token_type::parse_error;
+                }
+
+                case 0x1C:
+                {
+                    error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
+                    return token_type::parse_error;
+                }
+
+                case 0x1D:
+                {
+                    error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
+                    return token_type::parse_error;
+                }
+
+                case 0x1E:
+                {
+                    error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
+                    return token_type::parse_error;
+                }
+
+                case 0x1F:
+                {
+                    error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
+                    return token_type::parse_error;
+                }
+
+                // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
+                case 0x20:
+                case 0x21:
+                case 0x23:
+                case 0x24:
+                case 0x25:
+                case 0x26:
+                case 0x27:
+                case 0x28:
+                case 0x29:
+                case 0x2A:
+                case 0x2B:
+                case 0x2C:
+                case 0x2D:
+                case 0x2E:
+                case 0x2F:
+                case 0x30:
+                case 0x31:
+                case 0x32:
+                case 0x33:
+                case 0x34:
+                case 0x35:
+                case 0x36:
+                case 0x37:
+                case 0x38:
+                case 0x39:
+                case 0x3A:
+                case 0x3B:
+                case 0x3C:
+                case 0x3D:
+                case 0x3E:
+                case 0x3F:
+                case 0x40:
+                case 0x41:
+                case 0x42:
+                case 0x43:
+                case 0x44:
+                case 0x45:
+                case 0x46:
+                case 0x47:
+                case 0x48:
+                case 0x49:
+                case 0x4A:
+                case 0x4B:
+                case 0x4C:
+                case 0x4D:
+                case 0x4E:
+                case 0x4F:
+                case 0x50:
+                case 0x51:
+                case 0x52:
+                case 0x53:
+                case 0x54:
+                case 0x55:
+                case 0x56:
+                case 0x57:
+                case 0x58:
+                case 0x59:
+                case 0x5A:
+                case 0x5B:
+                case 0x5D:
+                case 0x5E:
+                case 0x5F:
+                case 0x60:
+                case 0x61:
+                case 0x62:
+                case 0x63:
+                case 0x64:
+                case 0x65:
+                case 0x66:
+                case 0x67:
+                case 0x68:
+                case 0x69:
+                case 0x6A:
+                case 0x6B:
+                case 0x6C:
+                case 0x6D:
+                case 0x6E:
+                case 0x6F:
+                case 0x70:
+                case 0x71:
+                case 0x72:
+                case 0x73:
+                case 0x74:
+                case 0x75:
+                case 0x76:
+                case 0x77:
+                case 0x78:
+                case 0x79:
+                case 0x7A:
+                case 0x7B:
+                case 0x7C:
+                case 0x7D:
+                case 0x7E:
+                case 0x7F:
+                {
+                    add(current);
+                    break;
+                }
+
+                // U+0080..U+07FF: bytes C2..DF 80..BF
+                case 0xC2:
+                case 0xC3:
+                case 0xC4:
+                case 0xC5:
+                case 0xC6:
+                case 0xC7:
+                case 0xC8:
+                case 0xC9:
+                case 0xCA:
+                case 0xCB:
+                case 0xCC:
+                case 0xCD:
+                case 0xCE:
+                case 0xCF:
+                case 0xD0:
+                case 0xD1:
+                case 0xD2:
+                case 0xD3:
+                case 0xD4:
+                case 0xD5:
+                case 0xD6:
+                case 0xD7:
+                case 0xD8:
+                case 0xD9:
+                case 0xDA:
+                case 0xDB:
+                case 0xDC:
+                case 0xDD:
+                case 0xDE:
+                case 0xDF:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
+                case 0xE0:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
+                // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
+                case 0xE1:
+                case 0xE2:
+                case 0xE3:
+                case 0xE4:
+                case 0xE5:
+                case 0xE6:
+                case 0xE7:
+                case 0xE8:
+                case 0xE9:
+                case 0xEA:
+                case 0xEB:
+                case 0xEC:
+                case 0xEE:
+                case 0xEF:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+D000..U+D7FF: bytes ED 80..9F 80..BF
+                case 0xED:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
+                case 0xF0:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
+                case 0xF1:
+                case 0xF2:
+                case 0xF3:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
+                case 0xF4:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
+                    {
+                        return token_type::parse_error;
+                    }
+                    break;
+                }
+
+                // remaining bytes (80..C1 and F5..FF) are ill-formed
+                default:
+                {
+                    error_message = "invalid string: ill-formed UTF-8 byte";
+                    return token_type::parse_error;
+                }
+            }
+        }
+    }
+
+    /*!
+     * @brief scan a comment
+     * @return whether comment could be scanned successfully
+     */
+    bool scan_comment()
+    {
+        switch (get())
+        {
+            // single-line comments skip input until a newline or EOF is read
+            case '/':
+            {
+                while (true)
+                {
+                    switch (get())
+                    {
+                        case '\n':
+                        case '\r':
+                        case std::char_traits<char_type>::eof():
+                        case '\0':
+                            return true;
+
+                        default:
+                            break;
+                    }
+                }
+            }
+
+            // multi-line comments skip input until */ is read
+            case '*':
+            {
+                while (true)
+                {
+                    switch (get())
+                    {
+                        case std::char_traits<char_type>::eof():
+                        case '\0':
+                        {
+                            error_message = "invalid comment; missing closing '*/'";
+                            return false;
+                        }
+
+                        case '*':
+                        {
+                            switch (get())
+                            {
+                                case '/':
+                                    return true;
+
+                                default:
+                                {
+                                    unget();
+                                    continue;
+                                }
+                            }
+                        }
+
+                        default:
+                            continue;
+                    }
+                }
+            }
+
+            // unexpected character after reading '/'
+            default:
+            {
+                error_message = "invalid comment; expecting '/' or '*' after '/'";
+                return false;
+            }
+        }
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(float& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtof(str, endptr);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(double& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtod(str, endptr);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    static void strtof(long double& f, const char* str, char** endptr) noexcept
+    {
+        f = std::strtold(str, endptr);
+    }
+
+    /*!
+    @brief scan a number literal
+
+    This function scans a string according to Sect. 6 of RFC 8259.
+
+    The function is realized with a deterministic finite state machine derived
+    from the grammar described in RFC 8259. Starting in state "init", the
+    input is read and used to determined the next state. Only state "done"
+    accepts the number. State "error" is a trap state to model errors. In the
+    table below, "anything" means any character but the ones listed before.
+
+    state    | 0        | 1-9      | e E      | +       | -       | .        | anything
+    ---------|----------|----------|----------|---------|---------|----------|-----------
+    init     | zero     | any1     | [error]  | [error] | minus   | [error]  | [error]
+    minus    | zero     | any1     | [error]  | [error] | [error] | [error]  | [error]
+    zero     | done     | done     | exponent | done    | done    | decimal1 | done
+    any1     | any1     | any1     | exponent | done    | done    | decimal1 | done
+    decimal1 | decimal2 | decimal2 | [error]  | [error] | [error] | [error]  | [error]
+    decimal2 | decimal2 | decimal2 | exponent | done    | done    | done     | done
+    exponent | any2     | any2     | [error]  | sign    | sign    | [error]  | [error]
+    sign     | any2     | any2     | [error]  | [error] | [error] | [error]  | [error]
+    any2     | any2     | any2     | done     | done    | done    | done     | done
+
+    The state machine is realized with one label per state (prefixed with
+    "scan_number_") and `goto` statements between them. The state machine
+    contains cycles, but any cycle can be left when EOF is read. Therefore,
+    the function is guaranteed to terminate.
+
+    During scanning, the read bytes are stored in token_buffer. This string is
+    then converted to a signed integer, an unsigned integer, or a
+    floating-point number.
+
+    @return token_type::value_unsigned, token_type::value_integer, or
+            token_type::value_float if number could be successfully scanned,
+            token_type::parse_error otherwise
+
+    @note The scanner is independent of the current locale. Internally, the
+          locale's decimal point is used instead of `.` to work with the
+          locale-dependent converters.
+    */
+    token_type scan_number()  // lgtm [cpp/use-of-goto]
+    {
+        // reset token_buffer to store the number's bytes
+        reset();
+
+        // the type of the parsed number; initially set to unsigned; will be
+        // changed if minus sign, decimal point or exponent is read
+        token_type number_type = token_type::value_unsigned;
+
+        // state (init): we just found out we need to scan a number
+        switch (current)
+        {
+            case '-':
+            {
+                add(current);
+                goto scan_number_minus;
+            }
+
+            case '0':
+            {
+                add(current);
+                goto scan_number_zero;
+            }
+
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            // all other characters are rejected outside scan_number()
+            default:            // LCOV_EXCL_LINE
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        }
+
+scan_number_minus:
+        // state: we just parsed a leading minus sign
+        number_type = token_type::value_integer;
+        switch (get())
+        {
+            case '0':
+            {
+                add(current);
+                goto scan_number_zero;
+            }
+
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after '-'";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_zero:
+        // state: we just parse a zero (maybe with a leading minus sign)
+        switch (get())
+        {
+            case '.':
+            {
+                add(decimal_point_char);
+                goto scan_number_decimal1;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_any1:
+        // state: we just parsed a number 0-9 (maybe with a leading minus sign)
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any1;
+            }
+
+            case '.':
+            {
+                add(decimal_point_char);
+                goto scan_number_decimal1;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_decimal1:
+        // state: we just parsed a decimal point
+        number_type = token_type::value_float;
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_decimal2;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after '.'";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_decimal2:
+        // we just parsed at least one number after a decimal point
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_decimal2;
+            }
+
+            case 'e':
+            case 'E':
+            {
+                add(current);
+                goto scan_number_exponent;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_exponent:
+        // we just parsed an exponent
+        number_type = token_type::value_float;
+        switch (get())
+        {
+            case '+':
+            case '-':
+            {
+                add(current);
+                goto scan_number_sign;
+            }
+
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+            {
+                error_message =
+                    "invalid number; expected '+', '-', or digit after exponent";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_sign:
+        // we just parsed an exponent sign
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+            {
+                error_message = "invalid number; expected digit after exponent sign";
+                return token_type::parse_error;
+            }
+        }
+
+scan_number_any2:
+        // we just parsed a number after the exponent or exponent sign
+        switch (get())
+        {
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            {
+                add(current);
+                goto scan_number_any2;
+            }
+
+            default:
+                goto scan_number_done;
+        }
+
+scan_number_done:
+        // unget the character after the number (we only read it to know that
+        // we are done scanning a number)
+        unget();
+
+        char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+        errno = 0;
+
+        // try to parse integers first and fall back to floats
+        if (number_type == token_type::value_unsigned)
+        {
+            const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
+
+            // we checked the number format before
+            JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+            if (errno == 0)
+            {
+                value_unsigned = static_cast<number_unsigned_t>(x);
+                if (value_unsigned == x)
+                {
+                    return token_type::value_unsigned;
+                }
+            }
+        }
+        else if (number_type == token_type::value_integer)
+        {
+            const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
+
+            // we checked the number format before
+            JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+            if (errno == 0)
+            {
+                value_integer = static_cast<number_integer_t>(x);
+                if (value_integer == x)
+                {
+                    return token_type::value_integer;
+                }
+            }
+        }
+
+        // this code is reached if we parse a floating-point number or if an
+        // integer conversion above failed
+        strtof(value_float, token_buffer.data(), &endptr);
+
+        // we checked the number format before
+        JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
+
+        return token_type::value_float;
+    }
+
+    /*!
+    @param[in] literal_text  the literal text to expect
+    @param[in] length        the length of the passed literal text
+    @param[in] return_type   the token type to return on success
+    */
+    JSON_HEDLEY_NON_NULL(2)
+    token_type scan_literal(const char_type* literal_text, const std::size_t length,
+                            token_type return_type)
+    {
+        JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
+        for (std::size_t i = 1; i < length; ++i)
+        {
+            if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
+            {
+                error_message = "invalid literal";
+                return token_type::parse_error;
+            }
+        }
+        return return_type;
+    }
+
+    /////////////////////
+    // input management
+    /////////////////////
+
+    /// reset token_buffer; current character is beginning of token
+    void reset() noexcept
+    {
+        token_buffer.clear();
+        token_string.clear();
+        token_string.push_back(std::char_traits<char_type>::to_char_type(current));
+    }
+
+    /*
+    @brief get next character from the input
+
+    This function provides the interface to the used input adapter. It does
+    not throw in case the input reached EOF, but returns a
+    `std::char_traits<char>::eof()` in that case.  Stores the scanned characters
+    for use in error messages.
+
+    @return character read from the input
+    */
+    char_int_type get()
+    {
+        ++position.chars_read_total;
+        ++position.chars_read_current_line;
+
+        if (next_unget)
+        {
+            // just reset the next_unget variable and work with current
+            next_unget = false;
+        }
+        else
+        {
+            current = ia.get_character();
+        }
+
+        if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
+        {
+            token_string.push_back(std::char_traits<char_type>::to_char_type(current));
+        }
+
+        if (current == '\n')
+        {
+            ++position.lines_read;
+            position.chars_read_current_line = 0;
+        }
+
+        return current;
+    }
+
+    /*!
+    @brief unget current character (read it again on next get)
+
+    We implement unget by setting variable next_unget to true. The input is not
+    changed - we just simulate ungetting by modifying chars_read_total,
+    chars_read_current_line, and token_string. The next call to get() will
+    behave as if the unget character is read again.
+    */
+    void unget()
+    {
+        next_unget = true;
+
+        --position.chars_read_total;
+
+        // in case we "unget" a newline, we have to also decrement the lines_read
+        if (position.chars_read_current_line == 0)
+        {
+            if (position.lines_read > 0)
+            {
+                --position.lines_read;
+            }
+        }
+        else
+        {
+            --position.chars_read_current_line;
+        }
+
+        if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
+        {
+            JSON_ASSERT(!token_string.empty());
+            token_string.pop_back();
+        }
+    }
+
+    /// add a character to token_buffer
+    void add(char_int_type c)
+    {
+        token_buffer.push_back(static_cast<typename string_t::value_type>(c));
+    }
+
+  public:
+    /////////////////////
+    // value getters
+    /////////////////////
+
+    /// return integer value
+    constexpr number_integer_t get_number_integer() const noexcept
+    {
+        return value_integer;
+    }
+
+    /// return unsigned integer value
+    constexpr number_unsigned_t get_number_unsigned() const noexcept
+    {
+        return value_unsigned;
+    }
+
+    /// return floating-point value
+    constexpr number_float_t get_number_float() const noexcept
+    {
+        return value_float;
+    }
+
+    /// return current string value (implicitly resets the token; useful only once)
+    string_t& get_string()
+    {
+        return token_buffer;
+    }
+
+    /////////////////////
+    // diagnostics
+    /////////////////////
+
+    /// return position of last read token
+    constexpr position_t get_position() const noexcept
+    {
+        return position;
+    }
+
+    /// return the last read token (for errors only).  Will never contain EOF
+    /// (an arbitrary value that is not a valid char value, often -1), because
+    /// 255 may legitimately occur.  May contain NUL, which should be escaped.
+    std::string get_token_string() const
+    {
+        // escape control characters
+        std::string result;
+        for (const auto c : token_string)
+        {
+            if (static_cast<unsigned char>(c) <= '\x1F')
+            {
+                // escape control characters
+                std::array<char, 9> cs{{}};
+                static_cast<void>((std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+                result += cs.data();
+            }
+            else
+            {
+                // add character as is
+                result.push_back(static_cast<std::string::value_type>(c));
+            }
+        }
+
+        return result;
+    }
+
+    /// return syntax error message
+    JSON_HEDLEY_RETURNS_NON_NULL
+    constexpr const char* get_error_message() const noexcept
+    {
+        return error_message;
+    }
+
+    /////////////////////
+    // actual scanner
+    /////////////////////
+
+    /*!
+    @brief skip the UTF-8 byte order mark
+    @return true iff there is no BOM or the correct BOM has been skipped
+    */
+    bool skip_bom()
+    {
+        if (get() == 0xEF)
+        {
+            // check if we completely parse the BOM
+            return get() == 0xBB && get() == 0xBF;
+        }
+
+        // the first character is not the beginning of the BOM; unget it to
+        // process is later
+        unget();
+        return true;
+    }
+
+    void skip_whitespace()
+    {
+        do
+        {
+            get();
+        }
+        while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
+    }
+
+    token_type scan()
+    {
+        // initially, skip the BOM
+        if (position.chars_read_total == 0 && !skip_bom())
+        {
+            error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
+            return token_type::parse_error;
+        }
+
+        // read next character and ignore whitespace
+        skip_whitespace();
+
+        // ignore comments
+        while (ignore_comments && current == '/')
+        {
+            if (!scan_comment())
+            {
+                return token_type::parse_error;
+            }
+
+            // skip following whitespace
+            skip_whitespace();
+        }
+
+        switch (current)
+        {
+            // structural characters
+            case '[':
+                return token_type::begin_array;
+            case ']':
+                return token_type::end_array;
+            case '{':
+                return token_type::begin_object;
+            case '}':
+                return token_type::end_object;
+            case ':':
+                return token_type::name_separator;
+            case ',':
+                return token_type::value_separator;
+
+            // literals
+            case 't':
+            {
+                std::array<char_type, 4> true_literal = {{static_cast<char_type>('t'), static_cast<char_type>('r'), static_cast<char_type>('u'), static_cast<char_type>('e')}};
+                return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
+            }
+            case 'f':
+            {
+                std::array<char_type, 5> false_literal = {{static_cast<char_type>('f'), static_cast<char_type>('a'), static_cast<char_type>('l'), static_cast<char_type>('s'), static_cast<char_type>('e')}};
+                return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
+            }
+            case 'n':
+            {
+                std::array<char_type, 4> null_literal = {{static_cast<char_type>('n'), static_cast<char_type>('u'), static_cast<char_type>('l'), static_cast<char_type>('l')}};
+                return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
+            }
+
+            // string
+            case '\"':
+                return scan_string();
+
+            // number
+            case '-':
+            case '0':
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+                return scan_number();
+
+            // end of input (the null byte is needed when parsing from
+            // string literals)
+            case '\0':
+            case std::char_traits<char_type>::eof():
+                return token_type::end_of_input;
+
+            // error
+            default:
+                error_message = "invalid literal";
+                return token_type::parse_error;
+        }
+    }
+
+  private:
+    /// input adapter
+    InputAdapterType ia;
+
+    /// whether comments should be ignored (true) or signaled as errors (false)
+    const bool ignore_comments = false;
+
+    /// the current character
+    char_int_type current = std::char_traits<char_type>::eof();
+
+    /// whether the next get() call should just return current
+    bool next_unget = false;
+
+    /// the start position of the current token
+    position_t position {};
+
+    /// raw input token string (for error messages)
+    std::vector<char_type> token_string {};
+
+    /// buffer for variable-length tokens (numbers, strings)
+    string_t token_buffer {};
+
+    /// a description of occurred lexer errors
+    const char* error_message = "";
+
+    // number values
+    number_integer_t value_integer = 0;
+    number_unsigned_t value_unsigned = 0;
+    number_float_t value_float = 0;
+
+    /// the decimal point
+    const char_int_type decimal_point_char = '.';
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+
+
+#include <cstdint> // size_t
+#include <utility> // declval
+#include <string> // string
+
+// #include <nlohmann/detail/meta/detected.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename T>
+using null_function_t = decltype(std::declval<T&>().null());
+
+template<typename T>
+using boolean_function_t =
+    decltype(std::declval<T&>().boolean(std::declval<bool>()));
+
+template<typename T, typename Integer>
+using number_integer_function_t =
+    decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
+
+template<typename T, typename Unsigned>
+using number_unsigned_function_t =
+    decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
+
+template<typename T, typename Float, typename String>
+using number_float_function_t = decltype(std::declval<T&>().number_float(
+                                    std::declval<Float>(), std::declval<const String&>()));
+
+template<typename T, typename String>
+using string_function_t =
+    decltype(std::declval<T&>().string(std::declval<String&>()));
+
+template<typename T, typename Binary>
+using binary_function_t =
+    decltype(std::declval<T&>().binary(std::declval<Binary&>()));
+
+template<typename T>
+using start_object_function_t =
+    decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
+
+template<typename T, typename String>
+using key_function_t =
+    decltype(std::declval<T&>().key(std::declval<String&>()));
+
+template<typename T>
+using end_object_function_t = decltype(std::declval<T&>().end_object());
+
+template<typename T>
+using start_array_function_t =
+    decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
+
+template<typename T>
+using end_array_function_t = decltype(std::declval<T&>().end_array());
+
+template<typename T, typename Exception>
+using parse_error_function_t = decltype(std::declval<T&>().parse_error(
+        std::declval<std::size_t>(), std::declval<const std::string&>(),
+        std::declval<const Exception&>()));
+
+template<typename SAX, typename BasicJsonType>
+struct is_sax
+{
+  private:
+    static_assert(is_basic_json<BasicJsonType>::value,
+                  "BasicJsonType must be of type basic_json<...>");
+
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+    using exception_t = typename BasicJsonType::exception;
+
+  public:
+    static constexpr bool value =
+        is_detected_exact<bool, null_function_t, SAX>::value &&
+        is_detected_exact<bool, boolean_function_t, SAX>::value &&
+        is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value &&
+        is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value &&
+        is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value &&
+        is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
+        is_detected_exact<bool, binary_function_t, SAX, binary_t>::value &&
+        is_detected_exact<bool, start_object_function_t, SAX>::value &&
+        is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
+        is_detected_exact<bool, end_object_function_t, SAX>::value &&
+        is_detected_exact<bool, start_array_function_t, SAX>::value &&
+        is_detected_exact<bool, end_array_function_t, SAX>::value &&
+        is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
+};
+
+template<typename SAX, typename BasicJsonType>
+struct is_sax_static_asserts
+{
+  private:
+    static_assert(is_basic_json<BasicJsonType>::value,
+                  "BasicJsonType must be of type basic_json<...>");
+
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+    using exception_t = typename BasicJsonType::exception;
+
+  public:
+    static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
+                  "Missing/invalid function: bool null()");
+    static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+                  "Missing/invalid function: bool boolean(bool)");
+    static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
+                  "Missing/invalid function: bool boolean(bool)");
+    static_assert(
+        is_detected_exact<bool, number_integer_function_t, SAX,
+        number_integer_t>::value,
+        "Missing/invalid function: bool number_integer(number_integer_t)");
+    static_assert(
+        is_detected_exact<bool, number_unsigned_function_t, SAX,
+        number_unsigned_t>::value,
+        "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
+    static_assert(is_detected_exact<bool, number_float_function_t, SAX,
+                  number_float_t, string_t>::value,
+                  "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
+    static_assert(
+        is_detected_exact<bool, string_function_t, SAX, string_t>::value,
+        "Missing/invalid function: bool string(string_t&)");
+    static_assert(
+        is_detected_exact<bool, binary_function_t, SAX, binary_t>::value,
+        "Missing/invalid function: bool binary(binary_t&)");
+    static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
+                  "Missing/invalid function: bool start_object(std::size_t)");
+    static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
+                  "Missing/invalid function: bool key(string_t&)");
+    static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
+                  "Missing/invalid function: bool end_object()");
+    static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
+                  "Missing/invalid function: bool start_array(std::size_t)");
+    static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
+                  "Missing/invalid function: bool end_array()");
+    static_assert(
+        is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
+        "Missing/invalid function: bool parse_error(std::size_t, const "
+        "std::string&, const exception&)");
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+/// how to treat CBOR tags
+enum class cbor_tag_handler_t
+{
+    error,   ///< throw a parse_error exception in case of a tag
+    ignore,  ///< ignore tags
+    store    ///< store tags as binary type
+};
+
+/*!
+@brief determine system byte order
+
+@return true if and only if system's byte order is little endian
+
+@note from https://stackoverflow.com/a/1001328/266378
+*/
+static inline bool little_endianness(int num = 1) noexcept
+{
+    return *reinterpret_cast<char*>(&num) == 1;
+}
+
+
+///////////////////
+// binary reader //
+///////////////////
+
+/*!
+@brief deserialization of CBOR, MessagePack, and UBJSON values
+*/
+template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
+class binary_reader
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+    using json_sax_t = SAX;
+    using char_type = typename InputAdapterType::char_type;
+    using char_int_type = typename std::char_traits<char_type>::int_type;
+
+  public:
+    /*!
+    @brief create a binary reader
+
+    @param[in] adapter  input adapter to read from
+    */
+    explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter))
+    {
+        (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
+    }
+
+    // make class move-only
+    binary_reader(const binary_reader&) = delete;
+    binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    binary_reader& operator=(const binary_reader&) = delete;
+    binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
+    ~binary_reader() = default;
+
+    /*!
+    @param[in] format  the binary format to parse
+    @param[in] sax_    a SAX event processor
+    @param[in] strict  whether to expect the input to be consumed completed
+    @param[in] tag_handler  how to treat CBOR tags
+
+    @return whether parsing was successful
+    */
+    JSON_HEDLEY_NON_NULL(3)
+    bool sax_parse(const input_format_t format,
+                   json_sax_t* sax_,
+                   const bool strict = true,
+                   const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
+    {
+        sax = sax_;
+        bool result = false;
+
+        switch (format)
+        {
+            case input_format_t::bson:
+                result = parse_bson_internal();
+                break;
+
+            case input_format_t::cbor:
+                result = parse_cbor_internal(true, tag_handler);
+                break;
+
+            case input_format_t::msgpack:
+                result = parse_msgpack_internal();
+                break;
+
+            case input_format_t::ubjson:
+                result = parse_ubjson_internal();
+                break;
+
+            case input_format_t::json: // LCOV_EXCL_LINE
+            default:            // LCOV_EXCL_LINE
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        }
+
+        // strict mode: next byte must be EOF
+        if (result && strict)
+        {
+            if (format == input_format_t::ubjson)
+            {
+                get_ignore_noop();
+            }
+            else
+            {
+                get();
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
+            {
+                return sax->parse_error(chars_read, get_token_string(),
+                                        parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType()));
+            }
+        }
+
+        return result;
+    }
+
+  private:
+    //////////
+    // BSON //
+    //////////
+
+    /*!
+    @brief Reads in a BSON-object and passes it to the SAX-parser.
+    @return whether a valid BSON-value was passed to the SAX parser
+    */
+    bool parse_bson_internal()
+    {
+        std::int32_t document_size{};
+        get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
+        {
+            return false;
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
+        {
+            return false;
+        }
+
+        return sax->end_object();
+    }
+
+    /*!
+    @brief Parses a C-style string from the BSON input.
+    @param[in,out] result  A reference to the string variable where the read
+                            string is to be stored.
+    @return `true` if the \x00-byte indicating the end of the string was
+             encountered before the EOF; false` indicates an unexpected EOF.
+    */
+    bool get_bson_cstr(string_t& result)
+    {
+        auto out = std::back_inserter(result);
+        while (true)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
+            {
+                return false;
+            }
+            if (current == 0x00)
+            {
+                return true;
+            }
+            *out++ = static_cast<typename string_t::value_type>(current);
+        }
+    }
+
+    /*!
+    @brief Parses a zero-terminated string of length @a len from the BSON
+           input.
+    @param[in] len  The length (including the zero-byte at the end) of the
+                    string to be read.
+    @param[in,out] result  A reference to the string variable where the read
+                            string is to be stored.
+    @tparam NumberType The type of the length @a len
+    @pre len >= 1
+    @return `true` if the string was successfully parsed
+    */
+    template<typename NumberType>
+    bool get_bson_string(const NumberType len, string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(len < 1))
+        {
+            auto last_token = get_token_string();
+            return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType()));
+        }
+
+        return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
+    }
+
+    /*!
+    @brief Parses a byte array input of length @a len from the BSON input.
+    @param[in] len  The length of the byte array to be read.
+    @param[in,out] result  A reference to the binary variable where the read
+                            array is to be stored.
+    @tparam NumberType The type of the length @a len
+    @pre len >= 0
+    @return `true` if the byte array was successfully parsed
+    */
+    template<typename NumberType>
+    bool get_bson_binary(const NumberType len, binary_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(len < 0))
+        {
+            auto last_token = get_token_string();
+            return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType()));
+        }
+
+        // All BSON binary values have a subtype
+        std::uint8_t subtype{};
+        get_number<std::uint8_t>(input_format_t::bson, subtype);
+        result.set_subtype(subtype);
+
+        return get_binary(input_format_t::bson, len, result);
+    }
+
+    /*!
+    @brief Read a BSON document element of the given @a element_type.
+    @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
+    @param[in] element_type_parse_position The position in the input stream,
+               where the `element_type` was read.
+    @warning Not all BSON element types are supported yet. An unsupported
+             @a element_type will give rise to a parse_error.114:
+             Unsupported BSON record type 0x...
+    @return whether a valid BSON-object/array was passed to the SAX parser
+    */
+    bool parse_bson_element_internal(const char_int_type element_type,
+                                     const std::size_t element_type_parse_position)
+    {
+        switch (element_type)
+        {
+            case 0x01: // double
+            {
+                double number{};
+                return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0x02: // string
+            {
+                std::int32_t len{};
+                string_t value;
+                return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
+            }
+
+            case 0x03: // object
+            {
+                return parse_bson_internal();
+            }
+
+            case 0x04: // array
+            {
+                return parse_bson_array();
+            }
+
+            case 0x05: // binary
+            {
+                std::int32_t len{};
+                binary_t value;
+                return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
+            }
+
+            case 0x08: // boolean
+            {
+                return sax->boolean(get() != 0);
+            }
+
+            case 0x0A: // null
+            {
+                return sax->null();
+            }
+
+            case 0x10: // int32
+            {
+                std::int32_t value{};
+                return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
+            }
+
+            case 0x12: // int64
+            {
+                std::int64_t value{};
+                return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
+            }
+
+            default: // anything else not supported (yet)
+            {
+                std::array<char, 3> cr{{}};
+                static_cast<void>((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+                return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief Read a BSON element list (as specified in the BSON-spec)
+
+    The same binary layout is used for objects and arrays, hence it must be
+    indicated with the argument @a is_array which one is expected
+    (true --> array, false --> object).
+
+    @param[in] is_array Determines if the element list being read is to be
+                        treated as an object (@a is_array == false), or as an
+                        array (@a is_array == true).
+    @return whether a valid BSON-object/array was passed to the SAX parser
+    */
+    bool parse_bson_element_list(const bool is_array)
+    {
+        string_t key;
+
+        while (auto element_type = get())
+        {
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
+            {
+                return false;
+            }
+
+            const std::size_t element_type_parse_position = chars_read;
+            if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
+            {
+                return false;
+            }
+
+            if (!is_array && !sax->key(key))
+            {
+                return false;
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
+            {
+                return false;
+            }
+
+            // get_bson_cstr only appends
+            key.clear();
+        }
+
+        return true;
+    }
+
+    /*!
+    @brief Reads an array from the BSON input and passes it to the SAX-parser.
+    @return whether a valid BSON-array was passed to the SAX parser
+    */
+    bool parse_bson_array()
+    {
+        std::int32_t document_size{};
+        get_number<std::int32_t, true>(input_format_t::bson, document_size);
+
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
+        {
+            return false;
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
+        {
+            return false;
+        }
+
+        return sax->end_array();
+    }
+
+    //////////
+    // CBOR //
+    //////////
+
+    /*!
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true) or whether the last read character should
+                         be considered instead (false)
+    @param[in] tag_handler how CBOR tags should be treated
+
+    @return whether a valid CBOR value was passed to the SAX parser
+    */
+    bool parse_cbor_internal(const bool get_char,
+                             const cbor_tag_handler_t tag_handler)
+    {
+        switch (get_char ? get() : current)
+        {
+            // EOF
+            case std::char_traits<char_type>::eof():
+                return unexpect_eof(input_format_t::cbor, "value");
+
+            // Integer 0x00..0x17 (0..23)
+            case 0x00:
+            case 0x01:
+            case 0x02:
+            case 0x03:
+            case 0x04:
+            case 0x05:
+            case 0x06:
+            case 0x07:
+            case 0x08:
+            case 0x09:
+            case 0x0A:
+            case 0x0B:
+            case 0x0C:
+            case 0x0D:
+            case 0x0E:
+            case 0x0F:
+            case 0x10:
+            case 0x11:
+            case 0x12:
+            case 0x13:
+            case 0x14:
+            case 0x15:
+            case 0x16:
+            case 0x17:
+                return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+            case 0x18: // Unsigned integer (one-byte uint8_t follows)
+            {
+                std::uint8_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+            }
+
+            case 0x19: // Unsigned integer (two-byte uint16_t follows)
+            {
+                std::uint16_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+            }
+
+            case 0x1A: // Unsigned integer (four-byte uint32_t follows)
+            {
+                std::uint32_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+            }
+
+            case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
+            {
+                std::uint64_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
+            }
+
+            // Negative integer -1-0x00..-1-0x17 (-1..-24)
+            case 0x20:
+            case 0x21:
+            case 0x22:
+            case 0x23:
+            case 0x24:
+            case 0x25:
+            case 0x26:
+            case 0x27:
+            case 0x28:
+            case 0x29:
+            case 0x2A:
+            case 0x2B:
+            case 0x2C:
+            case 0x2D:
+            case 0x2E:
+            case 0x2F:
+            case 0x30:
+            case 0x31:
+            case 0x32:
+            case 0x33:
+            case 0x34:
+            case 0x35:
+            case 0x36:
+            case 0x37:
+                return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
+
+            case 0x38: // Negative integer (one-byte uint8_t follows)
+            {
+                std::uint8_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
+            {
+                std::uint16_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
+            {
+                std::uint32_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
+            }
+
+            case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
+            {
+                std::uint64_t number{};
+                return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
+                        - static_cast<number_integer_t>(number));
+            }
+
+            // Binary data (0x00..0x17 bytes follow)
+            case 0x40:
+            case 0x41:
+            case 0x42:
+            case 0x43:
+            case 0x44:
+            case 0x45:
+            case 0x46:
+            case 0x47:
+            case 0x48:
+            case 0x49:
+            case 0x4A:
+            case 0x4B:
+            case 0x4C:
+            case 0x4D:
+            case 0x4E:
+            case 0x4F:
+            case 0x50:
+            case 0x51:
+            case 0x52:
+            case 0x53:
+            case 0x54:
+            case 0x55:
+            case 0x56:
+            case 0x57:
+            case 0x58: // Binary data (one-byte uint8_t for n follows)
+            case 0x59: // Binary data (two-byte uint16_t for n follow)
+            case 0x5A: // Binary data (four-byte uint32_t for n follow)
+            case 0x5B: // Binary data (eight-byte uint64_t for n follow)
+            case 0x5F: // Binary data (indefinite length)
+            {
+                binary_t b;
+                return get_cbor_binary(b) && sax->binary(b);
+            }
+
+            // UTF-8 string (0x00..0x17 bytes follow)
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+            case 0x7F: // UTF-8 string (indefinite length)
+            {
+                string_t s;
+                return get_cbor_string(s) && sax->string(s);
+            }
+
+            // array (0x00..0x17 data items follow)
+            case 0x80:
+            case 0x81:
+            case 0x82:
+            case 0x83:
+            case 0x84:
+            case 0x85:
+            case 0x86:
+            case 0x87:
+            case 0x88:
+            case 0x89:
+            case 0x8A:
+            case 0x8B:
+            case 0x8C:
+            case 0x8D:
+            case 0x8E:
+            case 0x8F:
+            case 0x90:
+            case 0x91:
+            case 0x92:
+            case 0x93:
+            case 0x94:
+            case 0x95:
+            case 0x96:
+            case 0x97:
+                return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
+
+            case 0x98: // array (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0x99: // array (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0x9A: // array (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0x9B: // array (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0x9F: // array (indefinite length)
+                return get_cbor_array(static_cast<std::size_t>(-1), tag_handler);
+
+            // map (0x00..0x17 pairs of data items follow)
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+                return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu), tag_handler);
+
+            case 0xB8: // map (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0xB9: // map (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0xBA: // map (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0xBB: // map (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len{};
+                return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast<std::size_t>(len), tag_handler);
+            }
+
+            case 0xBF: // map (indefinite length)
+                return get_cbor_object(static_cast<std::size_t>(-1), tag_handler);
+
+            case 0xC6: // tagged item
+            case 0xC7:
+            case 0xC8:
+            case 0xC9:
+            case 0xCA:
+            case 0xCB:
+            case 0xCC:
+            case 0xCD:
+            case 0xCE:
+            case 0xCF:
+            case 0xD0:
+            case 0xD1:
+            case 0xD2:
+            case 0xD3:
+            case 0xD4:
+            case 0xD8: // tagged item (1 bytes follow)
+            case 0xD9: // tagged item (2 bytes follow)
+            case 0xDA: // tagged item (4 bytes follow)
+            case 0xDB: // tagged item (8 bytes follow)
+            {
+                switch (tag_handler)
+                {
+                    case cbor_tag_handler_t::error:
+                    {
+                        auto last_token = get_token_string();
+                        return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
+                    }
+
+                    case cbor_tag_handler_t::ignore:
+                    {
+                        // ignore binary subtype
+                        switch (current)
+                        {
+                            case 0xD8:
+                            {
+                                std::uint8_t subtype_to_ignore{};
+                                get_number(input_format_t::cbor, subtype_to_ignore);
+                                break;
+                            }
+                            case 0xD9:
+                            {
+                                std::uint16_t subtype_to_ignore{};
+                                get_number(input_format_t::cbor, subtype_to_ignore);
+                                break;
+                            }
+                            case 0xDA:
+                            {
+                                std::uint32_t subtype_to_ignore{};
+                                get_number(input_format_t::cbor, subtype_to_ignore);
+                                break;
+                            }
+                            case 0xDB:
+                            {
+                                std::uint64_t subtype_to_ignore{};
+                                get_number(input_format_t::cbor, subtype_to_ignore);
+                                break;
+                            }
+                            default:
+                                break;
+                        }
+                        return parse_cbor_internal(true, tag_handler);
+                    }
+
+                    case cbor_tag_handler_t::store:
+                    {
+                        binary_t b;
+                        // use binary subtype and store in binary container
+                        switch (current)
+                        {
+                            case 0xD8:
+                            {
+                                std::uint8_t subtype{};
+                                get_number(input_format_t::cbor, subtype);
+                                b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+                                break;
+                            }
+                            case 0xD9:
+                            {
+                                std::uint16_t subtype{};
+                                get_number(input_format_t::cbor, subtype);
+                                b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+                                break;
+                            }
+                            case 0xDA:
+                            {
+                                std::uint32_t subtype{};
+                                get_number(input_format_t::cbor, subtype);
+                                b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+                                break;
+                            }
+                            case 0xDB:
+                            {
+                                std::uint64_t subtype{};
+                                get_number(input_format_t::cbor, subtype);
+                                b.set_subtype(detail::conditional_static_cast<typename binary_t::subtype_type>(subtype));
+                                break;
+                            }
+                            default:
+                                return parse_cbor_internal(true, tag_handler);
+                        }
+                        get();
+                        return get_cbor_binary(b) && sax->binary(b);
+                    }
+
+                    default:                 // LCOV_EXCL_LINE
+                        JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+                        return false;        // LCOV_EXCL_LINE
+                }
+            }
+
+            case 0xF4: // false
+                return sax->boolean(false);
+
+            case 0xF5: // true
+                return sax->boolean(true);
+
+            case 0xF6: // null
+                return sax->null();
+
+            case 0xF9: // Half-Precision Float (two-byte IEEE 754)
+            {
+                const auto byte1_raw = get();
+                if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
+                {
+                    return false;
+                }
+                const auto byte2_raw = get();
+                if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
+                {
+                    return false;
+                }
+
+                const auto byte1 = static_cast<unsigned char>(byte1_raw);
+                const auto byte2 = static_cast<unsigned char>(byte2_raw);
+
+                // code from RFC 7049, Appendix D, Figure 3:
+                // As half-precision floating-point numbers were only added
+                // to IEEE 754 in 2008, today's programming platforms often
+                // still only have limited support for them. It is very
+                // easy to include at least decoding support for them even
+                // without such support. An example of a small decoder for
+                // half-precision floating-point numbers in the C language
+                // is shown in Fig. 3.
+                const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
+                const double val = [&half]
+                {
+                    const int exp = (half >> 10u) & 0x1Fu;
+                    const unsigned int mant = half & 0x3FFu;
+                    JSON_ASSERT(0 <= exp&& exp <= 32);
+                    JSON_ASSERT(mant <= 1024);
+                    switch (exp)
+                    {
+                        case 0:
+                            return std::ldexp(mant, -24);
+                        case 31:
+                            return (mant == 0)
+                            ? std::numeric_limits<double>::infinity()
+                            : std::numeric_limits<double>::quiet_NaN();
+                        default:
+                            return std::ldexp(mant + 1024, exp - 25);
+                    }
+                }();
+                return sax->number_float((half & 0x8000u) != 0
+                                         ? static_cast<number_float_t>(-val)
+                                         : static_cast<number_float_t>(val), "");
+            }
+
+            case 0xFA: // Single-Precision Float (four-byte IEEE 754)
+            {
+                float number{};
+                return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
+            {
+                double number{};
+                return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            default: // anything else (0xFF is handled inside the other types)
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a CBOR string
+
+    This function first reads starting bytes to determine the expected
+    string length and then copies this number of bytes into a string.
+    Additionally, CBOR's strings with indefinite lengths are supported.
+
+    @param[out] result  created string
+
+    @return whether string creation completed
+    */
+    bool get_cbor_string(string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            // UTF-8 string (0x00..0x17 bytes follow)
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            {
+                return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
+            }
+
+            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len{};
+                return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
+            }
+
+            case 0x7F: // UTF-8 string (indefinite length)
+            {
+                while (get() != 0xFF)
+                {
+                    string_t chunk;
+                    if (!get_cbor_string(chunk))
+                    {
+                        return false;
+                    }
+                    result.append(chunk);
+                }
+                return true;
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a CBOR byte array
+
+    This function first reads starting bytes to determine the expected
+    byte array length and then copies this number of bytes into the byte array.
+    Additionally, CBOR's byte arrays with indefinite lengths are supported.
+
+    @param[out] result  created byte array
+
+    @return whether byte array creation completed
+    */
+    bool get_cbor_binary(binary_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            // Binary data (0x00..0x17 bytes follow)
+            case 0x40:
+            case 0x41:
+            case 0x42:
+            case 0x43:
+            case 0x44:
+            case 0x45:
+            case 0x46:
+            case 0x47:
+            case 0x48:
+            case 0x49:
+            case 0x4A:
+            case 0x4B:
+            case 0x4C:
+            case 0x4D:
+            case 0x4E:
+            case 0x4F:
+            case 0x50:
+            case 0x51:
+            case 0x52:
+            case 0x53:
+            case 0x54:
+            case 0x55:
+            case 0x56:
+            case 0x57:
+            {
+                return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
+            }
+
+            case 0x58: // Binary data (one-byte uint8_t for n follows)
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::cbor, len) &&
+                       get_binary(input_format_t::cbor, len, result);
+            }
+
+            case 0x59: // Binary data (two-byte uint16_t for n follow)
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::cbor, len) &&
+                       get_binary(input_format_t::cbor, len, result);
+            }
+
+            case 0x5A: // Binary data (four-byte uint32_t for n follow)
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::cbor, len) &&
+                       get_binary(input_format_t::cbor, len, result);
+            }
+
+            case 0x5B: // Binary data (eight-byte uint64_t for n follow)
+            {
+                std::uint64_t len{};
+                return get_number(input_format_t::cbor, len) &&
+                       get_binary(input_format_t::cbor, len, result);
+            }
+
+            case 0x5F: // Binary data (indefinite length)
+            {
+                while (get() != 0xFF)
+                {
+                    binary_t chunk;
+                    if (!get_cbor_binary(chunk))
+                    {
+                        return false;
+                    }
+                    result.insert(result.end(), chunk.begin(), chunk.end());
+                }
+                return true;
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @param[in] len  the length of the array or static_cast<std::size_t>(-1) for an
+                    array of indefinite size
+    @param[in] tag_handler how CBOR tags should be treated
+    @return whether array creation completed
+    */
+    bool get_cbor_array(const std::size_t len,
+                        const cbor_tag_handler_t tag_handler)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
+        {
+            return false;
+        }
+
+        if (len != static_cast<std::size_t>(-1))
+        {
+            for (std::size_t i = 0; i < len; ++i)
+            {
+                if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
+                {
+                    return false;
+                }
+            }
+        }
+        else
+        {
+            while (get() != 0xFF)
+            {
+                if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))
+                {
+                    return false;
+                }
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @param[in] len  the length of the object or static_cast<std::size_t>(-1) for an
+                    object of indefinite size
+    @param[in] tag_handler how CBOR tags should be treated
+    @return whether object creation completed
+    */
+    bool get_cbor_object(const std::size_t len,
+                         const cbor_tag_handler_t tag_handler)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
+        {
+            return false;
+        }
+
+        if (len != 0)
+        {
+            string_t key;
+            if (len != static_cast<std::size_t>(-1))
+            {
+                for (std::size_t i = 0; i < len; ++i)
+                {
+                    get();
+                    if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
+                    {
+                        return false;
+                    }
+
+                    if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+            else
+            {
+                while (get() != 0xFF)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
+                    {
+                        return false;
+                    }
+
+                    if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+        }
+
+        return sax->end_object();
+    }
+
+    /////////////
+    // MsgPack //
+    /////////////
+
+    /*!
+    @return whether a valid MessagePack value was passed to the SAX parser
+    */
+    bool parse_msgpack_internal()
+    {
+        switch (get())
+        {
+            // EOF
+            case std::char_traits<char_type>::eof():
+                return unexpect_eof(input_format_t::msgpack, "value");
+
+            // positive fixint
+            case 0x00:
+            case 0x01:
+            case 0x02:
+            case 0x03:
+            case 0x04:
+            case 0x05:
+            case 0x06:
+            case 0x07:
+            case 0x08:
+            case 0x09:
+            case 0x0A:
+            case 0x0B:
+            case 0x0C:
+            case 0x0D:
+            case 0x0E:
+            case 0x0F:
+            case 0x10:
+            case 0x11:
+            case 0x12:
+            case 0x13:
+            case 0x14:
+            case 0x15:
+            case 0x16:
+            case 0x17:
+            case 0x18:
+            case 0x19:
+            case 0x1A:
+            case 0x1B:
+            case 0x1C:
+            case 0x1D:
+            case 0x1E:
+            case 0x1F:
+            case 0x20:
+            case 0x21:
+            case 0x22:
+            case 0x23:
+            case 0x24:
+            case 0x25:
+            case 0x26:
+            case 0x27:
+            case 0x28:
+            case 0x29:
+            case 0x2A:
+            case 0x2B:
+            case 0x2C:
+            case 0x2D:
+            case 0x2E:
+            case 0x2F:
+            case 0x30:
+            case 0x31:
+            case 0x32:
+            case 0x33:
+            case 0x34:
+            case 0x35:
+            case 0x36:
+            case 0x37:
+            case 0x38:
+            case 0x39:
+            case 0x3A:
+            case 0x3B:
+            case 0x3C:
+            case 0x3D:
+            case 0x3E:
+            case 0x3F:
+            case 0x40:
+            case 0x41:
+            case 0x42:
+            case 0x43:
+            case 0x44:
+            case 0x45:
+            case 0x46:
+            case 0x47:
+            case 0x48:
+            case 0x49:
+            case 0x4A:
+            case 0x4B:
+            case 0x4C:
+            case 0x4D:
+            case 0x4E:
+            case 0x4F:
+            case 0x50:
+            case 0x51:
+            case 0x52:
+            case 0x53:
+            case 0x54:
+            case 0x55:
+            case 0x56:
+            case 0x57:
+            case 0x58:
+            case 0x59:
+            case 0x5A:
+            case 0x5B:
+            case 0x5C:
+            case 0x5D:
+            case 0x5E:
+            case 0x5F:
+            case 0x60:
+            case 0x61:
+            case 0x62:
+            case 0x63:
+            case 0x64:
+            case 0x65:
+            case 0x66:
+            case 0x67:
+            case 0x68:
+            case 0x69:
+            case 0x6A:
+            case 0x6B:
+            case 0x6C:
+            case 0x6D:
+            case 0x6E:
+            case 0x6F:
+            case 0x70:
+            case 0x71:
+            case 0x72:
+            case 0x73:
+            case 0x74:
+            case 0x75:
+            case 0x76:
+            case 0x77:
+            case 0x78:
+            case 0x79:
+            case 0x7A:
+            case 0x7B:
+            case 0x7C:
+            case 0x7D:
+            case 0x7E:
+            case 0x7F:
+                return sax->number_unsigned(static_cast<number_unsigned_t>(current));
+
+            // fixmap
+            case 0x80:
+            case 0x81:
+            case 0x82:
+            case 0x83:
+            case 0x84:
+            case 0x85:
+            case 0x86:
+            case 0x87:
+            case 0x88:
+            case 0x89:
+            case 0x8A:
+            case 0x8B:
+            case 0x8C:
+            case 0x8D:
+            case 0x8E:
+            case 0x8F:
+                return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+            // fixarray
+            case 0x90:
+            case 0x91:
+            case 0x92:
+            case 0x93:
+            case 0x94:
+            case 0x95:
+            case 0x96:
+            case 0x97:
+            case 0x98:
+            case 0x99:
+            case 0x9A:
+            case 0x9B:
+            case 0x9C:
+            case 0x9D:
+            case 0x9E:
+            case 0x9F:
+                return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
+
+            // fixstr
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+            case 0xB8:
+            case 0xB9:
+            case 0xBA:
+            case 0xBB:
+            case 0xBC:
+            case 0xBD:
+            case 0xBE:
+            case 0xBF:
+            case 0xD9: // str 8
+            case 0xDA: // str 16
+            case 0xDB: // str 32
+            {
+                string_t s;
+                return get_msgpack_string(s) && sax->string(s);
+            }
+
+            case 0xC0: // nil
+                return sax->null();
+
+            case 0xC2: // false
+                return sax->boolean(false);
+
+            case 0xC3: // true
+                return sax->boolean(true);
+
+            case 0xC4: // bin 8
+            case 0xC5: // bin 16
+            case 0xC6: // bin 32
+            case 0xC7: // ext 8
+            case 0xC8: // ext 16
+            case 0xC9: // ext 32
+            case 0xD4: // fixext 1
+            case 0xD5: // fixext 2
+            case 0xD6: // fixext 4
+            case 0xD7: // fixext 8
+            case 0xD8: // fixext 16
+            {
+                binary_t b;
+                return get_msgpack_binary(b) && sax->binary(b);
+            }
+
+            case 0xCA: // float 32
+            {
+                float number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xCB: // float 64
+            {
+                double number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 0xCC: // uint 8
+            {
+                std::uint8_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+            }
+
+            case 0xCD: // uint 16
+            {
+                std::uint16_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+            }
+
+            case 0xCE: // uint 32
+            {
+                std::uint32_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+            }
+
+            case 0xCF: // uint 64
+            {
+                std::uint64_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
+            }
+
+            case 0xD0: // int 8
+            {
+                std::int8_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+            }
+
+            case 0xD1: // int 16
+            {
+                std::int16_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+            }
+
+            case 0xD2: // int 32
+            {
+                std::int32_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+            }
+
+            case 0xD3: // int 64
+            {
+                std::int64_t number{};
+                return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
+            }
+
+            case 0xDC: // array 16
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
+            }
+
+            case 0xDD: // array 32
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
+            }
+
+            case 0xDE: // map 16
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
+            }
+
+            case 0xDF: // map 32
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
+            }
+
+            // negative fixint
+            case 0xE0:
+            case 0xE1:
+            case 0xE2:
+            case 0xE3:
+            case 0xE4:
+            case 0xE5:
+            case 0xE6:
+            case 0xE7:
+            case 0xE8:
+            case 0xE9:
+            case 0xEA:
+            case 0xEB:
+            case 0xEC:
+            case 0xED:
+            case 0xEE:
+            case 0xEF:
+            case 0xF0:
+            case 0xF1:
+            case 0xF2:
+            case 0xF3:
+            case 0xF4:
+            case 0xF5:
+            case 0xF6:
+            case 0xF7:
+            case 0xF8:
+            case 0xF9:
+            case 0xFA:
+            case 0xFB:
+            case 0xFC:
+            case 0xFD:
+            case 0xFE:
+            case 0xFF:
+                return sax->number_integer(static_cast<std::int8_t>(current));
+
+            default: // anything else
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a MessagePack string
+
+    This function first reads starting bytes to determine the expected
+    string length and then copies this number of bytes into a string.
+
+    @param[out] result  created string
+
+    @return whether string creation completed
+    */
+    bool get_msgpack_string(string_t& result)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            // fixstr
+            case 0xA0:
+            case 0xA1:
+            case 0xA2:
+            case 0xA3:
+            case 0xA4:
+            case 0xA5:
+            case 0xA6:
+            case 0xA7:
+            case 0xA8:
+            case 0xA9:
+            case 0xAA:
+            case 0xAB:
+            case 0xAC:
+            case 0xAD:
+            case 0xAE:
+            case 0xAF:
+            case 0xB0:
+            case 0xB1:
+            case 0xB2:
+            case 0xB3:
+            case 0xB4:
+            case 0xB5:
+            case 0xB6:
+            case 0xB7:
+            case 0xB8:
+            case 0xB9:
+            case 0xBA:
+            case 0xBB:
+            case 0xBC:
+            case 0xBD:
+            case 0xBE:
+            case 0xBF:
+            {
+                return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
+            }
+
+            case 0xD9: // str 8
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+            }
+
+            case 0xDA: // str 16
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+            }
+
+            case 0xDB: // str 32
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief reads a MessagePack byte array
+
+    This function first reads starting bytes to determine the expected
+    byte array length and then copies this number of bytes into a byte array.
+
+    @param[out] result  created byte array
+
+    @return whether byte array creation completed
+    */
+    bool get_msgpack_binary(binary_t& result)
+    {
+        // helper function to set the subtype
+        auto assign_and_return_true = [&result](std::int8_t subtype)
+        {
+            result.set_subtype(static_cast<std::uint8_t>(subtype));
+            return true;
+        };
+
+        switch (current)
+        {
+            case 0xC4: // bin 8
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_binary(input_format_t::msgpack, len, result);
+            }
+
+            case 0xC5: // bin 16
+            {
+                std::uint16_t len{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_binary(input_format_t::msgpack, len, result);
+            }
+
+            case 0xC6: // bin 32
+            {
+                std::uint32_t len{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_binary(input_format_t::msgpack, len, result);
+            }
+
+            case 0xC7: // ext 8
+            {
+                std::uint8_t len{};
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, len, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xC8: // ext 16
+            {
+                std::uint16_t len{};
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, len, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xC9: // ext 32
+            {
+                std::uint32_t len{};
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, len) &&
+                       get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, len, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xD4: // fixext 1
+            {
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, 1, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xD5: // fixext 2
+            {
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, 2, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xD6: // fixext 4
+            {
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, 4, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xD7: // fixext 8
+            {
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, 8, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            case 0xD8: // fixext 16
+            {
+                std::int8_t subtype{};
+                return get_number(input_format_t::msgpack, subtype) &&
+                       get_binary(input_format_t::msgpack, 16, result) &&
+                       assign_and_return_true(subtype);
+            }
+
+            default:           // LCOV_EXCL_LINE
+                return false;  // LCOV_EXCL_LINE
+        }
+    }
+
+    /*!
+    @param[in] len  the length of the array
+    @return whether array creation completed
+    */
+    bool get_msgpack_array(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
+        {
+            return false;
+        }
+
+        for (std::size_t i = 0; i < len; ++i)
+        {
+            if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
+            {
+                return false;
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @param[in] len  the length of the object
+    @return whether object creation completed
+    */
+    bool get_msgpack_object(const std::size_t len)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
+        {
+            return false;
+        }
+
+        string_t key;
+        for (std::size_t i = 0; i < len; ++i)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
+            {
+                return false;
+            }
+
+            if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
+            {
+                return false;
+            }
+            key.clear();
+        }
+
+        return sax->end_object();
+    }
+
+    ////////////
+    // UBJSON //
+    ////////////
+
+    /*!
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true, default) or whether the last read
+                         character should be considered instead
+
+    @return whether a valid UBJSON value was passed to the SAX parser
+    */
+    bool parse_ubjson_internal(const bool get_char = true)
+    {
+        return get_ubjson_value(get_char ? get_ignore_noop() : current);
+    }
+
+    /*!
+    @brief reads a UBJSON string
+
+    This function is either called after reading the 'S' byte explicitly
+    indicating a string, or in case of an object key where the 'S' byte can be
+    left out.
+
+    @param[out] result   created string
+    @param[in] get_char  whether a new character should be retrieved from the
+                         input (true, default) or whether the last read
+                         character should be considered instead
+
+    @return whether string creation completed
+    */
+    bool get_ubjson_string(string_t& result, const bool get_char = true)
+    {
+        if (get_char)
+        {
+            get();  // TODO(niels): may we ignore N here?
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
+        {
+            return false;
+        }
+
+        switch (current)
+        {
+            case 'U':
+            {
+                std::uint8_t len{};
+                return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'i':
+            {
+                std::int8_t len{};
+                return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'I':
+            {
+                std::int16_t len{};
+                return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'l':
+            {
+                std::int32_t len{};
+                return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
+            }
+
+            case 'L':
+            {
+                std::int64_t len{};
+                return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
+            }
+
+            default:
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType()));
+        }
+    }
+
+    /*!
+    @param[out] result  determined size
+    @return whether size determination completed
+    */
+    bool get_ubjson_size_value(std::size_t& result)
+    {
+        switch (get_ignore_noop())
+        {
+            case 'U':
+            {
+                std::uint8_t number{};
+                if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'i':
+            {
+                std::int8_t number{};
+                if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char
+                return true;
+            }
+
+            case 'I':
+            {
+                std::int16_t number{};
+                if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'l':
+            {
+                std::int32_t number{};
+                if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            case 'L':
+            {
+                std::int64_t number{};
+                if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
+                {
+                    return false;
+                }
+                result = static_cast<std::size_t>(number);
+                return true;
+            }
+
+            default:
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @brief determine the type and size for a container
+
+    In the optimized UBJSON format, a type and a size can be provided to allow
+    for a more compact representation.
+
+    @param[out] result  pair of the size and the type
+
+    @return whether pair creation completed
+    */
+    bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
+    {
+        result.first = string_t::npos; // size
+        result.second = 0; // type
+
+        get_ignore_noop();
+
+        if (current == '$')
+        {
+            result.second = get();  // must not ignore 'N', because 'N' maybe the type
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
+            {
+                return false;
+            }
+
+            get_ignore_noop();
+            if (JSON_HEDLEY_UNLIKELY(current != '#'))
+            {
+                if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
+                {
+                    return false;
+                }
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType()));
+            }
+
+            return get_ubjson_size_value(result.first);
+        }
+
+        if (current == '#')
+        {
+            return get_ubjson_size_value(result.first);
+        }
+
+        return true;
+    }
+
+    /*!
+    @param prefix  the previously read or set type prefix
+    @return whether value creation completed
+    */
+    bool get_ubjson_value(const char_int_type prefix)
+    {
+        switch (prefix)
+        {
+            case std::char_traits<char_type>::eof():  // EOF
+                return unexpect_eof(input_format_t::ubjson, "value");
+
+            case 'T':  // true
+                return sax->boolean(true);
+            case 'F':  // false
+                return sax->boolean(false);
+
+            case 'Z':  // null
+                return sax->null();
+
+            case 'U':
+            {
+                std::uint8_t number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
+            }
+
+            case 'i':
+            {
+                std::int8_t number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
+            }
+
+            case 'I':
+            {
+                std::int16_t number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
+            }
+
+            case 'l':
+            {
+                std::int32_t number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
+            }
+
+            case 'L':
+            {
+                std::int64_t number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
+            }
+
+            case 'd':
+            {
+                float number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 'D':
+            {
+                double number{};
+                return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
+            }
+
+            case 'H':
+            {
+                return get_ubjson_high_precision_number();
+            }
+
+            case 'C':  // char
+            {
+                get();
+                if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
+                {
+                    return false;
+                }
+                if (JSON_HEDLEY_UNLIKELY(current > 127))
+                {
+                    auto last_token = get_token_string();
+                    return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType()));
+                }
+                string_t s(1, static_cast<typename string_t::value_type>(current));
+                return sax->string(s);
+            }
+
+            case 'S':  // string
+            {
+                string_t s;
+                return get_ubjson_string(s) && sax->string(s);
+            }
+
+            case '[':  // array
+                return get_ubjson_array();
+
+            case '{':  // object
+                return get_ubjson_object();
+
+            default: // anything else
+            {
+                auto last_token = get_token_string();
+                return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType()));
+            }
+        }
+    }
+
+    /*!
+    @return whether array creation completed
+    */
+    bool get_ubjson_array()
+    {
+        std::pair<std::size_t, char_int_type> size_and_type;
+        if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
+        {
+            return false;
+        }
+
+        if (size_and_type.first != string_t::npos)
+        {
+            if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
+            {
+                return false;
+            }
+
+            if (size_and_type.second != 0)
+            {
+                if (size_and_type.second != 'N')
+                {
+                    for (std::size_t i = 0; i < size_and_type.first; ++i)
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
+                        {
+                            return false;
+                        }
+                    }
+                }
+            }
+            else
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
+                    {
+                        return false;
+                    }
+                }
+            }
+        }
+        else
+        {
+            if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
+            {
+                return false;
+            }
+
+            while (current != ']')
+            {
+                if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
+                {
+                    return false;
+                }
+                get_ignore_noop();
+            }
+        }
+
+        return sax->end_array();
+    }
+
+    /*!
+    @return whether object creation completed
+    */
+    bool get_ubjson_object()
+    {
+        std::pair<std::size_t, char_int_type> size_and_type;
+        if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
+        {
+            return false;
+        }
+
+        string_t key;
+        if (size_and_type.first != string_t::npos)
+        {
+            if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
+            {
+                return false;
+            }
+
+            if (size_and_type.second != 0)
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
+                    {
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+            else
+            {
+                for (std::size_t i = 0; i < size_and_type.first; ++i)
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
+                    {
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
+                    {
+                        return false;
+                    }
+                    key.clear();
+                }
+            }
+        }
+        else
+        {
+            if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
+            {
+                return false;
+            }
+
+            while (current != '}')
+            {
+                if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
+                {
+                    return false;
+                }
+                if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
+                {
+                    return false;
+                }
+                get_ignore_noop();
+                key.clear();
+            }
+        }
+
+        return sax->end_object();
+    }
+
+    // Note, no reader for UBJSON binary types is implemented because they do
+    // not exist
+
+    bool get_ubjson_high_precision_number()
+    {
+        // get size of following number string
+        std::size_t size{};
+        auto res = get_ubjson_size_value(size);
+        if (JSON_HEDLEY_UNLIKELY(!res))
+        {
+            return res;
+        }
+
+        // get number string
+        std::vector<char> number_vector;
+        for (std::size_t i = 0; i < size; ++i)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number")))
+            {
+                return false;
+            }
+            number_vector.push_back(static_cast<char>(current));
+        }
+
+        // parse number string
+        using ia_type = decltype(detail::input_adapter(number_vector));
+        auto number_lexer = detail::lexer<BasicJsonType, ia_type>(detail::input_adapter(number_vector), false);
+        const auto result_number = number_lexer.scan();
+        const auto number_string = number_lexer.get_token_string();
+        const auto result_remainder = number_lexer.scan();
+
+        using token_type = typename detail::lexer_base<BasicJsonType>::token_type;
+
+        if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))
+        {
+            return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
+        }
+
+        switch (result_number)
+        {
+            case token_type::value_integer:
+                return sax->number_integer(number_lexer.get_number_integer());
+            case token_type::value_unsigned:
+                return sax->number_unsigned(number_lexer.get_number_unsigned());
+            case token_type::value_float:
+                return sax->number_float(number_lexer.get_number_float(), std::move(number_string));
+            case token_type::uninitialized:
+            case token_type::literal_true:
+            case token_type::literal_false:
+            case token_type::literal_null:
+            case token_type::value_string:
+            case token_type::begin_array:
+            case token_type::begin_object:
+            case token_type::end_array:
+            case token_type::end_object:
+            case token_type::name_separator:
+            case token_type::value_separator:
+            case token_type::parse_error:
+            case token_type::end_of_input:
+            case token_type::literal_or_value:
+            default:
+                return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType()));
+        }
+    }
+
+    ///////////////////////
+    // Utility functions //
+    ///////////////////////
+
+    /*!
+    @brief get next character from the input
+
+    This function provides the interface to the used input adapter. It does
+    not throw in case the input reached EOF, but returns a -'ve valued
+    `std::char_traits<char_type>::eof()` in that case.
+
+    @return character read from the input
+    */
+    char_int_type get()
+    {
+        ++chars_read;
+        return current = ia.get_character();
+    }
+
+    /*!
+    @return character read from the input after ignoring all 'N' entries
+    */
+    char_int_type get_ignore_noop()
+    {
+        do
+        {
+            get();
+        }
+        while (current == 'N');
+
+        return current;
+    }
+
+    /*
+    @brief read a number from the input
+
+    @tparam NumberType the type of the number
+    @param[in] format   the current format (for diagnostics)
+    @param[out] result  number of type @a NumberType
+
+    @return whether conversion completed
+
+    @note This function needs to respect the system's endianness, because
+          bytes in CBOR, MessagePack, and UBJSON are stored in network order
+          (big endian) and therefore need reordering on little endian systems.
+    */
+    template<typename NumberType, bool InputIsLittleEndian = false>
+    bool get_number(const input_format_t format, NumberType& result)
+    {
+        // step 1: read input into array with system's byte order
+        std::array<std::uint8_t, sizeof(NumberType)> vec{};
+        for (std::size_t i = 0; i < sizeof(NumberType); ++i)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
+            {
+                return false;
+            }
+
+            // reverse byte order prior to conversion if necessary
+            if (is_little_endian != InputIsLittleEndian)
+            {
+                vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
+            }
+            else
+            {
+                vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
+            }
+        }
+
+        // step 2: convert array into number of type T and return
+        std::memcpy(&result, vec.data(), sizeof(NumberType));
+        return true;
+    }
+
+    /*!
+    @brief create a string by reading characters from the input
+
+    @tparam NumberType the type of the number
+    @param[in] format the current format (for diagnostics)
+    @param[in] len number of characters to read
+    @param[out] result string created by reading @a len bytes
+
+    @return whether string creation completed
+
+    @note We can not reserve @a len bytes for the result, because @a len
+          may be too large. Usually, @ref unexpect_eof() detects the end of
+          the input before we run out of string memory.
+    */
+    template<typename NumberType>
+    bool get_string(const input_format_t format,
+                    const NumberType len,
+                    string_t& result)
+    {
+        bool success = true;
+        for (NumberType i = 0; i < len; i++)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
+            {
+                success = false;
+                break;
+            }
+            result.push_back(static_cast<typename string_t::value_type>(current));
+        }
+        return success;
+    }
+
+    /*!
+    @brief create a byte array by reading bytes from the input
+
+    @tparam NumberType the type of the number
+    @param[in] format the current format (for diagnostics)
+    @param[in] len number of bytes to read
+    @param[out] result byte array created by reading @a len bytes
+
+    @return whether byte array creation completed
+
+    @note We can not reserve @a len bytes for the result, because @a len
+          may be too large. Usually, @ref unexpect_eof() detects the end of
+          the input before we run out of memory.
+    */
+    template<typename NumberType>
+    bool get_binary(const input_format_t format,
+                    const NumberType len,
+                    binary_t& result)
+    {
+        bool success = true;
+        for (NumberType i = 0; i < len; i++)
+        {
+            get();
+            if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
+            {
+                success = false;
+                break;
+            }
+            result.push_back(static_cast<std::uint8_t>(current));
+        }
+        return success;
+    }
+
+    /*!
+    @param[in] format   the current format (for diagnostics)
+    @param[in] context  further context information (for diagnostics)
+    @return whether the last read character is not EOF
+    */
+    JSON_HEDLEY_NON_NULL(3)
+    bool unexpect_eof(const input_format_t format, const char* context) const
+    {
+        if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
+        {
+            return sax->parse_error(chars_read, "<end of file>",
+                                    parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType()));
+        }
+        return true;
+    }
+
+    /*!
+    @return a string representation of the last read byte
+    */
+    std::string get_token_string() const
+    {
+        std::array<char, 3> cr{{}};
+        static_cast<void>((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+        return std::string{cr.data()};
+    }
+
+    /*!
+    @param[in] format   the current format
+    @param[in] detail   a detailed error message
+    @param[in] context  further context information
+    @return a message string to use in the parse_error exceptions
+    */
+    std::string exception_message(const input_format_t format,
+                                  const std::string& detail,
+                                  const std::string& context) const
+    {
+        std::string error_msg = "syntax error while parsing ";
+
+        switch (format)
+        {
+            case input_format_t::cbor:
+                error_msg += "CBOR";
+                break;
+
+            case input_format_t::msgpack:
+                error_msg += "MessagePack";
+                break;
+
+            case input_format_t::ubjson:
+                error_msg += "UBJSON";
+                break;
+
+            case input_format_t::bson:
+                error_msg += "BSON";
+                break;
+
+            case input_format_t::json: // LCOV_EXCL_LINE
+            default:            // LCOV_EXCL_LINE
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        }
+
+        return error_msg + " " + context + ": " + detail;
+    }
+
+  private:
+    /// input adapter
+    InputAdapterType ia;
+
+    /// the current character
+    char_int_type current = std::char_traits<char_type>::eof();
+
+    /// the number of characters read
+    std::size_t chars_read = 0;
+
+    /// whether we can assume little endianness
+    const bool is_little_endian = little_endianness();
+
+    /// the SAX parser
+    json_sax_t* sax = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+// #include <nlohmann/detail/input/parser.hpp>
+
+
+#include <cmath> // isfinite
+#include <cstdint> // uint8_t
+#include <functional> // function
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/input/input_adapters.hpp>
+
+// #include <nlohmann/detail/input/json_sax.hpp>
+
+// #include <nlohmann/detail/input/lexer.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/is_sax.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+////////////
+// parser //
+////////////
+
+enum class parse_event_t : std::uint8_t
+{
+    /// the parser read `{` and started to process a JSON object
+    object_start,
+    /// the parser read `}` and finished processing a JSON object
+    object_end,
+    /// the parser read `[` and started to process a JSON array
+    array_start,
+    /// the parser read `]` and finished processing a JSON array
+    array_end,
+    /// the parser read a key of a value in an object
+    key,
+    /// the parser finished reading a JSON value
+    value
+};
+
+template<typename BasicJsonType>
+using parser_callback_t =
+    std::function<bool(int /*depth*/, parse_event_t /*event*/, BasicJsonType& /*parsed*/)>;
+
+/*!
+@brief syntax analysis
+
+This class implements a recursive descent parser.
+*/
+template<typename BasicJsonType, typename InputAdapterType>
+class parser
+{
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using string_t = typename BasicJsonType::string_t;
+    using lexer_t = lexer<BasicJsonType, InputAdapterType>;
+    using token_type = typename lexer_t::token_type;
+
+  public:
+    /// a parser reading from an input adapter
+    explicit parser(InputAdapterType&& adapter,
+                    const parser_callback_t<BasicJsonType> cb = nullptr,
+                    const bool allow_exceptions_ = true,
+                    const bool skip_comments = false)
+        : callback(cb)
+        , m_lexer(std::move(adapter), skip_comments)
+        , allow_exceptions(allow_exceptions_)
+    {
+        // read first token
+        get_token();
+    }
+
+    /*!
+    @brief public parser interface
+
+    @param[in] strict      whether to expect the last token to be EOF
+    @param[in,out] result  parsed JSON value
+
+    @throw parse_error.101 in case of an unexpected token
+    @throw parse_error.102 if to_unicode fails or surrogate error
+    @throw parse_error.103 if to_unicode fails
+    */
+    void parse(const bool strict, BasicJsonType& result)
+    {
+        if (callback)
+        {
+            json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
+            sax_parse_internal(&sdp);
+
+            // in strict mode, input must be completely read
+            if (strict && (get_token() != token_type::end_of_input))
+            {
+                sdp.parse_error(m_lexer.get_position(),
+                                m_lexer.get_token_string(),
+                                parse_error::create(101, m_lexer.get_position(),
+                                                    exception_message(token_type::end_of_input, "value"), BasicJsonType()));
+            }
+
+            // in case of an error, return discarded value
+            if (sdp.is_errored())
+            {
+                result = value_t::discarded;
+                return;
+            }
+
+            // set top-level value to null if it was discarded by the callback
+            // function
+            if (result.is_discarded())
+            {
+                result = nullptr;
+            }
+        }
+        else
+        {
+            json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
+            sax_parse_internal(&sdp);
+
+            // in strict mode, input must be completely read
+            if (strict && (get_token() != token_type::end_of_input))
+            {
+                sdp.parse_error(m_lexer.get_position(),
+                                m_lexer.get_token_string(),
+                                parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
+            }
+
+            // in case of an error, return discarded value
+            if (sdp.is_errored())
+            {
+                result = value_t::discarded;
+                return;
+            }
+        }
+
+        result.assert_invariant();
+    }
+
+    /*!
+    @brief public accept interface
+
+    @param[in] strict  whether to expect the last token to be EOF
+    @return whether the input is a proper JSON text
+    */
+    bool accept(const bool strict = true)
+    {
+        json_sax_acceptor<BasicJsonType> sax_acceptor;
+        return sax_parse(&sax_acceptor, strict);
+    }
+
+    template<typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    bool sax_parse(SAX* sax, const bool strict = true)
+    {
+        (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
+        const bool result = sax_parse_internal(sax);
+
+        // strict mode: next byte must be EOF
+        if (result && strict && (get_token() != token_type::end_of_input))
+        {
+            return sax->parse_error(m_lexer.get_position(),
+                                    m_lexer.get_token_string(),
+                                    parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType()));
+        }
+
+        return result;
+    }
+
+  private:
+    template<typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    bool sax_parse_internal(SAX* sax)
+    {
+        // stack to remember the hierarchy of structured values we are parsing
+        // true = array; false = object
+        std::vector<bool> states;
+        // value to avoid a goto (see comment where set to true)
+        bool skip_to_state_evaluation = false;
+
+        while (true)
+        {
+            if (!skip_to_state_evaluation)
+            {
+                // invariant: get_token() was called before each iteration
+                switch (last_token)
+                {
+                    case token_type::begin_object:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast<std::size_t>(-1))))
+                        {
+                            return false;
+                        }
+
+                        // closing } -> we are done
+                        if (get_token() == token_type::end_object)
+                        {
+                            if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
+                            {
+                                return false;
+                            }
+                            break;
+                        }
+
+                        // parse key
+                        if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
+                        }
+                        if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+
+                        // parse separator (:)
+                        if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
+                        }
+
+                        // remember we are now inside an object
+                        states.push_back(false);
+
+                        // parse values
+                        get_token();
+                        continue;
+                    }
+
+                    case token_type::begin_array:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast<std::size_t>(-1))))
+                        {
+                            return false;
+                        }
+
+                        // closing ] -> we are done
+                        if (get_token() == token_type::end_array)
+                        {
+                            if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
+                            {
+                                return false;
+                            }
+                            break;
+                        }
+
+                        // remember we are now inside an array
+                        states.push_back(true);
+
+                        // parse values (no need to call get_token)
+                        continue;
+                    }
+
+                    case token_type::value_float:
+                    {
+                        const auto res = m_lexer.get_number_float();
+
+                        if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
+                        {
+                            return sax->parse_error(m_lexer.get_position(),
+                                                    m_lexer.get_token_string(),
+                                                    out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType()));
+                        }
+
+                        if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+
+                        break;
+                    }
+
+                    case token_type::literal_false:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::literal_null:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->null()))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::literal_true:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_integer:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_string:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::value_unsigned:
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
+                        {
+                            return false;
+                        }
+                        break;
+                    }
+
+                    case token_type::parse_error:
+                    {
+                        // using "uninitialized" to avoid "expected" message
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType()));
+                    }
+
+                    case token_type::uninitialized:
+                    case token_type::end_array:
+                    case token_type::end_object:
+                    case token_type::name_separator:
+                    case token_type::value_separator:
+                    case token_type::end_of_input:
+                    case token_type::literal_or_value:
+                    default: // the last token was unexpected
+                    {
+                        return sax->parse_error(m_lexer.get_position(),
+                                                m_lexer.get_token_string(),
+                                                parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType()));
+                    }
+                }
+            }
+            else
+            {
+                skip_to_state_evaluation = false;
+            }
+
+            // we reached this line after we successfully parsed a value
+            if (states.empty())
+            {
+                // empty stack: we reached the end of the hierarchy: done
+                return true;
+            }
+
+            if (states.back())  // array
+            {
+                // comma -> next value
+                if (get_token() == token_type::value_separator)
+                {
+                    // parse a new value
+                    get_token();
+                    continue;
+                }
+
+                // closing ]
+                if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
+                {
+                    if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
+                    {
+                        return false;
+                    }
+
+                    // We are done with this array. Before we can parse a
+                    // new value, we need to evaluate the new state first.
+                    // By setting skip_to_state_evaluation to false, we
+                    // are effectively jumping to the beginning of this if.
+                    JSON_ASSERT(!states.empty());
+                    states.pop_back();
+                    skip_to_state_evaluation = true;
+                    continue;
+                }
+
+                return sax->parse_error(m_lexer.get_position(),
+                                        m_lexer.get_token_string(),
+                                        parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType()));
+            }
+
+            // states.back() is false -> object
+
+            // comma -> next value
+            if (get_token() == token_type::value_separator)
+            {
+                // parse key
+                if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
+                {
+                    return sax->parse_error(m_lexer.get_position(),
+                                            m_lexer.get_token_string(),
+                                            parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType()));
+                }
+
+                if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
+                {
+                    return false;
+                }
+
+                // parse separator (:)
+                if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
+                {
+                    return sax->parse_error(m_lexer.get_position(),
+                                            m_lexer.get_token_string(),
+                                            parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType()));
+                }
+
+                // parse values
+                get_token();
+                continue;
+            }
+
+            // closing }
+            if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
+            {
+                if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
+                {
+                    return false;
+                }
+
+                // We are done with this object. Before we can parse a
+                // new value, we need to evaluate the new state first.
+                // By setting skip_to_state_evaluation to false, we
+                // are effectively jumping to the beginning of this if.
+                JSON_ASSERT(!states.empty());
+                states.pop_back();
+                skip_to_state_evaluation = true;
+                continue;
+            }
+
+            return sax->parse_error(m_lexer.get_position(),
+                                    m_lexer.get_token_string(),
+                                    parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType()));
+        }
+    }
+
+    /// get next token from lexer
+    token_type get_token()
+    {
+        return last_token = m_lexer.scan();
+    }
+
+    std::string exception_message(const token_type expected, const std::string& context)
+    {
+        std::string error_msg = "syntax error ";
+
+        if (!context.empty())
+        {
+            error_msg += "while parsing " + context + " ";
+        }
+
+        error_msg += "- ";
+
+        if (last_token == token_type::parse_error)
+        {
+            error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
+                         m_lexer.get_token_string() + "'";
+        }
+        else
+        {
+            error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
+        }
+
+        if (expected != token_type::uninitialized)
+        {
+            error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
+        }
+
+        return error_msg;
+    }
+
+  private:
+    /// callback function
+    const parser_callback_t<BasicJsonType> callback = nullptr;
+    /// the type of the last read token
+    token_type last_token = token_type::uninitialized;
+    /// the lexer
+    lexer_t m_lexer;
+    /// whether to throw exceptions in case of errors
+    const bool allow_exceptions = true;
+};
+
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+
+#include <cstddef> // ptrdiff_t
+#include <limits>  // numeric_limits
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/*
+@brief an iterator for primitive JSON types
+
+This class models an iterator for primitive JSON types (boolean, number,
+string). It's only purpose is to allow the iterator/const_iterator classes
+to "iterate" over primitive values. Internally, the iterator is modeled by
+a `difference_type` variable. Value begin_value (`0`) models the begin,
+end_value (`1`) models past the end.
+*/
+class primitive_iterator_t
+{
+  private:
+    using difference_type = std::ptrdiff_t;
+    static constexpr difference_type begin_value = 0;
+    static constexpr difference_type end_value = begin_value + 1;
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    /// iterator as signed integer type
+    difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
+
+  public:
+    constexpr difference_type get_value() const noexcept
+    {
+        return m_it;
+    }
+
+    /// set iterator to a defined beginning
+    void set_begin() noexcept
+    {
+        m_it = begin_value;
+    }
+
+    /// set iterator to a defined past the end
+    void set_end() noexcept
+    {
+        m_it = end_value;
+    }
+
+    /// return whether the iterator can be dereferenced
+    constexpr bool is_begin() const noexcept
+    {
+        return m_it == begin_value;
+    }
+
+    /// return whether the iterator is at end
+    constexpr bool is_end() const noexcept
+    {
+        return m_it == end_value;
+    }
+
+    friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it == rhs.m_it;
+    }
+
+    friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it < rhs.m_it;
+    }
+
+    primitive_iterator_t operator+(difference_type n) noexcept
+    {
+        auto result = *this;
+        result += n;
+        return result;
+    }
+
+    friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
+    {
+        return lhs.m_it - rhs.m_it;
+    }
+
+    primitive_iterator_t& operator++() noexcept
+    {
+        ++m_it;
+        return *this;
+    }
+
+    primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type)
+    {
+        auto result = *this;
+        ++m_it;
+        return result;
+    }
+
+    primitive_iterator_t& operator--() noexcept
+    {
+        --m_it;
+        return *this;
+    }
+
+    primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type)
+    {
+        auto result = *this;
+        --m_it;
+        return result;
+    }
+
+    primitive_iterator_t& operator+=(difference_type n) noexcept
+    {
+        m_it += n;
+        return *this;
+    }
+
+    primitive_iterator_t& operator-=(difference_type n) noexcept
+    {
+        m_it -= n;
+        return *this;
+    }
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/*!
+@brief an iterator value
+
+@note This structure could easily be a union, but MSVC currently does not allow
+unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
+*/
+template<typename BasicJsonType> struct internal_iterator
+{
+    /// iterator for JSON objects
+    typename BasicJsonType::object_t::iterator object_iterator {};
+    /// iterator for JSON arrays
+    typename BasicJsonType::array_t::iterator array_iterator {};
+    /// generic iterator for all other types
+    primitive_iterator_t primitive_iterator {};
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/iter_impl.hpp>
+
+
+#include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
+#include <type_traits> // conditional, is_const, remove_const
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/iterators/internal_iterator.hpp>
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+// forward declare, to be able to friend it later on
+template<typename IteratorType> class iteration_proxy;
+template<typename IteratorType> class iteration_proxy_value;
+
+/*!
+@brief a template for a bidirectional iterator for the @ref basic_json class
+This class implements a both iterators (iterator and const_iterator) for the
+@ref basic_json class.
+@note An iterator is called *initialized* when a pointer to a JSON value has
+      been set (e.g., by a constructor or a copy assignment). If the iterator is
+      default-constructed, it is *uninitialized* and most methods are undefined.
+      **The library uses assertions to detect calls on uninitialized iterators.**
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+  The iterator that can be moved can be moved in both directions (i.e.
+  incremented and decremented).
+@since version 1.0.0, simplified in version 2.0.9, change to bidirectional
+       iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
+*/
+template<typename BasicJsonType>
+class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
+{
+    /// the iterator with BasicJsonType of different const-ness
+    using other_iter_impl = iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
+    /// allow basic_json to access private members
+    friend other_iter_impl;
+    friend BasicJsonType;
+    friend iteration_proxy<iter_impl>;
+    friend iteration_proxy_value<iter_impl>;
+
+    using object_t = typename BasicJsonType::object_t;
+    using array_t = typename BasicJsonType::array_t;
+    // make sure BasicJsonType is basic_json or const basic_json
+    static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
+                  "iter_impl only accepts (const) basic_json");
+
+  public:
+
+    /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
+    /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
+    /// A user-defined iterator should provide publicly accessible typedefs named
+    /// iterator_category, value_type, difference_type, pointer, and reference.
+    /// Note that value_type is required to be non-const, even for constant iterators.
+    using iterator_category = std::bidirectional_iterator_tag;
+
+    /// the type of the values when the iterator is dereferenced
+    using value_type = typename BasicJsonType::value_type;
+    /// a type to represent differences between iterators
+    using difference_type = typename BasicJsonType::difference_type;
+    /// defines a pointer to the type iterated over (value_type)
+    using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
+          typename BasicJsonType::const_pointer,
+          typename BasicJsonType::pointer>::type;
+    /// defines a reference to the type iterated over (value_type)
+    using reference =
+        typename std::conditional<std::is_const<BasicJsonType>::value,
+        typename BasicJsonType::const_reference,
+        typename BasicJsonType::reference>::type;
+
+    iter_impl() = default;
+    ~iter_impl() = default;
+    iter_impl(iter_impl&&) noexcept = default;
+    iter_impl& operator=(iter_impl&&) noexcept = default;
+
+    /*!
+    @brief constructor for a given JSON instance
+    @param[in] object  pointer to a JSON object for this iterator
+    @pre object != nullptr
+    @post The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    explicit iter_impl(pointer object) noexcept : m_object(object)
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = typename object_t::iterator();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = typename array_t::iterator();
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                m_it.primitive_iterator = primitive_iterator_t();
+                break;
+            }
+        }
+    }
+
+    /*!
+    @note The conventional copy constructor and copy assignment are implicitly
+          defined. Combined with the following converting constructor and
+          assignment, they support: (1) copy from iterator to iterator, (2)
+          copy from const iterator to const iterator, and (3) conversion from
+          iterator to const iterator. However conversion from const iterator
+          to iterator is not defined.
+    */
+
+    /*!
+    @brief const copy constructor
+    @param[in] other const iterator to copy from
+    @note This copy constructor had to be defined explicitly to circumvent a bug
+          occurring on msvc v19.0 compiler (VS 2015) debug build. For more
+          information refer to: https://github.com/nlohmann/json/issues/1608
+    */
+    iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
+        : m_object(other.m_object), m_it(other.m_it)
+    {}
+
+    /*!
+    @brief converting assignment
+    @param[in] other const iterator to copy from
+    @return const/non-const iterator
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
+    {
+        if (&other != this)
+        {
+            m_object = other.m_object;
+            m_it = other.m_it;
+        }
+        return *this;
+    }
+
+    /*!
+    @brief converting constructor
+    @param[in] other  non-const iterator to copy from
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
+        : m_object(other.m_object), m_it(other.m_it)
+    {}
+
+    /*!
+    @brief converting assignment
+    @param[in] other  non-const iterator to copy from
+    @return const/non-const iterator
+    @note It is not checked whether @a other is initialized.
+    */
+    iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept // NOLINT(cert-oop54-cpp)
+    {
+        m_object = other.m_object;
+        m_it = other.m_it;
+        return *this;
+    }
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    /*!
+    @brief set the iterator to the first value
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    void set_begin() noexcept
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = m_object->m_value.object->begin();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = m_object->m_value.array->begin();
+                break;
+            }
+
+            case value_t::null:
+            {
+                // set to end so begin()==end() is true: null is empty
+                m_it.primitive_iterator.set_end();
+                break;
+            }
+
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                m_it.primitive_iterator.set_begin();
+                break;
+            }
+        }
+    }
+
+    /*!
+    @brief set the iterator past the last value
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    void set_end() noexcept
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                m_it.object_iterator = m_object->m_value.object->end();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_it.array_iterator = m_object->m_value.array->end();
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                m_it.primitive_iterator.set_end();
+                break;
+            }
+        }
+    }
+
+  public:
+    /*!
+    @brief return a reference to the value pointed to by the iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference operator*() const
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
+                return m_it.object_iterator->second;
+            }
+
+            case value_t::array:
+            {
+                JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
+                return *m_it.array_iterator;
+            }
+
+            case value_t::null:
+                JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
+
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
+                {
+                    return *m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
+            }
+        }
+    }
+
+    /*!
+    @brief dereference the iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    pointer operator->() const
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
+                return &(m_it.object_iterator->second);
+            }
+
+            case value_t::array:
+            {
+                JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
+                return &*m_it.array_iterator;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
+                {
+                    return m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
+            }
+        }
+    }
+
+    /*!
+    @brief post-increment (it++)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl const operator++(int) // NOLINT(readability-const-return-type)
+    {
+        auto result = *this;
+        ++(*this);
+        return result;
+    }
+
+    /*!
+    @brief pre-increment (++it)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator++()
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                std::advance(m_it.object_iterator, 1);
+                break;
+            }
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, 1);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                ++m_it.primitive_iterator;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief post-decrement (it--)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl const operator--(int) // NOLINT(readability-const-return-type)
+    {
+        auto result = *this;
+        --(*this);
+        return result;
+    }
+
+    /*!
+    @brief pre-decrement (--it)
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator--()
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+            {
+                std::advance(m_it.object_iterator, -1);
+                break;
+            }
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, -1);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                --m_it.primitive_iterator;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief comparison: equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr >
+    bool operator==(const IterImpl& other) const
+    {
+        // if objects are not the same, the comparison is undefined
+        if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
+        }
+
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                return (m_it.object_iterator == other.m_it.object_iterator);
+
+            case value_t::array:
+                return (m_it.array_iterator == other.m_it.array_iterator);
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                return (m_it.primitive_iterator == other.m_it.primitive_iterator);
+        }
+    }
+
+    /*!
+    @brief comparison: not equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    template < typename IterImpl, detail::enable_if_t < (std::is_same<IterImpl, iter_impl>::value || std::is_same<IterImpl, other_iter_impl>::value), std::nullptr_t > = nullptr >
+    bool operator!=(const IterImpl& other) const
+    {
+        return !operator==(other);
+    }
+
+    /*!
+    @brief comparison: smaller
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator<(const iter_impl& other) const
+    {
+        // if objects are not the same, the comparison is undefined
+        if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object));
+        }
+
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object));
+
+            case value_t::array:
+                return (m_it.array_iterator < other.m_it.array_iterator);
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                return (m_it.primitive_iterator < other.m_it.primitive_iterator);
+        }
+    }
+
+    /*!
+    @brief comparison: less than or equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator<=(const iter_impl& other) const
+    {
+        return !other.operator < (*this);
+    }
+
+    /*!
+    @brief comparison: greater than
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator>(const iter_impl& other) const
+    {
+        return !operator<=(other);
+    }
+
+    /*!
+    @brief comparison: greater than or equal
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    bool operator>=(const iter_impl& other) const
+    {
+        return !operator<(other);
+    }
+
+    /*!
+    @brief add to iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator+=(difference_type i)
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
+
+            case value_t::array:
+            {
+                std::advance(m_it.array_iterator, i);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                m_it.primitive_iterator += i;
+                break;
+            }
+        }
+
+        return *this;
+    }
+
+    /*!
+    @brief subtract from iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl& operator-=(difference_type i)
+    {
+        return operator+=(-i);
+    }
+
+    /*!
+    @brief add to iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl operator+(difference_type i) const
+    {
+        auto result = *this;
+        result += i;
+        return result;
+    }
+
+    /*!
+    @brief addition of distance and iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    friend iter_impl operator+(difference_type i, const iter_impl& it)
+    {
+        auto result = it;
+        result += i;
+        return result;
+    }
+
+    /*!
+    @brief subtract from iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    iter_impl operator-(difference_type i) const
+    {
+        auto result = *this;
+        result -= i;
+        return result;
+    }
+
+    /*!
+    @brief return difference
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    difference_type operator-(const iter_impl& other) const
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object));
+
+            case value_t::array:
+                return m_it.array_iterator - other.m_it.array_iterator;
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                return m_it.primitive_iterator - other.m_it.primitive_iterator;
+        }
+    }
+
+    /*!
+    @brief access to successor
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference operator[](difference_type n) const
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        switch (m_object->m_type)
+        {
+            case value_t::object:
+                JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object));
+
+            case value_t::array:
+                return *std::next(m_it.array_iterator, n);
+
+            case value_t::null:
+                JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
+
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
+                {
+                    return *m_object;
+                }
+
+                JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object));
+            }
+        }
+    }
+
+    /*!
+    @brief return the key of an object iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    const typename object_t::key_type& key() const
+    {
+        JSON_ASSERT(m_object != nullptr);
+
+        if (JSON_HEDLEY_LIKELY(m_object->is_object()))
+        {
+            return m_it.object_iterator->first;
+        }
+
+        JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object));
+    }
+
+    /*!
+    @brief return the value of an iterator
+    @pre The iterator is initialized; i.e. `m_object != nullptr`.
+    */
+    reference value() const
+    {
+        return operator*();
+    }
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    /// associated JSON instance
+    pointer m_object = nullptr;
+    /// the actual iterator of the associated instance
+    internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
+};
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
+
+// #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
+
+
+#include <cstddef> // ptrdiff_t
+#include <iterator> // reverse_iterator
+#include <utility> // declval
+
+namespace nlohmann
+{
+namespace detail
+{
+//////////////////////
+// reverse_iterator //
+//////////////////////
+
+/*!
+@brief a template for a reverse iterator class
+
+@tparam Base the base iterator type to reverse. Valid types are @ref
+iterator (to create @ref reverse_iterator) and @ref const_iterator (to
+create @ref const_reverse_iterator).
+
+@requirement The class satisfies the following concept requirements:
+-
+[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
+  The iterator that can be moved can be moved in both directions (i.e.
+  incremented and decremented).
+- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
+  It is possible to write to the pointed-to element (only if @a Base is
+  @ref iterator).
+
+@since version 1.0.0
+*/
+template<typename Base>
+class json_reverse_iterator : public std::reverse_iterator<Base>
+{
+  public:
+    using difference_type = std::ptrdiff_t;
+    /// shortcut to the reverse iterator adapter
+    using base_iterator = std::reverse_iterator<Base>;
+    /// the reference type for the pointed-to element
+    using reference = typename Base::reference;
+
+    /// create reverse iterator from iterator
+    explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
+        : base_iterator(it) {}
+
+    /// create reverse iterator from base class
+    explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
+
+    /// post-increment (it++)
+    json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type)
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
+    }
+
+    /// pre-increment (++it)
+    json_reverse_iterator& operator++()
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator++());
+    }
+
+    /// post-decrement (it--)
+    json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type)
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
+    }
+
+    /// pre-decrement (--it)
+    json_reverse_iterator& operator--()
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator--());
+    }
+
+    /// add to iterator
+    json_reverse_iterator& operator+=(difference_type i)
+    {
+        return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
+    }
+
+    /// add to iterator
+    json_reverse_iterator operator+(difference_type i) const
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
+    }
+
+    /// subtract from iterator
+    json_reverse_iterator operator-(difference_type i) const
+    {
+        return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
+    }
+
+    /// return difference
+    difference_type operator-(const json_reverse_iterator& other) const
+    {
+        return base_iterator(*this) - base_iterator(other);
+    }
+
+    /// access to successor
+    reference operator[](difference_type n) const
+    {
+        return *(this->operator+(n));
+    }
+
+    /// return the key of an object iterator
+    auto key() const -> decltype(std::declval<Base>().key())
+    {
+        auto it = --this->base();
+        return it.key();
+    }
+
+    /// return the value of an iterator
+    reference value() const
+    {
+        auto it = --this->base();
+        return it.operator * ();
+    }
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/iterators/primitive_iterator.hpp>
+
+// #include <nlohmann/detail/json_pointer.hpp>
+
+
+#include <algorithm> // all_of
+#include <cctype> // isdigit
+#include <limits> // max
+#include <numeric> // accumulate
+#include <string> // string
+#include <utility> // move
+#include <vector> // vector
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/string_escape.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+
+/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
+/// @sa https://json.nlohmann.me/api/json_pointer/
+template<typename BasicJsonType>
+class json_pointer
+{
+    // allow basic_json to access private members
+    NLOHMANN_BASIC_JSON_TPL_DECLARATION
+    friend class basic_json;
+
+  public:
+    /// @brief create JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/
+    explicit json_pointer(const std::string& s = "")
+        : reference_tokens(split(s))
+    {}
+
+    /// @brief return a string representation of the JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/to_string/
+    std::string to_string() const
+    {
+        return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
+                               std::string{},
+                               [](const std::string & a, const std::string & b)
+        {
+            return a + "/" + detail::escape(b);
+        });
+    }
+
+    /// @brief return a string representation of the JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/
+    operator std::string() const
+    {
+        return to_string();
+    }
+
+    /// @brief append another JSON pointer at the end of this JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+    json_pointer& operator/=(const json_pointer& ptr)
+    {
+        reference_tokens.insert(reference_tokens.end(),
+                                ptr.reference_tokens.begin(),
+                                ptr.reference_tokens.end());
+        return *this;
+    }
+
+    /// @brief append an unescaped reference token at the end of this JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+    json_pointer& operator/=(std::string token)
+    {
+        push_back(std::move(token));
+        return *this;
+    }
+
+    /// @brief append an array index at the end of this JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
+    json_pointer& operator/=(std::size_t array_idx)
+    {
+        return *this /= std::to_string(array_idx);
+    }
+
+    /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+    friend json_pointer operator/(const json_pointer& lhs,
+                                  const json_pointer& rhs)
+    {
+        return json_pointer(lhs) /= rhs;
+    }
+
+    /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+    friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param)
+    {
+        return json_pointer(lhs) /= std::move(token);
+    }
+
+    /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
+    friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx)
+    {
+        return json_pointer(lhs) /= array_idx;
+    }
+
+    /// @brief returns the parent of this JSON pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/
+    json_pointer parent_pointer() const
+    {
+        if (empty())
+        {
+            return *this;
+        }
+
+        json_pointer res = *this;
+        res.pop_back();
+        return res;
+    }
+
+    /// @brief remove last reference token
+    /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/
+    void pop_back()
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
+        }
+
+        reference_tokens.pop_back();
+    }
+
+    /// @brief return last reference token
+    /// @sa https://json.nlohmann.me/api/json_pointer/back/
+    const std::string& back() const
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
+        }
+
+        return reference_tokens.back();
+    }
+
+    /// @brief append an unescaped token at the end of the reference pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
+    void push_back(const std::string& token)
+    {
+        reference_tokens.push_back(token);
+    }
+
+    /// @brief append an unescaped token at the end of the reference pointer
+    /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
+    void push_back(std::string&& token)
+    {
+        reference_tokens.push_back(std::move(token));
+    }
+
+    /// @brief return whether pointer points to the root document
+    /// @sa https://json.nlohmann.me/api/json_pointer/empty/
+    bool empty() const noexcept
+    {
+        return reference_tokens.empty();
+    }
+
+  private:
+    /*!
+    @param[in] s  reference token to be converted into an array index
+
+    @return integer representation of @a s
+
+    @throw parse_error.106  if an array index begins with '0'
+    @throw parse_error.109  if an array index begins not with a digit
+    @throw out_of_range.404 if string @a s could not be converted to an integer
+    @throw out_of_range.410 if an array index exceeds size_type
+    */
+    static typename BasicJsonType::size_type array_index(const std::string& s)
+    {
+        using size_type = typename BasicJsonType::size_type;
+
+        // error condition (cf. RFC 6901, Sect. 4)
+        if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
+        {
+            JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
+        }
+
+        // error condition (cf. RFC 6901, Sect. 4)
+        if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
+        {
+            JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
+        }
+
+        std::size_t processed_chars = 0;
+        unsigned long long res = 0;  // NOLINT(runtime/int)
+        JSON_TRY
+        {
+            res = std::stoull(s, &processed_chars);
+        }
+        JSON_CATCH(std::out_of_range&)
+        {
+            JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
+        }
+
+        // check if the string was completely read
+        if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
+        {
+            JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
+        }
+
+        // only triggered on special platforms (like 32bit), see also
+        // https://github.com/nlohmann/json/pull/2203
+        if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)()))  // NOLINT(runtime/int)
+        {
+            JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
+        }
+
+        return static_cast<size_type>(res);
+    }
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    json_pointer top() const
+    {
+        if (JSON_HEDLEY_UNLIKELY(empty()))
+        {
+            JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
+        }
+
+        json_pointer result = *this;
+        result.reference_tokens = {reference_tokens[0]};
+        return result;
+    }
+
+  private:
+    /*!
+    @brief create and return a reference to the pointed to value
+
+    @complexity Linear in the number of reference tokens.
+
+    @throw parse_error.109 if array index is not a number
+    @throw type_error.313 if value cannot be unflattened
+    */
+    BasicJsonType& get_and_create(BasicJsonType& j) const
+    {
+        auto* result = &j;
+
+        // in case no reference tokens exist, return a reference to the JSON value
+        // j which will be overwritten by a primitive value
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (result->type())
+            {
+                case detail::value_t::null:
+                {
+                    if (reference_token == "0")
+                    {
+                        // start a new array if reference token is 0
+                        result = &result->operator[](0);
+                    }
+                    else
+                    {
+                        // start a new object otherwise
+                        result = &result->operator[](reference_token);
+                    }
+                    break;
+                }
+
+                case detail::value_t::object:
+                {
+                    // create an entry in the object
+                    result = &result->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    // create an entry in the array
+                    result = &result->operator[](array_index(reference_token));
+                    break;
+                }
+
+                /*
+                The following code is only reached if there exists a reference
+                token _and_ the current value is primitive. In this case, we have
+                an error situation, because primitive values may only occur as
+                single value; that is, with an empty list of reference tokens.
+                */
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                    JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
+            }
+        }
+
+        return *result;
+    }
+
+    /*!
+    @brief return a reference to the pointed to value
+
+    @note This version does not throw if a value is not present, but tries to
+          create nested values instead. For instance, calling this function
+          with pointer `"/this/that"` on a null value is equivalent to calling
+          `operator[]("this").operator[]("that")` on that value, effectively
+          changing the null value to an object.
+
+    @param[in] ptr  a JSON value
+
+    @return reference to the JSON value pointed to by the JSON pointer
+
+    @complexity Linear in the length of the JSON pointer.
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    BasicJsonType& get_unchecked(BasicJsonType* ptr) const
+    {
+        for (const auto& reference_token : reference_tokens)
+        {
+            // convert null values to arrays or objects before continuing
+            if (ptr->is_null())
+            {
+                // check if reference token is a number
+                const bool nums =
+                    std::all_of(reference_token.begin(), reference_token.end(),
+                                [](const unsigned char x)
+                {
+                    return std::isdigit(x);
+                });
+
+                // change value to array for numbers or "-" or to object otherwise
+                *ptr = (nums || reference_token == "-")
+                       ? detail::value_t::array
+                       : detail::value_t::object;
+            }
+
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // use unchecked object access
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (reference_token == "-")
+                    {
+                        // explicitly treat "-" as index beyond the end
+                        ptr = &ptr->operator[](ptr->m_value.array->size());
+                    }
+                    else
+                    {
+                        // convert array index to number; unchecked access
+                        ptr = &ptr->operator[](array_index(reference_token));
+                    }
+                    break;
+                }
+
+                case detail::value_t::null:
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    BasicJsonType& get_checked(BasicJsonType* ptr) const
+    {
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // note: at performs range check
+                    ptr = &ptr->at(reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        JSON_THROW(detail::out_of_range::create(402,
+                                                                "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
+                                                                ") is out of range", *ptr));
+                    }
+
+                    // note: at performs range check
+                    ptr = &ptr->at(array_index(reference_token));
+                    break;
+                }
+
+                case detail::value_t::null:
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @brief return a const reference to the pointed to value
+
+    @param[in] ptr  a JSON value
+
+    @return const reference to the JSON value pointed to by the JSON
+    pointer
+
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
+    {
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // use unchecked object access
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" cannot be used for const access
+                        JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
+                    }
+
+                    // use unchecked array access
+                    ptr = &ptr->operator[](array_index(reference_token));
+                    break;
+                }
+
+                case detail::value_t::null:
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    @throw out_of_range.402  if the array index '-' is used
+    @throw out_of_range.404  if the JSON pointer can not be resolved
+    */
+    const BasicJsonType& get_checked(const BasicJsonType* ptr) const
+    {
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    // note: at performs range check
+                    ptr = &ptr->at(reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        JSON_THROW(detail::out_of_range::create(402,
+                                                                "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
+                                                                ") is out of range", *ptr));
+                    }
+
+                    // note: at performs range check
+                    ptr = &ptr->at(array_index(reference_token));
+                    break;
+                }
+
+                case detail::value_t::null:
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                    JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
+            }
+        }
+
+        return *ptr;
+    }
+
+    /*!
+    @throw parse_error.106   if an array index begins with '0'
+    @throw parse_error.109   if an array index was not a number
+    */
+    bool contains(const BasicJsonType* ptr) const
+    {
+        for (const auto& reference_token : reference_tokens)
+        {
+            switch (ptr->type())
+            {
+                case detail::value_t::object:
+                {
+                    if (!ptr->contains(reference_token))
+                    {
+                        // we did not find the key in the object
+                        return false;
+                    }
+
+                    ptr = &ptr->operator[](reference_token);
+                    break;
+                }
+
+                case detail::value_t::array:
+                {
+                    if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
+                    {
+                        // "-" always fails the range check
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
+                    {
+                        // invalid char
+                        return false;
+                    }
+                    if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
+                    {
+                        if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
+                        {
+                            // first char should be between '1' and '9'
+                            return false;
+                        }
+                        for (std::size_t i = 1; i < reference_token.size(); i++)
+                        {
+                            if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
+                            {
+                                // other char should be between '0' and '9'
+                                return false;
+                            }
+                        }
+                    }
+
+                    const auto idx = array_index(reference_token);
+                    if (idx >= ptr->size())
+                    {
+                        // index out of range
+                        return false;
+                    }
+
+                    ptr = &ptr->operator[](idx);
+                    break;
+                }
+
+                case detail::value_t::null:
+                case detail::value_t::string:
+                case detail::value_t::boolean:
+                case detail::value_t::number_integer:
+                case detail::value_t::number_unsigned:
+                case detail::value_t::number_float:
+                case detail::value_t::binary:
+                case detail::value_t::discarded:
+                default:
+                {
+                    // we do not expect primitive values if there is still a
+                    // reference token to process
+                    return false;
+                }
+            }
+        }
+
+        // no reference token left means we found a primitive value
+        return true;
+    }
+
+    /*!
+    @brief split the string input to reference tokens
+
+    @note This function is only called by the json_pointer constructor.
+          All exceptions below are documented there.
+
+    @throw parse_error.107  if the pointer is not empty or begins with '/'
+    @throw parse_error.108  if character '~' is not followed by '0' or '1'
+    */
+    static std::vector<std::string> split(const std::string& reference_string)
+    {
+        std::vector<std::string> result;
+
+        // special case: empty reference string -> no reference tokens
+        if (reference_string.empty())
+        {
+            return result;
+        }
+
+        // check if nonempty reference string begins with slash
+        if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
+        {
+            JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
+        }
+
+        // extract the reference tokens:
+        // - slash: position of the last read slash (or end of string)
+        // - start: position after the previous slash
+        for (
+            // search for the first slash after the first character
+            std::size_t slash = reference_string.find_first_of('/', 1),
+            // set the beginning of the first reference token
+            start = 1;
+            // we can stop if start == 0 (if slash == std::string::npos)
+            start != 0;
+            // set the beginning of the next reference token
+            // (will eventually be 0 if slash == std::string::npos)
+            start = (slash == std::string::npos) ? 0 : slash + 1,
+            // find next slash
+            slash = reference_string.find_first_of('/', start))
+        {
+            // use the text between the beginning of the reference token
+            // (start) and the last slash (slash).
+            auto reference_token = reference_string.substr(start, slash - start);
+
+            // check reference tokens are properly escaped
+            for (std::size_t pos = reference_token.find_first_of('~');
+                    pos != std::string::npos;
+                    pos = reference_token.find_first_of('~', pos + 1))
+            {
+                JSON_ASSERT(reference_token[pos] == '~');
+
+                // ~ must be followed by 0 or 1
+                if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
+                                         (reference_token[pos + 1] != '0' &&
+                                          reference_token[pos + 1] != '1')))
+                {
+                    JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
+                }
+            }
+
+            // finally, store the reference token
+            detail::unescape(reference_token);
+            result.push_back(reference_token);
+        }
+
+        return result;
+    }
+
+  private:
+    /*!
+    @param[in] reference_string  the reference string to the current value
+    @param[in] value             the value to consider
+    @param[in,out] result        the result object to insert values to
+
+    @note Empty objects or arrays are flattened to `null`.
+    */
+    static void flatten(const std::string& reference_string,
+                        const BasicJsonType& value,
+                        BasicJsonType& result)
+    {
+        switch (value.type())
+        {
+            case detail::value_t::array:
+            {
+                if (value.m_value.array->empty())
+                {
+                    // flatten empty array as null
+                    result[reference_string] = nullptr;
+                }
+                else
+                {
+                    // iterate array and use index as reference string
+                    for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
+                    {
+                        flatten(reference_string + "/" + std::to_string(i),
+                                value.m_value.array->operator[](i), result);
+                    }
+                }
+                break;
+            }
+
+            case detail::value_t::object:
+            {
+                if (value.m_value.object->empty())
+                {
+                    // flatten empty object as null
+                    result[reference_string] = nullptr;
+                }
+                else
+                {
+                    // iterate object and use keys as reference string
+                    for (const auto& element : *value.m_value.object)
+                    {
+                        flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
+                    }
+                }
+                break;
+            }
+
+            case detail::value_t::null:
+            case detail::value_t::string:
+            case detail::value_t::boolean:
+            case detail::value_t::number_integer:
+            case detail::value_t::number_unsigned:
+            case detail::value_t::number_float:
+            case detail::value_t::binary:
+            case detail::value_t::discarded:
+            default:
+            {
+                // add primitive value with its reference string
+                result[reference_string] = value;
+                break;
+            }
+        }
+    }
+
+    /*!
+    @param[in] value  flattened JSON
+
+    @return unflattened JSON
+
+    @throw parse_error.109 if array index is not a number
+    @throw type_error.314  if value is not an object
+    @throw type_error.315  if object values are not primitive
+    @throw type_error.313  if value cannot be unflattened
+    */
+    static BasicJsonType
+    unflatten(const BasicJsonType& value)
+    {
+        if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
+        {
+            JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
+        }
+
+        BasicJsonType result;
+
+        // iterate the JSON object values
+        for (const auto& element : *value.m_value.object)
+        {
+            if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
+            {
+                JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
+            }
+
+            // assign value to reference pointed to by JSON pointer; Note that if
+            // the JSON pointer is "" (i.e., points to the whole value), function
+            // get_and_create returns a reference to result itself. An assignment
+            // will then create a primitive value.
+            json_pointer(element.first).get_and_create(result) = element.second;
+        }
+
+        return result;
+    }
+
+    /*!
+    @brief compares two JSON pointers for equality
+
+    @param[in] lhs  JSON pointer to compare
+    @param[in] rhs  JSON pointer to compare
+    @return whether @a lhs is equal to @a rhs
+
+    @complexity Linear in the length of the JSON pointer
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+    */
+    friend bool operator==(json_pointer const& lhs,
+                           json_pointer const& rhs) noexcept
+    {
+        return lhs.reference_tokens == rhs.reference_tokens;
+    }
+
+    /*!
+    @brief compares two JSON pointers for inequality
+
+    @param[in] lhs  JSON pointer to compare
+    @param[in] rhs  JSON pointer to compare
+    @return whether @a lhs is not equal @a rhs
+
+    @complexity Linear in the length of the JSON pointer
+
+    @exceptionsafety No-throw guarantee: this function never throws exceptions.
+    */
+    friend bool operator!=(json_pointer const& lhs,
+                           json_pointer const& rhs) noexcept
+    {
+        return !(lhs == rhs);
+    }
+
+    /// the reference tokens
+    std::vector<std::string> reference_tokens;
+};
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/json_ref.hpp>
+
+
+#include <initializer_list>
+#include <utility>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+template<typename BasicJsonType>
+class json_ref
+{
+  public:
+    using value_type = BasicJsonType;
+
+    json_ref(value_type&& value)
+        : owned_value(std::move(value))
+    {}
+
+    json_ref(const value_type& value)
+        : value_ref(&value)
+    {}
+
+    json_ref(std::initializer_list<json_ref> init)
+        : owned_value(init)
+    {}
+
+    template <
+        class... Args,
+        enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
+    json_ref(Args && ... args)
+        : owned_value(std::forward<Args>(args)...)
+    {}
+
+    // class should be movable only
+    json_ref(json_ref&&) noexcept = default;
+    json_ref(const json_ref&) = delete;
+    json_ref& operator=(const json_ref&) = delete;
+    json_ref& operator=(json_ref&&) = delete;
+    ~json_ref() = default;
+
+    value_type moved_or_copied() const
+    {
+        if (value_ref == nullptr)
+        {
+            return std::move(owned_value);
+        }
+        return *value_ref;
+    }
+
+    value_type const& operator*() const
+    {
+        return value_ref ? *value_ref : owned_value;
+    }
+
+    value_type const* operator->() const
+    {
+        return &** this;
+    }
+
+  private:
+    mutable value_type owned_value = nullptr;
+    value_type const* value_ref = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/string_escape.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/meta/type_traits.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+
+
+#include <algorithm> // reverse
+#include <array> // array
+#include <cmath> // isnan, isinf
+#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
+#include <cstring> // memcpy
+#include <limits> // numeric_limits
+#include <string> // string
+#include <utility> // move
+
+// #include <nlohmann/detail/input/binary_reader.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+
+#include <algorithm> // copy
+#include <cstddef> // size_t
+#include <iterator> // back_inserter
+#include <memory> // shared_ptr, make_shared
+#include <string> // basic_string
+#include <vector> // vector
+
+#ifndef JSON_NO_IO
+    #include <ios>      // streamsize
+    #include <ostream>  // basic_ostream
+#endif  // JSON_NO_IO
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+/// abstract output adapter interface
+template<typename CharType> struct output_adapter_protocol
+{
+    virtual void write_character(CharType c) = 0;
+    virtual void write_characters(const CharType* s, std::size_t length) = 0;
+    virtual ~output_adapter_protocol() = default;
+
+    output_adapter_protocol() = default;
+    output_adapter_protocol(const output_adapter_protocol&) = default;
+    output_adapter_protocol(output_adapter_protocol&&) noexcept = default;
+    output_adapter_protocol& operator=(const output_adapter_protocol&) = default;
+    output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default;
+};
+
+/// a type to simplify interfaces
+template<typename CharType>
+using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
+
+/// output adapter for byte vectors
+template<typename CharType, typename AllocatorType = std::allocator<CharType>>
+class output_vector_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_vector_adapter(std::vector<CharType, AllocatorType>& vec) noexcept
+        : v(vec)
+    {}
+
+    void write_character(CharType c) override
+    {
+        v.push_back(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        std::copy(s, s + length, std::back_inserter(v));
+    }
+
+  private:
+    std::vector<CharType, AllocatorType>& v;
+};
+
+#ifndef JSON_NO_IO
+/// output adapter for output streams
+template<typename CharType>
+class output_stream_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
+        : stream(s)
+    {}
+
+    void write_character(CharType c) override
+    {
+        stream.put(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        stream.write(s, static_cast<std::streamsize>(length));
+    }
+
+  private:
+    std::basic_ostream<CharType>& stream;
+};
+#endif  // JSON_NO_IO
+
+/// output adapter for basic_string
+template<typename CharType, typename StringType = std::basic_string<CharType>>
+class output_string_adapter : public output_adapter_protocol<CharType>
+{
+  public:
+    explicit output_string_adapter(StringType& s) noexcept
+        : str(s)
+    {}
+
+    void write_character(CharType c) override
+    {
+        str.push_back(c);
+    }
+
+    JSON_HEDLEY_NON_NULL(2)
+    void write_characters(const CharType* s, std::size_t length) override
+    {
+        str.append(s, length);
+    }
+
+  private:
+    StringType& str;
+};
+
+template<typename CharType, typename StringType = std::basic_string<CharType>>
+class output_adapter
+{
+  public:
+    template<typename AllocatorType = std::allocator<CharType>>
+    output_adapter(std::vector<CharType, AllocatorType>& vec)
+        : oa(std::make_shared<output_vector_adapter<CharType, AllocatorType>>(vec)) {}
+
+#ifndef JSON_NO_IO
+    output_adapter(std::basic_ostream<CharType>& s)
+        : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
+#endif  // JSON_NO_IO
+
+    output_adapter(StringType& s)
+        : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
+
+    operator output_adapter_t<CharType>()
+    {
+        return oa;
+    }
+
+  private:
+    output_adapter_t<CharType> oa = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////
+// binary writer //
+///////////////////
+
+/*!
+@brief serialization to CBOR and MessagePack values
+*/
+template<typename BasicJsonType, typename CharType>
+class binary_writer
+{
+    using string_t = typename BasicJsonType::string_t;
+    using binary_t = typename BasicJsonType::binary_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+
+  public:
+    /*!
+    @brief create a binary writer
+
+    @param[in] adapter  output adapter to write to
+    */
+    explicit binary_writer(output_adapter_t<CharType> adapter) : oa(std::move(adapter))
+    {
+        JSON_ASSERT(oa);
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    @pre       j.type() == value_t::object
+    */
+    void write_bson(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::object:
+            {
+                write_bson_object(*j.m_value.object);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::array:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));
+            }
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    */
+    void write_cbor(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+            {
+                oa->write_character(to_char_type(0xF6));
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                oa->write_character(j.m_value.boolean
+                                    ? to_char_type(0xF5)
+                                    : to_char_type(0xF4));
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                if (j.m_value.number_integer >= 0)
+                {
+                    // CBOR does not differentiate between positive signed
+                    // integers and unsigned integers. Therefore, we used the
+                    // code from the value_t::number_unsigned case here.
+                    if (j.m_value.number_integer <= 0x17)
+                    {
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x18));
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x19));
+                        write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x1A));
+                        write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                    }
+                    else
+                    {
+                        oa->write_character(to_char_type(0x1B));
+                        write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                    }
+                }
+                else
+                {
+                    // The conversions below encode the sign in the first
+                    // byte, and the value is converted to a positive number.
+                    const auto positive_number = -1 - j.m_value.number_integer;
+                    if (j.m_value.number_integer >= -24)
+                    {
+                        write_number(static_cast<std::uint8_t>(0x20 + positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x38));
+                        write_number(static_cast<std::uint8_t>(positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x39));
+                        write_number(static_cast<std::uint16_t>(positive_number));
+                    }
+                    else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        oa->write_character(to_char_type(0x3A));
+                        write_number(static_cast<std::uint32_t>(positive_number));
+                    }
+                    else
+                    {
+                        oa->write_character(to_char_type(0x3B));
+                        write_number(static_cast<std::uint64_t>(positive_number));
+                    }
+                }
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x18));
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x19));
+                    write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x1A));
+                    write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
+                }
+                else
+                {
+                    oa->write_character(to_char_type(0x1B));
+                    write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
+                }
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                if (std::isnan(j.m_value.number_float))
+                {
+                    // NaN is 0xf97e00 in CBOR
+                    oa->write_character(to_char_type(0xF9));
+                    oa->write_character(to_char_type(0x7E));
+                    oa->write_character(to_char_type(0x00));
+                }
+                else if (std::isinf(j.m_value.number_float))
+                {
+                    // Infinity is 0xf97c00, -Infinity is 0xf9fc00
+                    oa->write_character(to_char_type(0xf9));
+                    oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
+                    oa->write_character(to_char_type(0x00));
+                }
+                else
+                {
+                    write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
+                }
+                break;
+            }
+
+            case value_t::string:
+            {
+                // step 1: write control byte and the string length
+                const auto N = j.m_value.string->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0x60 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x78));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x79));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x7A));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x7B));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write the string
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                // step 1: write control byte and the array size
+                const auto N = j.m_value.array->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0x80 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x98));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x99));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x9A));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x9B));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_cbor(el);
+                }
+                break;
+            }
+
+            case value_t::binary:
+            {
+                if (j.m_value.binary->has_subtype())
+                {
+                    if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        write_number(static_cast<std::uint8_t>(0xd8));
+                        write_number(static_cast<std::uint8_t>(j.m_value.binary->subtype()));
+                    }
+                    else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        write_number(static_cast<std::uint8_t>(0xd9));
+                        write_number(static_cast<std::uint16_t>(j.m_value.binary->subtype()));
+                    }
+                    else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        write_number(static_cast<std::uint8_t>(0xda));
+                        write_number(static_cast<std::uint32_t>(j.m_value.binary->subtype()));
+                    }
+                    else if (j.m_value.binary->subtype() <= (std::numeric_limits<std::uint64_t>::max)())
+                    {
+                        write_number(static_cast<std::uint8_t>(0xdb));
+                        write_number(static_cast<std::uint64_t>(j.m_value.binary->subtype()));
+                    }
+                }
+
+                // step 1: write control byte and the binary array size
+                const auto N = j.m_value.binary->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0x40 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x58));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x59));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x5A));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0x5B));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write each element
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.binary->data()),
+                    N);
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                // step 1: write control byte and the object size
+                const auto N = j.m_value.object->size();
+                if (N <= 0x17)
+                {
+                    write_number(static_cast<std::uint8_t>(0xA0 + N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xB8));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xB9));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xBA));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+                // LCOV_EXCL_START
+                else if (N <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    oa->write_character(to_char_type(0xBB));
+                    write_number(static_cast<std::uint64_t>(N));
+                }
+                // LCOV_EXCL_STOP
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_cbor(el.first);
+                    write_cbor(el.second);
+                }
+                break;
+            }
+
+            case value_t::discarded:
+            default:
+                break;
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    */
+    void write_msgpack(const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::null: // nil
+            {
+                oa->write_character(to_char_type(0xC0));
+                break;
+            }
+
+            case value_t::boolean: // true and false
+            {
+                oa->write_character(j.m_value.boolean
+                                    ? to_char_type(0xC3)
+                                    : to_char_type(0xC2));
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                if (j.m_value.number_integer >= 0)
+                {
+                    // MessagePack does not differentiate between positive
+                    // signed integers and unsigned integers. Therefore, we used
+                    // the code from the value_t::number_unsigned case here.
+                    if (j.m_value.number_unsigned < 128)
+                    {
+                        // positive fixnum
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                    {
+                        // uint 8
+                        oa->write_character(to_char_type(0xCC));
+                        write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                    {
+                        // uint 16
+                        oa->write_character(to_char_type(0xCD));
+                        write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                    {
+                        // uint 32
+                        oa->write_character(to_char_type(0xCE));
+                        write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
+                    {
+                        // uint 64
+                        oa->write_character(to_char_type(0xCF));
+                        write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                    }
+                }
+                else
+                {
+                    if (j.m_value.number_integer >= -32)
+                    {
+                        // negative fixnum
+                        write_number(static_cast<std::int8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
+                             j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
+                    {
+                        // int 8
+                        oa->write_character(to_char_type(0xD0));
+                        write_number(static_cast<std::int8_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
+                             j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
+                    {
+                        // int 16
+                        oa->write_character(to_char_type(0xD1));
+                        write_number(static_cast<std::int16_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
+                             j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
+                    {
+                        // int 32
+                        oa->write_character(to_char_type(0xD2));
+                        write_number(static_cast<std::int32_t>(j.m_value.number_integer));
+                    }
+                    else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
+                             j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
+                    {
+                        // int 64
+                        oa->write_character(to_char_type(0xD3));
+                        write_number(static_cast<std::int64_t>(j.m_value.number_integer));
+                    }
+                }
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned < 128)
+                {
+                    // positive fixnum
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    // uint 8
+                    oa->write_character(to_char_type(0xCC));
+                    write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // uint 16
+                    oa->write_character(to_char_type(0xCD));
+                    write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // uint 32
+                    oa->write_character(to_char_type(0xCE));
+                    write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
+                }
+                else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
+                {
+                    // uint 64
+                    oa->write_character(to_char_type(0xCF));
+                    write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
+                }
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
+                break;
+            }
+
+            case value_t::string:
+            {
+                // step 1: write control byte and the string length
+                const auto N = j.m_value.string->size();
+                if (N <= 31)
+                {
+                    // fixstr
+                    write_number(static_cast<std::uint8_t>(0xA0 | N));
+                }
+                else if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    // str 8
+                    oa->write_character(to_char_type(0xD9));
+                    write_number(static_cast<std::uint8_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // str 16
+                    oa->write_character(to_char_type(0xDA));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // str 32
+                    oa->write_character(to_char_type(0xDB));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write the string
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                // step 1: write control byte and the array size
+                const auto N = j.m_value.array->size();
+                if (N <= 15)
+                {
+                    // fixarray
+                    write_number(static_cast<std::uint8_t>(0x90 | N));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // array 16
+                    oa->write_character(to_char_type(0xDC));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // array 32
+                    oa->write_character(to_char_type(0xDD));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_msgpack(el);
+                }
+                break;
+            }
+
+            case value_t::binary:
+            {
+                // step 0: determine if the binary type has a set subtype to
+                // determine whether or not to use the ext or fixext types
+                const bool use_ext = j.m_value.binary->has_subtype();
+
+                // step 1: write control byte and the byte string length
+                const auto N = j.m_value.binary->size();
+                if (N <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    std::uint8_t output_type{};
+                    bool fixed = true;
+                    if (use_ext)
+                    {
+                        switch (N)
+                        {
+                            case 1:
+                                output_type = 0xD4; // fixext 1
+                                break;
+                            case 2:
+                                output_type = 0xD5; // fixext 2
+                                break;
+                            case 4:
+                                output_type = 0xD6; // fixext 4
+                                break;
+                            case 8:
+                                output_type = 0xD7; // fixext 8
+                                break;
+                            case 16:
+                                output_type = 0xD8; // fixext 16
+                                break;
+                            default:
+                                output_type = 0xC7; // ext 8
+                                fixed = false;
+                                break;
+                        }
+
+                    }
+                    else
+                    {
+                        output_type = 0xC4; // bin 8
+                        fixed = false;
+                    }
+
+                    oa->write_character(to_char_type(output_type));
+                    if (!fixed)
+                    {
+                        write_number(static_cast<std::uint8_t>(N));
+                    }
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    std::uint8_t output_type = use_ext
+                                               ? 0xC8 // ext 16
+                                               : 0xC5; // bin 16
+
+                    oa->write_character(to_char_type(output_type));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    std::uint8_t output_type = use_ext
+                                               ? 0xC9 // ext 32
+                                               : 0xC6; // bin 32
+
+                    oa->write_character(to_char_type(output_type));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 1.5: if this is an ext type, write the subtype
+                if (use_ext)
+                {
+                    write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
+                }
+
+                // step 2: write the byte string
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.binary->data()),
+                    N);
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                // step 1: write control byte and the object size
+                const auto N = j.m_value.object->size();
+                if (N <= 15)
+                {
+                    // fixmap
+                    write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
+                }
+                else if (N <= (std::numeric_limits<std::uint16_t>::max)())
+                {
+                    // map 16
+                    oa->write_character(to_char_type(0xDE));
+                    write_number(static_cast<std::uint16_t>(N));
+                }
+                else if (N <= (std::numeric_limits<std::uint32_t>::max)())
+                {
+                    // map 32
+                    oa->write_character(to_char_type(0xDF));
+                    write_number(static_cast<std::uint32_t>(N));
+                }
+
+                // step 2: write each element
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_msgpack(el.first);
+                    write_msgpack(el.second);
+                }
+                break;
+            }
+
+            case value_t::discarded:
+            default:
+                break;
+        }
+    }
+
+    /*!
+    @param[in] j  JSON value to serialize
+    @param[in] use_count   whether to use '#' prefixes (optimized format)
+    @param[in] use_type    whether to use '$' prefixes (optimized format)
+    @param[in] add_prefix  whether prefixes need to be used for this value
+    */
+    void write_ubjson(const BasicJsonType& j, const bool use_count,
+                      const bool use_type, const bool add_prefix = true)
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('Z'));
+                }
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(j.m_value.boolean
+                                        ? to_char_type('T')
+                                        : to_char_type('F'));
+                }
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
+                break;
+            }
+
+            case value_t::string:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('S'));
+                }
+                write_number_with_ubjson_prefix(j.m_value.string->size(), true);
+                oa->write_characters(
+                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
+                    j.m_value.string->size());
+                break;
+            }
+
+            case value_t::array:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('['));
+                }
+
+                bool prefix_required = true;
+                if (use_type && !j.m_value.array->empty())
+                {
+                    JSON_ASSERT(use_count);
+                    const CharType first_prefix = ubjson_prefix(j.front());
+                    const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
+                                                         [this, first_prefix](const BasicJsonType & v)
+                    {
+                        return ubjson_prefix(v) == first_prefix;
+                    });
+
+                    if (same_prefix)
+                    {
+                        prefix_required = false;
+                        oa->write_character(to_char_type('$'));
+                        oa->write_character(first_prefix);
+                    }
+                }
+
+                if (use_count)
+                {
+                    oa->write_character(to_char_type('#'));
+                    write_number_with_ubjson_prefix(j.m_value.array->size(), true);
+                }
+
+                for (const auto& el : *j.m_value.array)
+                {
+                    write_ubjson(el, use_count, use_type, prefix_required);
+                }
+
+                if (!use_count)
+                {
+                    oa->write_character(to_char_type(']'));
+                }
+
+                break;
+            }
+
+            case value_t::binary:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('['));
+                }
+
+                if (use_type && !j.m_value.binary->empty())
+                {
+                    JSON_ASSERT(use_count);
+                    oa->write_character(to_char_type('$'));
+                    oa->write_character('U');
+                }
+
+                if (use_count)
+                {
+                    oa->write_character(to_char_type('#'));
+                    write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
+                }
+
+                if (use_type)
+                {
+                    oa->write_characters(
+                        reinterpret_cast<const CharType*>(j.m_value.binary->data()),
+                        j.m_value.binary->size());
+                }
+                else
+                {
+                    for (size_t i = 0; i < j.m_value.binary->size(); ++i)
+                    {
+                        oa->write_character(to_char_type('U'));
+                        oa->write_character(j.m_value.binary->data()[i]);
+                    }
+                }
+
+                if (!use_count)
+                {
+                    oa->write_character(to_char_type(']'));
+                }
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                if (add_prefix)
+                {
+                    oa->write_character(to_char_type('{'));
+                }
+
+                bool prefix_required = true;
+                if (use_type && !j.m_value.object->empty())
+                {
+                    JSON_ASSERT(use_count);
+                    const CharType first_prefix = ubjson_prefix(j.front());
+                    const bool same_prefix = std::all_of(j.begin(), j.end(),
+                                                         [this, first_prefix](const BasicJsonType & v)
+                    {
+                        return ubjson_prefix(v) == first_prefix;
+                    });
+
+                    if (same_prefix)
+                    {
+                        prefix_required = false;
+                        oa->write_character(to_char_type('$'));
+                        oa->write_character(first_prefix);
+                    }
+                }
+
+                if (use_count)
+                {
+                    oa->write_character(to_char_type('#'));
+                    write_number_with_ubjson_prefix(j.m_value.object->size(), true);
+                }
+
+                for (const auto& el : *j.m_value.object)
+                {
+                    write_number_with_ubjson_prefix(el.first.size(), true);
+                    oa->write_characters(
+                        reinterpret_cast<const CharType*>(el.first.c_str()),
+                        el.first.size());
+                    write_ubjson(el.second, use_count, use_type, prefix_required);
+                }
+
+                if (!use_count)
+                {
+                    oa->write_character(to_char_type('}'));
+                }
+
+                break;
+            }
+
+            case value_t::discarded:
+            default:
+                break;
+        }
+    }
+
+  private:
+    //////////
+    // BSON //
+    //////////
+
+    /*!
+    @return The size of a BSON document entry header, including the id marker
+            and the entry name size (and its null-terminator).
+    */
+    static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j)
+    {
+        const auto it = name.find(static_cast<typename string_t::value_type>(0));
+        if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
+        {
+            JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j));
+            static_cast<void>(j);
+        }
+
+        return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
+    }
+
+    /*!
+    @brief Writes the given @a element_type and @a name to the output adapter
+    */
+    void write_bson_entry_header(const string_t& name,
+                                 const std::uint8_t element_type)
+    {
+        oa->write_character(to_char_type(element_type)); // boolean
+        oa->write_characters(
+            reinterpret_cast<const CharType*>(name.c_str()),
+            name.size() + 1u);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and boolean value @a value
+    */
+    void write_bson_boolean(const string_t& name,
+                            const bool value)
+    {
+        write_bson_entry_header(name, 0x08);
+        oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and double value @a value
+    */
+    void write_bson_double(const string_t& name,
+                           const double value)
+    {
+        write_bson_entry_header(name, 0x01);
+        write_number<double, true>(value);
+    }
+
+    /*!
+    @return The size of the BSON-encoded string in @a value
+    */
+    static std::size_t calc_bson_string_size(const string_t& value)
+    {
+        return sizeof(std::int32_t) + value.size() + 1ul;
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and string value @a value
+    */
+    void write_bson_string(const string_t& name,
+                           const string_t& value)
+    {
+        write_bson_entry_header(name, 0x02);
+
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
+        oa->write_characters(
+            reinterpret_cast<const CharType*>(value.c_str()),
+            value.size() + 1);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and null value
+    */
+    void write_bson_null(const string_t& name)
+    {
+        write_bson_entry_header(name, 0x0A);
+    }
+
+    /*!
+    @return The size of the BSON-encoded integer @a value
+    */
+    static std::size_t calc_bson_integer_size(const std::int64_t value)
+    {
+        return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
+               ? sizeof(std::int32_t)
+               : sizeof(std::int64_t);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and integer @a value
+    */
+    void write_bson_integer(const string_t& name,
+                            const std::int64_t value)
+    {
+        if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
+        {
+            write_bson_entry_header(name, 0x10); // int32
+            write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
+        }
+        else
+        {
+            write_bson_entry_header(name, 0x12); // int64
+            write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
+        }
+    }
+
+    /*!
+    @return The size of the BSON-encoded unsigned integer in @a j
+    */
+    static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
+    {
+        return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+               ? sizeof(std::int32_t)
+               : sizeof(std::int64_t);
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and unsigned @a value
+    */
+    void write_bson_unsigned(const string_t& name,
+                             const BasicJsonType& j)
+    {
+        if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+        {
+            write_bson_entry_header(name, 0x10 /* int32 */);
+            write_number<std::int32_t, true>(static_cast<std::int32_t>(j.m_value.number_unsigned));
+        }
+        else if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
+        {
+            write_bson_entry_header(name, 0x12 /* int64 */);
+            write_number<std::int64_t, true>(static_cast<std::int64_t>(j.m_value.number_unsigned));
+        }
+        else
+        {
+            JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j));
+        }
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and object @a value
+    */
+    void write_bson_object_entry(const string_t& name,
+                                 const typename BasicJsonType::object_t& value)
+    {
+        write_bson_entry_header(name, 0x03); // object
+        write_bson_object(value);
+    }
+
+    /*!
+    @return The size of the BSON-encoded array @a value
+    */
+    static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
+    {
+        std::size_t array_index = 0ul;
+
+        const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast<std::size_t>(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
+        {
+            return result + calc_bson_element_size(std::to_string(array_index++), el);
+        });
+
+        return sizeof(std::int32_t) + embedded_document_size + 1ul;
+    }
+
+    /*!
+    @return The size of the BSON-encoded binary array @a value
+    */
+    static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
+    {
+        return sizeof(std::int32_t) + value.size() + 1ul;
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and array @a value
+    */
+    void write_bson_array(const string_t& name,
+                          const typename BasicJsonType::array_t& value)
+    {
+        write_bson_entry_header(name, 0x04); // array
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
+
+        std::size_t array_index = 0ul;
+
+        for (const auto& el : value)
+        {
+            write_bson_element(std::to_string(array_index++), el);
+        }
+
+        oa->write_character(to_char_type(0x00));
+    }
+
+    /*!
+    @brief Writes a BSON element with key @a name and binary value @a value
+    */
+    void write_bson_binary(const string_t& name,
+                           const binary_t& value)
+    {
+        write_bson_entry_header(name, 0x05);
+
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
+        write_number(value.has_subtype() ? static_cast<std::uint8_t>(value.subtype()) : static_cast<std::uint8_t>(0x00));
+
+        oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
+    }
+
+    /*!
+    @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
+    @return The calculated size for the BSON document entry for @a j with the given @a name.
+    */
+    static std::size_t calc_bson_element_size(const string_t& name,
+            const BasicJsonType& j)
+    {
+        const auto header_size = calc_bson_entry_header_size(name, j);
+        switch (j.type())
+        {
+            case value_t::object:
+                return header_size + calc_bson_object_size(*j.m_value.object);
+
+            case value_t::array:
+                return header_size + calc_bson_array_size(*j.m_value.array);
+
+            case value_t::binary:
+                return header_size + calc_bson_binary_size(*j.m_value.binary);
+
+            case value_t::boolean:
+                return header_size + 1ul;
+
+            case value_t::number_float:
+                return header_size + 8ul;
+
+            case value_t::number_integer:
+                return header_size + calc_bson_integer_size(j.m_value.number_integer);
+
+            case value_t::number_unsigned:
+                return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
+
+            case value_t::string:
+                return header_size + calc_bson_string_size(*j.m_value.string);
+
+            case value_t::null:
+                return header_size + 0ul;
+
+            // LCOV_EXCL_START
+            case value_t::discarded:
+            default:
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
+                return 0ul;
+                // LCOV_EXCL_STOP
+        }
+    }
+
+    /*!
+    @brief Serializes the JSON value @a j to BSON and associates it with the
+           key @a name.
+    @param name The name to associate with the JSON entity @a j within the
+                current BSON document
+    */
+    void write_bson_element(const string_t& name,
+                            const BasicJsonType& j)
+    {
+        switch (j.type())
+        {
+            case value_t::object:
+                return write_bson_object_entry(name, *j.m_value.object);
+
+            case value_t::array:
+                return write_bson_array(name, *j.m_value.array);
+
+            case value_t::binary:
+                return write_bson_binary(name, *j.m_value.binary);
+
+            case value_t::boolean:
+                return write_bson_boolean(name, j.m_value.boolean);
+
+            case value_t::number_float:
+                return write_bson_double(name, j.m_value.number_float);
+
+            case value_t::number_integer:
+                return write_bson_integer(name, j.m_value.number_integer);
+
+            case value_t::number_unsigned:
+                return write_bson_unsigned(name, j);
+
+            case value_t::string:
+                return write_bson_string(name, *j.m_value.string);
+
+            case value_t::null:
+                return write_bson_null(name);
+
+            // LCOV_EXCL_START
+            case value_t::discarded:
+            default:
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert)
+                return;
+                // LCOV_EXCL_STOP
+        }
+    }
+
+    /*!
+    @brief Calculates the size of the BSON serialization of the given
+           JSON-object @a j.
+    @param[in] value  JSON value to serialize
+    @pre       value.type() == value_t::object
+    */
+    static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
+    {
+        std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast<std::size_t>(0),
+                                    [](size_t result, const typename BasicJsonType::object_t::value_type & el)
+        {
+            return result += calc_bson_element_size(el.first, el.second);
+        });
+
+        return sizeof(std::int32_t) + document_size + 1ul;
+    }
+
+    /*!
+    @param[in] value  JSON value to serialize
+    @pre       value.type() == value_t::object
+    */
+    void write_bson_object(const typename BasicJsonType::object_t& value)
+    {
+        write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
+
+        for (const auto& el : value)
+        {
+            write_bson_element(el.first, el.second);
+        }
+
+        oa->write_character(to_char_type(0x00));
+    }
+
+    //////////
+    // CBOR //
+    //////////
+
+    static constexpr CharType get_cbor_float_prefix(float /*unused*/)
+    {
+        return to_char_type(0xFA);  // Single-Precision Float
+    }
+
+    static constexpr CharType get_cbor_float_prefix(double /*unused*/)
+    {
+        return to_char_type(0xFB);  // Double-Precision Float
+    }
+
+    /////////////
+    // MsgPack //
+    /////////////
+
+    static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
+    {
+        return to_char_type(0xCA);  // float 32
+    }
+
+    static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
+    {
+        return to_char_type(0xCB);  // float 64
+    }
+
+    ////////////
+    // UBJSON //
+    ////////////
+
+    // UBJSON: write number (floating point)
+    template<typename NumberType, typename std::enable_if<
+                 std::is_floating_point<NumberType>::value, int>::type = 0>
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if (add_prefix)
+        {
+            oa->write_character(get_ubjson_float_prefix(n));
+        }
+        write_number(n);
+    }
+
+    // UBJSON: write number (unsigned integer)
+    template<typename NumberType, typename std::enable_if<
+                 std::is_unsigned<NumberType>::value, int>::type = 0>
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('i'));  // int8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if (n <= (std::numeric_limits<std::uint8_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('U'));  // uint8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('I'));  // int16
+            }
+            write_number(static_cast<std::int16_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('l'));  // int32
+            }
+            write_number(static_cast<std::int32_t>(n));
+        }
+        else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('L'));  // int64
+            }
+            write_number(static_cast<std::int64_t>(n));
+        }
+        else
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('H'));  // high-precision number
+            }
+
+            const auto number = BasicJsonType(n).dump();
+            write_number_with_ubjson_prefix(number.size(), true);
+            for (std::size_t i = 0; i < number.size(); ++i)
+            {
+                oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
+            }
+        }
+    }
+
+    // UBJSON: write number (signed integer)
+    template < typename NumberType, typename std::enable_if <
+                   std::is_signed<NumberType>::value&&
+                   !std::is_floating_point<NumberType>::value, int >::type = 0 >
+    void write_number_with_ubjson_prefix(const NumberType n,
+                                         const bool add_prefix)
+    {
+        if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('i'));  // int8
+            }
+            write_number(static_cast<std::int8_t>(n));
+        }
+        else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('U'));  // uint8
+            }
+            write_number(static_cast<std::uint8_t>(n));
+        }
+        else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('I'));  // int16
+            }
+            write_number(static_cast<std::int16_t>(n));
+        }
+        else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('l'));  // int32
+            }
+            write_number(static_cast<std::int32_t>(n));
+        }
+        else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('L'));  // int64
+            }
+            write_number(static_cast<std::int64_t>(n));
+        }
+        // LCOV_EXCL_START
+        else
+        {
+            if (add_prefix)
+            {
+                oa->write_character(to_char_type('H'));  // high-precision number
+            }
+
+            const auto number = BasicJsonType(n).dump();
+            write_number_with_ubjson_prefix(number.size(), true);
+            for (std::size_t i = 0; i < number.size(); ++i)
+            {
+                oa->write_character(to_char_type(static_cast<std::uint8_t>(number[i])));
+            }
+        }
+        // LCOV_EXCL_STOP
+    }
+
+    /*!
+    @brief determine the type prefix of container values
+    */
+    CharType ubjson_prefix(const BasicJsonType& j) const noexcept
+    {
+        switch (j.type())
+        {
+            case value_t::null:
+                return 'Z';
+
+            case value_t::boolean:
+                return j.m_value.boolean ? 'T' : 'F';
+
+            case value_t::number_integer:
+            {
+                if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
+                {
+                    return 'i';
+                }
+                if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
+                {
+                    return 'U';
+                }
+                if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
+                {
+                    return 'I';
+                }
+                if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
+                {
+                    return 'l';
+                }
+                if ((std::numeric_limits<std::int64_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
+                {
+                    return 'L';
+                }
+                // anything else is treated as high-precision number
+                return 'H'; // LCOV_EXCL_LINE
+            }
+
+            case value_t::number_unsigned:
+            {
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
+                {
+                    return 'i';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
+                {
+                    return 'U';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
+                {
+                    return 'I';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
+                {
+                    return 'l';
+                }
+                if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
+                {
+                    return 'L';
+                }
+                // anything else is treated as high-precision number
+                return 'H'; // LCOV_EXCL_LINE
+            }
+
+            case value_t::number_float:
+                return get_ubjson_float_prefix(j.m_value.number_float);
+
+            case value_t::string:
+                return 'S';
+
+            case value_t::array: // fallthrough
+            case value_t::binary:
+                return '[';
+
+            case value_t::object:
+                return '{';
+
+            case value_t::discarded:
+            default:  // discarded values
+                return 'N';
+        }
+    }
+
+    static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
+    {
+        return 'd';  // float 32
+    }
+
+    static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
+    {
+        return 'D';  // float 64
+    }
+
+    ///////////////////////
+    // Utility functions //
+    ///////////////////////
+
+    /*
+    @brief write a number to output input
+    @param[in] n number of type @a NumberType
+    @tparam NumberType the type of the number
+    @tparam OutputIsLittleEndian Set to true if output data is
+                                 required to be little endian
+
+    @note This function needs to respect the system's endianness, because bytes
+          in CBOR, MessagePack, and UBJSON are stored in network order (big
+          endian) and therefore need reordering on little endian systems.
+    */
+    template<typename NumberType, bool OutputIsLittleEndian = false>
+    void write_number(const NumberType n)
+    {
+        // step 1: write number to array of length NumberType
+        std::array<CharType, sizeof(NumberType)> vec{};
+        std::memcpy(vec.data(), &n, sizeof(NumberType));
+
+        // step 2: write array to output (with possible reordering)
+        if (is_little_endian != OutputIsLittleEndian)
+        {
+            // reverse byte order prior to conversion if necessary
+            std::reverse(vec.begin(), vec.end());
+        }
+
+        oa->write_characters(vec.data(), sizeof(NumberType));
+    }
+
+    void write_compact_float(const number_float_t n, detail::input_format_t format)
+    {
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+        if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
+                static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
+                static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
+        {
+            oa->write_character(format == detail::input_format_t::cbor
+                                ? get_cbor_float_prefix(static_cast<float>(n))
+                                : get_msgpack_float_prefix(static_cast<float>(n)));
+            write_number(static_cast<float>(n));
+        }
+        else
+        {
+            oa->write_character(format == detail::input_format_t::cbor
+                                ? get_cbor_float_prefix(n)
+                                : get_msgpack_float_prefix(n));
+            write_number(n);
+        }
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+    }
+
+  public:
+    // The following to_char_type functions are implement the conversion
+    // between uint8_t and CharType. In case CharType is not unsigned,
+    // such a conversion is required to allow values greater than 128.
+    // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
+    template < typename C = CharType,
+               enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
+    static constexpr CharType to_char_type(std::uint8_t x) noexcept
+    {
+        return *reinterpret_cast<char*>(&x);
+    }
+
+    template < typename C = CharType,
+               enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
+    static CharType to_char_type(std::uint8_t x) noexcept
+    {
+        static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
+        static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
+        CharType result;
+        std::memcpy(&result, &x, sizeof(x));
+        return result;
+    }
+
+    template<typename C = CharType,
+             enable_if_t<std::is_unsigned<C>::value>* = nullptr>
+    static constexpr CharType to_char_type(std::uint8_t x) noexcept
+    {
+        return x;
+    }
+
+    template < typename InputCharType, typename C = CharType,
+               enable_if_t <
+                   std::is_signed<C>::value &&
+                   std::is_signed<char>::value &&
+                   std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
+                   > * = nullptr >
+    static constexpr CharType to_char_type(InputCharType x) noexcept
+    {
+        return x;
+    }
+
+  private:
+    /// whether we can assume little endianness
+    const bool is_little_endian = little_endianness();
+
+    /// the output
+    output_adapter_t<CharType> oa = nullptr;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/output/serializer.hpp>
+
+
+#include <algorithm> // reverse, remove, fill, find, none_of
+#include <array> // array
+#include <clocale> // localeconv, lconv
+#include <cmath> // labs, isfinite, isnan, signbit
+#include <cstddef> // size_t, ptrdiff_t
+#include <cstdint> // uint8_t
+#include <cstdio> // snprintf
+#include <limits> // numeric_limits
+#include <string> // string, char_traits
+#include <iomanip> // setfill, setw
+#include <sstream> // stringstream
+#include <type_traits> // is_same
+#include <utility> // move
+
+// #include <nlohmann/detail/conversions/to_chars.hpp>
+
+
+#include <array> // array
+#include <cmath>   // signbit, isfinite
+#include <cstdint> // intN_t, uintN_t
+#include <cstring> // memcpy, memmove
+#include <limits> // numeric_limits
+#include <type_traits> // conditional
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+
+/*!
+@brief implements the Grisu2 algorithm for binary to decimal floating-point
+conversion.
+
+This implementation is a slightly modified version of the reference
+implementation which may be obtained from
+http://florian.loitsch.com/publications (bench.tar.gz).
+
+The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
+
+For a detailed description of the algorithm see:
+
+[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
+    Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
+    Language Design and Implementation, PLDI 2010
+[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
+    Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
+    Design and Implementation, PLDI 1996
+*/
+namespace dtoa_impl
+{
+
+template<typename Target, typename Source>
+Target reinterpret_bits(const Source source)
+{
+    static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
+
+    Target target;
+    std::memcpy(&target, &source, sizeof(Source));
+    return target;
+}
+
+struct diyfp // f * 2^e
+{
+    static constexpr int kPrecision = 64; // = q
+
+    std::uint64_t f = 0;
+    int e = 0;
+
+    constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
+
+    /*!
+    @brief returns x - y
+    @pre x.e == y.e and x.f >= y.f
+    */
+    static diyfp sub(const diyfp& x, const diyfp& y) noexcept
+    {
+        JSON_ASSERT(x.e == y.e);
+        JSON_ASSERT(x.f >= y.f);
+
+        return {x.f - y.f, x.e};
+    }
+
+    /*!
+    @brief returns x * y
+    @note The result is rounded. (Only the upper q bits are returned.)
+    */
+    static diyfp mul(const diyfp& x, const diyfp& y) noexcept
+    {
+        static_assert(kPrecision == 64, "internal error");
+
+        // Computes:
+        //  f = round((x.f * y.f) / 2^q)
+        //  e = x.e + y.e + q
+
+        // Emulate the 64-bit * 64-bit multiplication:
+        //
+        // p = u * v
+        //   = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
+        //   = (u_lo v_lo         ) + 2^32 ((u_lo v_hi         ) + (u_hi v_lo         )) + 2^64 (u_hi v_hi         )
+        //   = (p0                ) + 2^32 ((p1                ) + (p2                )) + 2^64 (p3                )
+        //   = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3                )
+        //   = (p0_lo             ) + 2^32 (p0_hi + p1_lo + p2_lo                      ) + 2^64 (p1_hi + p2_hi + p3)
+        //   = (p0_lo             ) + 2^32 (Q                                          ) + 2^64 (H                 )
+        //   = (p0_lo             ) + 2^32 (Q_lo + 2^32 Q_hi                           ) + 2^64 (H                 )
+        //
+        // (Since Q might be larger than 2^32 - 1)
+        //
+        //   = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
+        //
+        // (Q_hi + H does not overflow a 64-bit int)
+        //
+        //   = p_lo + 2^64 p_hi
+
+        const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
+        const std::uint64_t u_hi = x.f >> 32u;
+        const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
+        const std::uint64_t v_hi = y.f >> 32u;
+
+        const std::uint64_t p0 = u_lo * v_lo;
+        const std::uint64_t p1 = u_lo * v_hi;
+        const std::uint64_t p2 = u_hi * v_lo;
+        const std::uint64_t p3 = u_hi * v_hi;
+
+        const std::uint64_t p0_hi = p0 >> 32u;
+        const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
+        const std::uint64_t p1_hi = p1 >> 32u;
+        const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
+        const std::uint64_t p2_hi = p2 >> 32u;
+
+        std::uint64_t Q = p0_hi + p1_lo + p2_lo;
+
+        // The full product might now be computed as
+        //
+        // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
+        // p_lo = p0_lo + (Q << 32)
+        //
+        // But in this particular case here, the full p_lo is not required.
+        // Effectively we only need to add the highest bit in p_lo to p_hi (and
+        // Q_hi + 1 does not overflow).
+
+        Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
+
+        const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
+
+        return {h, x.e + y.e + 64};
+    }
+
+    /*!
+    @brief normalize x such that the significand is >= 2^(q-1)
+    @pre x.f != 0
+    */
+    static diyfp normalize(diyfp x) noexcept
+    {
+        JSON_ASSERT(x.f != 0);
+
+        while ((x.f >> 63u) == 0)
+        {
+            x.f <<= 1u;
+            x.e--;
+        }
+
+        return x;
+    }
+
+    /*!
+    @brief normalize x such that the result has the exponent E
+    @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
+    */
+    static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
+    {
+        const int delta = x.e - target_exponent;
+
+        JSON_ASSERT(delta >= 0);
+        JSON_ASSERT(((x.f << delta) >> delta) == x.f);
+
+        return {x.f << delta, target_exponent};
+    }
+};
+
+struct boundaries
+{
+    diyfp w;
+    diyfp minus;
+    diyfp plus;
+};
+
+/*!
+Compute the (normalized) diyfp representing the input number 'value' and its
+boundaries.
+
+@pre value must be finite and positive
+*/
+template<typename FloatType>
+boundaries compute_boundaries(FloatType value)
+{
+    JSON_ASSERT(std::isfinite(value));
+    JSON_ASSERT(value > 0);
+
+    // Convert the IEEE representation into a diyfp.
+    //
+    // If v is denormal:
+    //      value = 0.F * 2^(1 - bias) = (          F) * 2^(1 - bias - (p-1))
+    // If v is normalized:
+    //      value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
+
+    static_assert(std::numeric_limits<FloatType>::is_iec559,
+                  "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
+
+    constexpr int      kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
+    constexpr int      kBias      = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
+    constexpr int      kMinExp    = 1 - kBias;
+    constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
+
+    using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
+
+    const auto bits = static_cast<std::uint64_t>(reinterpret_bits<bits_type>(value));
+    const std::uint64_t E = bits >> (kPrecision - 1);
+    const std::uint64_t F = bits & (kHiddenBit - 1);
+
+    const bool is_denormal = E == 0;
+    const diyfp v = is_denormal
+                    ? diyfp(F, kMinExp)
+                    : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
+
+    // Compute the boundaries m- and m+ of the floating-point value
+    // v = f * 2^e.
+    //
+    // Determine v- and v+, the floating-point predecessor and successor if v,
+    // respectively.
+    //
+    //      v- = v - 2^e        if f != 2^(p-1) or e == e_min                (A)
+    //         = v - 2^(e-1)    if f == 2^(p-1) and e > e_min                (B)
+    //
+    //      v+ = v + 2^e
+    //
+    // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
+    // between m- and m+ round to v, regardless of how the input rounding
+    // algorithm breaks ties.
+    //
+    //      ---+-------------+-------------+-------------+-------------+---  (A)
+    //         v-            m-            v             m+            v+
+    //
+    //      -----------------+------+------+-------------+-------------+---  (B)
+    //                       v-     m-     v             m+            v+
+
+    const bool lower_boundary_is_closer = F == 0 && E > 1;
+    const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
+    const diyfp m_minus = lower_boundary_is_closer
+                          ? diyfp(4 * v.f - 1, v.e - 2)  // (B)
+                          : diyfp(2 * v.f - 1, v.e - 1); // (A)
+
+    // Determine the normalized w+ = m+.
+    const diyfp w_plus = diyfp::normalize(m_plus);
+
+    // Determine w- = m- such that e_(w-) = e_(w+).
+    const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
+
+    return {diyfp::normalize(v), w_minus, w_plus};
+}
+
+// Given normalized diyfp w, Grisu needs to find a (normalized) cached
+// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
+// within a certain range [alpha, gamma] (Definition 3.2 from [1])
+//
+//      alpha <= e = e_c + e_w + q <= gamma
+//
+// or
+//
+//      f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
+//                          <= f_c * f_w * 2^gamma
+//
+// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
+//
+//      2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
+//
+// or
+//
+//      2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
+//
+// The choice of (alpha,gamma) determines the size of the table and the form of
+// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
+// in practice:
+//
+// The idea is to cut the number c * w = f * 2^e into two parts, which can be
+// processed independently: An integral part p1, and a fractional part p2:
+//
+//      f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
+//              = (f div 2^-e) + (f mod 2^-e) * 2^e
+//              = p1 + p2 * 2^e
+//
+// The conversion of p1 into decimal form requires a series of divisions and
+// modulos by (a power of) 10. These operations are faster for 32-bit than for
+// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
+// achieved by choosing
+//
+//      -e >= 32   or   e <= -32 := gamma
+//
+// In order to convert the fractional part
+//
+//      p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
+//
+// into decimal form, the fraction is repeatedly multiplied by 10 and the digits
+// d[-i] are extracted in order:
+//
+//      (10 * p2) div 2^-e = d[-1]
+//      (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
+//
+// The multiplication by 10 must not overflow. It is sufficient to choose
+//
+//      10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
+//
+// Since p2 = f mod 2^-e < 2^-e,
+//
+//      -e <= 60   or   e >= -60 := alpha
+
+constexpr int kAlpha = -60;
+constexpr int kGamma = -32;
+
+struct cached_power // c = f * 2^e ~= 10^k
+{
+    std::uint64_t f;
+    int e;
+    int k;
+};
+
+/*!
+For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
+power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
+satisfies (Definition 3.2 from [1])
+
+     alpha <= e_c + e + q <= gamma.
+*/
+inline cached_power get_cached_power_for_binary_exponent(int e)
+{
+    // Now
+    //
+    //      alpha <= e_c + e + q <= gamma                                    (1)
+    //      ==> f_c * 2^alpha <= c * 2^e * 2^q
+    //
+    // and since the c's are normalized, 2^(q-1) <= f_c,
+    //
+    //      ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
+    //      ==> 2^(alpha - e - 1) <= c
+    //
+    // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
+    //
+    //      k = ceil( log_10( 2^(alpha - e - 1) ) )
+    //        = ceil( (alpha - e - 1) * log_10(2) )
+    //
+    // From the paper:
+    // "In theory the result of the procedure could be wrong since c is rounded,
+    //  and the computation itself is approximated [...]. In practice, however,
+    //  this simple function is sufficient."
+    //
+    // For IEEE double precision floating-point numbers converted into
+    // normalized diyfp's w = f * 2^e, with q = 64,
+    //
+    //      e >= -1022      (min IEEE exponent)
+    //           -52        (p - 1)
+    //           -52        (p - 1, possibly normalize denormal IEEE numbers)
+    //           -11        (normalize the diyfp)
+    //         = -1137
+    //
+    // and
+    //
+    //      e <= +1023      (max IEEE exponent)
+    //           -52        (p - 1)
+    //           -11        (normalize the diyfp)
+    //         = 960
+    //
+    // This binary exponent range [-1137,960] results in a decimal exponent
+    // range [-307,324]. One does not need to store a cached power for each
+    // k in this range. For each such k it suffices to find a cached power
+    // such that the exponent of the product lies in [alpha,gamma].
+    // This implies that the difference of the decimal exponents of adjacent
+    // table entries must be less than or equal to
+    //
+    //      floor( (gamma - alpha) * log_10(2) ) = 8.
+    //
+    // (A smaller distance gamma-alpha would require a larger table.)
+
+    // NB:
+    // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
+
+    constexpr int kCachedPowersMinDecExp = -300;
+    constexpr int kCachedPowersDecStep = 8;
+
+    static constexpr std::array<cached_power, 79> kCachedPowers =
+    {
+        {
+            { 0xAB70FE17C79AC6CA, -1060, -300 },
+            { 0xFF77B1FCBEBCDC4F, -1034, -292 },
+            { 0xBE5691EF416BD60C, -1007, -284 },
+            { 0x8DD01FAD907FFC3C,  -980, -276 },
+            { 0xD3515C2831559A83,  -954, -268 },
+            { 0x9D71AC8FADA6C9B5,  -927, -260 },
+            { 0xEA9C227723EE8BCB,  -901, -252 },
+            { 0xAECC49914078536D,  -874, -244 },
+            { 0x823C12795DB6CE57,  -847, -236 },
+            { 0xC21094364DFB5637,  -821, -228 },
+            { 0x9096EA6F3848984F,  -794, -220 },
+            { 0xD77485CB25823AC7,  -768, -212 },
+            { 0xA086CFCD97BF97F4,  -741, -204 },
+            { 0xEF340A98172AACE5,  -715, -196 },
+            { 0xB23867FB2A35B28E,  -688, -188 },
+            { 0x84C8D4DFD2C63F3B,  -661, -180 },
+            { 0xC5DD44271AD3CDBA,  -635, -172 },
+            { 0x936B9FCEBB25C996,  -608, -164 },
+            { 0xDBAC6C247D62A584,  -582, -156 },
+            { 0xA3AB66580D5FDAF6,  -555, -148 },
+            { 0xF3E2F893DEC3F126,  -529, -140 },
+            { 0xB5B5ADA8AAFF80B8,  -502, -132 },
+            { 0x87625F056C7C4A8B,  -475, -124 },
+            { 0xC9BCFF6034C13053,  -449, -116 },
+            { 0x964E858C91BA2655,  -422, -108 },
+            { 0xDFF9772470297EBD,  -396, -100 },
+            { 0xA6DFBD9FB8E5B88F,  -369,  -92 },
+            { 0xF8A95FCF88747D94,  -343,  -84 },
+            { 0xB94470938FA89BCF,  -316,  -76 },
+            { 0x8A08F0F8BF0F156B,  -289,  -68 },
+            { 0xCDB02555653131B6,  -263,  -60 },
+            { 0x993FE2C6D07B7FAC,  -236,  -52 },
+            { 0xE45C10C42A2B3B06,  -210,  -44 },
+            { 0xAA242499697392D3,  -183,  -36 },
+            { 0xFD87B5F28300CA0E,  -157,  -28 },
+            { 0xBCE5086492111AEB,  -130,  -20 },
+            { 0x8CBCCC096F5088CC,  -103,  -12 },
+            { 0xD1B71758E219652C,   -77,   -4 },
+            { 0x9C40000000000000,   -50,    4 },
+            { 0xE8D4A51000000000,   -24,   12 },
+            { 0xAD78EBC5AC620000,     3,   20 },
+            { 0x813F3978F8940984,    30,   28 },
+            { 0xC097CE7BC90715B3,    56,   36 },
+            { 0x8F7E32CE7BEA5C70,    83,   44 },
+            { 0xD5D238A4ABE98068,   109,   52 },
+            { 0x9F4F2726179A2245,   136,   60 },
+            { 0xED63A231D4C4FB27,   162,   68 },
+            { 0xB0DE65388CC8ADA8,   189,   76 },
+            { 0x83C7088E1AAB65DB,   216,   84 },
+            { 0xC45D1DF942711D9A,   242,   92 },
+            { 0x924D692CA61BE758,   269,  100 },
+            { 0xDA01EE641A708DEA,   295,  108 },
+            { 0xA26DA3999AEF774A,   322,  116 },
+            { 0xF209787BB47D6B85,   348,  124 },
+            { 0xB454E4A179DD1877,   375,  132 },
+            { 0x865B86925B9BC5C2,   402,  140 },
+            { 0xC83553C5C8965D3D,   428,  148 },
+            { 0x952AB45CFA97A0B3,   455,  156 },
+            { 0xDE469FBD99A05FE3,   481,  164 },
+            { 0xA59BC234DB398C25,   508,  172 },
+            { 0xF6C69A72A3989F5C,   534,  180 },
+            { 0xB7DCBF5354E9BECE,   561,  188 },
+            { 0x88FCF317F22241E2,   588,  196 },
+            { 0xCC20CE9BD35C78A5,   614,  204 },
+            { 0x98165AF37B2153DF,   641,  212 },
+            { 0xE2A0B5DC971F303A,   667,  220 },
+            { 0xA8D9D1535CE3B396,   694,  228 },
+            { 0xFB9B7CD9A4A7443C,   720,  236 },
+            { 0xBB764C4CA7A44410,   747,  244 },
+            { 0x8BAB8EEFB6409C1A,   774,  252 },
+            { 0xD01FEF10A657842C,   800,  260 },
+            { 0x9B10A4E5E9913129,   827,  268 },
+            { 0xE7109BFBA19C0C9D,   853,  276 },
+            { 0xAC2820D9623BF429,   880,  284 },
+            { 0x80444B5E7AA7CF85,   907,  292 },
+            { 0xBF21E44003ACDD2D,   933,  300 },
+            { 0x8E679C2F5E44FF8F,   960,  308 },
+            { 0xD433179D9C8CB841,   986,  316 },
+            { 0x9E19DB92B4E31BA9,  1013,  324 },
+        }
+    };
+
+    // This computation gives exactly the same results for k as
+    //      k = ceil((kAlpha - e - 1) * 0.30102999566398114)
+    // for |e| <= 1500, but doesn't require floating-point operations.
+    // NB: log_10(2) ~= 78913 / 2^18
+    JSON_ASSERT(e >= -1500);
+    JSON_ASSERT(e <=  1500);
+    const int f = kAlpha - e - 1;
+    const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
+
+    const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
+    JSON_ASSERT(index >= 0);
+    JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
+
+    const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
+    JSON_ASSERT(kAlpha <= cached.e + e + 64);
+    JSON_ASSERT(kGamma >= cached.e + e + 64);
+
+    return cached;
+}
+
+/*!
+For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
+For n == 0, returns 1 and sets pow10 := 1.
+*/
+inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
+{
+    // LCOV_EXCL_START
+    if (n >= 1000000000)
+    {
+        pow10 = 1000000000;
+        return 10;
+    }
+    // LCOV_EXCL_STOP
+    if (n >= 100000000)
+    {
+        pow10 = 100000000;
+        return  9;
+    }
+    if (n >= 10000000)
+    {
+        pow10 = 10000000;
+        return  8;
+    }
+    if (n >= 1000000)
+    {
+        pow10 = 1000000;
+        return  7;
+    }
+    if (n >= 100000)
+    {
+        pow10 = 100000;
+        return  6;
+    }
+    if (n >= 10000)
+    {
+        pow10 = 10000;
+        return  5;
+    }
+    if (n >= 1000)
+    {
+        pow10 = 1000;
+        return  4;
+    }
+    if (n >= 100)
+    {
+        pow10 = 100;
+        return  3;
+    }
+    if (n >= 10)
+    {
+        pow10 = 10;
+        return  2;
+    }
+
+    pow10 = 1;
+    return 1;
+}
+
+inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
+                         std::uint64_t rest, std::uint64_t ten_k)
+{
+    JSON_ASSERT(len >= 1);
+    JSON_ASSERT(dist <= delta);
+    JSON_ASSERT(rest <= delta);
+    JSON_ASSERT(ten_k > 0);
+
+    //               <--------------------------- delta ---->
+    //                                  <---- dist --------->
+    // --------------[------------------+-------------------]--------------
+    //               M-                 w                   M+
+    //
+    //                                  ten_k
+    //                                <------>
+    //                                       <---- rest ---->
+    // --------------[------------------+----+--------------]--------------
+    //                                  w    V
+    //                                       = buf * 10^k
+    //
+    // ten_k represents a unit-in-the-last-place in the decimal representation
+    // stored in buf.
+    // Decrement buf by ten_k while this takes buf closer to w.
+
+    // The tests are written in this order to avoid overflow in unsigned
+    // integer arithmetic.
+
+    while (rest < dist
+            && delta - rest >= ten_k
+            && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
+    {
+        JSON_ASSERT(buf[len - 1] != '0');
+        buf[len - 1]--;
+        rest += ten_k;
+    }
+}
+
+/*!
+Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
+M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
+*/
+inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
+                             diyfp M_minus, diyfp w, diyfp M_plus)
+{
+    static_assert(kAlpha >= -60, "internal error");
+    static_assert(kGamma <= -32, "internal error");
+
+    // Generates the digits (and the exponent) of a decimal floating-point
+    // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
+    // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
+    //
+    //               <--------------------------- delta ---->
+    //                                  <---- dist --------->
+    // --------------[------------------+-------------------]--------------
+    //               M-                 w                   M+
+    //
+    // Grisu2 generates the digits of M+ from left to right and stops as soon as
+    // V is in [M-,M+].
+
+    JSON_ASSERT(M_plus.e >= kAlpha);
+    JSON_ASSERT(M_plus.e <= kGamma);
+
+    std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
+    std::uint64_t dist  = diyfp::sub(M_plus, w      ).f; // (significand of (M+ - w ), implicit exponent is e)
+
+    // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
+    //
+    //      M+ = f * 2^e
+    //         = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
+    //         = ((p1        ) * 2^-e + (p2        )) * 2^e
+    //         = p1 + p2 * 2^e
+
+    const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
+
+    auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
+    std::uint64_t p2 = M_plus.f & (one.f - 1);                    // p2 = f mod 2^-e
+
+    // 1)
+    //
+    // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
+
+    JSON_ASSERT(p1 > 0);
+
+    std::uint32_t pow10{};
+    const int k = find_largest_pow10(p1, pow10);
+
+    //      10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
+    //
+    //      p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
+    //         = (d[k-1]         ) * 10^(k-1) + (p1 mod 10^(k-1))
+    //
+    //      M+ = p1                                             + p2 * 2^e
+    //         = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1))          + p2 * 2^e
+    //         = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
+    //         = d[k-1] * 10^(k-1) + (                         rest) * 2^e
+    //
+    // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
+    //
+    //      p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
+    //
+    // but stop as soon as
+    //
+    //      rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
+
+    int n = k;
+    while (n > 0)
+    {
+        // Invariants:
+        //      M+ = buffer * 10^n + (p1 + p2 * 2^e)    (buffer = 0 for n = k)
+        //      pow10 = 10^(n-1) <= p1 < 10^n
+        //
+        const std::uint32_t d = p1 / pow10;  // d = p1 div 10^(n-1)
+        const std::uint32_t r = p1 % pow10;  // r = p1 mod 10^(n-1)
+        //
+        //      M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
+        //         = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
+        //
+        JSON_ASSERT(d <= 9);
+        buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+        //
+        //      M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
+        //
+        p1 = r;
+        n--;
+        //
+        //      M+ = buffer * 10^n + (p1 + p2 * 2^e)
+        //      pow10 = 10^n
+        //
+
+        // Now check if enough digits have been generated.
+        // Compute
+        //
+        //      p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
+        //
+        // Note:
+        // Since rest and delta share the same exponent e, it suffices to
+        // compare the significands.
+        const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
+        if (rest <= delta)
+        {
+            // V = buffer * 10^n, with M- <= V <= M+.
+
+            decimal_exponent += n;
+
+            // We may now just stop. But instead look if the buffer could be
+            // decremented to bring V closer to w.
+            //
+            // pow10 = 10^n is now 1 ulp in the decimal representation V.
+            // The rounding procedure works with diyfp's with an implicit
+            // exponent of e.
+            //
+            //      10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
+            //
+            const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
+            grisu2_round(buffer, length, dist, delta, rest, ten_n);
+
+            return;
+        }
+
+        pow10 /= 10;
+        //
+        //      pow10 = 10^(n-1) <= p1 < 10^n
+        // Invariants restored.
+    }
+
+    // 2)
+    //
+    // The digits of the integral part have been generated:
+    //
+    //      M+ = d[k-1]...d[1]d[0] + p2 * 2^e
+    //         = buffer            + p2 * 2^e
+    //
+    // Now generate the digits of the fractional part p2 * 2^e.
+    //
+    // Note:
+    // No decimal point is generated: the exponent is adjusted instead.
+    //
+    // p2 actually represents the fraction
+    //
+    //      p2 * 2^e
+    //          = p2 / 2^-e
+    //          = d[-1] / 10^1 + d[-2] / 10^2 + ...
+    //
+    // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
+    //
+    //      p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
+    //                      + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
+    //
+    // using
+    //
+    //      10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
+    //                = (                   d) * 2^-e + (                   r)
+    //
+    // or
+    //      10^m * p2 * 2^e = d + r * 2^e
+    //
+    // i.e.
+    //
+    //      M+ = buffer + p2 * 2^e
+    //         = buffer + 10^-m * (d + r * 2^e)
+    //         = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
+    //
+    // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
+
+    JSON_ASSERT(p2 > delta);
+
+    int m = 0;
+    for (;;)
+    {
+        // Invariant:
+        //      M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
+        //         = buffer * 10^-m + 10^-m * (p2                                 ) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * (10 * p2)                   ) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
+        //
+        JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
+        p2 *= 10;
+        const std::uint64_t d = p2 >> -one.e;     // d = (10 * p2) div 2^-e
+        const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
+        //
+        //      M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
+        //         = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
+        //         = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
+        //
+        JSON_ASSERT(d <= 9);
+        buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
+        //
+        //      M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
+        //
+        p2 = r;
+        m++;
+        //
+        //      M+ = buffer * 10^-m + 10^-m * p2 * 2^e
+        // Invariant restored.
+
+        // Check if enough digits have been generated.
+        //
+        //      10^-m * p2 * 2^e <= delta * 2^e
+        //              p2 * 2^e <= 10^m * delta * 2^e
+        //                    p2 <= 10^m * delta
+        delta *= 10;
+        dist  *= 10;
+        if (p2 <= delta)
+        {
+            break;
+        }
+    }
+
+    // V = buffer * 10^-m, with M- <= V <= M+.
+
+    decimal_exponent -= m;
+
+    // 1 ulp in the decimal representation is now 10^-m.
+    // Since delta and dist are now scaled by 10^m, we need to do the
+    // same with ulp in order to keep the units in sync.
+    //
+    //      10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
+    //
+    const std::uint64_t ten_m = one.f;
+    grisu2_round(buffer, length, dist, delta, p2, ten_m);
+
+    // By construction this algorithm generates the shortest possible decimal
+    // number (Loitsch, Theorem 6.2) which rounds back to w.
+    // For an input number of precision p, at least
+    //
+    //      N = 1 + ceil(p * log_10(2))
+    //
+    // decimal digits are sufficient to identify all binary floating-point
+    // numbers (Matula, "In-and-Out conversions").
+    // This implies that the algorithm does not produce more than N decimal
+    // digits.
+    //
+    //      N = 17 for p = 53 (IEEE double precision)
+    //      N = 9  for p = 24 (IEEE single precision)
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+JSON_HEDLEY_NON_NULL(1)
+inline void grisu2(char* buf, int& len, int& decimal_exponent,
+                   diyfp m_minus, diyfp v, diyfp m_plus)
+{
+    JSON_ASSERT(m_plus.e == m_minus.e);
+    JSON_ASSERT(m_plus.e == v.e);
+
+    //  --------(-----------------------+-----------------------)--------    (A)
+    //          m-                      v                       m+
+    //
+    //  --------------------(-----------+-----------------------)--------    (B)
+    //                      m-          v                       m+
+    //
+    // First scale v (and m- and m+) such that the exponent is in the range
+    // [alpha, gamma].
+
+    const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
+
+    const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
+
+    // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
+    const diyfp w       = diyfp::mul(v,       c_minus_k);
+    const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
+    const diyfp w_plus  = diyfp::mul(m_plus,  c_minus_k);
+
+    //  ----(---+---)---------------(---+---)---------------(---+---)----
+    //          w-                      w                       w+
+    //          = c*m-                  = c*v                   = c*m+
+    //
+    // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
+    // w+ are now off by a small amount.
+    // In fact:
+    //
+    //      w - v * 10^k < 1 ulp
+    //
+    // To account for this inaccuracy, add resp. subtract 1 ulp.
+    //
+    //  --------+---[---------------(---+---)---------------]---+--------
+    //          w-  M-                  w                   M+  w+
+    //
+    // Now any number in [M-, M+] (bounds included) will round to w when input,
+    // regardless of how the input rounding algorithm breaks ties.
+    //
+    // And digit_gen generates the shortest possible such number in [M-, M+].
+    // Note that this does not mean that Grisu2 always generates the shortest
+    // possible number in the interval (m-, m+).
+    const diyfp M_minus(w_minus.f + 1, w_minus.e);
+    const diyfp M_plus (w_plus.f  - 1, w_plus.e );
+
+    decimal_exponent = -cached.k; // = -(-k) = k
+
+    grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
+}
+
+/*!
+v = buf * 10^decimal_exponent
+len is the length of the buffer (number of decimal digits)
+The buffer must be large enough, i.e. >= max_digits10.
+*/
+template<typename FloatType>
+JSON_HEDLEY_NON_NULL(1)
+void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
+{
+    static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
+                  "internal error: not enough precision");
+
+    JSON_ASSERT(std::isfinite(value));
+    JSON_ASSERT(value > 0);
+
+    // If the neighbors (and boundaries) of 'value' are always computed for double-precision
+    // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
+    // decimal representations are not exactly "short".
+    //
+    // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
+    // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
+    // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars'
+    // does.
+    // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
+    // representation using the corresponding std::from_chars function recovers value exactly". That
+    // indicates that single precision floating-point numbers should be recovered using
+    // 'std::strtof'.
+    //
+    // NB: If the neighbors are computed for single-precision numbers, there is a single float
+    //     (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
+    //     value is off by 1 ulp.
+#if 0
+    const boundaries w = compute_boundaries(static_cast<double>(value));
+#else
+    const boundaries w = compute_boundaries(value);
+#endif
+
+    grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
+}
+
+/*!
+@brief appends a decimal representation of e to buf
+@return a pointer to the element following the exponent.
+@pre -1000 < e < 1000
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char* append_exponent(char* buf, int e)
+{
+    JSON_ASSERT(e > -1000);
+    JSON_ASSERT(e <  1000);
+
+    if (e < 0)
+    {
+        e = -e;
+        *buf++ = '-';
+    }
+    else
+    {
+        *buf++ = '+';
+    }
+
+    auto k = static_cast<std::uint32_t>(e);
+    if (k < 10)
+    {
+        // Always print at least two digits in the exponent.
+        // This is for compatibility with printf("%g").
+        *buf++ = '0';
+        *buf++ = static_cast<char>('0' + k);
+    }
+    else if (k < 100)
+    {
+        *buf++ = static_cast<char>('0' + k / 10);
+        k %= 10;
+        *buf++ = static_cast<char>('0' + k);
+    }
+    else
+    {
+        *buf++ = static_cast<char>('0' + k / 100);
+        k %= 100;
+        *buf++ = static_cast<char>('0' + k / 10);
+        k %= 10;
+        *buf++ = static_cast<char>('0' + k);
+    }
+
+    return buf;
+}
+
+/*!
+@brief prettify v = buf * 10^decimal_exponent
+
+If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
+notation. Otherwise it will be printed in exponential notation.
+
+@pre min_exp < 0
+@pre max_exp > 0
+*/
+JSON_HEDLEY_NON_NULL(1)
+JSON_HEDLEY_RETURNS_NON_NULL
+inline char* format_buffer(char* buf, int len, int decimal_exponent,
+                           int min_exp, int max_exp)
+{
+    JSON_ASSERT(min_exp < 0);
+    JSON_ASSERT(max_exp > 0);
+
+    const int k = len;
+    const int n = len + decimal_exponent;
+
+    // v = buf * 10^(n-k)
+    // k is the length of the buffer (number of decimal digits)
+    // n is the position of the decimal point relative to the start of the buffer.
+
+    if (k <= n && n <= max_exp)
+    {
+        // digits[000]
+        // len <= max_exp + 2
+
+        std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
+        // Make it look like a floating-point number (#362, #378)
+        buf[n + 0] = '.';
+        buf[n + 1] = '0';
+        return buf + (static_cast<size_t>(n) + 2);
+    }
+
+    if (0 < n && n <= max_exp)
+    {
+        // dig.its
+        // len <= max_digits10 + 1
+
+        JSON_ASSERT(k > n);
+
+        std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
+        buf[n] = '.';
+        return buf + (static_cast<size_t>(k) + 1U);
+    }
+
+    if (min_exp < n && n <= 0)
+    {
+        // 0.[000]digits
+        // len <= 2 + (-min_exp - 1) + max_digits10
+
+        std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
+        buf[0] = '0';
+        buf[1] = '.';
+        std::memset(buf + 2, '0', static_cast<size_t>(-n));
+        return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
+    }
+
+    if (k == 1)
+    {
+        // dE+123
+        // len <= 1 + 5
+
+        buf += 1;
+    }
+    else
+    {
+        // d.igitsE+123
+        // len <= max_digits10 + 1 + 5
+
+        std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
+        buf[1] = '.';
+        buf += 1 + static_cast<size_t>(k);
+    }
+
+    *buf++ = 'e';
+    return append_exponent(buf, n - 1);
+}
+
+} // namespace dtoa_impl
+
+/*!
+@brief generates a decimal representation of the floating-point number value in [first, last).
+
+The format of the resulting decimal representation is similar to printf's %g
+format. Returns an iterator pointing past-the-end of the decimal representation.
+
+@note The input number must be finite, i.e. NaN's and Inf's are not supported.
+@note The buffer must be large enough.
+@note The result is NOT null-terminated.
+*/
+template<typename FloatType>
+JSON_HEDLEY_NON_NULL(1, 2)
+JSON_HEDLEY_RETURNS_NON_NULL
+char* to_chars(char* first, const char* last, FloatType value)
+{
+    static_cast<void>(last); // maybe unused - fix warning
+    JSON_ASSERT(std::isfinite(value));
+
+    // Use signbit(value) instead of (value < 0) since signbit works for -0.
+    if (std::signbit(value))
+    {
+        value = -value;
+        *first++ = '-';
+    }
+
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+    if (value == 0) // +-0
+    {
+        *first++ = '0';
+        // Make it look like a floating-point number (#362, #378)
+        *first++ = '.';
+        *first++ = '0';
+        return first;
+    }
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+
+    JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
+
+    // Compute v = buffer * 10^decimal_exponent.
+    // The decimal digits are stored in the buffer, which needs to be interpreted
+    // as an unsigned decimal integer.
+    // len is the length of the buffer, i.e. the number of decimal digits.
+    int len = 0;
+    int decimal_exponent = 0;
+    dtoa_impl::grisu2(first, len, decimal_exponent, value);
+
+    JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
+
+    // Format the buffer like printf("%.*g", prec, value)
+    constexpr int kMinExp = -4;
+    // Use digits10 here to increase compatibility with version 2.
+    constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
+
+    JSON_ASSERT(last - first >= kMaxExp + 2);
+    JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
+    JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
+
+    return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
+}
+
+} // namespace detail
+} // namespace nlohmann
+
+// #include <nlohmann/detail/exceptions.hpp>
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+// #include <nlohmann/detail/meta/cpp_future.hpp>
+
+// #include <nlohmann/detail/output/binary_writer.hpp>
+
+// #include <nlohmann/detail/output/output_adapters.hpp>
+
+// #include <nlohmann/detail/value_t.hpp>
+
+
+namespace nlohmann
+{
+namespace detail
+{
+///////////////////
+// serialization //
+///////////////////
+
+/// how to treat decoding errors
+enum class error_handler_t
+{
+    strict,  ///< throw a type_error exception in case of invalid UTF-8
+    replace, ///< replace invalid UTF-8 sequences with U+FFFD
+    ignore   ///< ignore invalid UTF-8 sequences
+};
+
+template<typename BasicJsonType>
+class serializer
+{
+    using string_t = typename BasicJsonType::string_t;
+    using number_float_t = typename BasicJsonType::number_float_t;
+    using number_integer_t = typename BasicJsonType::number_integer_t;
+    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+    using binary_char_t = typename BasicJsonType::binary_t::value_type;
+    static constexpr std::uint8_t UTF8_ACCEPT = 0;
+    static constexpr std::uint8_t UTF8_REJECT = 1;
+
+  public:
+    /*!
+    @param[in] s  output stream to serialize to
+    @param[in] ichar  indentation character to use
+    @param[in] error_handler_  how to react on decoding errors
+    */
+    serializer(output_adapter_t<char> s, const char ichar,
+               error_handler_t error_handler_ = error_handler_t::strict)
+        : o(std::move(s))
+        , loc(std::localeconv())
+        , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
+        , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
+        , indent_char(ichar)
+        , indent_string(512, indent_char)
+        , error_handler(error_handler_)
+    {}
+
+    // delete because of pointer members
+    serializer(const serializer&) = delete;
+    serializer& operator=(const serializer&) = delete;
+    serializer(serializer&&) = delete;
+    serializer& operator=(serializer&&) = delete;
+    ~serializer() = default;
+
+    /*!
+    @brief internal implementation of the serialization function
+
+    This function is called by the public member function dump and organizes
+    the serialization internally. The indentation level is propagated as
+    additional parameter. In case of arrays and objects, the function is
+    called recursively.
+
+    - strings and object keys are escaped using `escape_string()`
+    - integer numbers are converted implicitly via `operator<<`
+    - floating-point numbers are converted to a string using `"%g"` format
+    - binary values are serialized as objects containing the subtype and the
+      byte array
+
+    @param[in] val               value to serialize
+    @param[in] pretty_print      whether the output shall be pretty-printed
+    @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
+    in the output are escaped with `\uXXXX` sequences, and the result consists
+    of ASCII characters only.
+    @param[in] indent_step       the indent level
+    @param[in] current_indent    the current indent level (only used internally)
+    */
+    void dump(const BasicJsonType& val,
+              const bool pretty_print,
+              const bool ensure_ascii,
+              const unsigned int indent_step,
+              const unsigned int current_indent = 0)
+    {
+        switch (val.m_type)
+        {
+            case value_t::object:
+            {
+                if (val.m_value.object->empty())
+                {
+                    o->write_characters("{}", 2);
+                    return;
+                }
+
+                if (pretty_print)
+                {
+                    o->write_characters("{\n", 2);
+
+                    // variable to hold indentation for recursive calls
+                    const auto new_indent = current_indent + indent_step;
+                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
+                    {
+                        indent_string.resize(indent_string.size() * 2, ' ');
+                    }
+
+                    // first n-1 elements
+                    auto i = val.m_value.object->cbegin();
+                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
+                    {
+                        o->write_characters(indent_string.c_str(), new_indent);
+                        o->write_character('\"');
+                        dump_escaped(i->first, ensure_ascii);
+                        o->write_characters("\": ", 3);
+                        dump(i->second, true, ensure_ascii, indent_step, new_indent);
+                        o->write_characters(",\n", 2);
+                    }
+
+                    // last element
+                    JSON_ASSERT(i != val.m_value.object->cend());
+                    JSON_ASSERT(std::next(i) == val.m_value.object->cend());
+                    o->write_characters(indent_string.c_str(), new_indent);
+                    o->write_character('\"');
+                    dump_escaped(i->first, ensure_ascii);
+                    o->write_characters("\": ", 3);
+                    dump(i->second, true, ensure_ascii, indent_step, new_indent);
+
+                    o->write_character('\n');
+                    o->write_characters(indent_string.c_str(), current_indent);
+                    o->write_character('}');
+                }
+                else
+                {
+                    o->write_character('{');
+
+                    // first n-1 elements
+                    auto i = val.m_value.object->cbegin();
+                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
+                    {
+                        o->write_character('\"');
+                        dump_escaped(i->first, ensure_ascii);
+                        o->write_characters("\":", 2);
+                        dump(i->second, false, ensure_ascii, indent_step, current_indent);
+                        o->write_character(',');
+                    }
+
+                    // last element
+                    JSON_ASSERT(i != val.m_value.object->cend());
+                    JSON_ASSERT(std::next(i) == val.m_value.object->cend());
+                    o->write_character('\"');
+                    dump_escaped(i->first, ensure_ascii);
+                    o->write_characters("\":", 2);
+                    dump(i->second, false, ensure_ascii, indent_step, current_indent);
+
+                    o->write_character('}');
+                }
+
+                return;
+            }
+
+            case value_t::array:
+            {
+                if (val.m_value.array->empty())
+                {
+                    o->write_characters("[]", 2);
+                    return;
+                }
+
+                if (pretty_print)
+                {
+                    o->write_characters("[\n", 2);
+
+                    // variable to hold indentation for recursive calls
+                    const auto new_indent = current_indent + indent_step;
+                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
+                    {
+                        indent_string.resize(indent_string.size() * 2, ' ');
+                    }
+
+                    // first n-1 elements
+                    for (auto i = val.m_value.array->cbegin();
+                            i != val.m_value.array->cend() - 1; ++i)
+                    {
+                        o->write_characters(indent_string.c_str(), new_indent);
+                        dump(*i, true, ensure_ascii, indent_step, new_indent);
+                        o->write_characters(",\n", 2);
+                    }
+
+                    // last element
+                    JSON_ASSERT(!val.m_value.array->empty());
+                    o->write_characters(indent_string.c_str(), new_indent);
+                    dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
+
+                    o->write_character('\n');
+                    o->write_characters(indent_string.c_str(), current_indent);
+                    o->write_character(']');
+                }
+                else
+                {
+                    o->write_character('[');
+
+                    // first n-1 elements
+                    for (auto i = val.m_value.array->cbegin();
+                            i != val.m_value.array->cend() - 1; ++i)
+                    {
+                        dump(*i, false, ensure_ascii, indent_step, current_indent);
+                        o->write_character(',');
+                    }
+
+                    // last element
+                    JSON_ASSERT(!val.m_value.array->empty());
+                    dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
+
+                    o->write_character(']');
+                }
+
+                return;
+            }
+
+            case value_t::string:
+            {
+                o->write_character('\"');
+                dump_escaped(*val.m_value.string, ensure_ascii);
+                o->write_character('\"');
+                return;
+            }
+
+            case value_t::binary:
+            {
+                if (pretty_print)
+                {
+                    o->write_characters("{\n", 2);
+
+                    // variable to hold indentation for recursive calls
+                    const auto new_indent = current_indent + indent_step;
+                    if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
+                    {
+                        indent_string.resize(indent_string.size() * 2, ' ');
+                    }
+
+                    o->write_characters(indent_string.c_str(), new_indent);
+
+                    o->write_characters("\"bytes\": [", 10);
+
+                    if (!val.m_value.binary->empty())
+                    {
+                        for (auto i = val.m_value.binary->cbegin();
+                                i != val.m_value.binary->cend() - 1; ++i)
+                        {
+                            dump_integer(*i);
+                            o->write_characters(", ", 2);
+                        }
+                        dump_integer(val.m_value.binary->back());
+                    }
+
+                    o->write_characters("],\n", 3);
+                    o->write_characters(indent_string.c_str(), new_indent);
+
+                    o->write_characters("\"subtype\": ", 11);
+                    if (val.m_value.binary->has_subtype())
+                    {
+                        dump_integer(val.m_value.binary->subtype());
+                    }
+                    else
+                    {
+                        o->write_characters("null", 4);
+                    }
+                    o->write_character('\n');
+                    o->write_characters(indent_string.c_str(), current_indent);
+                    o->write_character('}');
+                }
+                else
+                {
+                    o->write_characters("{\"bytes\":[", 10);
+
+                    if (!val.m_value.binary->empty())
+                    {
+                        for (auto i = val.m_value.binary->cbegin();
+                                i != val.m_value.binary->cend() - 1; ++i)
+                        {
+                            dump_integer(*i);
+                            o->write_character(',');
+                        }
+                        dump_integer(val.m_value.binary->back());
+                    }
+
+                    o->write_characters("],\"subtype\":", 12);
+                    if (val.m_value.binary->has_subtype())
+                    {
+                        dump_integer(val.m_value.binary->subtype());
+                        o->write_character('}');
+                    }
+                    else
+                    {
+                        o->write_characters("null}", 5);
+                    }
+                }
+                return;
+            }
+
+            case value_t::boolean:
+            {
+                if (val.m_value.boolean)
+                {
+                    o->write_characters("true", 4);
+                }
+                else
+                {
+                    o->write_characters("false", 5);
+                }
+                return;
+            }
+
+            case value_t::number_integer:
+            {
+                dump_integer(val.m_value.number_integer);
+                return;
+            }
+
+            case value_t::number_unsigned:
+            {
+                dump_integer(val.m_value.number_unsigned);
+                return;
+            }
+
+            case value_t::number_float:
+            {
+                dump_float(val.m_value.number_float);
+                return;
+            }
+
+            case value_t::discarded:
+            {
+                o->write_characters("<discarded>", 11);
+                return;
+            }
+
+            case value_t::null:
+            {
+                o->write_characters("null", 4);
+                return;
+            }
+
+            default:            // LCOV_EXCL_LINE
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        }
+    }
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    /*!
+    @brief dump escaped string
+
+    Escape a string by replacing certain special characters by a sequence of an
+    escape character (backslash) and another character and other control
+    characters by a sequence of "\u" followed by a four-digit hex
+    representation. The escaped string is written to output stream @a o.
+
+    @param[in] s  the string to escape
+    @param[in] ensure_ascii  whether to escape non-ASCII characters with
+                             \uXXXX sequences
+
+    @complexity Linear in the length of string @a s.
+    */
+    void dump_escaped(const string_t& s, const bool ensure_ascii)
+    {
+        std::uint32_t codepoint{};
+        std::uint8_t state = UTF8_ACCEPT;
+        std::size_t bytes = 0;  // number of bytes written to string_buffer
+
+        // number of bytes written at the point of the last valid byte
+        std::size_t bytes_after_last_accept = 0;
+        std::size_t undumped_chars = 0;
+
+        for (std::size_t i = 0; i < s.size(); ++i)
+        {
+            const auto byte = static_cast<std::uint8_t>(s[i]);
+
+            switch (decode(state, codepoint, byte))
+            {
+                case UTF8_ACCEPT:  // decode found a new code point
+                {
+                    switch (codepoint)
+                    {
+                        case 0x08: // backspace
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'b';
+                            break;
+                        }
+
+                        case 0x09: // horizontal tab
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 't';
+                            break;
+                        }
+
+                        case 0x0A: // newline
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'n';
+                            break;
+                        }
+
+                        case 0x0C: // formfeed
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'f';
+                            break;
+                        }
+
+                        case 0x0D: // carriage return
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = 'r';
+                            break;
+                        }
+
+                        case 0x22: // quotation mark
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = '\"';
+                            break;
+                        }
+
+                        case 0x5C: // reverse solidus
+                        {
+                            string_buffer[bytes++] = '\\';
+                            string_buffer[bytes++] = '\\';
+                            break;
+                        }
+
+                        default:
+                        {
+                            // escape control characters (0x00..0x1F) or, if
+                            // ensure_ascii parameter is used, non-ASCII characters
+                            if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
+                            {
+                                if (codepoint <= 0xFFFF)
+                                {
+                                    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+                                    static_cast<void>((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
+                                                                      static_cast<std::uint16_t>(codepoint)));
+                                    bytes += 6;
+                                }
+                                else
+                                {
+                                    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+                                    static_cast<void>((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
+                                                                      static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
+                                                                      static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu))));
+                                    bytes += 12;
+                                }
+                            }
+                            else
+                            {
+                                // copy byte to buffer (all previous bytes
+                                // been copied have in default case above)
+                                string_buffer[bytes++] = s[i];
+                            }
+                            break;
+                        }
+                    }
+
+                    // write buffer and reset index; there must be 13 bytes
+                    // left, as this is the maximal number of bytes to be
+                    // written ("\uxxxx\uxxxx\0") for one code point
+                    if (string_buffer.size() - bytes < 13)
+                    {
+                        o->write_characters(string_buffer.data(), bytes);
+                        bytes = 0;
+                    }
+
+                    // remember the byte position of this accept
+                    bytes_after_last_accept = bytes;
+                    undumped_chars = 0;
+                    break;
+                }
+
+                case UTF8_REJECT:  // decode found invalid UTF-8 byte
+                {
+                    switch (error_handler)
+                    {
+                        case error_handler_t::strict:
+                        {
+                            std::stringstream ss;
+                            ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0);
+                            JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType()));
+                        }
+
+                        case error_handler_t::ignore:
+                        case error_handler_t::replace:
+                        {
+                            // in case we saw this character the first time, we
+                            // would like to read it again, because the byte
+                            // may be OK for itself, but just not OK for the
+                            // previous sequence
+                            if (undumped_chars > 0)
+                            {
+                                --i;
+                            }
+
+                            // reset length buffer to the last accepted index;
+                            // thus removing/ignoring the invalid characters
+                            bytes = bytes_after_last_accept;
+
+                            if (error_handler == error_handler_t::replace)
+                            {
+                                // add a replacement character
+                                if (ensure_ascii)
+                                {
+                                    string_buffer[bytes++] = '\\';
+                                    string_buffer[bytes++] = 'u';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'f';
+                                    string_buffer[bytes++] = 'd';
+                                }
+                                else
+                                {
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
+                                    string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
+                                }
+
+                                // write buffer and reset index; there must be 13 bytes
+                                // left, as this is the maximal number of bytes to be
+                                // written ("\uxxxx\uxxxx\0") for one code point
+                                if (string_buffer.size() - bytes < 13)
+                                {
+                                    o->write_characters(string_buffer.data(), bytes);
+                                    bytes = 0;
+                                }
+
+                                bytes_after_last_accept = bytes;
+                            }
+
+                            undumped_chars = 0;
+
+                            // continue processing the string
+                            state = UTF8_ACCEPT;
+                            break;
+                        }
+
+                        default:            // LCOV_EXCL_LINE
+                            JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+                    }
+                    break;
+                }
+
+                default:  // decode found yet incomplete multi-byte code point
+                {
+                    if (!ensure_ascii)
+                    {
+                        // code point will not be escaped - copy byte to buffer
+                        string_buffer[bytes++] = s[i];
+                    }
+                    ++undumped_chars;
+                    break;
+                }
+            }
+        }
+
+        // we finished processing the string
+        if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
+        {
+            // write buffer
+            if (bytes > 0)
+            {
+                o->write_characters(string_buffer.data(), bytes);
+            }
+        }
+        else
+        {
+            // we finish reading, but do not accept: string was incomplete
+            switch (error_handler)
+            {
+                case error_handler_t::strict:
+                {
+                    std::stringstream ss;
+                    ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast<std::uint8_t>(s.back()) | 0);
+                    JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType()));
+                }
+
+                case error_handler_t::ignore:
+                {
+                    // write all accepted bytes
+                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
+                    break;
+                }
+
+                case error_handler_t::replace:
+                {
+                    // write all accepted bytes
+                    o->write_characters(string_buffer.data(), bytes_after_last_accept);
+                    // add a replacement character
+                    if (ensure_ascii)
+                    {
+                        o->write_characters("\\ufffd", 6);
+                    }
+                    else
+                    {
+                        o->write_characters("\xEF\xBF\xBD", 3);
+                    }
+                    break;
+                }
+
+                default:            // LCOV_EXCL_LINE
+                    JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+            }
+        }
+    }
+
+  private:
+    /*!
+    @brief count digits
+
+    Count the number of decimal (base 10) digits for an input unsigned integer.
+
+    @param[in] x  unsigned integer number to count its digits
+    @return    number of decimal digits
+    */
+    inline unsigned int count_digits(number_unsigned_t x) noexcept
+    {
+        unsigned int n_digits = 1;
+        for (;;)
+        {
+            if (x < 10)
+            {
+                return n_digits;
+            }
+            if (x < 100)
+            {
+                return n_digits + 1;
+            }
+            if (x < 1000)
+            {
+                return n_digits + 2;
+            }
+            if (x < 10000)
+            {
+                return n_digits + 3;
+            }
+            x = x / 10000u;
+            n_digits += 4;
+        }
+    }
+
+    // templates to avoid warnings about useless casts
+    template <typename NumberType, enable_if_t<std::is_signed<NumberType>::value, int> = 0>
+    bool is_negative_number(NumberType x)
+    {
+        return x < 0;
+    }
+
+    template < typename NumberType, enable_if_t <std::is_unsigned<NumberType>::value, int > = 0 >
+    bool is_negative_number(NumberType /*unused*/)
+    {
+        return false;
+    }
+
+    /*!
+    @brief dump an integer
+
+    Dump a given integer to output stream @a o. Works internally with
+    @a number_buffer.
+
+    @param[in] x  integer number (signed or unsigned) to dump
+    @tparam NumberType either @a number_integer_t or @a number_unsigned_t
+    */
+    template < typename NumberType, detail::enable_if_t <
+                   std::is_integral<NumberType>::value ||
+                   std::is_same<NumberType, number_unsigned_t>::value ||
+                   std::is_same<NumberType, number_integer_t>::value ||
+                   std::is_same<NumberType, binary_char_t>::value,
+                   int > = 0 >
+    void dump_integer(NumberType x)
+    {
+        static constexpr std::array<std::array<char, 2>, 100> digits_to_99
+        {
+            {
+                {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
+                {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
+                {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
+                {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
+                {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
+                {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
+                {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
+                {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
+                {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
+                {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
+            }
+        };
+
+        // special case for "0"
+        if (x == 0)
+        {
+            o->write_character('0');
+            return;
+        }
+
+        // use a pointer to fill the buffer
+        auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+
+        number_unsigned_t abs_value;
+
+        unsigned int n_chars{};
+
+        if (is_negative_number(x))
+        {
+            *buffer_ptr = '-';
+            abs_value = remove_sign(static_cast<number_integer_t>(x));
+
+            // account one more byte for the minus sign
+            n_chars = 1 + count_digits(abs_value);
+        }
+        else
+        {
+            abs_value = static_cast<number_unsigned_t>(x);
+            n_chars = count_digits(abs_value);
+        }
+
+        // spare 1 byte for '\0'
+        JSON_ASSERT(n_chars < number_buffer.size() - 1);
+
+        // jump to the end to generate the string from backward,
+        // so we later avoid reversing the result
+        buffer_ptr += n_chars;
+
+        // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
+        // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
+        while (abs_value >= 100)
+        {
+            const auto digits_index = static_cast<unsigned>((abs_value % 100));
+            abs_value /= 100;
+            *(--buffer_ptr) = digits_to_99[digits_index][1];
+            *(--buffer_ptr) = digits_to_99[digits_index][0];
+        }
+
+        if (abs_value >= 10)
+        {
+            const auto digits_index = static_cast<unsigned>(abs_value);
+            *(--buffer_ptr) = digits_to_99[digits_index][1];
+            *(--buffer_ptr) = digits_to_99[digits_index][0];
+        }
+        else
+        {
+            *(--buffer_ptr) = static_cast<char>('0' + abs_value);
+        }
+
+        o->write_characters(number_buffer.data(), n_chars);
+    }
+
+    /*!
+    @brief dump a floating-point number
+
+    Dump a given floating-point number to output stream @a o. Works internally
+    with @a number_buffer.
+
+    @param[in] x  floating-point number to dump
+    */
+    void dump_float(number_float_t x)
+    {
+        // NaN / inf
+        if (!std::isfinite(x))
+        {
+            o->write_characters("null", 4);
+            return;
+        }
+
+        // If number_float_t is an IEEE-754 single or double precision number,
+        // use the Grisu2 algorithm to produce short numbers which are
+        // guaranteed to round-trip, using strtof and strtod, resp.
+        //
+        // NB: The test below works if <long double> == <double>.
+        static constexpr bool is_ieee_single_or_double
+            = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) ||
+              (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024);
+
+        dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
+    }
+
+    void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
+    {
+        auto* begin = number_buffer.data();
+        auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
+
+        o->write_characters(begin, static_cast<size_t>(end - begin));
+    }
+
+    void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
+    {
+        // get number of digits for a float -> text -> float round-trip
+        static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
+
+        // the actual conversion
+        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
+        std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
+
+        // negative value indicates an error
+        JSON_ASSERT(len > 0);
+        // check if buffer was large enough
+        JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
+
+        // erase thousands separator
+        if (thousands_sep != '\0')
+        {
+            // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081
+            const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);
+            std::fill(end, number_buffer.end(), '\0');
+            JSON_ASSERT((end - number_buffer.begin()) <= len);
+            len = (end - number_buffer.begin());
+        }
+
+        // convert decimal point to '.'
+        if (decimal_point != '\0' && decimal_point != '.')
+        {
+            // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081
+            const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
+            if (dec_pos != number_buffer.end())
+            {
+                *dec_pos = '.';
+            }
+        }
+
+        o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
+
+        // determine if we need to append ".0"
+        const bool value_is_int_like =
+            std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
+                         [](char c)
+        {
+            return c == '.' || c == 'e';
+        });
+
+        if (value_is_int_like)
+        {
+            o->write_characters(".0", 2);
+        }
+    }
+
+    /*!
+    @brief check whether a string is UTF-8 encoded
+
+    The function checks each byte of a string whether it is UTF-8 encoded. The
+    result of the check is stored in the @a state parameter. The function must
+    be called initially with state 0 (accept). State 1 means the string must
+    be rejected, because the current byte is not allowed. If the string is
+    completely processed, but the state is non-zero, the string ended
+    prematurely; that is, the last byte indicated more bytes should have
+    followed.
+
+    @param[in,out] state  the state of the decoding
+    @param[in,out] codep  codepoint (valid only if resulting state is UTF8_ACCEPT)
+    @param[in] byte       next byte to decode
+    @return               new state
+
+    @note The function has been edited: a std::array is used.
+
+    @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
+    @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
+    */
+    static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
+    {
+        static const std::array<std::uint8_t, 400> utf8d =
+        {
+            {
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
+                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
+                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
+                7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
+                8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
+                0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
+                0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
+                0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
+                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
+                1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
+                1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
+                1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
+            }
+        };
+
+        JSON_ASSERT(byte < utf8d.size());
+        const std::uint8_t type = utf8d[byte];
+
+        codep = (state != UTF8_ACCEPT)
+                ? (byte & 0x3fu) | (codep << 6u)
+                : (0xFFu >> type) & (byte);
+
+        std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
+        JSON_ASSERT(index < 400);
+        state = utf8d[index];
+        return state;
+    }
+
+    /*
+     * Overload to make the compiler happy while it is instantiating
+     * dump_integer for number_unsigned_t.
+     * Must never be called.
+     */
+    number_unsigned_t remove_sign(number_unsigned_t x)
+    {
+        JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        return x; // LCOV_EXCL_LINE
+    }
+
+    /*
+     * Helper function for dump_integer
+     *
+     * This function takes a negative signed integer and returns its absolute
+     * value as unsigned integer. The plus/minus shuffling is necessary as we can
+     * not directly remove the sign of an arbitrary signed integer as the
+     * absolute values of INT_MIN and INT_MAX are usually not the same. See
+     * #1708 for details.
+     */
+    inline number_unsigned_t remove_sign(number_integer_t x) noexcept
+    {
+        JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)()); // NOLINT(misc-redundant-expression)
+        return static_cast<number_unsigned_t>(-(x + 1)) + 1;
+    }
+
+  private:
+    /// the output of the serializer
+    output_adapter_t<char> o = nullptr;
+
+    /// a (hopefully) large enough character buffer
+    std::array<char, 64> number_buffer{{}};
+
+    /// the locale
+    const std::lconv* loc = nullptr;
+    /// the locale's thousand separator character
+    const char thousands_sep = '\0';
+    /// the locale's decimal point character
+    const char decimal_point = '\0';
+
+    /// string buffer
+    std::array<char, 512> string_buffer{{}};
+
+    /// the indentation character
+    const char indent_char;
+    /// the indentation string
+    string_t indent_string;
+
+    /// error_handler how to react on decoding errors
+    const error_handler_t error_handler;
+};
+}  // namespace detail
+}  // namespace nlohmann
+
+// #include <nlohmann/detail/value_t.hpp>
+
+// #include <nlohmann/json_fwd.hpp>
+
+// #include <nlohmann/ordered_map.hpp>
+
+
+#include <functional> // less
+#include <initializer_list> // initializer_list
+#include <iterator> // input_iterator_tag, iterator_traits
+#include <memory> // allocator
+#include <stdexcept> // for out_of_range
+#include <type_traits> // enable_if, is_convertible
+#include <utility> // pair
+#include <vector> // vector
+
+// #include <nlohmann/detail/macro_scope.hpp>
+
+
+namespace nlohmann
+{
+
+/// ordered_map: a minimal map-like container that preserves insertion order
+/// for use within nlohmann::basic_json<ordered_map>
+template <class Key, class T, class IgnoredLess = std::less<Key>,
+          class Allocator = std::allocator<std::pair<const Key, T>>>
+                  struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
+{
+    using key_type = Key;
+    using mapped_type = T;
+    using Container = std::vector<std::pair<const Key, T>, Allocator>;
+    using iterator = typename Container::iterator;
+    using const_iterator = typename Container::const_iterator;
+    using size_type = typename Container::size_type;
+    using value_type = typename Container::value_type;
+
+    // Explicit constructors instead of `using Container::Container`
+    // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
+    ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
+    template <class It>
+    ordered_map(It first, It last, const Allocator& alloc = Allocator())
+        : Container{first, last, alloc} {}
+    ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
+        : Container{init, alloc} {}
+
+    std::pair<iterator, bool> emplace(const key_type& key, T&& t)
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return {it, false};
+            }
+        }
+        Container::emplace_back(key, t);
+        return {--this->end(), true};
+    }
+
+    T& operator[](const Key& key)
+    {
+        return emplace(key, T{}).first->second;
+    }
+
+    const T& operator[](const Key& key) const
+    {
+        return at(key);
+    }
+
+    T& at(const Key& key)
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return it->second;
+            }
+        }
+
+        JSON_THROW(std::out_of_range("key not found"));
+    }
+
+    const T& at(const Key& key) const
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return it->second;
+            }
+        }
+
+        JSON_THROW(std::out_of_range("key not found"));
+    }
+
+    size_type erase(const Key& key)
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                // Since we cannot move const Keys, re-construct them in place
+                for (auto next = it; ++next != this->end(); ++it)
+                {
+                    it->~value_type(); // Destroy but keep allocation
+                    new (&*it) value_type{std::move(*next)};
+                }
+                Container::pop_back();
+                return 1;
+            }
+        }
+        return 0;
+    }
+
+    iterator erase(iterator pos)
+    {
+        return erase(pos, std::next(pos));
+    }
+
+    iterator erase(iterator first, iterator last)
+    {
+        const auto elements_affected = std::distance(first, last);
+        const auto offset = std::distance(Container::begin(), first);
+
+        // This is the start situation. We need to delete elements_affected
+        // elements (3 in this example: e, f, g), and need to return an
+        // iterator past the last deleted element (h in this example).
+        // Note that offset is the distance from the start of the vector
+        // to first. We will need this later.
+
+        // [ a, b, c, d, e, f, g, h, i, j ]
+        //               ^        ^
+        //             first    last
+
+        // Since we cannot move const Keys, we re-construct them in place.
+        // We start at first and re-construct (viz. copy) the elements from
+        // the back of the vector. Example for first iteration:
+
+        //               ,--------.
+        //               v        |   destroy e and re-construct with h
+        // [ a, b, c, d, e, f, g, h, i, j ]
+        //               ^        ^
+        //               it       it + elements_affected
+
+        for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it)
+        {
+            it->~value_type(); // destroy but keep allocation
+            new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it
+        }
+
+        // [ a, b, c, d, h, i, j, h, i, j ]
+        //               ^        ^
+        //             first    last
+
+        // remove the unneeded elements at the end of the vector
+        Container::resize(this->size() - static_cast<size_type>(elements_affected));
+
+        // [ a, b, c, d, h, i, j ]
+        //               ^        ^
+        //             first    last
+
+        // first is now pointing past the last deleted element, but we cannot
+        // use this iterator, because it may have been invalidated by the
+        // resize call. Instead, we can return begin() + offset.
+        return Container::begin() + offset;
+    }
+
+    size_type count(const Key& key) const
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return 1;
+            }
+        }
+        return 0;
+    }
+
+    iterator find(const Key& key)
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return it;
+            }
+        }
+        return Container::end();
+    }
+
+    const_iterator find(const Key& key) const
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == key)
+            {
+                return it;
+            }
+        }
+        return Container::end();
+    }
+
+    std::pair<iterator, bool> insert( value_type&& value )
+    {
+        return emplace(value.first, std::move(value.second));
+    }
+
+    std::pair<iterator, bool> insert( const value_type& value )
+    {
+        for (auto it = this->begin(); it != this->end(); ++it)
+        {
+            if (it->first == value.first)
+            {
+                return {it, false};
+            }
+        }
+        Container::push_back(value);
+        return {--this->end(), true};
+    }
+
+    template<typename InputIt>
+    using require_input_iter = typename std::enable_if<std::is_convertible<typename std::iterator_traits<InputIt>::iterator_category,
+            std::input_iterator_tag>::value>::type;
+
+    template<typename InputIt, typename = require_input_iter<InputIt>>
+    void insert(InputIt first, InputIt last)
+    {
+        for (auto it = first; it != last; ++it)
+        {
+            insert(*it);
+        }
+    }
+};
+
+}  // namespace nlohmann
+
+
+#if defined(JSON_HAS_CPP_17)
+    #include <string_view>
+#endif
+
+/*!
+@brief namespace for Niels Lohmann
+@see https://github.com/nlohmann
+@since version 1.0.0
+*/
+namespace nlohmann
+{
+
+/*!
+@brief a class to store JSON values
+
+@internal
+@invariant The member variables @a m_value and @a m_type have the following
+relationship:
+- If `m_type == value_t::object`, then `m_value.object != nullptr`.
+- If `m_type == value_t::array`, then `m_value.array != nullptr`.
+- If `m_type == value_t::string`, then `m_value.string != nullptr`.
+The invariants are checked by member function assert_invariant().
+
+@note ObjectType trick from https://stackoverflow.com/a/9860911
+@endinternal
+
+@since version 1.0.0
+
+@nosubgrouping
+*/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
+{
+  private:
+    template<detail::value_t> friend struct detail::external_constructor;
+    friend ::nlohmann::json_pointer<basic_json>;
+
+    template<typename BasicJsonType, typename InputType>
+    friend class ::nlohmann::detail::parser;
+    friend ::nlohmann::detail::serializer<basic_json>;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::iter_impl;
+    template<typename BasicJsonType, typename CharType>
+    friend class ::nlohmann::detail::binary_writer;
+    template<typename BasicJsonType, typename InputType, typename SAX>
+    friend class ::nlohmann::detail::binary_reader;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::json_sax_dom_parser;
+    template<typename BasicJsonType>
+    friend class ::nlohmann::detail::json_sax_dom_callback_parser;
+    friend class ::nlohmann::detail::exception;
+
+    /// workaround type for MSVC
+    using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    // convenience aliases for types residing in namespace detail;
+    using lexer = ::nlohmann::detail::lexer_base<basic_json>;
+
+    template<typename InputAdapterType>
+    static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
+        InputAdapterType adapter,
+        detail::parser_callback_t<basic_json>cb = nullptr,
+        const bool allow_exceptions = true,
+        const bool ignore_comments = false
+                                 )
+    {
+        return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
+                std::move(cb), allow_exceptions, ignore_comments);
+    }
+
+  private:
+    using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
+    template<typename BasicJsonType>
+    using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
+    template<typename BasicJsonType>
+    using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
+    template<typename Iterator>
+    using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
+    template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
+
+    template<typename CharType>
+    using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
+
+    template<typename InputType>
+    using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
+    template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    using serializer = ::nlohmann::detail::serializer<basic_json>;
+
+  public:
+    using value_t = detail::value_t;
+    /// JSON Pointer, see @ref nlohmann::json_pointer
+    using json_pointer = ::nlohmann::json_pointer<basic_json>;
+    template<typename T, typename SFINAE>
+    using json_serializer = JSONSerializer<T, SFINAE>;
+    /// how to treat decoding errors
+    using error_handler_t = detail::error_handler_t;
+    /// how to treat CBOR tags
+    using cbor_tag_handler_t = detail::cbor_tag_handler_t;
+    /// helper type for initializer lists of basic_json values
+    using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
+
+    using input_format_t = detail::input_format_t;
+    /// SAX interface type, see @ref nlohmann::json_sax
+    using json_sax_t = json_sax<basic_json>;
+
+    ////////////////
+    // exceptions //
+    ////////////////
+
+    /// @name exceptions
+    /// Classes to implement user-defined exceptions.
+    /// @{
+
+    using exception = detail::exception;
+    using parse_error = detail::parse_error;
+    using invalid_iterator = detail::invalid_iterator;
+    using type_error = detail::type_error;
+    using out_of_range = detail::out_of_range;
+    using other_error = detail::other_error;
+
+    /// @}
+
+
+    /////////////////////
+    // container types //
+    /////////////////////
+
+    /// @name container types
+    /// The canonic container types to use @ref basic_json like any other STL
+    /// container.
+    /// @{
+
+    /// the type of elements in a basic_json container
+    using value_type = basic_json;
+
+    /// the type of an element reference
+    using reference = value_type&;
+    /// the type of an element const reference
+    using const_reference = const value_type&;
+
+    /// a type to represent differences between iterators
+    using difference_type = std::ptrdiff_t;
+    /// a type to represent container sizes
+    using size_type = std::size_t;
+
+    /// the allocator type
+    using allocator_type = AllocatorType<basic_json>;
+
+    /// the type of an element pointer
+    using pointer = typename std::allocator_traits<allocator_type>::pointer;
+    /// the type of an element const pointer
+    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
+
+    /// an iterator for a basic_json container
+    using iterator = iter_impl<basic_json>;
+    /// a const iterator for a basic_json container
+    using const_iterator = iter_impl<const basic_json>;
+    /// a reverse iterator for a basic_json container
+    using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
+    /// a const reverse iterator for a basic_json container
+    using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
+
+    /// @}
+
+
+    /// @brief returns the allocator associated with the container
+    /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/
+    static allocator_type get_allocator()
+    {
+        return allocator_type();
+    }
+
+    /// @brief returns version information on the library
+    /// @sa https://json.nlohmann.me/api/basic_json/meta/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json meta()
+    {
+        basic_json result;
+
+        result["copyright"] = "(C) 2013-2022 Niels Lohmann";
+        result["name"] = "JSON for Modern C++";
+        result["url"] = "https://github.com/nlohmann/json";
+        result["version"]["string"] =
+            std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
+            std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
+            std::to_string(NLOHMANN_JSON_VERSION_PATCH);
+        result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
+        result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
+        result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
+
+#ifdef _WIN32
+        result["platform"] = "win32";
+#elif defined __linux__
+        result["platform"] = "linux";
+#elif defined __APPLE__
+        result["platform"] = "apple";
+#elif defined __unix__
+        result["platform"] = "unix";
+#else
+        result["platform"] = "unknown";
+#endif
+
+#if defined(__ICC) || defined(__INTEL_COMPILER)
+        result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
+#elif defined(__clang__)
+        result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
+#elif defined(__GNUC__) || defined(__GNUG__)
+        result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
+#elif defined(__HP_cc) || defined(__HP_aCC)
+        result["compiler"] = "hp"
+#elif defined(__IBMCPP__)
+        result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
+#elif defined(_MSC_VER)
+        result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
+#elif defined(__PGI)
+        result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
+#elif defined(__SUNPRO_CC)
+        result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
+#else
+        result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
+#endif
+
+#ifdef __cplusplus
+        result["compiler"]["c++"] = std::to_string(__cplusplus);
+#else
+        result["compiler"]["c++"] = "unknown";
+#endif
+        return result;
+    }
+
+
+    ///////////////////////////
+    // JSON value data types //
+    ///////////////////////////
+
+    /// @name JSON value data types
+    /// The data types to store a JSON value. These types are derived from
+    /// the template arguments passed to class @ref basic_json.
+    /// @{
+
+    /// @brief object key comparator type
+    /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/
+#if defined(JSON_HAS_CPP_14)
+    // Use transparent comparator if possible, combined with perfect forwarding
+    // on find() and count() calls prevents unnecessary string construction.
+    using object_comparator_t = std::less<>;
+#else
+    using object_comparator_t = std::less<StringType>;
+#endif
+
+    /// @brief a type for an object
+    /// @sa https://json.nlohmann.me/api/basic_json/object_t/
+    using object_t = ObjectType<StringType,
+          basic_json,
+          object_comparator_t,
+          AllocatorType<std::pair<const StringType,
+          basic_json>>>;
+
+    /// @brief a type for an array
+    /// @sa https://json.nlohmann.me/api/basic_json/array_t/
+    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
+
+    /// @brief a type for a string
+    /// @sa https://json.nlohmann.me/api/basic_json/string_t/
+    using string_t = StringType;
+
+    /// @brief a type for a boolean
+    /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/
+    using boolean_t = BooleanType;
+
+    /// @brief a type for a number (integer)
+    /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/
+    using number_integer_t = NumberIntegerType;
+
+    /// @brief a type for a number (unsigned)
+    /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/
+    using number_unsigned_t = NumberUnsignedType;
+
+    /// @brief a type for a number (floating-point)
+    /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/
+    using number_float_t = NumberFloatType;
+
+    /// @brief a type for a packed binary type
+    /// @sa https://json.nlohmann.me/api/basic_json/binary_t/
+    using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
+
+    /// @}
+
+  private:
+
+    /// helper for exception-safe object creation
+    template<typename T, typename... Args>
+    JSON_HEDLEY_RETURNS_NON_NULL
+    static T* create(Args&& ... args)
+    {
+        AllocatorType<T> alloc;
+        using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
+
+        auto deleter = [&](T * obj)
+        {
+            AllocatorTraits::deallocate(alloc, obj, 1);
+        };
+        std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
+        AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
+        JSON_ASSERT(obj != nullptr);
+        return obj.release();
+    }
+
+    ////////////////////////
+    // JSON value storage //
+    ////////////////////////
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    /*!
+    @brief a JSON value
+
+    The actual storage for a JSON value of the @ref basic_json class. This
+    union combines the different storage types for the JSON value types
+    defined in @ref value_t.
+
+    JSON type | value_t type    | used type
+    --------- | --------------- | ------------------------
+    object    | object          | pointer to @ref object_t
+    array     | array           | pointer to @ref array_t
+    string    | string          | pointer to @ref string_t
+    boolean   | boolean         | @ref boolean_t
+    number    | number_integer  | @ref number_integer_t
+    number    | number_unsigned | @ref number_unsigned_t
+    number    | number_float    | @ref number_float_t
+    binary    | binary          | pointer to @ref binary_t
+    null      | null            | *no value is stored*
+
+    @note Variable-length types (objects, arrays, and strings) are stored as
+    pointers. The size of the union should not exceed 64 bits if the default
+    value types are used.
+
+    @since version 1.0.0
+    */
+    union json_value
+    {
+        /// object (stored with pointer to save storage)
+        object_t* object;
+        /// array (stored with pointer to save storage)
+        array_t* array;
+        /// string (stored with pointer to save storage)
+        string_t* string;
+        /// binary (stored with pointer to save storage)
+        binary_t* binary;
+        /// boolean
+        boolean_t boolean;
+        /// number (integer)
+        number_integer_t number_integer;
+        /// number (unsigned integer)
+        number_unsigned_t number_unsigned;
+        /// number (floating-point)
+        number_float_t number_float;
+
+        /// default constructor (for null values)
+        json_value() = default;
+        /// constructor for booleans
+        json_value(boolean_t v) noexcept : boolean(v) {}
+        /// constructor for numbers (integer)
+        json_value(number_integer_t v) noexcept : number_integer(v) {}
+        /// constructor for numbers (unsigned)
+        json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
+        /// constructor for numbers (floating-point)
+        json_value(number_float_t v) noexcept : number_float(v) {}
+        /// constructor for empty values of a given type
+        json_value(value_t t)
+        {
+            switch (t)
+            {
+                case value_t::object:
+                {
+                    object = create<object_t>();
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    array = create<array_t>();
+                    break;
+                }
+
+                case value_t::string:
+                {
+                    string = create<string_t>("");
+                    break;
+                }
+
+                case value_t::binary:
+                {
+                    binary = create<binary_t>();
+                    break;
+                }
+
+                case value_t::boolean:
+                {
+                    boolean = static_cast<boolean_t>(false);
+                    break;
+                }
+
+                case value_t::number_integer:
+                {
+                    number_integer = static_cast<number_integer_t>(0);
+                    break;
+                }
+
+                case value_t::number_unsigned:
+                {
+                    number_unsigned = static_cast<number_unsigned_t>(0);
+                    break;
+                }
+
+                case value_t::number_float:
+                {
+                    number_float = static_cast<number_float_t>(0.0);
+                    break;
+                }
+
+                case value_t::null:
+                {
+                    object = nullptr;  // silence warning, see #821
+                    break;
+                }
+
+                case value_t::discarded:
+                default:
+                {
+                    object = nullptr;  // silence warning, see #821
+                    if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
+                    {
+                        JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE
+                    }
+                    break;
+                }
+            }
+        }
+
+        /// constructor for strings
+        json_value(const string_t& value) : string(create<string_t>(value)) {}
+
+        /// constructor for rvalue strings
+        json_value(string_t&& value) : string(create<string_t>(std::move(value))) {}
+
+        /// constructor for objects
+        json_value(const object_t& value) : object(create<object_t>(value)) {}
+
+        /// constructor for rvalue objects
+        json_value(object_t&& value) : object(create<object_t>(std::move(value))) {}
+
+        /// constructor for arrays
+        json_value(const array_t& value) : array(create<array_t>(value)) {}
+
+        /// constructor for rvalue arrays
+        json_value(array_t&& value) : array(create<array_t>(std::move(value))) {}
+
+        /// constructor for binary arrays
+        json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {}
+
+        /// constructor for rvalue binary arrays
+        json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {}
+
+        /// constructor for binary arrays (internal type)
+        json_value(const binary_t& value) : binary(create<binary_t>(value)) {}
+
+        /// constructor for rvalue binary arrays (internal type)
+        json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {}
+
+        void destroy(value_t t)
+        {
+            if (t == value_t::array || t == value_t::object)
+            {
+                // flatten the current json_value to a heap-allocated stack
+                std::vector<basic_json> stack;
+
+                // move the top-level items to stack
+                if (t == value_t::array)
+                {
+                    stack.reserve(array->size());
+                    std::move(array->begin(), array->end(), std::back_inserter(stack));
+                }
+                else
+                {
+                    stack.reserve(object->size());
+                    for (auto&& it : *object)
+                    {
+                        stack.push_back(std::move(it.second));
+                    }
+                }
+
+                while (!stack.empty())
+                {
+                    // move the last item to local variable to be processed
+                    basic_json current_item(std::move(stack.back()));
+                    stack.pop_back();
+
+                    // if current_item is array/object, move
+                    // its children to the stack to be processed later
+                    if (current_item.is_array())
+                    {
+                        std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack));
+
+                        current_item.m_value.array->clear();
+                    }
+                    else if (current_item.is_object())
+                    {
+                        for (auto&& it : *current_item.m_value.object)
+                        {
+                            stack.push_back(std::move(it.second));
+                        }
+
+                        current_item.m_value.object->clear();
+                    }
+
+                    // it's now safe that current_item get destructed
+                    // since it doesn't have any children
+                }
+            }
+
+            switch (t)
+            {
+                case value_t::object:
+                {
+                    AllocatorType<object_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    AllocatorType<array_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
+                    break;
+                }
+
+                case value_t::string:
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
+                    break;
+                }
+
+                case value_t::binary:
+                {
+                    AllocatorType<binary_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
+                    break;
+                }
+
+                case value_t::null:
+                case value_t::boolean:
+                case value_t::number_integer:
+                case value_t::number_unsigned:
+                case value_t::number_float:
+                case value_t::discarded:
+                default:
+                {
+                    break;
+                }
+            }
+        }
+    };
+
+  private:
+    /*!
+    @brief checks the class invariants
+
+    This function asserts the class invariants. It needs to be called at the
+    end of every constructor to make sure that created objects respect the
+    invariant. Furthermore, it has to be called each time the type of a JSON
+    value is changed, because the invariant expresses a relationship between
+    @a m_type and @a m_value.
+
+    Furthermore, the parent relation is checked for arrays and objects: If
+    @a check_parents true and the value is an array or object, then the
+    container's elements must have the current value as parent.
+
+    @param[in] check_parents  whether the parent relation should be checked.
+               The value is true by default and should only be set to false
+               during destruction of objects when the invariant does not
+               need to hold.
+    */
+    void assert_invariant(bool check_parents = true) const noexcept
+    {
+        JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
+        JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
+        JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
+        JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
+
+#if JSON_DIAGNOSTICS
+        JSON_TRY
+        {
+            // cppcheck-suppress assertWithSideEffect
+            JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
+            {
+                return j.m_parent == this;
+            }));
+        }
+        JSON_CATCH(...) {} // LCOV_EXCL_LINE
+#endif
+        static_cast<void>(check_parents);
+    }
+
+    void set_parents()
+    {
+#if JSON_DIAGNOSTICS
+        switch (m_type)
+        {
+            case value_t::array:
+            {
+                for (auto& element : *m_value.array)
+                {
+                    element.m_parent = this;
+                }
+                break;
+            }
+
+            case value_t::object:
+            {
+                for (auto& element : *m_value.object)
+                {
+                    element.second.m_parent = this;
+                }
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                break;
+        }
+#endif
+    }
+
+    iterator set_parents(iterator it, typename iterator::difference_type count_set_parents)
+    {
+#if JSON_DIAGNOSTICS
+        for (typename iterator::difference_type i = 0; i < count_set_parents; ++i)
+        {
+            (it + i)->m_parent = this;
+        }
+#else
+        static_cast<void>(count_set_parents);
+#endif
+        return it;
+    }
+
+    reference set_parent(reference j, std::size_t old_capacity = static_cast<std::size_t>(-1))
+    {
+#if JSON_DIAGNOSTICS
+        if (old_capacity != static_cast<std::size_t>(-1))
+        {
+            // see https://github.com/nlohmann/json/issues/2838
+            JSON_ASSERT(type() == value_t::array);
+            if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
+            {
+                // capacity has changed: update all parents
+                set_parents();
+                return j;
+            }
+        }
+
+        // ordered_json uses a vector internally, so pointers could have
+        // been invalidated; see https://github.com/nlohmann/json/issues/2962
+#ifdef JSON_HEDLEY_MSVC_VERSION
+#pragma warning(push )
+#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
+#endif
+        if (detail::is_ordered_map<object_t>::value)
+        {
+            set_parents();
+            return j;
+        }
+#ifdef JSON_HEDLEY_MSVC_VERSION
+#pragma warning( pop )
+#endif
+
+        j.m_parent = this;
+#else
+        static_cast<void>(j);
+        static_cast<void>(old_capacity);
+#endif
+        return j;
+    }
+
+  public:
+    //////////////////////////
+    // JSON parser callback //
+    //////////////////////////
+
+    /// @brief parser event types
+    /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/
+    using parse_event_t = detail::parse_event_t;
+
+    /// @brief per-element parser callback type
+    /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/
+    using parser_callback_t = detail::parser_callback_t<basic_json>;
+
+    //////////////////
+    // constructors //
+    //////////////////
+
+    /// @name constructors and destructors
+    /// Constructors of class @ref basic_json, copy/move constructor, copy
+    /// assignment, static functions creating objects, and the destructor.
+    /// @{
+
+    /// @brief create an empty value with a given type
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(const value_t v)
+        : m_type(v), m_value(v)
+    {
+        assert_invariant();
+    }
+
+    /// @brief create a null object
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(std::nullptr_t = nullptr) noexcept
+        : basic_json(value_t::null)
+    {
+        assert_invariant();
+    }
+
+    /// @brief create a JSON value from compatible types
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    template < typename CompatibleType,
+               typename U = detail::uncvref_t<CompatibleType>,
+               detail::enable_if_t <
+                   !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
+    basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
+                JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
+                                           std::forward<CompatibleType>(val))))
+    {
+        JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief create a JSON value from an existing one
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    template < typename BasicJsonType,
+               detail::enable_if_t <
+                   detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
+    basic_json(const BasicJsonType& val)
+    {
+        using other_boolean_t = typename BasicJsonType::boolean_t;
+        using other_number_float_t = typename BasicJsonType::number_float_t;
+        using other_number_integer_t = typename BasicJsonType::number_integer_t;
+        using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
+        using other_string_t = typename BasicJsonType::string_t;
+        using other_object_t = typename BasicJsonType::object_t;
+        using other_array_t = typename BasicJsonType::array_t;
+        using other_binary_t = typename BasicJsonType::binary_t;
+
+        switch (val.type())
+        {
+            case value_t::boolean:
+                JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
+                break;
+            case value_t::number_float:
+                JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
+                break;
+            case value_t::number_integer:
+                JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
+                break;
+            case value_t::number_unsigned:
+                JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
+                break;
+            case value_t::string:
+                JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
+                break;
+            case value_t::object:
+                JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
+                break;
+            case value_t::array:
+                JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
+                break;
+            case value_t::binary:
+                JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
+                break;
+            case value_t::null:
+                *this = nullptr;
+                break;
+            case value_t::discarded:
+                m_type = value_t::discarded;
+                break;
+            default:            // LCOV_EXCL_LINE
+                JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+        }
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief create a container (array or object) from an initializer list
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(initializer_list_t init,
+               bool type_deduction = true,
+               value_t manual_type = value_t::array)
+    {
+        // check if each element is an array with two elements whose first
+        // element is a string
+        bool is_an_object = std::all_of(init.begin(), init.end(),
+                                        [](const detail::json_ref<basic_json>& element_ref)
+        {
+            return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
+        });
+
+        // adjust type if type deduction is not wanted
+        if (!type_deduction)
+        {
+            // if array is wanted, do not create an object though possible
+            if (manual_type == value_t::array)
+            {
+                is_an_object = false;
+            }
+
+            // if object is wanted but impossible, throw an exception
+            if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
+            {
+                JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json()));
+            }
+        }
+
+        if (is_an_object)
+        {
+            // the initializer list is a list of pairs -> create object
+            m_type = value_t::object;
+            m_value = value_t::object;
+
+            for (auto& element_ref : init)
+            {
+                auto element = element_ref.moved_or_copied();
+                m_value.object->emplace(
+                    std::move(*((*element.m_value.array)[0].m_value.string)),
+                    std::move((*element.m_value.array)[1]));
+            }
+        }
+        else
+        {
+            // the initializer list describes an array -> create array
+            m_type = value_t::array;
+            m_value.array = create<array_t>(init.begin(), init.end());
+        }
+
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief explicitly create a binary array (without subtype)
+    /// @sa https://json.nlohmann.me/api/basic_json/binary/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json binary(const typename binary_t::container_type& init)
+    {
+        auto res = basic_json();
+        res.m_type = value_t::binary;
+        res.m_value = init;
+        return res;
+    }
+
+    /// @brief explicitly create a binary array (with subtype)
+    /// @sa https://json.nlohmann.me/api/basic_json/binary/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
+    {
+        auto res = basic_json();
+        res.m_type = value_t::binary;
+        res.m_value = binary_t(init, subtype);
+        return res;
+    }
+
+    /// @brief explicitly create a binary array
+    /// @sa https://json.nlohmann.me/api/basic_json/binary/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json binary(typename binary_t::container_type&& init)
+    {
+        auto res = basic_json();
+        res.m_type = value_t::binary;
+        res.m_value = std::move(init);
+        return res;
+    }
+
+    /// @brief explicitly create a binary array (with subtype)
+    /// @sa https://json.nlohmann.me/api/basic_json/binary/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
+    {
+        auto res = basic_json();
+        res.m_type = value_t::binary;
+        res.m_value = binary_t(std::move(init), subtype);
+        return res;
+    }
+
+    /// @brief explicitly create an array from an initializer list
+    /// @sa https://json.nlohmann.me/api/basic_json/array/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json array(initializer_list_t init = {})
+    {
+        return basic_json(init, false, value_t::array);
+    }
+
+    /// @brief explicitly create an object from an initializer list
+    /// @sa https://json.nlohmann.me/api/basic_json/object/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json object(initializer_list_t init = {})
+    {
+        return basic_json(init, false, value_t::object);
+    }
+
+    /// @brief construct an array with count copies of given value
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(size_type cnt, const basic_json& val)
+        : m_type(value_t::array)
+    {
+        m_value.array = create<array_t>(cnt, val);
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief construct a JSON container given an iterator range
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    template < class InputIT, typename std::enable_if <
+                   std::is_same<InputIT, typename basic_json_t::iterator>::value ||
+                   std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
+    basic_json(InputIT first, InputIT last)
+    {
+        JSON_ASSERT(first.m_object != nullptr);
+        JSON_ASSERT(last.m_object != nullptr);
+
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json()));
+        }
+
+        // copy type from first iterator
+        m_type = first.m_object->m_type;
+
+        // check if iterator range is complete for primitive values
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            {
+                if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
+                                         || !last.m_it.primitive_iterator.is_end()))
+                {
+                    JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object));
+                }
+                break;
+            }
+
+            case value_t::null:
+            case value_t::object:
+            case value_t::array:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+                break;
+        }
+
+        switch (m_type)
+        {
+            case value_t::number_integer:
+            {
+                m_value.number_integer = first.m_object->m_value.number_integer;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value.number_unsigned = first.m_object->m_value.number_unsigned;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value.number_float = first.m_object->m_value.number_float;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value.boolean = first.m_object->m_value.boolean;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value = *first.m_object->m_value.string;
+                break;
+            }
+
+            case value_t::object:
+            {
+                m_value.object = create<object_t>(first.m_it.object_iterator,
+                                                  last.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value.array = create<array_t>(first.m_it.array_iterator,
+                                                last.m_it.array_iterator);
+                break;
+            }
+
+            case value_t::binary:
+            {
+                m_value = *first.m_object->m_value.binary;
+                break;
+            }
+
+            case value_t::null:
+            case value_t::discarded:
+            default:
+                JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object));
+        }
+
+        set_parents();
+        assert_invariant();
+    }
+
+
+    ///////////////////////////////////////
+    // other constructors and destructor //
+    ///////////////////////////////////////
+
+    template<typename JsonRef,
+             detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
+                                 std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
+    basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
+
+    /// @brief copy constructor
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(const basic_json& other)
+        : m_type(other.m_type)
+    {
+        // check of passed value is valid
+        other.assert_invariant();
+
+        switch (m_type)
+        {
+            case value_t::object:
+            {
+                m_value = *other.m_value.object;
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value = *other.m_value.array;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value = *other.m_value.string;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value = other.m_value.boolean;
+                break;
+            }
+
+            case value_t::number_integer:
+            {
+                m_value = other.m_value.number_integer;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value = other.m_value.number_unsigned;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value = other.m_value.number_float;
+                break;
+            }
+
+            case value_t::binary:
+            {
+                m_value = *other.m_value.binary;
+                break;
+            }
+
+            case value_t::null:
+            case value_t::discarded:
+            default:
+                break;
+        }
+
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief move constructor
+    /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
+    basic_json(basic_json&& other) noexcept
+        : m_type(std::move(other.m_type)),
+          m_value(std::move(other.m_value))
+    {
+        // check that passed value is valid
+        other.assert_invariant(false);
+
+        // invalidate payload
+        other.m_type = value_t::null;
+        other.m_value = {};
+
+        set_parents();
+        assert_invariant();
+    }
+
+    /// @brief copy assignment
+    /// @sa https://json.nlohmann.me/api/basic_json/operator=/
+    basic_json& operator=(basic_json other) noexcept (
+        std::is_nothrow_move_constructible<value_t>::value&&
+        std::is_nothrow_move_assignable<value_t>::value&&
+        std::is_nothrow_move_constructible<json_value>::value&&
+        std::is_nothrow_move_assignable<json_value>::value
+    )
+    {
+        // check that passed value is valid
+        other.assert_invariant();
+
+        using std::swap;
+        swap(m_type, other.m_type);
+        swap(m_value, other.m_value);
+
+        set_parents();
+        assert_invariant();
+        return *this;
+    }
+
+    /// @brief destructor
+    /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/
+    ~basic_json() noexcept
+    {
+        assert_invariant(false);
+        m_value.destroy(m_type);
+    }
+
+    /// @}
+
+  public:
+    ///////////////////////
+    // object inspection //
+    ///////////////////////
+
+    /// @name object inspection
+    /// Functions to inspect the type of a JSON value.
+    /// @{
+
+    /// @brief serialization
+    /// @sa https://json.nlohmann.me/api/basic_json/dump/
+    string_t dump(const int indent = -1,
+                  const char indent_char = ' ',
+                  const bool ensure_ascii = false,
+                  const error_handler_t error_handler = error_handler_t::strict) const
+    {
+        string_t result;
+        serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
+
+        if (indent >= 0)
+        {
+            s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
+        }
+        else
+        {
+            s.dump(*this, false, ensure_ascii, 0);
+        }
+
+        return result;
+    }
+
+    /// @brief return the type of the JSON value (explicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/type/
+    constexpr value_t type() const noexcept
+    {
+        return m_type;
+    }
+
+    /// @brief return whether type is primitive
+    /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/
+    constexpr bool is_primitive() const noexcept
+    {
+        return is_null() || is_string() || is_boolean() || is_number() || is_binary();
+    }
+
+    /// @brief return whether type is structured
+    /// @sa https://json.nlohmann.me/api/basic_json/is_structured/
+    constexpr bool is_structured() const noexcept
+    {
+        return is_array() || is_object();
+    }
+
+    /// @brief return whether value is null
+    /// @sa https://json.nlohmann.me/api/basic_json/is_null/
+    constexpr bool is_null() const noexcept
+    {
+        return m_type == value_t::null;
+    }
+
+    /// @brief return whether value is a boolean
+    /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/
+    constexpr bool is_boolean() const noexcept
+    {
+        return m_type == value_t::boolean;
+    }
+
+    /// @brief return whether value is a number
+    /// @sa https://json.nlohmann.me/api/basic_json/is_number/
+    constexpr bool is_number() const noexcept
+    {
+        return is_number_integer() || is_number_float();
+    }
+
+    /// @brief return whether value is an integer number
+    /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/
+    constexpr bool is_number_integer() const noexcept
+    {
+        return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
+    }
+
+    /// @brief return whether value is an unsigned integer number
+    /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/
+    constexpr bool is_number_unsigned() const noexcept
+    {
+        return m_type == value_t::number_unsigned;
+    }
+
+    /// @brief return whether value is a floating-point number
+    /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/
+    constexpr bool is_number_float() const noexcept
+    {
+        return m_type == value_t::number_float;
+    }
+
+    /// @brief return whether value is an object
+    /// @sa https://json.nlohmann.me/api/basic_json/is_object/
+    constexpr bool is_object() const noexcept
+    {
+        return m_type == value_t::object;
+    }
+
+    /// @brief return whether value is an array
+    /// @sa https://json.nlohmann.me/api/basic_json/is_array/
+    constexpr bool is_array() const noexcept
+    {
+        return m_type == value_t::array;
+    }
+
+    /// @brief return whether value is a string
+    /// @sa https://json.nlohmann.me/api/basic_json/is_string/
+    constexpr bool is_string() const noexcept
+    {
+        return m_type == value_t::string;
+    }
+
+    /// @brief return whether value is a binary array
+    /// @sa https://json.nlohmann.me/api/basic_json/is_binary/
+    constexpr bool is_binary() const noexcept
+    {
+        return m_type == value_t::binary;
+    }
+
+    /// @brief return whether value is discarded
+    /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/
+    constexpr bool is_discarded() const noexcept
+    {
+        return m_type == value_t::discarded;
+    }
+
+    /// @brief return the type of the JSON value (implicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/
+    constexpr operator value_t() const noexcept
+    {
+        return m_type;
+    }
+
+    /// @}
+
+  private:
+    //////////////////
+    // value access //
+    //////////////////
+
+    /// get a boolean (explicit)
+    boolean_t get_impl(boolean_t* /*unused*/) const
+    {
+        if (JSON_HEDLEY_LIKELY(is_boolean()))
+        {
+            return m_value.boolean;
+        }
+
+        JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this));
+    }
+
+    /// get a pointer to the value (object)
+    object_t* get_impl_ptr(object_t* /*unused*/) noexcept
+    {
+        return is_object() ? m_value.object : nullptr;
+    }
+
+    /// get a pointer to the value (object)
+    constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
+    {
+        return is_object() ? m_value.object : nullptr;
+    }
+
+    /// get a pointer to the value (array)
+    array_t* get_impl_ptr(array_t* /*unused*/) noexcept
+    {
+        return is_array() ? m_value.array : nullptr;
+    }
+
+    /// get a pointer to the value (array)
+    constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
+    {
+        return is_array() ? m_value.array : nullptr;
+    }
+
+    /// get a pointer to the value (string)
+    string_t* get_impl_ptr(string_t* /*unused*/) noexcept
+    {
+        return is_string() ? m_value.string : nullptr;
+    }
+
+    /// get a pointer to the value (string)
+    constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
+    {
+        return is_string() ? m_value.string : nullptr;
+    }
+
+    /// get a pointer to the value (boolean)
+    boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
+    {
+        return is_boolean() ? &m_value.boolean : nullptr;
+    }
+
+    /// get a pointer to the value (boolean)
+    constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
+    {
+        return is_boolean() ? &m_value.boolean : nullptr;
+    }
+
+    /// get a pointer to the value (integer number)
+    number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
+    {
+        return is_number_integer() ? &m_value.number_integer : nullptr;
+    }
+
+    /// get a pointer to the value (integer number)
+    constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
+    {
+        return is_number_integer() ? &m_value.number_integer : nullptr;
+    }
+
+    /// get a pointer to the value (unsigned number)
+    number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
+    {
+        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
+    }
+
+    /// get a pointer to the value (unsigned number)
+    constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
+    {
+        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
+    }
+
+    /// get a pointer to the value (floating-point number)
+    number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
+    {
+        return is_number_float() ? &m_value.number_float : nullptr;
+    }
+
+    /// get a pointer to the value (floating-point number)
+    constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
+    {
+        return is_number_float() ? &m_value.number_float : nullptr;
+    }
+
+    /// get a pointer to the value (binary)
+    binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
+    {
+        return is_binary() ? m_value.binary : nullptr;
+    }
+
+    /// get a pointer to the value (binary)
+    constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
+    {
+        return is_binary() ? m_value.binary : nullptr;
+    }
+
+    /*!
+    @brief helper function to implement get_ref()
+
+    This function helps to implement get_ref() without code duplication for
+    const and non-const overloads
+
+    @tparam ThisType will be deduced as `basic_json` or `const basic_json`
+
+    @throw type_error.303 if ReferenceType does not match underlying value
+    type of the current JSON
+    */
+    template<typename ReferenceType, typename ThisType>
+    static ReferenceType get_ref_impl(ThisType& obj)
+    {
+        // delegate the call to get_ptr<>()
+        auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
+
+        if (JSON_HEDLEY_LIKELY(ptr != nullptr))
+        {
+            return *ptr;
+        }
+
+        JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj));
+    }
+
+  public:
+    /// @name value access
+    /// Direct access to the stored value of a JSON value.
+    /// @{
+
+    /// @brief get a pointer value (implicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value, int>::type = 0>
+    auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
+    {
+        // delegate the call to get_impl_ptr<>()
+        return get_impl_ptr(static_cast<PointerType>(nullptr));
+    }
+
+    /// @brief get a pointer value (implicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
+    template < typename PointerType, typename std::enable_if <
+                   std::is_pointer<PointerType>::value&&
+                   std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
+    constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
+    {
+        // delegate the call to get_impl_ptr<>() const
+        return get_impl_ptr(static_cast<PointerType>(nullptr));
+    }
+
+  private:
+    /*!
+    @brief get a value (explicit)
+
+    Explicit type conversion between the JSON value and a compatible value
+    which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+    and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+    The value is converted by calling the @ref json_serializer<ValueType>
+    `from_json()` method.
+
+    The function is equivalent to executing
+    @code {.cpp}
+    ValueType ret;
+    JSONSerializer<ValueType>::from_json(*this, ret);
+    return ret;
+    @endcode
+
+    This overloads is chosen if:
+    - @a ValueType is not @ref basic_json,
+    - @ref json_serializer<ValueType> has a `from_json()` method of the form
+      `void from_json(const basic_json&, ValueType&)`, and
+    - @ref json_serializer<ValueType> does not have a `from_json()` method of
+      the form `ValueType from_json(const basic_json&)`
+
+    @tparam ValueType the returned value type
+
+    @return copy of the JSON value, converted to @a ValueType
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+    @liveexample{The example below shows several conversions from JSON values
+    to other types. There a few things to note: (1) Floating-point numbers can
+    be converted to integers\, (2) A JSON array can be converted to a standard
+    `std::vector<short>`\, (3) A JSON object can be converted to C++
+    associative containers such as `std::unordered_map<std::string\,
+    json>`.,get__ValueType_const}
+
+    @since version 2.1.0
+    */
+    template < typename ValueType,
+               detail::enable_if_t <
+                   detail::is_default_constructible<ValueType>::value&&
+                   detail::has_from_json<basic_json_t, ValueType>::value,
+                   int > = 0 >
+    ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
+                JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
+    {
+        auto ret = ValueType();
+        JSONSerializer<ValueType>::from_json(*this, ret);
+        return ret;
+    }
+
+    /*!
+    @brief get a value (explicit); special case
+
+    Explicit type conversion between the JSON value and a compatible value
+    which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
+    and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
+    The value is converted by calling the @ref json_serializer<ValueType>
+    `from_json()` method.
+
+    The function is equivalent to executing
+    @code {.cpp}
+    return JSONSerializer<ValueType>::from_json(*this);
+    @endcode
+
+    This overloads is chosen if:
+    - @a ValueType is not @ref basic_json and
+    - @ref json_serializer<ValueType> has a `from_json()` method of the form
+      `ValueType from_json(const basic_json&)`
+
+    @note If @ref json_serializer<ValueType> has both overloads of
+    `from_json()`, this one is chosen.
+
+    @tparam ValueType the returned value type
+
+    @return copy of the JSON value, converted to @a ValueType
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws
+
+    @since version 2.1.0
+    */
+    template < typename ValueType,
+               detail::enable_if_t <
+                   detail::has_non_default_from_json<basic_json_t, ValueType>::value,
+                   int > = 0 >
+    ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
+                JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
+    {
+        return JSONSerializer<ValueType>::from_json(*this);
+    }
+
+    /*!
+    @brief get special-case overload
+
+    This overloads converts the current @ref basic_json in a different
+    @ref basic_json type
+
+    @tparam BasicJsonType == @ref basic_json
+
+    @return a copy of *this, converted into @a BasicJsonType
+
+    @complexity Depending on the implementation of the called `from_json()`
+                method.
+
+    @since version 3.2.0
+    */
+    template < typename BasicJsonType,
+               detail::enable_if_t <
+                   detail::is_basic_json<BasicJsonType>::value,
+                   int > = 0 >
+    BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
+    {
+        return *this;
+    }
+
+    /*!
+    @brief get special-case overload
+
+    This overloads avoids a lot of template boilerplate, it can be seen as the
+    identity method
+
+    @tparam BasicJsonType == @ref basic_json
+
+    @return a copy of *this
+
+    @complexity Constant.
+
+    @since version 2.1.0
+    */
+    template<typename BasicJsonType,
+             detail::enable_if_t<
+                 std::is_same<BasicJsonType, basic_json_t>::value,
+                 int> = 0>
+    basic_json get_impl(detail::priority_tag<3> /*unused*/) const
+    {
+        return *this;
+    }
+
+    /*!
+    @brief get a pointer value (explicit)
+    @copydoc get()
+    */
+    template<typename PointerType,
+             detail::enable_if_t<
+                 std::is_pointer<PointerType>::value,
+                 int> = 0>
+    constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
+    -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
+    {
+        // delegate the call to get_ptr
+        return get_ptr<PointerType>();
+    }
+
+  public:
+    /*!
+    @brief get a (pointer) value (explicit)
+
+    Performs explicit type conversion between the JSON value and a compatible value if required.
+
+    - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
+    No copies are made.
+
+    - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
+    from the current @ref basic_json.
+
+    - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
+    method.
+
+    @tparam ValueTypeCV the provided value type
+    @tparam ValueType the returned value type
+
+    @return copy of the JSON value, converted to @tparam ValueType if necessary
+
+    @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
+
+    @since version 2.1.0
+    */
+    template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
+#if defined(JSON_HAS_CPP_14)
+    constexpr
+#endif
+    auto get() const noexcept(
+    noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
+    -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
+    {
+        // we cannot static_assert on ValueTypeCV being non-const, because
+        // there is support for get<const basic_json_t>(), which is why we
+        // still need the uncvref
+        static_assert(!std::is_reference<ValueTypeCV>::value,
+                      "get() cannot be used with reference types, you might want to use get_ref()");
+        return get_impl<ValueType>(detail::priority_tag<4> {});
+    }
+
+    /*!
+    @brief get a pointer value (explicit)
+
+    Explicit pointer access to the internally stored JSON value. No copies are
+    made.
+
+    @warning The pointer becomes invalid if the underlying JSON object
+    changes.
+
+    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
+    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
+    @ref number_unsigned_t, or @ref number_float_t.
+
+    @return pointer to the internally stored JSON value if the requested
+    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
+
+    @complexity Constant.
+
+    @liveexample{The example below shows how pointers to internal values of a
+    JSON value can be requested. Note that no type conversions are made and a
+    `nullptr` is returned if the value and the requested pointer type does not
+    match.,get__PointerType}
+
+    @sa see @ref get_ptr() for explicit pointer-member access
+
+    @since version 1.0.0
+    */
+    template<typename PointerType, typename std::enable_if<
+                 std::is_pointer<PointerType>::value, int>::type = 0>
+    auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
+    {
+        // delegate the call to get_ptr
+        return get_ptr<PointerType>();
+    }
+
+    /// @brief get a value (explicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/get_to/
+    template < typename ValueType,
+               detail::enable_if_t <
+                   !detail::is_basic_json<ValueType>::value&&
+                   detail::has_from_json<basic_json_t, ValueType>::value,
+                   int > = 0 >
+    ValueType & get_to(ValueType& v) const noexcept(noexcept(
+                JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
+    {
+        JSONSerializer<ValueType>::from_json(*this, v);
+        return v;
+    }
+
+    // specialization to allow calling get_to with a basic_json value
+    // see https://github.com/nlohmann/json/issues/2175
+    template<typename ValueType,
+             detail::enable_if_t <
+                 detail::is_basic_json<ValueType>::value,
+                 int> = 0>
+    ValueType & get_to(ValueType& v) const
+    {
+        v = *this;
+        return v;
+    }
+
+    template <
+        typename T, std::size_t N,
+        typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+        detail::enable_if_t <
+            detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
+    Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
+    noexcept(noexcept(JSONSerializer<Array>::from_json(
+                          std::declval<const basic_json_t&>(), v)))
+    {
+        JSONSerializer<Array>::from_json(*this, v);
+        return v;
+    }
+
+    /// @brief get a reference value (implicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
+    template<typename ReferenceType, typename std::enable_if<
+                 std::is_reference<ReferenceType>::value, int>::type = 0>
+    ReferenceType get_ref()
+    {
+        // delegate call to get_ref_impl
+        return get_ref_impl<ReferenceType>(*this);
+    }
+
+    /// @brief get a reference value (implicit)
+    /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
+    template < typename ReferenceType, typename std::enable_if <
+                   std::is_reference<ReferenceType>::value&&
+                   std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
+    ReferenceType get_ref() const
+    {
+        // delegate call to get_ref_impl
+        return get_ref_impl<ReferenceType>(*this);
+    }
+
+    /*!
+    @brief get a value (implicit)
+
+    Implicit type conversion between the JSON value and a compatible value.
+    The call is realized by calling @ref get() const.
+
+    @tparam ValueType non-pointer type compatible to the JSON value, for
+    instance `int` for JSON integer numbers, `bool` for JSON booleans, or
+    `std::vector` types for JSON arrays. The character type of @ref string_t
+    as well as an initializer list of this type is excluded to avoid
+    ambiguities as these types implicitly convert to `std::string`.
+
+    @return copy of the JSON value, converted to type @a ValueType
+
+    @throw type_error.302 in case passed type @a ValueType is incompatible
+    to the JSON value type (e.g., the JSON value is of type boolean, but a
+    string is requested); see example below
+
+    @complexity Linear in the size of the JSON value.
+
+    @liveexample{The example below shows several conversions from JSON values
+    to other types. There a few things to note: (1) Floating-point numbers can
+    be converted to integers\, (2) A JSON array can be converted to a standard
+    `std::vector<short>`\, (3) A JSON object can be converted to C++
+    associative containers such as `std::unordered_map<std::string\,
+    json>`.,operator__ValueType}
+
+    @since version 1.0.0
+    */
+    template < typename ValueType, typename std::enable_if <
+                   detail::conjunction <
+                       detail::negation<std::is_pointer<ValueType>>,
+                       detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
+                                        detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
+                                        detail::negation<detail::is_basic_json<ValueType>>,
+                                        detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
+
+#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
+                                                detail::negation<std::is_same<ValueType, std::string_view>>,
+#endif
+                                                detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
+                                                >::value, int >::type = 0 >
+                                        JSON_EXPLICIT operator ValueType() const
+    {
+        // delegate the call to get<>() const
+        return get<ValueType>();
+    }
+
+    /// @brief get a binary value
+    /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
+    binary_t& get_binary()
+    {
+        if (!is_binary())
+        {
+            JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
+        }
+
+        return *get_ptr<binary_t*>();
+    }
+
+    /// @brief get a binary value
+    /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
+    const binary_t& get_binary() const
+    {
+        if (!is_binary())
+        {
+            JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this));
+        }
+
+        return *get_ptr<const binary_t*>();
+    }
+
+    /// @}
+
+
+    ////////////////////
+    // element access //
+    ////////////////////
+
+    /// @name element access
+    /// Access to the JSON value.
+    /// @{
+
+    /// @brief access specified array element with bounds checking
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    reference at(size_type idx)
+    {
+        // at only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            JSON_TRY
+            {
+                return set_parent(m_value.array->at(idx));
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief access specified array element with bounds checking
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    const_reference at(size_type idx) const
+    {
+        // at only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            JSON_TRY
+            {
+                return m_value.array->at(idx);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief access specified object element with bounds checking
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    reference at(const typename object_t::key_type& key)
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_TRY
+            {
+                return set_parent(m_value.object->at(key));
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief access specified object element with bounds checking
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    const_reference at(const typename object_t::key_type& key) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_TRY
+            {
+                return m_value.object->at(key);
+            }
+            JSON_CATCH (std::out_of_range&)
+            {
+                // create better exception explanation
+                JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this));
+            }
+        }
+        else
+        {
+            JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief access specified array element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    reference operator[](size_type idx)
+    {
+        // implicitly convert null value to an empty array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value.array = create<array_t>();
+            assert_invariant();
+        }
+
+        // operator[] only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // fill up array with null values if given idx is outside range
+            if (idx >= m_value.array->size())
+            {
+#if JSON_DIAGNOSTICS
+                // remember array size & capacity before resizing
+                const auto old_size = m_value.array->size();
+                const auto old_capacity = m_value.array->capacity();
+#endif
+                m_value.array->resize(idx + 1);
+
+#if JSON_DIAGNOSTICS
+                if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity))
+                {
+                    // capacity has changed: update all parents
+                    set_parents();
+                }
+                else
+                {
+                    // set parent for values added above
+                    set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
+                }
+#endif
+                assert_invariant();
+            }
+
+            return m_value.array->operator[](idx);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified array element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    const_reference operator[](size_type idx) const
+    {
+        // const operator[] only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            return m_value.array->operator[](idx);
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    reference operator[](const typename object_t::key_type& key)
+    {
+        // implicitly convert null value to an empty object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value.object = create<object_t>();
+            assert_invariant();
+        }
+
+        // operator[] only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return set_parent(m_value.object->operator[](key));
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    const_reference operator[](const typename object_t::key_type& key) const
+    {
+        // const operator[] only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
+            return m_value.object->find(key)->second;
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    template<typename T>
+    JSON_HEDLEY_NON_NULL(2)
+    reference operator[](T* key)
+    {
+        // implicitly convert null to object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return set_parent(m_value.object->operator[](key));
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    template<typename T>
+    JSON_HEDLEY_NON_NULL(2)
+    const_reference operator[](T* key) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
+            return m_value.object->find(key)->second;
+        }
+
+        JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element with default value
+    /// @sa https://json.nlohmann.me/api/basic_json/value/
+    /// using std::is_convertible in a std::enable_if will fail when using explicit conversions
+    template < class ValueType, typename std::enable_if <
+                   detail::is_getable<basic_json_t, ValueType>::value
+                   && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
+    ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            // if key is found, return value and given default value otherwise
+            const auto it = find(key);
+            if (it != end())
+            {
+                return it->template get<ValueType>();
+            }
+
+            return default_value;
+        }
+
+        JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element with default value
+    /// @sa https://json.nlohmann.me/api/basic_json/value/
+    /// overload for a default value of type const char*
+    string_t value(const typename object_t::key_type& key, const char* default_value) const
+    {
+        return value(key, string_t(default_value));
+    }
+
+    /// @brief access specified object element via JSON Pointer with default value
+    /// @sa https://json.nlohmann.me/api/basic_json/value/
+    template<class ValueType, typename std::enable_if<
+                 detail::is_getable<basic_json_t, ValueType>::value, int>::type = 0>
+    ValueType value(const json_pointer& ptr, const ValueType& default_value) const
+    {
+        // at only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            // if pointer resolves a value, return it or use default value
+            JSON_TRY
+            {
+                return ptr.get_checked(this).template get<ValueType>();
+            }
+            JSON_INTERNAL_CATCH (out_of_range&)
+            {
+                return default_value;
+            }
+        }
+
+        JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this));
+    }
+
+    /// @brief access specified object element via JSON Pointer with default value
+    /// @sa https://json.nlohmann.me/api/basic_json/value/
+    /// overload for a default value of type const char*
+    JSON_HEDLEY_NON_NULL(3)
+    string_t value(const json_pointer& ptr, const char* default_value) const
+    {
+        return value(ptr, string_t(default_value));
+    }
+
+    /// @brief access the first element
+    /// @sa https://json.nlohmann.me/api/basic_json/front/
+    reference front()
+    {
+        return *begin();
+    }
+
+    /// @brief access the first element
+    /// @sa https://json.nlohmann.me/api/basic_json/front/
+    const_reference front() const
+    {
+        return *cbegin();
+    }
+
+    /// @brief access the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/back/
+    reference back()
+    {
+        auto tmp = end();
+        --tmp;
+        return *tmp;
+    }
+
+    /// @brief access the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/back/
+    const_reference back() const
+    {
+        auto tmp = cend();
+        --tmp;
+        return *tmp;
+    }
+
+    /// @brief remove element given an iterator
+    /// @sa https://json.nlohmann.me/api/basic_json/erase/
+    template < class IteratorType, typename std::enable_if <
+                   std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
+                   std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
+               = 0 >
+    IteratorType erase(IteratorType pos)
+    {
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
+        }
+
+        IteratorType result = end();
+
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            case value_t::binary:
+            {
+                if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
+                {
+                    JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this));
+                }
+
+                if (is_string())
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
+                    m_value.string = nullptr;
+                }
+                else if (is_binary())
+                {
+                    AllocatorType<binary_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
+                    m_value.binary = nullptr;
+                }
+
+                m_type = value_t::null;
+                assert_invariant();
+                break;
+            }
+
+            case value_t::object:
+            {
+                result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::discarded:
+            default:
+                JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
+        }
+
+        return result;
+    }
+
+    /// @brief remove elements given an iterator range
+    /// @sa https://json.nlohmann.me/api/basic_json/erase/
+    template < class IteratorType, typename std::enable_if <
+                   std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
+                   std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
+               = 0 >
+    IteratorType erase(IteratorType first, IteratorType last)
+    {
+        // make sure iterator fits the current value
+        if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this));
+        }
+
+        IteratorType result = end();
+
+        switch (m_type)
+        {
+            case value_t::boolean:
+            case value_t::number_float:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::string:
+            case value_t::binary:
+            {
+                if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
+                                       || !last.m_it.primitive_iterator.is_end()))
+                {
+                    JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this));
+                }
+
+                if (is_string())
+                {
+                    AllocatorType<string_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
+                    m_value.string = nullptr;
+                }
+                else if (is_binary())
+                {
+                    AllocatorType<binary_t> alloc;
+                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
+                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
+                    m_value.binary = nullptr;
+                }
+
+                m_type = value_t::null;
+                assert_invariant();
+                break;
+            }
+
+            case value_t::object:
+            {
+                result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
+                                              last.m_it.object_iterator);
+                break;
+            }
+
+            case value_t::array:
+            {
+                result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
+                                             last.m_it.array_iterator);
+                break;
+            }
+
+            case value_t::null:
+            case value_t::discarded:
+            default:
+                JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
+        }
+
+        return result;
+    }
+
+    /// @brief remove element from a JSON object given a key
+    /// @sa https://json.nlohmann.me/api/basic_json/erase/
+    size_type erase(const typename object_t::key_type& key)
+    {
+        // this erase only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            return m_value.object->erase(key);
+        }
+
+        JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
+    }
+
+    /// @brief remove element from a JSON array given an index
+    /// @sa https://json.nlohmann.me/api/basic_json/erase/
+    void erase(const size_type idx)
+    {
+        // this erase only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            if (JSON_HEDLEY_UNLIKELY(idx >= size()))
+            {
+                JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this));
+            }
+
+            m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
+        }
+        else
+        {
+            JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @}
+
+
+    ////////////
+    // lookup //
+    ////////////
+
+    /// @name lookup
+    /// @{
+
+    /// @brief find an element in a JSON object
+    /// @sa https://json.nlohmann.me/api/basic_json/find/
+    template<typename KeyT>
+    iterator find(KeyT&& key)
+    {
+        auto result = end();
+
+        if (is_object())
+        {
+            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
+        }
+
+        return result;
+    }
+
+    /// @brief find an element in a JSON object
+    /// @sa https://json.nlohmann.me/api/basic_json/find/
+    template<typename KeyT>
+    const_iterator find(KeyT&& key) const
+    {
+        auto result = cend();
+
+        if (is_object())
+        {
+            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
+        }
+
+        return result;
+    }
+
+    /// @brief returns the number of occurrences of a key in a JSON object
+    /// @sa https://json.nlohmann.me/api/basic_json/count/
+    template<typename KeyT>
+    size_type count(KeyT&& key) const
+    {
+        // return 0 for all nonobject types
+        return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
+    }
+
+    /// @brief check the existence of an element in a JSON object
+    /// @sa https://json.nlohmann.me/api/basic_json/contains/
+    template < typename KeyT, typename std::enable_if <
+                   !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
+    bool contains(KeyT && key) const
+    {
+        return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
+    }
+
+    /// @brief check the existence of an element in a JSON object given a JSON pointer
+    /// @sa https://json.nlohmann.me/api/basic_json/contains/
+    bool contains(const json_pointer& ptr) const
+    {
+        return ptr.contains(this);
+    }
+
+    /// @}
+
+
+    ///////////////
+    // iterators //
+    ///////////////
+
+    /// @name iterators
+    /// @{
+
+    /// @brief returns an iterator to the first element
+    /// @sa https://json.nlohmann.me/api/basic_json/begin/
+    iterator begin() noexcept
+    {
+        iterator result(this);
+        result.set_begin();
+        return result;
+    }
+
+    /// @brief returns an iterator to the first element
+    /// @sa https://json.nlohmann.me/api/basic_json/begin/
+    const_iterator begin() const noexcept
+    {
+        return cbegin();
+    }
+
+    /// @brief returns a const iterator to the first element
+    /// @sa https://json.nlohmann.me/api/basic_json/cbegin/
+    const_iterator cbegin() const noexcept
+    {
+        const_iterator result(this);
+        result.set_begin();
+        return result;
+    }
+
+    /// @brief returns an iterator to one past the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/end/
+    iterator end() noexcept
+    {
+        iterator result(this);
+        result.set_end();
+        return result;
+    }
+
+    /// @brief returns an iterator to one past the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/end/
+    const_iterator end() const noexcept
+    {
+        return cend();
+    }
+
+    /// @brief returns an iterator to one past the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/cend/
+    const_iterator cend() const noexcept
+    {
+        const_iterator result(this);
+        result.set_end();
+        return result;
+    }
+
+    /// @brief returns an iterator to the reverse-beginning
+    /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
+    reverse_iterator rbegin() noexcept
+    {
+        return reverse_iterator(end());
+    }
+
+    /// @brief returns an iterator to the reverse-beginning
+    /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
+    const_reverse_iterator rbegin() const noexcept
+    {
+        return crbegin();
+    }
+
+    /// @brief returns an iterator to the reverse-end
+    /// @sa https://json.nlohmann.me/api/basic_json/rend/
+    reverse_iterator rend() noexcept
+    {
+        return reverse_iterator(begin());
+    }
+
+    /// @brief returns an iterator to the reverse-end
+    /// @sa https://json.nlohmann.me/api/basic_json/rend/
+    const_reverse_iterator rend() const noexcept
+    {
+        return crend();
+    }
+
+    /// @brief returns a const reverse iterator to the last element
+    /// @sa https://json.nlohmann.me/api/basic_json/crbegin/
+    const_reverse_iterator crbegin() const noexcept
+    {
+        return const_reverse_iterator(cend());
+    }
+
+    /// @brief returns a const reverse iterator to one before the first
+    /// @sa https://json.nlohmann.me/api/basic_json/crend/
+    const_reverse_iterator crend() const noexcept
+    {
+        return const_reverse_iterator(cbegin());
+    }
+
+  public:
+    /// @brief wrapper to access iterator member functions in range-based for
+    /// @sa https://json.nlohmann.me/api/basic_json/items/
+    /// @deprecated This function is deprecated since 3.1.0 and will be removed in
+    ///             version 4.0.0 of the library. Please use @ref items() instead;
+    ///             that is, replace `json::iterator_wrapper(j)` with `j.items()`.
+    JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
+    static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
+    {
+        return ref.items();
+    }
+
+    /// @brief wrapper to access iterator member functions in range-based for
+    /// @sa https://json.nlohmann.me/api/basic_json/items/
+    /// @deprecated This function is deprecated since 3.1.0 and will be removed in
+    ///         version 4.0.0 of the library. Please use @ref items() instead;
+    ///         that is, replace `json::iterator_wrapper(j)` with `j.items()`.
+    JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
+    static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
+    {
+        return ref.items();
+    }
+
+    /// @brief helper to access iterator member functions in range-based for
+    /// @sa https://json.nlohmann.me/api/basic_json/items/
+    iteration_proxy<iterator> items() noexcept
+    {
+        return iteration_proxy<iterator>(*this);
+    }
+
+    /// @brief helper to access iterator member functions in range-based for
+    /// @sa https://json.nlohmann.me/api/basic_json/items/
+    iteration_proxy<const_iterator> items() const noexcept
+    {
+        return iteration_proxy<const_iterator>(*this);
+    }
+
+    /// @}
+
+
+    //////////////
+    // capacity //
+    //////////////
+
+    /// @name capacity
+    /// @{
+
+    /// @brief checks whether the container is empty.
+    /// @sa https://json.nlohmann.me/api/basic_json/empty/
+    bool empty() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::null:
+            {
+                // null values are empty
+                return true;
+            }
+
+            case value_t::array:
+            {
+                // delegate call to array_t::empty()
+                return m_value.array->empty();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::empty()
+                return m_value.object->empty();
+            }
+
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                // all other types are nonempty
+                return false;
+            }
+        }
+    }
+
+    /// @brief returns the number of elements
+    /// @sa https://json.nlohmann.me/api/basic_json/size/
+    size_type size() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::null:
+            {
+                // null values are empty
+                return 0;
+            }
+
+            case value_t::array:
+            {
+                // delegate call to array_t::size()
+                return m_value.array->size();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::size()
+                return m_value.object->size();
+            }
+
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                // all other types have size 1
+                return 1;
+            }
+        }
+    }
+
+    /// @brief returns the maximum possible number of elements
+    /// @sa https://json.nlohmann.me/api/basic_json/max_size/
+    size_type max_size() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::array:
+            {
+                // delegate call to array_t::max_size()
+                return m_value.array->max_size();
+            }
+
+            case value_t::object:
+            {
+                // delegate call to object_t::max_size()
+                return m_value.object->max_size();
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                // all other types have max_size() == size()
+                return size();
+            }
+        }
+    }
+
+    /// @}
+
+
+    ///////////////
+    // modifiers //
+    ///////////////
+
+    /// @name modifiers
+    /// @{
+
+    /// @brief clears the contents
+    /// @sa https://json.nlohmann.me/api/basic_json/clear/
+    void clear() noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::number_integer:
+            {
+                m_value.number_integer = 0;
+                break;
+            }
+
+            case value_t::number_unsigned:
+            {
+                m_value.number_unsigned = 0;
+                break;
+            }
+
+            case value_t::number_float:
+            {
+                m_value.number_float = 0.0;
+                break;
+            }
+
+            case value_t::boolean:
+            {
+                m_value.boolean = false;
+                break;
+            }
+
+            case value_t::string:
+            {
+                m_value.string->clear();
+                break;
+            }
+
+            case value_t::binary:
+            {
+                m_value.binary->clear();
+                break;
+            }
+
+            case value_t::array:
+            {
+                m_value.array->clear();
+                break;
+            }
+
+            case value_t::object:
+            {
+                m_value.object->clear();
+                break;
+            }
+
+            case value_t::null:
+            case value_t::discarded:
+            default:
+                break;
+        }
+    }
+
+    /// @brief add an object to an array
+    /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+    void push_back(basic_json&& val)
+    {
+        // push_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array (move semantics)
+        const auto old_capacity = m_value.array->capacity();
+        m_value.array->push_back(std::move(val));
+        set_parent(m_value.array->back(), old_capacity);
+        // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor
+    }
+
+    /// @brief add an object to an array
+    /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+    reference operator+=(basic_json&& val)
+    {
+        push_back(std::move(val));
+        return *this;
+    }
+
+    /// @brief add an object to an array
+    /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+    void push_back(const basic_json& val)
+    {
+        // push_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array
+        const auto old_capacity = m_value.array->capacity();
+        m_value.array->push_back(val);
+        set_parent(m_value.array->back(), old_capacity);
+    }
+
+    /// @brief add an object to an array
+    /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+    reference operator+=(const basic_json& val)
+    {
+        push_back(val);
+        return *this;
+    }
+
+    /// @brief add an object to an object
+    /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+    void push_back(const typename object_t::value_type& val)
+    {
+        // push_back only works for null objects or objects
+        if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
+        {
+            JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this));
+        }
+
+        // transform null object into an object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // add element to object
+        auto res = m_value.object->insert(val);
+        set_parent(res.first->second);
+    }
+
+    /// @brief add an object to an object
+    /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+    reference operator+=(const typename object_t::value_type& val)
+    {
+        push_back(val);
+        return *this;
+    }
+
+    /// @brief add an object to an object
+    /// @sa https://json.nlohmann.me/api/basic_json/push_back/
+    void push_back(initializer_list_t init)
+    {
+        if (is_object() && init.size() == 2 && (*init.begin())->is_string())
+        {
+            basic_json&& key = init.begin()->moved_or_copied();
+            push_back(typename object_t::value_type(
+                          std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
+        }
+        else
+        {
+            push_back(basic_json(init));
+        }
+    }
+
+    /// @brief add an object to an object
+    /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
+    reference operator+=(initializer_list_t init)
+    {
+        push_back(init);
+        return *this;
+    }
+
+    /// @brief add an object to an array
+    /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/
+    template<class... Args>
+    reference emplace_back(Args&& ... args)
+    {
+        // emplace_back only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
+        {
+            JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this));
+        }
+
+        // transform null object into an array
+        if (is_null())
+        {
+            m_type = value_t::array;
+            m_value = value_t::array;
+            assert_invariant();
+        }
+
+        // add element to array (perfect forwarding)
+        const auto old_capacity = m_value.array->capacity();
+        m_value.array->emplace_back(std::forward<Args>(args)...);
+        return set_parent(m_value.array->back(), old_capacity);
+    }
+
+    /// @brief add an object to an object if key does not exist
+    /// @sa https://json.nlohmann.me/api/basic_json/emplace/
+    template<class... Args>
+    std::pair<iterator, bool> emplace(Args&& ... args)
+    {
+        // emplace only works for null objects or arrays
+        if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
+        {
+            JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this));
+        }
+
+        // transform null object into an object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value = value_t::object;
+            assert_invariant();
+        }
+
+        // add element to array (perfect forwarding)
+        auto res = m_value.object->emplace(std::forward<Args>(args)...);
+        set_parent(res.first->second);
+
+        // create result iterator and set iterator to the result of emplace
+        auto it = begin();
+        it.m_it.object_iterator = res.first;
+
+        // return pair of iterator and boolean
+        return {it, res.second};
+    }
+
+    /// Helper for insertion of an iterator
+    /// @note: This uses std::distance to support GCC 4.8,
+    ///        see https://github.com/nlohmann/json/pull/1257
+    template<typename... Args>
+    iterator insert_iterator(const_iterator pos, Args&& ... args)
+    {
+        iterator result(this);
+        JSON_ASSERT(m_value.array != nullptr);
+
+        auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
+        m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
+        result.m_it.array_iterator = m_value.array->begin() + insert_pos;
+
+        // This could have been written as:
+        // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
+        // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
+
+        set_parents();
+        return result;
+    }
+
+    /// @brief inserts element into array
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    iterator insert(const_iterator pos, const basic_json& val)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // check if iterator pos fits to this JSON value
+            if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+            {
+                JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
+            }
+
+            // insert to array and return iterator
+            return insert_iterator(pos, val);
+        }
+
+        JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
+    }
+
+    /// @brief inserts element into array
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    iterator insert(const_iterator pos, basic_json&& val)
+    {
+        return insert(pos, val);
+    }
+
+    /// @brief inserts copies of element into array
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            // check if iterator pos fits to this JSON value
+            if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+            {
+                JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
+            }
+
+            // insert to array and return iterator
+            return insert_iterator(pos, cnt, val);
+        }
+
+        JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
+    }
+
+    /// @brief inserts range of elements into array
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    iterator insert(const_iterator pos, const_iterator first, const_iterator last)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_UNLIKELY(!is_array()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
+        }
+
+        // check if iterator pos fits to this JSON value
+        if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
+        {
+            JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this));
+        }
+
+        // insert to array and return iterator
+        return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
+    }
+
+    /// @brief inserts elements from initializer list into array
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    iterator insert(const_iterator pos, initializer_list_t ilist)
+    {
+        // insert only works for arrays
+        if (JSON_HEDLEY_UNLIKELY(!is_array()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
+        }
+
+        // check if iterator pos fits to this JSON value
+        if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this));
+        }
+
+        // insert to array and return iterator
+        return insert_iterator(pos, ilist.begin(), ilist.end());
+    }
+
+    /// @brief inserts range of elements into object
+    /// @sa https://json.nlohmann.me/api/basic_json/insert/
+    void insert(const_iterator first, const_iterator last)
+    {
+        // insert only works for objects
+        if (JSON_HEDLEY_UNLIKELY(!is_object()))
+        {
+            JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
+        }
+
+        // passed iterators must belong to objects
+        if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
+        {
+            JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this));
+        }
+
+        m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
+    }
+
+    /// @brief updates a JSON object from another object, overwriting existing keys
+    /// @sa https://json.nlohmann.me/api/basic_json/update/
+    void update(const_reference j, bool merge_objects = false)
+    {
+        update(j.begin(), j.end(), merge_objects);
+    }
+
+    /// @brief updates a JSON object from another object, overwriting existing keys
+    /// @sa https://json.nlohmann.me/api/basic_json/update/
+    void update(const_iterator first, const_iterator last, bool merge_objects = false)
+    {
+        // implicitly convert null value to an empty object
+        if (is_null())
+        {
+            m_type = value_t::object;
+            m_value.object = create<object_t>();
+            assert_invariant();
+        }
+
+        if (JSON_HEDLEY_UNLIKELY(!is_object()))
+        {
+            JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this));
+        }
+
+        // check if range iterators belong to the same JSON object
+        if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
+        {
+            JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this));
+        }
+
+        // passed iterators must belong to objects
+        if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
+        {
+            JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object));
+        }
+
+        for (auto it = first; it != last; ++it)
+        {
+            if (merge_objects && it.value().is_object())
+            {
+                auto it2 = m_value.object->find(it.key());
+                if (it2 != m_value.object->end())
+                {
+                    it2->second.update(it.value(), true);
+                    continue;
+                }
+            }
+            m_value.object->operator[](it.key()) = it.value();
+#if JSON_DIAGNOSTICS
+            m_value.object->operator[](it.key()).m_parent = this;
+#endif
+        }
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(reference other) noexcept (
+        std::is_nothrow_move_constructible<value_t>::value&&
+        std::is_nothrow_move_assignable<value_t>::value&&
+        std::is_nothrow_move_constructible<json_value>::value&&
+        std::is_nothrow_move_assignable<json_value>::value
+    )
+    {
+        std::swap(m_type, other.m_type);
+        std::swap(m_value, other.m_value);
+
+        set_parents();
+        other.set_parents();
+        assert_invariant();
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    friend void swap(reference left, reference right) noexcept (
+        std::is_nothrow_move_constructible<value_t>::value&&
+        std::is_nothrow_move_assignable<value_t>::value&&
+        std::is_nothrow_move_constructible<json_value>::value&&
+        std::is_nothrow_move_assignable<json_value>::value
+    )
+    {
+        left.swap(right);
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(array_t& other) // NOLINT(bugprone-exception-escape)
+    {
+        // swap only works for arrays
+        if (JSON_HEDLEY_LIKELY(is_array()))
+        {
+            std::swap(*(m_value.array), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(object_t& other) // NOLINT(bugprone-exception-escape)
+    {
+        // swap only works for objects
+        if (JSON_HEDLEY_LIKELY(is_object()))
+        {
+            std::swap(*(m_value.object), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(string_t& other) // NOLINT(bugprone-exception-escape)
+    {
+        // swap only works for strings
+        if (JSON_HEDLEY_LIKELY(is_string()))
+        {
+            std::swap(*(m_value.string), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
+    {
+        // swap only works for strings
+        if (JSON_HEDLEY_LIKELY(is_binary()))
+        {
+            std::swap(*(m_value.binary), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @brief exchanges the values
+    /// @sa https://json.nlohmann.me/api/basic_json/swap/
+    void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
+    {
+        // swap only works for strings
+        if (JSON_HEDLEY_LIKELY(is_binary()))
+        {
+            std::swap(*(m_value.binary), other);
+        }
+        else
+        {
+            JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this));
+        }
+    }
+
+    /// @}
+
+  public:
+    //////////////////////////////////////////
+    // lexicographical comparison operators //
+    //////////////////////////////////////////
+
+    /// @name lexicographical comparison operators
+    /// @{
+
+    /// @brief comparison: equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+    friend bool operator==(const_reference lhs, const_reference rhs) noexcept
+    {
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wfloat-equal"
+#endif
+        const auto lhs_type = lhs.type();
+        const auto rhs_type = rhs.type();
+
+        if (lhs_type == rhs_type)
+        {
+            switch (lhs_type)
+            {
+                case value_t::array:
+                    return *lhs.m_value.array == *rhs.m_value.array;
+
+                case value_t::object:
+                    return *lhs.m_value.object == *rhs.m_value.object;
+
+                case value_t::null:
+                    return true;
+
+                case value_t::string:
+                    return *lhs.m_value.string == *rhs.m_value.string;
+
+                case value_t::boolean:
+                    return lhs.m_value.boolean == rhs.m_value.boolean;
+
+                case value_t::number_integer:
+                    return lhs.m_value.number_integer == rhs.m_value.number_integer;
+
+                case value_t::number_unsigned:
+                    return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
+
+                case value_t::number_float:
+                    return lhs.m_value.number_float == rhs.m_value.number_float;
+
+                case value_t::binary:
+                    return *lhs.m_value.binary == *rhs.m_value.binary;
+
+                case value_t::discarded:
+                default:
+                    return false;
+            }
+        }
+        else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
+        {
+            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
+        }
+        else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
+        {
+            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
+        }
+        else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
+        }
+
+        return false;
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+    }
+
+    /// @brief comparison: equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs == basic_json(rhs);
+    }
+
+    /// @brief comparison: equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) == rhs;
+    }
+
+    /// @brief comparison: not equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return !(lhs == rhs);
+    }
+
+    /// @brief comparison: not equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs != basic_json(rhs);
+    }
+
+    /// @brief comparison: not equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) != rhs;
+    }
+
+    /// @brief comparison: less than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+    friend bool operator<(const_reference lhs, const_reference rhs) noexcept
+    {
+        const auto lhs_type = lhs.type();
+        const auto rhs_type = rhs.type();
+
+        if (lhs_type == rhs_type)
+        {
+            switch (lhs_type)
+            {
+                case value_t::array:
+                    // note parentheses are necessary, see
+                    // https://github.com/nlohmann/json/issues/1530
+                    return (*lhs.m_value.array) < (*rhs.m_value.array);
+
+                case value_t::object:
+                    return (*lhs.m_value.object) < (*rhs.m_value.object);
+
+                case value_t::null:
+                    return false;
+
+                case value_t::string:
+                    return (*lhs.m_value.string) < (*rhs.m_value.string);
+
+                case value_t::boolean:
+                    return (lhs.m_value.boolean) < (rhs.m_value.boolean);
+
+                case value_t::number_integer:
+                    return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
+
+                case value_t::number_unsigned:
+                    return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
+
+                case value_t::number_float:
+                    return (lhs.m_value.number_float) < (rhs.m_value.number_float);
+
+                case value_t::binary:
+                    return (*lhs.m_value.binary) < (*rhs.m_value.binary);
+
+                case value_t::discarded:
+                default:
+                    return false;
+            }
+        }
+        else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
+        {
+            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
+        }
+        else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
+        {
+            return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
+        }
+        else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
+        {
+            return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
+        }
+        else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
+        {
+            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
+        }
+
+        // We only reach this line if we cannot compare values. In that case,
+        // we compare types. Note we have to call the operator explicitly,
+        // because MSVC has problems otherwise.
+        return operator<(lhs_type, rhs_type);
+    }
+
+    /// @brief comparison: less than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs < basic_json(rhs);
+    }
+
+    /// @brief comparison: less than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) < rhs;
+    }
+
+    /// @brief comparison: less than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return !(rhs < lhs);
+    }
+
+    /// @brief comparison: less than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs <= basic_json(rhs);
+    }
+
+    /// @brief comparison: less than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) <= rhs;
+    }
+
+    /// @brief comparison: greater than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+    friend bool operator>(const_reference lhs, const_reference rhs) noexcept
+    {
+        return !(lhs <= rhs);
+    }
+
+    /// @brief comparison: greater than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs > basic_json(rhs);
+    }
+
+    /// @brief comparison: greater than
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) > rhs;
+    }
+
+    /// @brief comparison: greater than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
+    {
+        return !(lhs < rhs);
+    }
+
+    /// @brief comparison: greater than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
+    {
+        return lhs >= basic_json(rhs);
+    }
+
+    /// @brief comparison: greater than or equal
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
+    template<typename ScalarType, typename std::enable_if<
+                 std::is_scalar<ScalarType>::value, int>::type = 0>
+    friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
+    {
+        return basic_json(lhs) >= rhs;
+    }
+
+    /// @}
+
+    ///////////////////
+    // serialization //
+    ///////////////////
+
+    /// @name serialization
+    /// @{
+#ifndef JSON_NO_IO
+    /// @brief serialize to stream
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
+    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
+    {
+        // read width member and use it as indentation parameter if nonzero
+        const bool pretty_print = o.width() > 0;
+        const auto indentation = pretty_print ? o.width() : 0;
+
+        // reset width to 0 for subsequent calls to this stream
+        o.width(0);
+
+        // do the actual serialization
+        serializer s(detail::output_adapter<char>(o), o.fill());
+        s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
+        return o;
+    }
+
+    /// @brief serialize to stream
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
+    /// @deprecated This function is deprecated since 3.0.0 and will be removed in
+    ///             version 4.0.0 of the library. Please use
+    ///             operator<<(std::ostream&, const basic_json&) instead; that is,
+    ///             replace calls like `j >> o;` with `o << j;`.
+    JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
+    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
+    {
+        return o << j;
+    }
+#endif  // JSON_NO_IO
+    /// @}
+
+
+    /////////////////////
+    // deserialization //
+    /////////////////////
+
+    /// @name deserialization
+    /// @{
+
+    /// @brief deserialize from a compatible input
+    /// @sa https://json.nlohmann.me/api/basic_json/parse/
+    template<typename InputType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json parse(InputType&& i,
+                            const parser_callback_t cb = nullptr,
+                            const bool allow_exceptions = true,
+                            const bool ignore_comments = false)
+    {
+        basic_json result;
+        parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
+        return result;
+    }
+
+    /// @brief deserialize from a pair of character iterators
+    /// @sa https://json.nlohmann.me/api/basic_json/parse/
+    template<typename IteratorType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json parse(IteratorType first,
+                            IteratorType last,
+                            const parser_callback_t cb = nullptr,
+                            const bool allow_exceptions = true,
+                            const bool ignore_comments = false)
+    {
+        basic_json result;
+        parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
+        return result;
+    }
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
+    static basic_json parse(detail::span_input_adapter&& i,
+                            const parser_callback_t cb = nullptr,
+                            const bool allow_exceptions = true,
+                            const bool ignore_comments = false)
+    {
+        basic_json result;
+        parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
+        return result;
+    }
+
+    /// @brief check if the input is valid JSON
+    /// @sa https://json.nlohmann.me/api/basic_json/accept/
+    template<typename InputType>
+    static bool accept(InputType&& i,
+                       const bool ignore_comments = false)
+    {
+        return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
+    }
+
+    /// @brief check if the input is valid JSON
+    /// @sa https://json.nlohmann.me/api/basic_json/accept/
+    template<typename IteratorType>
+    static bool accept(IteratorType first, IteratorType last,
+                       const bool ignore_comments = false)
+    {
+        return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
+    }
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
+    static bool accept(detail::span_input_adapter&& i,
+                       const bool ignore_comments = false)
+    {
+        return parser(i.get(), nullptr, false, ignore_comments).accept(true);
+    }
+
+    /// @brief generate SAX events
+    /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+    template <typename InputType, typename SAX>
+    JSON_HEDLEY_NON_NULL(2)
+    static bool sax_parse(InputType&& i, SAX* sax,
+                          input_format_t format = input_format_t::json,
+                          const bool strict = true,
+                          const bool ignore_comments = false)
+    {
+        auto ia = detail::input_adapter(std::forward<InputType>(i));
+        return format == input_format_t::json
+               ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+               : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
+    }
+
+    /// @brief generate SAX events
+    /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+    template<class IteratorType, class SAX>
+    JSON_HEDLEY_NON_NULL(3)
+    static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
+                          input_format_t format = input_format_t::json,
+                          const bool strict = true,
+                          const bool ignore_comments = false)
+    {
+        auto ia = detail::input_adapter(std::move(first), std::move(last));
+        return format == input_format_t::json
+               ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+               : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
+    }
+
+    /// @brief generate SAX events
+    /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
+    /// @deprecated This function is deprecated since 3.8.0 and will be removed in
+    ///             version 4.0.0 of the library. Please use
+    ///             sax_parse(ptr, ptr + len) instead.
+    template <typename SAX>
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
+    JSON_HEDLEY_NON_NULL(2)
+    static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
+                          input_format_t format = input_format_t::json,
+                          const bool strict = true,
+                          const bool ignore_comments = false)
+    {
+        auto ia = i.get();
+        return format == input_format_t::json
+               // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+               ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
+               // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+               : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
+    }
+#ifndef JSON_NO_IO
+    /// @brief deserialize from stream
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
+    /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in
+    ///             version 4.0.0 of the library. Please use
+    ///             operator>>(std::istream&, basic_json&) instead; that is,
+    ///             replace calls like `j << i;` with `i >> j;`.
+    JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
+    friend std::istream& operator<<(basic_json& j, std::istream& i)
+    {
+        return operator>>(i, j);
+    }
+
+    /// @brief deserialize from stream
+    /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
+    friend std::istream& operator>>(std::istream& i, basic_json& j)
+    {
+        parser(detail::input_adapter(i)).parse(false, j);
+        return i;
+    }
+#endif  // JSON_NO_IO
+    /// @}
+
+    ///////////////////////////
+    // convenience functions //
+    ///////////////////////////
+
+    /// @brief return the type as string
+    /// @sa https://json.nlohmann.me/api/basic_json/type_name/
+    JSON_HEDLEY_RETURNS_NON_NULL
+    const char* type_name() const noexcept
+    {
+        switch (m_type)
+        {
+            case value_t::null:
+                return "null";
+            case value_t::object:
+                return "object";
+            case value_t::array:
+                return "array";
+            case value_t::string:
+                return "string";
+            case value_t::boolean:
+                return "boolean";
+            case value_t::binary:
+                return "binary";
+            case value_t::discarded:
+                return "discarded";
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            default:
+                return "number";
+        }
+    }
+
+
+  JSON_PRIVATE_UNLESS_TESTED:
+    //////////////////////
+    // member variables //
+    //////////////////////
+
+    /// the type of the current element
+    value_t m_type = value_t::null;
+
+    /// the value of the current element
+    json_value m_value = {};
+
+#if JSON_DIAGNOSTICS
+    /// a pointer to a parent value (for debugging purposes)
+    basic_json* m_parent = nullptr;
+#endif
+
+    //////////////////////////////////////////
+    // binary serialization/deserialization //
+    //////////////////////////////////////////
+
+    /// @name binary serialization/deserialization support
+    /// @{
+
+  public:
+    /// @brief create a CBOR serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+    static std::vector<std::uint8_t> to_cbor(const basic_json& j)
+    {
+        std::vector<std::uint8_t> result;
+        to_cbor(j, result);
+        return result;
+    }
+
+    /// @brief create a CBOR serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+    static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
+    {
+        binary_writer<std::uint8_t>(o).write_cbor(j);
+    }
+
+    /// @brief create a CBOR serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
+    static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_cbor(j);
+    }
+
+    /// @brief create a MessagePack serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+    static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
+    {
+        std::vector<std::uint8_t> result;
+        to_msgpack(j, result);
+        return result;
+    }
+
+    /// @brief create a MessagePack serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+    static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
+    {
+        binary_writer<std::uint8_t>(o).write_msgpack(j);
+    }
+
+    /// @brief create a MessagePack serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
+    static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_msgpack(j);
+    }
+
+    /// @brief create a UBJSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+    static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
+            const bool use_size = false,
+            const bool use_type = false)
+    {
+        std::vector<std::uint8_t> result;
+        to_ubjson(j, result, use_size, use_type);
+        return result;
+    }
+
+    /// @brief create a UBJSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+    static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
+                          const bool use_size = false, const bool use_type = false)
+    {
+        binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
+    }
+
+    /// @brief create a UBJSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
+    static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
+                          const bool use_size = false, const bool use_type = false)
+    {
+        binary_writer<char>(o).write_ubjson(j, use_size, use_type);
+    }
+
+    /// @brief create a BSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+    static std::vector<std::uint8_t> to_bson(const basic_json& j)
+    {
+        std::vector<std::uint8_t> result;
+        to_bson(j, result);
+        return result;
+    }
+
+    /// @brief create a BSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+    static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
+    {
+        binary_writer<std::uint8_t>(o).write_bson(j);
+    }
+
+    /// @brief create a BSON serialization of a given JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
+    static void to_bson(const basic_json& j, detail::output_adapter<char> o)
+    {
+        binary_writer<char>(o).write_bson(j);
+    }
+
+    /// @brief create a JSON value from an input in CBOR format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
+    template<typename InputType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_cbor(InputType&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true,
+                                const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::forward<InputType>(i));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in CBOR format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
+    template<typename IteratorType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_cbor(IteratorType first, IteratorType last,
+                                const bool strict = true,
+                                const bool allow_exceptions = true,
+                                const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::move(first), std::move(last));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    template<typename T>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
+    static basic_json from_cbor(const T* ptr, std::size_t len,
+                                const bool strict = true,
+                                const bool allow_exceptions = true,
+                                const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
+    {
+        return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
+    }
+
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
+    static basic_json from_cbor(detail::span_input_adapter&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true,
+                                const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = i.get();
+        // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in MessagePack format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
+    template<typename InputType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_msgpack(InputType&& i,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::forward<InputType>(i));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in MessagePack format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
+    template<typename IteratorType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_msgpack(IteratorType first, IteratorType last,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::move(first), std::move(last));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    template<typename T>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
+    static basic_json from_msgpack(const T* ptr, std::size_t len,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
+    }
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
+    static basic_json from_msgpack(detail::span_input_adapter&& i,
+                                   const bool strict = true,
+                                   const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = i.get();
+        // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in UBJSON format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
+    template<typename InputType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_ubjson(InputType&& i,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::forward<InputType>(i));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in UBJSON format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
+    template<typename IteratorType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_ubjson(IteratorType first, IteratorType last,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::move(first), std::move(last));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    template<typename T>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
+    static basic_json from_ubjson(const T* ptr, std::size_t len,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
+    }
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
+    static basic_json from_ubjson(detail::span_input_adapter&& i,
+                                  const bool strict = true,
+                                  const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = i.get();
+        // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in BSON format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
+    template<typename InputType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_bson(InputType&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::forward<InputType>(i));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    /// @brief create a JSON value from an input in BSON format
+    /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
+    template<typename IteratorType>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json from_bson(IteratorType first, IteratorType last,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = detail::input_adapter(std::move(first), std::move(last));
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+
+    template<typename T>
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
+    static basic_json from_bson(const T* ptr, std::size_t len,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        return from_bson(ptr, ptr + len, strict, allow_exceptions);
+    }
+
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
+    static basic_json from_bson(detail::span_input_adapter&& i,
+                                const bool strict = true,
+                                const bool allow_exceptions = true)
+    {
+        basic_json result;
+        detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
+        auto ia = i.get();
+        // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
+        const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
+        return res ? result : basic_json(value_t::discarded);
+    }
+    /// @}
+
+    //////////////////////////
+    // JSON Pointer support //
+    //////////////////////////
+
+    /// @name JSON Pointer functions
+    /// @{
+
+    /// @brief access specified element via JSON Pointer
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    reference operator[](const json_pointer& ptr)
+    {
+        return ptr.get_unchecked(this);
+    }
+
+    /// @brief access specified element via JSON Pointer
+    /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
+    const_reference operator[](const json_pointer& ptr) const
+    {
+        return ptr.get_unchecked(this);
+    }
+
+    /// @brief access specified element via JSON Pointer
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    reference at(const json_pointer& ptr)
+    {
+        return ptr.get_checked(this);
+    }
+
+    /// @brief access specified element via JSON Pointer
+    /// @sa https://json.nlohmann.me/api/basic_json/at/
+    const_reference at(const json_pointer& ptr) const
+    {
+        return ptr.get_checked(this);
+    }
+
+    /// @brief return flattened JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/flatten/
+    basic_json flatten() const
+    {
+        basic_json result(value_t::object);
+        json_pointer::flatten("", *this, result);
+        return result;
+    }
+
+    /// @brief unflatten a previously flattened JSON value
+    /// @sa https://json.nlohmann.me/api/basic_json/unflatten/
+    basic_json unflatten() const
+    {
+        return json_pointer::unflatten(*this);
+    }
+
+    /// @}
+
+    //////////////////////////
+    // JSON Patch functions //
+    //////////////////////////
+
+    /// @name JSON Patch functions
+    /// @{
+
+    /// @brief applies a JSON patch
+    /// @sa https://json.nlohmann.me/api/basic_json/patch/
+    basic_json patch(const basic_json& json_patch) const
+    {
+        // make a working copy to apply the patch to
+        basic_json result = *this;
+
+        // the valid JSON Patch operations
+        enum class patch_operations {add, remove, replace, move, copy, test, invalid};
+
+        const auto get_op = [](const std::string & op)
+        {
+            if (op == "add")
+            {
+                return patch_operations::add;
+            }
+            if (op == "remove")
+            {
+                return patch_operations::remove;
+            }
+            if (op == "replace")
+            {
+                return patch_operations::replace;
+            }
+            if (op == "move")
+            {
+                return patch_operations::move;
+            }
+            if (op == "copy")
+            {
+                return patch_operations::copy;
+            }
+            if (op == "test")
+            {
+                return patch_operations::test;
+            }
+
+            return patch_operations::invalid;
+        };
+
+        // wrapper for "add" operation; add value at ptr
+        const auto operation_add = [&result](json_pointer & ptr, basic_json val)
+        {
+            // adding to the root of the target document means replacing it
+            if (ptr.empty())
+            {
+                result = val;
+                return;
+            }
+
+            // make sure the top element of the pointer exists
+            json_pointer top_pointer = ptr.top();
+            if (top_pointer != ptr)
+            {
+                result.at(top_pointer);
+            }
+
+            // get reference to parent of JSON pointer ptr
+            const auto last_path = ptr.back();
+            ptr.pop_back();
+            basic_json& parent = result[ptr];
+
+            switch (parent.m_type)
+            {
+                case value_t::null:
+                case value_t::object:
+                {
+                    // use operator[] to add value
+                    parent[last_path] = val;
+                    break;
+                }
+
+                case value_t::array:
+                {
+                    if (last_path == "-")
+                    {
+                        // special case: append to back
+                        parent.push_back(val);
+                    }
+                    else
+                    {
+                        const auto idx = json_pointer::array_index(last_path);
+                        if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
+                        {
+                            // avoid undefined behavior
+                            JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent));
+                        }
+
+                        // default case: insert add offset
+                        parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
+                    }
+                    break;
+                }
+
+                // if there exists a parent it cannot be primitive
+                case value_t::string: // LCOV_EXCL_LINE
+                case value_t::boolean: // LCOV_EXCL_LINE
+                case value_t::number_integer: // LCOV_EXCL_LINE
+                case value_t::number_unsigned: // LCOV_EXCL_LINE
+                case value_t::number_float: // LCOV_EXCL_LINE
+                case value_t::binary: // LCOV_EXCL_LINE
+                case value_t::discarded: // LCOV_EXCL_LINE
+                default:            // LCOV_EXCL_LINE
+                    JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
+            }
+        };
+
+        // wrapper for "remove" operation; remove value at ptr
+        const auto operation_remove = [this, &result](json_pointer & ptr)
+        {
+            // get reference to parent of JSON pointer ptr
+            const auto last_path = ptr.back();
+            ptr.pop_back();
+            basic_json& parent = result.at(ptr);
+
+            // remove child
+            if (parent.is_object())
+            {
+                // perform range check
+                auto it = parent.find(last_path);
+                if (JSON_HEDLEY_LIKELY(it != parent.end()))
+                {
+                    parent.erase(it);
+                }
+                else
+                {
+                    JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this));
+                }
+            }
+            else if (parent.is_array())
+            {
+                // note erase performs range check
+                parent.erase(json_pointer::array_index(last_path));
+            }
+        };
+
+        // type check: top level value must be an array
+        if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
+        {
+            JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch));
+        }
+
+        // iterate and apply the operations
+        for (const auto& val : json_patch)
+        {
+            // wrapper to get a value for an operation
+            const auto get_value = [&val](const std::string & op,
+                                          const std::string & member,
+                                          bool string_type) -> basic_json &
+            {
+                // find value
+                auto it = val.m_value.object->find(member);
+
+                // context-sensitive error message
+                const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
+
+                // check if desired value is present
+                if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
+                {
+                    // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+                    JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val));
+                }
+
+                // check if result is of type string
+                if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
+                {
+                    // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
+                    JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val));
+                }
+
+                // no error: return value
+                return it->second;
+            };
+
+            // type check: every element of the array must be an object
+            if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
+            {
+                JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val));
+            }
+
+            // collect mandatory members
+            const auto op = get_value("op", "op", true).template get<std::string>();
+            const auto path = get_value(op, "path", true).template get<std::string>();
+            json_pointer ptr(path);
+
+            switch (get_op(op))
+            {
+                case patch_operations::add:
+                {
+                    operation_add(ptr, get_value("add", "value", false));
+                    break;
+                }
+
+                case patch_operations::remove:
+                {
+                    operation_remove(ptr);
+                    break;
+                }
+
+                case patch_operations::replace:
+                {
+                    // the "path" location must exist - use at()
+                    result.at(ptr) = get_value("replace", "value", false);
+                    break;
+                }
+
+                case patch_operations::move:
+                {
+                    const auto from_path = get_value("move", "from", true).template get<std::string>();
+                    json_pointer from_ptr(from_path);
+
+                    // the "from" location must exist - use at()
+                    basic_json v = result.at(from_ptr);
+
+                    // The move operation is functionally identical to a
+                    // "remove" operation on the "from" location, followed
+                    // immediately by an "add" operation at the target
+                    // location with the value that was just removed.
+                    operation_remove(from_ptr);
+                    operation_add(ptr, v);
+                    break;
+                }
+
+                case patch_operations::copy:
+                {
+                    const auto from_path = get_value("copy", "from", true).template get<std::string>();
+                    const json_pointer from_ptr(from_path);
+
+                    // the "from" location must exist - use at()
+                    basic_json v = result.at(from_ptr);
+
+                    // The copy is functionally identical to an "add"
+                    // operation at the target location using the value
+                    // specified in the "from" member.
+                    operation_add(ptr, v);
+                    break;
+                }
+
+                case patch_operations::test:
+                {
+                    bool success = false;
+                    JSON_TRY
+                    {
+                        // check if "value" matches the one at "path"
+                        // the "path" location must exist - use at()
+                        success = (result.at(ptr) == get_value("test", "value", false));
+                    }
+                    JSON_INTERNAL_CATCH (out_of_range&)
+                    {
+                        // ignore out of range errors: success remains false
+                    }
+
+                    // throw an exception if test fails
+                    if (JSON_HEDLEY_UNLIKELY(!success))
+                    {
+                        JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val));
+                    }
+
+                    break;
+                }
+
+                case patch_operations::invalid:
+                default:
+                {
+                    // op must be "add", "remove", "replace", "move", "copy", or
+                    // "test"
+                    JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val));
+                }
+            }
+        }
+
+        return result;
+    }
+
+    /// @brief creates a diff as a JSON patch
+    /// @sa https://json.nlohmann.me/api/basic_json/diff/
+    JSON_HEDLEY_WARN_UNUSED_RESULT
+    static basic_json diff(const basic_json& source, const basic_json& target,
+                           const std::string& path = "")
+    {
+        // the patch
+        basic_json result(value_t::array);
+
+        // if the values are the same, return empty patch
+        if (source == target)
+        {
+            return result;
+        }
+
+        if (source.type() != target.type())
+        {
+            // different types: replace value
+            result.push_back(
+            {
+                {"op", "replace"}, {"path", path}, {"value", target}
+            });
+            return result;
+        }
+
+        switch (source.type())
+        {
+            case value_t::array:
+            {
+                // first pass: traverse common elements
+                std::size_t i = 0;
+                while (i < source.size() && i < target.size())
+                {
+                    // recursive call to compare array values at index i
+                    auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
+                    result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+                    ++i;
+                }
+
+                // We now reached the end of at least one array
+                // in a second pass, traverse the remaining elements
+
+                // remove my remaining elements
+                const auto end_index = static_cast<difference_type>(result.size());
+                while (i < source.size())
+                {
+                    // add operations in reverse order to avoid invalid
+                    // indices
+                    result.insert(result.begin() + end_index, object(
+                    {
+                        {"op", "remove"},
+                        {"path", path + "/" + std::to_string(i)}
+                    }));
+                    ++i;
+                }
+
+                // add other remaining elements
+                while (i < target.size())
+                {
+                    result.push_back(
+                    {
+                        {"op", "add"},
+                        {"path", path + "/-"},
+                        {"value", target[i]}
+                    });
+                    ++i;
+                }
+
+                break;
+            }
+
+            case value_t::object:
+            {
+                // first pass: traverse this object's elements
+                for (auto it = source.cbegin(); it != source.cend(); ++it)
+                {
+                    // escape the key name to be used in a JSON patch
+                    const auto path_key = path + "/" + detail::escape(it.key());
+
+                    if (target.find(it.key()) != target.end())
+                    {
+                        // recursive call to compare object values at key it
+                        auto temp_diff = diff(it.value(), target[it.key()], path_key);
+                        result.insert(result.end(), temp_diff.begin(), temp_diff.end());
+                    }
+                    else
+                    {
+                        // found a key that is not in o -> remove it
+                        result.push_back(object(
+                        {
+                            {"op", "remove"}, {"path", path_key}
+                        }));
+                    }
+                }
+
+                // second pass: traverse other object's elements
+                for (auto it = target.cbegin(); it != target.cend(); ++it)
+                {
+                    if (source.find(it.key()) == source.end())
+                    {
+                        // found a key that is not in this -> add it
+                        const auto path_key = path + "/" + detail::escape(it.key());
+                        result.push_back(
+                        {
+                            {"op", "add"}, {"path", path_key},
+                            {"value", it.value()}
+                        });
+                    }
+                }
+
+                break;
+            }
+
+            case value_t::null:
+            case value_t::string:
+            case value_t::boolean:
+            case value_t::number_integer:
+            case value_t::number_unsigned:
+            case value_t::number_float:
+            case value_t::binary:
+            case value_t::discarded:
+            default:
+            {
+                // both primitive type: replace value
+                result.push_back(
+                {
+                    {"op", "replace"}, {"path", path}, {"value", target}
+                });
+                break;
+            }
+        }
+
+        return result;
+    }
+
+    /// @}
+
+    ////////////////////////////////
+    // JSON Merge Patch functions //
+    ////////////////////////////////
+
+    /// @name JSON Merge Patch functions
+    /// @{
+
+    /// @brief applies a JSON Merge Patch
+    /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/
+    void merge_patch(const basic_json& apply_patch)
+    {
+        if (apply_patch.is_object())
+        {
+            if (!is_object())
+            {
+                *this = object();
+            }
+            for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
+            {
+                if (it.value().is_null())
+                {
+                    erase(it.key());
+                }
+                else
+                {
+                    operator[](it.key()).merge_patch(it.value());
+                }
+            }
+        }
+        else
+        {
+            *this = apply_patch;
+        }
+    }
+
+    /// @}
+};
+
+/// @brief user-defined to_string function for JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/to_string/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
+{
+    return j.dump();
+}
+
+} // namespace nlohmann
+
+///////////////////////
+// nonmember support //
+///////////////////////
+
+namespace std // NOLINT(cert-dcl58-cpp)
+{
+
+/// @brief hash value for JSON objects
+/// @sa https://json.nlohmann.me/api/basic_json/std_hash/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL>
+{
+    std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const
+    {
+        return nlohmann::detail::hash(j);
+    }
+};
+
+// specialization for std::less<value_t>
+template<>
+struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679
+{
+    /*!
+    @brief compare two value_t enum values
+    @since version 3.0.0
+    */
+    bool operator()(nlohmann::detail::value_t lhs,
+                    nlohmann::detail::value_t rhs) const noexcept
+    {
+        return nlohmann::detail::operator<(lhs, rhs);
+    }
+};
+
+// C++20 prohibit function specialization in the std namespace.
+#ifndef JSON_HAS_CPP_20
+
+/// @brief exchanges the values of two JSON objects
+/// @sa https://json.nlohmann.me/api/basic_json/std_swap/
+NLOHMANN_BASIC_JSON_TPL_DECLARATION
+inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept(  // NOLINT(readability-inconsistent-declaration-parameter-name)
+    is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value&&                          // NOLINT(misc-redundant-expression)
+    is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value)
+{
+    j1.swap(j2);
+}
+
+#endif
+
+} // namespace std
+
+/// @brief user-defined string literal for JSON values
+/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
+JSON_HEDLEY_NON_NULL(1)
+inline nlohmann::json operator "" _json(const char* s, std::size_t n)
+{
+    return nlohmann::json::parse(s, s + n);
+}
+
+/// @brief user-defined string literal for JSON pointer
+/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
+JSON_HEDLEY_NON_NULL(1)
+inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
+{
+    return nlohmann::json::json_pointer(std::string(s, n));
+}
+
+// #include <nlohmann/detail/macro_unscope.hpp>
+
+
+// restore clang diagnostic settings
+#if defined(__clang__)
+    #pragma clang diagnostic pop
+#endif
+
+// clean up
+#undef JSON_ASSERT
+#undef JSON_INTERNAL_CATCH
+#undef JSON_CATCH
+#undef JSON_THROW
+#undef JSON_TRY
+#undef JSON_PRIVATE_UNLESS_TESTED
+#undef JSON_HAS_CPP_11
+#undef JSON_HAS_CPP_14
+#undef JSON_HAS_CPP_17
+#undef JSON_HAS_CPP_20
+#undef JSON_HAS_FILESYSTEM
+#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM
+#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
+#undef NLOHMANN_BASIC_JSON_TPL
+#undef JSON_EXPLICIT
+#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL
+
+// #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
+
+
+#undef JSON_HEDLEY_ALWAYS_INLINE
+#undef JSON_HEDLEY_ARM_VERSION
+#undef JSON_HEDLEY_ARM_VERSION_CHECK
+#undef JSON_HEDLEY_ARRAY_PARAM
+#undef JSON_HEDLEY_ASSUME
+#undef JSON_HEDLEY_BEGIN_C_DECLS
+#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_BUILTIN
+#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_CLANG_HAS_EXTENSION
+#undef JSON_HEDLEY_CLANG_HAS_FEATURE
+#undef JSON_HEDLEY_CLANG_HAS_WARNING
+#undef JSON_HEDLEY_COMPCERT_VERSION
+#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
+#undef JSON_HEDLEY_CONCAT
+#undef JSON_HEDLEY_CONCAT3
+#undef JSON_HEDLEY_CONCAT3_EX
+#undef JSON_HEDLEY_CONCAT_EX
+#undef JSON_HEDLEY_CONST
+#undef JSON_HEDLEY_CONSTEXPR
+#undef JSON_HEDLEY_CONST_CAST
+#undef JSON_HEDLEY_CPP_CAST
+#undef JSON_HEDLEY_CRAY_VERSION
+#undef JSON_HEDLEY_CRAY_VERSION_CHECK
+#undef JSON_HEDLEY_C_DECL
+#undef JSON_HEDLEY_DEPRECATED
+#undef JSON_HEDLEY_DEPRECATED_FOR
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
+#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION
+#undef JSON_HEDLEY_DIAGNOSTIC_POP
+#undef JSON_HEDLEY_DIAGNOSTIC_PUSH
+#undef JSON_HEDLEY_DMC_VERSION
+#undef JSON_HEDLEY_DMC_VERSION_CHECK
+#undef JSON_HEDLEY_EMPTY_BASES
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION
+#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
+#undef JSON_HEDLEY_END_C_DECLS
+#undef JSON_HEDLEY_FLAGS
+#undef JSON_HEDLEY_FLAGS_CAST
+#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_BUILTIN
+#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GCC_HAS_EXTENSION
+#undef JSON_HEDLEY_GCC_HAS_FEATURE
+#undef JSON_HEDLEY_GCC_HAS_WARNING
+#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
+#undef JSON_HEDLEY_GCC_VERSION
+#undef JSON_HEDLEY_GCC_VERSION_CHECK
+#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_BUILTIN
+#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_GNUC_HAS_EXTENSION
+#undef JSON_HEDLEY_GNUC_HAS_FEATURE
+#undef JSON_HEDLEY_GNUC_HAS_WARNING
+#undef JSON_HEDLEY_GNUC_VERSION
+#undef JSON_HEDLEY_GNUC_VERSION_CHECK
+#undef JSON_HEDLEY_HAS_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_BUILTIN
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
+#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
+#undef JSON_HEDLEY_HAS_EXTENSION
+#undef JSON_HEDLEY_HAS_FEATURE
+#undef JSON_HEDLEY_HAS_WARNING
+#undef JSON_HEDLEY_IAR_VERSION
+#undef JSON_HEDLEY_IAR_VERSION_CHECK
+#undef JSON_HEDLEY_IBM_VERSION
+#undef JSON_HEDLEY_IBM_VERSION_CHECK
+#undef JSON_HEDLEY_IMPORT
+#undef JSON_HEDLEY_INLINE
+#undef JSON_HEDLEY_INTEL_CL_VERSION
+#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK
+#undef JSON_HEDLEY_INTEL_VERSION
+#undef JSON_HEDLEY_INTEL_VERSION_CHECK
+#undef JSON_HEDLEY_IS_CONSTANT
+#undef JSON_HEDLEY_IS_CONSTEXPR_
+#undef JSON_HEDLEY_LIKELY
+#undef JSON_HEDLEY_MALLOC
+#undef JSON_HEDLEY_MCST_LCC_VERSION
+#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK
+#undef JSON_HEDLEY_MESSAGE
+#undef JSON_HEDLEY_MSVC_VERSION
+#undef JSON_HEDLEY_MSVC_VERSION_CHECK
+#undef JSON_HEDLEY_NEVER_INLINE
+#undef JSON_HEDLEY_NON_NULL
+#undef JSON_HEDLEY_NO_ESCAPE
+#undef JSON_HEDLEY_NO_RETURN
+#undef JSON_HEDLEY_NO_THROW
+#undef JSON_HEDLEY_NULL
+#undef JSON_HEDLEY_PELLES_VERSION
+#undef JSON_HEDLEY_PELLES_VERSION_CHECK
+#undef JSON_HEDLEY_PGI_VERSION
+#undef JSON_HEDLEY_PGI_VERSION_CHECK
+#undef JSON_HEDLEY_PREDICT
+#undef JSON_HEDLEY_PRINTF_FORMAT
+#undef JSON_HEDLEY_PRIVATE
+#undef JSON_HEDLEY_PUBLIC
+#undef JSON_HEDLEY_PURE
+#undef JSON_HEDLEY_REINTERPRET_CAST
+#undef JSON_HEDLEY_REQUIRE
+#undef JSON_HEDLEY_REQUIRE_CONSTEXPR
+#undef JSON_HEDLEY_REQUIRE_MSG
+#undef JSON_HEDLEY_RESTRICT
+#undef JSON_HEDLEY_RETURNS_NON_NULL
+#undef JSON_HEDLEY_SENTINEL
+#undef JSON_HEDLEY_STATIC_ASSERT
+#undef JSON_HEDLEY_STATIC_CAST
+#undef JSON_HEDLEY_STRINGIFY
+#undef JSON_HEDLEY_STRINGIFY_EX
+#undef JSON_HEDLEY_SUNPRO_VERSION
+#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
+#undef JSON_HEDLEY_TINYC_VERSION
+#undef JSON_HEDLEY_TINYC_VERSION_CHECK
+#undef JSON_HEDLEY_TI_ARMCL_VERSION
+#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL2000_VERSION
+#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL430_VERSION
+#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL6X_VERSION
+#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CL7X_VERSION
+#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
+#undef JSON_HEDLEY_TI_CLPRU_VERSION
+#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
+#undef JSON_HEDLEY_TI_VERSION
+#undef JSON_HEDLEY_TI_VERSION_CHECK
+#undef JSON_HEDLEY_UNAVAILABLE
+#undef JSON_HEDLEY_UNLIKELY
+#undef JSON_HEDLEY_UNPREDICTABLE
+#undef JSON_HEDLEY_UNREACHABLE
+#undef JSON_HEDLEY_UNREACHABLE_RETURN
+#undef JSON_HEDLEY_VERSION
+#undef JSON_HEDLEY_VERSION_DECODE_MAJOR
+#undef JSON_HEDLEY_VERSION_DECODE_MINOR
+#undef JSON_HEDLEY_VERSION_DECODE_REVISION
+#undef JSON_HEDLEY_VERSION_ENCODE
+#undef JSON_HEDLEY_WARNING
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT
+#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
+#undef JSON_HEDLEY_FALL_THROUGH
+
+
+
+#endif  // INCLUDE_NLOHMANN_JSON_HPP_
index 9fd13005a2bcfee426a17f7271775b4181aedbf7..01babf7da37b00702baff59ecac0d65a2d95c194 100644 (file)
@@ -3,7 +3,7 @@
 SUBDIRS =
 
 if BUILD_TESTS
-SUBDIRS += . utils unit regression stress destructive perf
+SUBDIRS += . utils meta unit regression stress destructive perf
 if HAVE_PGREP
 check-am:
        $(top_srcdir)/tests/utils/warn_processes.sh $(PGREP)
@@ -15,8 +15,8 @@ else
 endif
 
 
-dist_noinst_SCRIPTS = run.sh fast_regression long_regression root_regression root_destructive_tests perf_regression
-EXTRA_DIST = run.sh fast_regression long_regression root_regression README root_destructive_tests perf_regression
+dist_noinst_SCRIPTS = run.sh long_regression root_regression
+EXTRA_DIST = run.sh long_regression root_regression README
 
 all-local:
        @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
index ddd6b0225044651a1e80adc479c2f117ed1c2a1a..504f387bbe9ffebb611a9064a22c52533d43a3e0 100644 (file)
@@ -3,6 +3,12 @@
 noinst_SCRIPTS = metadata-regeneration
 EXTRA_DIST = metadata-regeneration
 
+LOG_DRIVER_FLAGS = --merge --post-script $(top_srcdir)/tests/utils/warn_processes.sh
+LOG_DRIVER = env PGREP='$(PGREP)' AM_TAP_AWK='$(AWK)' $(SHELL) \
+       $(top_srcdir)/tests/utils/tap-driver.sh
+
+TESTS = metadata-regeneration
+
 all-local:
        @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
                for script in $(EXTRA_DIST); do \
index 449dc05be7749d4ecc0b1360b6a9e7f8153945c2..dcae6bce0dfb901f318bd26bdc8012f0e7d51cc3 100755 (executable)
 
 TEST_DESC="Metadata regeneration after date change"
 
-CURDIR=$(dirname $0)/
+CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/..
 NUM_TESTS=44
 SESSION_NAME="regen"
 KERNEL_EVENT_NAME="lttng_test_filter_event"
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.metadata_regen_after_data_change.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.metadata_regen_after_data_change.XXXXXX)
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
@@ -31,7 +31,7 @@ DATE1="1970-02-02"
 DATE2="1980-02-02"
 HOUR="05:30"
 
-source $TESTDIR/utils/utils.sh
+source "$TESTDIR/utils/utils.sh"
 
 # MUST set TESTDIR before calling those functions
 plan_tests $NUM_TESTS
@@ -46,7 +46,7 @@ function validate_trace_date
        local test_date=$1
        local trace_path=$2
 
-       res=$($BABELTRACE_BIN --clock-date $trace_path 2>/dev/null | head -1 | grep $test_date)
+       res=$($BABELTRACE_BIN --clock-date "$trace_path" 2>/dev/null | head -1 | grep $test_date)
        if [ $? -eq 0 ]; then
                pass "Validate trace at date $test_date"
                ret=0
@@ -62,17 +62,17 @@ function test_kernel_local ()
 {
        diag "Test kernel local with metadata regeneration"
        date "+%Y-%m-%d %H:%M" -s "$DATE1 $HOUR" >/dev/null
-       create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+       create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
        lttng_enable_kernel_event $SESSION_NAME $KERNEL_EVENT_NAME
        start_lttng_tracing_ok $SESSION_NAME
        echo -n "100" > /proc/lttng-test-filter-event
        stop_lttng_tracing_ok $SESSION_NAME
-       validate_trace_date $DATE1 $TRACE_PATH
+       validate_trace_date $DATE1 "$TRACE_PATH"
        start_lttng_tracing_ok $SESSION_NAME
        date "+%Y-%m-%d %H:%M" -s "$DATE2 $HOUR" >/dev/null
        regenerate_metadata_ok $SESSION_NAME
        stop_lttng_tracing_ok $SESSION_NAME
-       validate_trace_date $DATE2 $TRACE_PATH
+       validate_trace_date $DATE2 "$TRACE_PATH"
        if [ $? -eq 0 ]; then
                # Only delete if successful
                rm -rf $TRACE_PATH
@@ -100,15 +100,18 @@ function test_kernel_streaming ()
                # Only delete if successful
                rm -rf $TRACE_PATH
        else
-               break
+               return
        fi
        destroy_lttng_session_ok $SESSION_NAME
 }
 
 function test_ust_local ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first
+       local file_sync_before_last
+
+       file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test UST local with metadata regeneration"
        date "+%Y-%m-%d %H:%M" -s "$DATE1 $HOUR" >/dev/null
@@ -116,17 +119,17 @@ function test_ust_local ()
        enable_ust_lttng_event_ok $SESSION_NAME $UST_EVENT_NAME
 
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT \
-               --sync-after-first-event ${file_sync_after_first} \
-               --sync-before-last-event ${file_sync_before_last} > /dev/null 2>&1 &
+               --sync-after-first-event "${file_sync_after_first}" \
+               --sync-before-last-event "${file_sync_before_last}" > /dev/null 2>&1 &
 
        start_lttng_tracing_ok $SESSION_NAME
 
-       touch ${file_sync_before_last}
+       touch "${file_sync_before_last}"
        # Wait for the applications started in background
        wait
 
        stop_lttng_tracing_ok $SESSION_NAME
-       validate_trace_date $DATE1 $TRACE_PATH
+       validate_trace_date $DATE1 "$TRACE_PATH"
 
        start_lttng_tracing_ok $SESSION_NAME
        date "+%Y-%m-%d %H:%M" -s "$DATE2 $HOUR" >/dev/null
@@ -134,19 +137,22 @@ function test_ust_local ()
 
        stop_lttng_tracing_ok $SESSION_NAME
        destroy_lttng_session_ok $SESSION_NAME
-       validate_trace_date $DATE2 $TRACE_PATH
+       validate_trace_date $DATE2 "$TRACE_PATH"
        if [ $? -eq 0 ]; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "$TRACE_PATH"
        fi
-       rm -f ${file_sync_after_first}
-       rm -f ${file_sync_before_last}
+       rm -f "${file_sync_after_first}"
+       rm -f "${file_sync_before_last}"
 }
 
 function test_ust_streaming ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first
+       local file_sync_before_last
+
+       file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test UST streaming with metadata regeneration"
        date "+%Y-%m-%d %H:%M" -s "$DATE1 $HOUR" >/dev/null
@@ -154,12 +160,12 @@ function test_ust_streaming ()
        enable_ust_lttng_event_ok $SESSION_NAME $UST_EVENT_NAME
 
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT \
-               --sync-after-first-event ${file_sync_after_first} \
-               --sync-before-last-event ${file_sync_before_last} > /dev/null 2>&1 &
+               --sync-after-first-event "${file_sync_after_first}" \
+               --sync-before-last-event "${file_sync_before_last}" > /dev/null 2>&1 &
 
        start_lttng_tracing_ok $SESSION_NAME
 
-       touch ${file_sync_before_last}
+       touch "${file_sync_before_last}"
 
        # Wait for the applications started in background
        wait
@@ -177,26 +183,22 @@ function test_ust_streaming ()
        validate_trace_date $DATE2 $TRACE_PATH/$HOSTNAME/$SESSION_NAME*
        if [ $? -eq 0 ]; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "$TRACE_PATH"
        fi
-       rm -f ${file_sync_after_first}
-       rm -f ${file_sync_before_last}
+       rm -f "${file_sync_after_first}"
+       rm -f "${file_sync_before_last}"
 }
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
 if ! destructive_tests_enabled ; then
-       echo 'You need to set the LTTNG_ENABLE_DESTRUCTIVE_TESTS to "will-break-my-system" as argument to run this test'
-       echo 'Moreover, please make sure that ntp is not running while executing this test'
+       echo 'Please make sure that ntp is not running while executing this test'
+       skip 0 "You need to set the LTTNG_ENABLE_DESTRUCTIVE_TESTS environment variable to \"will-break-my-system\" to run this test" $NUM_TESTS
+
        exit 0
 fi
 
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test $NUM_TESTS "Skipping all tests." ||
 {
+       original_date=$(date)
        start_lttng_relayd "-o $TRACE_PATH"
        start_lttng_sessiond
 
@@ -210,4 +212,11 @@ skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
 
        stop_lttng_sessiond
        stop_lttng_relayd
+
+       # This set of test sets the date in the past which causes
+       # `make` to panic when it sees files created in the "future"
+       # while running the "check" target. Obviously this doesn't set
+       # the correct date, but at least its close enough to allow the
+       # test suite to continue.
+       date --set "$original_date"
 }
diff --git a/tests/fast_regression b/tests/fast_regression
deleted file mode 100644 (file)
index 5052268..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-regression/tools/filtering/test_invalid_filter
-regression/tools/filtering/test_unsupported_op
-regression/tools/filtering/test_valid_filter
-regression/tools/streaming/test_ust
-regression/tools/health/test_thread_ok
-regression/tools/live/test_ust
-regression/tools/live/test_ust_tracefile_count
-regression/tools/live/test_lttng_ust
-regression/tools/tracefile-limits/test_tracefile_count
-regression/tools/tracefile-limits/test_tracefile_size
-regression/tools/tracker/test_event_tracker
-regression/tools/exclusion/test_exclusion
-regression/tools/snapshots/test_ust_fast
-regression/tools/snapshots/test_ust_streaming
-regression/tools/save-load/test_save
-regression/tools/save-load/test_load
-regression/tools/save-load/test_autoload
-regression/tools/mi/test_mi
-regression/tools/wildcard/test_event_wildcard
-regression/tools/crash/test_crash
-regression/tools/regen-metadata/test_ust
-regression/tools/regen-statedump/test_ust
-regression/ust/before-after/test_before_after
-regression/ust/buffers-pid/test_buffers_pid
-regression/ust/multi-session/test_multi_session
-regression/ust/multi-lib/test_multi_lib
-regression/ust/nprocesses/test_nprocesses
-regression/ust/overlap/test_overlap
-regression/ust/java-jul/test_java_jul
-regression/ust/java-log4j/test_java_log4j
-regression/ust/python-logging/test_python_logging
-regression/ust/getcpu-override/test_getcpu_override
-regression/ust/clock-override/test_clock_override
-regression/ust/rotation-destroy-flush/test_rotation_destroy_flush
-regression/ust/blocking/test_blocking
-regression/ust/test_event_basic
-regression/ust/test_event_tracef
-regression/ust/test_event_perf
index 162117640c989cb1cbf4eeb9b909c362b487d551..3601b4d580c675b8e02703a0fae0eb9fca2dceff 100644 (file)
@@ -1,19 +1,5 @@
-regression/tools/filtering/test_invalid_filter
-regression/tools/filtering/test_unsupported_op
-regression/tools/filtering/test_valid_filter
 regression/tools/health/test_thread_stall
 regression/tools/health/test_tp_fail
-regression/tools/streaming/test_ust
 regression/tools/snapshots/test_ust_long
-regression/tools/tracefile-limits/test_tracefile_count
-regression/tools/tracefile-limits/test_tracefile_size
-regression/tools/wildcard/test_event_wildcard
-regression/ust/before-after/test_before_after
-regression/ust/buffers-pid/test_buffers_pid
 regression/ust/high-throughput/test_high_throughput
 regression/ust/low-throughput/test_low_throughput
-regression/ust/multi-session/test_multi_session
-regression/ust/nprocesses/test_nprocesses
-regression/ust/overlap/test_overlap
-regression/ust/test_event_basic
-regression/ust/test_event_tracef
diff --git a/tests/meta/Makefile.am b/tests/meta/Makefile.am
new file mode 100644 (file)
index 0000000..0514ecc
--- /dev/null
@@ -0,0 +1,27 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+LOG_DRIVER_FLAGS = --merge
+LOG_DRIVER = env PGREP='$(PGREP)' AM_TAP_AWK='$(AWK)' $(SHELL) \
+               $(top_srcdir)/tests/utils/tap-driver.sh
+
+TESTS =
+
+if HAVE_SHELLCHECK
+TESTS += test_shellcheck
+endif
+
+EXTRA_DIST = $(TESTS)
+
+all-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       cp -f $(srcdir)/$$script $(builddir); \
+               done; \
+       fi
+
+clean-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       rm -f $(builddir)/$$script; \
+               done; \
+       fi
diff --git a/tests/meta/test_shellcheck b/tests/meta/test_shellcheck
new file mode 100755 (executable)
index 0000000..29a3976
--- /dev/null
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Copyright (c) 2023 Olivier Dion <odion@efficios.com>
+
+# Augment this list incrementally when a shell script passes shellcheck.
+#
+# All file must be relative to the test directory.
+files=(
+    meta/test_shellcheck
+    regression/tools/notification/util_event_generator.sh
+    run.sh
+)
+
+TESTDIR=$(dirname "$0")/..
+
+# shellcheck source=../utils/tap/tap.sh
+source "$TESTDIR/utils/tap/tap.sh"
+
+function shellcheck_ok() {
+    shellcheck --external-sources "$1"
+    ok $? "Checking $1"
+}
+
+plan_tests "${#files[@]}"
+
+for f in "${files[@]}";
+do
+    shellcheck_ok "$TESTDIR/$f"
+done
index aa1c964c399180ce95dc769ce5f1cfa404bc7536..7a8b549f1b59b6e34a5572dff34ab13eb70b6095 100644 (file)
@@ -6,12 +6,11 @@
  */
 
 #include <errno.h>
-#include <stdio.h>
-#include <string.h>
-
 #include <linux/perf_event.h>
 #include <perfmon/perf_event.h>
 #include <perfmon/pfmlib_perf_event.h>
+#include <stdio.h>
+#include <string.h>
 
 int main(int argc, char **argv)
 {
@@ -25,14 +24,16 @@ int main(int argc, char **argv)
        struct perf_event_attr attr;
 
        if (argc != 2) {
-               fprintf(stderr, "Usage: %s <pmu counter to find>\n"
-                               "ex: %s UNHALTED_REFERENCE_CYCLES\n"
-                               "Returns the event raw number if found and actionable with"
-                               "return code 0.\n"
-                               "If not found returns 1,"
-                               "If not actionable return 2,"
-                               "on error returns 255\n",
-                               argv[0], argv[0]);
+               fprintf(stderr,
+                       "Usage: %s <pmu counter to find>\n"
+                       "ex: %s UNHALTED_REFERENCE_CYCLES\n"
+                       "Returns the event raw number if found and actionable with"
+                       "return code 0.\n"
+                       "If not found returns 1,"
+                       "If not actionable return 2,"
+                       "on error returns 255\n",
+                       argv[0],
+                       argv[0]);
                ret = -1;
                goto end;
        }
@@ -54,18 +55,15 @@ int main(int argc, char **argv)
 
        ret = pfm_initialize();
        if (ret != PFM_SUCCESS) {
-               fprintf(stderr, "Failed to initialise libpfm: %s",
-                               pfm_strerror(ret));
+               fprintf(stderr, "Failed to initialise libpfm: %s", pfm_strerror(ret));
                ret = 255;
                goto end;
        }
 
-       ret = pfm_get_os_event_encoding(argv[1],
-                       PFM_PLM0 | PFM_PLM1 | PFM_PLM2 | PFM_PLM3,
-                       PFM_OS_PERF_EVENT, &pencoder);
+       ret = pfm_get_os_event_encoding(
+               argv[1], PFM_PLM0 | PFM_PLM1 | PFM_PLM2 | PFM_PLM3, PFM_OS_PERF_EVENT, &pencoder);
        if (ret != PFM_SUCCESS) {
-               fprintf(stderr, "libpfm: error pfm_get_os_event_encoding: %s\n",
-                               pfm_strerror(ret));
+               fprintf(stderr, "libpfm: error pfm_get_os_event_encoding: %s\n", pfm_strerror(ret));
                ret = 1;
                goto end;
        }
@@ -93,8 +91,7 @@ int main(int argc, char **argv)
        /* perf_event_open is provided by perfmon/perf_event.h. */
        fd = perf_event_open(pencoder.attr, 0, -1, -1, 0);
        if (fd == -1) {
-               fprintf(stderr, "perf: error perf_event_open: %d: %s\n", errno,
-                               strerror(errno));
+               fprintf(stderr, "perf: error perf_event_open: %d: %s\n", errno, strerror(errno));
                ret = 2;
                goto end;
        }
index f293ccd71e5ece6f3821cdc04513f7cb882df76c..00cdebc5567d1cccdc0ee9ddd13022040f382fc2 100644 (file)
@@ -64,7 +64,7 @@ function test_ust_raw()
                return
        fi
 
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
@@ -114,7 +114,7 @@ function test_kernel_raw()
                return
        fi
 
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
@@ -137,12 +137,6 @@ function test_kernel_raw()
        rm -rf $TRACE_PATH
 }
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
 # MUST set TESTDIR before calling those functions
 plan_tests $NUM_TESTS
 
@@ -154,7 +148,7 @@ have_libpfm
 
 test_ust_raw
 
-skip $isroot "Root access is needed for kernel testing, skipping." 9 ||
+check_skip_kernel_test 9 ||
 {
        modprobe lttng-test
        test_kernel_raw
diff --git a/tests/perf_regression b/tests/perf_regression
deleted file mode 100644 (file)
index c4b9b86..0000000
+++ /dev/null
@@ -1 +0,0 @@
-perf/test_perf_raw
index 477ee9735a5545c6cf7bfc96ab03c5c1f8571c5e..ca3fb2d52d281968f9ffb9daeca2e47035c4bb53 100644 (file)
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-SUBDIRS = tools kernel ust
+SUBDIRS = tools
 
 LOG_DRIVER_FLAGS = --merge --post-script $(top_srcdir)/tests/utils/warn_processes.sh
 LOG_DRIVER = env PGREP='$(PGREP)' AM_TAP_AWK='$(AWK)' $(SHELL) \
@@ -57,13 +57,23 @@ TESTS = tools/base-path/test_ust \
        tools/working-directory/test_relayd_working_directory \
        tools/clear/test_ust \
        tools/clear/test_kernel \
+       tools/clear/test_live_hang.py \
        tools/tracker/test_event_tracker \
        tools/trigger/start-stop/test_start_stop \
        tools/trigger/test_add_trigger_cli \
        tools/trigger/test_list_triggers_cli \
        tools/trigger/test_remove_trigger_cli \
        tools/trigger/name/test_trigger_name_backwards_compat \
-       tools/trigger/hidden/test_hidden_trigger
+       tools/trigger/hidden/test_hidden_trigger \
+       tools/context/test_ust.py \
+       tools/client/test_session_commands.py \
+       tools/client/test_event_rule_listing.py \
+       tools/client/test_bug1373_events_differ_only_by_loglevel
+
+# Only build kernel tests on Linux.
+if IS_LINUX
+SUBDIRS += kernel
+endif # IS_LINUX
 
 if HAVE_LIBLTTNG_UST_CTL
 SUBDIRS += ust
@@ -81,6 +91,10 @@ TESTS += ust/before-after/test_before_after \
        ust/blocking/test_blocking \
        ust/multi-lib/test_multi_lib \
        ust/rotation-destroy-flush/test_rotation_destroy_flush \
+       ust/ust-constructor/test_ust_constructor_c_dynamic.py \
+       ust/ust-constructor/test_ust_constructor_c_static.py \
+       ust/ust-constructor/test_ust_constructor_cpp_dynamic.py \
+       ust/ust-constructor/test_ust_constructor_cpp_static.py \
        tools/metadata/test_ust \
        tools/relayd-grouping/test_ust \
        tools/trigger/rate-policy/test_ust_rate_policy
index a257eb07a778c805b790ea9b2ccafb202a62d4b2..4fef90d36b18766553458b8211f4e1316750b65d 100644 (file)
@@ -19,7 +19,9 @@ EXTRA_DIST = test_all_events \
 noinst_PROGRAMS = select_poll_epoll
 select_poll_epoll_SOURCES = select_poll_epoll.cpp
 select_poll_epoll_LDADD = $(POPT_LIBS) $(top_builddir)/src/common/libcommon-lgpl.la
-select_poll_epoll_CFLAGS = $(POPT_CFLAGS) -fno-stack-protector -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 $(AM_CFLAGS)
+select_poll_epoll_CPPFLAGS = $(POPT_CFLAGS) $(AM_CPPFLAGS)
+# Disable stack protection, the test overflows the stack to test the poll/epoll syscalls
+select_poll_epoll_CXXFLAGS = -fno-stack-protector $(AM_CXXFLAGS)
 
 all-local:
        @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
index c0b6882172b13d471be9a3496ac80b2692595a67..b6f0210d503d24a03bf9e50235019d4b37c718be 100644 (file)
@@ -5,6 +5,18 @@
  *
  */
 
+/*
+ * This test voluntarily does buffer overflows and stack overruns, disable
+ * source fortification.
+ */
+#ifdef _FORTIFY_SOURCE
+#undef _FORTIFY_SOURCE
+#endif
+
+#include <common/compat/time.hpp>
+#include <common/error.hpp>
+
+#include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
 #include <poll.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/compat/time.hpp>
-#include <common/error.hpp>
-
 #define BUF_SIZE 256
-#define NB_FD 1
-#define MAX_FDS 2047
-#define NR_ITER 1000 /* for stress-tests */
+#define NB_FD   1
+#define MAX_FDS         2047
+#define NR_ITER         1000 /* for stress-tests */
 
-#define MIN_NR_FDS 5 /* the minimum number of open FDs required for the test to run */
+#define MIN_NR_FDS    5 /* the minimum number of open FDs required for the test to run */
 #define BIG_SELECT_FD 1022
 
 #define MSEC_PER_USEC 1000
@@ -47,11 +56,11 @@ static int wait_fd;
 int lttng_opt_quiet, lttng_opt_verbose, lttng_opt_mi;
 
 static void run_working_cases(FILE *validation_output_file);
-static void pselect_invalid_fd(FILE *validation_output_file);
 static void test_ppoll_big(FILE *validation_output_file);
-static void ppoll_fds_buffer_overflow(FILE *validation_output_file);
 static void pselect_invalid_pointer(FILE *validation_output_file);
+static void pselect_invalid_fd(FILE *validation_output_file);
 static void ppoll_fds_ulong_max(FILE *validation_output_file);
+static void ppoll_fds_buffer_overflow(FILE *validation_output_file);
 static void epoll_pwait_invalid_pointer(FILE *validation_output_file);
 static void epoll_pwait_int_max(FILE *validation_output_file);
 static void ppoll_concurrent_write(FILE *validation_output_file);
@@ -64,19 +73,67 @@ const struct test_case {
        test_case_cb run;
        bool produces_validation_info;
        int timeout;
-} test_cases [] =
-{
-       { .run = run_working_cases, .produces_validation_info = true, .timeout = -1 },
-       { .run = run_working_cases, .produces_validation_info = true, .timeout = 1 },
-       { .run = pselect_invalid_fd, .produces_validation_info = false, .timeout = 0 },
-       { .run = test_ppoll_big, .produces_validation_info = false, .timeout = 0 },
-       { .run = ppoll_fds_buffer_overflow, .produces_validation_info = false, .timeout = 0 },
-       { .run = pselect_invalid_pointer, .produces_validation_info = false, .timeout = 0 },
-       { .run = ppoll_fds_ulong_max, .produces_validation_info = false, .timeout = 0 },
-       { .run = epoll_pwait_invalid_pointer, .produces_validation_info = true, .timeout = 0 },
-       { .run = epoll_pwait_int_max, .produces_validation_info = true, .timeout = 0 },
-       { .run = ppoll_concurrent_write, .produces_validation_info = false, .timeout = 0 },
-       { .run = epoll_pwait_concurrent_munmap, .produces_validation_info = true, .timeout = 0 },
+       const char *name;
+       const char *description;
+} test_cases[] = {
+       { .run = run_working_cases,
+         .produces_validation_info = true,
+         .timeout = -1,
+         .name = "working_cases",
+         .description =
+                 "Working cases for select, pselect6, poll, ppoll and epoll, waiting for input" },
+       { .run = run_working_cases,
+         .produces_validation_info = true,
+         .timeout = 1,
+         .name = "working_cases_timeout",
+         .description = "Timeout cases (1ms) for select, pselect6, poll, ppoll and epoll" },
+       { .run = test_ppoll_big,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "ppoll_big",
+         .description = "ppoll with " XSTR(MAX_FDS) " FDs" },
+       { .run = epoll_pwait_invalid_pointer,
+         .produces_validation_info = true,
+         .timeout = 0,
+         .name = "epoll_pwait_invalid_pointer",
+         .description = "epoll_pwait with an invalid pointer, waits for input" },
+       { .run = epoll_pwait_int_max,
+         .produces_validation_info = true,
+         .timeout = 0,
+         .name = "epoll_pwait_int_max",
+         .description = "epoll_pwait with maxevents set to INT_MAX waits for input" },
+       { .run = ppoll_concurrent_write,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "ppoll_concurrent_write",
+         .description =
+                 "ppoll with concurrent updates of the structure from user-space, stress test (3000 iterations) waits for input + timeout 1ms" },
+       { .run = epoll_pwait_concurrent_munmap,
+         .produces_validation_info = true,
+         .timeout = 0,
+         .name = "epoll_pwait_concurrent_munmap",
+         .description =
+                 "epoll_pwait with concurrent munmap of the buffer from user-space, should randomly segfault, run multiple times, waits for input + timeout 1ms" },
+       { .run = pselect_invalid_pointer,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "pselect_invalid_pointer",
+         .description = "pselect with an invalid pointer, waits for input" },
+       { .run = pselect_invalid_fd,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "pselect_invalid_fd",
+         .description = "pselect with an invalid fd" },
+       { .run = ppoll_fds_ulong_max,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "ppoll_fds_ulong_max",
+         .description = "ppoll with ulong_max fds, waits for input" },
+       { .run = ppoll_fds_buffer_overflow,
+         .produces_validation_info = false,
+         .timeout = 0,
+         .name = "ppoll_fds_buffer_overflow",
+         .description = "ppoll buffer overflow, should segfault, waits for input" },
 };
 
 struct ppoll_thread_data {
@@ -85,8 +142,7 @@ struct ppoll_thread_data {
 };
 } /* namespace */
 
-static
-void test_select_big(void)
+static void test_select_big(void)
 {
        fd_set rfds, wfds, exfds;
        struct timeval tv;
@@ -132,8 +188,7 @@ end:
        return;
 }
 
-static
-void test_pselect(void)
+static void test_pselect_generic(long int syscall_id)
 {
        fd_set rfds;
        struct timespec tv;
@@ -147,9 +202,9 @@ void test_pselect(void)
        tv.tv_nsec = timeout * MSEC_PER_NSEC;
 
        if (timeout > 0) {
-               ret = pselect(1, &rfds, NULL, NULL, &tv, NULL);
+               ret = syscall(syscall_id, 1, &rfds, NULL, NULL, &tv, NULL);
        } else {
-               ret = pselect(1, &rfds, NULL, NULL, NULL, NULL);
+               ret = syscall(syscall_id, 1, &rfds, NULL, NULL, NULL, NULL);
        }
 
        if (ret == -1) {
@@ -162,8 +217,12 @@ void test_pselect(void)
        }
 }
 
-static
-void test_select(void)
+static void test_pselect(void)
+{
+       test_pselect_generic(SYS_pselect6);
+}
+
+static void test_select(void)
 {
        fd_set rfds;
        struct timeval tv;
@@ -192,15 +251,14 @@ void test_select(void)
        }
 }
 
-static
-void test_poll(void)
+static void test_poll(void)
 {
        struct pollfd ufds[NB_FD];
        char buf[BUF_SIZE];
        int ret;
 
        ufds[0].fd = wait_fd;
-       ufds[0].events = POLLIN|POLLPRI;
+       ufds[0].events = POLLIN | POLLPRI;
 
        ret = poll(ufds, 1, timeout);
 
@@ -214,8 +272,7 @@ void test_poll(void)
        }
 }
 
-static
-void test_ppoll(void)
+static void test_ppoll_generic(long int syscall_id)
 {
        struct pollfd ufds[NB_FD];
        char buf[BUF_SIZE];
@@ -223,17 +280,16 @@ void test_ppoll(void)
        struct timespec ts;
 
        ufds[0].fd = wait_fd;
-       ufds[0].events = POLLIN|POLLPRI;
+       ufds[0].events = POLLIN | POLLPRI;
 
        if (timeout > 0) {
                ts.tv_sec = 0;
                ts.tv_nsec = timeout * MSEC_PER_NSEC;
-               ret = ppoll(ufds, 1, &ts, NULL);
+               ret = syscall(syscall_id, ufds, 1, &ts, NULL);
        } else {
-               ret = ppoll(ufds, 1, NULL, NULL);
+               ret = syscall(syscall_id, ufds, 1, NULL, NULL);
        }
 
-
        if (ret < 0) {
                PERROR("ppoll");
        } else if (ret > 0) {
@@ -244,8 +300,12 @@ void test_ppoll(void)
        }
 }
 
-static
-void test_ppoll_big(FILE *validation_output_file __attribute__((unused)))
+static void test_ppoll(void)
+{
+       test_ppoll_generic(SYS_ppoll);
+}
+
+static void test_ppoll_big(FILE *validation_output_file __attribute__((unused)))
 {
        struct pollfd ufds[MAX_FDS];
        char buf[BUF_SIZE];
@@ -257,7 +317,7 @@ void test_ppoll_big(FILE *validation_output_file __attribute__((unused)))
                        PERROR("dup");
                }
                ufds[i].fd = fds[i];
-               ufds[i].events = POLLIN|POLLPRI;
+               ufds[i].events = POLLIN | POLLPRI;
        }
 
        ret = ppoll(ufds, MAX_FDS, NULL, NULL);
@@ -281,8 +341,7 @@ void test_ppoll_big(FILE *validation_output_file __attribute__((unused)))
        return;
 }
 
-static
-void test_epoll(FILE *validation_output_file)
+static void test_epoll(FILE *validation_output_file)
 {
        int ret, epollfd;
        char buf[BUF_SIZE];
@@ -294,8 +353,7 @@ void test_epoll(FILE *validation_output_file)
                goto end;
        }
 
-       ret = fprintf(validation_output_file,
-                       ", \"epoll_wait_fd\": %i", epollfd);
+       ret = fprintf(validation_output_file, ", \"epoll_wait_fd\": %i", epollfd);
        if (ret < 0) {
                PERROR("[epoll] Failed to write test validation output");
                goto error;
@@ -333,8 +391,7 @@ end:
        return;
 }
 
-static
-void test_epoll_pwait(FILE *validation_output_file)
+static void test_epoll_pwait(FILE *validation_output_file)
 {
        int ret, epollfd;
        char buf[BUF_SIZE];
@@ -346,8 +403,7 @@ void test_epoll_pwait(FILE *validation_output_file)
                goto end;
        }
 
-       ret = fprintf(validation_output_file,
-                       ", \"epoll_pwait_fd\": %i", epollfd);
+       ret = fprintf(validation_output_file, ", \"epoll_pwait_fd\": %i", epollfd);
        if (ret < 0) {
                PERROR("[epoll_pwait] Failed to write test validation output");
                goto error;
@@ -385,8 +441,7 @@ end:
        return;
 }
 
-static
-void run_working_cases(FILE *validation_output_file)
+static void run_working_cases(FILE *validation_output_file)
 {
        int ret;
        int pipe_fds[2];
@@ -405,12 +460,21 @@ void run_working_cases(FILE *validation_output_file)
                wait_fd = pipe_fds[0];
        }
        test_select();
+#ifdef sys_pselect6_time64
+       test_pselect_time64();
+#else
        test_pselect();
+#endif /* sys_pselect6_time64 */
        test_select_big();
        test_poll();
        test_ppoll();
+#ifdef sys_ppoll_time64
+       test_ppoll_time64();
+#else
+       test_ppoll();
+#endif /* sys_ppoll_time64 */
 
-       ret = fprintf(validation_output_file, "{ \"pid\": %i", getpid());
+       ret = fprintf(validation_output_file, "{\"pid\": %i", getpid());
        if (ret < 0) {
                PERROR("Failed to write pid to test validation file");
                goto end;
@@ -441,65 +505,80 @@ end:
 }
 
 /*
- * Ask for 100 FDs in a buffer for allocated for only 1 FD, should
- * segfault (eventually with a "*** stack smashing detected ***" message).
- * The event should contain an array of 100 FDs filled with garbage.
+ * Ask for ULONG_MAX FDs in a buffer for allocated for only 1 FD, should
+ * cleanly fail with a "Invalid argument".
+ * The event should contain an empty array of FDs and overflow = 1.
  */
-static
-void ppoll_fds_buffer_overflow(
-               FILE *validation_output_file __attribute__((unused)))
+static void generic_ppoll_fds_ulong_max(long int syscall_id)
 {
        struct pollfd ufds[NB_FD];
        char buf[BUF_SIZE];
        int ret;
 
        ufds[0].fd = wait_fd;
-       ufds[0].events = POLLIN|POLLPRI;
-
-       ret = syscall(SYS_ppoll, ufds, 100, NULL, NULL);
+       ufds[0].events = POLLIN | POLLPRI;
 
+       /* ppoll and/or ppoll_time64 are used, depending on platform support. */
+       ret = syscall(syscall_id, ufds, ULONG_MAX, NULL, NULL);
        if (ret < 0) {
-               PERROR("ppoll");
+               /* Expected error. */
        } else if (ret > 0) {
                ret = read(wait_fd, buf, BUF_SIZE);
                if (ret < 0) {
-                       PERROR("[ppoll] read");
+                       PERROR("Failed to read from wait file descriptor");
                }
        }
 }
 
 /*
- * Ask for ULONG_MAX FDs in a buffer for allocated for only 1 FD, should
- * cleanly fail with a "Invalid argument".
- * The event should contain an empty array of FDs and overflow = 1.
+ * Ask for 100 FDs in a buffer for allocated for only 1 FD, should
+ * segfault (eventually with a "*** stack smashing detected ***" message).
+ * The event should contain an array of 100 FDs filled with garbage.
  */
-static
-void ppoll_fds_ulong_max(FILE *validation_output_file __attribute__((unused)))
+static void generic_ppoll_fds_buffer_overflow(long int syscall_id)
 {
        struct pollfd ufds[NB_FD];
        char buf[BUF_SIZE];
        int ret;
 
        ufds[0].fd = wait_fd;
-       ufds[0].events = POLLIN|POLLPRI;
+       ufds[0].events = POLLIN | POLLPRI;
 
-       ret = syscall(SYS_ppoll, ufds, ULONG_MAX, NULL, NULL);
+       /* ppoll and/or ppoll_time64 are used, depending on platform support. */
+       ret = syscall(syscall_id, ufds, 100, NULL, NULL);
        if (ret < 0) {
-               /* Expected error. */
+               PERROR("Failed to wait using ppoll/ppoll_time64");
        } else if (ret > 0) {
                ret = read(wait_fd, buf, BUF_SIZE);
                if (ret < 0) {
-                       PERROR("[ppoll] read");
+                       PERROR("Failed to read from wait file descriptor");
                }
        }
 }
 
+static void ppoll_fds_ulong_max(FILE *validation_output_file __attribute__((unused)))
+{
+#ifdef SYS_ppoll_time64
+       generic_ppoll_fds_ulong_max(SYS_ppoll_time64);
+#else
+       generic_ppoll_fds_ulong_max(SYS_ppoll);
+#endif /* SYS_ppoll_time64 */
+}
+
+static void ppoll_fds_buffer_overflow(FILE *validation_output_file __attribute__((unused)))
+{
+#ifdef SYS_ppoll_time64
+       generic_ppoll_fds_buffer_overflow(SYS_ppoll_time64);
+#else
+       generic_ppoll_fds_buffer_overflow(SYS_ppoll);
+#endif /* SYS_ppoll_time64 */
+}
+
 /*
  * Pass an invalid file descriptor to pselect6(). The syscall should return
  * -EBADF. The recorded event should contain a "ret = -EBADF (-9)".
  */
-static
-void pselect_invalid_fd(FILE *validation_output_file __attribute__((unused)))
+static void generic_invalid_fd(long int syscall_id)
 {
        fd_set rfds;
        int ret;
@@ -511,26 +590,26 @@ void pselect_invalid_fd(FILE *validation_output_file __attribute__((unused)))
         */
        fd = open("/dev/null", O_RDONLY);
        if (fd == -1) {
-               PERROR("open");
+               PERROR("Failed to open /dev/null");
                goto error;
        }
 
        ret = close(fd);
        if (ret == -1) {
-               PERROR("close");
+               PERROR("Failed to close /dev/null file descriptor");
                goto error;
        }
 
        FD_ZERO(&rfds);
        FD_SET(fd, &rfds);
 
-       ret = syscall(SYS_pselect6, fd + 1, &rfds, NULL, NULL, NULL, NULL);
+       ret = syscall(syscall_id, fd + 1, &rfds, NULL, NULL, NULL, NULL);
        if (ret == -1) {
                /* Expected error. */
        } else if (ret) {
                ret = read(wait_fd, buf, BUF_SIZE);
                if (ret < 0) {
-                       PERROR("[pselect] read");
+                       PERROR("Failed to read from wait file descriptor");
                }
        }
 error:
@@ -541,9 +620,7 @@ error:
  * Invalid pointer as writefds, should output a ppoll event
  * with 0 FDs.
  */
-static
-void pselect_invalid_pointer(
-               FILE *validation_output_file __attribute__((unused)))
+static void generic_invalid_pointer(int syscall_id)
 {
        fd_set rfds;
        int ret;
@@ -553,24 +630,44 @@ void pselect_invalid_pointer(
        FD_ZERO(&rfds);
        FD_SET(wait_fd, &rfds);
 
-       ret = syscall(SYS_pselect6, 1, &rfds, (fd_set *) invalid, NULL, NULL,
-                       NULL);
+       ret = syscall(syscall_id, 1, &rfds, (fd_set *) invalid, NULL, NULL, NULL);
        if (ret == -1) {
                /* Expected error. */
        } else if (ret) {
                ret = read(wait_fd, buf, BUF_SIZE);
                if (ret < 0) {
-                       PERROR("[pselect] read");
+                       PERROR("Failed to read from wait file descriptor");
                }
        }
 }
 
+static void pselect_invalid_fd(FILE *validation_output_file __attribute__((unused)))
+{
+#ifdef SYS_pselect6_time64
+       generic_invalid_fd(SYS_pselect6_time64);
+#else
+       generic_invalid_fd(SYS_pselect6);
+#endif /* SYS_pselect6_time64 */
+}
+
+/*
+ * Invalid pointer as writefds, should output a ppoll event
+ * with 0 FDs.
+ */
+static void pselect_invalid_pointer(FILE *validation_output_file __attribute__((unused)))
+{
+#ifdef SYS_pselect6_time64
+       generic_invalid_pointer(SYS_pselect6_time64);
+#else
+       generic_invalid_pointer(SYS_pselect6);
+#endif /* SYS_pselect6_time64 */
+}
+
 /*
  * Pass an invalid pointer to epoll_pwait, should fail with
  * "Bad address", the event returns 0 FDs.
  */
-static
-void epoll_pwait_invalid_pointer(FILE *validation_output_file)
+static void epoll_pwait_invalid_pointer(FILE *validation_output_file)
 {
        int ret, epollfd;
        char buf[BUF_SIZE];
@@ -583,9 +680,7 @@ void epoll_pwait_invalid_pointer(FILE *validation_output_file)
                goto end;
        }
 
-       ret = fprintf(validation_output_file,
-                       "{ \"epollfd\": %i, \"pid\": %i }", epollfd,
-                       getpid());
+       ret = fprintf(validation_output_file, "{\"epollfd\": %i, \"pid\": %i }", epollfd, getpid());
        if (ret < 0) {
                PERROR("[epoll_pwait] Failed to write test validation output");
                goto error;
@@ -599,8 +694,7 @@ void epoll_pwait_invalid_pointer(FILE *validation_output_file)
                goto error;
        }
 
-       ret = syscall(SYS_epoll_pwait, epollfd,
-                       (struct epoll_event *) invalid, 1, -1, NULL);
+       ret = syscall(SYS_epoll_pwait, epollfd, (struct epoll_event *) invalid, 1, -1, NULL);
 
        if (ret == 1) {
                ret = read(wait_fd, buf, BUF_SIZE);
@@ -624,8 +718,7 @@ end:
  * Set maxevents to INT_MAX, should output "Invalid argument"
  * The event should return an empty array.
  */
-static
-void epoll_pwait_int_max(FILE *validation_output_file)
+static void epoll_pwait_int_max(FILE *validation_output_file)
 {
        int ret, epollfd;
        char buf[BUF_SIZE];
@@ -637,9 +730,7 @@ void epoll_pwait_int_max(FILE *validation_output_file)
                goto end;
        }
 
-       ret = fprintf(validation_output_file,
-                       "{ \"epollfd\": %i, \"pid\": %i }", epollfd,
-                       getpid());
+       ret = fprintf(validation_output_file, "{\"epollfd\": %i, \"pid\": %i }", epollfd, getpid());
        if (ret < 0) {
                PERROR("[epoll_pwait] Failed to write test validation output");
                goto error;
@@ -653,8 +744,7 @@ void epoll_pwait_int_max(FILE *validation_output_file)
                goto error;
        }
 
-       ret = syscall(SYS_epoll_pwait, epollfd, &epoll_event, INT_MAX, -1,
-                       NULL);
+       ret = syscall(SYS_epoll_pwait, epollfd, &epoll_event, INT_MAX, -1, NULL);
 
        if (ret == 1) {
                ret = read(wait_fd, buf, BUF_SIZE);
@@ -674,22 +764,19 @@ end:
        return;
 }
 
-static
-void *ppoll_writer(void *arg)
+static void *ppoll_writer(void *arg)
 {
        struct ppoll_thread_data *data = (struct ppoll_thread_data *) arg;
 
        while (!stop_thread) {
-               memset(data->ufds, data->value,
-                               MAX_FDS * sizeof(struct pollfd));
+               memset(data->ufds, data->value, MAX_FDS * sizeof(struct pollfd));
                usleep(100);
        }
 
        return NULL;
 }
 
-static
-void do_ppoll(int *fds, struct pollfd *ufds)
+static void do_ppoll(int *fds, struct pollfd *ufds)
 {
        int i, ret;
        struct timespec ts;
@@ -700,7 +787,7 @@ void do_ppoll(int *fds, struct pollfd *ufds)
 
        for (i = 0; i < MAX_FDS; i++) {
                ufds[i].fd = fds[i];
-               ufds[i].events = POLLIN|POLLPRI;
+               ufds[i].events = POLLIN | POLLPRI;
        }
 
        ret = ppoll(ufds, MAX_FDS, &ts, NULL);
@@ -715,8 +802,7 @@ void do_ppoll(int *fds, struct pollfd *ufds)
        }
 }
 
-static
-void stress_ppoll(int *fds, int value)
+static void stress_ppoll(int *fds, int value)
 {
        pthread_t writer;
        int iter, ret;
@@ -757,9 +843,7 @@ end:
  *
  * ppoll should work as expected and the trace should be readable at the end.
  */
-static
-void ppoll_concurrent_write(
-               FILE *validation_output_file __attribute__((unused)))
+static void ppoll_concurrent_write(FILE *validation_output_file __attribute__((unused)))
 {
        int i, ret, fds[MAX_FDS];
 
@@ -784,8 +868,7 @@ void ppoll_concurrent_write(
        return;
 }
 
-static
-void *epoll_pwait_writer(void *addr)
+static void *epoll_pwait_writer(void *addr)
 {
        srand(time(NULL));
 
@@ -802,8 +885,7 @@ void *epoll_pwait_writer(void *addr)
  * buffer allocated for the returned data. This should randomly segfault.
  * The trace should be readable and no kernel OOPS should occur.
  */
-static
-void epoll_pwait_concurrent_munmap(FILE *validation_output_file)
+static void epoll_pwait_concurrent_munmap(FILE *validation_output_file)
 {
        int ret, epollfd, i, fds[MAX_FDS];
        char buf[BUF_SIZE];
@@ -819,18 +901,18 @@ void epoll_pwait_concurrent_munmap(FILE *validation_output_file)
                goto end;
        }
 
-       ret = fprintf(validation_output_file,
-                       "{ \"epollfd\": %i, \"pid\": %i }", epollfd,
-                       getpid());
+       ret = fprintf(validation_output_file, "{\"epollfd\": %i, \"pid\": %i }", epollfd, getpid());
        if (ret < 0) {
                PERROR("[epoll_pwait] Failed to write test validation output");
                goto error;
        }
 
        epoll_event = (struct epoll_event *) mmap(NULL,
-                       MAX_FDS * sizeof(struct epoll_event),
-                       PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1,
-                       0);
+                                                 MAX_FDS * sizeof(struct epoll_event),
+                                                 PROT_READ | PROT_WRITE,
+                                                 MAP_PRIVATE | MAP_ANONYMOUS,
+                                                 -1,
+                                                 0);
        if (epoll_event == MAP_FAILED) {
                PERROR("mmap");
                goto error;
@@ -850,8 +932,7 @@ void epoll_pwait_concurrent_munmap(FILE *validation_output_file)
                }
        }
        stop_thread = 0;
-       ret = pthread_create(&writer, NULL, &epoll_pwait_writer,
-                       (void *) epoll_event);
+       ret = pthread_create(&writer, NULL, &epoll_pwait_writer, (void *) epoll_event);
        if (ret != 0) {
                fprintf(stderr, "[error] pthread_create\n");
                goto error_unmap;
@@ -896,51 +977,85 @@ end:
        return;
 }
 
-static
-void print_list(void)
+static void print_list(void)
+{
+       printf("Test list (-t X):\n");
+
+       for (size_t test_id = 0; test_id < ARRAY_SIZE(test_cases); test_id++) {
+               printf("\t%zu: %s - %s\n",
+                      test_id + 1,
+                      test_cases[test_id].name,
+                      test_cases[test_id].description);
+       }
+}
+
+static void print_test_syscalls(void)
 {
-       fprintf(stderr, "Test list (-t X):\n");
-       fprintf(stderr, "\t1: Working cases for select, pselect6, poll, ppoll "
-                       "and epoll, waiting for input\n");
-       fprintf(stderr, "\t2: Timeout cases (1ms) for select, pselect6, poll, "
-                       "ppoll and epoll\n");
-       fprintf(stderr, "\t3: pselect with an invalid fd\n");
-       fprintf(stderr, "\t4: ppoll with %d FDs\n", MAX_FDS);
-       fprintf(stderr, "\t5: ppoll buffer overflow, should segfault, waits "
-                       "for input\n");
-       fprintf(stderr, "\t6: pselect with an invalid pointer, waits for "
-                       "input\n");
-       fprintf(stderr, "\t7: ppoll with ulong_max fds, waits for input\n");
-       fprintf(stderr, "\t8: epoll_pwait with an invalid pointer, waits for "
-                       "input\n");
-       fprintf(stderr, "\t9: epoll_pwait with maxevents set to INT_MAX, "
-                       "waits for input\n");
-       fprintf(stderr, "\t10: ppoll with concurrent updates of the structure "
-                       "from user-space, stress test (3000 iterations), "
-                       "waits for input + timeout 1ms\n");
-       fprintf(stderr, "\t11: epoll_pwait with concurrent munmap of the buffer "
-                       "from user-space, should randomly segfault, run "
-                       "multiple times, waits for input + timeout 1ms\n");
+       const char *supported_syscalls[] = {
+#ifdef SYS_select
+               "select",
+#endif
+#if defined SYS_pselect6_time64 && defined SYS_pselect6
+               "pselect6",
+               "pselect6_time32",
+#elif defined SYS_pselect6_time32 ^ defined SYS_pselect6
+               "pselect6",
+#endif /* SYS_pselect6_time64 && defined SYS_pselect6 */
+#ifdef SYS_poll
+               "poll",
+#endif
+#if defined SYS_ppoll && defined SYS_ppoll_time64
+               "ppoll",
+               "ppoll_time32",
+#elif defined SYS_ppoll ^ defined SYS_ppoll_time64
+               "ppoll",
+#endif /* defined SYS_ppoll && defined SYS_ppoll_time64 */
+#ifdef SYS_epoll_ctl
+               "epoll_ctl",
+#endif
+#ifdef SYS_epoll_wait
+               "epoll_wait",
+#endif
+#ifdef SYS_epoll_pwait
+               "epoll_pwait",
+#endif
+       };
+
+       for (size_t i = 0; i < ARRAY_SIZE(supported_syscalls); i++) {
+               fputs(supported_syscalls[i], stdout);
+               fputs(i != ARRAY_SIZE(supported_syscalls) - 1 ? "," : "\n", stdout);
+       }
 }
 
 int main(int argc, const char **argv)
 {
-       int c, ret, test = -1;
+       int c, ret;
+       const char *test_name;
        poptContext optCon;
        struct rlimit open_lim;
        FILE *test_validation_output_file = NULL;
        const char *test_validation_output_file_path = NULL;
        struct poptOption optionsTable[] = {
-               { "test", 't', POPT_ARG_INT, &test, 0,
-                       "Test to run", NULL },
-               { "list", 'l', 0, 0, 'l',
-                       "List of tests (-t X)", NULL },
-               { "validation-file", 'o', POPT_ARG_STRING, &test_validation_output_file_path, 0,
-                       "Test case output", NULL },
-               POPT_AUTOHELP
-               { NULL, 0, 0, NULL, 0, NULL, NULL }
+               { "test", 't', POPT_ARG_STRING, &test_name, 0, "Name of test to run", NULL },
+               { "list-tests", 'l', 0, 0, 'l', "List tests (-t X)", NULL },
+               { "list-supported-test-syscalls",
+                 's',
+                 0,
+                 0,
+                 's',
+                 "List supported test syscalls",
+                 NULL },
+               { "validation-file",
+                 'o',
+                 POPT_ARG_STRING,
+                 &test_validation_output_file_path,
+                 0,
+                 "Test case output",
+                 NULL },
+               POPT_AUTOHELP{ NULL, 0, 0, NULL, 0, NULL, NULL }
        };
        const struct test_case *test_case;
+       size_t test_case_id;
 
        optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
 
@@ -957,6 +1072,9 @@ int main(int argc, const char **argv)
                case 'l':
                        print_list();
                        goto end;
+               case 's':
+                       print_test_syscalls();
+                       goto end;
                }
        }
 
@@ -969,7 +1087,7 @@ int main(int argc, const char **argv)
        test_validation_output_file = fopen(test_validation_output_file_path, "w+");
        if (!test_validation_output_file) {
                PERROR("Failed to create test validation output file at '%s'",
-                               test_validation_output_file_path);
+                      test_validation_output_file_path);
                ret = -1;
                goto end;
        }
@@ -992,12 +1110,19 @@ int main(int argc, const char **argv)
        wait_fd = STDIN_FILENO;
 
        /* Test case id is 1-based. */
-       if (test < 1 || test > ARRAY_SIZE(test_cases)) {
+       for (test_case_id = 0; test_case_id < ARRAY_SIZE(test_cases); test_case_id++) {
+               if (!strcmp(test_cases[test_case_id].name, test_name)) {
+                       break;
+               }
+       }
+
+       if (test_case_id == ARRAY_SIZE(test_cases)) {
                poptPrintUsage(optCon, stderr, 0);
                ret = -1;
+               goto end;
        }
 
-       test_case = &test_cases[test - 1];
+       test_case = &test_cases[test_case_id];
 
        timeout = test_case->timeout;
        if (!test_case->produces_validation_info) {
@@ -1005,7 +1130,7 @@ int main(int argc, const char **argv)
                 * All test cases need to provide, at minimum, the pid of the
                 * test application.
                 */
-               ret = fprintf(test_validation_output_file, "{ \"pid\": %i }", getpid());
+               ret = fprintf(test_validation_output_file, "{\"pid\": %i }", getpid());
                if (ret < 0) {
                        PERROR("Failed to write application pid to test validation file");
                        goto end;
index 2e20888df3590e26c7d2298e3d5f703799497325..dd6dab5e519c98ad64b82472e23b5e8e05497926 100755 (executable)
@@ -17,7 +17,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_all_event()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_all_events_basic"
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -43,13 +43,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 9e554bbc0d538859ac1bf94d8d0174292210b733..960bb8a44e1511f08ae425a675dc296c75dc4410 100755 (executable)
@@ -9,7 +9,7 @@ TEST_DESC="Kernel tracer - Callstack context"
 
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../..
-NUM_TESTS=11
+NUM_TESTS=12
 TEST_APP_USERSPACE="$TESTDIR/utils/testapp/gen-syscall-events-callstack/gen-syscall-events-callstack"
 TEST_APP_KERNELSPACE="$TESTDIR/utils/testapp/gen-syscall-events/gen-syscall-events"
 PARSE_CALLSTACK="$TESTDIR/utils/parse-callstack.py"
@@ -36,7 +36,7 @@ function run_workload()
        # shift the first argument, passing along the other args if any to the
        # test app.
        shift
-       local start_file_sync=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_first.XXXXXX")
+       local start_file_sync=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_first.XXXXXX")
 
        lttng_untrack_all
 
@@ -60,7 +60,7 @@ function run_workload()
 
 function test_user_callstack()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        # This is the expected userspace callstack. (see gen-syscall-events-callstack.c)
        USER_CS_EXPECTED="main fct_a fct_b fct_c my_gettid"
        EVENT_NAME="gettid"
@@ -84,7 +84,7 @@ function test_user_callstack()
 
 function test_kernel_callstack()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        # Those are symbol expected to be present in the kernel callstack. This
        # is not an exhaustive list since it's kernel dependent.
 
@@ -120,10 +120,10 @@ function test_kernel_callstack()
        rm -rf "$TRACE_PATH"
 }
 
-# Only run userspace callstack test on x86
-uname -m | grep -E "x86" >/dev/null 2>&1
+# Only run userspace callstack test on x86 (32 and 64 variants)
+uname -m | grep "86" >/dev/null 2>&1
 if test $? == 0; then
-       NUM_TESTS=$((NUM_TESTS+11))
+       NUM_TESTS=$((NUM_TESTS+10))
        RUN_USERSPACE_TEST=1
 else
        RUN_USERSPACE_TEST=0
@@ -136,13 +136,7 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." "$NUM_TESTS" ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 9cc74c4e83c6a258ff1d97d7218b54110784a460..6c7d2db0791bdbb810bb1ccd9b71bf5a1e11341b 100755 (executable)
@@ -15,7 +15,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_channel_buffer()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_session_name"
        CHANNEL_NAME="test_channel_name"
        create_lttng_session_ok "$SESSION_NAME" "$TRACE_PATH"
@@ -30,7 +30,7 @@ function test_channel_buffer()
 
 function test_channel_buffer_too_large()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_session_name"
        CHANNEL_NAME="test_channel_name"
        create_lttng_session_ok "$SESSION_NAME" "$TRACE_PATH"
@@ -47,13 +47,7 @@ function test_channel_buffer_too_large()
 plan_tests $NUM_TESTS
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        start_lttng_sessiond
 
index 0a44f5f288d5acf6e1f597295c298ccd83b6f14f..c3688d3599efa28aed83d8eab7483ba44934bd78 100755 (executable)
@@ -64,8 +64,8 @@ function extract_clock_metadata_token()
 
 function test_clock_override_metadata()
 {
-       local ctf_metadata_file=$(mktemp --tmpdir -p $TRACE_PATH ctf-metadata.XXXXXX)
-       local clock_metadata_file=$(mktemp --tmpdir -p $TRACE_PATH clock-metadata.XXXXXX)
+       local ctf_metadata_file=$(TMPDIR="$TRACE_PATH" mktemp -t ctf-metadata.XXXXXX)
+       local clock_metadata_file=$(TMPDIR="$TRACE_PATH" mktemp -t clock-metadata.XXXXXX)
        local result=""
 
        diag "Clock override plugin metadata test"
@@ -174,20 +174,14 @@ TESTS=(
 TEST_COUNT=${#TESTS[@]}
 i=0
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        trap signal_cleanup SIGTERM SIGINT
 
        while [ "$i" -lt "$TEST_COUNT" ]; do
 
-               TRACE_PATH=$(mktemp --tmpdir -d tmp.test_clock_override_trace_path.XXXXXX)
+               TRACE_PATH=$(mktemp -d -t tmp.test_clock_override_trace_path.XXXXXX)
 
                # Execute test
                ${TESTS[$i]}
index ac9ec05492cf2462f422af01b2fd19e2710dfc5b..e57cd6d26a1561805da32bc28ba1cb8192bd0433 100755 (executable)
@@ -17,7 +17,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_event_basic()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_event_basic"
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -45,7 +45,7 @@ function test_event_basic()
 
 function test_enable_after_start()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_enable_after_start"
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -73,13 +73,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test $NUM_TESTS "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index b1d5491fcd201835c39e77065552c1ea3b8cf2c3..3c941c72c78424b947e215117b360b62fff71c0f 100755 (executable)
@@ -15,7 +15,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_kernel_function_basic()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        local SESSION_NAME="kernel_function_basic"
        local EVENT_NAME="my_event_name"
        local TARGET_SYMBOL="lttng_test_filter_event_write"
@@ -43,13 +43,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        start_lttng_sessiond_notap
        validate_lttng_modules_present
index b8f7ded82364cf82e5bc64ad61ae97a5585ada2c..c6ed4f950589a0bdfe0e505f3c614ee4b2cb9932 100755 (executable)
@@ -19,7 +19,7 @@ function test_proc_logger()
 {
        diag "Test /proc/lttng-logger"
 
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
@@ -50,7 +50,7 @@ function test_dev_logger()
 {
        diag "Test /dev/lttng-logger"
 
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
@@ -81,7 +81,7 @@ function test_payload_limit()
 {
        diag "Test lttng-logger payload limit"
 
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
@@ -110,13 +110,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 0c8718d78e400d26cc71f51b5b268016737f4b4e..1c71ea503e998f26f2519675bfb4e32c3ef986fb 100755 (executable)
@@ -76,7 +76,7 @@ function test_ns()
        ns_inode=$(stat -c '%i' -L "/proc/$$/ns/$ns")
        ok $? "Get current $ns namespace inode: $ns_inode"
 
-       trace_path=$(mktemp --tmpdir -d tmp.{FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        start_lttng_sessiond
 
@@ -108,13 +108,7 @@ plan_tests $NUM_TESTS
 print_test_banner "$TEST_DESC"
 
 
-isroot=0
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." "$NUM_TESTS" && exit 0
-
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." && exit 0
 
 system_has_ns=0
 if [ -d "/proc/$$/ns" ]; then
index 42a61276be2222f0ef9e4c2ef61131be8a1018b2..10f97f8cbb922fa391dbe1831007da8bde1a7be5 100755 (executable)
@@ -80,10 +80,10 @@ function test_ns()
                return
        fi
 
-       trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       file_sync_wait_before_unshare=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_unshare.XXXXXX")
-       file_sync_wait_after_unshare=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_unshare.XXXXXX")
-       file_sync_signal_after_unshare=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_signal_after_unshare.XXXXXX")
+       trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       file_sync_wait_before_unshare=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_unshare.XXXXXX")
+       file_sync_wait_after_unshare=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_unshare.XXXXXX")
+       file_sync_signal_after_unshare=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_signal_after_unshare.XXXXXX")
 
        # Get the current ns inode number
        ns_inode=$(stat -c '%i' -L "/proc/$$/ns/$ns")
@@ -162,14 +162,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-
-isroot=0
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." "$NUM_TESTS" && exit 0
-
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." && exit 0
 
 system_has_ns=0
 if [ -d "/proc/$$/ns" ]; then
index cb773d7df59973c4a31ca69e6332cda9601f46f1..fc22740262afd6ffe259ee26e768a56e65e46c26 100755 (executable)
@@ -120,20 +120,14 @@ TESTS=(
 TEST_COUNT=${#TESTS[@]}
 i=0
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        trap signal_cleanup SIGTERM SIGINT
 
        while [ "$i" -lt "$TEST_COUNT" ]; do
 
-               TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_kernel_rotation_destroy_flush.XXXXXX)
+               TRACE_PATH=$(mktemp -d -t tmp.test_kernel_rotation_destroy_flush.XXXXXX)
 
                # Execute test
                ${TESTS[$i]}
index d8245a0e7297f0083fe070abef8d33320d58de53..a359945cd59881fa564c776bbf51d5e76bca64c0 100755 (executable)
@@ -10,7 +10,6 @@ TEST_DESC="Kernel tracer - select, poll and epoll payload extraction"
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../..
 VALIDATE_SCRIPT="$CURDIR/validate_select_poll_epoll.py"
-NUM_TESTS=102
 
 DISABLE_VALIDATE=0
 # Babeltrace python bindings are required for the validation, but
@@ -27,6 +26,12 @@ LAST_WARNING=$(dmesg | grep " WARNING:" | cut -d' ' -f1 | tail -1)
 LAST_OOPS=$(dmesg | grep " OOPS:" | cut -d' ' -f1 | tail -1)
 LAST_BUG=$(dmesg | grep " BUG:" | cut -d' ' -f1 | tail -1)
 
+SUPPORTED_SYSCALLS_LIST=$("$CURDIR"/select_poll_epoll --list-supported-test-syscalls)
+SUPPORTED_SYSCALLS_COUNT=$(echo $SUPPORTED_SYSCALLS_LIST | awk -F '[\t,]' '{print NF}')
+
+# Two tests validate their trace for every supported syscall
+NUM_TESTS=$((88+(2*SUPPORTED_SYSCALLS_COUNT)))
+
 # shellcheck source=../../utils/utils.sh
 source $TESTDIR/utils/utils.sh
 
@@ -48,30 +53,22 @@ function check_trace_content()
 function test_working_cases()
 {
        SESSION_NAME="syscall_payload"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
-
-       # arm64 does not have epoll_wait
-       uname -m | grep -E "aarch64" >/dev/null 2>&1
-       if test $? = 0; then
-               SYSCALL_LIST="select,pselect6,poll,ppoll,epoll_ctl,epoll_pwait"
-       else
-               SYSCALL_LIST="select,pselect6,poll,ppoll,epoll_ctl,epoll_wait,epoll_pwait"
-       fi
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "Working cases for select, pselect6, poll, ppoll and epoll, waiting for input"
 
        create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
 
-       lttng_enable_kernel_syscall_ok $SESSION_NAME $SYSCALL_LIST
+       lttng_enable_kernel_syscall_ok $SESSION_NAME $SUPPORTED_SYSCALLS_LIST
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 1
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t working_cases
        stop_lttng_tracing_ok
 
-       validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 1 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH"
+       validate_trace "$SUPPORTED_SYSCALLS_LIST" "$TRACE_PATH"
+       check_trace_content -t working_cases --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH"
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -82,30 +79,22 @@ function test_working_cases()
 function test_timeout_cases()
 {
        SESSION_NAME="syscall_payload"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
-
-       # arm64 does not have epoll_wait
-       uname -m | grep -E "aarch64" >/dev/null 2>&1
-       if test $? = 0; then
-               SYSCALL_LIST="select,pselect6,poll,ppoll,epoll_ctl,epoll_pwait"
-       else
-               SYSCALL_LIST="select,pselect6,poll,ppoll,epoll_ctl,epoll_wait,epoll_pwait"
-       fi
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "Timeout cases (1ms) for select, pselect6, poll, ppoll and epoll"
 
        create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
 
-       lttng_enable_kernel_syscall_ok $SESSION_NAME "$SYSCALL_LIST"
+       lttng_enable_kernel_syscall_ok $SESSION_NAME "$SUPPORTED_SYSCALLS_LIST"
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 2
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t working_cases_timeout
        stop_lttng_tracing_ok
 
-       validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 2 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       validate_trace "$SUPPORTED_SYSCALLS_LIST" "$TRACE_PATH"
+       check_trace_content -t working_cases_timeout --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -116,9 +105,9 @@ function test_timeout_cases()
 function test_pselect_invalid_fd()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="pselect6"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="pselect6"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "pselect with invalid FD"
 
@@ -128,11 +117,11 @@ function test_pselect_invalid_fd()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 3
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t pselect_invalid_fd
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 3 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t pselect_invalid_fd --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -140,12 +129,12 @@ function test_pselect_invalid_fd()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_big_ppoll()
+function test_ppoll_big()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="ppoll"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="ppoll"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "ppoll with 2047 FDs"
 
@@ -155,11 +144,11 @@ function test_big_ppoll()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 4
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t ppoll_big
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 4 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t ppoll_big --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -167,12 +156,12 @@ function test_big_ppoll()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_ppoll_overflow()
+function test_ppoll_fds_buffer_overflow()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="ppoll"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="ppoll"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "ppoll buffer overflow, should segfault, waits for input"
 
@@ -183,12 +172,12 @@ function test_ppoll_overflow()
 
        start_lttng_tracing_ok
        diag "Expect segfaults"
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 5
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t ppoll_fds_buffer_overflow
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
 
-       check_trace_content -t 5 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t ppoll_fds_buffer_overflow --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -196,12 +185,12 @@ function test_ppoll_overflow()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_pselect_invalid_ptr()
+function test_pselect_invalid_pointer()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="pselect6"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="pselect6"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "pselect with invalid pointer, waits for input"
 
@@ -211,11 +200,11 @@ function test_pselect_invalid_ptr()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 6
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t pselect_invalid_pointer
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 6 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t pselect_invalid_pointer --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -223,12 +212,12 @@ function test_pselect_invalid_ptr()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_ppoll_ulong_max()
+function test_ppoll_fds_ulong_max()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="ppoll"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="ppoll"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "ppoll with ulong_max fds, waits for input"
 
@@ -238,11 +227,11 @@ function test_ppoll_ulong_max()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 7
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t ppoll_fds_ulong_max
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 7 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t ppoll_fds_ulong_max --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -250,12 +239,12 @@ function test_ppoll_ulong_max()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_epoll_pwait_invalid_ptr()
+function test_epoll_pwait_invalid_pointer()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="epoll_pwait"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="epoll_pwait"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "epoll_pwait with invalid pointer, waits for input"
 
@@ -265,11 +254,11 @@ function test_epoll_pwait_invalid_ptr()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 8
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t epoll_pwait_invalid_pointer
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 8 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t epoll_pwait_invalid_pointer --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -277,12 +266,12 @@ function test_epoll_pwait_invalid_ptr()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_epoll_pwait_int_max()
+function test_epoll_pwait_fds_int_max()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="epoll_pwait"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="epoll_pwait"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "epoll_pwait with maxevents set to INT_MAX, waits for input"
 
@@ -292,11 +281,11 @@ function test_epoll_pwait_int_max()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 9
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t epoll_pwait_int_max
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 9 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t epoll_pwait_int_max --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -304,12 +293,12 @@ function test_epoll_pwait_int_max()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_ppoll_concurrent()
+function test_ppoll_concurrent_write()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="ppoll"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="ppoll"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "ppoll with concurrent updates of the structure from user-space, stress test (3000 iterations), waits for input + timeout 1ms"
 
@@ -319,11 +308,11 @@ function test_ppoll_concurrent()
        add_context_kernel_ok $SESSION_NAME channel0 pid
 
        start_lttng_tracing_ok
-       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 10
+       yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t ppoll_concurrent_write
        stop_lttng_tracing_ok
 
        validate_trace "$SYSCALL_LIST" "$TRACE_PATH"
-       check_trace_content -t 10 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t ppoll_concurrent_write --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -331,12 +320,12 @@ function test_ppoll_concurrent()
        rm -f "$TEST_VALIDATION_OUTPUT_PATH"
 }
 
-function test_epoll_pwait_concurrent()
+function test_epoll_pwait_concurrent_unmap()
 {
        SESSION_NAME="syscall_payload"
-       SYSCALL_LIST="epoll_ctl,epoll_pwait"
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
-       TEST_VALIDATION_OUTPUT_PATH=$(mktemp --tmpdir -u "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
+       local SYSCALL_LIST="epoll_ctl,epoll_pwait"
+       TRACE_PATH=$(mktemp -d -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_trace_path.XXXXXX")
+       TEST_VALIDATION_OUTPUT_PATH=$(mktemp -u -t "tmp.test_kernel_select_poll_epoll_${FUNCNAME[0]}_validation.XXXXXX")
 
        diag "epoll_pwait with concurrent munmap of the buffer from user-space, should randomly segfault, run multiple times, waits for input + timeout 1ms"
 
@@ -348,13 +337,13 @@ function test_epoll_pwait_concurrent()
        start_lttng_tracing_ok
        diag "Expect segfaults"
        for i in $(seq 1 100); do
-               yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t 11
+               yes | "$CURDIR"/select_poll_epoll --validation-file "$TEST_VALIDATION_OUTPUT_PATH" -t epoll_pwait_concurrent_munmap
        done
        stop_lttng_tracing_ok
 
        # epoll_wait is not always generated in the trace (stress test)
        validate_trace "epoll_ctl" "$TRACE_PATH"
-       check_trace_content -t 11 --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
+       check_trace_content -t epoll_pwait_concurrent_munmap --validation-file "$TEST_VALIDATION_OUTPUT_PATH" "$TRACE_PATH" 2>/dev/null
 
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -374,13 +363,9 @@ if test $? != 0; then
        exit 0
 fi
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
+diag "Supported syscalls are $SUPPORTED_SYSCALLS_LIST"
 
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
@@ -389,14 +374,14 @@ skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
        test_working_cases
        test_timeout_cases
        test_pselect_invalid_fd
-       test_big_ppoll
-       test_ppoll_overflow
-       test_pselect_invalid_ptr
-       test_ppoll_ulong_max
-       test_epoll_pwait_invalid_ptr
-       test_epoll_pwait_int_max
-       test_ppoll_concurrent
-       test_epoll_pwait_concurrent
+       test_ppoll_big
+       test_ppoll_fds_buffer_overflow
+       test_pselect_invalid_pointer
+       test_ppoll_fds_ulong_max
+       test_epoll_pwait_invalid_pointer
+       test_epoll_pwait_fds_int_max
+       test_ppoll_concurrent_write
+       test_epoll_pwait_concurrent_unmap
 
        stop_lttng_sessiond
 
@@ -405,12 +390,18 @@ skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
        NEW_BUG=$(dmesg | grep " BUG:" | cut -d' ' -f1 | tail -1)
 
        if test "$LAST_WARNING" != "$NEW_WARNING"; then
+               diag "Last WARNING before tests: ${LAST_WARNING}"
+               diag "Last WARNING after tests: ${NEW_WARNING}"
                fail "New WARNING generated"
        fi
        if test "$LAST_OOPS" != "$NEW_OOPS"; then
+               diag "Last OOPS before tests: ${LAST_OOPS}"
+               diag "Last OOPS after tests: ${NEW_OOPS}"
                fail "New OOPS generated"
        fi
        if test "$LAST_BUG" != "$NEW_BUG"; then
+               diag "Last BUG before tests: ${LAST_BUG}"
+               diag "Last BUG after tests: ${NEW_BUG}"
                fail "New BUG generated"
        fi
 }
index 401a18a8de4932b141abf9e87d6b98f9b390458e..92d79a7bcba884e28995ac75dfd6740a5f79dd7d 100755 (executable)
@@ -20,7 +20,7 @@ source $TESTDIR/utils/utils.sh
 
 function trace_testapp()
 {
-       local start_file_sync=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_start.XXXXXX")
+       local start_file_sync=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_start.XXXXXX")
 
        # Clear all entries from the resource tracker
        lttng_untrack_kernel_all_ok
@@ -72,7 +72,7 @@ function test_syscall_event_list()
 
 function test_syscall_simple_list()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_simple_list"
        local EVENT_NAME="close"
 
@@ -100,7 +100,7 @@ function test_syscall_simple_list()
 
 function test_syscall_simple_list_two()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_simple_list_two"
        local EVENT_NAME="close"
        local EVENT_NAME2="read"
@@ -134,7 +134,7 @@ function test_syscall_simple_list_two()
 
 function test_syscall_single()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_single"
 
        diag "Syscall trace single"
@@ -159,7 +159,7 @@ function test_syscall_single()
 
 function test_syscall_two()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_two"
 
        diag "Syscall trace two events"
@@ -187,7 +187,7 @@ function test_syscall_two()
 
 function test_syscall_all()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_all"
 
        diag "Syscall trace all events"
@@ -213,7 +213,7 @@ function test_syscall_all()
 
 function test_syscall_all_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_all_disable_one"
 
        diag "Syscall trace all events and disable one"
@@ -242,7 +242,7 @@ function test_syscall_all_disable_one()
 
 function test_syscall_all_disable_two()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_all_disable_two"
 
        diag "Syscall trace all events and disable two"
@@ -276,7 +276,7 @@ function test_syscall_all_disable_two()
 
 function test_syscall_enable_all_disable_all()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_disable_all"
 
        diag "Syscall trace all events and disable all"
@@ -300,7 +300,7 @@ function test_syscall_enable_all_disable_all()
 
 function test_syscall_enable_all_disable_all_enable_all()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_disable_all_enable_all"
 
        diag "Syscall trace all events and enable/disable all"
@@ -330,7 +330,7 @@ function test_syscall_enable_all_disable_all_enable_all()
 
 function test_syscall_enable_all_enable_one_disable_all()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_enable_one_disable_all"
 
        diag "Syscall trace all events, enable one and disable all"
@@ -359,7 +359,7 @@ function test_syscall_enable_all_enable_one_disable_all()
 
 function test_syscall_enable_one_enable_all_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_one_enable_all_disable_one"
 
        diag "Syscall trace all events and enable/disable one"
@@ -388,7 +388,7 @@ function test_syscall_enable_one_enable_all_disable_one()
 
 function test_syscall_enable_one_enable_all_disable_all_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_one_enable_all_disable_all_disable_one"
 
        diag "Syscall trace all events and enable/disable one"
@@ -420,7 +420,7 @@ function test_syscall_enable_one_enable_all_disable_all_disable_one()
 
 function test_syscall_enable_all_disable_all_twice()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_disable_all_twice"
 
        diag "Syscall trace all events and enable/disable all twice"
@@ -448,7 +448,7 @@ function test_syscall_enable_all_disable_all_twice()
 
 function test_syscall_enable_one_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_one_disable_one"
 
        diag "Syscall trace one event and disable one"
@@ -472,7 +472,7 @@ function test_syscall_enable_one_disable_one()
 
 function test_syscall_enable_two_disable_two()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_two_disable_two"
 
        diag "Syscall trace two events and disable two"
@@ -498,7 +498,7 @@ function test_syscall_enable_two_disable_two()
 
 function test_syscall_enable_two_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_two_disable_one"
 
        diag "Syscall trace two events and disable one"
@@ -527,7 +527,7 @@ function test_syscall_enable_two_disable_one()
 
 function test_syscall_disable_twice()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_disable_twice"
 
        diag "Syscall trace one event and disable twice"
@@ -547,7 +547,7 @@ function test_syscall_disable_twice()
 
 function test_syscall_disable_all_twice()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_disable_all_twice"
 
        diag "Syscall trace all events and disable all twice"
@@ -568,7 +568,7 @@ function test_syscall_disable_all_twice()
 
 function test_syscall_enable_unknown()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_unknown"
 
        diag "Syscall enable an unknown event"
@@ -586,7 +586,7 @@ function test_syscall_enable_unknown()
 
 function test_syscall_enable_all_enable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_enable_one"
 
        diag "Syscall enable all and enable one"
@@ -604,7 +604,7 @@ function test_syscall_enable_all_enable_one()
 
 function test_syscall_disable_all_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_all_enable_one"
 
        diag "Syscall disable all and disable one"
@@ -623,7 +623,7 @@ function test_syscall_disable_all_disable_one()
 
 function test_syscall_enable_channel_disable_all()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_channel_disable_all"
        CHANNEL_NAME="channel"
 
@@ -643,7 +643,7 @@ function test_syscall_enable_channel_disable_all()
 
 function test_syscall_enable_channel_disable_one()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="kernel_syscall_enable_channel_disable_all"
        CHANNEL_NAME="channel"
 
@@ -664,13 +664,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 31b11e98da99777b25e3f4079c1edeab12e636bc..38987f7b18aefafacc1953880c736e5fc180ca8f 100755 (executable)
@@ -44,7 +44,7 @@ function validate_list()
 
 function test_userspace_probe_enable_file_noexist ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_file_noexist"
        ENABLE_EXPR="elf:/etc/file-not-exist:$ELF_SYMBOL"
 
@@ -61,7 +61,7 @@ function test_userspace_probe_enable_file_noexist ()
 
 function test_userspace_probe_enable_file_not_elf ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_file_not_elf"
        ENABLE_EXPR="elf:/etc/passwd:$ELF_SYMBOL"
 
@@ -78,7 +78,7 @@ function test_userspace_probe_enable_file_not_elf ()
 
 function test_userspace_probe_enable_elf_missing_symbol_name ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_elf_missing_symbol"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:"
 
@@ -95,7 +95,7 @@ function test_userspace_probe_enable_elf_missing_symbol_name ()
 
 function test_userspace_probe_enable_elf_nonexistant_symbol ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_elf_nonexistant_symbol"
        ELF_SYMBOL_NO_EXIST="function_doesnt_exist"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL_NO_EXIST"
@@ -113,7 +113,7 @@ function test_userspace_probe_enable_elf_nonexistant_symbol ()
 
 function test_userspace_probe_enable_elf_symbol_not_function ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_elf_symbol_not_function"
        ELF_SYMBOL_NO_FUNC="not_a_function"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL_NO_FUNC"
@@ -131,7 +131,7 @@ function test_userspace_probe_enable_elf_symbol_not_function ()
 
 function test_userspace_probe_unsupported_types ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_unsupported_types"
        # Userspace probe at an address or at an offset to a function
        # instrumentation description types are not supported at the moment.
@@ -156,7 +156,7 @@ function test_userspace_probe_unsupported_types ()
 
 function test_userspace_probe_enable_implicit_probe_type ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_implicit_probe_type"
        ENABLE_EXPR="$ELF_TEST_BIN:$ELF_SYMBOL"
 
@@ -178,7 +178,7 @@ function test_userspace_probe_enable_implicit_probe_type ()
 
 function test_userspace_probe_enable_elf_symbol_exists ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_elf_symbol_exists"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL"
 
@@ -200,7 +200,7 @@ function test_userspace_probe_enable_elf_symbol_exists ()
 
 function test_userspace_probe_enable_in_path ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_in_path"
        ENABLE_EXPR="elf:$ELF_TEST_BIN_NAME:$ELF_SYMBOL"
 
@@ -229,7 +229,7 @@ function test_userspace_probe_enable_in_path ()
 
 function test_userspace_probe_enable_full_path ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_full_path"
        ENABLE_EXPR="elf:$(realpath $ELF_TEST_BIN):$ELF_SYMBOL"
        diag "Userspace probe with full path enabled successfully"
@@ -250,9 +250,9 @@ function test_userspace_probe_enable_full_path ()
 
 function test_userspace_probe_enable_colon_in_path ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userspace_probe_enable_colon_in_path"
-       COLON_FILE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       COLON_FILE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        ELF_BIN_SYMLINK="$COLON_FILE_PATH/colon_:_in_name"
        ELF_BIN_WITH_COLON_IN_NAME_ESCAPED="$COLON_FILE_PATH/colon_\:_in_name"
        ENABLE_EXPR="elf:"$ELF_BIN_WITH_COLON_IN_NAME_ESCAPED":$ELF_SYMBOL"
@@ -278,7 +278,7 @@ function test_userspace_probe_enable_colon_in_path ()
 
 function test_userspace_probe_elf ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL"
 
@@ -289,7 +289,7 @@ function test_userspace_probe_elf ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$ELF_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-elf-binary/.libs" "$ELF_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -301,7 +301,7 @@ function test_userspace_probe_elf ()
 
 function test_userspace_probe_elf_dynamic_symbol ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf"
        LIBFOO_PATH="$ELF_TEST_BIN_DIR/libfoo.so"
        ENABLE_EXPR="elf:$LIBFOO_PATH:dynamic_symbol"
@@ -313,7 +313,7 @@ function test_userspace_probe_elf_dynamic_symbol ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$ELF_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-elf-binary/.libs" "$ELF_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -325,7 +325,7 @@ function test_userspace_probe_elf_dynamic_symbol ()
 
 function test_userspace_probe_elf_cxx_function ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf_cxx_function"
        # Probing C++ mangled symbols should work the same way as regular Elf
        # symbols
@@ -351,7 +351,7 @@ function test_userspace_probe_elf_cxx_function ()
 
 function test_userspace_probe_elf_cxx_method ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf_cxx_method"
        # Probing C++ mangled symbols should work the same way as regular Elf
        # symbols
@@ -377,7 +377,7 @@ function test_userspace_probe_elf_cxx_method ()
 
 function test_userspace_probe_elf_disable ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf_disable"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL"
 
@@ -403,7 +403,7 @@ function test_userspace_probe_elf_disable ()
 
 function test_userspace_probe_elf_list ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_elf_list"
        ENABLE_EXPR="elf:$ELF_TEST_BIN:$ELF_SYMBOL"
 
@@ -431,9 +431,9 @@ function test_userspace_probe_save_load_elf()
        # saves the path to the link and not to the actual file. This is to
        # support instrumentation of shared objects that are often accessed
        # through symlinks and updated.
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       TMP_LINK_DIR=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       TMP_SAVE_DIR=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TMP_LINK_DIR=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TMP_SAVE_DIR=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        SESSION_NAME="test_userprobe_save_load_elf"
 
@@ -487,9 +487,9 @@ function test_userspace_probe_save_load_sdt()
        # saves the path to the link and not to the actual file. This is to
        # support instrumentation of shared objects that are often accessed
        # through symlinks and updated.
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       TMP_LINK_DIR=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       TMP_SAVE_DIR=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TMP_LINK_DIR=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TMP_SAVE_DIR=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        SESSION_NAME="test_userprobe_save_load_sdt"
        PROVIDER="foobar"
@@ -541,10 +541,11 @@ function test_userspace_probe_save_load_sdt()
 
 function test_userspace_probe_sdt ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        PROVIDER="foobar"
        PROBE="tp1"
        ENABLE_EXPR="sdt:$SDT_TEST_BIN:$PROVIDER:$PROBE"
+       SESSION_NAME="${FUNCNAME[0]}"
 
        diag "Userspace probe on SDT tracepoint enabled and traced"
 
@@ -553,7 +554,7 @@ function test_userspace_probe_sdt ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -565,7 +566,7 @@ function test_userspace_probe_sdt ()
 
 function test_userspace_probe_sdt_list ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_list"
        PROVIDER="foobar"
        PROBE="tp1"
@@ -591,7 +592,7 @@ function test_userspace_probe_sdt_list ()
 
 function test_userspace_probe_enable_sdt_nonexistant_provider ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_nonexistand_provider"
        PROVIDER="not_provider"
        PROBE="tp1"
@@ -610,7 +611,7 @@ function test_userspace_probe_enable_sdt_nonexistant_provider ()
 
 function test_userspace_probe_enable_sdt_nonexistant_probe ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_nonexistant_probe"
        PROVIDER="foobar"
        PROBE="not_a_tracepoint"
@@ -629,7 +630,7 @@ function test_userspace_probe_enable_sdt_nonexistant_probe ()
 
 function test_userspace_probe_enable_sdt_with_sema ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_with_sema"
        PROVIDER="foobar"
        PROBE="tp_with_semaphore"
@@ -648,7 +649,7 @@ function test_userspace_probe_enable_sdt_with_sema ()
 
 function test_userspace_probe_sdt_one_probe ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_one_probe"
        PROVIDER="foobar"
        PROBE="tp1"
@@ -661,7 +662,7 @@ function test_userspace_probe_sdt_one_probe ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -673,7 +674,7 @@ function test_userspace_probe_sdt_one_probe ()
 
 function test_userspace_probe_sdt_two_probes ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_two_probes"
        PROVIDER="foobar"
        PROBE="tp2"
@@ -686,7 +687,7 @@ function test_userspace_probe_sdt_two_probes ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -698,7 +699,7 @@ function test_userspace_probe_sdt_two_probes ()
 
 function test_userspace_probe_sdt_in_shared_object ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_shared_object"
        PROVIDER="foobar"
        PROBE="tp_in_shared_object"
@@ -711,7 +712,7 @@ function test_userspace_probe_sdt_in_shared_object ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -723,7 +724,7 @@ function test_userspace_probe_sdt_in_shared_object ()
 
 function test_userspace_probe_sdt_in_shared_object_dlopen ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_shared_object_dlopen"
        PROVIDER="foobar"
        PROBE="tp_in_dlopen"
@@ -736,7 +737,7 @@ function test_userspace_probe_sdt_in_shared_object_dlopen ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -748,7 +749,7 @@ function test_userspace_probe_sdt_in_shared_object_dlopen ()
 
 function test_userspace_probe_sdt_in_shared_object_ldpreload ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_shared_object_ldpreload"
        PROVIDER="foobar"
        PROBE="tp_in_ldpreload"
@@ -761,7 +762,7 @@ function test_userspace_probe_sdt_in_shared_object_ldpreload ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       LD_PRELOAD="$SDT_TEST_BIN_DIR/libzzz.so" eval "$SDT_TEST_BIN" > /dev/null
+       LD_PRELOAD="$SDT_TEST_BIN_DIR/libzzz.so" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -773,7 +774,7 @@ function test_userspace_probe_sdt_in_shared_object_ldpreload ()
 
 function test_userspace_probe_sdt_with_arg ()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="test_userprobe_sdt_arg"
        PROVIDER="foobar"
        PROBE="tp_with_arg"
@@ -786,7 +787,7 @@ function test_userspace_probe_sdt_with_arg ()
        lttng_enable_kernel_userspace_probe_event_ok $SESSION_NAME "$ENABLE_EXPR" $PROBE_EVENT_NAME
 
        start_lttng_tracing_ok $SESSION_NAME
-       eval "$SDT_TEST_BIN" > /dev/null
+       LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-sdt-binary/.libs" "$SDT_TEST_BIN" > /dev/null
        stop_lttng_tracing_ok $SESSION_NAME
 
        validate_trace $PROBE_EVENT_NAME "$TRACE_PATH"
@@ -814,13 +815,7 @@ fi
 plan_tests $NUM_TESTS
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 97c7764c0a9fbb4975539a20d159e490271e7912..0ca0ba67cc3c149a47dc34030124c4fb5b0deb73 100755 (executable)
@@ -17,12 +17,15 @@ try:
     import bt2
 except ImportError:
     # quick fix for debian-based distros
-    sys.path.append("/usr/local/lib/python%d.%d/site-packages" %
-                    (sys.version_info.major, sys.version_info.minor))
+    sys.path.append(
+        "/usr/local/lib/python%d.%d/site-packages"
+        % (sys.version_info.major, sys.version_info.minor)
+    )
     import bt2
 
 NSEC_PER_SEC = 1000000000
 
+
 class TraceParser:
     def __init__(self, trace_msg_iter, pid):
         self.trace = trace_msg_iter
@@ -37,7 +40,7 @@ class TraceParser:
         # Each test classes checks the payload of different events. Each of
         # those checks are stored in a event_name specific dictionnary in this
         # data structure.
-        self.expect = defaultdict(lambda : defaultdict(int))
+        self.expect = defaultdict(lambda: defaultdict(int))
 
         # This dictionnary holds the value recorded in the trace that are
         # tested. Its content is use to print the values that caused a test to
@@ -45,9 +48,13 @@ class TraceParser:
         self.recorded_values = {}
 
     def ns_to_hour_nsec(self, ns):
-        d = time.localtime(ns/NSEC_PER_SEC)
-        return "%02d:%02d:%02d.%09d" % (d.tm_hour, d.tm_min, d.tm_sec,
-                                        ns % NSEC_PER_SEC)
+        d = time.localtime(ns / NSEC_PER_SEC)
+        return "%02d:%02d:%02d.%09d" % (
+            d.tm_hour,
+            d.tm_min,
+            d.tm_sec,
+            ns % NSEC_PER_SEC,
+        )
 
     def parse(self):
         # iterate over all the events
@@ -59,7 +66,8 @@ class TraceParser:
                 continue
 
             method_name = "handle_%s" % msg.event.name.replace(":", "_").replace(
-                "+", "_")
+                "+", "_"
+            )
             # call the function to handle each event individually
             if hasattr(TraceParser, method_name):
                 func = getattr(TraceParser, method_name)
@@ -228,13 +236,13 @@ class TraceParser:
         pass
 
 
-class Test1(TraceParser):
+class WorkingCases(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
 
         # Values expected in the trace
-        self.epoll_wait_fd = validation_args['epoll_wait_fd']
-        self.epoll_pwait_fd = validation_args['epoll_pwait_fd']
+        self.epoll_wait_fd = validation_args["epoll_wait_fd"]
+        self.epoll_pwait_fd = validation_args["epoll_pwait_fd"]
 
         self.expect["select_entry"]["select_in_fd0"] = 0
         self.expect["select_entry"]["select_in_fd1023"] = 0
@@ -263,8 +271,12 @@ class Test1(TraceParser):
             exceptfd_127 = event["exceptfds"][127]
 
             # check that the FD 1023 is actually set in the readfds
-            if readfd_127 == 0x40 and writefd_127 == 0 and \
-                    exceptfd_127 == 0 and overflow == 0:
+            if (
+                readfd_127 == 0x40
+                and writefd_127 == 0
+                and exceptfd_127 == 0
+                and overflow == 0
+            ):
                 self.expect["select_entry"]["select_in_fd1023"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -287,8 +299,12 @@ class Test1(TraceParser):
                 readfd_127 = event["readfds"][127]
                 writefd_127 = event["writefds"][127]
                 exceptfd_127 = event["exceptfds"][127]
-                if readfd_127 == 0x40 and writefd_127 == 0 and \
-                        exceptfd_127 == 0 and tvp == 0:
+                if (
+                    readfd_127 == 0x40
+                    and writefd_127 == 0
+                    and exceptfd_127 == 0
+                    and tvp == 0
+                ):
                     self.expect["select_exit"]["select_out_fd1023"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -303,8 +319,11 @@ class Test1(TraceParser):
         # the raw value matches the events bit field.
         if nfds == 1 and fds_length == 1:
             fd_0 = event["fds"][0]
-            if fd_0["raw_events"] == 0x3 and fd_0["events"]["POLLIN"] == 1 and \
-                    fd_0["events"]["padding"] == 0:
+            if (
+                fd_0["raw_events"] == 0x3
+                and fd_0["events"]["POLLIN"] == 1
+                and fd_0["events"]["padding"] == 0
+            ):
                 self.expect["poll_entry"]["poll_in_nfds1"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -318,8 +337,11 @@ class Test1(TraceParser):
         # the raw value matches the events bit field.
         if ret == 1 and fds_length == 1:
             fd_0 = event["fds"][0]
-            if fd_0["raw_events"] == 0x1 and fd_0["events"]["POLLIN"] == 1 and \
-                fd_0["events"]["padding"] == 0:
+            if (
+                fd_0["raw_events"] == 0x1
+                and fd_0["events"]["POLLIN"] == 1
+                and fd_0["events"]["padding"] == 0
+            ):
                 self.expect["poll_exit"]["poll_out_nfds1"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -333,10 +355,14 @@ class Test1(TraceParser):
 
         # check that we have FD 0 waiting for EPOLLIN|EPOLLPRI and that
         # data.fd = 0
-        if (epfd == self.epoll_wait_fd or epfd == self.epoll_pwait_fd) and 'EPOLL_CTL_ADD' in op_enum.labels and fd == 0 and \
-                _event["data_union"]["fd"] == 0 and \
-                _event["events"]["EPOLLIN"] == 1 and \
-                _event["events"]["EPOLLPRI"] == 1:
+        if (
+            (epfd == self.epoll_wait_fd or epfd == self.epoll_pwait_fd)
+            and "EPOLL_CTL_ADD" in op_enum.labels
+            and fd == 0
+            and _event["data_union"]["fd"] == 0
+            and _event["events"]["EPOLLIN"] == 1
+            and _event["events"]["EPOLLPRI"] == 1
+        ):
             self.expect["epoll_ctl_entry"]["epoll_ctl_in_add"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -370,8 +396,11 @@ class Test1(TraceParser):
         # check that FD 0 returned with EPOLLIN and the right data.fd
         if ret == 1 and fds_length == 1:
             fd_0 = event["fds"][0]
-            if overflow == 0 and  fd_0["data_union"]["fd"] == 0 and \
-                fd_0["events"]["EPOLLIN"] == 1:
+            if (
+                overflow == 0
+                and fd_0["data_union"]["fd"] == 0
+                and fd_0["events"]["EPOLLIN"] == 1
+            ):
                 self.expect["epoll_wait_exit"]["epoll_wait_out_fd0"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -396,16 +425,20 @@ class Test1(TraceParser):
         # check that FD 0 returned with EPOLLIN and the right data.fd
         if ret == 1 and fds_length == 1:
             fd_0 = event["fds"][0]
-            if overflow == 0 and  fd_0["data_union"]["fd"] == 0 and \
-                fd_0["events"]["EPOLLIN"] == 1:
+            if (
+                overflow == 0
+                and fd_0["data_union"]["fd"] == 0
+                and fd_0["events"]["EPOLLIN"] == 1
+            ):
                 self.expect["epoll_pwait_exit"]["epoll_pwait_out_fd0"] = 1
 
         # Save values of local variables to print in case of test failure
         self.recorded_values["epoll_pwait_exit"] = locals()
 
-class Test2(TraceParser):
+
+class WorkingCasesTimeout(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["select_entry"]["select_timeout_in_fd0"] = 0
         self.expect["select_entry"]["select_timeout_in_fd1023"] = 0
         self.expect["select_exit"]["select_timeout_out"] = 0
@@ -427,8 +460,12 @@ class Test2(TraceParser):
             writefd_127 = event["writefds"][127]
             exceptfd_127 = event["exceptfds"][127]
 
-            if readfd_127 == 0x40 and writefd_127 == 0 and \
-                    exceptfd_127 == 0 and tvp != 0:
+            if (
+                readfd_127 == 0x40
+                and writefd_127 == 0
+                and exceptfd_127 == 0
+                and tvp != 0
+            ):
                 self.expect["select_entry"]["select_timeout_in_fd1023"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -452,9 +489,11 @@ class Test2(TraceParser):
         # field matches the value of POLLIN
         if nfds == 1 and fds_length == 1:
             fd_0 = event["fds"][0]
-            if fd_0["raw_events"] == 0x3 and \
-                    fd_0["events"]["POLLIN"] == 1 and \
-                    fd_0["events"]["padding"] == 0:
+            if (
+                fd_0["raw_events"] == 0x3
+                and fd_0["events"]["POLLIN"] == 1
+                and fd_0["events"]["padding"] == 0
+            ):
                 self.expect["poll_entry"]["poll_timeout_in"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -476,9 +515,11 @@ class Test2(TraceParser):
         _event = event["event"]
 
         # make sure we see a EPOLLIN|EPOLLPRI
-        if 'EPOLL_CTL_ADD' in op_enum.labels and \
-                _event["events"]["EPOLLIN"] == 1 and \
-                _event["events"]["EPOLLPRI"] == 1:
+        if (
+            "EPOLL_CTL_ADD" in op_enum.labels
+            and _event["events"]["EPOLLIN"] == 1
+            and _event["events"]["EPOLLPRI"] == 1
+        ):
             self.expect["epoll_ctl_entry"]["epoll_ctl_timeout_in_add"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -515,9 +556,9 @@ class Test2(TraceParser):
         self.recorded_values["epoll_wait_exit"] = locals()
 
 
-class Test3(TraceParser):
+class PselectInvalidFd(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["select_entry"]["select_invalid_fd_in"] = 0
         self.expect["select_exit"]["select_invalid_fd_out"] = 0
 
@@ -544,9 +585,9 @@ class Test3(TraceParser):
         self.recorded_values["select_exit"] = locals()
 
 
-class Test4(TraceParser):
+class PpollBig(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["poll_entry"]["big_poll_in"] = 0
         self.expect["poll_exit"]["big_poll_out"] = 0
 
@@ -559,10 +600,13 @@ class Test4(TraceParser):
         if nfds == 2047 and fds_length == 512 and overflow == 1:
             fd_0 = event["fds"][0]
             fd_511 = event["fds"][511]
-            if fd_0["raw_events"] == 0x3 and fd_0["events"]["POLLIN"] == 1 and \
-                    fd_0["events"]["padding"] == 0 and \
-                    fd_511["events"]["POLLIN"] == 1 and \
-                    fd_511["events"]["POLLPRI"] == 1:
+            if (
+                fd_0["raw_events"] == 0x3
+                and fd_0["events"]["POLLIN"] == 1
+                and fd_0["events"]["padding"] == 0
+                and fd_511["events"]["POLLIN"] == 1
+                and fd_511["events"]["POLLPRI"] == 1
+            ):
                 self.expect["poll_entry"]["big_poll_in"] = 1
 
         # Save values of local variables to print in case of test failure
@@ -576,17 +620,18 @@ class Test4(TraceParser):
 
         # test of big list of FDs and the behaviour of the overflow
         if ret == 2047 and nfds == 2047 and fds_length == 512 and overflow == 1:
-                fd_0 = event["fds"][0]
-                fd_511 = event["fds"][511]
-                if fd_0["events"]["POLLIN"] == 1 and fd_511["events"]["POLLIN"] == 1:
-                    self.expect["poll_exit"]["big_poll_out"] = 1
+            fd_0 = event["fds"][0]
+            fd_511 = event["fds"][511]
+            if fd_0["events"]["POLLIN"] == 1 and fd_511["events"]["POLLIN"] == 1:
+                self.expect["poll_exit"]["big_poll_out"] = 1
 
         # Save values of local variables to print in case of test failure
         self.recorded_values["poll_exit"] = locals()
 
-class Test5(TraceParser):
+
+class PpollFdsBufferOverflow(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["poll_entry"]["poll_overflow_in"] = 0
         self.expect["poll_exit"]["poll_overflow_out"] = 0
 
@@ -618,9 +663,9 @@ class Test5(TraceParser):
         self.recorded_values["poll_exit"] = locals()
 
 
-class Test6(TraceParser):
+class PselectInvalidPointer(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["select_entry"]["pselect_invalid_in"] = 0
         self.expect["select_exit"]["pselect_invalid_out"] = 0
 
@@ -651,9 +696,9 @@ class Test6(TraceParser):
         self.recorded_values["select_exit"] = locals()
 
 
-class Test7(TraceParser):
+class PpollFdsULongMax(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
         self.expect["poll_entry"]["poll_max_in"] = 0
         self.expect["poll_exit"]["poll_max_out"] = 0
 
@@ -668,7 +713,6 @@ class Test7(TraceParser):
         # Save values of local variables to print in case of test failure
         self.recorded_values["poll_entry"] = locals()
 
-
     def poll_exit(self, event):
         ret = event["ret"]
         nfds = event["nfds"]
@@ -682,12 +726,12 @@ class Test7(TraceParser):
         self.recorded_values["poll_exit"] = locals()
 
 
-class Test8(TraceParser):
+class EpollPwaitInvalidPointer(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
 
         # Values expected in the trace
-        self.epoll_fd = validation_args['epollfd']
+        self.epoll_fd = validation_args["epollfd"]
 
         self.expect["epoll_wait_entry"]["epoll_wait_invalid_in"] = 0
         self.expect["epoll_wait_exit"]["epoll_wait_invalid_out"] = 0
@@ -719,12 +763,12 @@ class Test8(TraceParser):
         self.recorded_values["epoll_wait_exit"] = locals()
 
 
-class Test9(TraceParser):
+class EpollPwaitIntMax(TraceParser):
     def __init__(self, trace, validation_args):
-        super().__init__(trace, validation_args['pid'])
+        super().__init__(trace, validation_args["pid"])
 
         # Values expected in the trace
-        self.epoll_fd = validation_args['epollfd']
+        self.epoll_fd = validation_args["epollfd"]
 
         self.expect["epoll_wait_entry"]["epoll_wait_max_in"] = 0
         self.expect["epoll_wait_exit"]["epoll_wait_max_out"] = 0
@@ -755,10 +799,12 @@ class Test9(TraceParser):
 
 
 if __name__ == "__main__":
-    parser = argparse.ArgumentParser(description='Trace parser')
-    parser.add_argument('path', metavar="<path/to/trace>", help='Trace path')
-    parser.add_argument('-t', '--test', type=int, help='Test to validate')
-    parser.add_argument('-o', '--validation-file', type=str, help='Validation file path')
+    parser = argparse.ArgumentParser(description="Trace parser")
+    parser.add_argument("path", metavar="<path/to/trace>", help="Trace path")
+    parser.add_argument("-t", "--test", type=str, help="Test to validate")
+    parser.add_argument(
+        "-o", "--validation-file", type=str, help="Validation file path"
+    )
     args = parser.parse_args()
 
     if not args.test:
@@ -775,33 +821,33 @@ if __name__ == "__main__":
         try:
             test_validation_args = json.load(f)
         except Exception as e:
-            print('Failed to parse validation file: ' + str(e))
+            print("Failed to parse validation file: " + str(e))
             sys.exit(1)
 
     t = None
 
-    if args.test == 1:
-        t = Test1(traces, test_validation_args)
-    elif args.test == 2:
-        t = Test2(traces, test_validation_args)
-    elif args.test == 3:
-        t = Test3(traces, test_validation_args)
-    elif args.test == 4:
-        t = Test4(traces, test_validation_args)
-    elif args.test == 5:
-        t = Test5(traces, test_validation_args)
-    elif args.test == 6:
-        t = Test6(traces, test_validation_args)
-    elif args.test == 7:
-        t = Test7(traces, test_validation_args)
-    elif args.test == 8:
-        t = Test8(traces, test_validation_args)
-    elif args.test == 9:
-        t = Test9(traces, test_validation_args)
-    elif args.test == 10:
+    if args.test == "working_cases":
+        t = WorkingCases(traces, test_validation_args)
+    elif args.test == "working_cases_timeout":
+        t = WorkingCasesTimeout(traces, test_validation_args)
+    elif args.test == "pselect_invalid_fd":
+        t = PselectInvalidFd(traces, test_validation_args)
+    elif args.test == "ppoll_big":
+        t = PpollBig(traces, test_validation_args)
+    elif args.test == "ppoll_fds_buffer_overflow":
+        t = PpollFdsBufferOverflow(traces, test_validation_args)
+    elif args.test == "pselect_invalid_pointer":
+        t = PselectInvalidPointer(traces, test_validation_args)
+    elif args.test == "ppoll_fds_ulong_max":
+        t = PpollFdsULongMax(traces, test_validation_args)
+    elif args.test == "epoll_pwait_invalid_pointer":
+        t = EpollPwaitInvalidPointer(traces, test_validation_args)
+    elif args.test == "epoll_pwait_int_max":
+        t = EpollPwaitIntMax(traces, test_validation_args)
+    elif args.test == "ppoll_concurrent_write":
         # stress test, nothing reliable to check
         ret = 0
-    elif args.test == 11:
+    elif args.test == "epoll_pwait_concurrent_munmap":
         # stress test, nothing reliable to check
         ret = 0
     else:
index fc39333c01a9a8bdcb500db222069bc79638c517..ecd4eabd62d5d9c1faab9f5065977f69ca2a5eb4 100644 (file)
@@ -3,6 +3,8 @@
 SUBDIRS = base-path \
        channel \
        clear \
+       client \
+       context \
        crash \
        exclusion \
        filtering \
index 38a0877531c8ea94ace15f2000140f40a5e0cda9..c7f03b59baa0d674fd14e1d50a63af581cb9a69a 100755 (executable)
@@ -13,7 +13,7 @@ TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_base_path_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_base_path_ust_trace_path.XXXXXX)
 
 NUM_TESTS=42
 
index 7244ac3c7d5f7e558dae133e21aae4cac5ded596..a530b649dcaa55ce25fb88703df80e3ecfef9a70 100755 (executable)
@@ -19,7 +19,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_channel_disable_stopped_session()
 {
-       local TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        local SESSION_NAME="test_channel"
        local CHAN_NAME="channel0"
        local EVENT_NAME="tp:tptest"
index 97f8d83a30021d0eae4e8d5057cec258b38f1901..dd0f0542109b44aff117ae27e51ab1f4d549b0a1 100644 (file)
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-noinst_SCRIPTS = test_kernel test_ust
-EXTRA_DIST = test_kernel test_ust
+noinst_SCRIPTS = test_kernel test_ust test_live_hang.py
+EXTRA_DIST = test_kernel test_ust test_live_hang.py
 
 all-local:
        @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
index 0229f5f92d1defd72ca29f8cb73eda43a834c8e4..2e383b8aa6c0971705831974fefcf0e2b644e776 100755 (executable)
@@ -11,11 +11,12 @@ TESTDIR=$CURDIR/../../..
 EVENT_NAME="lttng_test_filter_event"
 
 PAGE_SIZE=$(getconf PAGE_SIZE)
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_clear_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_clear_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=837
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source=../utils/utils.sh
+source "$TESTDIR/utils/utils.sh"
 
 function signal_cleanup ()
 {
@@ -200,8 +201,8 @@ function test_kernel_basic_streaming_live_viewer ()
        local local_path="${TRACE_PATH}/${HOSTNAME}/${SESSION_NAME}*"
        local remote_trace_path="${HOSTNAME}/${SESSION_NAME}"
        local channel_name="chan"
-       local bt_output_path=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
-       local file_sync_before_exit=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
+       local bt_output_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
+       local file_sync_before_exit=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
 
        diag "Test kernel basic streaming live with viewer"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice"
@@ -247,7 +248,7 @@ function test_kernel_streaming_live_viewer ()
        local local_path="${TRACE_PATH}/${HOSTNAME}/${SESSION_NAME}*"
        local remote_trace_path="${HOSTNAME}/${SESSION_NAME}"
        local channel_name="chan"
-       local bt_output_path=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
+       local bt_output_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
 
        diag "Test kernel streaming live clear with viewer"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice"
@@ -488,7 +489,7 @@ function test_kernel_streaming_tracefile_rotation_overwrite_files ()
                --tracefile-size=$PAGE_SIZE --tracefile-count=2
        enable_kernel_lttng_event_ok $SESSION_NAME $EVENT_NAME $channel_name
        start_lttng_tracing_ok $SESSION_NAME
-       taskset -c 0 echo -n "200000" > /proc/lttng-test-filter-event
+       taskset -c "$(get_any_available_cpu)" echo -n "200000" > /proc/lttng-test-filter-event
        do_clear_session $SESSION_NAME $tracing_active $clear_twice $rotate_before $rotate_after
        stop_lttng_tracing_ok $SESSION_NAME
 
@@ -499,7 +500,7 @@ function test_kernel_streaming_tracefile_rotation_overwrite_files ()
        fi
 
        start_lttng_tracing_ok $SESSION_NAME
-       taskset -c 0 echo -n "400000" > /proc/lttng-test-filter-event
+       taskset -c "$(get_any_available_cpu)" echo -n "400000" > /proc/lttng-test-filter-event
        stop_lttng_tracing_ok
 
        if [[ $rotate_before -eq 1 ]]; then
@@ -537,12 +538,6 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
 streaming_tests=(test_kernel_streaming
        test_kernel_streaming_rotate_clear
        test_kernel_streaming_clear_rotate
@@ -564,7 +559,7 @@ snapshot_tests=(test_kernel_streaming_snapshot
        test_kernel_local_snapshot
 )
 
-skip $isroot "Root access is needed. Skipping all kernel streaming tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping kernel streaming tests." ||
 {
        trap signal_cleanup SIGTERM SIGINT
 
diff --git a/tests/regression/tools/clear/test_live_hang.py b/tests/regression/tools/clear/test_live_hang.py
new file mode 100755 (executable)
index 0000000..67a89bc
--- /dev/null
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""
+Test for https://review.lttng.org/c/lttng-tools/+/11819
+
+A live client shouldn't hang around after a session with no data has
+been destroyed
+"""
+
+import pathlib
+import socket
+import subprocess
+import sys
+import time
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import bt2
+
+tap = lttngtest.TapGenerator(1)
+
+
+def test_live_hang(tap, test_env):
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    # lttng create --live
+    output = lttngtest.NetworkSessionOutputLocation(
+        "net://localhost:{}:{}/".format(
+            test_env.lttng_relayd_control_port, test_env.lttng_relayd_data_port
+        )
+    )
+    session = client.create_session(output=output, live=True)
+
+    # lttng enable-event --userspace --all
+    channel = session.add_channel(lttngtest.lttngctl.TracingDomain.User)
+    channel.add_recording_rule(lttngtest.lttngctl.UserTracepointEventRule())
+
+    session.start()
+    test_app = test_env.launch_wait_trace_test_application(100)
+    session.stop()
+    session.clear()
+
+    ctf_live_cc = bt2.find_plugin("ctf").source_component_classes["lttng-live"]
+    query_executor = bt2.QueryExecutor(
+        ctf_live_cc,
+        "sessions",
+        params={"url": "net://localhost:{}".format(test_env.lttng_relayd_live_port)},
+    )
+
+    # wait until 'ready'
+    ready = False
+    query_result = None
+    while not ready:
+        try:
+            query_result = query_executor.query()
+        except bt2._Error:
+            time.sleep(0.1)
+            continue
+
+        for live_session in query_result:
+            if live_session["session-name"] == session.name:
+                ready = True
+                break
+        time.sleep(0.1)
+
+    # start live viewer
+    bt2_args = [
+        "babeltrace2",
+        "-i",
+        "lttng-live",
+        "net://localhost:{}/host/{}/{}".format(
+            test_env.lttng_relayd_live_port, socket.gethostname(), session.name
+        ),
+        "--params=session-not-found-action=end",
+    ]
+    tap.diagnostic("Running bt2: {}".format(bt2_args))
+    bt2_proc = subprocess.Popen(bt2_args)
+
+    # wait until one client is connected
+    ready = False
+    while not ready:
+        try:
+            query_result = query_executor.query()
+        except bt2._Error:
+            time.sleep(0.1)
+            continue
+        for live_session in query_result:
+            if (
+                live_session["session-name"] == session.name
+                and live_session["client-count"] == 1
+            ):
+                ready = True
+                break
+        time.sleep(0.1)
+
+    session.destroy()
+
+    # assert live viewer has exited
+    stopped = False
+    try:
+        bt2_proc.wait(5)
+        stopped = True
+    except subprocess.TimeoutExpired as e:
+        tap.diagnostic("Timed out (5s) waiting for babeltrace2 to return")
+    tap.test(
+        stopped and bt2_proc.returncode == 0, "BT2 live viewer exited successfully"
+    )
+    if not stopped:
+        bt2_proc.terminate()
+
+
+with lttngtest.test_environment(
+    with_sessiond=True, log=tap.diagnostic, with_relayd=True
+) as test_env:
+    test_live_hang(tap, test_env)
+
+sys.exit(0 if tap.is_successful else 1)
index 27cd71fe9299b21f0778c407c4edc0f4f9a98b36..104753b98474ea57bf5a32538daee9f0bb5143b5 100755 (executable)
@@ -17,11 +17,13 @@ TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 
 NUM_TESTS=2071
-
+DELAYUS=500000
+LIVEVIEWER_TIMEOUT=10  # Timeout in seconds
 PAGE_SIZE=$(getconf PAGE_SIZE)
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_clear_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_clear_ust_trace_path.XXXXXX)
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source=../utils/utils.sh
+source "$TESTDIR/utils/utils.sh"
 
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST events binary detected."
@@ -112,7 +114,7 @@ function test_ust_streaming ()
                fi
        fi
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_streaming_no_event ()
@@ -137,7 +139,7 @@ function test_ust_streaming_no_event ()
 
        validate_directory_empty "$local_path"
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_streaming_rotate_clear ()
@@ -170,7 +172,7 @@ function test_ust_streaming_rotate_clear ()
        fi
        validate_trace_count $EVENT_NAME $local_path $expect_count
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_streaming_clear_rotate ()
@@ -203,7 +205,7 @@ function test_ust_streaming_clear_rotate ()
        fi
        validate_trace_count $EVENT_NAME $local_path $expect_count
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_streaming_live ()
@@ -217,7 +219,7 @@ function test_ust_streaming_live ()
 
        diag "Test ust streaming live clear"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice, buffer_type=$buffer_type"
-       create_lttng_session_uri $SESSION_NAME net://localhost "--live"
+       create_lttng_session_uri $SESSION_NAME net://localhost "--live=${DELAYUS}"
        enable_ust_lttng_channel_ok $SESSION_NAME $channel_name --buffers-$buffer_type
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $channel_name
        start_lttng_tracing_ok $SESSION_NAME
@@ -231,7 +233,7 @@ function test_ust_streaming_live ()
                validate_directory_empty $local_path
        fi
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 #no clear
@@ -244,12 +246,13 @@ function test_ust_basic_streaming_live_viewer ()
        local local_path="${TRACE_PATH}/${HOSTNAME}/${SESSION_NAME}*"
        local remote_trace_path="${HOSTNAME}/${SESSION_NAME}"
        local channel_name="chan"
-       local bt_output_path=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_bt_output_path.XXXXXX)
-       local file_sync_before_exit=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_sync_before_exit.XXXXXX)
+       local bt_output_path=$(mktemp -u -t tmp.test_${FUNCNAME[0]}_bt_output_path.XXXXXX)
+       local bt_error_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_error.XXXXXX")
+       local file_sync_before_exit=$(mktemp -u -t tmp.test_${FUNCNAME[0]}_sync_before_exit.XXXXXX)
 
        diag "Test ust basic streaming live with viewer"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice, buffer_type=$buffer_type"
-       create_lttng_session_uri $SESSION_NAME net://localhost "--live"
+       create_lttng_session_uri $SESSION_NAME net://localhost "--live=${DELAYUS}"
        enable_ust_lttng_channel_ok $SESSION_NAME $channel_name --buffers-$buffer_type
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $channel_name
        start_lttng_tracing_ok $SESSION_NAME
@@ -257,8 +260,9 @@ function test_ust_basic_streaming_live_viewer ()
        wait_live_trace_ready net://localhost
 
        # Connect a live viewer
-       $BABELTRACE_BIN -i lttng-live net://localhost/host/$remote_trace_path > $bt_output_path &
+       $BABELTRACE_BIN -i lttng-live net://localhost/host/$remote_trace_path --params=session-not-found-action=end 1> $bt_output_path 2> "${bt_error_path}" &
        local viewer_pid=$!
+       local viewer_iter=0
 
        wait_live_viewer_connect net://localhost
 
@@ -269,11 +273,15 @@ function test_ust_basic_streaming_live_viewer ()
        local evcount=0
        while [ $evcount -ne 10 ]; do
                evcount=$(cat $bt_output_path | wc -l)
-               sleep 0.5
+               sleep 0.1
+               viewer_iter=$((viewer_iter + 1))
+               if [ "${viewer_iter}" -gt $((LIVEVIEWER_TIMEOUT * 10)) ] ; then
+                       break;
+               fi
        done
-       pass "Live viewer read $evcount events, expect 10"
+       is "${evcount}" 10 "Live viewer read $evcount events, expect 10"
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
        touch $file_sync_before_exit
        diag "Waiting for application to exit"
        wait $app_pid
@@ -284,6 +292,7 @@ function test_ust_basic_streaming_live_viewer ()
        pass "Wait for viewer to exit"
 
        rm -f $bt_output_path
+       clean_path "${bt_error_path}"
        rm -f $file_sync_before_exit
 }
 
@@ -296,11 +305,12 @@ function test_ust_streaming_live_viewer ()
        local local_path="${TRACE_PATH}/${HOSTNAME}/${SESSION_NAME}*"
        local remote_trace_path="${HOSTNAME}/${SESSION_NAME}"
        local channel_name="chan"
-       local bt_output_path=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_bt_output_path.XXXXXX)
+       local bt_output_path=$(mktemp -u -t tmp.test_${FUNCNAME[0]}_bt_output_path.XXXXXX)
+       local bt_error_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_error.XXXXXX")
 
        diag "Test ust streaming live clear with viewer"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice, buffer_type=$buffer_type"
-       create_lttng_session_uri $SESSION_NAME net://localhost "--live"
+       create_lttng_session_uri $SESSION_NAME net://localhost "--live=${DELAYUS}"
        enable_ust_lttng_channel_ok $SESSION_NAME $channel_name --buffers-$buffer_type
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $channel_name
        start_lttng_tracing_ok $SESSION_NAME
@@ -308,7 +318,7 @@ function test_ust_streaming_live_viewer ()
        wait_live_trace_ready net://localhost
 
        # Connect a live viewer
-       $BABELTRACE_BIN -i lttng-live net://localhost/host/$remote_trace_path > $bt_output_path &
+       $BABELTRACE_BIN -i lttng-live net://localhost/host/$remote_trace_path --params=session-not-found-action=end 1> $bt_output_path 2> "${bt_error_path}" &
        local viewer_pid=$!
 
        wait_live_viewer_connect net://localhost
@@ -317,13 +327,14 @@ function test_ust_streaming_live_viewer ()
        do_clear_session $SESSION_NAME $tracing_active $clear_twice 0 0
        stop_lttng_tracing_ok $SESSION_NAME
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
        diag "Wait for viewer to exit"
        wait $viewer_pid
        ok $? "Babeltrace succeeds"
        pass "Wait for viewer to exit"
 
        clean_path $bt_output_path
+       clean_path "${bt_error_path}"
 }
 
 function test_ust_streaming_live_viewer_new_metadata_after_clear ()
@@ -336,13 +347,13 @@ function test_ust_streaming_live_viewer_new_metadata_after_clear ()
        local remote_trace_path="${HOSTNAME}/${SESSION_NAME}"
        local channel_name="chan"
 
-       local bt_output_path=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
-       local bt_error_path=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_bt_error.XXXXXX")
-       local file_sync_before_exit=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
+       local bt_output_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_output.XXXXXX")
+       local bt_error_path=$(mktemp -t "tmp.${FUNCNAME[0]}_bt_error.XXXXXX")
+       local file_sync_before_exit=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
 
        diag "Test ust streaming live clear with viewer with new metadata after clear"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice, buffer_type=$buffer_type"
-       create_lttng_session_uri "$SESSION_NAME" net://localhost "--live"
+       create_lttng_session_uri "$SESSION_NAME" net://localhost "--live=${DELAYUS}"
        enable_ust_lttng_channel_ok "$SESSION_NAME" $channel_name "--buffers-$buffer_type"
 
        # The vpid context is added to filter events based on the vpid of the
@@ -357,8 +368,9 @@ function test_ust_streaming_live_viewer_new_metadata_after_clear ()
        wait_live_trace_ready net://localhost
 
        # Connect a live viewer
-       $BABELTRACE_BIN -i lttng-live "net://localhost/host/$remote_trace_path" 1> "$bt_output_path" 2> "$bt_error_path" &
+       $BABELTRACE_BIN -i lttng-live "net://localhost/host/$remote_trace_path" --params=session-not-found-action=end 1> "$bt_output_path" 2> "$bt_error_path" &
        local viewer_pid=$!
+       local viewer_iter=0
 
        wait_live_viewer_connect net://localhost
 
@@ -369,9 +381,13 @@ function test_ust_streaming_live_viewer_new_metadata_after_clear ()
        local evcount=0
        while [ $evcount -ne 10 ]; do
                evcount=$(wc -l < "$bt_output_path")
-               sleep 0.5
+               sleep 0.1
+               viewer_iter=$((viewer_iter + 1))
+               if [ "${viewer_iter}" -gt $((LIVEVIEWER_TIMEOUT * 10)) ] ; then
+                       break
+               fi
        done
-       pass "Live viewer read $evcount events, expect 10"
+       is "${evcount}" 10 "Live viewer read $evcount events, expect 10"
 
        do_clear_session "$SESSION_NAME" "$tracing_active" "$clear_twice" 0 0
 
@@ -386,15 +402,20 @@ function test_ust_streaming_live_viewer_new_metadata_after_clear ()
 
        diag "Wait until viewer sees all 12 expected events"
        local evcount=0
+       local viewer_iter=0
        while [ $evcount -ne 12 ]; do
                evcount=$(wc -l < "$bt_output_path")
-               sleep 0.5
+               sleep 0.1
+               viewer_iter=$((viewer_iter + 1))
+               if [ "${viewer_iter}" -gt $((LIVEVIEWER_TIMEOUT * 10)) ]; then
+                       break
+               fi
        done
-       pass "Live viewer read $evcount events, expect 12"
+       is "${evcount}" 12 "Live viewer read $evcount events, expect 12"
 
        stop_lttng_tracing_ok "$SESSION_NAME"
 
-       destroy_lttng_session_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME" --no-wait
 
        touch "$file_sync_before_exit"
        diag "Waiting for application to exit"
@@ -443,7 +464,7 @@ function test_ust_local ()
                fi
        fi
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_local_no_event ()
@@ -467,7 +488,7 @@ function test_ust_local_no_event ()
 
        validate_directory_empty "$TRACE_PATH"
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_local_rotate_clear ()
@@ -499,7 +520,7 @@ function test_ust_local_rotate_clear ()
        fi
        validate_trace_count $EVENT_NAME $TRACE_PATH $expect_count
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_local_clear_rotate ()
@@ -531,7 +552,7 @@ function test_ust_local_clear_rotate ()
        fi
        validate_trace_count $EVENT_NAME $TRACE_PATH $expect_count
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function do_ust_snapshot ()
@@ -590,7 +611,7 @@ function test_ust_streaming_snapshot ()
 
        create_lttng_session_uri $SESSION_NAME net://localhost "--snapshot"
        do_ust_snapshot $SESSION_NAME $TRACE_PATH $tracing_active $clear_twice $buffer_type
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_local_snapshot ()
@@ -605,7 +626,7 @@ function test_ust_local_snapshot ()
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH "--snapshot"
        do_ust_snapshot $SESSION_NAME $TRACE_PATH $tracing_active $clear_twice $buffer_type
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 # snapshot for per-pid is tested independently of the "buffer type" parameter
@@ -617,10 +638,10 @@ function test_ust_local_snapshot_per_pid ()
        # 3, 4 unused.
        local buffer_type=$5
        local channel_name="channel0"
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
-       local file_sync_before_last_touch=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last_touch.XXXXXX")
-       local file_sync_before_exit=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
-       local file_sync_before_exit_touch=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_sync_before_exit_touch.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_before_last_touch=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last_touch.XXXXXX")
+       local file_sync_before_exit=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_exit.XXXXXX")
+       local file_sync_before_exit_touch=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_exit_touch.XXXXXX")
 
        diag "Test ust local snapshot clear per pid"
        diag "Parameters: tracing_active=$tracing_active, clear_twice=$clear_twice, buffer_type=$buffer_type"
@@ -636,10 +657,11 @@ function test_ust_local_snapshot_per_pid ()
                --sync-before-last-event-touch ${file_sync_before_last_touch} \
                --sync-before-exit ${file_sync_before_exit} \
                --sync-before-exit-touch ${file_sync_before_exit_touch} >/dev/null 2>&1 &
+       local app_pid="${!}"
 
        # Continue only when there is only the last event remaining.
        while [ ! -f "${file_sync_before_last_touch}" ]; do
-               sleep 0.5
+               sleep 0.1
        done
 
        # Take a first snapshot and validate that the events are present.
@@ -669,7 +691,7 @@ function test_ust_local_snapshot_per_pid ()
        # Wait for the before exit sync point. This ensure that we went over the
        # last tracepoint.
        while [ ! -f "${file_sync_before_exit_touch}" ]; do
-               sleep 0.5
+               sleep 0.1
        done
 
        # Make sure the snapshot contains the last event.
@@ -679,8 +701,8 @@ function test_ust_local_snapshot_per_pid ()
 
        # Release the application.
        touch ${file_sync_before_exit}
-       wait
-       destroy_lttng_session_ok $SESSION_NAME
+       wait "${app_pid}"
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        rm -f ${file_sync_before_last}
        rm -f ${file_sync_before_last_touch}
@@ -729,7 +751,7 @@ function test_ust_streaming_tracefile_rotation ()
                validate_trace_count $EVENT_NAME $local_path 20
        fi
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 # With 1 byte per event (as strict minimum), generating 200000 events
@@ -752,7 +774,7 @@ function test_ust_streaming_tracefile_rotation_overwrite_files ()
                --tracefile-size=$PAGE_SIZE --tracefile-count=2 --buffers-$buffer_type
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $channel_name
        start_lttng_tracing_ok $SESSION_NAME
-       taskset -c 0 $TESTAPP_BIN -i 200000
+       taskset -c "$(get_any_available_cpu)" $TESTAPP_BIN -i 200000
        do_clear_session $SESSION_NAME $tracing_active $clear_twice $rotate_before $rotate_after
        stop_lttng_tracing_ok $SESSION_NAME
 
@@ -767,7 +789,7 @@ function test_ust_streaming_tracefile_rotation_overwrite_files ()
        fi
 
        start_lttng_tracing_ok $SESSION_NAME
-       taskset -c 0 $TESTAPP_BIN -i 400000
+       taskset -c "$(get_any_available_cpu)" $TESTAPP_BIN -i 400000
        stop_lttng_tracing_ok
 
        if [[ $rotate_before -eq 1 ]]; then
@@ -776,7 +798,7 @@ function test_ust_streaming_tracefile_rotation_overwrite_files ()
                validate_trace_count_range_incl_min_excl_max $EVENT_NAME $local_path 1 200000
        fi
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 }
 
 function test_ust_disallow_clear ()
@@ -792,7 +814,7 @@ function test_ust_disallow_clear ()
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME
        start_lttng_tracing_ok $SESSION_NAME
        lttng_clear_session_fail $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        stop_lttng_sessiond
        stop_lttng_relayd
diff --git a/tests/regression/tools/client/Makefile.am b/tests/regression/tools/client/Makefile.am
new file mode 100644 (file)
index 0000000..5a85480
--- /dev/null
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+noinst_SCRIPTS = test_session_commands.py test_event_rule_listing.py \
+       test_bug1373_events_differ_only_by_loglevel
+EXTRA_DIST = test_session_commands.py test_event_rule_listing.py \
+       test_bug1373_events_differ_only_by_loglevel
+
+all-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       cp -f $(srcdir)/$$script $(builddir); \
+               done; \
+       fi
+
+clean-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       rm -f $(builddir)/$$script; \
+               done; \
+       fi
diff --git a/tests/regression/tools/client/test_bug1373_events_differ_only_by_loglevel b/tests/regression/tools/client/test_bug1373_events_differ_only_by_loglevel
new file mode 100755 (executable)
index 0000000..1508583
--- /dev/null
@@ -0,0 +1,60 @@
+#!/bin/bash
+#
+# Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+#
+# SPDX-License-Identifier: LGPL-2.1-only
+#
+
+TEST_DESC="lttng-sessiond should not crash when activating rules that different by loglevel only"
+
+CURDIR=$(dirname "$0")
+TESTDIR=$(realpath "${CURDIR}/../../../")
+
+# Test app for ust event
+TESTAPP_PATH="${TESTDIR}/utils/testapp"
+TESTAPP_NAME="gen-ust-events"
+TESTAPP_BIN="${TESTAPP_PATH}/${TESTAPP_NAME}/${TESTAPP_NAME}"
+NR_USEC_WAIT=1
+NR_ITER=100000
+
+SESSION_NAME="test_session"
+CHANNEL_NAME="test_channel"
+EVENT_NAME="'l*'"
+
+OUTPUT_DIR=$(mktemp -d -t tmp.test_events_differ_only_by_loglevels.XXXXXX)
+
+NUM_TESTS=9
+
+# shellcheck source-path=SCRIPTDIR/../../../
+source "${TESTDIR}/utils/utils.sh"
+
+if [ ! -x "${TESTAPP_BIN}" ] ; then
+    BAIL_OUT "No UST events binary detected"
+fi
+
+plan_tests "${NUM_TESTS}"
+print_test_banner "${TEST_DESC}"
+bail_out_if_no_babeltrace
+
+# shellcheck disable=SC2119
+start_lttng_sessiond
+
+"${TESTAPP_BIN}" -i "${NR_ITER}" -w "${NR_USEC_WAIT}" &
+ TESTAPP_PID="${!}"
+
+create_lttng_session_ok "${SESSION_NAME}" "${OUTPUT_DIR}"
+enable_ust_lttng_channel_ok "${SESSION_NAME}" "${CHANNEL_NAME}"
+start_lttng_tracing_ok "${SESSION_NAME}"
+enable_ust_lttng_event_loglevel "${SESSION_NAME}" "${EVENT_NAME}" TRACE_DEBUG_LINE "${CHANNEL_NAME}"
+enable_ust_lttng_event_loglevel_only "${SESSION_NAME}" "${EVENT_NAME}" TRACE_DEBUG_LINE "${CHANNEL_NAME}"
+
+sleep 1
+
+stop_lttng_tracing_ok "${SESSION_NAME}"
+destroy_lttng_session_ok "${SESSION_NAME}"
+
+# shellcheck disable=SC2119
+stop_lttng_sessiond
+
+kill "${TESTAPP_PID}"
+rm -rf "${OUTPUT_DIR}"
diff --git a/tests/regression/tools/client/test_bug1480_assert_data_pending b/tests/regression/tools/client/test_bug1480_assert_data_pending
new file mode 100755 (executable)
index 0000000..cf7216e
--- /dev/null
@@ -0,0 +1,43 @@
+#!/bin/bash
+#
+# Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+TEST_DESC="lttng-sessiond should not crash when receiving data-pending for an active session"
+CURDIR=$(dirname "$0")
+TESTDIR=$(realpath "${CURDIR}/../../../")
+# Test app for ust event
+TESTAPP_PATH="${TESTDIR}/utils/testapp"
+TESTAPP_NAME="gen-data-pending"
+TESTAPP_BIN="${TESTAPP_PATH}/${TESTAPP_NAME}/${TESTAPP_NAME}"
+SESSION_NAME=asdf
+
+NUM_TESTS=7
+
+# shellcheck source-path=SCRIPTDIR/../../../
+source "${TESTDIR}/utils/utils.sh"
+if [ ! -x "${TESTAPP_BIN}" ] ; then
+    BAIL_OUT "Test binary '${TESTAPP_BIN}' not detected or not executable"
+fi
+
+OUTPUT_DIR=$(mktemp -d)
+CHANNEL_NAME=asdf
+
+plan_tests "${NUM_TESTS}"
+print_test_banner "${TEST_DESC}"
+
+# shellcheck disable=SC2119
+start_lttng_sessiond
+
+create_lttng_session_ok "${SESSION_NAME}" "${OUTPUT_DIR}"
+enable_ust_lttng_channel_ok "${SESSION_NAME}" "${CHANNEL_NAME}"
+start_lttng_tracing_ok "${SESSION_NAME}"
+
+"${TESTAPP_BIN}" "${SESSION_NAME}"
+
+stop_lttng_tracing_ok "${SESSION_NAME}"
+destroy_lttng_session_ok "${SESSION_NAME}"
+# shellcheck disable=SC2119
+stop_lttng_sessiond
+rm -rf "${OUTPUT_DIR}"
diff --git a/tests/regression/tools/client/test_event_rule_listing.py b/tests/regression/tools/client/test_event_rule_listing.py
new file mode 100755 (executable)
index 0000000..e06deee
--- /dev/null
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+import pathlib
+import sys
+import os
+from typing import Any, Callable, Type, Dict, Iterator
+import random
+import string
+from collections.abc import Mapping
+
+"""
+Test the listing of recording rules associated to a channel.
+"""
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+
+
+def test_identical_recording_rules_except_log_level_rule_type(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic(
+        "Test adding and listing event rules that differ only by their log level rule type"
+    )
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    session = client.create_session()
+    channel = session.add_channel(lttngtest.TracingDomain.User)
+    session.start()
+
+    app = test_env.launch_wait_trace_test_application(100)
+
+    llr_exactly = lttngtest.LogLevelRuleExactly(lttngtest.UserLogLevel.DEBUG_LINE)
+    llr_as_severe_as = lttngtest.LogLevelRuleAsSevereAs(
+        lttngtest.UserLogLevel.DEBUG_LINE
+    )
+
+    recording_rule_log_at_level = lttngtest.UserTracepointEventRule(
+        "lttng*", None, llr_exactly, None
+    )
+    recording_rule_log_at_least_level = lttngtest.UserTracepointEventRule(
+        "lttng*", None, llr_as_severe_as, None
+    )
+    recording_rule_no_log_level = lttngtest.UserTracepointEventRule(
+        "lttng*", None, None, None
+    )
+
+    with tap.case("Adding a recording rule with an `exact` log level rule"):
+        channel.add_recording_rule(recording_rule_log_at_level)
+
+    with tap.case("Adding a recording rule with an `as severe as` log level rule"):
+        channel.add_recording_rule(recording_rule_log_at_least_level)
+
+    with tap.case(
+        "Adding a recording rule without a log level rule (all log levels enabled)"
+    ):
+        channel.add_recording_rule(recording_rule_no_log_level)
+
+    rule_match_count = 0
+    for rule in channel.recording_rules:
+        if (
+            rule != recording_rule_no_log_level
+            and rule != recording_rule_log_at_level
+            and rule != recording_rule_log_at_least_level
+        ):
+            continue
+
+        rule_match_count = rule_match_count + 1
+
+    tap.test(
+        rule_match_count == 3,
+        "Recording rules are added and listed",
+    )
+
+
+tap = lttngtest.TapGenerator(4)
+tap.diagnostic("Test the addition and listing of event rules associated to a channel")
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_identical_recording_rules_except_log_level_rule_type(tap, test_env)
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/tools/client/test_session_commands.py b/tests/regression/tools/client/test_session_commands.py
new file mode 100755 (executable)
index 0000000..8666c3a
--- /dev/null
@@ -0,0 +1,484 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+import pathlib
+import sys
+import os
+from typing import Any, Callable, Type, Dict, Iterator
+import random
+import string
+from collections.abc import Mapping
+
+"""
+Test the session commands of the `lttng` CLI client.
+"""
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import bt2
+
+
+class SessionSet(Mapping):
+    def __init__(self, client, name_prefixes):
+        self._sessions = {}  # type dict[str, lttngtest.Session]
+        for prefix in name_prefixes:
+            new_session = client.create_session(
+                name=self._generate_session_name_from_prefix(prefix),
+                output=lttngtest.LocalSessionOutputLocation(
+                    test_env.create_temporary_directory("trace")
+                ),
+            )
+            # Add a channel to all sessions to ensure the sessions can be started.
+            new_session.add_channel(lttngtest.TracingDomain.User)
+            self._sessions[prefix] = new_session
+
+    @staticmethod
+    def _generate_session_name_from_prefix(prefix):
+        # type: (str) -> str
+        return (
+            prefix
+            + "_"
+            + "".join(
+                random.choice(string.ascii_lowercase + string.digits) for _ in range(8)
+            )
+        )
+
+    def __getitem__(self, __key):
+        # type: (str) -> lttngtest.Session
+        return self._sessions[__key]
+
+    def __len__(self):
+        # type: () -> int
+        return len(self._sessions)
+
+    def __iter__(self):
+        # type: () -> Iterator[str]
+        return iter(self._sessions)
+
+
+def test_start_globbing(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test --glob match of start command")
+    name_prefixes = ["abba", "alakazou", "alakazam"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test globbing")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    tap.test(
+        all(not session.is_active for prefix, session in sessions.items()),
+        "All sessions created are in the inactive state",
+    )
+
+    start_pattern = "alak*"
+    with tap.case("Start sessions with --glob={}".format(start_pattern)) as test_case:
+        client.start_session_by_glob_pattern(start_pattern)
+
+    tap.test(
+        sessions["alakazou"].is_active
+        and sessions["alakazam"].is_active
+        and not sessions["abba"].is_active,
+        "Only sessions 'alakazou' and 'alakazam' are active",
+    )
+
+    with tap.case(
+        "Starting already started sessions with --glob={} doesn't produce an error".format(
+            start_pattern
+        )
+    ) as test_case:
+        client.start_session_by_glob_pattern(start_pattern)
+
+    start_pattern = "tintina*"
+    with tap.case(
+        "Starting with --glob={} that doesn't match any session doesn't produce an error".format(
+            start_pattern
+        )
+    ) as test_case:
+        client.start_session_by_glob_pattern(start_pattern)
+
+    for name, session in sessions.items():
+        session.destroy()
+
+    with tap.case(
+        "Starting with --glob={} when no sessions exist doesn't produce an error".format(
+            start_pattern
+        )
+    ) as test_case:
+        client.start_session_by_glob_pattern(start_pattern)
+
+
+def test_start_single(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test match of start command targeting a single session")
+    name_prefixes = ["un", "deux", "patate", "pouel"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test single session start")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    tap.test(
+        all(not session.is_active for prefix, session in sessions.items()),
+        "All sessions created are in the inactive state",
+    )
+
+    session_to_start_prefix = "patate"
+    full_session_name = sessions[session_to_start_prefix].name
+    with tap.case("Start session '{}'".format(session_to_start_prefix)) as test_case:
+        client.start_session_by_name(full_session_name)
+
+    tap.test(
+        any(
+            session.is_active and prefix != session_to_start_prefix
+            for prefix, session in sessions.items()
+        )
+        is False,
+        "Only session '{}' is active".format(session_to_start_prefix),
+    )
+
+    with tap.case(
+        "Starting already started session '{}' doesn't produce an error".format(
+            session_to_start_prefix
+        )
+    ) as test_case:
+        client.start_session_by_name(full_session_name)
+
+    for name, session in sessions.items():
+        session.destroy()
+
+
+def test_start_all(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test start command with the --all option")
+    name_prefixes = ["a", "b", "c", "d"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test starting all sessions")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    tap.test(
+        all(not session.is_active for prefix, session in sessions.items()),
+        "All sessions created are in the inactive state",
+    )
+
+    with tap.case("Start all sessions") as test_case:
+        client.start_sessions_all()
+
+    tap.test(
+        all(session.is_active for prefix, session in sessions.items()),
+        "All sessions are active",
+    )
+
+    with tap.case("Starting already started sessions") as test_case:
+        client.start_sessions_all()
+
+    for name, session in sessions.items():
+        session.destroy()
+
+    with tap.case(
+        "Starting all sessions when none exist doesn't produce an error"
+    ) as test_case:
+        client.start_sessions_all()
+
+
+def test_stop_globbing(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test --glob match of stop command")
+    name_prefixes = ["East Farnham", "Amqui", "Amos"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test globbing")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    client.start_sessions_all()
+    tap.test(
+        all(session.is_active for prefix, session in sessions.items()),
+        "All sessions are in the active state",
+    )
+
+    stop_pattern = "Am??i*"
+    with tap.case("Stop sessions with --glob={}".format(stop_pattern)) as test_case:
+        client.stop_session_by_glob_pattern(stop_pattern)
+
+    tap.test(
+        (
+            sessions["East Farnham"].is_active
+            and sessions["Amos"].is_active
+            and (not sessions["Amqui"].is_active)
+        ),
+        "Only session 'Amqui' is inactive",
+    )
+
+    stop_pattern = "Am*"
+    with tap.case(
+        "Stopping more sessions, including a stopped session, with --glob={} doesn't produce an error".format(
+            stop_pattern
+        )
+    ) as test_case:
+        client.stop_session_by_glob_pattern(stop_pattern)
+
+    tap.test(
+        sessions["East Farnham"].is_active
+        and (not sessions["Amqui"].is_active)
+        and (not sessions["Amos"].is_active),
+        "Only session 'East Farnham' is active",
+    )
+
+    stop_pattern = "Notre-Dame*"
+    with tap.case(
+        "Stopping with --glob={} that doesn't match any session doesn't produce an error".format(
+            stop_pattern
+        )
+    ) as test_case:
+        client.stop_session_by_glob_pattern(stop_pattern)
+
+    for name, session in sessions.items():
+        session.destroy()
+
+    with tap.case(
+        "Stopping with --glob={} when no sessions exist doesn't produce an error".format(
+            stop_pattern
+        )
+    ) as test_case:
+        client.stop_session_by_glob_pattern(stop_pattern)
+
+
+def test_stop_single(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test match of stop command targeting a single session")
+    name_prefixes = ["Grosses-Roches", "Kazabazua", "Laval", "Magog"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test single session stop")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    client.start_sessions_all()
+    tap.test(
+        all(session.is_active for prefix, session in sessions.items()),
+        "All sessions are in the active state",
+    )
+
+    session_to_stop_prefix = "Kazabazua"
+    full_session_name = sessions[session_to_stop_prefix].name
+    with tap.case("Stop session '{}'".format(session_to_stop_prefix)) as test_case:
+        client.stop_session_by_name(full_session_name)
+
+    inactive_session_prefixes = [
+        prefix for prefix, session in sessions.items() if not session.is_active
+    ]
+    tap.test(
+        len(inactive_session_prefixes) == 1
+        and inactive_session_prefixes[0] == session_to_stop_prefix,
+        "Only session '{}' is inactive".format(session_to_stop_prefix),
+    )
+
+    with tap.case(
+        "Stopping already stopped session '{}' doesn't produce an error".format(
+            session_to_stop_prefix
+        )
+    ) as test_case:
+        client.stop_session_by_name(full_session_name)
+
+    for name, session in sessions.items():
+        session.destroy()
+
+
+def test_stop_all(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test stop command with the --all option")
+    name_prefixes = ["a", "b", "c", "d"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test stopping all sessions")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    client.start_sessions_all()
+    tap.test(
+        all(session.is_active for prefix, session in sessions.items()),
+        "All sessions are in the active state",
+    )
+
+    with tap.case("Stop all sessions") as test_case:
+        client.stop_sessions_all()
+
+    tap.test(
+        all(not session.is_active for prefix, session in sessions.items()),
+        "All sessions are inactive",
+    )
+
+    with tap.case("Stopping already stopped sessions") as test_case:
+        client.stop_sessions_all()
+
+    for name, session in sessions.items():
+        session.destroy()
+
+    with tap.case(
+        "Stopping all sessions when none exist doesn't produce an error"
+    ) as test_case:
+        client.stop_sessions_all()
+
+
+def test_destroy_globbing(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test --glob match of destroy command")
+    name_prefixes = ["Mont-Laurier", "Montreal", "Montmagny", "Neuville"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test globbing")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    destroy_pattern = "Mont*"
+    with tap.case(
+        "Destroy sessions with --glob={}".format(destroy_pattern)
+    ) as test_case:
+        client.destroy_session_by_glob_pattern(destroy_pattern)
+
+    listed_sessions = client.list_sessions()
+    tap.test(
+        len(listed_sessions) == 1
+        and listed_sessions[0].name == sessions["Neuville"].name,
+        "Neuville is the only remaining session",
+    )
+
+    for session in listed_sessions:
+        session.destroy()
+
+    with tap.case(
+        "Destroying with --glob={} when no sessions exist doesn't produce an error".format(
+            destroy_pattern
+        )
+    ) as test_case:
+        client.destroy_session_by_glob_pattern(destroy_pattern)
+
+
+def test_destroy_single(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test match of destroy command targeting a single session")
+    name_prefixes = ["Natashquan", "Normetal", "Notre-Dame-des-Sept-Douleurs"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test single session destruction")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    session_to_destroy_prefix = "Normetal"
+    full_session_name = sessions[session_to_destroy_prefix].name
+    with tap.case(
+        "Destroy session '{}'".format(session_to_destroy_prefix)
+    ) as test_case:
+        client.destroy_session_by_name(full_session_name)
+
+    listed_sessions = client.list_sessions()
+    tap.test(
+        len(listed_sessions) == 2
+        and full_session_name not in [session.name for session in listed_sessions],
+        "Session '{}' no longer exists".format(session_to_destroy_prefix),
+    )
+
+    for session in listed_sessions:
+        session.destroy()
+
+
+def test_destroy_all(tap, test_env):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> None
+    tap.diagnostic("Test destroy command with the --all option")
+    name_prefixes = ["a", "b", "c", "d"]
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    tap.diagnostic("Create a set of sessions to test destroying all sessions")
+    sessions = None
+    with tap.case(
+        "Create sessions with prefixes [{}]".format(", ".join(name_prefixes))
+    ) as test_case:
+        sessions = SessionSet(client, name_prefixes)
+
+    with tap.case("Destroy all sessions") as test_case:
+        client.destroy_sessions_all()
+
+    tap.test(
+        len(client.list_sessions()) == 0,
+        "No sessions exist after destroying all sessions",
+    )
+
+    with tap.case(
+        "Destroy all sessions when none exist doesn't produce an error"
+    ) as test_case:
+        client.destroy_sessions_all()
+
+
+tap = lttngtest.TapGenerator(48)
+tap.diagnostic("Test client session command --glob and --all options")
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_start_globbing(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_start_single(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_start_all(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_stop_globbing(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_stop_single(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_stop_all(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_destroy_globbing(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_destroy_single(tap, test_env)
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_destroy_all(tap, test_env)
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/tools/context/Makefile.am b/tests/regression/tools/context/Makefile.am
new file mode 100644 (file)
index 0000000..53d92a2
--- /dev/null
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+noinst_SCRIPTS = test_ust.py
+EXTRA_DIST = test_ust.py
+
+all-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       cp -f $(srcdir)/$$script $(builddir); \
+               done; \
+       fi
+
+clean-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       rm -f $(builddir)/$$script; \
+               done; \
+       fi
diff --git a/tests/regression/tools/context/test_ust.py b/tests/regression/tools/context/test_ust.py
new file mode 100755 (executable)
index 0000000..fac8ca1
--- /dev/null
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+import pathlib
+import sys
+import os
+from typing import Any, Callable, Type
+
+"""
+Test the addition of various user space contexts.
+
+This test successively sets up a session with a certain context enabled, traces
+a test application, and then reads the resulting trace to determine if:
+  - the context field is present in the trace
+  - the context field has the expected value.
+
+The vpid, vuid, vgid and java application contexts are validated by this test.
+"""
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import bt2
+
+
+def context_trace_field_name(context_type):
+    # type: (Type[lttngtest.ContextType]) -> str
+    if isinstance(context_type, lttngtest.VpidContextType):
+        return "vpid"
+    elif isinstance(context_type, lttngtest.VuidContextType):
+        return "vuid"
+    elif isinstance(context_type, lttngtest.VgidContextType):
+        return "vgid"
+    elif isinstance(context_type, lttngtest.JavaApplicationContextType):
+        # Depends on the trace format and will need to be adapted for CTF 2.
+        return "_app_{retriever}_{name}".format(
+            retriever=context_type.retriever_name, name=context_type.field_name
+        )
+    else:
+        raise NotImplementedError
+
+
+def trace_stream_class_has_context_field_in_event_context(
+    trace_location, context_field_name
+):
+    # type: (pathlib.Path, str) -> bool
+    iterator = bt2.TraceCollectionMessageIterator(str(trace_location))
+
+    # A bt2 message sequence is guaranteed to begin with a StreamBeginningMessage.
+    # Since we only have one channel (one stream class) and one trace, it is
+    # safe to use it to determine if the stream class contains the expected
+    # context field.
+    stream_begin_msg = next(iterator)
+
+    trace_class = stream_begin_msg.stream.trace.cls
+    # Ensure the trace class has only one stream class.
+    assert len(trace_class)
+
+    stream_class_id = next(iter(trace_class))
+    stream_class = trace_class[stream_class_id]
+    event_common_context_field_class = stream_class.event_common_context_field_class
+
+    return context_field_name in event_common_context_field_class
+
+
+def trace_events_have_context_value(trace_location, context_field_name, value):
+    # type: (pathlib.Path, str, Any) -> bool
+    for msg in bt2.TraceCollectionMessageIterator(str(trace_location)):
+        if type(msg) is not bt2._EventMessageConst:
+            continue
+
+        if msg.event.common_context_field[context_field_name] != value:
+            print(msg.event.common_context_field[context_field_name])
+            return False
+    return True
+
+
+def test_static_context(tap, test_env, context_type, context_value_retriever):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment, lttngtest.ContextType, Callable[[lttngtest.WaitTraceTestApplication], Any]) -> None
+    tap.diagnostic(
+        "Test presence and expected value of context `{context_name}`".format(
+            context_name=type(context_type).__name__
+        )
+    )
+
+    session_output_location = lttngtest.LocalSessionOutputLocation(
+        test_env.create_temporary_directory("trace")
+    )
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    with tap.case("Create a session") as test_case:
+        session = client.create_session(output=session_output_location)
+    tap.diagnostic("Created session `{session_name}`".format(session_name=session.name))
+
+    with tap.case(
+        "Add a channel to session `{session_name}`".format(session_name=session.name)
+    ) as test_case:
+        channel = session.add_channel(lttngtest.TracingDomain.User)
+    tap.diagnostic("Created channel `{channel_name}`".format(channel_name=channel.name))
+
+    with tap.case(
+        "Add {context_type} context to channel `{channel_name}`".format(
+            context_type=type(context_type).__name__, channel_name=channel.name
+        )
+    ) as test_case:
+        channel.add_context(context_type)
+
+    test_app = test_env.launch_wait_trace_test_application(50)
+
+    # Only track the test application
+    session.user_vpid_process_attribute_tracker.track(test_app.vpid)
+    expected_context_value = context_value_retriever(test_app)
+
+    # Enable all user space events, the default for a user tracepoint event rule.
+    channel.add_recording_rule(lttngtest.UserTracepointEventRule())
+
+    session.start()
+    test_app.trace()
+    test_app.wait_for_exit()
+    session.stop()
+    session.destroy()
+
+    tap.test(
+        trace_stream_class_has_context_field_in_event_context(
+            session_output_location.path, context_trace_field_name(context_type)
+        ),
+        "Stream class contains field `{context_field_name}`".format(
+            context_field_name=context_trace_field_name(context_type)
+        ),
+    )
+
+    tap.test(
+        trace_events_have_context_value(
+            session_output_location.path,
+            context_trace_field_name(context_type),
+            expected_context_value,
+        ),
+        "Trace's events contain the expected `{context_field_name}` value `{expected_context_value}`".format(
+            context_field_name=context_trace_field_name(context_type),
+            expected_context_value=expected_context_value,
+        ),
+    )
+
+
+tap = lttngtest.TapGenerator(20)
+tap.diagnostic("Test user space context tracing")
+
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    test_static_context(
+        tap, test_env, lttngtest.VpidContextType(), lambda test_app: test_app.vpid
+    )
+    test_static_context(
+        tap, test_env, lttngtest.VuidContextType(), lambda test_app: os.getuid()
+    )
+    test_static_context(
+        tap, test_env, lttngtest.VgidContextType(), lambda test_app: os.getgid()
+    )
+    test_static_context(
+        tap,
+        test_env,
+        lttngtest.JavaApplicationContextType("mayo", "ketchup"),
+        lambda test_app: {},
+    )
+
+sys.exit(0 if tap.is_successful else 1)
index 7570ba9b96864de9eeb43f7707222147d4e0e4ca..3fa9dbe959bf0381354e93df06f679ffd9170155 100755 (executable)
@@ -19,7 +19,7 @@ NR_USEC_WAIT=0
 NR_ITER=-1
 
 # Temp file output
-OUTPUT_DIR=$(mktemp -d --tmpdir tmp.test_crash_shm.XXXXXX)
+OUTPUT_DIR=$(mktemp -d -t tmp.test_crash_shm.XXXXXX)
 
 LAST_APP_PID=
 
@@ -39,7 +39,7 @@ bail_out_if_no_babeltrace
 
 function start_test_app()
 {
-       local tmp_file=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}.XXXXXX")
+       local tmp_file=$(mktemp -u -t "tmp.${FUNCNAME[0]}.XXXXXX")
 
        # Start application with a temporary file.
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event $tmp_file &
@@ -95,7 +95,7 @@ function test_shm_path_per_pid()
        diag "Shm: ust per-pid test"
        local session_name=shm_path_per_pid
        local channel_name=channel_per_pid
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm.XXXXXX")
 
        # Build up
        start_lttng_sessiond
@@ -166,7 +166,7 @@ function test_shm_path_per_uid()
        local session_name=shm_path_per_uid
        local channel_name=channel_per_uid
        set -x
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
        set +x
 
        # Build up
@@ -218,8 +218,8 @@ function test_lttng_crash()
        diag "Lttng-crash: basic recuperation"
        local session_name=crash_test
        local channel_name=channel_crash
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
-       local shm_path_symlink=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path_symlink.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local shm_path_symlink=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path_symlink.XXXXXX")
        local event_name="tp:tptest"
 
        # Create a session in snapshot mode to deactivate any use of consumerd
@@ -255,8 +255,8 @@ function test_lttng_crash_extraction()
        diag "Lttng-crash: extraction to path"
        local session_name=crash_test
        local channel_name=channel_crash
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
-       local extraction_dir_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_extraction_dir_path.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local extraction_dir_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_extraction_dir_path.XXXXXX")
        local extraction_path=$extraction_dir_path/extract
        local event_name="tp:tptest"
 
@@ -289,7 +289,7 @@ function test_shm_path_per_pid_sigint()
        diag "Shm: ust per-pid test sigint"
        local session_name=shm_path_per_pid
        local channel_name=channel_per_pid
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
        local num_files=0
 
        # Build up
@@ -320,7 +320,7 @@ function test_shm_path_per_uid_sigint()
        diag "Shm: ust per-uid test sigint"
        local session_name=shm_path_per_uid_sigint
        local channel_name=channel_per_uid_sigint
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
        local ret=0
 
        # Build up
@@ -351,8 +351,8 @@ function test_lttng_crash_extraction_sigkill()
        diag "Lttng-crash: extraction with sigkill"
        local session_name=crash_test
        local channel_name=channel_crash
-       local shm_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
-       local extraction_dir_path=$(mktemp -d --tmpdir "tmp.${FUNCNAME[0]}_extraction_dir_path.XXXXXX")
+       local shm_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_shm_path.XXXXXX")
+       local extraction_dir_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_extraction_dir_path.XXXXXX")
        local extraction_path=$extraction_dir_path/extract
        local event_name="tp:tptest"
        local ret=0
index 0c9bdc8294effaa40260f0e8a2d587135a92661f..6b3a14fd476ffdb33771f470baecf75c188da12b 100755 (executable)
@@ -9,7 +9,8 @@ TEST_DESC="Event exclusion"
 
 CURDIR=$(dirname $0)/
 TESTDIR=$CURDIR/../../..
-STATS_BIN="$TESTDIR/utils/babelstats.pl"
+BT2_PLUGINS_DIR="${TESTDIR}/utils/bt2_plugins"
+
 SESSION_NAME="test-exclusion"
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-nevents"
@@ -40,7 +41,7 @@ function run_apps
 # of our test suite to generate events.
 function dry_run
 {
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        # Create session
        create_lttng_session_ok $SESSION_NAME $trace_path
@@ -70,7 +71,7 @@ function test_exclusion
 {
        local exclusions="$1"
        local event_name_expected_to_be_missing="$2"
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        # Create session
        create_lttng_session_ok $SESSION_NAME $trace_path
@@ -86,7 +87,7 @@ function test_exclusion
        # Destroy session
        destroy_lttng_session_ok $SESSION_NAME
 
-       stats=`"$BABELTRACE_BIN" $trace_path | $STATS_BIN --tracepoint "$event_name_expected_to_be_missing" | grep -v index 2> /dev/null`
+       stats=$("$BABELTRACE_BIN" --plugin-path "${BT2_PLUGINS_DIR}" "${trace_path}" -c filter.lttngtest.event_name -p "names=[\"${event_name_expected_to_be_missing}\"]" -c sink.lttngtest.field_stats | grep -v index 2> /dev/null)
        if [ ! -z "$stats" ]; then
                fail "Excluded event \"$event_name_expected_to_be_missing\" was found in trace!"
        else
@@ -99,9 +100,9 @@ function test_exclusion_tracing_started
 {
        local exclusions="$1"
        local event_name_expected_to_be_missing="$2"
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       local file_wait_before_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_first.XXXXXX")
-       local file_create_in_main=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_create_in_main.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local file_wait_before_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_first.XXXXXX")
+       local file_create_in_main=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_create_in_main.XXXXXX")
 
        # Create session
        create_lttng_session_ok $SESSION_NAME $trace_path
@@ -139,7 +140,7 @@ function test_exclusion_tracing_started
        # Destroy session
        destroy_lttng_session_ok $SESSION_NAME
 
-       stats=$("$BABELTRACE_BIN" $trace_path | $STATS_BIN --tracepoint "$event_name_expected_to_be_missing" | grep -v index 2> /dev/null)
+       stats=$("$BABELTRACE_BIN" --plugin-path "${BT2_PLUGINS_DIR}" "${trace_path}" -c filter.lttngtest.event_name -p "names=[\"${event_name_expected_to_be_missing}\"]" -c sink.lttngtest.field_stats | grep -v index 2> /dev/null)
        if [ ! -z "$stats" ]; then
                fail "Excluded event \"$event_name_expected_to_be_missing\" was found in trace!"
        else
index d4f8a57bd8650355163eb59ce717caad955ab4b6..681d191785f13340c62dfd507f0bf56cfbf82813 100644 (file)
@@ -46,8 +46,17 @@ int main(int argc, char **argv)
 
        for (i = 0; i < nr_iter; i++) {
                netint = htonl(i);
-               tracepoint(tp, tptest, i, netint, values, text, strlen(text), escape, dbl, flt,
-                       net_values);
+               tracepoint(tp,
+                          tptest,
+                          i,
+                          netint,
+                          values,
+                          text,
+                          strlen(text),
+                          escape,
+                          dbl,
+                          flt,
+                          net_values);
                usleep(nr_usec);
        }
 
index 01306123929a843e5531776deb400660e116c3f7..2dd57b0bbbbcceb1339929b2fc44e63a5fa3120b 100755 (executable)
@@ -24,7 +24,7 @@ TESTDIR=$CURDIR/../../..
 SESSION_NAME="filter-invalid"
 EVENT_NAME="bogus"
 ENABLE_EVENT_STDERR="/tmp/invalid-filters-stderr"
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_filtering_invalid_filters_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_filtering_invalid_filters_trace_path.XXXXXX)
 NUM_GLOBAL_TESTS=2
 NUM_UST_TESTS=138
 NUM_KERNEL_TESTS=138
@@ -170,13 +170,7 @@ done
 
 test_bytecode_limit -u
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel invalid filter tests." $NUM_KERNEL_TESTS ||
+check_skip_kernel_test "$NUM_KERNEL_TESTS" "Skipping kernel invalid filter tests." ||
 {
        diag "Test kernel filters"
        i=0
index 299247a3c5c8e845721f9eba7a0e426edd2161e8..672a980de959d2494d81c1b40e1373a3af1d8d15 100755 (executable)
@@ -12,7 +12,7 @@ TESTDIR=$CURDIR/../../..
 SESSION_NAME="filter-unsupported-ops"
 EVENT_NAME="bogus"
 ENABLE_EVENT_STDERR="/tmp/unsupported-ops-enable"
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_filtering_unsupported_ops_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_filtering_unsupported_ops_trace_path.XXXXXX)
 NUM_GLOBAL_TESTS=2
 NUM_UST_TESTS=20
 NUM_KERNEL_TESTS=20
@@ -103,13 +103,7 @@ while [ "$i" -lt "$OP_COUNT" ]; do
        let "i++"
 done
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel unsupported filter operations tests." $NUM_KERNEL_TESTS ||
+check_skip_kernel_test $NUM_KERNEL_TESTS "Skipping kernel unsupported filter operations tests." ||
 {
        diag "Test kernel unsupported filter operations"
 
index 7e764ca5d0caf10fc5ecee465dbca50ba719e932..79a9d85f237c393317e9df6da9ae369aeb3a29d0 100755 (executable)
@@ -9,7 +9,8 @@ TEST_DESC="Filtering - Valid filters"
 
 CURDIR=$(dirname $0)/
 TESTDIR=$CURDIR/../../..
-STATS_BIN="$TESTDIR/utils/babelstats.pl"
+BT2_PLUGINS_DIR="${TESTDIR}/utils/bt2_plugins"
+
 SESSION_NAME="valid_filter"
 NR_ITER=100
 NUM_GLOBAL_TESTS=2
@@ -94,7 +95,7 @@ function test_valid_filter
        event_name="$3"
        filter="$4"
        validator="$5"
-       local trace_path=$(mktemp --tmpdir -d tmp.test_filtering_invalid_filters_trace_path.XXXXXX)
+       local trace_path=$(mktemp -d -t tmp.test_filtering_valid_filters_trace_path.XXXXXX)
 
        diag "Test valid $domain_name filter: $filter"
 
@@ -110,16 +111,12 @@ function test_valid_filter
        stop_lttng_tracing_ok $SESSION_NAME
 
        # Destroy session
-       destroy_lttng_session_ok $SESSION_NAME
-
-       stats=`"$BABELTRACE_BIN" $trace_path | $STATS_BIN --tracepoint $event_name`
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
-       rm -rf $trace_path
+       stats=$("${BABELTRACE_BIN}" --plugin-path "${BT2_PLUGINS_DIR}" "${trace_path}" -c filter.lttngtest.event_name -p "names=[\"${event_name}\"]" -c sink.lttngtest.field_stats)
 
        $validator "$stats"
-
        ok $? "Validate trace filter output"
-
        rm -rf $trace_path
 }
 
@@ -1454,13 +1451,7 @@ KERNEL_FILTERS=(
 
 IFS=$OLDIFS
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel valid filter tests." $NUM_KERNEL_TESTS ||
+check_skip_kernel_test "$NUM_KERNEL_TESTS" "Skipping kernel valid filter tests." ||
 {
        diag "Test kernel valid filters"
 
index ce2b6d1e9498f24a0f76c4c3a6c643805178cca1..44ca83573bd8c097939d697ad6d0a0b8b030bc50 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, tptest,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               char *, etext, double, doublearg, float, floatarg,
-               uint32_t *, net_values),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_array_network(uint32_t, arrfield3, net_values, 3)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_sequence_network(uint32_t, seqfield3, net_values, size_t, 3)
-               ctf_sequence(long, seqfield4, values, size_t, 3)
-               ctf_string(stringfield, text)
-               ctf_string(stringfield2, etext)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
+TRACEPOINT_EVENT(
+       tp,
+       tptest,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               char *,
+               etext,
+               double,
+               doublearg,
+               float,
+               floatarg,
+               uint32_t *,
+               net_values),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_array_network(
+                                         uint32_t,
+                                         arrfield3,
+                                         net_values,
+                                         3) ctf_sequence(char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_sequence_network(uint32_t,
+                                                                      seqfield3,
+                                                                      net_values,
+                                                                      size_t,
+                                                                      3) ctf_sequence(long,
+                                                                                      seqfield4,
+                                                                                      values,
+                                                                                      size_t,
+                                                                                      3)
+                                                         ctf_string(stringfield,
+                                                                    text) ctf_string(stringfield2,
+                                                                                     etext)
+                                                                 ctf_float(float,
+                                                                           floatfield,
+                                                                           floatarg)
+                                                                         ctf_float(double,
+                                                                                   doublefield,
+                                                                                   doublearg)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index deeab67b91b5c07fa698cb65c885261ebc7d4e01..805eff8840c26203d367fb9bbf5a9db7d55ad025 100644 (file)
@@ -6,17 +6,16 @@
  *
  */
 
+#include <lttng/health.h>
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include <lttng/health.h>
-
 static const char *relayd_path;
 
-static
-int check_component(struct lttng_health *lh, const char *component_name,
-               int ok_if_not_running)
+static int
+check_component(struct lttng_health *lh, const char *component_name, int ok_if_not_running)
 {
        const struct lttng_health_thread *thread;
        int nr_threads, i, status;
@@ -25,8 +24,7 @@ int check_component(struct lttng_health *lh, const char *component_name,
                if (ok_if_not_running) {
                        return 0;
                }
-               fprintf(stderr, "Error querying %s health\n",
-                       component_name);
+               fprintf(stderr, "Error querying %s health\n", component_name);
                return -1;
        }
        status = lttng_health_state(lh);
@@ -54,15 +52,13 @@ int check_component(struct lttng_health *lh, const char *component_name,
                        continue;
                }
                printf("Thread \"%s\" is not responding in component \"%s\".\n",
-                       lttng_health_thread_name(thread),
-                       component_name);
-
+                      lttng_health_thread_name(thread),
+                      component_name);
        }
        return status;
 }
 
-static
-int check_sessiond(void)
+static int check_sessiond(void)
 {
        struct lttng_health *lh;
        int status;
@@ -80,8 +76,7 @@ int check_sessiond(void)
        return status;
 }
 
-static
-int check_consumerd(enum lttng_health_consumerd hc)
+static int check_consumerd(enum lttng_health_consumerd hc)
 {
        struct lttng_health *lh;
        int status;
@@ -104,8 +99,7 @@ int check_consumerd(enum lttng_health_consumerd hc)
        return status;
 }
 
-static
-int check_relayd(const char *path)
+static int check_relayd(const char *path)
 {
        struct lttng_health *lh;
        int status;
@@ -129,11 +123,12 @@ int main(int argc, char *argv[])
 
        for (i = 1; i < argc; i++) {
                size_t relayd_path_arg_len = strlen("--relayd-path=");
-               if (!strncmp(argv[i], "--relayd-path=",
-                               relayd_path_arg_len)) {
+               if (!strncmp(argv[i], "--relayd-path=", relayd_path_arg_len)) {
                        relayd_path = &argv[i][relayd_path_arg_len];
                } else {
-                       fprintf(stderr, "Unknown option \"%s\". Try --relayd-path=PATH.\n", argv[i]);
+                       fprintf(stderr,
+                               "Unknown option \"%s\". Try --relayd-path=PATH.\n",
+                               argv[i]);
                        exit(EXIT_FAILURE);
                }
        }
index 6520337e4c41ec7ea7b0dad06c66a21cff55fab7..2994694fda1be8d2c818fc3c653ef617eebb0170 100644 (file)
@@ -7,17 +7,17 @@
  */
 
 #include <lttng/lttng-export.h>
+
+#include <pthread.h>
 #include <stdlib.h>
 #include <string.h>
-#include <pthread.h>
 #include <urcu.h>
 
 /*
  * Check if the specified environment variable is set.
  * Return 1 if set, otherwise 0.
  */
-static
-int check_env_var(const char *env)
+static int check_env_var(const char *env)
 {
        if (env) {
                char *env_val = getenv(env);
index d01ad4cb9210c2b854af4165b5c96fdec0e37c98..c88e5742a30b08ec6cac328e0ff5de742986a9c1 100644 (file)
@@ -7,9 +7,10 @@
  */
 
 #include <lttng/lttng-export.h>
+
+#include <pthread.h>
 #include <stdlib.h>
 #include <string.h>
-#include <pthread.h>
 #include <unistd.h>
 #include <urcu.h>
 
@@ -19,8 +20,7 @@
  * Check if the specified environment variable is set.
  * Return 1 if set, otherwise 0.
  */
-static
-int check_env_var(const char *env)
+static int check_env_var(const char *env)
 {
        if (env) {
                char *env_val = getenv(env);
@@ -32,8 +32,7 @@ int check_env_var(const char *env)
        return 0;
 }
 
-static
-void do_stall(void)
+static void do_stall(void)
 {
        unsigned int sleep_time = STALL_TIME;
 
index 01da978a92147c8b20a83e161db8873c1e3e8c9c..23cb05075d33a0edabd2dd4a6060710e3d0dbbca 100644 (file)
@@ -82,7 +82,7 @@ function test_health
                diag "With UST consumer daemons"
                enable_ust_lttng_event_ok $SESSION_NAME $UST_EVENT_NAME $CHANNEL_NAME
 
-               skip $isroot "Root access is needed. Skipping kernel consumer health check test." "1" ||
+               check_skip_kernel_test "1" "Skipping kernel consumer health check test." ||
                {
                        diag "With kernel consumer daemon"
                        lttng_enable_kernel_event $SESSION_NAME $KERNEL_EVENT_NAME $CHANNEL_NAME
@@ -113,7 +113,7 @@ function test_health
 
 
        if [ ${test_needs_root} -eq 1 ]; then
-               skip ${isroot} "Root access needed for test \"${test_thread_name}\"." "1" ||
+               check_skip_kernel_test "1" "Skipping \"${test_thread_name}\"." ||
                {
                        report_errors "${test_thread_error_string}" "${test_relayd}"
                }
@@ -266,16 +266,10 @@ TEST_RELAYD=(
        1
 )
 
-STDOUT_PATH=$(mktemp --tmpdir tmp.test_health_stdout_path.XXXXXX)
-STDERR_PATH=$(mktemp --tmpdir tmp.test_health_stderr_path.XXXXXX)
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_health_trace_path.XXXXXX)
-HEALTH_PATH=$(mktemp --tmpdir -d tmp.test_health_trace_path.XXXXXX)
-
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
+STDOUT_PATH=$(mktemp -t tmp.test_health_stdout_path.XXXXXX)
+STDERR_PATH=$(mktemp -t tmp.test_health_stderr_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_health_trace_path.XXXXXX)
+HEALTH_PATH=$(mktemp -d -t tmp.test_health_trace_path.XXXXXX)
 
 THREAD_COUNT=${#THREAD[@]}
 i=0
index e84adb611a00f1531310dd623d109cfa3db84bb2..5441b2f064b56eb74ecce145c1f5b64268b14aa3 100755 (executable)
@@ -67,7 +67,7 @@ function test_thread_ok
        $CURDIR/$HEALTH_CHECK_BIN > ${STDOUT_PATH} 2> ${STDERR_PATH}
        report_errors
 
-       skip $isroot "Root access is needed. Skipping kernel consumer health check test." "5" ||
+       check_skip_kernel_test "5" "Skipping kernel consumer health check test." ||
        {
                diag "With kernel consumer daemon"
                create_lttng_session_no_output $SESSION_NAME
@@ -110,17 +110,10 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-STDOUT_PATH=$(mktemp --tmpdir tmp.test_thread_ok_stdout_path.XXXXXX)
-STDERR_PATH=$(mktemp --tmpdir tmp.test_thread_ok_stderr_path.XXXXXX)
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_thread_ok_trace_path.XXXXXX)
-HEALTH_PATH=$(mktemp --tmpdir -d tmp.test_thread_ok_trace_path.XXXXXX)
-
-# The manage kernel thread is only spawned if we are root
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
+STDOUT_PATH=$(mktemp -t tmp.test_thread_ok_stdout_path.XXXXXX)
+STDERR_PATH=$(mktemp -t tmp.test_thread_ok_stderr_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_thread_ok_trace_path.XXXXXX)
+HEALTH_PATH=$(mktemp -d -t tmp.test_thread_ok_trace_path.XXXXXX)
 
 test_thread_ok
 
index 559b9a7b1e8298885ae574090a26683e6058eb82..9c9838ac7f337f6860ad4fb57519b5e83a6139c9 100644 (file)
@@ -5,34 +5,31 @@
  *
  */
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
+#include <common/common.hpp>
+#include <common/compat/endian.hpp>
+#include <common/compat/errno.hpp>
 #include <common/compat/time.hpp>
-#include <sys/types.h>
+#include <common/index/ctf-index.hpp>
+
+#include <lttng/lttng.h>
+
+#include <bin/lttng-relayd/lttng-viewer-abi.hpp>
+#include <fcntl.h>
 #include <inttypes.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
 #include <netdb.h>
-#include <fcntl.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/mman.h>
+#include <sys/socket.h>
 #include <sys/stat.h>
-
+#include <sys/types.h>
 #include <tap/tap.h>
-#include <lttng/lttng.h>
-
+#include <unistd.h>
 #include <urcu/list.h>
-#include <common/common.hpp>
 
-#include <bin/lttng-relayd/lttng-viewer-abi.hpp>
-#include <common/index/ctf-index.hpp>
-
-#include <common/compat/errno.hpp>
-#include <common/compat/endian.hpp>
-
-#define SESSION1 "test1"
+#define SESSION1   "test1"
 #define RELAYD_URL "net://localhost"
 #define LIVE_TIMER 2000000
 
@@ -71,8 +68,7 @@ struct live_session {
 };
 } /* namespace */
 
-static
-ssize_t lttng_live_recv(int fd, void *buf, size_t len)
+static ssize_t lttng_live_recv(int fd, void *buf, size_t len)
 {
        ssize_t ret;
        size_t copied = 0, to_copy = len;
@@ -84,16 +80,14 @@ ssize_t lttng_live_recv(int fd, void *buf, size_t len)
                        copied += ret;
                        to_copy -= ret;
                }
-       } while ((ret > 0 && to_copy > 0)
-               || (ret < 0 && errno == EINTR));
+       } while ((ret > 0 && to_copy > 0) || (ret < 0 && errno == EINTR));
        if (ret > 0)
                ret = copied;
        /* ret = 0 means orderly shutdown, ret < 0 is error. */
        return ret;
 }
 
-static
-ssize_t lttng_live_send(int fd, const void *buf, size_t len)
+static ssize_t lttng_live_send(int fd, const void *buf, size_t len)
 {
        ssize_t ret;
 
@@ -103,8 +97,7 @@ ssize_t lttng_live_send(int fd, const void *buf, size_t len)
        return ret;
 }
 
-static
-int connect_viewer(const char *hostname)
+static int connect_viewer(const char *hostname)
 {
        struct hostent *host;
        struct sockaddr_in server_addr;
@@ -127,8 +120,8 @@ int connect_viewer(const char *hostname)
        server_addr.sin_addr = *((struct in_addr *) host->h_addr);
        bzero(&(server_addr.sin_zero), 8);
 
-       if (connect(control_sock, (struct sockaddr *) &server_addr,
-                               sizeof(struct sockaddr)) == -1) {
+       if (connect(control_sock, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)) ==
+           -1) {
                PERROR("Connect");
                ret = -1;
                goto end;
@@ -145,8 +138,7 @@ end:
        return ret;
 }
 
-static
-int establish_connection(void)
+static int establish_connection()
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_connect connect;
@@ -190,8 +182,7 @@ error:
 /*
  * Returns the number of sessions, should be 1 during the unit test.
  */
-static
-int list_sessions(uint64_t *session_id)
+static int list_sessions(uint64_t *session_id)
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_list_sessions list;
@@ -238,8 +229,7 @@ error:
        return -1;
 }
 
-static
-int create_viewer_session(void)
+static int create_viewer_session()
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_create_session_response resp;
@@ -277,8 +267,7 @@ error:
        return -1;
 }
 
-static
-int attach_session(uint64_t id)
+static int attach_session(uint64_t id)
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_attach_session_request rq;
@@ -348,9 +337,12 @@ int attach_session(uint64_t id)
 
                session->streams[i].ctf_trace_id = be64toh(stream.ctf_trace_id);
                session->streams[i].first_read = 1;
-               session->streams[i].mmap_base = mmap(NULL, mmap_size,
-                               PROT_READ | PROT_WRITE,
-                               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+               session->streams[i].mmap_base = mmap(nullptr,
+                                                    mmap_size,
+                                                    PROT_READ | PROT_WRITE,
+                                                    MAP_PRIVATE | MAP_ANONYMOUS,
+                                                    -1,
+                                                    0);
                if (session->streams[i].mmap_base == MAP_FAILED) {
                        diag("mmap error");
                        goto error;
@@ -366,8 +358,7 @@ error:
        return -1;
 }
 
-static
-int get_metadata(void)
+static int get_metadata()
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_get_metadata rq;
@@ -375,7 +366,7 @@ int get_metadata(void)
        ssize_t ret_len;
        int ret;
        uint64_t i;
-       char *data = NULL;
+       char *data = nullptr;
        uint64_t len = 0;
        int metadata_stream_id = -1;
 
@@ -462,8 +453,7 @@ error:
        return -1;
 }
 
-static
-int get_next_index(void)
+static int get_next_index()
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_get_next_index rq;
@@ -482,7 +472,7 @@ int get_next_index(void)
                memset(&rq, 0, sizeof(rq));
                rq.stream_id = htobe64(session->streams[id].id);
 
-retry:
+       retry:
                ret_len = lttng_live_send(control_sock, &cmd, sizeof(cmd));
                if (ret_len < 0) {
                        diag("Error sending cmd");
@@ -524,7 +514,8 @@ retry:
                        diag("Got LTTNG_VIEWER_INDEX_ERR");
                        goto error;
                default:
-                       diag("Unknown reply status during LTTNG_VIEWER_GET_NEXT_INDEX (%d)", be32toh(rp.status));
+                       diag("Unknown reply status during LTTNG_VIEWER_GET_NEXT_INDEX (%d)",
+                            be32toh(rp.status));
                        goto error;
                }
                if (first_packet_stream_id < 0) {
@@ -536,7 +527,8 @@ retry:
                        first_packet_len = be64toh(rp.packet_size) / CHAR_BIT;
                        first_packet_stream_id = id;
                        diag("Got first packet index with offset %d and len %d",
-                                       first_packet_offset, first_packet_len);
+                            first_packet_offset,
+                            first_packet_len);
                }
        }
        return 0;
@@ -545,9 +537,7 @@ error:
        return -1;
 }
 
-static
-int get_data_packet(int id, uint64_t offset,
-               uint64_t len)
+static int get_data_packet(int id, uint64_t offset, uint64_t len)
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_get_packet rq;
@@ -628,8 +618,7 @@ error:
        return -1;
 }
 
-static
-int detach_viewer_session(uint64_t id)
+static int detach_viewer_session(uint64_t id)
 {
        struct lttng_viewer_cmd cmd;
        struct lttng_viewer_detach_session_response resp;
@@ -676,7 +665,7 @@ error:
        return ret;
 }
 
-int main(void)
+int main()
 {
        int ret;
        uint64_t session_id;
@@ -689,8 +678,10 @@ int main(void)
        ok(ret == 0, "Connect viewer to relayd");
 
        ret = establish_connection();
-       ok(ret == 0, "Established connection and version check with %d.%d",
-                       VERSION_MAJOR, VERSION_MINOR);
+       ok(ret == 0,
+          "Established connection and version check with %d.%d",
+          VERSION_MAJOR,
+          VERSION_MINOR);
 
        ret = list_sessions(&session_id);
        ok(ret > 0, "List sessions : %d session(s)", ret);
@@ -710,12 +701,12 @@ int main(void)
        ret = get_next_index();
        ok(ret == 0, "Get one index per stream");
 
-       ret = get_data_packet(first_packet_stream_id, first_packet_offset,
-                       first_packet_len);
+       ret = get_data_packet(first_packet_stream_id, first_packet_offset, first_packet_len);
        ok(ret == 0,
-                       "Get one data packet for stream %d, offset %d, len %d",
-                       first_packet_stream_id, first_packet_offset,
-                       first_packet_len);
+          "Get one data packet for stream %d, offset %d, len %d",
+          first_packet_stream_id,
+          first_packet_offset,
+          first_packet_len);
 
        ret = detach_viewer_session(session_id);
        ok(ret == 0, "Detach viewer session");
index b622b52143d3bc4a740fb9e7a1ade7739dc60f19..df30fcf56242e940ec974af197414de788bf95fe 100755 (executable)
@@ -16,7 +16,7 @@ DELAY_USEC=2000000
 SESSION_NAME="live"
 EVENT_NAME="lttng_test_filter_event"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_live_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_live_kernel_trace_path.XXXXXX)
 
 DIR=$(readlink -f $TESTDIR)
 
@@ -39,13 +39,11 @@ function clean_live_tracing()
        rm -rf $TRACE_PATH
 }
 
-# Need root access for kernel tracing.
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       plan_skip_all "Root access is needed. Skipping all tests."
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
        exit 0
-fi
+}
 
 modprobe lttng-test
 
index a23d9373a842fbb41eb55d0a8c2a3828140a804f..94f2c008729c4db25abfd74500b288a41238e4eb 100755 (executable)
@@ -14,7 +14,7 @@ DELAY_USEC=2000000
 SESSION_NAME="live"
 EVENT_NAME="lttng_test_filter_event"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_lttng_live_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_lttng_live_kernel_trace_path.XXXXXX)
 
 DIR=$(readlink -f $TESTDIR)
 
@@ -45,13 +45,7 @@ function clean_live_tracing()
 }
 
 # Need root access for kernel tracing.
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        modprobe lttng-test
 
index 3aa1083b0518da95fe5d3e9f86dc2b3fa7ab71a8..133564416e358aa5997270d138da292847875454 100755 (executable)
@@ -19,7 +19,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="live"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_test_live_lttng_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_test_live_lttng_ust_trace_path.XXXXXX)
 
 DIR=$(readlink -f $TESTDIR)
 
index 45761c5c90cabcff7fba7a64a9bd0a7f428207b0..d901421c7c7e7c65e73af3c46185880a921f3b1c 100755 (executable)
@@ -19,7 +19,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="live"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_live_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_live_ust_trace_path.XXXXXX)
 
 DIR=$(readlink -f $TESTDIR)
 
@@ -44,7 +44,7 @@ function clean_live_tracing()
        rm -rf $TRACE_PATH
 }
 
-file_sync_after_first=$(mktemp --tmpdir -u tmp.test_live_ust_sync_after_first.XXXXXX)
+file_sync_after_first=$(mktemp -u -t tmp.test_live_ust_sync_after_first.XXXXXX)
 
 start_lttng_sessiond_notap
 start_lttng_relayd_notap "-o $TRACE_PATH"
index d576f35069cda685b24aa6b0604d2919d699d47b..3225b65d6ecdb5de962d7449ca0155d42becda00 100755 (executable)
@@ -19,7 +19,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="live"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_ust_trace_file_count_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_ust_trace_file_count_trace_path.XXXXXX)
 
 DIR=$(readlink -f $TESTDIR)
 
@@ -45,7 +45,7 @@ function clean_live_tracing()
        rm -rf $TRACE_PATH
 }
 
-file_sync_after_first=$(mktemp --tmpdir -u tmp.test_ust_trace_file_count_sync_after_first.XXXXXX)
+file_sync_after_first=$(mktemp -u -t tmp.test_ust_trace_file_count_sync_after_first.XXXXXX)
 
 start_lttng_sessiond_notap
 start_lttng_relayd_notap "-o $TRACE_PATH"
index 08743008bccf339052669b31cca6756d0b8b1da6..d38af841df2d009592f88a5ba23ed34529085398 100755 (executable)
@@ -10,7 +10,7 @@ CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../..
 EVENT_NAME="lttng_test_filter_event"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_metadata_env_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_metadata_env_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=13
 
@@ -22,12 +22,14 @@ source "$CURDIR/utils.sh"
 function test_kernel ()
 {
        local metadata_path
-       local value
+       local metadata
+       local metadata_env
 
        local expected_path="${TRACE_PATH}/lttng-traces"
        local session_name="kernel"
-       local metadata=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_metadata.XXXXXX")
-       local metadata_env=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_metadata_env.XXXXXX")
+
+       metadata=$(mktemp -t "tmp.test_kernel_metadata.XXXXXX")
+       metadata_env=$(mktemp -t "tmp.test_kernel_metadata_env.XXXXXX")
 
        diag "Test Kernel metadata env field"
        create_lttng_session_ok "$session_name"
@@ -55,33 +57,37 @@ function test_kernel ()
        # to allow trace viewer to recreate the same directory hierarchy.
 
        # Trace name
-       value=$(get_env_value "$metadata_env" trace_name)
-       ok $? "Extracting trace_name from env metadata"
-       expected_path="${expected_path}/${value}"
+       local trace_name
+       trace_name=$(get_env_value "$metadata_env" trace_name)
+       ok $? "Extracting trace_name from env metadata: \`$trace_name\`"
+       expected_path="${expected_path}/${trace_name}"
 
        # Session creation time
-       value=$(get_env_value "$metadata_env" trace_creation_datetime)
-       ok $? "Extracting trace_creation_datetime from env metadata"
-       value=$(iso8601_to_lttng_dir_datetime "$value")
-       expected_path="${expected_path}-${value}"
+       local trace_creation_datetime
+       trace_creation_datetime=$(get_env_value "$metadata_env" trace_creation_datetime)
+       ok $? "Extracting trace_creation_datetime from env metadata: \`$trace_creation_datetime\`"
+       trace_creation_datetime=$(iso8601_to_lttng_dir_datetime "$trace_creation_datetime")
+       expected_path="${expected_path}-${trace_creation_datetime}"
 
        # Domain
-       value=$(get_env_value "$metadata_env" domain)
-       ok $? "Extracting domain from env metadata"
-       expected_path="${expected_path}/${value}"
+       local domain
+       domain=$(get_env_value "$metadata_env" domain)
+       ok $? "Extracting domain from env metadata: \`$domain\`"
+       expected_path="${expected_path}/${domain}"
 
        # Append "metadata" and test that we find the file.
        expected_path="${expected_path}/metadata"
 
-       test -e "$expected_path"
-       ok $? "Reconstructed path from metadata is valid"
+       test -f "$expected_path"
+       ok $? "Reconstructed path from metadata is an existing file: \`$expected_path\`"
 
        # Hostname
        # The hostname is not part of the lttng hierarchy still we can test for
        # its validity here.
-       value=$(get_env_value "$metadata_env" hostname)
-       ok $? "Extracting hostname from env metadata"
-       is "$value" "$(hostname)" "Hostname is valid"
+       local hostname
+       hostname=$(get_env_value "$metadata_env" hostname)
+       ok $? "Extracting hostname from env metadata: \`$hostname\`"
+       is "$hostname" "$(hostname)" "Extracted hostname matches current hostname"
 
        rm -f "$metadata"
        rm -f "$metadata_env"
@@ -92,22 +98,15 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel metadata tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping kernel metadata tests." ||
 {
        validate_lttng_modules_present
        modprobe lttng-test
 
        # Use LTTNG_HOME since we want the complete "default" lttng directory hierarchy
        # with "<session_name>-<datetime>/...".
-       LTTNG_HOME="$TRACE_PATH"
+       export LTTNG_HOME="$TRACE_PATH"
 
-       export LTTNG_HOME
        start_lttng_sessiond
 
        tests=( test_kernel )
index 6b17b02cf6439eed92c09057254a00d01755ae84..05a2a8bec6771fc6a885ab74685d215615a1885c 100755 (executable)
@@ -13,7 +13,7 @@ TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_metadata_env_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_metadata_env_ust_trace_path.XXXXXX)
 
 NUM_TESTS=37
 
@@ -32,13 +32,14 @@ fi
 function test_per_uid ()
 {
        local metadata_path
-       local value
-       local value2
+       local metadata
+       local metadata_env
 
        local expected_path="${TRACE_PATH}/lttng-traces"
        local session_name="per-uid"
-       local metadata=$(mktemp --tmpdir tmp.test_${FUNCNAME[0]}_metadata.XXXXXX)
-       local metadata_env=$(mktemp --tmpdir tmp.test_${FUNCNAME[0]}_metadata_env.XXXXXX)
+
+       metadata=$(mktemp -t tmp.test_per_uid_metadata.XXXXXX)
+       metadata_env=$(mktemp -t tmp.test_per_uid_metadata_env.XXXXXX)
 
        diag "Test UST metadata env field in per-uid mode"
        create_lttng_session_ok "$session_name"
@@ -66,51 +67,58 @@ function test_per_uid ()
        # to allow trace viewer to recreate the same directory hierarchy.
 
        # Trace name
-       value=$(get_env_value "$metadata_env" trace_name)
-       ok $? "Extracting trace_name from env metadata"
-       expected_path="${expected_path}/${value}"
+       local trace_name
+       trace_name=$(get_env_value "$metadata_env" trace_name)
+       ok $? "Extracting trace_name from env metadata: \`$trace_name\`"
+       expected_path="${expected_path}/${trace_name}"
 
        # Session creation time
-       value=$(get_env_value "$metadata_env" trace_creation_datetime)
-       ok $? "Extracting trace_creation_datetime from env metadata"
-       value=$(iso8601_to_lttng_dir_datetime "$value")
-       expected_path="${expected_path}-${value}"
+       local trace_creation_datetime
+       trace_creation_datetime=$(get_env_value "$metadata_env" trace_creation_datetime)
+       ok $? "Extracting trace_creation_datetime from env metadata: \`$trace_creation_datetime\`"
+       trace_creation_datetime=$(iso8601_to_lttng_dir_datetime "$trace_creation_datetime")
+       expected_path="${expected_path}-${trace_creation_datetime}"
 
        # Domain
-       value=$(get_env_value "$metadata_env" domain)
-       ok $? "Extracting domain from env metadata"
-       expected_path="${expected_path}/${value}"
+       local domain
+       domain=$(get_env_value "$metadata_env" domain)
+       ok $? "Extracting domain from env metadata: \`$domain\`"
+       expected_path="${expected_path}/${domain}"
 
        # Buffering scheme
-       value=$(get_env_value "$metadata_env" tracer_buffering_scheme)
-       ok $? "Extracting tracer_buffering_scheme from env metadata"
-       expected_path="${expected_path}/${value}"
+       local tracer_buffering_scheme
+       tracer_buffering_scheme=$(get_env_value "$metadata_env" tracer_buffering_scheme)
+       ok $? "Extracting tracer_buffering_scheme from env metadata: \`$tracer_buffering_scheme\`"
+       expected_path="${expected_path}/${tracer_buffering_scheme}"
 
        # tracer_buffering_id
-       value=$(get_env_value "$metadata_env" tracer_buffering_id)
-       ok $? "Extracting tracer_buffering_id from env metadata"
-       expected_path="${expected_path}/${value}"
+       local tracer_buffering_id
+       tracer_buffering_id=$(get_env_value "$metadata_env" tracer_buffering_id)
+       ok $? "Extracting tracer_buffering_id from env metadata: \`$tracer_buffering_id\`"
+       expected_path="${expected_path}/${tracer_buffering_id}"
 
        # Check that the uid is the one we expect from the current user
-       is "$value" "$(id -u)" "tracer_buffering_id match current user uid"
+       is "$tracer_buffering_id" "$(id -u)" "tracer_buffering_id match current user uid: \`$tracer_buffering_id\`"
 
        # Architecture_bit_width
-       value=$(get_env_value "$metadata_env" architecture_bit_width)
-       ok $? "Extracting architecture_bit_width from env metadata"
-       expected_path="${expected_path}/${value}-bit"
+       local architecture_bit_width
+       architecture_bit_width=$(get_env_value "$metadata_env" architecture_bit_width)
+       ok $? "Extracting architecture_bit_width from env metadata: \`$architecture_bit_width\`"
+       expected_path="${expected_path}/${architecture_bit_width}-bit"
 
        # Append "metadata" and test that we find the file.
        expected_path="${expected_path}/metadata"
 
-       test -e "$expected_path"
-       ok $? "Reconstructed path from metadata is valid"
+       test -f "$expected_path"
+       ok $? "Reconstructed path from metadata is an existing file: \`$expected_path\`"
 
        # Hostname
        # The hostname is not part of the lttng hierarchy still we can test for
        # its validity here.
-       value=$(get_env_value "$metadata_env" hostname)
-       ok $? "Extracting hostname from env metadata"
-       is "$value" "$(hostname)" "Hostname is valid"
+       local hostname
+       hostname=$(get_env_value "$metadata_env" hostname)
+       ok $? "Extracting hostname from env metadata: \`$hostname\`"
+       is "$hostname" "$(hostname)" "Extracted hostname matches current hostname"
 
        rm -f "$metadata"
        rm -f "$metadata_env"
@@ -119,14 +127,15 @@ function test_per_uid ()
 function test_per_pid ()
 {
        local metadata_path
+       local metadata
+       local metadata_env
        local testapp_pid
-       local value
-       local value2
 
        local expected_path="${TRACE_PATH}/lttng-traces"
        local session_name="per-pid"
-       local metadata=$(mktemp --tmpdir tmp.test_${FUNCNAME[0]}_metadata.XXXXXX)
-       local metadata_env=$(mktemp --tmpdir tmp.test_${FUNCNAME[0]}_metadata_env.XXXXXX)
+
+       metadata=$(mktemp -t tmp.test_per_pid_metadata.XXXXXX)
+       metadata_env=$(mktemp -t tmp.test_per_pid_metadata_env.XXXXXX)
 
        diag "Test UST metadata env field in per-pid mode"
        create_lttng_session_ok "$session_name"
@@ -157,62 +166,70 @@ function test_per_pid ()
        # to allow trace viewer to recreate the same directory hierarchy.
 
        # Trace name
-       value=$(get_env_value "$metadata_env" trace_name)
-       ok $? "Extracting trace_name from env metadata"
-       expected_path="${expected_path}/${value}"
+       local trace_name
+       trace_name=$(get_env_value "$metadata_env" trace_name)
+       ok $? "Extracting trace_name from env metadata: \`$trace_name\`"
+       expected_path="${expected_path}/${trace_name}"
 
        # Session creation time
-       value=$(get_env_value "$metadata_env" trace_creation_datetime)
-       ok $? "Extracting trace_creation_datetime from env metadata"
-       value=$(iso8601_to_lttng_dir_datetime "$value")
-       expected_path="${expected_path}-${value}"
+       local trace_creation_datetime
+       trace_creation_datetime=$(get_env_value "$metadata_env" trace_creation_datetime)
+       ok $? "Extracting trace_creation_datetime from env metadata: \`$trace_creation_datetime\`"
+       trace_creation_datetime=$(iso8601_to_lttng_dir_datetime "$trace_creation_datetime")
+       expected_path="${expected_path}-${trace_creation_datetime}"
 
        # Domain
-       value=$(get_env_value "$metadata_env" domain)
-       ok $? "Extracting domain from env metadata"
-       expected_path="${expected_path}/${value}"
+       local domain
+       domain=$(get_env_value "$metadata_env" domain)
+       ok $? "Extracting domain from env metadata: \`$domain\`"
+       expected_path="${expected_path}/${domain}"
 
        # Buffering scheme
-       value=$(get_env_value "$metadata_env" tracer_buffering_scheme)
-       ok $? "Extracting tracer_buffering_scheme from env metadata"
-       expected_path="${expected_path}/${value}"
+       local tracer_buffering_scheme
+       tracer_buffering_scheme=$(get_env_value "$metadata_env" tracer_buffering_scheme)
+       ok $? "Extracting tracer_buffering_scheme from env metadata: \`$tracer_buffering_scheme\`"
+       expected_path="${expected_path}/${tracer_buffering_scheme}"
 
        # Procname
-       value=$(get_env_value "$metadata_env" procname)
-       ok $? "Extracting procname from env metadata"
-       expected_path="${expected_path}/${value}"
+       local procname
+       procname=$(get_env_value "$metadata_env" procname)
+       ok $? "Extracting procname from env metadata: \`$procname\`"
+       expected_path="${expected_path}/${procname}"
 
        # vpid and tracer_buffering_id should be the same here.
-       # "vpid =" is used since other key have vpid in them.
-       value=$(get_env_value "$metadata_env" "vpid =")
-       ok $? "Extracting vpid from env metadata"
+       local vpid
+       vpid=$(get_env_value "$metadata_env" "vpid")
+       ok $? "Extracting vpid from env metadata: \`$vpid\`"
 
-       value2=$(get_env_value "$metadata_env" tracer_buffering_id)
-       ok $? "Extracting tracer_buffering_id from env metadata"
-       expected_path="${expected_path}-${value2}"
+       local tracer_buffering_id
+       tracer_buffering_id=$(get_env_value "$metadata_env" tracer_buffering_id)
+       ok $? "Extracting tracer_buffering_id from env metadata: \`$tracer_buffering_id\`"
+       expected_path="${expected_path}-${tracer_buffering_id}"
 
-       is "$value" "$value2" "vpid and tracer_buffering_id are identical"
-       is "$testapp_pid" "$value" "vpid and known testapp pid are identical"
-       is "$testapp_pid" "$value2" "tracer_buffering_id and known testapp pid are identical"
+       is "$vpid" "$tracer_buffering_id" "vpid and tracer_buffering_id are identical"
+       is "$testapp_pid" "$vpid" "vpid and known testapp pid are identical"
+       is "$testapp_pid" "$tracer_buffering_id" "tracer_buffering_id and known testapp pid are identical"
 
        # vpid_datetime
-       value=$(get_env_value "$metadata_env" vpid_datetime)
-       ok $? "Extracting vpid_datetime from env metadata"
-       value=$(iso8601_to_lttng_dir_datetime "$value")
-       expected_path="${expected_path}-${value}"
+       local vpid_datetime
+       vpid_datetime=$(get_env_value "$metadata_env" vpid_datetime)
+       ok $? "Extracting vpid_datetime from env metadata: \`$vpid_datetime\`"
+       vpid_datetime=$(iso8601_to_lttng_dir_datetime "$vpid_datetime")
+       expected_path="${expected_path}-${vpid_datetime}"
 
        # Append "metadata" and test that we find the file.
        expected_path="${expected_path}/metadata"
 
-       test -e "$expected_path"
-       ok $? "Reconstructed path from metadata is valid"
+       test -f "$expected_path"
+       ok $? "Reconstructed path from metadata is an existing file: \`$expected_path\`"
 
        # Hostname
        # The hostname is not part of the lttng hierarchy still we can test for
        # its validity here.
-       value=$(get_env_value "$metadata_env" hostname)
-       ok $? "Extracting hostname from env metadata"
-       is "$value" "$(hostname)" "Hostname is valid"
+       local hostname
+       hostname=$(get_env_value "$metadata_env" hostname)
+       ok $? "Extracting hostname from env metadata: \`$hostname\`"
+       is "$hostname" "$(hostname)" "Extracted hostname matches current hostname"
 
        rm -f "$metadata"
        rm -f "$metadata_env"
@@ -226,9 +243,8 @@ bail_out_if_no_babeltrace
 
 # Use LTTNG_HOME since we want the complete "default" lttng directory hierarchy
 # with "<session_name>-<datetime>/...".
-LTTNG_HOME="$TRACE_PATH"
+export LTTNG_HOME="$TRACE_PATH"
 
-export LTTNG_HOME
 start_lttng_sessiond
 
 tests=( test_per_uid test_per_pid )
index 99a6cc6d856caeb3af20e9188a0729717733aef6..a355936c6d2265f69faf869b82bd658a3d534743 100644 (file)
@@ -11,7 +11,7 @@ function get_env_value ()
        local result
        local ret
 
-       result=$(grep "$key" < "$env_file")
+       result=$(grep "$key =" < "$env_file")
        ret=$?
        if [ $ret -eq 1 ]; then
                echo "invalid_value_extraction"
index bd0c59b8559438eb806bd5df49f63e4695327b7f..faeb3d09bc5f7bac534cfa742e26ad7771233fb5 100755 (executable)
@@ -17,8 +17,8 @@ NR_USEC_WAIT=0
 NR_ITER=10000
 
 #Temp file output
-OUTPUT_DIR=$(mktemp --tmpdir -d tmp.test_mi_output_dir.XXXXXX)
-SESSIOND_LOAD_DIR=$(mktemp --tmpdir -d tmp.test_mi_sessiond_load_dir.XXXXXX)
+OUTPUT_DIR=$(mktemp -d -t tmp.test_mi_output_dir.XXXXXX)
+SESSIOND_LOAD_DIR=$(mktemp -d -t tmp.test_mi_sessiond_load_dir.XXXXXX)
 OUTPUT_FILE="default.xml"
 
 XPATH_CMD_OUTPUT="//lttng:command/lttng:output"
@@ -536,8 +536,8 @@ function test_list_ust_event ()
 {
        diag "Test list ust event"
 
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        OUTPUT_FILE="list_ust_event.xml"
 
@@ -656,14 +656,14 @@ function test_start_stop ()
        ok $? "Mi test: enabled element : $result expected: false"
 
        #Test failing stop command
-       stop_lttng_tracing_fail $session_name
+       stop_lttng_tracing_ok $session_name
        $MI_VALIDATE $OUTPUT_DEST
-       ok $? "Mi test: failed stop xsd validation"
+       ok $? "Mi test: stop warning xsd validation"
 
-       #Expect a false element
+       #Expect a true element
        extract_xml $OUTPUT_DEST $XPATH_COMMAND_SUCCESS result
-       test "$result" = "false"
-       ok $? "Mi test: mi report failure on start command as expected"
+       test "$result" = "true"
+       ok $? "Mi test: mi reports success on stop command as expected"
 
        #Teardown
        OUTPUT_DEST=$DEVNULL
index b7e1a9f42f8eef81fa0be4ef55d924eec30c3034..1f7158aea34457782fb6a7e34005e88795f3b672 100644 (file)
@@ -9,12 +9,6 @@
  *
  */
 
-#include <stdio.h>
-#include <stdbool.h>
-#include <string.h>
-#include <unistd.h>
-#include <inttypes.h>
-
 #include <lttng/action/action.h>
 #include <lttng/action/list.h>
 #include <lttng/action/notify.h>
 #include <lttng/condition/evaluation.h>
 #include <lttng/domain.h>
 #include <lttng/endpoint.h>
+#include <lttng/lttng-error.h>
 #include <lttng/notification/channel.h>
 #include <lttng/notification/notification.h>
 #include <lttng/trigger/trigger.h>
-#include <lttng/lttng-error.h>
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
 
 static unsigned int nr_notifications = 0;
 static unsigned int nr_expected_notifications = 0;
@@ -39,12 +39,10 @@ static bool use_action_list = false;
 static enum lttng_condition_type buffer_usage_type = LTTNG_CONDITION_TYPE_UNKNOWN;
 static enum lttng_domain_type domain_type = LTTNG_DOMAIN_NONE;
 
-int handle_condition(
-               const struct lttng_condition *condition,
-               const struct lttng_evaluation *condition_evaluation);
+int handle_condition(const struct lttng_condition *condition,
+                    const struct lttng_evaluation *condition_evaluation);
 
-static
-int parse_arguments(char **argv)
+static int parse_arguments(char **argv)
 {
        int sscanf_ret;
        const char *domain_type_string = NULL;
@@ -91,32 +89,29 @@ int parse_arguments(char **argv)
        /* Ratio or bytes ? */
        if (!strcasecmp("bytes", buffer_usage_threshold_type)) {
                is_threshold_ratio = false;
-               sscanf_ret = sscanf(buffer_usage_threshold_value, "%" SCNu64,
-                               &threshold_bytes);
+               sscanf_ret = sscanf(buffer_usage_threshold_value, "%" SCNu64, &threshold_bytes);
                if (sscanf_ret != 1) {
                        printf("error: Invalid buffer usage threshold value bytes (integer), sscanf returned %d\n",
-                                       sscanf_ret);
+                              sscanf_ret);
                        goto error;
                }
        }
 
        if (!strcasecmp("ratio", buffer_usage_threshold_type)) {
                is_threshold_ratio = true;
-               sscanf_ret = sscanf(buffer_usage_threshold_value, "%lf",
-                               &threshold_ratio);
+               sscanf_ret = sscanf(buffer_usage_threshold_value, "%lf", &threshold_ratio);
                if (sscanf_ret != 1) {
                        printf("error: Invalid buffer usage threshold value ratio (float), sscanf returned %d\n",
-                                       sscanf_ret);
+                              sscanf_ret);
                        goto error;
                }
        }
 
        /* Number of notification to expect */
-       sscanf_ret = sscanf(nr_expected_notifications_string, "%d",
-                       &nr_expected_notifications);
+       sscanf_ret = sscanf(nr_expected_notifications_string, "%d", &nr_expected_notifications);
        if (sscanf_ret != 1) {
                printf("error: Invalid nr_expected_notifications, sscanf returned %d\n",
-                               sscanf_ret);
+                      sscanf_ret);
                goto error;
        }
 
@@ -162,8 +157,8 @@ int main(int argc, char **argv)
        }
 
        /* Setup */
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        if (!notification_channel) {
                printf("error: Could not create notification channel\n");
                ret = 1;
@@ -191,10 +186,10 @@ int main(int argc, char **argv)
 
        if (is_threshold_ratio) {
                condition_status = lttng_condition_buffer_usage_set_threshold_ratio(
-                               condition, threshold_ratio);
+                       condition, threshold_ratio);
        } else {
-               condition_status = lttng_condition_buffer_usage_set_threshold(
-                               condition, threshold_bytes);
+               condition_status =
+                       lttng_condition_buffer_usage_set_threshold(condition, threshold_bytes);
        }
 
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
@@ -203,22 +198,19 @@ int main(int argc, char **argv)
                goto end;
        }
 
-       condition_status = lttng_condition_buffer_usage_set_session_name(
-                       condition, session_name);
+       condition_status = lttng_condition_buffer_usage_set_session_name(condition, session_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                printf("error: Could not set session name\n");
                ret = 1;
                goto end;
        }
-       condition_status = lttng_condition_buffer_usage_set_channel_name(
-                       condition, channel_name);
+       condition_status = lttng_condition_buffer_usage_set_channel_name(condition, channel_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                printf("error: Could not set channel name\n");
                ret = 1;
                goto end;
        }
-       condition_status = lttng_condition_buffer_usage_set_domain_type(
-                       condition, domain_type);
+       condition_status = lttng_condition_buffer_usage_set_domain_type(condition, domain_type);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                printf("error: Could not set domain type\n");
                ret = 1;
@@ -302,9 +294,8 @@ int main(int argc, char **argv)
                        goto end;
                }
                /* Receive the next notification. */
-               status = lttng_notification_channel_get_next_notification(
-                               notification_channel,
-                               &notification);
+               status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                         &notification);
 
                switch (status) {
                case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
@@ -355,9 +346,8 @@ end:
        return ret;
 }
 
-int handle_condition(
-               const struct lttng_condition *condition,
-               const struct lttng_evaluation *evaluation)
+int handle_condition(const struct lttng_condition *condition,
+                    const struct lttng_evaluation *evaluation)
 {
        int ret = 0;
        const char *string_low = "low";
@@ -379,22 +369,19 @@ int handle_condition(
        }
 
        /* Fetch info to test */
-       ret = lttng_condition_buffer_usage_get_session_name(condition,
-                       &condition_session_name);
+       ret = lttng_condition_buffer_usage_get_session_name(condition, &condition_session_name);
        if (ret) {
                printf("error: session name could not be fetched\n");
                ret = 1;
                goto end;
        }
-       ret = lttng_condition_buffer_usage_get_channel_name(condition,
-                       &condition_channel_name);
+       ret = lttng_condition_buffer_usage_get_channel_name(condition, &condition_channel_name);
        if (ret) {
                printf("error: channel name could not be fetched\n");
                ret = 1;
                goto end;
        }
-       ret = lttng_condition_buffer_usage_get_domain_type(condition,
-                       &condition_domain_type);
+       ret = lttng_condition_buffer_usage_get_domain_type(condition, &condition_domain_type);
        if (ret) {
                printf("error: domain type could not be fetched\n");
                ret = 1;
@@ -420,8 +407,7 @@ int handle_condition(
        }
 
        if (is_threshold_ratio) {
-               lttng_evaluation_buffer_usage_get_usage_ratio(
-                               evaluation, &buffer_usage_ratio);
+               lttng_evaluation_buffer_usage_get_usage_ratio(evaluation, &buffer_usage_ratio);
                switch (condition_type) {
                case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
                        if (buffer_usage_ratio > threshold_ratio) {
@@ -443,8 +429,7 @@ int handle_condition(
                        goto end;
                }
        } else {
-               lttng_evaluation_buffer_usage_get_usage(
-                               evaluation, &buffer_usage_bytes);
+               lttng_evaluation_buffer_usage_get_usage(evaluation, &buffer_usage_bytes);
                switch (condition_type) {
                case LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW:
                        if (buffer_usage_bytes > threshold_bytes) {
index 9f2314acb8d3f82807ecbd95db581827a601261a..d7dc4c21e011401ee09322913d7cc4936517be5b 100644 (file)
@@ -7,15 +7,17 @@
 
 #include <common/compat/getenv.hpp>
 #include <common/consumer/consumer.hpp>
-#include <common/pipe.hpp>
 #include <common/error.hpp>
-#include <unistd.h>
-#include <stdbool.h>
+#include <common/pipe.hpp>
+
 #include <lttng/constant.h>
 #include <lttng/lttng-export.h>
-#include <fcntl.h>
+
 #include <dlfcn.h>
+#include <fcntl.h>
+#include <stdbool.h>
 #include <stdio.h>
+#include <unistd.h>
 
 static char *pause_pipe_path;
 static struct lttng_pipe *pause_pipe;
@@ -27,8 +29,7 @@ int lttng_opt_verbose;
 int lttng_opt_mi;
 int lttng_opt_quiet;
 
-static
-void __attribute__((destructor)) pause_pipe_fini(void)
+static void __attribute__((destructor)) pause_pipe_fini()
 {
        int ret;
 
@@ -54,8 +55,7 @@ int __testpoint_consumerd_thread_data(void)
        int ret = 0;
        const char *pause_pipe_path_prefix, *domain;
 
-       pause_pipe_path_prefix = lttng_secure_getenv(
-                       "CONSUMER_PAUSE_PIPE_PATH");
+       pause_pipe_path_prefix = lttng_secure_getenv("CONSUMER_PAUSE_PIPE_PATH");
        if (!pause_pipe_path_prefix) {
                ret = -1;
                goto end;
@@ -67,9 +67,10 @@ int __testpoint_consumerd_thread_data(void)
         * dynamically would not allow this shared object to be LD_PRELOAD-ed
         * when launching the session daemon.
         */
-       data_consumption_state = (int *) dlsym(NULL, "data_consumption_paused");
+       data_consumption_state = (int *) dlsym(nullptr, "data_consumption_paused");
        LTTNG_ASSERT(data_consumption_state);
-       lttng_consumer_get_type = (lttng_consumer_type (*)()) dlsym(NULL, "lttng_consumer_get_type");
+       lttng_consumer_get_type =
+               (lttng_consumer_type(*)()) dlsym(nullptr, "lttng_consumer_get_type");
        LTTNG_ASSERT(lttng_consumer_get_type);
 
        switch (lttng_consumer_get_type()) {
@@ -86,16 +87,15 @@ int __testpoint_consumerd_thread_data(void)
                abort();
        }
 
-       ret = asprintf(&pause_pipe_path, "%s-%s", pause_pipe_path_prefix,
-                       domain);
+       ret = asprintf(&pause_pipe_path, "%s-%s", pause_pipe_path_prefix, domain);
        if (ret < 1) {
                ERR("Failed to allocate pause pipe path");
                goto end;
        }
 
        DBG("Creating pause pipe at %s", pause_pipe_path);
-       pause_pipe = lttng_pipe_named_open(pause_pipe_path,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, O_NONBLOCK);
+       pause_pipe = lttng_pipe_named_open(
+               pause_pipe_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, O_NONBLOCK);
        if (!pause_pipe) {
                ERR("Failed to create pause pipe at %s", pause_pipe_path);
                ret = -1;
@@ -133,7 +133,7 @@ int __testpoint_consumerd_thread_data_poll(void)
        if (value_read) {
                *data_consumption_state = !!value;
                DBG("Message received on pause pipe: %s data consumption",
-                               *data_consumption_state ? "paused" : "resumed");
+                   *data_consumption_state ? "paused" : "resumed");
        }
 end:
        return ret;
index 843070b5923cd07dda15511d40d4f699085ec72d..34eb3cdd35fd514498f1169da196239d7d1c0ecb 100644 (file)
 #define _GNU_SOURCE
 #endif
 
-#include <unistd.h>
+#include <common/error.hpp>
+#include <common/pipe.hpp>
+
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
-
-#include <common/pipe.hpp>
-#include <common/error.hpp>
+#include <unistd.h>
 
 int lttng_opt_verbose;
 int lttng_opt_mi;
 int lttng_opt_quiet;
 
-int main(void)
+namespace {
+#ifdef __linux__
+/*
+ * Return the default pipe buffer size or a negative error.
+ */
+int get_pipe_size()
 {
        int ret;
        /*
@@ -38,20 +43,40 @@ int main(void)
 
        if (!pipe) {
                /* lttng_pipe_open already logs on error. */
-               ret = EXIT_FAILURE;
+               ret = -1;
                goto end;
        }
 
        ret = fcntl(lttng_pipe_get_writefd(pipe), F_GETPIPE_SZ);
        if (ret < 0) {
                PERROR("Failed to get the size of the pipe");
-               ret = EXIT_FAILURE;
-               goto end;
        }
 
-       printf("%d\n", ret);
-       ret = EXIT_SUCCESS;
-end:
        lttng_pipe_destroy(pipe);
+end:
        return ret;
 }
+#elif defined(__FreeBSD__)
+int get_pipe_size(void)
+{
+       return 65536;
+}
+#else
+#error "Implement get_pipe_size() for your platform."
+#endif
+} /* namespace */
+
+int main()
+{
+       int ret;
+
+       ret = get_pipe_size();
+       if (ret < 0) {
+               return EXIT_FAILURE;
+       }
+
+       /* Print the pipe buffer size to stdout. */
+       printf("%d\n", ret);
+
+       return EXIT_SUCCESS;
+}
index d3d486be3574a85c2f8bc5f6abc2ec0030d4834a..8eae08460a016034423b0ed2f6fd70c23a27e269 100644 (file)
@@ -9,37 +9,37 @@
  *
  */
 
+#include <common/compat/errno.hpp>
+#include <common/macros.hpp>
+
+#include <lttng/lttng.h>
+
+#include <fcntl.h>
+#include <inttypes.h>
 #include <math.h>
+#include <poll.h>
+#include <signal.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <inttypes.h>
-#include <sys/types.h>
 #include <sys/stat.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <poll.h>
-
-#include <common/compat/errno.hpp>
-#include <common/macros.hpp>
-#include <lttng/lttng.h>
-
+#include <sys/types.h>
 #include <tap/tap.h>
+#include <unistd.h>
 
 #define FIELD_NAME_MAX_LEN 256
 
 /* A callback to populate the condition capture descriptor. */
-typedef int (*condition_capture_desc_cb)(struct lttng_condition *condition);
+using condition_capture_desc_cb = int (*)(struct lttng_condition *);
 
 /* A callback for captured field validation. */
-typedef int (*validate_cb)(const struct lttng_event_field_value *event_field, unsigned iteration);
+using validate_cb = int (*)(const struct lttng_event_field_value *, unsigned int);
 
 int nb_args = 0;
 int named_pipe_args_start = 0;
 pid_t app_pid = 0;
-const char *app_state_file = NULL;
+const char *app_state_file = nullptr;
 
 enum field_type {
        FIELD_TYPE_PAYLOAD,
@@ -61,8 +61,7 @@ struct capture_base_field_tuple {
 };
 } /* namespace */
 
-static
-const char *field_value_type_to_str(enum lttng_event_field_value_type type)
+static const char *field_value_type_to_str(enum lttng_event_field_value_type type)
 {
        switch (type) {
        case LTTNG_EVENT_FIELD_VALUE_TYPE_UNKNOWN:
@@ -89,7 +88,7 @@ const char *field_value_type_to_str(enum lttng_event_field_value_type type)
 }
 
 static int validate_type(const struct lttng_event_field_value *event_field,
-               enum lttng_event_field_value_type expect)
+                        enum lttng_event_field_value_type expect)
 {
        int ret;
        enum lttng_event_field_value_type value;
@@ -100,9 +99,10 @@ static int validate_type(const struct lttng_event_field_value *event_field,
                goto end;
        }
 
-       ok(expect == value, "Expected field type %s, got %s",
-                       field_value_type_to_str(expect),
-                       field_value_type_to_str(value));
+       ok(expect == value,
+          "Expected field type %s, got %s",
+          field_value_type_to_str(expect),
+          field_value_type_to_str(value));
 
        ret = expect != value;
 
@@ -113,32 +113,30 @@ end:
 /*
  * Validate unsigned captured field against the iteration number.
  */
-static int validate_unsigned_int_field(
-               const struct lttng_event_field_value *event_field,
-               unsigned int expected_value)
+static int validate_unsigned_int_field(const struct lttng_event_field_value *event_field,
+                                      unsigned int expected_value)
 {
        int ret;
        uint64_t value;
        enum lttng_event_field_value_status status;
 
-       ret = validate_type(
-                       event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT);
+       ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT);
        if (ret) {
                goto end;
        }
 
-       status = lttng_event_field_value_unsigned_int_get_value(
-                       event_field, &value);
+       status = lttng_event_field_value_unsigned_int_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_unsigned_int_get_value returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
        ok(value == (uint64_t) expected_value,
-                       "Expected unsigned integer value %u, got %" PRIu64,
-                       expected_value, value);
+          "Expected unsigned integer value %u, got %" PRIu64,
+          expected_value,
+          value);
 
        ret = value != (uint64_t) expected_value;
 
@@ -149,9 +147,8 @@ end:
 /*
  * Validate signed captured field.
  */
-static int validate_signed_int_field(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_signed_int_field(const struct lttng_event_field_value *event_field,
+                                    unsigned int iteration)
 {
        int ret;
        const int64_t expected = -1;
@@ -161,25 +158,23 @@ static int validate_signed_int_field(
        /* Unused. */
        (void) iteration;
 
-       ret = validate_type(
-                       event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT);
+       ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_INT);
        if (ret) {
                goto end;
        }
 
-       status = lttng_event_field_value_signed_int_get_value(
-                       event_field, &value);
+       status = lttng_event_field_value_signed_int_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_signed_int_get_value returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
        ok(value == expected,
-                       "Expected signed integer value %" PRId64
-                       ", got %" PRId64,
-                       expected, value);
+          "Expected signed integer value %" PRId64 ", got %" PRId64,
+          expected,
+          value);
 
        ret = value != expected;
 
@@ -191,9 +186,8 @@ end:
 /*
  * Validate array of unsigned int.
  */
-static int validate_array_unsigned_int_field(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_array_unsigned_int_field(const struct lttng_event_field_value *event_field,
+                                            unsigned int iteration)
 {
        int ret;
        enum lttng_event_field_value_status status;
@@ -215,8 +209,7 @@ static int validate_array_unsigned_int_field(
                goto end;
        }
 
-       ok(count == expected, "Expected %d subelements, got %d", expected,
-                       count);
+       ok(count == expected, "Expected %d subelements, got %d", expected, count);
        if (count != expected) {
                ret = 1;
                goto end;
@@ -226,10 +219,10 @@ static int validate_array_unsigned_int_field(
                const struct lttng_event_field_value *value;
 
                status = lttng_event_field_value_array_get_element_at_index(
-                               event_field, i - 1, &value);
+                       event_field, i - 1, &value);
                if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        fail("lttng_event_field_value_array_get_element_at_index returned an error: status = %d",
-                                       (int) status);
+                            (int) status);
                        ret = 1;
                        goto end;
                }
@@ -246,9 +239,9 @@ end:
        return ret;
 }
 
-static int validate_array_unsigned_int_field_at_index(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int
+validate_array_unsigned_int_field_at_index(const struct lttng_event_field_value *event_field,
+                                          unsigned int iteration)
 {
        int ret;
        const uint64_t expected_value = 2;
@@ -258,24 +251,23 @@ static int validate_array_unsigned_int_field_at_index(
        /* Unused. */
        (void) iteration;
 
-       ret = validate_type(
-                       event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT);
+       ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_INT);
        if (ret) {
                goto end;
        }
 
-       status = lttng_event_field_value_unsigned_int_get_value(
-                       event_field, &value);
+       status = lttng_event_field_value_unsigned_int_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_unsigned_int_get_value returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
        ok(value == expected_value,
-                       "Expected unsigned integer value %" PRIu64 ", got %" PRIu64,
-                       expected_value, value);
+          "Expected unsigned integer value %" PRIu64 ", got %" PRIu64,
+          expected_value,
+          value);
 
        ret = 0;
 end:
@@ -288,12 +280,12 @@ end:
  * Value: "test" encoded in UTF-8: [116, 101, 115, 116]
  */
 static int validate_seqfield1(const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+                             unsigned int iteration)
 {
        int ret;
        enum lttng_event_field_value_status status;
        unsigned int i, count;
-       const unsigned int expect[] = {116, 101, 115, 116};
+       const unsigned int expect[] = { 116, 101, 115, 116 };
        const size_t array_count = sizeof(expect) / sizeof(*expect);
 
        /* Unused. */
@@ -307,13 +299,12 @@ static int validate_seqfield1(const struct lttng_event_field_value *event_field,
        status = lttng_event_field_value_array_get_length(event_field, &count);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_array_get_length returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
-       ok(count == array_count, "Expected %zu array sub-elements, got %d",
-                       array_count, count);
+       ok(count == array_count, "Expected %zu array sub-elements, got %d", array_count, count);
        if (count != array_count) {
                ret = 1;
                goto end;
@@ -322,11 +313,10 @@ static int validate_seqfield1(const struct lttng_event_field_value *event_field,
        for (i = 0; i < count; i++) {
                const struct lttng_event_field_value *value;
 
-               status = lttng_event_field_value_array_get_element_at_index(
-                               event_field, i, &value);
+               status = lttng_event_field_value_array_get_element_at_index(event_field, i, &value);
                if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        fail("lttng_event_field_value_array_get_element_at_index returned an error: status = %d",
-                                       (int) status);
+                            (int) status);
                        ret = 1;
                        goto end;
                }
@@ -342,12 +332,10 @@ end:
        return ret;
 }
 
-static int validate_string(
-               const struct lttng_event_field_value *event_field,
-               const char *expect)
+static int validate_string(const struct lttng_event_field_value *event_field, const char *expect)
 {
        int ret;
-       const char *value = NULL;
+       const char *value = nullptr;
        enum lttng_event_field_value_status status;
 
        ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_STRING);
@@ -358,13 +346,12 @@ static int validate_string(
        status = lttng_event_field_value_string_get_value(event_field, &value);
        if (!value) {
                fail("lttng_event_field_value_array_get_length returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
-       ok(!strcmp(value, expect), "Expected string value \"%s\", got \"%s\"",
-                       expect, value);
+       ok(!strcmp(value, expect), "Expected string value \"%s\", got \"%s\"", expect, value);
 
        ret = 0;
 end:
@@ -375,11 +362,10 @@ end:
 /*
  * Validate string. Expected value is "test".
  */
-static int validate_string_test(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_string_test(const struct lttng_event_field_value *event_field,
+                               unsigned int iteration)
 {
-       const char * const expect = "test";
+       const char *const expect = "test";
 
        /* Unused. */
        (void) iteration;
@@ -390,11 +376,10 @@ static int validate_string_test(
 /*
  * Validate escaped string. Expected value is "\*".
  */
-static int validate_string_escaped(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_string_escaped(const struct lttng_event_field_value *event_field,
+                                  unsigned int iteration)
 {
-       const char * const expect = "\\*";
+       const char *const expect = "\\*";
 
        /* Unused. */
        (void) iteration;
@@ -405,9 +390,7 @@ static int validate_string_escaped(
 /*
  * Validate real field.
  */
-static int validate_real(
-               const struct lttng_event_field_value *event_field,
-               double expect)
+static int validate_real(const struct lttng_event_field_value *event_field, double expect)
 {
        int ret;
        double value;
@@ -421,7 +404,7 @@ static int validate_real(
        status = lttng_event_field_value_real_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_real_get_value returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
@@ -435,9 +418,8 @@ end:
 /*
  * Validate floatfield.
  */
-static int validate_floatfield(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_floatfield(const struct lttng_event_field_value *event_field,
+                              unsigned int iteration)
 {
        const double expect = 2222.0;
 
@@ -450,9 +432,8 @@ static int validate_floatfield(
 /*
  * Validate doublefield.
  */
-static int validate_doublefield(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_doublefield(const struct lttng_event_field_value *event_field,
+                               unsigned int iteration)
 {
        const double expect = 2.0;
 
@@ -465,8 +446,7 @@ static int validate_doublefield(
 /*
  * Validate enum0: enum0 = ( "AUTO: EXPECT 0" : container = 0 )
  */
-static int validate_enum0(const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_enum0(const struct lttng_event_field_value *event_field, unsigned int iteration)
 {
        int ret;
        enum lttng_event_field_value_status status;
@@ -476,24 +456,23 @@ static int validate_enum0(const struct lttng_event_field_value *event_field,
        /* Unused. */
        (void) iteration;
 
-       ret = validate_type(event_field,
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM);
+       ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_UNSIGNED_ENUM);
        if (ret) {
                goto end;
        }
 
-       status = lttng_event_field_value_unsigned_int_get_value(
-                       event_field, &value);
+       status = lttng_event_field_value_unsigned_int_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_unsigned_int_get_value returned an error: status = %d",
-                               (int) status);
+                    (int) status);
                ret = 1;
                goto end;
        }
 
        ok(value == expected_value,
-                       "Expected enum value %" PRIu64 ", got %" PRIu64,
-                       expected_value, value);
+          "Expected enum value %" PRIu64 ", got %" PRIu64,
+          expected_value,
+          value);
 
 end:
        return ret;
@@ -504,9 +483,8 @@ end:
  *
  * We expect 2 labels here.
  */
-static int validate_enumnegative(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_enumnegative(const struct lttng_event_field_value *event_field,
+                                unsigned int iteration)
 {
        int ret;
        enum lttng_event_field_value_status status;
@@ -516,14 +494,12 @@ static int validate_enumnegative(
        /* Unused. */
        (void) iteration;
 
-       ret = validate_type(event_field,
-                       LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM);
+       ret = validate_type(event_field, LTTNG_EVENT_FIELD_VALUE_TYPE_SIGNED_ENUM);
        if (ret) {
                goto end;
        }
 
-       status = lttng_event_field_value_signed_int_get_value(
-                       event_field, &value);
+       status = lttng_event_field_value_signed_int_get_value(event_field, &value);
        if (status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("lttng_event_field_value_unsigned_int_get_value");
                ret = 1;
@@ -531,25 +507,24 @@ static int validate_enumnegative(
        }
 
        ok(value == expected_value,
-                       "Expected enum value %" PRId64 ", got %" PRId64,
-                       expected_value, value);
+          "Expected enum value %" PRId64 ", got %" PRId64,
+          expected_value,
+          value);
 
 end:
        return ret;
 }
 
-static int validate_context_procname_ust(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_context_procname_ust(const struct lttng_event_field_value *event_field,
+                                        unsigned int iteration)
 {
        /* Unused. */
        (void) iteration;
        return validate_string(event_field, "gen-ust-events");
 }
 
-static int validate_context_procname_kernel(
-               const struct lttng_event_field_value *event_field,
-               unsigned int iteration)
+static int validate_context_procname_kernel(const struct lttng_event_field_value *event_field,
+                                           unsigned int iteration)
 {
        /* Unused. */
        (void) iteration;
@@ -557,31 +532,90 @@ static int validate_context_procname_kernel(
 }
 
 struct capture_base_field_tuple test_capture_base_fields[] = {
-       { "DOESNOTEXIST", FIELD_TYPE_PAYLOAD, false, false, NULL, NULL },
-       { "intfield", FIELD_TYPE_PAYLOAD, true, true, validate_unsigned_int_field, validate_unsigned_int_field },
-       { "longfield", FIELD_TYPE_PAYLOAD, true, true, validate_unsigned_int_field, validate_unsigned_int_field },
-       { "signedfield", FIELD_TYPE_PAYLOAD, true, true, validate_signed_int_field, validate_signed_int_field },
-       { "arrfield1", FIELD_TYPE_PAYLOAD, true, true, validate_array_unsigned_int_field, validate_array_unsigned_int_field },
+       { "DOESNOTEXIST", FIELD_TYPE_PAYLOAD, false, false, nullptr, nullptr },
+       { "intfield",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_unsigned_int_field,
+         validate_unsigned_int_field },
+       { "longfield",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_unsigned_int_field,
+         validate_unsigned_int_field },
+       { "signedfield",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_signed_int_field,
+         validate_signed_int_field },
+       { "arrfield1",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_array_unsigned_int_field,
+         validate_array_unsigned_int_field },
        { "arrfield2", FIELD_TYPE_PAYLOAD, true, true, validate_string_test, validate_string_test },
-       { "arrfield3", FIELD_TYPE_PAYLOAD, true, true, validate_array_unsigned_int_field, validate_array_unsigned_int_field },
+       { "arrfield3",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_array_unsigned_int_field,
+         validate_array_unsigned_int_field },
        { "seqfield1", FIELD_TYPE_PAYLOAD, true, true, validate_seqfield1, validate_seqfield1 },
        { "seqfield2", FIELD_TYPE_PAYLOAD, true, true, validate_string_test, validate_string_test },
-       { "seqfield3", FIELD_TYPE_PAYLOAD, true, true, validate_array_unsigned_int_field, validate_array_unsigned_int_field },
-       { "seqfield4", FIELD_TYPE_PAYLOAD, true, true, validate_array_unsigned_int_field, validate_array_unsigned_int_field },
-       { "arrfield1[1]", FIELD_TYPE_ARRAY_FIELD, true, true, validate_array_unsigned_int_field_at_index, validate_array_unsigned_int_field_at_index },
+       { "seqfield3",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_array_unsigned_int_field,
+         validate_array_unsigned_int_field },
+       { "seqfield4",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_array_unsigned_int_field,
+         validate_array_unsigned_int_field },
+       { "arrfield1[1]",
+         FIELD_TYPE_ARRAY_FIELD,
+         true,
+         true,
+         validate_array_unsigned_int_field_at_index,
+         validate_array_unsigned_int_field_at_index },
        { "stringfield", FIELD_TYPE_PAYLOAD, true, true, validate_string_test, validate_string_test },
-       { "stringfield2", FIELD_TYPE_PAYLOAD, true, true, validate_string_escaped, validate_string_escaped },
+       { "stringfield2",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_string_escaped,
+         validate_string_escaped },
        { "floatfield", FIELD_TYPE_PAYLOAD, true, false, validate_floatfield, validate_floatfield },
-       { "doublefield", FIELD_TYPE_PAYLOAD, true, false, validate_doublefield, validate_doublefield },
+       { "doublefield",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         false,
+         validate_doublefield,
+         validate_doublefield },
        { "enum0", FIELD_TYPE_PAYLOAD, true, true, validate_enum0, validate_enum0 },
-       { "enumnegative", FIELD_TYPE_PAYLOAD, true, true, validate_enumnegative, validate_enumnegative },
-       { "$ctx.procname", FIELD_TYPE_CONTEXT, true, true, validate_context_procname_ust, validate_context_procname_kernel },
+       { "enumnegative",
+         FIELD_TYPE_PAYLOAD,
+         true,
+         true,
+         validate_enumnegative,
+         validate_enumnegative },
+       { "$ctx.procname",
+         FIELD_TYPE_CONTEXT,
+         true,
+         true,
+         validate_context_procname_ust,
+         validate_context_procname_kernel },
 };
 
-static const char *get_notification_trigger_name(
-               struct lttng_notification *notification)
+static const char *get_notification_trigger_name(struct lttng_notification *notification)
 {
-       const char *trigger_name = NULL;
+       const char *trigger_name = nullptr;
        enum lttng_trigger_status trigger_status;
        const struct lttng_trigger *trigger;
 
@@ -607,9 +641,8 @@ end:
        return trigger_name;
 }
 
-static int validator_notification_trigger_name(
-               struct lttng_notification *notification,
-               const char *trigger_name)
+static int validator_notification_trigger_name(struct lttng_notification *notification,
+                                              const char *trigger_name)
 {
        int ret;
        bool name_is_equal;
@@ -619,14 +652,13 @@ static int validator_notification_trigger_name(
        LTTNG_ASSERT(trigger_name);
 
        name = get_notification_trigger_name(notification);
-       if (name == NULL) {
+       if (name == nullptr) {
                ret = 1;
                goto end;
        }
 
        name_is_equal = (strcmp(trigger_name, name) == 0);
-       ok(name_is_equal, "Expected trigger name: %s got %s", trigger_name,
-                       name);
+       ok(name_is_equal, "Expected trigger name: %s got %s", trigger_name, name);
 
        ret = !name_is_equal;
 
@@ -634,8 +666,7 @@ end:
        return ret;
 }
 
-static
-void wait_on_file(const char *path, bool file_exist)
+static void wait_on_file(const char *path, bool file_exist)
 {
        if (!path) {
                return;
@@ -651,7 +682,7 @@ void wait_on_file(const char *path, bool file_exist)
                                 * The file does not exist. wait a bit and
                                 * continue looping until it does.
                                 */
-                               (void) poll(NULL, 0, 10);
+                               (void) poll(nullptr, 0, 10);
                                continue;
                        }
 
@@ -675,8 +706,7 @@ void wait_on_file(const char *path, bool file_exist)
        }
 }
 
-static
-int write_pipe(const char *path, uint8_t data)
+static int write_pipe(const char *path, uint8_t data)
 {
        int ret = 0;
        int fd = 0;
@@ -687,7 +717,7 @@ int write_pipe(const char *path, uint8_t data)
                goto end;
        }
 
-       ret = write(fd, &data , sizeof(data));
+       ret = write(fd, &data, sizeof(data));
        if (ret < 1) {
                perror("Named pipe write failed");
                if (close(fd)) {
@@ -707,8 +737,7 @@ end:
        return ret;
 }
 
-static
-int stop_consumer(const char **argv)
+static int stop_consumer(const char **argv)
 {
        int ret = 0, i;
 
@@ -718,8 +747,7 @@ int stop_consumer(const char **argv)
        return ret;
 }
 
-static
-int resume_consumer(const char **argv)
+static int resume_consumer(const char **argv)
 {
        int ret = 0, i;
 
@@ -729,8 +757,7 @@ int resume_consumer(const char **argv)
        return ret;
 }
 
-static
-int suspend_application(void)
+static int suspend_application()
 {
        int ret;
        struct stat buf;
@@ -757,11 +784,9 @@ int suspend_application(void)
 
 error:
        return ret;
-
 }
 
-static
-int resume_application(void)
+static int resume_application()
 {
        int ret;
        struct stat buf;
@@ -789,14 +814,11 @@ int resume_application(void)
 
 error:
        return ret;
-
 }
 
-
-static
-void test_triggers_buffer_usage_condition(const char *session_name,
-               const char *channel_name,
-               enum lttng_condition_type condition_type)
+static void test_triggers_buffer_usage_condition(const char *session_name,
+                                                const char *channel_name,
+                                                enum lttng_condition_type condition_type)
 {
        unsigned int test_vector_size = 5, i;
        enum lttng_condition_status condition_status;
@@ -810,13 +832,14 @@ void test_triggers_buffer_usage_condition(const char *session_name,
        }
 
        /* Test lttng_register_trigger with null value */
-       ok(lttng_register_trigger(NULL) == -LTTNG_ERR_INVALID, "Registering a NULL trigger fails as expected");
+       ok(lttng_register_trigger(nullptr) == -LTTNG_ERR_INVALID,
+          "Registering a NULL trigger fails as expected");
 
        /* Test: register a trigger */
 
-       for (i = 0; i < pow(2,test_vector_size); i++) {
+       for (i = 0; i < pow(2, test_vector_size); i++) {
                int loop_ret = 0;
-               char *test_tuple_string = NULL;
+               char *test_tuple_string = nullptr;
                unsigned int mask_position = 0;
                bool session_name_set = false;
                bool channel_name_set = false;
@@ -824,8 +847,8 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                bool threshold_byte_set = false;
                bool domain_type_set = false;
 
-               struct lttng_trigger *trigger = NULL;
-               struct lttng_condition *condition = NULL;
+               struct lttng_trigger *trigger = nullptr;
+               struct lttng_condition *condition = nullptr;
 
                /* Create base condition */
                switch (condition_type) {
@@ -843,7 +866,6 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                if (!condition) {
                        loop_ret = 1;
                        goto loop_end;
-
                }
 
                /* Prepare the condition for trigger registration test */
@@ -851,7 +873,7 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                /* Set session name */
                if ((1 << mask_position) & i) {
                        condition_status = lttng_condition_buffer_usage_set_session_name(
-                                       condition, session_name);
+                               condition, session_name);
                        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                                loop_ret = 1;
                                goto loop_end;
@@ -863,7 +885,7 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                /* Set channel name */
                if ((1 << mask_position) & i) {
                        condition_status = lttng_condition_buffer_usage_set_channel_name(
-                                       condition, channel_name);
+                               condition, channel_name);
                        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                                loop_ret = 1;
                                goto loop_end;
@@ -874,8 +896,8 @@ void test_triggers_buffer_usage_condition(const char *session_name,
 
                /* Set threshold ratio */
                if ((1 << mask_position) & i) {
-                       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(
-                                       condition, 0.0);
+                       condition_status =
+                               lttng_condition_buffer_usage_set_threshold_ratio(condition, 0.0);
                        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                                loop_ret = 1;
                                goto loop_end;
@@ -886,8 +908,7 @@ void test_triggers_buffer_usage_condition(const char *session_name,
 
                /* Set threshold byte */
                if ((1 << mask_position) & i) {
-                       condition_status = lttng_condition_buffer_usage_set_threshold(
-                                       condition, 0);
+                       condition_status = lttng_condition_buffer_usage_set_threshold(condition, 0);
                        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                                loop_ret = 1;
                                goto loop_end;
@@ -899,7 +920,7 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                /* Set domain type */
                if ((1 << mask_position) & i) {
                        condition_status = lttng_condition_buffer_usage_set_domain_type(
-                                       condition, LTTNG_DOMAIN_UST);
+                               condition, LTTNG_DOMAIN_UST);
                        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                                loop_ret = 1;
                                goto loop_end;
@@ -908,16 +929,18 @@ void test_triggers_buffer_usage_condition(const char *session_name,
                }
 
                /* Safety check */
-               if (mask_position != test_vector_size -1) {
+               if (mask_position != test_vector_size - 1) {
                        LTTNG_ASSERT("Logic error for test vector generation");
                }
 
-               loop_ret = asprintf(&test_tuple_string, "session name %s, channel name %s, threshold ratio %s, threshold byte %s, domain type %s",
-                               session_name_set ? "set" : "unset",
-                               channel_name_set ? "set" : "unset",
-                               threshold_ratio_set ? "set" : "unset",
-                               threshold_byte_set ? "set" : "unset",
-                               domain_type_set? "set" : "unset");
+               loop_ret = asprintf(
+                       &test_tuple_string,
+                       "session name %s, channel name %s, threshold ratio %s, threshold byte %s, domain type %s",
+                       session_name_set ? "set" : "unset",
+                       channel_name_set ? "set" : "unset",
+                       threshold_ratio_set ? "set" : "unset",
+                       threshold_byte_set ? "set" : "unset",
+                       domain_type_set ? "set" : "unset");
                if (!test_tuple_string || loop_ret < 0) {
                        loop_ret = 1;
                        goto loop_end;
@@ -932,16 +955,15 @@ void test_triggers_buffer_usage_condition(const char *session_name,
 
                loop_ret = lttng_register_trigger(trigger);
 
-loop_end:
+       loop_end:
                if (loop_ret == 1) {
                        fail("Setup error occurred for tuple: %s", test_tuple_string);
                        goto loop_cleanup;
                }
 
                /* This combination happens three times */
-               if (session_name_set && channel_name_set
-                               && (threshold_ratio_set || threshold_byte_set)
-                               && domain_type_set) {
+               if (session_name_set && channel_name_set &&
+                   (threshold_ratio_set || threshold_byte_set) && domain_type_set) {
                        ok(loop_ret == 0, "Trigger is registered: %s", test_tuple_string);
 
                        /*
@@ -949,7 +971,9 @@ loop_end:
                         * multiple time.
                         */
                        loop_ret = lttng_register_trigger(trigger);
-                       ok(loop_ret == -LTTNG_ERR_TRIGGER_EXISTS, "Re-register trigger fails as expected: %s", test_tuple_string);
+                       ok(loop_ret == -LTTNG_ERR_TRIGGER_EXISTS,
+                          "Re-register trigger fails as expected: %s",
+                          test_tuple_string);
 
                        /* Test that a trigger can be unregistered */
                        loop_ret = lttng_unregister_trigger(trigger);
@@ -960,12 +984,16 @@ loop_end:
                         * registered trigger fail.
                         */
                        loop_ret = lttng_unregister_trigger(trigger);
-                       ok(loop_ret == -LTTNG_ERR_TRIGGER_NOT_FOUND, "Unregister of a non-registered trigger fails as expected: %s", test_tuple_string);
+                       ok(loop_ret == -LTTNG_ERR_TRIGGER_NOT_FOUND,
+                          "Unregister of a non-registered trigger fails as expected: %s",
+                          test_tuple_string);
                } else {
-                       ok(loop_ret == -LTTNG_ERR_INVALID_TRIGGER, "Trigger is invalid as expected and cannot be registered: %s", test_tuple_string);
+                       ok(loop_ret == -LTTNG_ERR_INVALID_TRIGGER,
+                          "Trigger is invalid as expected and cannot be registered: %s",
+                          test_tuple_string);
                }
 
-loop_cleanup:
+       loop_cleanup:
                free(test_tuple_string);
                lttng_trigger_destroy(trigger);
                lttng_condition_destroy(condition);
@@ -975,8 +1003,7 @@ end:
        lttng_action_destroy(action);
 }
 
-static
-void wait_data_pending(const char *session_name)
+static void wait_data_pending(const char *session_name)
 {
        int ret;
 
@@ -986,39 +1013,32 @@ void wait_data_pending(const char *session_name)
        } while (ret != 0);
 }
 
-static
-int setup_buffer_usage_condition(struct lttng_condition *condition,
-               const char *condition_name,
-               const char *session_name,
-               const char *channel_name,
-               const enum lttng_domain_type domain_type)
+static int setup_buffer_usage_condition(struct lttng_condition *condition,
+                                       const char *condition_name,
+                                       const char *session_name,
+                                       const char *channel_name,
+                                       const enum lttng_domain_type domain_type)
 {
        enum lttng_condition_status condition_status;
        int ret = 0;
 
-       condition_status = lttng_condition_buffer_usage_set_session_name(
-                       condition, session_name);
+       condition_status = lttng_condition_buffer_usage_set_session_name(condition, session_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               fail("Failed to set session name on creation of condition `%s`",
-                               condition_name);
+               fail("Failed to set session name on creation of condition `%s`", condition_name);
                ret = -1;
                goto end;
        }
 
-       condition_status = lttng_condition_buffer_usage_set_channel_name(
-                       condition, channel_name);
+       condition_status = lttng_condition_buffer_usage_set_channel_name(condition, channel_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               fail("Failed to set channel name on creation of condition `%s`",
-                               condition_name);
+               fail("Failed to set channel name on creation of condition `%s`", condition_name);
                ret = -1;
                goto end;
        }
 
-       condition_status = lttng_condition_buffer_usage_set_domain_type(
-                       condition, domain_type);
+       condition_status = lttng_condition_buffer_usage_set_domain_type(condition, domain_type);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
-               fail("Failed to set domain type on creation of condition `%s`",
-                               condition_name);
+               fail("Failed to set domain type on creation of condition `%s`", condition_name);
                ret = -1;
                goto end;
        }
@@ -1027,19 +1047,17 @@ end:
        return ret;
 }
 
-static
-void test_invalid_channel_subscription(
-               const enum lttng_domain_type domain_type)
+static void test_invalid_channel_subscription(const enum lttng_domain_type domain_type)
 {
        enum lttng_condition_status condition_status;
        enum lttng_notification_channel_status nc_status;
-       struct lttng_condition *dummy_condition = NULL;
-       struct lttng_condition *dummy_invalid_condition = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
+       struct lttng_condition *dummy_condition = nullptr;
+       struct lttng_condition *dummy_invalid_condition = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
        int ret = 0;
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
        if (!notification_channel) {
                goto end;
@@ -1058,15 +1076,15 @@ void test_invalid_channel_subscription(
         * Test subscription and unsubscription of an invalid condition to/from
         * a channel.
         */
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, dummy_invalid_condition);
+       nc_status =
+               lttng_notification_channel_subscribe(notification_channel, dummy_invalid_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INVALID,
-                       "Subscribing to an invalid condition");
+          "Subscribing to an invalid condition");
 
-       nc_status = lttng_notification_channel_unsubscribe(
-                       notification_channel, dummy_invalid_condition);
+       nc_status = lttng_notification_channel_unsubscribe(notification_channel,
+                                                          dummy_invalid_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INVALID,
-                       "Unsubscribing from an invalid condition");
+          "Unsubscribing from an invalid condition");
 
        /* Create a valid dummy condition with a ratio of 0.5 */
        dummy_condition = lttng_condition_buffer_usage_low_create();
@@ -1075,15 +1093,14 @@ void test_invalid_channel_subscription(
                goto end;
        }
 
-       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(
-                       dummy_condition, 0.5);
+       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(dummy_condition, 0.5);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                fail("Setup error on condition creation");
                goto end;
        }
 
-       ret = setup_buffer_usage_condition(dummy_condition, "dummy_condition",
-                       "dummy_session", "dummy_channel", domain_type);
+       ret = setup_buffer_usage_condition(
+               dummy_condition, "dummy_condition", "dummy_session", "dummy_channel", domain_type);
        if (ret) {
                fail("Setup error on dummy condition creation");
                goto end;
@@ -1093,23 +1110,21 @@ void test_invalid_channel_subscription(
         * Test subscription and unsubscription to/from a channel with invalid
         * parameters.
         */
-       nc_status = lttng_notification_channel_subscribe(NULL, NULL);
+       nc_status = lttng_notification_channel_subscribe(nullptr, nullptr);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INVALID,
-                       "Notification channel subscription is invalid: NULL, NULL");
+          "Notification channel subscription is invalid: NULL, NULL");
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, NULL);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, nullptr);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INVALID,
-                       "Notification channel subscription is invalid: NON-NULL, NULL");
+          "Notification channel subscription is invalid: NON-NULL, NULL");
 
-       nc_status = lttng_notification_channel_subscribe(NULL, dummy_condition);
+       nc_status = lttng_notification_channel_subscribe(nullptr, dummy_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INVALID,
-                       "Notification channel subscription is invalid: NULL, NON-NULL");
+          "Notification channel subscription is invalid: NULL, NON-NULL");
 
-       nc_status = lttng_notification_channel_unsubscribe(
-                       notification_channel, dummy_condition);
+       nc_status = lttng_notification_channel_unsubscribe(notification_channel, dummy_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_UNKNOWN_CONDITION,
-                       "Unsubscribing from a valid unknown condition");
+          "Unsubscribing from a valid unknown condition");
 
 end:
        lttng_notification_channel_destroy(notification_channel);
@@ -1124,18 +1139,18 @@ enum buffer_usage_type {
 };
 
 static int register_buffer_usage_notify_trigger(const char *session_name,
-               const char *channel_name,
-               const enum lttng_domain_type domain_type,
-               enum buffer_usage_type buffer_usage_type,
-               double ratio,
-               struct lttng_condition **condition,
-               struct lttng_action **action,
-               struct lttng_trigger **trigger)
+                                               const char *channel_name,
+                                               const enum lttng_domain_type domain_type,
+                                               enum buffer_usage_type buffer_usage_type,
+                                               double ratio,
+                                               struct lttng_condition **condition,
+                                               struct lttng_action **action,
+                                               struct lttng_trigger **trigger)
 {
        enum lttng_condition_status condition_status;
-       struct lttng_action *tmp_action = NULL;
-       struct lttng_condition *tmp_condition = NULL;
-       struct lttng_trigger *tmp_trigger = NULL;
+       struct lttng_action *tmp_action = nullptr;
+       struct lttng_condition *tmp_condition = nullptr;
+       struct lttng_trigger *tmp_trigger = nullptr;
        int ret = 0;
 
        /* Set-up */
@@ -1159,16 +1174,15 @@ static int register_buffer_usage_notify_trigger(const char *session_name,
        }
 
        /* Set the buffer usage threashold */
-       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(
-                       tmp_condition, ratio);
+       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(tmp_condition, ratio);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                fail("Setup error on condition creation");
                ret = -1;
                goto error;
        }
 
-       ret = setup_buffer_usage_condition(tmp_condition, "condition_name",
-                       session_name, channel_name, domain_type);
+       ret = setup_buffer_usage_condition(
+               tmp_condition, "condition_name", session_name, channel_name, domain_type);
        if (ret) {
                fail("Setup error on condition creation");
                ret = -1;
@@ -1205,46 +1219,47 @@ end:
 }
 
 static void test_subscription_twice(const char *session_name,
-               const char *channel_name,
-               const enum lttng_domain_type domain_type)
+                                   const char *channel_name,
+                                   const enum lttng_domain_type domain_type)
 {
        int ret = 0;
        enum lttng_notification_channel_status nc_status;
 
-       struct lttng_action *action = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_action *action = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *trigger = nullptr;
 
-       struct lttng_condition *condition = NULL;
+       struct lttng_condition *condition = nullptr;
 
-       ret = register_buffer_usage_notify_trigger(session_name, channel_name,
-                       domain_type, BUFFER_USAGE_TYPE_LOW, 0.99, &condition,
-                       &action, &trigger);
+       ret = register_buffer_usage_notify_trigger(session_name,
+                                                  channel_name,
+                                                  domain_type,
+                                                  BUFFER_USAGE_TYPE_LOW,
+                                                  0.99,
+                                                  &condition,
+                                                  &action,
+                                                  &trigger);
        if (ret) {
-               fail("Setup error on trigger registration in %s()",
-                               __FUNCTION__);
+               fail("Setup error on trigger registration in %s()", __FUNCTION__);
                goto end;
        }
 
        /* Begin testing. */
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
        if (!notification_channel) {
                goto end;
        }
 
        /* Subscribe a valid condition. */
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
-       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to condition");
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
+       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK, "Subscribe to condition");
 
        /* Subscribing again should fail. */
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_ALREADY_SUBSCRIBED,
-                       "Subscribe to a condition for which subscription was already done");
+          "Subscribe to a condition for which subscription was already done");
 
 end:
        ret = lttng_unregister_trigger(trigger);
@@ -1259,61 +1274,67 @@ end:
 }
 
 static void test_buffer_usage_notification_channel(const char *session_name,
-               const char *channel_name,
-               const enum lttng_domain_type domain_type,
-               const char **argv)
+                                                  const char *channel_name,
+                                                  const enum lttng_domain_type domain_type,
+                                                  const char **argv)
 {
        int ret = 0;
        enum lttng_notification_channel_status nc_status;
 
-       struct lttng_action *low_action = NULL;
-       struct lttng_action *high_action = NULL;
-       struct lttng_notification *notification = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *low_trigger = NULL;
-       struct lttng_trigger *high_trigger = NULL;
+       struct lttng_action *low_action = nullptr;
+       struct lttng_action *high_action = nullptr;
+       struct lttng_notification *notification = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *low_trigger = nullptr;
+       struct lttng_trigger *high_trigger = nullptr;
 
-       struct lttng_condition *low_condition = NULL;
-       struct lttng_condition *high_condition = NULL;
+       struct lttng_condition *low_condition = nullptr;
+       struct lttng_condition *high_condition = nullptr;
 
        const double low_ratio = 0.0;
        const double high_ratio = 0.90;
 
-       ret = register_buffer_usage_notify_trigger(session_name, channel_name,
-                       domain_type, BUFFER_USAGE_TYPE_LOW, low_ratio,
-                       &low_condition, &low_action, &low_trigger);
+       ret = register_buffer_usage_notify_trigger(session_name,
+                                                  channel_name,
+                                                  domain_type,
+                                                  BUFFER_USAGE_TYPE_LOW,
+                                                  low_ratio,
+                                                  &low_condition,
+                                                  &low_action,
+                                                  &low_trigger);
        if (ret) {
                fail("Setup error on low trigger registration");
                goto end;
        }
 
-       ret = register_buffer_usage_notify_trigger(session_name, channel_name,
-                       domain_type, BUFFER_USAGE_TYPE_HIGH, high_ratio,
-                       &high_condition, &high_action, &high_trigger);
+       ret = register_buffer_usage_notify_trigger(session_name,
+                                                  channel_name,
+                                                  domain_type,
+                                                  BUFFER_USAGE_TYPE_HIGH,
+                                                  high_ratio,
+                                                  &high_condition,
+                                                  &high_action,
+                                                  &high_trigger);
        if (ret) {
                fail("Setup error on high trigger registration");
                goto end;
        }
 
        /* Begin testing */
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
        if (!notification_channel) {
                goto end;
        }
 
        /* Subscribe a valid low condition */
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, low_condition);
-       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to low condition");
+       nc_status = lttng_notification_channel_subscribe(notification_channel, low_condition);
+       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK, "Subscribe to low condition");
 
        /* Subscribe a valid high condition */
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, high_condition);
-       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to high condition");
+       nc_status = lttng_notification_channel_subscribe(notification_channel, high_condition);
+       ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK, "Subscribe to high condition");
 
        resume_application();
 
@@ -1323,16 +1344,15 @@ static void test_buffer_usage_notification_channel(const char *session_name,
 
        /* Wait for high notification */
        do {
-               nc_status = lttng_notification_channel_get_next_notification(
-                               notification_channel, &notification);
+               nc_status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                            &notification);
        } while (nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification &&
-                                       lttng_condition_get_type(lttng_notification_get_condition(
-                                                       notification)) ==
-                                                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
-                       "High notification received after intermediary communication");
+                  lttng_condition_get_type(lttng_notification_get_condition(notification)) ==
+                          LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
+          "High notification received after intermediary communication");
        lttng_notification_destroy(notification);
-       notification = NULL;
+       notification = nullptr;
 
        suspend_application();
        lttng_stop_tracing_no_wait(session_name);
@@ -1344,27 +1364,24 @@ static void test_buffer_usage_notification_channel(const char *session_name,
         * waiting for consumption.
         */
 
-       nc_status = lttng_notification_channel_unsubscribe(
-                       notification_channel, low_condition);
+       nc_status = lttng_notification_channel_unsubscribe(notification_channel, low_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Unsubscribe with pending notification");
+          "Unsubscribe with pending notification");
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, low_condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, low_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe with pending notification");
+          "Subscribe with pending notification");
 
        do {
-               nc_status = lttng_notification_channel_get_next_notification(
-                               notification_channel, &notification);
+               nc_status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                            &notification);
        } while (nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification &&
-                                       lttng_condition_get_type(lttng_notification_get_condition(
-                                                       notification)) ==
-                                                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW,
-                       "Low notification received after intermediary communication");
+                  lttng_condition_get_type(lttng_notification_get_condition(notification)) ==
+                          LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW,
+          "Low notification received after intermediary communication");
        lttng_notification_destroy(notification);
-       notification = NULL;
+       notification = nullptr;
 
        /* Stop consumer to force a high notification */
        stop_consumer(argv);
@@ -1372,16 +1389,15 @@ static void test_buffer_usage_notification_channel(const char *session_name,
        lttng_start_tracing(session_name);
 
        do {
-               nc_status = lttng_notification_channel_get_next_notification(
-                               notification_channel, &notification);
+               nc_status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                            &notification);
        } while (nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification &&
-                                       lttng_condition_get_type(lttng_notification_get_condition(
-                                                       notification)) ==
-                                                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
-                       "High notification received after intermediary communication");
+                  lttng_condition_get_type(lttng_notification_get_condition(notification)) ==
+                          LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
+          "High notification received after intermediary communication");
        lttng_notification_destroy(notification);
-       notification = NULL;
+       notification = nullptr;
 
        suspend_application();
        lttng_stop_tracing_no_wait(session_name);
@@ -1389,16 +1405,15 @@ static void test_buffer_usage_notification_channel(const char *session_name,
        wait_data_pending(session_name);
 
        do {
-               nc_status = lttng_notification_channel_get_next_notification(
-                               notification_channel, &notification);
+               nc_status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                            &notification);
        } while (nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification &&
-                                       lttng_condition_get_type(lttng_notification_get_condition(
-                                                       notification)) ==
-                                                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW,
-                       "Low notification received after re-subscription");
+                  lttng_condition_get_type(lttng_notification_get_condition(notification)) ==
+                          LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW,
+          "Low notification received after re-subscription");
        lttng_notification_destroy(notification);
-       notification = NULL;
+       notification = nullptr;
 
        stop_consumer(argv);
        resume_application();
@@ -1406,16 +1421,15 @@ static void test_buffer_usage_notification_channel(const char *session_name,
        lttng_start_tracing(session_name);
 
        do {
-               nc_status = lttng_notification_channel_get_next_notification(
-                               notification_channel, &notification);
+               nc_status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                            &notification);
        } while (nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification &&
-                                       lttng_condition_get_type(lttng_notification_get_condition(
-                                                       notification)) ==
-                                                       LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
-                       "High notification");
+                  lttng_condition_get_type(lttng_notification_get_condition(notification)) ==
+                          LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
+          "High notification");
        lttng_notification_destroy(notification);
-       notification = NULL;
+       notification = nullptr;
 
        suspend_application();
 
@@ -1424,15 +1438,13 @@ static void test_buffer_usage_notification_channel(const char *session_name,
        resume_consumer(argv);
        wait_data_pending(session_name);
 
-       nc_status = lttng_notification_channel_unsubscribe(
-                       notification_channel, low_condition);
+       nc_status = lttng_notification_channel_unsubscribe(notification_channel, low_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Unsubscribe low condition with pending notification");
+          "Unsubscribe low condition with pending notification");
 
-       nc_status = lttng_notification_channel_unsubscribe(
-                       notification_channel, high_condition);
+       nc_status = lttng_notification_channel_unsubscribe(notification_channel, high_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Unsubscribe high condition with pending notification");
+          "Unsubscribe high condition with pending notification");
 
 end:
        lttng_notification_channel_destroy(notification_channel);
@@ -1445,32 +1457,28 @@ end:
 }
 
 static void create_tracepoint_event_rule_trigger(const char *event_pattern,
-               const char *trigger_name,
-               const char *filter,
-               unsigned int exclusion_count,
-               const char * const *exclusions,
-               enum lttng_domain_type domain_type,
-               condition_capture_desc_cb capture_desc_cb,
-               struct lttng_condition **condition,
-               struct lttng_trigger **trigger)
+                                                const char *trigger_name,
+                                                const char *filter,
+                                                unsigned int exclusion_count,
+                                                const char *const *exclusions,
+                                                enum lttng_domain_type domain_type,
+                                                condition_capture_desc_cb capture_desc_cb,
+                                                struct lttng_condition **condition,
+                                                struct lttng_trigger **trigger)
 {
-       typedef struct lttng_event_rule *(*event_rule_create)(void);
-       typedef enum lttng_event_rule_status (
-                       *event_rule_set_name_pattern)(
-                       struct lttng_event_rule *rule,
-                       const char *pattern);
-       typedef enum lttng_event_rule_status (*event_rule_set_filter)(
-                       struct lttng_event_rule *rule,
-                       const char *expression);
-       typedef enum lttng_event_rule_status (
-                       *event_rule_add_name_pattern_exclusion)(
-                       struct lttng_event_rule * rule, const char *exclusion);
+       using event_rule_create = struct lttng_event_rule *(*) ();
+       using event_rule_set_name_pattern =
+               enum lttng_event_rule_status (*)(struct lttng_event_rule *, const char *);
+       using event_rule_set_filter =
+               enum lttng_event_rule_status (*)(struct lttng_event_rule *, const char *);
+       using event_rule_add_name_pattern_exclusion =
+               enum lttng_event_rule_status (*)(struct lttng_event_rule *, const char *);
 
        enum lttng_event_rule_status event_rule_status;
-       struct lttng_action *tmp_action = NULL;
-       struct lttng_event_rule *event_rule = NULL;
-       struct lttng_condition *tmp_condition = NULL;
-       struct lttng_trigger *tmp_trigger = NULL;
+       struct lttng_action *tmp_action = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
+       struct lttng_condition *tmp_condition = nullptr;
+       struct lttng_trigger *tmp_trigger = nullptr;
        int ret;
        enum lttng_error_code ret_code;
        event_rule_create create;
@@ -1489,13 +1497,14 @@ static void create_tracepoint_event_rule_trigger(const char *event_pattern,
                create = lttng_event_rule_user_tracepoint_create;
                set_name_pattern = lttng_event_rule_user_tracepoint_set_name_pattern;
                set_filter = lttng_event_rule_user_tracepoint_set_filter;
-               add_name_pattern_exclusion = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion;
+               add_name_pattern_exclusion =
+                       lttng_event_rule_user_tracepoint_add_name_pattern_exclusion;
                break;
        case LTTNG_DOMAIN_KERNEL:
                create = lttng_event_rule_kernel_tracepoint_create;
                set_name_pattern = lttng_event_rule_kernel_tracepoint_set_name_pattern;
                set_filter = lttng_event_rule_kernel_tracepoint_set_filter;
-               add_name_pattern_exclusion = NULL;
+               add_name_pattern_exclusion = nullptr;
                break;
        default:
                abort();
@@ -1507,14 +1516,14 @@ static void create_tracepoint_event_rule_trigger(const char *event_pattern,
 
        event_rule_status = set_name_pattern(event_rule, event_pattern);
        ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting tracepoint event rule pattern: '%s'",
-                       event_pattern);
+          "Setting tracepoint event rule pattern: '%s'",
+          event_pattern);
 
        if (filter) {
                event_rule_status = set_filter(event_rule, filter);
                ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Setting tracepoint event rule filter: '%s'",
-                               filter);
+                  "Setting tracepoint event rule filter: '%s'",
+                  filter);
        }
 
        if (exclusions) {
@@ -1522,15 +1531,14 @@ static void create_tracepoint_event_rule_trigger(const char *event_pattern,
                bool success = true;
 
                LTTNG_ASSERT(domain_type == LTTNG_DOMAIN_UST);
-               LTTNG_ASSERT(add_name_pattern_exclusion != NULL);
+               LTTNG_ASSERT(add_name_pattern_exclusion != nullptr);
                LTTNG_ASSERT(exclusion_count > 0);
 
                for (i = 0; i < exclusion_count; i++) {
-                       event_rule_status = add_name_pattern_exclusion(
-                                       event_rule, exclusions[i]);
+                       event_rule_status = add_name_pattern_exclusion(event_rule, exclusions[i]);
                        if (event_rule_status != LTTNG_EVENT_RULE_STATUS_OK) {
                                fail("Setting tracepoint event rule exclusion '%s'.",
-                                               exclusions[i]);
+                                    exclusions[i]);
                                success = false;
                        }
                }
@@ -1566,46 +1574,45 @@ static void create_tracepoint_event_rule_trigger(const char *event_pattern,
        return;
 }
 
-static struct lttng_notification *get_next_notification(
-               struct lttng_notification_channel *notification_channel)
+static struct lttng_notification *
+get_next_notification(struct lttng_notification_channel *notification_channel)
 {
-       struct lttng_notification *local_notification = NULL;
+       struct lttng_notification *local_notification = nullptr;
        enum lttng_notification_channel_status status;
 
        /* Receive the next notification. */
-       status = lttng_notification_channel_get_next_notification(
-                       notification_channel, &local_notification);
+       status = lttng_notification_channel_get_next_notification(notification_channel,
+                                                                 &local_notification);
 
        switch (status) {
        case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
                break;
        case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
                fail("Notifications have been dropped");
-               local_notification = NULL;
+               local_notification = nullptr;
                break;
        default:
                /* Unhandled conditions / errors. */
                fail("Failed to get next notification (unknown notification channel status): status = %d",
-                               (int) status);
-               local_notification = NULL;
+                    (int) status);
+               local_notification = nullptr;
                break;
        }
 
        return local_notification;
 }
 
-static void test_tracepoint_event_rule_notification(
-               enum lttng_domain_type domain_type)
+static void test_tracepoint_event_rule_notification(enum lttng_domain_type domain_type)
 {
        int i;
        int ret;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
-       struct lttng_action *action = NULL;
-       struct lttng_condition *condition = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *trigger = NULL;
-       const char * const trigger_name = "my_precious";
+       struct lttng_action *action = nullptr;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       const char *const trigger_name = "my_precious";
        const char *pattern;
 
        if (domain_type == LTTNG_DOMAIN_UST) {
@@ -1614,30 +1621,35 @@ static void test_tracepoint_event_rule_notification(
                pattern = "lttng_test_filter_event";
        }
 
-       create_tracepoint_event_rule_trigger(pattern, trigger_name, NULL, 0,
-                       NULL, domain_type, NULL, &condition, &trigger);
+       create_tracepoint_event_rule_trigger(pattern,
+                                            trigger_name,
+                                            nullptr,
+                                            0,
+                                            nullptr,
+                                            domain_type,
+                                            nullptr,
+                                            &condition,
+                                            &trigger);
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        /* Get notifications. */
        for (i = 0; i < notification_count; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -1658,17 +1670,16 @@ end:
        return;
 }
 
-static void test_tracepoint_event_rule_notification_filter(
-               enum lttng_domain_type domain_type)
+static void test_tracepoint_event_rule_notification_filter(enum lttng_domain_type domain_type)
 {
        int i;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
-       struct lttng_condition *ctrl_condition = NULL, *condition = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *ctrl_trigger = NULL, *trigger = NULL;
-       const char * const ctrl_trigger_name = "control_trigger";
-       const char * const trigger_name = "trigger";
+       struct lttng_condition *ctrl_condition = nullptr, *condition = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *ctrl_trigger = nullptr, *trigger = nullptr;
+       const char *const ctrl_trigger_name = "control_trigger";
+       const char *const trigger_name = "trigger";
        const char *pattern;
        int ctrl_count = 0, count = 0;
 
@@ -1678,30 +1689,41 @@ static void test_tracepoint_event_rule_notification_filter(
                pattern = "lttng_test_filter_event";
        }
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
-       create_tracepoint_event_rule_trigger(pattern, ctrl_trigger_name, NULL,
-                       0, NULL, domain_type, NULL, &ctrl_condition, &ctrl_trigger);
-
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, ctrl_condition);
+       create_tracepoint_event_rule_trigger(pattern,
+                                            ctrl_trigger_name,
+                                            nullptr,
+                                            0,
+                                            nullptr,
+                                            domain_type,
+                                            nullptr,
+                                            &ctrl_condition,
+                                            &ctrl_trigger);
+
+       nc_status = lttng_notification_channel_subscribe(notification_channel, ctrl_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        /*
         * Attach a filter expression to get notification only if the
         * `intfield` is even.
         */
-       create_tracepoint_event_rule_trigger(pattern, trigger_name,
-                       "(intfield & 1) == 0", 0, NULL, domain_type, NULL, &condition,
-                       &trigger);
-
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       create_tracepoint_event_rule_trigger(pattern,
+                                            trigger_name,
+                                            "(intfield & 1) == 0",
+                                            0,
+                                            nullptr,
+                                            domain_type,
+                                            nullptr,
+                                            &condition,
+                                            &trigger);
+
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        /*
         * We registered 2 notifications triggers, one with a filter and one
@@ -1718,19 +1740,18 @@ static void test_tracepoint_event_rule_notification_filter(
         */
        for (i = 0; i < notification_count; i++) {
                const char *name;
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
                name = get_notification_trigger_name(notification);
-               if (name == NULL) {
+               if (name == nullptr) {
                        lttng_notification_destroy(notification);
                        goto end;
                }
@@ -1744,8 +1765,7 @@ static void test_tracepoint_event_rule_notification_filter(
                lttng_notification_destroy(notification);
        }
 
-       ok(ctrl_count / 2 == count,
-                       "Get twice as many control notif as of regular notif");
+       ok(ctrl_count / 2 == count, "Get twice as many control notif as of regular notif");
 
 end:
        suspend_application();
@@ -1759,46 +1779,50 @@ end:
        lttng_condition_destroy(ctrl_condition);
 }
 
-static void test_tracepoint_event_rule_notification_exclusion(
-               enum lttng_domain_type domain_type)
+static void test_tracepoint_event_rule_notification_exclusion(enum lttng_domain_type domain_type)
 {
        enum lttng_notification_channel_status nc_status;
-       struct lttng_condition *ctrl_condition = NULL, *condition = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *ctrl_trigger = NULL, *trigger = NULL;
+       struct lttng_condition *ctrl_condition = nullptr, *condition = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *ctrl_trigger = nullptr, *trigger = nullptr;
        int ctrl_count = 0, count = 0, i;
        const int notification_count = 6;
-       const char * const ctrl_trigger_name = "control_exclusion_trigger";
-       const char * const trigger_name = "exclusion_trigger";
-       const char * const pattern = "tp:tptest*";
-       const char * const exclusions[] = {
-               "tp:tptest2",
-               "tp:tptest3",
-               "tp:tptest4",
-               "tp:tptest5"
-       };
-
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
-       ok(notification_channel, "Notification channel object creation");
+       const char *const ctrl_trigger_name = "control_exclusion_trigger";
+       const char *const trigger_name = "exclusion_trigger";
+       const char *const pattern = "tp:tptest*";
+       const char *const exclusions[] = { "tp:tptest2", "tp:tptest3", "tp:tptest4", "tp:tptest5" };
 
-       create_tracepoint_event_rule_trigger(pattern, ctrl_trigger_name, NULL,
-                       0, NULL, domain_type, NULL, &ctrl_condition,
-                       &ctrl_trigger);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
+       ok(notification_channel, "Notification channel object creation");
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, ctrl_condition);
+       create_tracepoint_event_rule_trigger(pattern,
+                                            ctrl_trigger_name,
+                                            nullptr,
+                                            0,
+                                            nullptr,
+                                            domain_type,
+                                            nullptr,
+                                            &ctrl_condition,
+                                            &ctrl_trigger);
+
+       nc_status = lttng_notification_channel_subscribe(notification_channel, ctrl_condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
-
-       create_tracepoint_event_rule_trigger(pattern, trigger_name, NULL, 4,
-                       exclusions, domain_type, NULL, &condition,
-                       &trigger);
-
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+          "Subscribe to tracepoint event rule condition");
+
+       create_tracepoint_event_rule_trigger(pattern,
+                                            trigger_name,
+                                            nullptr,
+                                            4,
+                                            exclusions,
+                                            domain_type,
+                                            nullptr,
+                                            &condition,
+                                            &trigger);
+
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        /*
         * We registered 2 notifications triggers, one with an exclusion and
@@ -1819,19 +1843,18 @@ static void test_tracepoint_event_rule_notification_exclusion(
         */
        for (i = 0; i < notification_count; i++) {
                const char *name;
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
                name = get_notification_trigger_name(notification);
-               if (name == NULL) {
+               if (name == nullptr) {
                        lttng_notification_destroy(notification);
                        goto end;
                }
@@ -1845,8 +1868,7 @@ static void test_tracepoint_event_rule_notification_exclusion(
                lttng_notification_destroy(notification);
        }
 
-       ok(ctrl_count / 5 == count,
-                       "Got 5 times as many control notif as of regular notif");
+       ok(ctrl_count / 5 == count, "Got 5 times as many control notif as of regular notif");
 
 end:
        suspend_application();
@@ -1861,21 +1883,21 @@ end:
        return;
 }
 
-static void test_kprobe_event_rule_notification(void)
+static void test_kprobe_event_rule_notification()
 {
        int i, ret;
        enum lttng_error_code ret_code;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
        enum lttng_event_rule_status event_rule_status;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_condition *condition = NULL;
-       struct lttng_kernel_probe_location *location = NULL;
-       struct lttng_event_rule *event_rule = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
-       const char * const trigger_name = "kprobe_trigger";
-       const char * const symbol_name = "lttng_test_filter_event_write";
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_kernel_probe_location *location = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       const char *const trigger_name = "kprobe_trigger";
+       const char *const symbol_name = "lttng_test_filter_event_write";
 
        action = lttng_action_notify_create();
        if (!action) {
@@ -1889,17 +1911,17 @@ static void test_kprobe_event_rule_notification(void)
                goto end;
        }
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
        event_rule = lttng_event_rule_kernel_kprobe_create(location);
        ok(event_rule, "kprobe event rule object creation");
 
-       event_rule_status = lttng_event_rule_kernel_kprobe_set_event_name(
-                       event_rule, trigger_name);
+       event_rule_status = lttng_event_rule_kernel_kprobe_set_event_name(event_rule, trigger_name);
        ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting kprobe event rule name: '%s'", trigger_name);
+          "Setting kprobe event rule name: '%s'",
+          trigger_name);
 
        condition = lttng_condition_event_rule_matches_create(event_rule);
        ok(condition, "Condition event rule object creation");
@@ -1917,22 +1939,20 @@ static void test_kprobe_event_rule_notification(void)
                goto end;
        }
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        for (i = 0; i < notification_count; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -1955,24 +1975,22 @@ end:
        return;
 }
 
-static void test_uprobe_event_rule_notification(
-               const char *testapp_path,
-               const char *test_symbol_name)
+static void test_uprobe_event_rule_notification(const char *testapp_path,
+                                               const char *test_symbol_name)
 {
        int i, ret;
        enum lttng_error_code ret_code;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
        enum lttng_event_rule_status event_rule_status;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_userspace_probe_location *probe_location = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method =
-                       NULL;
-       struct lttng_condition *condition = NULL;
-       struct lttng_event_rule *event_rule = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
-       const char * const trigger_name = "uprobe_trigger";
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_userspace_probe_location *probe_location = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       const char *const trigger_name = "uprobe_trigger";
 
        action = lttng_action_notify_create();
        if (!action) {
@@ -1987,23 +2005,23 @@ static void test_uprobe_event_rule_notification(
        }
 
        probe_location = lttng_userspace_probe_location_function_create(
-                       testapp_path, test_symbol_name, lookup_method);
+               testapp_path, test_symbol_name, lookup_method);
        if (!probe_location) {
                fail("Failed to create userspace probe location");
                goto end;
        }
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
        event_rule = lttng_event_rule_kernel_uprobe_create(probe_location);
-       ok(event_rule, "kprobe event rule object creation");
+       ok(event_rule, "uprobe event rule object creation");
 
-       event_rule_status = lttng_event_rule_kernel_uprobe_set_event_name(
-                       event_rule, trigger_name);
+       event_rule_status = lttng_event_rule_kernel_uprobe_set_event_name(event_rule, trigger_name);
        ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting uprobe event rule name: '%s'", trigger_name);
+          "Setting uprobe event rule name: '%s'",
+          trigger_name);
 
        condition = lttng_condition_event_rule_matches_create(event_rule);
        ok(condition, "Condition event rule object creation");
@@ -2021,22 +2039,20 @@ static void test_uprobe_event_rule_notification(
                goto end;
        }
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        for (i = 0; i < 3; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -2059,20 +2075,20 @@ end:
        return;
 }
 
-static void test_syscall_event_rule_notification(void)
+static void test_syscall_event_rule_notification()
 {
        int i, ret;
        enum lttng_error_code ret_code;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
        enum lttng_event_rule_status event_rule_status;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_condition *condition = NULL;
-       struct lttng_event_rule *event_rule = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
-       const char * const trigger_name = "syscall_trigger";
-       const char * const syscall_name = "openat";
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       const char *const trigger_name = "syscall_trigger";
+       const char *const syscall_name = "openat";
 
        action = lttng_action_notify_create();
        if (!action) {
@@ -2080,17 +2096,19 @@ static void test_syscall_event_rule_notification(void)
                goto end;
        }
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
-       event_rule = lttng_event_rule_kernel_syscall_create(LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
+       event_rule = lttng_event_rule_kernel_syscall_create(
+               LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
        ok(event_rule, "syscall event rule object creation");
 
-       event_rule_status = lttng_event_rule_kernel_syscall_set_name_pattern(
-                       event_rule, syscall_name);
+       event_rule_status =
+               lttng_event_rule_kernel_syscall_set_name_pattern(event_rule, syscall_name);
        ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting syscall event rule pattern: '%s'", syscall_name);
+          "Setting syscall event rule pattern: '%s'",
+          syscall_name);
 
        condition = lttng_condition_event_rule_matches_create(event_rule);
        ok(condition, "Condition syscall event rule object creation");
@@ -2108,22 +2126,20 @@ static void test_syscall_event_rule_notification(void)
                goto end;
        }
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        for (i = 0; i < notification_count; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -2143,21 +2159,21 @@ end:
        return;
 }
 
-static void test_syscall_event_rule_notification_filter(void)
+static void test_syscall_event_rule_notification_filter()
 {
        int i, ret;
        enum lttng_error_code ret_code;
        const int notification_count = 3;
        enum lttng_notification_channel_status nc_status;
        enum lttng_event_rule_status event_rule_status;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_condition *condition = NULL;
-       struct lttng_event_rule *event_rule = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
-       const char * const trigger_name = "syscall_trigger";
-       const char * const syscall_name = "openat";
-       const char * const filter_pattern = "filename == \"/proc/cpuinfo\"";
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_event_rule *event_rule = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
+       const char *const trigger_name = "syscall_trigger";
+       const char *const syscall_name = "openat";
+       const char *const filter_pattern = "filename == \"/proc/cpuinfo\"";
 
        action = lttng_action_notify_create();
        if (!action) {
@@ -2165,22 +2181,22 @@ static void test_syscall_event_rule_notification_filter(void)
                goto end;
        }
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
-       event_rule = lttng_event_rule_kernel_syscall_create(LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
+       event_rule = lttng_event_rule_kernel_syscall_create(
+               LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
        ok(event_rule, "syscall event rule object creation");
 
-       event_rule_status = lttng_event_rule_kernel_syscall_set_name_pattern(
-                       event_rule, syscall_name);
+       event_rule_status =
+               lttng_event_rule_kernel_syscall_set_name_pattern(event_rule, syscall_name);
        ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting syscall event rule pattern: '%s'", syscall_name);
+          "Setting syscall event rule pattern: '%s'",
+          syscall_name);
 
-       event_rule_status = lttng_event_rule_kernel_syscall_set_filter(
-                       event_rule, filter_pattern);
-       ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting filter: '%s'", filter_pattern);
+       event_rule_status = lttng_event_rule_kernel_syscall_set_filter(event_rule, filter_pattern);
+       ok(event_rule_status == LTTNG_EVENT_RULE_STATUS_OK, "Setting filter: '%s'", filter_pattern);
 
        condition = lttng_condition_event_rule_matches_create(event_rule);
        ok(condition, "Condition event rule object creation");
@@ -2198,22 +2214,20 @@ static void test_syscall_event_rule_notification_filter(void)
                goto end;
        }
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        for (i = 0; i < notification_count; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
 
-               ok(notification, "Received notification (%d/%d)", i + 1,
-                               notification_count);
+               ok(notification, "Received notification (%d/%d)", i + 1, notification_count);
 
                /* Error. */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -2238,45 +2252,44 @@ end:
 static int generate_capture_descr(struct lttng_condition *condition)
 {
        int ret, i;
-       struct lttng_event_expr *expr = NULL;
-       const unsigned int basic_field_count = sizeof(test_capture_base_fields) /
-                       sizeof(*test_capture_base_fields);
+       struct lttng_event_expr *expr = nullptr;
+       const unsigned int basic_field_count =
+               sizeof(test_capture_base_fields) / sizeof(*test_capture_base_fields);
        enum lttng_condition_status cond_status;
 
        for (i = 0; i < basic_field_count; i++) {
-               diag("Adding capture descriptor '%s'",
-                               test_capture_base_fields[i].field_name);
+               diag("Adding capture descriptor '%s'", test_capture_base_fields[i].field_name);
 
                switch (test_capture_base_fields[i].field_type) {
                case FIELD_TYPE_PAYLOAD:
                        expr = lttng_event_expr_event_payload_field_create(
-                                       test_capture_base_fields[i].field_name);
+                               test_capture_base_fields[i].field_name);
                        break;
                case FIELD_TYPE_CONTEXT:
                        expr = lttng_event_expr_channel_context_field_create(
-                                       test_capture_base_fields[i].field_name);
+                               test_capture_base_fields[i].field_name);
                        break;
                case FIELD_TYPE_ARRAY_FIELD:
                {
                        int nb_matches;
                        unsigned int index;
                        char field_name[FIELD_NAME_MAX_LEN];
-                       struct lttng_event_expr *array_expr = NULL;
+                       struct lttng_event_expr *array_expr = nullptr;
 
                        nb_matches = sscanf(test_capture_base_fields[i].field_name,
-                                       "%[^[][%u]", field_name, &index);
+                                           "%[^[][%u]",
+                                           field_name,
+                                           &index);
                        if (nb_matches != 2) {
                                fail("Unexpected array field name format: field name = '%s'",
-                                               test_capture_base_fields[i].field_name);
+                                    test_capture_base_fields[i].field_name);
                                ret = 1;
                                goto end;
                        }
 
-                       array_expr = lttng_event_expr_event_payload_field_create(
-                               field_name);
+                       array_expr = lttng_event_expr_event_payload_field_create(field_name);
 
-                       expr = lttng_event_expr_array_field_element_create(
-                               array_expr, index);
+                       expr = lttng_event_expr_array_field_element_create(array_expr, index);
                        break;
                }
                case FIELD_TYPE_APP_CONTEXT:
@@ -2287,14 +2300,14 @@ static int generate_capture_descr(struct lttng_condition *condition)
                        goto end;
                }
 
-               if (expr == NULL) {
+               if (expr == nullptr) {
                        fail("Failed to create capture expression");
                        ret = -1;
                        goto end;
                }
 
                cond_status = lttng_condition_event_rule_matches_append_capture_descriptor(
-                               condition, expr);
+                       condition, expr);
                if (cond_status != LTTNG_CONDITION_STATUS_OK) {
                        fail("Failed to append capture descriptor");
                        ret = -1;
@@ -2309,41 +2322,37 @@ end:
        return ret;
 }
 
-static int validator_notification_trigger_capture(
-               enum lttng_domain_type domain,
-               struct lttng_notification *notification,
-               const int iteration)
+static int validator_notification_trigger_capture(enum lttng_domain_type domain,
+                                                 struct lttng_notification *notification,
+                                                 const int iteration)
 {
        int ret;
        unsigned int capture_count, i;
-       enum lttng_evaluation_event_rule_matches_status
-                       event_rule_matches_evaluation_status;
+       enum lttng_evaluation_event_rule_matches_status event_rule_matches_evaluation_status;
        enum lttng_event_field_value_status event_field_value_status;
        const struct lttng_evaluation *evaluation;
        const struct lttng_event_field_value *captured_fields;
        bool at_least_one_error = false;
 
        evaluation = lttng_notification_get_evaluation(notification);
-       if (evaluation == NULL) {
+       if (evaluation == nullptr) {
                fail("Failed to get evaluation from notification during trigger capture test");
                ret = 1;
                goto end;
        }
 
        event_rule_matches_evaluation_status =
-                       lttng_evaluation_event_rule_matches_get_captured_values(
-                                       evaluation, &captured_fields);
-       if (event_rule_matches_evaluation_status !=
-                       LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_OK) {
+               lttng_evaluation_event_rule_matches_get_captured_values(evaluation,
+                                                                       &captured_fields);
+       if (event_rule_matches_evaluation_status != LTTNG_EVALUATION_EVENT_RULE_MATCHES_STATUS_OK) {
                diag("Failed to get event rule evaluation captured values: status = %d",
-                               (int) event_rule_matches_evaluation_status);
+                    (int) event_rule_matches_evaluation_status);
                ret = 1;
                goto end;
        }
 
        event_field_value_status =
-               lttng_event_field_value_array_get_length(captured_fields,
-                               &capture_count);
+               lttng_event_field_value_array_get_length(captured_fields, &capture_count);
        if (event_field_value_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                fail("Failed to get count of captured value field array");
                ret = 1;
@@ -2351,18 +2360,15 @@ static int validator_notification_trigger_capture(
        }
 
        for (i = 0; i < capture_count; i++) {
-               const struct lttng_event_field_value *captured_field = NULL;
+               const struct lttng_event_field_value *captured_field = nullptr;
                validate_cb validate;
                bool expected;
 
-               diag("Validating capture of field '%s'",
-                               test_capture_base_fields[i].field_name);
-               event_field_value_status =
-                               lttng_event_field_value_array_get_element_at_index(
-                                               captured_fields, i,
-                                               &captured_field);
+               diag("Validating capture of field '%s'", test_capture_base_fields[i].field_name);
+               event_field_value_status = lttng_event_field_value_array_get_element_at_index(
+                       captured_fields, i, &captured_field);
 
-               switch(domain) {
+               switch (domain) {
                case LTTNG_DOMAIN_UST:
                        expected = test_capture_base_fields[i].expected_ust;
                        break;
@@ -2370,8 +2376,7 @@ static int validator_notification_trigger_capture(
                        expected = test_capture_base_fields[i].expected_kernel;
                        break;
                default:
-                       fail("Unexpected domain encountered: domain = %d",
-                                       (int) domain);
+                       fail("Unexpected domain encountered: domain = %d", (int) domain);
                        ret = 1;
                        goto end;
                }
@@ -2384,17 +2389,17 @@ static int validator_notification_trigger_capture(
 
                if (!expected) {
                        ok(event_field_value_status == LTTNG_EVENT_FIELD_VALUE_STATUS_UNAVAILABLE,
-                                       "No payload captured");
+                          "No payload captured");
                        continue;
                }
 
                if (event_field_value_status != LTTNG_EVENT_FIELD_VALUE_STATUS_OK) {
                        if (event_field_value_status ==
-                                       LTTNG_EVENT_FIELD_VALUE_STATUS_UNAVAILABLE) {
+                           LTTNG_EVENT_FIELD_VALUE_STATUS_UNAVAILABLE) {
                                fail("Expected a capture but it is unavailable");
                        } else {
                                fail("lttng_event_field_value_array_get_element_at_index returned an error: status = %d",
-                                               (int) event_field_value_status);
+                                    (int) event_field_value_status);
                        }
 
                        ret = 1;
@@ -2402,8 +2407,7 @@ static int validator_notification_trigger_capture(
                }
 
                diag("Captured field of type %s",
-                               field_value_type_to_str(
-                                       lttng_event_field_value_get_type(captured_field)));
+                    field_value_type_to_str(lttng_event_field_value_get_type(captured_field)));
 
                LTTNG_ASSERT(validate);
                ret = validate(captured_field, iteration);
@@ -2418,15 +2422,14 @@ end:
        return ret;
 }
 
-static void test_tracepoint_event_rule_notification_capture(
-               enum lttng_domain_type domain_type)
+static void test_tracepoint_event_rule_notification_capture(enum lttng_domain_type domain_type)
 {
        enum lttng_notification_channel_status nc_status;
 
        int i, ret;
-       struct lttng_condition *condition = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_notification_channel *notification_channel = nullptr;
+       struct lttng_trigger *trigger = nullptr;
        const char *trigger_name = "my_precious";
        const char *pattern;
 
@@ -2436,29 +2439,34 @@ static void test_tracepoint_event_rule_notification_capture(
                pattern = "lttng_test_filter_event";
        }
 
-       create_tracepoint_event_rule_trigger(pattern, trigger_name, NULL, 0,
-                       NULL, domain_type, generate_capture_descr, &condition,
-                       &trigger);
+       create_tracepoint_event_rule_trigger(pattern,
+                                            trigger_name,
+                                            nullptr,
+                                            0,
+                                            nullptr,
+                                            domain_type,
+                                            generate_capture_descr,
+                                            &condition,
+                                            &trigger);
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        ok(notification_channel, "Notification channel object creation");
 
-       nc_status = lttng_notification_channel_subscribe(
-                       notification_channel, condition);
+       nc_status = lttng_notification_channel_subscribe(notification_channel, condition);
        ok(nc_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to tracepoint event rule condition");
+          "Subscribe to tracepoint event rule condition");
 
        resume_application();
 
        /* Get 3 notifications */
        for (i = 0; i < 3; i++) {
-               struct lttng_notification *notification = get_next_notification(
-                               notification_channel);
+               struct lttng_notification *notification =
+                       get_next_notification(notification_channel);
                ok(notification, "Received notification");
 
                /* Error */
-               if (notification == NULL) {
+               if (notification == nullptr) {
                        goto end;
                }
 
@@ -2489,7 +2497,7 @@ end:
 int main(int argc, const char *argv[])
 {
        int test_scenario;
-       const char *domain_type_string = NULL;
+       const char *domain_type_string = nullptr;
        enum lttng_domain_type domain_type = LTTNG_DOMAIN_NONE;
 
        if (argc < 5) {
@@ -2525,16 +2533,14 @@ int main(int argc, const char *argv[])
                plan_tests(41);
 
                /* Test cases that need gen-ust-event testapp. */
-               diag("Test basic notification error paths for %s domain",
-                               domain_type_string);
+               diag("Test basic notification error paths for %s domain", domain_type_string);
                test_invalid_channel_subscription(domain_type);
 
-               diag("Test tracepoint event rule notifications for domain %s",
-                               domain_type_string);
+               diag("Test tracepoint event rule notifications for domain %s", domain_type_string);
                test_tracepoint_event_rule_notification(domain_type);
 
                diag("Test tracepoint event rule notifications with filter for domain %s",
-                               domain_type_string);
+                    domain_type_string);
                test_tracepoint_event_rule_notification_filter(domain_type);
                break;
        }
@@ -2561,23 +2567,22 @@ int main(int argc, const char *argv[])
                session_name = argv[5];
                channel_name = argv[6];
 
-               test_subscription_twice(session_name, channel_name,
-                               domain_type);
+               test_subscription_twice(session_name, channel_name, domain_type);
 
                diag("Test trigger for domain %s with buffer_usage_low condition",
-                               domain_type_string);
-               test_triggers_buffer_usage_condition(session_name, channel_name,
-                               LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW);
+                    domain_type_string);
+               test_triggers_buffer_usage_condition(
+                       session_name, channel_name, LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW);
 
                diag("Test trigger for domain %s with buffer_usage_high condition",
-                               domain_type_string);
-               test_triggers_buffer_usage_condition(session_name, channel_name,
-                               LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH);
+                    domain_type_string);
+               test_triggers_buffer_usage_condition(
+                       session_name, channel_name, LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH);
 
                diag("Test buffer usage notification channel api for domain %s",
-                               domain_type_string);
-               test_buffer_usage_notification_channel(session_name, channel_name,
-                               domain_type, argv);
+                    domain_type_string);
+               test_buffer_usage_notification_channel(
+                       session_name, channel_name, domain_type, argv);
                break;
        }
        case 3:
@@ -2594,7 +2599,7 @@ int main(int argc, const char *argv[])
                 */
                LTTNG_ASSERT(domain_type == LTTNG_DOMAIN_UST);
                diag("Test tracepoint event rule notifications with exclusion for domain %s",
-                               domain_type_string);
+                    domain_type_string);
                test_tracepoint_event_rule_notification_exclusion(domain_type);
 
                break;
@@ -2605,8 +2610,7 @@ int main(int argc, const char *argv[])
                /* Test cases that need the kernel tracer. */
                LTTNG_ASSERT(domain_type == LTTNG_DOMAIN_KERNEL);
 
-               diag("Test kprobe event rule notifications for domain %s",
-                               domain_type_string);
+               diag("Test kprobe event rule notifications for domain %s", domain_type_string);
 
                test_kprobe_event_rule_notification();
 
@@ -2618,13 +2622,12 @@ int main(int argc, const char *argv[])
                /* Test cases that need the kernel tracer. */
                LTTNG_ASSERT(domain_type == LTTNG_DOMAIN_KERNEL);
 
-               diag("Test syscall event rule notifications for domain %s",
-                               domain_type_string);
+               diag("Test syscall event rule notifications for domain %s", domain_type_string);
 
                test_syscall_event_rule_notification();
 
                diag("Test syscall filtering event rule notifications for domain %s",
-                               domain_type_string);
+                    domain_type_string);
 
                test_syscall_event_rule_notification_filter();
 
@@ -2647,16 +2650,15 @@ int main(int argc, const char *argv[])
                LTTNG_ASSERT(domain_type == LTTNG_DOMAIN_KERNEL);
 
                diag("Test userspace-probe event rule notifications for domain %s",
-                               domain_type_string);
+                    domain_type_string);
 
-               test_uprobe_event_rule_notification(
-                               testapp_path, test_symbol_name);
+               test_uprobe_event_rule_notification(testapp_path, test_symbol_name);
 
                break;
        }
        case 7:
        {
-               switch(domain_type) {
+               switch (domain_type) {
                case LTTNG_DOMAIN_UST:
                        plan_tests(221);
                        break;
@@ -2668,7 +2670,7 @@ int main(int argc, const char *argv[])
                }
 
                diag("Test tracepoint event rule notification captures for domain %s",
-                               domain_type_string);
+                    domain_type_string);
                test_tracepoint_event_rule_notification_capture(domain_type);
 
                break;
@@ -2681,4 +2683,3 @@ int main(int argc, const char *argv[])
 error:
        return exit_status();
 }
-
index 55ee2e69e79b15c37d7464150b94b6ae87e2397d..1007de44ee18e5d7ce987c8b14714a512b97c145 100644 (file)
@@ -9,12 +9,13 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <tap/tap.h>
+#include <lttng/lttng.h>
+
 #include <stdint.h>
+#include <stdio.h>
 #include <string.h>
-#include <lttng/lttng.h>
+#include <tap/tap.h>
+#include <unistd.h>
 
 #define TEST_COUNT 36
 
@@ -25,41 +26,35 @@ struct session {
 
 uint64_t expected_rotation_id = UINT64_MAX;
 
-static
-int test_condition(struct lttng_condition *condition, const char *type_name)
+static int test_condition(struct lttng_condition *condition, const char *type_name)
 {
        int ret = 0;
        const char *out_session_name;
-       const char * const session_name = "test session name";
+       const char *const session_name = "test session name";
        enum lttng_condition_status status;
 
-       status = lttng_condition_session_rotation_get_session_name(condition,
-                       &out_session_name);
+       status = lttng_condition_session_rotation_get_session_name(condition, &out_session_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET,
-                       "Getting unset name of %s condition fails with LTTNG_CONDITION_STATUS_UNSET",
-                       type_name);
+          "Getting unset name of %s condition fails with LTTNG_CONDITION_STATUS_UNSET",
+          type_name);
 
-       status = lttng_condition_session_rotation_set_session_name(condition,
-                       session_name);
+       status = lttng_condition_session_rotation_set_session_name(condition, session_name);
        ok(status == LTTNG_CONDITION_STATUS_OK,
-                       "Setting session name \"%s\" of %s condition succeeds",
-                       session_name, type_name);
+          "Setting session name \"%s\" of %s condition succeeds",
+          session_name,
+          type_name);
 
-       status = lttng_condition_session_rotation_get_session_name(condition,
-                       &out_session_name);
-       ok(status == LTTNG_CONDITION_STATUS_OK,
-                       "Getting name of %s condition succeeds",
-                       type_name);
+       status = lttng_condition_session_rotation_get_session_name(condition, &out_session_name);
+       ok(status == LTTNG_CONDITION_STATUS_OK, "Getting name of %s condition succeeds", type_name);
 
        ok(out_session_name && !strcmp(session_name, out_session_name),
-                       "Session name returned by %s condition matches the expected name",
-                       type_name);
+          "Session name returned by %s condition matches the expected name",
+          type_name);
        return ret;
 }
 
-static
-int setup_rotation_trigger(const struct session *session,
-               struct lttng_notification_channel *notification_channel)
+static int setup_rotation_trigger(const struct session *session,
+                                 struct lttng_notification_channel *notification_channel)
 {
        int ret;
        struct lttng_condition *rotation_ongoing_condition = NULL;
@@ -78,8 +73,7 @@ int setup_rotation_trigger(const struct session *session,
        }
 
        /* Create rotation ongoing and completed conditions. */
-       rotation_ongoing_condition =
-                       lttng_condition_session_rotation_ongoing_create();
+       rotation_ongoing_condition = lttng_condition_session_rotation_ongoing_create();
        ok(rotation_ongoing_condition, "Create session rotation ongoing condition");
        if (!rotation_ongoing_condition) {
                ret = -1;
@@ -90,15 +84,14 @@ int setup_rotation_trigger(const struct session *session,
                goto end;
        }
        condition_status = lttng_condition_session_rotation_set_session_name(
-                       rotation_ongoing_condition, session->name);
+               rotation_ongoing_condition, session->name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                ret = -1;
                diag("Failed to set session name on session rotation ongoing condition");
                goto end;
        }
 
-       rotation_completed_condition =
-                       lttng_condition_session_rotation_completed_create();
+       rotation_completed_condition = lttng_condition_session_rotation_completed_create();
        ok(rotation_completed_condition, "Create session rotation completed condition");
        if (!rotation_completed_condition) {
                ret = -1;
@@ -110,42 +103,38 @@ int setup_rotation_trigger(const struct session *session,
                goto end;
        }
        condition_status = lttng_condition_session_rotation_set_session_name(
-                       rotation_completed_condition, session->name);
+               rotation_completed_condition, session->name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
        notification_channel_status = lttng_notification_channel_subscribe(
-                       notification_channel, rotation_ongoing_condition);
+               notification_channel, rotation_ongoing_condition);
        ok(notification_channel_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to session rotation ongoing notifications");
-       if (notification_channel_status !=
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
+          "Subscribe to session rotation ongoing notifications");
+       if (notification_channel_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
                ret = -1;
                goto end;
        }
        notification_channel_status = lttng_notification_channel_subscribe(
-                       notification_channel, rotation_completed_condition);
+               notification_channel, rotation_completed_condition);
        ok(notification_channel_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Subscribe to session rotation completed notifications");
-       if (notification_channel_status !=
-                       LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
+          "Subscribe to session rotation completed notifications");
+       if (notification_channel_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
        /* Create rotation ongoing and completed triggers. */
-       rotation_ongoing_trigger = lttng_trigger_create(
-                       rotation_ongoing_condition, notify);
+       rotation_ongoing_trigger = lttng_trigger_create(rotation_ongoing_condition, notify);
        ok(rotation_ongoing_trigger, "Create a rotation ongoing notification trigger");
        if (!rotation_ongoing_trigger) {
                ret = -1;
                goto end;
        }
 
-       rotation_completed_trigger = lttng_trigger_create(
-                       rotation_completed_condition, notify);
+       rotation_completed_trigger = lttng_trigger_create(rotation_completed_condition, notify);
        ok(rotation_completed_trigger, "Create a rotation completed notification trigger");
        if (!rotation_completed_trigger) {
                ret = -1;
@@ -153,18 +142,15 @@ int setup_rotation_trigger(const struct session *session,
        }
 
        /* Register rotation ongoing and completed triggers. */
-       ret_code = lttng_register_trigger_with_automatic_name(
-                       rotation_ongoing_trigger);
+       ret_code = lttng_register_trigger_with_automatic_name(rotation_ongoing_trigger);
        ok(ret_code == LTTNG_OK, "Registered session rotation ongoing trigger");
        if (ret_code != LTTNG_OK) {
                ret = -ret_code;
                goto end;
        }
 
-       ret_code = lttng_register_trigger_with_automatic_name(
-                       rotation_completed_trigger);
-       ok(ret_code == LTTNG_OK,
-                       "Registered session rotation completed trigger");
+       ret_code = lttng_register_trigger_with_automatic_name(rotation_completed_trigger);
+       ok(ret_code == LTTNG_OK, "Registered session rotation completed trigger");
        if (ret_code != LTTNG_OK) {
                ret = -ret_code;
                goto end;
@@ -179,12 +165,10 @@ end:
        return ret;
 }
 
-static
-int test_notification(
-               struct lttng_notification_channel *notification_channel,
-               const struct session *session,
-               const char *expected_notification_type_name,
-               enum lttng_condition_type expected_condition_type)
+static int test_notification(struct lttng_notification_channel *notification_channel,
+                            const struct session *session,
+                            const char *expected_notification_type_name,
+                            enum lttng_condition_type expected_condition_type)
 {
        int ret = 0;
        bool notification_pending;
@@ -202,28 +186,28 @@ int test_notification(
        const char *chunk_path = NULL;
 
        notification_channel_status = lttng_notification_channel_has_pending_notification(
-                       notification_channel, &notification_pending);
+               notification_channel, &notification_pending);
        ok(notification_channel_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK,
-                       "Check for %s notification pending on notification channel",
-                       expected_notification_type_name);
+          "Check for %s notification pending on notification channel",
+          expected_notification_type_name);
        if (notification_channel_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK) {
                ret = -1;
                goto end;
        }
 
        ok(notification_pending,
-                       "Session %s notification is pending on notification channel",
-                       expected_notification_type_name);
+          "Session %s notification is pending on notification channel",
+          expected_notification_type_name);
        if (!notification_pending) {
                ret = -1;
                goto end;
        }
 
        notification_channel_status = lttng_notification_channel_get_next_notification(
-                       notification_channel, &notification);
+               notification_channel, &notification);
        ok(notification_channel_status == LTTNG_NOTIFICATION_CHANNEL_STATUS_OK && notification,
-                       "Get %s notification from notification channel",
-                       expected_notification_type_name);
+          "Get %s notification from notification channel",
+          expected_notification_type_name);
        if (notification_channel_status != LTTNG_NOTIFICATION_CHANNEL_STATUS_OK || !notification) {
                ret = -1;
                goto end;
@@ -238,18 +222,18 @@ int test_notification(
 
        condition_type = lttng_condition_get_type(condition);
        ok(condition_type == expected_condition_type,
-                       "Notification condition obtained from notification channel is of type \"%s\"",
-                       expected_notification_type_name);
+          "Notification condition obtained from notification channel is of type \"%s\"",
+          expected_notification_type_name);
        if (condition_type != expected_condition_type) {
                ret = -1;
                goto end;
        }
 
-       condition_status = lttng_condition_session_rotation_get_session_name(
-                       condition, &session_name);
+       condition_status =
+               lttng_condition_session_rotation_get_session_name(condition, &session_name);
        ok(condition_status == LTTNG_CONDITION_STATUS_OK && session_name &&
-                       !strcmp(session_name, session->name),
-                       "Condition obtained from notification has the correct session name assigned");
+                  !strcmp(session_name, session->name),
+          "Condition obtained from notification has the correct session name assigned");
        if (condition_status != LTTNG_CONDITION_STATUS_OK || !session_name) {
                ret = -1;
                goto end;
@@ -263,18 +247,17 @@ int test_notification(
        }
        condition_type = lttng_evaluation_get_type(evaluation);
        ok(condition_type == expected_condition_type,
-                       "Condition evaluation obtained from notification channel is of type \"%s\"",
-                       expected_notification_type_name);
+          "Condition evaluation obtained from notification channel is of type \"%s\"",
+          expected_notification_type_name);
        if (condition_type != expected_condition_type) {
                ret = -1;
                goto end;
        }
 
-       evaluation_status = lttng_evaluation_session_rotation_get_id(evaluation,
-                       &rotation_id);
+       evaluation_status = lttng_evaluation_session_rotation_get_id(evaluation, &rotation_id);
        ok(evaluation_status == LTTNG_EVALUATION_STATUS_OK,
-                       "Get %s id from notification evaluation",
-                       expected_notification_type_name);
+          "Get %s id from notification evaluation",
+          expected_notification_type_name);
        if (evaluation_status != LTTNG_EVALUATION_STATUS_OK) {
                ret = -1;
                goto end;
@@ -288,51 +271,52 @@ int test_notification(
                goto end;
        }
 
-       evaluation_status = lttng_evaluation_session_rotation_completed_get_location(
-                       evaluation, &location);
+       evaluation_status =
+               lttng_evaluation_session_rotation_completed_get_location(evaluation, &location);
        ok(evaluation_status == LTTNG_EVALUATION_STATUS_OK && location,
-                       "Get session %s chunk location from evaluation",
-                       expected_notification_type_name);
+          "Get session %s chunk location from evaluation",
+          expected_notification_type_name);
        if (evaluation_status != LTTNG_EVALUATION_STATUS_OK || !location) {
                ret = -1;
                goto end;
        }
 
-       ok(lttng_trace_archive_location_get_type(location) == LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL,
-                       "Location returned from the session rotation completed notification is of type 'local'");
+       ok(lttng_trace_archive_location_get_type(location) ==
+                  LTTNG_TRACE_ARCHIVE_LOCATION_TYPE_LOCAL,
+          "Location returned from the session rotation completed notification is of type 'local'");
 
-       location_status = lttng_trace_archive_location_local_get_absolute_path(
-                       location, &chunk_path);
+       location_status =
+               lttng_trace_archive_location_local_get_absolute_path(location, &chunk_path);
        ok(location_status == LTTNG_TRACE_ARCHIVE_LOCATION_STATUS_OK && chunk_path,
-                       "Retrieved path from location returned by the session rotation completed notification");
+          "Retrieved path from location returned by the session rotation completed notification");
        diag("Chunk available at %s", chunk_path ? chunk_path : "NULL");
 
        ok(chunk_path && !strncmp(session->output_path, chunk_path, strlen(session->output_path)),
-                       "Returned path from location starts with the output path");
+          "Returned path from location starts with the output path");
 
 end:
        lttng_notification_destroy(notification);
        return ret;
 }
 
-static
-int test_rotation_ongoing_notification(
-               struct lttng_notification_channel *notification_channel,
-               struct session *session)
+static int
+test_rotation_ongoing_notification(struct lttng_notification_channel *notification_channel,
+                                  struct session *session)
 {
-       return test_notification(notification_channel, session,
-                       "rotation ongoing",
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
+       return test_notification(notification_channel,
+                                session,
+                                "rotation ongoing",
+                                LTTNG_CONDITION_TYPE_SESSION_ROTATION_ONGOING);
 }
 
-static
-int test_rotation_completed_notification(
-               struct lttng_notification_channel *notification_channel,
-               struct session *session)
+static int
+test_rotation_completed_notification(struct lttng_notification_channel *notification_channel,
+                                    struct session *session)
 {
-       return test_notification(notification_channel, session,
-                       "rotation completed",
-                       LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
+       return test_notification(notification_channel,
+                                session,
+                                "rotation completed",
+                                LTTNG_CONDITION_TYPE_SESSION_ROTATION_COMPLETED);
 }
 
 int main(int argc, const char *argv[])
@@ -342,8 +326,7 @@ int main(int argc, const char *argv[])
        struct lttng_notification_channel *notification_channel = NULL;
        struct lttng_rotation_handle *rotation_handle = NULL;
        enum lttng_rotation_status rotation_status;
-       enum lttng_rotation_state rotation_state =
-                       LTTNG_ROTATION_STATE_NO_ROTATION;
+       enum lttng_rotation_state rotation_state = LTTNG_ROTATION_STATE_NO_ROTATION;
 
        if (argc != 3) {
                puts("Usage: rotation SESSION_NAME SESSION_OUTPUT_PATH");
@@ -356,8 +339,8 @@ int main(int argc, const char *argv[])
 
        plan_tests(TEST_COUNT);
 
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
        if (!notification_channel) {
                diag("Failed to create notification channel");
                ret = -1;
@@ -371,20 +354,19 @@ int main(int argc, const char *argv[])
 
        /* Start rotation and wait for its completion. */
        ret = lttng_rotate_session(session.name, NULL, &rotation_handle);
-       ok(ret >= 0 && rotation_handle, "Start rotation of session \"%s\"",
-                       session.name);
+       ok(ret >= 0 && rotation_handle, "Start rotation of session \"%s\"", session.name);
        if (ret < 0 || !rotation_handle) {
                goto error;
        }
 
        do {
-               rotation_status = lttng_rotation_handle_get_state(
-                               rotation_handle, &rotation_state);
+               rotation_status = lttng_rotation_handle_get_state(rotation_handle, &rotation_state);
        } while (rotation_state == LTTNG_ROTATION_STATE_ONGOING &&
-                       rotation_status == LTTNG_ROTATION_STATUS_OK);
+                rotation_status == LTTNG_ROTATION_STATUS_OK);
        ok(rotation_status == LTTNG_ROTATION_STATUS_OK &&
-                       rotation_state == LTTNG_ROTATION_STATE_COMPLETED,
-                       "Complete rotation of session \"%s\"", session.name);
+                  rotation_state == LTTNG_ROTATION_STATE_COMPLETED,
+          "Complete rotation of session \"%s\"",
+          session.name);
 
        /*
         * After a rotation has completed, we can expect two notifications to
@@ -392,14 +374,12 @@ int main(int argc, const char *argv[])
         *  - Session rotation ongoing
         *  - Session rotation completed
         */
-       ret = test_rotation_ongoing_notification(notification_channel,
-                       &session);
+       ret = test_rotation_ongoing_notification(notification_channel, &session);
        if (ret) {
                goto error;
        }
 
-       ret = test_rotation_completed_notification(notification_channel,
-                       &session);
+       ret = test_rotation_completed_notification(notification_channel, &session);
        if (ret) {
                goto error;
        }
index f0517ed14b911f9e62fc2bbf2ccd2d2e0036f76e..44e6b6e7b7a2ffee9d721aeaaa1e6ac4124b985a 100644 (file)
@@ -8,34 +8,35 @@
 
 #include <common/compat/getenv.hpp>
 #include <common/consumer/consumer.hpp>
-#include <common/pipe.hpp>
 #include <common/error.hpp>
-#include <unistd.h>
-#include <stdbool.h>
+#include <common/pipe.hpp>
+
 #include <lttng/constant.h>
 #include <lttng/lttng-export.h>
-#include <fcntl.h>
+
 #include <dlfcn.h>
+#include <fcntl.h>
+#include <stdbool.h>
 #include <stdio.h>
+#include <unistd.h>
 
 static char *pause_pipe_path;
 static struct lttng_pipe *pause_pipe;
-static int *notifier_notif_consumption_state;;
+static int *notifier_notif_consumption_state;
+;
 
 int lttng_opt_verbose;
 int lttng_opt_mi;
 int lttng_opt_quiet;
 
-static
-void __attribute__((destructor)) pause_pipe_fini(void)
+static void __attribute__((destructor)) pause_pipe_fini()
 {
        int ret;
 
        if (pause_pipe_path) {
                ret = unlink(pause_pipe_path);
                if (ret) {
-                       PERROR("Failed to unlink pause pipe: path = %s",
-                                       pause_pipe_path);
+                       PERROR("Failed to unlink pause pipe: path = %s", pause_pipe_path);
                }
        }
 
@@ -49,14 +50,13 @@ int __testpoint_sessiond_thread_notification(void)
        int ret = 0;
        const char *pause_pipe_path_prefix;
 
-       pause_pipe_path_prefix = lttng_secure_getenv(
-                       "NOTIFIER_PAUSE_PIPE_PATH");
+       pause_pipe_path_prefix = lttng_secure_getenv("NOTIFIER_PAUSE_PIPE_PATH");
        if (!pause_pipe_path_prefix) {
                ret = -1;
                goto end;
        }
 
-       notifier_notif_consumption_state = (int *) dlsym(NULL, "notifier_consumption_paused");
+       notifier_notif_consumption_state = (int *) dlsym(nullptr, "notifier_consumption_paused");
        LTTNG_ASSERT(notifier_notif_consumption_state);
 
        ret = asprintf(&pause_pipe_path, "%s", pause_pipe_path_prefix);
@@ -66,8 +66,8 @@ int __testpoint_sessiond_thread_notification(void)
        }
 
        DBG("Creating pause pipe at %s", pause_pipe_path);
-       pause_pipe = lttng_pipe_named_open(pause_pipe_path,
-                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, O_NONBLOCK);
+       pause_pipe = lttng_pipe_named_open(
+               pause_pipe_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, O_NONBLOCK);
        if (!pause_pipe) {
                ERR("Failed to create pause pipe at %s", pause_pipe_path);
                ret = -1;
@@ -105,7 +105,7 @@ int __testpoint_sessiond_handle_notifier_event_pipe(void)
        if (value_read) {
                *notifier_notif_consumption_state = !!value;
                DBG("Message received on pause pipe: %s data consumption",
-                               *notifier_notif_consumption_state ? "paused" : "resumed");
+                   *notifier_notif_consumption_state ? "paused" : "resumed");
        }
 end:
        return ret;
index 76e69a77e876f5fd406e486bdb926c9e0ebfd7b5..a89355a448ac9e92b3eeac99726ddf4afc6faf2f 100755 (executable)
@@ -7,13 +7,16 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TEST_TMPDIR=$(mktemp --tmpdir -d tmp.test_notif_kernel_buffer_usage_dir.XXXXXX)
+TEST_TMPDIR=$(mktemp -d -t tmp.test_notif_kernel_buffer_usage_dir.XXXXXX)
+
+# Set TMPDIR for further call to mktemp
+export TMPDIR="$TEST_TMPDIR"
 
 #This is needed since the testpoint create a pipe with the consumerd type suffixed
 TESTPOINT_BASE_PATH=$(readlink -f "$TEST_TMPDIR/lttng.t_p_n")
-TESTPOINT_PIPE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "lttng.t_p_n.XXXXXX")
+TESTPOINT_PIPE_PATH=$(mktemp -u -t "lttng.t_p_n.XXXXXX")
 TESTPOINT=$(readlink -f "${CURDIR}/.libs/libpause_consumer.so")
-TESTAPP_STATE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "application_state.XXXXXXXXXX")
 
 
 SESSION_NAME="my_session"
@@ -33,7 +36,7 @@ function test_buffer_usage_notification
        local page_size
        local consumerd_pipe=()
 
-       trace_path=$(mktemp -d --tmpdir="$TEST_TMPDIR" "tmp.${FUNCNAME[0]}_trace_path.XXXXXXX")
+       trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXXX")
        page_size=$(getconf PAGE_SIZE)
 
        create_lttng_session_notap $SESSION_NAME "$trace_path"
@@ -60,29 +63,27 @@ function test_buffer_usage_notification
        wait $APP_PID 2> /dev/null
 }
 
-if [ "$(id -u)" == "0" ]; then
-
-       validate_lttng_modules_present
-
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       rm -rf "$TEST_TMPDIR"
+       exit 0
+}
 
-       modprobe lttng-test
+validate_lttng_modules_present
 
-       # Used on sessiond launch.
-       LTTNG_SESSIOND_ENV_VARS="LTTNG_TESTPOINT_ENABLE=1 \
-               CONSUMER_PAUSE_PIPE_PATH=${TESTPOINT_PIPE_PATH} \
-               LD_PRELOAD=${TESTPOINT}"
-       start_lttng_sessiond_notap
+modprobe lttng-test
 
-       test_buffer_usage_notification
+# Used on sessiond launch.
+LTTNG_SESSIOND_ENV_VARS="LTTNG_TESTPOINT_ENABLE=1 \
+       CONSUMER_PAUSE_PIPE_PATH=${TESTPOINT_PIPE_PATH} \
+       LD_PRELOAD=${TESTPOINT}"
+start_lttng_sessiond_notap
 
-       stop_lttng_sessiond_notap
-       rmmod lttng-test
+test_buffer_usage_notification
 
-       rm -rf "${consumerd_pipe[@]}" 2> /dev/null
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
+stop_lttng_sessiond_notap
+rmmod lttng-test
 
+rm -rf "${consumerd_pipe[@]}" 2> /dev/null
 rm -rf "$TEST_TMPDIR"
index 88f123d3d6a662eb434cf20f463294090d12c107..b65310d8801a6a50c0261db12ad330ef7f6620a4 100755 (executable)
@@ -8,7 +8,7 @@ CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_kernel_capture_application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_kernel_capture_application_state.XXXXXXXXXX")
 
 NUM_TESTS=104
 
@@ -31,22 +31,21 @@ function test_basic_error_path
 }
 
 
-if [ "$(id -u)" == "0" ]; then
-       validate_lttng_modules_present
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       exit 0
+}
 
-       modprobe lttng-test
+validate_lttng_modules_present
 
-       start_lttng_sessiond_notap
+modprobe lttng-test
 
-       test_basic_error_path
+start_lttng_sessiond_notap
 
-       stop_lttng_sessiond_notap
-       rmmod lttng-test
+test_basic_error_path
 
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
+stop_lttng_sessiond_notap
+rmmod lttng-test
 
 rm -f "$TESTAPP_STATE_PATH"
index 80fe6e5b51d62ab0cdadf6e6e914afb59a21735f..5f53f5b1b8399987a1591ba57484d1dda53cea5b 100755 (executable)
@@ -8,7 +8,7 @@ CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_kernel_error_application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_kernel_error_application_state.XXXXXXXXXX")
 
 NUM_TESTS=44
 
@@ -30,23 +30,22 @@ function test_basic_error_path
        wait $APP_PID 2> /dev/null
 }
 
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       exit 0
+}
 
-if [ "$(id -u)" == "0" ]; then
-       validate_lttng_modules_present
+validate_lttng_modules_present
 
-       modprobe lttng-test
+modprobe lttng-test
 
-       start_lttng_sessiond_notap
+start_lttng_sessiond_notap
 
-       test_basic_error_path
+test_basic_error_path
 
-       stop_lttng_sessiond_notap
-       rmmod lttng-test
+stop_lttng_sessiond_notap
+rmmod lttng-test
 
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
 
 rm -f "$TESTAPP_STATE_PATH"
index 90545a5417a704d5954c4bb9085079c89a16938e..9a8d323a1371cabe3847047d9d4791489f7cd64b 100755 (executable)
@@ -7,7 +7,7 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_kernel_instrumentation_application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_kernel_instrumentation_application_state.XXXXXXXXXX")
 
 NUM_TESTS=13
 
@@ -28,22 +28,21 @@ function test_kernel_instrumentation_notification
        wait $APP_PID 2> /dev/null
 }
 
-if [ "$(id -u)" == "0" ]; then
-       validate_lttng_modules_present
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       exit 0
+}
 
-       modprobe lttng-test
+validate_lttng_modules_present
 
-       start_lttng_sessiond_notap
+modprobe lttng-test
 
-       test_kernel_instrumentation_notification
+start_lttng_sessiond_notap
 
-       stop_lttng_sessiond_notap
-       rmmod lttng-test
+test_kernel_instrumentation_notification
 
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
+stop_lttng_sessiond_notap
+rmmod lttng-test
 
 rm -f "$TESTAPP_STATE_PATH"
index d273cb55d5d6a8036bc36aabc86301c576047db1..c9a40d077a5967844cf4d9374f13c2b502da578b 100755 (executable)
@@ -7,7 +7,7 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_kernel_syscall_application_state.XXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_kernel_syscall_application_state.XXXXXX")
 
 NUM_TESTS=25
 
@@ -31,19 +31,18 @@ function test_kernel_syscall_notification
        wait $APP_PID 2> /dev/null
 }
 
-if [ "$(id -u)" == "0" ]; then
-       validate_lttng_modules_present
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       exit 0
+}
 
-       start_lttng_sessiond_notap
+validate_lttng_modules_present
 
-       test_kernel_syscall_notification
+start_lttng_sessiond_notap
 
-       stop_lttng_sessiond_notap
+test_kernel_syscall_notification
 
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
+stop_lttng_sessiond_notap
 
 rm -f "$TESTAPP_STATE_PATH"
index 8ef8d708d282c10260773c3a05f3a0179c8aff68..38f5a5f41426e6f887ac963939a77f00ffc37321 100755 (executable)
@@ -7,7 +7,7 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_kernel_uprobe_application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_kernel_uprobe_application_state.XXXXXXXXXX")
 
 NUM_TESTS=13
 
@@ -29,18 +29,18 @@ function test_kernel_userspace_probe_notification
        wait $APP_PID 2> /dev/null
 }
 
-if [ "$(id -u)" == "0" ]; then
-       validate_lttng_modules_present
+check_skip_kernel_test &&
+{
+       plan_skip_all "Skipping all tests."
+       exit 0
+}
+
+validate_lttng_modules_present
 
-       start_lttng_sessiond_notap
+start_lttng_sessiond_notap
 
-       test_kernel_userspace_probe_notification
+test_kernel_userspace_probe_notification
 
-       stop_lttng_sessiond_notap
-else
-       # Kernel tests are skipped.
-       plan_tests $NUM_TESTS
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $NUM_TESTS
-fi
+stop_lttng_sessiond_notap
 
 rm -f "$TESTAPP_STATE_PATH"
index d8b6392259e96fe631496876949dc0db1ee94c60..a7156c4fea1dd31a95694476d5a86eac67fb046d 100755 (executable)
@@ -14,7 +14,7 @@ TESTPOINT=$(readlink -f ${CURDIR}/.libs/libpause_consumer.so)
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
-TESTAPP_STATE_FILE="$(mktemp --tmpdir -u tmp.test_notification_multi_app_state_file.XXXXXX)"
+TESTAPP_STATE_FILE="$(mktemp -u -t tmp.test_notification_multi_app_state_file.XXXXXX)"
 
 NR_ITER=1000
 NR_USEC_WAIT=5
@@ -35,7 +35,7 @@ source $TESTDIR/utils/utils.sh
 source $CURDIR/util_event_generator.sh
 
 consumerd_pipe=()
-file_sync_after_first_event=$(mktemp --tmpdir -u tmp.test_notification_multi_app_sync_after_first.XXXXXX)
+file_sync_after_first_event=$(mktemp -u -t tmp.test_notification_multi_app_sync_after_first.XXXXXX)
 
 # MUST set TESTDIR before calling those functions
 plan_tests $NUM_TESTS
@@ -135,10 +135,10 @@ function test_multi_app ()
        local app_pids=()
        local low_output_file_pattern="low_app_output_file_"
        local high_output_file_pattern="high_app_output_file_"
-       local output_dir=$(mktemp --tmpdir -d "tmp.test_${FUNCNAME[0]}_output_dir.XXXXXX")
+       local output_dir=$(mktemp -d -t "tmp.test_${FUNCNAME[0]}_output_dir.XXXXXX")
 
        local testpoint_base_path=$(readlink -f "$output_dir/lttng.t_p_n_multi_app")
-       local testpoint_pipe_path=$(mktemp --tmpdir="$output_dir" -u "lttng.t_p_n_multi_app.XXXXXX")
+       local testpoint_pipe_path=$(TMPDIR="$output_dir" mktemp -u -t "lttng.t_p_n_multi_app.XXXXXX")
 
        local nr_notification_expected=5
        local nr_client_app=50
@@ -325,9 +325,9 @@ function test_on_register_evaluation ()
        local app_pids=()
        local high_output_file_pattern="high_app_output_file_on_register_evaluation"
 
-       local output_dir=$(mktemp --tmpdir -d "tmp.test_${FUNCNAME[0]}_output_dir.XXXXXX")
+       local output_dir=$(mktemp -d -t "tmp.test_${FUNCNAME[0]}_output_dir.XXXXXX")
        local testpoint_base_path=$(readlink -f "$output_dir/lttng.t_p_n_register_evaluation")
-       local testpoint_pipe_path=$(mktemp --tmpdir="$output_dir" -u "lttng.t_p_n_register_evaluation.XXXXXX")
+       local testpoint_pipe_path=$(TMPDIR="$output_dir" mktemp -u -t "lttng.t_p_n_register_evaluation.XXXXXX")
        local domain_string=""
        local event_name=""
 
@@ -411,26 +411,22 @@ function test_on_register_evaluation ()
        rm -rf "$output_dir"
 }
 
-
 TESTS=(
        test_multi_app_ust
        test_on_register_evaluation_ust
 )
 
-if [ "$(id -u)" == "0" ]; then
+check_skip_kernel_test "$NUM_TEST_KERNEL" "Skipping kernel multi-app notification tests." || {
        validate_lttng_modules_present
        TESTS+=(
-       test_multi_app_kernel
-       test_on_register_evaluation_kernel
-)
-else
-        skip 0 "Root access is needed. Skipping all kernel multi-app notification tests." $NUM_TEST_KERNEL
-fi
-
+               test_multi_app_kernel
+               test_on_register_evaluation_kernel
+       )
+}
 
 for fct_test in ${TESTS[@]};
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_notification_multi_app_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_notification_multi_app_trace_path.XXXXXX)
 
        ${fct_test}
        if [ $? -ne 0 ]; then
index c9235393ef27cfba645d62eb0f5be132a432ba60..25ef370fad0641bafee60a64b56fd3f33c627253 100755 (executable)
@@ -7,14 +7,17 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TEST_TMPDIR=$(mktemp --tmpdir -d tmp.test_notifier_discarded_count.XXXXXX)
+TEST_TMPDIR=$(mktemp -d -t tmp.test_notifier_discarded_count.XXXXXX)
+
+# Set TMPDIR for further call to mktemp
+export TMPDIR="$TEST_TMPDIR"
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 
 TESTPOINT_BASE_PATH=$(readlink -f "$TEST_TMPDIR/lttng.t_p_n")
-TESTPOINT_PIPE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "lttng.t_p_n.XXXXXX")
+TESTPOINT_PIPE_PATH=$(mktemp -u -t "lttng.t_p_n.XXXXXX")
 TESTPOINT=$(readlink -f "${CURDIR}/.libs/libpause_sessiond.so")
 
 SH_TAP=1
@@ -37,7 +40,7 @@ plan_tests $NUM_TESTS
 function trigger_get_discarded_notif_number()
 {
        local trigger_name="$1"
-       local list_triggers_stdout=$(mktemp --tmpdir="$TEST_TMPDIR" "list_triggers_stdout.XXXXXX")
+       local list_triggers_stdout=$(mktemp -t "list_triggers_stdout.XXXXXX")
 
        "$FULL_LTTNG_BIN" list-triggers > "$list_triggers_stdout"
 
@@ -60,7 +63,7 @@ function test_kernel_notifier_discarded_count
 {
        local sessiond_pipe=()
        local trigger_name="my_trigger"
-       local list_triggers_stdout=$(mktemp --tmpdir="$TEST_TMPDIR" "list_triggers_stdout.XXXXXX")
+       local list_triggers_stdout=$(mktemp -t "list_triggers_stdout.XXXXXX")
 
        # Used on sessiond launch.
        LTTNG_SESSIOND_ENV_VARS="LTTNG_TESTPOINT_ENABLE=1 \
@@ -244,7 +247,7 @@ function test_ust_notifier_discarded_count_multi_uid
        local sessiond_pipe=()
        local root_trigger_name="root_trigger"
        local user_trigger_name="user_trigger"
-       local list_triggers_stdout=$(mktemp --tmpdir="$TEST_TMPDIR" "list_triggers_stdout.XXXXXX")
+       local list_triggers_stdout=$(mktemp -t "list_triggers_stdout.XXXXXX")
        local NR_USEC_WAIT=0
        local PIPE_SIZE
        local NR_ITER
@@ -324,7 +327,7 @@ function test_ust_notifier_discarded_regardless_trigger_owner
        local sessiond_pipe=()
        local root_trigger_name="root_trigger"
        local user_trigger_name="user_trigger"
-       local list_triggers_stdout=$(mktemp --tmpdir="$TEST_TMPDIR" "list_triggers_stdout.XXXXXX")
+       local list_triggers_stdout=$(mktemp -t "list_triggers_stdout.XXXXXX")
        local NR_USEC_WAIT=0
        local PIPE_SIZE
        local NR_ITER
@@ -391,7 +394,8 @@ function test_ust_notifier_discarded_regardless_trigger_owner
 test_ust_notifier_discarded_count
 test_ust_notifier_discarded_count_max_bucket
 
-if [ "$(id -u)" == "0" ]; then
+check_skip_kernel_test "$KERNEL_NUM_TESTS" "Skipping kernel notification tests." ||
+{
 
        validate_lttng_modules_present
 
@@ -413,9 +417,7 @@ if [ "$(id -u)" == "0" ]; then
        modprobe --remove lttng-test
 
        rm -rf "${sessiond_pipe[@]}" 2> /dev/null
-else
-       # Kernel tests are skipped.
-       skip 0 "Root access is needed. Skipping all kernel notification tests." $KERNEL_NUM_TESTS
-fi
+
+}
 
 rm -rf "$TEST_TMPDIR"
index 4a4c14f3a5f4730aded9385f1e54c7f0ccac50ef..836eceb2e838eba6228ec3a4f48a6373cfb73ed8 100755 (executable)
@@ -7,12 +7,15 @@
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../../
 
-TEST_TMPDIR=$(mktemp --tmpdir -d tmp.test_notif_ust_buffer_usage_dir.XXXXXX)
+TEST_TMPDIR=$(mktemp -d -t tmp.test_notif_ust_buffer_usage_dir.XXXXXX)
+
+# Set TMPDIR for further call to mktemp
+export TMPDIR="$TEST_TMPDIR"
 
 set -x
 #This is needed since the testpoint create a pipe with the consumerd type suffixed
 TESTPOINT_BASE_PATH=$(readlink -f "$TEST_TMPDIR/lttng.t_p_n")
-TESTPOINT_PIPE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "lttng.t_p_n.XXXXXX")
+TESTPOINT_PIPE_PATH=$(mktemp -u -t "lttng.t_p_n.XXXXXX")
 TESTPOINT=$(readlink -f "${CURDIR}/.libs/libpause_consumer.so")
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
@@ -20,12 +23,12 @@ TESTAPP_PATH="$TESTDIR/utils/testapp"
 GEN_UST_EVENTS_TESTAPP_NAME="gen-ust-events"
 GEN_UST_EVENTS_TESTAPP_BIN="$TESTAPP_PATH/$GEN_UST_EVENTS_TESTAPP_NAME/$GEN_UST_EVENTS_TESTAPP_NAME"
 
-TESTAPP_STATE_PATH=$(mktemp -u --tmpdir="$TEST_TMPDIR" "application_state.XXXXXXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "application_state.XXXXXXXXXX")
 
 SESSION_NAME="my_session"
 CHANNEL_NAME="my_channel"
 
-TRACE_PATH=$(mktemp -d --tmpdir="$TEST_TMPDIR" "trace_path.XXXXXX")
+TRACE_PATH=$(mktemp -d -t "trace_path.XXXXXX")
 PAGE_SIZE=$(getconf PAGE_SIZE)
 set +x
 
index 3546d32ec77f6949fefcccca9e5f8cd9bf39888f..f16dbb64723ff701c33136cb9fa18ca5355948af 100755 (executable)
@@ -12,7 +12,7 @@ TESTAPP_PATH="$TESTDIR/utils/testapp"
 GEN_UST_EVENTS_TESTAPP_NAME="gen-ust-events"
 GEN_UST_EVENTS_TESTAPP_BIN="$TESTAPP_PATH/$GEN_UST_EVENTS_TESTAPP_NAME/$GEN_UST_EVENTS_TESTAPP_NAME"
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_ust_capture_application_state.XXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_ust_capture_application_state.XXXXXX")
 
 # shellcheck source=../../../utils/utils.sh
 source "$TESTDIR/utils/utils.sh"
index dead3105996424d33b165b11cffb5554bd236ec6..e3b5e9859bfcf837588e2000471f7b74a02a7e33 100755 (executable)
@@ -13,7 +13,7 @@ TESTAPP_PATH="$TESTDIR/utils/testapp"
 GEN_UST_EVENTS_TESTAPP_NAME="gen-ust-events"
 GEN_UST_EVENTS_TESTAPP_BIN="$TESTAPP_PATH/$GEN_UST_EVENTS_TESTAPP_NAME/$GEN_UST_EVENTS_TESTAPP_NAME"
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_ust_error_application_state.XXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_ust_error_application_state.XXXXXX")
 
 # shellcheck source=../../../utils/utils.sh
 source "$TESTDIR/utils/utils.sh"
index c15ecff08a626c5c965487fcf0a2c20045e41ff8..b8dbcc859bb686c58db774a886820267f683e0ae 100755 (executable)
@@ -12,7 +12,7 @@ TESTAPP_PATH="$TESTDIR/utils/testapp"
 GEN_UST_NEVENTS_TESTAPP_NAME="gen-ust-nevents"
 GEN_UST_NEVENTS_TESTAPP_BIN="$TESTAPP_PATH/$GEN_UST_NEVENTS_TESTAPP_NAME/$GEN_UST_NEVENTS_TESTAPP_NAME"
 
-TESTAPP_STATE_PATH=$(mktemp --tmpdir -u "tmp.test_notif_event_rule_exclusion_ust_application_state.XXXXXX")
+TESTAPP_STATE_PATH=$(mktemp -u -t "tmp.test_notif_event_rule_exclusion_ust_application_state.XXXXXX")
 
 # shellcheck source=../../../utils/utils.sh
 source "$TESTDIR/utils/utils.sh"
index 90f7887863de271dbac5f073d78f7bd66feef793..5d6db8f557cde6484685fba5d5f27552d01b1f22 100755 (executable)
@@ -12,13 +12,13 @@ TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 
 SESSION_NAME="my_session"
-SESSION_OUTPUT_PATH=$(mktemp --tmpdir -d tmp.test_notif_rotation_trace_path.XXXXXX)
+SESSION_OUTPUT_PATH=$(mktemp -d -t tmp.test_notif_rotation_trace_path.XXXXXX)
 EVENT_NAME="tp:tptest"
 
 PAGE_SIZE=$(getconf PAGE_SIZE)
 SUBBUF_SIZE=$(expr $PAGE_SIZE \* 8)
 
-FILE_SYNC_AFTER_FIRST_EVENT=$(mktemp --tmpdir -u tmp.test_rotation_sync_after_first.XXXXXX)
+FILE_SYNC_AFTER_FIRST_EVENT=$(mktemp -u -t tmp.test_rotation_sync_after_first.XXXXXX)
 
 NR_ITER=-1
 NR_USEC_WAIT=5
index 5eef0deea82f0a775e88f04d7144816d4e6bd3b1..bac089086444c7453301f65a8337c131c6f4067c 100644 (file)
@@ -14,6 +14,9 @@ SYSCALL_TESTAPP_BIN=${SYSCALL_TESTAPP_BIN:-"$TESTAPP_PATH/$SYSCALL_TESTAPP_NAME/
 USERSPACE_PROBE_ELF_TESTAPP_NAME=${USERSPACE_PROBE_ELF_TESTAPP_NAME:-"userspace-probe-elf-binary"}
 USERSPACE_PROBE_ELF_TESTAPP_BIN=${USERSPACE_PROBE_ELF_TESTAPP_BIN:-"$TESTAPP_PATH/$USERSPACE_PROBE_ELF_TESTAPP_NAME/.libs/$USERSPACE_PROBE_ELF_TESTAPP_NAME"}
 
+# shellcheck source=../utils/utils.sh
+source "$GENERATOR_TESTDIR/utils/utils.sh"
+
 function generate_filter_events
 {
        local nr=$1
@@ -25,7 +28,7 @@ function generate_syscalls
        local nr=$1
        shift
 
-       for i in $(seq 1 "$nr"); do
+       for _ in $(seq 1 "$nr"); do
                # Pass /dev/null so to generate the syscall right away.
                $SYSCALL_TESTAPP_BIN /dev/null "$@"
        done
@@ -36,8 +39,20 @@ function userspace_probe_testapp
        local nr=$1
        shift 
 
-       for i in $(seq 1 "$nr"); do
-               $USERSPACE_PROBE_ELF_TESTAPP_BIN "$@"
+       for _ in $(seq 1 "$nr"); do
+               # This userspace probe test has to instrument the actual elf
+               # binary and not the generated libtool wrapper. However, we
+               # can't invoke the wrapper either since it will re-link the test
+               # application binary on its first invocation, resulting in a new
+               # binary with an 'lt-*' prefix under the .libs folder. The
+               # relinking stage adds the .libs folder to the 'lt-*' binary's
+               # rpath.
+               #
+               # To ensure the binary (inode) that instrumented is the same as
+               # what is running, set LD_LIBRARY_PATH to find the .libs folder
+               # that contains the libfoo.so library and invoke the binary
+               # directly.
+               LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TESTDIR/utils/testapp/userspace-probe-elf-binary/.libs" $USERSPACE_PROBE_ELF_TESTAPP_BIN "$@"
        done
 }
 
@@ -78,7 +93,7 @@ function ust_event_generator_run_once_per_transition
                        run=true
                        sleep 0.5
                elif [ "$run" = true ]; then
-                       taskset -c 0 "$test_app" -i "$nr_iter" -w "$nr_usec_wait" "$@"> /dev/null 2>&1
+                       taskset -c "$(get_any_available_cpu)" "$test_app" -i "$nr_iter" -w "$nr_usec_wait" "$@"> /dev/null 2>&1
                        run=false;
                        if [[ -f $state_file ]]; then
                                rm -rf "$state_file" 2> /dev/null
@@ -115,7 +130,7 @@ function ust_event_generator
                        # Reset the "run" state
                        sleep 0.5
                else
-                       taskset -c 0 "$test_app" -i $nr_iter -w $nr_usec_wait "$@" > /dev/null 2>&1
+                       taskset -c "$(get_any_available_cpu)" "$test_app" -i $nr_iter -w $nr_usec_wait "$@" > /dev/null 2>&1
                        if [[ -f $state_file ]]; then
                                rm -rf "$state_file" 2> /dev/null
                        fi
index 49eea32a7dbe73114f0d733efc895d5d293a7616..1b5ce2a0b2239545fd58b2a367baef9141cf4a43 100755 (executable)
@@ -11,7 +11,7 @@ TESTDIR=$CURDIR/../../..
 EVENT_NAME="lttng_test_filter_event"
 SESSION_NAME=""
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_regen_metadata_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_regen_metadata_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=32
 
@@ -99,13 +99,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel streaming tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
index 224a379957dab8f4ce87c56f41f97851cdad26ce..a482213236073c4c9a0ef310d402a1afd29afbdd 100755 (executable)
@@ -16,7 +16,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="stream"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_regen_metadata_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_regen_metadata_ust_trace_path.XXXXXX)
 
 NUM_TESTS=47
 
@@ -39,8 +39,8 @@ function enable_channel_per_pid()
 
 function test_ust_streaming ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
        local metadata_path
 
        diag "Test UST streaming with metadata regeneration"
@@ -83,8 +83,8 @@ function test_ust_streaming ()
 
 function test_ust_local ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
        local metadata_path
 
        diag "Test UST local with metadata regeneration"
@@ -127,8 +127,8 @@ function test_ust_local ()
 
 function test_ust_pid ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test UST per-pid with metadata regeneration (expect failure)"
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -161,8 +161,8 @@ function test_ust_pid ()
 
 function test_ust_live ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test UST live with metadata regeneration (expect failure)"
        create_lttng_session_uri $SESSION_NAME net://localhost --live
index 8a261355dedec3636b69e6d781bdc329a075df5a..758b95d071efceea6974fa291aacd2fba6c95408 100755 (executable)
@@ -12,7 +12,7 @@ EVENT_NAME="lttng_test_filter_event"
 SESSION_NAME=""
 EVENT_NAME="lttng_statedump_start,lttng_statedump_end"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_regenerate_statedump_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_regenerate_statedump_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=11
 
@@ -39,13 +39,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel streaming tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
        start_lttng_sessiond
index 29e1d1b9d2c1c84100dd141321448311336688d7..1a872c99596d2f5bb653a78fe107f34ca379fd16 100755 (executable)
@@ -16,7 +16,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="stream"
 EVENT_NAME="lttng_ust_statedump:start,lttng_ust_statedump:end"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_regenerate_statedump_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_regenerate_statedump_ust_trace_path.XXXXXX)
 
 NUM_TESTS=11
 
@@ -28,8 +28,8 @@ fi
 
 function test_ust_local ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_sync_after_first.XXXXXX)
-       local file_sync_before_last=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_sync_before_last.XXXXXX)
+       local file_sync_after_first=$(mktemp -u -t tmp.test_${FUNCNAME[0]}_sync_after_first.XXXXXX)
+       local file_sync_before_last=$(mktemp -u -t tmp.test_${FUNCNAME[0]}_sync_before_last.XXXXXX)
 
        diag "Test UST local with statedump regeneration"
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
index 592dbd90d0e59d35ba06c90ea0ba74c3e98a6714..8e2dca9cccef08696623a5bfcd1c5314d2cdefdf 100755 (executable)
@@ -19,7 +19,7 @@ CHANNEL_NAME="my_channel"
 XPATH_CMD_OUTPUT="//lttng:command/lttng:output"
 XPATH_SESSION="$XPATH_CMD_OUTPUT/lttng:sessions/lttng:session"
 
-NUM_TESTS=688
+NUM_TESTS=254
 
 source "$TESTDIR/utils/utils.sh"
 
@@ -34,7 +34,7 @@ function get_auto_session_name ()
        local lttng_bin=$LTTNG_BIN
 
        LTTNG_BIN="${lttng_bin} --mi xml"
-       OUTPUT_DEST=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output.XXXXXX")
+       OUTPUT_DEST=$(mktemp -t "tmp.${FUNCNAME[0]}_output.XXXXXX")
 
        list_lttng_ok
        $MI_VALIDATE "$OUTPUT_DEST"
@@ -54,18 +54,10 @@ function test_ust_uid_live ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer live [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer live [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost --live
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -74,7 +66,7 @@ function test_ust_uid_live ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -93,18 +85,10 @@ function test_ust_pid_live ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST pid buffer live [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST pid buffer live [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost --live
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-pid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -113,7 +97,7 @@ function test_ust_pid_live ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -133,18 +117,10 @@ function test_ust_uid_live_custom_output ()
        local session_name="$1"
        local grouping="$2"
        local custom_output="my_live_custom_output"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer live, custom output [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer live, custom output [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost/$custom_output --live
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -153,7 +129,7 @@ function test_ust_uid_live_custom_output ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/$custom_output"
@@ -172,18 +148,10 @@ function test_ust_uid_streaming ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
-
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
 
-       diag "Test UST uid buffer streaming [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer streaming [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -192,7 +160,7 @@ function test_ust_uid_streaming ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -211,18 +179,9 @@ function test_ust_pid_streaming ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
-
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST pid buffer streaming [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST pid buffer streaming [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-pid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -231,7 +190,7 @@ function test_ust_pid_streaming ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -251,18 +210,10 @@ function test_ust_uid_streaming_custom_output ()
        local session_name="$1"
        local grouping="$2"
        local custom_output="custom_second_token"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer streaming, custom output [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer streaming, custom output [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost/$custom_output
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -271,7 +222,7 @@ function test_ust_uid_streaming_custom_output ()
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/$custom_output"
@@ -290,18 +241,10 @@ function test_ust_uid_streaming_rotate ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer rotate [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer rotate [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -311,7 +254,7 @@ function test_ust_uid_streaming_rotate ()
        rotate_session_ok "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -331,18 +274,10 @@ function test_ust_uid_streaming_rotate_custom_output ()
        local session_name="$1"
        local grouping="$2"
        local custom_output="rotate_custom_path"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer rotate, custom output [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer rotate, custom output [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost/$custom_output
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -353,7 +288,7 @@ function test_ust_uid_streaming_rotate_custom_output ()
 
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/$custom_output"
@@ -372,18 +307,10 @@ function test_ust_pid_streaming_rotate ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST pid buffer rotate with session_name [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST pid buffer rotate with session_name [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-pid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -393,7 +320,7 @@ function test_ust_pid_streaming_rotate ()
        rotate_session_ok "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -412,18 +339,10 @@ function test_ust_uid_streaming_snapshot ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer snapshot streaming using 'create --snapshot' [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer snapshot streaming using 'create --snapshot' [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost --snapshot
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-uid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -433,7 +352,7 @@ function test_ust_uid_streaming_snapshot ()
        lttng_snapshot_record "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME*"
@@ -452,24 +371,16 @@ function test_ust_pid_streaming_snapshot ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
 
        local file_sync_after_first
        local file_sync_before_last
 
-       file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST pid buffer snapshot streaming using 'create --snapshot' [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST pid buffer snapshot streaming using 'create --snapshot' [$grouping][${session_name}]"
 
        create_lttng_session_uri "$session_name" net://localhost --snapshot
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_ust_lttng_channel_ok "$session_name" "$CHANNEL_NAME" "--buffers-pid"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -489,7 +400,7 @@ function test_ust_pid_streaming_snapshot ()
        wait
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/snapshot-1*"
@@ -511,18 +422,10 @@ function test_ust_uid_streaming_snapshot_add_output_default_name ()
 {
        local session_name="$1"
        local grouping="$2"
-       local is_automatic_session=false
-
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
 
-       diag "Test UST uid buffer snapshot using 'add-output' with default snapshot name [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer snapshot using 'add-output' with default snapshot name [$grouping][${session_name}]"
 
        create_lttng_session_no_output "$session_name"
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_lttng_mmap_overwrite_ust_channel "$session_name" "$CHANNEL_NAME"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -534,7 +437,7 @@ function test_ust_uid_streaming_snapshot_add_output_default_name ()
        lttng_snapshot_record "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/snapshot-1*"
@@ -554,18 +457,10 @@ function test_ust_uid_streaming_snapshot_add_output_custom_name ()
        local session_name="$1"
        local grouping="$2"
        local snapshot_name="this_is_my_snapshot"
-       local is_automatic_session=false
 
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
-
-       diag "Test UST uid buffer snapshot using 'add-output' with custom snapshot name [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer snapshot using 'add-output' with custom snapshot name [$grouping][${session_name}]"
 
        create_lttng_session_no_output "$session_name"
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_lttng_mmap_overwrite_ust_channel "$session_name" "$CHANNEL_NAME"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -577,7 +472,7 @@ function test_ust_uid_streaming_snapshot_add_output_custom_name ()
        lttng_snapshot_record "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        # When session name is automatic, the actual directory is "auto", not
        # auto-<datetime>.
@@ -600,18 +495,10 @@ function test_ust_uid_streaming_snapshot_add_output_custom_name_custom_output ()
        local grouping="$2"
        local snapshot_name="this_is_my_snapshot"
        local custom_output="this/is/my/custom/path"
-       local is_automatic_session=false
-
-       if [ -z "$session_name" ]; then
-               is_automatic_session=true
-       fi
 
-       diag "Test UST uid buffer snapshot using 'add-output' with custom snapshot name and custom output path [$grouping][${session_name:-automatic session name}]"
+       diag "Test UST uid buffer snapshot using 'add-output' with custom snapshot name and custom output path [$grouping][${session_name}]"
 
        create_lttng_session_no_output "$session_name"
-       if [ "$is_automatic_session" = true ]; then
-               get_auto_session_name session_name
-       fi
 
        enable_lttng_mmap_overwrite_ust_channel "$session_name" "$CHANNEL_NAME"
        enable_ust_lttng_event_ok "$session_name" "$EVENT_NAME" "$CHANNEL_NAME"
@@ -623,7 +510,7 @@ function test_ust_uid_streaming_snapshot_add_output_custom_name_custom_output ()
        lttng_snapshot_record "$session_name"
 
        stop_lttng_tracing_ok "$session_name"
-       destroy_lttng_session_ok "$session_name"
+       destroy_lttng_session_ok "$session_name" --no-wait
 
        if [ "$grouping" = "$GROUP_BY_SESSION" ]; then
                validate_trace "$EVENT_NAME" "$TRACE_PATH/$session_name/$HOSTNAME-*/$custom_output/$snapshot_name*"
@@ -668,30 +555,21 @@ grouping_types=(
        $GROUP_BY_SESSION
        $GROUP_BY_HOSTNAME
 )
-for fct_test in "${tests[@]}";
+for grouping in "${grouping_types[@]}";
 do
-       for grouping in "${grouping_types[@]}";
+       TRACE_PATH=$(mktemp -d -t tmp.test_relayd_grouping_ust_trace_path.XXXXXX)
+       # Set the relayd in --group-output-by-session mode
+       start_lttng_relayd "-o $TRACE_PATH $grouping"
+       start_lttng_sessiond
+       for fct_test in "${tests[@]}";
        do
-               TRACE_PATH=$(mktemp --tmpdir -d tmp.test_relayd_grouping_ust_trace_path.XXXXXX)
-               # Set the relayd in --group-output-by-session mode
-               start_lttng_relayd "-o $TRACE_PATH $grouping"
-               start_lttng_sessiond
-
-               name=""
-               # Perform test when session name is generated by the client
-               ${fct_test} "$name" "$grouping"
-               count=$(find "$TRACE_PATH/" -maxdepth 1 -mindepth 1 | wc -l)
-               is "$count" "0" "LTTng-relayd output directory empty"
-
                # Perform test when session name is given
                name="my-session"
                ${fct_test} "$name" "$grouping"
                count=$(find "$TRACE_PATH/" -maxdepth 1 -mindepth 1 | wc -l)
                is "$count" "0" "LTTng-relayd output directory empty"
-
-               rm -rf "$TRACE_PATH"
-               stop_lttng_relayd
-               stop_lttng_sessiond
        done
+       rm -rf "$TRACE_PATH"
+       stop_lttng_relayd
+       stop_lttng_sessiond
 done
-
index 009473893b9fb37e004a5936580c9063f47ef5ea..3a195c12b932c6c50a0dd497e4a759441ad2d75c 100644 (file)
@@ -9,22 +9,21 @@
  *
  */
 
-#include <stddef.h>
+#include <lttng/lttng.h>
+
 #include <stdbool.h>
+#include <stddef.h>
 #include <tap/tap.h>
 
-#include <lttng/lttng.h>
-
 #define NUM_TESTS 26
 
 #define SIZE_THRESHOLD_BYTES 1024
-#define PERIODIC_TIME_US 1000000
+#define PERIODIC_TIME_US     1000000
 
 const char *session_name;
 
-static
-bool schedules_equal(const struct lttng_rotation_schedule *a,
-               const struct lttng_rotation_schedule *b)
+static bool schedules_equal(const struct lttng_rotation_schedule *a,
+                           const struct lttng_rotation_schedule *b)
 {
        bool equal = false;
        enum lttng_rotation_schedule_type a_type, b_type;
@@ -34,22 +33,19 @@ bool schedules_equal(const struct lttng_rotation_schedule *a,
        a_type = lttng_rotation_schedule_get_type(a);
        b_type = lttng_rotation_schedule_get_type(b);
        if (a_type != b_type) {
-               diag("Schedules are not of the same type (%i != %i)",
-                               a_type, b_type);
+               diag("Schedules are not of the same type (%i != %i)", a_type, b_type);
                goto end;
        }
 
        switch (a_type) {
        case LTTNG_ROTATION_SCHEDULE_TYPE_SIZE_THRESHOLD:
        {
-               status = lttng_rotation_schedule_size_threshold_get_threshold(a,
-                               &a_value);
+               status = lttng_rotation_schedule_size_threshold_get_threshold(a, &a_value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        diag("Failed to retrieve size threshold of schedule 'a'");
                        goto end;
                }
-               status = lttng_rotation_schedule_size_threshold_get_threshold(b,
-                               &b_value);
+               status = lttng_rotation_schedule_size_threshold_get_threshold(b, &b_value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        diag("Failed to retrieve size threshold of schedule 'b'");
                        goto end;
@@ -58,14 +54,12 @@ bool schedules_equal(const struct lttng_rotation_schedule *a,
        }
        case LTTNG_ROTATION_SCHEDULE_TYPE_PERIODIC:
        {
-               status = lttng_rotation_schedule_periodic_get_period(a,
-                               &a_value);
+               status = lttng_rotation_schedule_periodic_get_period(a, &a_value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        diag("Failed to retrieve period of schedule 'a'");
                        goto end;
                }
-               status = lttng_rotation_schedule_periodic_get_period(b,
-                               &b_value);
+               status = lttng_rotation_schedule_periodic_get_period(b, &b_value);
                if (status != LTTNG_ROTATION_STATUS_OK) {
                        diag("Failed to retrieve period of schedule 'b'");
                        goto end;
@@ -85,8 +79,7 @@ end:
        return equal;
 }
 
-static
-void test_add_null_session(void)
+static void test_add_null_session(void)
 {
        enum lttng_rotation_status status;
        struct lttng_rotation_schedule *size_schedule = NULL;
@@ -95,49 +88,43 @@ void test_add_null_session(void)
 
        status = lttng_session_add_rotation_schedule(NULL, size_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "NULL session name rejected by lttng_session_add_rotation_schedule()");
+          "NULL session name rejected by lttng_session_add_rotation_schedule()");
        lttng_rotation_schedule_destroy(size_schedule);
 }
 
-static
-void test_add_null_schedule(void)
+static void test_add_null_schedule(void)
 {
        enum lttng_rotation_status status;
 
        status = lttng_session_add_rotation_schedule(session_name, NULL);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "NULL schedule rejected by lttng_session_add_rotation_schedule()");
+          "NULL schedule rejected by lttng_session_add_rotation_schedule()");
 }
 
-static
-void test_add_uninitialized_schedule(void)
+static void test_add_uninitialized_schedule(void)
 {
        enum lttng_rotation_status status;
-       struct lttng_rotation_schedule *size_schedule = NULL,
-                       *periodic_schedule = NULL;
+       struct lttng_rotation_schedule *size_schedule = NULL, *periodic_schedule = NULL;
 
        size_schedule = lttng_rotation_schedule_size_threshold_create();
        ok(size_schedule, "Created a size threshold session rotation schedule");
 
-       status = lttng_session_add_rotation_schedule(session_name,
-                       size_schedule);
+       status = lttng_session_add_rotation_schedule(session_name, size_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "Uninitialized size schedule rejected by lttng_session_add_rotation_schedule()");
+          "Uninitialized size schedule rejected by lttng_session_add_rotation_schedule()");
 
        periodic_schedule = lttng_rotation_schedule_periodic_create();
        ok(periodic_schedule, "Created a periodic session rotation schedule");
 
-       status = lttng_session_add_rotation_schedule(session_name,
-                       periodic_schedule);
+       status = lttng_session_add_rotation_schedule(session_name, periodic_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "Uninitialized periodic schedule rejected by lttng_session_add_rotation_schedule()");
+          "Uninitialized periodic schedule rejected by lttng_session_add_rotation_schedule()");
 
        lttng_rotation_schedule_destroy(size_schedule);
        lttng_rotation_schedule_destroy(periodic_schedule);
 }
 
-static
-void test_remove_null_session(void)
+static void test_remove_null_session(void)
 {
        enum lttng_rotation_status status;
        struct lttng_rotation_schedule *size_schedule = NULL;
@@ -146,71 +133,59 @@ void test_remove_null_session(void)
 
        status = lttng_session_remove_rotation_schedule(NULL, size_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "NULL session name rejected by lttng_session_remove_rotation_schedule()");
+          "NULL session name rejected by lttng_session_remove_rotation_schedule()");
        lttng_rotation_schedule_destroy(size_schedule);
 }
 
-static
-void test_remove_null_schedule(void)
+static void test_remove_null_schedule(void)
 {
        enum lttng_rotation_status status;
 
        status = lttng_session_remove_rotation_schedule(session_name, NULL);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "NULL schedule rejected by lttng_session_remove_rotation_schedule()");
+          "NULL schedule rejected by lttng_session_remove_rotation_schedule()");
 }
 
-static
-void test_remove_uninitialized_schedule(void)
+static void test_remove_uninitialized_schedule(void)
 {
        enum lttng_rotation_status status;
-       struct lttng_rotation_schedule *size_schedule = NULL,
-                       *periodic_schedule = NULL;
+       struct lttng_rotation_schedule *size_schedule = NULL, *periodic_schedule = NULL;
 
        size_schedule = lttng_rotation_schedule_size_threshold_create();
-       status = lttng_session_remove_rotation_schedule(session_name,
-                       size_schedule);
+       status = lttng_session_remove_rotation_schedule(session_name, size_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "Uninitialized size schedule rejected by lttng_session_remove_rotation_schedule()");
+          "Uninitialized size schedule rejected by lttng_session_remove_rotation_schedule()");
 
        periodic_schedule = lttng_rotation_schedule_periodic_create();
-       status = lttng_session_remove_rotation_schedule(session_name,
-                       periodic_schedule);
+       status = lttng_session_remove_rotation_schedule(session_name, periodic_schedule);
        ok(status == LTTNG_ROTATION_STATUS_INVALID,
-                       "Uninitialized periodic schedule rejected by lttng_session_remove_rotation_schedule()");
+          "Uninitialized periodic schedule rejected by lttng_session_remove_rotation_schedule()");
 
        lttng_rotation_schedule_destroy(size_schedule);
        lttng_rotation_schedule_destroy(periodic_schedule);
 }
 
-static
-void test_uninitialized_schedule_get(void)
+static void test_uninitialized_schedule_get(void)
 {
        uint64_t value;
        enum lttng_rotation_status status;
-       struct lttng_rotation_schedule *size_schedule = NULL,
-                       *periodic_schedule = NULL;
+       struct lttng_rotation_schedule *size_schedule = NULL, *periodic_schedule = NULL;
 
        size_schedule = lttng_rotation_schedule_size_threshold_create();
        periodic_schedule = lttng_rotation_schedule_periodic_create();
 
-       status = lttng_rotation_schedule_size_threshold_get_threshold(
-                       size_schedule, &value);
+       status = lttng_rotation_schedule_size_threshold_get_threshold(size_schedule, &value);
        ok(status == LTTNG_ROTATION_STATUS_UNAVAILABLE,
-                       "Getter on size threshold rotation schedule returns LTTNG_ROTATION_STATUS_UNAVAILABLE by default");
-       status = lttng_rotation_schedule_periodic_get_period(periodic_schedule,
-                       &value);
+          "Getter on size threshold rotation schedule returns LTTNG_ROTATION_STATUS_UNAVAILABLE by default");
+       status = lttng_rotation_schedule_periodic_get_period(periodic_schedule, &value);
        ok(status == LTTNG_ROTATION_STATUS_UNAVAILABLE,
-                       "Getter on periodic rotation schedule returns LTTNG_ROTATION_STATUS_UNAVAILABLE by default");
+          "Getter on periodic rotation schedule returns LTTNG_ROTATION_STATUS_UNAVAILABLE by default");
 
        lttng_rotation_schedule_destroy(size_schedule);
        lttng_rotation_schedule_destroy(periodic_schedule);
-
 }
 
-static
-void test_add_list_remove_schedule(
-               const struct lttng_rotation_schedule *original_schedule)
+static void test_add_list_remove_schedule(const struct lttng_rotation_schedule *original_schedule)
 {
        int ret;
        unsigned int schedules_count = 0;
@@ -218,68 +193,57 @@ void test_add_list_remove_schedule(
        const struct lttng_rotation_schedule *list_schedule;
        struct lttng_rotation_schedules *list_schedules;
 
-       status = lttng_session_add_rotation_schedule(session_name,
-                       original_schedule);
+       status = lttng_session_add_rotation_schedule(session_name, original_schedule);
        ok(status == LTTNG_ROTATION_STATUS_OK,
-                       "Add a rotation schedule to session \'%s\'",
-                       session_name);
+          "Add a rotation schedule to session \'%s\'",
+          session_name);
 
-       ret = lttng_session_list_rotation_schedules(session_name,
-                       &list_schedules);
+       ret = lttng_session_list_rotation_schedules(session_name, &list_schedules);
        ok(ret == LTTNG_OK && list_schedules,
-                       "List rotation schedules of session \'%s\'",
-                       session_name);
+          "List rotation schedules of session \'%s\'",
+          session_name);
 
-       status = lttng_rotation_schedules_get_count(list_schedules,
-                       &schedules_count);
+       status = lttng_rotation_schedules_get_count(list_schedules, &schedules_count);
        ok(status == LTTNG_ROTATION_STATUS_OK && schedules_count == 1,
-                       "Listing returned 1 rotation schedule");
+          "Listing returned 1 rotation schedule");
 
-       list_schedule = lttng_rotation_schedules_get_at_index(list_schedules,
-                       0);
-       ok(list_schedule,
-                       "Obtain the first schedule of a schedules list");
+       list_schedule = lttng_rotation_schedules_get_at_index(list_schedules, 0);
+       ok(list_schedule, "Obtain the first schedule of a schedules list");
 
        ok(schedules_equal(original_schedule, list_schedule),
-                       "Schedule returned by the listing is equal to the reference schedule that was added");
+          "Schedule returned by the listing is equal to the reference schedule that was added");
 
-       status = lttng_session_remove_rotation_schedule(session_name,
-                       list_schedule);
+       status = lttng_session_remove_rotation_schedule(session_name, list_schedule);
        ok(status == LTTNG_ROTATION_STATUS_OK,
-                       "Remove rotation schedule returned by the schedules listing");
+          "Remove rotation schedule returned by the schedules listing");
        lttng_rotation_schedules_destroy(list_schedules);
 
-       (void) lttng_session_list_rotation_schedules(session_name,
-                       &list_schedules);
-       status = lttng_rotation_schedules_get_count(list_schedules,
-                       &schedules_count);
+       (void) lttng_session_list_rotation_schedules(session_name, &list_schedules);
+       status = lttng_rotation_schedules_get_count(list_schedules, &schedules_count);
        ok(status == LTTNG_ROTATION_STATUS_OK && schedules_count == 0,
-                       "Listing returned 0 rotation schedules after removal");
+          "Listing returned 0 rotation schedules after removal");
        lttng_rotation_schedules_destroy(list_schedules);
 }
 
-static
-void test_add_list_remove_size_schedule(void)
+static void test_add_list_remove_size_schedule(void)
 {
        struct lttng_rotation_schedule *size_schedule;
 
        diag("Add, list, and remove a size threshold rotation schedule");
        size_schedule = lttng_rotation_schedule_size_threshold_create();
-       (void) lttng_rotation_schedule_size_threshold_set_threshold(
-                       size_schedule, SIZE_THRESHOLD_BYTES);
+       (void) lttng_rotation_schedule_size_threshold_set_threshold(size_schedule,
+                                                                   SIZE_THRESHOLD_BYTES);
        test_add_list_remove_schedule(size_schedule);
        lttng_rotation_schedule_destroy(size_schedule);
 }
 
-static
-void test_add_list_remove_periodic_schedule(void)
+static void test_add_list_remove_periodic_schedule(void)
 {
        struct lttng_rotation_schedule *periodic_schedule;
 
        diag("Add, list, and remove a periodic rotation schedule");
        periodic_schedule = lttng_rotation_schedule_periodic_create();
-       (void) lttng_rotation_schedule_periodic_set_period(
-                       periodic_schedule, PERIODIC_TIME_US);
+       (void) lttng_rotation_schedule_periodic_set_period(periodic_schedule, PERIODIC_TIME_US);
        test_add_list_remove_schedule(periodic_schedule);
        lttng_rotation_schedule_destroy(periodic_schedule);
 }
index 760930e958a506754fafd9b7689d662910431355..e66a257a962da00ec612d81e143e133e7bfa9944 100755 (executable)
@@ -10,7 +10,7 @@ CURDIR=$(dirname $0)/
 TESTDIR=$CURDIR/../../..
 EVENT_NAME="lttng_test_filter_event"
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.rotation_kernel_tracing.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.rotation_kernel_tracing.XXXXXX)
 
 NUM_TESTS=66
 
@@ -107,13 +107,7 @@ plan_tests $NUM_TESTS
 print_test_banner "$TEST_DESC"
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel streaming tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
index 6a1f42101b23aa333e23ebd2cf49b48692ee00ea..94c98c9883a0cca7d1e5d04caf4ab07fcd14b2fe 100755 (executable)
@@ -28,9 +28,9 @@ XPATH_LIST_ROTATE_SIZE="$XPATH_SESSION/lttng:rotation_schedules/lttng:size_thres
 
 function test_save_load_mi ()
 {
-       local tmp_xml_output=$(mktemp --tmpdir -u -t "tmp.${FUNCNAME[0]}_xml_output.XXXXXX")
-       local tmp_save_output=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_save_output.XXXXXX")
-       local trace_path=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local tmp_xml_output=$(mktemp -u -t "tmp.${FUNCNAME[0]}_xml_output.XXXXXX")
+       local tmp_save_output=$(mktemp -d -t "tmp.${FUNCNAME[0]}_save_output.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        diag "Test save/load/list/MI with rotation"
        create_lttng_session_ok $SESSION_NAME $trace_path
index 8b4f42d19a4093eed790124ae0124916f1ca15d4..e2be8c1b885dcbd46176e7a6aaa8270c7861ed7c 100755 (executable)
@@ -10,7 +10,7 @@ CURDIR=$(dirname $0)/
 TESTDIR=$CURDIR/../../..
 
 SESSION_NAME="my_session"
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.rotation_schedule_api.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.rotation_schedule_api.XXXXXX)
 
 source $TESTDIR/utils/utils.sh
 
index 043b123bfa2f640d6edbd0cb30a29cad50ef72a2..cbeb47d8a4d8326c143ba89a195cd7ad8f3454a2 100755 (executable)
@@ -15,7 +15,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="stream"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_ust_rotation_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_ust_rotation_trace_path.XXXXXX)
 
 NUM_TESTS=152
 
index 4f8294ef0e30746515b2880e612929103a251bf7..af7d452b04fbf66651e591963ea97e0623b57127 100755 (executable)
@@ -16,7 +16,7 @@ SESSION_NAME="stream"
 UST_EVENT_NAME="tp:tptest"
 KERNEL_EVENT_NAME="lttng_test_filter_event"
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.rotation_ust_kernel_tracing.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.rotation_ust_kernel_tracing.XXXXXX)
 
 NUM_TESTS=64
 
@@ -85,13 +85,7 @@ plan_tests $NUM_TESTS
 print_test_banner "$TEST_DESC"
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
index ddf54db594e65cb6ef1aa952473025d8b640a623..df3fbf153a402faa44020d5d2a22f70e3ab3d64e 100755 (executable)
@@ -62,8 +62,8 @@ TESTS=(
 
 for fct_test in ${TESTS[@]};
 do
-       export LTTNG_HOME=$(mktemp --tmpdir -d tmp.test_lttng_home_dir.XXXXXX)
-       export LTTNG_DIR=$(mktemp --tmpdir -d tmp.test_lttng_dir.XXXXXX)
+       export LTTNG_HOME=$(mktemp -d -t tmp.test_lttng_home_dir.XXXXXX)
+       export LTTNG_DIR=$(mktemp -d -t tmp.test_lttng_dir.XXXXXX)
 
        ${fct_test}
        rm -rf $LTTNG_DIR
index cbdf96f6ebeded149cdb0ad9e7816d0aeb80f0e2..e073e6071aabad107dc5d05c90d4348795bf9ccf 100755 (executable)
@@ -58,7 +58,7 @@ function test_complex_load()
        disable_ust_lttng_channel $sess chan3
 
        # Confirm that an event stored as disabled is restored in its disabled state
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -127,7 +127,7 @@ function test_trackers()
        lttng_load_ok "-i $CURDIR/$SESSION_NAME-trackers.lttng"
 
        diag "Test pid tracker"
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -168,7 +168,7 @@ function test_override_url_normal()
 {
        local local_url_override="file:///tmp/override/to/here"
        local local_path_override="/tmp/override/to/here"
-       local local_path_compare_value="/tmp/override/to/here/"
+       local local_path_compare_value="/tmp/override/to/here"
        local stream_url_override="net://127.0.0.1:8172:9817"
        local stream_url_compare="tcp4://127.0.0.1:8172/ [data: 9817]"
 
@@ -176,7 +176,7 @@ function test_override_url_normal()
 
        start_lttng_relayd "-C tcp://127.0.0.1:8172 -D tcp://127.0.0.1:9817"
 
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -216,7 +216,7 @@ function test_override_url_snapshot()
 {
        local url_override="file:///tmp/override/to/here"
        local path_override="/tmp/override/to/here"
-       local path_compare_value="/tmp/override/to/here/"
+       local path_compare_value="/tmp/override/to/here"
        local stream_url_override="net://127.0.0.1:8172:9817"
        local stream_url_compare_ctrl="tcp4://127.0.0.1:8172/"
        local stream_url_compare_data="tcp4://127.0.0.1:9817/"
@@ -226,7 +226,7 @@ function test_override_url_snapshot()
 
        start_lttng_relayd "-C tcp://127.0.0.1:8172 -D tcp://127.0.0.1:9817"
 
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -271,7 +271,7 @@ function test_override_url_live()
 {
        local url_override="file:///tmp/override/to/here"
        local path_override="/tmp/override/to/here"
-       local path_compare_value="/tmp/override/to/here/"
+       local path_compare_value="/tmp/override/to/here"
        local stream_url_override="net://127.0.0.1:8172:9817"
        local stream_url_compare="tcp4://127.0.0.1:8172/ [data: 9817]"
        local local_session_name="${SESSION_NAME}-live"
@@ -280,7 +280,7 @@ function test_override_url_live()
 
        start_lttng_relayd "-C tcp://127.0.0.1:8172 -D tcp://127.0.0.1:9817"
 
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -316,7 +316,7 @@ function test_override_session_name()
        local override_name="PinkyAndTheBrain"
        local output_path="/tmp/lttng/load-42-1"
 
-       local mi_output_file=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
+       local mi_output_file=$(mktemp -t "tmp.${FUNCNAME[0]}_output_file.XXXXXX")
        if [ $? -ne 0 ]; then
                break;
        fi
@@ -362,7 +362,7 @@ TESTS=(
 
 for fct_test in ${TESTS[@]};
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_load_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_load_trace_path.XXXXXX)
 
        ${fct_test}
        if [ $? -ne 0 ]; then
index 73527ec7b8d568ced4dd2323a25ba5db2cf96402..47b792dc9aca6644d75512c56ddc0e30a607aec1 100755 (executable)
@@ -134,7 +134,7 @@ TESTS=(
 
 for fct_test in ${TESTS[@]};
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_save_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_save_trace_path.XXXXXX)
 
        ${fct_test}
        if [ $? -ne 0 ]; then
index f1015ee25c938be9d557c2cf27e46fee7ac2276f..302e5b341c0b800059a5c84750ead2de5b962714 100755 (executable)
@@ -12,7 +12,7 @@ EVENT_NAME="sched_switch"
 SESSION_NAME=""
 CHANNEL_NAME="snapchan"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_snapshots_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_snapshots_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=2061
 
@@ -96,8 +96,8 @@ function test_kernel_local_snapshot_append_to_metadata ()
 
 function generate_filter_events_cpu0()
 {
-       # Generate many events (fill buffers) on CPU 0
-       taskset 0x00000001 /bin/echo -n "$1" > /proc/lttng-test-filter-event 2> /dev/null
+       # Generate many events (fill buffers) on a single CPU
+       taskset --cpu-list "$(get_any_available_cpu)" /bin/echo -n "$1" > /proc/lttng-test-filter-event 2> /dev/null
 }
 
 function test_kernel_local_snapshot_discard ()
@@ -221,14 +221,7 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel snapshot tests" $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
 
        validate_lttng_modules_present
index 0c92dc710af39620ee1110c9ddf8fc717c0dacc5..e80e78a8cf64650c94f6507c6f7a05be63356bca 100755 (executable)
@@ -12,7 +12,7 @@ EVENT_NAME="sched_switch"
 SESSION_NAME=""
 CHANNEL_NAME="chan1"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_snapshots_kernel_streaming_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_snapshots_kernel_streaming_trace_path.XXXXXX)
 
 NUM_TESTS=66
 
@@ -145,13 +145,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel streaming tests" $NUM_TESTS ||
+check_skip_kernel_test $NUM_TESTS "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
index 1b11c500b9344588dc8e503c23fa9cf6d756e926..9fb4e0068d1c8504a73743c1ca2e340f921bffdc 100755 (executable)
@@ -15,4 +15,4 @@ if [ ! -x "$CURDIR/$TEST_BIN" ]; then
        BAIL_OUT "No UST test found: $TEST_BIN"
 fi
 
-./$CURDIR/$TEST_BIN $NR_SNAPSHOT
+exec $CURDIR/$TEST_BIN $NR_SNAPSHOT
index d0e779a834b8413f30f1d8f287b8ab9e32f1ec85..bc6abac316c00ef63c4b1af9f704629e79e08736 100755 (executable)
@@ -15,4 +15,4 @@ if [ ! -x "$CURDIR/$TEST_BIN" ]; then
        BAIL_OUT "No UST test found: $TEST_BIN"
 fi
 
-./$CURDIR/$TEST_BIN $NR_SNAPSHOT
+exec $CURDIR/$TEST_BIN $NR_SNAPSHOT
index 24e52c4161db2dd8de065ba084174860f883c4df..2e04d667e76890a9dbf7141fef82b429d4f9dbad 100755 (executable)
@@ -6,24 +6,24 @@
 
 TEST_DESC="Streaming - Snapshot UST tracing"
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/../../..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/../../.."
 EVENT_NAME="tp:tptest"
 SESSION_NAME=""
 CHANNEL_NAME="chan1"
-BIN_NAME="gen-nevents"
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 NR_ITER=-1
 NR_USEC_WAIT=100
-APPS_PID=
+APP_PIDS=()
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_snapshots_ust_streaming_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_snapshots_ust_streaming_trace_path.XXXXXX)
 
 NUM_TESTS=85
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../../../
+source "$TESTDIR/utils/utils.sh"
 
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST events binary detected."
@@ -34,25 +34,42 @@ function snapshot_add_output ()
        local sess_name=$1
        local trace_path=$2
        local name=$3
-       local extra_opt=""
+       local options=()
+       local args=()
 
-       if [ ! -z $name ]; then
-               extra_opt="-n $name"
+       if [ -n "$sess_name" ] ; then
+               options+=(-s "$sess_name")
        fi
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN snapshot add-output -s $sess_name $extra_opt $trace_path >/dev/null 2>&1
+       if [ -n "$name" ]; then
+               options+=(-n "$name")
+       fi
+
+       # Checking for any other optional arguments that should be passed to the lttng command
+       args=("$@")
+       if [ -n "${args[*]:3}" ] ; then
+               options+=("${args[@]:3}")
+       fi
+
+       # The trace_path is a positional argument and must always come last if it is defined
+       if [ -n "$trace_path" ] ; then
+               options+=("$trace_path")
+       fi
+
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" snapshot add-output "${options[@]}" >/dev/null 2>&1
        ok $? "Added snapshot output $trace_path"
 }
 
 # Start trace application and return once one event has been hit.
 function start_test_app()
 {
-       local tmp_file=$(mktemp --tmpdir -u tmp.test_${FUNCNAME[0]}_tmp_file.XXXXXX)
+       local tmp_file
+       tmp_file=$(mktemp -u -t tmp.test_"${FUNCNAME[0]}"_tmp_file.XXXXXX)
 
        # Start application with a temporary file.
-       $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event $tmp_file &
+       $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event "$tmp_file" &
        ret=$?
-       APPS_PID="${APPS_PID} ${!}"
+       APP_PIDS+=(${!})
        ok $ret "Start application to trace"
 
        # Wait for the application file to appear indicating that at least one
@@ -61,55 +78,51 @@ function start_test_app()
                sleep 0.5
        done
        diag "Removing test app temporary file $tmp_file"
-       rm -f $tmp_file
+       rm -f "$tmp_file"
 }
 
 function stop_test_apps()
 {
        diag "Stopping $TESTAPP_NAME"
-       for p in ${APPS_PID}; do
-               kill ${p}
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       kill "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
+       APP_PIDS=()
 }
 
 # Test a snapshot using a default name for the output destination.
 function test_ust_default_name_with_del()
 {
        diag "Test UST snapshot streaming with default name with delete output"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
 
        start_test_app
 
-       snapshot_add_output $SESSION_NAME "net://localhost"
-       lttng_snapshot_record $SESSION_NAME
+       snapshot_add_output "$SESSION_NAME" "net://localhost"
+       lttng_snapshot_record "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*
-       if [ $? -ne 0 ]; then
+       if ! validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*" ; then
                stop_test_apps
                return $?
        fi
 
-       lttng_snapshot_del_output_ok $SESSION_NAME 1
-       snapshot_add_output $SESSION_NAME "net://localhost"
-       lttng_snapshot_record $SESSION_NAME
+       lttng_snapshot_del_output_ok "$SESSION_NAME" 1
+       snapshot_add_output "$SESSION_NAME" "net://localhost"
+       lttng_snapshot_record "$SESSION_NAME"
 
        # Validate test with the next ID since a del output was done prior.
        validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-2" 1
-       validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-2*
-       if [ $? -ne 0 ]; then
+       if ! validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-2*" ; then
                stop_test_apps
                return $?
        fi
 
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        stop_test_apps
 
@@ -120,20 +133,20 @@ function test_ust_default_name_with_del()
 function test_ust_default_name()
 {
        diag "Test UST snapshot streaming with default name"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
 
        start_test_app
 
-       snapshot_add_output $SESSION_NAME "net://localhost"
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       snapshot_add_output "$SESSION_NAME" "net://localhost"
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
        # Validate test
        validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*
+       validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*"
        out=$?
 
        stop_test_apps
@@ -144,20 +157,20 @@ function test_ust_default_name()
 function test_ust_default_name_custom_uri()
 {
        diag "Test UST snapshot streaming with default name with custom URL"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
 
        start_test_app
 
-       snapshot_add_output $SESSION_NAME "-C tcp://localhost:5342 -D tcp://localhost:5343"
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       snapshot_add_output "$SESSION_NAME" '' '' -C tcp://localhost:5342 -D tcp://localhost:5343
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
        # Validate test
        validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*
+       validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*"
        out=$?
 
        stop_test_apps
@@ -172,23 +185,23 @@ function test_ust_custom_name()
        local name="asnapshotname"
 
        diag "Test UST snapshot streaming with custom name"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
 
        start_test_app
 
-       snapshot_add_output $SESSION_NAME "net://localhost" $name
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       snapshot_add_output "$SESSION_NAME" "net://localhost" $name
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
-       if ls $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/$name* &> /dev/null; then
+       if ls "$TRACE_PATH/$HOSTNAME/$SESSION_NAME"*/"$name"* &> /dev/null; then
                ok 0 "Custom name snapshot exists"
                # Validate test
                validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "$name" 0
-               validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/$name-*
+               validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/$name-*"
                out=$?
        else
                fail "No custom name snapshot found"
@@ -203,27 +216,26 @@ function test_ust_custom_name()
 function test_ust_n_snapshot()
 {
        diag "Test ust snapshot streaming multiple consecutive snapshot"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       snapshot_add_output $SESSION_NAME "net://localhost"
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       snapshot_add_output "$SESSION_NAME" "net://localhost"
        start_test_app
        for i in {0..4};
        do
-               start_lttng_tracing_ok $SESSION_NAME
-               lttng_snapshot_record $SESSION_NAME
-               stop_lttng_tracing_ok $SESSION_NAME
-               validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-1" $i
-               validate_trace $EVENT_NAME $TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*
-               if [ $? -ne 0 ]; then
+               start_lttng_tracing_ok "$SESSION_NAME"
+               lttng_snapshot_record "$SESSION_NAME"
+               stop_lttng_tracing_ok "$SESSION_NAME"
+               validate_trace_path_ust_uid_snapshot_network "$TRACE_PATH" "$SESSION_NAME" "snapshot-1" "$i"
+               if ! validate_trace $EVENT_NAME "$TRACE_PATH/$HOSTNAME/$SESSION_NAME*/snapshot-1*" ; then
                        return 1
                fi
                set -u
-               rm -rf $TRACE_PATH/$HOSTNAME
+               rm -rf "${TRACE_PATH:?}/${HOSTNAME}"
                set +u
        done
 
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok "$SESSION_NAME"
        stop_test_apps
        return 0
 }
@@ -234,13 +246,8 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
 start_lttng_relayd "-o $TRACE_PATH"
+# shellcheck disable=SC2119
 start_lttng_sessiond
 
 tests=( test_ust_default_name_with_del
@@ -250,17 +257,18 @@ tests=( test_ust_default_name_with_del
        test_ust_n_snapshot
 )
 
-for fct_test in ${tests[@]};
+for fct_test in "${tests[@]}";
 do
        SESSION_NAME=$(randstring 16 0)
-       ${fct_test}
-       if [ $? -eq 0 ]; then
+       if ${fct_test} ; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "$TRACE_PATH"
        else
                break
        fi
 done
 
+# shellcheck disable=SC2119
 stop_lttng_sessiond
+# shellcheck disable=SC2119
 stop_lttng_relayd
index e2e84b5c343017177f890a782d8d941f00ec9233..5188c2b5b21215c58adec2bc88a52f4aa98f0f39 100755 (executable)
@@ -6,42 +6,44 @@
 
 TEST_DESC="Snapshots - UST tracing"
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/../../..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/../../.."
 EVENT_NAME="tp:tptest"
 SESSION_NAME=""
 CHANNEL_NAME="snapchan"
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
-APPS_PID=
+APPS_PID=()
 
-NUM_TESTS=105
+NUM_TESTS=104
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_snapshots_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_snapshots_ust_trace_path.XXXXXX)
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../../../
+source "$TESTDIR/utils/utils.sh"
 
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST events binary detected"
 fi
 
 # Need the number of snapshot to do.
-if [ -z $1 ]; then
+if [ -z "$1" ]; then
        BAIL_OUT "A number of snapshot is needed"
 fi
 NR_SNAPSHOT=$1
 
-NUM_TESTS=$(($NUM_TESTS + ($NR_SNAPSHOT * 3)))
+NUM_TESTS=$((NUM_TESTS + (NR_SNAPSHOT * 3)))
 
 function start_test_app()
 {
-       local tmp_file=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_tmp_file.XXXXXX")
+       local tmp_file
+       tmp_file=$(mktemp -u -t "tmp.${FUNCNAME[0]}_tmp_file.XXXXXX")
 
        # Start application with a temporary file.
-       $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event $tmp_file &
+       $TESTAPP_BIN -i "$NR_ITER" -w "$NR_USEC_WAIT" --sync-after-first-event "$tmp_file" &
        ret=$?
-       APPS_PID="${APPS_PID} ${!}"
+       APPS_PID+=(${!})
        ok $ret "Start application to trace"
 
        # Wait for the application file to appear indicating that at least one
@@ -50,25 +52,21 @@ function start_test_app()
                sleep 0.5
        done
        diag "Removing test app temporary file $tmp_file"
-       rm -f $tmp_file
+       rm -f "$tmp_file"
 }
 
 function wait_test_apps()
 {
        diag "Waiting for $TESTAPP_NAME"
-       for p in ${APPS_PID}; do
-               wait ${p} 2>/dev/null
-       done
+       wait "${APPS_PID[@]}" 2>/dev/null
 }
 
 function stop_test_apps()
 {
        diag "Stopping $TESTAPP_NAME"
-       for p in ${APPS_PID}; do
-               kill ${p}
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       kill "${APPS_PID[@]}"
+       wait "${APPS_PID[@]}"
+       APPS_PID=()
 }
 
 function snapshot_add_output ()
@@ -77,20 +75,20 @@ function snapshot_add_output ()
        local trace_path=$2
        local name=$3
        local max_size=$4
-       local extra_opt=""
+       local extra_opt=()
 
-       if [ ! -z $name ]; then
-               extra_opt+=" -n $name "
+       if [ -n "$name" ]; then
+               extra_opt+=(-n "$name")
        fi
 
-       if [ ! -z $max_size ]; then
-               extra_opt+=" -m $max_size "
+       if [ -n "$max_size" ]; then
+               extra_opt+=(-m "$max_size")
        fi
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN snapshot add-output \
-               -s $sess_name $extra_opt $trace_path > /dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" snapshot add-output \
+               -s "$sess_name" "${extra_opt[@]}" "$trace_path" > /dev/null 2>&1
 
-       ok $? "Added snapshot output $trace_path ($extra_opt)"
+       ok $? "Added snapshot output $trace_path (${extra_opt[*]})"
 }
 
 function snapshot_del_output ()
@@ -98,8 +96,8 @@ function snapshot_del_output ()
        local sess_name=$1
        local name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN snapshot del-output \
-               -s $sess_name $name > /dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" snapshot del-output \
+               -s "$sess_name" "$name" > /dev/null 2>&1
 
        ok $? "Deleted snapshot output named $name"
 }
@@ -109,10 +107,12 @@ function enable_mmap_overwrite_subbuf_ust_channel ()
        local sess_name=$1
        local chan_name=$2
        local subbuf_size=$3
+       local subbuf_count=$4
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel -s $sess_name \
-               $chan_name -u --output mmap --overwrite \
-               --subbuf-size $subbuf_size > /dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel -s "$sess_name" \
+               "$chan_name" -u --output mmap --overwrite \
+               --num-subbuf="$subbuf_count" \
+               --subbuf-size "$subbuf_size" > /dev/null 2>&1
 
        ok $? "Enable channel $channel_name for session $sess_name with subbuf size $subbuf_size"
 }
@@ -122,9 +122,9 @@ function enable_mmap_small_discard_ust_channel ()
        local sess_name=$1
        local chan_name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel -s $sess_name \
-               $chan_name -u --output mmap --discard \
-               --subbuf-size $(getconf PAGE_SIZE) --num-subbuf 2 \
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel -s "$sess_name" \
+               "$chan_name" -u --output mmap --discard \
+               --subbuf-size "$(getconf PAGE_SIZE)" --num-subbuf 2 \
                > /dev/null 2>&1
 
        ok $? "Enable channel $channel_name for session $sess_name with small discard buffers"
@@ -135,9 +135,9 @@ function enable_mmap_small_overwrite_ust_channel ()
        local sess_name=$1
        local chan_name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel -s $sess_name \
-               $chan_name -u --output mmap --overwrite \
-               --subbuf-size $(getconf PAGE_SIZE) --num-subbuf 2 \
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel -s "$sess_name" \
+               "$chan_name" -u --output mmap --overwrite \
+               --subbuf-size "$(getconf PAGE_SIZE)" --num-subbuf 2 \
                > /dev/null 2>&1
 
        ok $? "Enable channel $channel_name for session $sess_name with small discard buffers"
@@ -148,29 +148,29 @@ function test_ust_list_output ()
        output_names=("randomname" "somesnapshot")
 
        diag "Test UST snapshot output listing"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
 
-       start_lttng_tracing_ok $SESSION_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
 
-       snapshot_add_output $SESSION_NAME "file://$TRACE_PATH" ${output_names[0]}
+       snapshot_add_output "$SESSION_NAME" "file://$TRACE_PATH" "${output_names[0]}"
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN snapshot list-output \
-               -s $SESSION_NAME 2>&1 | grep ${output_names[0]} > /dev/null
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" snapshot list-output \
+               -s "$SESSION_NAME" 2>&1 | grep "${output_names[0]}" > /dev/null
        ok $? "Snapshot named ${output_names[0]} present in list-output listing"
 
-       snapshot_del_output $SESSION_NAME ${output_names[0]}
+       snapshot_del_output "$SESSION_NAME" "${output_names[0]}"
 
-       snapshot_add_output $SESSION_NAME "file://$TRACE_PATH" ${output_names[1]}
+       snapshot_add_output "$SESSION_NAME" "file://$TRACE_PATH" "${output_names[1]}"
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN snapshot list-output \
-               -s $SESSION_NAME 2>&1 | grep ${output_names[1]} > /dev/null
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" snapshot list-output \
+               -s "$SESSION_NAME" 2>&1 | grep "${output_names[1]}" > /dev/null
 
        ok $? "Snapshot named ${output_names[1]} present in list-output listing"
 
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 }
 
 function test_ust_local_snapshot ()
@@ -179,25 +179,24 @@ function test_ust_local_snapshot ()
        NR_USEC_WAIT=100
 
        diag "Test local UST snapshots"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Returns once the application has at least fired ONE tracepoint.
        start_test_app
 
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/
-       if [ $? -eq 0 ]; then
+       if validate_trace $EVENT_NAME "$TRACE_PATH/" ; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "$TRACE_PATH"
        fi
 
        stop_test_apps
@@ -210,32 +209,32 @@ function test_ust_local_snapshot_small_discard_buffers ()
        OLDCPUSET=$(taskset -p $$)
 
        diag "Test local UST snapshots with small discard buffers"
-       taskset -p 0x1 $$ 1>/dev/null 2>&1      # CPU 0 only
-       create_lttng_session_no_output $SESSION_NAME
-       enable_mmap_small_discard_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       taskset -c "$(get_any_available_cpu)" -p $$ 1>/dev/null 2>&1
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_mmap_small_discard_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Run test apps, wait for them to complete.
        start_test_app
        wait_test_apps
 
        # Take first snapshot, remember first line.
-       lttng_snapshot_record $SESSION_NAME
-       FIRST_LINE="$(trace_first_line $TRACE_PATH/)"
+       lttng_snapshot_record "$SESSION_NAME"
+       FIRST_LINE="$(trace_first_line "$TRACE_PATH/")"
        diag "First line (1st snapshot): $FIRST_LINE"
-       rm -rf $TRACE_PATH/
+       rm -rf "${TRACE_PATH:?}/"
 
        # Run test apps, wait for them to complete.
        start_test_app
        wait_test_apps
 
        # Take second snapshot, remember first line.
-       lttng_snapshot_record $SESSION_NAME
-       FIRST_LINE_2="$(trace_first_line $TRACE_PATH/)"
+       lttng_snapshot_record "$SESSION_NAME"
+       FIRST_LINE_2="$(trace_first_line "$TRACE_PATH/")"
        diag "First line (2nd snapshot): $FIRST_LINE_2"
-       rm -rf $TRACE_PATH/
+       rm -rf "${TRACE_PATH:?}/"
 
        if [ x"$FIRST_LINE" != x"$FIRST_LINE_2" ]; then
                fail "First snapshot event do not match"
@@ -243,9 +242,9 @@ function test_ust_local_snapshot_small_discard_buffers ()
                pass "First snapshot event match"
        fi
 
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
-       taskset -p $OLDCPUSET $$ 1>/dev/null 2>&1
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
+       taskset -p "$OLDCPUSET" $$ 1>/dev/null 2>&1
 }
 
 function test_ust_local_snapshot_small_overwrite_buffers ()
@@ -255,32 +254,32 @@ function test_ust_local_snapshot_small_overwrite_buffers ()
        OLDCPUSET=$(taskset -p $$)
 
        diag "Test local UST snapshots with small overwrite buffers"
-       taskset -p 0x1 $$ 1>/dev/null 2>&1      # CPU 0 only
-       create_lttng_session_no_output $SESSION_NAME
-       enable_mmap_small_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       taskset -p "$(get_any_available_cpu)" $$ 1>/dev/null 2>&1
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_mmap_small_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Run test apps, wait for them to complete.
        start_test_app
        wait_test_apps
 
        # Take first snapshot, remember first line.
-       lttng_snapshot_record $SESSION_NAME
-       FIRST_LINE="$(trace_first_line $TRACE_PATH/)"
+       lttng_snapshot_record "$SESSION_NAME"
+       FIRST_LINE="$(trace_first_line "$TRACE_PATH/")"
        diag "First line (1st snapshot): $FIRST_LINE"
-       rm -rf $TRACE_PATH/
+       rm -rf "${TRACE_PATH:?}/"
 
        # Run test apps, wait for them to complete.
        start_test_app
        wait_test_apps
 
        # Take second snapshot, remember first line.
-       lttng_snapshot_record $SESSION_NAME
-       FIRST_LINE_2="$(trace_first_line $TRACE_PATH/)"
+       lttng_snapshot_record "$SESSION_NAME"
+       FIRST_LINE_2="$(trace_first_line "$TRACE_PATH/")"
        diag "First line (2nd snapshot): $FIRST_LINE_2"
-       rm -rf $TRACE_PATH/
+       rm -rf "${TRACE_PATH:?}/"
 
        if [ x"$FIRST_LINE" != x"$FIRST_LINE_2" ]; then
                pass "First snapshot event do not match"
@@ -288,60 +287,74 @@ function test_ust_local_snapshot_small_overwrite_buffers ()
                fail "First snapshot event match"
        fi
 
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
-       taskset -p $OLDCPUSET $$ 1>/dev/null 2>&1
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
+       taskset -p "$OLDCPUSET" $$ 1>/dev/null 2>&1
 }
 
 function test_ust_local_snapshot_max_size ()
 {
-       NR_ITER=-1
-       NR_USEC_WAIT=100
-       page_size=`getconf PAGE_SIZE`
-       num_cpus=$(conf_proc_count)
+       local possible_cpus
+       local cpus_list
+       local subbuf_size
+       local subbuf_count
+       local snapshot_max_size
+       local channel_max_size_per_cpu
 
-       # The minimum subbuf size is the platform PAGE_SIZE
-       subbuf_size=$(($page_size*2))
+       IFS=" " read -r -a cpus_list <<< "$(get_online_cpus)"
 
-       # The minimum size limit is min(subbuf_size) * nb_streams
-       max_size=$(($subbuf_size*$num_cpus))
+       possible_cpus=$(get_possible_cpus_count)
+       subbuf_size=$(getconf PAGE_SIZE)
+       subbuf_count=8
+       snapshot_max_size=$((subbuf_size*possible_cpus))
+       channel_max_size_per_cpu=$((subbuf_size*subbuf_count))
 
        diag "Test local UST snapshots with max size $max_size"
-       create_lttng_session_no_output $SESSION_NAME
+       create_lttng_session_no_output "$SESSION_NAME"
 
-       enable_mmap_overwrite_subbuf_ust_channel $SESSION_NAME $CHANNEL_NAME $subbuf_size
+       enable_mmap_overwrite_subbuf_ust_channel \
+               "$SESSION_NAME" "$CHANNEL_NAME" \
+               "$subbuf_size" "$subbuf_count"
 
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" "$EVENT_NAME" "$CHANNEL_NAME"
+       start_lttng_tracing_ok "$SESSION_NAME"
 
-       snapshot_add_output $SESSION_NAME "file://$TRACE_PATH" "" $max_size
+       snapshot_add_output "$SESSION_NAME" "file://$TRACE_PATH" "" "$snapshot_max_size"
 
-       # Returns once the application has at least fired ONE tracepoint.
-       start_test_app
+       # Fill all ring-buffers of the channel; assuming event size of at least one
+       # byte
+       for cpu in "${cpus_list[@]}";
+       do
+               diag "setting affinity to $cpu"
+               taskset --cpu-list "$cpu" "$TESTAPP_BIN" \
+                       --iter "$channel_max_size_per_cpu"
+       done
+       diag "Filled channel ring-buffers"
 
-       lttng_snapshot_record $SESSION_NAME
+       lttng_snapshot_record "$SESSION_NAME"
 
        # Check file size
-       sum_size_tracefiles=$(find $TRACE_PATH -name "${CHANNEL_NAME}_*" \
-               -exec stat -c '%s' {} \; | awk '{s = s + $1}END{print s}')
+       local snapshot_size
+       snapshot_size=$(find "$TRACE_PATH" -name "${CHANNEL_NAME}_*" \
+                               -exec stat -c '%s' {} \; | \
+                               awk '{s = s + $1}END{print s}')
 
-       if [ "$sum_size_tracefiles" -gt "$max_size" ]; then
-               fail "Tracefiles size sum validation"
-               diag "Tracefiles size sum: $sum_size_tracefiles Expected max: $max_size"
-       else
+       if [ "$snapshot_size" -eq "$snapshot_max_size" ]; then
                pass "Tracefiles size sum validation"
+       else
+               fail "Tracefiles size sum validation"
+               diag "Tracefiles size sum: $snapshot_size Expected max: $snapshot_max_size"
        fi
 
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/
 
-       if [ $? -eq 0 ]; then
+       if validate_trace "$EVENT_NAME" "$TRACE_PATH/"; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "$TRACE_PATH"
        fi
 
        stop_test_apps
@@ -355,23 +368,22 @@ function test_ust_local_snapshot_large_metadata ()
        LM_BIN="$LM_PATH/$LM_NAME/$LM_NAME"
 
        diag "Test local UST snapshots with > 4kB metadata"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $LM_EVENT $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $LM_EVENT $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
        $LM_BIN --iter 1 --wait 1
        ok $? "Start application to trace"
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" 0
-       validate_trace $LM_EVENT $TRACE_PATH/
-       if [ $? -eq 0 ]; then
+       if validate_trace $LM_EVENT "$TRACE_PATH/" ; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "${TRACE_PATH:?}/"
        fi
 }
 
@@ -380,7 +392,7 @@ function enable_channel_per_uid_mmap_overwrite()
        sess_name=$1
        channel_name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name --output mmap --overwrite >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" --output mmap --overwrite >/dev/null 2>&1
        ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
@@ -389,25 +401,24 @@ function test_ust_per_uid_local_snapshot ()
        NR_ITER=-1
        NR_USEC_WAIT=100
        diag "Test per-uid local UST snapshots"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_channel_per_uid_mmap_overwrite $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_channel_per_uid_mmap_overwrite "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Returns once the application has at least fired ONE tracepoint.
        start_test_app
 
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/
-       if [ $? -eq 0 ]; then
+       if validate_trace $EVENT_NAME "$TRACE_PATH/" ; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "${TRACE_PATH:?}/"
        fi
 
        stop_test_apps
@@ -419,26 +430,25 @@ function test_ust_per_uid_local_snapshot_post_mortem ()
        NR_USEC_WAIT=100
 
        diag "Test local UST snapshots post-mortem"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_channel_per_uid_mmap_overwrite $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_channel_per_uid_mmap_overwrite "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Returns once the application has at least fired ONE tracepoint.
        start_test_app
        stop_test_apps
 
-       lttng_snapshot_record $SESSION_NAME
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       lttng_snapshot_record "$SESSION_NAME"
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        # Validate test
        validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" 0
-       validate_trace $EVENT_NAME $TRACE_PATH/
-       if [ $? -eq 0 ]; then
+       if validate_trace $EVENT_NAME "$TRACE_PATH/" ; then
                # Only delete if successful
-               rm -rf $TRACE_PATH
+               rm -rf "${TRACE_PATH:?}/"
        fi
 }
 
@@ -448,29 +458,28 @@ function test_ust_local_snapshots ()
        NR_USEC_WAIT=100
 
        diag "Test $NR_SNAPSHOT local UST snapshots"
-       create_lttng_session_no_output $SESSION_NAME
-       enable_lttng_mmap_overwrite_ust_channel $SESSION_NAME $CHANNEL_NAME
-       enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME $CHANNEL_NAME
-       start_lttng_tracing_ok $SESSION_NAME
-       lttng_snapshot_add_output_ok $SESSION_NAME file://$TRACE_PATH
+       create_lttng_session_no_output "$SESSION_NAME"
+       enable_lttng_mmap_overwrite_ust_channel "$SESSION_NAME" $CHANNEL_NAME
+       enable_ust_lttng_event_ok "$SESSION_NAME" $EVENT_NAME $CHANNEL_NAME
+       start_lttng_tracing_ok "$SESSION_NAME"
+       lttng_snapshot_add_output_ok "$SESSION_NAME" "file://$TRACE_PATH"
 
        # Returns once the application has at least fired ONE tracepoint.
        start_test_app
 
-       for i in $(seq 1 $NR_SNAPSHOT); do
+       for i in $(seq 1 "$NR_SNAPSHOT"); do
                diag "Snapshot $i/$NR_SNAPSHOT"
-               rm -rf $TRACE_PATH/snapshot/* 2>/dev/null
-               lttng_snapshot_record $SESSION_NAME
+               rm -rf "$TRACE_PATH/snapshot/*" 2>/dev/null
+               lttng_snapshot_record "$SESSION_NAME"
                # Validate test
                validate_trace_path_ust_uid_snapshot "$TRACE_PATH" "" "snapshot-1" $((i - 1))
-               validate_trace $EVENT_NAME $TRACE_PATH/
-               if [ $? -eq 0 ]; then
+               if validate_trace $EVENT_NAME "$TRACE_PATH/" ; then
                        # Only delete if successful
-                       rm -rf $TRACE_PATH
+                       rm -rf "${TRACE_PATH:?}/"
                fi
        done
-       stop_lttng_tracing_ok $SESSION_NAME
-       destroy_lttng_session_ok $SESSION_NAME
+       stop_lttng_tracing_ok "$SESSION_NAME"
+       destroy_lttng_session_ok "$SESSION_NAME"
 
        stop_test_apps
 }
@@ -481,6 +490,7 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
+# shellcheck disable=SC2119
 start_lttng_sessiond
 tests=( test_ust_list_output
        test_ust_local_snapshot
@@ -493,10 +503,11 @@ tests=( test_ust_list_output
        test_ust_local_snapshot_small_overwrite_buffers
 )
 
-for fct_test in ${tests[@]};
+for fct_test in "${tests[@]}";
 do
        SESSION_NAME=$(randstring 16 0)
        ${fct_test}
 done
 
+# shellcheck disable=SC2119
 stop_lttng_sessiond
index cd97dc7769ce8ae19913d6f2df3cd923b8e12937..91ab2fe7b25e945d77eb4f6ba725a03eeea55aa4 100755 (executable)
@@ -7,10 +7,14 @@
 
 TEST_DESC="Streaming - High throughput with bandwidth limits"
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/../../..
+# The goal of this test is to try and catch races during tests in conditions
+# where bandwidth is quite limited. It is useful to have enough iterations and
+# apps so that there are dropped events.
+
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/../../.."
 NR_APP_ITER=10
-NR_ITER=1000000
+NR_ITER=5000
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
@@ -20,10 +24,11 @@ SESSIOND_CTRL_PORT=5342
 SESSIOND_DATA_PORT=5343
 DEFAULT_IF="lo"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_streaming_high_throughput_limits_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_streaming_high_throughput_limits_trace_path.XXXXXX)
 
-NUM_TESTS=104
+NUM_TESTS=39
 
+# shellcheck source-path=SCRIPTDIR/../../../
 source $TESTDIR/utils/utils.sh
 
 if [ ! -x "$TESTAPP_BIN" ]; then
@@ -48,40 +53,34 @@ function set_bw_limit
 
        diag "Set bandwidth limits to ${limit}kbits, ${ctrlportlimit} for control and ${dataportlimit} for data"
 
-       tc qdisc add dev $DEFAULT_IF root handle 1: htb default 15 >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc qdisc add dev $DEFAULT_IF root handle 1: htb default 15 >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
 
        # the total bandwidth is the limit set by the user
-       tc class add dev $DEFAULT_IF parent 1: classid 1:1 htb rate ${limit}kbit ceil ${limit}kbit >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc class add dev $DEFAULT_IF parent 1: classid 1:1 htb rate ${limit}kbit ceil ${limit}kbit >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
        # 1/10 of the bandwidth guaranteed and traffic prioritized for the control port
-       tc class add dev $DEFAULT_IF parent 1:1 classid 1:10 htb rate ${ctrlportlimit}kbit ceil ${limit}kbit prio 1 >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc class add dev $DEFAULT_IF parent 1:1 classid 1:10 htb rate ${ctrlportlimit}kbit ceil ${limit}kbit prio 1 >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
        # 9/10 of the bandwidth guaranteed and can borrow up to the total bandwidth (if unused)
-       tc class add dev $DEFAULT_IF parent 1:1 classid 1:11 htb rate ${dataportlimit}kbit ceil ${limit}kbit prio 2 >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc class add dev $DEFAULT_IF parent 1:1 classid 1:11 htb rate ${dataportlimit}kbit ceil ${limit}kbit prio 2 >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
 
        # filter to assign control traffic to the 1:10 class
-       tc filter add dev $DEFAULT_IF parent 1: protocol ip u32 match ip dport $SESSIOND_CTRL_PORT 0xffff flowid 1:10 >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc filter add dev $DEFAULT_IF parent 1: protocol ip u32 match ip dport $SESSIOND_CTRL_PORT 0xffff flowid 1:10 >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
        # filter to assign data traffic to the 1:11 class
-       tc filter add dev $DEFAULT_IF parent 1: protocol ip u32 match ip dport $SESSIOND_DATA_PORT 0xffff flowid 1:11 >/dev/null 2>&1
-       if [ $? -ne 0 ]; then
+       if ! tc filter add dev $DEFAULT_IF parent 1: protocol ip u32 match ip dport $SESSIOND_DATA_PORT 0xffff flowid 1:11 >/dev/null 2>&1 ; then
                reset_bw_limit
                return 1
        fi
@@ -94,18 +93,18 @@ function create_lttng_session_with_uri
        sess_name=$1
        uri=$2
        # Create session with custom URI
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN create -U $uri $sess_name >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" create -U "$uri" "$sess_name" >/dev/null 2>&1
        ok $? "Create session with uri $uri"
 }
 
 function run_apps
 {
-       for i in `seq 1 $NR_APP_ITER`; do
+       for i in $(seq 1 $NR_APP_ITER); do
                # With bandwidth limitation, unfortunately, application easily timeout
                # due to very slow communication between the consumer and relayd making
                # the status reply from the consumer quite slow thus delaying the
                # registration done message.
-               LTTNG_UST_REGISTER_TIMEOUT=-1 $TESTAPP_BIN -i $NR_ITER & >/dev/null 2>&1
+               LTTNG_UST_REGISTER_TIMEOUT=-1 $TESTAPP_BIN -i "$NR_ITER" >/dev/null 2>&1 &
        done
 }
 
@@ -126,23 +125,26 @@ function test_high_throughput
 
 function validate_event_count
 {
-       TEMP_FILE=$(mktemp --tmpdir tmp.streaming_high_throughput_limit_file1.XXXXXX)
-       TEMP_FILE_2=$(mktemp --tmpdir tmp.streaming_high_throughput_limit_file2.XXXXXX)
+       TEMP_FILE=$(mktemp -t tmp.streaming_high_throughput_limit_file1.XXXXXX)
+       TEMP_FILE_2=$(mktemp -t tmp.streaming_high_throughput_limit_file2.XXXXXX)
 
-       traced=$("$BABELTRACE_BIN" $TRACE_PATH 2>/dev/null | wc -l)
-       "$BABELTRACE_BIN" $TRACE_PATH >/dev/null 2>$TEMP_FILE_2
+       traced=$("$BABELTRACE_BIN" "$TRACE_PATH" 2>/dev/null | wc -l)
+       "$BABELTRACE_BIN" "$TRACE_PATH" >/dev/null 2>"$TEMP_FILE_2"
 
-       cat $TEMP_FILE_2 | cut -f4 -d " " >$TEMP_FILE
+       cat "$TEMP_FILE_2" | cut -f4 -d " " >"$TEMP_FILE"
 
        dropped=0
-       while read line;
-       do
-               let dropped=$dropped+$line
-       done < $TEMP_FILE
+       while read -r line; do
+               dropped=$(( dropped + line ))
+       done < "$TEMP_FILE"
 
-       let total=$dropped+$traced
-       let wanted=$NR_APP_ITER*$NR_ITER
+       total=$(( dropped + traced ))
+       wanted=$(( NR_APP_ITER * NR_ITER ))
 
+       if [ $dropped -le 0 ]; then
+               diag "No dropped events during test, consider increasing the number of " \
+                        "apps or iterations"
+       fi
        if [ $wanted -ne $total ]; then
                fail "Validate trace event count"
                diag "Expected $wanted. Dropped $dropped. Recorded $traced. Total $total... "
@@ -151,8 +153,8 @@ function validate_event_count
                pass "Validate trace event count"
                diag "Expected $wanted. Dropped $dropped. Recorded $traced. Total $total... "
 
-               rm -rf $TRACE_PATH
-               rm $TEMP_FILE $TEMP_FILE_2
+               rm -rf "$TRACE_PATH"
+               rm "$TEMP_FILE" "$TEMP_FILE_2"
 
                return 0
        fi
@@ -172,31 +174,28 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed to set bandwith limits. Skipping all tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
 
        # Catch sigint and try to cleanup limits
        trap interrupt_cleanup SIGTERM SIGINT
 
-       BW_LIMITS=(3200 1600 800 400 200 100 50 25)
-       for BW in ${BW_LIMITS[@]};
+       BW_LIMITS=(3200 400 100)
+       for BW in "${BW_LIMITS[@]}";
        do
                diag "Test high-throughput with bandwidth limit set to ${BW}kbits"
 
-               set_bw_limit $BW
+               set_bw_limit "$BW"
                ok $? "Setting bandwidth limit"
 
+               # shellcheck disable=SC2119
                start_lttng_sessiond
                start_lttng_relayd "-o $TRACE_PATH"
                test_high_throughput
                result=$?
+               # shellcheck disable=SC2119
                stop_lttng_relayd
+               # shellcheck disable=SC2119
                stop_lttng_sessiond
                reset_bw_limit
                ok $? "Reset bandwith limits"
index 33334229f4840ef06ff8d375e2a2f0f72810ccc5..3c78ac50bf5283fa9d9433fee3039efd895d8826 100755 (executable)
@@ -11,7 +11,7 @@ TESTDIR=$CURDIR/../../..
 EVENT_NAME="sched_switch"
 SESSION_NAME=""
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_streaming_kernel_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_streaming_kernel_trace_path.XXXXXX)
 
 NUM_TESTS=11
 
@@ -47,13 +47,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel streaming tests." $NUM_TESTS ||
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." ||
 {
        validate_lttng_modules_present
 
index b88e945f8e0cd43da0abc938a3239123ae7d99ed..27f6b679bc551abc8fdfa92677bc63b3031e4cd0 100755 (executable)
@@ -16,7 +16,7 @@ TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="stream"
 EVENT_NAME="tp:tptest"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_streaming_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_streaming_ust_trace_path.XXXXXX)
 
 NUM_TESTS=18
 
@@ -30,7 +30,7 @@ fi
 
 function test_ust_before_start ()
 {
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.test_${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.test_${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test UST streaming BEFORE tracing starts"
        create_lttng_session_uri $SESSION_NAME net://localhost
@@ -53,7 +53,7 @@ function test_ust_before_start ()
 
 function test_ust_after_start ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.test_${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.test_${FUNCNAME[0]}_sync_after_first.XXXXXX")
 
        diag "Test UST streaming AFTER tracing starts"
        create_lttng_session_uri $SESSION_NAME net://localhost
index 5f114af044e25b696907b832b5aa427f65d5ce17..9253d3ec2fcc0afdb2b6abe7320bb6f086b51ed7 100755 (executable)
@@ -9,12 +9,12 @@ TEST_DESC="Tracefile count limits"
 
 CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../..
+BT2_PLUGINS_DIR="${TESTDIR}/utils/bt2_plugins"
 
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 
-STATS_BIN="$TESTDIR/utils/babelstats.pl"
 NUM_TESTS=74
 
 PAGE_SIZE=$(getconf PAGE_SIZE)
@@ -22,30 +22,15 @@ TRACEFILE_SIZE=$PAGE_SIZE
 
 source "$TESTDIR"/utils/utils.sh
 
-NUM_CPUS=$(conf_proc_count)
-
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST events binary detected."
 fi
 
 function pick_random_cpuid ()
 {
-        local cpuid=0
-
-        # On Linux pick a random available cpuid from sysfs
-        if [ -d "/sys/devices/system/cpu" ]; then
-                local cpuids=()
-
-                for i in /sys/devices/system/cpu/cpu[0-9]*; do
-                        cpuids+=("${i#/sys/devices/system/cpu/cpu}")
-                done
-
-                cpuid=${cpuids[ $RANDOM % ${#cpuids[@]} ]}
-        else
-                cpuid=$((RANDOM % NUM_CPUS))
-        fi
-
-        echo $cpuid
+       local cpuids
+       read -r -a cpuids <<< "$(get_online_cpus)"
+       echo "${cpuids[ $RANDOM % ${#cpuids[@]} ]}"
 }
 
 function enable_lttng_channel_count_limit ()
@@ -111,7 +96,7 @@ function test_tracefile_count_limit ()
        local session_name
        local stream_pattern=".*${channel_name}_${cpuno}_[0-9]*"
        local stream_size=0
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        session_name=$(randstring 16 0)
 
@@ -155,7 +140,7 @@ function test_tracefile_count_limit ()
        [ "$(get_stream_file_count "$trace_path" "$stream_pattern")" -eq "$count_limit" ]
        ok $? "Stream meets the trace file limit of $count_limit"
 
-       stats=`"$BABELTRACE_BIN" $trace_path | $STATS_BIN --tracepoint $event_name`
+       stats=$("$BABELTRACE_BIN" --plugin-path "${BT2_PLUGINS_DIR}" convert $trace_path -c filter.lttngtest.event_name -p "names=[\"${event_name}\"]" -c sink.lttngtest.field_stats)
 
        validate_min_max "$stats" "intfield" "[0-9]+" "$expected_max"
        ok $? "Trace validation - intfield"
index 5d9f21b604de63f20b08d974e282356ca94bb246..489e68510f299a7cbe34e91a78ea7461da8b874e 100755 (executable)
@@ -85,7 +85,7 @@ function check_file_size ()
 function test_tracefile_size_limit ()
 {
        local size_limit="$1"
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        local session_name=$(randstring 16 0)
        local channel_name="channel"
        local event_name="tp:tptest"
@@ -125,7 +125,7 @@ function test_tracefile_size_limit_pagesize ()
 {
        # Set a size limit lower than the page_size
        local size_limit="$(($PAGE_SIZE-2))"
-       local trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       local trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        local session_name=$(randstring 16 0)
        local channel_name="channel"
        local event_name="tp:tptest"
index deecb8f8072ab7969a6608962781842c6e635ee4..2507498bfb452aa301653650152f0adf2119d8a0 100755 (executable)
@@ -40,8 +40,8 @@ source $TESTDIR/utils/utils.sh
 # untracking on an active app.
 function prepare_ust_app
 {
-       TOUCH_BEFORE_LAST_PATH=$(mktemp --tmpdir -u tmp.${FUNCNAME[0]}_touch_before_last.XXXXXX)
-       SYNC_BEFORE_LAST_PATH=$(mktemp --tmpdir -u tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX)
+       TOUCH_BEFORE_LAST_PATH=$(mktemp -u -t tmp.${FUNCNAME[0]}_touch_before_last.XXXXXX)
+       SYNC_BEFORE_LAST_PATH=$(mktemp -u -t tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX)
 
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT \
                --sync-before-last-event-touch "$TOUCH_BEFORE_LAST_PATH" \
@@ -52,7 +52,7 @@ function prepare_ust_app
        # Wait for the app to execute all the way to right before the last
        # event.
        while [ ! -f "${TOUCH_BEFORE_LAST_PATH}" ]; do
-               sleep 0.5
+               sleep 0.01
        done
 }
 
@@ -69,7 +69,7 @@ function trace_ust_app
 
 function prepare_kernel_app
 {
-       WAIT_PATH=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_wait_path.XXXXXX")
+       WAIT_PATH=$(mktemp -u -t "tmp.${FUNCNAME[0]}_wait_path.XXXXXX")
 
        "$TESTAPP_KERNEL_BIN" "$WAIT_PATH" $NR_ITER &
        CHILD_PID=$!
@@ -94,7 +94,7 @@ function test_event_tracker()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -114,7 +114,7 @@ function test_event_tracker()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                trace_matches "$EVENT_NAME" $NR_ITER "$trace_path"
@@ -135,7 +135,7 @@ function test_event_vpid_tracker()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -159,7 +159,7 @@ function test_event_vpid_tracker()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                validate_trace "$EVENT_NAME" "$trace_path"
@@ -180,7 +180,7 @@ function test_event_pid_tracker()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -204,7 +204,7 @@ function test_event_pid_tracker()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                validate_trace "$EVENT_NAME" "$trace_path"
@@ -225,12 +225,12 @@ function test_event_tracker_fail()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
        enable_"$domain"_lttng_event_ok $SESSION_NAME "$wildcard"
        lttng_track_"$domain"_fail "${tracker}"
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        rm -rf "$trace_path"
 }
@@ -246,7 +246,7 @@ function test_event_track_untrack()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -267,7 +267,7 @@ function test_event_track_untrack()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                trace_matches "$EVENT_NAME" $NR_ITER "$trace_path"
@@ -288,7 +288,7 @@ function test_event_vpid_track_untrack()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -309,7 +309,7 @@ function test_event_vpid_track_untrack()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                validate_trace "$EVENT_NAME" "$trace_path"
@@ -330,7 +330,7 @@ function test_event_pid_track_untrack()
 
        diag "${FUNCNAME[0]} $*"
 
-       trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path"
 
@@ -351,7 +351,7 @@ function test_event_pid_track_untrack()
        trace_"$domain"_app
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        if [ "$expect_event" -eq 1 ]; then
                validate_trace "$EVENT_NAME" "$trace_path"
@@ -366,7 +366,7 @@ function test_event_ust_vpid_untrack_snapshot()
 {
        diag "${FUNCNAME[0]} $*"
 
-       local trace_path=$(mktemp --tmpdir -d tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
+       local trace_path=$(mktemp -d -t tmp.${FUNCNAME[0]}_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME "$trace_path" "--snapshot"
 
@@ -382,7 +382,7 @@ function test_event_ust_vpid_untrack_snapshot()
        lttng_snapshot_record $SESSION_NAME
 
        stop_lttng_tracing_ok
-       destroy_lttng_session_ok $SESSION_NAME
+       destroy_lttng_session_ok $SESSION_NAME --no-wait
 
        snapshot_count=$(find "$trace_path" -name metadata | wc -l)
        is "$snapshot_count" 0 "Number of snapshot is zero"
@@ -468,13 +468,7 @@ test_event_track_untrack ust 0 "${EVENT_NAME}" "--pid --all"       # backward compat
 test_event_tracker ust 1 "${EVENT_NAME}" "--pid --all" # backward compat
 test_event_pid_tracker ust 1 "${EVENT_NAME}"
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel tracker tests." $NUM_KERNEL_TESTS ||
+check_skip_kernel_test "$NUM_KERNEL_TESTS" "Skipping kernel tracker tests." ||
 {
        diag "Test kernel tracker"
 
@@ -565,6 +559,19 @@ skip $isroot "Root access is needed. Skipping all kernel tracker tests." $NUM_KE
        test_event_tracker kernel 1 "${EVENT_NAME}" "--pid --all"
        test_event_pid_tracker kernel 1 "${EVENT_NAME}"
 
+       # When using session destroy with '--no-wait', the quick
+       # exit at the end means that the lttng-test modules is
+       # still marked as being in use and 'modprobe --remove' fails.
+       #
+       # It is possible to work around the issue by not setting
+       # '--no-wait' on the last kernel test, but it seems like
+       # an easy detail to forget about.
+       #
+       # The sleep here gives the system a small amount of time to
+       # finish wrapping up the session that had the lttng-test kernel
+       # module loaded.
+       sleep 1
+
        modprobe --remove lttng-test
        ok $? "Unloading lttng-test module"
 }
index 969cab11eabb05050d1d96f80929f88516367d19..a7d0d149d45cf8014d64f20c30a672afbc8ccecd 100644 (file)
@@ -9,29 +9,28 @@
  *
  */
 
+#include <common/macros.hpp>
+
+#include <lttng/lttng.h>
+
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-
 #include <tap/tap.h>
-
-#include <common/macros.hpp>
-#include <lttng/lttng.h>
+#include <unistd.h>
 
 #define TEST_COUNT 1
 
 #define TEST_SESSION_NAME "test_session"
 #define TEST_CHANNEL_NAME "test_channel"
 
-static
-int get_registered_triggers_count(void)
+static int get_registered_triggers_count()
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_trigger_status trigger_status;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count;
 
        ret_code = lttng_list_triggers(&triggers);
@@ -55,24 +54,21 @@ end:
        return ret;
 }
 
-static
-int setup_session_with_size_rotation_schedule(const char *session_output_path)
+static int setup_session_with_size_rotation_schedule(const char *session_output_path)
 {
        int ret;
-       struct lttng_session_descriptor *session_desriptor = NULL;
+       struct lttng_session_descriptor *session_desriptor = nullptr;
        enum lttng_error_code ret_code;
-       struct lttng_handle ust_channel_handle = {
-               TEST_SESSION_NAME,
-               {
-                       .type = LTTNG_DOMAIN_UST,
-                       .buf_type = LTTNG_BUFFER_PER_UID,
-                       .padding = {},
-                       .attr = {},
-               },
-               {}
-       };
-
-       lttng_channel channel_cfg {};
+       struct lttng_handle ust_channel_handle = { TEST_SESSION_NAME,
+                                                  {
+                                                          .type = LTTNG_DOMAIN_UST,
+                                                          .buf_type = LTTNG_BUFFER_PER_UID,
+                                                          .padding = {},
+                                                          .attr = {},
+                                                  },
+                                                  {} };
+
+       lttng_channel channel_cfg{};
        strcpy(channel_cfg.name, TEST_CHANNEL_NAME);
        channel_cfg.enabled = 1;
        channel_cfg.attr.overwrite = -1;
@@ -81,37 +77,35 @@ int setup_session_with_size_rotation_schedule(const char *session_output_path)
        channel_cfg.attr.output = LTTNG_EVENT_MMAP;
 
        enum lttng_rotation_status rotation_status;
-       struct lttng_rotation_schedule *rotation_schedule = NULL;
+       struct lttng_rotation_schedule *rotation_schedule = nullptr;
 
-       session_desriptor = lttng_session_descriptor_local_create(
-                       TEST_SESSION_NAME, session_output_path);
+       session_desriptor =
+               lttng_session_descriptor_local_create(TEST_SESSION_NAME, session_output_path);
        if (!session_desriptor) {
-               fail("Failed to create session descriptor for session `%s`",
-                               TEST_SESSION_NAME);
+               fail("Failed to create session descriptor for session `%s`", TEST_SESSION_NAME);
                ret = -1;
                goto end;
        }
 
        ret_code = lttng_create_session_ext(session_desriptor);
        if (ret_code != LTTNG_OK) {
-               fail("Failed to create session `%s`: %s", TEST_SESSION_NAME,
-                               lttng_strerror(-ret_code));
+               fail("Failed to create session `%s`: %s",
+                    TEST_SESSION_NAME,
+                    lttng_strerror(-ret_code));
                ret = -1;
                goto end;
        }
 
        ret = lttng_enable_channel(&ust_channel_handle, &channel_cfg);
        if (ret) {
-               fail("Failed to enable channel `%s`: %s", TEST_CHANNEL_NAME,
-                               lttng_strerror(ret));
+               fail("Failed to enable channel `%s`: %s", TEST_CHANNEL_NAME, lttng_strerror(ret));
                ret = -1;
                goto end;
        }
 
        ret = lttng_start_tracing(TEST_SESSION_NAME);
        if (ret) {
-               fail("Failed to start session `%s`: %s", TEST_SESSION_NAME,
-                               lttng_strerror(ret));
+               fail("Failed to start session `%s`: %s", TEST_SESSION_NAME, lttng_strerror(ret));
                ret = -1;
                goto end;
        }
@@ -129,18 +123,17 @@ int setup_session_with_size_rotation_schedule(const char *session_output_path)
         * time.
         */
        rotation_status = lttng_rotation_schedule_size_threshold_set_threshold(
-                       rotation_schedule, sysconf(_SC_PAGE_SIZE) * 4096);
+               rotation_schedule, sysconf(_SC_PAGE_SIZE) * 4096);
        if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
                fail("Failed to set size threshold of session rotation schedule");
                ret = -1;
                goto end;
        }
 
-       rotation_status = lttng_session_add_rotation_schedule(
-                       TEST_SESSION_NAME, rotation_schedule);
+       rotation_status = lttng_session_add_rotation_schedule(TEST_SESSION_NAME, rotation_schedule);
        if (rotation_status != LTTNG_ROTATION_STATUS_OK) {
                fail("Failed to set size-based rotation schedule on session `%s`",
-                               TEST_SESSION_NAME);
+                    TEST_SESSION_NAME);
                ret = -1;
                goto end;
        }
@@ -174,7 +167,7 @@ int main(int argc, const char **argv)
        }
 
        ok(get_registered_triggers_count() == 0,
-                       "No triggers visible while session has an enabled size-based rotation schedule");
+          "No triggers visible while session has an enabled size-based rotation schedule");
 
        ret = lttng_destroy_session(TEST_SESSION_NAME);
        if (ret) {
index 0adce61eb55fa416be6b3109a8d4f42438ed923b..75387f3fc11197c0738590ea564db4297b1ad1a1 100755 (executable)
@@ -8,7 +8,7 @@ TEST_DESC="Triggers - Hidden internal triggers"
 
 CURDIR=$(dirname "$0")/
 TESTDIR=${CURDIR}/../../../..
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_trigger_hidden.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_trigger_hidden.XXXXXX)
 
 # shellcheck source=../../../../utils/utils.sh
 source "$TESTDIR/utils/utils.sh"
index 1e2a676dc4000003eec31a6eccb2736ff5d2c42f..b878af48639771979821777821aec3df4548183e 100644 (file)
@@ -9,13 +9,15 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <tap/tap.h>
+#include <common/macros.hpp>
+
+#include <lttng/lttng.h>
+
 #include <stdint.h>
+#include <stdio.h>
 #include <string.h>
-#include <lttng/lttng.h>
-#include <common/macros.hpp>
+#include <tap/tap.h>
+#include <unistd.h>
 
 #define TEST_COUNT 70
 
@@ -24,10 +26,9 @@ enum unregistration_trigger_instance {
        UNREGISTRATION_TRIGGER_INSTANCE_FROM_LISTING,
 };
 
-typedef void (*test_function)(enum unregistration_trigger_instance);
+using test_function = void (*)(enum unregistration_trigger_instance);
 
-static
-const char *get_trigger_name(const struct lttng_trigger *trigger)
+static const char *get_trigger_name(const struct lttng_trigger *trigger)
 {
        const char *trigger_name;
        enum lttng_trigger_status trigger_status;
@@ -47,9 +48,8 @@ const char *get_trigger_name(const struct lttng_trigger *trigger)
        return trigger_name;
 }
 
-static
-const char *unregistration_trigger_instance_name(
-               enum unregistration_trigger_instance unregistration_trigger)
+static const char *
+unregistration_trigger_instance_name(enum unregistration_trigger_instance unregistration_trigger)
 {
        const char *name;
 
@@ -71,13 +71,12 @@ const char *unregistration_trigger_instance_name(
  * Returns a negative error code on error, else the number of unregistered
  * triggers.
  */
-static
-int unregister_all_triggers(void)
+static int unregister_all_triggers()
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_trigger_status trigger_status;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count, i, unregistered_trigger_count = 0;
 
        ret_code = lttng_list_triggers(&triggers);
@@ -123,13 +122,12 @@ end:
        return ret;
 }
 
-static
-int get_registered_triggers_count(void)
+static int get_registered_triggers_count()
 {
        int ret;
        enum lttng_error_code ret_code;
        enum lttng_trigger_status trigger_status;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count;
 
        ret_code = lttng_list_triggers(&triggers);
@@ -157,14 +155,13 @@ end:
  * Create a generic trigger. The specifics of the condition and action are not
  * important for the purposes of this test.
  */
-static
-struct lttng_trigger *create_trigger(uint64_t threshold)
+static struct lttng_trigger *create_trigger(uint64_t threshold)
 {
-       struct lttng_condition *condition = NULL;
-       struct lttng_action *action = NULL;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_action *action = nullptr;
+       struct lttng_trigger *trigger = nullptr;
        enum lttng_condition_status condition_status;
-       const char * const session_name = "test session";
+       const char *const session_name = "test session";
 
        condition = lttng_condition_session_consumed_size_create();
        if (!condition) {
@@ -172,14 +169,15 @@ struct lttng_trigger *create_trigger(uint64_t threshold)
                goto end;
        }
 
-       condition_status = lttng_condition_session_consumed_size_set_session_name(condition, session_name);
+       condition_status =
+               lttng_condition_session_consumed_size_set_session_name(condition, session_name);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                fail("Failed to set session name on 'session consumed size' condition");
                goto end;
        }
 
-       condition_status = lttng_condition_session_consumed_size_set_threshold(
-                       condition, threshold);
+       condition_status =
+               lttng_condition_session_consumed_size_set_threshold(condition, threshold);
        if (condition_status != LTTNG_CONDITION_STATUS_OK) {
                fail("Failed to set threshold on 'session consumed size' condition");
                goto end;
@@ -203,21 +201,18 @@ end:
        return trigger;
 }
 
-static
-void register_anonymous_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void register_anonymous_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger = create_trigger(0xbadc0ffee);
        enum lttng_trigger_status trigger_status;
        const char *trigger_name;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count, i;
        enum lttng_error_code ret_code;
 
        diag("Register an anonymous trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger) {
                fail("Failed to create trigger");
@@ -229,8 +224,8 @@ void register_anonymous_trigger(
 
        trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
        ok(trigger_status == LTTNG_TRIGGER_STATUS_UNSET,
-                       "Anonymous trigger name remains unset after registration: trigger name = '%s'",
-                       get_trigger_name(trigger));
+          "Anonymous trigger name remains unset after registration: trigger name = '%s'",
+          get_trigger_name(trigger));
 
        ret_code = lttng_list_triggers(&triggers);
        if (ret_code != LTTNG_OK) {
@@ -256,18 +251,20 @@ void register_anonymous_trigger(
 
                trigger_status = lttng_trigger_get_name(trigger_from_listing, &trigger_name);
                ok(trigger_status == LTTNG_TRIGGER_STATUS_UNSET,
-                               "Anonymous trigger returned by listing has an unset name: trigger name = '%s'",
-                               get_trigger_name(trigger_from_listing));
+                  "Anonymous trigger returned by listing has an unset name: trigger name = '%s'",
+                  get_trigger_name(trigger_from_listing));
 
                if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_FROM_LISTING) {
                        ret = lttng_unregister_trigger(trigger_from_listing);
-                       ok(ret == 0, "Successfully unregistered anonymous trigger using the trigger instance returned by the listing");
+                       ok(ret == 0,
+                          "Successfully unregistered anonymous trigger using the trigger instance returned by the listing");
                }
        }
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger);
-               ok(ret == 0, "Successfully unregistered anonymous trigger using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered anonymous trigger using the trigger instance used on registration");
        }
 
 end:
@@ -275,22 +272,19 @@ end:
        lttng_trigger_destroy(trigger);
 }
 
-static
-void register_named_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void register_named_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger = create_trigger(0xbadc0ffee);
        enum lttng_trigger_status trigger_status;
        const char *returned_trigger_name;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count, i;
        enum lttng_error_code ret_code;
-       const char * const trigger_name = "some name that is hopefully unique";
+       const char *const trigger_name = "some name that is hopefully unique";
 
        diag("Register a named trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger) {
                fail("Failed to create trigger");
@@ -298,16 +292,17 @@ void register_named_trigger(
        }
 
        ret_code = lttng_register_trigger_with_name(trigger, trigger_name);
-       ok(ret_code == LTTNG_OK, "Registered trigger with name: trigger name = '%s'",
-                       get_trigger_name(trigger));
+       ok(ret_code == LTTNG_OK,
+          "Registered trigger with name: trigger name = '%s'",
+          get_trigger_name(trigger));
 
        trigger_status = lttng_trigger_get_name(trigger, &returned_trigger_name);
        ok(trigger_status == LTTNG_TRIGGER_STATUS_OK,
-                       "Trigger name is set after registration: trigger name = '%s'",
-                       get_trigger_name(trigger));
+          "Trigger name is set after registration: trigger name = '%s'",
+          get_trigger_name(trigger));
 
        ok(!strcmp(get_trigger_name(trigger), trigger_name),
-                       "Name set on trigger after registration is correct");
+          "Name set on trigger after registration is correct");
 
        ret_code = lttng_list_triggers(&triggers);
        if (ret_code != LTTNG_OK) {
@@ -331,26 +326,28 @@ void register_named_trigger(
                trigger_from_listing = lttng_triggers_get_at_index(triggers, i);
                LTTNG_ASSERT(trigger_from_listing);
 
-               trigger_status = lttng_trigger_get_name(trigger_from_listing, &returned_trigger_name);
+               trigger_status =
+                       lttng_trigger_get_name(trigger_from_listing, &returned_trigger_name);
                ok(trigger_status == LTTNG_TRIGGER_STATUS_OK,
-                               "Trigger returned by listing has a name: trigger name = '%s'",
-                               get_trigger_name(trigger_from_listing));
+                  "Trigger returned by listing has a name: trigger name = '%s'",
+                  get_trigger_name(trigger_from_listing));
 
-               ok(!strcmp(get_trigger_name(trigger_from_listing),
-                               trigger_name),
-                               "Name set on trigger returned from listing is correct: name returned from listing = '%s', expected name = '%s'",
-                               get_trigger_name(trigger_from_listing),
-                               trigger_name);
+               ok(!strcmp(get_trigger_name(trigger_from_listing), trigger_name),
+                  "Name set on trigger returned from listing is correct: name returned from listing = '%s', expected name = '%s'",
+                  get_trigger_name(trigger_from_listing),
+                  trigger_name);
 
                if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_FROM_LISTING) {
                        ret = lttng_unregister_trigger(trigger_from_listing);
-                       ok(ret == 0, "Successfully unregistered named trigger using the trigger instance returned by the listing");
+                       ok(ret == 0,
+                          "Successfully unregistered named trigger using the trigger instance returned by the listing");
                }
        }
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger);
-               ok(ret == 0, "Successfully unregistered named trigger using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered named trigger using the trigger instance used on registration");
        }
 
 end:
@@ -358,21 +355,19 @@ end:
        lttng_trigger_destroy(trigger);
 }
 
-static
-void register_automatic_name_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void
+register_automatic_name_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger = create_trigger(0xbadc0ffee);
        enum lttng_trigger_status trigger_status;
        const char *returned_trigger_name;
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        unsigned int trigger_count, i;
        enum lttng_error_code ret_code;
 
        diag("Register an automatic name trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger) {
                fail("Failed to create trigger");
@@ -384,11 +379,11 @@ void register_automatic_name_trigger(
 
        trigger_status = lttng_trigger_get_name(trigger, &returned_trigger_name);
        ok(trigger_status == LTTNG_TRIGGER_STATUS_OK,
-                       "Trigger name is set after registration: trigger name = '%s'",
-                       get_trigger_name(trigger));
+          "Trigger name is set after registration: trigger name = '%s'",
+          get_trigger_name(trigger));
 
        ok(returned_trigger_name && strlen(returned_trigger_name) > 0,
-                       "Automatic name set on trigger after registration longer is not an empty string");
+          "Automatic name set on trigger after registration longer is not an empty string");
 
        ret_code = lttng_list_triggers(&triggers);
        if (ret_code != LTTNG_OK) {
@@ -412,20 +407,23 @@ void register_automatic_name_trigger(
                trigger_from_listing = lttng_triggers_get_at_index(triggers, i);
                LTTNG_ASSERT(trigger_from_listing);
 
-               trigger_status = lttng_trigger_get_name(trigger_from_listing, &returned_trigger_name);
+               trigger_status =
+                       lttng_trigger_get_name(trigger_from_listing, &returned_trigger_name);
                ok(trigger_status == LTTNG_TRIGGER_STATUS_OK,
-                               "Trigger returned by listing has a name: trigger name = '%s'",
-                               get_trigger_name(trigger_from_listing));
+                  "Trigger returned by listing has a name: trigger name = '%s'",
+                  get_trigger_name(trigger_from_listing));
 
                if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_FROM_LISTING) {
                        ret = lttng_unregister_trigger(trigger_from_listing);
-                       ok(ret == 0, "Successfully unregistered automatic name trigger using the trigger instance returned by the listing");
+                       ok(ret == 0,
+                          "Successfully unregistered automatic name trigger using the trigger instance returned by the listing");
                }
        }
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger);
-               ok(ret == 0, "Successfully unregistered automatic trigger using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered automatic trigger using the trigger instance used on registration");
        }
 
 end:
@@ -433,17 +431,15 @@ end:
        lttng_trigger_destroy(trigger);
 }
 
-static
-void double_register_anonymous_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void
+double_register_anonymous_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger = create_trigger(0xbadc0ffee);
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
 
        diag("Register duplicate anonymous trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger) {
                fail("Failed to create trigger");
@@ -455,17 +451,16 @@ void double_register_anonymous_trigger(
 
        ret = lttng_register_trigger(trigger);
        ok(ret == -LTTNG_ERR_TRIGGER_EXISTS,
-                       "Registering identical anonymous trigger fails with `LTTNG_ERR_TRIGGER_EXISTS`");
-
+          "Registering identical anonymous trigger fails with `LTTNG_ERR_TRIGGER_EXISTS`");
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger);
-               ok(ret == 0, "Successfully unregistered anonymous trigger using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered anonymous trigger using the trigger instance used on registration");
        } else {
-               ok(get_registered_triggers_count() == 1,
-                               "Trigger listing returns 1 trigger");
+               ok(get_registered_triggers_count() == 1, "Trigger listing returns 1 trigger");
                ok(unregister_all_triggers() == 1,
-                               "Successfully unregistered anonymous trigger using the trigger instance returned by the listing");
+                  "Successfully unregistered anonymous trigger using the trigger instance returned by the listing");
        }
 
 end:
@@ -473,20 +468,18 @@ end:
        lttng_trigger_destroy(trigger);
 }
 
-static
-void double_register_named_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void
+double_register_named_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger_a = create_trigger(0xbadc0ffee);
        struct lttng_trigger *trigger_b = create_trigger(0xbadc0ffee);
-       struct lttng_triggers *triggers = NULL;
-       const char * const trigger_name = "a unique trigger name";
+       struct lttng_triggers *triggers = nullptr;
+       const char *const trigger_name = "a unique trigger name";
        enum lttng_error_code ret_code;
 
        diag("Register duplicate named trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger_a || !trigger_b) {
                fail("Failed to create triggers");
@@ -498,27 +491,28 @@ void double_register_named_trigger(
 
        ret = lttng_register_trigger(trigger_a);
        ok(ret == -LTTNG_ERR_INVALID,
-                       "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (anonymous registration)");
+          "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (anonymous registration)");
 
        ret_code = lttng_register_trigger_with_name(trigger_a, trigger_name);
        ok(ret_code == LTTNG_ERR_INVALID,
-                       "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (register with name)");
+          "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (register with name)");
 
        ret_code = lttng_register_trigger_with_automatic_name(trigger_a);
        ok(ret_code == LTTNG_ERR_INVALID,
-                       "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (register with automatic name)");
+          "Registering a trigger instance already used for registration fails with `LTTNG_ERR_INVALID` (register with automatic name)");
 
        ret_code = lttng_register_trigger_with_name(trigger_b, trigger_name);
-       ok(ret_code == LTTNG_ERR_TRIGGER_EXISTS, "Registering trigger with an already used name fails with `LTTNG_ERR_TRIGGER_EXISTS`");
+       ok(ret_code == LTTNG_ERR_TRIGGER_EXISTS,
+          "Registering trigger with an already used name fails with `LTTNG_ERR_TRIGGER_EXISTS`");
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger_a);
-               ok(ret == 0, "Successfully unregistered named trigger using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered named trigger using the trigger instance used on registration");
        } else {
-               ok(get_registered_triggers_count() == 1,
-                               "Trigger listing returns 1 trigger");
+               ok(get_registered_triggers_count() == 1, "Trigger listing returns 1 trigger");
                ok(unregister_all_triggers() == 1,
-                               "Successfully unregistered named trigger using the trigger instance returned by the listing");
+                  "Successfully unregistered named trigger using the trigger instance returned by the listing");
        }
 
 end:
@@ -527,19 +521,17 @@ end:
        lttng_trigger_destroy(trigger_b);
 }
 
-static
-void double_register_automatic_name_trigger(
-               enum unregistration_trigger_instance unregistration_trigger)
+static void
+double_register_automatic_name_trigger(enum unregistration_trigger_instance unregistration_trigger)
 {
        int ret;
        struct lttng_trigger *trigger_a = create_trigger(0xbadc0ffee);
        struct lttng_trigger *trigger_b = create_trigger(0xbadc0ffee);
-       struct lttng_triggers *triggers = NULL;
+       struct lttng_triggers *triggers = nullptr;
        enum lttng_error_code ret_code;
 
        diag("Register duplicate automatic name trigger (Unregistration performed with the trigger instance %s)",
-                       unregistration_trigger_instance_name(
-                                       unregistration_trigger));
+            unregistration_trigger_instance_name(unregistration_trigger));
 
        if (!trigger_a || !trigger_b) {
                fail("Failed to create triggers");
@@ -547,25 +539,30 @@ void double_register_automatic_name_trigger(
        }
 
        ret_code = lttng_register_trigger_with_automatic_name(trigger_a);
-       ok(ret_code == LTTNG_OK, "Registered automatic name trigger: trigger name = '%s'", get_trigger_name(trigger_a));
+       ok(ret_code == LTTNG_OK,
+          "Registered automatic name trigger: trigger name = '%s'",
+          get_trigger_name(trigger_a));
 
        ret = lttng_register_trigger_with_automatic_name(trigger_b);
-       ok(ret_code == LTTNG_OK, "Registering an identical trigger instance with an automatic name succeeds: trigger name = '%s'", get_trigger_name(trigger_b));
+       ok(ret_code == LTTNG_OK,
+          "Registering an identical trigger instance with an automatic name succeeds: trigger name = '%s'",
+          get_trigger_name(trigger_b));
 
        ok(strcmp(get_trigger_name(trigger_a), get_trigger_name(trigger_b)),
-                       "Two identical triggers registered with an automatic name have different names");
+          "Two identical triggers registered with an automatic name have different names");
 
        if (unregistration_trigger == UNREGISTRATION_TRIGGER_INSTANCE_USED_FOR_REGISTRATION) {
                ret = lttng_unregister_trigger(trigger_a);
-               ok(ret == 0, "Successfully unregistered automatic trigger A using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered automatic trigger A using the trigger instance used on registration");
 
                ret = lttng_unregister_trigger(trigger_b);
-               ok(ret == 0, "Successfully unregistered automatic trigger B using the trigger instance used on registration");
+               ok(ret == 0,
+                  "Successfully unregistered automatic trigger B using the trigger instance used on registration");
        } else {
-               ok(get_registered_triggers_count() == 2,
-                               "Trigger listing returns 2 trigger");
+               ok(get_registered_triggers_count() == 2, "Trigger listing returns 2 trigger");
                ok(unregister_all_triggers() == 2,
-                               "Successfully unregistered automatic name triggers using the trigger instance returned by the listing");
+                  "Successfully unregistered automatic name triggers using the trigger instance returned by the listing");
        }
 
 end:
@@ -574,8 +571,7 @@ end:
        lttng_trigger_destroy(trigger_b);
 }
 
-static
-void register_multiple_anonymous_triggers(void)
+static void register_multiple_anonymous_triggers()
 {
        int ret;
        struct lttng_trigger *trigger_a = create_trigger(0xbadc0ffee);
@@ -594,10 +590,8 @@ void register_multiple_anonymous_triggers(void)
        ret = lttng_register_trigger(trigger_b);
        ok(ret == 0, "Registered second anonymous trigger");
 
-       ok(get_registered_triggers_count() == 2,
-                       "Trigger listing returns 2 trigger");
-       ok(unregister_all_triggers() == 2,
-                       "Successfully unregistered two anonymous triggers");
+       ok(get_registered_triggers_count() == 2, "Trigger listing returns 2 trigger");
+       ok(unregister_all_triggers() == 2, "Successfully unregistered two anonymous triggers");
 
 end:
        lttng_trigger_destroy(trigger_a);
@@ -605,15 +599,12 @@ end:
 }
 
 const test_function test_functions[] = {
-       register_anonymous_trigger,
-       register_named_trigger,
-       register_automatic_name_trigger,
-       double_register_anonymous_trigger,
-       double_register_named_trigger,
-       double_register_automatic_name_trigger,
+       register_anonymous_trigger,      register_named_trigger,
+       register_automatic_name_trigger, double_register_anonymous_trigger,
+       double_register_named_trigger,   double_register_automatic_name_trigger,
 };
 
-int main(void)
+int main()
 {
        size_t i;
 
index ee5b590bd710a150a952bb7b08789b15632e8d48..cf68144f8d26d0c4215e9bfeacb617aa04810f96 100755 (executable)
@@ -28,7 +28,7 @@ function test_rate_policy_every_n()
        local END_TRIGGER_NAME="end-trigger1"
        local SYNC_AFTER_NOTIF_REGISTER_PATH
 
-       SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp --tmpdir -u test-notif-register.XXXXXX)
+       SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp -u -t test-notif-register.XXXXXX)
 
        diag "Every N rate policy"
 
@@ -114,7 +114,7 @@ function test_rate_policy_once_after_n()
        local END_TRIGGER_NAME="end-trigger1"
        local SYNC_AFTER_NOTIF_REGISTER_PATH
 
-       SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp --tmpdir -u test-notif-register.XXXXXX)
+       SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp -u -t test-notif-register.XXXXXX)
 
        diag "Once after N rate policy"
 
index 823fb27a8e8eeb6b83b4bd241fd08b2806f63426..9a6d52b35aa77ccbe03fd5b9b16a6bd97056edbd 100755 (executable)
@@ -42,8 +42,8 @@ function test_start_session_action()
 {
        local SESSION_NAME="my_triggered_session"
        local TRIGGER_NAME="trigger1"
-       local TRACE_PATH=$(mktemp --tmpdir -d test-start-action-trace.XXXXXX)
-       local SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp --tmpdir -u test-notif-register.XXXXXX)
+       local TRACE_PATH=$(mktemp -d -t test-start-action-trace.XXXXXX)
+       local SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp -u -t test-notif-register.XXXXXX)
 
        diag "Start session action"
 
@@ -95,8 +95,8 @@ function test_stop_session_action()
 {
        local SESSION_NAME="my_triggered_session"
        local TRIGGER_NAME="trigger1"
-       local TRACE_PATH=$(mktemp --tmpdir -d test-stop-action-trace.XXXXXX)
-       local SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp --tmpdir -u test-notif-register.XXXXXX)
+       local TRACE_PATH=$(mktemp -d -t test-stop-action-trace.XXXXXX)
+       local SYNC_AFTER_NOTIF_REGISTER_PATH=$(mktemp -u -t test-notif-register.XXXXXX)
 
        diag "Stop session action"
        create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
index a12e15ce811702ee4052141a9972ebc0f297869f..eeef3e250b86dc62c362da05fa4f7a9cd27232f5 100755 (executable)
@@ -30,16 +30,10 @@ FULL_LTTNG_BIN="${TESTDIR}/../src/bin/lttng/${LTTNG_BIN}"
 # shellcheck disable=SC2119
 start_lttng_sessiond_notap
 
-tmp_stdout=$(mktemp --tmpdir -t test_parse_cli_trigger_stdout.XXXXXX)
-tmp_stderr=$(mktemp --tmpdir -t test_parse_cli_trigger_stderr.XXXXXX)
+tmp_stdout=$(mktemp -t test_parse_cli_trigger_stdout.XXXXXX)
+tmp_stderr=$(mktemp -t test_parse_cli_trigger_stderr.XXXXXX)
 uprobe_elf_binary="${TESTDIR}/utils/testapp/userspace-probe-elf-binary/.libs/userspace-probe-elf-binary"
 
-if [ "$(id -u)" == "0" ]; then
-       ist_root=1
-else
-       ist_root=0
-fi
-
 function test_success ()
 {
        local test_name="$1"
@@ -47,10 +41,8 @@ function test_success ()
        shift 2
 
        diag "${FULL_LTTNG_BIN} add-trigger $*"
-       set -x
        "${FULL_LTTNG_BIN}" add-trigger "$@" > "${tmp_stdout}" 2> "${tmp_stderr}"
        ok $? "${test_name}: exit code is 0"
-       set +x
 
        diff -u "${tmp_stdout}" <(echo "Added trigger \`$trigger_name\`.")
        ok $? "${test_name}: expected stdout"
@@ -86,8 +78,8 @@ function test_mi ()
        # the one used by the list command. Here we simply validate that a
        # simple trigger is correctly generated.
 
-       tmp_stdout_raw=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
-       tmp_expected_stdout=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_expected_stdout.XXXXXX")
+       tmp_stdout_raw=$(mktemp -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
+       tmp_expected_stdout=$(mktemp -t "tmp.${FUNCNAME[0]}_expected_stdout.XXXXXX")
 
        diag "${FULL_LTTNG_BIN} --mi=xml add-trigger"
 
@@ -225,7 +217,7 @@ test_success "--exclude-name two" "trigger5" \
        --condition event-rule-matches --type=user --name='jean-*' --exclude-name jean-chretien -x jean-charest \
        --action notify
 
-skip $ist_root "non-root user: skipping kprobe tests" 18 || {
+check_skip_kernel_test 18 "Skipping kprobe tests." || {
        i=0
 
        for type in kprobe kernel:kprobe; do
@@ -264,7 +256,7 @@ skip $ist_root "non-root user: skipping kprobe tests" 18 || {
        done
 }
 
-skip $ist_root "non-root user: skipping uprobe tests" 6 || {
+check_skip_kernel_test 6 "Skipping uprobe tests." || {
        test_success "--condition event-rule-matches uprobe" "uprobe-trigger-0" \
                --name="uprobe-trigger-0" \
                --condition event-rule-matches --type=kernel:uprobe --location=${uprobe_elf_binary}:test_function --event-name=ma-probe \
@@ -276,7 +268,7 @@ skip $ist_root "non-root user: skipping uprobe tests" 6 || {
                --action notify
 }
 
-skip $ist_root "non-root user: skipping syscall tests" 30 || {
+check_skip_kernel_test 30 "Skipping syscall tests." || {
        test_success "--condition event-rule-matches one syscall" "syscall-trigger-0" \
                --name="syscall-trigger-0" \
                --condition event-rule-matches --type=syscall --name=open \
@@ -506,7 +498,7 @@ test_failure "--condition event-rule-matches: --type=syscall:nope" \
        --name=open
 
 test_failure "--exclude-name with non-glob name" \
-       "Error: Event jean: Exclusions can only be used with a globbing pattern" \
+       "Error: Event name pattern must contain wildcard characters to use exclusions" \
        --condition event-rule-matches --type=user --name='jean' --exclude-name jean-chretien \
        --action notify
 
index a040180138bac02f356bcdae687dc1b826250722..b99288471d92b8ee5b446ea63143887ae2c61b75 100755 (executable)
@@ -27,31 +27,21 @@ NUM_TESTS=150
 
 FULL_LTTNG_BIN="${TESTDIR}/../src/bin/lttng/${LTTNG_BIN}"
 
-tmp_stdout=$(mktemp --tmpdir -t test_list_triggers_cli_stdout.XXXXXX)
-tmp_stderr=$(mktemp --tmpdir -t test_list_triggers_cli_stderr.XXXXXX)
-tmp_expected_stdout=$(mktemp --tmpdir -t test_list_triggers_cli_expected_stdout.XXXXXX)
-tmp_expected_stdout_mi=$(mktemp --tmpdir -t test_list_triggers_cli_expected_stdout.mi.XXXXXX)
+tmp_stdout=$(mktemp -t test_list_triggers_cli_stdout.XXXXXX)
+tmp_stderr=$(mktemp -t test_list_triggers_cli_stderr.XXXXXX)
+tmp_expected_stdout=$(mktemp -t test_list_triggers_cli_expected_stdout.XXXXXX)
+tmp_expected_stdout_mi=$(mktemp -t test_list_triggers_cli_expected_stdout.mi.XXXXXX)
 uprobe_elf_binary=$(realpath "${TESTDIR}/utils/testapp/userspace-probe-elf-binary/.libs/userspace-probe-elf-binary")
 uprobe_sdt_binary=$(realpath "${TESTDIR}/utils/testapp/userspace-probe-sdt-binary/.libs/userspace-probe-sdt-binary")
 register_some_triggers_bin=$(realpath "${CURDIR}/utils/register-some-triggers")
 
 uid=$(id --user)
-gid=$(id --group)
 
-if [ "$uid" == "0" ]; then
-       ist_root=1
-       ls "$uprobe_sdt_binary" >/dev/null 2>&1
-       if test $? == 0; then
-               hast_sdt_binary=1
-       else
-               hast_sdt_binary=0
-       fi
-else
-       ist_root=0
-       hast_sdt_binary=0
+sdt_binary_present=0
+if [ -f "$uprobe_sdt_binary" ]; then
+       sdt_binary_present=1
 fi
 
-
 test_top_level_options ()
 {
        diag "Listing top level options"
@@ -799,8 +789,8 @@ test_event_rule_matches_probe ()
 
        diag "Listing event-rule-matches kernel probe"
 
-       channel_enable_addr=$(grep 'lttng_channel_enable' /proc/kallsyms | cut -f 1 -d ' ')
-       channel_disable_addr=$(grep 'lttng_channel_disable' /proc/kallsyms | cut -f 1 -d ' ')
+       channel_enable_addr=$(grep '\<lttng_channel_enable\>' /proc/kallsyms | cut -f 1 -d ' ')
+       channel_disable_addr=$(grep '\<lttng_channel_disable\>' /proc/kallsyms | cut -f 1 -d ' ')
 
        # We need to find a valid offset.
        base_symbol=""
@@ -1606,7 +1596,7 @@ test_buffer_usage_conditions ()
          condition: buffer usage high
            session name: the-session-name
            channel name: the-channel-name
-           domain: ust
+           domain: user space
            threshold (bytes): 1234
            errors: none
          actions:
@@ -1618,7 +1608,7 @@ test_buffer_usage_conditions ()
          condition: buffer usage high
            session name: the-session-name
            channel name: the-channel-name
-           domain: ust
+           domain: user space
            threshold (ratio): 0.25
            errors: none
          actions:
@@ -1630,7 +1620,7 @@ test_buffer_usage_conditions ()
          condition: buffer usage low
            session name: the-session-name
            channel name: the-channel-name
-           domain: ust
+           domain: user space
            threshold (bytes): 2345
            errors: none
          actions:
@@ -1642,7 +1632,7 @@ test_buffer_usage_conditions ()
          condition: buffer usage low
            session name: the-session-name
            channel name: the-channel-name
-           domain: ust
+           domain: user space
            threshold (ratio): 0.40
            errors: none
          actions:
@@ -2695,10 +2685,12 @@ start_lttng_sessiond_notap
 
 test_top_level_options
 test_event_rule_matches_tracepoint
-skip $ist_root "non-root user: skipping kprobe tests" 13 || test_event_rule_matches_probe
-skip $ist_root "non-root user: skipping uprobe tests" 9 || test_event_rule_matches_userspace_probe_elf
-skip $(($ist_root && $hast_sdt_binary)) "skipping userspace probe SDT tests" 9 || test_event_rule_matches_userspace_probe_sdt
-skip $ist_root "non-root user: skipping syscall tests" 17 || test_event_rule_matches_syscall
+check_skip_kernel_test 48 "Skipping kprobe, uprobe, SDT and syscall tests." || {
+       test_event_rule_matches_probe
+       test_event_rule_matches_userspace_probe_elf
+       skip $sdt_binary_present "No SDT binary. Skipping userspace probe SDT tests" 9 || test_event_rule_matches_userspace_probe_sdt
+       test_event_rule_matches_syscall
+}
 test_session_consumed_size_condition
 test_buffer_usage_conditions
 test_session_rotation_conditions
index aafbe4e24df1eec858ccd229ca9c92936a6467c7..ded80bb9b06e0d3512facddb5fafc53cc070a3e1 100755 (executable)
@@ -27,9 +27,9 @@ plan_tests 22
 
 FULL_LTTNG_BIN="${TESTDIR}/../src/bin/lttng/${LTTNG_BIN}"
 
-tmp_stdout=$(mktemp --tmpdir -t test_remove_triggers_cli_stdout.XXXXXX)
-tmp_stderr=$(mktemp --tmpdir -t test_remove_triggers_cli_stderr.XXXXXX)
-tmp_expected_stdout=$(mktemp --tmpdir -t test_remove_triggers_cli_expected_stdout.XXXXXX)
+tmp_stdout=$(mktemp -t test_remove_triggers_cli_stdout.XXXXXX)
+tmp_stderr=$(mktemp -t test_remove_triggers_cli_stderr.XXXXXX)
+tmp_expected_stdout=$(mktemp -t test_remove_triggers_cli_expected_stdout.XXXXXX)
 
 uid=$(id --user)
 gid=$(id --group)
@@ -73,8 +73,8 @@ function test_mi ()
        # the one used by the list command. Here we simply validate that a
        # simple trigger is correctly generated on removal for MI.
 
-       tmp_stdout_raw=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
-       tmp_expected_stdout=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_expected_stdout.XXXXXX")
+       tmp_stdout_raw=$(mktemp -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
+       tmp_expected_stdout=$(mktemp -t "tmp.${FUNCNAME[0]}_expected_stdout.XXXXXX")
 
        diag "${FULL_LTTNG_BIN} --mi=xml remove-trigger"
 
index a6a0258d4188df730f16bb18e73ad67ad8ae7e7a..d90a45ea570e2b82e31eddfe1292d3539bd3c230 100644 (file)
@@ -2,13 +2,14 @@
 
 AM_CPPFLAGS += -I$(srcdir) -I$(top_srcdir)/tests/utils
 LIBLTTNG_CTL=$(top_builddir)/src/lib/lttng-ctl/liblttng-ctl.la
+LIBCOMMON_LGPL=$(top_builddir)/src/common/libcommon-lgpl.la
 
 noinst_PROGRAMS = \
        notification-client \
        register-some-triggers
 
-notification_client_SOURCES = notification-client.c
-notification_client_LDADD = $(LIBLTTNG_CTL) \
+notification_client_SOURCES = notification-client.cpp
+notification_client_LDADD = $(LIBLTTNG_CTL) $(LIBCOMMON_LGPL) \
        $(top_builddir)/tests/utils/libtestutils.la
 
 register_some_triggers_SOURCES = register-some-triggers.cpp
diff --git a/tests/regression/tools/trigger/utils/notification-client.c b/tests/regression/tools/trigger/utils/notification-client.c
deleted file mode 100644 (file)
index 3d8aec4..0000000
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * Copyright (C) 2020 Jérémie Galarneau <jeremie.galarneau@efficios.com>
- *
- * SPDX-License-Identifier: MIT
- *
- */
-
-#include <getopt.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/time.h>
-#include <time.h>
-
-#include <lttng/condition/event-rule-matches.h>
-#include <lttng/lttng.h>
-
-#include "utils.h"
-
-static struct option long_options[] =
-{
-       /* These options set a flag. */
-       {"trigger", required_argument, 0, 't'},
-       {"sync-after-notif-register", required_argument, 0, 'a'},
-       /* Default alue for count is 1 */
-       {"count", required_argument, 0, 'b'},
-       /*
-        * When end-trigger is present the reception loop is exited only when a
-        * notification matching the end trigger is received.
-        * Otherwise the loop is exited when the count of notification received
-        * for `trigger` math the `count` argument.
-        */
-       {"end-trigger", required_argument, 0, 'c'},
-       {0, 0, 0, 0}
-};
-
-static bool action_list_contains_notify(
-               const struct lttng_action *action_list)
-{
-       unsigned int i, count;
-       enum lttng_action_status status =
-                       lttng_action_list_get_count(action_list, &count);
-
-       if (status != LTTNG_ACTION_STATUS_OK) {
-               printf("Failed to get action count from action list\n");
-               exit(1);
-       }
-
-       for (i = 0; i < count; i++) {
-               const struct lttng_action *action =
-                               lttng_action_list_get_at_index(
-                                               action_list, i);
-               const enum lttng_action_type action_type =
-                               lttng_action_get_type(action);
-
-               if (action_type == LTTNG_ACTION_TYPE_NOTIFY) {
-                       return true;
-               }
-       }
-       return false;
-}
-
-/* Only expects named triggers. */
-static bool is_trigger_name(const char *expected_trigger_name,
-               struct lttng_notification *notification)
-{
-       const char *trigger_name = NULL;
-       enum lttng_trigger_status trigger_status;
-       const struct lttng_trigger *trigger;
-       bool names_match;
-
-       trigger = lttng_notification_get_trigger(notification);
-       if (!trigger) {
-               fprintf(stderr, "Failed to get trigger from notification\n");
-               names_match = false;
-               goto end;
-       }
-
-       trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
-       if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
-               fprintf(stderr, "Failed to get name from notification's trigger\n");
-               names_match = false;
-               goto end;
-       }
-
-       names_match = strcmp(expected_trigger_name, trigger_name) == 0;
-       if (!names_match) {
-               fprintf(stderr, "Got an unexpected trigger name: name = '%s', expected name = '%s'\n",
-                               trigger_name, expected_trigger_name);
-       }
-end:
-       return names_match;
-}
-
-int main(int argc, char **argv)
-{
-       int ret;
-       int option;
-       int option_index;
-       char *expected_trigger_name = NULL;
-       char *end_trigger_name = NULL;
-       struct lttng_triggers *triggers = NULL;
-       unsigned int count, i, subcription_count = 0;
-       enum lttng_trigger_status trigger_status;
-       char *after_notif_register_file_path = NULL;
-       struct lttng_notification_channel *notification_channel = NULL;
-       int expected_notifications = 1, notification_count = 0;
-
-       while ((option = getopt_long(argc, argv, "a:b:c:t:", long_options,
-                               &option_index)) != -1) {
-               switch (option) {
-               case 'a':
-                       after_notif_register_file_path = strdup(optarg);
-                       break;
-               case 'b':
-                       expected_notifications = atoi(optarg);
-                       break;
-               case 'c':
-                       end_trigger_name = strdup(optarg);
-                       break;
-               case 't':
-                       expected_trigger_name = strdup(optarg);
-                       break;
-               case '?':
-                       /* getopt_long already printed an error message. */
-               default:
-                       ret = -1;
-                       goto end;
-               }
-       }
-
-       if (optind != argc) {
-               ret = -1;
-               goto end;
-       }
-
-
-       notification_channel = lttng_notification_channel_create(
-                       lttng_session_daemon_notification_endpoint);
-       if (!notification_channel) {
-               fprintf(stderr, "Failed to create notification channel\n");
-               ret = -1;
-               goto end;
-       }
-
-       ret = lttng_list_triggers(&triggers);
-       if (ret != LTTNG_OK) {
-               fprintf(stderr, "Failed to list triggers\n");
-               ret = -1;
-               goto end;
-       }
-
-       trigger_status = lttng_triggers_get_count(triggers, &count);
-       if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
-               fprintf(stderr, "Failed to get trigger count\n");
-               ret = -1;
-               goto end;
-       }
-
-       /* Look for the trigger we want to subscribe to. */
-       for (i = 0; i < count; i++) {
-               const struct lttng_trigger *trigger =
-                               lttng_triggers_get_at_index(triggers, i);
-               const struct lttng_condition *condition =
-                               lttng_trigger_get_const_condition(trigger);
-               const struct lttng_action *action =
-                               lttng_trigger_get_const_action(trigger);
-               const enum lttng_action_type action_type =
-                               lttng_action_get_type(action);
-               enum lttng_notification_channel_status channel_status;
-               const char *trigger_name = NULL;
-
-               lttng_trigger_get_name(trigger, &trigger_name);
-               if (strcmp(trigger_name, expected_trigger_name)) {
-                       /* Might match the end event trigger */
-                       if (end_trigger_name != NULL &&
-                                       strcmp(trigger_name,
-                                                       end_trigger_name)) {
-                               continue;
-                       }
-               }
-               if (!((action_type == LTTNG_ACTION_TYPE_LIST &&
-                                     action_list_contains_notify(action)) ||
-                                   action_type == LTTNG_ACTION_TYPE_NOTIFY)) {
-                       /* "The action of trigger is not notify, skipping. */
-                       continue;
-               }
-
-               channel_status = lttng_notification_channel_subscribe(
-                               notification_channel, condition);
-               if (channel_status) {
-                       fprintf(stderr, "Failed to subscribe to notifications of trigger \"%s\"\n",
-                                       trigger_name);
-                       ret = -1;
-                       goto end;
-               }
-
-               subcription_count++;
-       }
-
-       if (subcription_count == 0) {
-               fprintf(stderr, "No matching trigger with a notify action found.\n");
-               ret = -1;
-               goto end;
-       }
-
-       if (end_trigger_name != NULL && subcription_count != 2) {
-               fprintf(stderr, "No matching end event trigger with a notify action found.\n");
-               ret = -1;
-               goto end;
-       }
-
-       /*
-        * We registered to the notification of our target trigger. We can now
-        * create the sync file to signify that we are ready.
-        */
-       ret = create_file(after_notif_register_file_path);
-       if (ret != 0) {
-               goto end;
-       }
-
-       for (;;) {
-               struct lttng_notification *notification;
-               enum lttng_notification_channel_status channel_status;
-
-               channel_status =
-                               lttng_notification_channel_get_next_notification(
-                                               notification_channel,
-                                               &notification);
-               switch (channel_status) {
-               case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
-                       printf("Dropped notification\n");
-                       ret = -1;
-                       goto end;
-               case LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED:
-                       ret = -1;
-                       goto end;
-               case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
-                       break;
-               case LTTNG_NOTIFICATION_CHANNEL_STATUS_CLOSED:
-                       printf("Notification channel was closed by peer.\n");
-                       break;
-               default:
-                       fprintf(stderr, "A communication error occurred on the notification channel.\n");
-                       ret = -1;
-                       goto end;
-               }
-
-               /* Early exit check. */
-               if (end_trigger_name != NULL &&
-                               is_trigger_name(end_trigger_name,
-                                               notification)) {
-                       /* Exit the loop immediately. */
-                       printf("Received end event notification from trigger %s\n",
-                                       end_trigger_name);
-                       lttng_notification_destroy(notification);
-                       goto evaluate_success;
-               }
-
-               ret = is_trigger_name(expected_trigger_name, notification);
-               lttng_notification_destroy(notification);
-               if (!ret) {
-                       ret = -1;
-                       goto end;
-               }
-
-               printf("Received event notification from trigger %s\n",
-                               expected_trigger_name);
-               notification_count++;
-               if (end_trigger_name == NULL &&
-                               expected_notifications == notification_count) {
-                       /*
-                        * Here the loop exit is controlled by the number of
-                        * notification and not by the reception of the end
-                        * event trigger notification. This represent the
-                        * default behavior.
-                        *
-                        */
-                       goto evaluate_success;
-               }
-       }
-
-evaluate_success:
-       if (expected_notifications == notification_count) {
-               /* Success */
-               ret = 0;
-       } else {
-               fprintf(stderr, "Expected %d notification got %d\n",
-                               expected_notifications, notification_count);
-               ret = 1;
-       }
-
-end:
-       lttng_triggers_destroy(triggers);
-       lttng_notification_channel_destroy(notification_channel);
-       free(after_notif_register_file_path);
-       free(end_trigger_name);
-       free(expected_trigger_name);
-       return !!ret;
-}
diff --git a/tests/regression/tools/trigger/utils/notification-client.cpp b/tests/regression/tools/trigger/utils/notification-client.cpp
new file mode 100644 (file)
index 0000000..27bd100
--- /dev/null
@@ -0,0 +1,293 @@
+/*
+ * Copyright (C) 2020 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#include "utils.h"
+
+#include <common/error.hpp>
+
+#include <lttng/action/list-internal.hpp>
+#include <lttng/condition/event-rule-matches.h>
+#include <lttng/lttng.h>
+
+#include <getopt.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+#include <time.h>
+
+static struct option long_options[] = {
+       /* These options set a flag. */
+       { "trigger", required_argument, 0, 't' },
+       { "sync-after-notif-register", required_argument, 0, 'a' },
+       /* Default alue for count is 1 */
+       { "count", required_argument, 0, 'b' },
+       /*
+        * When end-trigger is present the reception loop is exited only when a
+        * notification matching the end trigger is received.
+        * Otherwise the loop is exited when the count of notification received
+        * for `trigger` math the `count` argument.
+        */
+       { "end-trigger", required_argument, 0, 'c' },
+       { 0, 0, 0, 0 }
+};
+
+static bool action_list_contains_notify(const struct lttng_action *action_list)
+{
+       for (auto sub_action : lttng::ctl::const_action_list_view(action_list)) {
+               if (lttng_action_get_type(sub_action) == LTTNG_ACTION_TYPE_NOTIFY) {
+                       return true;
+               }
+       }
+
+       return false;
+}
+
+/* Only expects named triggers. */
+static bool is_trigger_name(const char *expected_trigger_name,
+                           struct lttng_notification *notification)
+{
+       const char *trigger_name = NULL;
+       enum lttng_trigger_status trigger_status;
+       const struct lttng_trigger *trigger;
+       bool names_match;
+
+       trigger = lttng_notification_get_trigger(notification);
+       if (!trigger) {
+               fprintf(stderr, "Failed to get trigger from notification\n");
+               names_match = false;
+               goto end;
+       }
+
+       trigger_status = lttng_trigger_get_name(trigger, &trigger_name);
+       if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
+               fprintf(stderr, "Failed to get name from notification's trigger\n");
+               names_match = false;
+               goto end;
+       }
+
+       names_match = strcmp(expected_trigger_name, trigger_name) == 0;
+       if (!names_match) {
+               fprintf(stderr,
+                       "Got an unexpected trigger name: name = '%s', expected name = '%s'\n",
+                       trigger_name,
+                       expected_trigger_name);
+       }
+end:
+       return names_match;
+}
+
+static int _main(int argc, char **argv)
+{
+       int ret;
+       int option;
+       int option_index;
+       char *expected_trigger_name = NULL;
+       char *end_trigger_name = NULL;
+       struct lttng_triggers *triggers = NULL;
+       unsigned int count, i, subcription_count = 0;
+       enum lttng_trigger_status trigger_status;
+       char *after_notif_register_file_path = NULL;
+       struct lttng_notification_channel *notification_channel = NULL;
+       int expected_notifications = 1, notification_count = 0;
+
+       while ((option = getopt_long(argc, argv, "a:b:c:t:", long_options, &option_index)) != -1) {
+               switch (option) {
+               case 'a':
+                       after_notif_register_file_path = strdup(optarg);
+                       break;
+               case 'b':
+                       expected_notifications = atoi(optarg);
+                       break;
+               case 'c':
+                       end_trigger_name = strdup(optarg);
+                       break;
+               case 't':
+                       expected_trigger_name = strdup(optarg);
+                       break;
+               case '?':
+                       /* getopt_long already printed an error message. */
+               default:
+                       ret = -1;
+                       goto end;
+               }
+       }
+
+       if (optind != argc) {
+               ret = -1;
+               goto end;
+       }
+
+       notification_channel =
+               lttng_notification_channel_create(lttng_session_daemon_notification_endpoint);
+       if (!notification_channel) {
+               fprintf(stderr, "Failed to create notification channel\n");
+               ret = -1;
+               goto end;
+       }
+
+       ret = lttng_list_triggers(&triggers);
+       if (ret != LTTNG_OK) {
+               fprintf(stderr, "Failed to list triggers\n");
+               ret = -1;
+               goto end;
+       }
+
+       trigger_status = lttng_triggers_get_count(triggers, &count);
+       if (trigger_status != LTTNG_TRIGGER_STATUS_OK) {
+               fprintf(stderr, "Failed to get trigger count\n");
+               ret = -1;
+               goto end;
+       }
+
+       /* Look for the trigger we want to subscribe to. */
+       for (i = 0; i < count; i++) {
+               const struct lttng_trigger *trigger = lttng_triggers_get_at_index(triggers, i);
+               const struct lttng_condition *condition =
+                       lttng_trigger_get_const_condition(trigger);
+               const struct lttng_action *action = lttng_trigger_get_const_action(trigger);
+               const enum lttng_action_type action_type = lttng_action_get_type(action);
+               enum lttng_notification_channel_status channel_status;
+               const char *trigger_name = NULL;
+
+               lttng_trigger_get_name(trigger, &trigger_name);
+               if (strcmp(trigger_name, expected_trigger_name) != 0) {
+                       /* Might match the end event trigger */
+                       if (end_trigger_name != NULL &&
+                           strcmp(trigger_name, end_trigger_name) != 0) {
+                               continue;
+                       }
+               }
+               if (!((action_type == LTTNG_ACTION_TYPE_LIST &&
+                      action_list_contains_notify(action)) ||
+                     action_type == LTTNG_ACTION_TYPE_NOTIFY)) {
+                       /* "The action of trigger is not notify, skipping. */
+                       continue;
+               }
+
+               channel_status =
+                       lttng_notification_channel_subscribe(notification_channel, condition);
+               if (channel_status) {
+                       fprintf(stderr,
+                               "Failed to subscribe to notifications of trigger \"%s\"\n",
+                               trigger_name);
+                       ret = -1;
+                       goto end;
+               }
+
+               subcription_count++;
+       }
+
+       if (subcription_count == 0) {
+               fprintf(stderr, "No matching trigger with a notify action found.\n");
+               ret = -1;
+               goto end;
+       }
+
+       if (end_trigger_name != NULL && subcription_count != 2) {
+               fprintf(stderr, "No matching end event trigger with a notify action found.\n");
+               ret = -1;
+               goto end;
+       }
+
+       /*
+        * We registered to the notification of our target trigger. We can now
+        * create the sync file to signify that we are ready.
+        */
+       ret = create_file(after_notif_register_file_path);
+       if (ret != 0) {
+               goto end;
+       }
+
+       for (;;) {
+               struct lttng_notification *notification;
+               enum lttng_notification_channel_status channel_status;
+
+               channel_status = lttng_notification_channel_get_next_notification(
+                       notification_channel, &notification);
+               switch (channel_status) {
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_NOTIFICATIONS_DROPPED:
+                       printf("Dropped notification\n");
+                       ret = -1;
+                       goto end;
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_INTERRUPTED:
+                       ret = -1;
+                       goto end;
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_OK:
+                       break;
+               case LTTNG_NOTIFICATION_CHANNEL_STATUS_CLOSED:
+                       printf("Notification channel was closed by peer.\n");
+                       break;
+               default:
+                       fprintf(stderr,
+                               "A communication error occurred on the notification channel.\n");
+                       ret = -1;
+                       goto end;
+               }
+
+               /* Early exit check. */
+               if (end_trigger_name != NULL && is_trigger_name(end_trigger_name, notification)) {
+                       /* Exit the loop immediately. */
+                       printf("Received end event notification from trigger %s\n",
+                              end_trigger_name);
+                       lttng_notification_destroy(notification);
+                       goto evaluate_success;
+               }
+
+               ret = is_trigger_name(expected_trigger_name, notification);
+               lttng_notification_destroy(notification);
+               if (!ret) {
+                       ret = -1;
+                       goto end;
+               }
+
+               printf("Received event notification from trigger %s\n", expected_trigger_name);
+               notification_count++;
+               if (end_trigger_name == NULL && expected_notifications == notification_count) {
+                       /*
+                        * Here the loop exit is controlled by the number of
+                        * notification and not by the reception of the end
+                        * event trigger notification. This represent the
+                        * default behavior.
+                        *
+                        */
+                       goto evaluate_success;
+               }
+       }
+
+evaluate_success:
+       if (expected_notifications == notification_count) {
+               /* Success */
+               ret = 0;
+       } else {
+               fprintf(stderr,
+                       "Expected %d notification got %d\n",
+                       expected_notifications,
+                       notification_count);
+               ret = 1;
+       }
+
+end:
+       lttng_triggers_destroy(triggers);
+       lttng_notification_channel_destroy(notification_channel);
+       free(after_notif_register_file_path);
+       free(end_trigger_name);
+       free(expected_trigger_name);
+       return !!ret;
+}
+
+int main(int argc, char **argv)
+{
+       try {
+               return _main(argc, argv);
+       } catch (const std::exception& e) {
+               ERR_FMT("Unhandled exception caught by notification client: {}", e.what());
+               abort();
+       }
+}
index 6a173b7c18293430e9a5bd5fabd885ce9fdc7727..97257cf12507b37859feb3284e93fdd1cfde55ef 100644 (file)
@@ -9,14 +9,15 @@
 
 #include <common/filter/filter-ast.hpp>
 #include <common/macros.hpp>
+
 #include <lttng/lttng.h>
 
 #include <stdlib.h>
 #include <string.h>
 
 static void register_trigger(const char *trigger_name,
-               struct lttng_condition *condition,
-               struct lttng_action *action)
+                            struct lttng_condition *condition,
+                            struct lttng_action *action)
 {
        struct lttng_trigger *trigger;
        enum lttng_error_code ret;
@@ -33,8 +34,8 @@ static void register_trigger(const char *trigger_name,
  * Register a trigger with the given condition and an action list containing a
  * single notify action.
  */
-static void register_trigger_action_list_notify(
-               const char *trigger_name, struct lttng_condition *condition)
+static void register_trigger_action_list_notify(const char *trigger_name,
+                                               struct lttng_condition *condition)
 {
        struct lttng_action *action_notify;
        struct lttng_action *action_list;
@@ -42,187 +43,172 @@ static void register_trigger_action_list_notify(
 
        action_list = lttng_action_list_create();
        action_notify = lttng_action_notify_create();
-       action_status = lttng_action_list_add_action(
-                       action_list, action_notify);
+       action_status = lttng_action_list_add_action(action_list, action_notify);
        LTTNG_ASSERT(action_status == LTTNG_ACTION_STATUS_OK);
        lttng_action_destroy(action_notify);
 
        register_trigger(trigger_name, condition, action_list);
 }
 
-static struct lttng_condition *create_session_consumed_size_condition(
-               const char *session_name, uint64_t threshold)
+static struct lttng_condition *create_session_consumed_size_condition(const char *session_name,
+                                                                     uint64_t threshold)
 {
        struct lttng_condition *condition;
        enum lttng_condition_status condition_status;
 
        condition = lttng_condition_session_consumed_size_create();
        condition_status =
-                       lttng_condition_session_consumed_size_set_session_name(
-                                       condition, session_name);
+               lttng_condition_session_consumed_size_set_session_name(condition, session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
-       condition_status = lttng_condition_session_consumed_size_set_threshold(
-                       condition, threshold);
+       condition_status =
+               lttng_condition_session_consumed_size_set_threshold(condition, threshold);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 
        return condition;
 }
 
-static void test_session_consumed_size_condition(void)
+static void test_session_consumed_size_condition()
 {
        register_trigger_action_list_notify(
-                       "trigger-with-session-consumed-size-condition",
-                       create_session_consumed_size_condition(
-                                       "the-session-name", 1234));
+               "trigger-with-session-consumed-size-condition",
+               create_session_consumed_size_condition("the-session-name", 1234));
 }
 
 static void fill_buffer_usage_condition(struct lttng_condition *condition,
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type)
+                                       const char *session_name,
+                                       const char *channel_name,
+                                       enum lttng_domain_type domain_type)
 {
        enum lttng_condition_status condition_status;
 
-       condition_status = lttng_condition_buffer_usage_set_session_name(
-                       condition, session_name);
+       condition_status = lttng_condition_buffer_usage_set_session_name(condition, session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
-       condition_status = lttng_condition_buffer_usage_set_channel_name(
-                       condition, channel_name);
+       condition_status = lttng_condition_buffer_usage_set_channel_name(condition, channel_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
-       condition_status = lttng_condition_buffer_usage_set_domain_type(
-                       condition, domain_type);
+       condition_status = lttng_condition_buffer_usage_set_domain_type(condition, domain_type);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 }
 
 static void fill_buffer_usage_bytes_condition(struct lttng_condition *condition,
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               uint64_t threshold)
+                                             const char *session_name,
+                                             const char *channel_name,
+                                             enum lttng_domain_type domain_type,
+                                             uint64_t threshold)
 {
        enum lttng_condition_status condition_status;
 
-       fill_buffer_usage_condition(
-                       condition, session_name, channel_name, domain_type);
-       condition_status = lttng_condition_buffer_usage_set_threshold(
-                       condition, threshold);
+       fill_buffer_usage_condition(condition, session_name, channel_name, domain_type);
+       condition_status = lttng_condition_buffer_usage_set_threshold(condition, threshold);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 }
 
 static void fill_buffer_usage_ratio_condition(struct lttng_condition *condition,
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               double ratio)
+                                             const char *session_name,
+                                             const char *channel_name,
+                                             enum lttng_domain_type domain_type,
+                                             double ratio)
 {
        enum lttng_condition_status condition_status;
 
-       fill_buffer_usage_condition(
-                       condition, session_name, channel_name, domain_type);
-       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(
-                       condition, ratio);
+       fill_buffer_usage_condition(condition, session_name, channel_name, domain_type);
+       condition_status = lttng_condition_buffer_usage_set_threshold_ratio(condition, ratio);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 }
 
-static struct lttng_condition *create_buffer_usage_high_bytes_condition(
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               uint64_t threshold)
+static struct lttng_condition *
+create_buffer_usage_high_bytes_condition(const char *session_name,
+                                        const char *channel_name,
+                                        enum lttng_domain_type domain_type,
+                                        uint64_t threshold)
 {
        struct lttng_condition *condition;
 
        condition = lttng_condition_buffer_usage_high_create();
-       fill_buffer_usage_bytes_condition(condition, session_name, channel_name,
-                       domain_type, threshold);
+       fill_buffer_usage_bytes_condition(
+               condition, session_name, channel_name, domain_type, threshold);
 
        return condition;
 }
 
-static struct lttng_condition *create_buffer_usage_low_bytes_condition(
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               uint64_t threshold)
+static struct lttng_condition *
+create_buffer_usage_low_bytes_condition(const char *session_name,
+                                       const char *channel_name,
+                                       enum lttng_domain_type domain_type,
+                                       uint64_t threshold)
 {
        struct lttng_condition *condition;
 
        condition = lttng_condition_buffer_usage_low_create();
-       fill_buffer_usage_bytes_condition(condition, session_name, channel_name,
-                       domain_type, threshold);
+       fill_buffer_usage_bytes_condition(
+               condition, session_name, channel_name, domain_type, threshold);
 
        return condition;
 }
 
-static struct lttng_condition *create_buffer_usage_high_ratio_condition(
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               double ratio)
+static struct lttng_condition *
+create_buffer_usage_high_ratio_condition(const char *session_name,
+                                        const char *channel_name,
+                                        enum lttng_domain_type domain_type,
+                                        double ratio)
 {
        struct lttng_condition *condition;
 
        condition = lttng_condition_buffer_usage_high_create();
-       fill_buffer_usage_ratio_condition(condition, session_name, channel_name,
-                       domain_type, ratio);
+       fill_buffer_usage_ratio_condition(
+               condition, session_name, channel_name, domain_type, ratio);
 
        return condition;
 }
 
-static struct lttng_condition *create_buffer_usage_low_ratio_condition(
-               const char *session_name,
-               const char *channel_name,
-               enum lttng_domain_type domain_type,
-               double ratio)
+static struct lttng_condition *
+create_buffer_usage_low_ratio_condition(const char *session_name,
+                                       const char *channel_name,
+                                       enum lttng_domain_type domain_type,
+                                       double ratio)
 {
        struct lttng_condition *condition;
 
        condition = lttng_condition_buffer_usage_low_create();
-       fill_buffer_usage_ratio_condition(condition, session_name, channel_name,
-                       domain_type, ratio);
+       fill_buffer_usage_ratio_condition(
+               condition, session_name, channel_name, domain_type, ratio);
 
        return condition;
 }
 
-static void test_buffer_usage_conditions(void)
+static void test_buffer_usage_conditions()
 {
        register_trigger_action_list_notify(
-                       "trigger-with-buffer-usage-high-bytes-condition",
-                       create_buffer_usage_high_bytes_condition(
-                                       "the-session-name", "the-channel-name",
-                                       LTTNG_DOMAIN_UST, 1234));
+               "trigger-with-buffer-usage-high-bytes-condition",
+               create_buffer_usage_high_bytes_condition(
+                       "the-session-name", "the-channel-name", LTTNG_DOMAIN_UST, 1234));
 
        register_trigger_action_list_notify(
-                       "trigger-with-buffer-usage-low-bytes-condition",
-                       create_buffer_usage_low_bytes_condition(
-                                       "the-session-name", "the-channel-name",
-                                       LTTNG_DOMAIN_UST, 2345));
+               "trigger-with-buffer-usage-low-bytes-condition",
+               create_buffer_usage_low_bytes_condition(
+                       "the-session-name", "the-channel-name", LTTNG_DOMAIN_UST, 2345));
 
        register_trigger_action_list_notify(
-                       "trigger-with-buffer-usage-high-ratio-condition",
-                       create_buffer_usage_high_ratio_condition(
-                                       "the-session-name", "the-channel-name",
-                                       LTTNG_DOMAIN_UST, 0.25));
+               "trigger-with-buffer-usage-high-ratio-condition",
+               create_buffer_usage_high_ratio_condition(
+                       "the-session-name", "the-channel-name", LTTNG_DOMAIN_UST, 0.25));
 
        register_trigger_action_list_notify(
-                       "trigger-with-buffer-usage-low-ratio-condition",
-                       create_buffer_usage_low_ratio_condition(
-                                       "the-session-name", "the-channel-name",
-                                       LTTNG_DOMAIN_UST, 0.4));
+               "trigger-with-buffer-usage-low-ratio-condition",
+               create_buffer_usage_low_ratio_condition(
+                       "the-session-name", "the-channel-name", LTTNG_DOMAIN_UST, 0.4));
 }
 
-static void fill_session_rotation_condition(
-               struct lttng_condition *condition, const char *session_name)
+static void fill_session_rotation_condition(struct lttng_condition *condition,
+                                           const char *session_name)
 {
        enum lttng_condition_status condition_status;
 
-       condition_status = lttng_condition_session_rotation_set_session_name(
-                       condition, session_name);
+       condition_status =
+               lttng_condition_session_rotation_set_session_name(condition, session_name);
        LTTNG_ASSERT(condition_status == LTTNG_CONDITION_STATUS_OK);
 }
 
-static struct lttng_condition *create_session_rotation_ongoing_condition(
-               const char *session_name)
+static struct lttng_condition *create_session_rotation_ongoing_condition(const char *session_name)
 {
        struct lttng_condition *condition;
 
@@ -233,8 +219,7 @@ static struct lttng_condition *create_session_rotation_ongoing_condition(
        return condition;
 }
 
-static struct lttng_condition *create_session_rotation_completed_condition(
-               const char *session_name)
+static struct lttng_condition *create_session_rotation_completed_condition(const char *session_name)
 {
        struct lttng_condition *condition;
 
@@ -245,33 +230,30 @@ static struct lttng_condition *create_session_rotation_completed_condition(
        return condition;
 }
 
-static void test_session_rotation_conditions(void)
+static void test_session_rotation_conditions()
 {
        register_trigger_action_list_notify(
-                       "trigger-with-session-rotation-ongoing-condition",
-                       create_session_rotation_ongoing_condition(
-                                       "the-session-name"));
+               "trigger-with-session-rotation-ongoing-condition",
+               create_session_rotation_ongoing_condition("the-session-name"));
 
        register_trigger_action_list_notify(
-                       "trigger-with-session-rotation-completed-condition",
-                       create_session_rotation_completed_condition(
-                                       "the-session-name"));
+               "trigger-with-session-rotation-completed-condition",
+               create_session_rotation_completed_condition("the-session-name"));
 }
 
 static struct {
        const char *name;
-       void (*callback)(void);
+       void (*callback)();
 } tests[] = {
-               {
-                               "test_session_consumed_size_condition",
-                               test_session_consumed_size_condition,
-               },
-               {"test_buffer_usage_conditions", test_buffer_usage_conditions},
-               {"test_session_rotation_conditions",
-                               test_session_rotation_conditions},
+       {
+               "test_session_consumed_size_condition",
+               test_session_consumed_size_condition,
+       },
+       { "test_buffer_usage_conditions", test_buffer_usage_conditions },
+       { "test_session_rotation_conditions", test_session_rotation_conditions },
 };
 
-static void show_known_tests(void)
+static void show_known_tests()
 {
        size_t i;
 
index c226461753b919759adc51239dbe614c998b8523..8777424196e52169f02679e929d88bcbd2104e2e 100755 (executable)
@@ -35,7 +35,7 @@ function run_kernel
 
 function test_event_wildcard()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        DOMAIN="$1"
        FIND="$2"
        WILDCARD="$3"
@@ -69,7 +69,7 @@ function test_event_wildcard()
 
 function test_event_wildcard_fail()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        DOMAIN="$1"
        WILDCARD="$2"
 
@@ -126,13 +126,7 @@ test_event_wildcard ust 1 'tp*tptest'
 test_event_wildcard ust 1 'tp**tptest'
 test_event_wildcard ust 1 'tp*test'
 
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-else
-       isroot=0
-fi
-
-skip $isroot "Root access is needed. Skipping all kernel wildcard tests." $NUM_KERNEL_TESTS ||
+check_skip_kernel_test "$NUM_KERNEL_TESTS" "Skipping kernel wildcard tests." ||
 {
        diag "Test kernel wildcards"
 
index c7e784cca2feaedc20c2d92049d0655fe7db2517..db44120e788fd36c122853544b7e335484741ba4 100755 (executable)
@@ -22,7 +22,7 @@ print_test_banner "$TEST_DESC"
 function test_relayd()
 {
        local relayd_bin_path="$DIR/../src/bin/lttng-relayd/$RELAYD_BIN"
-       local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+       local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
        local pid
        local cwd
 
@@ -58,7 +58,7 @@ function test_relayd_daemon()
 {
        local cwd
        local pid
-       local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+       local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
 
        diag "Test lttng-relayd daemon mode change working directory"
 
@@ -100,7 +100,7 @@ function test_relayd_background()
 {
        local cwd
        local pid
-       local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+       local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
 
        diag "Test lttng-relayd background mode change working directory"
 
@@ -145,9 +145,9 @@ function test_relayd_debug_permission()
        diag "Test lttng-relayd change working directory on non writable directory"
 
        if [ "$(id -u)" == "0" ]; then
-           is_user=0
+               is_user=0
        else
-           is_user=1
+               is_user=1
        fi
 
        skip $is_user "Skipping permission debug output test; operation can't fail as root" 6 ||
@@ -155,14 +155,14 @@ function test_relayd_debug_permission()
                local output_pattern='Working directory \".*\" is not writable'
                local cwd
                local pid
-               local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+               local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
 
                # Removing write access to working dir
                okx chmod -w "$working_dir"
 
                # Redirect the error output to a temporary file
 
-               ERROR_OUTPUT_DEST=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_error_output.XXXXXX")
+               ERROR_OUTPUT_DEST=$(mktemp -t "tmp.${FUNCNAME[0]}_error_output.XXXXXX")
                start_lttng_relayd_opt 1 "-b" "-v --working-dir $working_dir"
 
                pid=$(lttng_pgrep "$RELAYD_MATCH")
@@ -185,8 +185,8 @@ function test_relayd_failure()
 {
        local output_pattern='Failed to change working directory to'
        local relayd_bin_path="$DIR/../src/bin/lttng-relayd/$RELAYD_BIN"
-       local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
-       local output_dest=$(mktemp --tmpdir "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")
+       local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+       local output_dest=$(mktemp -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")
 
        local working_dir_imaginary
        local pid
@@ -218,7 +218,7 @@ function test_relayd_env()
 {
        local cwd
        local pid
-       local working_dir=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
+       local working_dir=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir.XXXXXX")")
 
        diag "Test lttng-relayd change working directory from env. variable"
 
@@ -241,8 +241,8 @@ function test_relayd_cmdline_overwrite_env()
 {
        local cwd
        local pid
-       local working_dir_env=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir_even.XXXXXX")")
-       local working_dir_cmdline=$(realpath "$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_working_dir_cmdline.XXXXXX")")
+       local working_dir_env=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir_even.XXXXXX")")
+       local working_dir_cmdline=$(realpath "$(mktemp -d -t "tmp.${FUNCNAME[0]}_working_dir_cmdline.XXXXXX")")
 
        diag "Test lttng-relayd change working directory command line overwrite env variable"
 
index 5af414966d80fc5cf07583f95c43519e74a1f568..dd8186f9a652953aa62fbf88a25a1b4ca56583cf 100644 (file)
@@ -24,7 +24,8 @@ SUBDIRS = \
        overlap \
        periodical-metadata-flush \
        rotation-destroy-flush \
-       type-declarations
+       type-declarations \
+       ust-constructor
 
 if HAVE_OBJCOPY
 SUBDIRS += \
index f8fe263955ee18b51b906c1fb93545b403933a5e..d37dbb6dd5751f5f0264a165440264b9718e8eb5 100644 (file)
@@ -19,11 +19,11 @@ EXTRA_DIST = test_baddr-statedump test_baddr-statedump.py
 
 # Extract debug symbols
 prog.debug: prog
-       $(objcopy_verbose)$(OBJCOPY) --only-keep-debug prog prog.debug
+       $(objcopy_verbose)$(LIBTOOL) --mode=execute $(OBJCOPY) --only-keep-debug prog prog.debug
 
 # Strip and add debuglink
 prog.strip: prog.debug
-       @cp -f prog prog.strip
+       @$(LIBTOOL) --mode=execute cp -f prog prog.strip
        $(objcopy_verbose)$(OBJCOPY) --strip-debug --add-gnu-debuglink=prog.debug prog.strip
 
 all-local: prog.strip
index c145972bb7fe4071c435d2bbac71c42c0c84a47b..f785289a7f8d4c1de7fae9703cef28d158d1a390 100644 (file)
@@ -26,27 +26,40 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("""No sessiond running. Please make sure you are running this test
+    bail(
+        """No sessiond running. Please make sure you are running this test
     with the "run" shell script and verify that the lttng tools are
-    properly installed.""")
+    properly installed."""
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "*")
 start_session(session_info)
 
-test_process = subprocess.Popen(test_path + "prog.strip", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+test_process = subprocess.Popen(
+    test_path + "prog.strip", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
+)
 test_process.wait()
 
-print_test_result(test_process.returncode == 0, current_test, "Test application exited normally")
+print_test_result(
+    test_process.returncode == 0, current_test, "Test application exited normally"
+)
 current_test += 1
 
 stop_session(session_info)
 
 # Check for statedump events in the resulting trace
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
-    bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN), session_info)
+    bail(
+        "Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN),
+        session_info,
+    )
 
 start_event_found = False
 bin_info_event_found = False
@@ -56,11 +69,16 @@ end_event_found = False
 
 for event_line in babeltrace_process.stdout:
     # Let babeltrace finish to get the return code
-    if start_event_found and bin_info_event_found and build_id_event_found and \
-       debug_link_event_found and end_event_found:
+    if (
+        start_event_found
+        and bin_info_event_found
+        and build_id_event_found
+        and debug_link_event_found
+        and end_event_found
+    ):
         continue
 
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
     if re.search(r".*lttng_ust_statedump:start.*", event_line) is not None:
         start_event_found = True
     elif re.search(r".*lttng_ust_statedump:bin_info.*", event_line) is not None:
@@ -74,22 +92,44 @@ for event_line in babeltrace_process.stdout:
 
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
-print_test_result(start_event_found, current_test, "lttng_ust_statedump:start event found in resulting trace")
+print_test_result(
+    start_event_found,
+    current_test,
+    "lttng_ust_statedump:start event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(bin_info_event_found, current_test, "lttng_ust_statedump:bin_info event found in resulting trace")
+print_test_result(
+    bin_info_event_found,
+    current_test,
+    "lttng_ust_statedump:bin_info event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(build_id_event_found, current_test, "lttng_ust_statedump:build_id event found in resulting trace")
+print_test_result(
+    build_id_event_found,
+    current_test,
+    "lttng_ust_statedump:build_id event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(debug_link_event_found, current_test, "lttng_ust_statedump:debug_link event found in resulting trace")
+print_test_result(
+    debug_link_event_found,
+    current_test,
+    "lttng_ust_statedump:debug_link event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(end_event_found, current_test, "lttng_ust_statedump:end event found in resulting trace")
+print_test_result(
+    end_event_found,
+    current_test,
+    "lttng_ust_statedump:end event found in resulting trace",
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
index bbde2b7beb9a20331e0544202571de067323c617..d1dcec4347babb87047b9a45a2416bac1b902d31 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(
-               my_provider,
-               my_first_tracepoint,
-               TP_ARGS(
-               int, my_integer_arg,
-               char*, my_string_arg
-       ),
-       TP_FIELDS(
-               ctf_string(my_string_field, my_string_arg)
-               ctf_integer(int, my_integer_field, my_integer_arg)
-       )
-)
+TRACEPOINT_EVENT(my_provider,
+                my_first_tracepoint,
+                TP_ARGS(int, my_integer_arg, char *, my_string_arg),
+                TP_FIELDS(ctf_string(my_string_field, my_string_arg)
+                                  ctf_integer(int, my_integer_field, my_integer_arg)))
 
 #endif /* _TP_H */
 
index 0c3ebec5485f3609e5802361a8d88017b04ac02b..f7b95477964fbe627d9fd084ac86ff1a644a7528 100755 (executable)
@@ -47,8 +47,8 @@ function test_before_apps()
 function test_after_apps()
 {
        local out
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME
@@ -86,7 +86,7 @@ start_lttng_sessiond
 
 diag "Start tracing BEFORE application is started"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_before_after_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_before_after_ust_trace_path.XXXXXX)
 
 test_before_apps
 out=$?
@@ -99,7 +99,7 @@ rm -rf $TRACE_PATH
 
 diag "Start tracing AFTER application is started"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_before_after_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_before_after_ust_trace_path.XXXXXX)
 
 test_after_apps
 out=$?
index ca864353248d29f1fbc603ddb5102d3c4cd40437..51e2130908c78758af7b2d63ef3e6aa46d87a7a5 100755 (executable)
@@ -19,16 +19,30 @@ EVENT_NAME="tp:tptest"
 
 NUM_TESTS=49
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source=../utils/utils.sh
+source "$TESTDIR/utils/utils.sh"
 
 # MUST set TESTDIR before calling those functions
-# Run app on CPU 0 to ensure we only write in a single ring buffer.
+# Run app on a single CPU to ensure we only write in a single ring buffer.
 function run_app()
 {
-       taskset 0x00000001 $TESTAPP_BIN -i $NUM_EVENT
+       taskset --cpu-list "$(get_any_available_cpu)" $TESTAPP_BIN -i $NUM_EVENT
        ok $? "Application done"
 }
 
+function check_disk_space()
+{
+       local path
+
+       path="${1:?}"
+       kb_free=$(df -k -P "${path}" | tail -n 1 | awk '{ print $4 }')
+       if [ "${kb_free}" -lt "1048576" ] ; then
+               return 1
+       fi
+
+       return 0
+}
+
 function test_ust_implicit_no_blocking()
 {
        NUM_EVENT=5000000
@@ -120,13 +134,12 @@ function test_ust_blocking_no_discard()
        start_lttng_tracing_ok $SESSION_NAME
        LTTNG_UST_ALLOW_BLOCKING=1 run_app
        stop_lttng_tracing_ok $SESSION_NAME
+       discarded=$("${XML_EXTRACT}" <("${TESTDIR}/../src/bin/lttng/${LTTNG_BIN}" --mi=xml list --channel="${CHANNEL_NAME}" "${SESSION_NAME}") '//lttng:command/lttng:output/lttng:sessions/lttng:session/lttng:domains/lttng:domain/lttng:channels/lttng:channel/lttng:attributes/lttng:discarded_events')
        destroy_lttng_session_ok $SESSION_NAME
        stop_lttng_sessiond
 
-       nr_events=$("$BABELTRACE_BIN" $TRACE_PATH 2>/dev/null | wc -l)
-
-       test $nr_events -eq $NUM_EVENT
-       ok $? "No event lost with UST blocking mode: found $nr_events expect $NUM_EVENT"
+       test "$(echo "${discarded}" | grep -Eo '[0-9]+')" = "0"
+       ok $? "No event lost with UST blocking mode: ${discarded}"
 }
 
 plan_tests $NUM_TESTS
@@ -135,6 +148,10 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
+if ! check_disk_space "${TMPDIR:-/tmp}"; then
+       BAIL_OUT "Not enough free space to run blocking tests"
+fi
+
 TESTS=(
        "test_ust_implicit_no_blocking"
        "test_ust_implicit_no_blocking_with_channel_blocking"
@@ -148,7 +165,7 @@ i=0
 
 while [ "$i" -lt "$TEST_COUNT" ]; do
 
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_blocking_ust_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_blocking_ust_trace_path.XXXXXX)
 
        # Execute test
        ${TESTS[$i]}
index 982ee2d58dff73a25f7c0f4a41589634b317d601..9463d1a511f889daf739b94e90a9b1ea651a9af7 100755 (executable)
@@ -64,8 +64,8 @@ test_after_multiple_apps() {
 test_before_multiple_apps() {
        local out
        local i
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Start multiple applications BEFORE tracing is started"
 
@@ -137,8 +137,8 @@ test_after_app() {
 
 test_before_app() {
        local out
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Start application BEFORE tracing is started"
 
@@ -238,7 +238,7 @@ i=0
 start_lttng_sessiond
 
 while [ $i -lt $TEST_COUNT ]; do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_buffers_pid_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_buffers_pid_trace_path.XXXXXX)
        ${TESTS[$i]}
        rm -rf $TRACE_PATH
        let "i++"
index a38cd515e217cfaee7cc55845f285790dd8067f2..180712ee8dc19c61371673668300d2ad9321cea7 100644 (file)
  *
  */
 
-#include <stdlib.h>
 #include <common/compat/time.hpp>
-#include <string.h>
-#include <stdio.h>
+
 #include <lttng/lttng-export.h>
 #include <lttng/ust-clock.h>
 
-static
-uint64_t plugin_read64(void)
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static uint64_t plugin_read64(void)
 {
        /* Freeze time */
        return 0;
 }
 
-static
-uint64_t plugin_freq(void)
+static uint64_t plugin_freq(void)
 {
-       return 1000;    /* 1KHz clock (very coarse!) */
+       return 1000; /* 1KHz clock (very coarse!) */
 }
 
-static
-int plugin_uuid(char *uuid)
+static int plugin_uuid(char *uuid)
 {
        const char myuuid[] = "83c63deb-7aa4-48fb-abda-946f400d76e6";
        memcpy(uuid, myuuid, LTTNG_UST_UUID_STR_LEN);
        return 0;
 }
 
-static
-const char *plugin_name(void)
+static const char *plugin_name(void)
 {
        return "lttng_test_clock_override";
 }
 
-static
-const char *plugin_description(void)
+static const char *plugin_description(void)
 {
        return "Freeze time with 1KHz for regression test";
 }
@@ -57,41 +54,39 @@ void lttng_ust_clock_plugin_init(void)
 
        ret = lttng_ust_trace_clock_set_read64_cb(plugin_read64);
        if (ret) {
-               fprintf(stderr, "Error setting clock override read64 callback: %s\n",
+               fprintf(stderr,
+                       "Error setting clock override read64 callback: %s\n",
                        strerror(-ret));
                goto error;
        }
        ret = lttng_ust_trace_clock_set_freq_cb(plugin_freq);
        if (ret) {
-               fprintf(stderr, "Error setting clock override freq callback: %s\n",
-                       strerror(-ret));
+               fprintf(stderr, "Error setting clock override freq callback: %s\n", strerror(-ret));
                goto error;
        }
        ret = lttng_ust_trace_clock_set_uuid_cb(plugin_uuid);
        if (ret) {
-               fprintf(stderr, "Error setting clock override uuid callback: %s\n",
-                       strerror(-ret));
+               fprintf(stderr, "Error setting clock override uuid callback: %s\n", strerror(-ret));
                goto error;
        }
 
        ret = lttng_ust_trace_clock_set_name_cb(plugin_name);
        if (ret) {
-               fprintf(stderr, "Error setting clock override name callback: %s\n",
-                       strerror(-ret));
+               fprintf(stderr, "Error setting clock override name callback: %s\n", strerror(-ret));
                goto error;
        }
 
        ret = lttng_ust_trace_clock_set_description_cb(plugin_description);
        if (ret) {
-               fprintf(stderr, "Error setting clock override description callback: %s\n",
+               fprintf(stderr,
+                       "Error setting clock override description callback: %s\n",
                        strerror(-ret));
                goto error;
        }
 
        ret = lttng_ust_enable_trace_clock_override();
        if (ret) {
-               fprintf(stderr, "Error enabling clock override: %s\n",
-                       strerror(-ret));
+               fprintf(stderr, "Error enabling clock override: %s\n", strerror(-ret));
                goto error;
        }
 
index 6be2d8dff0d5c132fbf0a74879d6a56ad95c1b1c..c7157720ecc7a8576ebba851eb6515e6cd8c40df 100755 (executable)
@@ -66,8 +66,8 @@ function extract_clock_metadata_token()
 
 function test_getcpu_override_metadata()
 {
-       local ctf_metadata_file=$(mktemp --tmpdir -p $TRACE_PATH ctf-metadata.XXXXXX)
-       local clock_metadata_file=$(mktemp --tmpdir -p $TRACE_PATH clock-metadata.XXXXXX)
+       local ctf_metadata_file=$(TMPDIR="$TRACE_PATH" mktemp -t ctf-metadata.XXXXXX)
+       local clock_metadata_file=$(TMPDIR="$TRACE_PATH" mktemp -t clock-metadata.XXXXXX)
        local result=""
 
        diag "Clock override plugin metadata test"
@@ -174,7 +174,7 @@ i=0
 
 while [ "$i" -lt "$TEST_COUNT" ]; do
 
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_clock_override_ust_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_clock_override_ust_trace_path.XXXXXX)
 
        # Execute test
        ${TESTS[$i]}
index 44ec182fab47a2e5340d115783ebcea62f69e65e..1ce1b50df81f13a60e1f260f16dc456f3bd647be 100644 (file)
@@ -7,9 +7,9 @@
  */
 
 #include <stdio.h>
-#include <unistd.h>
-#include <sys/types.h>
 #include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #define TRACEPOINT_DEFINE
 #define TRACEPOINT_CREATE_PROBES
index 46df102b9bb42284e1d124ab08763cffabf841d0..058821ca390f9ddab606a89e0b0d785370b90787 100644 (file)
@@ -26,7 +26,9 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "*")
@@ -37,7 +39,7 @@ parent_pid = None
 daemon_pid = None
 daemon_process = subprocess.Popen(test_path + "daemon", stdout=subprocess.PIPE)
 for line in daemon_process.stdout:
-    name, pid = line.decode('utf-8').split()
+    name, pid = line.decode("utf-8").split()
     if name == "child_pid":
         daemon_pid = int(pid)
     if name == "parent_pid":
@@ -46,9 +48,16 @@ for line in daemon_process.stdout:
 daemon_process_return_code = daemon_process.wait()
 
 if parent_pid is None or daemon_pid is None:
-    bail("Unexpected output received from daemon test executable." + str(daemon_process_output))
-
-print_test_result(daemon_process_return_code == 0, current_test, "Successful call to daemon() and normal exit")
+    bail(
+        "Unexpected output received from daemon test executable."
+        + str(daemon_process_output)
+    )
+
+print_test_result(
+    daemon_process_return_code == 0,
+    current_test,
+    "Successful call to daemon() and normal exit",
+)
 current_test += 1
 
 if daemon_process_return_code != 0:
@@ -57,7 +66,9 @@ if daemon_process_return_code != 0:
 stop_session(session_info)
 
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE
+    )
 except FileNotFoundError:
     bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN))
 
@@ -67,11 +78,13 @@ after_daemon_event_found = False
 after_daemon_event_pid = -1
 
 for event_line in babeltrace_process.stdout:
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
 
     if re.search(r"before_daemon", event_line) is not None:
         if before_daemon_event_found:
-            bail("Multiple instances of the before_daemon event found. Please make sure only one instance of this test is runnning.")
+            bail(
+                "Multiple instances of the before_daemon event found. Please make sure only one instance of this test is runnning."
+            )
         before_daemon_event_found = True
         match = re.search(r"(?<=pid = )\d+", event_line)
 
@@ -80,7 +93,9 @@ for event_line in babeltrace_process.stdout:
 
     if re.search(r"after_daemon", event_line) is not None:
         if after_daemon_event_found:
-            bail("Multiple instances of the after_daemon event found. Please make sure only one instance of this test is runnning.")
+            bail(
+                "Multiple instances of the after_daemon event found. Please make sure only one instance of this test is runnning."
+            )
         after_daemon_event_found = True
         match = re.search(r"(?<=pid = )\d+", event_line)
 
@@ -88,19 +103,37 @@ for event_line in babeltrace_process.stdout:
             after_daemon_event_pid = int(match.group(0))
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
 if babeltrace_process.returncode != 0:
     bail("Unreadable trace; can't proceed with analysis.")
 
-print_test_result(before_daemon_event_found, current_test, "before_daemon event found in resulting trace")
+print_test_result(
+    before_daemon_event_found,
+    current_test,
+    "before_daemon event found in resulting trace",
+)
 current_test += 1
-print_test_result(before_daemon_event_pid == parent_pid, current_test, "Parent pid reported in trace is correct")
+print_test_result(
+    before_daemon_event_pid == parent_pid,
+    current_test,
+    "Parent pid reported in trace is correct",
+)
 current_test += 1
-print_test_result(before_daemon_event_found, current_test, "after_daemon event found in resulting trace")
+print_test_result(
+    before_daemon_event_found,
+    current_test,
+    "after_daemon event found in resulting trace",
+)
 current_test += 1
-print_test_result(after_daemon_event_pid == daemon_pid, current_test, "Daemon pid reported in trace is correct")
+print_test_result(
+    after_daemon_event_pid == daemon_pid,
+    current_test,
+    "Daemon pid reported in trace is correct",
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
index 60fec4a94699121dcce70c0748772960fba346a0..4dea6aa6c786b4c8285d6ba940d9b54d532cc1c3 100644 (file)
 #define _TRACEPOINT_UST_TESTS_DAEMON_H
 
 #include <lttng/tracepoint.h>
+
 #include <sys/types.h>
 
-TRACEPOINT_EVENT(ust_tests_daemon, before_daemon,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
-
-TRACEPOINT_EVENT(ust_tests_daemon, after_daemon_child,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
-
-TRACEPOINT_EVENT(ust_tests_daemon, after_daemon_parent,
-       TP_ARGS(),
-       TP_FIELDS()
-)
+TRACEPOINT_EVENT(ust_tests_daemon,
+                before_daemon,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
+
+TRACEPOINT_EVENT(ust_tests_daemon,
+                after_daemon_child,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
+
+TRACEPOINT_EVENT(ust_tests_daemon, after_daemon_parent, TP_ARGS(), TP_FIELDS())
 
 #endif /* _TRACEPOINT_UST_TESTS_DAEMON_H */
 
index aaacd4529049ac5a2d19ed27ca3d5d0125189ca9..9d66126803c9eb93d1474df33fca0e7e0741af25 100644 (file)
@@ -27,7 +27,9 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "ust_tests_exitfast*")
@@ -36,49 +38,81 @@ start_session(session_info)
 test_env = os.environ.copy()
 test_env["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
 
-exit_fast_process = subprocess.Popen(test_path + "exit-fast", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=test_env)
+exit_fast_process = subprocess.Popen(
+    test_path + "exit-fast",
+    stdout=subprocess.DEVNULL,
+    stderr=subprocess.DEVNULL,
+    env=test_env,
+)
 exit_fast_process.wait()
 
-print_test_result(exit_fast_process.returncode == 0, current_test, "Test application exited normally")
+print_test_result(
+    exit_fast_process.returncode == 0, current_test, "Test application exited normally"
+)
 current_test += 1
 
-exit_fast_process = subprocess.Popen([test_path + "exit-fast", "suicide"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=test_env)
+exit_fast_process = subprocess.Popen(
+    [test_path + "exit-fast", "suicide"],
+    stdout=subprocess.DEVNULL,
+    stderr=subprocess.DEVNULL,
+    env=test_env,
+)
 exit_fast_process.wait()
 
 stop_session(session_info)
 
 # Check both events (normal exit and suicide messages) are present in the resulting trace
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
     bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN))
 
 event_lines = []
 for event_line in babeltrace_process.stdout:
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
     event_lines.append(event_line)
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
 if babeltrace_process.returncode != 0:
     bail("Unreadable trace; can't proceed with analysis.")
 
-print_test_result(len(event_lines) == 2, current_test, "Correct number of events found in resulting trace")
+print_test_result(
+    len(event_lines) == 2,
+    current_test,
+    "Correct number of events found in resulting trace",
+)
 current_test += 1
 
 if len(event_lines) != 2:
-    bail("Unexpected number of events found in resulting trace (" + session_info.trace_path + ")." )
+    bail(
+        "Unexpected number of events found in resulting trace ("
+        + session_info.trace_path
+        + ")."
+    )
 
 match = re.search(r".*message = \"(.*)\"", event_lines[0])
-print_test_result(match is not None and match.group(1) == normal_exit_message, current_test,\
-                      "Tracepoint message generated during normal exit run is present in trace and has the expected value")
+print_test_result(
+    match is not None and match.group(1) == normal_exit_message,
+    current_test,
+    "Tracepoint message generated during normal exit run is present in trace and has the expected value",
+)
 current_test += 1
 
 match = re.search(r".*message = \"(.*)\"", event_lines[1])
-print_test_result(match is not None and match.group(1) == suicide_exit_message, current_test,\
-                      "Tracepoint message generated during suicide run is present in trace and has the expected value")
+print_test_result(
+    match is not None and match.group(1) == suicide_exit_message,
+    current_test,
+    "Tracepoint message generated during suicide run is present in trace and has the expected value",
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
index 1952981f12cdc764029fff2b89b6e80e6b0a14e1..1827fdcc1be6319721a772fb5ea8c961649e2a97 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_exitfast, message,
-               TP_ARGS(char *, text),
-               TP_FIELDS(ctf_string(message, text))
-)
+TRACEPOINT_EVENT(ust_tests_exitfast,
+                message,
+                TP_ARGS(char *, text),
+                TP_FIELDS(ctf_string(message, text)))
 
 TRACEPOINT_LOGLEVEL(ust_tests_exitfast, message, TRACE_INFO)
 
index 7030a293d532db5d81cca4fa96c1948a938b7f55..2387f245e89678e8c71bc59bd6190228f62c11d5 100644 (file)
@@ -7,10 +7,10 @@
  */
 
 #include <stdio.h>
-#include <unistd.h>
+#include <stdlib.h>
 #include <sys/types.h>
 #include <sys/wait.h>
-#include <stdlib.h>
+#include <unistd.h>
 
 #define TRACEPOINT_DEFINE
 #define TRACEPOINT_CREATE_PROBES
index 3c9a2ea91e538e0d781fe6fb826754894dc94252..40f0b4073f96cc410f6f36f3c81b0980050348a8 100644 (file)
@@ -25,17 +25,23 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "ust_tests_fork*")
 start_session(session_info)
 
-fork_process = subprocess.Popen([test_path + "fork", test_path + "fork2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+fork_process = subprocess.Popen(
+    [test_path + "fork", test_path + "fork2"],
+    stdout=subprocess.PIPE,
+    stderr=subprocess.PIPE,
+)
 parent_pid = -1
 child_pid = -1
 for line in fork_process.stdout:
-    line = line.decode('utf-8').replace("\n", "")
+    line = line.decode("utf-8").replace("\n", "")
     match = re.search(r"child_pid (\d+)", line)
     if match:
         child_pid = match.group(1)
@@ -45,28 +51,39 @@ for line in fork_process.stdout:
 
 fork_process.wait()
 
-print_test_result(fork_process.returncode == 0, current_test, "Fork test application exited normally")
+print_test_result(
+    fork_process.returncode == 0, current_test, "Fork test application exited normally"
+)
 current_test += 1
 
 stop_session(session_info)
 
 # Check both events (normal exit and suicide messages) are present in the resulting trace
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
     bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN))
 
 event_lines = []
 for event_line in babeltrace_process.stdout:
-    event_line = event_line.decode('utf-8').replace("\n", "")
-    if re.search(r"warning", event_line) is not None or re.search(r"error", event_line) is not None:
-        print( "# " + event_line )
+    event_line = event_line.decode("utf-8").replace("\n", "")
+    if (
+        re.search(r"warning", event_line) is not None
+        or re.search(r"error", event_line) is not None
+    ):
+        print("# " + event_line)
     else:
         event_lines.append(event_line)
 
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
 if babeltrace_process.returncode != 0:
@@ -85,21 +102,37 @@ for event_line in event_lines:
         continue
 
     if re.search(r"before_fork", event_line):
-        event_before_fork = (event_pid == parent_pid)
+        event_before_fork = event_pid == parent_pid
     if re.search(r"after_fork_parent", event_line):
-        event_after_fork_parent = (event_pid == parent_pid)
+        event_after_fork_parent = event_pid == parent_pid
     if re.search(r"after_fork_child", event_line):
-        event_after_fork_child = (event_pid == child_pid)
+        event_after_fork_child = event_pid == child_pid
     if re.search(r"after_exec", event_line):
-        event_after_exec = (event_pid == child_pid)
+        event_after_exec = event_pid == child_pid
 
-print_test_result(event_before_fork, current_test, "before_fork event logged by parent process found in trace")
+print_test_result(
+    event_before_fork,
+    current_test,
+    "before_fork event logged by parent process found in trace",
+)
 current_test += 1
-print_test_result(event_after_fork_parent, current_test, "after_fork_parent event logged by parent process found in trace")
+print_test_result(
+    event_after_fork_parent,
+    current_test,
+    "after_fork_parent event logged by parent process found in trace",
+)
 current_test += 1
-print_test_result(event_after_fork_child, current_test, "after_fork_child event logged by child process found in trace")
+print_test_result(
+    event_after_fork_child,
+    current_test,
+    "after_fork_child event logged by child process found in trace",
+)
 current_test += 1
-print_test_result(event_after_exec, current_test, "after_exec event logged by child process found in trace")
+print_test_result(
+    event_after_exec,
+    current_test,
+    "after_exec event logged by child process found in trace",
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
index 92c2a630be251893ae8353cfffbb8860e73cacad..fb417717fbda54ac217eb59fc8a994adabb15d3f 100644 (file)
 #define _TRACEPOINT_UST_TESTS_FORK_H
 
 #include <lttng/tracepoint.h>
+
 #include <sys/types.h>
 
-TRACEPOINT_EVENT(ust_tests_fork, before_fork,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
-
-TRACEPOINT_EVENT(ust_tests_fork, after_fork_child,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
-
-TRACEPOINT_EVENT(ust_tests_fork, after_fork_parent,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
-
-TRACEPOINT_EVENT(ust_tests_fork, after_exec,
-       TP_ARGS(pid_t, pid),
-       TP_FIELDS(
-               ctf_integer(pid_t, pid, pid)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_fork,
+                before_fork,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
+
+TRACEPOINT_EVENT(ust_tests_fork,
+                after_fork_child,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
+
+TRACEPOINT_EVENT(ust_tests_fork,
+                after_fork_parent,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
+
+TRACEPOINT_EVENT(ust_tests_fork,
+                after_exec,
+                TP_ARGS(pid_t, pid),
+                TP_FIELDS(ctf_integer(pid_t, pid, pid)))
 
 #endif /* _TRACEPOINT_UST_TESTS_FORK_H */
 
index 80240f1f5da47eb5d676b77cb99da9596717a0e1..c98d7070062197bb1995c5fcc63c415e04e59700 100644 (file)
@@ -9,18 +9,19 @@
  *
  */
 
-#include <stdlib.h>
 #include <common/compat/time.hpp>
-#include <string.h>
-#include <stdio.h>
-#include <unistd.h>
+
 #include <lttng/lttng-export.h>
 #include <lttng/ust-getcpu.h>
 
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
 static long nprocessors;
 
-static
-int plugin_getcpu(void)
+static int plugin_getcpu(void)
 {
        /* Generate a sequence based on the number of configurated processor
         * by using sequence[i] % nb_configured_processors. Where sequence
@@ -31,26 +32,24 @@ int plugin_getcpu(void)
         * plugin but provide a strong argument of it's validity.
         */
        static int i = 0;
-       static int seq_seed[256] = { 100, 57, 232, 236, 42, 193, 224, 184, 216,
-               150, 92, 91, 108, 118, 55, 243, 65, 101, 209, 0, 147, 36, 29,
-               34, 49, 188, 174, 105, 253, 245, 227, 238, 112, 20, 222, 201,
-               102, 175, 119, 19, 132, 41, 78, 90, 114, 64, 138, 14, 48, 18,
-               162, 85, 204, 124, 133, 73, 172, 106, 241, 126, 28, 104, 111,
-               21, 127, 219, 9, 244, 237, 189, 59, 214, 52, 141, 107, 26, 25,
-               199, 3, 157, 117, 234, 33, 44, 46, 84, 69, 155, 122, 250, 231,
-               86, 239, 76, 190, 120, 1, 94, 206, 8, 148, 159, 167, 215, 164,
-               31, 217, 61, 71, 125, 68, 109, 195, 177, 95, 82, 142, 182, 129,
-               87, 37, 140, 134, 186, 173, 39, 116, 143, 254, 229, 131, 67,
-               121, 192, 240, 15, 221, 30, 242, 185, 80, 170, 135, 51, 187,
-               194, 246, 12, 225, 181, 137, 211, 228, 88, 218, 27, 233, 161,
-               77, 252, 123, 93, 220, 248, 205, 223, 144, 128, 196, 70, 247,
-               210, 178, 203, 154, 24, 169, 149, 163, 35, 7, 151, 103, 197,
-               139, 165, 158, 207, 72, 113, 145, 45, 183, 11, 198, 43, 81, 230,
-               97, 96, 2, 66, 213, 146, 179, 22, 58, 54, 38, 160, 200, 235,
-               226, 156, 56, 208, 249, 32, 176, 168, 110, 191, 79, 152, 115,
-               10, 74, 60, 251, 17, 83, 180, 171, 202, 40, 166, 255, 53, 212,
-               98, 5, 50, 99, 4, 89, 13, 63, 6, 136, 153, 23, 16, 47, 130, 75,
-               62 };
+       static int seq_seed[256] = {
+               100, 57,  232, 236, 42,  193, 224, 184, 216, 150, 92,  91,  108, 118, 55,  243,
+               65,  101, 209, 0,   147, 36,  29,  34,  49,  188, 174, 105, 253, 245, 227, 238,
+               112, 20,  222, 201, 102, 175, 119, 19,  132, 41,  78,  90,  114, 64,  138, 14,
+               48,  18,  162, 85,  204, 124, 133, 73,  172, 106, 241, 126, 28,  104, 111, 21,
+               127, 219, 9,   244, 237, 189, 59,  214, 52,  141, 107, 26,  25,  199, 3,   157,
+               117, 234, 33,  44,  46,  84,  69,  155, 122, 250, 231, 86,  239, 76,  190, 120,
+               1,   94,  206, 8,   148, 159, 167, 215, 164, 31,  217, 61,  71,  125, 68,  109,
+               195, 177, 95,  82,  142, 182, 129, 87,  37,  140, 134, 186, 173, 39,  116, 143,
+               254, 229, 131, 67,  121, 192, 240, 15,  221, 30,  242, 185, 80,  170, 135, 51,
+               187, 194, 246, 12,  225, 181, 137, 211, 228, 88,  218, 27,  233, 161, 77,  252,
+               123, 93,  220, 248, 205, 223, 144, 128, 196, 70,  247, 210, 178, 203, 154, 24,
+               169, 149, 163, 35,  7,   151, 103, 197, 139, 165, 158, 207, 72,  113, 145, 45,
+               183, 11,  198, 43,  81,  230, 97,  96,  2,   66,  213, 146, 179, 22,  58,  54,
+               38,  160, 200, 235, 226, 156, 56,  208, 249, 32,  176, 168, 110, 191, 79,  152,
+               115, 10,  74,  60,  251, 17,  83,  180, 171, 202, 40,  166, 255, 53,  212, 98,
+               5,   50,  99,  4,   89,  13,  63,  6,   136, 153, 23,  16,  47,  130, 75,  62
+       };
        int ret;
 
        ret = seq_seed[i] % nprocessors;
@@ -72,8 +71,7 @@ void lttng_ust_getcpu_plugin_init(void)
 
        ret = lttng_ust_getcpu_override(plugin_getcpu);
        if (ret) {
-               fprintf(stderr, "Error enabling getcpu override: %s\n",
-                       strerror(-ret));
+               fprintf(stderr, "Error enabling getcpu override: %s\n", strerror(-ret));
                goto error;
        }
        return;
index 124219a36757352c743d563ff5004cc8aef69745..7723a76790417e111393a2816d51bc187de5d80b 100755 (executable)
@@ -175,7 +175,7 @@ start_lttng_sessiond
 
 for fct_test in ${TESTS[@]};
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_getcpu_override_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_getcpu_override_trace_path.XXXXXX)
 
        ${fct_test}
        if [ $? -ne 0 ]; then
index 055d8823e146edd63a2a55b886ec5eb1c71e281c..2306c2da1b8539e3fb1329275dd09138c989d149 100644 (file)
@@ -6,28 +6,26 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <stdarg.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <arpa/inet.h>
 #include <fcntl.h>
 #include <signal.h>
-#include <string.h>
-#include <arpa/inet.h>
+#include <stdarg.h>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #define TRACEPOINT_DEFINE
 #include "tp.h"
 
-static
-void inthandler(int sig __attribute__((unused)))
+static void inthandler(int sig __attribute__((unused)))
 {
 }
 
-static
-int init_int_handler(void)
+static int init_int_handler(void)
 {
        int result;
        struct sigaction act;
@@ -72,8 +70,7 @@ int main(int argc, char **argv)
 
        for (i = 0; i < 1000000; i++) {
                netint = htonl(i);
-               tracepoint(tp, tptest, i, netint, values, text,
-                               strlen(text), dbl, flt);
+               tracepoint(tp, tptest, i, netint, values, text, strlen(text), dbl, flt);
        }
 
        return 0;
index 873646fa912ab77b7ea8c1fd11e42c3990bc7fdd..9f59836c2351a6a46feee85a56d952d0d62be81c 100755 (executable)
@@ -20,7 +20,7 @@ if [ ! -x "$CURDIR/$BIN_NAME" ]; then
        BAIL_OUT "No UST nevents binary detected."
 fi
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_high_throughput_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_high_throughput_ust_trace_path.XXXXXX)
 
 # MUST set TESTDIR before calling those functions
 
@@ -52,8 +52,8 @@ stop_lttng_sessiond
 
 # Validate test
 
-TEMP_FILE=$(mktemp --tmpdir tmp.test_high_throughput_tmp_file1.XXXXXX)
-TEMP_FILE_2=$(mktemp --tmpdir tmp.test_high_throughput_tmp_file2.XXXXXX)
+TEMP_FILE=$(mktemp -t tmp.test_high_throughput_tmp_file1.XXXXXX)
+TEMP_FILE_2=$(mktemp -t tmp.test_high_throughput_tmp_file2.XXXXXX)
 
 traced=$("$BABELTRACE_BIN" $TRACE_PATH 2>/dev/null | wc -l)
 "$BABELTRACE_BIN" $TRACE_PATH >/dev/null 2>$TEMP_FILE_2
index 9c74d8c0aabf856b794d94e4fbf145fb90af11bd..79fcfe57a6f18d53432e6d6789361a36959e0e62 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, tptest,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen, double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
+TRACEPOINT_EVENT(
+       tp,
+       tptest,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index 90c1758e1131fabbf68ad5cba1e87bd1f353d207..41e2656ffbc09590a747f44b83949b80c7f1598e 100755 (executable)
@@ -79,8 +79,8 @@ function enable_jul_filter_loglevel_only()
 
 function test_jul_before_start ()
 {
-       local file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       local file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       local file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       local file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test JUL application BEFORE tracing starts"
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -696,7 +696,7 @@ skip $withapp "JUL support is needed. Skipping all tests." $NUM_TESTS ||
 
        for fct_test in ${tests[@]};
        do
-               TRACE_PATH=$(mktemp --tmpdir -d tmp.test_java_jul_trace_path.XXXXXX)
+               TRACE_PATH=$(mktemp -d -t tmp.test_java_jul_trace_path.XXXXXX)
 
                ${fct_test}
                if [ $? -ne 0 ]; then
index 825889f52539ae1b92b2721581217fd83c9bb663..556d473b4cd7f89486977d931660ff3dac97a1b3 100755 (executable)
@@ -57,8 +57,8 @@ function test_log4j_before_start ()
        local file_sync_after_first
        local file_sync_before_last
 
-       file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test LOG4J application BEFORE tracing starts"
        create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
@@ -579,7 +579,7 @@ tests=(
 
 for fct_test in "${tests[@]}";
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_java_log4j_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_java_log4j_trace_path.XXXXXX)
 
        ${fct_test}
 
index 11091f5455034f7270af86c9ae666980d74b5f27..55960be871023d3e34a4fd70901fccb2c8bcb371 100755 (executable)
@@ -58,8 +58,8 @@ function test_log4j2_before_start ()
        local file_sync_after_first
        local file_sync_before_last
 
-       file_sync_after_first=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
-       file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       file_sync_after_first=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_first.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
 
        diag "Test LOG4J2 application BEFORE tracing starts"
        create_lttng_session_ok "log4j2_before_start" "$TRACE_PATH"
@@ -580,7 +580,7 @@ tests=(
 
 for fct_test in "${tests[@]}";
 do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_java_log4j2_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_java_log4j2_trace_path.XXXXXX)
 
        ${fct_test}
 
index c7aa0d307479b9bf7eed71693e0e9dff703ee3b1..882dbb82f63097641d852b1ae54c361c95277de4 100644 (file)
@@ -7,8 +7,8 @@
 /* This program is used to test malloc instrumentation with libustinstr-malloc.
  */
 
-#include <string.h>
 #include <stdlib.h>
+#include <string.h>
 
 #define N_ITER 1000
 
@@ -19,7 +19,7 @@ int main(void)
        void *ptrs[N_ITER];
 
        for (i = 0; i < N_ITER; i++) {
-               ptrs[i] = malloc(i+1000);
+               ptrs[i] = malloc(i + 1000);
                if (!ptrs[i]) {
                        exit(EXIT_FAILURE);
                }
index f07152a28a97bd8aab0d7dd6e4b54878abba3bb7..37e6acb4181ecf9dbe804a5df5735c42b4cad8ce 100644 (file)
@@ -25,25 +25,38 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "lttng_ust_libc*")
 start_session(session_info)
 
-malloc_process = subprocess.Popen(test_path + "prog", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+malloc_process = subprocess.Popen(
+    test_path + "prog", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
+)
 malloc_process.wait()
 
-print_test_result(malloc_process.returncode == 0, current_test, "Test application exited normally")
+print_test_result(
+    malloc_process.returncode == 0, current_test, "Test application exited normally"
+)
 current_test += 1
 
 stop_session(session_info)
 
 # Check for malloc events in the resulting trace
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
-    bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN), session_info)
+    bail(
+        "Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN),
+        session_info,
+    )
 
 malloc_event_found = False
 free_event_found = False
@@ -53,7 +66,7 @@ for event_line in babeltrace_process.stdout:
     if malloc_event_found and free_event_found:
         continue
 
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
     if re.search(r".*lttng_ust_libc:malloc.*", event_line) is not None:
         malloc_event_found = True
 
@@ -62,13 +75,21 @@ for event_line in babeltrace_process.stdout:
 
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
-print_test_result(malloc_event_found, current_test, "lttng_ust_libc:malloc event found in resulting trace")
+print_test_result(
+    malloc_event_found,
+    current_test,
+    "lttng_ust_libc:malloc event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(free_event_found, current_test, "lttng_ust_libc:free event found in resulting trace")
+print_test_result(
+    free_event_found, current_test, "lttng_ust_libc:free event found in resulting trace"
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
index 74d1d22a601f11ab7840b59e41a54fa69e82fb52..43b0f641c4f4c8713806b55b822aca8768aa005c 100644 (file)
@@ -6,17 +6,17 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <stdarg.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <arpa/inet.h>
 #include <fcntl.h>
 #include <signal.h>
-#include <string.h>
-#include <arpa/inet.h>
+#include <stdarg.h>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #define TRACEPOINT_DEFINE
 
@@ -48,8 +48,7 @@ int main(int argc, char **argv)
        tracepoint(ust_tests_demo, starting, 123);
        for (i = 0; i < 5; i++) {
                netint = htonl(i);
-               tracepoint(ust_tests_demo2, loop, i, netint, values,
-                          text, strlen(text), dbl, flt);
+               tracepoint(ust_tests_demo2, loop, i, netint, values, text, strlen(text), dbl, flt);
        }
        tracepoint(ust_tests_demo, done, 456);
        tracepoint(ust_tests_demo3, done, 42);
index 264747ea68aeca8f8742ad46cbc3d36ac89b280e..38ae4ed4b7e0f9b70dc398454ade137e3dfa3c19 100644 (file)
@@ -47,11 +47,27 @@ def check_ust_test_demo2_event(event_line, expected_int_field_value):
     match = re.search(r".*_seqfield1_length = (\d+)", event_line)
     if match is None or int(match.group(1)) != 4:
         return False
-    match = re.search(r".*seqfield1 = \[ \[0\] = (\d+), \[1\] = (\d+), \[2\] = (\d+), \[3\] = (\d+) \]", event_line)
-    if match is None or int(match.group(1)) != 116 or int(match.group(2)) != 101 or int(match.group(3)) != 115 or int(match.group(4)) != 116:
+    match = re.search(
+        r".*seqfield1 = \[ \[0\] = (\d+), \[1\] = (\d+), \[2\] = (\d+), \[3\] = (\d+) \]",
+        event_line,
+    )
+    if (
+        match is None
+        or int(match.group(1)) != 116
+        or int(match.group(2)) != 101
+        or int(match.group(3)) != 115
+        or int(match.group(4)) != 116
+    ):
         return False
-    match = re.search(r".*arrfield1 = \[ \[0\] = (\d), \[1\] = (\d), \[2\] = (\d) \]", event_line)
-    if match is None or int(match.group(1)) != 1 or int(match.group(2)) != 2 or int(match.group(3)) != 3:
+    match = re.search(
+        r".*arrfield1 = \[ \[0\] = (\d), \[1\] = (\d), \[2\] = (\d) \]", event_line
+    )
+    if (
+        match is None
+        or int(match.group(1)) != 1
+        or int(match.group(2)) != 2
+        or int(match.group(3)) != 3
+    ):
         return False
     match = re.search(r".*arrfield2 = \"([a-z]*)\"", event_line)
     if match is None or match.group(1) != "test":
@@ -68,6 +84,7 @@ def check_ust_test_demo2_event(event_line, expected_int_field_value):
 
     return True
 
+
 NR_TESTS = 0
 DYNAMIC_TEST_ENABLED = False
 
@@ -78,7 +95,9 @@ if os.path.exists(test_path + "demo"):
     DYNAMIC_TEST_ENABLED = True
 
 # Only enable tests that were compiled successfully
-test_executables = [executable for executable in test_executables if os.path.exists(executable)]
+test_executables = [
+    executable for executable in test_executables if os.path.exists(executable)
+]
 
 NR_TESTS += len(test_executables) * 10
 
@@ -91,7 +110,9 @@ if NR_TESTS == 0:
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 if DYNAMIC_TEST_ENABLED:
     session_info = create_session()
@@ -99,16 +120,24 @@ if DYNAMIC_TEST_ENABLED:
     start_session(session_info)
 
     # Dry run, no events should be logged
-    demo_process = subprocess.Popen(test_path + "demo", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+    demo_process = subprocess.Popen(
+        test_path + "demo", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
+    )
     demo_process.wait()
     stop_session(session_info)
 
-    print_test_result(demo_process.returncode == 0, current_test,\
-                          "Running application dynamically linked to providers, no preload")
+    print_test_result(
+        demo_process.returncode == 0,
+        current_test,
+        "Running application dynamically linked to providers, no preload",
+    )
     current_test += 1
     trace_path = os.path.join(session_info.trace_path, "ust", "uid")
-    print_test_result(not os.path.exists(trace_path), current_test,\
-                          "No events logged when running demo application without preloading providers")
+    print_test_result(
+        not os.path.exists(trace_path),
+        current_test,
+        "No events logged when running demo application without preloading providers",
+    )
     current_test += 1
 
     shutil.rmtree(session_info.tmp_directory)
@@ -119,13 +148,16 @@ for executable in test_executables:
     enable_ust_tracepoint_event(session_info, "ust_tests_demo*")
     start_session(session_info)
 
-    demo_process = subprocess.Popen(executable, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+    demo_process = subprocess.Popen(
+        executable, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
+    )
     demo_process.wait()
     stop_session(session_info)
 
     trace_found = os.path.exists(session_info.trace_path)
-    print_test_result(trace_found, current_test,\
-                          "{0}, resulting trace found".format(executable_name))
+    print_test_result(
+        trace_found, current_test, "{0}, resulting trace found".format(executable_name)
+    )
     current_test += 1
 
     if not trace_found:
@@ -133,43 +165,78 @@ for executable in test_executables:
         continue
 
     try:
-        babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        babeltrace_process = subprocess.Popen(
+            [BABELTRACE_BIN, session_info.trace_path],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
     except FileNotFoundError:
-        bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN))
+        bail(
+            "Could not open {}. Please make sure it is installed.".format(
+                BABELTRACE_BIN
+            )
+        )
 
     # We should find 8 events in the resulting trace
     event_entries = []
     for event_line in babeltrace_process.stdout:
-        event_line = event_line.decode('utf-8').replace("\n", "")
+        event_line = event_line.decode("utf-8").replace("\n", "")
         event_entries.append(event_line)
 
     if len(event_entries) != 8:
-        bail("{0}, wrong number of events found in resulting trace.".format(executable_name))
+        bail(
+            "{0}, wrong number of events found in resulting trace.".format(
+                executable_name
+            )
+        )
 
     shutil.rmtree(session_info.tmp_directory)
 
-    print_test_result(len(event_entries) == 8, current_test,\
-                          "{0}, total number of events logged is correct".format(executable_name))
+    print_test_result(
+        len(event_entries) == 8,
+        current_test,
+        "{0}, total number of events logged is correct".format(executable_name),
+    )
     current_test += 1
 
     # Check each loop event
     match = re.search(r".*ust_tests_demo:starting.*value = (\d+) ", event_entries[0])
-    print_test_result(match is not None and (int(match.group(1)) == 123), current_test,\
-                          "{0}, ust_tests_demo:starting event found in trace with a correct integer argument".format(executable_name))
+    print_test_result(
+        match is not None and (int(match.group(1)) == 123),
+        current_test,
+        "{0}, ust_tests_demo:starting event found in trace with a correct integer argument".format(
+            executable_name
+        ),
+    )
     current_test += 1
 
     for i in range(5):
-        print_test_result(check_ust_test_demo2_event(event_entries[i+1], i), current_test,\
-                              "{0}, ust_tests_demo2:loop event found in trace and arguments are correct, iteration ".format(executable_name)\
-                              + str(i + 1))
+        print_test_result(
+            check_ust_test_demo2_event(event_entries[i + 1], i),
+            current_test,
+            "{0}, ust_tests_demo2:loop event found in trace and arguments are correct, iteration ".format(
+                executable_name
+            )
+            + str(i + 1),
+        )
         current_test += 1
 
     match = re.search(r".*ust_tests_demo:done.*value = (\d+)", event_entries[6])
-    print_test_result(match is not None and (int(match.group(1)) == 456), current_test,\
-                          "{0}, ust_tests_demo:done event found in resulting trace with a correct integer argument".format(executable_name))
+    print_test_result(
+        match is not None and (int(match.group(1)) == 456),
+        current_test,
+        "{0}, ust_tests_demo:done event found in resulting trace with a correct integer argument".format(
+            executable_name
+        ),
+    )
     current_test += 1
 
     match = re.search(r".*ust_tests_demo3:done.*value = (\d+)", event_entries[7])
-    print_test_result(match is not None and (int(match.group(1)) == 42), current_test,\
-                          "{0}, ust_tests_demo3:done event found in resulting trace with a correct integer argument".format(executable_name))
+    print_test_result(
+        match is not None and (int(match.group(1)) == 42),
+        current_test,
+        "{0}, ust_tests_demo3:done event found in resulting trace with a correct integer argument".format(
+            executable_name
+        ),
+    )
     current_test += 1
index 627873e4c448f99f2a6b55c687a5640edca18478..f08c407861a62748dd6157e802bd7cb2f48c1372 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo, starting,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_demo,
+                starting,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo, starting, TRACE_CRIT)
 
-TRACEPOINT_EVENT(ust_tests_demo, done,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_demo,
+                done,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo, done, TRACE_CRIT)
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO_H */
index b45f3899160220ffc21360d4e0b10edf9a29c7ac..6df9e1c4e0ebe0ba4e4f2da369371d01920dcec6 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo2, loop,
-       TP_ARGS(int, anint, int, netint, long *, values,
-                char *, text, size_t, textlen,
-                double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text,
-                            size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text,
-                            size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
+TRACEPOINT_EVENT(
+       ust_tests_demo2,
+       loop,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo2, loop, TRACE_WARNING)
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO2_H */
index e220f8bab1a31b9f8cc1116d6467f90a1da9afa0..7d4ca287a7ba4946f572a3ec61deb641280b05e2 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo3, done,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_demo3,
+                done,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo3, done, TRACE_WARNING)
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO3_H */
index e03d9f01eff5f4ef8c171b8d9f6659e795244c4a..2861324f2d303b2d1c19aee2a60f28398d09988b 100755 (executable)
@@ -19,7 +19,7 @@ if [ ! -x "$CURDIR/$BIN_NAME" ]; then
        BAIL_OUT "No UST nevents binary detected."
 fi
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_low_throughput_ust_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_low_throughput_ust_trace_path.XXXXXX)
 
 # MUST set TESTDIR before calling those functions
 
index 961f2e907c64acb2655200ab6a4655296605f2cb..d17d2bae044e969fcc74dabe0f319ee730800574 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, slow,
-       TP_ARGS(unsigned int, c, const char *, thread_name),
-       TP_FIELDS(
-               ctf_integer(unsigned int, counter, c)
-               ctf_string(th_name, thread_name)
-       )
-)
+TRACEPOINT_EVENT(tp,
+                slow,
+                TP_ARGS(unsigned int, c, const char *, thread_name),
+                TP_FIELDS(ctf_integer(unsigned int, counter, c) ctf_string(th_name, thread_name)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index ed86a0ed975f5fbbc9db3e1e7b4a15c71a72001c..d847e5b668a02129673cbb33eff6564696ac63f4 100644 (file)
@@ -7,14 +7,13 @@
 
 #define TRACEPOINT_DEFINE
 #define TRACEPOINT_PROBE_DYNAMIC_LINKAGE
+#include "callsites.h"
 #include "probes.h"
 
+#include <pthread.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <time.h>
-#include <pthread.h>
-
-#include "callsites.h"
 
 #ifndef VALUE
 #define VALUE (-1)
@@ -24,4 +23,3 @@ void call_tracepoint(void)
 {
        tracepoint(multi, tp, VALUE);
 }
-
index eb14162489ff07d924d25d0b8ae604206ce08ea0..155ef81ae27ebc6ba7c699916129ab48425fc915 100644 (file)
@@ -6,10 +6,10 @@
  */
 
 #include <dlfcn.h>
+#include <popt.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
-#include <popt.h>
 
 #if HAS_CALLSITES
 #include "callsites.h"
@@ -23,19 +23,20 @@ void exec_callsite(void)
 #endif
 }
 
-static
-void print_list(void)
+static void print_list(void)
 {
        fprintf(stderr, "Test list (-t X):\n");
-       fprintf(stderr, "\t0: dlopen() all libraries pass in arguments and execute "
-                       "the callsite.\n");
-       fprintf(stderr, "\t1: simulate the upgrade of a probe provider using dlopen() and dlclose(). \n");
-       fprintf(stderr, "\t2: simulate the upgrade of a library containing the callsites using dlopen() and dlclose(). \n");
+       fprintf(stderr,
+               "\t0: dlopen() all libraries pass in arguments and execute "
+               "the callsite.\n");
+       fprintf(stderr,
+               "\t1: simulate the upgrade of a probe provider using dlopen() and dlclose(). \n");
+       fprintf(stderr,
+               "\t2: simulate the upgrade of a library containing the callsites using dlopen() and dlclose(). \n");
 }
 
 #if HAS_CALLSITES
-static
-int dl_open_all(int nb_libraries, char **libraries)
+static int dl_open_all(int nb_libraries, char **libraries)
 {
        int i, ret = 0;
        void **handles;
@@ -65,8 +66,7 @@ error:
  * Takes 2 paths to libraries, dlopen() the first, trace, dlopen() the second,
  * and dlclose the first to simulate the upgrade of a library.
  */
-static
-int upgrade_lib(int nb_libraries, char **libraries)
+static int upgrade_lib(int nb_libraries, char **libraries)
 {
        int i, ret = 0;
        void *handles[2];
@@ -104,8 +104,7 @@ error:
  * Simulate the upgrade of a library containing a callsite.
  * Receives two libraries containing callsites for the same tracepoint.
  */
-static
-int upgrade_callsite(int nb_libraries, char **libraries)
+static int upgrade_callsite(int nb_libraries, char **libraries)
 {
        int ret = 0;
        void *handles[2];
@@ -175,10 +174,9 @@ int main(int argc, const char **argv)
        char **libraries = NULL;
        poptContext optCon;
        struct poptOption optionsTable[] = {
-                       { "test", 't', POPT_ARG_INT, &test, 0, "Test to run", NULL },
-                       { "list", 'l', 0, 0, 'l', "List of tests (-t X)", NULL },
-                       POPT_AUTOHELP
-                       { NULL, 0, 0, NULL, 0, NULL, NULL }
+               { "test", 't', POPT_ARG_INT, &test, 0, "Test to run", NULL },
+               { "list", 'l', 0, 0, 'l', "List of tests (-t X)", NULL },
+               POPT_AUTOHELP{ NULL, 0, 0, NULL, 0, NULL, NULL }
        };
 
        optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
@@ -189,7 +187,7 @@ int main(int argc, const char **argv)
        }
 
        while ((c = poptGetNextOpt(optCon)) >= 0) {
-               switch(c) {
+               switch (c) {
                case 'l':
                        print_list();
                        goto error;
@@ -212,29 +210,35 @@ int main(int argc, const char **argv)
                libraries[nb_libraries - 1] = (char *) poptGetArg(optCon);
        }
 
-       switch(test) {
+       switch (test) {
        case 0:
 #if HAS_CALLSITES
                ret = dl_open_all(nb_libraries, libraries);
 #else
-               fprintf(stderr, "Test not implemented for configuration "
-                               "(HAS_CALLSITES=%d)\n", HAS_CALLSITES == 1);
+               fprintf(stderr,
+                       "Test not implemented for configuration "
+                       "(HAS_CALLSITES=%d)\n",
+                       HAS_CALLSITES == 1);
 #endif
                break;
        case 1:
 #if HAS_CALLSITES
                ret = upgrade_lib(nb_libraries, libraries);
 #else
-               fprintf(stderr, "Test not implemented for configuration "
-                               "(HAS_CALLSITES=%d)\n", HAS_CALLSITES == 1);
+               fprintf(stderr,
+                       "Test not implemented for configuration "
+                       "(HAS_CALLSITES=%d)\n",
+                       HAS_CALLSITES == 1);
 #endif
                break;
        case 2:
 #if !HAS_CALLSITES
                ret = upgrade_callsite(nb_libraries, libraries);
 #else
-               fprintf(stderr, "Test not implemented for configuration "
-                               "(HAS_CALLSITES=%d)\n", HAS_CALLSITES == 1);
+               fprintf(stderr,
+                       "Test not implemented for configuration "
+                       "(HAS_CALLSITES=%d)\n",
+                       HAS_CALLSITES == 1);
 #endif
                break;
        default:
index 05bab2dd7c5963199cd8f12098e8e53c5b4c0bb5..d58fa26847a7cedc032f80111688f6315c3afdea 100644 (file)
 #define PROBES_H
 
 #include <lttng/tracepoint.h>
+
 #include <stdint.h>
 
 #if defined(ACTIVATE_PROBES_A)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer(uint64_t, arg_long_A, arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_integer(uint64_t, arg_long_A, arg)))
 #elif defined(ACTIVATE_PROBES_B)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer(uint64_t, arg_long_B, arg)
-               ctf_float(float, arg_float_B, (float) arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_integer(uint64_t, arg_long_B, arg)
+                                  ctf_float(float, arg_float_B, (float) arg)))
 #elif defined(ACTIVATE_PROBES_C)
-TRACEPOINT_ENUM(multi, enum_a,
-       TP_ENUM_VALUES(
-               ctf_enum_value("FIELD_A", 0)
-               ctf_enum_value("FIELD_B", 1)
-               ctf_enum_range("RANGE_C", 2, 10)
-       )
-)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_enum(multi, enum_a, int16_t, enum_short_C,  0)
-               ctf_enum(multi, enum_a, int32_t, enum_int_C,  1)
-               ctf_enum(multi, enum_a, uint64_t, enum_long_C,  2)
-       )
-)
+TRACEPOINT_ENUM(multi,
+               enum_a,
+               TP_ENUM_VALUES(ctf_enum_value("FIELD_A", 0) ctf_enum_value("FIELD_B", 1)
+                                      ctf_enum_range("RANGE_C", 2, 10)))
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_enum(multi, enum_a, int16_t, enum_short_C, 0)
+                                  ctf_enum(multi, enum_a, int32_t, enum_int_C, 1)
+                                          ctf_enum(multi, enum_a, uint64_t, enum_long_C, 2)))
 #elif defined(ACTIVATE_PROBES_D)
-TRACEPOINT_ENUM(multi, enum_a,
-       TP_ENUM_VALUES(
-               ctf_enum_value("FIELD_A", 0)
-               ctf_enum_value("FIELD_B", 1)
-               ctf_enum_range("RANGE_C_PRIME", 2, 10)
-       )
-)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_enum(multi, enum_a, int32_t, enum_int_D,  1)
-               ctf_enum(multi, enum_a, int16_t, enum_short_D,  0)
-               ctf_enum(multi, enum_a, uint64_t, enum_long_D,  2)
-       )
-)
+TRACEPOINT_ENUM(multi,
+               enum_a,
+               TP_ENUM_VALUES(ctf_enum_value("FIELD_A", 0) ctf_enum_value("FIELD_B", 1)
+                                      ctf_enum_range("RANGE_C_PRIME", 2, 10)))
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_enum(multi, enum_a, int32_t, enum_int_D, 1)
+                                  ctf_enum(multi, enum_a, int16_t, enum_short_D, 0)
+                                          ctf_enum(multi, enum_a, uint64_t, enum_long_D, 2)))
 #elif defined(ACTIVATE_PROBES_E)
 /*
  * Here we declare tracepoints really similar to one another but are different.
  * This is meant to test tracepoint comparaison code.
  */
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer(uint64_t, arg_long, arg)
-       )
-)
+TRACEPOINT_EVENT(multi, tp, TP_ARGS(uint64_t, arg), TP_FIELDS(ctf_integer(uint64_t, arg_long, arg)))
 #elif defined(ACTIVATE_PROBES_F)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer(int64_t, arg_long, arg)
-       )
-)
+TRACEPOINT_EVENT(multi, tp, TP_ARGS(uint64_t, arg), TP_FIELDS(ctf_integer(int64_t, arg_long, arg)))
 #elif defined(ACTIVATE_PROBES_G)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer_hex(int64_t, arg_long, arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_integer_hex(int64_t, arg_long, arg)))
 #elif defined(ACTIVATE_PROBES_H)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer_hex(int16_t, arg_long, arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_integer_hex(int16_t, arg_long, arg)))
 #elif defined(ACTIVATE_PROBES_I)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_integer_hex(int32_t, arg_long, arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_integer_hex(int32_t, arg_long, arg)))
 #elif defined(ACTIVATE_PROBES_J)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_float(float, arg_float, (float) arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_float(float, arg_float, (float) arg)))
 #elif defined(ACTIVATE_PROBES_K)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_float(double, arg_float, (double) arg)
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_float(double, arg_float, (double) arg)))
 #elif defined(ACTIVATE_PROBES_L)
-TRACEPOINT_ENUM(multi, enum_a,
-       TP_ENUM_VALUES(
-               ctf_enum_value("FIELD_A", 0)
-               ctf_enum_value("FIELD_B", 1)
-               ctf_enum_range("RANGE_C", 2, 10)
-       )
-)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_enum(multi, enum_a, int32_t, enum_int,  1)
-       )
-)
+TRACEPOINT_ENUM(multi,
+               enum_a,
+               TP_ENUM_VALUES(ctf_enum_value("FIELD_A", 0) ctf_enum_value("FIELD_B", 1)
+                                      ctf_enum_range("RANGE_C", 2, 10)))
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_enum(multi, enum_a, int32_t, enum_int, 1)))
 #elif defined(ACTIVATE_PROBES_M)
-TRACEPOINT_ENUM(multi, enum_a,
-       TP_ENUM_VALUES(
-               ctf_enum_value("FIELD_A", 0)
-               ctf_enum_value("FIELD_B", 1)
-               ctf_enum_range("RANGE_C", 2, 10)
-       )
-)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_enum(multi, enum_a, int64_t, enum_int,  1)
-       )
-)
+TRACEPOINT_ENUM(multi,
+               enum_a,
+               TP_ENUM_VALUES(ctf_enum_value("FIELD_A", 0) ctf_enum_value("FIELD_B", 1)
+                                      ctf_enum_range("RANGE_C", 2, 10)))
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_enum(multi, enum_a, int64_t, enum_int, 1)))
 #elif defined(ACTIVATE_PROBES_N)
-TRACEPOINT_ENUM(multi, enum_a,
-       TP_ENUM_VALUES(
-               ctf_enum_value("FIELD_A", 0)
-               ctf_enum_value("FIELD_B", 1)
-               ctf_enum_range("RANGE_C", 2, 10)
-       )
-)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_enum(multi, enum_a, int16_t, enum_int,  1)
-       )
-)
+TRACEPOINT_ENUM(multi,
+               enum_a,
+               TP_ENUM_VALUES(ctf_enum_value("FIELD_A", 0) ctf_enum_value("FIELD_B", 1)
+                                      ctf_enum_range("RANGE_C", 2, 10)))
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_enum(multi, enum_a, int16_t, enum_int, 1)))
 #elif defined(ACTIVATE_PROBES_O)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_string(arg_string, "string")
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_string(arg_string, "string")))
 #elif defined(ACTIVATE_PROBES_P)
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-               ctf_string(my_arg_string, "string")
-       )
-)
+TRACEPOINT_EVENT(multi,
+                tp,
+                TP_ARGS(uint64_t, arg),
+                TP_FIELDS(ctf_unused(arg) ctf_string(my_arg_string, "string")))
 #else
-TRACEPOINT_EVENT(multi, tp,
-       TP_ARGS(uint64_t, arg),
-       TP_FIELDS(
-               ctf_unused(arg)
-       )
-)
+TRACEPOINT_EVENT(multi, tp, TP_ARGS(uint64_t, arg), TP_FIELDS(ctf_unused(arg)))
 #endif
 
 #endif /* PROBES_H */
index 071d8e530ec7eb46328b002913e269a77cb588e7..4a96dd032f668f5cd066b30cf4c38747a6ae98bb 100755 (executable)
@@ -236,7 +236,7 @@ start_lttng_sessiond
 
 while [ "$i" -lt "$TEST_COUNT" ]; do
 
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_multi_lib_ust_trace_path.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_multi_lib_ust_trace_path.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
index 91f064daea1500df297172fdfbd7323f9ffaf9c4..c0d1c307e7fbce5760db4e3822e3fb242611c5b5 100755 (executable)
@@ -65,7 +65,7 @@ print_test_banner "$TEST_DESC"
 
 start_lttng_sessiond
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_multi_session_ust.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_multi_session_ust.XXXXXX)
 
 test_multi_session
 out=$?
index 09fb640a9076c8a585aa08ca7415627ff35eb4cf..09a4683bec1eeae9d0f186a4f5bd43787fa48538 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_gen_nevents, tptest0,
-       TP_ARGS(int, anint, long, value),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer(long, longfield, value)
-       )
-)
-
-TRACEPOINT_EVENT(ust_gen_nevents, tptest1,
-       TP_ARGS(int, anint, long, value),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer(long, longfield, value)
-       )
-)
-
-TRACEPOINT_EVENT(ust_gen_nevents, tptest2,
-       TP_ARGS(int, anint, long, value),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer(long, longfield, value)
-       )
-)
-
-TRACEPOINT_EVENT(ust_gen_nevents, tptest3,
-       TP_ARGS(int, anint, long, value),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer(long, longfield, value)
-       )
-)
+TRACEPOINT_EVENT(ust_gen_nevents,
+                tptest0,
+                TP_ARGS(int, anint, long, value),
+                TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer(long, longfield, value)))
+
+TRACEPOINT_EVENT(ust_gen_nevents,
+                tptest1,
+                TP_ARGS(int, anint, long, value),
+                TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer(long, longfield, value)))
+
+TRACEPOINT_EVENT(ust_gen_nevents,
+                tptest2,
+                TP_ARGS(int, anint, long, value),
+                TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer(long, longfield, value)))
+
+TRACEPOINT_EVENT(ust_gen_nevents,
+                tptest3,
+                TP_ARGS(int, anint, long, value),
+                TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer(long, longfield, value)))
 
 #endif /* _TRACEPOINT_UST_GEN_NEVENTS_H */
 
index e65cc247598533bf2f2053f38d7687395ed756e3..0af3193eff024d8036142f77db1a67edd5656dd3 100755 (executable)
@@ -44,7 +44,7 @@ function test_ns()
                return
        fi
 
-       trace_path=$(mktemp --tmpdir -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
 
        # Get the current ns inode number
        ns_inode=$(stat -c '%i' -L "/proc/$$/ns/$ns")
index 78fc37b5d1973b14a8d969fcbb2326f4fa256798..ac14748ee1cb93de842cbd55aaac98542812db61 100755 (executable)
@@ -46,9 +46,9 @@ function test_ns()
        ns_inode=$(stat -c '%i' -L "/proc/$$/ns/$ns")
        ok $? "Get current $ns namespace inode: $ns_inode" || ns_inode="invalid"
 
-       trace_path=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
-       file_sync_before_last=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
-       file_sync_after_unshare=$(mktemp --tmpdir -u "tmp.${FUNCNAME[0]}_sync_after_unshare.XXXXXX")
+       trace_path=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       file_sync_before_last=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_before_last.XXXXXX")
+       file_sync_after_unshare=$(mktemp -u -t "tmp.${FUNCNAME[0]}_sync_after_unshare.XXXXXX")
 
        start_lttng_sessiond
 
@@ -103,12 +103,7 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-isroot=0
-if [ "$(id -u)" == "0" ]; then
-       isroot=1
-fi
-
-skip $isroot "Root access is needed. Skipping all tests." "$NUM_TESTS" && exit 0
+check_skip_kernel_test "$NUM_TESTS" "Skipping all tests." && exit 0
 
 system_has_ns=0
 if [ -d "/proc/$$/ns" ]; then
index 7673370ce08ba2e8dc9f5d89ebbd1efe36da4c29..cd897d42b1f58cab69d809e3ee217cb35fb21745 100755 (executable)
@@ -7,20 +7,20 @@
 NUM_PROCESS=30
 TEST_DESC="UST tracer - Generate $NUM_PROCESS process"
 
-CURDIR=$(dirname $0)/
+CURDIR=$(dirname "$0")/
 TESTDIR=$CURDIR/../../..
-NR_ITER=-1     # infinite loop
+NR_ITER=-1 # infinite loop
 NR_USEC_WAIT=1000000
 TESTAPP_PATH="$TESTDIR/utils/testapp"
 TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="ust-nprocesses"
 EVENT_NAME="tp:tptest"
-TEST_WAIT_SEC=5
 NUM_TESTS=9
-APPS_PID=
+APP_PIDS=()
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../../../
+source "${TESTDIR}/utils/utils.sh"
 
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST $TESTAPP_BIN binary detected."
@@ -32,40 +32,42 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
+# shellcheck disable=SC2119
 start_lttng_sessiond
 
 # Start tests. Each is an infinite tracing loop.
 
-file_sync_after_first=$(mktemp --tmpdir -u tmp.test_nprocesses_sync_after_first.XXXXXX)
-file_sync_before_last=$(mktemp --tmpdir -u tmp.test_nprocesses_sync_before_last.XXXXXX)
+file_sync_after_first=$(mktemp -u -t tmp.test_nprocesses_sync_after_first.XXXXXX)
+file_sync_before_last=$(mktemp -u -t tmp.test_nprocesses_sync_before_last.XXXXXX)
 
 diag "Starting $NUM_PROCESS test applications"
-for i in `seq 1 $NUM_PROCESS`
+# shellcheck disable=SC2034
+for i in $(seq 1 $NUM_PROCESS)
 do
        $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT \
-               --sync-after-first-event ${file_sync_after_first} \
-               --sync-before-last-event ${file_sync_before_last} >/dev/null 2>&1 &
-       APPS_PID="${APPS_PID} ${!}"
+               --sync-after-first-event "${file_sync_after_first}" \
+               --sync-before-last-event "${file_sync_before_last}" >/dev/null 2>&1 &
+       APP_PIDS+=(${!})
 done
 
 diag "Waiting for applications to be registered to sessiond"
 
 reg_app_count=0
 while [ $reg_app_count -ne $NUM_PROCESS ]; do
-       listing=$($TESTDIR/../src/bin/lttng/$LTTNG_BIN list -u)
-       reg_app_count=$(echo -n $listing | sed "s#$TESTAPP_BIN#$TESTAPP_BIN\n#g" | grep "$TESTAPP_BIN" | wc -l)
+       listing=$("${TESTDIR}/../src/bin/lttng/${LTTNG_BIN}" list -u)
+       reg_app_count=$(echo -n "${listing}" | sed "s#$TESTAPP_BIN#$TESTAPP_BIN\n#g" | grep -c "$TESTAPP_BIN")
 done
 
 pass "All applications are registered to sessiond"
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_nprocesses_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_nprocesses_trace_path.XXXXXX)
 
-create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+create_lttng_session_ok $SESSION_NAME "${TRACE_PATH}"
 
 enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME
 start_lttng_tracing_ok $SESSION_NAME
 
-touch ${file_sync_before_last}
+touch "${file_sync_before_last}"
 
 # We don't validate whether the applications have traced here, rather
 # just that they registered to sessiond (above).
@@ -75,17 +77,16 @@ destroy_lttng_session_ok $SESSION_NAME
 
 #TODO: add trace validation.
 
-rm -rf $TRACE_PATH
+rm -rf "${TRACE_PATH}"
 
 diag "Stopping all spawned applications"
-for p in ${APPS_PID}; do
-       kill ${p}
-       wait ${p} 2>/dev/null
-done
-APPS_PID=
+kill "${APP_PIDS[@]}"
+wait "${APP_PIDS[@]}" 2>/dev/null
+APP_PIDS=()
 pass "Stopped all spawned applications"
 
-rm -f ${file_sync_after_first}
-rm -f ${file_sync_before_last}
+rm -f "${file_sync_after_first}"
+rm -f "${file_sync_before_last}"
 
+# shellcheck disable=SC2119
 stop_lttng_sessiond
index 4ca61cd022aa1b2d0f24a522d242d593a81ccb4e..12286293f43214a7a3ed7ba34f1eefe33ce4a5f1 100644 (file)
@@ -6,17 +6,17 @@
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <stdarg.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <arpa/inet.h>
 #include <fcntl.h>
 #include <signal.h>
-#include <string.h>
-#include <arpa/inet.h>
+#include <stdarg.h>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 
 #define TRACEPOINT_DEFINE
 #define TRACEPOINT_PROBE_DYNAMIC_LINKAGE
@@ -44,8 +44,7 @@ int main(int argc, char **argv)
        tracepoint(ust_tests_demo, starting, 123);
        for (i = 0; i < 5; i++) {
                netint = htonl(i);
-               tracepoint(ust_tests_demo2, loop, i, netint, values,
-                          text, strlen(text), dbl, flt);
+               tracepoint(ust_tests_demo2, loop, i, netint, values, text, strlen(text), dbl, flt);
        }
        tracepoint(ust_tests_demo, done, 456);
        tracepoint(ust_tests_demo3, done, 42);
index 8c9c89058be1398064c9b2f8c2ee8880895dfa90..c9d12eaed943050855d0270eb66f4dbb3d0c8650 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo, starting,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_demo,
+                starting,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo, starting, TRACE_CRIT)
 
 /*
  * Dummy model information, just for example. TODO: we should check if
  * EMF model URI have some standard format we should follow.
  */
-TRACEPOINT_MODEL_EMF_URI(ust_tests_demo, starting,
-       "http://example.com/path_to_model?q=ust_tests_demo:starting")
-
-TRACEPOINT_EVENT(ust_tests_demo, done,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_MODEL_EMF_URI(ust_tests_demo,
+                        starting,
+                        "http://example.com/path_to_model?q=ust_tests_demo:starting")
+
+TRACEPOINT_EVENT(ust_tests_demo,
+                done,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo, done, TRACE_CRIT)
 
-TRACEPOINT_MODEL_EMF_URI(ust_tests_demo, done,
-       "http://example.com/path_to_model?q=ust_tests_demo:done")
+TRACEPOINT_MODEL_EMF_URI(ust_tests_demo,
+                        done,
+                        "http://example.com/path_to_model?q=ust_tests_demo:done")
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO_H */
 
index a8b30e8a11997453ffbb47a986547f12ae17fa88..0c39786b6650e8a6cd5047d02539fa3302e3abc5 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo2, loop,
-       TP_ARGS(int, anint, int, netint, long *, values,
-                char *, text, size_t, textlen,
-                double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text,
-                            size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text,
-                            size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
+TRACEPOINT_EVENT(
+       ust_tests_demo2,
+       loop,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo2, loop, TRACE_WARNING)
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO2_H */
index 7511c2dc175318431a88d21b2eac982e71c12e35..8018f22acfa26ea0629fd8853a35de40952202ad 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(ust_tests_demo3, done,
-       TP_ARGS(int, value),
-       TP_FIELDS(
-               ctf_integer(int, value, value)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_demo3,
+                done,
+                TP_ARGS(int, value),
+                TP_FIELDS(ctf_integer(int, value, value)))
 TRACEPOINT_LOGLEVEL(ust_tests_demo3, done, TRACE_WARNING)
 
 #endif /* _TRACEPOINT_UST_TESTS_DEMO3_H */
index a942d066afae2fea9ef8ac99521711a421010219..8eddc8247bb696ccc5977a8ef5d41af23b4f7adf 100755 (executable)
@@ -645,7 +645,7 @@ start_lttng_sessiond
 
 while [ "$i" -lt "$TEST_COUNT" ]; do
 
-       TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_overlap.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_overlap.XXXXXX)
 
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
 
index d81d475d47632efc57645e403ec94037ffeae803..f1132c2e49e9218b465f1688b037f146a1891713 100755 (executable)
@@ -6,8 +6,8 @@
 
 TEST_DESC="UST tracer - Tracing with per UID buffers and periodical flush"
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/../../..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/../../.."
 NR_ITER=100
 NR_USEC_WAIT=100000
 TESTAPP_PATH="$TESTDIR/utils/testapp"
@@ -15,12 +15,12 @@ TESTAPP_NAME="gen-ust-events"
 TESTAPP_BIN="$TESTAPP_PATH/$TESTAPP_NAME/$TESTAPP_NAME"
 SESSION_NAME="periodical-flush"
 EVENT_NAME="tp:tptest"
-BIN_NAME="gen-nevents"
 NUM_TESTS=38
-APP_TMP_FILE=$(mktemp --tmpdir -u tmp.test_periodical_metadata_flush_ust_app_tmp_file.XXXXXX)
-APPS_PID=
+APP_TMP_FILE=$(mktemp -u -t tmp.test_periodical_metadata_flush_ust_app_tmp_file.XXXXXX)
+APP_PIDS=()
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../../../
+source "$TESTDIR/utils/utils.sh"
 
 if [ ! -x "$TESTAPP_BIN" ]; then
        BAIL_OUT "No UST events binary detected."
@@ -33,7 +33,7 @@ function enable_channel_per_uid()
        local sess_name=$1
        local channel_name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name --switch-timer 100000 >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" --switch-timer 100000 >/dev/null 2>&1
        ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
@@ -42,7 +42,7 @@ function enable_channel_per_pid()
        local sess_name=$1
        local channel_name=$2
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-pid -u $channel_name -s $sess_name --switch-timer 100000 >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-pid -u "$channel_name" -s "$sess_name" --switch-timer 100000 >/dev/null 2>&1
        ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
@@ -51,7 +51,7 @@ function enable_metadata_per_uid()
        local sess_name=$1
        local channel_name="metadata"
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name --switch-timer 200000 >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" --switch-timer 200000  2>&1
        ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
@@ -60,7 +60,7 @@ function enable_metadata_per_pid()
        local sess_name=$1
        local channel_name="metadata"
 
-       $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-pid -u $channel_name -s $sess_name --switch-timer 200000 >/dev/null 2>&1
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-pid -u "$channel_name" -s "$sess_name" --switch-timer 200000 >/dev/null 2>&1
        ok $? "Enable channel $channel_name per PID for session $sess_name"
 }
 
@@ -68,8 +68,8 @@ function validate_trace()
 {
        local out
 
-       out=$("$BABELTRACE_BIN" $TRACE_PATH | grep $EVENT_NAME | wc -l)
-       if [ $out -eq 0 ]; then
+       out=$("$BABELTRACE_BIN" "$TRACE_PATH" | grep -c $EVENT_NAME)
+       if [ "$out" -eq 0 ]; then
                fail "Trace validation"
                diag "No event(s) found. We are supposed to have at least one."
                out=1
@@ -90,15 +90,15 @@ function check_app_tmp_file()
                sleep 0.5
        done
        diag "Removing test app temporary file $APP_TMP_FILE"
-       rm -f $APP_TMP_FILE
+       rm -f "$APP_TMP_FILE"
 }
 
 function start_trace_app()
 {
        # Start application with a temporary file.
-       $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event $APP_TMP_FILE &
+       $TESTAPP_BIN -i $NR_ITER -w $NR_USEC_WAIT --sync-after-first-event "$APP_TMP_FILE" &
        ret=$?
-       APPS_PID="${APPS_PID} ${!}"
+       APP_PIDS+=(${!})
        ok $ret "Start application to trace"
 }
 
@@ -111,20 +111,18 @@ function start_check_trace_app()
 
 function wait_trace_apps()
 {
-       for p in ${APPS_PID}; do
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       wait "${APP_PIDS[@]}" 2> /dev/null
+       APP_PIDS=()
 }
 
 test_after_app_pid() {
        local out
 
-       APPS_PID=
+       APP_PIDS=()
 
        diag "Start application AFTER tracing is started"
 
-       create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+       create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
        enable_metadata_per_pid $SESSION_NAME
        enable_channel_per_pid $SESSION_NAME "channel0"
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME "channel0"
@@ -137,20 +135,17 @@ test_after_app_pid() {
        # Make sure the application does not generate any more data,
        # thus ensuring that we are not flushing a packet concurrently
        # with validate_trace.
-       for p in ${APPS_PID}; do
-               kill -s SIGSTOP ${p}
-       done
+       kill -s SIGSTOP "${APP_PIDS[@]}"
 
        # Give time to the consumer to write inflight data.
        sleep 2
 
+       # shellcheck disable=SC2119
        validate_trace
        out=$?
 
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
        stop_lttng_tracing_ok $SESSION_NAME
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -161,16 +156,15 @@ test_after_app_pid() {
 
 test_before_app_pid() {
        local out
-       local tmp_file="/tmp/lttng_test_ust.42.file"
 
-       APPS_PID=
+       APP_PIDS=()
 
        diag "Start application BEFORE tracing is started"
 
        start_trace_app
 
        # Start application before tracing
-       create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+       create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
        enable_metadata_per_pid $SESSION_NAME
        enable_channel_per_pid $SESSION_NAME "channel0"
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME "channel0"
@@ -183,20 +177,17 @@ test_before_app_pid() {
        # Make sure the application does not generate any more data,
        # thus ensuring that we are not flushing a packet concurrently
        # with validate_trace.
-       for p in ${APPS_PID}; do
-               kill -s SIGSTOP ${p}
-       done
+       kill -s SIGSTOP "${APP_PIDS[@]}"
 
        # Give time to the consumer to write inflight data.
        sleep 2
 
+       # shellcheck disable=SC2119
        validate_trace
        out=$?
 
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
 
        stop_lttng_tracing_ok $SESSION_NAME
        destroy_lttng_session_ok $SESSION_NAME
@@ -209,11 +200,11 @@ test_before_app_pid() {
 test_after_app_uid() {
        local out
 
-       APPS_PID=
+       APP_PIDS=()
 
        diag "Start application AFTER tracing is started"
 
-       create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+       create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
        enable_metadata_per_uid $SESSION_NAME
        enable_channel_per_uid $SESSION_NAME "channel0"
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME "channel0"
@@ -226,21 +217,17 @@ test_after_app_uid() {
        # Make sure the application does not generate any more data,
        # thus ensuring that we are not flushing a packet concurrently
        # with validate_trace.
-       for p in ${APPS_PID}; do
-               kill -s SIGSTOP ${p}
-       done
-
+       kill -s SIGSTOP "${APP_PIDS[@]}"
 
        # Give time to the consumer to write inflight data.
        sleep 2
 
+       # shellcheck disable=SC2119
        validate_trace
        out=$?
 
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}"
        stop_lttng_tracing_ok $SESSION_NAME
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -252,14 +239,14 @@ test_after_app_uid() {
 test_before_app_uid() {
        local out
 
-       APPS_PID=
+       APP_PIDS=()
 
        diag "Start application BEFORE tracing is started"
 
        # Start application before tracing
        start_trace_app
 
-       create_lttng_session_ok $SESSION_NAME $TRACE_PATH
+       create_lttng_session_ok $SESSION_NAME "$TRACE_PATH"
        enable_metadata_per_uid $SESSION_NAME
        enable_channel_per_uid $SESSION_NAME "channel0"
        enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME "channel0"
@@ -272,20 +259,17 @@ test_before_app_uid() {
        # Make sure the application does not generate any more data,
        # thus ensuring that we are not flushing a packet concurrently
        # with validate_trace.
-       for p in ${APPS_PID}; do
-               kill -s SIGSTOP ${p}
-       done
+       kill -s SIGSTOP "${APP_PIDS[@]}"
 
        # Give time to the consumer to write inflight data.
        sleep 2
 
+       # shellcheck disable=SC2119
        validate_trace
        out=$?
 
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}"
        stop_lttng_tracing_ok $SESSION_NAME
        destroy_lttng_session_ok $SESSION_NAME
 
@@ -310,13 +294,15 @@ TESTS=(
 TEST_COUNT=${#TESTS[@]}
 i=0
 
+# shellcheck disable=SC2119
 start_lttng_sessiond
 
-while [ $i -lt $TEST_COUNT ]; do
-       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_periodical_metadata_flush_ust_trace_path.XXXXXX)
+while [ $i -lt "$TEST_COUNT" ]; do
+       TRACE_PATH=$(mktemp -d -t tmp.test_periodical_metadata_flush_ust_trace_path.XXXXXX)
        ${TESTS[$i]}
-       rm -rf $TRACE_PATH
-       let "i++"
+       rm -rf "$TRACE_PATH"
+       (( "i++" ))
 done
 
+# shellcheck disable=SC2119
 stop_lttng_sessiond
index 470452260eb49132258425ab7a914e62bbe6f58f..0bb7ef24d82989e77ed71b945c3fcf6dcd6fa6ab 100755 (executable)
@@ -106,8 +106,8 @@ function enable_python_filter_loglevel_only()
 
 function test_python_before_start ()
 {
-       local ready_file=$(mktemp --tmpdir -u)
-       local go_file=$(mktemp --tmpdir -u)
+       local ready_file=$(mktemp -u -t)
+       local go_file=$(mktemp -u -t)
 
        diag "Test Python application BEFORE tracing starts"
        create_lttng_session_ok $SESSION_NAME $TRACE_PATH
@@ -688,7 +688,7 @@ function test_python_filter_loglevel()
 function test_python_trigger_notify_action
 {
        uid=$(id --user)
-       tmp_expected_stdout=$(mktemp --tmpdir -t test_list_triggers_python_cli_expected_stdout.XXXXXX)
+       tmp_expected_stdout=$(mktemp -t test_list_triggers_python_cli_expected_stdout.XXXXXX)
 
        diag "Test Python trigger with notify action"
 
@@ -754,7 +754,7 @@ skip $skip_agent "Python agent test skipped." $NUM_TESTS ||
        do
                for fct_test in ${tests[@]};
                do
-                       TRACE_PATH=$(mktemp --tmpdir -d tmp.test_python_logging_trace_path.XXXXXX)
+                       TRACE_PATH=$(mktemp -d -t tmp.test_python_logging_trace_path.XXXXXX)
 
                        diag "(Python $python_version)"
                        ${fct_test} $python_version
index 8ef4f0d8cd8b7c95288abdfdd3743793190e004d..64161768f1e3fe286fc84a1d65577c5a1ce7c7c3 100755 (executable)
@@ -23,11 +23,11 @@ SIZE_LIMIT=$PAGE_SIZE
 NR_ITER=10
 NUM_TESTS=$((15*$NR_ITER))
 
-# Ensure the daemons invoke abort on error.
-export LTTNG_ABORT_ON_ERROR=1
-
 source $TESTDIR/utils/utils.sh
 
+# Ensure the daemons invoke abort on error.
+check_skip_kernel_test || export LTTNG_ABORT_ON_ERROR=1
+
 # MUST set TESTDIR before calling those functions
 function run_app()
 {
@@ -130,7 +130,7 @@ while [ "$i" -lt "$TEST_COUNT" ]; do
 
        trap signal_cleanup SIGTERM SIGINT
 
-       TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_rotation_destroy_flush.XXXXXX)
+       TRACE_PATH=$(mktemp -d -t tmp.test_rotation_destroy_flush.XXXXXX)
 
        # Execute test
        ${TESTS[$i]}
index dd0c771451c5e73ec65574c8863bd16b941db23f..1e4e67f61f046b178e59c8aba7f5c9cb964a470f 100755 (executable)
@@ -19,7 +19,7 @@ source $TESTDIR/utils/utils.sh
 
 function test_event_basic()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="ust_event_basic"
        SESSION_NAME2="ust_event_basic2"
        CHAN_NAME="mychan"
index 01c137a19b23a3b3d72f32b11416d152e764822a..127cdb0b7f25304257567a7c26995ba127fbf54c 100755 (executable)
@@ -56,7 +56,7 @@ function add_context_ust_skip_ok()
 # Only test parsing of the enabling by raw ID
 function test_parsing_raw()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="ust_event_basic"
        CHAN_NAME="mychan"
 
@@ -84,7 +84,7 @@ function test_parsing_raw()
 
 function test_event_basic()
 {
-       TRACE_PATH=$(mktemp --tmpdir -d "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
+       TRACE_PATH=$(mktemp -d -t "tmp.${FUNCNAME[0]}_trace_path.XXXXXX")
        SESSION_NAME="ust_event_basic"
        CHAN_NAME="mychan"
 
@@ -121,17 +121,11 @@ print_test_banner "$TEST_DESC"
 
 bail_out_if_no_babeltrace
 
-if [ "$(id -u)" == "0" ]; then
-        isroot=1
-else
-        isroot=0
-fi
-
 start_lttng_sessiond
 
 test_parsing_raw
 
-skip $isroot "Root access is needed. Skipping UST perf tests." 8 ||
+check_skip_kernel_test 8 "Skipping UST perf tests." ||
 {
        test_event_basic
 }
index 2d7a6415492a07166be69af9a63a36c8d59dd04e..30922a6cf9ea5a7a921980fc2ed56da20002ebb0 100755 (executable)
@@ -49,7 +49,7 @@ bail_out_if_no_babeltrace
 
 start_lttng_sessiond
 
-TRACE_PATH=$(mktemp --tmpdir -d tmp.test_event_tracef_trace_path.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_event_tracef_trace_path.XXXXXX)
 test_event_tracef
 out=$?
 if [ $out -ne 0 ]; then
index bdb649b9a1f2400d1196f30aafa04ba6cdeab232..0d74dee0e35b7042bd4aa4e0c4cecde24261eb86 100644 (file)
@@ -24,7 +24,9 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("No sessiond running. Please make sure you are running this test with the \"run\" shell script and verify that the lttng tools are properly installed.")
+    bail(
+        'No sessiond running. Please make sure you are running this test with the "run" shell script and verify that the lttng tools are properly installed.'
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "ust_tests_td*")
@@ -33,67 +35,116 @@ start_session(session_info)
 test_env = os.environ.copy()
 test_env["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
 
-td_process = subprocess.Popen(test_path + "type-declarations", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=test_env)
+td_process = subprocess.Popen(
+    test_path + "type-declarations",
+    stdout=subprocess.DEVNULL,
+    stderr=subprocess.DEVNULL,
+    env=test_env,
+)
 td_process.wait()
 
-print_test_result(td_process.returncode == 0, current_test, "Test application exited normally")
+print_test_result(
+    td_process.returncode == 0, current_test, "Test application exited normally"
+)
 current_test += 1
 
 stop_session(session_info)
 
 # Check event fields using type declarations are present
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
     bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN))
 
 event_lines = []
 for event_line in babeltrace_process.stdout:
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
     event_lines.append(event_line)
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
 if babeltrace_process.returncode != 0:
     bail("Unreadable trace; can't proceed with analysis.")
 
-print_test_result(len(event_lines) == 5, current_test, "Correct number of events found in resulting trace")
+print_test_result(
+    len(event_lines) == 5,
+    current_test,
+    "Correct number of events found in resulting trace",
+)
 current_test += 1
 
 if len(event_lines) != 5:
-    bail("Unexpected number of events found in resulting trace (" + session_info.trace_path + ")." )
-
-match = re.search(r".*ust_tests_td:(.*):.*enumfield = \( \"(.*)\" :.*enumfield_bis = \( \"(.*)\" :.*enumfield_third = .*:.*", event_lines[0])
-print_test_result(match is not None and match.group(1) == "tptest", current_test,\
-                      "First tracepoint is present")
+    bail(
+        "Unexpected number of events found in resulting trace ("
+        + session_info.trace_path
+        + ")."
+    )
+
+match = re.search(
+    r".*ust_tests_td:(.*):.*enumfield = \( \"(.*)\" :.*enumfield_bis = \( \"(.*)\" :.*enumfield_third = .*:.*",
+    event_lines[0],
+)
+print_test_result(
+    match is not None and match.group(1) == "tptest",
+    current_test,
+    "First tracepoint is present",
+)
 current_test += 1
 
-print_test_result(match is not None and match.group(2) == "zero", current_test,\
-                      "First tracepoint's enum value maps to zero")
+print_test_result(
+    match is not None and match.group(2) == "zero",
+    current_test,
+    "First tracepoint's enum value maps to zero",
+)
 current_test += 1
 
-print_test_result(match is not None and match.group(3) == "one", current_test,\
-                      "First tracepoint's second enum value maps to one")
+print_test_result(
+    match is not None and match.group(3) == "one",
+    current_test,
+    "First tracepoint's second enum value maps to one",
+)
 current_test += 1
 
 match = re.search(r".*ust_tests_td:(.*):.*enumfield = \( \"(.*)\" :.*", event_lines[1])
-print_test_result(match is not None and match.group(1) == "tptest_bis", current_test,\
-                      "Second tracepoint is present")
+print_test_result(
+    match is not None and match.group(1) == "tptest_bis",
+    current_test,
+    "Second tracepoint is present",
+)
 current_test += 1
 
-print_test_result(match is not None and match.group(2) == "zero", current_test,\
-                      "Second tracepoint's enum value maps to zero")
+print_test_result(
+    match is not None and match.group(2) == "zero",
+    current_test,
+    "Second tracepoint's enum value maps to zero",
+)
 current_test += 1
 
-match = re.search(r".*ust_tests_td:(.*):.*enumfield = \( \"(.*)\" :.*enumfield_bis = \( \"(.*)\" .*", event_lines[2])
+match = re.search(
+    r".*ust_tests_td:(.*):.*enumfield = \( \"(.*)\" :.*enumfield_bis = \( \"(.*)\" .*",
+    event_lines[2],
+)
 
-print_test_result(match is not None and match.group(2) == "one", current_test,\
-                      "Third tracepoint's enum value maps to one")
+print_test_result(
+    match is not None and match.group(2) == "one",
+    current_test,
+    "Third tracepoint's enum value maps to one",
+)
 current_test += 1
 
-print_test_result('{ zero = ( "zero" : container = 0 ), two = ( "two" : container = 2 ), three = ( "three" : container = 3 ), fifteen = ( "ten_to_twenty" : container = 15 ), twenty_one = ( "twenty_one" : container = 21 ) }' in event_lines[4],
-                  current_test, 'Auto-incrementing enum values are correct')
+print_test_result(
+    '{ zero = ( "zero" : container = 0 ), two = ( "two" : container = 2 ), three = ( "three" : container = 3 ), fifteen = ( "ten_to_twenty" : container = 15 ), twenty_one = ( "twenty_one" : container = 21 ) }'
+    in event_lines[4],
+    current_test,
+    "Auto-incrementing enum values are correct",
+)
 
 shutil.rmtree(session_info.tmp_directory)
index d7d2aff73939f408218e3d2eac14d09784ba6a2c..7ac8981ca5132efa3d3c7ebee99de76a726c4e60 100644 (file)
@@ -20,8 +20,8 @@ int main(void)
        int i;
 
        for (i = 0; i < 2; i++) {
-               tracepoint(ust_tests_td, tptest, i % 2, (i+1) % 2, i % 21);
-               tracepoint(ust_tests_td, tptest_bis,  i % 2);
+               tracepoint(ust_tests_td, tptest, i % 2, (i + 1) % 2, i % 21);
+               tracepoint(ust_tests_td, tptest_bis, i % 2);
        }
 
        tracepoint(ust_tests_td, test_auto);
index 84a8f7c32a81dfd6dca2dfe7b3abd35eaf6c79e2..8551b328df106deeb0a982e070fc5b93e11d6dfc 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_ENUM(ust_tests_td, testenum,
-       TP_ENUM_VALUES(
-               ctf_enum_value("zero", 0)
-               ctf_enum_value("one", 1)
-       )
-)
+TRACEPOINT_ENUM(ust_tests_td,
+               testenum,
+               TP_ENUM_VALUES(ctf_enum_value("zero", 0) ctf_enum_value("one", 1)))
 
-TRACEPOINT_ENUM(ust_tests_td, testenum2,
-       TP_ENUM_VALUES(
-               ctf_enum_value("zero", 0)
-               ctf_enum_value("five", 5)
-               ctf_enum_range("ten_to_twenty", 10, 20)
-       )
-)
+TRACEPOINT_ENUM(ust_tests_td,
+               testenum2,
+               TP_ENUM_VALUES(ctf_enum_value("zero", 0) ctf_enum_value("five", 5)
+                                      ctf_enum_range("ten_to_twenty", 10, 20)))
 
-TRACEPOINT_ENUM(ust_tests_td, testenum3,
-       TP_ENUM_VALUES(
-               ctf_enum_auto("zero")
-               ctf_enum_value("two", 2)
-               ctf_enum_auto("three")
-               ctf_enum_range("ten_to_twenty", 10, 20)
-               ctf_enum_auto("twenty_one")
-       )
-)
+TRACEPOINT_ENUM(ust_tests_td,
+               testenum3,
+               TP_ENUM_VALUES(ctf_enum_auto("zero") ctf_enum_value("two", 2) ctf_enum_auto("three")
+                                      ctf_enum_range("ten_to_twenty", 10, 20)
+                                              ctf_enum_auto("twenty_one")))
 
 /*
  * Enumeration field is used twice to make sure the global type declaration
  * is entered only once in the metadata file.
  */
-TRACEPOINT_EVENT(ust_tests_td, tptest,
+TRACEPOINT_EVENT(
+       ust_tests_td,
+       tptest,
        TP_ARGS(int, enumval, int, enumval2, int, enumval3),
        TP_FIELDS(
-               ctf_enum(ust_tests_td, testenum, int, enumfield, enumval)
-               ctf_enum(ust_tests_td, testenum, long long,
-                               enumfield_bis, enumval2)
-               ctf_enum(ust_tests_td, testenum2, unsigned int,
-                               enumfield_third, enumval3)
-       )
-)
+               ctf_enum(ust_tests_td, testenum, int, enumfield, enumval) ctf_enum(
+                       ust_tests_td, testenum, long long, enumfield_bis, enumval2)
+                       ctf_enum(ust_tests_td, testenum2, unsigned int, enumfield_third, enumval3)))
 
 /*
  * Another tracepoint using the global types to make sure each global type is
  * entered only once in the metadata file.
  */
-TRACEPOINT_EVENT(ust_tests_td, tptest_bis,
-       TP_ARGS(int, enumval),
-       TP_FIELDS(
-               ctf_enum(ust_tests_td, testenum, unsigned char,
-                               enumfield, enumval)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_td,
+                tptest_bis,
+                TP_ARGS(int, enumval),
+                TP_FIELDS(ctf_enum(ust_tests_td, testenum, unsigned char, enumfield, enumval)))
 
 /*
  * Test autoincrementing enumeration values.
  */
-TRACEPOINT_EVENT(ust_tests_td, test_auto,
-       TP_ARGS(void),
-       TP_FIELDS(
-               ctf_enum(ust_tests_td, testenum3, int, zero, 0)
-               ctf_enum(ust_tests_td, testenum3, int, two, 2)
-               ctf_enum(ust_tests_td, testenum3, int, three, 3)
-               ctf_enum(ust_tests_td, testenum3, int, fifteen, 15)
-               ctf_enum(ust_tests_td, testenum3, int, twenty_one, 21)
-       )
-)
+TRACEPOINT_EVENT(ust_tests_td,
+                test_auto,
+                TP_ARGS(void),
+                TP_FIELDS(ctf_enum(ust_tests_td, testenum3, int, zero, 0) ctf_enum(
+                        ust_tests_td, testenum3, int, two, 2)
+                                  ctf_enum(ust_tests_td, testenum3, int, three, 3) ctf_enum(
+                                          ust_tests_td, testenum3, int, fifteen, 15)
+                                          ctf_enum(ust_tests_td, testenum3, int, twenty_one, 21)))
 
 #endif /* _TRACEPOINT_UST_TESTS_TD_H */
 
diff --git a/tests/regression/ust/ust-constructor/Makefile.am b/tests/regression/ust/ust-constructor/Makefile.am
new file mode 100644 (file)
index 0000000..89267d3
--- /dev/null
@@ -0,0 +1,30 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+noinst_SCRIPTS = __init__.py \
+       test_ust_constructor_c_dynamic.py \
+       test_ust_constructor_c_static.py \
+       test_ust_constructor_cpp_dynamic.py \
+       test_ust_constructor_cpp_static.py \
+       ust_constructor_common.py
+
+EXTRA_DIST = __init__.py \
+       test_ust_constructor_c_dynamic.py \
+       test_ust_constructor_c_static.py \
+       test_ust_constructor_cpp_dynamic.py \
+       test_ust_constructor_cpp_static.py \
+       ust_constructor_common.py
+
+
+all-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       cp -f $(srcdir)/$$script $(builddir); \
+               done; \
+       fi
+
+clean-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       rm -f $(builddir)/$$script; \
+               done; \
+       fi
diff --git a/tests/regression/ust/ust-constructor/__init__.py b/tests/regression/ust/ust-constructor/__init__.py
new file mode 100644 (file)
index 0000000..5acd59f
--- /dev/null
@@ -0,0 +1,4 @@
+#!/usr/bin/env python3
+#
+# SPDX-FileCopyrightText: Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifier: GPL-2.0-only
diff --git a/tests/regression/ust/ust-constructor/test_ust_constructor_c_dynamic.py b/tests/regression/ust/ust-constructor/test_ust_constructor_c_dynamic.py
new file mode 100755 (executable)
index 0000000..93ef4c1
--- /dev/null
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+#
+# SPDX-FileCopyrightText: Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""
+Test instrumentation coverage of C constructors and destructors by LTTng-UST
+tracepoints with a dynamic object.
+
+This test successively sets up a session, traces a test application, and then
+reads the resulting trace to determine if all the expected events are present.
+"""
+
+import copy
+import pathlib
+import sys
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import ust_constructor_common as ust
+
+test = {
+    "description": "Test user space constructor/destructor instrumentation coverage (C w/ dynamic object)",
+    "application": "gen-ust-events-constructor/gen-ust-events-c-constructor-so",
+    "expected_events": copy.deepcopy(
+        ust.expected_events_common + ust.expected_events_tp_so
+    ),
+    # This application is not be built when `NO_SHARED` is set in the
+    # configuration options.
+    "skip_if_application_not_present": True,
+}
+
+tap = lttngtest.TapGenerator(7 + len(test["expected_events"]))
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    try:
+        outputlocation = ust.capture_trace(
+            tap, test_env, test["application"], test["description"]
+        )
+    except FileNotFoundError as fne:
+        tap.diagnostic(fne)
+        if test["skip_if_application_not_present"]:
+            tap.skip(
+                "Test application '{}' not found".format(test["application"]),
+                tap.remaining_test_cases,
+            )
+            sys.exit(0)
+    # Warning: validate_trace mutates test['expected_events']
+    ust.validate_trace(outputlocation.path, tap, test["expected_events"])
+
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/ust/ust-constructor/test_ust_constructor_c_static.py b/tests/regression/ust/ust-constructor/test_ust_constructor_c_static.py
new file mode 100755 (executable)
index 0000000..4fb509a
--- /dev/null
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+#
+# SPDX-FileCopyrightText: Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""
+Test instrumentation coverage of C constructors and destructors by LTTng-UST
+tracepoints with a static archive.
+
+This test successively sets up a session, traces a test application, and then
+reads the resulting trace to determine if all the expected events are present.
+"""
+
+import copy
+import pathlib
+import sys
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import ust_constructor_common as ust
+
+test = {
+    "description": "Test user space constructor/destructor instrumentation coverage (C w/ static archive)",
+    "application": "gen-ust-events-constructor/gen-ust-events-c-constructor-a",
+    "expected_events": copy.deepcopy(
+        ust.expected_events_common + ust.expected_events_tp_a
+    ),
+    "skip_if_application_not_present": False,
+}
+
+tap = lttngtest.TapGenerator(7 + len(test["expected_events"]))
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    try:
+        outputlocation = ust.capture_trace(
+            tap, test_env, test["application"], test["description"]
+        )
+    except FileNotFoundError as fne:
+        tap.diagnostic(fne)
+        if test["skip_if_application_not_present"]:
+            tap.skip(
+                "Test application '{}' not found".format(test["application"]),
+                tap.remaining_test_cases,
+            )
+            sys.exit(0)
+    # Warning: validate_trace mutates test['expected_events']
+    ust.validate_trace(outputlocation.path, tap, test["expected_events"])
+
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/ust/ust-constructor/test_ust_constructor_cpp_dynamic.py b/tests/regression/ust/ust-constructor/test_ust_constructor_cpp_dynamic.py
new file mode 100755 (executable)
index 0000000..cc7988a
--- /dev/null
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+#
+# SPDX-FileCopyrightText: Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""
+Test instrumentation coverage of C++ constructors and destructors by LTTng-UST
+tracepoints with a dynamic object.
+
+This test successively sets up a session, traces a test application, and then
+reads the resulting trace to determine if all the expected events are present.
+"""
+
+import copy
+import pathlib
+import sys
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import ust_constructor_common as ust
+
+test = {
+    "description": "Test user space constructor/destructor instrumentation coverage (C++ w/ dynamic object",
+    "application": "gen-ust-events-constructor/gen-ust-events-constructor-so",
+    "expected_events": copy.deepcopy(
+        ust.expected_events_common
+        + ust.expected_events_common_cpp
+        + ust.expected_events_tp_so
+        + ust.expected_events_tp_so_cpp
+    ),
+    # This application is not be built when `NO_SHARED` is set in the
+    # configuration options.
+    "skip_if_application_not_present": True,
+}
+
+tap = lttngtest.TapGenerator(7 + len(test["expected_events"]))
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    try:
+        outputlocation = ust.capture_trace(
+            tap, test_env, test["application"], test["description"]
+        )
+    except FileNotFoundError as fne:
+        tap.diagnostic(fne)
+        if test["skip_if_application_not_present"]:
+            tap.skip(
+                "Test application '{}' not found".format(test["application"]),
+                tap.remaining_test_cases,
+            )
+            sys.exit(0)
+    # Warning: validate_trace mutates test['expected_events']
+    ust.validate_trace(outputlocation.path, tap, test["expected_events"])
+
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/ust/ust-constructor/test_ust_constructor_cpp_static.py b/tests/regression/ust/ust-constructor/test_ust_constructor_cpp_static.py
new file mode 100755 (executable)
index 0000000..db1570d
--- /dev/null
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+# Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+
+"""
+Test instrumentation coverage of C++ constructors and destructors by LTTng-UST
+tracepoints with a static archive.
+
+This test successively sets up a session, traces a test application, and then
+reads the resulting trace to determine if all the expected events are present.
+"""
+
+import copy
+import pathlib
+import sys
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import ust_constructor_common as ust
+
+test = {
+    "description": "Test user space constructor/destructor instrumentation coverage (C++ w/ static archive)",
+    "application": "gen-ust-events-constructor/gen-ust-events-constructor-a",
+    "expected_events": copy.deepcopy(
+        ust.expected_events_common
+        + ust.expected_events_common_cpp
+        + ust.expected_events_tp_a
+        + ust.expected_events_tp_a_cpp
+    ),
+    "skip_if_application_not_present": False,
+}
+
+tap = lttngtest.TapGenerator(7 + len(test["expected_events"]))
+with lttngtest.test_environment(with_sessiond=True, log=tap.diagnostic) as test_env:
+    try:
+        outputlocation = ust.capture_trace(
+            tap, test_env, test["application"], test["description"]
+        )
+    except FileNotFoundError as fne:
+        tap.diagnostic(fne)
+        if test["skip_if_application_not_present"]:
+            tap.skip(
+                "Test application '{}' not found".format(test["application"]),
+                tap.remaining_test_cases,
+            )
+            sys.exit(0)
+    # Warning: validate_trace mutates test['expected_events']
+    ust.validate_trace(outputlocation.path, tap, test["expected_events"])
+
+
+sys.exit(0 if tap.is_successful else 1)
diff --git a/tests/regression/ust/ust-constructor/ust_constructor_common.py b/tests/regression/ust/ust-constructor/ust_constructor_common.py
new file mode 100644 (file)
index 0000000..0ea7248
--- /dev/null
@@ -0,0 +1,361 @@
+#!/usr/bin/env python3
+#
+# SPDX-FileCopyrightText: 2024 Kienan Stewart <kstewart@efficios.com>
+# SPDX-License-Identifer: GPL-2.0-only
+#
+
+import copy
+import pathlib
+import sys
+import os
+import subprocess
+from typing import Any, Callable, Type
+
+# Import in-tree test utils
+test_utils_import_path = pathlib.Path(__file__).absolute().parents[3] / "utils"
+sys.path.append(str(test_utils_import_path))
+
+import lttngtest
+import bt2
+
+# Determine if LTTNG_UST_ALLOCATE_COMPOUND_LITERAL_ON_HEAP is set. This will
+# affect if certain events may or may not be expected when compiling with
+# C++.
+# @see https://github.com/lttng/lttng-ust/blob/47fa3e4ed7ab43e034dc61fc1480f919f4ee51d0/include/lttng/ust-compiler.h#L51
+#
+compound_literal_on_heap = False
+process = subprocess.Popen(
+    [
+        os.path.join(
+            str(test_utils_import_path),
+            "testapp",
+            "gen-ust-events-constructor",
+            "uses_heap",
+        )
+    ]
+)
+process.wait()
+if process.returncode == 0:
+    compound_literal_on_heap = True
+
+expected_events_common_cpp = [
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - across units before define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - same unit before define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - same unit after define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - across units after define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - same unit before provider",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - same unit after provider",
+        "count": 0,
+    },
+    {
+        "name": "tp:constructor_cplusplus",
+        "msg": "global - across units after provider",
+        "count": 0,
+    },
+    {"name": "tp:constructor_cplusplus", "msg": "main() local", "count": 0},
+    {"name": "tp:destructor_cplusplus", "msg": "main() local", "count": 0},
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - across units after provider",
+        "count": 0,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - same unit after provider",
+        "count": 0,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - same unit before provider",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - across units after define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - same unit after define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - same unit before define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_cplusplus",
+        "msg": "global - across units before define",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+]
+
+expected_events_common = [
+    {
+        "name": "tp:constructor_c_across_units_before_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_c_same_unit_before_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_c_same_unit_after_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_c_across_units_after_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_c_same_unit_before_provider",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:constructor_c_same_unit_after_provider",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {"name": "tp:constructor_c_across_units_after_provider", "msg": None, "count": 0},
+    {"name": "tp:main", "msg": None, "count": 0},
+    {
+        "name": "tp:destructor_c_across_units_after_provider",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_same_unit_after_provider",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_same_unit_before_provider",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_across_units_after_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_same_unit_after_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_same_unit_before_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp:destructor_c_across_units_before_define",
+        "msg": None,
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+]
+
+expected_events_tp_so_cpp = [
+    {
+        "name": "tp_so:constructor_cplusplus_provider_shared_library",
+        "msg": "global - shared library define and provider",
+        "count": 0,
+    },
+    {
+        "name": "tp_so:constructor_cplusplus_provider_shared_library",
+        "msg": "main() local - shared library define and provider",
+        "count": 0,
+    },
+    {
+        "name": "tp_so:destructor_cplusplus_provider_shared_library",
+        "msg": "main() local - shared library define and provider",
+        "count": 0,
+    },
+    {
+        "name": "tp_so:destructor_cplusplus_provider_shared_library",
+        "msg": "global - shared library define and provider",
+        "count": 0,
+    },
+]
+
+expected_events_tp_so = [
+    {"name": "tp_so_c:constructor_c_provider_shared_library", "msg": None, "count": 0},
+    {"name": "tp_so_c:destructor_c_provider_shared_library", "msg": None, "count": 0},
+]
+
+expected_events_tp_a_cpp = [
+    {
+        "name": "tp_a:constructor_cplusplus_provider_static_archive",
+        "msg": "global - static archive define and provider",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+    {
+        "name": "tp_a:constructor_cplusplus_provider_static_archive",
+        "msg": "main() local - static archive define and provider",
+        "count": 0,
+    },
+    {
+        "name": "tp_a:destructor_cplusplus_provider_static_archive",
+        "msg": "main() local - static archive define and provider",
+        "count": 0,
+    },
+    {
+        "name": "tp_a:destructor_cplusplus_provider_static_archive",
+        "msg": "global - static archive define and provider",
+        "count": 0,
+        "may_fail": compound_literal_on_heap,
+    },
+]
+
+expected_events_tp_a = [
+    {"name": "tp_a_c:constructor_c_provider_static_archive", "msg": None, "count": 0},
+    {"name": "tp_a_c:destructor_c_provider_static_archive", "msg": None, "count": 0},
+]
+
+
+def capture_trace(tap, test_env, application, description):
+    # type: (lttngtest.TapGenerator, lttngtest._Environment) -> lttngtest.LocalSessionOutputLocation
+    tap.diagnostic(description)
+
+    session_output_location = lttngtest.LocalSessionOutputLocation(
+        test_env.create_temporary_directory("trace")
+    )
+
+    client = lttngtest.LTTngClient(test_env, log=tap.diagnostic)
+
+    with tap.case("Create a session") as test_case:
+        session = client.create_session(output=session_output_location)
+    tap.diagnostic("Created session `{session_name}`".format(session_name=session.name))
+
+    with tap.case(
+        "Add a channel to session `{session_name}`".format(session_name=session.name)
+    ) as test_case:
+        channel = session.add_channel(lttngtest.TracingDomain.User)
+    tap.diagnostic("Created channel `{channel_name}`".format(channel_name=channel.name))
+
+    # Enable all user space events, the default for a user tracepoint event rule.
+    channel.add_recording_rule(lttngtest.UserTracepointEventRule("tp*"))
+
+    with tap.case(
+        "Start session `{session_name}`".format(session_name=session.name)
+    ) as test_case:
+        session.start()
+
+    test_app = test_env.launch_test_application(application)
+    with tap.case(
+        "Run test app '{}'".format(application, session_name=session.name)
+    ) as test_case:
+        test_app.wait_for_exit()
+
+    with tap.case(
+        "Stop session `{session_name}`".format(session_name=session.name)
+    ) as test_case:
+        session.stop()
+
+    with tap.case(
+        "Destroy session `{session_name}`".format(session_name=session.name)
+    ) as test_case:
+        session.destroy()
+
+    return session_output_location
+
+
+def validate_trace(trace_location, tap, expected_events):
+    # type: (pathlib.Path, lttngtest.TapGenerator)
+    unknown_event_count = 0
+
+    for msg in bt2.TraceCollectionMessageIterator(str(trace_location)):
+        if type(msg) is not bt2._EventMessageConst:
+            continue
+
+        found = False
+        for event in expected_events:
+            if event["name"] == msg.event.name and event["msg"] is None:
+                found = True
+                event["count"] = event["count"] + 1
+                break
+            elif (
+                event["name"] == msg.event.name
+                and event["msg"] is not None
+                and event["msg"] == msg.event["msg"]
+            ):
+                found = True
+                event["count"] = event["count"] + 1
+                break
+
+        if found == False:
+            unknown_event_count = unknown_event_count + 1
+            printmsg = None
+            if "msg" in msg.event:
+                printmsg = msg.event["msg"]
+            tap.diagnostic(
+                'Unexpected event name="{}" msg="{}" encountered'.format(
+                    msg.event.name, str(printmsg)
+                )
+            )
+
+    for event in expected_events:
+        may_fail = "may_fail" in event.keys() and event["may_fail"]
+        if not may_fail:
+            tap.test(
+                event["count"] == 1,
+                'Found expected event name="{}" msg="{}"'.format(
+                    event["name"], str(event["msg"])
+                ),
+            )
+        else:
+            tap.skip("Event '{}' may or may not be recorded".format(event["name"]))
+
+    tap.test(unknown_event_count == 0, "Found no unexpected events")
index 366b02bb0eb9daf13e10847a77e00bd8cee653cc..322a2c65f7fdcee12e6e8c1df51e8bd760d65a09 100644 (file)
@@ -31,16 +31,16 @@ noinst_LTLIBRARIES = libzzz.la libbar.la libfoo.la libtp.la
 
 libzzz_la_SOURCES = libzzz.c libzzz.h
 libzzz_la_LDFLAGS = -module -shared -avoid-version \
-               -rpath $(abs_builddir)
+               -rpath $(libdir)
 
 libbar_la_SOURCES = libbar.c libbar.h
 libbar_la_LDFLAGS = -module -shared -avoid-version \
-               -rpath $(abs_builddir)
+               -rpath $(libdir)
 libbar_la_LIBADD = libzzz.la
 
 libfoo_la_SOURCES = libfoo.c libfoo.h
 libfoo_la_LDFLAGS = -module -shared -avoid-version \
-               -rpath $(abs_builddir)
+               -rpath $(libdir)
 libfoo_la_LIBADD = libbar.la
 
 CLEANFILES = libfoo.so libfoo.so.debug libbar.so libbar.so.debug \
@@ -48,7 +48,7 @@ CLEANFILES = libfoo.so libfoo.so.debug libbar.so libbar.so.debug \
 
 libtp_la_SOURCES = libbar-tp.h libbar-tp.c libfoo-tp.h libfoo-tp.c \
        libzzz-tp.h libzzz-tp.c
-libtp_la_LDFLAGS = -module -shared -rpath $(abs_builddir)
+libtp_la_LDFLAGS = -module -shared -rpath $(libdir)
 
 # Extract debug symbols
 libfoo.so.debug: libfoo.la
index 13ff1f2d196f1dc2207988d6f908ae56e2a511e9..ef7c68d7d75ce77927dc884354bdedac0fa5f9fa 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(
-    libbar,
-    bar,
-    TP_ARGS(void),
-    TP_FIELDS()
-)
+TRACEPOINT_EVENT(libbar, bar, TP_ARGS(void), TP_FIELDS())
 
 #endif /* _LIBBAR_TP_H */
 
index 1f1a0bbfd3ef0ffb17ff98791529223c4f298f70..7248e5d6f03ed3e8382707f4cae56fe106571453 100644 (file)
@@ -12,4 +12,4 @@
 
 LTTNG_EXPORT int bar(void);
 
-#endif  /* _LIBBAR_H */
+#endif /* _LIBBAR_H */
index c95a0885269f670437e7ebdd4a951ccd93bfd67e..5dcc2507c9af16b37121c3ff66acd7acd0e627ac 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(
-    libfoo,
-    foo,
-    TP_ARGS(void),
-    TP_FIELDS()
-)
+TRACEPOINT_EVENT(libfoo, foo, TP_ARGS(void), TP_FIELDS())
 
 #endif /* _LIBFOO_TP_H */
 
index 3c92464d849f03a1d7a22cf0c2df69aba6f84a9f..908eb1f80891ebe828d010e43b6d25553c4c542e 100644 (file)
@@ -5,8 +5,8 @@
  *
  */
 
-#include "libfoo.h"
 #include "libbar.h"
+#include "libfoo.h"
 
 #define TRACEPOINT_DEFINE
 #define TRACEPOINT_PROBE_DYNAMIC_LINKAGE
index 43ae5b9b88f4432a1d1ddfe7c9ee6e70adfc11fb..30e94a0869d8a82025589684c1c926e1639a3568 100644 (file)
@@ -12,4 +12,4 @@
 
 LTTNG_EXPORT int foo(void);
 
-#endif  /* _LIBFOO_H */
+#endif /* _LIBFOO_H */
index c7390fa27731524bdaca23d322b089e81037f52d..17761a422f91a8da5cdc36c48f44310a217f2281 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(
-    libzzz,
-    zzz,
-    TP_ARGS(void),
-    TP_FIELDS()
-)
+TRACEPOINT_EVENT(libzzz, zzz, TP_ARGS(void), TP_FIELDS())
 
 #endif /* _LIBZZZ_TP_H */
 
index e1ea4ce9c5dc726121b38a3b8e63703ea88ddd6f..ba7d84c86a8735af4e889abe112024c4d7a5f867 100644 (file)
@@ -10,4 +10,4 @@
 
 int zzz(void);
 
-#endif  /* _LIBZZZ_H */
+#endif /* _LIBZZZ_H */
index e4288928fad5235245086f8f47087bcb4eb2ab3c..60fb0d1dc9c415f9671a04ae910eb4780c5dd8c7 100644 (file)
@@ -6,12 +6,12 @@
  */
 
 /* _GNU_SOURCE is defined by config.h */
+#include <common/compat/errno.hpp>
+
 #include <dlfcn.h>
 #include <stdio.h>
-#include <unistd.h>
 #include <stdlib.h>
-
-#include <common/compat/errno.hpp>
+#include <unistd.h>
 
 /*
  * libfoo has a direct dependency on libbar.
index 04903af260d02417a4814f1d964f807a966dbfb3..660fb7b195d3124710f1ab545e18a370bc77b472 100644 (file)
@@ -20,7 +20,7 @@ sys.path.append(test_utils_path)
 from test_utils import *
 
 
-have_dlmopen = (os.environ.get('LTTNG_TOOLS_HAVE_DLMOPEN') == '1')
+have_dlmopen = os.environ.get("LTTNG_TOOLS_HAVE_DLMOPEN") == "1"
 
 
 NR_TESTS = 14
@@ -29,9 +29,11 @@ print("1..{0}".format(NR_TESTS))
 
 # Check if a sessiond is running... bail out if none found.
 if session_daemon_alive() == 0:
-    bail("""No sessiond running. Please make sure you are running this test
+    bail(
+        """No sessiond running. Please make sure you are running this test
     with the "run" shell script and verify that the lttng tools are
-    properly installed.""")
+    properly installed."""
+    )
 
 session_info = create_session()
 enable_ust_tracepoint_event(session_info, "*")
@@ -40,21 +42,33 @@ start_session(session_info)
 test_env = os.environ.copy()
 test_env["LD_PRELOAD"] = test_env.get("LD_PRELOAD", "") + ":liblttng-ust-dl.so"
 test_env["LD_LIBRARY_PATH"] = test_env.get("LD_LIBRARY_PATH", "") + ":" + test_path
-test_process = subprocess.Popen(test_path + "prog",
-                                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
-                                env=test_env)
+test_process = subprocess.Popen(
+    test_path + "prog",
+    stdout=subprocess.DEVNULL,
+    stderr=subprocess.DEVNULL,
+    env=test_env,
+)
 test_process.wait()
 
-print_test_result(test_process.returncode == 0, current_test, "Test application exited normally")
+print_test_result(
+    test_process.returncode == 0, current_test, "Test application exited normally"
+)
 current_test += 1
 
 stop_session(session_info)
 
 # Check for dl events in the resulting trace
 try:
-    babeltrace_process = subprocess.Popen([BABELTRACE_BIN, session_info.trace_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    babeltrace_process = subprocess.Popen(
+        [BABELTRACE_BIN, session_info.trace_path],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
 except FileNotFoundError:
-    bail("Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN), session_info)
+    bail(
+        "Could not open {}. Please make sure it is installed.".format(BABELTRACE_BIN),
+        session_info,
+    )
 
 dlopen_event_found = 0
 dlmopen_event_found = 0
@@ -71,7 +85,7 @@ load_libzzz_found = 0
 
 for event_line in babeltrace_process.stdout:
 
-    event_line = event_line.decode('utf-8').replace("\n", "")
+    event_line = event_line.decode("utf-8").replace("\n", "")
     if re.search(r".*lttng_ust_dl:dlopen.*", event_line) is not None:
         dlopen_event_found += 1
     elif re.search(r".*lttng_ust_dl:dlmopen.*", event_line) is not None:
@@ -99,47 +113,97 @@ for event_line in babeltrace_process.stdout:
 
 babeltrace_process.wait()
 
-print_test_result(babeltrace_process.returncode == 0, current_test, "Resulting trace is readable")
+print_test_result(
+    babeltrace_process.returncode == 0, current_test, "Resulting trace is readable"
+)
 current_test += 1
 
-print_test_result(dlopen_event_found > 0, current_test, "lttng_ust_dl:dlopen event found in resulting trace")
+print_test_result(
+    dlopen_event_found > 0,
+    current_test,
+    "lttng_ust_dl:dlopen event found in resulting trace",
+)
 current_test += 1
 
 if have_dlmopen:
-    print_test_result(dlmopen_event_found > 0, current_test, "lttng_ust_dl:dlmopen event found in resulting trace")
+    print_test_result(
+        dlmopen_event_found > 0,
+        current_test,
+        "lttng_ust_dl:dlmopen event found in resulting trace",
+    )
 else:
-    skip_test(current_test, 'dlmopen() is not available')
+    skip_test(current_test, "dlmopen() is not available")
 
 current_test += 1
 
-print_test_result(build_id_event_found > 0, current_test, "lttng_ust_dl:build_id event found in resulting trace")
+print_test_result(
+    build_id_event_found > 0,
+    current_test,
+    "lttng_ust_dl:build_id event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(debug_link_event_found > 0, current_test, "lttng_ust_dl:debug_link event found in resulting trace")
+print_test_result(
+    debug_link_event_found > 0,
+    current_test,
+    "lttng_ust_dl:debug_link event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(dlclose_event_found > 0, current_test, "lttng_ust_dl:dlclose event found in resulting trace")
+print_test_result(
+    dlclose_event_found > 0,
+    current_test,
+    "lttng_ust_dl:dlclose event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_event_found > 0, current_test, "lttng_ust_lib:load event found in resulting trace")
+print_test_result(
+    load_event_found > 0,
+    current_test,
+    "lttng_ust_lib:load event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_build_id_event_found > 0, current_test, "lttng_ust_lib:build_id event found in resulting trace")
+print_test_result(
+    load_build_id_event_found > 0,
+    current_test,
+    "lttng_ust_lib:build_id event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_debug_link_event_found > 0, current_test, "lttng_ust_lib:debug_link event found in resulting trace")
+print_test_result(
+    load_debug_link_event_found > 0,
+    current_test,
+    "lttng_ust_lib:debug_link event found in resulting trace",
+)
 current_test += 1
 
-print_test_result(unload_event_found == 3, current_test, "lttng_ust_lib:unload event found 3 times in resulting trace")
+print_test_result(
+    unload_event_found == 3,
+    current_test,
+    "lttng_ust_lib:unload event found 3 times in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_libfoo_found == 1, current_test, "lttng_ust_lib:load libfoo.so event found once in resulting trace")
+print_test_result(
+    load_libfoo_found == 1,
+    current_test,
+    "lttng_ust_lib:load libfoo.so event found once in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_libbar_found == 1, current_test, "lttng_ust_lib:load libbar.so event found once in resulting trace")
+print_test_result(
+    load_libbar_found == 1,
+    current_test,
+    "lttng_ust_lib:load libbar.so event found once in resulting trace",
+)
 current_test += 1
 
-print_test_result(load_libzzz_found == 1, current_test, "lttng_ust_lib:load libzzz.so event found once in resulting trace")
+print_test_result(
+    load_libzzz_found == 1,
+    current_test,
+    "lttng_ust_lib:load libzzz.so event found once in resulting trace",
+)
 current_test += 1
 
 shutil.rmtree(session_info.tmp_directory)
diff --git a/tests/root_destructive_tests b/tests/root_destructive_tests
deleted file mode 100644 (file)
index 73a7bb8..0000000
+++ /dev/null
@@ -1 +0,0 @@
-destructive/metadata-regeneration
index 26565464abf7a246a6cb628ada5259705757d640..5ddc6be64eb5675ceaa88bc006c7a211d2a42ab6 100755 (executable)
@@ -5,8 +5,8 @@
 # SPDX-License-Identifier: LGPL-2.1-only
 #
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/.."
 LAUNCH_APP="launch_ust_app"
 SESSION_NAME="stress"
 EVENT_NAME="tp:tptest"
@@ -17,32 +17,34 @@ NR_APP=10
 NR_SESSION=5
 NR_LOOP=1000
 COREDUMP_FILE=$(cat /proc/sys/kernel/core_pattern)
-APPS_PID=
+APP_PIDS=()
 
 TEST_DESC="Stress test - $NR_SESSION sessions per UID with $NR_APP apps"
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../
+source "$TESTDIR/utils/utils.sh"
 
 # MUST set TESTDIR before calling those functions
 
 function enable_channel_per_uid()
 {
-    local sess_name=$1
-    local channel_name=$2
+       local sess_name=$1
+       local channel_name=$2
 
-    $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name >/dev/null 2>&1
-    ok $? "Enable channel $channel_name per UID for session $sess_name"
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" >/dev/null 2>&1
+       ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
 function check_sessiond()
 {
-       if [ -z "$(lttng_pgrep lt-lttng-sessiond)" ]; then
-               local str_date=$(date +%H%M%S-%d%m%Y)
+       local str_date=''
+       if [ -z "$(lttng_pgrep lttng-sessiond)" ]; then
+               str_date=$(date +%H%M%S-%d%m%Y)
 
                diag "!!!The session daemon died unexpectedly!!!"
-               mv $LOG_FILE $LOG_FILE-$str_date
-               if [ -e $COREDUMP_FILE ]; then
-                       mv $COREDUMP_FILE $COREDUMP_FILE-$str_date
+               mv $LOG_FILE "$LOG_FILE-$str_date"
+               if [ -e "$COREDUMP_FILE" ]; then
+                       mv "$COREDUMP_FILE" "$COREDUMP_FILE-$str_date"
                fi
                exit 1
        fi
@@ -50,16 +52,15 @@ function check_sessiond()
 
 function start_sessiond()
 {
-       validate_kernel_version
-       if [ $? -ne 0 ]; then
+       if ! validate_kernel_version ; then
                fail "Start session daemon"
                BAIL_OUT "*** Kernel too old for session daemon tests ***"
        fi
 
-       if [ -z $(lttng_pgrep lt-$SESSIOND_BIN) ]; then
+       if [ -z "$(lttng_pgrep $SESSIOND_BIN)" ]; then
                # We have to start it like this so the ulimit -c is used by this
                # process. Also, we collect any error message printed out.
-               $TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN --quiet --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE 2>&1
+               "$TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN" --quiet --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE 2>&1
                status=$?
                ok $status "Start session daemon"
        fi
@@ -67,22 +68,23 @@ function start_sessiond()
 
 test_stress()
 {
+       # shellcheck disable=SC2034
        for b in $(seq 1 $NR_LOOP); do
                for a in $(seq 1 $NR_SESSION); do
-                       create_lttng_session_ok $SESSION_NAME-$a $TRACE_PATH
+                       create_lttng_session_ok $SESSION_NAME-"$a" "$TRACE_PATH"
                        check_sessiond
-                       enable_channel_per_uid $SESSION_NAME-$a $CHANNEL_NAME
+                       enable_channel_per_uid $SESSION_NAME-"$a" $CHANNEL_NAME
                        check_sessiond
-                       enable_ust_lttng_event_ok $SESSION_NAME-$a $EVENT_NAME
+                       enable_ust_lttng_event_ok $SESSION_NAME-"$a" $EVENT_NAME
                        check_sessiond
-                       start_lttng_tracing_ok $SESSION_NAME-$a
+                       start_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
                done
 
                for a in $(seq 1 $NR_SESSION); do
-                       stop_lttng_tracing_ok $SESSION_NAME-$a
+                       stop_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
-                       destroy_lttng_session_ok $SESSION_NAME-$a
+                       destroy_lttng_session_ok $SESSION_NAME-"$a"
                        check_sessiond
                done
        done
@@ -93,18 +95,17 @@ test_stress()
 function cleanup()
 {
        diag "Cleaning up!"
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
+       APP_PIDS=()
+       # shellcheck disable=SC2119
        stop_lttng_sessiond
 }
 
 function sighandler()
 {
        cleanup
-       rm $LOG_FILE
+       rm "$LOG_FILE"
        full_cleanup
 }
 
@@ -123,10 +124,10 @@ start_sessiond
 diag "Starting applications"
 
 # Start NR_APP applications script that will spawn apps non stop.
-./$TESTDIR/stress/$LAUNCH_APP $NR_APP &
-APPS_PID="${APPS_PID} ${!}"
+"./$TESTDIR/stress/$LAUNCH_APP" $NR_APP &
+APP_PIDS+=(${!})
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_multi_sess_per_uid_10app.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_multi_sess_per_uid_10app.XXXXXX)
 
 test_stress
 out=$?
@@ -136,6 +137,6 @@ if [ $out -ne 0 ]; then
 fi
 
 cleanup
-rm -rf $TRACE_PATH
+rm -rf "${TRACE_PATH:?}/"
 rm $LOG_FILE
 exit 0
index db225db0eeda9562a587f6a394d58bd7d7b097d8..8800f6f233679e44d7ffb2d5d713cc078f901ca9 100755 (executable)
@@ -5,8 +5,8 @@
 # SPDX-License-Identifier: LGPL-2.1-only
 #
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/.."
 LAUNCH_APP="launch_ust_app"
 SESSION_NAME="stress"
 EVENT_NAME="tp:tptest"
@@ -18,32 +18,34 @@ NR_SESSION=5
 NR_LOOP=1000
 COREDUMP_FILE=$(cat /proc/sys/kernel/core_pattern)
 NUM_TESTS=16
-APPS_PID=
+APP_PIDS=()
 
 TEST_DESC="Stress test - $NR_SESSION sessions per UID streaming with $NR_APP apps"
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../
+source "$TESTDIR/utils/utils.sh"
 
 # MUST set TESTDIR before calling those functions
 
 function enable_channel_per_uid()
 {
-    local sess_name=$1
-    local channel_name=$2
+       local sess_name=$1
+       local channel_name=$2
 
-    $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name >/dev/null 2>&1
-    ok $? "Enable channel $channel_name per UID for session $sess_name"
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" >/dev/null 2>&1
+       ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
 function check_sessiond()
 {
-       if [ -z "$(lttng_pgrep lt-lttng-sessiond)" ]; then
-               local str_date=$(date +%H%M%S-%d%m%Y)
+       local str_date
+       if [ -z "$(lttng_pgrep lttng-sessiond)" ]; then
+               str_date=$(date +%H%M%S-%d%m%Y)
 
                diag "!!!The session daemon died unexpectedly!!!"
-               mv $LOG_FILE_SESSIOND $LOG_FILE_SESSIOND-$str_date
-               if [ -e $COREDUMP_FILE ]; then
-                       mv $COREDUMP_FILE $COREDUMP_FILE-$str_date
+               mv $LOG_FILE_SESSIOND "$LOG_FILE_SESSIOND-$str_date"
+               if [ -e "$COREDUMP_FILE" ]; then
+                       mv "$COREDUMP_FILE" "$COREDUMP_FILE-$str_date"
                fi
                exit 1
        fi
@@ -51,13 +53,14 @@ function check_sessiond()
 
 function check_relayd()
 {
-       if [ -z "$(lttng_pgrep lt-lttng-relayd)" ]; then
-               local str_date=$(date +%H%M%S-%d%m%Y)
+       local str_date
+       if [ -z "$(lttng_pgrep lttng-relayd)" ]; then
+               str_date=$(date +%H%M%S-%d%m%Y)
 
                diag "!!!The relay daemon died unexpectedly!!!"
-               mv $LOG_FILE_RELAYD $LOG_FILE_RELAYD-$str_date
-               if [ -e $COREDUMP_FILE ]; then
-                       mv $COREDUMP_FILE $COREDUMP_FILE-$str_date
+               mv $LOG_FILE_RELAYD "$LOG_FILE_RELAYD-$str_date"
+               if [ -e "$COREDUMP_FILE" ]; then
+                       mv "$COREDUMP_FILE" "$COREDUMP_FILE-$str_date"
                fi
                exit 1
        fi
@@ -65,16 +68,15 @@ function check_relayd()
 
 function start_sessiond()
 {
-       validate_kernel_version
-       if [ $? -ne 0 ]; then
+       if ! validate_kernel_version ; then
                fail "Start session daemon"
                BAIL_OUT "*** Kernel too old for session daemon tests ***"
        fi
 
-       if [ -z $(lttng_pgrep lt-$SESSIOND_BIN) ]; then
+       if [ -z "$(lttng_pgrep lt-$SESSIOND_BIN)" ]; then
                # We have to start it like this so the ulimit -c is used by this
                # process. Also, we collect any error message printed out.
-               $TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN --quiet --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
+               "$TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN" --quiet --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
                status=$?
                ok $status "Start session daemon"
        fi
@@ -84,35 +86,36 @@ function start_relayd
 {
        local opt=$1
 
-       if [ -z $(lttng_pgrep lt-$RELAYD_BIN) ]; then
-               $TESTDIR/../src/bin/lttng-relayd/$RELAYD_BIN $opt >$LOG_FILE_RELAYD 2>&1 &
+       if [ -z "$(lttng_pgrep lt-$RELAYD_BIN)" ]; then
+               "$TESTDIR/../src/bin/lttng-relayd/$RELAYD_BIN" "$opt" >"$LOG_FILE_RELAYD" 2>&1 &
                ok $? "Start lttng-relayd (opt: \"$opt\")"
        fi
 }
 
 test_stress()
 {
+       # shellcheck disable=SC2034
        for b in $(seq 1 $NR_LOOP); do
                for a in $(seq 1 $NR_SESSION); do
-                       create_lttng_session_uri $SESSION_NAME-$a net://localhost
+                       create_lttng_session_uri $SESSION_NAME-"$a" net://localhost
                        check_sessiond
                        check_relayd
-                       enable_channel_per_uid $SESSION_NAME-$a $CHANNEL_NAME
+                       enable_channel_per_uid $SESSION_NAME-"$a" $CHANNEL_NAME
                        check_sessiond
                        check_relayd
-                       enable_ust_lttng_event_ok $SESSION_NAME-$a $EVENT_NAME
+                       enable_ust_lttng_event_ok $SESSION_NAME-"$a" $EVENT_NAME
                        check_sessiond
                        check_relayd
-                       start_lttng_tracing_ok $SESSION_NAME-$a
+                       start_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
                done
 
                for a in $(seq 1 $NR_SESSION); do
-                       stop_lttng_tracing_ok $SESSION_NAME-$a
+                       stop_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
-                       destroy_lttng_session_ok $SESSION_NAME-$a
+                       destroy_lttng_session_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
                done
@@ -124,12 +127,12 @@ test_stress()
 function cleanup()
 {
        diag "Cleaning up!"
-       for p in ${APPS_PID}; do
-               kill -s SIGKILL ${p}
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       kill -s SIGKILL "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
+       APP_PIDS=()
+       # shellcheck disable=SC2119
        stop_lttng_sessiond
+       # shellcheck disable=SC2119
        stop_lttng_relayd
 }
 
@@ -150,7 +153,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_multi_sess_per_uid_5app_streaming.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_multi_sess_per_uid_5app_streaming.XXXXXX)
 
 start_relayd "-o $TRACE_PATH"
 start_sessiond
@@ -158,8 +161,8 @@ start_sessiond
 diag "Starting applications launcher"
 
 # Start NR_APP applications script that will spawn apps non stop.
-./$TESTDIR/stress/$LAUNCH_APP $NR_APP &
-APPS_PID="${APPS_PID} ${!}"
+"./$TESTDIR/stress/$LAUNCH_APP" $NR_APP &
+APP_PIDS+=(${!})
 
 test_stress
 out=$?
@@ -169,6 +172,6 @@ if [ $out -ne 0 ]; then
 fi
 
 cleanup
-rm -rf $TRACE_PATH
+rm -rf "${TRACE_PATH:?}/"
 rm $LOG_FILE_SESSIOND $LOG_FILE_RELAYD
 exit 0
index 9cb664d5b13278e3670063650b69d313898e711e..3d5da8f84b914c7ddc7a59122d4843514a1d88d5 100755 (executable)
@@ -5,8 +5,8 @@
 # SPDX-License-Identifier: LGPL-2.1-only
 #
 
-CURDIR=$(dirname $0)/
-TESTDIR=$CURDIR/..
+CURDIR=$(dirname "$0")/
+TESTDIR="$CURDIR/.."
 LAUNCH_APP="launch_ust_app"
 KILL_RELAYD_HELPER="kill_relayd"
 SESSION_NAME="stress"
@@ -19,32 +19,34 @@ NR_SESSION=5
 NR_LOOP=100000
 COREDUMP_FILE=$(cat /proc/sys/kernel/core_pattern)
 NUM_TESTS=16
-APPS_PID=
+APP_PIDS=()
 
 TEST_DESC="Stress test - $NR_SESSION sessions per UID streaming with $NR_APP apps. The relayd is killed sporadically"
 
-source $TESTDIR/utils/utils.sh
+# shellcheck source-path=SCRIPTDIR/../
+source "$TESTDIR/utils/utils.sh"
 
 # MUST set TESTDIR before calling those functions
 
 function enable_channel_per_uid()
 {
-    local sess_name=$1
-    local channel_name=$2
+       local sess_name=$1
+       local channel_name=$2
 
-    $TESTDIR/../src/bin/lttng/$LTTNG_BIN enable-channel --buffers-uid -u $channel_name -s $sess_name >/dev/null 2>&1
-    ok $? "Enable channel $channel_name per UID for session $sess_name"
+       "$TESTDIR/../src/bin/lttng/$LTTNG_BIN" enable-channel --buffers-uid -u "$channel_name" -s "$sess_name" >/dev/null 2>&1
+       ok $? "Enable channel $channel_name per UID for session $sess_name"
 }
 
 function check_sessiond()
 {
-       if [ -z "$(lttng_pgrep lt-lttng-sessiond)" ]; then
-               local str_date=$(date +%H%M%S-%d%m%Y)
+       local str_date
+       if [ -z "$(lttng_pgrep lttng-sessiond)" ]; then
+               str_date=$(date +%H%M%S-%d%m%Y)
 
                diag "!!!The session daemon died unexpectedly!!!"
-               mv $LOG_FILE_SESSIOND $LOG_FILE_SESSIOND-$str_date
-               if [ -e $COREDUMP_FILE ]; then
-                       mv $COREDUMP_FILE $COREDUMP_FILE-$str_date
+               mv $LOG_FILE_SESSIOND "$LOG_FILE_SESSIOND-$str_date"
+               if [ -e "$COREDUMP_FILE" ]; then
+                       mv "$COREDUMP_FILE" "$COREDUMP_FILE-$str_date"
                fi
                exit 1
        fi
@@ -52,17 +54,16 @@ function check_sessiond()
 
 function start_sessiond()
 {
-       validate_kernel_version
-       if [ $? -ne 0 ]; then
+       if ! validate_kernel_version ; then
                fail "Start session daemon"
                BAIL_OUT "*** Kernel too old for session daemon tests ***"
        fi
 
-       if [ -z $(lttng_pgrep lt-$SESSIOND_BIN) ]; then
+       if [ -z "$(lttng_pgrep $SESSIOND_BIN)" ]; then
                # We have to start it like this so the ulimit -c is used by this
                # process. Also, we collect any error message printed out.
                #$TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN --quiet --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
-               $TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN --verbose-consumer -vvv --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
+               "$TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN" --verbose-consumer -vvv --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
                #$TESTDIR/../src/bin/lttng-sessiond/$SESSIOND_BIN --background --consumerd32-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" --consumerd64-path="$TESTDIR/../src/bin/lttng-consumerd/lttng-consumerd" >$LOG_FILE_SESSIOND 2>&1
                status=$?
                ok $status "Start session daemon"
@@ -73,20 +74,21 @@ function start_relayd
 {
        local opt=$1
 
-       if [ -z $(lttng_pgrep lt-$RELAYD_BIN) ]; then
-               $TESTDIR/../src/bin/lttng-relayd/$RELAYD_BIN $opt >$LOG_FILE_RELAYD 2>&1 &
+       if [ -z "$(lttng_pgrep $RELAYD_BIN)" ]; then
+               "$TESTDIR/../src/bin/lttng-relayd/$RELAYD_BIN" "$opt" >$LOG_FILE_RELAYD 2>&1 &
                ok $? "Start lttng-relayd (opt: \"$opt\")"
        fi
 }
 
 function check_relayd()
 {
-       if [ -z "$(lttng_pgrep lt-lttng-relayd)" ]; then
-               local str_date=$(date +%H%M%S-%d%m%Y)
+       local str_date
+       if [ -z "$(lttng_pgrep lttng-relayd)" ]; then
+               str_date=$(date +%H%M%S-%d%m%Y)
 
                #diag "Relay daemon died. Starting it again"
-               if [ -e $COREDUMP_FILE ]; then
-                       mv $COREDUMP_FILE $COREDUMP_FILE-$str_date
+               if [ -e "$COREDUMP_FILE" ]; then
+                       mv "$COREDUMP_FILE" "$COREDUMP_FILE-$str_date"
                fi
                start_relayd
        fi
@@ -94,27 +96,28 @@ function check_relayd()
 
 test_stress()
 {
+       # shellcheck disable=SC2034
        for b in $(seq 1 $NR_LOOP); do
                for a in $(seq 1 $NR_SESSION); do
-                       create_lttng_session_uri $SESSION_NAME-$a net://localhost
+                       create_lttng_session_uri $SESSION_NAME-"$a" net://localhost
                        check_sessiond
                        check_relayd
-                       enable_channel_per_uid $SESSION_NAME-$a $CHANNEL_NAME
+                       enable_channel_per_uid $SESSION_NAME-"$a" $CHANNEL_NAME
                        check_sessiond
                        check_relayd
-                       enable_ust_lttng_event_ok $SESSION_NAME-$a $EVENT_NAME
+                       enable_ust_lttng_event_ok $SESSION_NAME-"$a" $EVENT_NAME
                        check_sessiond
                        check_relayd
-                       start_lttng_tracing_ok $SESSION_NAME-$a
+                       start_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
                done
 
                for a in $(seq 1 $NR_SESSION); do
-                       stop_lttng_tracing_ok $SESSION_NAME-$a
+                       stop_lttng_tracing_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
-                       destroy_lttng_session_ok $SESSION_NAME-$a
+                       destroy_lttng_session_ok $SESSION_NAME-"$a"
                        check_sessiond
                        check_relayd
                done
@@ -126,12 +129,12 @@ test_stress()
 function cleanup()
 {
        diag "Cleaning up!"
-       for p in ${APPS_PID}; do
-               kill ${p}
-               wait ${p} 2>/dev/null
-       done
-       APPS_PID=
+       kill "${APP_PIDS[@]}"
+       wait "${APP_PIDS[@]}" 2>/dev/null
+       APP_PIDS=()
+       # shellcheck disable=SC2119
        stop_lttng_sessiond
+       # shellcheck disable=SC2119
        stop_lttng_relayd
 }
 
@@ -152,7 +155,7 @@ plan_tests $NUM_TESTS
 
 print_test_banner "$TEST_DESC"
 
-TRACE_PATH=$(mktemp --tmpdir -d -t tmp.test_multi_sess_per_uid_5app_kill_relayd.XXXXXX)
+TRACE_PATH=$(mktemp -d -t tmp.test_multi_sess_per_uid_5app_kill_relayd.XXXXXX)
 
 start_relayd "-o $TRACE_PATH"
 start_sessiond
@@ -160,12 +163,12 @@ start_sessiond
 diag "Starting applications launcher"
 
 # Start NR_APP applications script that will spawn apps non stop.
-./$TESTDIR/stress/$LAUNCH_APP $NR_APP &
-APPS_PID="${APPS_PID} ${!}"
+"./$TESTDIR/stress/$LAUNCH_APP" $NR_APP &
+APP_PIDS+=(${!})
 
 # Launch the helper script that will randomly kill the relayd at vitam eternam.
-./$TESTDIR/stress/$KILL_RELAYD_HELPER 1 1 &
-APPS_PID="${APPS_PID} ${!}"
+"./$TESTDIR/stress/$KILL_RELAYD_HELPER" 1 1 &
+APP_PIDS+=(${!})
 
 test_stress
 out=$?
@@ -175,6 +178,6 @@ if [ $out -ne 0 ]; then
 fi
 
 cleanup
-rm -rf $TRACE_PATH
+rm -rf "${TRACE_PATH:?}/"
 rm $LOG_FILE_SESSIOND $LOG_FILE_RELAYD
 exit 0
index bc9aedf1063e73a032c85900fcd55642ea9f82d4..4cc22119b63e3148881beebfde86a78ecab21df8 100644 (file)
@@ -5,13 +5,15 @@
  *
  */
 
-#include <tap/tap.h>
 #include <common/ini-config/ini-config.hpp>
-#include <common/utils.hpp>
 #include <common/path.hpp>
-#include <string.h>
+#include <common/utils.hpp>
+
 #include <lttng/constant.h>
 
+#include <string.h>
+#include <tap/tap.h>
+
 namespace {
 struct state {
        int section_1;
@@ -38,8 +40,7 @@ static int entry_handler(const struct config_entry *entry, struct state *state)
 
        if (!strcmp(entry->section, "section1")) {
                state->section_1 = 1;
-               if (!strcmp(entry->name, "section1_entry") &&
-                       !strcmp(entry->value, "42")) {
+               if (!strcmp(entry->name, "section1_entry") && !strcmp(entry->value, "42")) {
                        state->int_entry = 1;
                }
        }
@@ -51,7 +52,7 @@ static int entry_handler(const struct config_entry *entry, struct state *state)
        if (!strcmp(entry->section, "section 3")) {
                state->section_3 = 1;
                if (!strcmp(entry->name, "name with a space") &&
-                       !strcmp(entry->value, "another value")) {
+                   !strcmp(entry->value, "another value")) {
                        state->text_entry = 1;
                }
        }
@@ -65,7 +66,7 @@ end:
 
 int main(int argc, char **argv)
 {
-       char *path = NULL;
+       char *path = nullptr;
        int ret;
        struct state state = {};
 
@@ -76,7 +77,7 @@ int main(int argc, char **argv)
 
        if (strlen(argv[1]) >= LTTNG_PATH_MAX) {
                diag("The provided path exceeds the maximal permitted length of %i bytes",
-                               LTTNG_PATH_MAX);
+                    LTTNG_PATH_MAX);
                goto end;
        }
        path = utils_expand_path(argv[1]);
@@ -85,27 +86,26 @@ int main(int argc, char **argv)
        }
 
        plan_no_plan();
-       ret = config_get_section_entries(path, NULL,
-               (config_entry_handler_cb)entry_handler, &state);
+       ret = config_get_section_entries(
+               path, nullptr, (config_entry_handler_cb) entry_handler, &state);
        ok(ret == 0, "Successfully opened a config file, registered to all sections");
-       ok(state.section_1 && state.section_2 && state.section_3 &&
-               state.section_global, "Processed entries from each sections");
+       ok(state.section_1 && state.section_2 && state.section_3 && state.section_global,
+          "Processed entries from each sections");
        ok(state.text_entry, "Text value parsed correctly");
 
        memset(&state, 0, sizeof(struct state));
-       ret = config_get_section_entries(path, "section1",
-               (config_entry_handler_cb)entry_handler, &state);
+       ret = config_get_section_entries(
+               path, "section1", (config_entry_handler_cb) entry_handler, &state);
        ok(ret == 0, "Successfully opened a config file, registered to one section");
-       ok(state.section_1 && !state.section_2 && !state.section_3 &&
-               !state.section_global, "Processed an entry from section1 only");
+       ok(state.section_1 && !state.section_2 && !state.section_3 && !state.section_global,
+          "Processed an entry from section1 only");
        ok(state.int_entry, "Int value parsed correctly");
 
        memset(&state, 0, sizeof(struct state));
-       ret = config_get_section_entries(path, "",
-               (config_entry_handler_cb)entry_handler, &state);
+       ret = config_get_section_entries(path, "", (config_entry_handler_cb) entry_handler, &state);
        ok(ret == 0, "Successfully opened a config file, registered to the global section");
-       ok(!state.section_1 && !state.section_2 && !state.section_3 &&
-               state.section_global, "Processed an entry from the global section only");
+       ok(!state.section_1 && !state.section_2 && !state.section_3 && state.section_global,
+          "Processed an entry from the global section only");
 end:
        free(path);
        return exit_status();
index de2197ed0d964d690c846a2b95c1cff256af832f..52f6d26ca66a70799db00cd135d90478d9b3a52a 100644 (file)
@@ -9,17 +9,13 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
-
+#include <common/error.hpp>
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/action/action-internal.hpp>
 #include <lttng/action/action.h>
+#include <lttng/action/list-internal.hpp>
 #include <lttng/action/notify.h>
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
 #include <lttng/action/start-session.h>
 #include <lttng/action/stop-session.h>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
+
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
 int lttng_opt_mi;
 
-#define NUM_TESTS 60
+#define NUM_TESTS 71
 
-static void test_action_notify(void)
+static void test_action_notify()
 {
        int ret;
        enum lttng_action_status status;
-       struct lttng_action *notify_action = NULL,
-                           *notify_action_from_buffer = NULL;
-       struct lttng_rate_policy *policy = NULL, *default_policy;
+       struct lttng_action *notify_action = nullptr, *notify_action_from_buffer = nullptr;
+       struct lttng_rate_policy *policy = nullptr, *default_policy;
        struct lttng_payload payload;
 
        lttng_payload_init(&payload);
@@ -56,18 +57,15 @@ static void test_action_notify(void)
        notify_action = lttng_action_notify_create();
        ok(notify_action, "Create notify action");
        ok(lttng_action_get_type(notify_action) == LTTNG_ACTION_TYPE_NOTIFY,
-                       "Action has type LTTNG_ACTION_TYPE_NOTIFY");
+          "Action has type LTTNG_ACTION_TYPE_NOTIFY");
 
        /* Validate the default policy for a notify action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_notify_get_rate_policy(
-                               notify_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_notify_get_rate_policy(notify_action, &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               default_policy,
-                                                               cur_policy),
-                               "Default policy is every n=1");
+                          lttng_rate_policy_is_equal(default_policy, cur_policy),
+                  "Default policy is every n=1");
        }
 
        /* Set a custom policy. */
@@ -76,31 +74,24 @@ static void test_action_notify(void)
 
        /* Validate the custom policy for a notify action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_notify_get_rate_policy(
-                               notify_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_notify_get_rate_policy(notify_action, &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               policy,
-                                                               cur_policy),
-                               "Notify action policy get");
+                          lttng_rate_policy_is_equal(policy, cur_policy),
+                  "Notify action policy get");
        }
 
        ret = lttng_action_serialize(notify_action, &payload);
        ok(ret == 0, "Action notify serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               (void) lttng_action_create_from_payload(
-                               &view, &notify_action_from_buffer);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view, &notify_action_from_buffer);
        }
-       ok(notify_action_from_buffer,
-                       "Notify action created from payload is non-null");
+       ok(notify_action_from_buffer, "Notify action created from payload is non-null");
 
        ok(lttng_action_is_equal(notify_action, notify_action_from_buffer),
-                       "Serialized and de-serialized notify action are equal");
+          "Serialized and de-serialized notify action are equal");
 
        lttng_rate_policy_destroy(default_policy);
        lttng_rate_policy_destroy(policy);
@@ -109,13 +100,99 @@ static void test_action_notify(void)
        lttng_payload_reset(&payload);
 }
 
+static void test_action_list(void)
+{
+       int ret, action_idx;
+       struct lttng_action *list_action = NULL, *list_action_from_buffer = NULL,
+                           *stop_session_action = NULL, *notify_action = NULL,
+                           *start_session_action = NULL;
+       struct lttng_payload payload;
+
+       lttng_payload_init(&payload);
+
+       list_action = lttng_action_list_create();
+       ok(list_action, "Create list action");
+       ok(lttng_action_get_type(list_action) == LTTNG_ACTION_TYPE_LIST,
+          "Action has type LTTNG_ACTION_TYPE_LIST");
+
+       start_session_action = lttng_action_start_session_create();
+       (void) lttng_action_start_session_set_session_name(start_session_action, "une-session");
+
+       stop_session_action = lttng_action_stop_session_create();
+       (void) lttng_action_stop_session_set_session_name(stop_session_action, "une-autre-session");
+       notify_action = lttng_action_notify_create();
+
+       lttng_action_list_add_action(list_action, start_session_action);
+       lttng_action_list_add_action(list_action, stop_session_action);
+       lttng_action_list_add_action(list_action, notify_action);
+
+       ret = lttng_action_serialize(list_action, &payload);
+       ok(ret == 0, "Action list serialized");
+
+       {
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view, &list_action_from_buffer);
+       }
+       ok(list_action_from_buffer, "Notify action created from payload is non-null");
+
+       ok(lttng_action_is_equal(list_action, list_action_from_buffer),
+          "Serialized and de-serialized list action are equal");
+
+       action_idx = 0;
+       for (auto action : lttng::ctl::const_action_list_view(list_action)) {
+               enum lttng_action_type inner_action_type = lttng_action_get_type(action);
+               switch (action_idx) {
+               case 0:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_START_SESSION,
+                          "First inner action of action list is `start-session` action");
+                       break;
+               case 1:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_STOP_SESSION,
+                          "Second inner action of action list is `stop-session` action");
+                       break;
+               case 2:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_NOTIFY,
+                          "Third inner action of action list is `notify` action");
+                       break;
+               }
+               action_idx++;
+       }
+
+       action_idx = 0;
+       for (auto action : lttng::ctl::action_list_view(list_action)) {
+               enum lttng_action_type inner_action_type = lttng_action_get_type(action);
+               switch (action_idx) {
+               case 0:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_START_SESSION,
+                          "First inner action of action list is `start-session` action");
+                       break;
+               case 1:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_STOP_SESSION,
+                          "Second inner action of action list is `stop-session` action");
+                       break;
+               case 2:
+                       ok(inner_action_type == LTTNG_ACTION_TYPE_NOTIFY,
+                          "Third inner action of action list is `notify` action");
+                       break;
+               }
+               action_idx++;
+       }
+
+       lttng_action_destroy(list_action);
+       lttng_action_destroy(list_action_from_buffer);
+       lttng_action_destroy(start_session_action);
+       lttng_action_destroy(stop_session_action);
+       lttng_action_destroy(notify_action);
+       lttng_payload_reset(&payload);
+}
+
 static void test_action_rotate_session(void)
 {
        int ret;
        enum lttng_action_status status;
-       struct lttng_action *rotate_session_action = NULL,
-                           *rotate_session_action_from_buffer = NULL;
-       struct lttng_rate_policy *policy = NULL, *default_policy;
+       struct lttng_action *rotate_session_action = nullptr,
+                           *rotate_session_action_from_buffer = nullptr;
+       struct lttng_rate_policy *policy = nullptr, *default_policy;
        struct lttng_payload payload;
        const char *session_name = "my_session_name";
        const char *get_session_name;
@@ -131,62 +208,50 @@ static void test_action_rotate_session(void)
 
        rotate_session_action = lttng_action_rotate_session_create();
        ok(rotate_session_action, "Create rotate_session action");
-       ok(lttng_action_get_type(rotate_session_action) ==
-                                       LTTNG_ACTION_TYPE_ROTATE_SESSION,
-                       "Action has type LTTNG_ACTION_TYPE_ROTATE_SESSION");
+       ok(lttng_action_get_type(rotate_session_action) == LTTNG_ACTION_TYPE_ROTATE_SESSION,
+          "Action has type LTTNG_ACTION_TYPE_ROTATE_SESSION");
 
        /* Session name setter. */
-       status = lttng_action_rotate_session_set_session_name(NULL, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,NULL) expect invalid");
-       status = lttng_action_rotate_session_set_session_name(
-                       rotate_session_action, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (object,NULL) expect invalid");
-       status = lttng_action_rotate_session_set_session_name(
-                       NULL, session_name);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,object) expect invalid");
+       status = lttng_action_rotate_session_set_session_name(nullptr, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,NULL) expect invalid");
+       status = lttng_action_rotate_session_set_session_name(rotate_session_action, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (object,NULL) expect invalid");
+       status = lttng_action_rotate_session_set_session_name(nullptr, session_name);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,object) expect invalid");
 
        /* Set the session name */
-       status = lttng_action_rotate_session_set_session_name(
-                       rotate_session_action, session_name);
+       status = lttng_action_rotate_session_set_session_name(rotate_session_action, session_name);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set session name");
 
-       status = lttng_action_rotate_session_get_session_name(
-                       rotate_session_action, &get_session_name);
-       ok(status == LTTNG_ACTION_STATUS_OK &&
-                                       !strcmp(session_name, get_session_name),
-                       "Get session name, expected `%s` got `%s`",
-                       session_name, get_session_name);
+       status = lttng_action_rotate_session_get_session_name(rotate_session_action,
+                                                             &get_session_name);
+       ok(status == LTTNG_ACTION_STATUS_OK && !strcmp(session_name, get_session_name),
+          "Get session name, expected `%s` got `%s`",
+          session_name,
+          get_session_name);
 
        /* Validate the default policy for a rotate_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_rotate_session_get_rate_policy(
-                               rotate_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_rotate_session_get_rate_policy(rotate_session_action,
+                                                                    &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               default_policy,
-                                                               cur_policy),
-                               "Default policy is every n=1");
+                          lttng_rate_policy_is_equal(default_policy, cur_policy),
+                  "Default policy is every n=1");
        }
 
        /* Set a custom policy. */
-       status = lttng_action_rotate_session_set_rate_policy(
-                       rotate_session_action, policy);
+       status = lttng_action_rotate_session_set_rate_policy(rotate_session_action, policy);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set rate policy");
 
        /* Validate the custom policy for a rotate_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_rotate_session_get_rate_policy(
-                               rotate_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_rotate_session_get_rate_policy(rotate_session_action,
+                                                                    &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               policy,
-                                                               cur_policy),
-                               "rotate_session action policy get");
+                          lttng_rate_policy_is_equal(policy, cur_policy),
+                  "rotate_session action policy get");
        }
 
        /* Ser/des tests. */
@@ -194,18 +259,14 @@ static void test_action_rotate_session(void)
        ok(ret == 0, "Action rotate_session serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               (void) lttng_action_create_from_payload(
-                               &view, &rotate_session_action_from_buffer);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view, &rotate_session_action_from_buffer);
        }
        ok(rotate_session_action_from_buffer,
-                       "rotate_session action created from payload is non-null");
+          "rotate_session action created from payload is non-null");
 
-       ok(lttng_action_is_equal(rotate_session_action,
-                          rotate_session_action_from_buffer),
-                       "Serialized and de-serialized rotate_session action are equal");
+       ok(lttng_action_is_equal(rotate_session_action, rotate_session_action_from_buffer),
+          "Serialized and de-serialized rotate_session action are equal");
 
        lttng_rate_policy_destroy(default_policy);
        lttng_rate_policy_destroy(policy);
@@ -214,13 +275,13 @@ static void test_action_rotate_session(void)
        lttng_payload_reset(&payload);
 }
 
-static void test_action_start_session(void)
+static void test_action_start_session()
 {
        int ret;
        enum lttng_action_status status;
-       struct lttng_action *start_session_action = NULL,
-                           *start_session_action_from_buffer = NULL;
-       struct lttng_rate_policy *policy = NULL, *default_policy;
+       struct lttng_action *start_session_action = nullptr,
+                           *start_session_action_from_buffer = nullptr;
+       struct lttng_rate_policy *policy = nullptr, *default_policy;
        struct lttng_payload payload;
        const char *session_name = "my_session_name";
        const char *get_session_name;
@@ -236,62 +297,50 @@ static void test_action_start_session(void)
 
        start_session_action = lttng_action_start_session_create();
        ok(start_session_action, "Create start_session action");
-       ok(lttng_action_get_type(start_session_action) ==
-                                       LTTNG_ACTION_TYPE_START_SESSION,
-                       "Action has type LTTNG_ACTION_TYPE_START_SESSION");
+       ok(lttng_action_get_type(start_session_action) == LTTNG_ACTION_TYPE_START_SESSION,
+          "Action has type LTTNG_ACTION_TYPE_START_SESSION");
 
        /* Session name setter. */
-       status = lttng_action_start_session_set_session_name(NULL, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,NULL) expect invalid");
-       status = lttng_action_start_session_set_session_name(
-                       start_session_action, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (object,NULL) expect invalid");
-       status = lttng_action_start_session_set_session_name(
-                       NULL, session_name);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,object) expect invalid");
+       status = lttng_action_start_session_set_session_name(nullptr, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,NULL) expect invalid");
+       status = lttng_action_start_session_set_session_name(start_session_action, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (object,NULL) expect invalid");
+       status = lttng_action_start_session_set_session_name(nullptr, session_name);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,object) expect invalid");
 
        /* Set the session name */
-       status = lttng_action_start_session_set_session_name(
-                       start_session_action, session_name);
+       status = lttng_action_start_session_set_session_name(start_session_action, session_name);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set session name");
 
-       status = lttng_action_start_session_get_session_name(
-                       start_session_action, &get_session_name);
-       ok(status == LTTNG_ACTION_STATUS_OK &&
-                                       !strcmp(session_name, get_session_name),
-                       "Get session name, expected `%s` got `%s`",
-                       session_name, get_session_name);
+       status = lttng_action_start_session_get_session_name(start_session_action,
+                                                            &get_session_name);
+       ok(status == LTTNG_ACTION_STATUS_OK && !strcmp(session_name, get_session_name),
+          "Get session name, expected `%s` got `%s`",
+          session_name,
+          get_session_name);
 
        /* Validate the default policy for a start_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_start_session_get_rate_policy(
-                               start_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_start_session_get_rate_policy(start_session_action,
+                                                                   &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               default_policy,
-                                                               cur_policy),
-                               "Default policy is every n=1");
+                          lttng_rate_policy_is_equal(default_policy, cur_policy),
+                  "Default policy is every n=1");
        }
 
        /* Set a custom policy. */
-       status = lttng_action_start_session_set_rate_policy(
-                       start_session_action, policy);
+       status = lttng_action_start_session_set_rate_policy(start_session_action, policy);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set rate policy");
 
        /* Validate the custom policy for a start_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_start_session_get_rate_policy(
-                               start_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_start_session_get_rate_policy(start_session_action,
+                                                                   &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               policy,
-                                                               cur_policy),
-                               "start_session action policy get");
+                          lttng_rate_policy_is_equal(policy, cur_policy),
+                  "start_session action policy get");
        }
 
        /* Ser/des tests. */
@@ -299,18 +348,14 @@ static void test_action_start_session(void)
        ok(ret == 0, "Action start_session serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               (void) lttng_action_create_from_payload(
-                               &view, &start_session_action_from_buffer);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view, &start_session_action_from_buffer);
        }
        ok(start_session_action_from_buffer,
-                       "start_session action created from payload is non-null");
+          "start_session action created from payload is non-null");
 
-       ok(lttng_action_is_equal(start_session_action,
-                          start_session_action_from_buffer),
-                       "Serialized and de-serialized start_session action are equal");
+       ok(lttng_action_is_equal(start_session_action, start_session_action_from_buffer),
+          "Serialized and de-serialized start_session action are equal");
 
        lttng_rate_policy_destroy(default_policy);
        lttng_rate_policy_destroy(policy);
@@ -319,13 +364,13 @@ static void test_action_start_session(void)
        lttng_payload_reset(&payload);
 }
 
-static void test_action_stop_session(void)
+static void test_action_stop_session()
 {
        int ret;
        enum lttng_action_status status;
-       struct lttng_action *stop_session_action = NULL,
-                           *stop_session_action_from_buffer = NULL;
-       struct lttng_rate_policy *policy = NULL, *default_policy;
+       struct lttng_action *stop_session_action = nullptr,
+                           *stop_session_action_from_buffer = nullptr;
+       struct lttng_rate_policy *policy = nullptr, *default_policy;
        struct lttng_payload payload;
        const char *session_name = "my_session_name";
        const char *get_session_name;
@@ -341,61 +386,49 @@ static void test_action_stop_session(void)
 
        stop_session_action = lttng_action_stop_session_create();
        ok(stop_session_action, "Create stop_session action");
-       ok(lttng_action_get_type(stop_session_action) ==
-                                       LTTNG_ACTION_TYPE_STOP_SESSION,
-                       "Action has type LTTNG_ACTION_TYPE_STOP_SESSION");
+       ok(lttng_action_get_type(stop_session_action) == LTTNG_ACTION_TYPE_STOP_SESSION,
+          "Action has type LTTNG_ACTION_TYPE_STOP_SESSION");
 
        /* Session name setter. */
-       status = lttng_action_stop_session_set_session_name(NULL, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,NULL) expect invalid");
-       status = lttng_action_stop_session_set_session_name(
-                       stop_session_action, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (object,NULL) expect invalid");
-       status = lttng_action_stop_session_set_session_name(NULL, session_name);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,object) expect invalid");
+       status = lttng_action_stop_session_set_session_name(nullptr, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,NULL) expect invalid");
+       status = lttng_action_stop_session_set_session_name(stop_session_action, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (object,NULL) expect invalid");
+       status = lttng_action_stop_session_set_session_name(nullptr, session_name);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,object) expect invalid");
 
        /* Set the session name */
-       status = lttng_action_stop_session_set_session_name(
-                       stop_session_action, session_name);
+       status = lttng_action_stop_session_set_session_name(stop_session_action, session_name);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set session name");
 
-       status = lttng_action_stop_session_get_session_name(
-                       stop_session_action, &get_session_name);
-       ok(status == LTTNG_ACTION_STATUS_OK &&
-                                       !strcmp(session_name, get_session_name),
-                       "Get session name, expected `%s` got `%s`",
-                       session_name, get_session_name);
+       status = lttng_action_stop_session_get_session_name(stop_session_action, &get_session_name);
+       ok(status == LTTNG_ACTION_STATUS_OK && !strcmp(session_name, get_session_name),
+          "Get session name, expected `%s` got `%s`",
+          session_name,
+          get_session_name);
 
        /* Validate the default policy for a stop_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_stop_session_get_rate_policy(
-                               stop_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status =
+                       lttng_action_stop_session_get_rate_policy(stop_session_action, &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               default_policy,
-                                                               cur_policy),
-                               "Default policy is every n=1");
+                          lttng_rate_policy_is_equal(default_policy, cur_policy),
+                  "Default policy is every n=1");
        }
 
        /* Set a custom policy. */
-       status = lttng_action_stop_session_set_rate_policy(
-                       stop_session_action, policy);
+       status = lttng_action_stop_session_set_rate_policy(stop_session_action, policy);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set rate policy");
 
        /* Validate the custom policy for a stop_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_stop_session_get_rate_policy(
-                               stop_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status =
+                       lttng_action_stop_session_get_rate_policy(stop_session_action, &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               policy,
-                                                               cur_policy),
-                               "stop_session action policy get");
+                          lttng_rate_policy_is_equal(policy, cur_policy),
+                  "stop_session action policy get");
        }
 
        /* Ser/des tests. */
@@ -403,18 +436,13 @@ static void test_action_stop_session(void)
        ok(ret == 0, "Action stop_session serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               (void) lttng_action_create_from_payload(
-                               &view, &stop_session_action_from_buffer);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view, &stop_session_action_from_buffer);
        }
-       ok(stop_session_action_from_buffer,
-                       "stop_session action created from payload is non-null");
+       ok(stop_session_action_from_buffer, "stop_session action created from payload is non-null");
 
-       ok(lttng_action_is_equal(stop_session_action,
-                          stop_session_action_from_buffer),
-                       "Serialized and de-serialized stop_session action are equal");
+       ok(lttng_action_is_equal(stop_session_action, stop_session_action_from_buffer),
+          "Serialized and de-serialized stop_session action are equal");
 
        lttng_rate_policy_destroy(default_policy);
        lttng_rate_policy_destroy(policy);
@@ -423,13 +451,13 @@ static void test_action_stop_session(void)
        lttng_payload_reset(&payload);
 }
 
-static void test_action_snapshot_session(void)
+static void test_action_snapshot_session()
 {
        int ret;
        enum lttng_action_status status;
-       struct lttng_action *snapshot_session_action = NULL,
-                           *snapshot_session_action_from_buffer = NULL;
-       struct lttng_rate_policy *policy = NULL, *default_policy;
+       struct lttng_action *snapshot_session_action = nullptr,
+                           *snapshot_session_action_from_buffer = nullptr;
+       struct lttng_rate_policy *policy = nullptr, *default_policy;
        struct lttng_payload payload;
        const char *session_name = "my_session_name";
        const char *get_session_name;
@@ -445,62 +473,51 @@ static void test_action_snapshot_session(void)
 
        snapshot_session_action = lttng_action_snapshot_session_create();
        ok(snapshot_session_action, "Create snapshot_session action");
-       ok(lttng_action_get_type(snapshot_session_action) ==
-                                       LTTNG_ACTION_TYPE_SNAPSHOT_SESSION,
-                       "Action has type LTTNG_ACTION_TYPE_SNAPSHOT_SESSION");
+       ok(lttng_action_get_type(snapshot_session_action) == LTTNG_ACTION_TYPE_SNAPSHOT_SESSION,
+          "Action has type LTTNG_ACTION_TYPE_SNAPSHOT_SESSION");
 
        /* Session name setter. */
-       status = lttng_action_snapshot_session_set_session_name(NULL, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,NULL) expect invalid");
-       status = lttng_action_snapshot_session_set_session_name(
-                       snapshot_session_action, NULL);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (object,NULL) expect invalid");
-       status = lttng_action_snapshot_session_set_session_name(
-                       NULL, session_name);
-       ok(status == LTTNG_ACTION_STATUS_INVALID,
-                       "Set session name (NULL,object) expect invalid");
+       status = lttng_action_snapshot_session_set_session_name(nullptr, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,NULL) expect invalid");
+       status = lttng_action_snapshot_session_set_session_name(snapshot_session_action, nullptr);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (object,NULL) expect invalid");
+       status = lttng_action_snapshot_session_set_session_name(nullptr, session_name);
+       ok(status == LTTNG_ACTION_STATUS_INVALID, "Set session name (NULL,object) expect invalid");
 
        /* Set the session name */
-       status = lttng_action_snapshot_session_set_session_name(
-                       snapshot_session_action, session_name);
+       status = lttng_action_snapshot_session_set_session_name(snapshot_session_action,
+                                                               session_name);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set session name");
 
-       status = lttng_action_snapshot_session_get_session_name(
-                       snapshot_session_action, &get_session_name);
-       ok(status == LTTNG_ACTION_STATUS_OK &&
-                                       !strcmp(session_name, get_session_name),
-                       "Get session name, expected `%s` got `%s`",
-                       session_name, get_session_name);
+       status = lttng_action_snapshot_session_get_session_name(snapshot_session_action,
+                                                               &get_session_name);
+       ok(status == LTTNG_ACTION_STATUS_OK && !strcmp(session_name, get_session_name),
+          "Get session name, expected `%s` got `%s`",
+          session_name,
+          get_session_name);
 
        /* Validate the default policy for a snapshot_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_snapshot_session_get_rate_policy(
-                               snapshot_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_snapshot_session_get_rate_policy(snapshot_session_action,
+                                                                      &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               default_policy,
-                                                               cur_policy),
-                               "Default policy is every n=1");
+                          lttng_rate_policy_is_equal(default_policy, cur_policy),
+                  "Default policy is every n=1");
        }
 
        /* Set a custom policy. */
-       status = lttng_action_snapshot_session_set_rate_policy(
-                       snapshot_session_action, policy);
+       status = lttng_action_snapshot_session_set_rate_policy(snapshot_session_action, policy);
        ok(status == LTTNG_ACTION_STATUS_OK, "Set rate policy");
 
        /* Validate the custom policy for a snapshot_session action. */
        {
-               const struct lttng_rate_policy *cur_policy = NULL;
-               status = lttng_action_snapshot_session_get_rate_policy(
-                               snapshot_session_action, &cur_policy);
+               const struct lttng_rate_policy *cur_policy = nullptr;
+               status = lttng_action_snapshot_session_get_rate_policy(snapshot_session_action,
+                                                                      &cur_policy);
                ok(status == LTTNG_ACTION_STATUS_OK &&
-                                               lttng_rate_policy_is_equal(
-                                                               policy,
-                                                               cur_policy),
-                               "snapshot_session action policy get");
+                          lttng_rate_policy_is_equal(policy, cur_policy),
+                  "snapshot_session action policy get");
        }
 
        /* Ser/des tests. */
@@ -508,18 +525,15 @@ static void test_action_snapshot_session(void)
        ok(ret == 0, "Action snapshot_session serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               (void) lttng_action_create_from_payload(
-                               &view, &snapshot_session_action_from_buffer);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               (void) lttng_action_create_from_payload(&view,
+                                                       &snapshot_session_action_from_buffer);
        }
        ok(snapshot_session_action_from_buffer,
-                       "snapshot_session action created from payload is non-null");
+          "snapshot_session action created from payload is non-null");
 
-       ok(lttng_action_is_equal(snapshot_session_action,
-                          snapshot_session_action_from_buffer),
-                       "Serialized and de-serialized snapshot_session action are equal");
+       ok(lttng_action_is_equal(snapshot_session_action, snapshot_session_action_from_buffer),
+          "Serialized and de-serialized snapshot_session action are equal");
 
        lttng_rate_policy_destroy(default_policy);
        lttng_rate_policy_destroy(policy);
@@ -528,13 +542,24 @@ static void test_action_snapshot_session(void)
        lttng_payload_reset(&payload);
 }
 
-int main(void)
+static int _main()
 {
        plan_tests(NUM_TESTS);
        test_action_notify();
+       test_action_list();
        test_action_rotate_session();
        test_action_start_session();
        test_action_stop_session();
        test_action_snapshot_session();
        return exit_status();
 }
+
+int main()
+{
+       try {
+               return _main();
+       } catch (const std::exception& e) {
+               ERR_FMT("Unhandled exception caught by action unit test: {}", e.what());
+               abort();
+       }
+}
index 764549b83da41c7e289090286d4d22326c819dd1..69812de43301952434d9ea8334a9cef0a0d05946 100644 (file)
@@ -5,8 +5,8 @@
  *
  */
 
-
 #include <common/buffer-view.hpp>
+
 #include <tap/tap.h>
 
 static const int TEST_COUNT = 5;
@@ -16,12 +16,11 @@ int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
 int lttng_opt_mi;
 
-static void test_contains_string(void)
+static void test_contains_string()
 {
-       const char buf[] = {'A', 'l', 'l', 'o', '\0'};
+       const char buf[] = { 'A', 'l', 'l', 'o', '\0' };
        struct lttng_buffer_view view = lttng_buffer_view_init(buf, 0, 5);
-       struct lttng_buffer_view view_minus_one =
-                       lttng_buffer_view_init(buf, 0, 4);
+       struct lttng_buffer_view view_minus_one = lttng_buffer_view_init(buf, 0, 4);
 
        ok1(!lttng_buffer_view_contains_string(&view, buf, 4));
        ok1(lttng_buffer_view_contains_string(&view, buf, 5));
@@ -31,7 +30,7 @@ static void test_contains_string(void)
        ok1(!lttng_buffer_view_contains_string(&view_minus_one, buf, 5));
 }
 
-int main(void)
+int main()
 {
        plan_tests(TEST_COUNT);
 
index 9ed6b89418e9225ce2481fe390a2186c76f21938..45dbe2acbcbba37d4e1a7a94a76bee3a36a374b7 100644 (file)
@@ -9,22 +9,22 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
+#include <common/buffer-view.hpp>
+#include <common/dynamic-buffer.hpp>
 
-#include <lttng/event.h>
-#include <lttng/event-rule/user-tracepoint.h>
 #include <lttng/condition/condition-internal.hpp>
-#include <lttng/condition/event-rule-matches.h>
 #include <lttng/condition/event-rule-matches-internal.hpp>
+#include <lttng/condition/event-rule-matches.h>
 #include <lttng/domain.h>
+#include <lttng/event-rule/user-tracepoint.h>
+#include <lttng/event.h>
 #include <lttng/log-level-rule.h>
-#include <common/dynamic-buffer.hpp>
-#include <common/buffer-view.hpp>
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
 
 /* For error.h */
 int lttng_opt_quiet = 1;
@@ -33,28 +33,26 @@ int lttng_opt_mi;
 
 #define NUM_TESTS 13
 
-static
-void test_condition_event_rule(void)
+static void test_condition_event_rule()
 {
        int ret, i;
-       struct lttng_event_rule *tracepoint = NULL;
-       const struct lttng_event_rule *tracepoint_tmp = NULL;
+       struct lttng_event_rule *tracepoint = nullptr;
+       const struct lttng_event_rule *tracepoint_tmp = nullptr;
        enum lttng_event_rule_status status;
-       struct lttng_condition *condition = NULL;
-       struct lttng_condition *condition_from_buffer = NULL;
+       struct lttng_condition *condition = nullptr;
+       struct lttng_condition *condition_from_buffer = nullptr;
        enum lttng_condition_status condition_status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *exclusions[] = { "my_event_test1", "my_event_test2", "my_event_test3" };
-       struct lttng_log_level_rule *log_level_rule_at_least_as_severe = NULL;
+       struct lttng_log_level_rule *log_level_rule_at_least_as_severe = nullptr;
        struct lttng_payload buffer;
 
        lttng_payload_init(&buffer);
 
        /* Create log level rule. */
        log_level_rule_at_least_as_severe =
-                       lttng_log_level_rule_at_least_as_severe_as_create(
-                                       LTTNG_LOGLEVEL_WARNING);
+               lttng_log_level_rule_at_least_as_severe_as_create(LTTNG_LOGLEVEL_WARNING);
        LTTNG_ASSERT(log_level_rule_at_least_as_severe);
 
        tracepoint = lttng_event_rule_user_tracepoint_create();
@@ -67,40 +65,37 @@ void test_condition_event_rule(void)
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Setting filter");
 
        status = lttng_event_rule_user_tracepoint_set_log_level_rule(
-                       tracepoint, log_level_rule_at_least_as_severe);
+               tracepoint, log_level_rule_at_least_as_severe);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Setting log level range");
 
        for (i = 0; i < 3; i++) {
-               status = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
-                               tracepoint, exclusions[i]);
-               ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Setting exclusion pattern");
+               status = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(tracepoint,
+                                                                                    exclusions[i]);
+               ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Setting exclusion pattern");
        }
 
        condition = lttng_condition_event_rule_matches_create(tracepoint);
        ok(condition, "Created condition");
 
-       condition_status = lttng_condition_event_rule_matches_get_rule(
-                       condition, &tracepoint_tmp);
+       condition_status = lttng_condition_event_rule_matches_get_rule(condition, &tracepoint_tmp);
        ok(condition_status == LTTNG_CONDITION_STATUS_OK,
-                       "Getting event rule from event rule condition");
-       ok(tracepoint == tracepoint_tmp, "lttng_condition_event_rule_get_rule provides a reference to the original rule");
+          "Getting event rule from event rule condition");
+       ok(tracepoint == tracepoint_tmp,
+          "lttng_condition_event_rule_get_rule provides a reference to the original rule");
 
        ret = lttng_condition_serialize(condition, &buffer);
        ok(ret == 0, "Condition serialized");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(&buffer, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&buffer, 0, -1);
 
-               (void) lttng_condition_create_from_payload(
-                               &view, &condition_from_buffer);
+               (void) lttng_condition_create_from_payload(&view, &condition_from_buffer);
        }
 
        ok(condition_from_buffer, "Condition created from payload is non-null");
 
        ok(lttng_condition_is_equal(condition, condition_from_buffer),
-                       "Serialized and de-serialized conditions are equal");
+          "Serialized and de-serialized conditions are equal");
 
        lttng_payload_reset(&buffer);
        lttng_event_rule_destroy(tracepoint);
@@ -109,7 +104,7 @@ void test_condition_event_rule(void)
        lttng_log_level_rule_destroy(log_level_rule_at_least_as_severe);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_condition_event_rule();
index 8a4e614993379ff42e01779b9cde562507d91b93..05a276db0b1b10b79f7e24851affc04c7f21687f 100644 (file)
@@ -5,6 +5,10 @@
  *
  */
 
+#include <common/compat/directory-handle.hpp>
+#include <common/compat/errno.hpp>
+#include <common/error.hpp>
+
 #include <fcntl.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <unistd.h>
-
-#include <common/compat/directory-handle.hpp>
-#include <common/compat/errno.hpp>
-#include <common/error.hpp>
 #include <tap/tap.h>
+#include <unistd.h>
 
 #define TEST_COUNT 9
 
@@ -32,7 +32,7 @@ int lttng_opt_mi;
  * Returns the number of tests that ran (irrespective of the result) or a
  * negative value on error (will abort all tests).
  */
-typedef int(test_func)(const char *test_base_path);
+using test_func = int(const char *);
 
 static test_func test_rmdir_fail_non_empty;
 static test_func test_rmdir_skip_non_empty;
@@ -63,14 +63,13 @@ static bool dir_exists(const char *path)
  *             ├── f
  *             └── file1
  */
-static int create_non_empty_hierarchy_with_root(
-               struct lttng_directory_handle *test_dir_handle,
-               const char *test_root_name)
+static int create_non_empty_hierarchy_with_root(struct lttng_directory_handle *test_dir_handle,
+                                               const char *test_root_name)
 {
        int ret;
        const int file_flags = O_WRONLY | O_CREAT | O_TRUNC;
        const mode_t file_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
-       char *branch_name = NULL;
+       char *branch_name = nullptr;
 
        ret = asprintf(&branch_name, "%s/%s", test_root_name, "a/b/c/d");
        if (ret < 0) {
@@ -78,9 +77,7 @@ static int create_non_empty_hierarchy_with_root(
                goto end;
        }
        ret = lttng_directory_handle_create_subdirectory_recursive(
-                       test_dir_handle,
-                       branch_name,
-                       DIR_CREATION_MODE);
+               test_dir_handle, branch_name, DIR_CREATION_MODE);
        if (ret) {
                diag("Failed to create test folder hierarchy %s", branch_name);
                goto end;
@@ -93,9 +90,7 @@ static int create_non_empty_hierarchy_with_root(
                goto end;
        }
        ret = lttng_directory_handle_create_subdirectory_recursive(
-                       test_dir_handle,
-                       branch_name,
-                       DIR_CREATION_MODE);
+               test_dir_handle, branch_name, DIR_CREATION_MODE);
        if (ret) {
                diag("Failed to create test folder hierarchy %s", branch_name);
                goto end;
@@ -107,16 +102,14 @@ static int create_non_empty_hierarchy_with_root(
                diag("Failed to format file path");
                goto end;
        }
-       ret = lttng_directory_handle_open_file(
-                       test_dir_handle, branch_name, file_flags, file_mode);
+       ret = lttng_directory_handle_open_file(test_dir_handle, branch_name, file_flags, file_mode);
        if (ret < 0) {
                diag("Failed to create file %s", branch_name);
                goto end;
        }
        ret = close(ret);
        if (ret) {
-               PERROR("Failed to close fd to newly created file %s",
-                               branch_name);
+               PERROR("Failed to close fd to newly created file %s", branch_name);
                goto end;
        }
 end:
@@ -125,12 +118,11 @@ end:
 }
 
 /* Remove "file1" from the test folder hierarchy. */
-static
-int remove_file_from_hierarchy(struct lttng_directory_handle *test_dir_handle,
-               const char *test_root_name)
+static int remove_file_from_hierarchy(struct lttng_directory_handle *test_dir_handle,
+                                     const char *test_root_name)
 {
        int ret;
-       char *file_name = NULL;
+       char *file_name = nullptr;
 
        ret = asprintf(&file_name, "%s/%s", test_root_name, "a/b/e/file1");
        if (ret < 0) {
@@ -138,8 +130,7 @@ int remove_file_from_hierarchy(struct lttng_directory_handle *test_dir_handle,
                goto end;
        }
 
-       ret = lttng_directory_handle_unlink_file(test_dir_handle,
-                       file_name);
+       ret = lttng_directory_handle_unlink_file(test_dir_handle, file_name);
        if (ret) {
                PERROR("Failed to unlink file %s", file_name);
                goto end;
@@ -153,9 +144,9 @@ static int test_rmdir_fail_non_empty(const char *test_dir)
 {
        int ret, tests_ran = 0;
        struct lttng_directory_handle *test_dir_handle;
-       char *created_dir = NULL;
+       char *created_dir = nullptr;
        const char test_root_name[] = "fail_non_empty";
-       char *test_dir_path = NULL;
+       char *test_dir_path = nullptr;
 
        diag("rmdir (fail if non-empty)");
 
@@ -174,9 +165,9 @@ static int test_rmdir_fail_non_empty(const char *test_dir)
        }
 
        ret = lttng_directory_handle_remove_subdirectory_recursive(
-                       test_dir_handle, test_root_name,
-                       LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG);
-       ok(ret == -1, "Error returned when attempting to recursively remove non-empty hierarchy with LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG");
+               test_dir_handle, test_root_name, LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG);
+       ok(ret == -1,
+          "Error returned when attempting to recursively remove non-empty hierarchy with LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG");
        tests_ran++;
 
        ret = remove_file_from_hierarchy(test_dir_handle, test_root_name);
@@ -186,9 +177,9 @@ static int test_rmdir_fail_non_empty(const char *test_dir)
        }
 
        ret = lttng_directory_handle_remove_subdirectory_recursive(
-                       test_dir_handle, test_root_name,
-                       LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG);
-       ok(ret == 0, "No error returned when recursively removing empty hierarchy with LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG");
+               test_dir_handle, test_root_name, LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG);
+       ok(ret == 0,
+          "No error returned when recursively removing empty hierarchy with LTTNG_DIRECTORY_HANDLE_FAIL_NON_EMPTY_FLAG");
        tests_ran++;
 
        ret = asprintf(&test_dir_path, "%s/%s", test_dir, test_root_name);
@@ -197,8 +188,8 @@ static int test_rmdir_fail_non_empty(const char *test_dir)
                goto end;
        }
        ok(!dir_exists(test_dir_path) && errno == ENOENT,
-                       "Folder hierarchy %s successfully removed",
-                       test_dir_path);
+          "Folder hierarchy %s successfully removed",
+          test_dir_path);
        tests_ran++;
        ret = 0;
 end:
@@ -212,9 +203,9 @@ static int test_rmdir_skip_non_empty(const char *test_dir)
 {
        int ret, tests_ran = 0;
        struct lttng_directory_handle *test_dir_handle;
-       char *created_dir = NULL;
+       char *created_dir = nullptr;
        const char test_root_name[] = "skip_non_empty";
-       char *test_dir_path = NULL;
+       char *test_dir_path = nullptr;
 
        diag("rmdir (skip if non-empty)");
 
@@ -233,9 +224,9 @@ static int test_rmdir_skip_non_empty(const char *test_dir)
        }
 
        ret = lttng_directory_handle_remove_subdirectory_recursive(
-                       test_dir_handle, test_root_name,
-                       LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
-       ok(ret == 0, "No error returned when attempting to recursively remove non-empty hierarchy with LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG");
+               test_dir_handle, test_root_name, LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+       ok(ret == 0,
+          "No error returned when attempting to recursively remove non-empty hierarchy with LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG");
        tests_ran++;
 
        ret = asprintf(&test_dir_path, "%s/%s", test_dir, test_root_name);
@@ -253,14 +244,14 @@ static int test_rmdir_skip_non_empty(const char *test_dir)
        }
 
        ret = lttng_directory_handle_remove_subdirectory_recursive(
-                       test_dir_handle, test_root_name,
-                       LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
-       ok(ret == 0, "No error returned when recursively removing empty hierarchy with LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG");
+               test_dir_handle, test_root_name, LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG);
+       ok(ret == 0,
+          "No error returned when recursively removing empty hierarchy with LTTNG_DIRECTORY_HANDLE_SKIP_NON_EMPTY_FLAG");
        tests_ran++;
 
        ok(!dir_exists(test_dir_path) && errno == ENOENT,
-                       "Folder hierarchy %s successfully removed",
-                       test_dir_path);
+          "Folder hierarchy %s successfully removed",
+          test_dir_path);
        tests_ran++;
        ret = 0;
 end:
@@ -270,7 +261,7 @@ end:
        return ret == 0 ? tests_ran : ret;
 }
 
-int main(void)
+int main()
 {
        int ret;
        char test_dir[] = "/tmp/lttng-XXXXXX";
@@ -286,13 +277,12 @@ int main(void)
                goto end;
        }
 
-       for (func_idx = 0; func_idx < sizeof(test_funcs) / sizeof(*test_funcs);
-                       func_idx++) {
+       for (func_idx = 0; func_idx < sizeof(test_funcs) / sizeof(*test_funcs); func_idx++) {
                tests_left -= test_funcs[func_idx](test_dir);
        }
        if (tests_left) {
                diag("Skipping %d tests that could not be executed due to a prior error",
-                               tests_left);
+                    tests_left);
                skip(tests_left, "test due to an error");
        }
 end:
index 577dea93229ce1ffc12c785508383b20e217b83e..a0d04357ddcf2db9d7019bdb3e26d906441f1e4f 100644 (file)
@@ -6,17 +6,18 @@
  */
 
 #include <common/bytecode/bytecode.hpp>
+
 #include <lttng/event-expr-internal.hpp>
 #include <lttng/event-expr.h>
+
 #include <tap/tap.h>
 
 #define NR_TESTS 4
 
-static
-void test_event_payload_field(void)
+static void test_event_payload_field()
 {
        struct lttng_event_expr *event_expr;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        int ret;
 
        event_expr = lttng_event_expr_event_payload_field_create("tourlou");
@@ -28,11 +29,10 @@ void test_event_payload_field(void)
        free(bytecode);
 }
 
-static
-void test_channel_context_field(void)
+static void test_channel_context_field()
 {
        struct lttng_event_expr *event_expr;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        int ret;
 
        event_expr = lttng_event_expr_channel_context_field_create("tourlou");
@@ -44,11 +44,10 @@ void test_channel_context_field(void)
        free(bytecode);
 }
 
-static
-void test_app_specific_context_field(void)
+static void test_app_specific_context_field()
 {
        struct lttng_event_expr *event_expr;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        int ret;
 
        event_expr = lttng_event_expr_app_specific_context_field_create("Bob", "Leponge");
@@ -60,11 +59,10 @@ void test_app_specific_context_field(void)
        free(bytecode);
 }
 
-static
-void test_array_field_element(void)
+static void test_array_field_element()
 {
        struct lttng_event_expr *event_expr;
-       struct lttng_bytecode *bytecode = NULL;
+       struct lttng_bytecode *bytecode = nullptr;
        int ret;
 
        event_expr = lttng_event_expr_event_payload_field_create("allo");
@@ -77,7 +75,7 @@ void test_array_field_element(void)
        free(bytecode);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NR_TESTS);
 
index d7228d0f31f236fc47cac685e547633f3633752f..654d4903e5e76bb393222c6f291bdcd75ed2eed7 100644 (file)
@@ -7,15 +7,11 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
+#include "bin/lttng/loglevel.hpp"
 
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/domain.h>
 #include <lttng/event-rule/jul-logging-internal.hpp>
 #include <lttng/event-rule/jul-logging.h>
 #include <lttng/event-rule/kernel-kprobe.h>
 #include <lttng/event-rule/kernel-syscall-internal.hpp>
 #include <lttng/event-rule/kernel-syscall.h>
-#include <lttng/event-rule/python-logging-internal.hpp>
-#include <lttng/event-rule/python-logging.h>
 #include <lttng/event-rule/kernel-tracepoint-internal.hpp>
 #include <lttng/event-rule/kernel-tracepoint.h>
 #include <lttng/event-rule/kernel-uprobe-internal.hpp>
 #include <lttng/event-rule/kernel-uprobe.h>
+#include <lttng/event-rule/python-logging-internal.hpp>
+#include <lttng/event-rule/python-logging.h>
 #include <lttng/event-rule/user-tracepoint-internal.hpp>
 #include <lttng/event-rule/user-tracepoint.h>
 #include <lttng/event.h>
 #include <lttng/kernel-probe.h>
 #include <lttng/userspace-probe-internal.hpp>
 #include <lttng/userspace-probe.h>
-#include "bin/lttng/loglevel.hpp"
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
 
 /* For error.h. */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
 int lttng_opt_mi;
 
-#define NUM_TESTS 212
+#ifdef __linux__
+#define UPROBE_NUM_TESTS 9
+#else /* __linux__ */
+#define UPROBE_NUM_TESTS 0
+#endif /* __linux__ */
+
+#define NUM_TESTS (203 + UPROBE_NUM_TESTS)
 
 namespace {
 struct tracepoint_test {
@@ -52,21 +59,19 @@ struct tracepoint_test {
 };
 } /* namespace */
 
-typedef const char *(*log_level_name_getter)(int log_level);
+using log_level_name_getter = const char *(*) (int);
 
-typedef struct lttng_event_rule *(*event_rule_create)(void);
-typedef enum lttng_event_rule_status (*event_rule_set_log_level)(
-               struct lttng_event_rule *rule,
-               const struct lttng_log_level_rule *log_level_rule);
+using event_rule_create = struct lttng_event_rule *(*) ();
+using event_rule_set_log_level = enum lttng_event_rule_status (*)(
+       struct lttng_event_rule *, const struct lttng_log_level_rule *);
 
-static
-void test_event_rule_kernel_tracepoint(void)
+static void test_event_rule_kernel_tracepoint()
 {
-       struct lttng_event_rule *tracepoint = NULL;
-       struct lttng_event_rule *tracepoint_from_buffer = NULL;
+       struct lttng_event_rule *tracepoint = nullptr;
+       struct lttng_event_rule *tracepoint_from_buffer = nullptr;
        enum lttng_event_rule_status status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *tmp;
        struct lttng_payload payload;
 
@@ -92,36 +97,35 @@ void test_event_rule_kernel_tracepoint(void)
        ok(lttng_event_rule_serialize(tracepoint, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                               &view, &tracepoint_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &tracepoint_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_event_rule_is_equal(tracepoint, tracepoint_from_buffer), "serialized and from buffer are equal.");
+       ok(lttng_event_rule_is_equal(tracepoint, tracepoint_from_buffer),
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(tracepoint);
        lttng_event_rule_destroy(tracepoint_from_buffer);
 }
 
-static
-void test_event_rule_user_tracepoint(void)
+static void test_event_rule_user_tracepoint()
 {
        int i;
        unsigned int count;
-       struct lttng_event_rule *tracepoint = NULL;
-       struct lttng_event_rule *tracepoint_from_buffer = NULL;
+       struct lttng_event_rule *tracepoint = nullptr;
+       struct lttng_event_rule *tracepoint_from_buffer = nullptr;
        enum lttng_event_rule_status status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *tmp;
-       const char *name_pattern_exclusions[] = {"my_event_test1", "my_event_test2" ,"my_event_test3"};
-       struct lttng_log_level_rule *log_level_rule = NULL;
-       const struct lttng_log_level_rule *log_level_rule_return = NULL;
+       const char *name_pattern_exclusions[] = { "my_event_test1",
+                                                 "my_event_test2",
+                                                 "my_event_test3" };
+       struct lttng_log_level_rule *log_level_rule = nullptr;
+       const struct lttng_log_level_rule *log_level_rule_return = nullptr;
        struct lttng_payload payload;
 
        diag("Testing lttng_event_rule_user_tracepoint.");
@@ -146,55 +150,53 @@ void test_event_rule_user_tracepoint(void)
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "getting filter.");
        ok(!strncmp(filter, tmp, strlen(filter)), "filter is equal.");
 
-       status = lttng_event_rule_user_tracepoint_get_log_level_rule(tracepoint, &log_level_rule_return);
+       status = lttng_event_rule_user_tracepoint_get_log_level_rule(tracepoint,
+                                                                    &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_UNSET, "get unset log level rule.");
 
-       status = lttng_event_rule_user_tracepoint_set_log_level_rule(
-                       tracepoint, log_level_rule);
+       status = lttng_event_rule_user_tracepoint_set_log_level_rule(tracepoint, log_level_rule);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "setting log level rule.");
-       status = lttng_event_rule_user_tracepoint_get_log_level_rule(
-                       tracepoint, &log_level_rule_return);
+       status = lttng_event_rule_user_tracepoint_get_log_level_rule(tracepoint,
+                                                                    &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "get log level rule.");
 
        /* Name pattern exclusions */
        for (i = 0; i < 3; i++) {
                status = lttng_event_rule_user_tracepoint_add_name_pattern_exclusion(
-                               tracepoint, name_pattern_exclusions[i]);
+                       tracepoint, name_pattern_exclusions[i]);
                ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "setting name pattern exclusions \"%s\"",
-                               name_pattern_exclusions[i]);
+                  "setting name pattern exclusions \"%s\"",
+                  name_pattern_exclusions[i]);
        }
 
-       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(
-                       tracepoint, &count);
-       ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "getting name pattern exclusion count.");
+       status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_count(tracepoint,
+                                                                                  &count);
+       ok(status == LTTNG_EVENT_RULE_STATUS_OK, "getting name pattern exclusion count.");
        ok(count == 3, "count is %d/3", count);
 
        for (i = 0; i < count; i++) {
                status = lttng_event_rule_user_tracepoint_get_name_pattern_exclusion_at_index(
-                               tracepoint, i, &tmp);
+                       tracepoint, i, &tmp);
                ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "getting name pattern exclusion at index %d.",
-                               i);
-               ok(!strncmp(name_pattern_exclusions[i], tmp,
-                                  strlen(name_pattern_exclusions[i])),
-                               "%s == %s.", tmp, name_pattern_exclusions[i]);
+                  "getting name pattern exclusion at index %d.",
+                  i);
+               ok(!strncmp(name_pattern_exclusions[i], tmp, strlen(name_pattern_exclusions[i])),
+                  "%s == %s.",
+                  tmp,
+                  name_pattern_exclusions[i]);
        }
 
        ok(lttng_event_rule_serialize(tracepoint, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                               &view, &tracepoint_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &tracepoint_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_event_rule_is_equal(tracepoint, tracepoint_from_buffer), "serialized and from buffer are equal.");
+       ok(lttng_event_rule_is_equal(tracepoint, tracepoint_from_buffer),
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(tracepoint);
@@ -202,10 +204,10 @@ void test_event_rule_user_tracepoint(void)
        lttng_log_level_rule_destroy(log_level_rule);
 }
 
-static void test_event_rule_syscall(void)
+static void test_event_rule_syscall()
 {
-       struct lttng_event_rule *syscall = NULL;
-       struct lttng_event_rule *syscall_from_buffer = NULL;
+       struct lttng_event_rule *syscall = nullptr;
+       struct lttng_event_rule *syscall_from_buffer = nullptr;
        enum lttng_event_rule_status status;
        const char *pattern = "my_event_*";
        const char *filter = "msg_id == 23 && size >= 2048";
@@ -216,7 +218,8 @@ static void test_event_rule_syscall(void)
 
        lttng_payload_init(&payload);
 
-       syscall = lttng_event_rule_kernel_syscall_create(LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
+       syscall = lttng_event_rule_kernel_syscall_create(
+               LTTNG_EVENT_RULE_KERNEL_SYSCALL_EMISSION_SITE_ENTRY);
        ok(syscall, "syscall object.");
 
        status = lttng_event_rule_kernel_syscall_set_name_pattern(syscall, pattern);
@@ -234,34 +237,30 @@ static void test_event_rule_syscall(void)
        ok(lttng_event_rule_serialize(syscall, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                                  &view, &syscall_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &syscall_from_buffer) > 0,
+                  "Deserializing.");
        }
 
        ok(lttng_event_rule_is_equal(syscall, syscall_from_buffer),
-                       "serialized and from buffer are equal.");
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(syscall);
        lttng_event_rule_destroy(syscall_from_buffer);
 }
 
-static
-void test_event_rule_jul_logging(void)
+static void test_event_rule_jul_logging()
 {
-       struct lttng_event_rule *jul_logging = NULL;
-       struct lttng_event_rule *jul_logging_from_buffer = NULL;
+       struct lttng_event_rule *jul_logging = nullptr;
+       struct lttng_event_rule *jul_logging_from_buffer = nullptr;
        enum lttng_event_rule_status status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *tmp;
-       struct lttng_log_level_rule *log_level_rule = NULL;
-       const struct lttng_log_level_rule *log_level_rule_return = NULL;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
+       const struct lttng_log_level_rule *log_level_rule_return = nullptr;
        struct lttng_payload payload;
 
        diag("Testing lttng_event_rule_user_jul_logging.");
@@ -286,29 +285,27 @@ void test_event_rule_jul_logging(void)
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "getting filter.");
        ok(!strncmp(filter, tmp, strlen(filter)), "filter is equal.");
 
-       status = lttng_event_rule_jul_logging_get_log_level_rule(jul_logging, &log_level_rule_return);
+       status = lttng_event_rule_jul_logging_get_log_level_rule(jul_logging,
+                                                                &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_UNSET, "get unset log level rule.");
 
-       status = lttng_event_rule_jul_logging_set_log_level_rule(
-                       jul_logging, log_level_rule);
+       status = lttng_event_rule_jul_logging_set_log_level_rule(jul_logging, log_level_rule);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "setting log level rule.");
-       status = lttng_event_rule_jul_logging_get_log_level_rule(
-                       jul_logging, &log_level_rule_return);
+       status = lttng_event_rule_jul_logging_get_log_level_rule(jul_logging,
+                                                                &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "get log level rule.");
 
        ok(lttng_event_rule_serialize(jul_logging, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                               &view, &jul_logging_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &jul_logging_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_event_rule_is_equal(jul_logging, jul_logging_from_buffer), "serialized and from buffer are equal.");
+       ok(lttng_event_rule_is_equal(jul_logging, jul_logging_from_buffer),
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(jul_logging);
@@ -316,17 +313,16 @@ void test_event_rule_jul_logging(void)
        lttng_log_level_rule_destroy(log_level_rule);
 }
 
-static
-void test_event_rule_log4j_logging(void)
+static void test_event_rule_log4j_logging()
 {
-       struct lttng_event_rule *log4j_logging = NULL;
-       struct lttng_event_rule *log4j_logging_from_buffer = NULL;
+       struct lttng_event_rule *log4j_logging = nullptr;
+       struct lttng_event_rule *log4j_logging_from_buffer = nullptr;
        enum lttng_event_rule_status status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *tmp;
-       struct lttng_log_level_rule *log_level_rule = NULL;
-       const struct lttng_log_level_rule *log_level_rule_return = NULL;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
+       const struct lttng_log_level_rule *log_level_rule_return = nullptr;
        struct lttng_payload payload;
 
        diag("Testing lttng_event_rule_user_log4j_logging.");
@@ -351,29 +347,27 @@ void test_event_rule_log4j_logging(void)
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "getting filter.");
        ok(!strncmp(filter, tmp, strlen(filter)), "filter is equal.");
 
-       status = lttng_event_rule_log4j_logging_get_log_level_rule(log4j_logging, &log_level_rule_return);
+       status = lttng_event_rule_log4j_logging_get_log_level_rule(log4j_logging,
+                                                                  &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_UNSET, "get unset log level rule.");
 
-       status = lttng_event_rule_log4j_logging_set_log_level_rule(
-                       log4j_logging, log_level_rule);
+       status = lttng_event_rule_log4j_logging_set_log_level_rule(log4j_logging, log_level_rule);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "setting log level rule.");
-       status = lttng_event_rule_log4j_logging_get_log_level_rule(
-                       log4j_logging, &log_level_rule_return);
+       status = lttng_event_rule_log4j_logging_get_log_level_rule(log4j_logging,
+                                                                  &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "get log level rule.");
 
        ok(lttng_event_rule_serialize(log4j_logging, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                               &view, &log4j_logging_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &log4j_logging_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_event_rule_is_equal(log4j_logging, log4j_logging_from_buffer), "serialized and from buffer are equal.");
+       ok(lttng_event_rule_is_equal(log4j_logging, log4j_logging_from_buffer),
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(log4j_logging);
@@ -381,17 +375,16 @@ void test_event_rule_log4j_logging(void)
        lttng_log_level_rule_destroy(log_level_rule);
 }
 
-static
-void test_event_rule_python_logging(void)
+static void test_event_rule_python_logging()
 {
-       struct lttng_event_rule *python_logging = NULL;
-       struct lttng_event_rule *python_logging_from_buffer = NULL;
+       struct lttng_event_rule *python_logging = nullptr;
+       struct lttng_event_rule *python_logging_from_buffer = nullptr;
        enum lttng_event_rule_status status;
-       const char *pattern="my_event_*";
-       const char *filter="msg_id == 23 && size >= 2048";
+       const char *pattern = "my_event_*";
+       const char *filter = "msg_id == 23 && size >= 2048";
        const char *tmp;
-       struct lttng_log_level_rule *log_level_rule = NULL;
-       const struct lttng_log_level_rule *log_level_rule_return = NULL;
+       struct lttng_log_level_rule *log_level_rule = nullptr;
+       const struct lttng_log_level_rule *log_level_rule_return = nullptr;
        struct lttng_payload payload;
 
        diag("Testing lttng_event_rule_user_python_logging.");
@@ -416,29 +409,27 @@ void test_event_rule_python_logging(void)
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "getting filter.");
        ok(!strncmp(filter, tmp, strlen(filter)), "filter is equal.");
 
-       status = lttng_event_rule_python_logging_get_log_level_rule(python_logging, &log_level_rule_return);
+       status = lttng_event_rule_python_logging_get_log_level_rule(python_logging,
+                                                                   &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_UNSET, "get unset log level rule.");
 
-       status = lttng_event_rule_python_logging_set_log_level_rule(
-                       python_logging, log_level_rule);
+       status = lttng_event_rule_python_logging_set_log_level_rule(python_logging, log_level_rule);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "setting log level rule.");
-       status = lttng_event_rule_python_logging_get_log_level_rule(
-                       python_logging, &log_level_rule_return);
+       status = lttng_event_rule_python_logging_get_log_level_rule(python_logging,
+                                                                   &log_level_rule_return);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "get log level rule.");
 
        ok(lttng_event_rule_serialize(python_logging, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                               &view, &python_logging_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &python_logging_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_event_rule_is_equal(python_logging, python_logging_from_buffer), "serialized and from buffer are equal.");
+       ok(lttng_event_rule_is_equal(python_logging, python_logging_from_buffer),
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(python_logging);
@@ -446,14 +437,14 @@ void test_event_rule_python_logging(void)
        lttng_log_level_rule_destroy(log_level_rule);
 }
 
-static void test_event_rule_userspace_probe(void)
+#ifdef __linux__
+static void test_event_rule_userspace_probe()
 {
-       struct lttng_event_rule *uprobe = NULL;
-       struct lttng_event_rule *uprobe_from_buffer = NULL;
-       struct lttng_userspace_probe_location_lookup_method *lookup_method =
-                       NULL;
-       struct lttng_userspace_probe_location *probe_location = NULL;
-       const struct lttng_userspace_probe_location *probe_location_tmp = NULL;
+       struct lttng_event_rule *uprobe = nullptr;
+       struct lttng_event_rule *uprobe_from_buffer = nullptr;
+       struct lttng_userspace_probe_location_lookup_method *lookup_method = nullptr;
+       struct lttng_userspace_probe_location *probe_location = nullptr;
+       const struct lttng_userspace_probe_location *probe_location_tmp = nullptr;
        enum lttng_event_rule_status status;
 
        const char *probe_name = "my_probe.";
@@ -470,33 +461,29 @@ static void test_event_rule_userspace_probe(void)
        }
 
        probe_location = lttng_userspace_probe_location_function_create(
-                       "/proc/self/exe",
-                       "lttng_userspace_probe_location_tracepoint_create",
-                       lookup_method);
+               "/proc/self/exe",
+               "lttng_userspace_probe_location_tracepoint_create",
+               lookup_method);
        if (!probe_location) {
                fail("Setup error on userspace probe location creation.");
                goto end;
        }
 
        /* Ownership transferred to the probe location function object. */
-       lookup_method = NULL;
+       lookup_method = nullptr;
 
        lttng_payload_init(&payload);
 
        uprobe = lttng_event_rule_kernel_uprobe_create(probe_location);
        ok(uprobe, "uprobe event rule object creation.");
 
-       status = lttng_event_rule_kernel_uprobe_get_location(
-                       uprobe, &probe_location_tmp);
-       ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Getting uprobe event rule location.");
-       ok(lttng_userspace_probe_location_is_equal(
-                          probe_location, probe_location_tmp),
-                       "Location is equal.");
+       status = lttng_event_rule_kernel_uprobe_get_location(uprobe, &probe_location_tmp);
+       ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Getting uprobe event rule location.");
+       ok(lttng_userspace_probe_location_is_equal(probe_location, probe_location_tmp),
+          "Location is equal.");
 
        status = lttng_event_rule_kernel_uprobe_set_event_name(uprobe, probe_name);
-       ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting uprobe event rule name: %s.", probe_name);
+       ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Setting uprobe event rule name: %s.", probe_name);
        status = lttng_event_rule_kernel_uprobe_get_event_name(uprobe, &tmp);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Getting uprobe name.");
        ok(!strcmp(probe_name, tmp), "Uprobe name are equal.");
@@ -504,17 +491,14 @@ static void test_event_rule_userspace_probe(void)
        ok(lttng_event_rule_serialize(uprobe, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                                  &view, &uprobe_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &uprobe_from_buffer) > 0,
+                  "Deserializing.");
        }
 
        ok(lttng_event_rule_is_equal(uprobe, uprobe_from_buffer),
-                       "serialized and from buffer are equal.");
+          "serialized and from buffer are equal.");
 
 end:
        lttng_payload_reset(&payload);
@@ -523,12 +507,17 @@ end:
        lttng_userspace_probe_location_destroy(probe_location);
        lttng_userspace_probe_location_lookup_method_destroy(lookup_method);
 }
+#else
+static void test_event_rule_userspace_probe(void)
+{
+}
+#endif
 
-static void test_event_rule_kernel_probe_by_location(
-               const struct lttng_kernel_probe_location *location)
+static void
+test_event_rule_kernel_probe_by_location(const struct lttng_kernel_probe_location *location)
 {
-       struct lttng_event_rule *kprobe = NULL;
-       struct lttng_event_rule *kprobe_from_buffer = NULL;
+       struct lttng_event_rule *kprobe = nullptr;
+       struct lttng_event_rule *kprobe_from_buffer = nullptr;
        enum lttng_event_rule_status status;
        const struct lttng_kernel_probe_location *_location;
 
@@ -537,7 +526,7 @@ static void test_event_rule_kernel_probe_by_location(
        struct lttng_payload payload;
 
        diag("Event rule kprobe for location type %d.",
-                       lttng_kernel_probe_location_get_type(location));
+            lttng_kernel_probe_location_get_type(location));
 
        lttng_payload_init(&payload);
 
@@ -545,13 +534,11 @@ static void test_event_rule_kernel_probe_by_location(
        ok(kprobe, "kprobe event rule object creation.");
 
        status = lttng_event_rule_kernel_kprobe_get_location(kprobe, &_location);
-       ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Getting kprobe event rule location.");
+       ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Getting kprobe event rule location.");
        ok(lttng_kernel_probe_location_is_equal(location, _location), "Locations are equal.");
 
        status = lttng_event_rule_kernel_kprobe_set_event_name(kprobe, probe_name);
-       ok(status == LTTNG_EVENT_RULE_STATUS_OK,
-                       "Setting kprobe event rule name: %s.", probe_name);
+       ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Setting kprobe event rule name: %s.", probe_name);
        status = lttng_event_rule_kernel_kprobe_get_event_name(kprobe, &tmp);
        ok(status == LTTNG_EVENT_RULE_STATUS_OK, "Getting kprobe name.");
        ok(!strcmp(probe_name, tmp), "kprobe name are equal.");
@@ -559,27 +546,24 @@ static void test_event_rule_kernel_probe_by_location(
        ok(lttng_event_rule_serialize(kprobe, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_event_rule_create_from_payload(
-                                  &view, &kprobe_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_event_rule_create_from_payload(&view, &kprobe_from_buffer) > 0,
+                  "Deserializing.");
        }
 
        ok(lttng_event_rule_is_equal(kprobe, kprobe_from_buffer),
-                       "serialized and from buffer are equal.");
+          "serialized and from buffer are equal.");
 
        lttng_payload_reset(&payload);
        lttng_event_rule_destroy(kprobe);
        lttng_event_rule_destroy(kprobe_from_buffer);
 }
 
-static void test_event_rule_kernel_probe(void)
+static void test_event_rule_kernel_probe()
 {
-       struct lttng_kernel_probe_location *address_location = NULL;
-       struct lttng_kernel_probe_location *symbol_location = NULL;
+       struct lttng_kernel_probe_location *address_location = nullptr;
+       struct lttng_kernel_probe_location *symbol_location = nullptr;
 
        address_location = lttng_kernel_probe_location_address_create(50);
        symbol_location = lttng_kernel_probe_location_symbol_create("une_bonne", 50);
@@ -593,48 +577,43 @@ static void test_event_rule_kernel_probe(void)
        lttng_kernel_probe_location_destroy(symbol_location);
 }
 
-static void test_set_event_rule_log_level_rules(
-               struct lttng_event_rule *event_rule,
-               event_rule_set_log_level set_log_level,
-               int log_level,
-               enum lttng_event_rule_status *exactly_status,
-               enum lttng_event_rule_status *as_severe_status)
+static void test_set_event_rule_log_level_rules(struct lttng_event_rule *event_rule,
+                                               event_rule_set_log_level set_log_level,
+                                               int log_level,
+                                               enum lttng_event_rule_status *exactly_status,
+                                               enum lttng_event_rule_status *as_severe_status)
 {
        struct lttng_log_level_rule *log_level_rule;
 
-       log_level_rule = lttng_log_level_rule_at_least_as_severe_as_create(
-                       log_level);
+       log_level_rule = lttng_log_level_rule_at_least_as_severe_as_create(log_level);
        LTTNG_ASSERT(log_level_rule);
 
-       *as_severe_status = set_log_level(
-                       event_rule, log_level_rule);
+       *as_severe_status = set_log_level(event_rule, log_level_rule);
        lttng_log_level_rule_destroy(log_level_rule);
 
        log_level_rule = lttng_log_level_rule_exactly_create(log_level);
        LTTNG_ASSERT(log_level_rule);
 
-       *exactly_status = set_log_level(
-                       event_rule, log_level_rule);
+       *exactly_status = set_log_level(event_rule, log_level_rule);
        lttng_log_level_rule_destroy(log_level_rule);
 }
 
 static void test_event_rule_log_level_generic(enum lttng_event_rule_type event_rule_type,
-               log_level_name_getter get_log_level_name,
-               event_rule_create create_event_rule,
-               event_rule_set_log_level set_log_level,
-               const int tagged_log_level_values[],
-               size_t tagged_log_level_values_count,
-               const int valid_log_level_values[],
-               size_t valid_log_level_values_count,
-               const int invalid_log_level_values[],
-               size_t invalid_log_level_values_count)
+                                             log_level_name_getter get_log_level_name,
+                                             event_rule_create create_event_rule,
+                                             event_rule_set_log_level set_log_level,
+                                             const int tagged_log_level_values[],
+                                             size_t tagged_log_level_values_count,
+                                             const int valid_log_level_values[],
+                                             size_t valid_log_level_values_count,
+                                             const int invalid_log_level_values[],
+                                             size_t invalid_log_level_values_count)
 {
        size_t i;
        struct lttng_event_rule *rule;
        enum lttng_event_rule_status er_exactly_status, er_as_severe_status;
        const char *event_rule_type_str = lttng_event_rule_type_str(event_rule_type);
 
-
        diag("Test %s event rule + log level rule", event_rule_type_str);
 
        rule = create_event_rule();
@@ -643,73 +622,70 @@ static void test_event_rule_log_level_generic(enum lttng_event_rule_type event_r
        for (i = 0; i < tagged_log_level_values_count; i++) {
                const int tagged_log_level_value = tagged_log_level_values[i];
 
-               test_set_event_rule_log_level_rules(rule, set_log_level,
-                               tagged_log_level_value,
-                               &er_exactly_status, &er_as_severe_status);
+               test_set_event_rule_log_level_rules(rule,
+                                                   set_log_level,
+                                                   tagged_log_level_value,
+                                                   &er_exactly_status,
+                                                   &er_as_severe_status);
                ok(er_exactly_status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Log level rule \"exactly\" accepted by %s event rule: level = %s",
-                               event_rule_type_str,
-                               get_log_level_name(
-                                               tagged_log_level_value));
+                  "Log level rule \"exactly\" accepted by %s event rule: level = %s",
+                  event_rule_type_str,
+                  get_log_level_name(tagged_log_level_value));
                ok(er_as_severe_status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Log level rule \"as least as severe as\" accepted by %s event rule: level = %s",
-                               event_rule_type_str,
-                               get_log_level_name(
-                                               tagged_log_level_value));
+                  "Log level rule \"as least as severe as\" accepted by %s event rule: level = %s",
+                  event_rule_type_str,
+                  get_log_level_name(tagged_log_level_value));
        }
 
        for (i = 0; i < valid_log_level_values_count; i++) {
                const int valid_log_level_value = valid_log_level_values[i];
 
-               test_set_event_rule_log_level_rules(rule, set_log_level,
-                               valid_log_level_value,
-                               &er_exactly_status, &er_as_severe_status);
+               test_set_event_rule_log_level_rules(rule,
+                                                   set_log_level,
+                                                   valid_log_level_value,
+                                                   &er_exactly_status,
+                                                   &er_as_severe_status);
                ok(er_exactly_status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Log level rule \"exactly\" accepted by %s event rule: level = %d",
-                               event_rule_type_str,
-                               valid_log_level_value);
+                  "Log level rule \"exactly\" accepted by %s event rule: level = %d",
+                  event_rule_type_str,
+                  valid_log_level_value);
                ok(er_as_severe_status == LTTNG_EVENT_RULE_STATUS_OK,
-                               "Log level rule \"as least as severe as\" accepted by %s event rule: level = %d",
-                               event_rule_type_str,
-                               valid_log_level_value);
+                  "Log level rule \"as least as severe as\" accepted by %s event rule: level = %d",
+                  event_rule_type_str,
+                  valid_log_level_value);
        }
 
        for (i = 0; i < invalid_log_level_values_count; i++) {
                const int invalid_log_level_value = invalid_log_level_values[i];
 
-               test_set_event_rule_log_level_rules(rule, set_log_level,
-                               invalid_log_level_value,
-                               &er_exactly_status, &er_as_severe_status);
+               test_set_event_rule_log_level_rules(rule,
+                                                   set_log_level,
+                                                   invalid_log_level_value,
+                                                   &er_exactly_status,
+                                                   &er_as_severe_status);
                ok(er_exactly_status == LTTNG_EVENT_RULE_STATUS_INVALID,
-                               "Log level rule \"exactly\" rejected by %s event rule: level = %d",
-                               event_rule_type_str,
-                               invalid_log_level_value);
+                  "Log level rule \"exactly\" rejected by %s event rule: level = %d",
+                  event_rule_type_str,
+                  invalid_log_level_value);
                ok(er_as_severe_status == LTTNG_EVENT_RULE_STATUS_INVALID,
-                               "Log level rule \"as least as severe as\" rejected by %s event rule: level = %d",
-                               event_rule_type_str,
-                               invalid_log_level_value);
+                  "Log level rule \"as least as severe as\" rejected by %s event rule: level = %d",
+                  event_rule_type_str,
+                  invalid_log_level_value);
        }
 
        lttng_event_rule_destroy(rule);
 }
 
-static void test_event_rule_log_level_ust(void)
+static void test_event_rule_log_level_ust()
 {
        const int tagged_log_level_values[] = {
-               LTTNG_LOGLEVEL_EMERG,
-               LTTNG_LOGLEVEL_ALERT,
-               LTTNG_LOGLEVEL_CRIT,
-               LTTNG_LOGLEVEL_ERR,
-               LTTNG_LOGLEVEL_WARNING,
-               LTTNG_LOGLEVEL_NOTICE,
-               LTTNG_LOGLEVEL_INFO,
-               LTTNG_LOGLEVEL_DEBUG_SYSTEM,
-               LTTNG_LOGLEVEL_DEBUG_PROGRAM,
-               LTTNG_LOGLEVEL_DEBUG_PROCESS,
-               LTTNG_LOGLEVEL_DEBUG_MODULE,
-               LTTNG_LOGLEVEL_DEBUG_UNIT,
-               LTTNG_LOGLEVEL_DEBUG_FUNCTION,
-               LTTNG_LOGLEVEL_DEBUG_LINE,
+               LTTNG_LOGLEVEL_EMERG,          LTTNG_LOGLEVEL_ALERT,
+               LTTNG_LOGLEVEL_CRIT,           LTTNG_LOGLEVEL_ERR,
+               LTTNG_LOGLEVEL_WARNING,        LTTNG_LOGLEVEL_NOTICE,
+               LTTNG_LOGLEVEL_INFO,           LTTNG_LOGLEVEL_DEBUG_SYSTEM,
+               LTTNG_LOGLEVEL_DEBUG_PROGRAM,  LTTNG_LOGLEVEL_DEBUG_PROCESS,
+               LTTNG_LOGLEVEL_DEBUG_MODULE,   LTTNG_LOGLEVEL_DEBUG_UNIT,
+               LTTNG_LOGLEVEL_DEBUG_FUNCTION, LTTNG_LOGLEVEL_DEBUG_LINE,
                LTTNG_LOGLEVEL_DEBUG,
        };
        const int invalid_log_level_values[] = {
@@ -720,81 +696,65 @@ static void test_event_rule_log_level_ust(void)
        };
 
        test_event_rule_log_level_generic(LTTNG_EVENT_RULE_TYPE_USER_TRACEPOINT,
-                       loglevel_value_to_name,
-                       lttng_event_rule_user_tracepoint_create,
-                       lttng_event_rule_user_tracepoint_set_log_level_rule,
-                       tagged_log_level_values,
-                       ARRAY_SIZE(tagged_log_level_values), NULL, 0,
-                       invalid_log_level_values,
-                       ARRAY_SIZE(invalid_log_level_values));
+                                         loglevel_value_to_name,
+                                         lttng_event_rule_user_tracepoint_create,
+                                         lttng_event_rule_user_tracepoint_set_log_level_rule,
+                                         tagged_log_level_values,
+                                         ARRAY_SIZE(tagged_log_level_values),
+                                         nullptr,
+                                         0,
+                                         invalid_log_level_values,
+                                         ARRAY_SIZE(invalid_log_level_values));
 }
 
-static void test_event_rule_log_level_jul(void)
+static void test_event_rule_log_level_jul()
 {
        const int tagged_log_level_values[] = {
-               LTTNG_LOGLEVEL_JUL_OFF,
-               LTTNG_LOGLEVEL_JUL_SEVERE,
-               LTTNG_LOGLEVEL_JUL_WARNING,
-               LTTNG_LOGLEVEL_JUL_INFO,
-               LTTNG_LOGLEVEL_JUL_CONFIG,
-               LTTNG_LOGLEVEL_JUL_FINE,
-               LTTNG_LOGLEVEL_JUL_FINER,
-               LTTNG_LOGLEVEL_JUL_FINEST,
-               LTTNG_LOGLEVEL_JUL_ALL,
-       };
-       const int valid_log_level_values[] = {
-               0,
-               -1980,
-               1995
+               LTTNG_LOGLEVEL_JUL_OFF,   LTTNG_LOGLEVEL_JUL_SEVERE, LTTNG_LOGLEVEL_JUL_WARNING,
+               LTTNG_LOGLEVEL_JUL_INFO,  LTTNG_LOGLEVEL_JUL_CONFIG, LTTNG_LOGLEVEL_JUL_FINE,
+               LTTNG_LOGLEVEL_JUL_FINER, LTTNG_LOGLEVEL_JUL_FINEST, LTTNG_LOGLEVEL_JUL_ALL,
        };
+       const int valid_log_level_values[] = { 0, -1980, 1995 };
 
        test_event_rule_log_level_generic(LTTNG_EVENT_RULE_TYPE_JUL_LOGGING,
-                       loglevel_jul_value_to_name,
-                       lttng_event_rule_jul_logging_create,
-                       lttng_event_rule_jul_logging_set_log_level_rule,
-                       tagged_log_level_values,
-                       ARRAY_SIZE(tagged_log_level_values),
-                       valid_log_level_values,
-                       ARRAY_SIZE(valid_log_level_values), NULL, 0);
+                                         loglevel_jul_value_to_name,
+                                         lttng_event_rule_jul_logging_create,
+                                         lttng_event_rule_jul_logging_set_log_level_rule,
+                                         tagged_log_level_values,
+                                         ARRAY_SIZE(tagged_log_level_values),
+                                         valid_log_level_values,
+                                         ARRAY_SIZE(valid_log_level_values),
+                                         nullptr,
+                                         0);
 }
 
-static void test_event_rule_log_level_log4j(void)
+static void test_event_rule_log_level_log4j()
 {
        const int tagged_log_level_values[] = {
-               LTTNG_LOGLEVEL_LOG4J_OFF,
-               LTTNG_LOGLEVEL_LOG4J_FATAL,
-               LTTNG_LOGLEVEL_LOG4J_ERROR,
-               LTTNG_LOGLEVEL_LOG4J_WARN,
-               LTTNG_LOGLEVEL_LOG4J_INFO,
-               LTTNG_LOGLEVEL_LOG4J_DEBUG,
-               LTTNG_LOGLEVEL_LOG4J_TRACE,
-               LTTNG_LOGLEVEL_LOG4J_ALL,
-       };
-       const int valid_log_level_values[] = {
-               0
-               -1980,
-               1995
+               LTTNG_LOGLEVEL_LOG4J_OFF,   LTTNG_LOGLEVEL_LOG4J_FATAL, LTTNG_LOGLEVEL_LOG4J_ERROR,
+               LTTNG_LOGLEVEL_LOG4J_WARN,  LTTNG_LOGLEVEL_LOG4J_INFO,  LTTNG_LOGLEVEL_LOG4J_DEBUG,
+               LTTNG_LOGLEVEL_LOG4J_TRACE, LTTNG_LOGLEVEL_LOG4J_ALL,
        };
+       const int valid_log_level_values[] = { 0 - 1980, 1995 };
 
        test_event_rule_log_level_generic(LTTNG_EVENT_RULE_TYPE_LOG4J_LOGGING,
-                       loglevel_log4j_value_to_name,
-                       lttng_event_rule_log4j_logging_create,
-                       lttng_event_rule_log4j_logging_set_log_level_rule,
-                       tagged_log_level_values,
-                       ARRAY_SIZE(tagged_log_level_values),
-                       valid_log_level_values,
-                       ARRAY_SIZE(valid_log_level_values), NULL, 0);
+                                         loglevel_log4j_value_to_name,
+                                         lttng_event_rule_log4j_logging_create,
+                                         lttng_event_rule_log4j_logging_set_log_level_rule,
+                                         tagged_log_level_values,
+                                         ARRAY_SIZE(tagged_log_level_values),
+                                         valid_log_level_values,
+                                         ARRAY_SIZE(valid_log_level_values),
+                                         nullptr,
+                                         0);
 }
 
-static void test_event_rule_log_level_python(void)
+static void test_event_rule_log_level_python()
 {
        const int tagged_log_level_values[] = {
-               LTTNG_LOGLEVEL_PYTHON_CRITICAL,
-               LTTNG_LOGLEVEL_PYTHON_ERROR,
-               LTTNG_LOGLEVEL_PYTHON_WARNING,
-               LTTNG_LOGLEVEL_PYTHON_INFO,
-               LTTNG_LOGLEVEL_PYTHON_DEBUG,
-               LTTNG_LOGLEVEL_PYTHON_NOTSET,
+               LTTNG_LOGLEVEL_PYTHON_CRITICAL, LTTNG_LOGLEVEL_PYTHON_ERROR,
+               LTTNG_LOGLEVEL_PYTHON_WARNING,  LTTNG_LOGLEVEL_PYTHON_INFO,
+               LTTNG_LOGLEVEL_PYTHON_DEBUG,    LTTNG_LOGLEVEL_PYTHON_NOTSET,
        };
        const int valid_log_level_values[] = {
                45,
@@ -804,17 +764,18 @@ static void test_event_rule_log_level_python(void)
        };
 
        test_event_rule_log_level_generic(LTTNG_EVENT_RULE_TYPE_PYTHON_LOGGING,
-                       loglevel_python_value_to_name,
-                       lttng_event_rule_python_logging_create,
-                       lttng_event_rule_python_logging_set_log_level_rule,
-                       tagged_log_level_values,
-                       ARRAY_SIZE(tagged_log_level_values),
-                       valid_log_level_values,
-                       ARRAY_SIZE(valid_log_level_values),
-                       NULL, 0);
+                                         loglevel_python_value_to_name,
+                                         lttng_event_rule_python_logging_create,
+                                         lttng_event_rule_python_logging_set_log_level_rule,
+                                         tagged_log_level_values,
+                                         ARRAY_SIZE(tagged_log_level_values),
+                                         valid_log_level_values,
+                                         ARRAY_SIZE(valid_log_level_values),
+                                         nullptr,
+                                         0);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_event_rule_kernel_tracepoint();
index 63f3d0afa31921ab78a2b3086d3c1292e6bb97a5..cdc622a04e463e30dbdd6971bd3e6a03d55f39ab 100644 (file)
@@ -5,28 +5,26 @@
  *
  */
 
-#include <stdlib.h>
+#include <common/compat/directory-handle.hpp>
+#include <common/compat/errno.hpp>
+#include <common/error.hpp>
+#include <common/fd-tracker/fd-tracker.hpp>
+#include <common/fs-handle.hpp>
+
+#include <dirent.h>
+#include <fcntl.h>
 #include <inttypes.h>
-#include <stdbool.h>
-#include <string.h>
 #include <stdarg.h>
-#include <tap/tap.h>
-#include <sys/types.h>
-#include <dirent.h>
+#include <stdbool.h>
 #include <stdio.h>
-#include <unistd.h>
-#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-
+#include <tap/tap.h>
+#include <unistd.h>
 #include <urcu.h>
 
-#include <common/compat/directory-handle.hpp>
-#include <common/compat/errno.hpp>
-#include <common/error.hpp>
-#include <common/fs-handle.hpp>
-#include <common/fd-tracker/fd-tracker.hpp>
-
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
@@ -35,9 +33,9 @@ int lttng_opt_mi;
 /* Number of TAP tests in this file */
 #define NUM_TESTS 61
 /* 3 for stdin, stdout, and stderr */
-#define STDIO_FD_COUNT 3
-#define TRACKER_FD_LIMIT 50
-#define TMP_DIR_PATTERN "/tmp/fd-tracker-XXXXXX"
+#define STDIO_FD_COUNT            3
+#define TRACKER_FD_LIMIT          50
+#define TMP_DIR_PATTERN                   "/tmp/fd-tracker-XXXXXX"
 #define TEST_UNLINK_DIRECTORY_NAME "unlinked_files"
 
 #ifdef __linux__
@@ -56,13 +54,12 @@ int lttng_opt_mi;
 int unknown_fds_count;
 
 const char file_contents[] = "Bacon ipsum dolor amet jerky drumstick sirloin "
-       "strip steak venison boudin filet mignon picanha doner shoulder. "
-       "Strip steak brisket alcatra, venison beef chuck cupim pastrami. "
-       "Landjaeger tri-tip salami leberkas ball tip, ham hock chuck sausage "
-       "flank jerky cupim. Pig bacon chuck pancetta andouille.";
+                            "strip steak venison boudin filet mignon picanha doner shoulder. "
+                            "Strip steak brisket alcatra, venison beef chuck cupim pastrami. "
+                            "Landjaeger tri-tip salami leberkas ball tip, ham hock chuck sausage "
+                            "flank jerky cupim. Pig bacon chuck pancetta andouille.";
 
-static
-void get_temporary_directories(char **_test_directory, char **_unlink_directory)
+static void get_temporary_directories(char **_test_directory, char **_unlink_directory)
 {
        int ret;
        char tmp_path_pattern[] = TMP_DIR_PATTERN;
@@ -70,22 +67,19 @@ void get_temporary_directories(char **_test_directory, char **_unlink_directory)
 
        output_dir = mkdtemp(tmp_path_pattern);
        if (!output_dir) {
-               diag("Failed to create temporary path of the form %s",
-                               TMP_DIR_PATTERN);
+               diag("Failed to create temporary path of the form %s", TMP_DIR_PATTERN);
                abort();
        }
 
        *_test_directory = strdup(output_dir);
        LTTNG_ASSERT(*_test_directory);
-       ret = asprintf(_unlink_directory, "%s/%s", output_dir,
-                       TEST_UNLINK_DIRECTORY_NAME);
+       ret = asprintf(_unlink_directory, "%s/%s", output_dir, TEST_UNLINK_DIRECTORY_NAME);
        if (ret < 0) {
                abort();
        }
 }
 
-static
-int fd_count(void)
+static int fd_count()
 {
        DIR *dir;
        struct dirent *entry;
@@ -93,12 +87,13 @@ int fd_count(void)
 
        dir = opendir(SELF_FD_DIR);
        if (!dir) {
-               perror("# Failed to enumerate " SELF_FD_DIR " to count the number of used file descriptors");
+               perror("# Failed to enumerate " SELF_FD_DIR
+                      " to count the number of used file descriptors");
                count = -1;
                goto end;
        }
 
-       while ((entry = readdir(dir)) != NULL) {
+       while ((entry = readdir(dir)) != nullptr) {
                if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
                        continue;
                }
@@ -107,41 +102,42 @@ int fd_count(void)
        /* Don't account for the file descriptor opened by opendir(). */
        count--;
        if (closedir(dir)) {
-               perror("# Failed to close test program's " SELF_FD_DIR " directory file descriptor");
+               perror("# Failed to close test program's " SELF_FD_DIR
+                      " directory file descriptor");
        }
 end:
        return count;
 }
 
-static
-void check_fd_count(int expected_count)
+static void check_fd_count(int expected_count)
 {
        int count = 0;
 
        count = fd_count();
-       ok(count == expected_count, "Expected %d open file descriptors (%d are open)",
-                       expected_count, count);
+       ok(count == expected_count,
+          "Expected %d open file descriptors (%d are open)",
+          expected_count,
+          count);
 }
 
-static
-int noop_open(void *data, int *fds)
+static int noop_open(void *data, int *fds)
 {
        *fds = *((int *) data);
        return 0;
 }
 
-static
-int noop_close(void *data __attribute__((unused)),
-               int *fds __attribute__((unused)))
+static int noop_close(void *data __attribute__((unused)), int *fds __attribute__((unused)))
 {
        return 0;
 }
 
-static
-void track_std_fds(struct fd_tracker *tracker)
+static void track_std_fds(struct fd_tracker *tracker)
 {
        int i;
-       struct { int fd; const char *name; } files[] = {
+       struct {
+               int fd;
+               const char *name;
+       } files[] = {
                { .fd = fileno(stdin), .name = "stdin" },
                { .fd = fileno(stdout), .name = "stdout" },
                { .fd = fileno(stderr), .name = "stderr" },
@@ -150,20 +146,21 @@ void track_std_fds(struct fd_tracker *tracker)
        for (i = 0; i < sizeof(files) / sizeof(*files); i++) {
                int out_fd, ret;
 
-               ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                               &files[i].name, 1, noop_open, &files[i].fd);
+               ret = fd_tracker_open_unsuspendable_fd(
+                       tracker, &out_fd, &files[i].name, 1, noop_open, &files[i].fd);
                LTTNG_ASSERT(out_fd == files[i].fd);
 
-               ok(ret == 0, "Track unsuspendable fd %d (%s)", files[i].fd,
-                               files[i].name);
+               ok(ret == 0, "Track unsuspendable fd %d (%s)", files[i].fd, files[i].name);
        }
 }
 
-static
-void untrack_std_fds(struct fd_tracker *tracker)
+static void untrack_std_fds(struct fd_tracker *tracker)
 {
        int i;
-       struct { int fd; const char *name; } files[] = {
+       struct {
+               int fd;
+               const char *name;
+       } files[] = {
                { .fd = fileno(stdin), .name = "stdin" },
                { .fd = fileno(stdout), .name = "stdout" },
                { .fd = fileno(stderr), .name = "stderr" },
@@ -171,29 +168,28 @@ void untrack_std_fds(struct fd_tracker *tracker)
 
        for (i = 0; i < sizeof(files) / sizeof(*files); i++) {
                int fd = files[i].fd;
-               int ret = fd_tracker_close_unsuspendable_fd(tracker,
-                               &files[i].fd, 1, noop_close, NULL);
+               int ret = fd_tracker_close_unsuspendable_fd(
+                       tracker, &files[i].fd, 1, noop_close, nullptr);
 
-               ok(ret == 0, "Untrack unsuspendable fd %d (%s)", fd,
-                               files[i].name);
+               ok(ret == 0, "Untrack unsuspendable fd %d (%s)", fd, files[i].name);
        }
 }
 
 /*
- * Basic test opening and closing three unsuspendable fds. 
+ * Basic test opening and closing three unsuspendable fds.
  */
-static
-void test_unsuspendable_basic(void)
+static void test_unsuspendable_basic()
 {
        int ret;
        struct fd_tracker *tracker;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
 
        tracker = fd_tracker_create(unlinked_files_directory, TRACKER_FD_LIMIT);
-       ok(tracker, "Created an fd tracker with a limit of %d simulateously opened file descriptors",
-                       TRACKER_FD_LIMIT);
+       ok(tracker,
+          "Created an fd tracker with a limit of %d simulateously opened file descriptors",
+          TRACKER_FD_LIMIT);
        if (!tracker) {
                goto end;
        }
@@ -209,14 +205,12 @@ end:
        free(unlinked_files_directory);
 }
 
-static
-int error_open(void *data, int *fds __attribute__((unused)))
+static int error_open(void *data, int *fds __attribute__((unused)))
 {
        return *((int *) data);
 }
 
-static
-int error_close(void *data, int *fds __attribute__((unused)))
+static int error_close(void *data, int *fds __attribute__((unused)))
 {
        return *((int *) data);
 }
@@ -225,13 +219,12 @@ int error_close(void *data, int *fds __attribute__((unused)))
  * Validate that user callback return values are returned to the
  * caller of the fd tracker.
  */
-static
-void test_unsuspendable_cb_return(void)
+static void test_unsuspendable_cb_return()
 {
        int ret, stdout_fd = fileno(stdout), out_fd = 42;
        struct fd_tracker *tracker;
        int expected_error = -ENETDOWN;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
 
@@ -239,25 +232,28 @@ void test_unsuspendable_cb_return(void)
        LTTNG_ASSERT(tracker);
 
        /* The error_open callback should fail and return 'expected_error'. */
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, error_open, &expected_error);
-       ok(ret == expected_error, "fd_tracker_open_unsuspendable_fd() forwards the user callback's error code");
-       ok(out_fd == 42, "Output fd parameter is unaffected on error of fd_tracker_open_unsuspendable_fd()");
+       ret = fd_tracker_open_unsuspendable_fd(
+               tracker, &out_fd, nullptr, 1, error_open, &expected_error);
+       ok(ret == expected_error,
+          "fd_tracker_open_unsuspendable_fd() forwards the user callback's error code");
+       ok(out_fd == 42,
+          "Output fd parameter is unaffected on error of fd_tracker_open_unsuspendable_fd()");
 
        /*
         * Track a valid fd since we don't want the tracker to fail with an
         * invalid fd error for this test.
         */
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, noop_open, &stdout_fd);
-       ok(out_fd == stdout_fd, "fd_tracker_open_unsuspendable_fd() sets the output fd parameter to the newly-tracked fd's value");
+       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd, nullptr, 1, noop_open, &stdout_fd);
+       ok(out_fd == stdout_fd,
+          "fd_tracker_open_unsuspendable_fd() sets the output fd parameter to the newly-tracked fd's value");
        LTTNG_ASSERT(!ret);
 
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       &stdout_fd, 1, error_close, &expected_error);
-       ok(ret == expected_error, "fd_tracker_close_unsuspendable_fd() forwards the user callback's error code");
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       &stdout_fd, 1, noop_close, &expected_error);
+       ret = fd_tracker_close_unsuspendable_fd(
+               tracker, &stdout_fd, 1, error_close, &expected_error);
+       ok(ret == expected_error,
+          "fd_tracker_close_unsuspendable_fd() forwards the user callback's error code");
+       ret = fd_tracker_close_unsuspendable_fd(
+               tracker, &stdout_fd, 1, noop_close, &expected_error);
        LTTNG_ASSERT(!ret);
 
        fd_tracker_destroy(tracker);
@@ -271,27 +267,23 @@ void test_unsuspendable_cb_return(void)
  * Validate that the tracker refuses to track two identical unsuspendable
  * file descriptors.
  */
-static
-void test_unsuspendable_duplicate(void)
+static void test_unsuspendable_duplicate()
 {
        int ret, stdout_fd = fileno(stdout), out_fd;
        struct fd_tracker *tracker;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
 
        tracker = fd_tracker_create(unlinked_files_directory, TRACKER_FD_LIMIT);
        LTTNG_ASSERT(tracker);
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, noop_open, &stdout_fd);
+       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd, nullptr, 1, noop_open, &stdout_fd);
        LTTNG_ASSERT(!ret);
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, noop_open, &stdout_fd);
+       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd, nullptr, 1, noop_open, &stdout_fd);
        ok(ret == -EEXIST, "EEXIST reported on open of an already tracked file descriptor");
 
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       &stdout_fd, 1, noop_close, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(tracker, &stdout_fd, 1, noop_close, nullptr);
        LTTNG_ASSERT(!ret);
 
        fd_tracker_destroy(tracker);
@@ -301,8 +293,7 @@ void test_unsuspendable_duplicate(void)
        free(unlinked_files_directory);
 }
 
-static
-int open_pipes(void *data __attribute__((unused)), int *out_fds)
+static int open_pipes(void *data __attribute__((unused)), int *out_fds)
 {
        unsigned int i;
        const unsigned int pipe_count = TRACKER_FD_LIMIT / 2;
@@ -317,8 +308,7 @@ int open_pipes(void *data __attribute__((unused)), int *out_fds)
        return 0;
 }
 
-static
-int close_pipes(void *data __attribute__((unused)), int *fds)
+static int close_pipes(void *data __attribute__((unused)), int *fds)
 {
        int i;
        int *pipes = fds;
@@ -337,13 +327,12 @@ int close_pipes(void *data __attribute__((unused)), int *fds)
  * Validate that the tracker enforces the open file descriptor limit
  * when unsuspendable file descriptors are being opened.
  */
-static
-void test_unsuspendable_limit(void)
+static void test_unsuspendable_limit()
 {
        struct fd_tracker *tracker;
        int ret, stdout_fd = fileno(stdout), out_fd;
        int fds[TRACKER_FD_LIMIT];
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
 
@@ -353,17 +342,18 @@ void test_unsuspendable_limit(void)
        tracker = fd_tracker_create(unlinked_files_directory, TRACKER_FD_LIMIT);
        LTTNG_ASSERT(tracker);
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, fds,
-                       NULL, TRACKER_FD_LIMIT, open_pipes, NULL);
-       ok(ret == 0, "File descriptor tracker allowed the user to meet its limit with unsuspendable file descriptors (%d)",
-                       TRACKER_FD_LIMIT);
+       ret = fd_tracker_open_unsuspendable_fd(
+               tracker, fds, nullptr, TRACKER_FD_LIMIT, open_pipes, nullptr);
+       ok(ret == 0,
+          "File descriptor tracker allowed the user to meet its limit with unsuspendable file descriptors (%d)",
+          TRACKER_FD_LIMIT);
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, noop_open, &stdout_fd);
-       ok(ret == -EMFILE, "EMFILE reported when exceeding the file descriptor limit while opening an unsuspendable fd");
+       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd, nullptr, 1, noop_open, &stdout_fd);
+       ok(ret == -EMFILE,
+          "EMFILE reported when exceeding the file descriptor limit while opening an unsuspendable fd");
 
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       fds, TRACKER_FD_LIMIT, close_pipes, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(
+               tracker, fds, TRACKER_FD_LIMIT, close_pipes, nullptr);
        LTTNG_ASSERT(!ret);
 
        fd_tracker_destroy(tracker);
@@ -377,18 +367,18 @@ void test_unsuspendable_limit(void)
  * Validate that the tracker refuses to track two identical unsuspendable
  * file descriptors.
  */
-static
-void test_unsuspendable_close_untracked(void)
+static void test_unsuspendable_close_untracked()
 {
        int ret, stdout_fd = fileno(stdout), unknown_fds[2], out_fd;
        struct fd_tracker *tracker;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
 
        tracker = fd_tracker_create(unlinked_files_directory, TRACKER_FD_LIMIT);
        if (!tracker) {
-               goto end;;
+               goto end;
+               ;
        }
 
        ret = pipe(unknown_fds);
@@ -398,16 +388,13 @@ void test_unsuspendable_close_untracked(void)
        ret = close(unknown_fds[1]);
        LTTNG_ASSERT(ret == 0);
 
-       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd,
-                       NULL, 1, noop_open, &stdout_fd);
+       ret = fd_tracker_open_unsuspendable_fd(tracker, &out_fd, nullptr, 1, noop_open, &stdout_fd);
        LTTNG_ASSERT(!ret);
 
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       unknown_fds, 1, noop_close, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(tracker, unknown_fds, 1, noop_close, nullptr);
        ok(ret == -EINVAL, "EINVAL reported on close of an untracked file descriptor");
 
-       ret = fd_tracker_close_unsuspendable_fd(tracker,
-                       &stdout_fd, 1, noop_close, NULL);
+       ret = fd_tracker_close_unsuspendable_fd(tracker, &stdout_fd, 1, noop_close, nullptr);
        LTTNG_ASSERT(!ret);
 
        fd_tracker_destroy(tracker);
@@ -419,10 +406,10 @@ end:
 }
 
 static int open_files(struct fd_tracker *tracker,
-               struct lttng_directory_handle *directory,
-               unsigned int count,
-               struct fs_handle **handles,
-               char **file_paths)
+                     struct lttng_directory_handle *directory,
+                     unsigned int count,
+                     struct fs_handle **handles,
+                     char **file_paths)
 {
        int ret = 0;
        unsigned int i;
@@ -437,8 +424,8 @@ static int open_files(struct fd_tracker *tracker,
                LTTNG_ASSERT(p_ret >= 0);
                file_paths[i] = file_path;
 
-               handle = fd_tracker_open_fs_handle(tracker, directory, file_path,
-                               O_RDWR | O_CREAT, &mode);
+               handle = fd_tracker_open_fs_handle(
+                       tracker, directory, file_path, O_RDWR | O_CREAT, &mode);
                if (!handle) {
                        ret = -1;
                        break;
@@ -449,10 +436,10 @@ static int open_files(struct fd_tracker *tracker,
 }
 
 static int open_same_file(struct fd_tracker *tracker,
-               struct lttng_directory_handle *directory,
-               const char *file,
-               unsigned int count,
-               struct fs_handle **handles)
+                         struct lttng_directory_handle *directory,
+                         const char *file,
+                         unsigned int count,
+                         struct fs_handle **handles)
 {
        int ret = 0;
        unsigned int i;
@@ -461,8 +448,8 @@ static int open_same_file(struct fd_tracker *tracker,
                struct fs_handle *handle;
                mode_t mode = S_IWUSR | S_IRUSR;
 
-               handle = fd_tracker_open_fs_handle(tracker, directory, file,
-                               O_RDWR | O_CREAT, &mode);
+               handle = fd_tracker_open_fs_handle(
+                       tracker, directory, file, O_RDWR | O_CREAT, &mode);
                if (!handle) {
                        ret = -1;
                        break;
@@ -472,11 +459,11 @@ static int open_same_file(struct fd_tracker *tracker,
        return ret;
 }
 
-static
-int cleanup_files(struct fd_tracker *tracker __attribute__((unused)),
-               const char *dir __attribute__((unused)),
-               unsigned int count, struct fs_handle **handles,
-               char **file_paths)
+static int cleanup_files(struct fd_tracker *tracker __attribute__((unused)),
+                        const char *dir __attribute__((unused)),
+                        unsigned int count,
+                        struct fs_handle **handles,
+                        char **file_paths)
 {
        int ret = 0;
        unsigned int i;
@@ -500,16 +487,15 @@ int cleanup_files(struct fd_tracker *tracker __attribute__((unused)),
        return ret;
 }
 
-static
-void test_suspendable_limit(void)
+static void test_suspendable_limit()
 {
        int ret;
        const int files_to_create = TRACKER_FD_LIMIT * 10;
        struct fd_tracker *tracker;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
        char *output_files[files_to_create];
        struct fs_handle *handles[files_to_create];
-       struct lttng_directory_handle *dir_handle = NULL;
+       struct lttng_directory_handle *dir_handle = nullptr;
        int dir_handle_fd_count;
 
        memset(output_files, 0, sizeof(output_files));
@@ -526,15 +512,14 @@ void test_suspendable_limit(void)
        LTTNG_ASSERT(dir_handle);
        dir_handle_fd_count = !!lttng_directory_handle_uses_fd(dir_handle);
 
-       ret = open_files(tracker, dir_handle, files_to_create, handles,
-                       output_files);
-       ok(!ret, "Created %d files with a limit of %d simultaneously-opened file descriptor",
-                       files_to_create, TRACKER_FD_LIMIT);
-       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count +
-                       dir_handle_fd_count);
+       ret = open_files(tracker, dir_handle, files_to_create, handles, output_files);
+       ok(!ret,
+          "Created %d files with a limit of %d simultaneously-opened file descriptor",
+          files_to_create,
+          TRACKER_FD_LIMIT);
+       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count + dir_handle_fd_count);
 
-       ret = cleanup_files(tracker, test_directory, files_to_create, handles,
-                       output_files);
+       ret = cleanup_files(tracker, test_directory, files_to_create, handles, output_files);
        ok(!ret, "Close all opened filesystem handles");
        ret = rmdir(test_directory);
        ok(ret == 0, "Test directory is empty");
@@ -545,16 +530,15 @@ end:
        free(unlinked_files_directory);
 }
 
-static
-void test_mixed_limit(void)
+static void test_mixed_limit()
 {
        int ret;
        const int files_to_create = TRACKER_FD_LIMIT;
        struct fd_tracker *tracker;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
        char *output_files[files_to_create];
        struct fs_handle *handles[files_to_create];
-       struct lttng_directory_handle *dir_handle = NULL;
+       struct lttng_directory_handle *dir_handle = nullptr;
        int dir_handle_fd_count;
 
        memset(output_files, 0, sizeof(output_files));
@@ -571,30 +555,26 @@ void test_mixed_limit(void)
        LTTNG_ASSERT(dir_handle);
        dir_handle_fd_count = !!lttng_directory_handle_uses_fd(dir_handle);
 
-       ret = open_files(tracker, dir_handle, files_to_create, handles,
-                       output_files);
-       ok(!ret, "Created %d files with a limit of %d simultaneously-opened file descriptor",
-                       files_to_create, TRACKER_FD_LIMIT);
+       ret = open_files(tracker, dir_handle, files_to_create, handles, output_files);
+       ok(!ret,
+          "Created %d files with a limit of %d simultaneously-opened file descriptor",
+          files_to_create,
+          TRACKER_FD_LIMIT);
        diag("Check file descriptor count after opening %u files", files_to_create);
-       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count +
-                       dir_handle_fd_count);
+       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count + dir_handle_fd_count);
 
        /*
         * Open unsuspendable fds (stdin, stdout, stderr) and verify that the fd
         * cap is still respected.
         */
-       diag("Check file descriptor count after adding %d unsuspendable fds",
-                       STDIO_FD_COUNT);
+       diag("Check file descriptor count after adding %d unsuspendable fds", STDIO_FD_COUNT);
        track_std_fds(tracker);
-       check_fd_count(TRACKER_FD_LIMIT + unknown_fds_count +
-                       dir_handle_fd_count);
+       check_fd_count(TRACKER_FD_LIMIT + unknown_fds_count + dir_handle_fd_count);
        diag("Untrack unsuspendable file descriptors");
        untrack_std_fds(tracker);
-       check_fd_count(TRACKER_FD_LIMIT + unknown_fds_count +
-                       dir_handle_fd_count);
+       check_fd_count(TRACKER_FD_LIMIT + unknown_fds_count + dir_handle_fd_count);
 
-       ret = cleanup_files(tracker, test_directory, files_to_create, handles,
-                       output_files);
+       ret = cleanup_files(tracker, test_directory, files_to_create, handles, output_files);
        ok(!ret, "Close all opened filesystem handles");
        ret = rmdir(test_directory);
        ok(ret == 0, "Test directory is empty");
@@ -613,8 +593,7 @@ end:
  *
  * The content of the files is also verified at the end.
  */
-static
-void test_suspendable_restore(void)
+static void test_suspendable_restore()
 {
        int ret;
        const int files_to_create = TRACKER_FD_LIMIT * 10;
@@ -626,9 +605,9 @@ void test_suspendable_restore(void)
        bool write_success = true;
        bool fd_cap_respected = true;
        bool content_ok = true;
-       struct lttng_directory_handle *dir_handle = NULL;
+       struct lttng_directory_handle *dir_handle = nullptr;
        int dir_handle_fd_count;
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
 
        memset(output_files, 0, sizeof(output_files));
        memset(handles, 0, sizeof(handles));
@@ -644,13 +623,13 @@ void test_suspendable_restore(void)
        LTTNG_ASSERT(dir_handle);
        dir_handle_fd_count = !!lttng_directory_handle_uses_fd(dir_handle);
 
-       ret = open_files(tracker, dir_handle, files_to_create, handles,
-                       output_files);
-       ok(!ret, "Created %d files with a limit of %d simultaneously-opened file descriptor",
-                       files_to_create, TRACKER_FD_LIMIT);
+       ret = open_files(tracker, dir_handle, files_to_create, handles, output_files);
+       ok(!ret,
+          "Created %d files with a limit of %d simultaneously-opened file descriptor",
+          files_to_create,
+          TRACKER_FD_LIMIT);
        diag("Check file descriptor count after opening %u files", files_to_create);
-       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count +
-                       dir_handle_fd_count);
+       check_fd_count(TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count + dir_handle_fd_count);
 
        for (content_index = 0; content_index < sizeof(file_contents); content_index++) {
                for (handle_index = 0; handle_index < files_to_create; handle_index++) {
@@ -661,8 +640,7 @@ void test_suspendable_restore(void)
                        fd = fs_handle_get_fd(handle);
                        if (fd < 0) {
                                write_success = false;
-                               diag("Failed to restore fs_handle to %s",
-                                               path);
+                               diag("Failed to restore fs_handle to %s", path);
                                goto skip_write;
                        }
 
@@ -676,9 +654,8 @@ void test_suspendable_restore(void)
                                goto skip_write;
                        }
 
-                       if (fd_count() > (TRACKER_FD_LIMIT + STDIO_FD_COUNT +
-                                                       unknown_fds_count +
-                                                       dir_handle_fd_count)) {
+                       if (fd_count() > (TRACKER_FD_LIMIT + STDIO_FD_COUNT + unknown_fds_count +
+                                         dir_handle_fd_count)) {
                                fd_cap_respected = false;
                        }
 
@@ -686,8 +663,7 @@ void test_suspendable_restore(void)
                }
        }
 skip_write:
-       ok(write_success, "Wrote reference string to %d files",
-                       files_to_create);
+       ok(write_success, "Wrote reference string to %d files", files_to_create);
        ok(fd_cap_respected, "FD tracker enforced the file descriptor cap");
 
        /* Validate the contents of the files. */
@@ -699,15 +675,15 @@ skip_write:
                size_t to_read = sizeof(read_buf);
                int fd;
 
-               fd = lttng_directory_handle_open_file(
-                               dir_handle, path, O_RDONLY, 0);
+               fd = lttng_directory_handle_open_file(dir_handle, path, O_RDONLY, 0);
                LTTNG_ASSERT(fd >= 0);
                ret = fstat(fd, &fd_stat);
                LTTNG_ASSERT(!ret);
                if (fd_stat.st_size != sizeof(file_contents)) {
                        diag("Content size of file %s doesn't match, got %" PRId64 ", expected %zu",
-                                       path, (int64_t) fd_stat.st_size,
-                                       sizeof(file_contents));
+                            path,
+                            (int64_t) fd_stat.st_size,
+                            sizeof(file_contents));
                        content_ok = false;
                        (void) close(fd);
                        break;
@@ -728,7 +704,7 @@ skip_write:
                        break;
                }
 
-               if (strcmp(file_contents, read_buf)) {
+               if (strcmp(file_contents, read_buf) != 0) {
                        content_ok = false;
                        diag("File content doesn't match the expectated string");
                        (void) close(fd);
@@ -737,8 +713,7 @@ skip_write:
                (void) close(fd);
        }
        ok(content_ok, "Files contain the expected content");
-       ret = cleanup_files(tracker, test_directory, files_to_create, handles,
-                       output_files);
+       ret = cleanup_files(tracker, test_directory, files_to_create, handles, output_files);
        ok(!ret, "Close all opened filesystem handles");
        ret = rmdir(test_directory);
        ok(ret == 0, "Test directory is empty");
@@ -749,27 +724,24 @@ end:
        free(unlinked_files_directory);
 }
 
-static
-void test_unlink(void)
+static void test_unlink()
 {
        int ret;
        struct fd_tracker *tracker;
        const int handles_to_open = 2;
        struct fs_handle *handles[handles_to_open];
-       struct fs_handle *new_handle = NULL;
+       struct fs_handle *new_handle = nullptr;
        struct stat statbuf;
-       struct lttng_directory_handle *dir_handle = NULL;
+       struct lttng_directory_handle *dir_handle = nullptr;
        const char file_name[] = "my_file";
-       char *test_directory = NULL, *unlinked_files_directory = NULL;
-       char *unlinked_file_zero = NULL, *unlinked_file_one = NULL;
+       char *test_directory = nullptr, *unlinked_files_directory = nullptr;
+       char *unlinked_file_zero = nullptr, *unlinked_file_one = nullptr;
        int fd;
 
        get_temporary_directories(&test_directory, &unlinked_files_directory);
-       ret = asprintf(&unlinked_file_zero, "%s/%u", unlinked_files_directory,
-                       0);
+       ret = asprintf(&unlinked_file_zero, "%s/%u", unlinked_files_directory, 0);
        LTTNG_ASSERT(ret > 0);
-       ret = asprintf(&unlinked_file_one, "%s/%u", unlinked_files_directory,
-                       1);
+       ret = asprintf(&unlinked_file_one, "%s/%u", unlinked_files_directory, 1);
        LTTNG_ASSERT(ret > 0);
 
        tracker = fd_tracker_create(unlinked_files_directory, 1);
@@ -781,10 +753,12 @@ void test_unlink(void)
        LTTNG_ASSERT(dir_handle);
 
        /* Open two handles to the same file. */
-       ret = open_same_file(tracker, dir_handle, file_name, handles_to_open,
-                       handles);
-       ok(!ret, "Successfully opened %i handles to %s/%s", handles_to_open,
-                       test_directory, file_name);
+       ret = open_same_file(tracker, dir_handle, file_name, handles_to_open, handles);
+       ok(!ret,
+          "Successfully opened %i handles to %s/%s",
+          handles_to_open,
+          test_directory,
+          file_name);
        if (ret) {
                goto end;
        }
@@ -794,21 +768,18 @@ void test_unlink(void)
         * to '0'.
         */
        ret = fs_handle_unlink(handles[0]);
-       ok(!ret, "Successfully unlinked the first handle to %s/%s",
-                       test_directory, file_name);
+       ok(!ret, "Successfully unlinked the first handle to %s/%s", test_directory, file_name);
 
        /*
         * The original file should no longer exist on the file system, and a
         * new file named '0' should exist.
         */
-       ok(lttng_directory_handle_stat(dir_handle, file_name, &statbuf) == -1 &&
-                                       errno == ENOENT,
-                       "%s no longer present on file system after unlink",
-                       file_name);
-       ok(lttng_directory_handle_stat(
-                       dir_handle, unlinked_file_zero, &statbuf) == 0,
-                       "%s exists on file system after unlink",
-                       unlinked_file_zero);
+       ok(lttng_directory_handle_stat(dir_handle, file_name, &statbuf) == -1 && errno == ENOENT,
+          "%s no longer present on file system after unlink",
+          file_name);
+       ok(lttng_directory_handle_stat(dir_handle, unlinked_file_zero, &statbuf) == 0,
+          "%s exists on file system after unlink",
+          unlinked_file_zero);
 
        /*
         * It should be possible to use the file descriptors of both handles.
@@ -819,7 +790,7 @@ void test_unlink(void)
        ok(fd >= 0, "Got fd from first handle");
 
        fd = fs_handle_get_fd(handles[1]);
-       ok (fd < 0, "fd tracker does not allow two fds to be used at once");
+       ok(fd < 0, "fd tracker does not allow two fds to be used at once");
 
        fs_handle_put_fd(handles[0]);
        fd = fs_handle_get_fd(handles[1]);
@@ -829,15 +800,18 @@ void test_unlink(void)
        /* The second unlink should fail with -ENOENT. */
        ret = fs_handle_unlink(handles[1]);
        ok(ret == -ENOENT,
-                       "ENOENT is reported when attempting to unlink the second handle to %s/%s",
-                       test_directory, file_name);
+          "ENOENT is reported when attempting to unlink the second handle to %s/%s",
+          test_directory,
+          file_name);
 
        /*
         * Opening a new handle to 'my_file' should succeed.
         */
        ret = open_same_file(tracker, dir_handle, file_name, 1, &new_handle);
-       ok(!ret, "Successfully opened a new handle to previously unlinked file %s/%s",
-                       test_directory, file_name);
+       ok(!ret,
+          "Successfully opened a new handle to previously unlinked file %s/%s",
+          test_directory,
+          file_name);
        LTTNG_ASSERT(new_handle);
 
        /*
@@ -845,11 +819,10 @@ void test_unlink(void)
         * to '1' since '0' already exists.
         */
        ret = fs_handle_unlink(new_handle);
-       ok(!ret, "Successfully unlinked the new handle handle to %s/%s",
-                       test_directory, file_name);
+       ok(!ret, "Successfully unlinked the new handle handle to %s/%s", test_directory, file_name);
        ok(stat(unlinked_file_one, &statbuf) == 0,
-                       "%s exists on file system after unlink",
-                       unlinked_file_one);
+          "%s exists on file system after unlink",
+          unlinked_file_one);
 
        ret = fs_handle_close(handles[0]);
        ok(!ret, "Successfully closed the first handle");
@@ -858,20 +831,17 @@ void test_unlink(void)
        ret = fs_handle_close(new_handle);
        ok(!ret, "Successfully closed the third handle");
 
-       ok(lttng_directory_handle_stat(dir_handle, file_name, &statbuf) == -1 &&
-                                       errno == ENOENT,
-                       "%s no longer present on file system after handle close",
-                       file_name);
-       ok(lttng_directory_handle_stat(
-                       dir_handle, unlinked_file_zero, &statbuf) == -1 &&
-                                       errno == ENOENT,
-                       "%s no longer present on file system after handle close",
-                       unlinked_file_zero);
-       ok(lttng_directory_handle_stat(dir_handle, unlinked_file_one,
-                       &statbuf) == -1 &&
-                                       errno == ENOENT,
-                       "%s no longer present on file system after handle close",
-                       unlinked_file_one);
+       ok(lttng_directory_handle_stat(dir_handle, file_name, &statbuf) == -1 && errno == ENOENT,
+          "%s no longer present on file system after handle close",
+          file_name);
+       ok(lttng_directory_handle_stat(dir_handle, unlinked_file_zero, &statbuf) == -1 &&
+                  errno == ENOENT,
+          "%s no longer present on file system after handle close",
+          unlinked_file_zero);
+       ok(lttng_directory_handle_stat(dir_handle, unlinked_file_one, &statbuf) == -1 &&
+                  errno == ENOENT,
+          "%s no longer present on file system after handle close",
+          unlinked_file_one);
 
        ret = rmdir(test_directory);
        ok(ret == 0, "Test directory is empty");
@@ -884,7 +854,7 @@ end:
        lttng_directory_handle_put(dir_handle);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        diag("File descriptor tracker unit tests");
index eae335be205026b0abd549cf166cf342d32b40aa..2deaef72057050e4ea903f4e0c27864e4f78a892 100644 (file)
@@ -5,19 +5,18 @@
  *
  */
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <time.h>
-
 #include <common/compat/errno.hpp>
-#include <bin/lttng-sessiond/trace-kernel.hpp>
 #include <common/defaults.hpp>
 
+#include <bin/lttng-sessiond/trace-kernel.hpp>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <tap/tap.h>
+#include <time.h>
+#include <unistd.h>
 
-#define RANDOM_STRING_LEN      11
+#define RANDOM_STRING_LEN 11
 
 /* Number of TAP tests in this file */
 #define NUM_TESTS 11
 LTTNG_EXPORT DEFINE_LTTNG_UST_SIGBUS_STATE();
 #endif
 
-static const char alphanum[] =
-       "0123456789"
-       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-       "abcdefghijklmnopqrstuvwxyz";
+static const char alphanum[] = "0123456789"
+                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                              "abcdefghijklmnopqrstuvwxyz";
 
 static struct ltt_kernel_session *kern;
 static char random_string[RANDOM_STRING_LEN];
@@ -40,7 +38,7 @@ static char random_string[RANDOM_STRING_LEN];
  * Return random string of 10 characters.
  * Not thread-safe.
  */
-static char *get_random_string(void)
+static char *get_random_string()
 {
        int i;
 
@@ -53,51 +51,42 @@ static char *get_random_string(void)
        return random_string;
 }
 
-static void test_create_one_kernel_session(void)
+static void test_create_one_kernel_session()
 {
        kern = trace_kernel_create_session();
-       ok(kern != NULL, "Create kernel session");
+       ok(kern != nullptr, "Create kernel session");
 
        if (!kern) {
                skip(1, "Kernel session is null");
                return;
        }
-       ok(kern->fd == -1 &&
-          kern->metadata_stream_fd == -1 &&
-          kern->consumer_fds_sent == 0 &&
-          kern->channel_count == 0 &&
-          kern->stream_count_global == 0 &&
-          kern->metadata == NULL,
+       ok(kern->fd == -1 && kern->metadata_stream_fd == -1 && kern->consumer_fds_sent == 0 &&
+                  kern->channel_count == 0 && kern->stream_count_global == 0 &&
+                  kern->metadata == nullptr,
           "Validate kernel session");
 }
 
-static void test_create_kernel_metadata(void)
+static void test_create_kernel_metadata()
 {
-       LTTNG_ASSERT(kern != NULL);
+       LTTNG_ASSERT(kern != nullptr);
 
        kern->metadata = trace_kernel_create_metadata();
-       ok(kern->metadata != NULL, "Create kernel metadata");
-
-       ok(kern->metadata->fd == -1 &&
-          kern->metadata->conf != NULL &&
-          kern->metadata->conf->attr.overwrite
-                       == DEFAULT_METADATA_OVERWRITE &&
-          kern->metadata->conf->attr.subbuf_size
-                       == default_get_metadata_subbuf_size() &&
-          kern->metadata->conf->attr.num_subbuf
-                       == DEFAULT_METADATA_SUBBUF_NUM &&
-          kern->metadata->conf->attr.switch_timer_interval
-                       == DEFAULT_METADATA_SWITCH_TIMER &&
-          kern->metadata->conf->attr.read_timer_interval
-                       == DEFAULT_METADATA_READ_TIMER &&
-          kern->metadata->conf->attr.output
-                       == LTTNG_EVENT_MMAP,
+       ok(kern->metadata != nullptr, "Create kernel metadata");
+
+       ok(kern->metadata->fd == -1 && kern->metadata->conf != nullptr &&
+                  kern->metadata->conf->attr.overwrite == DEFAULT_METADATA_OVERWRITE &&
+                  kern->metadata->conf->attr.subbuf_size == default_get_metadata_subbuf_size() &&
+                  kern->metadata->conf->attr.num_subbuf == DEFAULT_METADATA_SUBBUF_NUM &&
+                  kern->metadata->conf->attr.switch_timer_interval ==
+                          DEFAULT_METADATA_SWITCH_TIMER &&
+                  kern->metadata->conf->attr.read_timer_interval == DEFAULT_METADATA_READ_TIMER &&
+                  kern->metadata->conf->attr.output == LTTNG_EVENT_MMAP,
           "Validate kernel session metadata");
 
        trace_kernel_destroy_metadata(kern->metadata);
 }
 
-static void test_create_kernel_channel(void)
+static void test_create_kernel_channel()
 {
        struct ltt_kernel_channel *chan;
        struct lttng_channel attr;
@@ -108,17 +97,15 @@ static void test_create_kernel_channel(void)
        attr.attr.extended.ptr = &extended;
 
        chan = trace_kernel_create_channel(&attr);
-       ok(chan != NULL, "Create kernel channel");
+       ok(chan != nullptr, "Create kernel channel");
 
        if (!chan) {
                skip(1, "Channel is null");
                return;
        }
 
-       ok(chan->fd == -1 &&
-          chan->enabled == 1 &&
-          chan->stream_count == 0 &&
-          chan->channel->attr.overwrite  == attr.attr.overwrite,
+       ok(chan->fd == -1 && chan->enabled && chan->stream_count == 0 &&
+                  chan->channel->attr.overwrite == attr.attr.overwrite,
           "Validate kernel channel");
 
        /* Init list in order to avoid sefaults from cds_list_del */
@@ -126,20 +113,19 @@ static void test_create_kernel_channel(void)
        trace_kernel_destroy_channel(chan);
 }
 
-static void test_create_kernel_event(void)
+static void test_create_kernel_event()
 {
        enum lttng_error_code ret;
        struct ltt_kernel_event *event;
        struct lttng_event ev;
 
        memset(&ev, 0, sizeof(ev));
-       ok(!lttng_strncpy(ev.name, get_random_string(),
-                       RANDOM_STRING_LEN),
-               "Validate string length");
+       ok(!lttng_strncpy(ev.name, get_random_string(), RANDOM_STRING_LEN),
+          "Validate string length");
        ev.type = LTTNG_EVENT_TRACEPOINT;
        ev.loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
 
-       ret = trace_kernel_create_event(&ev, NULL, NULL, &event);
+       ret = trace_kernel_create_event(&ev, nullptr, nullptr, &event);
        ok(ret == LTTNG_OK, "Create kernel event");
 
        if (!event) {
@@ -147,10 +133,9 @@ static void test_create_kernel_event(void)
                return;
        }
 
-       ok(event->fd == -1 &&
-          event->enabled == 1 &&
-          event->event->instrumentation == LTTNG_KERNEL_ABI_TRACEPOINT &&
-          strlen(event->event->name),
+       ok(event->fd == -1 && event->enabled &&
+                  event->event->instrumentation == LTTNG_KERNEL_ABI_TRACEPOINT &&
+                  strlen(event->event->name),
           "Validate kernel event");
 
        /* Init list in order to avoid sefaults from cds_list_del */
@@ -158,28 +143,26 @@ static void test_create_kernel_event(void)
        trace_kernel_destroy_event(event);
 }
 
-static void test_create_kernel_stream(void)
+static void test_create_kernel_stream()
 {
        struct ltt_kernel_stream *stream;
 
        stream = trace_kernel_create_stream("stream1", 0);
-       ok(stream != NULL, "Create kernel stream");
+       ok(stream != nullptr, "Create kernel stream");
 
        if (!stream) {
                skip(1, "Stream is null");
                return;
        }
 
-       ok(stream->fd == -1 &&
-          stream->state == 0,
-          "Validate kernel stream");
+       ok(stream->fd == -1 && stream->state == 0, "Validate kernel stream");
 
        /* Init list in order to avoid sefaults from cds_list_del */
        CDS_INIT_LIST_HEAD(&stream->list);
        trace_kernel_destroy_stream(stream);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
 
index 1ec6945d4aae72de31fb67a4f4cf9d609991d0e0..bec28825b2c5b3c700c3f7fc68d54ffbbd90a78e 100644 (file)
@@ -7,18 +7,18 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
-
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/kernel-probe-internal.hpp>
 #include <lttng/kernel-probe.h>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
+
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
@@ -26,10 +26,10 @@ int lttng_opt_mi;
 
 #define NUM_TESTS 24
 
-static void test_kernel_probe_location_address(void)
+static void test_kernel_probe_location_address()
 {
-       struct lttng_kernel_probe_location *location = NULL;
-       struct lttng_kernel_probe_location *location_from_buffer = NULL;
+       struct lttng_kernel_probe_location *location = nullptr;
+       struct lttng_kernel_probe_location *location_from_buffer = nullptr;
        enum lttng_kernel_probe_location_status status;
        enum lttng_kernel_probe_location_type type;
        uint64_t address = 50, _address;
@@ -44,52 +44,50 @@ static void test_kernel_probe_location_address(void)
 
        type = lttng_kernel_probe_location_get_type(location);
        ok(LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS == type,
-                       "Location type got %d expected %d", type,
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
+          "Location type got %d expected %d",
+          type,
+          LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
 
-       status = lttng_kernel_probe_location_address_get_address(
-                       location, &_address);
+       status = lttng_kernel_probe_location_address_get_address(location, &_address);
        ok(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK, "Getting address");
        ok(address == _address,
-                       "Address is equal. Got %" PRIu64 " expected %" PRIu64,
-                       _address, address);
+          "Address is equal. Got %" PRIu64 " expected %" PRIu64,
+          _address,
+          address);
 
-       ok(lttng_kernel_probe_location_serialize(location, &payload) > 0,
-                       "Serializing");
+       ok(lttng_kernel_probe_location_serialize(location, &payload) > 0, "Serializing");
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               ok(lttng_kernel_probe_location_create_from_payload(
-                                  &view, &location_from_buffer) > 0,
-                               "Deserializing");
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               ok(lttng_kernel_probe_location_create_from_payload(&view, &location_from_buffer) >
+                          0,
+                  "Deserializing");
        }
 
        type = lttng_kernel_probe_location_get_type(location_from_buffer);
        ok(LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS == type,
-                       "Location from buffer type got %d expected %d", type,
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
+          "Location from buffer type got %d expected %d",
+          type,
+          LTTNG_KERNEL_PROBE_LOCATION_TYPE_ADDRESS);
 
-       status = lttng_kernel_probe_location_address_get_address(
-                       location_from_buffer, &_address);
+       status = lttng_kernel_probe_location_address_get_address(location_from_buffer, &_address);
        ok(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK, "Getting address");
        ok(address == _address,
-                       "Address from buffer is equal. Got %" PRIu64
-                       " expected %" PRIu64,
-                       _address, address);
+          "Address from buffer is equal. Got %" PRIu64 " expected %" PRIu64,
+          _address,
+          address);
 
        ok(lttng_kernel_probe_location_is_equal(location, location_from_buffer),
-                       "serialized and from buffer are equal");
+          "serialized and from buffer are equal");
 
        lttng_payload_reset(&payload);
        lttng_kernel_probe_location_destroy(location);
        lttng_kernel_probe_location_destroy(location_from_buffer);
 }
 
-static void test_kernel_probe_location_symbol(void)
+static void test_kernel_probe_location_symbol()
 {
-       struct lttng_kernel_probe_location *location = NULL;
-       struct lttng_kernel_probe_location *location_from_buffer = NULL;
+       struct lttng_kernel_probe_location *location = nullptr;
+       struct lttng_kernel_probe_location *location_from_buffer = nullptr;
        enum lttng_kernel_probe_location_status status;
        enum lttng_kernel_probe_location_type type;
        uint64_t offset = 50, _offset;
@@ -105,61 +103,55 @@ static void test_kernel_probe_location_symbol(void)
 
        type = lttng_kernel_probe_location_get_type(location);
        ok(LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET == type,
-                       "Location type got %d expected %d", type,
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
+          "Location type got %d expected %d",
+          type,
+          LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
 
        _symbol = lttng_kernel_probe_location_symbol_get_name(location);
        ok(_symbol, "Getting symbol name");
        ok(!strncmp(symbol, _symbol, strlen(symbol)),
-                       "Symbol name is equal. Got %s, expected %s", _symbol,
-                       symbol);
+          "Symbol name is equal. Got %s, expected %s",
+          _symbol,
+          symbol);
 
-       status = lttng_kernel_probe_location_symbol_get_offset(
-                       location, &_offset);
+       status = lttng_kernel_probe_location_symbol_get_offset(location, &_offset);
        ok(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK, "Getting offset");
-       ok(offset == _offset,
-                       "Offset is equal. Got %" PRIu64 " expected %" PRIu64,
-                       _offset, offset);
+       ok(offset == _offset, "Offset is equal. Got %" PRIu64 " expected %" PRIu64, _offset, offset);
 
-       ok(lttng_kernel_probe_location_serialize(location, &payload) > 0,
-                       "Serializing");
+       ok(lttng_kernel_probe_location_serialize(location, &payload) > 0, "Serializing");
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-               ok(lttng_kernel_probe_location_create_from_payload(
-                                  &view, &location_from_buffer) > 0,
-                               "Deserializing");
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+               ok(lttng_kernel_probe_location_create_from_payload(&view, &location_from_buffer) >
+                          0,
+                  "Deserializing");
        }
 
        type = lttng_kernel_probe_location_get_type(location_from_buffer);
        ok(LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET == type,
-                       "Location from buffer type got %d expected %d", type,
-                       LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
+          "Location from buffer type got %d expected %d",
+          type,
+          LTTNG_KERNEL_PROBE_LOCATION_TYPE_SYMBOL_OFFSET);
 
-       _symbol = lttng_kernel_probe_location_symbol_get_name(
-                       location_from_buffer);
+       _symbol = lttng_kernel_probe_location_symbol_get_name(location_from_buffer);
        ok(_symbol, "Getting symbol name");
        ok(!strncmp(symbol, _symbol, strlen(symbol)),
-                       "Symbol name is equal. Got %s, expected %s", _symbol,
-                       symbol);
+          "Symbol name is equal. Got %s, expected %s",
+          _symbol,
+          symbol);
 
-       status = lttng_kernel_probe_location_symbol_get_offset(
-                       location_from_buffer, &_offset);
+       status = lttng_kernel_probe_location_symbol_get_offset(location_from_buffer, &_offset);
        ok(status == LTTNG_KERNEL_PROBE_LOCATION_STATUS_OK, "Getting offset");
-       ok(offset == _offset,
-                       "Offset is equal. Got %" PRIu64 " expected %" PRIu64,
-                       _offset, offset);
+       ok(offset == _offset, "Offset is equal. Got %" PRIu64 " expected %" PRIu64, _offset, offset);
 
        ok(lttng_kernel_probe_location_is_equal(location, location_from_buffer),
-                       "serialized and from buffer are equal");
+          "serialized and from buffer are equal");
 
        lttng_payload_reset(&payload);
        lttng_kernel_probe_location_destroy(location);
        lttng_kernel_probe_location_destroy(location_from_buffer);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_kernel_probe_location_address();
index be60e82c78ed0f989ebeef87e114ffe0f741e3fb..209253267b176dadb29d1de1eac78485bdb7912a 100644 (file)
@@ -7,18 +7,18 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
-
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/log-level-rule-internal.hpp>
 #include <lttng/log-level-rule.h>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
+
 /* For error.h. */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
@@ -26,33 +26,43 @@ int lttng_opt_mi;
 
 #define NUM_TESTS 29
 
-static void test_log_level_rule_error(void)
+static void test_log_level_rule_error()
 {
        int level = 9000;
-       struct lttng_log_level_rule *exactly =
-                       lttng_log_level_rule_exactly_create(level);
+       struct lttng_log_level_rule *exactly = lttng_log_level_rule_exactly_create(level);
        struct lttng_log_level_rule *at_least_as_severe =
-                       lttng_log_level_rule_at_least_as_severe_as_create(
-                                       level);
-
-       ok(lttng_log_level_rule_get_type(NULL) == LTTNG_LOG_LEVEL_RULE_TYPE_UNKNOWN, "Get type on invalid pointer");
-
-       ok(lttng_log_level_rule_exactly_get_level(NULL, NULL) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_exactly_get_level (NULL, NULL) returns invalid");
-       ok(lttng_log_level_rule_exactly_get_level(exactly, NULL) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_exactly_get_level (valid, NULL) returns invalid");
-       ok(lttng_log_level_rule_exactly_get_level(NULL, &level) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_exactly_get_level (NULL, valid) returns invalid");
-
-       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(NULL, NULL) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_at_least_as_severe_as_get_level (NULL, NULL) returns invalid");
-       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(exactly, NULL) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_at_least_as_severe_as_get_level (valid, NULL) returns invalid");
-       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(NULL, &level) == LTTNG_LOG_LEVEL_RULE_STATUS_INVALID, "lttng_log_level_rule_at_least_as_severe_as_get_level (NULL, valid) returns invalid");
+               lttng_log_level_rule_at_least_as_severe_as_create(level);
+
+       ok(lttng_log_level_rule_get_type(nullptr) == LTTNG_LOG_LEVEL_RULE_TYPE_UNKNOWN,
+          "Get type on invalid pointer");
+
+       ok(lttng_log_level_rule_exactly_get_level(nullptr, nullptr) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_exactly_get_level (NULL, NULL) returns invalid");
+       ok(lttng_log_level_rule_exactly_get_level(exactly, nullptr) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_exactly_get_level (valid, NULL) returns invalid");
+       ok(lttng_log_level_rule_exactly_get_level(nullptr, &level) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_exactly_get_level (NULL, valid) returns invalid");
+
+       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(nullptr, nullptr) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_at_least_as_severe_as_get_level (NULL, NULL) returns invalid");
+       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(exactly, nullptr) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_at_least_as_severe_as_get_level (valid, NULL) returns invalid");
+       ok(lttng_log_level_rule_at_least_as_severe_as_get_level(nullptr, &level) ==
+                  LTTNG_LOG_LEVEL_RULE_STATUS_INVALID,
+          "lttng_log_level_rule_at_least_as_severe_as_get_level (NULL, valid) returns invalid");
 
        lttng_log_level_rule_destroy(exactly);
        lttng_log_level_rule_destroy(at_least_as_severe);
 }
 
-static
-void test_log_level_rule_serialize_deserialize(const struct lttng_log_level_rule *rule)
+static void test_log_level_rule_serialize_deserialize(const struct lttng_log_level_rule *rule)
 {
-       struct lttng_log_level_rule *log_level_rule_from_buffer = NULL;
+       struct lttng_log_level_rule *log_level_rule_from_buffer = nullptr;
        struct lttng_payload payload;
 
        lttng_payload_init(&payload);
@@ -60,23 +70,20 @@ void test_log_level_rule_serialize_deserialize(const struct lttng_log_level_rule
        ok(lttng_log_level_rule_serialize(rule, &payload) == 0, "Serializing.");
 
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
-               ok(lttng_log_level_rule_create_from_payload(
-                               &view, &log_level_rule_from_buffer) > 0,
-                               "Deserializing.");
+               ok(lttng_log_level_rule_create_from_payload(&view, &log_level_rule_from_buffer) > 0,
+                  "Deserializing.");
        }
 
-       ok(lttng_log_level_rule_is_equal(rule, log_level_rule_from_buffer), "Serialized and from buffer are equal");
+       ok(lttng_log_level_rule_is_equal(rule, log_level_rule_from_buffer),
+          "Serialized and from buffer are equal");
 
        lttng_log_level_rule_destroy(log_level_rule_from_buffer);
        lttng_payload_reset(&payload);
 }
 
-static
-void test_log_level_rule_is_equal_exactly(void)
+static void test_log_level_rule_is_equal_exactly()
 {
        int level = 9000, no_eq_level = 420;
        struct lttng_log_level_rule *a, *b, *different_level, *different_type;
@@ -95,8 +102,10 @@ void test_log_level_rule_is_equal_exactly(void)
 
        ok(lttng_log_level_rule_is_equal(a, a), "Same object is equal");
        ok(lttng_log_level_rule_is_equal(a, b), "Object a and b are equal");
-       ok(!lttng_log_level_rule_is_equal(a, different_level), " Object of different levels are not equal");
-       ok(!lttng_log_level_rule_is_equal(a, different_type), " Object of different types are not equal");
+       ok(!lttng_log_level_rule_is_equal(a, different_level),
+          " Object of different levels are not equal");
+       ok(!lttng_log_level_rule_is_equal(a, different_type),
+          " Object of different types are not equal");
 
        lttng_log_level_rule_destroy(a);
        lttng_log_level_rule_destroy(b);
@@ -104,8 +113,7 @@ void test_log_level_rule_is_equal_exactly(void)
        lttng_log_level_rule_destroy(different_type);
 }
 
-static
-void test_log_level_rule_is_equal_at_least_as_severe_as(void)
+static void test_log_level_rule_is_equal_at_least_as_severe_as()
 {
        int level = 9000, no_eq_level = 420;
        struct lttng_log_level_rule *a, *b, *different_level, *different_type;
@@ -124,8 +132,10 @@ void test_log_level_rule_is_equal_at_least_as_severe_as(void)
 
        ok(lttng_log_level_rule_is_equal(a, a), "Same object is equal");
        ok(lttng_log_level_rule_is_equal(a, b), "Object a and b are equal");
-       ok(!lttng_log_level_rule_is_equal(a, different_level), " Object of different levels are not equal");
-       ok(!lttng_log_level_rule_is_equal(a, different_type), " Object of different types are not equal");
+       ok(!lttng_log_level_rule_is_equal(a, different_level),
+          " Object of different levels are not equal");
+       ok(!lttng_log_level_rule_is_equal(a, different_type),
+          " Object of different types are not equal");
 
        lttng_log_level_rule_destroy(a);
        lttng_log_level_rule_destroy(b);
@@ -133,19 +143,18 @@ void test_log_level_rule_is_equal_at_least_as_severe_as(void)
        lttng_log_level_rule_destroy(different_type);
 }
 
-static void test_log_level_rule_exactly(void)
+static void test_log_level_rule_exactly()
 {
        int level = 9000;
        int _level;
-       struct lttng_log_level_rule *exactly = NULL;
+       struct lttng_log_level_rule *exactly = nullptr;
        enum lttng_log_level_rule_status status;
 
        exactly = lttng_log_level_rule_exactly_create(level);
 
        ok(exactly, "Log level exactly allocated");
-       ok(lttng_log_level_rule_get_type(exactly) ==
-                                       LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY,
-                       "Log level rule exactly type");
+       ok(lttng_log_level_rule_get_type(exactly) == LTTNG_LOG_LEVEL_RULE_TYPE_EXACTLY,
+          "Log level rule exactly type");
 
        status = lttng_log_level_rule_exactly_get_level(exactly, &_level);
        ok(status == LTTNG_LOG_LEVEL_RULE_STATUS_OK, "Get the level");
@@ -156,21 +165,22 @@ static void test_log_level_rule_exactly(void)
        lttng_log_level_rule_destroy(exactly);
 }
 
-static void test_log_level_rule_at_least_as_severe_as(void)
+static void test_log_level_rule_at_least_as_severe_as()
 {
        int level = 9000;
        int _level;
-       struct lttng_log_level_rule *at_least_as_severe_as = NULL;
+       struct lttng_log_level_rule *at_least_as_severe_as = nullptr;
        enum lttng_log_level_rule_status status;
 
        at_least_as_severe_as = lttng_log_level_rule_at_least_as_severe_as_create(level);
 
        ok(at_least_as_severe_as, "Log level at_least_as_severe_as allocated");
        ok(lttng_log_level_rule_get_type(at_least_as_severe_as) ==
-                                       LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS,
-                       "Log level rule at_least_as_severe_as type");
+                  LTTNG_LOG_LEVEL_RULE_TYPE_AT_LEAST_AS_SEVERE_AS,
+          "Log level rule at_least_as_severe_as type");
 
-       status = lttng_log_level_rule_at_least_as_severe_as_get_level(at_least_as_severe_as, &_level);
+       status = lttng_log_level_rule_at_least_as_severe_as_get_level(at_least_as_severe_as,
+                                                                     &_level);
        ok(status == LTTNG_LOG_LEVEL_RULE_STATUS_OK, "Get the level");
        ok(_level == level, "Level property is valid");
 
@@ -179,7 +189,7 @@ static void test_log_level_rule_at_least_as_severe_as(void)
        lttng_log_level_rule_destroy(at_least_as_severe_as);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_log_level_rule_exactly();
index e870cbef6dab355eab2e8f6151c642589b1bd8e3..5dfc83c1a58fa33f7de1b1d7a14e96252f2260b4 100644 (file)
@@ -9,12 +9,7 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
+#include <common/macros.hpp>
 
 #include <lttng/action/action.h>
 #include <lttng/action/notify.h>
 #include <lttng/notification/notification.h>
 #include <lttng/trigger/trigger.h>
 
-#include <common/macros.hpp>
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
 
 /* For error.h */
 int lttng_opt_quiet = 1;
@@ -33,12 +32,11 @@ int lttng_opt_mi;
 
 #define NUM_TESTS 180
 
-static void test_condition_buffer_usage(
-               struct lttng_condition *buffer_usage_condition)
+static void test_condition_buffer_usage(struct lttng_condition *buffer_usage_condition)
 {
        enum lttng_condition_status status = LTTNG_CONDITION_STATUS_OK;
-       const char *session_name = NULL;
-       const char *channel_name = NULL;
+       const char *session_name = nullptr;
+       const char *channel_name = nullptr;
        enum lttng_domain_type domain_type;
        /* Start at a non zero value to validate initialization */
        double threshold_ratio;
@@ -47,17 +45,21 @@ static void test_condition_buffer_usage(
        LTTNG_ASSERT(buffer_usage_condition);
 
        diag("Validating initialization");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold ratio is unset");
 
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold byte is unset");
 
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Session name is unset");
        ok(!session_name, "Session name is null");
 
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Channel name is unset");
        ok(!session_name, "Channel name is null");
 
@@ -65,30 +67,35 @@ static void test_condition_buffer_usage(
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Domain name is unset");
 
        diag("Testing session name set/get");
-       status = lttng_condition_buffer_usage_set_session_name(NULL, "Test");
+       status = lttng_condition_buffer_usage_set_session_name(nullptr, "Test");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set null condition on set session name");
-       status = lttng_condition_buffer_usage_get_session_name(NULL, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(nullptr, &session_name);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Get session name with null condition");
        ok(!session_name, "Session name is null");
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Session name is unset");
        ok(!session_name, "Session name is null");
 
-       status = lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, NULL);
+       status = lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, nullptr);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set null session name");
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Session name is unset");
        ok(!session_name, "Session name is null");
 
        status = lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, "");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set empty session name");
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Session name is unset");
        ok(!session_name, "Session name is null");
 
-       status = lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, "session420");
+       status =
+               lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, "session420");
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set session name session420");
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Session name is set");
        ok(session_name, "Session name has a value");
        ok(strcmp("session420", session_name) == 0, "Session name is %s", "session420");
@@ -100,35 +107,41 @@ static void test_condition_buffer_usage(
 
        status = lttng_condition_buffer_usage_set_session_name(buffer_usage_condition, "");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set session name to empty");
-       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition, &session_name);
+       status = lttng_condition_buffer_usage_get_session_name(buffer_usage_condition,
+                                                              &session_name);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Session name is still set");
        ok(session_name, "Session name has a value");
        ok(strcmp("session420", session_name) == 0, "Session is still name is %s", "session420");
 
        diag("Testing channel name set/get");
-       status = lttng_condition_buffer_usage_set_channel_name(NULL, "Test");
+       status = lttng_condition_buffer_usage_set_channel_name(nullptr, "Test");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set null condition on set channel name");
-       status = lttng_condition_buffer_usage_get_channel_name(NULL, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(nullptr, &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Get channel name with null condition");
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Channel name is unset");
        ok(!channel_name, "Channel name is null");
 
-       status = lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, NULL);
+       status = lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, nullptr);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set null channel name");
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Channel name is unset");
        ok(!channel_name, "Channel name is null");
 
        status = lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, "");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set empty channel name");
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Channel name is unset");
        ok(!channel_name, "Channel name is null");
 
-       status = lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, "channel420");
+       status =
+               lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, "channel420");
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set channel name channel420");
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Channel name is set");
        ok(channel_name, "Channel name has a value");
        ok(strcmp("channel420", channel_name) == 0, "Channel name is %s", "channel420");
@@ -140,70 +153,81 @@ static void test_condition_buffer_usage(
 
        status = lttng_condition_buffer_usage_set_channel_name(buffer_usage_condition, "");
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set channel name to empty");
-       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition, &channel_name);
+       status = lttng_condition_buffer_usage_get_channel_name(buffer_usage_condition,
+                                                              &channel_name);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Channel name is still set");
        ok(channel_name, "Channel name has a value");
        ok(strcmp("channel420", channel_name) == 0, "Channel is still name is %s", "channel420");
 
        diag("Testing threshold ratio set/get");
-       status = lttng_condition_buffer_usage_set_threshold_ratio(NULL, 0.420);
+       status = lttng_condition_buffer_usage_set_threshold_ratio(nullptr, 0.420);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set threshold ratio with null condition");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(NULL, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(nullptr, &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Get threshold ratio with null condition");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold ratio is unset");
 
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, -100.0);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set threshold ratio < 0");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold ratio is unset");
 
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, 200.0);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set Threshold ratio > 1");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold ratio is unset");
 
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, 1.0);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold ratio == 1.0");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold ratio is set");
        ok(threshold_ratio == 1.0, "Threshold ratio is 1.0");
 
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, 0.0);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold ratio == 0.0");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold ratio is set");
        ok(threshold_ratio == 0.0, "Threshold ratio is 0.0");
 
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, 0.420);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold ratio == 0.420");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold ratio is set");
        ok(threshold_ratio == 0.420, "Threshold ratio is 0.420");
 
        diag("Testing threshold bytes set/get");
-       status = lttng_condition_buffer_usage_set_threshold(NULL, 100000);
+       status = lttng_condition_buffer_usage_set_threshold(nullptr, 100000);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set threshold with null condition");
-       status = lttng_condition_buffer_usage_get_threshold(NULL, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(nullptr, &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Get threshold value with null condition ");
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold is unset");
 
        status = lttng_condition_buffer_usage_set_threshold(buffer_usage_condition, 100000);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold > 0");
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold is set");
        ok(threshold_bytes == 100000, "Threshold is 100000");
 
        status = lttng_condition_buffer_usage_set_threshold(buffer_usage_condition, UINT64_MAX);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold UINT64_MAX");
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold is set");
        ok(threshold_bytes == UINT64_MAX, "Threshold is UINT64_MAX");
 
        status = lttng_condition_buffer_usage_set_threshold(buffer_usage_condition, 0);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold  == 0");
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold is set");
        ok(threshold_bytes == 0, "Threshold is %d", 0);
 
@@ -214,84 +238,91 @@ static void test_condition_buffer_usage(
        diag("Testing interaction between byte and ratio thresholds");
 
        threshold_ratio = -1.0;
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold ratio is unset");
        ok(threshold_ratio == -1.0, "Threshold ratio is untouched");
 
        /* Set a ratio to validate that the byte threshold is now unset */
        status = lttng_condition_buffer_usage_set_threshold_ratio(buffer_usage_condition, 0.420);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set threshold ratio == 0.420");
-       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition, &threshold_ratio);
+       status = lttng_condition_buffer_usage_get_threshold_ratio(buffer_usage_condition,
+                                                                 &threshold_ratio);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Threshold ratio is set");
        ok(threshold_ratio == 0.420, "Threshold ratio is 0.420");
 
        threshold_bytes = 420;
-       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition, &threshold_bytes);
+       status = lttng_condition_buffer_usage_get_threshold(buffer_usage_condition,
+                                                           &threshold_bytes);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Threshold is unset");
        ok(threshold_bytes == 420, "Threshold is untouched");
 
        diag("Testing domain type set/get");
-       status = lttng_condition_buffer_usage_set_domain_type(NULL, LTTNG_DOMAIN_UST);
+       status = lttng_condition_buffer_usage_set_domain_type(nullptr, LTTNG_DOMAIN_UST);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set domain type with null condition");
-       status = lttng_condition_buffer_usage_get_domain_type(NULL, &domain_type);
+       status = lttng_condition_buffer_usage_get_domain_type(nullptr, &domain_type);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Get domain type with null condition");
 
-       status = lttng_condition_buffer_usage_set_domain_type(buffer_usage_condition, LTTNG_DOMAIN_NONE);
+       status = lttng_condition_buffer_usage_set_domain_type(buffer_usage_condition,
+                                                             LTTNG_DOMAIN_NONE);
        ok(status == LTTNG_CONDITION_STATUS_INVALID, "Set domain type as LTTNG_DOMAIN_NONE");
        status = lttng_condition_buffer_usage_get_domain_type(buffer_usage_condition, &domain_type);
        ok(status == LTTNG_CONDITION_STATUS_UNSET, "Domain type is unset");
 
-       status = lttng_condition_buffer_usage_set_domain_type(buffer_usage_condition, LTTNG_DOMAIN_UST);
+       status = lttng_condition_buffer_usage_set_domain_type(buffer_usage_condition,
+                                                             LTTNG_DOMAIN_UST);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Set domain type as LTTNG_DOMAIN_UST");
        status = lttng_condition_buffer_usage_get_domain_type(buffer_usage_condition, &domain_type);
        ok(status == LTTNG_CONDITION_STATUS_OK, "Domain type is set");
        ok(domain_type == LTTNG_DOMAIN_UST, "Domain type is LTTNG_DOMAIN_UST");
 }
 
-static void test_condition_buffer_usage_low(void)
+static void test_condition_buffer_usage_low()
 {
-       struct lttng_condition *buffer_usage_low = NULL;
+       struct lttng_condition *buffer_usage_low = nullptr;
 
        diag("Testing lttng_condition_buffer_usage_low_create");
        buffer_usage_low = lttng_condition_buffer_usage_low_create();
        ok(buffer_usage_low, "Condition allocated");
 
-       ok(lttng_condition_get_type(buffer_usage_low) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW, "Condition is of type \"low buffer usage\"");
+       ok(lttng_condition_get_type(buffer_usage_low) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_LOW,
+          "Condition is of type \"low buffer usage\"");
 
        test_condition_buffer_usage(buffer_usage_low);
 
        lttng_condition_destroy(buffer_usage_low);
 }
 
-static void test_condition_buffer_usage_high(void)
+static void test_condition_buffer_usage_high()
 {
-       struct lttng_condition *buffer_usage_high = NULL;
+       struct lttng_condition *buffer_usage_high = nullptr;
 
        diag("Testing lttng_condition_buffer_usage_high_create");
        buffer_usage_high = lttng_condition_buffer_usage_high_create();
        ok(buffer_usage_high, "High buffer usage condition allocated");
 
-       ok(lttng_condition_get_type(buffer_usage_high) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH, "Condition is of type \"high buffer usage\"");
+       ok(lttng_condition_get_type(buffer_usage_high) == LTTNG_CONDITION_TYPE_BUFFER_USAGE_HIGH,
+          "Condition is of type \"high buffer usage\"");
 
        test_condition_buffer_usage(buffer_usage_high);
 
        lttng_condition_destroy(buffer_usage_high);
 }
 
-static void test_trigger(void)
+static void test_trigger()
 {
-       struct lttng_action *notify_action = NULL;
-       struct lttng_condition *buffer_usage_high = NULL;
-       struct lttng_trigger *trigger = NULL;
+       struct lttng_action *notify_action = nullptr;
+       struct lttng_condition *buffer_usage_high = nullptr;
+       struct lttng_trigger *trigger = nullptr;
 
        notify_action = lttng_action_notify_create();
        buffer_usage_high = lttng_condition_buffer_usage_high_create();
 
-       trigger = lttng_trigger_create(NULL, NULL);
+       trigger = lttng_trigger_create(nullptr, nullptr);
        ok(!trigger, "lttng_trigger_create(NULL, NULL) returns null");
-       trigger = lttng_trigger_create(buffer_usage_high, NULL);
+       trigger = lttng_trigger_create(buffer_usage_high, nullptr);
        ok(!trigger, "lttng_trigger_create(NON-NULL, NULL) returns null");
-       trigger = lttng_trigger_create(NULL, notify_action);
+       trigger = lttng_trigger_create(nullptr, notify_action);
        ok(!trigger, "lttng_trigger_create(NULL, NON-NULL) returns null");
 
        trigger = lttng_trigger_create(buffer_usage_high, notify_action);
@@ -302,8 +333,7 @@ static void test_trigger(void)
        lttng_trigger_destroy(trigger);
 }
 
-
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_condition_buffer_usage_low();
index de50ed383b5a6ec8cfc4e1160124a30385f703c2..419fc893d23796609aac808dc153c78f2e8551a2 100644 (file)
@@ -5,12 +5,12 @@
  *
  */
 
-#include <unistd.h>
-
-#include <common/compat/fcntl.hpp>
-#include <common/payload.hpp>
 #include <common/payload-view.hpp>
+#include <common/payload.hpp>
+
+#include <fcntl.h>
 #include <tap/tap.h>
+#include <unistd.h>
 
 static const int TEST_COUNT = 5;
 
@@ -19,7 +19,7 @@ int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
 int lttng_opt_mi;
 
-static void test_fd_push_pop_order(void)
+static void test_fd_push_pop_order()
 {
        int ret, i;
        struct lttng_payload payload;
@@ -49,29 +49,28 @@ static void test_fd_push_pop_order(void)
 
        {
                bool fail_pop = false;
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                       &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
                for (i = 0; i < 3; i++) {
-                       struct fd_handle *handle =
-                                       lttng_payload_view_pop_fd_handle(&view);
+                       struct fd_handle *handle = lttng_payload_view_pop_fd_handle(&view);
 
                        fail_pop |= fd_handle_get_fd(handle) != fds[i];
                        fd_handle_put(handle);
                }
 
-               ok(!fail_pop, "File descriptors are popped from a payload view in the order of insertion");
+               ok(!fail_pop,
+                  "File descriptors are popped from a payload view in the order of insertion");
        }
 
        lttng_payload_reset(&payload);
 }
 
-static void test_fd_push_pop_imbalance(void)
+static void test_fd_push_pop_imbalance()
 {
        int ret, i;
        struct lttng_payload payload;
-       const char * const test_description = "Error reported when popping more file descriptors than were pushed";
+       const char *const test_description =
+               "Error reported when popping more file descriptors than were pushed";
 
        lttng_payload_init(&payload);
 
@@ -94,9 +93,7 @@ static void test_fd_push_pop_imbalance(void)
 
        {
                struct fd_handle *handle;
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                       &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
                for (i = 0; i < 10; i++) {
                        handle = lttng_payload_view_pop_fd_handle(&view);
@@ -118,13 +115,14 @@ fail:
        lttng_payload_reset(&payload);
 }
 
-static void test_fd_pop_fd_root_views(void)
+static void test_fd_pop_fd_root_views()
 {
        int ret, i;
        int fd = fcntl(STDOUT_FILENO, F_DUPFD, 0);
        struct fd_handle *handle;
        struct lttng_payload payload;
-       const char * const test_description = "Same file descriptor returned when popping from different top-level views";
+       const char *const test_description =
+               "Same file descriptor returned when popping from different top-level views";
 
        LTTNG_ASSERT(fd >= 0);
        handle = fd_handle_create(fd);
@@ -141,9 +139,7 @@ static void test_fd_pop_fd_root_views(void)
        for (i = 0; i < 5; i++) {
                int view_fd;
                struct fd_handle *view_handle;
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                       &payload, 0, -1);
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
 
                view_handle = lttng_payload_view_pop_fd_handle(&view);
                if (!view_handle) {
@@ -167,15 +163,16 @@ fail:
        fd_handle_put(handle);
 }
 
-static void test_fd_pop_fd_descendant_views(void)
+static void test_fd_pop_fd_descendant_views()
 {
        int ret;
        const int fd1 = 42, fd2 = 1837;
        struct fd_handle *handle1 = fd_handle_create(fd1);
        struct fd_handle *handle2 = fd_handle_create(fd2);
-       struct fd_handle *view_handle1 = NULL, *view_handle2 = NULL;
+       struct fd_handle *view_handle1 = nullptr, *view_handle2 = nullptr;
        struct lttng_payload payload;
-       const char * const test_description = "Different file descriptors returned when popping from descendant views";
+       const char *const test_description =
+               "Different file descriptors returned when popping from descendant views";
 
        lttng_payload_init(&payload);
        LTTNG_ASSERT(handle1);
@@ -193,12 +190,8 @@ static void test_fd_pop_fd_descendant_views(void)
        }
 
        {
-               struct lttng_payload_view view1 =
-                               lttng_payload_view_from_payload(
-                                       &payload, 0, -1);
-               struct lttng_payload_view view2 =
-                       lttng_payload_view_from_view(
-                               &view1, 0, -1);
+               struct lttng_payload_view view1 = lttng_payload_view_from_payload(&payload, 0, -1);
+               struct lttng_payload_view view2 = lttng_payload_view_from_view(&view1, 0, -1);
 
                view_handle1 = lttng_payload_view_pop_fd_handle(&view1);
                if (!view_handle1 || fd_handle_get_fd(view_handle1) != fd1) {
@@ -227,7 +220,7 @@ fail:
        fd_handle_put(view_handle2);
 }
 
-int main(void)
+int main()
 {
        plan_tests(TEST_COUNT);
 
index 755bfca029e4e95f3b90ddb13e06e08740c86df5..40ac0b4d6a118f1faa17d8e59b4a1dd9513dfc13 100644 (file)
@@ -7,18 +7,18 @@
  *
  */
 
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <tap/tap.h>
-
 #include <common/payload-view.hpp>
 #include <common/payload.hpp>
+
 #include <lttng/action/rate-policy-internal.hpp>
 #include <lttng/action/rate-policy.h>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <tap/tap.h>
+#include <unistd.h>
+
 /* For error.h. */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
@@ -26,13 +26,13 @@ int lttng_opt_mi;
 
 #define NUM_TESTS 42
 
-static void test_rate_policy_every_n(void)
+static void test_rate_policy_every_n()
 {
        enum lttng_rate_policy_status status;
-       struct lttng_rate_policy *policy_a = NULL; /* Interval of 100. */
-       struct lttng_rate_policy *policy_b = NULL; /* Interval of 100 */
-       struct lttng_rate_policy *policy_c = NULL; /* Interval of 1 */
-       struct lttng_rate_policy *policy_from_buffer = NULL;
+       struct lttng_rate_policy *policy_a = nullptr; /* Interval of 100. */
+       struct lttng_rate_policy *policy_b = nullptr; /* Interval of 100 */
+       struct lttng_rate_policy *policy_c = nullptr; /* Interval of 1 */
+       struct lttng_rate_policy *policy_from_buffer = nullptr;
        uint64_t interval_a_b = 100;
        uint64_t interval_c = 1;
        uint64_t interval_query = 0;
@@ -43,90 +43,65 @@ static void test_rate_policy_every_n(void)
        policy_a = lttng_rate_policy_every_n_create(interval_a_b);
        policy_b = lttng_rate_policy_every_n_create(interval_a_b);
        policy_c = lttng_rate_policy_every_n_create(interval_c);
-       ok(policy_a != NULL,
-                       "Rate policy every n A created: interval: %" PRIu64,
-                       interval_a_b);
-       ok(policy_b != NULL,
-                       "Rate policy every n B created: interval: %" PRIu64,
-                       interval_a_b);
-       ok(policy_c != NULL,
-                       "Rate policy every n C created: interval: %" PRIu64,
-                       interval_c);
-
-       ok(LTTNG_RATE_POLICY_TYPE_EVERY_N ==
-                                       lttng_rate_policy_get_type(policy_a),
-                       "Type is LTTNG_RATE_POLICY_TYPE_EVERY_N");
+       ok(policy_a != nullptr, "Rate policy every n A created: interval: %" PRIu64, interval_a_b);
+       ok(policy_b != nullptr, "Rate policy every n B created: interval: %" PRIu64, interval_a_b);
+       ok(policy_c != nullptr, "Rate policy every n C created: interval: %" PRIu64, interval_c);
+
+       ok(LTTNG_RATE_POLICY_TYPE_EVERY_N == lttng_rate_policy_get_type(policy_a),
+          "Type is LTTNG_RATE_POLICY_TYPE_EVERY_N");
 
        /* Getter tests */
-       status = lttng_rate_policy_every_n_get_interval(NULL, NULL);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get interval returns INVALID");
-
-       status = lttng_rate_policy_every_n_get_interval(NULL, &interval_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get interval returns INVALID");
-
-       status = lttng_rate_policy_every_n_get_interval(policy_a, NULL);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get interval returns INVALID");
-
-       status = lttng_rate_policy_every_n_get_interval(
-                       policy_a, &interval_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       interval_query == interval_a_b,
-                       " Getting interval A");
-
-       status = lttng_rate_policy_every_n_get_interval(
-                       policy_b, &interval_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       interval_query == interval_a_b,
-                       " Getting interval B");
-
-       status = lttng_rate_policy_every_n_get_interval(
-                       policy_c, &interval_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       interval_query == interval_c,
-                       " Getting interval C");
+       status = lttng_rate_policy_every_n_get_interval(nullptr, nullptr);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get interval returns INVALID");
+
+       status = lttng_rate_policy_every_n_get_interval(nullptr, &interval_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get interval returns INVALID");
+
+       status = lttng_rate_policy_every_n_get_interval(policy_a, nullptr);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get interval returns INVALID");
+
+       status = lttng_rate_policy_every_n_get_interval(policy_a, &interval_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && interval_query == interval_a_b,
+          " Getting interval A");
+
+       status = lttng_rate_policy_every_n_get_interval(policy_b, &interval_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && interval_query == interval_a_b,
+          " Getting interval B");
+
+       status = lttng_rate_policy_every_n_get_interval(policy_c, &interval_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && interval_query == interval_c,
+          " Getting interval C");
 
        /* is_equal tests */
        /* TODO: this is the behaviour introduced by the
         * lttng_condition_is_equal back in 2017 do we want to fix this and
         * return true if both are NULL?
         */
-       ok(false == lttng_rate_policy_is_equal(NULL, NULL),
-                       "is equal (NULL,NULL)");
-       ok(false == lttng_rate_policy_is_equal(policy_a, NULL),
-                       "is equal (object, NULL)");
-       ok(false == lttng_rate_policy_is_equal(NULL, policy_a),
-                       " is equal (NULL, object)");
-       ok(true == lttng_rate_policy_is_equal(policy_a, policy_a),
-                       "is equal (object A, object A)");
-
-       ok(true == lttng_rate_policy_is_equal(policy_a, policy_b),
-                       "is equal (object A, object B");
-       ok(true == lttng_rate_policy_is_equal(policy_b, policy_a),
-                       "is equal (object B, object A");
+       ok(false == lttng_rate_policy_is_equal(nullptr, nullptr), "is equal (NULL,NULL)");
+       ok(false == lttng_rate_policy_is_equal(policy_a, nullptr), "is equal (object, NULL)");
+       ok(false == lttng_rate_policy_is_equal(nullptr, policy_a), " is equal (NULL, object)");
+       ok(true == lttng_rate_policy_is_equal(policy_a, policy_a), "is equal (object A, object A)");
+
+       ok(true == lttng_rate_policy_is_equal(policy_a, policy_b), "is equal (object A, object B");
+       ok(true == lttng_rate_policy_is_equal(policy_b, policy_a), "is equal (object B, object A");
 
        ok(false == lttng_rate_policy_is_equal(policy_a, policy_c),
-                       "is equal (object A, object C)");
+          "is equal (object A, object C)");
        ok(false == lttng_rate_policy_is_equal(policy_c, policy_a),
-                       "is equal (object C, object A)");
+          "is equal (object C, object A)");
 
        /* Serialization and create_from buffer. */
        ok(lttng_rate_policy_serialize(policy_a, &payload) == 0, "Serializing");
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-
-               ok(lttng_rate_policy_create_from_payload(
-                                  &view, &policy_from_buffer) > 0 &&
-                                               policy_from_buffer != NULL,
-                               "Deserializing");
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+
+               ok(lttng_rate_policy_create_from_payload(&view, &policy_from_buffer) > 0 &&
+                          policy_from_buffer != nullptr,
+                  "Deserializing");
        }
 
        ok(lttng_rate_policy_is_equal(policy_a, policy_from_buffer),
-                       "serialized and from buffer are equal");
+          "serialized and from buffer are equal");
 
        lttng_rate_policy_destroy(policy_a);
        lttng_rate_policy_destroy(policy_b);
@@ -135,13 +110,13 @@ static void test_rate_policy_every_n(void)
        lttng_payload_reset(&payload);
 }
 
-static void test_rate_policy_once_after_n(void)
+static void test_rate_policy_once_after_n()
 {
        enum lttng_rate_policy_status status;
-       struct lttng_rate_policy *policy_a = NULL; /* Threshold of 100. */
-       struct lttng_rate_policy *policy_b = NULL; /* threshold of 100 */
-       struct lttng_rate_policy *policy_c = NULL; /* threshold of 1 */
-       struct lttng_rate_policy *policy_from_buffer = NULL;
+       struct lttng_rate_policy *policy_a = nullptr; /* Threshold of 100. */
+       struct lttng_rate_policy *policy_b = nullptr; /* threshold of 100 */
+       struct lttng_rate_policy *policy_c = nullptr; /* threshold of 1 */
+       struct lttng_rate_policy *policy_from_buffer = nullptr;
        uint64_t threshold_a_b = 100;
        uint64_t threshold_c = 1;
        uint64_t threshold_query = 0;
@@ -152,87 +127,65 @@ static void test_rate_policy_once_after_n(void)
        policy_a = lttng_rate_policy_once_after_n_create(threshold_a_b);
        policy_b = lttng_rate_policy_once_after_n_create(threshold_a_b);
        policy_c = lttng_rate_policy_once_after_n_create(threshold_c);
-       ok(policy_a != NULL,
-                       "Rate policy every n A created: threshold: %" PRIu64,
-                       threshold_a_b);
-       ok(policy_b != NULL,
-                       "Rate policy every n B created: threshold: %" PRIu64,
-                       threshold_a_b);
-       ok(policy_c != NULL,
-                       "Rate policy every n C created: threshold: %" PRIu64,
-                       threshold_c);
-
-       ok(LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N ==
-                                       lttng_rate_policy_get_type(policy_a),
-                       "Type is LTTNG_RATE_POLICY_TYPE_once_after_n");
+       ok(policy_a != nullptr,
+          "Rate policy every n A created: threshold: %" PRIu64,
+          threshold_a_b);
+       ok(policy_b != nullptr,
+          "Rate policy every n B created: threshold: %" PRIu64,
+          threshold_a_b);
+       ok(policy_c != nullptr, "Rate policy every n C created: threshold: %" PRIu64, threshold_c);
+
+       ok(LTTNG_RATE_POLICY_TYPE_ONCE_AFTER_N == lttng_rate_policy_get_type(policy_a),
+          "Type is LTTNG_RATE_POLICY_TYPE_once_after_n");
 
        /* Getter tests */
-       status = lttng_rate_policy_once_after_n_get_threshold(NULL, NULL);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get threshold returns INVALID");
-
-       status = lttng_rate_policy_once_after_n_get_threshold(
-                       NULL, &threshold_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get threshold returns INVALID");
-
-       status = lttng_rate_policy_once_after_n_get_threshold(policy_a, NULL);
-       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID,
-                       "Get threshold returns INVALID");
-
-       status = lttng_rate_policy_once_after_n_get_threshold(
-                       policy_a, &threshold_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       threshold_query == threshold_a_b,
-                       " Getting threshold A");
-
-       status = lttng_rate_policy_once_after_n_get_threshold(
-                       policy_b, &threshold_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       threshold_query == threshold_a_b,
-                       " Getting threshold B");
-
-       status = lttng_rate_policy_once_after_n_get_threshold(
-                       policy_c, &threshold_query);
-       ok(status == LTTNG_RATE_POLICY_STATUS_OK &&
-                                       threshold_query == threshold_c,
-                       " Getting threshold C");
+       status = lttng_rate_policy_once_after_n_get_threshold(nullptr, nullptr);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get threshold returns INVALID");
+
+       status = lttng_rate_policy_once_after_n_get_threshold(nullptr, &threshold_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get threshold returns INVALID");
+
+       status = lttng_rate_policy_once_after_n_get_threshold(policy_a, nullptr);
+       ok(status == LTTNG_RATE_POLICY_STATUS_INVALID, "Get threshold returns INVALID");
+
+       status = lttng_rate_policy_once_after_n_get_threshold(policy_a, &threshold_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && threshold_query == threshold_a_b,
+          " Getting threshold A");
+
+       status = lttng_rate_policy_once_after_n_get_threshold(policy_b, &threshold_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && threshold_query == threshold_a_b,
+          " Getting threshold B");
+
+       status = lttng_rate_policy_once_after_n_get_threshold(policy_c, &threshold_query);
+       ok(status == LTTNG_RATE_POLICY_STATUS_OK && threshold_query == threshold_c,
+          " Getting threshold C");
 
        /* is_equal tests */
-       ok(false == lttng_rate_policy_is_equal(NULL, NULL),
-                       "is equal (NULL,NULL)");
-       ok(false == lttng_rate_policy_is_equal(policy_a, NULL),
-                       "is equal (object, NULL)");
-       ok(false == lttng_rate_policy_is_equal(NULL, policy_a),
-                       " is equal (NULL, object)");
-       ok(true == lttng_rate_policy_is_equal(policy_a, policy_a),
-                       "is equal (object A, object A)");
-
-       ok(true == lttng_rate_policy_is_equal(policy_a, policy_b),
-                       "is equal (object A, object B");
-       ok(true == lttng_rate_policy_is_equal(policy_b, policy_a),
-                       "is equal (object B, object A");
+       ok(false == lttng_rate_policy_is_equal(nullptr, nullptr), "is equal (NULL,NULL)");
+       ok(false == lttng_rate_policy_is_equal(policy_a, nullptr), "is equal (object, NULL)");
+       ok(false == lttng_rate_policy_is_equal(nullptr, policy_a), " is equal (NULL, object)");
+       ok(true == lttng_rate_policy_is_equal(policy_a, policy_a), "is equal (object A, object A)");
+
+       ok(true == lttng_rate_policy_is_equal(policy_a, policy_b), "is equal (object A, object B");
+       ok(true == lttng_rate_policy_is_equal(policy_b, policy_a), "is equal (object B, object A");
 
        ok(false == lttng_rate_policy_is_equal(policy_a, policy_c),
-                       "is equal (object A, object C)");
+          "is equal (object A, object C)");
        ok(false == lttng_rate_policy_is_equal(policy_c, policy_a),
-                       "is equal (object C, object A)");
+          "is equal (object C, object A)");
 
        /* Serialization and create_from buffer. */
        ok(lttng_rate_policy_serialize(policy_a, &payload) == 0, "Serializing");
        {
-               struct lttng_payload_view view =
-                               lttng_payload_view_from_payload(
-                                               &payload, 0, -1);
-
-               ok(lttng_rate_policy_create_from_payload(
-                                  &view, &policy_from_buffer) > 0 &&
-                                               policy_from_buffer != NULL,
-                               "Deserializing");
+               struct lttng_payload_view view = lttng_payload_view_from_payload(&payload, 0, -1);
+
+               ok(lttng_rate_policy_create_from_payload(&view, &policy_from_buffer) > 0 &&
+                          policy_from_buffer != nullptr,
+                  "Deserializing");
        }
 
        ok(lttng_rate_policy_is_equal(policy_a, policy_from_buffer),
-                       "serialized and from buffer are equal");
+          "serialized and from buffer are equal");
 
        lttng_rate_policy_destroy(policy_a);
        lttng_rate_policy_destroy(policy_b);
@@ -241,7 +194,7 @@ static void test_rate_policy_once_after_n(void)
        lttng_payload_reset(&payload);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        test_rate_policy_every_n();
index 4b794faf7c7081660cc1317dbdc575c999f8cfbb..527d41ac920041bc0c8631f137aa0d70be442878 100644 (file)
@@ -5,16 +5,16 @@
  *
  */
 
+#include "backward-compatibility-group-by.hpp"
+
+#include <common/time.hpp>
+
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <tap/tap.h>
 
-#include <common/time.hpp>
-
-#include "backward-compatibility-group-by.hpp"
-
 /* Number of TAP tests in this file */
 #define NUM_TESTS_PER_TEST 1
 
@@ -35,105 +35,148 @@ int lttng_opt_mi;
 int lttng_opt_verbose;
 
 struct test tests[] = {
-               /* Default name session streaming. */
-               {"hostname/auto-20190918-164429/ust/uid/1000/64-bit",
-                               "auto-20190918-164429", "hostname",
-                               "20190918-164429", "", "ust/uid/1000/64-bit",
-                               true},
-               /* Custom default name session */
-               {"hostname/custom_auto-20190319-120000/ust/uid/1000/64-bit",
-                               "custom_auto-20190319-120000", "hostname",
-                               "20190319-120000", "", "ust/uid/1000/64-bit",
-                               true},
-               /* Named session streaming */
-               {"hostname/test-20190918-164709/ust/uid/1000/64-bit", "test",
-                               "hostname", "20190918-164709", "",
-                               "ust/uid/1000/64-bit", true},
-               /* Default session snapshot streaming */
-               {"hostname//snapshot-1-20190918-164829-0/ust//uid/1000/64-bit",
-                               "my_session", "hostname", "", "",
-                               "snapshot-1-20190918-164829-0/ust//uid/1000/64-bit",
-                               true},
-               /* Named session snapshot streaming */
-               {"hostname//snapshot-1-20190918-175919-0/ust//uid/1000/64-bit",
-                               "my_session", "hostname", "", "",
-                               "snapshot-1-20190918-175919-0/ust//uid/1000/64-bit",
-                               true},
-               /* Default name session, live */
-               {"hostname//auto-20190918-171641/ust/uid/1000/64-bit",
-                               "auto-20190918-171641", "hostname",
-                               "20190918-171641", "", "ust/uid/1000/64-bit",
-                               true},
-               /* Named session, live */
-               {"hostname//test-20190918-180333//ust/uid/1000/64-bit",
-                               "test-20190918-180333", "hostname",
-                               "20190918-180333", "", "/ust/uid/1000/64-bit",
-                               true},
-               /* Default name session, streaming & live , extra path */
-               {"hostname/extra/path/ust/uid/1000/64-bit",
-                               "auto-20190919-122110", "hostname",
-                               "20190919-122110", "extra",
-                               "path/ust/uid/1000/64-bit", true},
-               /* Named session, live, extra path */
-               {"hostname/extra/path/ust/uid/1000/64-bit", "test", "hostname",
-                               "", "extra", "path/ust/uid/1000/64-bit", true},
-               /* Named session, snapshot, extra path */
-               {"hostname/extra/path/snapshot-1-20190919-140702-0/ust//uid/1000/64-bit",
-                               "test", "hostname", "", "extra",
-                               "path/snapshot-1-20190919-140702-0/ust//uid/1000/64-bit",
-                               true},
-               /* Corner cases*/
-               /* Named session with valid datetime in it */
-               /* Default name session, extra path with session name in it*/
-               {"hostname/test-20190319-120000-20190918-180921/ust/uid/1000/64-bit",
-                               "test-20190319-120000", "hostname",
-                               "20190918-180921", "", "ust/uid/1000/64-bit",
-                               true},
-               /* Empty path */
-               {"", "test", "", "", "", "", false},
-               /* Path without second token */
-               {"hostname", "test", "hostname", "", "", "", false},
-               /* No leftover */
-               {"hostname/test", "test", "hostname", "", "", "", true},
-               /* Path with ession name but no datetime */
-               {"hostname/test/ust/uid/1000/64-bit", "test", "hostname", "",
-                               "", "ust/uid/1000/64-bit", true},
+       /* Default name session streaming. */
+       { "hostname/auto-20190918-164429/ust/uid/1000/64-bit",
+         "auto-20190918-164429",
+         "hostname",
+         "20190918-164429",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
+       /* Custom default name session */
+       { "hostname/custom_auto-20190319-120000/ust/uid/1000/64-bit",
+         "custom_auto-20190319-120000",
+         "hostname",
+         "20190319-120000",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
+       /* Named session streaming */
+       { "hostname/test-20190918-164709/ust/uid/1000/64-bit",
+         "test",
+         "hostname",
+         "20190918-164709",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
+       /* Default session snapshot streaming */
+       { "hostname//snapshot-1-20190918-164829-0/ust//uid/1000/64-bit",
+         "my_session",
+         "hostname",
+         "",
+         "",
+         "snapshot-1-20190918-164829-0/ust//uid/1000/64-bit",
+         true },
+       /* Named session snapshot streaming */
+       { "hostname//snapshot-1-20190918-175919-0/ust//uid/1000/64-bit",
+         "my_session",
+         "hostname",
+         "",
+         "",
+         "snapshot-1-20190918-175919-0/ust//uid/1000/64-bit",
+         true },
+       /* Default name session, live */
+       { "hostname//auto-20190918-171641/ust/uid/1000/64-bit",
+         "auto-20190918-171641",
+         "hostname",
+         "20190918-171641",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
+       /* Named session, live */
+       { "hostname//test-20190918-180333//ust/uid/1000/64-bit",
+         "test-20190918-180333",
+         "hostname",
+         "20190918-180333",
+         "",
+         "/ust/uid/1000/64-bit",
+         true },
+       /* Default name session, streaming & live , extra path */
+       { "hostname/extra/path/ust/uid/1000/64-bit",
+         "auto-20190919-122110",
+         "hostname",
+         "20190919-122110",
+         "extra",
+         "path/ust/uid/1000/64-bit",
+         true },
+       /* Named session, live, extra path */
+       { "hostname/extra/path/ust/uid/1000/64-bit",
+         "test",
+         "hostname",
+         "",
+         "extra",
+         "path/ust/uid/1000/64-bit",
+         true },
+       /* Named session, snapshot, extra path */
+       { "hostname/extra/path/snapshot-1-20190919-140702-0/ust//uid/1000/64-bit",
+         "test",
+         "hostname",
+         "",
+         "extra",
+         "path/snapshot-1-20190919-140702-0/ust//uid/1000/64-bit",
+         true },
+       /* Corner cases*/
+       /* Named session with valid datetime in it */
+       /* Default name session, extra path with session name in it*/
+       { "hostname/test-20190319-120000-20190918-180921/ust/uid/1000/64-bit",
+         "test-20190319-120000",
+         "hostname",
+         "20190918-180921",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
+       /* Empty path */
+       { "", "test", "", "", "", "", false },
+       /* Path without second token */
+       { "hostname", "test", "hostname", "", "", "", false },
+       /* No leftover */
+       { "hostname/test", "test", "hostname", "", "", "", true },
+       /* Path with ession name but no datetime */
+       { "hostname/test/ust/uid/1000/64-bit",
+         "test",
+         "hostname",
+         "",
+         "",
+         "ust/uid/1000/64-bit",
+         true },
 };
 
 static char *craft_expected(struct test *test, time_t relay_session_creation_time)
 {
        int ret;
-       char *result = NULL;
+       char *result = nullptr;
        char relay_session_creation_datetime[DATETIME_STR_LEN];
 
        ret = time_to_datetime_str(relay_session_creation_time,
-                       relay_session_creation_datetime,
-                       sizeof(relay_session_creation_datetime));
+                                  relay_session_creation_datetime,
+                                  sizeof(relay_session_creation_datetime));
        if (ret < 0) {
-               result = NULL;
+               result = nullptr;
                goto end;
        }
 
-       ret = asprintf(&result, "%s/%s-%s/%s%s%s", test->session_name,
-                       test->hostname,
-                       test->creation_time[0] == '\0' ?
-                                       relay_session_creation_datetime :
-                                       test->creation_time,
-                       test->extra_path,
-                       test->extra_path[0] != '\0' ? "/" : "", test->leftover);
+       ret = asprintf(&result,
+                      "%s/%s-%s/%s%s%s",
+                      test->session_name,
+                      test->hostname,
+                      test->creation_time[0] == '\0' ? relay_session_creation_datetime :
+                                                       test->creation_time,
+                      test->extra_path,
+                      test->extra_path[0] != '\0' ? "/" : "",
+                      test->leftover);
        if (ret < 0) {
-               result = NULL;
+               result = nullptr;
                goto end;
        }
 end:
        return result;
 }
 
-int main(void)
+int main()
 {
        int i;
        int num_test = sizeof(tests) / sizeof(struct test);
-       const time_t test_time = time(NULL);
+       const time_t test_time = time(nullptr);
 
        plan_tests(NUM_TESTS_PER_TEST * num_test);
        diag("Backward compatibility utils for lttng-relayd --group-by-session");
@@ -144,8 +187,8 @@ int main(void)
        }
 
        for (i = 0; i < num_test; i++) {
-               char *expected = NULL;
-               char *result = NULL;
+               char *expected = nullptr;
+               char *result = nullptr;
 
                expected = craft_expected(&tests[i], test_time);
                if (!expected) {
@@ -153,19 +196,21 @@ int main(void)
                        goto loop;
                }
 
-               result = backward_compat_group_by_session(tests[i].stream_path,
-                               tests[i].session_name, test_time);
+               result = backward_compat_group_by_session(
+                       tests[i].stream_path, tests[i].session_name, test_time);
                if (!result && tests[i].is_valid) {
                        fprintf(stderr, "Failed to get result\n");
                        goto loop;
-               } else if (!result && tests[i].is_valid == false) {
+               } else if (!result && !tests[i].is_valid) {
                        pass("Returned null as expected");
                        goto loop;
                }
 
                ok(strncmp(expected, result, strlen(expected)) == 0,
-                               "In: %s, out: %s, expected: %s",
-                               tests[i].stream_path, result, expected);
+                  "In: %s, out: %s, expected: %s",
+                  tests[i].stream_path,
+                  result,
+                  expected);
        loop:
                free(expected);
                free(result);
index c19a1afddfc0a17a445b71d367b74dfaaf7444b6..f6e58c8cb48cae044539d0310a78814b58745c90 100644 (file)
@@ -5,45 +5,43 @@
  *
  */
 
+#include <common/common.hpp>
+#include <common/compat/errno.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
+
+#include <bin/lttng-sessiond/health-sessiond.hpp>
+#include <bin/lttng-sessiond/session.hpp>
+#include <bin/lttng-sessiond/thread.hpp>
+#include <bin/lttng-sessiond/ust-app.hpp>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
+#include <tap/tap.h>
 #include <time.h>
 #include <unistd.h>
 #include <urcu.h>
 
-#include <bin/lttng-sessiond/health-sessiond.hpp>
-#include <bin/lttng-sessiond/session.hpp>
-#include <bin/lttng-sessiond/thread.hpp>
-#include <bin/lttng-sessiond/ust-app.hpp>
-#include <common/common.hpp>
-#include <common/compat/errno.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-
-#include <tap/tap.h>
-
 #define SESSION1 "test1"
 
-#define MAX_SESSIONS 10000
-#define RANDOM_STRING_LEN      11
+#define MAX_SESSIONS     10000
+#define RANDOM_STRING_LEN 11
 
 /* Number of TAP tests in this file */
 #define NUM_TESTS 11
 
 static struct ltt_session_list *session_list;
 
-static const char alphanum[] =
-       "0123456789"
-       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-       "abcdefghijklmnopqrstuvwxyz";
+static const char alphanum[] = "0123456789"
+                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                              "abcdefghijklmnopqrstuvwxyz";
 static char random_string[RANDOM_STRING_LEN];
 
 /*
  * Return random string of 10 characters.
  * Not thread-safe.
  */
-static char *get_random_string(void)
+static char *get_random_string()
 {
        int i;
 
@@ -63,7 +61,7 @@ static int find_session_name(const char *name)
 {
        struct ltt_session *iter;
 
-       cds_list_for_each_entry(iter, &session_list->head, list) {
+       cds_list_for_each_entry (iter, &session_list->head, list) {
                if (strcmp(iter->name, name) == 0) {
                        return 0;
                }
@@ -72,12 +70,12 @@ static int find_session_name(const char *name)
        return -1;
 }
 
-static int session_list_count(void)
+static int session_list_count()
 {
        int count = 0;
        struct ltt_session *iter;
 
-       cds_list_for_each_entry(iter, &session_list->head, list) {
+       cds_list_for_each_entry (iter, &session_list->head, list) {
                count++;
        }
        return count;
@@ -86,12 +84,12 @@ static int session_list_count(void)
 /*
  * Empty session list manually.
  */
-static void empty_session_list(void)
+static void empty_session_list()
 {
        struct ltt_session *iter, *tmp;
 
        session_lock_list();
-       cds_list_for_each_entry_safe(iter, tmp, &session_list->head, list) {
+       cds_list_for_each_entry_safe (iter, tmp, &session_list->head, list) {
                session_destroy(iter);
        }
        session_unlock_list();
@@ -107,7 +105,7 @@ static int create_one_session(const char *name)
 {
        int ret;
        enum lttng_error_code ret_code;
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
 
        session_lock_list();
        ret_code = session_create(name, geteuid(), getegid(), &session);
@@ -163,7 +161,7 @@ static int destroy_one_session(struct ltt_session *session)
  * This test is supposed to fail at the second create call. If so, return 0 for
  * test success, else -1.
  */
-static int two_session_same_name(void)
+static int two_session_same_name()
 {
        int ret;
        struct ltt_session *sess;
@@ -194,32 +192,28 @@ end:
        return ret;
 }
 
-static void test_session_list(void)
+static void test_session_list()
 {
        session_list = session_get_list();
-       ok(session_list != NULL, "Session list: not NULL");
+       ok(session_list != nullptr, "Session list: not NULL");
 }
 
-static void test_create_one_session(void)
+static void test_create_one_session()
 {
-       ok(create_one_session(SESSION1) == 0,
-          "Create session: %s",
-          SESSION1);
+       ok(create_one_session(SESSION1) == 0, "Create session: %s", SESSION1);
 }
 
-static void test_validate_session(void)
+static void test_validate_session()
 {
        struct ltt_session *tmp;
 
        session_lock_list();
        tmp = session_find_by_name(SESSION1);
 
-       ok(tmp != NULL,
-          "Validating session: session found");
+       ok(tmp != nullptr, "Validating session: session found");
 
        if (tmp) {
-               ok(tmp->kernel_session == NULL &&
-                  strlen(tmp->name),
+               ok(tmp->kernel_session == nullptr && strlen(tmp->name),
                   "Validating session: basic sanity check");
        } else {
                skip(1, "Skipping session validation check as session was not found");
@@ -233,58 +227,54 @@ end:
        session_unlock_list();
 }
 
-static void test_destroy_session(void)
+static void test_destroy_session()
 {
        struct ltt_session *tmp;
 
        session_lock_list();
        tmp = session_find_by_name(SESSION1);
 
-       ok(tmp != NULL,
-          "Destroying session: session found");
+       ok(tmp != nullptr, "Destroying session: session found");
 
        if (tmp) {
-               ok(destroy_one_session(tmp) == 0,
-                  "Destroying session: %s destroyed",
-                  SESSION1);
+               ok(destroy_one_session(tmp) == 0, "Destroying session: %s destroyed", SESSION1);
        } else {
                skip(1, "Skipping session destruction as it was not found");
        }
        session_unlock_list();
 }
 
-static void test_duplicate_session(void)
+static void test_duplicate_session()
 {
-       ok(two_session_same_name() == 0,
-          "Duplicate session creation");
+       ok(two_session_same_name() == 0, "Duplicate session creation");
 }
 
-static void test_session_name_generation(void)
+static void test_session_name_generation()
 {
-       struct ltt_session *session = NULL;
+       struct ltt_session *session = nullptr;
        enum lttng_error_code ret_code;
        const char *expected_session_name_prefix = DEFAULT_SESSION_NAME;
 
        session_lock_list();
-       ret_code = session_create(NULL, geteuid(), getegid(), &session);
-       ok(ret_code == LTTNG_OK,
-               "Create session with a NULL name (auto-generate a name)");
+       ret_code = session_create(nullptr, geteuid(), getegid(), &session);
+       ok(ret_code == LTTNG_OK, "Create session with a NULL name (auto-generate a name)");
        if (!session) {
                skip(1, "Skipping session name generation tests as session_create() failed.");
                goto end;
        }
-       diag("Automatically-generated session name: %s", *session->name ?
-               session->name : "ERROR");
-       ok(*session->name && !strncmp(expected_session_name_prefix, session->name,
-                       sizeof(DEFAULT_SESSION_NAME) - 1),
-                       "Auto-generated session name starts with %s",
-                       DEFAULT_SESSION_NAME);
+       diag("Automatically-generated session name: %s", *session->name ? session->name : "ERROR");
+       ok(*session->name &&
+                  !strncmp(expected_session_name_prefix,
+                           session->name,
+                           sizeof(DEFAULT_SESSION_NAME) - 1),
+          "Auto-generated session name starts with %s",
+          DEFAULT_SESSION_NAME);
 end:
        session_put(session);
        session_unlock_list();
 }
 
-static void test_large_session_number(void)
+static void test_large_session_number()
 {
        int ret, i, failed = 0;
        struct ltt_session *iter, *tmp;
@@ -298,15 +288,13 @@ static void test_large_session_number(void)
                }
        }
 
-       ok(failed == 0,
-          "Large sessions number: created %u sessions",
-          MAX_SESSIONS);
+       ok(failed == 0, "Large sessions number: created %u sessions", MAX_SESSIONS);
 
        failed = 0;
 
        session_lock_list();
        for (i = 0; i < MAX_SESSIONS; i++) {
-               cds_list_for_each_entry_safe(iter, tmp, &session_list->head, list) {
+               cds_list_for_each_entry_safe (iter, tmp, &session_list->head, list) {
                        LTTNG_ASSERT(session_get(iter));
                        ret = destroy_one_session(iter);
                        if (ret < 0) {
@@ -322,9 +310,8 @@ static void test_large_session_number(void)
           MAX_SESSIONS);
 }
 
-int main(void)
+int main()
 {
-
        plan_tests(NUM_TESTS);
 
        the_health_sessiond = health_app_create(NR_HEALTH_SESSIOND_TYPES);
index ff06bf9b6774ade76bb419822fca0c3afe4532a8..ca0f607ba04cab7f9b4865fd5ccdaeff9f2bed59 100644 (file)
@@ -5,11 +5,12 @@
  *
  */
 
-#include <stdlib.h>
+#include <common/string-utils/string-utils.hpp>
+
+#include <stdarg.h>
 #include <stdbool.h>
+#include <stdlib.h>
 #include <string.h>
-#include <stdarg.h>
-#include <common/string-utils/string-utils.hpp>
 #include <tap/tap.h>
 
 /* Number of TAP tests in this file */
@@ -20,8 +21,7 @@ int lttng_opt_quiet = 1;
 int lttng_opt_verbose;
 int lttng_opt_mi;
 
-static void test_one_split(const char *input, char delim, int escape_delim,
-               ...)
+static void test_one_split(const char *input, char delim, int escape_delim, ...)
 {
        va_list vl;
        bool all_ok = true;
@@ -38,8 +38,7 @@ static void test_one_split(const char *input, char delim, int escape_delim,
        for (i = 0; i < string_count; i++) {
                const char *expected_substring = va_arg(vl, const char *);
                const char *substring =
-                       (const char *) lttng_dynamic_pointer_array_get_pointer(
-                               &strings, i);
+                       (const char *) lttng_dynamic_pointer_array_get_pointer(&strings, i);
 
                diag("  got `%s`, expecting `%s`", substring, expected_substring);
 
@@ -56,11 +55,14 @@ static void test_one_split(const char *input, char delim, int escape_delim,
 
        lttng_dynamic_pointer_array_reset(&strings);
        va_end(vl);
-       ok(all_ok, "strutils_split() produces the expected substrings: `%s` (delim. `%c`, escape `%d`)",
-                       input, delim, escape_delim);
+       ok(all_ok,
+          "strutils_split() produces the expected substrings: `%s` (delim. `%c`, escape `%d`)",
+          input,
+          delim,
+          escape_delim);
 }
 
-static void test_split(void)
+static void test_split()
 {
        test_one_split("a/b/c/d/e", '/', false, "a", "b", "c", "d", "e", NULL);
        test_one_split("a/b//d/e", '/', false, "a", "b", "", "d", "e", NULL);
@@ -84,11 +86,12 @@ static void test_split(void)
 static void test_one_is_star_at_the_end_only_glob_pattern(const char *pattern, bool expected)
 {
        ok(strutils_is_star_at_the_end_only_glob_pattern(pattern) == expected,
-               "strutils_is_star_at_the_end_only_glob_pattern() returns the expected result: `%s` -> %d",
-               pattern, expected);
+          "strutils_is_star_at_the_end_only_glob_pattern() returns the expected result: `%s` -> %d",
+          pattern,
+          expected);
 }
 
-static void test_is_star_at_the_end_only_glob_pattern(void)
+static void test_is_star_at_the_end_only_glob_pattern()
 {
        test_one_is_star_at_the_end_only_glob_pattern("allo*", true);
        test_one_is_star_at_the_end_only_glob_pattern("allo\\\\*", true);
@@ -105,11 +108,12 @@ static void test_is_star_at_the_end_only_glob_pattern(void)
 static void test_one_is_star_glob_pattern(const char *pattern, bool expected)
 {
        ok(strutils_is_star_glob_pattern(pattern) == expected,
-               "strutils_is_star_glob_pattern() returns the expected result: `%s` -> %d",
-               pattern, expected);
+          "strutils_is_star_glob_pattern() returns the expected result: `%s` -> %d",
+          pattern,
+          expected);
 }
 
-static void test_is_star_glob_pattern(void)
+static void test_is_star_glob_pattern()
 {
        test_one_is_star_glob_pattern("allo*", true);
        test_one_is_star_glob_pattern("*allo", true);
@@ -128,20 +132,20 @@ static void test_is_star_glob_pattern(void)
        test_one_is_star_glob_pattern("allo\\", false);
 }
 
-static void test_one_normalize_star_glob_pattern(const char *pattern,
-               const char *expected)
+static void test_one_normalize_star_glob_pattern(const char *pattern, const char *expected)
 {
        char *rw_pattern = strdup(pattern);
 
        LTTNG_ASSERT(rw_pattern);
        strutils_normalize_star_glob_pattern(rw_pattern);
        ok(strcmp(rw_pattern, expected) == 0,
-               "strutils_normalize_star_glob_pattern() produces the expected result: `%s` -> `%s`",
-               pattern, expected);
+          "strutils_normalize_star_glob_pattern() produces the expected result: `%s` -> `%s`",
+          pattern,
+          expected);
        free(rw_pattern);
 }
 
-static void test_normalize_star_glob_pattern(void)
+static void test_normalize_star_glob_pattern()
 {
        test_one_normalize_star_glob_pattern("salut", "salut");
        test_one_normalize_star_glob_pattern("sal*ut", "sal*ut");
@@ -172,7 +176,7 @@ static void test_normalize_star_glob_pattern(void)
        test_one_normalize_star_glob_pattern("**\\***", "*\\**");
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
        diag("String utils unit tests");
index 2ff65a679749838586fb47846306a740cc0b3f0f..e0af6e2969b4125417d0ec11d98659cac54ff32d 100644 (file)
@@ -5,28 +5,30 @@
  *
  */
 
-#include <algorithm>
-#include <common/compat/fcntl.hpp>
-#include <common/sessiond-comm/sessiond-comm.hpp>
-#include <common/payload.hpp>
+#include <common/defaults.hpp>
+#include <common/error.hpp>
 #include <common/payload-view.hpp>
+#include <common/payload.hpp>
+#include <common/sessiond-comm/sessiond-comm.hpp>
 #include <common/unix.hpp>
 #include <common/utils.hpp>
-#include <common/defaults.hpp>
-#include <tap/tap.h>
-#include <stdbool.h>
-#include <common/error.hpp>
+
 #include <lttng/constant.h>
-#include <stdio.h>
+
+#include <algorithm>
+#include <fcntl.h>
 #include <pthread.h>
-#include <unistd.h>
-#include <sys/wait.h>
+#include <stdbool.h>
+#include <stdio.h>
 #include <stdlib.h>
+#include <sys/wait.h>
+#include <tap/tap.h>
+#include <unistd.h>
 
-#define HIGH_FD_COUNT LTTCOMM_MAX_SEND_FDS
-#define MESSAGE_COUNT 4
-#define LARGE_PAYLOAD_SIZE 4 * 1024
-#define LARGE_PAYLOAD_RECV_SIZE        100
+#define HIGH_FD_COUNT          LTTCOMM_MAX_SEND_FDS
+#define MESSAGE_COUNT          4
+#define LARGE_PAYLOAD_SIZE     (4 * 1024)
+#define LARGE_PAYLOAD_RECV_SIZE 100
 
 static const int TEST_COUNT = 37;
 
@@ -40,7 +42,7 @@ int lttng_opt_mi;
  */
 static void test_high_fd_count(unsigned int fd_count)
 {
-       int sockets[2] = {-1, -1};
+       int sockets[2] = { -1, -1 };
        int ret;
        unsigned int i;
        const unsigned int payload_content = 42;
@@ -59,8 +61,8 @@ static void test_high_fd_count(unsigned int fd_count)
        }
 
        /* Add dummy content to payload. */
-       ret = lttng_dynamic_buffer_append(&sent_payload.buffer,
-                       &payload_content, sizeof(payload_content));
+       ret = lttng_dynamic_buffer_append(
+               &sent_payload.buffer, &payload_content, sizeof(payload_content));
        if (ret) {
                PERROR("Failed to initialize test payload");
                goto error;
@@ -94,29 +96,30 @@ static void test_high_fd_count(unsigned int fd_count)
        /* Send payload. */
        {
                ssize_t sock_ret;
-               struct lttng_payload_view pv = lttng_payload_view_from_payload(
-                               &sent_payload, 0, -1);
+               struct lttng_payload_view pv =
+                       lttng_payload_view_from_payload(&sent_payload, 0, -1);
 
                /* Not expected to block considering the size of the payload. */
-               sock_ret = lttcomm_send_unix_sock(
-                               sockets[0], pv.buffer.data, pv.buffer.size);
+               sock_ret = lttcomm_send_unix_sock(sockets[0], pv.buffer.data, pv.buffer.size);
                ok(sock_ret == pv.buffer.size, "Sent complete test payload");
                if (sock_ret != pv.buffer.size) {
                        ERR("Failed to send test payload bytes: ret = %zd, expected = %zu",
-                                       sock_ret, pv.buffer.size);
+                           sock_ret,
+                           pv.buffer.size);
                        goto error;
                }
 
-               sock_ret = lttcomm_send_payload_view_fds_unix_sock(
-                               sockets[0], &pv);
+               sock_ret = lttcomm_send_payload_view_fds_unix_sock(sockets[0], &pv);
                ok(sock_ret == 1, "Sent test payload file descriptors");
                if (sock_ret != 1) {
                        if (sock_ret < 0) {
                                PERROR("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                               sock_ret, 1);
+                                      sock_ret,
+                                      1);
                        } else {
                                diag("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                               sock_ret, 1);
+                                    sock_ret,
+                                    1);
                        }
 
                        goto error;
@@ -128,45 +131,40 @@ static void test_high_fd_count(unsigned int fd_count)
                ssize_t sock_ret;
 
                ret = lttng_dynamic_buffer_set_size(&received_payload.buffer,
-                               sent_payload.buffer.size);
+                                                   sent_payload.buffer.size);
                if (ret) {
                        PERROR("Failed to pre-allocate reception buffer");
                        goto error;
                }
 
-               sock_ret = lttcomm_recv_unix_sock(sockets[1],
-                               received_payload.buffer.data,
-                               received_payload.buffer.size);
-               ok(sock_ret == received_payload.buffer.size,
-                               "Received payload bytes");
+               sock_ret = lttcomm_recv_unix_sock(
+                       sockets[1], received_payload.buffer.data, received_payload.buffer.size);
+               ok(sock_ret == received_payload.buffer.size, "Received payload bytes");
                if (sock_ret != received_payload.buffer.size) {
                        ERR("Failed to receive payload bytes: ret = %zd, expected = %zu",
-                                       sock_ret, received_payload.buffer.size);
+                           sock_ret,
+                           received_payload.buffer.size);
                        goto error;
                }
 
-               sock_ret = lttcomm_recv_payload_fds_unix_sock(
-                               sockets[1], fd_count, &received_payload);
+               sock_ret =
+                       lttcomm_recv_payload_fds_unix_sock(sockets[1], fd_count, &received_payload);
                ok(sock_ret == (int) (sizeof(int) * fd_count),
-                               "FD reception return value is number of fd * sizeof(int)");
+                  "FD reception return value is number of fd * sizeof(int)");
                if (sock_ret != (int) (sizeof(int) * fd_count)) {
                        ERR("Failed to receive test payload file descriptors: ret = %zd, expected = %d",
-                                       sock_ret,
-                                       (int) (fd_count * sizeof(int)));
+                           sock_ret,
+                           (int) (fd_count * sizeof(int)));
                        goto error;
                }
 
                {
                        const struct lttng_payload_view pv =
-                                       lttng_payload_view_from_payload(
-                                                       &received_payload, 0,
-                                                       -1);
-                       const int fd_handle_count =
-                                       lttng_payload_view_get_fd_handle_count(
-                                                       &pv);
+                               lttng_payload_view_from_payload(&received_payload, 0, -1);
+                       const int fd_handle_count = lttng_payload_view_get_fd_handle_count(&pv);
 
                        ok(fd_handle_count == fd_count,
-                                       "Received all test payload file descriptors in one invocation");
+                          "Received all test payload file descriptors in one invocation");
                }
        }
 
@@ -193,14 +191,13 @@ error:
 static void test_one_fd_per_message(unsigned int message_count)
 {
        const unsigned int payload_content = 42;
-       int sockets[2] = {-1, -1};
+       int sockets[2] = { -1, -1 };
        int ret;
        unsigned int i;
        struct lttng_payload sent_payload;
        struct lttng_payload received_payload;
 
-       diag("Send and receive small messages with one FD each (%u messages)",
-                       message_count);
+       diag("Send and receive small messages with one FD each (%u messages)", message_count);
        lttng_payload_init(&sent_payload);
        lttng_payload_init(&received_payload);
 
@@ -217,8 +214,8 @@ static void test_one_fd_per_message(unsigned int message_count)
                int fd;
 
                /* Add dummy content to payload. */
-               ret = lttng_dynamic_buffer_append(&sent_payload.buffer,
-                               &payload_content, sizeof(payload_content));
+               ret = lttng_dynamic_buffer_append(
+                       &sent_payload.buffer, &payload_content, sizeof(payload_content));
                if (ret) {
                        PERROR("Failed to initialize test payload");
                        goto error;
@@ -249,34 +246,31 @@ static void test_one_fd_per_message(unsigned int message_count)
                {
                        ssize_t sock_ret;
                        struct lttng_payload_view pv =
-                                       lttng_payload_view_from_payload(
-                                                       &sent_payload, 0, -1);
+                               lttng_payload_view_from_payload(&sent_payload, 0, -1);
 
                        /* Not expected to block considering the size of the
                         * payload. */
-                       sock_ret = lttcomm_send_unix_sock(sockets[0],
-                                       pv.buffer.data, pv.buffer.size);
-                       ok(sock_ret == pv.buffer.size,
-                                       "Sent binary payload for message %u",
-                                       i);
+                       sock_ret =
+                               lttcomm_send_unix_sock(sockets[0], pv.buffer.data, pv.buffer.size);
+                       ok(sock_ret == pv.buffer.size, "Sent binary payload for message %u", i);
                        if (sock_ret != pv.buffer.size) {
                                ERR("Failed to send test payload bytes: ret = %zd, expected = %zu",
-                                               sock_ret, pv.buffer.size);
+                                   sock_ret,
+                                   pv.buffer.size);
                                goto error;
                        }
 
-                       sock_ret = lttcomm_send_payload_view_fds_unix_sock(
-                                       sockets[0], &pv);
-                       ok(sock_ret == 1,
-                                       "Sent file descriptors payload for message %u",
-                                       i);
+                       sock_ret = lttcomm_send_payload_view_fds_unix_sock(sockets[0], &pv);
+                       ok(sock_ret == 1, "Sent file descriptors payload for message %u", i);
                        if (sock_ret != 1) {
                                if (sock_ret < 0) {
                                        PERROR("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                                       sock_ret, 1);
+                                              sock_ret,
+                                              1);
                                } else {
                                        diag("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                                       sock_ret, 1);
+                                            sock_ret,
+                                            1);
                                }
 
                                goto error;
@@ -291,45 +285,39 @@ static void test_one_fd_per_message(unsigned int message_count)
                ssize_t sock_ret;
 
                ret = lttng_dynamic_buffer_set_size(&received_payload.buffer,
-                               sizeof(payload_content));
+                                                   sizeof(payload_content));
                if (ret) {
                        PERROR("Failed to pre-allocate reception buffer");
                        goto error;
                }
 
-               sock_ret = lttcomm_recv_unix_sock(sockets[1],
-                               received_payload.buffer.data,
-                               received_payload.buffer.size);
+               sock_ret = lttcomm_recv_unix_sock(
+                       sockets[1], received_payload.buffer.data, received_payload.buffer.size);
                ok(sock_ret == received_payload.buffer.size,
-                               "Received payload bytes for message %u", i);
+                  "Received payload bytes for message %u",
+                  i);
                if (sock_ret != received_payload.buffer.size) {
                        ERR("Failed to receive payload bytes: ret = %zd, expected = %zu",
-                                       sock_ret, received_payload.buffer.size);
+                           sock_ret,
+                           received_payload.buffer.size);
                        goto error;
                }
 
-               sock_ret = lttcomm_recv_payload_fds_unix_sock(
-                               sockets[1], 1, &received_payload);
-               ok(sock_ret == (int) sizeof(int), "Received fd for message %u",
-                               i);
+               sock_ret = lttcomm_recv_payload_fds_unix_sock(sockets[1], 1, &received_payload);
+               ok(sock_ret == (int) sizeof(int), "Received fd for message %u", i);
                if (sock_ret != (int) sizeof(int)) {
                        ERR("Failed to receive test payload file descriptors: ret = %zd, expected = %u",
-                                       sock_ret, (int) sizeof(int));
+                           sock_ret,
+                           (int) sizeof(int));
                        goto error;
                }
 
                {
                        const struct lttng_payload_view pv =
-                                       lttng_payload_view_from_payload(
-                                                       &received_payload, 0,
-                                                       -1);
-                       const int fd_handle_count =
-                                       lttng_payload_view_get_fd_handle_count(
-                                                       &pv);
+                               lttng_payload_view_from_payload(&received_payload, 0, -1);
+                       const int fd_handle_count = lttng_payload_view_get_fd_handle_count(&pv);
 
-                       ok(fd_handle_count == 1,
-                                       "Payload contains 1 fd for message %u",
-                                       i);
+                       ok(fd_handle_count == 1, "Payload contains 1 fd for message %u", i);
                }
 
                lttng_payload_clear(&received_payload);
@@ -353,10 +341,9 @@ error:
 /*
  * Validate that a large message can be received in multiple chunks.
  */
-static void test_receive_in_chunks(
-               unsigned int payload_size, unsigned int max_recv_size)
+static void test_receive_in_chunks(unsigned int payload_size, unsigned int max_recv_size)
 {
-       int sockets[2] = {-1, -1};
+       int sockets[2] = { -1, -1 };
        int ret;
        unsigned int i;
        struct lttng_payload sent_payload;
@@ -406,29 +393,30 @@ static void test_receive_in_chunks(
 
        /* Send payload. */
        {
-               struct lttng_payload_view pv = lttng_payload_view_from_payload(
-                               &sent_payload, 0, -1);
+               struct lttng_payload_view pv =
+                       lttng_payload_view_from_payload(&sent_payload, 0, -1);
 
                /* Not expected to block considering the size of the payload. */
-               sock_ret = lttcomm_send_unix_sock(
-                               sockets[0], pv.buffer.data, pv.buffer.size);
+               sock_ret = lttcomm_send_unix_sock(sockets[0], pv.buffer.data, pv.buffer.size);
                ok(sock_ret == pv.buffer.size, "Sent complete test payload");
                if (sock_ret != pv.buffer.size) {
                        ERR("Failed to send test payload bytes: ret = %zd, expected = %zu",
-                                       sock_ret, pv.buffer.size);
+                           sock_ret,
+                           pv.buffer.size);
                        goto error;
                }
 
-               sock_ret = lttcomm_send_payload_view_fds_unix_sock(
-                               sockets[0], &pv);
+               sock_ret = lttcomm_send_payload_view_fds_unix_sock(sockets[0], &pv);
                ok(sock_ret == 1, "Sent test payload file descriptors");
                if (sock_ret != 1) {
                        if (sock_ret < 0) {
                                PERROR("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                               sock_ret, 1);
+                                      sock_ret,
+                                      1);
                        } else {
                                diag("Failed to send test payload file descriptors: ret = %zd, expected = %d",
-                                               sock_ret, 1);
+                                    sock_ret,
+                                    1);
                        }
 
                        goto error;
@@ -436,8 +424,7 @@ static void test_receive_in_chunks(
        }
 
        /* Receive payload */
-       ret = lttng_dynamic_buffer_set_size(
-                       &received_payload.buffer, sent_payload.buffer.size);
+       ret = lttng_dynamic_buffer_set_size(&received_payload.buffer, sent_payload.buffer.size);
        if (ret) {
                PERROR("Failed to pre-allocate reception buffer");
                goto error;
@@ -445,15 +432,14 @@ static void test_receive_in_chunks(
 
        do {
                const ssize_t to_receive_this_pass =
-                       std::min<ssize_t>(max_recv_size,
-                               sent_payload.buffer.size - received);
+                       std::min<ssize_t>(max_recv_size, sent_payload.buffer.size - received);
 
-               sock_ret = lttcomm_recv_unix_sock(sockets[1],
-                               received_payload.buffer.data + received,
-                               to_receive_this_pass);
+               sock_ret = lttcomm_recv_unix_sock(
+                       sockets[1], received_payload.buffer.data + received, to_receive_this_pass);
                if (sock_ret != to_receive_this_pass) {
                        ERR("Failed to receive payload bytes: ret = %zd, expected = %zu",
-                                       sock_ret, to_receive_this_pass);
+                           sock_ret,
+                           to_receive_this_pass);
                        break;
                }
 
@@ -461,31 +447,28 @@ static void test_receive_in_chunks(
        } while (received < sent_payload.buffer.size);
 
        ok(received == sent_payload.buffer.size,
-                       "Received complete payload in chunks of %u bytes",
-                       max_recv_size);
+          "Received complete payload in chunks of %u bytes",
+          max_recv_size);
        if (received != sent_payload.buffer.size) {
                goto error;
        }
 
-       sock_ret = lttcomm_recv_payload_fds_unix_sock(
-                       sockets[1], 1, &received_payload);
+       sock_ret = lttcomm_recv_payload_fds_unix_sock(sockets[1], 1, &received_payload);
        ok(sock_ret == (int) sizeof(int),
-                       "Received file descriptor after receiving payload in chunks");
+          "Received file descriptor after receiving payload in chunks");
        if (sock_ret != (int) sizeof(int)) {
                ERR("Failed to receive test payload file descriptors: ret = %zd, expected = %d",
-                               sock_ret, (int) sizeof(int));
+                   sock_ret,
+                   (int) sizeof(int));
                goto error;
        }
 
        {
                const struct lttng_payload_view pv =
-                               lttng_payload_view_from_payload(
-                                               &received_payload, 0, -1);
-               const int fd_handle_count =
-                               lttng_payload_view_get_fd_handle_count(&pv);
+                       lttng_payload_view_from_payload(&received_payload, 0, -1);
+               const int fd_handle_count = lttng_payload_view_get_fd_handle_count(&pv);
 
-               ok(fd_handle_count == 1,
-                               "Payload contains 1 fd after receiving payload in chunks");
+               ok(fd_handle_count == 1, "Payload contains 1 fd after receiving payload in chunks");
        }
 
 error:
@@ -503,8 +486,7 @@ error:
        lttng_payload_reset(&received_payload);
 }
 
-static
-void test_creds_passing(void)
+static void test_creds_passing()
 {
        pid_t fork_ret = -1;
        int ret, parent_socket = -1, child_connection_socket = -1;
@@ -524,10 +506,8 @@ void test_creds_passing(void)
                goto error;
        }
 
-       strncat(socket_path, socket_dir_path,
-                       sizeof(socket_path) - strlen(socket_path) - 1);
-       strncat(socket_path, "/test_unix_socket",
-                       sizeof(socket_path) - strlen(socket_path) - 1);
+       strncat(socket_path, socket_dir_path, sizeof(socket_path) - strlen(socket_path) - 1);
+       strncat(socket_path, "/test_unix_socket", sizeof(socket_path) - strlen(socket_path) - 1);
 
        parent_socket = lttcomm_create_unix_sock(socket_path);
        ok(parent_socket >= 0, "Created unix socket at path `%s`", socket_path);
@@ -575,8 +555,8 @@ void test_creds_passing(void)
                        PERROR("Failed to set SO_PASSCRED on child socket");
                }
 
-               sock_ret = lttcomm_send_creds_unix_sock(child_socket, &expected_creds,
-                               sizeof(expected_creds));
+               sock_ret = lttcomm_send_creds_unix_sock(
+                       child_socket, &expected_creds, sizeof(expected_creds));
                if (sock_ret < 0) {
                        PERROR("Failed to send expected credentials");
                }
@@ -591,23 +571,22 @@ void test_creds_passing(void)
                pid_t wait_pid_ret;
                lttng_sock_cred received_creds = {};
 
-               child_connection_socket =
-                               lttcomm_accept_unix_sock(parent_socket);
+               child_connection_socket = lttcomm_accept_unix_sock(parent_socket);
                if (child_connection_socket < 0) {
                        PERROR();
                        goto error;
                }
 
-               ret = lttcomm_setsockopt_creds_unix_sock(
-                               child_connection_socket);
+               ret = lttcomm_setsockopt_creds_unix_sock(child_connection_socket);
                if (ret) {
                        PERROR("Failed to set SO_PASSCRED on child connection socket");
                        goto error;
                }
 
                sock_ret = lttcomm_recv_creds_unix_sock(child_connection_socket,
-                               &expected_creds, sizeof(expected_creds),
-                               &received_creds);
+                                                       &expected_creds,
+                                                       sizeof(expected_creds),
+                                                       &received_creds);
                if (sock_ret < 0) {
                        PERROR("Failed to receive credentials");
                        goto error;
@@ -624,14 +603,17 @@ void test_creds_passing(void)
                }
 
                ok(expected_creds.euid == received_creds.uid,
-                               "Received the expected effective uid (%d == %d)",
-                               expected_creds.euid, received_creds.uid);
+                  "Received the expected effective uid (%d == %d)",
+                  expected_creds.euid,
+                  received_creds.uid);
                ok(expected_creds.egid == received_creds.gid,
-                               "Received the expected effective gid (%d == %d)",
-                               expected_creds.egid, received_creds.gid);
+                  "Received the expected effective gid (%d == %d)",
+                  expected_creds.egid,
+                  received_creds.gid);
                ok(expected_creds.pid == received_creds.pid,
-                               "Received the expected pid (%d == %d)",
-                               expected_creds.pid, received_creds.pid);
+                  "Received the expected pid (%d == %d)",
+                  expected_creds.pid,
+                  received_creds.pid);
        }
 
 error:
@@ -659,19 +641,17 @@ error:
 
                ret = unlink(socket_path);
                if (ret) {
-                       PERROR("Failed to unlink socket at path `%s`",
-                                       socket_path);
+                       PERROR("Failed to unlink socket at path `%s`", socket_path);
                }
 
                ret = rmdir(socket_dir_path);
                if (ret) {
-                       PERROR("Failed to remove test directory at `%s`",
-                                       socket_dir_path);
+                       PERROR("Failed to remove test directory at `%s`", socket_dir_path);
                }
        }
 }
 
-int main(void)
+int main()
 {
        plan_tests(TEST_COUNT);
 
index e89396e34ed28ebd7fa047221177d5492e953cb4..41c74203dd035d263b4750c8f845c9f5a6c17ff5 100644 (file)
@@ -5,12 +5,11 @@
  *
  */
 
-#include <string.h>
+#include <common/uri.hpp>
 
+#include <string.h>
 #include <tap/tap.h>
 
-#include <common/uri.hpp>
-
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose = 3;
@@ -19,160 +18,119 @@ int lttng_opt_mi;
 /* Number of TAP tests in this file */
 #define NUM_TESTS 11
 
-static void test_uri_parsing(void)
+static void test_uri_parsing()
 {
        ssize_t size;
        const char *s_uri1;
-       struct lttng_uri *uri = NULL;
+       struct lttng_uri *uri = nullptr;
 
        s_uri1 = "net://localhost";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 2 &&
-          uri[0].dtype == LTTNG_DST_IPV4 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 0 &&
-          strlen(uri[0].subdir) == 0 &&
-          strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 &&
-          uri[1].dtype == LTTNG_DST_IPV4 &&
-          uri[1].utype == LTTNG_URI_DST &&
-          uri[1].stype == 0 &&
-          uri[1].port == 0 &&
-          strlen(uri[1].subdir) == 0 &&
-          strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
+       ok(size == 2 && uri[0].dtype == LTTNG_DST_IPV4 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 0 && strlen(uri[0].subdir) == 0 &&
+                  strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 && uri[1].dtype == LTTNG_DST_IPV4 &&
+                  uri[1].utype == LTTNG_URI_DST && uri[1].stype == 0 && uri[1].port == 0 &&
+                  strlen(uri[1].subdir) == 0 && strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
           "URI set to net://localhost");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "net://localhost:8989:4242/my/test/path";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 2 &&
-          uri[0].dtype == LTTNG_DST_IPV4 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 8989 &&
-          strcmp(uri[0].subdir, "my/test/path") == 0 &&
-          strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 &&
-          uri[1].dtype == LTTNG_DST_IPV4 &&
-          uri[1].utype == LTTNG_URI_DST &&
-          uri[1].stype == 0 &&
-          uri[1].port == 4242 &&
-          strlen(uri[1].subdir) == 0 &&
-          strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
+       ok(size == 2 && uri[0].dtype == LTTNG_DST_IPV4 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 8989 &&
+                  strcmp(uri[0].subdir, "my/test/path") == 0 &&
+                  strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 && uri[1].dtype == LTTNG_DST_IPV4 &&
+                  uri[1].utype == LTTNG_URI_DST && uri[1].stype == 0 && uri[1].port == 4242 &&
+                  strlen(uri[1].subdir) == 0 && strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
           "URI set to net://localhost:8989:4242/my/test/path");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "net://localhost:8989:4242";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 2 &&
-          uri[0].dtype == LTTNG_DST_IPV4 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 8989 &&
-          strlen(uri[0].subdir) == 0 &&
-          strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 &&
-          uri[1].dtype == LTTNG_DST_IPV4 &&
-          uri[1].utype == LTTNG_URI_DST &&
-          uri[1].stype == 0 &&
-          uri[1].port == 4242 &&
-          strlen(uri[1].subdir) == 0 &&
-          strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
+       ok(size == 2 && uri[0].dtype == LTTNG_DST_IPV4 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 8989 && strlen(uri[0].subdir) == 0 &&
+                  strcmp(uri[0].dst.ipv4, "127.0.0.1") == 0 && uri[1].dtype == LTTNG_DST_IPV4 &&
+                  uri[1].utype == LTTNG_URI_DST && uri[1].stype == 0 && uri[1].port == 4242 &&
+                  strlen(uri[1].subdir) == 0 && strcmp(uri[1].dst.ipv4, "127.0.0.1") == 0,
           "URI set to net://localhost:8989:4242");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "net6://[::1]:8989";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 2 &&
-          uri[0].dtype == LTTNG_DST_IPV6 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 8989 &&
-          strlen(uri[0].subdir) == 0 &&
-          strcmp(uri[0].dst.ipv6, "::1") == 0 &&
-          uri[1].dtype == LTTNG_DST_IPV6 &&
-          uri[1].utype == LTTNG_URI_DST &&
-          uri[1].stype == 0 &&
-          uri[1].port == 0 &&
-          strlen(uri[1].subdir) == 0 &&
-          strcmp(uri[1].dst.ipv6, "::1") == 0,
+       ok(size == 2 && uri[0].dtype == LTTNG_DST_IPV6 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 8989 && strlen(uri[0].subdir) == 0 &&
+                  strcmp(uri[0].dst.ipv6, "::1") == 0 && uri[1].dtype == LTTNG_DST_IPV6 &&
+                  uri[1].utype == LTTNG_URI_DST && uri[1].stype == 0 && uri[1].port == 0 &&
+                  strlen(uri[1].subdir) == 0 && strcmp(uri[1].dst.ipv6, "::1") == 0,
           "URI set to net6://[::1]:8989");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "tcp://42.42.42.42/my/test/path";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 1 &&
-          uri[0].dtype == LTTNG_DST_IPV4 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 0 &&
-          strcmp(uri[0].subdir, "my/test/path") == 0 &&
-          strcmp(uri[0].dst.ipv4, "42.42.42.42") == 0,
+       ok(size == 1 && uri[0].dtype == LTTNG_DST_IPV4 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 0 &&
+                  strcmp(uri[0].subdir, "my/test/path") == 0 &&
+                  strcmp(uri[0].dst.ipv4, "42.42.42.42") == 0,
           "URI set to tcp://42.42.42.42/my/test/path");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "tcp6://[fe80::f66d:4ff:fe53:d220]/my/test/path";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 1 &&
-          uri[0].dtype == LTTNG_DST_IPV6 &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 0 &&
-          strcmp(uri[0].subdir, "my/test/path") == 0 &&
-          strcmp(uri[0].dst.ipv6, "fe80::f66d:4ff:fe53:d220") == 0,
+       ok(size == 1 && uri[0].dtype == LTTNG_DST_IPV6 && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 0 &&
+                  strcmp(uri[0].subdir, "my/test/path") == 0 &&
+                  strcmp(uri[0].dst.ipv6, "fe80::f66d:4ff:fe53:d220") == 0,
           "URI set to tcp6://[fe80::f66d:4ff:fe53:d220]/my/test/path");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        s_uri1 = "file:///my/test/path";
 
        size = uri_parse(s_uri1, &uri);
 
-       ok(size == 1 &&
-          uri[0].dtype == LTTNG_DST_PATH &&
-          uri[0].utype == LTTNG_URI_DST &&
-          uri[0].stype == 0 &&
-          uri[0].port == 0 &&
-          strlen(uri[0].subdir) == 0 &&
-          strcmp(uri[0].dst.path, "/my/test/path") == 0,
+       ok(size == 1 && uri[0].dtype == LTTNG_DST_PATH && uri[0].utype == LTTNG_URI_DST &&
+                  uri[0].stype == 0 && uri[0].port == 0 && strlen(uri[0].subdir) == 0 &&
+                  strcmp(uri[0].dst.path, "/my/test/path") == 0,
           "URI set to file:///my/test/path");
 
        if (uri) {
                uri_free(uri);
-               uri = NULL;
+               uri = nullptr;
        }
 
        /* FIXME: Noisy on stdout */
@@ -187,7 +145,7 @@ static void test_uri_parsing(void)
        LTTNG_ASSERT(!uri);
 }
 
-static void test_uri_cmp(void)
+static void test_uri_cmp()
 {
        struct lttng_uri *uri1, *uri2;
        const char *s_uri1 = "net://localhost";
@@ -230,19 +188,17 @@ static void test_uri_cmp(void)
 
        res = uri_compare(uri1, uri1);
 
-       ok(res == 0,
-          "URI compare net://localhost == net://localhost");
+       ok(res == 0, "URI compare net://localhost == net://localhost");
 
        res = uri_compare(uri1, uri2);
 
-       ok(res != 0,
-          "URI compare net://localhost != net://localhost:8989:4242");
+       ok(res != 0, "URI compare net://localhost != net://localhost:8989:4242");
 
        uri_free(uri1);
        uri_free(uri2);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
 
index cdd9cbd66dd033a3e6b60486562a6107a6722c4f..ec945a03623b3478529ee3cae44f7241695c6fad 100644 (file)
@@ -5,46 +5,44 @@
  *
  */
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <time.h>
-#include <urcu.h>
+#include <common/compat/errno.hpp>
+#include <common/defaults.hpp>
 
 #include <lttng/lttng.h>
+#include <lttng/ust-sigbus.h>
+
 #include <bin/lttng-sessiond/lttng-ust-abi.hpp>
-#include <common/defaults.hpp>
-#include <common/compat/errno.hpp>
+#include <bin/lttng-sessiond/notification-thread.hpp>
 #include <bin/lttng-sessiond/trace-ust.hpp>
 #include <bin/lttng-sessiond/ust-app.hpp>
-#include <bin/lttng-sessiond/notification-thread.hpp>
-
-#include <lttng/ust-sigbus.h>
-
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <tap/tap.h>
+#include <time.h>
+#include <unistd.h>
+#include <urcu.h>
 
 /* This path will NEVER be created in this test */
 #define PATH1 "/tmp/.test-junk-lttng"
 
-#define RANDOM_STRING_LEN      11
+#define RANDOM_STRING_LEN 11
 
 /* Number of TAP tests in this file */
 #define NUM_TESTS 16
 
 LTTNG_EXPORT DEFINE_LTTNG_UST_SIGBUS_STATE();
 
-static const char alphanum[] =
-       "0123456789"
-       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-       "abcdefghijklmnopqrstuvwxyz";
+static const char alphanum[] = "0123456789"
+                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                              "abcdefghijklmnopqrstuvwxyz";
 static char random_string[RANDOM_STRING_LEN];
 
 /*
  * Return random string of 10 characters.
  * Not thread-safe.
  */
-static char *get_random_string(void)
+static char *get_random_string()
 {
        int i;
 
@@ -57,30 +55,26 @@ static char *get_random_string(void)
        return random_string;
 }
 
-static void test_create_one_ust_session(void)
+static void test_create_one_ust_session()
 {
-       struct ltt_ust_session *usess =
-               trace_ust_create_session(42);
+       struct ltt_ust_session *usess = trace_ust_create_session(42);
 
-       ok(usess != NULL, "Create UST session");
+       ok(usess != nullptr, "Create UST session");
 
        if (!usess) {
                skip(1, "UST session is null");
                return;
        }
 
-       ok(usess->id == 42 &&
-          usess->active == 0 &&
-          usess->domain_global.channels != NULL &&
-          usess->uid == 0 &&
-          usess->gid == 0,
+       ok(usess->id == 42 && !usess->active && usess->domain_global.channels != nullptr &&
+                  usess->uid == 0 && usess->gid == 0,
           "Validate UST session");
 
        trace_ust_destroy_session(usess);
        trace_ust_free_session(usess);
 }
 
-static void test_create_ust_channel(void)
+static void test_create_ust_channel()
 {
        struct ltt_ust_channel *uchan;
        struct lttng_channel attr;
@@ -91,40 +85,36 @@ static void test_create_ust_channel(void)
        attr.attr.extended.ptr = &extended;
 
        ok(lttng_strncpy(attr.name, "channel0", sizeof(attr.name)) == 0,
-               "Validate channel name length");
+          "Validate channel name length");
        uchan = trace_ust_create_channel(&attr, LTTNG_DOMAIN_UST);
-       ok(uchan != NULL, "Create UST channel");
+       ok(uchan != nullptr, "Create UST channel");
 
        if (!uchan) {
                skip(1, "UST channel is null");
                return;
        }
 
-       ok(uchan->enabled == 0 &&
-          strncmp(uchan->name, "channel0", 8) == 0 &&
-          uchan->name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0' &&
-          uchan->ctx != NULL &&
-          uchan->events != NULL &&
-          uchan->attr.overwrite  == attr.attr.overwrite,
+       ok(!uchan->enabled && strncmp(uchan->name, "channel0", 8) == 0 &&
+                  uchan->name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0' && uchan->ctx != nullptr &&
+                  uchan->events != nullptr && uchan->attr.overwrite == attr.attr.overwrite,
           "Validate UST channel");
 
        trace_ust_destroy_channel(uchan);
 }
 
-static void test_create_ust_event(void)
+static void test_create_ust_event()
 {
        struct ltt_ust_event *event;
        struct lttng_event ev;
        enum lttng_error_code ret;
 
        memset(&ev, 0, sizeof(ev));
-       ok(lttng_strncpy(ev.name, get_random_string(),
-                       LTTNG_SYMBOL_NAME_LEN) == 0,
-               "Validate string length");
+       ok(lttng_strncpy(ev.name, get_random_string(), LTTNG_SYMBOL_NAME_LEN) == 0,
+          "Validate string length");
        ev.type = LTTNG_EVENT_TRACEPOINT;
        ev.loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
 
-       ret = trace_ust_create_event(&ev, NULL, NULL, NULL, false, &event);
+       ret = trace_ust_create_event(&ev, nullptr, nullptr, nullptr, false, &event);
 
        ok(ret == LTTNG_OK, "Create UST event");
 
@@ -133,16 +123,15 @@ static void test_create_ust_event(void)
                return;
        }
 
-       ok(event->enabled == 0 &&
-          event->attr.instrumentation == LTTNG_UST_ABI_TRACEPOINT &&
-          strcmp(event->attr.name, ev.name) == 0 &&
-          event->attr.name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0',
+       ok(!event->enabled && event->attr.instrumentation == LTTNG_UST_ABI_TRACEPOINT &&
+                  strcmp(event->attr.name, ev.name) == 0 &&
+                  event->attr.name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0',
           "Validate UST event");
 
        trace_ust_destroy_event(event);
 }
 
-static void test_create_ust_event_exclusion(void)
+static void test_create_ust_event_exclusion()
 {
        int copy_ret;
        enum lttng_error_code ret;
@@ -150,8 +139,8 @@ static void test_create_ust_event_exclusion(void)
        struct lttng_event ev;
        char *name;
        char *random_name;
-       struct lttng_event_exclusion *exclusion = NULL;
-       struct lttng_event_exclusion *exclusion_copy = NULL;
+       struct lttng_event_exclusion *exclusion = nullptr;
+       struct lttng_event_exclusion *exclusion_copy = nullptr;
        const int exclusion_count = 2;
 
        memset(&ev, 0, sizeof(ev));
@@ -159,16 +148,15 @@ static void test_create_ust_event_exclusion(void)
        /* make a wildcarded event name */
        name = get_random_string();
        name[strlen(name) - 1] = '*';
-       ok(lttng_strncpy(ev.name, name, LTTNG_SYMBOL_NAME_LEN) == 0,
-               "Validate string length");
+       ok(lttng_strncpy(ev.name, name, LTTNG_SYMBOL_NAME_LEN) == 0, "Validate string length");
 
        ev.type = LTTNG_EVENT_TRACEPOINT;
        ev.loglevel_type = LTTNG_EVENT_LOGLEVEL_ALL;
 
        /* set up an exclusion set */
        exclusion = zmalloc<lttng_event_exclusion>(sizeof(*exclusion) +
-               LTTNG_SYMBOL_NAME_LEN * exclusion_count);
-       ok(exclusion != NULL, "Create UST exclusion");
+                                                  LTTNG_SYMBOL_NAME_LEN * exclusion_count);
+       ok(exclusion != nullptr, "Create UST exclusion");
        if (!exclusion) {
                skip(4, "zmalloc failed");
                goto end;
@@ -176,26 +164,28 @@ static void test_create_ust_event_exclusion(void)
 
        exclusion->count = exclusion_count;
        random_name = get_random_string();
-       strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0), random_name,
+       strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0),
+               random_name,
                LTTNG_SYMBOL_NAME_LEN - 1);
-       strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1), random_name,
+       strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1),
+               random_name,
                LTTNG_SYMBOL_NAME_LEN - 1);
 
-       ret = trace_ust_create_event(&ev, NULL, NULL, exclusion, false, &event);
-       exclusion = NULL;
+       ret = trace_ust_create_event(&ev, nullptr, nullptr, exclusion, false, &event);
+       exclusion = nullptr;
 
        ok(ret != LTTNG_OK, "Create UST event with identical exclusion names fails");
 
        exclusion = zmalloc<lttng_event_exclusion>(sizeof(*exclusion) +
-               LTTNG_SYMBOL_NAME_LEN * exclusion_count);
-       ok(exclusion != NULL, "Create UST exclusion");
+                                                  LTTNG_SYMBOL_NAME_LEN * exclusion_count);
+       ok(exclusion != nullptr, "Create UST exclusion");
        if (!exclusion) {
                skip(2, "zmalloc failed");
                goto end;
        }
 
        exclusion_copy = zmalloc<lttng_event_exclusion>(sizeof(*exclusion) +
-               LTTNG_SYMBOL_NAME_LEN * exclusion_count);
+                                                       LTTNG_SYMBOL_NAME_LEN * exclusion_count);
        if (!exclusion_copy) {
                skip(2, "zmalloc failed");
                goto end;
@@ -209,26 +199,26 @@ static void test_create_ust_event_exclusion(void)
 
        exclusion->count = exclusion_count;
        copy_ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0),
-                       get_random_string(),
-                       sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0)));
+                                get_random_string(),
+                                sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0)));
        LTTNG_ASSERT(copy_ret == 0);
        copy_ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1),
-                       get_random_string(),
-                       sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1)));
+                                get_random_string(),
+                                sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1)));
        LTTNG_ASSERT(copy_ret == 0);
 
        exclusion_copy->count = exclusion_count;
        copy_ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 0),
-                       LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0),
-                       sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 0)));
+                                LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 0),
+                                sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 0)));
        LTTNG_ASSERT(copy_ret == 0);
        copy_ret = lttng_strncpy(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 1),
-                       LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1),
-                       sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 1)));
+                                LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion, 1),
+                                sizeof(LTTNG_EVENT_EXCLUSION_NAME_AT(exclusion_copy, 1)));
        LTTNG_ASSERT(copy_ret == 0);
 
-       ret = trace_ust_create_event(&ev, NULL, NULL, exclusion, false, &event);
-       exclusion = NULL;
+       ret = trace_ust_create_event(&ev, nullptr, nullptr, exclusion, false, &event);
+       exclusion = nullptr;
        ok(ret == LTTNG_OK, "Create UST event with different exclusion names");
 
        if (!event) {
@@ -236,15 +226,14 @@ static void test_create_ust_event_exclusion(void)
                goto end;
        }
 
-       ok(event->enabled == 0 &&
-               event->attr.instrumentation == LTTNG_UST_ABI_TRACEPOINT &&
-               strcmp(event->attr.name, ev.name) == 0 &&
-               event->exclusion != NULL &&
-               event->exclusion->count == exclusion_count &&
-               !memcmp(event->exclusion->names, exclusion_copy->names,
-                       LTTNG_SYMBOL_NAME_LEN * exclusion_count) &&
-               event->attr.name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0',
-               "Validate UST event and exclusion");
+       ok(!event->enabled && event->attr.instrumentation == LTTNG_UST_ABI_TRACEPOINT &&
+                  strcmp(event->attr.name, ev.name) == 0 && event->exclusion != nullptr &&
+                  event->exclusion->count == exclusion_count &&
+                  !memcmp(event->exclusion->names,
+                          exclusion_copy->names,
+                          LTTNG_SYMBOL_NAME_LEN * exclusion_count) &&
+                  event->attr.name[LTTNG_UST_ABI_SYM_NAME_LEN - 1] == '\0',
+          "Validate UST event and exclusion");
 
        trace_ust_destroy_event(event);
 end:
@@ -253,8 +242,7 @@ end:
        return;
 }
 
-
-static void test_create_ust_context(void)
+static void test_create_ust_context()
 {
        struct lttng_event_context ectx;
        struct ltt_ust_context *uctx;
@@ -262,18 +250,17 @@ static void test_create_ust_context(void)
        ectx.ctx = LTTNG_EVENT_CONTEXT_VTID;
 
        uctx = trace_ust_create_context(&ectx);
-       ok(uctx != NULL, "Create UST context");
+       ok(uctx != nullptr, "Create UST context");
 
        if (uctx) {
-               ok((int) uctx->ctx.ctx == LTTNG_UST_ABI_CONTEXT_VTID,
-                  "Validate UST context");
+               ok((int) uctx->ctx.ctx == LTTNG_UST_ABI_CONTEXT_VTID, "Validate UST context");
        } else {
                skip(1, "Skipping UST context validation as creation failed");
        }
        free(uctx);
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
 
index f34ef5d0ea27f7da28484eafcfef21416c6e66b8..6c865b298e975dc73ad5da5f8e02ec85be7f6428 100644 (file)
@@ -9,27 +9,27 @@
  *
  */
 
+#include <common/compat/poll.hpp>
+#include <common/dynamic-array.hpp>
+#include <common/pipe.hpp>
+#include <common/readwrite.hpp>
+
 #include <inttypes.h>
 #include <stdio.h>
 #include <string.h>
-#include <unistd.h>
 #include <sys/types.h>
 #include <sys/wait.h>
-
 #include <tap/tap.h>
-
-#include <common/compat/poll.hpp>
-#include <common/readwrite.hpp>
-#include <common/pipe.hpp>
-#include <common/dynamic-array.hpp>
+#include <unistd.h>
 
 /* Verification without trashing test order in the child process */
-#define childok(e, test, ...) do { \
-       if (!(e)) { \
-               diag(test, ## __VA_ARGS__); \
-               _exit(EXIT_FAILURE); \
-       } \
-} while(0)
+#define childok(e, test, ...)                      \
+       do {                                       \
+               if (!(e)) {                        \
+                       diag(test, ##__VA_ARGS__); \
+                       _exit(EXIT_FAILURE);       \
+               }                                  \
+       } while (0)
 
 /* For error.h */
 int lttng_opt_quiet = 1;
@@ -56,8 +56,7 @@ int lttng_opt_mi;
 #define CLOE_VALUE FD_CLOEXEC
 #endif
 
-static
-void test_epoll_compat(void)
+static void test_epoll_compat()
 {
        /*
         * Type conversion present to disable warning of anonymous enum from
@@ -67,14 +66,14 @@ void test_epoll_compat(void)
 }
 #endif
 
-static void test_alloc(void)
+static void test_alloc()
 {
        struct lttng_poll_event poll_events;
 
        lttng_poll_init(&poll_events);
 
        /* Null pointer */
-       ok(lttng_poll_create(NULL, 1, 0) != 0, "Create over NULL pointer fails");
+       ok(lttng_poll_create(nullptr, 1, 0) != 0, "Create over NULL pointer fails");
        /* Size 0 */
        ok(lttng_poll_create(&poll_events, 0, 0) != 0, "Create with size 0 fails");
        /* without CLOEXEC */
@@ -88,19 +87,20 @@ static void test_alloc(void)
 }
 
 /* Tests stuff related to what would be handled with epoll_ctl. */
-static void test_add_del(void)
+static void test_add_del()
 {
        struct lttng_poll_event poll_events;
 
        lttng_poll_init(&poll_events);
-       ok(lttng_poll_add(NULL, 1, LPOLLIN) != 0, "Adding to NULL set fails");
-       ok(lttng_poll_add(&poll_events, 1, LPOLLIN) != 0, "Adding to uninitialized structure fails");
+       ok(lttng_poll_add(nullptr, 1, LPOLLIN) != 0, "Adding to NULL set fails");
+       ok(lttng_poll_add(&poll_events, 1, LPOLLIN) != 0,
+          "Adding to uninitialized structure fails");
        ok(lttng_poll_add(&poll_events, -1, LPOLLIN) != 0, "Adding invalid FD fails");
 
        ok(lttng_poll_create(&poll_events, 1, 0) == 0, "Create a poll set succeeds");
        ok(LTTNG_POLL_GETNB(&poll_events) == 0, "Set created empty");
 
-       ok(lttng_poll_add(NULL, 1, LPOLLIN) != 0, "Adding to NULL set fails");
+       ok(lttng_poll_add(nullptr, 1, LPOLLIN) != 0, "Adding to NULL set fails");
        ok(LTTNG_POLL_GETNB(&poll_events) == 0, "Set still empty");
        ok(lttng_poll_add(&poll_events, -1, LPOLLIN) != 0, "Adding invalid FD fails");
        ok(LTTNG_POLL_GETNB(&poll_events) == 0, "Set still empty");
@@ -108,7 +108,7 @@ static void test_add_del(void)
        ok(lttng_poll_add(&poll_events, 1, LPOLLIN) == 0, "Adding valid FD succeeds");
        ok(LTTNG_POLL_GETNB(&poll_events) == 1, "Nb of elements incremented");
 
-       ok(lttng_poll_del(NULL, 1) != 0, "Removing from NULL set fails");
+       ok(lttng_poll_del(nullptr, 1) != 0, "Removing from NULL set fails");
        ok(LTTNG_POLL_GETNB(&poll_events) == 1, "Number of FD in set unchanged");
 
        ok(lttng_poll_del(&poll_events, -1) != 0, "Removing from negative FD fails");
@@ -126,7 +126,7 @@ static void test_add_del(void)
        lttng_poll_clean(&poll_events);
 }
 
-static void test_mod_wait(void)
+static void test_mod_wait()
 {
        struct lttng_poll_event poll_events;
        struct lttng_poll_event cpoll_events;
@@ -144,13 +144,20 @@ static void test_mod_wait(void)
 
        cpid = fork();
        if (cpid == 0) {
-               childok(lttng_poll_create(&cpoll_events, 1, 0) == 0, "Create valid poll set succeeds");
-               childok(lttng_poll_mod(NULL, infd[0], LPOLLIN) == -1, "lttng_poll_mod with invalid input returns an error");
-               childok(lttng_poll_mod(&cpoll_events, infd[0], LPOLLIN) == -1, "lttng_poll_mod with invalid input returns an error");
-               childok(lttng_poll_add(&cpoll_events, infd[0], LPOLLHUP) == 0, "Add valid FD succeeds");
-               childok(lttng_poll_mod(&cpoll_events, -1, LPOLLIN) == -1, "lttng_poll_mod with invalid input returns an error");
-               childok(lttng_poll_mod(&cpoll_events, hupfd[0], LPOLLIN) == 0, "lttng_poll_mod on unincluded FD goes on");
-               childok(lttng_poll_mod(&cpoll_events, infd[0], LPOLLIN) == 0, "Modify event type succeeds");
+               childok(lttng_poll_create(&cpoll_events, 1, 0) == 0,
+                       "Create valid poll set succeeds");
+               childok(lttng_poll_mod(nullptr, infd[0], LPOLLIN) == -1,
+                       "lttng_poll_mod with invalid input returns an error");
+               childok(lttng_poll_mod(&cpoll_events, infd[0], LPOLLIN) == -1,
+                       "lttng_poll_mod with invalid input returns an error");
+               childok(lttng_poll_add(&cpoll_events, infd[0], LPOLLIN) == 0,
+                       "Add valid FD succeeds");
+               childok(lttng_poll_mod(&cpoll_events, -1, LPOLLIN) == -1,
+                       "lttng_poll_mod with invalid input returns an error");
+               childok(lttng_poll_mod(&cpoll_events, hupfd[0], LPOLLIN) == 0,
+                       "lttng_poll_mod on unincluded FD goes on");
+               childok(lttng_poll_mod(&cpoll_events, infd[0], LPOLLIN) == 0,
+                       "Modify event type succeeds");
                childok(close(infd[1]) == 0, "Close valid FD succeeds");
                childok(lttng_poll_wait(&cpoll_events, -1) == 1, "Wait on close times out");
                childok(lttng_read(infd[0], &rbuf, 1) == 1, "Data is present in the pipe");
@@ -165,11 +172,13 @@ static void test_mod_wait(void)
                ok(close(hupfd[1]) == 0, "Close valid FD succeeds");
                ok(close(infd[0]) == 0, "Close valid FD succeeds");
 
-               ok(lttng_poll_wait(NULL, -1) == -1, "lttng_poll_wait call with invalid input returns error");
+               ok(lttng_poll_wait(nullptr, -1) == -1,
+                  "lttng_poll_wait call with invalid input returns error");
 
                ok(lttng_poll_create(&poll_events, 1, 0) == 0, "Create valid poll set succeeds");
-               ok(lttng_poll_wait(&poll_events, -1) == -1, "lttng_poll_wait call with invalid input returns error");
-               ok(lttng_poll_add(&poll_events, hupfd[0], LPOLLHUP) == 0, "Add valid FD succeeds");
+               ok(lttng_poll_wait(&poll_events, -1) == -1,
+                  "lttng_poll_wait call with invalid input returns error");
+               ok(lttng_poll_add(&poll_events, hupfd[0], LPOLLIN) == 0, "Add valid FD succeeds");
                ok(lttng_write(infd[1], &tbuf, 1) == 1, "Write to pipe succeeds");
                ok(lttng_poll_wait(&poll_events, -1) == 1, "Wakes up on one event");
                ok(lttng_poll_del(&poll_events, hupfd[0]) == 0, "Removing valid FD succeeds");
@@ -187,23 +196,21 @@ static void destroy_pipe(void *pipe)
        lttng_pipe_destroy((lttng_pipe *) pipe);
 }
 
-static int run_active_set_combination(unsigned int fd_count,
-               unsigned int active_fds_mask)
+static int run_active_set_combination(unsigned int fd_count, unsigned int active_fds_mask)
 {
        int ret = 0;
        unsigned int i;
        const unsigned int active_fds_count = __builtin_popcount(active_fds_mask);
        struct lttng_poll_event poll_events;
        struct lttng_dynamic_pointer_array pipes;
-       struct lttng_pipe *pipe = NULL;
+       struct lttng_pipe *pipe = nullptr;
 
        lttng_poll_init(&poll_events);
        lttng_dynamic_pointer_array_init(&pipes, destroy_pipe);
 
        ret = lttng_poll_create(&poll_events, fd_count, 0);
        if (ret) {
-               diag("Failed to create poll set for %u file descriptors",
-                               fd_count);
+               diag("Failed to create poll set for %u file descriptors", fd_count);
                goto end;
        }
 
@@ -216,8 +223,7 @@ static int run_active_set_combination(unsigned int fd_count,
                        goto end;
                }
 
-               ret = lttng_poll_add(&poll_events, lttng_pipe_get_readfd(pipe),
-                               LPOLLIN);
+               ret = lttng_poll_add(&poll_events, lttng_pipe_get_readfd(pipe), LPOLLIN);
                if (ret) {
                        diag("Failed to add file descriptor to poll set");
                        ret = -1;
@@ -232,7 +238,7 @@ static int run_active_set_combination(unsigned int fd_count,
                }
 
                /* Ownership transferred to the pointer array. */
-               pipe = NULL;
+               pipe = nullptr;
        }
 
        /* Write one byte for all active fds that should be active. */
@@ -244,13 +250,10 @@ static int run_active_set_combination(unsigned int fd_count,
                        continue;
                }
 
-               borrowed_pipe =
-                       (lttng_pipe *) lttng_dynamic_pointer_array_get_pointer(
-                               &pipes, i);
+               borrowed_pipe = (lttng_pipe *) lttng_dynamic_pointer_array_get_pointer(&pipes, i);
 
                char c = 'a';
-               ret = lttng_pipe_write(
-                       borrowed_pipe, &c, sizeof(char));
+               ret = lttng_pipe_write(borrowed_pipe, &c, sizeof(char));
                if (ret != sizeof(char)) {
                        diag("Failed to write to pipe");
                        ret = -1;
@@ -261,7 +264,8 @@ static int run_active_set_combination(unsigned int fd_count,
        ret = lttng_poll_wait(&poll_events, 0);
        if (ret != active_fds_count) {
                diag("lttng_poll_wait returned %d, expected %u active file descriptors",
-                               ret, active_fds_count);
+                    ret,
+                    active_fds_count);
                ret = -1;
                goto end;
        } else {
@@ -301,7 +305,7 @@ fail:
        fail("Test all combinations of active file descriptors for %u file descriptors", fd_count);
 }
 
-static void test_func_def(void)
+static void test_func_def()
 {
 #ifdef LTTNG_POLL_GETFD
 #define PASS_GETFD 1
@@ -328,14 +332,14 @@ static void test_func_def(void)
 #endif
 
        ok(lttng_poll_reset == lttng_poll_reset, "lttng_poll_reset is defined");
-       ok(lttng_poll_init == lttng_poll_init , "lttng_poll_init is defined");
+       ok(lttng_poll_init == lttng_poll_init, "lttng_poll_init is defined");
        ok(PASS_GETFD, "GETFD is defined");
        ok(PASS_GETEV, "GETEV is defined");
        ok(PASS_GETSZ, "GETSZ is defined");
        ok(PASS_GET_PREV_FD, "GET_PREV_FD is defined");
 }
 
-int main(void)
+int main()
 {
        plan_tests(NUM_TESTS);
 #ifdef HAVE_EPOLL
index 55e584b8bc9b34745a074e3f73732c1f2e3c5259..db39d49b7ce5544d8d995df582c4dc87ed54c678 100644 (file)
@@ -5,15 +5,15 @@
  *
  */
 
-#include <stdio.h>
-#include <string.h>
 #include "common/compat/pthread.hpp"
 
+#include <stdio.h>
+#include <string.h>
 #include <tap/tap.h>
 
 #define TEST_NAME_PROPER_LEN 16
 
-int main(void)
+int main()
 {
        int ret;
        char name1[TEST_NAME_PROPER_LEN];
@@ -44,8 +44,10 @@ int main(void)
        /* Get the thread name again, should be the one we set */
        ret = lttng_pthread_getname_np(name1, TEST_NAME_PROPER_LEN);
        ok(ret == 0, "Get a short thread name: '%s'", name1);
-       ok(strcmp(short_name, name1) == 0, "Compare the short thread name: '%s' == '%s'", short_name, name1);
-
+       ok(strcmp(short_name, name1) == 0,
+          "Compare the short thread name: '%s' == '%s'",
+          short_name,
+          name1);
 
        /* Set a thread name of 16 bytes */
        ret = lttng_pthread_setname_np(long_name);
@@ -54,7 +56,10 @@ int main(void)
        /* Get the thread name again, should be the one we set */
        ret = lttng_pthread_getname_np(name1, TEST_NAME_PROPER_LEN);
        ok(ret == 0, "Get a long thread name: '%s'", name1);
-       ok(strncmp(long_name, name1, TEST_NAME_PROPER_LEN - 1) == 0, "Compare the long thread name: '%s' == '%s'", long_name, name1);
+       ok(strncmp(long_name, name1, TEST_NAME_PROPER_LEN - 1) == 0,
+          "Compare the long thread name: '%s' == '%s'",
+          long_name,
+          name1);
 
        return exit_status();
 }
index 9892727bad86f7e615e9a644c43236cb78208191..8809448caf5b62e781e352efe169916a5394c9c2 100644 (file)
@@ -5,20 +5,18 @@
  *
  */
 
-#include <string.h>
+#include <common/common.hpp>
+#include <common/path.hpp>
+#include <common/utils.hpp>
+
+#include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <limits.h>
-
+#include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-
 #include <tap/tap.h>
 
-#include <common/utils.hpp>
-#include <common/path.hpp>
-#include <common/common.hpp>
-
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose = 3;
@@ -43,89 +41,76 @@ struct symlink_test_input {
 
 /* Valid test cases */
 struct valid_test_input valid_tests_inputs[] = {
-       { "/a/b/c/d/e",                 "",             "/a/b/c/d/e"    },
-       { "/a//b//c/d/e",               "",             "/a/b/c/d/e"    },
-       { "./a/b/c/d/e",                ".",            "/a/b/c/d/e"    },
-       { "../a/b/c/d/../e",            "..",           "/a/b/c/e"      },
-       { ".././a/b/c/d/./e",           "..",           "/a/b/c/d/e"    },
-       { "../../a/b/c/d/e",            "../..",        "/a/b/c/d/e"    },
-       { "./a/b/../c/d/../e",          ".",            "/a/c/e"        },
-       { "../a/b/../../c/./d/./e",     "..",           "/c/d/e"        },
-       { "../../a/b/../c/d/../../e",   "../..",        "/a/e"          },
-       { "./a/b/c/d/../../../../e",    ".",            "/e"            },
-       { ".././a/b/c/d/./e",           "..",           "/a/b/c/d/e"    },
-       { "a/",                         ".",            "/a/"           },
-       { "a",                          ".",            "/a"            },
-       { "../../",                     "../..",        "/"             },
-       { "../..",                      "../..",        ""              },
-       { "../",                        "..",           "/"             },
-       { "..",                         "..",           ""              },
-       { "./",                         ".",            "/"             },
-       { ".",                          ".",            ""              },
-       { "/../a/b/c/d/e",              "",             "/a/b/c/d/e"    },
-       { "/a/b/c/d/../../../../../e",  "",             "/e"            },
-       { "/..",                        "",             "/"             },
-       { "/a/..",                      "",             "/"             },
+       { "/a/b/c/d/e", "", "/a/b/c/d/e" },
+       { "/a//b//c/d/e", "", "/a/b/c/d/e" },
+       { "./a/b/c/d/e", ".", "/a/b/c/d/e" },
+       { "../a/b/c/d/../e", "..", "/a/b/c/e" },
+       { ".././a/b/c/d/./e", "..", "/a/b/c/d/e" },
+       { "../../a/b/c/d/e", "../..", "/a/b/c/d/e" },
+       { "./a/b/../c/d/../e", ".", "/a/c/e" },
+       { "../a/b/../../c/./d/./e", "..", "/c/d/e" },
+       { "../../a/b/../c/d/../../e", "../..", "/a/e" },
+       { "./a/b/c/d/../../../../e", ".", "/e" },
+       { ".././a/b/c/d/./e", "..", "/a/b/c/d/e" },
+       { "a/", ".", "/a/" },
+       { "a", ".", "/a" },
+       { "../../", "../..", "/" },
+       { "../..", "../..", "" },
+       { "../", "..", "/" },
+       { "..", "..", "" },
+       { "./", ".", "/" },
+       { ".", ".", "" },
+       { "/../a/b/c/d/e", "", "/a/b/c/d/e" },
+       { "/a/b/c/d/../../../../../e", "", "/e" },
+       { "/..", "", "/" },
+       { "/a/..", "", "/" },
 };
 char **valid_tests_expected_results;
-const int num_valid_tests =
-               sizeof(valid_tests_inputs) / sizeof(valid_tests_inputs[0]);
+const int num_valid_tests = sizeof(valid_tests_inputs) / sizeof(valid_tests_inputs[0]);
 
 /* Symlinks test cases */
 char tree_origin[] = "/tmp/test_utils_expand_path.XXXXXX";
 
-const char * const tree_dirs[] = {
+const char *const tree_dirs[] = {
        "a",
        "a/b",
        "a/b/c",
        "a/e",
 };
-const int num_tree_dirs =
-               sizeof(tree_dirs) / sizeof(tree_dirs[0]);
+const int num_tree_dirs = sizeof(tree_dirs) / sizeof(tree_dirs[0]);
 
 struct tree_symlink tree_symlinks[] = {
-       { "a/d",                        "b/c/"          },
-       { "a/g",                        "d/"            },
-       { "a/b/f",                      "../e/"         },
-       { "a/b/h",                      "../g/"         },
-       { "a/b/k",                      "c/g/"          },
-       { "a/b/c/g",                    "../../../"     },
+       { "a/d", "b/c/" },    { "a/g", "d/" },     { "a/b/f", "../e/" },
+       { "a/b/h", "../g/" }, { "a/b/k", "c/g/" }, { "a/b/c/g", "../../../" },
 };
-const int num_tree_symlinks =
-               sizeof(tree_symlinks) / sizeof(tree_symlinks[0]);
+const int num_tree_symlinks = sizeof(tree_symlinks) / sizeof(tree_symlinks[0]);
 
 static struct symlink_test_input symlink_tests_inputs[] = {
-       { "a/g/../l/.",                 "a/b/l"         },
-       { "a/g/../l/./",                "a/b/l/"        },
-       { "a/g/../l/..",                "a/b"           },
-       { "a/g/../l/../",               "a/b/"          },
-       { "a/b/h/g/",                   ""              },
+       { "a/g/../l/.", "a/b/l" },  { "a/g/../l/./", "a/b/l/" }, { "a/g/../l/..", "a/b" },
+       { "a/g/../l/../", "a/b/" }, { "a/b/h/g/", "" },
 };
-const int num_symlink_tests =
-               sizeof(symlink_tests_inputs) / sizeof(symlink_tests_inputs[0]);
+const int num_symlink_tests = sizeof(symlink_tests_inputs) / sizeof(symlink_tests_inputs[0]);
 
 /* Invalid test cases */
 char *invalid_tests_inputs[] = {
-       NULL,
+       nullptr,
 };
-const int num_invalid_tests =
-               sizeof(invalid_tests_inputs) / sizeof(invalid_tests_inputs[0]);
+const int num_invalid_tests = sizeof(invalid_tests_inputs) / sizeof(invalid_tests_inputs[0]);
 } /* namespace */
 
-#define PRINT_ERR(fmt, args...)                                                \
-       fprintf(stderr, "test_utils_expand_path: error: " fmt "\n", ## args)
+#define PRINT_ERR(fmt, args...) fprintf(stderr, "test_utils_expand_path: error: " fmt "\n", ##args)
 
-static int prepare_valid_results(void)
+static int prepare_valid_results()
 {
        int i;
-       char *relative, *cur_path = NULL, *prev_path = NULL,
-                       *pprev_path = NULL, *empty = NULL;
+       char *relative, *cur_path = nullptr, *prev_path = nullptr, *pprev_path = nullptr,
+                       *empty = nullptr;
        int ret = 0;
 
        /* Prepare the relative paths */
-       cur_path = realpath(".", NULL);
-       prev_path = realpath("..", NULL);
-       pprev_path = realpath("../..", NULL);
+       cur_path = realpath(".", nullptr);
+       prev_path = realpath("..", nullptr);
+       pprev_path = realpath("../..", nullptr);
        empty = strdup("");
        if (!cur_path || !prev_path || !pprev_path || !empty) {
                PRINT_ERR("strdup out of memory");
@@ -142,7 +127,7 @@ static int prepare_valid_results(void)
        }
        for (i = 0; i < num_valid_tests; i++) {
                valid_tests_expected_results[i] = calloc<char>(PATH_MAX);
-               if (valid_tests_expected_results[i] == NULL) {
+               if (valid_tests_expected_results[i] == nullptr) {
                        PRINT_ERR("malloc expected results");
                        ret = -1;
                        goto end;
@@ -158,8 +143,11 @@ static int prepare_valid_results(void)
                        relative = empty;
                }
 
-               snprintf(valid_tests_expected_results[i], PATH_MAX,
-                               "%s%s", relative, valid_tests_inputs[i].absolute_part);
+               snprintf(valid_tests_expected_results[i],
+                        PATH_MAX,
+                        "%s%s",
+                        relative,
+                        valid_tests_inputs[i].absolute_part);
        }
 
 end:
@@ -171,7 +159,7 @@ end:
        return ret;
 }
 
-static int free_valid_results(void)
+static int free_valid_results()
 {
        int i;
 
@@ -184,21 +172,20 @@ static int free_valid_results(void)
        return 0;
 }
 
-static int prepare_symlink_tree(void)
+static int prepare_symlink_tree()
 {
        int i;
        char tmppath[PATH_MAX] = {};
 
        /* Create the temporary directory */
-       if (mkdtemp(tree_origin) == NULL) {
+       if (mkdtemp(tree_origin) == nullptr) {
                PRINT_ERR("failed to mkdtemp");
                goto error;
        }
 
        /* Create the directories of the test tree */
        for (i = 0; i < num_tree_dirs; i++) {
-               snprintf(tmppath, sizeof(tmppath), "%s/%s", tree_origin,
-                               tree_dirs[i]);
+               snprintf(tmppath, sizeof(tmppath), "%s/%s", tree_origin, tree_dirs[i]);
 
                if (mkdir(tmppath, 0755) != 0) {
                        PRINT_ERR("mkdir failed with path \"%s\"", tmppath);
@@ -208,12 +195,12 @@ static int prepare_symlink_tree(void)
 
        /* Create the symlinks of the test tree */
        for (i = 0; i < num_tree_symlinks; i++) {
-               snprintf(tmppath, sizeof(tmppath), "%s/%s",
-                               tree_origin, tree_symlinks[i].orig);
+               snprintf(tmppath, sizeof(tmppath), "%s/%s", tree_origin, tree_symlinks[i].orig);
 
                if (symlink(tree_symlinks[i].dest, tmppath) != 0) {
-                       PRINT_ERR("failed to symlink \"%s\" to \"%s\"", tmppath,
-                                       tree_symlinks[i].dest);
+                       PRINT_ERR("failed to symlink \"%s\" to \"%s\"",
+                                 tmppath,
+                                 tree_symlinks[i].dest);
                        goto error;
                }
        }
@@ -224,15 +211,14 @@ error:
        return 1;
 }
 
-static int free_symlink_tree(void)
+static int free_symlink_tree()
 {
        int i;
        char tmppath[PATH_MAX];
 
        /* Remove the symlinks from the test tree */
-       for (i =  num_tree_symlinks - 1; i > -1; i--) {
-               snprintf(tmppath, PATH_MAX, "%s/%s",
-                               tree_origin, tree_symlinks[i].orig);
+       for (i = num_tree_symlinks - 1; i > -1; i--) {
+               snprintf(tmppath, PATH_MAX, "%s/%s", tree_origin, tree_symlinks[i].orig);
 
                if (unlink(tmppath) != 0) {
                        PRINT_ERR("failed to unlink \"%s\"", tmppath);
@@ -262,7 +248,7 @@ error:
        return 1;
 }
 
-static void test_utils_expand_path(void)
+static void test_utils_expand_path()
 {
        char *result;
        char name[100], tmppath[PATH_MAX], real_tree_origin[PATH_MAX];
@@ -273,8 +259,9 @@ static void test_utils_expand_path(void)
                sprintf(name, "valid test case: %s", valid_tests_inputs[i].input);
 
                result = utils_expand_path(valid_tests_inputs[i].input);
-               ok(result != NULL &&
-                       strcmp(result, valid_tests_expected_results[i]) == 0, "%s", name);
+               ok(result != nullptr && strcmp(result, valid_tests_expected_results[i]) == 0,
+                  "%s",
+                  name);
 
                free(result);
        }
@@ -294,22 +281,27 @@ static void test_utils_expand_path(void)
        for (i = 0; i < num_symlink_tests; i++) {
                int ret;
 
-               sprintf(name, "symlink tree test case: [tmppath/]%s",
-                               symlink_tests_inputs[i].input);
+               sprintf(name,
+                       "symlink tree test case: [tmppath/]%s",
+                       symlink_tests_inputs[i].input);
 
-               ret = snprintf(tmppath, PATH_MAX, "%s/%s",
-                               real_tree_origin,
-                               symlink_tests_inputs[i].input);
+               ret = snprintf(tmppath,
+                              PATH_MAX,
+                              "%s/%s",
+                              real_tree_origin,
+                              symlink_tests_inputs[i].input);
                if (ret == -1 || ret >= PATH_MAX) {
                        PRINT_ERR("truncation occurred while concatenating paths \"%s\" and \"%s\"",
-                                       real_tree_origin,
-                                       symlink_tests_inputs[i].input);
+                                 real_tree_origin,
+                                 symlink_tests_inputs[i].input);
                        fail("%s", name);
                        continue;
                }
                result = utils_expand_path(tmppath);
-               ok(result != NULL && strcmp(result + treelen,
-                       symlink_tests_inputs[i].expected_result) == 0, "%s", name);
+               ok(result != nullptr &&
+                          strcmp(result + treelen, symlink_tests_inputs[i].expected_result) == 0,
+                  "%s",
+                  name);
 
                free(result);
        }
@@ -318,18 +310,17 @@ static void test_utils_expand_path(void)
        for (i = 0; i < num_invalid_tests; i++) {
                const char *test_input = invalid_tests_inputs[i];
 
-               sprintf(name, "invalid test case: %s", test_input ?
-                               test_input : "NULL");
+               sprintf(name, "invalid test case: %s", test_input ? test_input : "NULL");
 
                result = utils_expand_path(test_input);
-               if (result != NULL) {
+               if (result != nullptr) {
                        free(result);
                }
-               ok(result == NULL, "%s", name);
+               ok(result == nullptr, "%s", name);
        }
 }
 
-int main(void)
+int main()
 {
        if (prepare_symlink_tree() != 0) {
                goto error_mkdir;
index 840d4fc5bd93b88347d4709ae534f9b695a70c75..4af3bc90d96090150ee1c49aa6ac1becc6f26629 100644 (file)
@@ -5,13 +5,12 @@
  *
  */
 
-#include <string.h>
-#include <stdio.h>
+#include <common/utils.hpp>
 
+#include <stdio.h>
+#include <string.h>
 #include <tap/tap.h>
 
-#include <common/utils.hpp>
-
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose = 3;
@@ -25,76 +24,61 @@ struct valid_test_input {
 
 /* Valid test cases */
 struct valid_test_input valid_tests_inputs[] = {
-               { "0", 0 },
-               { "1234", 1234 },
-               { "0x400", 1024 },
-               { "0300", 192 },
-               { "16k", 16384 },
-               { "128K", 131072 },
-               { "0x1234k", 4771840 },
-               { "32M", 33554432 },
-               { "1024G", 1099511627776ULL },
-               { "0X400", 1024 },
-               { "0x40a", 1034 },
-               { "0X40b", 1035 },
-               { "0x40C", 1036 },
-               { "0X40D", 1037 },
-               { "0x40e", 1038 },
-               { "0X40f", 1039 },
-               { "00", 0 },
-               { "0k", 0 },
-               { "0K", 0 },
-               { "0M", 0 },
-               { "0G", 0 },
-               { "00k", 0 },
-               { "00K", 0 },
-               { "00M", 0 },
-               { "00G", 0 },
-               { "0x0", 0 },
-               { "0X0", 0 },
-               { "0x0k", 0 },
-               { "0X0K", 0 },
-               { "0x0M", 0 },
-               { "0X0G", 0 },
-               { "0X40G", 68719476736ULL },
-               { "0300k", 196608 },
-               { "0300K", 196608 },
-               { "030M", 25165824 },
-               { "020G", 17179869184ULL },
-               { "0xa0k", 163840 },
-               { "0xa0K", 163840 },
-               { "0XA0M", 167772160 },
-               { "0xA0G", 171798691840ULL },
+       { "0", 0 },
+       { "1234", 1234 },
+       { "0x400", 1024 },
+       { "0300", 192 },
+       { "16k", 16384 },
+       { "128K", 131072 },
+       { "0x1234k", 4771840 },
+       { "32M", 33554432 },
+       { "1024G", 1099511627776ULL },
+       { "0X400", 1024 },
+       { "0x40a", 1034 },
+       { "0X40b", 1035 },
+       { "0x40C", 1036 },
+       { "0X40D", 1037 },
+       { "0x40e", 1038 },
+       { "0X40f", 1039 },
+       { "00", 0 },
+       { "0k", 0 },
+       { "0K", 0 },
+       { "0M", 0 },
+       { "0G", 0 },
+       { "00k", 0 },
+       { "00K", 0 },
+       { "00M", 0 },
+       { "00G", 0 },
+       { "0x0", 0 },
+       { "0X0", 0 },
+       { "0x0k", 0 },
+       { "0X0K", 0 },
+       { "0x0M", 0 },
+       { "0X0G", 0 },
+       { "0X40G", 68719476736ULL },
+       { "0300k", 196608 },
+       { "0300K", 196608 },
+       { "030M", 25165824 },
+       { "020G", 17179869184ULL },
+       { "0xa0k", 163840 },
+       { "0xa0K", 163840 },
+       { "0XA0M", 167772160 },
+       { "0xA0G", 171798691840ULL },
 };
 const int num_valid_tests = sizeof(valid_tests_inputs) / sizeof(valid_tests_inputs[0]);
 
 /* Invalid test cases */
 const char *invalid_tests_inputs[] = {
-               "",
-               " ",
-               "-1",
-               "k",
-               "4611686018427387904G",
-               "0x40g",
-               "08",
-               "09",
-               "0x",
-               "x0",
-               "0xx0",
-               "07kK",
-               "0xk",
-               "0XM",
-               "0xG",
-               "0x0MM",
-               "0X0GG",
-               "0a",
-               "0B",
+       "",      " ",     "-1",  "k",   "4611686018427387904G",
+       "0x40g", "08",    "09",  "0x",  "x0",
+       "0xx0",  "07kK",  "0xk", "0XM", "0xG",
+       "0x0MM", "0X0GG", "0a",  "0B",
 };
 
 const int num_invalid_tests = sizeof(invalid_tests_inputs) / sizeof(invalid_tests_inputs[0]);
 } /* namespace */
 
-static void test_utils_parse_size_suffix(void)
+static void test_utils_parse_size_suffix()
 {
        uint64_t result;
        int ret;
@@ -119,7 +103,7 @@ static void test_utils_parse_size_suffix(void)
        }
 }
 
-int main(void)
+int main()
 {
        plan_tests(num_valid_tests + num_invalid_tests);
 
index 765c96fb5d01bb96c7509d1c0f167a3803c4cb8f..12185830f140b32e5f026923f37edd27966934d8 100644 (file)
@@ -5,14 +5,13 @@
  *
  */
 
-#include <string.h>
-#include <stdio.h>
-#include <inttypes.h>
+#include <common/utils.hpp>
 
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
 #include <tap/tap.h>
 
-#include <common/utils.hpp>
-
 /* For error.h */
 int lttng_opt_quiet = 1;
 int lttng_opt_verbose = 3;
@@ -26,72 +25,53 @@ struct valid_test_input {
 
 /* Valid test cases */
 struct valid_test_input valid_tests_inputs[] = {
-               { "0", 0 },
-               { "1234", 1234 },
-               { "1234us", 1234 },
-               { "16ms", 16000 },
-               { "128ms", 128000 },
-               { "32s", 32000000 },
-               { "1m", 60000000 },
-               { "20m", 1200000000 },
-               { "1h", 3600000000 },
-               { "5h", 18000000000 },
-               { "00", 0 },
-               { "0us", 0 },
-               { "0ms", 0 },
-               { "0s", 0 },
-               { "0m", 0 },
-               { "0h", 0 },
-               { "00us", 0 },
-               { "00ms", 0 },
-               { "00s", 0 },
-               { "00m", 0 },
-               { "00h", 0 },
-               { "12ms", 12000 },
-               { "3597us", 3597 },
-               { "+5", 5 },
-               { "08", 8 },
-               { "0145us", 145 },
+       { "0", 0 },           { "1234", 1234 },      { "1234us", 1234 }, { "16ms", 16000 },
+       { "128ms", 128000 },  { "32s", 32000000 },   { "1m", 60000000 }, { "20m", 1200000000 },
+       { "1h", 3600000000 }, { "5h", 18000000000 }, { "00", 0 },        { "0us", 0 },
+       { "0ms", 0 },         { "0s", 0 },           { "0m", 0 },        { "0h", 0 },
+       { "00us", 0 },        { "00ms", 0 },         { "00s", 0 },       { "00m", 0 },
+       { "00h", 0 },         { "12ms", 12000 },     { "3597us", 3597 }, { "+5", 5 },
+       { "08", 8 },          { "0145us", 145 },
 };
 const int num_valid_tests = sizeof(valid_tests_inputs) / sizeof(valid_tests_inputs[0]);
 
 /* Invalid test cases */
 const char *invalid_tests_inputs[] = {
-               "",
-               " ",
-               "-1",
-               "m",
-               "4611686018427387904s",
-               "0x40M",
-               "0x",
-               "x0",
-               "0xx0",
-               "07mm",
-               "0xm",
-               "0Xs",
-               "0x0ss",
-               "0a",
-               "0B",
-               "0x3 s",
-               "0xbs ",
-               "14ns",
-               "0xbs",
-               "14ns",
-               "14ms garbage after value",
-               "0x14s",
-               "0u",
-               "5mS",
-               "5Ms",
-               "12ussr",
-               "67msrp",
-               "14si",
-               "12mo",
-               "53hi",
+       "",
+       " ",
+       "-1",
+       "m",
+       "4611686018427387904s",
+       "0x40M",
+       "0x",
+       "x0",
+       "0xx0",
+       "07mm",
+       "0xm",
+       "0Xs",
+       "0x0ss",
+       "0a",
+       "0B",
+       "0x3 s",
+       "0xbs ",
+       "14ns",
+       "0xbs",
+       "14ns",
+       "14ms garbage after value",
+       "0x14s",
+       "0u",
+       "5mS",
+       "5Ms",
+       "12ussr",
+       "67msrp",
+       "14si",
+       "12mo",
+       "53hi",
 };
 const int num_invalid_tests = sizeof(invalid_tests_inputs) / sizeof(invalid_tests_inputs[0]);
 } /* namespace */
 
-static void test_utils_parse_time_suffix(void)
+static void test_utils_parse_time_suffix()
 {
        uint64_t result;
        int ret;
@@ -102,7 +82,10 @@ static void test_utils_parse_time_suffix(void)
                char name[256];
 
                ret = utils_parse_time_suffix(valid_tests_inputs[i].input, &result);
-               sprintf(name, "valid test case: %s expected %" PRIu64, valid_tests_inputs[i].input, result);
+               sprintf(name,
+                       "valid test case: %s expected %" PRIu64,
+                       valid_tests_inputs[i].input,
+                       result);
                ok(ret == 0 && result == valid_tests_inputs[i].expected_result, "%s", name);
        }
 
@@ -117,7 +100,7 @@ static void test_utils_parse_time_suffix(void)
        }
 }
 
-int main(void)
+int main()
 {
        plan_tests(num_valid_tests + num_invalid_tests);
 
index 07a2f4afb221d393f5fc9c5dfb095520e5927d05..6db6d54b30451812825b311676074de521ef3a05 100644 (file)
@@ -5,14 +5,13 @@
  *
  */
 
-#include <stdio.h>
+#include "common/uuid.hpp"
+
 #include <stdbool.h>
+#include <stdio.h>
 #include <string.h>
-
 #include <tap/tap.h>
 
-#include "common/uuid.hpp"
-
 #define NR_TESTS 21
 
 static const char valid_str_1[] = "3d260c88-75ea-47b8-a7e2-d6077c0378d9";
@@ -21,18 +20,12 @@ static const char valid_str_3[] = "1b4855cc-96de-4ae8-abe3-86449c2a43c4";
 static const char valid_str_4[] = "8ADED5B9-ACD2-439F-A60C-897403AA2AB4";
 static const char valid_str_5[] = "f109e0a2-C619-4d18-b760-20EA20E0F69A";
 
-static lttng_uuid valid_uuid_1 = {
-       0x3d, 0x26, 0x0c, 0x88, 0x75, 0xea, 0x47, 0xb8,
-       0xa7, 0xe2, 0xd6, 0x07, 0x7c, 0x03, 0x78, 0xd9
-};
-static lttng_uuid valid_uuid_2 = {
-       0x61, 0x1c, 0xf3, 0xa6, 0xa6, 0x8b, 0x45, 0x15,
-       0x83, 0x4f, 0x20, 0x8b, 0xc2, 0x76, 0x25, 0x92
-};
-static lttng_uuid valid_uuid_3 = {
-       0x1b, 0x48, 0x55, 0xcc, 0x96, 0xde, 0x4a, 0xe8,
-       0xab, 0xe3, 0x86, 0x44, 0x9c, 0x2a, 0x43, 0xc4
-};
+static lttng_uuid valid_uuid_1 = { 0x3d, 0x26, 0x0c, 0x88, 0x75, 0xea, 0x47, 0xb8,
+                                  0xa7, 0xe2, 0xd6, 0x07, 0x7c, 0x03, 0x78, 0xd9 };
+static lttng_uuid valid_uuid_2 = { 0x61, 0x1c, 0xf3, 0xa6, 0xa6, 0x8b, 0x45, 0x15,
+                                  0x83, 0x4f, 0x20, 0x8b, 0xc2, 0x76, 0x25, 0x92 };
+static lttng_uuid valid_uuid_3 = { 0x1b, 0x48, 0x55, 0xcc, 0x96, 0xde, 0x4a, 0xe8,
+                                  0xab, 0xe3, 0x86, 0x44, 0x9c, 0x2a, 0x43, 0xc4 };
 
 static const char invalid_str_1[] = "1b485!cc-96de-4XX8-abe3-86449c2a43?4";
 static const char invalid_str_2[] = "c2e6eddb&3955&4006&be3a&70bb63bd5f25";
@@ -41,8 +34,12 @@ static const char invalid_str_4[] = "2d-6c6d756574-470e-9142-a4e6ad03f143";
 static const char invalid_str_5[] = "4542ad19-9e4f-4931-8261-2101c3e089ae7";
 static const char invalid_str_6[] = "XX0123";
 
-static
-void run_test_lttng_uuid_from_str(void)
+/* For error.hpp */
+int lttng_opt_quiet = 1;
+int lttng_opt_verbose = 0;
+int lttng_opt_mi;
+
+static void run_test_lttng_uuid_from_str()
 {
        int ret;
        lttng_uuid uuid1;
@@ -69,41 +66,57 @@ void run_test_lttng_uuid_from_str(void)
         * Parse invalid UUID strings, expect failure.
         */
        ret = lttng_uuid_from_str(invalid_str_1, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_1);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_1);
 
        ret = lttng_uuid_from_str(invalid_str_2, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_2);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_2);
 
        ret = lttng_uuid_from_str(invalid_str_3, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_3);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_3);
 
        ret = lttng_uuid_from_str(invalid_str_4, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_4);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_4);
 
        ret = lttng_uuid_from_str(invalid_str_5, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_5);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_5);
 
        ret = lttng_uuid_from_str(invalid_str_6, uuid1);
-       ok(ret != 0, "lttng_uuid_from_str - Parse invalid string '%s', expect failure", invalid_str_6);
+       ok(ret != 0,
+          "lttng_uuid_from_str - Parse invalid string '%s', expect failure",
+          invalid_str_6);
 }
 
-static
-void run_test_lttng_uuid_to_str(void)
+static void run_test_lttng_uuid_to_str()
 {
        char uuid_str[LTTNG_UUID_STR_LEN];
 
        lttng_uuid_to_str(valid_uuid_1, uuid_str);
-       ok(strcmp(uuid_str, valid_str_1) == 0, "lttng_uuid_to_str - Convert UUID '%s' to string, expect success", valid_str_1);
+       ok(strcmp(uuid_str, valid_str_1) == 0,
+          "lttng_uuid_to_str - Convert UUID '%s' to string, expect success",
+          valid_str_1);
 
        lttng_uuid_to_str(valid_uuid_2, uuid_str);
-       ok(strcmp(uuid_str, valid_str_2) == 0, "lttng_uuid_to_str - Convert UUID '%s' to string, expect success", valid_str_2);
+       ok(strcmp(uuid_str, valid_str_2) == 0,
+          "lttng_uuid_to_str - Convert UUID '%s' to string, expect success",
+          valid_str_2);
 
        lttng_uuid_to_str(valid_uuid_3, uuid_str);
-       ok(strcmp(uuid_str, valid_str_3) == 0, "lttng_uuid_to_str - Convert UUID '%s' to string, expect success", valid_str_3);
+       ok(strcmp(uuid_str, valid_str_3) == 0,
+          "lttng_uuid_to_str - Convert UUID '%s' to string, expect success",
+          valid_str_3);
 }
 
-static
-void run_test_lttng_uuid_is_equal(void)
+static void run_test_lttng_uuid_is_equal()
 {
        int ret;
        lttng_uuid uuid1, uuid2;
@@ -121,8 +134,7 @@ void run_test_lttng_uuid_is_equal(void)
        ok(ret == false, "lttng_uuid_is_equal - Compare different UUID, expect failure");
 }
 
-static
-void run_test_lttng_uuid_copy(void)
+static void run_test_lttng_uuid_copy()
 {
        bool ret;
        lttng_uuid uuid1;
@@ -133,8 +145,7 @@ void run_test_lttng_uuid_copy(void)
        ok(ret == true, "lttng_uuid_copy - Compare copied UUID with source, expect success");
 }
 
-static
-void run_test_lttng_uuid_generate(void)
+static void run_test_lttng_uuid_generate()
 {
        int ret;
        lttng_uuid uuid1, uuid2;
@@ -163,8 +174,7 @@ void run_test_lttng_uuid_generate(void)
        ok(ret == LTTNG_UUID_VER, "lttng_uuid_generate - Generated UUID version check");
 }
 
-static
-void run_test(void)
+static void run_test()
 {
        plan_tests(NR_TESTS);
 
@@ -175,7 +185,7 @@ void run_test(void)
        run_test_lttng_uuid_generate();
 }
 
-int main(void)
+int main()
 {
        /* Run tap-formated tests */
        run_test();
index 96dbe28523693488d72c2442809db3bd2da266ee..455e749a25f2a553217d43df2ddcaf549964ca11 100644 (file)
@@ -1,10 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
-SUBDIRS = . tap testapp xml-utils
+SUBDIRS = . tap testapp xml-utils lttngtest bt2_plugins
 
-EXTRA_DIST = utils.sh test_utils.py babelstats.pl warn_processes.sh \
+EXTRA_DIST = utils.sh test_utils.py warn_processes.sh \
              parse-callstack.py
-dist_noinst_SCRIPTS = utils.sh test_utils.py babelstats.pl tap-driver.sh
+dist_noinst_SCRIPTS = utils.sh test_utils.py tap-driver.sh
 noinst_LTLIBRARIES = libtestutils.la
 
 libtestutils_la_SOURCES = \
diff --git a/tests/utils/babelstats.pl b/tests/utils/babelstats.pl
deleted file mode 100755 (executable)
index 8dbb7a3..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-#!/usr/bin/perl
-
-# Copyright (C) 2012 Christian Babeux <christian.babeux@efficios.com>
-#
-# SPDX-License-Identifier: GPL-2.0-only
-#
-
-use strict;
-use warnings;
-
-use Getopt::Long;
-
-my $opt_tracepoint;
-
-GetOptions('tracepoint=s' => \$opt_tracepoint)
-       or die("Invalid command-line option\n");
-
-defined($opt_tracepoint)
-       or die("Missing tracepoint, use --tracepoint <name>");
-
-# Parse an array string.
-# The format is as follow: [ [index] = value, ... ]
-sub parse_array
-{
-       my ($arr_str) = @_;
-       my @array = ();
-
-       # Strip leading and ending brackets, remove whitespace
-       $arr_str =~ s/^\[//;
-       $arr_str =~ s/\]$//;
-       $arr_str =~ s/\s//g;
-
-       my @entries = split(',', $arr_str);
-
-       foreach my $entry (@entries) {
-               if ($entry =~ /^\[(\d+)\]=(\d+)$/) {
-                       my $index = $1;
-                       my $value = $2;
-                       splice @array, $index, 0, $value;
-               }
-       }
-
-       return \@array;
-}
-
-# Parse fields values.
-# Format can either be a name = array or a name = value pair.
-sub parse_fields
-{
-       my ($fields_str) = @_;
-       my %fields_hash;
-
-       my $field_name = '[\w\d_]+';
-       my $field_value = '[\w\d_\\\*"]+';
-       my $array = '\[(?:\s\[\d+\]\s=\s\d+,)*\s\[\d+\]\s=\s\d+\s\]';
-
-       # Split the various fields
-       my @fields = ($fields_str =~ /$field_name\s=\s(?:$array|$field_value)/g);
-
-       foreach my $field (@fields) {
-               if ($field =~ /($field_name)\s=\s($array)/) {
-                       my $name  = $1;
-                       my $value = parse_array($2);
-                       $fields_hash{$name} = $value;
-               }
-
-               if ($field =~ /($field_name)\s=\s($field_value)/) {
-                       my $name  = $1;
-                       my $value = $2;
-                       $fields_hash{$name} = $value;
-               }
-       }
-
-       return \%fields_hash;
-}
-
-# Using an event array, merge all the fields
-# of a particular tracepoint.
-sub merge_fields
-{
-       my ($events_ref) = @_;
-       my %merged;
-
-       foreach my $event (@{$events_ref}) {
-               my $tp_event     = $event->{'tp_event'};
-               my $tracepoint  = "${tp_event}";
-
-               foreach my $key (keys %{$event->{'fields'}}) {
-                       my $val = $event->{'fields'}->{$key};
-
-                       # TODO: Merge of array is not implemented.
-                       next if (ref($val) eq 'ARRAY');
-                       $merged{$tracepoint}{$key}{$val} = undef;
-               }
-       }
-
-       return \%merged;
-}
-
-# Print the minimum and maximum of each fields
-# for a particular tracepoint.
-sub print_fields_stats
-{
-       my ($merged_ref, $tracepoint) = @_;
-
-       return unless ($tracepoint && exists $merged_ref->{$tracepoint});
-
-       foreach my $field (keys %{$merged_ref->{$tracepoint}}) {
-               my @sorted;
-               my @val = keys %{$merged_ref->{$tracepoint}->{$field}};
-
-               if ($val[0] =~ /^\d+$/) {
-                       # Sort numerically
-                       @sorted = sort { $a <=> $b } @val;
-               } elsif ($val[0] =~ /^0x[\da-f]+$/i) {
-                       # Convert the hex values and sort numerically
-                       @sorted = sort { hex($a) <=> hex($b) } @val;
-               } else {
-                       # Fallback, alphabetical sort
-                       @sorted = sort { lc($a) cmp lc($b) } @val;
-               }
-
-               my $min = $sorted[0];
-               my $max = $sorted[-1];
-
-               print "$field $min $max\n";
-       }
-}
-
-my @events;
-
-while (<>)
-{
-       my $timestamp   = '\[(?:.*)\]';
-       my $elapsed     = '\((?:.*)\)';
-       my $hostname    = '(?:.*)';
-       my $tp_event    = '(.*)';
-       my $pkt_context = '(?:\{[^}]*\},\s)*';
-       my $fields      = '\{(.*)\}$';
-
-       # Parse babeltrace text output format
-       if (/$timestamp\s$elapsed\s$hostname\s$tp_event:\s$pkt_context$fields/) {
-               my %event_hash;
-               $event_hash{'tp_event'}    = $1;
-               $event_hash{'fields'}      = parse_fields($2);
-
-               push @events, \%event_hash;
-       }
-}
-
-my %merged_fields = %{merge_fields(\@{events})};
-print_fields_stats(\%merged_fields, $opt_tracepoint);
diff --git a/tests/utils/bt2_plugins/Makefile.am b/tests/utils/bt2_plugins/Makefile.am
new file mode 100644 (file)
index 0000000..ce6697e
--- /dev/null
@@ -0,0 +1,30 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+SUBDIRS = event_name field_stats
+
+AM_CPPFLAGS += -I$(srcdir)
+AM_CXXFLAGS += $(babeltrace2_CFLAGS) \
+       $(WARN_FLAGS)
+
+noinst_LTLIBRARIES = lttngtest.la
+
+# lttng-tools uses -fvisibility=hidden by default, but to
+# produce a loadable plugin some of the symbols must not be
+# hidden. Override the `-fvisibility` for this shared object.
+lttngtest_la_CXXFLAGS = \
+       $(AM_CXXFLAGS) \
+       -fvisibility=default
+
+lttngtest_la_SOURCES = \
+       lttngtest-plugin.cpp \
+       fmt.hpp \
+       utils.hpp
+
+lttngtest_la_LDFLAGS = \
+       $(AM_LDFLAGS) \
+       $(LD_NO_UNDEFINED) \
+       -rpath / -avoid-version -module $(LD_NOTEXT)
+
+lttngtest_la_LIBADD = \
+       event_name/event_name.la \
+       field_stats/field_stats.la
diff --git a/tests/utils/bt2_plugins/README.md b/tests/utils/bt2_plugins/README.md
new file mode 100644 (file)
index 0000000..5c0186f
--- /dev/null
@@ -0,0 +1,23 @@
+The `filter.lttngtest.event_name` plugin only has a single input and output port.
+This means that it cannot be connected directly to a `source.ctf.fs` plugin, as
+those have multiple output ports for the different event streams.
+
+A `filter.utils.muxer` plugin must be placed between any multi-output port plugin
+and the `filter.lttngtest.event_name` plugin. This is done automatically with in
+the architecture created by `babeltrace2 convert`.
+
+Example with `babeltrace2 convert`:
+
+```
+SOURCE_PATH=/tmp/tmp.1J5DueCziG
+EVENT_NAME=tp:the_string
+babeltrace2 --plugin-path=.libs/ convert "${SOURCE_PATH}" -c filter.lttngtest.event_name -p "names=[\"$EVENT_NAME\"]" -c sink.lttngtest.field_stats
+```
+
+Example with `babeltrace2 run`:
+
+```
+SOURCE_PATH=/tmp/tmp.1J5DueCziG
+EVENT_NAME=tp:the_string
+babeltrace2 --plugin-path=.libs/ run -c A:source.ctf.fs -p "inputs=[\"$SOURCE_PATH\"]" -c muxer:filter.utils.muxer -c B:filter.lttngtest.event_name -p "names=[\"$EVENT_NAME\"]" -c C:sink.lttngtest.field_stats -x A:muxer -x muxer:B -x B:C
+```
diff --git a/tests/utils/bt2_plugins/event_name/Makefile.am b/tests/utils/bt2_plugins/event_name/Makefile.am
new file mode 100644 (file)
index 0000000..d4dc2f1
--- /dev/null
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+AM_CXXFLAGS += $(babeltrace2_CFLAGS) \
+       $(WARN_FLAGS)
+
+noinst_LTLIBRARIES = event_name.la
+event_name_la_SOURCES = \
+       event_name.cpp \
+       event_name.hpp
+event_name_la_LDFLAGS = \
+       $(AM_LDFLAGS) \
+       $(LD_NO_UNDEFINED) \
+       -avoid-version -module $(LD_NOTEXT)
diff --git a/tests/utils/bt2_plugins/event_name/event_name.cpp b/tests/utils/bt2_plugins/event_name/event_name.cpp
new file mode 100644 (file)
index 0000000..170e375
--- /dev/null
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "../utils.hpp"
+#include "event_name.hpp"
+
+#include <common/container-wrapper.hpp>
+#include <common/macros.hpp>
+#include <common/make-unique.hpp>
+
+#include <assert.h>
+#include <babeltrace2/babeltrace.h>
+#include <cstdint>
+#include <exception>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <unordered_set>
+
+class event_name_set_operations {
+public:
+       static const char *get(const bt_value *array, std::size_t index)
+       {
+               const auto *names_entry =
+                       bt_value_array_borrow_element_by_index_const(array, index);
+
+               if (bt_value_get_type(names_entry) != BT_VALUE_TYPE_STRING) {
+                       throw std::runtime_error(
+                               "All members of the 'names' parameter array must be strings");
+               }
+
+               return bt_value_string_get(names_entry);
+       }
+
+       static std::size_t size(const bt_value *array)
+       {
+               return bt_value_array_get_length(array);
+       }
+};
+
+class event_name_set
+       : public lttng::utils::random_access_container_wrapper<const bt_value *,
+                                                              const char *,
+                                                              event_name_set_operations> {
+public:
+       friend event_name_set_operations;
+
+       event_name_set() :
+               lttng::utils::random_access_container_wrapper<const bt_value *,
+                                                             const char *,
+                                                             event_name_set_operations>(nullptr)
+       {
+       }
+
+       event_name_set(event_name_set&& original) :
+               lttng::utils::random_access_container_wrapper<const bt_value *,
+                                                             const char *,
+                                                             event_name_set_operations>(
+                       std::move(original._container))
+       {
+       }
+
+       event_name_set(const bt_value *names) :
+               lttng::utils::random_access_container_wrapper<const bt_value *,
+                                                             const char *,
+                                                             event_name_set_operations>(names)
+       {
+               if (bt_value_get_type(names) != BT_VALUE_TYPE_ARRAY) {
+                       throw std::invalid_argument("'names' parameter must be an array");
+               }
+       }
+};
+
+class event_name_filter {
+public:
+       event_name_filter(bt_self_component_port_input *input_port_,
+                         const event_name_set& name_set) :
+               input_port{ input_port_ }, _names{ name_set.begin(), name_set.end() }
+       {
+       }
+
+       bool event_name_is_allowed(const char *event_name) const noexcept
+       {
+               return _names.find(event_name) != _names.end();
+       }
+
+       /* weak reference */
+       bt_self_component_port_input *const input_port;
+
+private:
+       const std::unordered_set<std::string> _names;
+};
+
+struct event_name_iterator_data {
+       event_name_iterator_data(lttng::bt2::message_iterator_ref iterator_,
+                                const class event_name_filter& event_name_filter_) :
+               upstream_iterator{ std::move(iterator_) }, event_name_filter{ event_name_filter_ }
+       {
+       }
+
+       ~event_name_iterator_data()
+       {
+       }
+
+       const lttng::bt2::message_iterator_ref upstream_iterator;
+       const class event_name_filter& event_name_filter;
+};
+
+namespace {
+bool message_passes(const bt_message *message, const event_name_filter& event_name_filter)
+{
+       if (bt_message_get_type(message) != BT_MESSAGE_TYPE_EVENT) {
+               return true;
+       }
+
+       const bt_event *event = bt_message_event_borrow_event_const(message);
+       const bt_event_class *event_class = bt_event_borrow_class_const(event);
+       const char *event_name = bt_event_class_get_name(event_class);
+
+       if (event_name == nullptr) {
+               return false;
+       }
+
+       return event_name_filter.event_name_is_allowed(event_name);
+}
+} /* namespace */
+
+bt_component_class_initialize_method_status
+event_name_initialize(bt_self_component_filter *self_comp,
+                     bt_self_component_filter_configuration *,
+                     const bt_value *params,
+                     void *)
+{
+       bt_self_component_port_input *input_port;
+       std::unique_ptr<class event_name_filter> event_name_filter;
+
+       auto self = bt_self_component_filter_as_self_component(self_comp);
+       if (bt_self_component_filter_add_input_port(self_comp, "in", nullptr, &input_port) !=
+           BT_SELF_COMPONENT_ADD_PORT_STATUS_OK) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(self,
+                                                                   "Failed to add input port");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       if (bt_self_component_filter_add_output_port(self_comp, "out", nullptr, nullptr) !=
+           BT_SELF_COMPONENT_ADD_PORT_STATUS_OK) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(self,
+                                                                   "Failed to add output port");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       const auto names_param = bt_value_map_borrow_entry_value_const(params, "names");
+       if (names_param == nullptr) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       self, "'names' parameter is required");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       try {
+               event_name_set event_names{ names_param };
+               if (event_names.empty()) {
+                       BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                               bt_self_component_filter_as_self_component(self_comp),
+                               "'names' parameter must not be empty");
+                       return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+               }
+
+               event_name_filter =
+                       lttng::make_unique<class event_name_filter>(input_port, event_names);
+       } catch (const std::bad_alloc&) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       self, "Failed to allocate memory for private component data");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
+       } catch (const std::exception& ex) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(self, "%s", ex.what());
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       /* Ownership of event_name is transferred to the component. */
+       bt_self_component_set_data(self, event_name_filter.release());
+       return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK;
+}
+
+void event_name_finalize(bt_self_component_filter *self_comp)
+{
+       class event_name_filter *event_name_filter =
+               (class event_name_filter *) bt_self_component_get_data(
+                       bt_self_component_filter_as_self_component(self_comp));
+
+       delete event_name_filter;
+}
+
+bt_message_iterator_class_initialize_method_status
+event_name_message_iterator_initialize(bt_self_message_iterator *self_message_iterator,
+                                      bt_self_message_iterator_configuration *,
+                                      bt_self_component_port_output *)
+{
+       const auto& event_name_filter =
+               *static_cast<class event_name_filter *>(bt_self_component_get_data(
+                       bt_self_message_iterator_borrow_component(self_message_iterator)));
+
+       bt_message_iterator *raw_iterator;
+       if (bt_message_iterator_create_from_message_iterator(
+                   self_message_iterator, event_name_filter.input_port, &raw_iterator) !=
+           BT_MESSAGE_ITERATOR_CREATE_FROM_MESSAGE_ITERATOR_STATUS_OK) {
+               return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       lttng::bt2::message_iterator_ref iterator(raw_iterator);
+       raw_iterator = nullptr;
+
+       std::unique_ptr<event_name_iterator_data> iter_data;
+       try {
+               iter_data = lttng::make_unique<event_name_iterator_data>(std::move(iterator),
+                                                                        event_name_filter);
+       } catch (const std::bad_alloc&) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_MESSAGE_ITERATOR(
+                       self_message_iterator, "Failed to allocate event_name iterator data");
+               return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       /* Transfer the ownership of iter_data to the iterator. */
+       bt_self_message_iterator_set_data(self_message_iterator, iter_data.release());
+       return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_OK;
+}
+
+void event_name_message_iterator_finalize(bt_self_message_iterator *self_message)
+{
+       event_name_iterator_data *iter_data = static_cast<event_name_iterator_data *>(
+               bt_self_message_iterator_get_data(self_message));
+
+       LTTNG_ASSERT(iter_data);
+       delete iter_data;
+}
+
+bt_message_iterator_class_next_method_status
+event_name_message_iterator_next(bt_self_message_iterator *self_message_iterator,
+                                bt_message_array_const messages_to_deliver_downstream,
+                                uint64_t,
+                                uint64_t *_messages_to_deliver_count)
+{
+       std::uint64_t messages_to_deliver_count = 0;
+       auto *iter_data = static_cast<event_name_iterator_data *>(
+               bt_self_message_iterator_get_data(self_message_iterator));
+       const auto& event_name_filter =
+               *static_cast<class event_name_filter *>(bt_self_component_get_data(
+                       bt_self_message_iterator_borrow_component(self_message_iterator)));
+
+       LTTNG_ASSERT(iter_data);
+
+       /* Retry until we have at least one message to deliver downstream. */
+       while (messages_to_deliver_count == 0) {
+               bt_message_array_const upstream_messages;
+               bt_message_iterator_next_status next_status;
+               uint64_t upstream_message_count;
+
+               next_status = bt_message_iterator_next(iter_data->upstream_iterator.get(),
+                                                      &upstream_messages,
+                                                      &upstream_message_count);
+               if (next_status != BT_MESSAGE_ITERATOR_NEXT_STATUS_OK) {
+                       return static_cast<bt_message_iterator_class_next_method_status>(
+                               next_status);
+               }
+
+               for (std::uint64_t upstream_index = 0; upstream_index < upstream_message_count;
+                    upstream_index++) {
+                       lttng::bt2::message_const_ref upstream_message(
+                               upstream_messages[upstream_index]);
+
+                       if (message_passes(upstream_message.get(), event_name_filter)) {
+                               /* Reference transferred to downstream message batch. */
+                               messages_to_deliver_downstream[messages_to_deliver_count] =
+                                       upstream_message.release();
+                               messages_to_deliver_count++;
+                       }
+               }
+       }
+
+       *_messages_to_deliver_count = messages_to_deliver_count;
+       return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK;
+}
diff --git a/tests/utils/bt2_plugins/event_name/event_name.hpp b/tests/utils/bt2_plugins/event_name/event_name.hpp
new file mode 100644 (file)
index 0000000..9798b66
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_TEST_UTILS_BT2_PLUGIN_EVENT_NAME_HPP
+#define LTTNG_TEST_UTILS_BT2_PLUGIN_EVENT_NAME_HPP
+
+#include <babeltrace2/babeltrace.h>
+
+bt_component_class_initialize_method_status
+event_name_initialize(bt_self_component_filter *self_comp,
+                     bt_self_component_filter_configuration *config,
+                     const bt_value *params,
+                     void *init_data);
+
+void event_name_finalize(bt_self_component_filter *self_comp);
+
+bt_message_iterator_class_initialize_method_status
+event_name_message_iterator_initialize(bt_self_message_iterator *self_message_iterator,
+                                      bt_self_message_iterator_configuration *config,
+                                      bt_self_component_port_output *self_port);
+
+void event_name_message_iterator_finalize(bt_self_message_iterator *self_message_iterator);
+
+bt_message_iterator_class_next_method_status
+event_name_message_iterator_next(bt_self_message_iterator *self_message_iterator,
+                                bt_message_array_const messages,
+                                uint64_t capacity,
+                                uint64_t *count);
+
+#endif /* LTTNG_TEST_UTILS_BT2_PLUGIN_EVENT_NAME_HPP */
diff --git a/tests/utils/bt2_plugins/field_stats/Makefile.am b/tests/utils/bt2_plugins/field_stats/Makefile.am
new file mode 100644 (file)
index 0000000..9341356
--- /dev/null
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+AM_CXXFLAGS += $(babeltrace2_CFLAGS) \
+       $(WARN_FLAGS)
+
+noinst_LTLIBRARIES = field_stats.la
+field_stats_la_SOURCES = \
+       field_stats.cpp \
+       field_stats.hpp
+field_stats_la_LDFLAGS = \
+       $(AM_LDFLAGS) \
+       $(LD_NO_UNDEFINED) \
+       -avoid-version -module $(LD_NOTEXT)
diff --git a/tests/utils/bt2_plugins/field_stats/field_stats.cpp b/tests/utils/bt2_plugins/field_stats/field_stats.cpp
new file mode 100644 (file)
index 0000000..dc8894f
--- /dev/null
@@ -0,0 +1,455 @@
+/**
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "../fmt.hpp"
+#include "../utils.hpp"
+#include "field_stats.hpp"
+
+#include <common/make-unique-wrapper.hpp>
+#include <common/make-unique.hpp>
+
+#include <assert.h>
+#include <babeltrace2/babeltrace.h>
+#include <cstdint>
+#include <cstring>
+#include <iostream>
+#include <stdio.h>
+#include <stdlib.h>
+
+class bad_alloc_with_msg : public std::bad_alloc {
+public:
+       explicit bad_alloc_with_msg(const std::string& msg) : _msg(msg)
+       {
+       }
+
+       virtual const char *what() const noexcept override
+       {
+               return _msg.c_str();
+       }
+
+private:
+       std::string _msg;
+};
+
+struct field_stats {
+public:
+       field_stats() : stats_value{ lttng::bt2::make_value_ref(bt_value_map_create()) }
+       {
+               if (!stats_value) {
+                       throw bad_alloc_with_msg(
+                               "Failed to allocate memory for field_stats.stats map");
+               }
+       }
+
+       ~field_stats()
+       {
+       }
+
+       lttng::bt2::message_iterator_ref upstream_iterator;
+       lttng::bt2::event_class_const_ref event_class;
+       const lttng::bt2::value_ref stats_value;
+};
+
+namespace {
+bt_value_map_foreach_entry_const_func_status
+stats_value_print_summary(const char *key, const bt_value *value, void *)
+{
+       LTTNG_ASSERT(bt_value_is_map(value));
+
+       const auto *min = bt_value_map_borrow_entry_value_const(value, "min");
+       LTTNG_ASSERT(min != nullptr);
+       const auto *max = bt_value_map_borrow_entry_value_const(value, "max");
+       LTTNG_ASSERT(max != nullptr);
+
+       const auto *display_base = bt_value_map_borrow_entry_value_const(value, "display_base");
+       auto display_base_value = BT_FIELD_CLASS_INTEGER_PREFERRED_DISPLAY_BASE_DECIMAL;
+
+       if (display_base != nullptr) {
+               display_base_value = (enum bt_field_class_integer_preferred_display_base)
+                       bt_value_integer_unsigned_get(display_base);
+       }
+
+       LTTNG_ASSERT(bt_value_get_type(min) == bt_value_get_type(max));
+
+       switch (bt_value_get_type(min)) {
+       case BT_VALUE_TYPE_STRING:
+               fmt::print("{} \"{}\" \"{}\"\n",
+                          key,
+                          bt_value_string_get(min),
+                          bt_value_string_get(max));
+               break;
+       case BT_VALUE_TYPE_UNSIGNED_INTEGER:
+               switch (display_base_value) {
+               case BT_FIELD_CLASS_INTEGER_PREFERRED_DISPLAY_BASE_HEXADECIMAL:
+                       std::cout << lttng::format("{} 0x{:X} 0x{:X}\n",
+                                                  key,
+                                                  bt_value_integer_unsigned_get(min),
+                                                  bt_value_integer_unsigned_get(max));
+                       break;
+               default:
+                       std::cout << lttng::format("{} {} {}\n",
+                                                  key,
+                                                  bt_value_integer_unsigned_get(min),
+                                                  bt_value_integer_unsigned_get(max));
+                       break;
+               }
+
+               break;
+       case BT_VALUE_TYPE_SIGNED_INTEGER:
+               switch (display_base_value) {
+               case BT_FIELD_CLASS_INTEGER_PREFERRED_DISPLAY_BASE_HEXADECIMAL:
+                       std::cout << lttng::format("{} 0x{:X} 0x{:X}\n",
+                                                  key,
+                                                  std::uint64_t(bt_value_integer_signed_get(min)),
+                                                  std::uint64_t(bt_value_integer_signed_get(max)));
+                       break;
+               default:
+                       std::cout << lttng::format("{} {} {}\n",
+                                                  key,
+                                                  bt_value_integer_signed_get(min),
+                                                  bt_value_integer_signed_get(max));
+                       break;
+               }
+
+               break;
+       case BT_VALUE_TYPE_REAL:
+               std::cout << lttng::format(
+                       "{} {:0g} {:0g}\n", key, bt_value_real_get(min), bt_value_real_get(max));
+               break;
+       default:
+               abort();
+       }
+
+       return BT_VALUE_MAP_FOREACH_ENTRY_CONST_FUNC_STATUS_OK;
+}
+
+void member_stats_set_min_max(bt_value *member_map,
+                             const bt_field_class_structure_member *member,
+                             const bt_field *member_field,
+                             const bt_field_class *member_class,
+                             const bt_field_class_type *member_class_type)
+{
+       lttng::bt2::value_ref min, max, display_base;
+       const char *name = bt_field_class_structure_member_get_name(member);
+
+       if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_UNSIGNED_INTEGER)) {
+               min = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_integer_unsigned_get_value(member_field)));
+               max = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_integer_unsigned_get_value(member_field)));
+               display_base = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_class_integer_get_preferred_display_base(member_class)));
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_SIGNED_INTEGER)) {
+               min = lttng::bt2::make_value_ref(bt_value_integer_signed_create_init(
+                       bt_field_integer_signed_get_value(member_field)));
+               max = lttng::bt2::make_value_ref(bt_value_integer_signed_create_init(
+                       bt_field_integer_signed_get_value(member_field)));
+               display_base = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_class_integer_get_preferred_display_base(member_class)));
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_STRING)) {
+               min = lttng::bt2::make_value_ref(
+                       bt_value_string_create_init(bt_field_string_get_value(member_field)));
+               max = lttng::bt2::make_value_ref(
+                       bt_value_string_create_init(bt_field_string_get_value(member_field)));
+       } else if (bt_field_class_type_is(*member_class_type,
+                                         BT_FIELD_CLASS_TYPE_DOUBLE_PRECISION_REAL)) {
+               min = lttng::bt2::make_value_ref(bt_value_real_create_init(
+                       bt_field_real_double_precision_get_value(member_field)));
+               max = lttng::bt2::make_value_ref(bt_value_real_create_init(
+                       bt_field_real_double_precision_get_value(member_field)));
+       } else if (bt_field_class_type_is(*member_class_type,
+                                         BT_FIELD_CLASS_TYPE_SINGLE_PRECISION_REAL)) {
+               min = lttng::bt2::make_value_ref(bt_value_real_create_init(
+                       bt_field_real_single_precision_get_value(member_field)));
+               max = lttng::bt2::make_value_ref(bt_value_real_create_init(
+                       bt_field_real_single_precision_get_value(member_field)));
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_BIT_ARRAY)) {
+               min = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_bit_array_get_value_as_integer(member_field)));
+               max = lttng::bt2::make_value_ref(bt_value_integer_unsigned_create_init(
+                       bt_field_bit_array_get_value_as_integer(member_field)));
+       } else {
+               throw std::runtime_error(lttng::format(
+                       "Unsupported field type '{}' for member '{}'", *member_class_type, name));
+       }
+
+       if (min) {
+               bt_value_map_insert_entry(member_map, "min", min.get());
+       } else {
+               throw std::runtime_error(lttng::format("No minimum value for member '{}'", name));
+       }
+
+       if (max) {
+               bt_value_map_insert_entry(member_map, "max", max.get());
+       } else {
+               throw std::runtime_error(lttng::format("No maximum value for member '{}'", name));
+       }
+
+       if (display_base) {
+               bt_value_map_insert_entry(member_map, "display_base", display_base.get());
+       }
+}
+
+void member_stats_update_min_max(bt_value *member_map,
+                                const bt_field_class_structure_member *member,
+                                const bt_field *member_field,
+                                const bt_field_class_type *member_class_type)
+{
+       const char *name = bt_field_class_structure_member_get_name(member);
+       bt_value *min = bt_value_map_borrow_entry_value(member_map, "min");
+       bt_value *max = bt_value_map_borrow_entry_value(member_map, "max");
+
+       if (min == nullptr || max == nullptr) {
+               throw std::runtime_error(
+                       lttng::format("Missing min or max value for member '{}'", name));
+       }
+
+       if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_UNSIGNED_INTEGER)) {
+               const auto value = bt_field_integer_unsigned_get_value(member_field);
+
+               if (value < bt_value_integer_unsigned_get(min)) {
+                       bt_value_integer_unsigned_set(min, value);
+               }
+
+               if (value > bt_value_integer_unsigned_get(max)) {
+                       bt_value_integer_unsigned_set(max, value);
+               }
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_SIGNED_INTEGER)) {
+               const auto value = bt_field_integer_signed_get_value(member_field);
+
+               if (value < bt_value_integer_signed_get(min)) {
+                       bt_value_integer_signed_set(min, value);
+               }
+
+               if (value > bt_value_integer_signed_get(max)) {
+                       bt_value_integer_signed_set(max, value);
+               }
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_STRING)) {
+               const auto value = bt_field_string_get_value(member_field);
+
+               if (strcmp(value, bt_value_string_get(min)) < 0) {
+                       bt_value_string_set(min, value);
+               }
+
+               if (strcmp(value, bt_value_string_get(max)) > 0) {
+                       bt_value_string_set(max, value);
+               }
+       } else if (bt_field_class_type_is(*member_class_type,
+                                         BT_FIELD_CLASS_TYPE_DOUBLE_PRECISION_REAL)) {
+               const auto value = bt_field_real_double_precision_get_value(member_field);
+
+               if (value < bt_value_real_get(min)) {
+                       bt_value_real_set(min, value);
+               }
+
+               if (value > bt_value_real_get(max)) {
+                       bt_value_real_set(max, value);
+               }
+       } else if (bt_field_class_type_is(*member_class_type,
+                                         BT_FIELD_CLASS_TYPE_SINGLE_PRECISION_REAL)) {
+               const auto value = double(bt_field_real_single_precision_get_value(member_field));
+
+               if (value < bt_value_real_get(min)) {
+                       bt_value_real_set(min, value);
+               }
+
+               if (value > bt_value_real_get(max)) {
+                       bt_value_real_set(max, value);
+               }
+       } else if (bt_field_class_type_is(*member_class_type, BT_FIELD_CLASS_TYPE_BIT_ARRAY)) {
+               const auto value = bt_field_bit_array_get_value_as_integer(member_field);
+
+               if (value < bt_value_integer_unsigned_get(min)) {
+                       bt_value_integer_unsigned_set(min, value);
+               }
+
+               if (value > bt_value_integer_unsigned_get(max)) {
+                       bt_value_integer_unsigned_set(max, value);
+               }
+       } else {
+               throw std::runtime_error(lttng::format(
+                       "Unsupported field type '%{}' for member '{}'", *member_class_type, name));
+       }
+}
+
+bt_component_class_sink_consume_method_status
+update_stats(const bt_message *message,
+            field_stats& field_stats,
+            bt_self_component_sink *self_component_sink)
+{
+       if (bt_message_get_type(message) != BT_MESSAGE_TYPE_EVENT) {
+               /* It's not an error to get non-EVENT messages. */
+               return BT_COMPONENT_CLASS_SINK_CONSUME_METHOD_STATUS_OK;
+       }
+
+       const auto *event = bt_message_event_borrow_event_const(message);
+       const auto *event_payload = bt_event_borrow_payload_field_const(event);
+       const auto *event_class = bt_event_borrow_class_const(event);
+       const auto *event_payload_class =
+               bt_event_class_borrow_payload_field_class_const(event_class);
+
+       if (field_stats.event_class != nullptr) {
+               LTTNG_ASSERT(event_class == field_stats.event_class.get());
+       } else {
+               bt_event_class_get_ref(event_class);
+               field_stats.event_class.reset(event_class);
+       }
+
+       /* Iterate over each field in the event payload */
+       for (std::uint64_t index = 0;
+            index < bt_field_class_structure_get_member_count(event_payload_class);
+            index++) {
+               const bt_field_class_structure_member *member =
+                       bt_field_class_structure_borrow_member_by_index_const(event_payload_class,
+                                                                             index);
+               const auto *name = bt_field_class_structure_member_get_name(member);
+               const auto *member_field =
+                       bt_field_structure_borrow_member_field_by_name_const(event_payload, name);
+               const auto *member_class =
+                       bt_field_class_structure_member_borrow_field_class_const(member);
+               const auto member_class_type = bt_field_class_get_type(member_class);
+
+               if (bt_field_class_type_is(member_class_type, BT_FIELD_CLASS_TYPE_ARRAY) ||
+                   bt_field_class_type_is(member_class_type, BT_FIELD_CLASS_TYPE_STRUCTURE)) {
+                       /* Ignore array and structure field types. */
+                       continue;
+               }
+
+               try {
+                       auto *member_map = bt_value_map_borrow_entry_value(
+                               field_stats.stats_value.get(), name);
+                       if (member_map == nullptr) {
+                               /* Initial creation of the value. */
+                               if (bt_value_map_insert_empty_map_entry(
+                                           field_stats.stats_value.get(), name, &member_map) !=
+                                   BT_VALUE_MAP_INSERT_ENTRY_STATUS_OK) {
+                                       throw std::runtime_error(lttng::format(
+                                               "Failed to insert new empty map entry for field '{}'",
+                                               name));
+                               }
+
+                               member_stats_set_min_max(member_map,
+                                                        member,
+                                                        member_field,
+                                                        member_class,
+                                                        &member_class_type);
+                       } else {
+                               /* Update the value with min/max values. */
+                               member_stats_update_min_max(
+                                       member_map, member, member_field, &member_class_type);
+                       }
+               } catch (const std::exception& ex) {
+                       BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                               bt_self_component_sink_as_self_component(self_component_sink),
+                               "%s",
+                               ex.what());
+                       return BT_COMPONENT_CLASS_SINK_CONSUME_METHOD_STATUS_ERROR;
+               }
+       }
+
+       return BT_COMPONENT_CLASS_SINK_CONSUME_METHOD_STATUS_OK;
+}
+} /* namespace */
+
+bt_component_class_initialize_method_status
+field_stats_initialize(bt_self_component_sink *self_component_sink,
+                      bt_self_component_sink_configuration *,
+                      const bt_value *,
+                      void *)
+{
+       if (bt_self_component_sink_add_input_port(self_component_sink, "in", nullptr, nullptr) !=
+           BT_SELF_COMPONENT_ADD_PORT_STATUS_OK) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       bt_self_component_sink_as_self_component(self_component_sink),
+                       "Failed to add input port");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
+       }
+
+       std::unique_ptr<struct field_stats> field_stats;
+       try {
+               field_stats = lttng::make_unique<struct field_stats>();
+       } catch (const bad_alloc_with_msg& ex) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       bt_self_component_sink_as_self_component(self_component_sink),
+                       "%s",
+                       ex.what());
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
+       } catch (const std::bad_alloc&) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       bt_self_component_sink_as_self_component(self_component_sink),
+                       "Failed to allocate memory for private data");
+               return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
+       }
+
+       /* Transfer ownership to the component. */
+       bt_self_component_set_data(bt_self_component_sink_as_self_component(self_component_sink),
+                                  field_stats.release());
+       return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK;
+}
+
+void field_stats_finalize(bt_self_component_sink *self_component_sink)
+{
+       auto *field_stats = static_cast<struct field_stats *>(bt_self_component_get_data(
+               bt_self_component_sink_as_self_component(self_component_sink)));
+
+       delete field_stats;
+}
+
+bt_component_class_sink_graph_is_configured_method_status
+field_stats_graph_is_configured(bt_self_component_sink *self_component_sink)
+{
+       auto& field_stats = *static_cast<struct field_stats *>(bt_self_component_get_data(
+               bt_self_component_sink_as_self_component(self_component_sink)));
+       auto *input_port =
+               bt_self_component_sink_borrow_input_port_by_index(self_component_sink, 0);
+
+       bt_message_iterator *raw_iterator;
+       if (bt_message_iterator_create_from_sink_component(
+                   self_component_sink, input_port, &raw_iterator) !=
+           BT_MESSAGE_ITERATOR_CREATE_FROM_SINK_COMPONENT_STATUS_OK) {
+               BT_CURRENT_THREAD_ERROR_APPEND_CAUSE_FROM_COMPONENT(
+                       bt_self_component_sink_as_self_component(self_component_sink),
+                       "input port message iterator creation failed");
+               return BT_COMPONENT_CLASS_SINK_GRAPH_IS_CONFIGURED_METHOD_STATUS_ERROR;
+       }
+
+       field_stats.upstream_iterator.reset(raw_iterator);
+       return BT_COMPONENT_CLASS_SINK_GRAPH_IS_CONFIGURED_METHOD_STATUS_OK;
+}
+
+bt_component_class_sink_consume_method_status
+field_stats_consume(bt_self_component_sink *self_component_sink)
+{
+       auto& field_stats = *static_cast<struct field_stats *>(bt_self_component_get_data(
+               bt_self_component_sink_as_self_component(self_component_sink)));
+
+       std::uint64_t message_count;
+       bt_message_array_const messages;
+       const auto next_status = bt_message_iterator_next(
+               field_stats.upstream_iterator.get(), &messages, &message_count);
+
+       if (next_status != BT_MESSAGE_ITERATOR_NEXT_STATUS_OK) {
+               if (next_status == BT_MESSAGE_ITERATOR_NEXT_STATUS_END) {
+                       /* End reached, print the summary. */
+                       bt_value_map_foreach_entry_const(
+                               field_stats.stats_value.get(), stats_value_print_summary, nullptr);
+               }
+
+               return static_cast<bt_component_class_sink_consume_method_status>(next_status);
+       }
+
+       for (std::uint64_t index = 0; index < message_count; index++) {
+               const auto message = lttng::bt2::message_const_ref(messages[index]);
+
+               const auto status = update_stats(message.get(), field_stats, self_component_sink);
+               if (status != BT_COMPONENT_CLASS_SINK_CONSUME_METHOD_STATUS_OK) {
+                       return status;
+               }
+       }
+
+       return BT_COMPONENT_CLASS_SINK_CONSUME_METHOD_STATUS_OK;
+}
diff --git a/tests/utils/bt2_plugins/field_stats/field_stats.hpp b/tests/utils/bt2_plugins/field_stats/field_stats.hpp
new file mode 100644 (file)
index 0000000..b1977af
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_TEST_UTILS_BT2_PLUGIN_FIELD_STATS_HPP
+#define LTTNG_TEST_UTILS_BT2_PLUGIN_FIELD_STATS_HPP
+
+#include <babeltrace2/babeltrace.h>
+
+bt_component_class_initialize_method_status
+field_stats_initialize(bt_self_component_sink *self_component_sink,
+                      bt_self_component_sink_configuration *config,
+                      const bt_value *params,
+                      void *initialize_method_data);
+
+void field_stats_finalize(bt_self_component_sink *self_component_sink);
+
+bt_component_class_sink_graph_is_configured_method_status
+field_stats_graph_is_configured(bt_self_component_sink *self_component_sink);
+
+bt_component_class_sink_consume_method_status
+field_stats_consume(bt_self_component_sink *self_component_sink);
+
+#endif /* LTTNG_TEST_UTILS_BT2_PLUGIN_FIELD_STATS_HPP */
diff --git a/tests/utils/bt2_plugins/fmt.hpp b/tests/utils/bt2_plugins/fmt.hpp
new file mode 100644 (file)
index 0000000..d5c0857
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2024 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_TESTS_UTILS_BT2_PLUGINS_FMT_H
+#define LTTNG_TESTS_UTILS_BT2_PLUGINS_FMT_H
+
+#include <common/format.hpp>
+
+#include <babeltrace2/babeltrace.h>
+
+/*
+ * Due to a bug in g++ < 7.1, this specialization must be enclosed in the fmt namespace,
+ * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480.
+ */
+namespace fmt {
+template <>
+struct formatter<bt_field_class_type> : formatter<std::string> {
+       template <typename FormatContextType>
+       typename FormatContextType::iterator format(const bt_field_class_type field_class_type,
+                                                   FormatContextType& ctx)
+       {
+               const char *name;
+
+               switch (field_class_type) {
+               case BT_FIELD_CLASS_TYPE_BOOL:
+                       name = "BOOL";
+                       break;
+               case BT_FIELD_CLASS_TYPE_BIT_ARRAY:
+                       name = "BIT_ARRAY";
+                       break;
+               case BT_FIELD_CLASS_TYPE_INTEGER:
+                       name = "INTEGER";
+                       break;
+               case BT_FIELD_CLASS_TYPE_UNSIGNED_INTEGER:
+                       name = "UNSIGNED_INTEGER";
+                       break;
+               case BT_FIELD_CLASS_TYPE_SIGNED_INTEGER:
+                       name = "SIGNED_INTEGER";
+                       break;
+               case BT_FIELD_CLASS_TYPE_ENUMERATION:
+                       name = "ENUMERATION";
+                       break;
+               case BT_FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION:
+                       name = "UNSIGNED_ENUMERATION";
+                       break;
+               case BT_FIELD_CLASS_TYPE_SIGNED_ENUMERATION:
+                       name = "SIGNED_ENUMERATION";
+                       break;
+               case BT_FIELD_CLASS_TYPE_REAL:
+                       name = "REAL";
+                       break;
+               case BT_FIELD_CLASS_TYPE_SINGLE_PRECISION_REAL:
+                       name = "SINGLE_PRECISION_REAL";
+                       break;
+               case BT_FIELD_CLASS_TYPE_DOUBLE_PRECISION_REAL:
+                       name = "DOUBLE_PRECISION_REAL";
+                       break;
+               case BT_FIELD_CLASS_TYPE_STRING:
+                       name = "STRING";
+                       break;
+               case BT_FIELD_CLASS_TYPE_STRUCTURE:
+                       name = "STRUCTURE";
+                       break;
+               case BT_FIELD_CLASS_TYPE_ARRAY:
+                       name = "ARRAY";
+                       break;
+               case BT_FIELD_CLASS_TYPE_STATIC_ARRAY:
+                       name = "STATIC_ARRAY";
+                       break;
+               case BT_FIELD_CLASS_TYPE_DYNAMIC_ARRAY:
+                       name = "DYNAMIC_ARRAY";
+                       break;
+               case BT_FIELD_CLASS_TYPE_DYNAMIC_ARRAY_WITHOUT_LENGTH_FIELD:
+                       name = "DYNAMIC_ARRAY_WITHOUT_LENGTH_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_DYNAMIC_ARRAY_WITH_LENGTH_FIELD:
+                       name = "DYNAMIC_ARRAY_WITH_LENGTH_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION:
+                       name = "OPTION";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITHOUT_SELECTOR_FIELD:
+                       name = "OPTION_WITHOUT_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITH_SELECTOR_FIELD:
+                       name = "OPTION_WITH_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITH_BOOL_SELECTOR_FIELD:
+                       name = "OPTION_WITH_BOOL_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITH_INTEGER_SELECTOR_FIELD:
+                       name = "OPTION_WITH_INTEGER_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITH_UNSIGNED_INTEGER_SELECTOR_FIELD:
+                       name = "OPTION_WITH_UNSIGNED_INTEGER_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_OPTION_WITH_SIGNED_INTEGER_SELECTOR_FIELD:
+                       name = "OPTION_WITH_SIGNED_INTEGER_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT:
+                       name = "VARIANT";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR_FIELD:
+                       name = "VARIANT_WITHOUT_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT_WITH_SELECTOR_FIELD:
+                       name = "VARIANT_WITH_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT_WITH_INTEGER_SELECTOR_FIELD:
+                       name = "VARIANT_WITH_INTEGER_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_INTEGER_SELECTOR_FIELD:
+                       name = "VARIANT_WITH_UNSIGNED_INTEGER_SELECTOR_FIELD";
+                       break;
+               case BT_FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_INTEGER_SELECTOR_FIELD:
+                       name = "VARIANT_WITH_SIGNED_INTEGER_SELECTOR_FIELD";
+                       break;
+               default:
+                       abort();
+               }
+
+               return format_to(ctx.out(), name);
+       }
+};
+} /* namespace fmt */
+
+#endif /* LTTNG_TESTS_UTILS_BT2_PLUGINS_FMT_H */
diff --git a/tests/utils/bt2_plugins/lttngtest-plugin.cpp b/tests/utils/bt2_plugins/lttngtest-plugin.cpp
new file mode 100644 (file)
index 0000000..ef6d6d2
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#include "event_name/event_name.hpp"
+#include "field_stats/field_stats.hpp"
+
+#include <babeltrace2/babeltrace.h>
+
+BT_PLUGIN_MODULE();
+
+BT_PLUGIN(lttngtest);
+BT_PLUGIN_DESCRIPTION("Filter and sink used in lttng-tools test suite");
+BT_PLUGIN_AUTHOR("Kienan Stewart");
+BT_PLUGIN_LICENSE("LGPL-2.1-only");
+
+/* flt.lttngtest.event_name */
+/* Filter class to pass events matching given names */
+BT_PLUGIN_FILTER_COMPONENT_CLASS(event_name, event_name_message_iterator_next);
+BT_PLUGIN_FILTER_COMPONENT_CLASS_DESCRIPTION(event_name, "Filter events by tracepoint name(s)");
+BT_PLUGIN_FILTER_COMPONENT_CLASS_INITIALIZE_METHOD(event_name, event_name_initialize);
+BT_PLUGIN_FILTER_COMPONENT_CLASS_FINALIZE_METHOD(event_name, event_name_finalize);
+BT_PLUGIN_FILTER_COMPONENT_CLASS_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD(
+       event_name, event_name_message_iterator_initialize);
+BT_PLUGIN_FILTER_COMPONENT_CLASS_MESSAGE_ITERATOR_CLASS_FINALIZE_METHOD(
+       event_name, event_name_message_iterator_finalize);
+
+/* sink.lttngtest.field_stats */
+/* Sink class to produce certain statistics for seen fields */
+BT_PLUGIN_SINK_COMPONENT_CLASS(field_stats, field_stats_consume);
+BT_PLUGIN_SINK_COMPONENT_CLASS_DESCRIPTION(field_stats,
+                                          "Track minimum and maxiumum values of seen fields");
+BT_PLUGIN_SINK_COMPONENT_CLASS_INITIALIZE_METHOD(field_stats, field_stats_initialize);
+BT_PLUGIN_SINK_COMPONENT_CLASS_FINALIZE_METHOD(field_stats, field_stats_finalize);
+BT_PLUGIN_SINK_COMPONENT_CLASS_GRAPH_IS_CONFIGURED_METHOD(field_stats,
+                                                         field_stats_graph_is_configured);
diff --git a/tests/utils/bt2_plugins/utils.hpp b/tests/utils/bt2_plugins/utils.hpp
new file mode 100644 (file)
index 0000000..1d306fd
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2024 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef LTTNG_TEST_UTILS_BT2_PLUGIN_UTILS_HPP
+#define LTTNG_TEST_UTILS_BT2_PLUGIN_UTILS_HPP
+
+#include <common/make-unique-wrapper.hpp>
+
+#include <babeltrace2/babeltrace.h>
+
+namespace lttng {
+namespace bt2 {
+namespace internal {
+static inline void bt_value_put_ref(bt_value *value)
+{
+       bt_value_put_ref(static_cast<const bt_value *>(value));
+}
+} /* namespace internal */
+
+using value_ref = std::unique_ptr<
+       bt_value,
+       lttng::memory::create_deleter_class<bt_value, internal::bt_value_put_ref>::deleter>;
+
+using event_class_const_ref = std::unique_ptr<
+       const bt_event_class,
+       lttng::memory::create_deleter_class<const bt_event_class, bt_event_class_put_ref>::deleter>;
+
+static inline value_ref make_value_ref(bt_value *instance)
+{
+       const memory::create_deleter_class<bt_value, internal::bt_value_put_ref> unique_deleter;
+       return unique_deleter(instance);
+}
+
+using message_const_ref = std::unique_ptr<
+       const bt_message,
+       lttng::memory::create_deleter_class<const bt_message, bt_message_put_ref>::deleter>;
+
+using message_iterator_ref =
+       std::unique_ptr<bt_message_iterator,
+                       lttng::memory::create_deleter_class<const bt_message_iterator,
+                                                           bt_message_iterator_put_ref>::deleter>;
+} /* namespace bt2 */
+} /* namespace lttng */
+
+#endif /* LTTNG_TEST_UTILS_BT2_PLUGIN_UTILS_HPP */
diff --git a/tests/utils/lttngtest/Makefile.am b/tests/utils/lttngtest/Makefile.am
new file mode 100644 (file)
index 0000000..a78c626
--- /dev/null
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+EXTRA_DIST = __init__.py \
+       environment.py \
+       logger.py \
+       lttngctl.py \
+       lttng.py \
+       tap_generator.py
+
+dist_noinst_SCRIPTS = __init__.py \
+       environment.py \
+       logger.py \
+       lttngctl.py \
+       lttng.py \
+       tap_generator.py
+
+all-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       cp -f $(srcdir)/$$script $(builddir); \
+               done; \
+       fi
+
+clean-local:
+       @if [ x"$(srcdir)" != x"$(builddir)" ]; then \
+               for script in $(EXTRA_DIST); do \
+                       rm -f $(builddir)/$$script; \
+               done; \
+       fi
diff --git a/tests/utils/lttngtest/__init__.py b/tests/utils/lttngtest/__init__.py
new file mode 100644 (file)
index 0000000..3676667
--- /dev/null
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+from .tap_generator import *
+from .environment import *
+from .environment import _Environment
+from .lttngctl import *
+from .lttng import *
diff --git a/tests/utils/lttngtest/environment.py b/tests/utils/lttngtest/environment.py
new file mode 100644 (file)
index 0000000..74dcfb8
--- /dev/null
@@ -0,0 +1,671 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+from types import FrameType
+from typing import Callable, Iterator, Optional, Tuple, List, Generator
+import sys
+import pathlib
+import signal
+import subprocess
+import shlex
+import shutil
+import os
+import queue
+import tempfile
+from . import logger
+import time
+import threading
+import contextlib
+
+
+class TemporaryDirectory:
+    def __init__(self, prefix):
+        # type: (str) -> None
+        self._directory_path = tempfile.mkdtemp(prefix=prefix)
+
+    def __del__(self):
+        shutil.rmtree(self._directory_path, ignore_errors=True)
+
+    @property
+    def path(self):
+        # type: () -> pathlib.Path
+        return pathlib.Path(self._directory_path)
+
+
+class _SignalWaitQueue:
+    """
+    Utility class useful to wait for a signal before proceeding.
+
+    Simply register the `signal` method as the handler for the signal you are
+    interested in and call `wait_for_signal` to wait for its reception.
+
+    Registering a signal:
+        signal.signal(signal.SIGWHATEVER, queue.signal)
+
+    Waiting for the signal:
+        queue.wait_for_signal()
+    """
+
+    def __init__(self):
+        self._queue = queue.Queue()  # type: queue.Queue
+
+    def signal(
+        self,
+        signal_number,
+        frame,  # type: Optional[FrameType]
+    ):
+        self._queue.put_nowait(signal_number)
+
+    def wait_for_signal(self):
+        self._queue.get(block=True)
+
+    @contextlib.contextmanager
+    def intercept_signal(self, signal_number):
+        # type: (int) -> Generator[None, None, None]
+        original_handler = signal.getsignal(signal_number)
+        signal.signal(signal_number, self.signal)
+        try:
+            yield
+        except:
+            # Restore the original signal handler and forward the exception.
+            raise
+        finally:
+            signal.signal(signal_number, original_handler)
+
+
+class _WaitTraceTestApplication:
+    """
+    Create an application that waits before tracing. This allows a test to
+    launch an application, get its PID, and get it to start tracing when it
+    has completed its setup.
+    """
+
+    def __init__(
+        self,
+        binary_path,  # type: pathlib.Path
+        event_count,  # type: int
+        environment,  # type: Environment
+        wait_time_between_events_us=0,  # type: int
+        wait_before_exit=False,  # type: bool
+        wait_before_exit_file_path=None,  # type: Optional[pathlib.Path]
+    ):
+        self._process = None
+        self._environment = environment  # type: Environment
+        self._iteration_count = event_count
+        # File that the application will wait to see before tracing its events.
+        self._app_start_tracing_file_path = pathlib.Path(
+            tempfile.mktemp(
+                prefix="app_",
+                suffix="_start_tracing",
+                dir=self._compat_pathlike(environment.lttng_home_location),
+            )
+        )
+        # File that the application will create when all events have been emitted.
+        self._app_tracing_done_file_path = pathlib.Path(
+            tempfile.mktemp(
+                prefix="app_",
+                suffix="_done_tracing",
+                dir=self._compat_pathlike(environment.lttng_home_location),
+            )
+        )
+
+        if wait_before_exit and wait_before_exit_file_path is None:
+            wait_before_exit_file_path = pathlib.Path(
+                tempfile.mktemp(
+                    prefix="app_",
+                    suffix="_exit",
+                    dir=self._compat_pathlike(environment.lttng_home_location),
+                )
+            )
+
+        self._has_returned = False
+
+        test_app_env = os.environ.copy()
+        test_app_env["LTTNG_HOME"] = str(environment.lttng_home_location)
+        # Make sure the app is blocked until it is properly registered to
+        # the session daemon.
+        test_app_env["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
+
+        # File that the application will create to indicate it has completed its initialization.
+        app_ready_file_path = tempfile.mktemp(
+            prefix="app_",
+            suffix="_ready",
+            dir=self._compat_pathlike(environment.lttng_home_location),
+        )  # type: str
+
+        test_app_args = [str(binary_path)]
+        test_app_args.extend(["--iter", str(event_count)])
+        test_app_args.extend(
+            ["--sync-application-in-main-touch", str(app_ready_file_path)]
+        )
+        test_app_args.extend(
+            ["--sync-before-first-event", str(self._app_start_tracing_file_path)]
+        )
+        test_app_args.extend(
+            ["--sync-before-exit-touch", str(self._app_tracing_done_file_path)]
+        )
+        if wait_time_between_events_us != 0:
+            test_app_args.extend(["--wait", str(wait_time_between_events_us)])
+
+        self._process = subprocess.Popen(
+            test_app_args,
+            env=test_app_env,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+        )  # type: subprocess.Popen
+
+        # Wait for the application to create the file indicating it has fully
+        # initialized. Make sure the app hasn't crashed in order to not wait
+        # forever.
+        self._wait_for_file_to_be_created(pathlib.Path(app_ready_file_path))
+
+    def _wait_for_file_to_be_created(self, sync_file_path):
+        # type: (pathlib.Path) -> None
+        while True:
+            if os.path.exists(self._compat_pathlike(sync_file_path)):
+                break
+
+            if self._process.poll() is not None:
+                # Application has unexepectedly returned.
+                raise RuntimeError(
+                    "Test application has unexepectedly returned while waiting for synchronization file to be created: sync_file=`{sync_file}`, return_code=`{return_code}`".format(
+                        sync_file=sync_file_path, return_code=self._process.returncode
+                    )
+                )
+
+            time.sleep(0.001)
+
+    def trace(self):
+        # type: () -> None
+        if self._process.poll() is not None:
+            # Application has unexepectedly returned.
+            raise RuntimeError(
+                "Test application has unexepectedly before tracing with return code `{return_code}`".format(
+                    return_code=self._process.returncode
+                )
+            )
+        open(self._compat_pathlike(self._app_start_tracing_file_path), mode="x")
+
+    def wait_for_tracing_done(self):
+        # type: () -> None
+        self._wait_for_file_to_be_created(self._app_tracing_done_file_path)
+
+    def wait_for_exit(self):
+        # type: () -> None
+        if self._process.wait() != 0:
+            raise RuntimeError(
+                "Test application has exit with return code `{return_code}`".format(
+                    return_code=self._process.returncode
+                )
+            )
+        self._has_returned = True
+
+    @property
+    def vpid(self):
+        # type: () -> int
+        return self._process.pid
+
+    @staticmethod
+    def _compat_pathlike(path):
+        # type: (pathlib.Path) -> pathlib.Path | str
+        """
+        The builtin open() and many methods of the 'os' library in Python >= 3.6
+        expect a path-like object while prior versions expect a string or
+        bytes object. Return the correct type based on the presence of the
+        "__fspath__" attribute specified in PEP-519.
+        """
+        if hasattr(path, "__fspath__"):
+            return path
+        else:
+            return str(path)
+
+    def __del__(self):
+        if self._process is not None and not self._has_returned:
+            # This is potentially racy if the pid has been recycled. However,
+            # we can't use pidfd_open since it is only available in python >= 3.9.
+            self._process.kill()
+            self._process.wait()
+
+
+class WaitTraceTestApplicationGroup:
+    def __init__(
+        self,
+        environment,  # type: Environment
+        application_count,  # type: int
+        event_count,  # type: int
+        wait_time_between_events_us=0,  # type: int
+        wait_before_exit=False,  # type: bool
+    ):
+        self._wait_before_exit_file_path = (
+            pathlib.Path(
+                tempfile.mktemp(
+                    prefix="app_group_",
+                    suffix="_exit",
+                    dir=_WaitTraceTestApplication._compat_pathlike(
+                        environment.lttng_home_location
+                    ),
+                )
+            )
+            if wait_before_exit
+            else None
+        )
+
+        self._apps = []
+        self._consumers = []
+        for i in range(application_count):
+            new_app = environment.launch_wait_trace_test_application(
+                event_count,
+                wait_time_between_events_us,
+                wait_before_exit,
+                self._wait_before_exit_file_path,
+            )
+
+            # Attach an output consumer to log the application's error output (if any).
+            if environment._logging_function:
+                app_output_consumer = ProcessOutputConsumer(
+                    new_app._process,
+                    "app-{}".format(str(new_app.vpid)),
+                    environment._logging_function,
+                )  # type: Optional[ProcessOutputConsumer]
+                app_output_consumer.daemon = True
+                app_output_consumer.start()
+                self._consumers.append(app_output_consumer)
+
+            self._apps.append(new_app)
+
+    def trace(self):
+        # type: () -> None
+        for app in self._apps:
+            app.trace()
+
+    def exit(
+        self, wait_for_apps=False  # type: bool
+    ):
+        if self._wait_before_exit_file_path is None:
+            raise RuntimeError(
+                "Can't call exit on an application group created with `wait_before_exit=False`"
+            )
+
+        # Wait for apps to have produced all of their events so that we can
+        # cause the death of all apps to happen within a short time span.
+        for app in self._apps:
+            app.wait_for_tracing_done()
+
+        open(
+            _WaitTraceTestApplication._compat_pathlike(
+                self._wait_before_exit_file_path
+            ),
+            mode="x",
+        )
+        # Performed in two passes to allow tests to stress the unregistration of many applications.
+        # Waiting for each app to exit turn-by-turn would defeat the purpose here.
+        if wait_for_apps:
+            for app in self._apps:
+                app.wait_for_exit()
+
+
+class _TraceTestApplication:
+    """
+    Create an application that emits events as soon as it is launched. In most
+    scenarios, it is preferable to use a WaitTraceTestApplication.
+    """
+
+    def __init__(self, binary_path, environment):
+        # type: (pathlib.Path, Environment)
+        self._process = None
+        self._environment = environment  # type: Environment
+        self._has_returned = False
+
+        test_app_env = os.environ.copy()
+        test_app_env["LTTNG_HOME"] = str(environment.lttng_home_location)
+        # Make sure the app is blocked until it is properly registered to
+        # the session daemon.
+        test_app_env["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
+
+        test_app_args = [str(binary_path)]
+
+        self._process = subprocess.Popen(
+            test_app_args, env=test_app_env
+        )  # type: subprocess.Popen
+
+    def wait_for_exit(self):
+        # type: () -> None
+        if self._process.wait() != 0:
+            raise RuntimeError(
+                "Test application has exit with return code `{return_code}`".format(
+                    return_code=self._process.returncode
+                )
+            )
+        self._has_returned = True
+
+    def __del__(self):
+        if self._process is not None and not self._has_returned:
+            # This is potentially racy if the pid has been recycled. However,
+            # we can't use pidfd_open since it is only available in python >= 3.9.
+            self._process.kill()
+            self._process.wait()
+
+
+class ProcessOutputConsumer(threading.Thread, logger._Logger):
+    def __init__(
+        self,
+        process,  # type: subprocess.Popen
+        name,  # type: str
+        log,  # type: Callable[[str], None]
+    ):
+        threading.Thread.__init__(self)
+        self._prefix = name
+        logger._Logger.__init__(self, log)
+        self._process = process
+
+    def run(self):
+        # type: () -> None
+        while self._process.poll() is None:
+            assert self._process.stdout
+            line = self._process.stdout.readline().decode("utf-8").replace("\n", "")
+            if len(line) != 0:
+                self._log("{prefix}: {line}".format(prefix=self._prefix, line=line))
+
+
+# Generate a temporary environment in which to execute a test.
+class _Environment(logger._Logger):
+    def __init__(
+        self,
+        with_sessiond,  # type: bool
+        log=None,  # type: Optional[Callable[[str], None]]
+        with_relayd=False,  # type: bool
+    ):
+        super().__init__(log)
+        signal.signal(signal.SIGTERM, self._handle_termination_signal)
+        signal.signal(signal.SIGINT, self._handle_termination_signal)
+
+        # Assumes the project's hierarchy to this file is:
+        # tests/utils/python/this_file
+        self._project_root = (
+            pathlib.Path(__file__).absolute().parents[3]
+        )  # type: pathlib.Path
+        self._lttng_home = TemporaryDirectory(
+            "lttng_test_env_home"
+        )  # type: Optional[TemporaryDirectory]
+
+        self._relayd = (
+            self._launch_lttng_relayd() if with_relayd else None
+        )  # type: Optional[subprocess.Popen[bytes]]
+        self._relayd_output_consumer = None
+
+        self._sessiond = (
+            self._launch_lttng_sessiond() if with_sessiond else None
+        )  # type: Optional[subprocess.Popen[bytes]]
+
+    @property
+    def lttng_home_location(self):
+        # type: () -> pathlib.Path
+        if self._lttng_home is None:
+            raise RuntimeError("Attempt to access LTTng home after clean-up")
+        return self._lttng_home.path
+
+    @property
+    def lttng_client_path(self):
+        # type: () -> pathlib.Path
+        return self._project_root / "src" / "bin" / "lttng" / "lttng"
+
+    @property
+    def lttng_relayd_control_port(self):
+        # type: () -> int
+        return 5400
+
+    @property
+    def lttng_relayd_data_port(self):
+        # type: () -> int
+        return 5401
+
+    @property
+    def lttng_relayd_live_port(self):
+        # type: () -> int
+        return 5402
+
+    def create_temporary_directory(self, prefix=None):
+        # type: (Optional[str]) -> pathlib.Path
+        # Simply return a path that is contained within LTTNG_HOME; it will
+        # be destroyed when the temporary home goes out of scope.
+        assert self._lttng_home
+        return pathlib.Path(
+            tempfile.mkdtemp(
+                prefix="tmp" if prefix is None else prefix,
+                dir=str(self._lttng_home.path),
+            )
+        )
+
+    # Unpack a list of environment variables from a string
+    # such as "HELLO=is_it ME='/you/are/looking/for'"
+    @staticmethod
+    def _unpack_env_vars(env_vars_string):
+        # type: (str) -> List[Tuple[str, str]]
+        unpacked_vars = []
+        for var in shlex.split(env_vars_string):
+            equal_position = var.find("=")
+            # Must have an equal sign and not end with an equal sign
+            if equal_position == -1 or equal_position == len(var) - 1:
+                raise ValueError(
+                    "Invalid sessiond environment variable: `{}`".format(var)
+                )
+
+            var_name = var[0:equal_position]
+            var_value = var[equal_position + 1 :]
+            # Unquote any paths
+            var_value = var_value.replace("'", "")
+            var_value = var_value.replace('"', "")
+            unpacked_vars.append((var_name, var_value))
+
+        return unpacked_vars
+
+    def _launch_lttng_relayd(self):
+        # type: () -> Optional[subprocess.Popen]
+        relayd_path = (
+            self._project_root / "src" / "bin" / "lttng-relayd" / "lttng-relayd"
+        )
+        if os.environ.get("LTTNG_TEST_NO_RELAYD", "0") == "1":
+            # Run without a relay daemon; the user may be running one
+            # under gdb, for example.
+            return None
+
+        relayd_env_vars = os.environ.get("LTTNG_RELAYD_ENV_VARS")
+        relayd_env = os.environ.copy()
+        if relayd_env_vars:
+            self._log("Additional lttng-relayd environment variables:")
+            for name, value in self._unpack_env_vars(relayd_env_vars):
+                self._log("{}={}".format(name, value))
+                relayd_env[name] = value
+
+        assert self._lttng_home is not None
+        relayd_env["LTTNG_HOME"] = str(self._lttng_home.path)
+        self._log(
+            "Launching relayd with LTTNG_HOME='${}'".format(str(self._lttng_home.path))
+        )
+        process = subprocess.Popen(
+            [
+                str(relayd_path),
+                "-C",
+                "tcp://0.0.0.0:{}".format(self.lttng_relayd_control_port),
+                "-D",
+                "tcp://0.0.0.0:{}".format(self.lttng_relayd_data_port),
+                "-L",
+                "tcp://localhost:{}".format(self.lttng_relayd_live_port),
+            ],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            env=relayd_env,
+        )
+
+        if self._logging_function:
+            self._relayd_output_consumer = ProcessOutputConsumer(
+                process, "lttng-relayd", self._logging_function
+            )
+            self._relayd_output_consumer.daemon = True
+            self._relayd_output_consumer.start()
+
+        return process
+
+    def _launch_lttng_sessiond(self):
+        # type: () -> Optional[subprocess.Popen]
+        is_64bits_host = sys.maxsize > 2**32
+
+        sessiond_path = (
+            self._project_root / "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
+        )
+        consumerd_path_option_name = "--consumerd{bitness}-path".format(
+            bitness="64" if is_64bits_host else "32"
+        )
+        consumerd_path = (
+            self._project_root / "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
+        )
+
+        no_sessiond_var = os.environ.get("TEST_NO_SESSIOND")
+        if no_sessiond_var and no_sessiond_var == "1":
+            # Run test without a session daemon; the user probably
+            # intends to run one under gdb for example.
+            return None
+
+        # Setup the session daemon's environment
+        sessiond_env_vars = os.environ.get("LTTNG_SESSIOND_ENV_VARS")
+        sessiond_env = os.environ.copy()
+        if sessiond_env_vars:
+            self._log("Additional lttng-sessiond environment variables:")
+            additional_vars = self._unpack_env_vars(sessiond_env_vars)
+            for var_name, var_value in additional_vars:
+                self._log("  {name}={value}".format(name=var_name, value=var_value))
+                sessiond_env[var_name] = var_value
+
+        sessiond_env["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
+            self._project_root / "src" / "common"
+        )
+
+        assert self._lttng_home is not None
+        sessiond_env["LTTNG_HOME"] = str(self._lttng_home.path)
+
+        wait_queue = _SignalWaitQueue()
+        with wait_queue.intercept_signal(signal.SIGUSR1):
+            self._log(
+                "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
+                    home_dir=str(self._lttng_home.path)
+                )
+            )
+            process = subprocess.Popen(
+                [
+                    str(sessiond_path),
+                    consumerd_path_option_name,
+                    str(consumerd_path),
+                    "--sig-parent",
+                ],
+                stdout=subprocess.PIPE,
+                stderr=subprocess.STDOUT,
+                env=sessiond_env,
+            )
+
+            if self._logging_function:
+                self._sessiond_output_consumer = ProcessOutputConsumer(
+                    process, "lttng-sessiond", self._logging_function
+                )  # type: Optional[ProcessOutputConsumer]
+                self._sessiond_output_consumer.daemon = True
+                self._sessiond_output_consumer.start()
+
+            # Wait for SIGUSR1, indicating the sessiond is ready to proceed
+            wait_queue.wait_for_signal()
+
+        return process
+
+    def _handle_termination_signal(self, signal_number, frame):
+        # type: (int, Optional[FrameType]) -> None
+        self._log(
+            "Killed by {signal_name} signal, cleaning-up".format(
+                signal_name=signal.strsignal(signal_number)
+            )
+        )
+        self._cleanup()
+
+    def launch_wait_trace_test_application(
+        self,
+        event_count,  # type: int
+        wait_time_between_events_us=0,
+        wait_before_exit=False,
+        wait_before_exit_file_path=None,
+    ):
+        # type: (int, int, bool, Optional[pathlib.Path]) -> _WaitTraceTestApplication
+        """
+        Launch an application that will wait before tracing `event_count` events.
+        """
+        return _WaitTraceTestApplication(
+            self._project_root
+            / "tests"
+            / "utils"
+            / "testapp"
+            / "gen-ust-events"
+            / "gen-ust-events",
+            event_count,
+            self,
+            wait_time_between_events_us,
+            wait_before_exit,
+            wait_before_exit_file_path,
+        )
+
+    def launch_test_application(self, subpath):
+        # type () -> TraceTestApplication
+        """
+        Launch an application that will trace from within constructors.
+        """
+        return _TraceTestApplication(
+            self._project_root
+            / "tests"
+            / "utils"
+            / "testapp"
+            / subpath,
+            self,
+        )
+
+    # Clean-up managed processes
+    def _cleanup(self):
+        # type: () -> None
+        if self._sessiond and self._sessiond.poll() is None:
+            # The session daemon is alive; kill it.
+            self._log(
+                "Killing session daemon (pid = {sessiond_pid})".format(
+                    sessiond_pid=self._sessiond.pid
+                )
+            )
+
+            self._sessiond.terminate()
+            self._sessiond.wait()
+            if self._sessiond_output_consumer:
+                self._sessiond_output_consumer.join()
+                self._sessiond_output_consumer = None
+
+            self._log("Session daemon killed")
+            self._sessiond = None
+
+        if self._relayd and self._relayd.poll() is None:
+            self._relayd.terminate()
+            self._relayd.wait()
+            if self._relayd_output_consumer:
+                self._relayd_output_consumer.join()
+                self._relayd_output_consumer = None
+            self._log("Relayd killed")
+            self._relayd = None
+
+        self._lttng_home = None
+
+    def __del__(self):
+        self._cleanup()
+
+
+@contextlib.contextmanager
+def test_environment(with_sessiond, log=None, with_relayd=False):
+    # type: (bool, Optional[Callable[[str], None]], bool) -> Iterator[_Environment]
+    env = _Environment(with_sessiond, log, with_relayd)
+    try:
+        yield env
+    finally:
+        env._cleanup()
diff --git a/tests/utils/lttngtest/logger.py b/tests/utils/lttngtest/logger.py
new file mode 100644 (file)
index 0000000..b0363d1
--- /dev/null
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+from typing import Callable, Optional
+
+
+class _Logger:
+    def __init__(self, log):
+        # type: (Optional[Callable[[str], None]]) -> None
+        self._logging_function = log  # type: Optional[Callable[[str], None]]
+
+    def _log(self, msg):
+        # type: (str) -> None
+        if self._logging_function:
+            self._logging_function(msg)
+
+    @property
+    def logger(self):
+        # type: () -> Optional[Callable[[str], None]]
+        return self._logging_function
diff --git a/tests/utils/lttngtest/lttng.py b/tests/utils/lttngtest/lttng.py
new file mode 100644 (file)
index 0000000..3598cc9
--- /dev/null
@@ -0,0 +1,807 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+
+from . import lttngctl, logger, environment
+import os
+from typing import Callable, Optional, Type, Union, Iterator
+import shlex
+import subprocess
+import enum
+import xml.etree.ElementTree
+
+"""
+Implementation of the lttngctl interface based on the `lttng` command line client.
+"""
+
+
+class Unsupported(lttngctl.ControlException):
+    def __init__(self, msg):
+        # type: (str) -> None
+        super().__init__(msg)
+
+
+class InvalidMI(lttngctl.ControlException):
+    def __init__(self, msg):
+        # type: (str) -> None
+        super().__init__(msg)
+
+
+class ChannelNotFound(lttngctl.ControlException):
+    def __init__(self, msg):
+        # type: (str) -> None
+        super().__init__(msg)
+
+
+def _get_domain_option_name(domain):
+    # type: (lttngctl.TracingDomain) -> str
+    return {
+        lttngctl.TracingDomain.User: "userspace",
+        lttngctl.TracingDomain.Kernel: "kernel",
+        lttngctl.TracingDomain.Log4j: "log4j",
+        lttngctl.TracingDomain.Python: "python",
+        lttngctl.TracingDomain.JUL: "jul",
+    }[domain]
+
+
+def _get_domain_xml_mi_name(domain):
+    # type: (lttngctl.TracingDomain) -> str
+    return {
+        lttngctl.TracingDomain.User: "UST",
+        lttngctl.TracingDomain.Kernel: "KERNEL",
+        lttngctl.TracingDomain.Log4j: "LOG4J",
+        lttngctl.TracingDomain.Python: "PYTHON",
+        lttngctl.TracingDomain.JUL: "JUL",
+    }[domain]
+
+
+def _get_context_type_name(context):
+    # type: (lttngctl.ContextType) -> str
+    if isinstance(context, lttngctl.VgidContextType):
+        return "vgid"
+    elif isinstance(context, lttngctl.VuidContextType):
+        return "vuid"
+    elif isinstance(context, lttngctl.VpidContextType):
+        return "vpid"
+    elif isinstance(context, lttngctl.JavaApplicationContextType):
+        return "$app.{retriever}:{field}".format(
+            retriever=context.retriever_name, field=context.field_name
+        )
+    else:
+        raise Unsupported(
+            "Context `{context_name}` is not supported by the LTTng client".format(
+                type(context).__name__
+            )
+        )
+
+
+def _get_log_level_argument_name(log_level):
+    # type: (lttngctl.LogLevel) -> str
+    if isinstance(log_level, lttngctl.UserLogLevel):
+        return {
+            lttngctl.UserLogLevel.EMERGENCY: "EMER",
+            lttngctl.UserLogLevel.ALERT: "ALERT",
+            lttngctl.UserLogLevel.CRITICAL: "CRIT",
+            lttngctl.UserLogLevel.ERROR: "ERR",
+            lttngctl.UserLogLevel.WARNING: "WARNING",
+            lttngctl.UserLogLevel.NOTICE: "NOTICE",
+            lttngctl.UserLogLevel.INFO: "INFO",
+            lttngctl.UserLogLevel.DEBUG_SYSTEM: "DEBUG_SYSTEM",
+            lttngctl.UserLogLevel.DEBUG_PROGRAM: "DEBUG_PROGRAM",
+            lttngctl.UserLogLevel.DEBUG_PROCESS: "DEBUG_PROCESS",
+            lttngctl.UserLogLevel.DEBUG_MODULE: "DEBUG_MODULE",
+            lttngctl.UserLogLevel.DEBUG_UNIT: "DEBUG_UNIT",
+            lttngctl.UserLogLevel.DEBUG_FUNCTION: "DEBUG_FUNCTION",
+            lttngctl.UserLogLevel.DEBUG_LINE: "DEBUG_LINE",
+            lttngctl.UserLogLevel.DEBUG: "DEBUG",
+        }[log_level]
+    elif isinstance(log_level, lttngctl.JULLogLevel):
+        return {
+            lttngctl.JULLogLevel.OFF: "OFF",
+            lttngctl.JULLogLevel.SEVERE: "SEVERE",
+            lttngctl.JULLogLevel.WARNING: "WARNING",
+            lttngctl.JULLogLevel.INFO: "INFO",
+            lttngctl.JULLogLevel.CONFIG: "CONFIG",
+            lttngctl.JULLogLevel.FINE: "FINE",
+            lttngctl.JULLogLevel.FINER: "FINER",
+            lttngctl.JULLogLevel.FINEST: "FINEST",
+            lttngctl.JULLogLevel.ALL: "ALL",
+        }[log_level]
+    elif isinstance(log_level, lttngctl.Log4jLogLevel):
+        return {
+            lttngctl.Log4jLogLevel.OFF: "OFF",
+            lttngctl.Log4jLogLevel.FATAL: "FATAL",
+            lttngctl.Log4jLogLevel.ERROR: "ERROR",
+            lttngctl.Log4jLogLevel.WARN: "WARN",
+            lttngctl.Log4jLogLevel.INFO: "INFO",
+            lttngctl.Log4jLogLevel.DEBUG: "DEBUG",
+            lttngctl.Log4jLogLevel.TRACE: "TRACE",
+            lttngctl.Log4jLogLevel.ALL: "ALL",
+        }[log_level]
+    elif isinstance(log_level, lttngctl.PythonLogLevel):
+        return {
+            lttngctl.PythonLogLevel.CRITICAL: "CRITICAL",
+            lttngctl.PythonLogLevel.ERROR: "ERROR",
+            lttngctl.PythonLogLevel.WARNING: "WARNING",
+            lttngctl.PythonLogLevel.INFO: "INFO",
+            lttngctl.PythonLogLevel.DEBUG: "DEBUG",
+            lttngctl.PythonLogLevel.NOTSET: "NOTSET",
+        }[log_level]
+
+    raise TypeError("Unknown log level type")
+
+
+def _get_log_level_from_mi_log_level_name(mi_log_level_name):
+    # type: (str) -> lttngctl.LogLevel
+    return {
+        "TRACE_EMERG": lttngctl.UserLogLevel.EMERGENCY,
+        "TRACE_ALERT": lttngctl.UserLogLevel.ALERT,
+        "TRACE_CRIT": lttngctl.UserLogLevel.CRITICAL,
+        "TRACE_ERR": lttngctl.UserLogLevel.ERROR,
+        "TRACE_WARNING": lttngctl.UserLogLevel.WARNING,
+        "TRACE_NOTICE": lttngctl.UserLogLevel.NOTICE,
+        "TRACE_INFO": lttngctl.UserLogLevel.INFO,
+        "TRACE_DEBUG_SYSTEM": lttngctl.UserLogLevel.DEBUG_SYSTEM,
+        "TRACE_DEBUG_PROGRAM": lttngctl.UserLogLevel.DEBUG_PROGRAM,
+        "TRACE_DEBUG_PROCESS": lttngctl.UserLogLevel.DEBUG_PROCESS,
+        "TRACE_DEBUG_MODULE": lttngctl.UserLogLevel.DEBUG_MODULE,
+        "TRACE_DEBUG_UNIT": lttngctl.UserLogLevel.DEBUG_UNIT,
+        "TRACE_DEBUG_FUNCTION": lttngctl.UserLogLevel.DEBUG_FUNCTION,
+        "TRACE_DEBUG_LINE": lttngctl.UserLogLevel.DEBUG_LINE,
+        "TRACE_DEBUG": lttngctl.UserLogLevel.DEBUG,
+        "JUL_OFF": lttngctl.JULLogLevel.OFF,
+        "JUL_SEVERE": lttngctl.JULLogLevel.SEVERE,
+        "JUL_WARNING": lttngctl.JULLogLevel.WARNING,
+        "JUL_INFO": lttngctl.JULLogLevel.INFO,
+        "JUL_CONFIG": lttngctl.JULLogLevel.CONFIG,
+        "JUL_FINE": lttngctl.JULLogLevel.FINE,
+        "JUL_FINER": lttngctl.JULLogLevel.FINER,
+        "JUL_FINEST": lttngctl.JULLogLevel.FINEST,
+        "JUL_ALL": lttngctl.JULLogLevel.ALL,
+        "LOG4J_OFF": lttngctl.Log4jLogLevel.OFF,
+        "LOG4J_FATAL": lttngctl.Log4jLogLevel.FATAL,
+        "LOG4J_ERROR": lttngctl.Log4jLogLevel.ERROR,
+        "LOG4J_WARN": lttngctl.Log4jLogLevel.WARN,
+        "LOG4J_INFO": lttngctl.Log4jLogLevel.INFO,
+        "LOG4J_DEBUG": lttngctl.Log4jLogLevel.DEBUG,
+        "LOG4J_TRACE": lttngctl.Log4jLogLevel.TRACE,
+        "LOG4J_ALL": lttngctl.Log4jLogLevel.ALL,
+        "PYTHON_CRITICAL": lttngctl.PythonLogLevel.CRITICAL,
+        "PYTHON_ERROR": lttngctl.PythonLogLevel.ERROR,
+        "PYTHON_WARNING": lttngctl.PythonLogLevel.WARNING,
+        "PYTHON_INFO": lttngctl.PythonLogLevel.INFO,
+        "PYTHON_DEBUG": lttngctl.PythonLogLevel.DEBUG,
+        "PYTHON_NOTSET": lttngctl.PythonLogLevel.NOTSET,
+    }[mi_log_level_name]
+
+
+def _get_tracepoint_event_rule_class_from_domain_type(domain_type):
+    # type: (lttngctl.TracingDomain) -> Type[lttngctl.UserTracepointEventRule] | Type[lttngctl.Log4jTracepointEventRule] | Type[lttngctl.JULTracepointEventRule] | Type[lttngctl.PythonTracepointEventRule] | Type[lttngctl.KernelTracepointEventRule]
+    return {
+        lttngctl.TracingDomain.User: lttngctl.UserTracepointEventRule,
+        lttngctl.TracingDomain.JUL: lttngctl.JULTracepointEventRule,
+        lttngctl.TracingDomain.Log4j: lttngctl.Log4jTracepointEventRule,
+        lttngctl.TracingDomain.Python: lttngctl.PythonTracepointEventRule,
+        lttngctl.TracingDomain.Kernel: lttngctl.KernelTracepointEventRule,
+    }[domain_type]
+
+
+class _Channel(lttngctl.Channel):
+    def __init__(
+        self,
+        client,  # type: LTTngClient
+        name,  # type: str
+        domain,  # type: lttngctl.TracingDomain
+        session,  # type: _Session
+    ):
+        self._client = client  # type: LTTngClient
+        self._name = name  # type: str
+        self._domain = domain  # type: lttngctl.TracingDomain
+        self._session = session  # type: _Session
+
+    def add_context(self, context_type):
+        # type: (lttngctl.ContextType) -> None
+        domain_option_name = _get_domain_option_name(self.domain)
+        context_type_name = _get_context_type_name(context_type)
+        self._client._run_cmd(
+            "add-context --{domain_option_name} --channel '{channel_name}' --type {context_type_name}".format(
+                domain_option_name=domain_option_name,
+                channel_name=self.name,
+                context_type_name=context_type_name,
+            )
+        )
+
+    def add_recording_rule(self, rule):
+        # type: (Type[lttngctl.EventRule]) -> None
+        client_args = (
+            "enable-event --session {session_name} --channel {channel_name}".format(
+                session_name=self._session.name, channel_name=self.name
+            )
+        )
+        if isinstance(rule, lttngctl.TracepointEventRule):
+            domain_option_name = (
+                "userspace"
+                if isinstance(rule, lttngctl.UserTracepointEventRule)
+                else "kernel"
+            )
+            client_args = client_args + " --{domain_option_name}".format(
+                domain_option_name=domain_option_name
+            )
+
+            if rule.name_pattern:
+                client_args = client_args + " " + rule.name_pattern
+            else:
+                client_args = client_args + " --all"
+
+            if rule.filter_expression:
+                client_args = client_args + " " + rule.filter_expression
+
+            if rule.log_level_rule:
+                if isinstance(rule.log_level_rule, lttngctl.LogLevelRuleAsSevereAs):
+                    client_args = client_args + " --loglevel {log_level}".format(
+                        log_level=_get_log_level_argument_name(
+                            rule.log_level_rule.level
+                        )
+                    )
+                elif isinstance(rule.log_level_rule, lttngctl.LogLevelRuleExactly):
+                    client_args = client_args + " --loglevel-only {log_level}".format(
+                        log_level=_get_log_level_argument_name(
+                            rule.log_level_rule.level
+                        )
+                    )
+                else:
+                    raise Unsupported(
+                        "Unsupported log level rule type `{log_level_rule_type}`".format(
+                            log_level_rule_type=type(rule.log_level_rule).__name__
+                        )
+                    )
+
+            if rule.name_pattern_exclusions:
+                client_args = client_args + " --exclude "
+                for idx, pattern in enumerate(rule.name_pattern_exclusions):
+                    if idx != 0:
+                        client_args = client_args + ","
+                    client_args = client_args + pattern
+        else:
+            raise Unsupported(
+                "event rule type `{event_rule_type}` is unsupported by LTTng client".format(
+                    event_rule_type=type(rule).__name__
+                )
+            )
+
+        self._client._run_cmd(client_args)
+
+    @property
+    def name(self):
+        # type: () -> str
+        return self._name
+
+    @property
+    def domain(self):
+        # type: () -> lttngctl.TracingDomain
+        return self._domain
+
+    @property
+    def recording_rules(self):
+        # type: () -> Iterator[lttngctl.EventRule]
+        list_session_xml = self._client._run_cmd(
+            "list '{session_name}'".format(session_name=self._session.name),
+            LTTngClient.CommandOutputFormat.MI_XML,
+        )
+
+        root = xml.etree.ElementTree.fromstring(list_session_xml)
+        command_output = LTTngClient._mi_get_in_element(root, "output")
+        sessions = LTTngClient._mi_get_in_element(command_output, "sessions")
+
+        # The channel's session is supposed to be the only session returned by the command
+        if len(sessions) != 1:
+            raise InvalidMI(
+                "Only one session expected when listing with an explicit session name"
+            )
+        session = sessions[0]
+
+        # Look for the channel's domain
+        target_domain = None
+        target_domain_mi_name = _get_domain_xml_mi_name(self.domain)
+        for domain in LTTngClient._mi_get_in_element(session, "domains"):
+            if (
+                LTTngClient._mi_get_in_element(domain, "type").text
+                == target_domain_mi_name
+            ):
+                target_domain = domain
+
+        if target_domain is None:
+            raise ChannelNotFound(
+                "Failed to find channel `{channel_name}`: no channel in target domain".format(
+                    channel_name=self.name
+                )
+            )
+
+        target_channel = None
+        for channel in LTTngClient._mi_get_in_element(target_domain, "channels"):
+            if LTTngClient._mi_get_in_element(channel, "name").text == self.name:
+                target_channel = channel
+                break
+
+        if target_channel is None:
+            raise ChannelNotFound(
+                "Failed to find channel `{channel_name}`: no such channel in target domain".format(
+                    channel_name=self.name
+                )
+            )
+
+        tracepoint_event_rule_class = None
+
+        for event in LTTngClient._mi_get_in_element(target_channel, "events"):
+            # Note that the "enabled" property is ignored as it is not exposed by
+            # the EventRule interface.
+            pattern = LTTngClient._mi_get_in_element(event, "name").text
+            type = LTTngClient._mi_get_in_element(event, "type").text
+
+            filter_expression = None
+            filter_expression_element = LTTngClient._mi_find_in_element(
+                event, "filter_expression"
+            )
+            if filter_expression_element:
+                filter_expression = filter_expression_element.text
+
+            exclusions = []
+            for exclusion in LTTngClient._mi_get_in_element(event, "exclusions"):
+                exclusions.append(exclusion.text)
+
+            exclusions = exclusions if len(exclusions) > 0 else None
+
+            if type != "TRACEPOINT":
+                raise Unsupported(
+                    "Non-tracepoint event rules are not supported by this Controller implementation"
+                )
+
+            tracepoint_event_rule_class = (
+                _get_tracepoint_event_rule_class_from_domain_type(self.domain)
+            )
+            event_rule = None
+            if self.domain != lttngctl.TracingDomain.Kernel:
+                log_level_element = LTTngClient._mi_find_in_element(event, "loglevel")
+                log_level_type_element = LTTngClient._mi_find_in_element(
+                    event, "loglevel_type"
+                )
+
+                log_level_rule = None
+                if log_level_element is not None and log_level_type_element is not None:
+                    if log_level_element.text is None:
+                        raise InvalidMI("`loglevel` element of event rule has no text")
+
+                    if log_level_type_element.text == "RANGE":
+                        log_level_rule = lttngctl.LogLevelRuleAsSevereAs(
+                            _get_log_level_from_mi_log_level_name(
+                                log_level_element.text
+                            )
+                        )
+                    elif log_level_type_element.text == "SINGLE":
+                        log_level_rule = lttngctl.LogLevelRuleExactly(
+                            _get_log_level_from_mi_log_level_name(
+                                log_level_element.text
+                            )
+                        )
+
+                yield tracepoint_event_rule_class(
+                    pattern, filter_expression, log_level_rule, exclusions
+                )
+            else:
+                yield tracepoint_event_rule_class(pattern, filter_expression)
+
+
+@enum.unique
+class _ProcessAttribute(enum.Enum):
+    PID = "Process ID"
+    VPID = "Virtual Process ID"
+    UID = "User ID"
+    VUID = "Virtual User ID"
+    GID = "Group ID"
+    VGID = "Virtual Group ID"
+
+    def __repr__(self):
+        return "<%s.%s>" % (self.__class__.__name__, self.name)
+
+
+def _get_process_attribute_option_name(attribute):
+    # type: (_ProcessAttribute) -> str
+    return {
+        _ProcessAttribute.PID: "pid",
+        _ProcessAttribute.VPID: "vpid",
+        _ProcessAttribute.UID: "uid",
+        _ProcessAttribute.VUID: "vuid",
+        _ProcessAttribute.GID: "gid",
+        _ProcessAttribute.VGID: "vgid",
+    }[attribute]
+
+
+class _ProcessAttributeTracker(lttngctl.ProcessAttributeTracker):
+    def __init__(
+        self,
+        client,  # type: LTTngClient
+        attribute,  # type: _ProcessAttribute
+        domain,  # type: lttngctl.TracingDomain
+        session,  # type: _Session
+    ):
+        self._client = client  # type: LTTngClient
+        self._tracked_attribute = attribute  # type: _ProcessAttribute
+        self._domain = domain  # type: lttngctl.TracingDomain
+        self._session = session  # type: _Session
+        if attribute == _ProcessAttribute.PID or attribute == _ProcessAttribute.VPID:
+            self._allowed_value_types = [int, str]  # type: list[type]
+        else:
+            self._allowed_value_types = [int]  # type: list[type]
+
+    def _call_client(self, cmd_name, value):
+        # type: (str, Union[int, str]) -> None
+        if type(value) not in self._allowed_value_types:
+            raise TypeError(
+                "Value of type `{value_type}` is not allowed for process attribute {attribute_name}".format(
+                    value_type=type(value).__name__,
+                    attribute_name=self._tracked_attribute.name,
+                )
+            )
+
+        process_attribute_option_name = _get_process_attribute_option_name(
+            self._tracked_attribute
+        )
+        domain_name = _get_domain_option_name(self._domain)
+        self._client._run_cmd(
+            "{cmd_name} --session '{session_name}' --{domain_name} --{tracked_attribute_name} {value}".format(
+                cmd_name=cmd_name,
+                session_name=self._session.name,
+                domain_name=domain_name,
+                tracked_attribute_name=process_attribute_option_name,
+                value=value,
+            )
+        )
+
+    def track(self, value):
+        # type: (Union[int, str]) -> None
+        self._call_client("track", value)
+
+    def untrack(self, value):
+        # type: (Union[int, str]) -> None
+        self._call_client("untrack", value)
+
+
+class _Session(lttngctl.Session):
+    def __init__(
+        self,
+        client,  # type: LTTngClient
+        name,  # type: str
+        output,  # type: Optional[lttngctl.SessionOutputLocation]
+    ):
+        self._client = client  # type: LTTngClient
+        self._name = name  # type: str
+        self._output = output  # type: Optional[lttngctl.SessionOutputLocation]
+
+    @property
+    def name(self):
+        # type: () -> str
+        return self._name
+
+    def add_channel(
+        self,
+        domain,
+        channel_name=None,
+        buffer_sharing_policy=lttngctl.BufferSharingPolicy.PerUID,
+    ):
+        # type: (lttngctl.TracingDomain, Optional[str], lttngctl.BufferSharingPolicy) -> lttngctl.Channel
+        channel_name = lttngctl.Channel._generate_name()
+        domain_option_name = _get_domain_option_name(domain)
+        self._client._run_cmd(
+            "enable-channel --session '{session_name}' --{domain_name} '{channel_name}' {buffer_sharing_policy}".format(
+                session_name=self.name,
+                domain_name=domain_option_name,
+                channel_name=channel_name,
+                buffer_sharing_policy=(
+                    "--buffers-uid"
+                    if buffer_sharing_policy == lttngctl.BufferSharingPolicy.PerUID
+                    else "--buffers-pid"
+                ),
+            )
+        )
+        return _Channel(self._client, channel_name, domain, self)
+
+    def add_context(self, context_type):
+        # type: (lttngctl.ContextType) -> None
+        pass
+
+    @property
+    def output(self):
+        # type: () -> "Optional[Type[lttngctl.SessionOutputLocation]]"
+        return self._output  # type: ignore
+
+    def start(self):
+        # type: () -> None
+        self._client._run_cmd("start '{session_name}'".format(session_name=self.name))
+
+    def stop(self):
+        # type: () -> None
+        self._client._run_cmd("stop '{session_name}'".format(session_name=self.name))
+
+    def clear(self):
+        # type: () -> None
+        self._client._run_cmd("clear '{session_name}'".format(session_name=self.name))
+
+    def destroy(self):
+        # type: () -> None
+        self._client._run_cmd("destroy '{session_name}'".format(session_name=self.name))
+
+    def rotate(self, wait=True):
+        # type: (bool) -> None
+        self._client.rotate_session_by_name(self.name, wait)
+
+    @property
+    def is_active(self):
+        # type: () -> bool
+        list_session_xml = self._client._run_cmd(
+            "list '{session_name}'".format(session_name=self.name),
+            LTTngClient.CommandOutputFormat.MI_XML,
+        )
+
+        root = xml.etree.ElementTree.fromstring(list_session_xml)
+        command_output = LTTngClient._mi_get_in_element(root, "output")
+        sessions = LTTngClient._mi_get_in_element(command_output, "sessions")
+        session_mi = LTTngClient._mi_get_in_element(sessions, "session")
+
+        enabled_text = LTTngClient._mi_get_in_element(session_mi, "enabled").text
+        if enabled_text not in ["true", "false"]:
+            raise InvalidMI(
+                "Expected boolean value in element '{}': value='{}'".format(
+                    session_mi.tag, enabled_text
+                )
+            )
+
+        return enabled_text == "true"
+
+    @property
+    def kernel_pid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.ProcessIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.PID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def kernel_vpid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualProcessIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VPID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def user_vpid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualProcessIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VPID, lttngctl.TracingDomain.User, self)  # type: ignore
+
+    @property
+    def kernel_gid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.GroupIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.GID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def kernel_vgid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualGroupIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VGID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def user_vgid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualGroupIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VGID, lttngctl.TracingDomain.User, self)  # type: ignore
+
+    @property
+    def kernel_uid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.UserIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.UID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def kernel_vuid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualUserIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VUID, lttngctl.TracingDomain.Kernel, self)  # type: ignore
+
+    @property
+    def user_vuid_process_attribute_tracker(self):
+        # type: () -> Type[lttngctl.VirtualUserIDProcessAttributeTracker]
+        return _ProcessAttributeTracker(self._client, _ProcessAttribute.VUID, lttngctl.TracingDomain.User, self)  # type: ignore
+
+
+class LTTngClientError(lttngctl.ControlException):
+    def __init__(
+        self,
+        command_args,  # type: str
+        error_output,  # type: str
+    ):
+        self._command_args = command_args  # type: str
+        self._output = error_output  # type: str
+
+
+class LTTngClient(logger._Logger, lttngctl.Controller):
+    """
+    Implementation of a LTTngCtl Controller that uses the `lttng` client as a back-end.
+    """
+
+    class CommandOutputFormat(enum.Enum):
+        MI_XML = 0
+        HUMAN = 1
+
+    _MI_NS = "{https://lttng.org/xml/ns/lttng-mi}"
+
+    def __init__(
+        self,
+        test_environment,  # type: environment._Environment
+        log,  # type: Optional[Callable[[str], None]]
+    ):
+        logger._Logger.__init__(self, log)
+        self._environment = test_environment  # type: environment._Environment
+
+    @staticmethod
+    def _namespaced_mi_element(property):
+        # type: (str) -> str
+        return LTTngClient._MI_NS + property
+
+    def _run_cmd(self, command_args, output_format=CommandOutputFormat.MI_XML):
+        # type: (str, CommandOutputFormat) -> str
+        """
+        Invoke the `lttng` client with a set of arguments. The command is
+        executed in the context of the client's test environment.
+        """
+        args = [str(self._environment.lttng_client_path)]  # type: list[str]
+        if output_format == LTTngClient.CommandOutputFormat.MI_XML:
+            args.extend(["--mi", "xml"])
+
+        args.extend(shlex.split(command_args))
+
+        self._log("lttng {command_args}".format(command_args=command_args))
+
+        client_env = os.environ.copy()  # type: dict[str, str]
+        client_env["LTTNG_HOME"] = str(self._environment.lttng_home_location)
+
+        process = subprocess.Popen(
+            args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=client_env
+        )
+
+        out = process.communicate()[0]
+
+        if process.returncode != 0:
+            decoded_output = out.decode("utf-8")
+            for error_line in decoded_output.splitlines():
+                self._log(error_line)
+
+            raise LTTngClientError(command_args, decoded_output)
+        else:
+            return out.decode("utf-8")
+
+    def create_session(self, name=None, output=None, live=False):
+        # type: (Optional[str], Optional[lttngctl.SessionOutputLocation], bool) -> lttngctl.Session
+        name = name if name else lttngctl.Session._generate_name()
+
+        if isinstance(output, lttngctl.LocalSessionOutputLocation):
+            output_option = "--output '{output_path}'".format(output_path=output.path)
+        elif isinstance(output, lttngctl.NetworkSessionOutputLocation):
+            output_option = "--set-url '{}'".format(output.url)
+        elif output is None:
+            output_option = "--no-output"
+        else:
+            raise TypeError("LTTngClient only supports local or no output")
+
+        self._run_cmd(
+            "create '{session_name}' {output_option} {live_option}".format(
+                session_name=name,
+                output_option=output_option,
+                live_option="--live" if live else "",
+            )
+        )
+        return _Session(self, name, output)
+
+    def start_session_by_name(self, name):
+        # type: (str) -> None
+        self._run_cmd("start '{session_name}'".format(session_name=name))
+
+    def start_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        self._run_cmd("start --glob '{pattern}'".format(pattern=pattern))
+
+    def start_sessions_all(self):
+        # type: () -> None
+        self._run_cmd("start --all")
+
+    def stop_session_by_name(self, name):
+        # type: (str) -> None
+        self._run_cmd("stop '{session_name}'".format(session_name=name))
+
+    def stop_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        self._run_cmd("stop --glob '{pattern}'".format(pattern=pattern))
+
+    def stop_sessions_all(self):
+        # type: () -> None
+        self._run_cmd("stop --all")
+
+    def destroy_session_by_name(self, name):
+        # type: (str) -> None
+        self._run_cmd("destroy '{session_name}'".format(session_name=name))
+
+    def destroy_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        self._run_cmd("destroy --glob '{pattern}'".format(pattern=pattern))
+
+    def destroy_sessions_all(self):
+        # type: () -> None
+        self._run_cmd("destroy --all")
+
+    def rotate_session_by_name(self, name, wait=True):
+        self._run_cmd(
+            "rotate '{session_name}' {wait_option}".format(
+                session_name=name, wait_option="-n" if wait is False else ""
+            )
+        )
+
+    def schedule_size_based_rotation(self, name, size_bytes):
+        # type (str, int) -> None
+        self._run_cmd(
+            "enable-rotation --session '{session_name}' --size {size}".format(
+                session_name=name, size=size_bytes
+            )
+        )
+
+    def schedule_time_based_rotation(self, name, period_seconds):
+        # type (str, int) -> None
+        self._run_cmd(
+            "enable-rotation --session '{session_name}' --timer {period_seconds}s".format(
+                session_name=name, period_seconds=period_seconds
+            )
+        )
+
+    @staticmethod
+    def _mi_find_in_element(element, sub_element_name):
+        # type: (xml.etree.ElementTree.Element, str) -> Optional[xml.etree.ElementTree.Element]
+        return element.find(LTTngClient._namespaced_mi_element(sub_element_name))
+
+    @staticmethod
+    def _mi_get_in_element(element, sub_element_name):
+        # type: (xml.etree.ElementTree.Element, str) -> xml.etree.ElementTree.Element
+        result = LTTngClient._mi_find_in_element(element, sub_element_name)
+        if result is None:
+            raise InvalidMI(
+                "Failed to find element '{}' within command MI element '{}'".format(
+                    element.tag, sub_element_name
+                )
+            )
+
+        return result
+
+    def list_sessions(self):
+        # type () -> List[Session]
+        list_sessions_xml = self._run_cmd(
+            "list", LTTngClient.CommandOutputFormat.MI_XML
+        )
+
+        root = xml.etree.ElementTree.fromstring(list_sessions_xml)
+        command_output = self._mi_get_in_element(root, "output")
+        sessions = self._mi_get_in_element(command_output, "sessions")
+
+        ctl_sessions = []  # type: list[lttngctl.Session]
+
+        for session_mi in sessions:
+            name = self._mi_get_in_element(session_mi, "name").text
+            path = self._mi_get_in_element(session_mi, "path").text
+
+            if name is None:
+                raise InvalidMI(
+                    "Invalid empty 'name' element in '{}'".format(session_mi.tag)
+                )
+            if path is None:
+                raise InvalidMI(
+                    "Invalid empty 'path' element in '{}'".format(session_mi.tag)
+                )
+            if not path.startswith("/"):
+                raise Unsupported(
+                    "{} does not support non-local session outputs".format(type(self))
+                )
+
+            ctl_sessions.append(
+                _Session(self, name, lttngctl.LocalSessionOutputLocation(path))
+            )
+
+        return ctl_sessions
diff --git a/tests/utils/lttngtest/lttngctl.py b/tests/utils/lttngtest/lttngctl.py
new file mode 100644 (file)
index 0000000..5b937dc
--- /dev/null
@@ -0,0 +1,778 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+
+import abc
+import random
+import string
+import pathlib
+import enum
+from typing import Optional, Type, Union, List
+
+"""
+Defines an abstract interface to control LTTng tracing.
+
+The various control concepts are defined by this module. You can use them with a
+Controller to interact with a session daemon.
+
+This interface is not comprehensive; it currently provides a subset of the
+control functionality that is used by tests.
+"""
+
+
+def _generate_random_string(length):
+    # type: (int) -> str
+    return "".join(
+        random.choice(string.ascii_lowercase + string.digits) for _ in range(length)
+    )
+
+
+class ContextType(abc.ABC):
+    """Base class representing a tracing context field."""
+
+    pass
+
+
+class VpidContextType(ContextType):
+    """Application's virtual process id."""
+
+    pass
+
+
+class VuidContextType(ContextType):
+    """Application's virtual user id."""
+
+    pass
+
+
+class VgidContextType(ContextType):
+    """Application's virtual group id."""
+
+    pass
+
+
+class JavaApplicationContextType(ContextType):
+    """A java application-specific context field is a piece of state which the application provides."""
+
+    def __init__(
+        self,
+        retriever_name,  # type: str
+        field_name,  # type: str
+    ):
+        self._retriever_name = retriever_name  # type: str
+        self._field_name = field_name  # type: str
+
+    @property
+    def retriever_name(self):
+        # type: () -> str
+        return self._retriever_name
+
+    @property
+    def field_name(self):
+        # type: () -> str
+        return self._field_name
+
+
+@enum.unique
+class TracingDomain(enum.Enum):
+    """Tracing domain."""
+
+    User = "User space tracing domain"
+    Kernel = "Linux kernel tracing domain."
+    Log4j = "Log4j tracing back-end."
+    JUL = "Java Util Logging tracing back-end."
+    Python = "Python logging module tracing back-end."
+
+    def __repr__(self):
+        return "<%s.%s>" % (self.__class__.__name__, self.name)
+
+
+@enum.unique
+class BufferSharingPolicy(enum.Enum):
+    """Buffer sharing policy."""
+
+    PerUID = "Per-UID buffering"
+    PerPID = "Per-PID buffering"
+
+    def __repr__(self):
+        return "<%s.%s>" % (self.__class__.__name__, self.name)
+
+
+class EventRule(abc.ABC):
+    """Event rule base class, see LTTNG-EVENT-RULE(7)."""
+
+    pass
+
+
+class LogLevelRule:
+    def __eq__(self, other):
+        # type (LogLevelRule) -> bool
+        if type(self) != type(other):
+            return False
+
+        return self.level == other.level
+
+
+@enum.unique
+class LogLevel(enum.Enum):
+    pass
+
+
+@enum.unique
+class UserLogLevel(LogLevel):
+    EMERGENCY = 0
+    ALERT = 1
+    CRITICAL = 2
+    ERROR = 3
+    WARNING = 4
+    NOTICE = 5
+    INFO = 6
+    DEBUG_SYSTEM = 7
+    DEBUG_PROGRAM = 8
+    DEBUG_PROCESS = 9
+    DEBUG_MODULE = 10
+    DEBUG_UNIT = 11
+    DEBUG_FUNCTION = 12
+    DEBUG_LINE = 13
+    DEBUG = 14
+
+
+@enum.unique
+class JULLogLevel(LogLevel):
+    OFF = 2147483647
+    SEVERE = 1000
+    WARNING = 900
+    INFO = 800
+    CONFIG = 700
+    FINE = 500
+    FINER = 400
+    FINEST = 300
+    ALL = -2147483648
+
+
+@enum.unique
+class Log4jLogLevel(LogLevel):
+    OFF = 2147483647
+    FATAL = 50000
+    ERROR = 40000
+    WARN = 30000
+    INFO = 20000
+    DEBUG = 10000
+    TRACE = 5000
+    ALL = -2147483648
+
+
+@enum.unique
+class PythonLogLevel(LogLevel):
+    CRITICAL = 50
+    ERROR = 40
+    WARNING = 30
+    INFO = 20
+    DEBUG = 10
+    NOTSET = 0
+
+
+class LogLevelRuleAsSevereAs(LogLevelRule):
+    def __init__(self, level):
+        # type: (LogLevel)
+        self._level = level
+
+    @property
+    def level(self):
+        # type: () -> LogLevel
+        return self._level
+
+
+class LogLevelRuleExactly(LogLevelRule):
+    def __init__(self, level):
+        # type: (LogLevel)
+        self._level = level
+
+    @property
+    def level(self):
+        # type: () -> LogLevel
+        return self._level
+
+
+class TracepointEventRule(EventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+    ):
+        self._name_pattern = name_pattern  # type: Optional[str]
+        self._filter_expression = filter_expression  # type: Optional[str]
+
+    def _equals(self, other):
+        # type (TracepointEventRule) -> bool
+        # Overridden by derived classes that have supplementary attributes.
+        return True
+
+    def __eq__(self, other):
+        # type (TracepointEventRule) -> bool
+        if type(self) != type(other):
+            return False
+
+        if self.name_pattern != other.name_pattern:
+            return False
+
+        if self.filter_expression != other.filter_expression:
+            return False
+
+        return self._equals(other)
+
+    @property
+    def name_pattern(self):
+        # type: () -> Optional[str]
+        return self._name_pattern
+
+    @property
+    def filter_expression(self):
+        # type: () -> Optional[str]
+        return self._filter_expression
+
+
+class UserTracepointEventRule(TracepointEventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+        log_level_rule=None,  # type: Optional[LogLevelRule]
+        name_pattern_exclusions=None,  # type: Optional[List[str]]
+    ):
+        TracepointEventRule.__init__(self, name_pattern, filter_expression)
+        self._log_level_rule = log_level_rule  # type: Optional[LogLevelRule]
+        self._name_pattern_exclusions = (
+            name_pattern_exclusions
+        )  # type: Optional[List[str]]
+
+        if log_level_rule and not isinstance(log_level_rule.level, UserLogLevel):
+            raise ValueError("Log level rule must use a UserLogLevel as its value")
+
+    def _equals(self, other):
+        # type (UserTracepointEventRule) -> bool
+        return (
+            self.log_level_rule == other.log_level_rule
+            and self.name_pattern_exclusions == other.name_pattern_exclusions
+        )
+
+    @property
+    def log_level_rule(self):
+        # type: () -> Optional[LogLevelRule]
+        return self._log_level_rule
+
+    @property
+    def name_pattern_exclusions(self):
+        # type: () -> Optional[List[str]]
+        return self._name_pattern_exclusions
+
+
+class Log4jTracepointEventRule(TracepointEventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+        log_level_rule=None,  # type: Optional[LogLevelRule]
+        name_pattern_exclusions=None,  # type: Optional[List[str]]
+    ):
+        TracepointEventRule.__init__(self, name_pattern, filter_expression)
+        self._log_level_rule = log_level_rule  # type: Optional[LogLevelRule]
+        self._name_pattern_exclusions = (
+            name_pattern_exclusions
+        )  # type: Optional[List[str]]
+
+        if log_level_rule and not isinstance(log_level_rule.level, Log4jLogLevel):
+            raise ValueError("Log level rule must use a Log4jLogLevel as its value")
+
+    def _equals(self, other):
+        # type (Log4jTracepointEventRule) -> bool
+        return (
+            self.log_level_rule == other.log_level_rule
+            and self.name_pattern_exclusions == other.name_pattern_exclusions
+        )
+
+    @property
+    def log_level_rule(self):
+        # type: () -> Optional[LogLevelRule]
+        return self._log_level_rule
+
+    @property
+    def name_pattern_exclusions(self):
+        # type: () -> Optional[List[str]]
+        return self._name_pattern_exclusions
+
+
+class JULTracepointEventRule(TracepointEventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+        log_level_rule=None,  # type: Optional[LogLevelRule]
+        name_pattern_exclusions=None,  # type: Optional[List[str]]
+    ):
+        TracepointEventRule.__init__(self, name_pattern, filter_expression)
+        self._log_level_rule = log_level_rule  # type: Optional[LogLevelRule]
+        self._name_pattern_exclusions = (
+            name_pattern_exclusions
+        )  # type: Optional[List[str]]
+
+        if log_level_rule and not isinstance(log_level_rule.level, JULLogLevel):
+            raise ValueError("Log level rule must use a JULLogLevel as its value")
+
+    def _equals(self, other):
+        # type (JULTracepointEventRule) -> bool
+        return (
+            self.log_level_rule == other.log_level_rule
+            and self.name_pattern_exclusions == other.name_pattern_exclusions
+        )
+
+    @property
+    def log_level_rule(self):
+        # type: () -> Optional[LogLevelRule]
+        return self._log_level_rule
+
+    @property
+    def name_pattern_exclusions(self):
+        # type: () -> Optional[List[str]]
+        return self._name_pattern_exclusions
+
+
+class PythonTracepointEventRule(TracepointEventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+        log_level_rule=None,  # type: Optional[LogLevelRule]
+        name_pattern_exclusions=None,  # type: Optional[List[str]]
+    ):
+        TracepointEventRule.__init__(self, name_pattern, filter_expression)
+        self._log_level_rule = log_level_rule  # type: Optional[LogLevelRule]
+        self._name_pattern_exclusions = (
+            name_pattern_exclusions
+        )  # type: Optional[List[str]]
+
+        if log_level_rule and not isinstance(log_level_rule.level, PythonLogLevel):
+            raise ValueError("Log level rule must use a PythonLogLevel as its value")
+
+    def _equals(self, other):
+        # type (PythonTracepointEventRule) -> bool
+        return (
+            self.log_level_rule == other.log_level_rule
+            and self.name_pattern_exclusions == other.name_pattern_exclusions
+        )
+
+    @property
+    def log_level_rule(self):
+        # type: () -> Optional[LogLevelRule]
+        return self._log_level_rule
+
+    @property
+    def name_pattern_exclusions(self):
+        # type: () -> Optional[List[str]]
+        return self._name_pattern_exclusions
+
+
+class KernelTracepointEventRule(TracepointEventRule):
+    def __init__(
+        self,
+        name_pattern=None,  # type: Optional[str]
+        filter_expression=None,  # type: Optional[str]
+    ):
+        TracepointEventRule.__init__(**locals())
+
+
+class Channel(abc.ABC):
+    """
+    A channel is an object which is responsible for a set of ring buffers. It is
+    associated to a domain and
+    """
+
+    @staticmethod
+    def _generate_name():
+        # type: () -> str
+        return "channel_{random_id}".format(random_id=_generate_random_string(8))
+
+    @abc.abstractmethod
+    def add_context(self, context_type):
+        # type: (ContextType) -> None
+        raise NotImplementedError
+
+    @property
+    @abc.abstractmethod
+    def domain(self):
+        # type: () -> TracingDomain
+        raise NotImplementedError
+
+    @property
+    @abc.abstractmethod
+    def name(self):
+        # type: () -> str
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def add_recording_rule(self, rule) -> None:
+        # type: (Type[EventRule]) -> None
+        raise NotImplementedError
+
+
+class SessionOutputLocation(abc.ABC):
+    pass
+
+
+class LocalSessionOutputLocation(SessionOutputLocation):
+    def __init__(self, trace_path):
+        # type: (pathlib.Path)
+        self._path = trace_path
+
+    @property
+    def path(self):
+        # type: () -> pathlib.Path
+        return self._path
+
+
+class NetworkSessionOutputLocation(SessionOutputLocation):
+    def __init__(self, set_url):
+        # type (str)
+        self._set_url = set_url
+
+    @property
+    def url(self):
+        # type: () -> str
+        return self._set_url
+
+
+class ProcessAttributeTracker(abc.ABC):
+    """
+    Process attribute tracker used to filter before the evaluation of event
+    rules.
+
+    Note that this interface is currently limited as it doesn't allow changing
+    the tracking policy. For instance, it is not possible to set the tracking
+    policy back to "all" once it has transitioned to "include set".
+    """
+
+    @enum.unique
+    class TrackingPolicy(enum.Enum):
+        INCLUDE_ALL = """
+            Track all possible process attribute value of a given type (i.e. no filtering).
+            This is the default state of a process attribute tracker.
+            """
+        EXCLUDE_ALL = "Exclude all possible process attribute values of a given type."
+        INCLUDE_SET = "Track a set of specific process attribute values."
+
+        def __repr__(self):
+            return "<%s.%s>" % (self.__class__.__name__, self.name)
+
+    def __init__(self, policy):
+        # type: (TrackingPolicy)
+        self._policy = policy
+
+    @property
+    def tracking_policy(self):
+        # type: () -> TrackingPolicy
+        return self._policy
+
+
+class ProcessIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, pid):
+        # type: (int) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, pid):
+        # type: (int) -> None
+        raise NotImplementedError
+
+
+class VirtualProcessIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, vpid):
+        # type: (int) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, vpid):
+        # type: (int) -> None
+        raise NotImplementedError
+
+
+class UserIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, uid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, uid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+
+class VirtualUserIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, vuid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, vuid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+
+class GroupIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, gid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, gid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+
+class VirtualGroupIDProcessAttributeTracker(ProcessAttributeTracker):
+    @abc.abstractmethod
+    def track(self, vgid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def untrack(self, vgid):
+        # type: (Union[int, str]) -> None
+        raise NotImplementedError
+
+
+class Session(abc.ABC):
+    @staticmethod
+    def _generate_name():
+        # type: () -> str
+        return "session_{random_id}".format(random_id=_generate_random_string(8))
+
+    @property
+    @abc.abstractmethod
+    def name(self):
+        # type: () -> str
+        raise NotImplementedError
+
+    @property
+    @abc.abstractmethod
+    def output(self):
+        # type: () -> Optional[Type[SessionOutputLocation]]
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def add_channel(
+        self,
+        domain,
+        channel_name=None,
+        buffer_sharing_policy=BufferSharingPolicy.PerUID,
+    ):
+        # type: (TracingDomain, Optional[str], BufferSharingPolicy) -> Channel
+        """Add a channel with default attributes to the session."""
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def start(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def stop(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def destroy(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def is_active(self):
+        # type: () -> bool
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def rotate(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_pid_process_attribute_tracker(self):
+        # type: () -> Type[ProcessIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_vpid_process_attribute_tracker(self):
+        # type: () -> Type[VirtualProcessIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def user_vpid_process_attribute_tracker(
+        self,
+    ) -> Type[VirtualProcessIDProcessAttributeTracker]:
+        # type: () -> Type[VirtualProcessIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_gid_process_attribute_tracker(self):
+        # type: () -> Type[GroupIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_vgid_process_attribute_tracker(self):
+        # type: () -> Type[VirtualGroupIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def user_vgid_process_attribute_tracker(self):
+        # type: () -> Type[VirtualGroupIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_uid_process_attribute_tracker(self):
+        # type: () -> Type[UserIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def kernel_vuid_process_attribute_tracker(self):
+        # type: () -> Type[VirtualUserIDProcessAttributeTracker]
+        raise NotImplementedError
+
+    @abc.abstractproperty
+    def user_vuid_process_attribute_tracker(self):
+        # type: () -> Type[VirtualUserIDProcessAttributeTracker]
+        raise NotImplementedError
+
+
+class ControlException(RuntimeError):
+    """Base type for exceptions thrown by a controller."""
+
+    def __init__(self, msg):
+        # type: (str)
+        super().__init__(msg)
+
+
+class Controller(abc.ABC):
+    """
+    Interface of a top-level control interface. A control interface can be, for
+    example, the LTTng client or a wrapper around liblttng-ctl. It is used to
+    create and manage top-level objects of a session daemon instance.
+    """
+
+    @abc.abstractmethod
+    def create_session(self, name=None, output=None):
+        # type: (Optional[str], Optional[SessionOutputLocation]) -> Session
+        """
+        Create a session with an output. Don't specify an output
+        to create a session without an output.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def start_session_by_name(self, name):
+        # type: (str) -> None
+        """
+        Start a session by name.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def start_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        """
+        Start sessions whose name matches `pattern`, see GLOB(7).
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def start_sessions_all(self):
+        """
+        Start all sessions visible to the current user.
+        """
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def stop_session_by_name(self, name):
+        # type: (str) -> None
+        """
+        Stop a session by name.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def stop_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        """
+        Stop sessions whose name matches `pattern`, see GLOB(7).
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def stop_sessions_all(self):
+        """
+        Stop all sessions visible to the current user.
+        """
+        # type: () -> None
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def destroy_session_by_name(self, name):
+        # type: (str) -> None
+        """
+        Destroy a session by name.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def destroy_session_by_glob_pattern(self, pattern):
+        # type: (str) -> None
+        """
+        Destroy sessions whose name matches `pattern`, see GLOB(7).
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def destroy_sessions_all(self):
+        # type: () -> None
+        """
+        Destroy all sessions visible to the current user.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def list_sessions(self):
+        # type: () -> List[Session]
+        """
+        List all sessions visible to the current user.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def rotate_session_by_name(self, name, wait=True):
+        # type: (str, bool) -> None
+        """
+        Rotate a session
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def schedule_size_based_rotation(self, name, size_bytes):
+        # type: (str, int) -> None
+        """
+        Schedule automatic size-based rotations.
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def schedule_time_based_rotation(self, name, period_seconds):
+        # type: (str, int) -> None
+        """
+        Schedule automatic time-based rotations.
+        """
+        raise NotImplementedError
diff --git a/tests/utils/lttngtest/tap_generator.py b/tests/utils/lttngtest/tap_generator.py
new file mode 100644 (file)
index 0000000..c9bd8ed
--- /dev/null
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import contextlib
+import os
+import sys
+import time
+from typing import Iterator, Optional
+
+
+def _get_time_ns():
+    # type: () -> int
+
+    # time.monotonic is only available since Python 3.3. We don't support
+    # those older versions so we can simply assert here.
+    assert sys.version_info >= (3, 3, 0)
+
+    # time.monotonic_ns is only available for python >= 3.8,
+    # so the value is multiplied by 10^9 to maintain compatibility with
+    # older versions of the interpreter.
+    return int(time.monotonic() * 1000000000)
+
+
+class InvalidTestPlan(RuntimeError):
+    def __init__(self, msg):
+        # type: (str) -> None
+        super().__init__(msg)
+
+
+class BailOut(RuntimeError):
+    def __init__(self, msg):
+        # type: (str) -> None
+        super().__init__(msg)
+
+
+class TestCase:
+    def __init__(
+        self,
+        tap_generator,  # type: "TapGenerator"
+        description,  # type: str
+    ):
+        self._tap_generator = tap_generator  # type: "TapGenerator"
+        self._result = None  # type: Optional[bool]
+        self._description = description  # type: str
+
+    @property
+    def result(self):
+        # type: () -> Optional[bool]
+        return self._result
+
+    @property
+    def description(self):
+        # type: () -> str
+        return self._description
+
+    def _set_result(self, result):
+        # type: (bool) -> None
+        if self._result is not None:
+            raise RuntimeError("Can't set test case result twice")
+
+        self._result = result
+        self._tap_generator.test(result, self._description)
+
+    def success(self):
+        # type: () -> None
+        self._set_result(True)
+
+    def fail(self):
+        # type: () -> None
+        self._set_result(False)
+
+
+# Produces a test execution report in the TAP format.
+class TapGenerator:
+    def __init__(self, total_test_count):
+        # type: (int) -> None
+        if total_test_count <= 0:
+            raise ValueError("Test count must be greater than zero")
+
+        self._total_test_count = total_test_count  # type: int
+        self._last_test_case_id = 0  # type: int
+        self._printed_plan = False  # type: bool
+        self._has_failure = False  # type: bool
+        self._time_tests = True  # type: bool
+        if os.getenv("LTTNG_TESTS_TAP_AUTOTIME", "1") == "0":
+            self._time_tests = False
+        self._last_time = _get_time_ns()
+
+    def __del__(self):
+        if self.remaining_test_cases > 0:
+            self.bail_out(
+                "Missing {remaining_test_cases} test cases".format(
+                    remaining_test_cases=self.remaining_test_cases
+                )
+            )
+
+    @property
+    def remaining_test_cases(self):
+        # type: () -> int
+        return self._total_test_count - self._last_test_case_id
+
+    def _print(self, msg):
+        # type: (str) -> None
+        if not self._printed_plan:
+            print(
+                "1..{total_test_count}".format(total_test_count=self._total_test_count),
+                flush=True,
+            )
+            self._printed_plan = True
+
+        print(msg, flush=True)
+
+    def skip_all(self, reason):
+        # type: (str) -> None
+        if self._last_test_case_id != 0:
+            raise RuntimeError("Can't skip all tests after running test cases")
+
+        if reason:
+            self._print("1..0 # Skip all: {reason}".format(reason=reason))
+
+        self._last_test_case_id = self._total_test_count
+
+    def skip(self, reason, skip_count=1):
+        # type: (str, int) -> None
+        for i in range(skip_count):
+            self._last_test_case_id = self._last_test_case_id + 1
+            self._print(
+                "ok {test_number} # Skip: {reason}".format(
+                    reason=reason, test_number=(self._last_test_case_id)
+                )
+            )
+
+    def bail_out(self, reason):
+        # type: (str) -> None
+        self._print("Bail out! {reason}".format(reason=reason))
+        self._last_test_case_id = self._total_test_count
+        raise BailOut(reason)
+
+    def test(self, result, description):
+        # type: (bool, str) -> None
+        duration = (_get_time_ns() - self._last_time) / 1000000
+        if self._last_test_case_id == self._total_test_count:
+            raise InvalidTestPlan("Executing too many tests")
+
+        if result is False:
+            self._has_failure = True
+
+        result_string = "ok" if result else "not ok"
+        self._last_test_case_id = self._last_test_case_id + 1
+        self._print(
+            "{result_string} {case_id} - {description}".format(
+                result_string=result_string,
+                case_id=self._last_test_case_id,
+                description=description,
+            )
+        )
+        if self._time_tests:
+            self._print("---\n  duration_ms: {}\n...\n".format(duration))
+        self._last_time = _get_time_ns()
+
+    def ok(self, description):
+        # type: (str) -> None
+        self.test(True, description)
+
+    def fail(self, description):
+        # type: (str) -> None
+        self.test(False, description)
+
+    @property
+    def is_successful(self):
+        # type: () -> bool
+        return (
+            self._last_test_case_id == self._total_test_count and not self._has_failure
+        )
+
+    @contextlib.contextmanager
+    def case(self, description):
+        # type: (str) -> Iterator[TestCase]
+        test_case = TestCase(self, description)
+        try:
+            yield test_case
+        except Exception as e:
+            self.diagnostic(
+                "Exception `{exception_type}` thrown during test case `{description}`, marking as failure.".format(
+                    description=test_case.description, exception_type=type(e).__name__
+                )
+            )
+
+            if str(e) != "":
+                self.diagnostic(str(e))
+
+            test_case.fail()
+        finally:
+            if test_case.result is None:
+                test_case.success()
+
+    def diagnostic(self, msg):
+        # type: (str) -> None
+        print("# {msg}".format(msg=msg), file=sys.stderr, flush=True)
index 3bfddd9eff36631b5d179f6495c672d7e28c9965..f16ab8e404adddb41dec5a1754d353a3b794a585 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/python3
+#!/usr/bin/env python3
 #
 # Copyright (C) 2017 Francis Deslauriers <francis.deslauriers@efficios.com>
 #
@@ -10,118 +10,138 @@ import bisect
 import subprocess
 import re
 
+
 def addr2line(executable, addr):
     """
-        Uses binutils' addr2line to get function containing a given address
+    Uses binutils' addr2line to get function containing a given address
     """
-    cmd =['addr2line']
+    cmd = ["addr2line"]
 
-    cmd += ['-e', executable]
+    cmd += ["-e", executable]
 
     # Print function names
-    cmd += ['--functions']
+    cmd += ["--functions"]
 
     # Expand inlined functions
-    cmd += ['--addresses', addr]
+    cmd += ["--addresses", addr]
+
+    status = subprocess.run(cmd, stdout=subprocess.PIPE, check=True)
 
-    addr2line_output = subprocess.getoutput(' '.join(cmd))
+    addr2line_output = status.stdout.decode("utf-8").splitlines()
+    # addr2line's output is made of 3-tuples:
+    #   - address
+    #   - function name
+    #   - source location
+    if len(addr2line_output) % 3 != 0:
+        raise Exception(
+            "Unexpected addr2line output:\n\t{}".format("\n\t".join(addr2line_output))
+        )
 
-    # Omit the last 2 lines as the caller of main can not be determine
-    fcts = [addr2line_output.split()[-2]]
+    function_names = []
+    for address_line_number in range(0, len(addr2line_output), 3):
+        function_name = addr2line_output[address_line_number + 1]
 
-    fcts = [ f for f in fcts if '??' not in f]
+        # Filter-out unresolved functions
+        if "??" not in function_name:
+            function_names.append(addr2line_output[address_line_number + 1])
+
+    return function_names
 
-    return fcts
 
 def extract_user_func_names(executable, raw_callstack):
     """
-        Given a callstack from the Babeltrace CLI output, returns a set
-        containing the name of the functions. This assumes that the binary have
-        not changed since the execution.
+    Given a callstack from the Babeltrace CLI output, returns a set
+    containing the name of the functions. This assumes that the binary have
+    not changed since the execution.
     """
     recorded_callstack = set()
 
     # Remove commas and split on spaces
-    for index, addr in enumerate(raw_callstack.replace(',', '').split(' ')):
+    for index, addr in enumerate(raw_callstack.replace(",", "").split(" ")):
         # Consider only the elements starting with '0x' which are the
         # addresses recorded in the callstack
-        if '0x' in addr[:2]:
+        if "0x" in addr[:2]:
             funcs = addr2line(executable, addr)
             recorded_callstack.update(funcs)
 
     return recorded_callstack
 
+
 def extract_kernel_func_names(raw_callstack):
     """
-        Given a callstack from the Babeltrace CLI output, returns a set
-        containing the name of the functions.
-        Uses the /proc/kallsyms procfile to find the symbol associated with an
-        address. This function should only be used if the user is root or has
-        access to /proc/kallsyms.
+    Given a callstack from the Babeltrace CLI output, returns a set
+    containing the name of the functions.
+    Uses the /proc/kallsyms procfile to find the symbol associated with an
+    address. This function should only be used if the user is root or has
+    access to /proc/kallsyms.
     """
     recorded_callstack = set()
-    syms=[]
-    addresses=[]
+    syms = []
+    addresses = []
     # We read kallsyms file and save the output
-    with open('/proc/kallsyms') as kallsyms_f:
+    with open("/proc/kallsyms") as kallsyms_f:
         for line in kallsyms_f:
             line_tokens = line.split()
             addr = line_tokens[0]
             symbol = line_tokens[2]
             addresses.append(int(addr, 16))
-            syms.append({'addr':int(addr, 16), 'symbol':symbol})
+            syms.append({"addr": int(addr, 16), "symbol": symbol})
 
     # Save the address and symbol in a sorted list of tupple
-    syms = sorted(syms, key=lambda k:k['addr'])
+    syms = sorted(syms, key=lambda k: k["addr"])
     # We save the list of addresses in a seperate sorted list to easily bisect
     # the closer address of a symbol.
     addresses = sorted(addresses)
 
     # Remove commas and split on spaces
-    for addr in raw_callstack.replace(',', '').split(' '):
-        if '0x' in addr[:2]:
+    for addr in raw_callstack.replace(",", "").split(" "):
+        if "0x" in addr[:2]:
             # Search the location of the address in the addresses list and
             # deference this location in the syms list to add the associated
             # symbol.
             loc = bisect.bisect(addresses, int(addr, 16))
-            recorded_callstack.add(syms[loc-1]['symbol'])
+            recorded_callstack.add(syms[loc - 1]["symbol"])
 
     return recorded_callstack
 
+
 # Regex capturing the callstack_user and callstack_kernel context
-user_cs_rexp='.*callstack_user\ \=\ \[(.*)\]\ .*\}, \{.*\}'
-kernel_cs_rexp='.*callstack_kernel\ \=\ \[(.*)\]\ .*\}, \{.*\}'
+user_cs_rexp = ".*callstack_user\ \=\ \[(.*)\]\ .*\}, \{.*\}"
+kernel_cs_rexp = ".*callstack_kernel\ \=\ \[(.*)\]\ .*\}, \{.*\}"
+
 
 def main():
     """
-        Reads a line from stdin and expect it to be a wellformed Babeltrace CLI
-        output containing containing a callstack context of the domain passed
-        as argument.
+    Reads a line from stdin and expect it to be a wellformed Babeltrace CLI
+    output containing containing a callstack context of the domain passed
+    as argument.
     """
     expected_callstack = set()
     recorded_callstack = set()
-    cs_type=None
+    cs_type = None
 
     if len(sys.argv) <= 2:
         print(sys.argv)
-        raise ValueError('USAGE: ./{} (--kernel|--user EXE) FUNC-NAMES'.format(sys.argv[0]))
+        raise ValueError(
+            "USAGE: ./{} (--kernel|--user EXE) FUNC-NAMES".format(sys.argv[0])
+        )
 
     # If the `--user` option is passed, save the next argument as the path
     # to the executable
-    argc=1
-    executable=None
-    if sys.argv[argc] in '--kernel':
+    argc = 1
+    executable = None
+    if sys.argv[argc] in "--kernel":
         rexp = kernel_cs_rexp
-        cs_type='kernel'
-    elif sys.argv[argc] in '--user':
+        cs_type = "kernel"
+    elif sys.argv[argc] in "--user":
         rexp = user_cs_rexp
-        cs_type='user'
-        argc+=1
+        cs_type = "user"
+        argc += 1
         executable = sys.argv[argc]
     else:
-        raise Exception('Unknown domain')
+        raise Exception("Unknown domain")
 
-    argc+=1
+    argc += 1
 
     # Extract the function names that are expected to be found call stack of
     # the current events
@@ -139,22 +159,23 @@ def main():
 
     # If there is no match, exit with error
     if m is None:
-        raise re.error('Callstack not found in event line')
+        raise re.error("Callstack not found in event line")
     else:
         raw_callstack = str(m.group(1))
-        if cs_type in 'user':
-            recorded_callstack=extract_user_func_names(executable, raw_callstack)
-        elif cs_type in 'kernel':
-            recorded_callstack=extract_kernel_func_names(raw_callstack)
+        if cs_type in "user":
+            recorded_callstack = extract_user_func_names(executable, raw_callstack)
+        elif cs_type in "kernel":
+            recorded_callstack = extract_kernel_func_names(raw_callstack)
         else:
-            raise Exception('Unknown domain')
+            raise Exception("Unknown domain")
 
     # Verify that all expected function are present in the callstack
     for e in expected_callstack:
         if e not in recorded_callstack:
-            raise Exception('Expected function name not found in recorded callstack')
+            raise Exception("Expected function name not found in recorded callstack")
 
     sys.exit(0)
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
index 65037ab65f5dfb03d729704d0132217b66091053..56d4d3e45487d8eb2c15800f92a355b43b332340 100755 (executable)
@@ -117,6 +117,8 @@ else
   init_colors=''
 fi
 
+TIME_SCRIPT="$(realpath -e -- "$(dirname "$0")")/tap/clock"
+
 # :; is there to work around a bug in bash 3.2 (and earlier) which
 # does not always set '$?' properly on redirection failure.
 # See the Autoconf manual for more details.
@@ -142,7 +144,17 @@ fi
     else
       exec 2>&3
     fi
-    "$@"
+    # Since stderr and stdout may go to the same file and the script
+    # may run in situations with different types of buffering, enforce
+    # line buffering for both FDs. This helps to prevent interleave between
+    # the outputs in the resulting file for half written lines, eg.
+    #   ok 93 - Tes# PERROR - xxxx
+    #   t some function
+    if [ "${LTTNG_TESTS_TAP_AUTOTIME:-}" != 0 ]; then
+      stdbuf -eL -oL -- "$@"
+    else
+      "$@"
+    fi
     echo $?
   ) | LC_ALL=C ${AM_TAP_AWK-awk} \
         -v me="$me" \
@@ -154,6 +166,7 @@ fi
         -v ignore_exit="$ignore_exit" \
         -v comments="$comments" \
         -v diag_string="$diag_string" \
+        -v time_script="${TIME_SCRIPT}" \
 '
 # TODO: the usages of "cat >&3" below could be optimized when using
 #       GNU awk, and/on on systems that supports /dev/fd/.
@@ -211,6 +224,16 @@ function copy_in_global_log()
   return 0
 }
 
+function gettime_ns(    r)
+{
+   r = ""
+   if (time_script | getline r) {
+     r = r
+   }
+   close(time_script)
+   return sprintf("%f", r)
+}
+
 function get_global_test_result()
 {
     if ("ERROR" in test_results_seen)
@@ -482,6 +505,7 @@ function write_test_results()
   print ":global-test-result: " get_global_test_result() > trs_file
   print ":recheck: "  yn(must_recheck()) > trs_file
   print ":copy-in-global-log: " yn(copy_in_global_log()) > trs_file
+  print ":time-taken: " sprintf("%f", gettime_ns() - TIME_START) > trs_file
   for (i = 0; i < test_results_index; i += 1)
     print ":test-result: " test_results_list[i] > trs_file
   close(trs_file);
@@ -515,6 +539,7 @@ bailed_out = 0 # Whether a "Bail out!" directive has been seen.
 # it is ("early" is seen before any test result, "late" otherwise).
 plan_seen = NO_PLAN
 
+TIME_START = gettime_ns();
 ## --------- ##
 ##  PARSING  ##
 ## --------- ##
index f84d91c8ae331061358098a24b601881fd39ed47..a914b781313ec8c02f556b3fcc0104bfc3c83942 100644 (file)
@@ -1,7 +1,13 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
+AM_CPPFLAGS += -I$(top_srcdir)/src/ -I$(top_srcdir)/include
+
+noinst_PROGRAMS = clock
+clock_SOURCES = clock.cpp
+clock_CPPFLAGS = $(AM_CPPFLAGS)
 noinst_LTLIBRARIES = libtap.la
 libtap_la_SOURCES = tap.c tap.h
+libtap_la_LIBADD = ../libtestutils.la
 dist_noinst_SCRIPTS = tap.sh
 EXTRA_DIST = tap.sh
 
diff --git a/tests/utils/tap/clock.cpp b/tests/utils/tap/clock.cpp
new file mode 100644 (file)
index 0000000..9af321f
--- /dev/null
@@ -0,0 +1,21 @@
+/**
+ * Copyright (C) 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "common/time.hpp"
+
+#include <stdio.h>
+
+int main()
+{
+       struct timespec t;
+       const auto ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t);
+
+       if (ret == 0) {
+               printf("%ld.%09ld\n", t.tv_sec, t.tv_nsec);
+       }
+
+       return ret;
+}
index 9f41408bd4c4dd25a729b607b4c276bb115ab27b..687ea22f28a9adf7f787dc473b5313d1da129cf3 100644 (file)
@@ -5,15 +5,19 @@
  * Copyright (C) 2017 Jérémie Galarneau
  */
 
+#include "../utils.h"
+#include "common/compat/time.hpp"
+#include "tap.h"
+
+#include <assert.h>
 #include <ctype.h>
+#include <errno.h>
+#include <limits.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <limits.h>
-#include <assert.h>
-
-#include "tap.h"
+#include <time.h>
 
 static int no_plan = 0;
 static int skip_all = 0;
@@ -25,17 +29,19 @@ static char *todo_msg = NULL;
 static const char *todo_msg_fixed = "libtap malloc issue";
 static int todo = 0;
 static int test_died = 0;
+static int time_tests = 1;
+struct timespec last_time;
 
 /* Encapsulate the pthread code in a conditional.  In the absence of
    libpthread the code does nothing */
 #ifdef HAVE_LIBPTHREAD
 #include <pthread.h>
 static pthread_mutex_t M = PTHREAD_MUTEX_INITIALIZER;
-# define LOCK pthread_mutex_lock(&M);
-# define UNLOCK pthread_mutex_unlock(&M);
+#define LOCK   pthread_mutex_lock(&M);
+#define UNLOCK pthread_mutex_unlock(&M);
 #else
-# define LOCK
-# define UNLOCK
+#define LOCK
+#define UNLOCK
 #endif
 
 static void _expected_tests(unsigned int);
@@ -43,14 +49,14 @@ static void _tap_init(void);
 static void _cleanup(void);
 
 #ifdef __MINGW32__
-static inline
-void flockfile (FILE * filehandle) {
-       return;
+static inline void flockfile(FILE *filehandle)
+{
+       return;
 }
 
-static inline
-void funlockfile(FILE * filehandle) {
-       return;
+static inline void funlockfile(FILE *filehandle)
+{
+       return;
 }
 #endif
 
@@ -61,9 +67,8 @@ void funlockfile(FILE * filehandle) {
  * test_name -- the name of the test, may be NULL
  * test_comment -- a comment to print afterwards, may be NULL
  */
-unsigned int
-_gen_result(int ok, const char *func, const char *file, unsigned int line,
-           const char *test_name, ...)
+unsigned int _gen_result(
+       int ok, const char *func, const char *file, unsigned int line, const char *test_name, ...)
 {
        va_list ap;
        char *local_test_name = NULL;
@@ -76,7 +81,7 @@ _gen_result(int ok, const char *func, const char *file, unsigned int line,
 
        /* Start by taking the test name and performing any printf()
           expansions on it */
-       if(test_name != NULL) {
+       if (test_name != NULL) {
                va_start(ap, test_name);
                if (vasprintf(&local_test_name, test_name, ap) == -1) {
                        local_test_name = NULL;
@@ -86,43 +91,44 @@ _gen_result(int ok, const char *func, const char *file, unsigned int line,
                /* Make sure the test name contains more than digits
                   and spaces.  Emit an error message and exit if it
                   does */
-               if(local_test_name) {
+               if (local_test_name) {
                        name_is_digits = 1;
-                       for(c = local_test_name; *c != '\0'; c++) {
-                               if(!isdigit((unsigned char) *c) && !isspace((unsigned char) *c)) {
+                       for (c = local_test_name; *c != '\0'; c++) {
+                               if (!isdigit((unsigned char) *c) && !isspace((unsigned char) *c)) {
                                        name_is_digits = 0;
                                        break;
                                }
                        }
 
-                       if(name_is_digits) {
-                               diag("    You named your test '%s'.  You shouldn't use numbers for your test names.", local_test_name);
+                       if (name_is_digits) {
+                               diag("    You named your test '%s'.  You shouldn't use numbers for your test names.",
+                                    local_test_name);
                                diag("    Very confusing.");
                        }
                }
        }
 
-       if(!ok) {
+       if (!ok) {
                printf("not ");
                failures++;
        }
 
        printf("ok %d", test_count);
 
-       if(test_name != NULL) {
+       if (test_name != NULL) {
                printf(" - ");
 
                /* Print the test name, escaping any '#' characters it
                   might contain */
-               if(local_test_name != NULL) {
+               if (local_test_name != NULL) {
                        flockfile(stdout);
-                       for(c = local_test_name; *c != '\0'; c++) {
-                               if(*c == '#')
+                       for (c = local_test_name; *c != '\0'; c++) {
+                               if (*c == '#')
                                        fputc('\\', stdout);
-                               fputc((int)*c, stdout);
+                               fputc((int) *c, stdout);
                        }
                        funlockfile(stdout);
-               } else {        /* vasprintf() failed, use a fixed message */
+               } else { /* vasprintf() failed, use a fixed message */
                        printf("%s", todo_msg_fixed);
                }
        }
@@ -134,20 +140,24 @@ _gen_result(int ok, const char *func, const char *file, unsigned int line,
 
           This is not counted as a failure, so decrement the counter if
           the test failed. */
-       if(todo) {
+       if (todo) {
                printf(" # TODO %s", todo_msg ? todo_msg : todo_msg_fixed);
-               if(!ok)
+               if (!ok)
                        failures--;
        }
 
        printf("\n");
+       _output_test_time();
 
-       if(!ok) {
-               if(getenv("HARNESS_ACTIVE") != NULL)
+       if (!ok) {
+               if (getenv("HARNESS_ACTIVE") != NULL)
                        fputs("\n", stderr);
 
                diag("    Failed %stest (%s:%s() at line %d)",
-                    todo ? "(TODO) " : "", file, func, line);
+                    todo ? "(TODO) " : "",
+                    file,
+                    func,
+                    line);
        }
        free(local_test_name);
 
@@ -162,34 +172,52 @@ _gen_result(int ok, const char *func, const char *file, unsigned int line,
  * Initialise the TAP library.  Will only do so once, however many times it's
  * called.
  */
-void
-_tap_init(void)
+void _tap_init(void)
 {
        static int run_once = 0;
 
-       if(!run_once) {
+       if (!run_once) {
                atexit(_cleanup);
 
                /* stdout needs to be unbuffered so that the output appears
                   in the same place relative to stderr output as it does
                   with Test::Harness */
                setbuf(stdout, 0);
+
+               /*
+                * Check if the LTTNG_TESTS_TAP_AUTOTIME environment variable
+                * is set and contains at least one byte.
+                */
+               const char *autotime_env = getenv("LTTNG_TESTS_TAP_AUTOTIME");
+               if (autotime_env != NULL && strnlen(autotime_env, 1)) {
+                       int tap_autotime;
+
+                       /*
+                        * Check if LTTNG_TESTS_TAP_AUTOTIME is '0', also check
+                        * errno because strtol() can return '0' on error.
+                        */
+                       errno = 0;
+                       tap_autotime = strtol(autotime_env, NULL, 10);
+                       if (tap_autotime == 0 && errno == 0) {
+                               time_tests = 0;
+                       }
+               }
+
                run_once = 1;
        }
+       lttng_clock_gettime(CLOCK_MONOTONIC, &last_time);
 }
 
 /*
  * Note that there's no plan.
  */
-int
-plan_no_plan(void)
+int plan_no_plan(void)
 {
-
        LOCK;
 
        _tap_init();
 
-       if(have_plan != 0) {
+       if (have_plan != 0) {
                fprintf(stderr, "You tried to plan twice!\n");
                test_died = 1;
                UNLOCK;
@@ -207,10 +235,8 @@ plan_no_plan(void)
 /*
  * Note that the plan is to skip all tests
  */
-int
-plan_skip_all(const char *reason)
+int plan_skip_all(const char *reason)
 {
-
        LOCK;
 
        _tap_init();
@@ -219,7 +245,7 @@ plan_skip_all(const char *reason)
 
        printf("1..0");
 
-       if(reason != NULL)
+       if (reason != NULL)
                printf(" # Skip %s", reason);
 
        printf("\n");
@@ -232,22 +258,20 @@ plan_skip_all(const char *reason)
 /*
  * Note the number of tests that will be run.
  */
-int
-plan_tests(unsigned int tests)
+int plan_tests(unsigned int tests)
 {
-
        LOCK;
 
        _tap_init();
 
-       if(have_plan != 0) {
+       if (have_plan != 0) {
                fprintf(stderr, "You tried to plan twice!\n");
                test_died = 1;
                UNLOCK;
                exit(255);
        }
 
-       if(tests == 0) {
+       if (tests == 0) {
                fprintf(stderr, "You said to run 0 tests!  You've got to run something.\n");
                test_died = 1;
                UNLOCK;
@@ -263,8 +287,7 @@ plan_tests(unsigned int tests)
        return e_tests;
 }
 
-unsigned int
-diag(const char *fmt, ...)
+unsigned int diag(const char *fmt, ...)
 {
        va_list ap;
 
@@ -279,8 +302,7 @@ diag(const char *fmt, ...)
        return 0;
 }
 
-void
-diag_multiline(const char *val)
+void diag_multiline(const char *val)
 {
        size_t len, i, line_start_idx = 0;
 
@@ -301,16 +323,13 @@ diag_multiline(const char *val)
        }
 }
 
-void
-_expected_tests(unsigned int tests)
+void _expected_tests(unsigned int tests)
 {
-
        printf("1..%d\n", tests);
        e_tests = tests;
 }
 
-int
-skip(unsigned int n, const char *fmt, ...)
+int skip(unsigned int n, const char *fmt, ...)
 {
        va_list ap;
        char *skip_msg = NULL;
@@ -323,11 +342,12 @@ skip(unsigned int n, const char *fmt, ...)
        }
        va_end(ap);
 
-       while(n-- > 0) {
+       while (n-- > 0) {
                test_count++;
-               printf("ok %d # skip %s\n", test_count,
-                      skip_msg != NULL ?
-                      skip_msg : "libtap():malloc() failed");
+               printf("ok %d # skip %s\n",
+                      test_count,
+                      skip_msg != NULL ? skip_msg : "libtap():malloc() failed");
+               _output_test_time();
        }
 
        free(skip_msg);
@@ -337,8 +357,21 @@ skip(unsigned int n, const char *fmt, ...)
        return 1;
 }
 
-void
-todo_start(const char *fmt, ...)
+void _output_test_time(void)
+{
+       struct timespec new_time;
+       int64_t time_ns;
+       if (time_tests) {
+               lttng_clock_gettime(CLOCK_MONOTONIC, &new_time);
+               time_ns = elapsed_time_ns(&last_time, &new_time);
+               printf("  ---\n    duration_ms: %ld.%ld\n  ...\n",
+                      time_ns / 1000000,
+                      time_ns % 1000000);
+       }
+       lttng_clock_gettime(CLOCK_MONOTONIC, &last_time);
+}
+
+void todo_start(const char *fmt, ...)
 {
        va_list ap;
 
@@ -355,10 +388,8 @@ todo_start(const char *fmt, ...)
        UNLOCK;
 }
 
-void
-todo_end(void)
+void todo_end(void)
 {
-
        LOCK;
 
        todo = 0;
@@ -367,22 +398,21 @@ todo_end(void)
        UNLOCK;
 }
 
-int
-exit_status(void)
+int exit_status(void)
 {
        int r;
 
        LOCK;
 
        /* If there's no plan, just return the number of failures */
-       if(no_plan || !have_plan) {
+       if (no_plan || !have_plan) {
                UNLOCK;
                return failures;
        }
 
        /* Ran too many tests?  Return the number of tests that were run
           that shouldn't have been */
-       if(e_tests < test_count) {
+       if (e_tests < test_count) {
                r = test_count - e_tests;
                UNLOCK;
                return r;
@@ -400,51 +430,54 @@ exit_status(void)
  * Cleanup at the end of the run, produce any final output that might be
  * required.
  */
-void
-_cleanup(void)
+void _cleanup(void)
 {
-
        LOCK;
 
        /* If plan_no_plan() wasn't called, and we don't have a plan,
           and we're not skipping everything, then something happened
           before we could produce any output */
-       if(!no_plan && !have_plan && !skip_all) {
+       if (!no_plan && !have_plan && !skip_all) {
                diag("Looks like your test died before it could output anything.");
                UNLOCK;
                return;
        }
 
-       if(test_died) {
+       if (test_died) {
                diag("Looks like your test died just after %d.", test_count);
                UNLOCK;
                return;
        }
 
-
        /* No plan provided, but now we know how many tests were run, and can
           print the header at the end */
-       if(!skip_all && (no_plan || !have_plan)) {
+       if (!skip_all && (no_plan || !have_plan)) {
                printf("1..%d\n", test_count);
        }
 
-       if((have_plan && !no_plan) && e_tests < test_count) {
+       if ((have_plan && !no_plan) && e_tests < test_count) {
                diag("Looks like you planned %d %s but ran %d extra.",
-                    e_tests, e_tests == 1 ? "test" : "tests", test_count - e_tests);
+                    e_tests,
+                    e_tests == 1 ? "test" : "tests",
+                    test_count - e_tests);
                UNLOCK;
                return;
        }
 
-       if((have_plan || !no_plan) && e_tests > test_count) {
+       if ((have_plan || !no_plan) && e_tests > test_count) {
                diag("Looks like you planned %d %s but only ran %d.",
-                    e_tests, e_tests == 1 ? "test" : "tests", test_count);
+                    e_tests,
+                    e_tests == 1 ? "test" : "tests",
+                    test_count);
                UNLOCK;
                return;
        }
 
-       if(failures)
+       if (failures)
                diag("Looks like you failed %d %s of %d.",
-                    failures, failures == 1 ? "test" : "tests", test_count);
+                    failures,
+                    failures == 1 ? "test" : "tests",
+                    test_count);
 
        UNLOCK;
 }
index bc6745a73862040006ab51712ff48ade74d628bb..d4419181a64212521ea2481dc1740af67796df08 100644 (file)
@@ -13,74 +13,71 @@ extern "C" {
    and requires the caller to add the final comma if they've ommitted
    the optional arguments */
 #ifdef __GNUC__
-# define ok(e, test, ...) ((e) ?                                       \
-                          _gen_result(1, __func__, __FILE__, __LINE__, \
-                                      test, ## __VA_ARGS__) :          \
-                          _gen_result(0, __func__, __FILE__, __LINE__, \
-                                      test, ## __VA_ARGS__))
-
-# define ok1(e) ((e) ?                                                 \
-                _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
-                _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
-
-# define pass(test, ...) ok(1, test, ## __VA_ARGS__)
-# define fail(test, ...) ok(0, test, ## __VA_ARGS__)
-
-# define skip_start(test, n, fmt, ...)                 \
-       do {                                            \
-               if((test)) {                            \
-                       skip(n, fmt, ## __VA_ARGS__);   \
-                       continue;                       \
+#define ok(e, test, ...)                                                           \
+       ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__) : \
+              _gen_result(0, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__))
+
+#define ok1(e)                                                          \
+       ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
+              _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
+
+#define pass(test, ...) ok(1, test, ##__VA_ARGS__)
+#define fail(test, ...) ok(0, test, ##__VA_ARGS__)
+
+#define skip_start(test, n, fmt, ...)                \
+       do {                                         \
+               if ((test)) {                        \
+                       skip(n, fmt, ##__VA_ARGS__); \
+                       continue;                    \
                }
 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* __GNUC__ */
-# define ok(e, ...) ((e) ?                                             \
-                    _gen_result(1, __func__, __FILE__, __LINE__,       \
-                                __VA_ARGS__) :                         \
-                    _gen_result(0, __func__, __FILE__, __LINE__,       \
-                                __VA_ARGS__))
-
-# define ok1(e) ((e) ?                                                 \
-                _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
-                _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
-
-# define pass(...) ok(1, __VA_ARGS__)
-# define fail(...) ok(0, __VA_ARGS__)
-
-# define skip_start(test, n, ...)                      \
-       do {                                            \
-               if((test)) {                            \
-                       skip(n,  __VA_ARGS__);          \
-                       continue;                       \
+#define ok(e, ...)                                                         \
+       ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, __VA_ARGS__) : \
+              _gen_result(0, __func__, __FILE__, __LINE__, __VA_ARGS__))
+
+#define ok1(e)                                                          \
+       ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : \
+              _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
+
+#define pass(...) ok(1, __VA_ARGS__)
+#define fail(...) ok(0, __VA_ARGS__)
+
+#define skip_start(test, n, ...)              \
+       do {                                  \
+               if ((test)) {                 \
+                       skip(n, __VA_ARGS__); \
+                       continue;             \
                }
 #else /* __STDC_VERSION__ */
-# error "Needs gcc or C99 compiler for variadic macros."
+#error "Needs gcc or C99 compiler for variadic macros."
 #endif /* __STDC_VERSION__ */
 
-#define skip_end() } while(0);
+#define skip_end() \
+       }          \
+       while (0)  \
+               ;
 
 #ifdef __MINGW_PRINTF_FORMAT
-# define TAP_PRINTF_FORMAT __MINGW_PRINTF_FORMAT
+#define TAP_PRINTF_FORMAT __MINGW_PRINTF_FORMAT
 #else
-# define TAP_PRINTF_FORMAT printf
+#define TAP_PRINTF_FORMAT printf
 #endif
 
-__attribute__((format(TAP_PRINTF_FORMAT, 5, 6)))
-unsigned int _gen_result(int, const char *, const char *, unsigned int, const char *, ...);
+__attribute__((format(TAP_PRINTF_FORMAT, 5, 6))) unsigned int
+_gen_result(int, const char *, const char *, unsigned int, const char *, ...);
+
+void _output_test_time(void);
 
 int plan_no_plan(void);
-__attribute__((noreturn))
-int plan_skip_all(const char *);
+__attribute__((noreturn)) int plan_skip_all(const char *);
 int plan_tests(unsigned int);
 
-__attribute__((format(TAP_PRINTF_FORMAT, 1, 2)))
-unsigned int diag(const char *, ...);
+__attribute__((format(TAP_PRINTF_FORMAT, 1, 2))) unsigned int diag(const char *, ...);
 void diag_multiline(const char *);
 
-__attribute__((format(TAP_PRINTF_FORMAT, 2, 3)))
-int skip(unsigned int, const char *, ...);
+__attribute__((format(TAP_PRINTF_FORMAT, 2, 3))) int skip(unsigned int, const char *, ...);
 
-__attribute__((format(TAP_PRINTF_FORMAT, 1, 2)))
-void todo_start(const char *, ...);
+__attribute__((format(TAP_PRINTF_FORMAT, 1, 2))) void todo_start(const char *, ...);
 void todo_end(void);
 
 int exit_status(void);
index 4b51106c013273aee268342734446f5c43f2aabe..eae7c3a2c2610784d2f45f479883c35329c68223 100755 (executable)
@@ -14,8 +14,10 @@ _test_died=0
 _expected_tests=0
 _executed_tests=0
 _failed_tests=0
+_auto_timing="${LTTNG_TESTS_TAP_AUTOTIME:-1}"
+_last_time=''
 TODO=
-
+TIME_SCRIPT="$(realpath -e -- "$(dirname "${BASH_SOURCE[0]}")")/clock"
 
 usage(){
     cat <<'USAGE'
@@ -52,6 +54,7 @@ TODO:
 
 OTHER:
   diag MSG
+  autotime 0|1
 
 EXAMPLE:
   #!/bin/bash
@@ -105,6 +108,7 @@ plan_no_plan(){
 
     _plan_set=1
     _no_plan=1
+    _last_time=$("${TIME_SCRIPT}")
 
     return 0
 }
@@ -119,6 +123,7 @@ plan_skip_all(){
 
     _skip_all=1
     _plan_set=1
+    _last_time=$("${TIME_SCRIPT}")
     _exit 0
 
     return 0
@@ -133,6 +138,7 @@ plan_tests(){
     _print_plan $tests
     _expected_tests=$tests
     _plan_set=1
+    _last_time=$("${TIME_SCRIPT}")
 
     return $tests
 }
@@ -195,6 +201,7 @@ ok(){
     fi
 
     echo
+    _autotime
     if (( result != 0 )) ; then
         local file='tap-functions'
         local func=
@@ -233,6 +240,7 @@ okx(){
         diag "$line"
     done
     ok ${PIPESTATUS[0]} "$command"
+    _autotime
 }
 
 
@@ -342,6 +350,7 @@ skip(){
         for (( i=0 ; i<$n ; i++ )) ; do
             _executed_tests=$(( _executed_tests + 1 ))
             echo "ok $_executed_tests # skip: $reason"
+            _autotime
         done
         return 0
     else
@@ -349,6 +358,32 @@ skip(){
     fi
 }
 
+_autotime(){
+    local new_time
+    local duration
+
+    if [ "${_auto_timing}" -eq "1" ] ; then
+        new_time=$("${TIME_SCRIPT}")
+        duration=$(awk "BEGIN { printf(\"%f\n\", ($new_time - $_last_time)*1000) }")
+        echo "  ---"
+        echo "    duration_ms: ${duration}"
+        echo "  ..."
+    fi
+    _last_time=$("${TIME_SCRIPT}")
+    return 0
+}
+
+
+autotime(){
+    local val=${1:?}
+
+    if [[ "${val}" != "0" ]] ; then
+        _auto_timing=1
+    else
+        _auto_timing=0;
+    fi
+    return 0
+}
 
 diag(){
     local msg=${1:?}
index ba9c2946e7654cea703f74cd43b23a872ec662b9..2cae263c43db60dddeac144ac893175851dadb14 100644 (file)
@@ -10,6 +10,7 @@ import os
 import subprocess
 import shutil
 import sys
+import time
 import tempfile
 
 # Import lttng bindings generated in the current tree
@@ -22,7 +23,28 @@ sys.path.append(lttng_bindings_path)
 sys.path.append(lttng_bindings_libs_path)
 from lttng import *
 
-BABELTRACE_BIN="babeltrace2"
+_time_tests = True
+if os.getenv("LTTNG_TESTS_TAP_AUTOTIME", "1") == "0":
+    _time_tests = False
+
+
+def _get_time_ns():
+    # type: () -> int
+
+    # time.monotonic is only available since Python 3.3. We don't support
+    # those older versions so we can simply assert here.
+    assert sys.version_info >= (3, 3, 0)
+
+    # time.monotonic_ns is only available for python >= 3.8,
+    # so the value is multiplied by 10^9 to maintain compatibility with
+    # older versions of the interpreter.
+    return int(time.monotonic() * 1000000000)
+
+
+_last_time = _get_time_ns()
+
+BABELTRACE_BIN = "babeltrace2"
+
 
 class SessionInfo:
     def __init__(self, handle, session_name, tmp_directory, channel_name):
@@ -32,7 +54,8 @@ class SessionInfo:
         self.trace_path = tmp_directory + "/" + session_name
         self.channel_name = channel_name
 
-def bail(diag, session_info = None):
+
+def bail(diag, session_info=None):
     print("Bail out!")
     print("#", diag)
 
@@ -43,6 +66,17 @@ def bail(diag, session_info = None):
             shutil.rmtree(session_info.tmp_directory)
     exit(-1)
 
+
+def print_automatic_test_timing():
+    global _time_tests
+    global _last_time
+    if not _time_tests:
+        return
+    duration_ns = _get_time_ns() - _last_time
+    print("  ---\n    duration_ms: {:02f}\n  ...".format(duration_ns / 1000000))
+    _last_time = _get_time_ns()
+
+
 def print_test_result(result, number, description):
     result_string = None
     if result is True:
@@ -52,9 +86,13 @@ def print_test_result(result, number, description):
 
     result_string += " {0} - {1}".format(number, description)
     print(result_string)
+    print_automatic_test_timing()
+
 
 def skip_test(number, description):
-    print('ok {} # skip {}'.format(number, description))
+    print("ok {} # skip {}".format(number, description))
+    print_automatic_test_timing()
+
 
 def enable_ust_tracepoint_event(session_info, event_name):
     event = Event()
@@ -65,6 +103,7 @@ def enable_ust_tracepoint_event(session_info, event_name):
     if res < 0:
         bail("Failed to enable userspace event " + event_name, session_info)
 
+
 def create_session():
     dom = Domain()
     dom.type = DOMAIN_UST
@@ -89,17 +128,23 @@ def create_session():
         bail("Failed to enable channel " + channel.name, session_info)
     return session_info
 
+
 def start_session(session_info):
     start(session_info.name)
 
-def stop_session(session_info, bailing = False):
+
+def stop_session(session_info, bailing=False):
     # Workaround lttng-ctl outputing directly to stdout by spawning a subprocess.
     lttng_binary_path = os.path.dirname(os.path.abspath(__file__)) + "/"
     for i in range(3):
         lttng_binary_path = os.path.dirname(lttng_binary_path)
     lttng_binary_path = lttng_binary_path + "/src/bin/lttng/lttng"
 
-    retcode = subprocess.call([lttng_binary_path, "stop", session_info.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    retcode = subprocess.call(
+        [lttng_binary_path, "stop", session_info.name],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+    )
     if retcode != 0 and not bailing:
         bail("Unable to stop session " + session_info.name, session_info)
     destroy(session_info.name)
index 55a7ba7ebddb055b0f61346a9ee8e69abb433091..b58c233d5fcca555652456b4c4b50b5bb93ccb8d 100644 (file)
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 SUBDIRS = \
+         gen-data-pending \
          gen-kernel-test-events \
          gen-py-events \
          gen-syscall-events \
@@ -8,7 +9,8 @@ SUBDIRS = \
          gen-ust-nevents-str \
          gen-ust-tracef \
          userspace-probe-elf-binary \
-         userspace-probe-elf-cxx-binary
+         userspace-probe-elf-cxx-binary \
+         gen-ust-events-constructor
 
 if TEST_SDT_UPROBE
 SUBDIRS += userspace-probe-sdt-binary
diff --git a/tests/utils/testapp/gen-data-pending/Makefile.am b/tests/utils/testapp/gen-data-pending/Makefile.am
new file mode 100644 (file)
index 0000000..70e0d01
--- /dev/null
@@ -0,0 +1,14 @@
+# SPDX-FileCopyrightText: 2023 Kienan Stewart <kstewart@efficios.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+AM_CPPFLAGS += -I$(top_srcdir)/tests/utils -I$(srcdir) \
+       -I$(top_srcdir)/tests/utils/testapp
+LIB_LTTNG_CTL = $(top_builddir)/src/lib/lttng-ctl/liblttng-ctl.la
+
+if HAVE_LIBLTTNG_UST_CTL
+noinst_PROGRAMS = gen-data-pending
+gen_data_pending_SOURCES = main.cpp
+gen_data_pending_LDADD = $(LIB_LTTNG_CTL)
+endif
diff --git a/tests/utils/testapp/gen-data-pending/main.cpp b/tests/utils/testapp/gen-data-pending/main.cpp
new file mode 100644 (file)
index 0000000..e92ceb3
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * SPDX-FileCopyrightText: 2023 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ *
+ */
+
+#include <lttng/lttng.h>
+
+#include <assert.h>
+
+int main(int argc, const char **argv)
+{
+       assert(argc >= 2);
+       lttng_data_pending(argv[1]);
+       return 0;
+}
index 5e488f9829df05bac1b387805f36ee11bb733f82..af8b76a17314d96078912f12f05d3167d5a8f2fc 100644 (file)
@@ -6,6 +6,8 @@
  *
  */
 
+#include "utils.h"
+
 #include <fcntl.h>
 #include <stdio.h>
 #include <string.h>
@@ -13,8 +15,6 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#include "utils.h"
-
 #define LTTNG_MODULES_FILE "/proc/lttng-test-filter-event"
 
 /*
@@ -31,8 +31,7 @@ int main(int argc, char **argv)
 
        if (argc != 3) {
                fprintf(stderr, "Error: Missing argument\n");
-               fprintf(stderr, "USAGE: %s PATH_WAIT_FILE NR_EVENTS\n",
-                               argv[0]);
+               fprintf(stderr, "USAGE: %s PATH_WAIT_FILE NR_EVENTS\n", argv[0]);
                ret = -1;
                goto end;
        }
index 5c1cddefeb09917e862c7b994ac084a05adc7987..b556aa96f24b62a46ed9e513f4e8f56055e571c1 100644 (file)
@@ -5,6 +5,7 @@ AM_CPPFLAGS += -I$(top_srcdir)/tests/utils -I$(srcdir) \
 
 noinst_PROGRAMS = gen-ns-events
 gen_ns_events_SOURCES = gen-ns-events.cpp
+gen_ns_events_CPPFLAGS = $(POPT_CFLAGS) $(AM_CPPFLAGS)
 gen_ns_events_LDADD = \
                $(top_builddir)/tests/utils/libtestutils.la \
                $(DL_LIBS) $(POPT_LIBS)
index 80afdb6d63ed27c99510c7068436a7539d23bcf2..fef6b02f52f113e8844d766bc7e5b867e963d411 100644 (file)
@@ -9,6 +9,13 @@
 #define _GNU_SOURCE
 #endif
 
+#include "signal-helper.hpp"
+#include "utils.h"
+
+#include <common/compat/tid.hpp>
+#include <common/macros.hpp>
+
+#include <inttypes.h>
 #include <popt.h>
 #include <sched.h>
 #include <stdarg.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-
-#include <common/compat/tid.hpp>
-#include <common/macros.hpp>
-
-#include "signal-helper.hpp"
-#include "utils.h"
 
 #define LTTNG_PROC_NS_PATH_MAX 40
 
  * but that use a libc that doesn't define its associated clone flag.
  */
 #ifndef CLONE_NEWNS
-#define CLONE_NEWNS     0x00020000
+#define CLONE_NEWNS 0x00020000
 #endif
 #ifndef CLONE_NEWCGROUP
 #define CLONE_NEWCGROUP 0x02000000
 #endif
 #ifndef CLONE_NEWUTS
-#define CLONE_NEWUTS    0x04000000
+#define CLONE_NEWUTS 0x04000000
 #endif
 #ifndef CLONE_NEWIPC
-#define CLONE_NEWIPC    0x08000000
+#define CLONE_NEWIPC 0x08000000
 #endif
 #ifndef CLONE_NEWUSER
-#define CLONE_NEWUSER   0x10000000
+#define CLONE_NEWUSER 0x10000000
 #endif
 #ifndef CLONE_NEWPID
-#define CLONE_NEWPID    0x20000000
+#define CLONE_NEWPID 0x20000000
 #endif
 #ifndef CLONE_NEWNET
-#define CLONE_NEWNET    0x40000000
+#define CLONE_NEWNET 0x40000000
 #endif
 #ifndef CLONE_NEWTIME
-#define CLONE_NEWTIME   0x00000080
+#define CLONE_NEWTIME 0x00000080
 #endif
 
 static int debug = 0;
-static char *ns_opt = NULL;
-static char *before_unshare_wait_file_path = NULL;
-static char *after_unshare_wait_file_path = NULL;
-static char *after_unshare_signal_file_path = NULL;
+static char *ns_opt = nullptr;
+static char *before_unshare_wait_file_path = nullptr;
+static char *after_unshare_wait_file_path = nullptr;
+static char *after_unshare_signal_file_path = nullptr;
 
 static struct poptOption opts[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       { "debug", 'd', POPT_ARG_NONE, &debug, 0, "Enable debug output", NULL },
-       { "ns", 'n', POPT_ARG_STRING, &ns_opt, 0, "Namespace short identifier", NULL },
-       { "before", 'b', POPT_ARG_STRING, &before_unshare_wait_file_path, 0, "Wait for file before unshare", NULL },
-       { "after", 'a', POPT_ARG_STRING, &after_unshare_wait_file_path, 0, "Wait for file after unshare", NULL },
-       { "signal", 's', POPT_ARG_STRING, &after_unshare_signal_file_path, 0, "Create signal file after unshare", NULL },
-       POPT_AUTOHELP
-       { NULL, 0, 0, NULL, 0, NULL, NULL }
+       { "debug", 'd', POPT_ARG_NONE, &debug, 0, "Enable debug output", nullptr },
+       { "ns", 'n', POPT_ARG_STRING, &ns_opt, 0, "Namespace short identifier", nullptr },
+       { "before",
+         'b',
+         POPT_ARG_STRING,
+         &before_unshare_wait_file_path,
+         0,
+         "Wait for file before unshare",
+         nullptr },
+       { "after",
+         'a',
+         POPT_ARG_STRING,
+         &after_unshare_wait_file_path,
+         0,
+         "Wait for file after unshare",
+         nullptr },
+       { "signal",
+         's',
+         POPT_ARG_STRING,
+         &after_unshare_signal_file_path,
+         0,
+         "Create signal file after unshare",
+         nullptr },
+       POPT_AUTOHELP{ nullptr, 0, 0, nullptr, 0, nullptr, nullptr }
 };
 
-static ATTR_FORMAT_PRINTF(1, 2)
-void debug_printf(const char *format, ...)
+static ATTR_FORMAT_PRINTF(1, 2) void debug_printf(const char *format, ...)
 {
        va_list args;
        va_start(args, format);
@@ -98,8 +114,7 @@ static int get_ns_inum(const char *ns, ino_t *ns_inum)
        /*
         * /proc/thread-self was introduced in kernel v3.17
         */
-       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX,
-                       "/proc/thread-self/ns/%s", ns) >= 0) {
+       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX, "/proc/thread-self/ns/%s", ns) >= 0) {
                if (stat(proc_ns_path, &sb) == 0) {
                        *ns_inum = sb.st_ino;
                } else {
@@ -108,8 +123,11 @@ static int get_ns_inum(const char *ns, ino_t *ns_inum)
                goto end;
        }
 
-       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX,
-                       "/proc/self/task/%d/%s/net", lttng_gettid(), ns) >= 0) {
+       if (snprintf(proc_ns_path,
+                    LTTNG_PROC_NS_PATH_MAX,
+                    "/proc/self/task/%d/%s/net",
+                    lttng_gettid(),
+                    ns) >= 0) {
                if (stat(proc_ns_path, &sb) == 0) {
                        *ns_inum = sb.st_ino;
                } else {
@@ -128,8 +146,7 @@ static int do_the_needful(int ns_flag, const char *ns_str)
 
        ret = get_ns_inum(ns_str, &ns1);
        if (ret) {
-               debug_printf("Failed to get ns inode number for namespace %s",
-                               ns_str);
+               debug_printf("Failed to get ns inode number for namespace %s", ns_str);
                ret = -1;
                goto end;
        }
@@ -151,8 +168,7 @@ static int do_the_needful(int ns_flag, const char *ns_str)
 
        ret = get_ns_inum(ns_str, &ns2);
        if (ret) {
-               debug_printf("Failed to get ns inode number for namespace %s",
-                               ns_str);
+               debug_printf("Failed to get ns inode number for namespace %s", ns_str);
                ret = -1;
                goto end;
        }
@@ -184,7 +200,7 @@ int main(int argc, const char **argv)
        int ret = EXIT_SUCCESS;
        poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, opts, 0);
+       pc = poptGetContext(nullptr, argc, argv, opts, 0);
        poptReadDefaultConfig(pc, 0);
 
        if (argc < 2) {
@@ -205,14 +221,15 @@ int main(int argc, const char **argv)
        if (opt < -1) {
                /* an error occurred during option processing */
                poptPrintUsage(pc, stderr, 0);
-               fprintf(stderr, "%s: %s\n",
+               fprintf(stderr,
+                       "%s: %s\n",
                        poptBadOption(pc, POPT_BADOPTION_NOALIAS),
                        poptStrerror(opt));
                ret = EXIT_FAILURE;
                goto end;
        }
 
-       if (ns_opt == NULL) {
+       if (ns_opt == nullptr) {
                poptPrintUsage(pc, stderr, 0);
                ret = EXIT_FAILURE;
                goto end;
index de6afef296f34b0f68e7b0f0ba4c18256252af8f..f48fca80707c907ddf9be25a2e4bd25272729730 100644 (file)
@@ -18,23 +18,23 @@ def _perror(msg):
 
 try:
     import lttngust
-except (ImportError) as e:
-    _perror('lttngust package not found: {}'.format(e))
+except ImportError as e:
+    _perror("lttngust package not found: {}".format(e))
 
 
 def _main():
-    ev1 = logging.getLogger('python-ev-test1');
-    ev2 = logging.getLogger('python-ev-test2');
+    ev1 = logging.getLogger("python-ev-test1")
+    ev2 = logging.getLogger("python-ev-test2")
 
     logging.basicConfig()
 
     parser = argparse.ArgumentParser()
-    parser.add_argument('-n', '--nr-iter', required=True)
-    parser.add_argument('-s', '--wait', required=True)
-    parser.add_argument('-d', '--fire-debug-event', action="store_true")
-    parser.add_argument('-e', '--fire-second-event', action="store_true")
-    parser.add_argument('-r', '--ready-file')
-    parser.add_argument('-g', '--go-file')
+    parser.add_argument("-n", "--nr-iter", required=True)
+    parser.add_argument("-s", "--wait", required=True)
+    parser.add_argument("-d", "--fire-debug-event", action="store_true")
+    parser.add_argument("-e", "--fire-second-event", action="store_true")
+    parser.add_argument("-r", "--ready-file")
+    parser.add_argument("-g", "--go-file")
     args = parser.parse_args()
 
     nr_iter = int(args.nr_iter)
@@ -46,34 +46,34 @@ def _main():
     go_file = args.go_file
 
     if ready_file is not None and os.path.exists(ready_file):
-        raise ValueError('Ready file already exist')
+        raise ValueError("Ready file already exist")
 
     if go_file is not None and os.path.exists(go_file):
-        raise ValueError('Go file already exist. Review synchronization')
+        raise ValueError("Go file already exist. Review synchronization")
 
     if (ready_file is None) != (go_file is None):
-        raise ValueError('--go-file and --ready-file need each others, review'
-                'synchronization')
-
+        raise ValueError(
+            "--go-file and --ready-file need each others, review" "synchronization"
+        )
 
     # Inform that we are ready, if necessary
     if ready_file is not None:
-        open(ready_file, 'a').close()
+        open(ready_file, "a").close()
 
     # Wait for go, if necessary
     while go_file is not None and not os.path.exists(go_file):
         time.sleep(0.5)
 
     for i in range(nr_iter):
-        ev1.info('{} fired [INFO]'.format(ev1.name))
+        ev1.info("{} fired [INFO]".format(ev1.name))
 
         if fire_debug_ev:
-            ev1.debug('{} fired [DEBUG]'.format(ev1.name))
+            ev1.debug("{} fired [DEBUG]".format(ev1.name))
 
         time.sleep(wait_time)
 
     if fire_second_ev:
-        ev2.info('{} fired [INFO]'.format(ev2.name))
+        ev2.info("{} fired [INFO]".format(ev2.name))
 
     if ready_file is not None:
         try:
@@ -83,5 +83,5 @@ def _main():
             raise
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     _main()
index 9d3e030b7f2c0079169a51c34983e14e612e1e84..bee03a42ce2148e0fdb72476eea0d37c5478c367 100644 (file)
@@ -5,6 +5,8 @@
  *
  */
 
+#include "utils.h"
+
 #include <fcntl.h>
 #include <signal.h>
 #include <stdbool.h>
@@ -15,8 +17,6 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#include "utils.h"
-
 /**
  * The process waits for the creation of a file passed as argument from an
  * external processes to execute a syscall and exiting. This is useful for tests
 volatile int val = 0;
 
 long nooptimization my_gettid(void);
-long nooptimization
-my_gettid(void)
+long nooptimization my_gettid(void)
 {
-    long ret;
+       long ret;
 #ifdef __x86_64
-    asm volatile
-    (
-        "syscall"
-        : "=a" (ret)
-        : "0"(__NR_gettid)
-        : "cc", "rcx", "r11", "memory"
-    );
+       asm volatile("syscall" : "=a"(ret) : "0"(__NR_gettid) : "cc", "rcx", "r11", "memory");
 #elif defined(__i386)
-    asm volatile
-    (
-        "int $0x80"
-        : "=a" (ret)
-        : "0"(__NR_gettid)
-        : "cc", "edi", "esi", "memory"
-    );
+       asm volatile("int $0x80" : "=a"(ret) : "0"(__NR_gettid) : "cc", "edi", "esi", "memory");
 #else
 #error "Userspace callstack test not supported for this architecture."
 #endif
-    return ret;
+       return ret;
 }
 
 int nooptimization fct_c(void);
-int nooptimization
-fct_c(void)
+int nooptimization fct_c(void)
 {
        return my_gettid();
 }
 
 int nooptimization fct_b(void);
-int nooptimization
-fct_b(void)
+int nooptimization fct_b(void)
 {
        val += fct_c();
        return val;
 }
 
 int nooptimization fct_a(void);
-int nooptimization
-fct_a(void)
+int nooptimization fct_a(void)
 {
        val += fct_b();
        return val;
index 9b19d2d2d6d5424866a388ede519700ea0de2793..726fbc8ed0805e280115ab9e5b31dd6ae4513db4 100644 (file)
@@ -5,14 +5,15 @@
  *
  */
 
+#include "utils.h"
+
+#include <common/align.hpp>
+#include <common/error.hpp>
+
 #include <fcntl.h>
 #include <stdio.h>
 #include <sys/syscall.h>
 #include <unistd.h>
-#include <common/error.hpp>
-#include <common/align.hpp>
-
-#include "utils.h"
 
 #define MAX_LEN 16
 
  * This isn't a proper fix; it is simply the best we can do for now.
  * See bug #1261 for more context.
  */
-static
-void prefault_string(const char *p)
+static void prefault_string(const char *p)
 {
-       const char * const end = p + strlen(p) + 1;
+       const char *const end = p + strlen(p) + 1;
 
        while (p < end) {
                /*
@@ -41,8 +41,7 @@ void prefault_string(const char *p)
        }
 }
 
-static
-int open_read_close(const char *path)
+static int open_read_close(const char *path)
 {
        int fd, ret;
        char buf[MAX_LEN];
@@ -63,7 +62,9 @@ int open_read_close(const char *path)
        ret = syscall(SYS_read, fd, buf, MAX_LEN);
        if (ret < 0) {
                PERROR_NO_LOGGER("Failed to read file: path = '%s', fd = %d, length = %d",
-                               path, fd, MAX_LEN);
+                                path,
+                                fd,
+                                MAX_LEN);
                ret = -1;
                goto error;
        }
diff --git a/tests/utils/testapp/gen-ust-events-constructor/01-c-tp-before-define.c b/tests/utils/testapp/gen-ust-events-constructor/01-c-tp-before-define.c
new file mode 100644 (file)
index 0000000..6b1d9ed
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "tp.h"
+
+void test_constructor1(void) __attribute__((constructor));
+void test_constructor1(void)
+{
+       tracepoint(tp, constructor_c_across_units_before_define);
+}
+
+void test_destructor1(void) __attribute__((destructor));
+void test_destructor1(void)
+{
+       tracepoint(tp, destructor_c_across_units_before_define);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/01-tp-before-define.cpp b/tests/utils/testapp/gen-ust-events-constructor/01-tp-before-define.cpp
new file mode 100644 (file)
index 0000000..5219924
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+#include "tp.h"
+
+void test_constructor1(void) __attribute__((constructor));
+void test_constructor1(void)
+{
+       tracepoint(tp, constructor_c_across_units_before_define);
+}
+
+void test_destructor1(void) __attribute__((destructor));
+void test_destructor1(void)
+{
+       tracepoint(tp, destructor_c_across_units_before_define);
+}
+
+Obj g_obj_across_units_before_define("global - across units before define");
diff --git a/tests/utils/testapp/gen-ust-events-constructor/02-c-define-tp.c b/tests/utils/testapp/gen-ust-events-constructor/02-c-define-tp.c
new file mode 100644 (file)
index 0000000..117ffba
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+static void fct_constructor2(void);
+static void fct_destructor2(void);
+
+void test_constructor2_same_unit_before(void) __attribute__((constructor));
+void test_constructor2_same_unit_before(void)
+{
+       fct_constructor2();
+}
+
+void test_destructor2_same_unit_before(void) __attribute__((destructor));
+void test_destructor2_same_unit_before(void)
+{
+       fct_destructor2();
+}
+
+#define TRACEPOINT_DEFINE
+#include "tp.h"
+
+static void fct_constructor2(void)
+{
+       tracepoint(tp, constructor_c_same_unit_before_define);
+}
+
+static void fct_destructor2(void)
+{
+       tracepoint(tp, destructor_c_same_unit_before_define);
+}
+
+void test_constructor2_same_unit_after(void) __attribute__((constructor));
+void test_constructor2_same_unit_after(void)
+{
+       tracepoint(tp, constructor_c_same_unit_after_define);
+}
+
+void test_destructor2_same_unit_after(void) __attribute__((destructor));
+void test_destructor2_same_unit_after(void)
+{
+       tracepoint(tp, destructor_c_same_unit_after_define);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/02-define-tp.cpp b/tests/utils/testapp/gen-ust-events-constructor/02-define-tp.cpp
new file mode 100644 (file)
index 0000000..9d550fc
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+
+static void fct_constructor2(void);
+static void fct_destructor2(void);
+
+void test_constructor2_same_unit_before(void) __attribute__((constructor));
+void test_constructor2_same_unit_before(void)
+{
+       fct_constructor2();
+}
+
+void test_destructor2_same_unit_before(void) __attribute__((destructor));
+void test_destructor2_same_unit_before(void)
+{
+       fct_destructor2();
+}
+
+Obj g_obj_same_unit_before_define("global - same unit before define");
+
+#define TRACEPOINT_DEFINE
+#include "tp.h"
+
+Obj g_obj_same_unit_after_define("global - same unit after define");
+
+static void fct_constructor2(void)
+{
+       tracepoint(tp, constructor_c_same_unit_before_define);
+}
+
+static void fct_destructor2(void)
+{
+       tracepoint(tp, destructor_c_same_unit_before_define);
+}
+
+void test_constructor2_same_unit_after(void) __attribute__((constructor));
+void test_constructor2_same_unit_after(void)
+{
+       tracepoint(tp, constructor_c_same_unit_after_define);
+}
+
+void test_destructor2_same_unit_after(void) __attribute__((destructor));
+void test_destructor2_same_unit_after(void)
+{
+       tracepoint(tp, destructor_c_same_unit_after_define);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/03-c-tp-after-define.c b/tests/utils/testapp/gen-ust-events-constructor/03-c-tp-after-define.c
new file mode 100644 (file)
index 0000000..2be0b77
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "tp.h"
+
+void test_constructor3(void) __attribute__((constructor));
+void test_constructor3(void)
+{
+       tracepoint(tp, constructor_c_across_units_after_define);
+}
+
+void test_destructor3(void) __attribute__((destructor));
+void test_destructor3(void)
+{
+       tracepoint(tp, destructor_c_across_units_after_define);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/03-tp-after-define.cpp b/tests/utils/testapp/gen-ust-events-constructor/03-tp-after-define.cpp
new file mode 100644 (file)
index 0000000..fba3c26
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+#include "tp.h"
+
+void test_constructor3(void) __attribute__((constructor));
+void test_constructor3(void)
+{
+       tracepoint(tp, constructor_c_across_units_after_define);
+}
+
+void test_destructor3(void) __attribute__((destructor));
+void test_destructor3(void)
+{
+       tracepoint(tp, destructor_c_across_units_after_define);
+}
+
+Obj g_obj_across_units_after_define("global - across units after define");
diff --git a/tests/utils/testapp/gen-ust-events-constructor/04-c-tp-provider.c b/tests/utils/testapp/gen-ust-events-constructor/04-c-tp-provider.c
new file mode 100644 (file)
index 0000000..51b47e1
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+static void fct_constructor4(void);
+static void fct_destructor4(void);
+
+void test_constructor4_same_unit_before(void) __attribute__((constructor));
+void test_constructor4_same_unit_before(void)
+{
+       fct_constructor4();
+}
+
+void test_destructor4_same_unit_before(void) __attribute__((destructor));
+void test_destructor4_same_unit_before(void)
+{
+       fct_destructor4();
+}
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp.h"
+
+static void fct_constructor4(void)
+{
+       tracepoint(tp, constructor_c_same_unit_before_provider);
+}
+
+static void fct_destructor4(void)
+{
+       tracepoint(tp, destructor_c_same_unit_before_provider);
+}
+
+void test_constructor4_same_unit_after(void) __attribute__((constructor));
+void test_constructor4_same_unit_after(void)
+{
+       tracepoint(tp, constructor_c_same_unit_after_provider);
+}
+
+void test_destructor4_same_unit_after(void) __attribute__((destructor));
+void test_destructor4_same_unit_after(void)
+{
+       tracepoint(tp, destructor_c_same_unit_after_provider);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/04-tp-provider.cpp b/tests/utils/testapp/gen-ust-events-constructor/04-tp-provider.cpp
new file mode 100644 (file)
index 0000000..bebf0d2
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+
+static void fct_constructor4(void);
+static void fct_destructor4(void);
+
+void test_constructor4_same_unit_before(void) __attribute__((constructor));
+void test_constructor4_same_unit_before(void)
+{
+       fct_constructor4();
+}
+
+void test_destructor4_same_unit_before(void) __attribute__((destructor));
+void test_destructor4_same_unit_before(void)
+{
+       fct_destructor4();
+}
+
+Obj g_obj_same_unit_before_provider("global - same unit before provider");
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp.h"
+
+Obj g_obj_same_unit_after_provider("global - same unit after provider");
+
+static void fct_constructor4(void)
+{
+       tracepoint(tp, constructor_c_same_unit_before_provider);
+}
+
+static void fct_destructor4(void)
+{
+       tracepoint(tp, destructor_c_same_unit_before_provider);
+}
+
+void test_constructor4_same_unit_after(void) __attribute__((constructor));
+void test_constructor4_same_unit_after(void)
+{
+       tracepoint(tp, constructor_c_same_unit_after_provider);
+}
+
+void test_destructor4_same_unit_after(void) __attribute__((destructor));
+void test_destructor4_same_unit_after(void)
+{
+       tracepoint(tp, destructor_c_same_unit_after_provider);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/05-c-tp-after-provider.c b/tests/utils/testapp/gen-ust-events-constructor/05-c-tp-after-provider.c
new file mode 100644 (file)
index 0000000..4bc566d
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "tp.h"
+
+void test_constructor5(void) __attribute__((constructor));
+void test_constructor5(void)
+{
+       tracepoint(tp, constructor_c_across_units_after_provider);
+}
+
+void test_destructor5(void) __attribute__((destructor));
+void test_destructor5(void)
+{
+       tracepoint(tp, destructor_c_across_units_after_provider);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/05-tp-after-provider.cpp b/tests/utils/testapp/gen-ust-events-constructor/05-tp-after-provider.cpp
new file mode 100644 (file)
index 0000000..17d3a6e
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+#include "tp.h"
+
+void test_constructor5(void) __attribute__((constructor));
+void test_constructor5(void)
+{
+       tracepoint(tp, constructor_c_across_units_after_provider);
+}
+
+void test_destructor5(void) __attribute__((destructor));
+void test_destructor5(void)
+{
+       tracepoint(tp, destructor_c_across_units_after_provider);
+}
+
+Obj g_obj_across_units_after_provider("global - across units after provider");
diff --git a/tests/utils/testapp/gen-ust-events-constructor/Makefile.am b/tests/utils/testapp/gen-ust-events-constructor/Makefile.am
new file mode 100644 (file)
index 0000000..6c09cf5
--- /dev/null
@@ -0,0 +1,143 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+AM_CPPFLAGS += -I$(top_srcdir)/tests/utils -I$(srcdir) \
+       -I$(top_srcdir)/tests/utils/testapp
+
+if HAVE_LIBLTTNG_UST_CTL
+# Disable some warnings flags to accomodate the tracepoint headers
+WARN_FLAGS = \
+       -Wno-redundant-decls \
+       -Wno-missing-field-initializers
+
+AM_CFLAGS += $(WARN_FLAGS)
+AM_CXXFLAGS += $(WARN_FLAGS)
+
+noinst_LTLIBRARIES = libtp-a-provider.la libtp-a-define.la \
+       libtp-a_c-provider.la libtp-a_c-define.la
+noinst_PROGRAMS = gen-ust-events-constructor-a \
+       gen-ust-events-c-constructor-a \
+       uses_heap
+
+if NO_SHARED
+# Build the shared library as a static archive if shared libraries
+# are disabled.
+FORCE_SHARED_LIB_OPTIONS =
+else
+# Force the shared flag on the noinst libraries since they are
+# only built static by default
+FORCE_SHARED_LIB_OPTIONS = -module -shared -avoid-version \
+                          -rpath $(abs_builddir)
+
+noinst_LTLIBRARIES += libtp-so-provider.la libtp-so-define.la \
+       libtp-so_c-provider.la libtp-so_c-define.la
+noinst_PROGRAMS += gen-ust-events-constructor-so \
+       gen-ust-events-c-constructor-so
+endif
+
+
+# dynamic libraries
+libtp_so_provider_la_SOURCES = \
+       tp-so-provider.cpp \
+       tp-so.h
+libtp_so_provider_la_LDFLAGS = \
+       $(FORCE_SHARED_LIB_OPTIONS)
+
+libtp_so_define_la_SOURCES = \
+       tp-so-define.cpp \
+       tp-so.h
+libtp_so_define_la_LDFLAGS = \
+       $(FORCE_SHARED_LIB_OPTIONS)
+
+libtp_so_c_provider_la_SOURCES = \
+       tp-so_c-provider.c \
+       tp-so_c.h
+libtp_so_c_provider_la_LDFLAGS = $(FORCE_SHARED_LIB_OPTIONS)
+
+libtp_so_c_define_la_SOURCES = \
+       tp-so_c-define.c \
+       tp-so_c.h
+libtp_so_c_define_la_LDFLAGS = $(FORCE_SHARED_LIB_OPTIONS)
+
+# static archives
+libtp_a_provider_la_SOURCES = \
+       tp-a-provider.cpp \
+       tp-a.h
+
+libtp_a_define_la_SOURCES = \
+       tp-a-define.cpp \
+       tp-a.h
+
+libtp_a_c_provider_la_SOURCES = \
+       tp-a_c-provider.c \
+       tp-a_c.h
+
+libtp_a_c_define_la_SOURCES = \
+       tp-a_c-define.c \
+       tp-a_c.h
+
+
+gen_ust_events_constructor_so_SOURCES = main.cpp \
+       01-tp-before-define.cpp \
+       02-define-tp.cpp \
+       03-tp-after-define.cpp \
+       04-tp-provider.cpp \
+       05-tp-after-provider.cpp \
+       obj.cpp \
+       obj.h \
+       tp.h
+gen_ust_events_constructor_so_LDADD = $(UST_LIBS) \
+       $(builddir)/libtp-so-define.la \
+       $(builddir)/libtp-so-provider.la \
+       $(builddir)/libtp-so_c-define.la \
+       $(builddir)/libtp-so_c-provider.la \
+       $(top_builddir)/tests/utils/libtestutils.la \
+       $(DL_LIBS)
+
+gen_ust_events_c_constructor_so_SOURCES = main_c-so.c \
+       01-c-tp-before-define.c \
+       02-c-define-tp.c \
+       03-c-tp-after-define.c \
+       04-c-tp-provider.c \
+       05-c-tp-after-provider.c \
+       tp.h
+gen_ust_events_c_constructor_so_LDADD = $(UST_LIBS) \
+       $(builddir)/libtp-so-define.la \
+       $(builddir)/libtp-so-provider.la \
+       $(builddir)/libtp-so_c-define.la \
+       $(builddir)/libtp-so_c-provider.la \
+       $(top_builddir)/tests/utils/libtestutils.la \
+       $(DL_LIBS)
+
+gen_ust_events_constructor_a_SOURCES = main-a.cpp \
+       01-tp-before-define.cpp \
+       02-define-tp.cpp \
+       03-tp-after-define.cpp \
+       04-tp-provider.cpp \
+       05-tp-after-provider.cpp \
+       obj-a.cpp \
+       obj-a.h \
+       tp.h
+gen_ust_events_constructor_a_LDADD = $(UST_LIBS) \
+       $(builddir)/libtp-a-define.la \
+       $(builddir)/libtp-a-provider.la \
+       $(builddir)/libtp-a_c-define.la \
+       $(builddir)/libtp-a_c-provider.la \
+       $(top_builddir)/tests/utils/libtestutils.la \
+       $(DL_LIBS)
+
+gen_ust_events_c_constructor_a_SOURCES = main_c-a.c \
+       01-c-tp-before-define.c \
+       02-c-define-tp.c \
+       03-c-tp-after-define.c \
+       04-c-tp-provider.c \
+       05-c-tp-after-provider.c \
+       tp.h
+gen_ust_events_c_constructor_a_LDADD = $(UST_LIBS) \
+       $(builddir)/libtp-a_c-define.la \
+       $(builddir)/libtp-a_c-provider.la \
+       $(top_builddir)/tests/utils/libtestutils.la \
+       $(DL_LIBS)
+
+uses_heap_SOURCES = uses_heap.cpp
+
+endif
diff --git a/tests/utils/testapp/gen-ust-events-constructor/main-a.cpp b/tests/utils/testapp/gen-ust-events-constructor/main-a.cpp
new file mode 100644 (file)
index 0000000..118ce66
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LPGL-2.1-only
+ */
+
+#include "obj-a.h"
+#include "tp-a.h"
+extern "C" {
+#include "tp-a_c.h"
+}
+#include "tp.h"
+
+/* Use tracepoints defined and provided by static archive. */
+void test_constructor_a(void) __attribute__((constructor));
+void test_constructor_a(void)
+{
+       tracepoint(tp_a_c, constructor_c_provider_static_archive);
+}
+
+void test_destructor_a(void) __attribute__((destructor));
+void test_destructor_a(void)
+{
+       tracepoint(tp_a_c, destructor_c_provider_static_archive);
+}
+
+Obja g_obja_static_archive("global - static archive define and provider");
+
+int main(void)
+{
+       Obj l_obj("main() local");
+       Obja l_obja("main() local - static archive define and provider");
+
+       tracepoint(tp, main);
+       return 0;
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/main.cpp b/tests/utils/testapp/gen-ust-events-constructor/main.cpp
new file mode 100644 (file)
index 0000000..35240ac
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "obj.h"
+#include "tp-so.h"
+#include "tp-so_c.h"
+#include "tp.h"
+
+/* Use tracepoints defined and provided by shared libraries. */
+void test_constructor_so(void) __attribute__((constructor));
+void test_constructor_so(void)
+{
+       tracepoint(tp_so_c, constructor_c_provider_shared_library);
+}
+
+void test_destructor_so(void) __attribute__((destructor));
+void test_destructor_so(void)
+{
+       tracepoint(tp_so_c, destructor_c_provider_shared_library);
+}
+
+Objso g_objso_shared_library("global - shared library define and provider");
+
+int main(void)
+{
+       Obj l_obj("main() local");
+       Objso l_objso("main() local - shared library define and provider");
+
+       tracepoint(tp, main);
+       return 0;
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/main_c-a.c b/tests/utils/testapp/gen-ust-events-constructor/main_c-a.c
new file mode 100644 (file)
index 0000000..0a7d1f0
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include "tp-a_c.h"
+#include "tp.h"
+
+/* Use tracepoints defined and provided by static archive. */
+void test_constructor_a(void) __attribute__((constructor));
+void test_constructor_a(void)
+{
+       tracepoint(tp_a_c, constructor_c_provider_static_archive);
+}
+
+void test_destructor_a(void) __attribute__((destructor));
+void test_destructor_a(void)
+{
+       tracepoint(tp_a_c, destructor_c_provider_static_archive);
+}
+
+int main(void)
+{
+       tracepoint(tp, main);
+       return 0;
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/main_c-so.c b/tests/utils/testapp/gen-ust-events-constructor/main_c-so.c
new file mode 100644 (file)
index 0000000..70ee49b
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-LIcense-Identifier: LGPL-2.1-only
+ */
+
+#include "tp-so_c.h"
+#include "tp.h"
+
+/* Use tracepoints defined and provided by shared libraries. */
+void test_constructor_so(void) __attribute__((constructor));
+void test_constructor_so(void)
+{
+       tracepoint(tp_so_c, constructor_c_provider_shared_library);
+}
+
+void test_destructor_so(void) __attribute__((destructor));
+void test_destructor_so(void)
+{
+       tracepoint(tp_so_c, destructor_c_provider_shared_library);
+}
+
+int main(void)
+{
+       tracepoint(tp, main);
+       return 0;
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/obj-a.cpp b/tests/utils/testapp/gen-ust-events-constructor/obj-a.cpp
new file mode 100644 (file)
index 0000000..58c5c94
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifer: LGPL-2.1-only
+ */
+
+#include "obj-a.h"
+#include "tp-a.h"
+#include "tp.h"
+
+Obj::Obj(const char *_msg) : msg(_msg)
+{
+       tracepoint(tp, constructor_cplusplus, msg);
+}
+
+Obj::~Obj()
+{
+       tracepoint(tp, destructor_cplusplus, msg);
+}
+
+Obja::Obja(const char *_msg) : msg(_msg)
+{
+       tracepoint(tp_a, constructor_cplusplus_provider_static_archive, msg);
+}
+
+Obja::~Obja()
+{
+       tracepoint(tp_a, destructor_cplusplus_provider_static_archive, msg);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/obj-a.h b/tests/utils/testapp/gen-ust-events-constructor/obj-a.h
new file mode 100644 (file)
index 0000000..cd341d8
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ *
+ */
+
+#ifndef _OBJ_A_H
+#define _OBJ_A_H
+
+struct Obj {
+       const char *msg;
+       Obj(const char *msg);
+       ~Obj();
+};
+
+struct Obja {
+       const char *msg;
+       Obja(const char *msg);
+       ~Obja();
+};
+
+#endif /* _OBJ_A_H */
diff --git a/tests/utils/testapp/gen-ust-events-constructor/obj.cpp b/tests/utils/testapp/gen-ust-events-constructor/obj.cpp
new file mode 100644 (file)
index 0000000..430cfe3
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#include "obj.h"
+#include "tp-so.h"
+#include "tp.h"
+
+Obj::Obj(const char *_msg) : msg(_msg)
+{
+       tracepoint(tp, constructor_cplusplus, msg);
+}
+
+Obj::~Obj()
+{
+       tracepoint(tp, destructor_cplusplus, msg);
+}
+
+Objso::Objso(const char *_msg) : msg(_msg)
+{
+       tracepoint(tp_so, constructor_cplusplus_provider_shared_library, msg);
+}
+
+Objso::~Objso()
+{
+       tracepoint(tp_so, destructor_cplusplus_provider_shared_library, msg);
+}
diff --git a/tests/utils/testapp/gen-ust-events-constructor/obj.h b/tests/utils/testapp/gen-ust-events-constructor/obj.h
new file mode 100644 (file)
index 0000000..0efe5ab
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#ifndef _OBJ_H
+#define _OBJ_H
+
+struct Obj {
+       const char *msg;
+       Obj(const char *msg);
+       ~Obj();
+};
+
+struct Objso {
+       const char *msg;
+       Objso(const char *msg);
+       ~Objso();
+};
+
+#endif /* _OBJ_H */
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a-define.cpp b/tests/utils/testapp/gen-ust-events-constructor/tp-a-define.cpp
new file mode 100644 (file)
index 0000000..1d01015
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_DEFINE
+#include "tp-a.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a-provider.cpp b/tests/utils/testapp/gen-ust-events-constructor/tp-a-provider.cpp
new file mode 100644 (file)
index 0000000..75ae70f
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp-a.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a.h b/tests/utils/testapp/gen-ust-events-constructor/tp-a.h
new file mode 100644 (file)
index 0000000..2e161b2
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#undef TRACEPOINT_PROVIDER
+#define TRACEPOINT_PROVIDER tp_a
+
+#if !defined(_TRACEPOINT_TP_A_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
+#define _TRACEPOINT_TP_A_H
+
+#include <lttng/tracepoint.h>
+
+#include <stdint.h>
+
+TRACEPOINT_EVENT(tp_a,
+                constructor_cplusplus_provider_static_archive,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+TRACEPOINT_EVENT(tp_a,
+                destructor_cplusplus_provider_static_archive,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+#endif /* _TRACEPOINT_TP_A_H */
+
+#undef TRACEPOINT_INCLUDE
+#define TRACEPOINT_INCLUDE "./tp-a.h"
+
+/* This part must be outside ifdef protection */
+#include <lttng/tracepoint-event.h>
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a_c-define.c b/tests/utils/testapp/gen-ust-events-constructor/tp-a_c-define.c
new file mode 100644 (file)
index 0000000..c3496eb
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_DEFINE
+#include "tp-a_c.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a_c-provider.c b/tests/utils/testapp/gen-ust-events-constructor/tp-a_c-provider.c
new file mode 100644 (file)
index 0000000..8d4c184
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp-a_c.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-a_c.h b/tests/utils/testapp/gen-ust-events-constructor/tp-a_c.h
new file mode 100644 (file)
index 0000000..f2ab443
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#undef TRACEPOINT_PROVIDER
+#define TRACEPOINT_PROVIDER tp_a_c
+
+#if !defined(_TRACEPOINT_TP_A_C_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
+#define _TRACEPOINT_TP_A_C_H
+
+#include <lttng/tracepoint.h>
+
+TRACEPOINT_EVENT(tp_a_c, constructor_c_provider_static_archive, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp_a_c, destructor_c_provider_static_archive, TP_ARGS(), TP_FIELDS())
+
+#endif /* _TRACEPOINT_TP_A_H */
+
+#undef TRACEPOINT_INCLUDE
+#define TRACEPOINT_INCLUDE "./tp-a_c.h"
+
+/* This part must be outside ifdef protection */
+#include <lttng/tracepoint-event.h>
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so-define.cpp b/tests/utils/testapp/gen-ust-events-constructor/tp-so-define.cpp
new file mode 100644 (file)
index 0000000..5ff4395
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_DEFINE
+#include "tp-so.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so-provider.cpp b/tests/utils/testapp/gen-ust-events-constructor/tp-so-provider.cpp
new file mode 100644 (file)
index 0000000..d4844ea
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2023 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp-so.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so.h b/tests/utils/testapp/gen-ust-events-constructor/tp-so.h
new file mode 100644 (file)
index 0000000..41faec7
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#undef TRACEPOINT_PROVIDER
+#define TRACEPOINT_PROVIDER tp_so
+
+#if !defined(_TRACEPOINT_TP_SO_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
+#define _TRACEPOINT_TP_SO_H
+
+#include <lttng/tracepoint.h>
+
+#include <stdint.h>
+
+TRACEPOINT_EVENT(tp_so,
+                constructor_cplusplus_provider_shared_library,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+TRACEPOINT_EVENT(tp_so,
+                destructor_cplusplus_provider_shared_library,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+#endif /* _TRACEPOINT_TP_SO_H */
+
+#undef TRACEPOINT_INCLUDE
+#define TRACEPOINT_INCLUDE "./tp-so.h"
+
+/* This part must be outside ifdef protection */
+#include <lttng/tracepoint-event.h>
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so_c-define.c b/tests/utils/testapp/gen-ust-events-constructor/tp-so_c-define.c
new file mode 100644 (file)
index 0000000..e16bce0
--- /dev/null
@@ -0,0 +1,7 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+#define TRACEPOINT_DEFINE
+#include "tp-so_c.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so_c-provider.c b/tests/utils/testapp/gen-ust-events-constructor/tp-so_c-provider.c
new file mode 100644 (file)
index 0000000..aae3196
--- /dev/null
@@ -0,0 +1,8 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#define TRACEPOINT_CREATE_PROBES
+#include "tp-so_c.h"
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp-so_c.h b/tests/utils/testapp/gen-ust-events-constructor/tp-so_c.h
new file mode 100644 (file)
index 0000000..58d77cd
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#ifdef _cplusplus
+extern "C" {
+#endif
+
+#undef TRACEPOINT_PROVIDER
+#define TRACEPOINT_PROVIDER tp_so_c
+
+#if !defined(_TRACEPOINT_TP_SO_C_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
+#define _TRACEPOINT_TP_SO_C_H
+
+#include <lttng/tracepoint.h>
+
+TRACEPOINT_EVENT(tp_so_c, constructor_c_provider_shared_library, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp_so_c, destructor_c_provider_shared_library, TP_ARGS(), TP_FIELDS())
+
+#endif /* _TRACEPOINT_TP_SO_C_H */
+
+#undef TRACEPOINT_INCLUDE
+#define TRACEPOINT_INCLUDE "./tp-so_c.h"
+
+/* This part must be outside ifdef protection */
+#include <lttng/tracepoint-event.h>
+
+#ifdef _cplusplus
+}
+#endif
diff --git a/tests/utils/testapp/gen-ust-events-constructor/tp.h b/tests/utils/testapp/gen-ust-events-constructor/tp.h
new file mode 100644 (file)
index 0000000..934ca7d
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ *
+ */
+
+#undef TRACEPOINT_PROVIDER
+#define TRACEPOINT_PROVIDER tp
+
+#if !defined(_TRACEPOINT_TP_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
+#define _TRACEPOINT_TP_H
+
+#include <lttng/tracepoint.h>
+
+#include <stdint.h>
+
+TRACEPOINT_EVENT(tp, main, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_across_units_before_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_across_units_before_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_across_units_after_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_across_units_after_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_across_units_after_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_across_units_after_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_same_unit_before_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_same_unit_before_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_same_unit_after_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_same_unit_after_define, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_same_unit_before_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_same_unit_before_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, constructor_c_same_unit_after_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp, destructor_c_same_unit_after_provider, TP_ARGS(), TP_FIELDS())
+
+TRACEPOINT_EVENT(tp,
+                constructor_cplusplus,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+TRACEPOINT_EVENT(tp,
+                destructor_cplusplus,
+                TP_ARGS(const char *, msg),
+                TP_FIELDS(ctf_string(msg, msg)))
+
+#endif /* _TRACEPOINT_TP_H */
+
+#undef TRACEPOINT_INCLUDE
+#define TRACEPOINT_INCLUDE "./tp.h"
+
+/* This part must be outside ifdef protection */
+#include <lttng/tracepoint-event.h>
diff --git a/tests/utils/testapp/gen-ust-events-constructor/uses_heap.cpp b/tests/utils/testapp/gen-ust-events-constructor/uses_heap.cpp
new file mode 100644 (file)
index 0000000..35933de
--- /dev/null
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2024 Kienan Stewart <kstewart@efficios.com>
+ *
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+#include <lttng/ust-compiler.h>
+
+int main()
+{
+#ifdef LTTNG_UST_ALLOCATE_COMPOUND_LITERAL_ON_HEAP
+       return 0;
+#else
+       return 1;
+#endif
+}
index 22242fb92209455ae4a49b48d1d2c41751e6c370..1e0a80c4e09f7793b37b6a1f946f93a9bab5d989 100644 (file)
@@ -17,6 +17,7 @@ gen_ust_events_ns_SOURCES = \
        gen-ust-events-ns.cpp \
        tp.c \
        tp.h
+gen_ust_events_ns_CPPFLAGS = $(POPT_CFLAGS) $(AM_CPPFLAGS)
 gen_ust_events_ns_LDADD = $(UST_LIBS) -llttng-ust-fork \
                $(top_builddir)/tests/utils/libtestutils.la \
                $(DL_LIBS) $(POPT_LIBS)
index ba506b1131b57eeb1e2f8313e16dc90546ba5d60..c6b40f53dd2daaa01616718acccd5f0b3941c545 100644 (file)
@@ -9,6 +9,13 @@
 #define _GNU_SOURCE
 #endif
 
+#include "signal-helper.hpp"
+#include "utils.h"
+
+#include <common/compat/tid.hpp>
+#include <common/macros.hpp>
+
+#include <inttypes.h>
 #include <popt.h>
 #include <sched.h>
 #include <stdarg.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <inttypes.h>
-
-#include <common/compat/tid.hpp>
-#include <common/macros.hpp>
-
-#include "signal-helper.hpp"
-#include "utils.h"
 
 #define TRACEPOINT_DEFINE
 #include "tp.h"
  * but that use a libc that doesn't define its associated clone flag.
  */
 #ifndef CLONE_NEWNS
-#define CLONE_NEWNS     0x00020000
+#define CLONE_NEWNS 0x00020000
 #endif
 #ifndef CLONE_NEWCGROUP
 #define CLONE_NEWCGROUP 0x02000000
 #endif
 #ifndef CLONE_NEWUTS
-#define CLONE_NEWUTS    0x04000000
+#define CLONE_NEWUTS 0x04000000
 #endif
 #ifndef CLONE_NEWIPC
-#define CLONE_NEWIPC    0x08000000
+#define CLONE_NEWIPC 0x08000000
 #endif
 #ifndef CLONE_NEWUSER
-#define CLONE_NEWUSER   0x10000000
+#define CLONE_NEWUSER 0x10000000
 #endif
 #ifndef CLONE_NEWPID
-#define CLONE_NEWPID    0x20000000
+#define CLONE_NEWPID 0x20000000
 #endif
 #ifndef CLONE_NEWNET
-#define CLONE_NEWNET    0x40000000
+#define CLONE_NEWNET 0x40000000
 #endif
 #ifndef CLONE_NEWTIME
-#define CLONE_NEWTIME   0x00000080
+#define CLONE_NEWTIME 0x00000080
 #endif
 
 static int nr_iter = 100;
 static int debug = 0;
-static char *ns_opt = NULL;
-static char *after_unshare_file_path = NULL;
-static char *before_second_event_file_path = NULL;
+static char *ns_opt = nullptr;
+static char *after_unshare_file_path = nullptr;
+static char *before_second_event_file_path = nullptr;
 
-static
-struct poptOption opts[] = {
+static struct poptOption opts[] = {
        /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
-       { "debug", 'd', POPT_ARG_NONE, &debug, 0, "Enable debug output", NULL },
-       { "ns", 'n', POPT_ARG_STRING, &ns_opt, 0, "Namespace short identifier", NULL },
-       { "iter", 'i', POPT_ARG_INT, &nr_iter, 0, "Number of tracepoint iterations", NULL },
-       { "after", 'a', POPT_ARG_STRING, &after_unshare_file_path, 0, "after_unshare_file_path,", NULL },
-       { "before", 'b', POPT_ARG_STRING, &before_second_event_file_path, 0, "before_second_event_file_path,", NULL },
-       POPT_AUTOHELP
-       { NULL, 0, 0, NULL, 0 }
+       { "debug", 'd', POPT_ARG_NONE, &debug, 0, "Enable debug output", nullptr },
+       { "ns", 'n', POPT_ARG_STRING, &ns_opt, 0, "Namespace short identifier", nullptr },
+       { "iter", 'i', POPT_ARG_INT, &nr_iter, 0, "Number of tracepoint iterations", nullptr },
+       { "after",
+         'a',
+         POPT_ARG_STRING,
+         &after_unshare_file_path,
+         0,
+         "after_unshare_file_path,",
+         nullptr },
+       { "before",
+         'b',
+         POPT_ARG_STRING,
+         &before_second_event_file_path,
+         0,
+         "before_second_event_file_path,",
+         nullptr },
+       POPT_AUTOHELP{ nullptr, 0, 0, nullptr, 0 }
 };
 
-static ATTR_FORMAT_PRINTF(1, 2)
-void debug_printf(const char *format, ...)
+static ATTR_FORMAT_PRINTF(1, 2) void debug_printf(const char *format, ...)
 {
        va_list args;
        va_start(args, format);
@@ -101,8 +110,7 @@ static int get_ns_inum(const char *ns, ino_t *ns_inum)
        /*
         * /proc/thread-self was introduced in kernel v3.17
         */
-       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX,
-                       "/proc/thread-self/ns/%s", ns) >= 0) {
+       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX, "/proc/thread-self/ns/%s", ns) >= 0) {
                if (stat(proc_ns_path, &sb) == 0) {
                        *ns_inum = sb.st_ino;
                        ret = 0;
@@ -110,8 +118,11 @@ static int get_ns_inum(const char *ns, ino_t *ns_inum)
                goto end;
        }
 
-       if (snprintf(proc_ns_path, LTTNG_PROC_NS_PATH_MAX,
-                       "/proc/self/task/%d/%s/net", lttng_gettid(), ns) >= 0) {
+       if (snprintf(proc_ns_path,
+                    LTTNG_PROC_NS_PATH_MAX,
+                    "/proc/self/task/%d/%s/net",
+                    lttng_gettid(),
+                    ns) >= 0) {
                if (stat(proc_ns_path, &sb) == 0) {
                        *ns_inum = sb.st_ino;
                        ret = 0;
@@ -129,8 +140,7 @@ static int do_the_needful(int ns_flag, const char *ns_str)
 
        ret = get_ns_inum(ns_str, &ns1);
        if (ret) {
-               debug_printf("Failed to get ns inode number for namespace %s",
-                               ns_str);
+               debug_printf("Failed to get ns inode number for namespace %s", ns_str);
                ret = -1;
                goto end;
        }
@@ -151,8 +161,7 @@ static int do_the_needful(int ns_flag, const char *ns_str)
 
        ret = get_ns_inum(ns_str, &ns2);
        if (ret) {
-               debug_printf("Failed to get ns inode number for namespace %s",
-                               ns_str);
+               debug_printf("Failed to get ns inode number for namespace %s", ns_str);
                ret = -1;
                goto end;
        }
@@ -198,7 +207,7 @@ int main(int argc, const char **argv)
        int ret = EXIT_SUCCESS;
        poptContext pc;
 
-       pc = poptGetContext(NULL, argc, argv, opts, 0);
+       pc = poptGetContext(nullptr, argc, argv, opts, 0);
        poptReadDefaultConfig(pc, 0);
 
        if (argc < 2) {
@@ -219,14 +228,15 @@ int main(int argc, const char **argv)
        if (opt < -1) {
                /* An error occurred during option processing. */
                poptPrintUsage(pc, stderr, 0);
-               fprintf(stderr, "%s: %s\n",
-                               poptBadOption(pc, POPT_BADOPTION_NOALIAS),
-                               poptStrerror(opt));
+               fprintf(stderr,
+                       "%s: %s\n",
+                       poptBadOption(pc, POPT_BADOPTION_NOALIAS),
+                       poptStrerror(opt));
                ret = EXIT_FAILURE;
                goto end;
        }
 
-       if (ns_opt == NULL) {
+       if (ns_opt == nullptr) {
                poptPrintUsage(pc, stderr, 0);
                ret = EXIT_FAILURE;
                goto end;
index b9540e53f6918cc1c222151cb82c12bd6f5dcab5..624bb5c073bf92ddea945d03a852e61ff0cd7e64 100644 (file)
 #if !defined(_TRACEPOINT_TP_H) || defined(TRACEPOINT_HEADER_MULTI_READ)
 #define _TRACEPOINT_TP_H
 
-#include <sys/types.h>
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, tptest,
-       TP_ARGS(ino_t, ns_ino),
-       TP_FIELDS(
-               ctf_integer(ino_t, ns_ino, ns_ino)
-       )
-)
+#include <sys/types.h>
+
+TRACEPOINT_EVENT(tp, tptest, TP_ARGS(ino_t, ns_ino), TP_FIELDS(ctf_integer(ino_t, ns_ino, ns_ino)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index b66f1ce8c6efc099c1aa5eb0aa71ed602e97426f..3b62ed0dfee9a80baa82b6cb50c0c05dcd0232ec 100644 (file)
@@ -6,10 +6,17 @@
  */
 
 #define _LGPL_SOURCE
-#include <getopt.h>
+#include "signal-helper.hpp"
+#include "utils.h"
+
 #include <arpa/inet.h>
+#include <errno.h>
 #include <fcntl.h>
+#include <getopt.h>
+#include <poll.h>
+#include <signal.h>
 #include <stdarg.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <stdbool.h>
-#include <signal.h>
-#include <poll.h>
-#include <errno.h>
-#include "utils.h"
-#include "signal-helper.hpp"
 
 #define TRACEPOINT_DEFINE
 #include "tp.h"
 
-static struct option long_options[] =
-{
+static struct option long_options[] = {
        /* These options set a flag. */
-       {"iter", required_argument, 0, 'i'},
-       {"wait", required_argument, 0, 'w'},
-       {"sync-after-first-event", required_argument, 0, 'a'},
-       {"sync-before-last-event", required_argument, 0, 'b'},
-       {"sync-before-last-event-touch", required_argument, 0, 'c'},
-       {"sync-before-exit", required_argument, 0, 'd'},
-       {"sync-before-exit-touch", required_argument, 0, 'e'},
-       {"emit-end-event", no_argument, 0, 'f'},
-       {0, 0, 0, 0}
+       { "iter", required_argument, nullptr, 'i' },
+       { "wait", required_argument, nullptr, 'w' },
+       { "sync-application-in-main-touch", required_argument, nullptr, 'a' },
+       { "sync-before-first-event", required_argument, nullptr, 'b' },
+       { "sync-after-first-event", required_argument, nullptr, 'c' },
+       { "sync-before-last-event", required_argument, nullptr, 'd' },
+       { "sync-before-last-event-touch", required_argument, nullptr, 'e' },
+       { "sync-before-exit", required_argument, nullptr, 'f' },
+       { "sync-before-exit-touch", required_argument, nullptr, 'g' },
+       { "emit-end-event", no_argument, nullptr, 'h' },
+       { nullptr, 0, nullptr, 0 }
 };
 
 int main(int argc, char **argv)
@@ -54,17 +56,19 @@ int main(int argc, char **argv)
        uint32_t net_values[] = { 1, 2, 3 };
        int nr_iter = 100, ret = 0, first_event_file_created = 0;
        useconds_t nr_usec = 0;
-       char *after_first_event_file_path = NULL;
-       char *before_last_event_file_path = NULL;
+       char *application_in_main_file_path = nullptr;
+       char *before_first_event_file_path = nullptr;
+       char *after_first_event_file_path = nullptr;
+       char *before_last_event_file_path = nullptr;
        /*
         * Touch a file to indicate that all events except one were
         * generated.
         */
-       char *before_last_event_file_path_touch = NULL;
+       char *before_last_event_file_path_touch = nullptr;
        /* Touch file when we are exiting */
-       char *before_exit_file_path_touch = NULL;
+       char *before_exit_file_path_touch = nullptr;
        /* Wait on file before exiting */
-       char *before_exit_file_path = NULL;
+       char *before_exit_file_path = nullptr;
        /* Emit an end event */
        bool emit_end_event = false;
 
@@ -72,25 +76,31 @@ int main(int argc, char **argv)
                net_values[i] = htonl(net_values[i]);
        }
 
-       while ((option = getopt_long(argc, argv, "i:w:a:b:c:d:e:f",
-                               long_options, &option_index)) != -1) {
+       while ((option = getopt_long(
+                       argc, argv, "i:w:a:b:c:d:e:f:g:h", long_options, &option_index)) != -1) {
                switch (option) {
                case 'a':
-                       after_first_event_file_path = strdup(optarg);
+                       application_in_main_file_path = strdup(optarg);
                        break;
                case 'b':
-                       before_last_event_file_path = strdup(optarg);
+                       before_first_event_file_path = strdup(optarg);
                        break;
                case 'c':
-                       before_last_event_file_path_touch = strdup(optarg);
+                       after_first_event_file_path = strdup(optarg);
                        break;
                case 'd':
-                       before_exit_file_path = strdup(optarg);
+                       before_last_event_file_path = strdup(optarg);
                        break;
                case 'e':
-                       before_exit_file_path_touch = strdup(optarg);
+                       before_last_event_file_path_touch = strdup(optarg);
                        break;
                case 'f':
+                       before_exit_file_path = strdup(optarg);
+                       break;
+               case 'g':
+                       before_exit_file_path_touch = strdup(optarg);
+                       break;
+               case 'h':
                        emit_end_event = true;
                        break;
                case 'i':
@@ -124,12 +134,19 @@ int main(int argc, char **argv)
                goto end;
        }
 
-
        if (set_signal_handler()) {
                ret = -1;
                goto end;
        }
 
+       if (application_in_main_file_path) {
+               create_file(application_in_main_file_path);
+       }
+
+       if (before_first_event_file_path) {
+               wait_on_file(before_first_event_file_path);
+       }
+
        for (i = 0; nr_iter < 0 || i < nr_iter; i++) {
                if (nr_iter >= 0 && i == nr_iter - 1) {
                        if (before_last_event_file_path_touch) {
@@ -151,8 +168,17 @@ int main(int argc, char **argv)
                        }
                }
                netint = htonl(i);
-               tracepoint(tp, tptest, i, netint, values, text,
-                       strlen(text), escape, net_values, dbl, flt);
+               tracepoint(tp,
+                          tptest,
+                          i,
+                          netint,
+                          values,
+                          text,
+                          strlen(text),
+                          escape,
+                          net_values,
+                          dbl,
+                          flt);
 
                /*
                 * First loop we create the file if asked to indicate
@@ -169,7 +195,7 @@ int main(int argc, char **argv)
                }
 
                if (nr_usec) {
-                       if (usleep_safe(nr_usec)) {
+                       if (usleep_safe(nr_usec)) {
                                ret = -1;
                                goto end;
                        }
@@ -196,6 +222,8 @@ int main(int argc, char **argv)
                }
        }
 end:
+       free(application_in_main_file_path);
+       free(before_first_event_file_path);
        free(after_first_event_file_path);
        free(before_last_event_file_path);
        free(before_last_event_file_path_touch);
index 6f22887cfbac098e907e48dafa6b43c114b62ce9..08c5f92de0105cea2a76745139dc19fe12818c6c 100644 (file)
 #define _TRACEPOINT_TP_H
 
 #include <lttng/tracepoint.h>
+
 #include <stdint.h>
 
-TRACEPOINT_ENUM(
-       tp, tptest_enum,
-       TP_ENUM_VALUES(
-               ctf_enum_auto("AUTO: EXPECT 0")
-               ctf_enum_value("VALUE: 23", 23)
-               ctf_enum_value("VALUE: 27", 27)
-               ctf_enum_auto("AUTO: EXPECT 28")
-               ctf_enum_range("RANGE: 101 TO 303", 101, 303)
-               ctf_enum_auto("AUTO: EXPECT 304")
-               ctf_enum_value("VALUE: -1", -1)
-       )
-)
+TRACEPOINT_ENUM(tp,
+               tptest_enum,
+               TP_ENUM_VALUES(ctf_enum_auto("AUTO: EXPECT 0") ctf_enum_value("VALUE: 23", 23)
+                                      ctf_enum_value("VALUE: 27",
+                                                     27) ctf_enum_auto("AUTO: EXPECT 28")
+                                              ctf_enum_range("RANGE: 101 TO 303", 101, 303)
+                                                      ctf_enum_auto("AUTO: EXPECT 304")
+                                                              ctf_enum_value("VALUE: -1", -1)))
 
-TRACEPOINT_EVENT(tp, tptest,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               char *, etext, uint32_t * , net_values,
-               double, doublearg, float, floatarg),
+TRACEPOINT_EVENT(
+       tp,
+       tptest,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               char *,
+               etext,
+               uint32_t *,
+               net_values,
+               double,
+               doublearg,
+               float,
+               floatarg),
        TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer(int, signedfield, -1)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_array_network(uint32_t, arrfield3, net_values, 3)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_sequence_network(uint32_t, seqfield3, net_values, size_t, 3)
-               ctf_sequence(long, seqfield4, values, size_t, 3)
-               ctf_string(stringfield, text)
-               ctf_string(stringfield2, etext)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-               ctf_enum(tp, tptest_enum, int, enum0, 0)
-               ctf_enum(tp, tptest_enum, int, enum23, 23)
-               ctf_enum(tp, tptest_enum, int, enum27, 27)
-               ctf_enum(tp, tptest_enum, int, enum28, 28)
-               ctf_enum(tp, tptest_enum, int, enum202, 202)
-               ctf_enum(tp, tptest_enum, int, enum304, 304)
-               ctf_enum(tp, tptest_enum, int, enumnegative, -1)
-       )
-)
+               ctf_integer(int, intfield, anint) ctf_integer_hex(int, intfield2, anint) ctf_integer(
+                       long, longfield, anint) ctf_integer(int,
+                                                           signedfield,
+                                                           -1) ctf_integer_network(int,
+                                                                                   netintfield,
+                                                                                   netint)
+                       ctf_integer_network_hex(int, netintfieldhex, netint) ctf_array(
+                               long,
+                               arrfield1,
+                               values,
+                               3) ctf_array_text(char,
+                                                 arrfield2,
+                                                 text,
+                                                 10) ctf_array_network(uint32_t,
+                                                                       arrfield3,
+                                                                       net_values,
+                                                                       3) ctf_sequence(char,
+                                                                                       seqfield1,
+                                                                                       text,
+                                                                                       size_t,
+                                                                                       textlen)
+                               ctf_sequence_text(char,
+                                                 seqfield2,
+                                                 text,
+                                                 size_t,
+                                                 textlen) ctf_sequence_network(uint32_t,
+                                                                               seqfield3,
+                                                                               net_values,
+                                                                               size_t,
+                                                                               3)
+                                       ctf_sequence(long, seqfield4, values, size_t, 3) ctf_string(
+                                               stringfield,
+                                               text) ctf_string(stringfield2,
+                                                                etext) ctf_float(float,
+                                                                                 floatfield,
+                                                                                 floatarg)
+                                               ctf_float(double, doublefield, doublearg) ctf_enum(
+                                                       tp,
+                                                       tptest_enum,
+                                                       int,
+                                                       enum0,
+                                                       0) ctf_enum(tp,
+                                                                   tptest_enum,
+                                                                   int,
+                                                                   enum23,
+                                                                   23) ctf_enum(tp,
+                                                                                tptest_enum,
+                                                                                int,
+                                                                                enum27,
+                                                                                27)
+                                                       ctf_enum(tp, tptest_enum, int, enum28, 28)
+                                                               ctf_enum(tp,
+                                                                        tptest_enum,
+                                                                        int,
+                                                                        enum202,
+                                                                        202) ctf_enum(tp,
+                                                                                      tptest_enum,
+                                                                                      int,
+                                                                                      enum304,
+                                                                                      304)
+                                                                       ctf_enum(tp,
+                                                                                tptest_enum,
+                                                                                int,
+                                                                                enumnegative,
+                                                                                -1)))
 
-TRACEPOINT_EVENT(tp, end,
-       TP_ARGS(),
-       TP_FIELDS(
-       )
-)
+TRACEPOINT_EVENT(tp, end, TP_ARGS(), TP_FIELDS())
 
 #endif /* _TRACEPOINT_TP_H */
 
index d59dfa3d81c919cf1993bb7487ac5a302e8f1bb6..b6270c60eb0f68c8be99595c432965641ea535e9 100644 (file)
@@ -6,9 +6,10 @@
  */
 
 #define _LGPL_SOURCE
-#include <stdio.h>
 #include "signal-helper.hpp"
 
+#include <stdio.h>
+
 #define TRACEPOINT_DEFINE
 #include "tp.h"
 
@@ -21,8 +22,7 @@ int main(int argc, char **argv)
        }
 
        if (argc <= 3) {
-               fprintf(stderr, "Usage: %s COUNT STRING [STRING]...\n",
-                       argv[0]);
+               fprintf(stderr, "Usage: %s COUNT STRING [STRING]...\n", argv[0]);
                return 1;
        }
 
index b9fe384297ad9ee45450fa9c0b0b1cc4881e62f5..3a4054a84cfd5a45cfeee7feeee8fa21dc6022b6 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, the_string,
-       TP_ARGS(
-               int, i,
-               int, arg_i,
-               const char *, str
-       ),
-       TP_FIELDS(
-               ctf_integer(int, i, i)
-               ctf_integer(long, arg_i, arg_i)
-               ctf_string(str, str)
-       )
-)
+TRACEPOINT_EVENT(tp,
+                the_string,
+                TP_ARGS(int, i, int, arg_i, const char *, str),
+                TP_FIELDS(ctf_integer(int, i, i) ctf_integer(long, arg_i, arg_i)
+                                  ctf_string(str, str)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index a2aae040f9b01cefb419332afdc0175f10c1546d..b7c3974ee52c268e2f1d93e09e29b9ba4d00c1ee 100644 (file)
@@ -6,6 +6,9 @@
  */
 
 #define _LGPL_SOURCE
+#include "signal-helper.hpp"
+#include "utils.h"
+
 #include <arpa/inet.h>
 #include <getopt.h>
 #include <stdarg.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include "utils.h"
-#include "signal-helper.hpp"
 
 #define TRACEPOINT_DEFINE
 #include "tp.h"
 
-static struct option long_options[] =
-{
+static struct option long_options[] = {
        /* These options set a flag. */
-       {"iter", required_argument, 0, 'i'},
-       {"wait", required_argument, 0, 'w'},
-       {"create-in-main", required_argument, 0, 'm'},
-       {"wait-before-first-event", required_argument, 0, 'b'},
-       {0, 0, 0, 0}
+       { "iter", required_argument, nullptr, 'i' },
+       { "wait", required_argument, nullptr, 'w' },
+       { "create-in-main", required_argument, nullptr, 'm' },
+       { "wait-before-first-event", required_argument, nullptr, 'b' },
+       { nullptr, 0, nullptr, 0 }
 };
 
 int main(int argc, char **argv)
@@ -41,11 +41,10 @@ int main(int argc, char **argv)
        float flt = 2222.0;
        unsigned int nr_iter = 100;
        useconds_t nr_usec = 0;
-       char *wait_before_first_event_file_path = NULL;
-       char *create_in_main_file_path = NULL;
+       char *wait_before_first_event_file_path = nullptr;
+       char *create_in_main_file_path = nullptr;
 
-       while ((option = getopt_long(argc, argv, "i:w:b:m:",
-                       long_options, &option_index)) != -1) {
+       while ((option = getopt_long(argc, argv, "i:w:b:m:", long_options, &option_index)) != -1) {
                switch (option) {
                case 'b':
                        wait_before_first_event_file_path = strdup(optarg);
@@ -92,18 +91,13 @@ int main(int argc, char **argv)
 
        for (i = 0; i < nr_iter; i++) {
                netint = htonl(i);
-               tracepoint(tp, tptest1, i, netint, values, text, strlen(text),
-                          dbl, flt);
-               tracepoint(tp, tptest2, i, netint, values, text, strlen(text),
-                               dbl, flt);
-               tracepoint(tp, tptest3, i, netint, values, text, strlen(text),
-                               dbl, flt);
-               tracepoint(tp, tptest4, i, netint, values, text, strlen(text),
-                               dbl, flt);
-               tracepoint(tp, tptest5, i, netint, values, text, strlen(text),
-                               dbl, flt);
+               tracepoint(tp, tptest1, i, netint, values, text, strlen(text), dbl, flt);
+               tracepoint(tp, tptest2, i, netint, values, text, strlen(text), dbl, flt);
+               tracepoint(tp, tptest3, i, netint, values, text, strlen(text), dbl, flt);
+               tracepoint(tp, tptest4, i, netint, values, text, strlen(text), dbl, flt);
+               tracepoint(tp, tptest5, i, netint, values, text, strlen(text), dbl, flt);
                if (nr_usec) {
-                       if (usleep_safe(nr_usec)) {
+                       if (usleep_safe(nr_usec)) {
                                ret = -1;
                                goto end;
                        }
index 8b68b374df1ed38adc4e26965ce90808a69f6d2f..c9f214ea4e9a3509f8928915443184eb42fd9c43 100644 (file)
 
 #include <lttng/tracepoint.h>
 
-TRACEPOINT_EVENT(tp, tptest1,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
-TRACEPOINT_EVENT(tp, tptest2,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
-TRACEPOINT_EVENT(tp, tptest3,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
-TRACEPOINT_EVENT(tp, tptest4,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
-TRACEPOINT_EVENT(tp, tptest5,
-       TP_ARGS(int, anint, int, netint, long *, values,
-               char *, text, size_t, textlen,
-               double, doublearg, float, floatarg),
-       TP_FIELDS(
-               ctf_integer(int, intfield, anint)
-               ctf_integer_hex(int, intfield2, anint)
-               ctf_integer(long, longfield, anint)
-               ctf_integer_network(int, netintfield, netint)
-               ctf_integer_network_hex(int, netintfieldhex, netint)
-               ctf_array(long, arrfield1, values, 3)
-               ctf_array_text(char, arrfield2, text, 10)
-               ctf_sequence(char, seqfield1, text, size_t, textlen)
-               ctf_sequence_text(char, seqfield2, text, size_t, textlen)
-               ctf_string(stringfield, text)
-               ctf_float(float, floatfield, floatarg)
-               ctf_float(double, doublefield, doublearg)
-       )
-)
+TRACEPOINT_EVENT(
+       tp,
+       tptest1,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
+TRACEPOINT_EVENT(
+       tp,
+       tptest2,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
+TRACEPOINT_EVENT(
+       tp,
+       tptest3,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
+TRACEPOINT_EVENT(
+       tp,
+       tptest4,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
+TRACEPOINT_EVENT(
+       tp,
+       tptest5,
+       TP_ARGS(int,
+               anint,
+               int,
+               netint,
+               long *,
+               values,
+               char *,
+               text,
+               size_t,
+               textlen,
+               double,
+               doublearg,
+               float,
+               floatarg),
+       TP_FIELDS(ctf_integer(int, intfield, anint) ctf_integer_hex(
+               int, intfield2, anint) ctf_integer(long, longfield, anint)
+                         ctf_integer_network(int, netintfield, netint) ctf_integer_network_hex(
+                                 int, netintfieldhex, netint) ctf_array(long, arrfield1, values, 3)
+                                 ctf_array_text(char, arrfield2, text, 10) ctf_sequence(
+                                         char, seqfield1, text, size_t, textlen)
+                                         ctf_sequence_text(char, seqfield2, text, size_t, textlen)
+                                                 ctf_string(stringfield, text)
+                                                         ctf_float(float, floatfield, floatarg)
+                                                                 ctf_float(double,
+                                                                           doublefield,
+                                                                           doublearg)))
 
 #endif /* _TRACEPOINT_TP_H */
 
index 31aa3798f99432c198696d55100d9d347c5210c2..8389b3f76b26f768502c982a21ee775e2d0374da 100644 (file)
@@ -7,6 +7,12 @@
  */
 
 #define _LGPL_SOURCE
+#include "signal-helper.hpp"
+
+#include <common/macros.hpp>
+
+#include <lttng/tracef.h>
+
 #include <fcntl.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/macros.hpp>
-#include <lttng/tracef.h>
-#include "signal-helper.hpp"
-
 const char *str = "test string";
 
-static
-void create_file(const char *path)
+static void create_file(const char *path)
 {
        int ret;
 
@@ -44,7 +45,7 @@ int main(int argc, char **argv)
        int i;
        unsigned int nr_iter = 100;
        useconds_t nr_usec = 0;
-       char *tmp_file_path = NULL;
+       char *tmp_file_path = nullptr;
 
        if (set_signal_handler()) {
                return 1;
index ceadcb37277225bab6adf92667032888f6be49a0..26272e37e4ad599a49acaa66677f8c67bc4c38d3 100644 (file)
@@ -9,19 +9,18 @@
 #define LTTNG_TESTAPP_SIGNAL_HELPER_H
 
 #include <signal.h>
+#include <stdio.h>
 
 static volatile int should_quit;
 
-static
-void sighandler(int sig)
+static void sighandler(int sig)
 {
        if (sig == SIGTERM) {
                should_quit = 1;
        }
 }
 
-static
-int set_signal_handler(void)
+static int set_signal_handler()
 {
        int ret;
        struct sigaction sa {};
@@ -34,7 +33,7 @@ int set_signal_handler(void)
                goto end;
        }
 
-       ret = sigaction(SIGTERM, &sa, NULL);
+       ret = sigaction(SIGTERM, &sa, nullptr);
        if (ret) {
                perror("sigaction");
                goto end;
index af76ae7fc909c60d8cb682dc30ec18dca521ed57..836f13e9543874af8db5814d80a8cb5c165b9384 100644 (file)
@@ -5,7 +5,7 @@ AM_CFLAGS += -O0
 noinst_LTLIBRARIES = libfoo.la
 
 libfoo_la_SOURCES = foo.c foo.h
-libfoo_la_LDFLAGS = -shared -module -avoid-version -rpath $(abs_builddir)/.libs/
+libfoo_la_LDFLAGS = -shared -module -avoid-version -rpath $(libdir)
 
 noinst_PROGRAMS = userspace-probe-elf-binary
 userspace_probe_elf_binary_SOURCES = userspace-probe-elf-binary.c
index d530be2691b8cbacbae6db4ca57be36145376293..7a5040051e7314e137b7e22d30ce56f853af0574 100644 (file)
@@ -8,8 +8,8 @@
 #include "foo.h"
 volatile int not_a_function = 0;
 
-void __attribute__ ((noinline)) test_function(void);
-void __attribute__ ((noinline)) test_function(void)
+void __attribute__((noinline)) test_function(void);
+void __attribute__((noinline)) test_function(void)
 {
        not_a_function += 1;
 }
index 05a20c7a188466471b8a39370178b295eaa122da..7dd53df39c1b3dd10b9e2fb6fb33cbb7a1064942 100644 (file)
@@ -6,10 +6,12 @@
  */
 
 #include "test_class.hpp"
-test_class::test_class() {
+test_class::test_class()
+{
        test_member = 1;
 }
 
-void test_class::test_method() {
+void test_class::test_method()
+{
        test_member += 1;
 }
index aa518e425fba349dd93633dbe5fab1b0f1443ad4..05babd4ce723610b817a6effac18500db41d2c7d 100644 (file)
@@ -5,12 +5,9 @@
  *
  */
 
-class test_class
-{
+class test_class {
 public:
        test_class();
        void test_method();
        volatile int test_member;
 };
-
-
index 544628ff9deee18bdf9e45d4c65f1745277e593c..e135416367da19b2dfcf5ad07fb15ced1718153d 100644 (file)
@@ -9,13 +9,13 @@
 
 volatile int not_a_function = 0;
 
-void test_cxx_function() __attribute__ ((noinline));
+void test_cxx_function() __attribute__((noinline));
 void test_cxx_function()
 {
        not_a_function += 1;
 }
 
-int main(void)
+int main()
 {
        test_class my_test_class;
        /* Call test function. */
index f12ced228e4611ee6b48361fafe28454b4621b47..77567f2fc6913d15004bf0f65915407e668eea79 100644 (file)
@@ -22,19 +22,19 @@ noinst_LTLIBRARIES = libfoo.la libbar.la libzzz.la
 libfoo_la_SOURCES = libfoo.h libfoo.c
 libfoo_la_LIBADD = foobar_provider.o
 libfoo_la_CFLAGS = -I$(abs_builddir)
-libfoo_la_LDFLAGS = -module -shared -avoid-version -rpath $(abs_builddir)/.libs/
+libfoo_la_LDFLAGS = -module -shared -avoid-version -rpath $(libdir)
 nodist_libfoo_la_SOURCES = $(abs_builddir)/foobar_provider.h
 
 libbar_la_SOURCES = libbar.h libbar.c
 libbar_la_LIBADD = foobar_provider.o
 libbar_la_CFLAGS = -I$(abs_builddir)
-libbar_la_LDFLAGS = -module -shared -avoid-version -rpath $(abs_builddir)/.libs/
+libbar_la_LDFLAGS = -module -shared -avoid-version -rpath $(libdir)
 nodist_libbar_la_SOURCES = $(abs_builddir)/foobar_provider.h
 
 libzzz_la_SOURCES = libzzz.h libzzz.c
 libzzz_la_LIBADD = foobar_provider.o
 libzzz_la_CFLAGS = -I$(abs_builddir)
-libzzz_la_LDFLAGS = -module -shared -avoid-version -rpath $(abs_builddir)/.libs/
+libzzz_la_LDFLAGS = -module -shared -avoid-version -rpath $(libdir)
 nodist_libzzz_la_SOURCES = $(abs_builddir)/foobar_provider.h
 
 dtrace_verbose = $(dtrace_verbose_@AM_V@)
index a504ac89e3407b4346b26e080adf7779bd69df21..0a0edfb81a9249ea71b0fe2a51254c28066f1227 100644 (file)
@@ -5,8 +5,17 @@
  *
  */
 
+/*
+ * The order of inclusion is important here: including sdt.h _before_ the probe
+ * declarations ensures that semaphore-protected SDT probes (which we don't support) are not
+ * generated. See SYSTEMTAP(2) for more details.
+ */
+/* clang-format off */
 #include <sys/sdt.h>
 #include "foobar_provider.h"
-void bar_function() {
+/* clang-format on */
+
+void bar_function()
+{
        FOOBAR_TP_IN_DLOPEN();
 }
index 103b3d729285ea637da28ec0ecc4086b37bdbea7..283dac24e5387d6e1af90e4cc126ec3f6b7582f1 100644 (file)
@@ -5,10 +5,20 @@
  *
  */
 
+/*
+ * The order of inclusion is important here: including sdt.h _before_ the probe
+ * declarations ensures that semaphore-protected SDT probes (which we don't support) are not
+ * generated. See SYSTEMTAP(2) for more details.
+ */
+/* clang-format off */
 #include <sys/sdt.h>
 #include "foobar_provider.h"
-void foo_function() {
+/* clang-format on */
+
+void foo_function()
+{
        FOOBAR_TP_IN_SHARED_OBJECT();
 }
-void overridable_function() {
+void overridable_function()
+{
 }
index 64660283e4069d781c8f25bc6b904cfc8b721440..8b3a0b2081e4facef5aa5df988a1ad12bfe87d27 100644 (file)
@@ -5,8 +5,17 @@
  *
  */
 
+/*
+ * The order of inclusion is important here: including sdt.h _before_ the probe
+ * declarations ensures that semaphore-protected SDT probes (which we don't support) are not
+ * generated. See SYSTEMTAP(2) for more details.
+ */
+/* clang-format off */
 #include <sys/sdt.h>
 #include "foobar_provider.h"
-void overridable_function() {
+/* clang-format on */
+
+void overridable_function()
+{
        FOOBAR_TP_IN_LDPRELOAD();
 }
index 3126e91ada8212385f0e0b7fe3a2014cc0cb991b..ef8ed2629ddc6bc6fafa5c3fb3f26238593776aa 100644 (file)
@@ -5,8 +5,17 @@
  *
  */
 
+/*
+ * The order of inclusion is important here: including sdt.h _after_ the probe
+ * declarations ensures that semaphore-protected SDT probes are
+ * generated. See SYSTEMTAP(2) for more details.
+ */
+/* clang-format off */
 #include "foobar_provider.h"
 #include <sys/sdt.h>
-void sema_function() {
+/* clang-format on */
+
+void sema_function()
+{
        FOOBAR_TP_WITH_SEMAPHORE();
 }
index 45eec1203128b9d82d1138e9301e2bc4c3c08124..551b42b5a7e33310dd783b6a897de180fa48ea2d 100644 (file)
@@ -9,6 +9,19 @@
 #define _GNU_SOURCE
 #endif
 
+/*
+ * The order of inclusion is important here: including sdt.h _before_ the probe
+ * declarations ensures that semaphore-protected SDT probes (which we don't support) are not
+ * generated. See SYSTEMTAP(2) for more details.
+ */
+/* clang-format off */
+#include <sys/sdt.h>
+#include "foobar_provider.h"
+/* clang-format on */
+
+#include "libfoo.h"
+#include "sema.h"
+
 #include <dlfcn.h>
 #include <fcntl.h>
 #include <stdbool.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#include <sys/sdt.h>
-
-#include "foobar_provider.h"
-#include "libfoo.h"
-#include "sema.h"
-
 int main(int argc, char *argv[])
 {
        void *handle;
@@ -31,16 +38,16 @@ int main(int argc, char *argv[])
        FOOBAR_TP1();
        FOOBAR_TP2();
        /*
-        * This SDT tracepoint has an argument. Argument extraction is not support
-        * at the moment but tracing of the tracepoint should work.
+        * This SDT tracepoint has an argument. Argument extraction is not supported
+        * at the moment, but tracing of the tracepoint should work.
         */
        FOOBAR_TP_WITH_ARG(42);
 
-       /* Call function containing an SDT tracepoint in shared object */
+       /* Call a function containing an SDT tracepoint in shared object. */
        foo_function();
 
        /*
-        * Load a show shared object and call a function containing an SDT
+        * Load a shared object and call a function containing an SDT
         * tracepoint
         */
        handle = dlopen("libbar.so", RTLD_LAZY);
@@ -48,16 +55,16 @@ int main(int argc, char *argv[])
                fprintf(stderr, "Can't dlopen libbar.so");
                return -1;
        }
-       bar_function = (void (*)())dlsym(handle, "bar_function");
+       bar_function = (void (*)()) dlsym(handle, "bar_function");
        bar_function();
        dlclose(handle);
 
-       /* This tracepoint has 2 callsites in this binary */
+       /* This tracepoint has 2 call sites in this binary. */
        FOOBAR_TP2();
 
        /*
-        * This function is defined in libfoo AND in libzzz. For a test, libzzz is
-        * LD_PRELOADed and should override this function
+        * This function is defined in libfoo and in libzzz. For a test, libzzz is
+        * LD_PRELOADed and should override this function.
         */
        overridable_function();
 
@@ -68,4 +75,3 @@ int main(int argc, char *argv[])
        sema_function();
        return 0;
 }
-
index 0f1bd28c7e7a3da58d09abc63c5c3270347b7071..fbf0019cb713f43d08ced60a39553a9e770dce50 100644 (file)
@@ -5,8 +5,13 @@
  *
  */
 
+#include "utils.h"
+
+#include <common/compat/errno.hpp>
 #include <common/compat/time.hpp>
+#include <common/macros.hpp>
 #include <common/time.hpp>
+
 #include <fcntl.h>
 #include <poll.h>
 #include <stdbool.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <common/compat/errno.hpp>
-#include <common/macros.hpp>
-
-#include "utils.h"
-
-static inline
 int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2)
 {
        struct timespec delta;
@@ -30,8 +29,7 @@ int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2)
        LTTNG_ASSERT(t1 && t2);
        delta.tv_sec = t2->tv_sec - t1->tv_sec;
        delta.tv_nsec = t2->tv_nsec - t1->tv_nsec;
-       return ((int64_t) NSEC_PER_SEC * (int64_t) delta.tv_sec) +
-                       (int64_t) delta.tv_nsec;
+       return ((int64_t) NSEC_PER_SEC * (int64_t) delta.tv_sec) + (int64_t) delta.tv_nsec;
 }
 
 int usleep_safe(useconds_t usec)
@@ -101,24 +99,23 @@ int wait_on_file(const char *path)
        for (;;) {
                ret = stat(path, &buf);
                if (ret == -1 && errno == ENOENT) {
-                       ret = poll(NULL, 0, 10);        /* 10 ms delay */
+                       ret = poll(nullptr, 0, 10); /* 10 ms delay */
                        /* Should return 0 everytime */
                        if (ret) {
                                if (ret < 0) {
                                        perror("perror");
                                } else {
-                                       fprintf(stderr,
-                                               "poll return value is larger than zero\n");
+                                       fprintf(stderr, "poll return value is larger than zero\n");
                                }
                                return -1;
                        }
-                       continue;                       /* retry */
+                       continue; /* retry */
                }
                if (ret) {
                        perror("stat");
                        return -1;
                }
-               break;  /* found */
+               break; /* found */
        }
 
        return 0;
index fc06b4ace4d7a058d481d1a8ecec519b07ae5bce..802743ec1fd32fc3c6c5c420ac058c9181dc132c 100644 (file)
@@ -8,11 +8,15 @@
 #ifndef TEST_UTILS_H
 #define TEST_UTILS_H
 
+#include <sys/types.h>
+#include <unistd.h>
+
 #if defined(__cplusplus)
 extern "C" {
 #endif
 
-#if !defined(__GLIBC__) || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
+#if !defined(__GLIBC__) || \
+       ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined(_GNU_SOURCE))
 
 /*
  * Version using XSI strerror_r.
@@ -27,20 +31,19 @@ extern "C" {
 /*
  * Version using GNU strerror_r, for linux with appropriate defines.
  */
-#define PERROR_NO_LOGGER(msg, args...)                                    \
-       do {                                                              \
-               char *_perror_buf;                                        \
-               char _perror_tmp[200];                                    \
-               _perror_buf = strerror_r(                                 \
-                               errno, _perror_tmp, sizeof(_perror_tmp)); \
-               fprintf(stderr, msg ": %s\n", ##args, _perror_buf);       \
+#define PERROR_NO_LOGGER(msg, args...)                                             \
+       do {                                                                       \
+               char *_perror_buf;                                                 \
+               char _perror_tmp[200];                                             \
+               _perror_buf = strerror_r(errno, _perror_tmp, sizeof(_perror_tmp)); \
+               fprintf(stderr, msg ": %s\n", ##args, _perror_buf);                \
        } while (0);
 #endif
 
 int usleep_safe(useconds_t usec);
 int create_file(const char *path);
 int wait_on_file(const char *path);
-
+int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2);
 #if defined(__cplusplus)
 }
 #endif
index 18b673b11452491bc3946abda5aa0225d53be587..0e8ec54dd4f102b99424466eafc5275f0ba10092 100644 (file)
@@ -148,7 +148,7 @@ function lttng_pgrep ()
 
        while IFS= read -r pid ; do
                # /proc/pid/cmdline is null separated.
-               if full_command_no_argument=$(cut -d '' -f 1 2>/dev/null < /proc/"$pid"/cmdline); then
+               if full_command_no_argument=$( (tr '\0' '\n' < /proc/"$pid"/cmdline) 2>/dev/null | head -n1); then
                        command_basename=$(basename "$full_command_no_argument")
                        if grep -q "$pattern" <<< "$command_basename"; then
                                echo "$pid"
@@ -204,11 +204,115 @@ function validate_kernel_version ()
 #  $2 = include special characters; 1 = yes, 0 = no; defaults to yes
 function randstring()
 {
+       local len="${1:-16}"
+
        [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
-       cat /dev/urandom 2>/dev/null | tr -cd "$CHAR" 2>/dev/null | head -c ${1:-16} 2>/dev/null
+       # /dev/urandom isn't guaranteed to generate valid multi-byte characters.
+       # Specifying the C locale eliminates the "Illegal byte sequence" error
+       # that 'tr' outputs in such cases.
+       LC_CTYPE=C tr -cd "$CHAR" < /dev/urandom 2>/dev/null | head -c "$len" 2>/dev/null
        echo
 }
 
+# Return a space-separated string of online CPU IDs, based on
+# /sys/devices/system/cpu/online, or from 0 to nproc - 1 otherwise.
+function get_online_cpus()
+{
+       local cpus=()
+       local range_re
+       if [ -f /sys/devices/system/cpu/online ]; then
+               range_re='([0-9]+)-([0-9]+)'
+               while read -r range ; do
+                       if [[ "${range}" =~ ${range_re} ]] ; then
+                               mapfile -t -O "${#cpus[*]}" cpus <<< $(seq "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}")
+                       else
+                               cpus+=("${range}")
+                       fi
+               done < <(tr ',' $'\n' < /sys/devices/system/cpu/online)
+       else
+               read -r -a cpus <<< $(seq 0 $(( $(conf_proc_count) - 1 )) )
+       fi
+       echo "${cpus[*]}"
+}
+
+# Helpers for get_possible_cpus.
+function get_possible_cpus_count_from_sysfs_possible_mask()
+{
+       local max_possible_cpu_id
+
+       # The Awk script extracts the highest CPU id from the possible CPU
+       # mask. Assuming a numerical order, a field separator '-' and a record
+       # separator ','. The last value parsed is the highest id.
+       if [ -f /sys/devices/system/cpu/possible ]; then
+               max_possible_cpu_id=$(awk -F '-' 'BEGIN { RS = ","} { last = $NF } END { printf("%d\n", last) }' \
+                                     /sys/devices/system/cpu/possible)
+               echo "$((max_possible_cpu_id+1))"
+       else
+               echo "0"
+       fi
+}
+
+# This is a fallback if the possible CPU mask is not available. This will not
+# take into account unplugged CPUs.
+function get_max_cpus_count_from_sysfs_cpu_directories()
+{
+       local max_possible_cpu_id=0
+       local current_cpu_id
+
+       for i in /sys/devices/system/cpu/cpu[0-9]*; do
+               current_cpu_id="${i#/sys/devices/system/cpu/cpu}"
+               if [ "$current_cpu_id" -gt "$max_possible_cpu_id" ]; then
+                       max_possible_cpu_id="$current_cpu_id"
+               fi
+       done
+
+       echo "$((max_possible_cpu_id+1))"
+}
+
+# Return the number of possible CPUs.
+function get_possible_cpus_count()
+{
+       local possible_cpus_count
+       possible_cpus_count=$(get_possible_cpus_count_from_sysfs_possible_mask)
+
+       if [ "$possible_cpus_count" -eq "0" ]; then
+               local configured_cpus_count
+               configured_cpus_count=$(getconf _NPROCESSORS_CONF)
+               possible_cpus_count=$(get_max_cpus_count_from_sysfs_cpu_directories)
+               possible_cpus_count=$((configured_cpus_count > possible_cpus_count \
+                                                            ? configured_cpus_count \
+                                                            : possible_cpus_count))
+       fi
+
+       echo "$possible_cpus_count"
+}
+
+# Return the list of exposed CPU.
+#
+# NOTE! Use it like so:
+#
+# IFS=" " read -r -a VARIABLE <<< "$(get_exposed_cpus_list)"
+function get_exposed_cpus_list()
+{
+       local list=()
+
+       for i in /sys/devices/system/cpu/cpu[0-9]*; do
+               list+=("${i#/sys/devices/system/cpu/cpu}")
+       done
+
+       echo "${list[@]}"
+}
+
+# Return any available CPU found. Do not make assumption about the returned
+# value, e.g. that it could be 0.
+function get_any_available_cpu()
+{
+       for cpu in $(get_online_cpus); do
+               echo "${cpu}"
+               break;
+       done
+}
+
 # Return the number of _configured_ CPUs.
 function conf_proc_count()
 {
@@ -219,6 +323,41 @@ function conf_proc_count()
        echo
 }
 
+# Usage:
+# check_skip_kernel_test [NB_TESTS] [SKIP_MESSAGE]
+# Return 0 if LTTNG_TOOLS_DISABLE_KERNEL_TESTS was set or the current user is not a root user
+# If NB_TESTS is set, call skip() to skip number of tests.
+# If NB_TESTS is empty, just output a reason with diag.
+# An optional message can be added.
+
+function check_skip_kernel_test ()
+{
+       local num_tests="$1"
+       local skip_message="$2"
+
+       # Check for skip test kernel flag
+       if [ "$LTTNG_TOOLS_DISABLE_KERNEL_TESTS" == "1" ]; then
+               if ! test -z "$num_tests"; then
+                       skip 0 "LTTNG_TOOLS_DISABLE_KERNEL_TESTS was set.${skip_message+ }${skip_message}" "$num_tests"
+               else
+                       diag "LTTNG_TOOLS_DISABLE_KERNEL_TESTS was set.${skip_message+ }${skip_message}"
+               fi
+               return 0
+       fi
+
+       # Check if we are running as root
+       if [ "$(id -u)" != "0" ]; then
+               if ! test -z "$num_tests"; then
+                       skip 0 "Root access is needed for kernel testing.${skip_message+ }${skip_message}" "$num_tests"
+               else
+                       diag "Root access is needed for kernel testing.${skip_message+ }${skip_message}"
+               fi
+               return 0
+       fi
+
+       return 1
+}
+
 # Check if base lttng-modules are present.
 # Bail out on failure
 function validate_lttng_modules_present ()
@@ -529,7 +668,7 @@ function start_lttng_relayd_opt()
        if [ -z $(lttng_pgrep "$RELAYD_MATCH") ]; then
                # shellcheck disable=SC2086
                $DIR/../src/bin/lttng-relayd/$RELAYD_BIN $process_mode $opt 1> $OUTPUT_DEST 2> $ERROR_OUTPUT_DEST
-               #$DIR/../src/bin/lttng-relayd/$RELAYD_BIN $opt -vvv >>/tmp/relayd.log 2>&1 &
+               #$DIR/../src/bin/lttng-relayd/$RELAYD_BIN $process_mode $opt -vvv >>/tmp/relayd.log 2>&1 &
                if [ $? -eq 1 ]; then
                        if [ $withtap -eq "1" ]; then
                                fail "Start lttng-relayd (process mode: $process_mode opt: $opt)"
@@ -571,8 +710,9 @@ function stop_lttng_relayd_opt()
 
 
        # Multiply time by 2 to simplify integer arithmetic
+       # Multiply time by 5 to adjust for sleeping every 0.1s
        if [ -n "$timeout_s" ]; then
-               dtimeleft_s=$((timeout_s * 2))
+               dtimeleft_s=$((timeout_s * 2 * 5))
        fi
 
 
@@ -607,7 +747,7 @@ function stop_lttng_relayd_opt()
                                fi
                                dtimeleft_s=$((dtimeleft_s - 1))
                        fi
-                       sleep 0.5
+                       sleep 0.1
                done
                if [ "$withtap" -eq "1" ]; then
                        if [ "$retval" -eq "0" ]; then
@@ -731,8 +871,9 @@ function stop_lttng_sessiond_opt()
        fi
 
        # Multiply time by 2 to simplify integer arithmetic
+       # Multiply time by 5 to adjust for sleeping every 0.1s
        if [ -n "$timeout_s" ]; then
-               dtimeleft_s=$((timeout_s * 2))
+               dtimeleft_s=$((timeout_s * 2 * 5))
        fi
 
        if [ -n "$TEST_NO_SESSIOND" ] && [ "$TEST_NO_SESSIOND" == "1" ]; then
@@ -777,7 +918,7 @@ function stop_lttng_sessiond_opt()
                                fi
                                dtimeleft_s=$((dtimeleft_s - 1))
                        fi
-                       sleep 0.5
+                       sleep 0.1
                done
                out=1
                while [ -n "$out" ]; do
@@ -789,7 +930,7 @@ function stop_lttng_sessiond_opt()
                                fi
                                dtimeleft_s=$((dtimeleft_s - 1))
                        fi
-                       sleep 0.5
+                       sleep 0.1
                done
 
                if [ "$withtap" -eq "1" ]; then
@@ -899,8 +1040,9 @@ function stop_lttng_consumerd_opt()
        fi
 
        # Multiply time by 2 to simplify integer arithmetic
+       # Multiply time by 5 to adjust for sleeping every 0.1s
        if [ -n "$timeout_s" ]; then
-               dtimeleft_s=$((timeout_s * 2))
+               dtimeleft_s=$((timeout_s * 2 * 5))
        fi
 
        pids="$(lttng_pgrep "$CONSUMERD_MATCH")"
@@ -945,7 +1087,7 @@ function stop_lttng_consumerd_opt()
                                fi
                                dtimeleft_s=$((dtimeleft_s - 1))
                        fi
-                       sleep 0.5
+                       sleep 0.1
                done
                if [ "$withtap" -eq "1" ]; then
                        if [ "$retval" -eq "0" ]; then
@@ -1431,9 +1573,14 @@ function enable_ust_lttng_event_loglevel()
        local sess_name="$1"
        local event_name="$2"
        local loglevel="$3"
+       local channel_name="$4"
+       local chan=()
+       if [ -n "${channel_name}" ] ; then
+               chan=('-c' "${channel_name}")
+       fi
 
        _run_lttng_cmd "$OUTPUT_DEST" "$ERROR_OUTPUT_DEST" \
-               enable-event "$event_name" -s $sess_name -u --loglevel $loglevel
+               enable-event "${chan[@]}" "$event_name" -s "${sess_name}" -u --loglevel="${loglevel}"
        ok $? "Enable event $event_name with loglevel $loglevel"
 }
 
@@ -1442,9 +1589,14 @@ function enable_ust_lttng_event_loglevel_only()
        local sess_name="$1"
        local event_name="$2"
        local loglevel="$3"
+       local channel_name="$4"
+       local chan=()
+       if [ -n "${channel_name}" ] ; then
+               chan=('-c' "${channel_name}")
+       fi
 
        _run_lttng_cmd "$OUTPUT_DEST" "$ERROR_OUTPUT_DEST" \
-               enable-event "$event_name" -s $sess_name -u --loglevel-only $loglevel
+               enable-event "${chan[@]}" "$event_name" -s "${sess_name}" -u --loglevel-only "${loglevel}"
        ok $? "Enable event $event_name with loglevel-only $loglevel"
 }
 
@@ -1574,9 +1726,10 @@ function destroy_lttng_session ()
        local withtap=$1
        local expected_to_fail=$2
        local sess_name=$3
+       shift 3
 
        _run_lttng_cmd "$OUTPUT_DEST" "$ERROR_OUTPUT_DEST" \
-               destroy $sess_name
+               destroy $sess_name $@
        ret=$?
        if [[ $expected_to_fail -eq "1" ]]; then
                test "$ret" -ne "0"
@@ -1881,7 +2034,7 @@ function wait_live_trace_ready ()
        diag "Waiting for live trace at url: $url"
        while [ $zero_client_match -eq 0 ]; do
                zero_client_match=$($BABELTRACE_BIN -i lttng-live $url | grep "0 client(s) connected" | wc -l)
-               sleep 0.5
+               sleep 0.1
        done
        pass "Waiting for live trace at url: $url"
 }
@@ -1894,7 +2047,7 @@ function wait_live_viewer_connect ()
        diag "Waiting for live viewers on url: $url"
        while [ $one_client_match -eq 0 ]; do
                one_client_match=$($BABELTRACE_BIN -i lttng-live $url | grep "1 client(s) connected" | wc -l)
-               sleep 0.5
+               sleep 0.1
        done
        pass "Waiting for live viewers on url: $url"
 }
@@ -1907,216 +2060,220 @@ function bail_out_if_no_babeltrace()
        fi
 }
 
-function validate_metadata_event ()
+# Check that the trace metadata contains '$expected' event ids matching '$event_name'.
+function validate_metadata_event()
 {
        local event_name=$1
-       local nr_event_id=$2
+       local expected=$2
        local trace_path=$3
 
-       local metadata_file=$(find $trace_path -name "metadata")
-       local metadata_path=$(dirname $metadata_file)
+       local metadata_file
+       local metadata_path
+       local count
+
+       metadata_file=$(find "$trace_path" -name "metadata")
+       metadata_path=$(dirname "$metadata_file")
 
        bail_out_if_no_babeltrace
 
-       local count=$($BABELTRACE_BIN --output-format=ctf-metadata $metadata_path | grep $event_name | wc -l)
-
-       if [ "$count" -ne "$nr_event_id" ]; then
-               fail "Metadata match with the metadata of $nr_event_id event(s) named $event_name"
-               diag "$count matching event names found in metadata"
-       else
-               pass "Metadata match with the metadata of $nr_event_id event(s) named $event_name"
-       fi
+       count=$($BABELTRACE_BIN --output-format=ctf-metadata "$metadata_path" | grep -c "$event_name")
 
+       test "$count" -eq "$expected"
+       ok $? "Found $count / $expected metadata event id matching '$event_name'"
 }
 
-function trace_matches ()
+# Check that the trace contains '$expected' events matching '$event_name', other
+# events not matching '$event_name' can be present.
+function trace_matches()
 {
        local event_name=$1
-       local nr_iter=$2
+       local expected=$2
        local trace_path=$3
 
+       local count
+       local total
+
        bail_out_if_no_babeltrace
 
-       local count=$($BABELTRACE_BIN $trace_path | grep $event_name | wc -l)
+       count=$($BABELTRACE_BIN "$trace_path" | grep -c "$event_name")
+       total=$($BABELTRACE_BIN "$trace_path" | wc -l)
 
-       if [ "$count" -ne "$nr_iter" ]; then
-               fail "Trace match"
-               diag "$count matching events found in trace"
-       else
-               pass "Trace match"
-       fi
+       test "$count" -eq "$expected"
+
+       ok $? "Found $count / $expected events matching '$event_name' out of $total events"
 }
 
+# Check that the trace contains '$expected' events matching '$event_name' and no
+# other events.
 function trace_match_only()
 {
        local event_name=$1
-       local nr_iter=$2
+       local expected=$2
        local trace_path=$3
 
+       local count
+       local total
+
        bail_out_if_no_babeltrace
-       #which "$BABELTRACE_BIN" >/dev/null
-       #skip $? -ne 0 "\"$BABELTRACE_BIN\" binary not found. Skipping trace comparison"
 
-       local count=$($BABELTRACE_BIN $trace_path | grep $event_name | wc -l)
-       local total=$($BABELTRACE_BIN $trace_path | wc -l)
+       count=$($BABELTRACE_BIN "$trace_path" | grep -c "$event_name")
+       total=$($BABELTRACE_BIN "$trace_path" | wc -l)
 
-       if [ "$nr_iter" -eq "$count" ] && [ "$total" -eq "$nr_iter" ]; then
-               pass "Trace match with $total event $event_name"
-       else
-               fail "Trace match"
-               diag "$total event(s) found, expecting $nr_iter of event $event_name and only found $count"
-       fi
+       test "$expected" -eq "$count" && test "$total" -eq "$expected"
+
+       ok $? "Found $count / $expected events matching '$event_name' amongst $total events"
 }
 
-function validate_trace
+# Check that the trace contains at least 1 event matching each name in the
+# comma separated list '$event_names'.
+function validate_trace()
 {
-       local event_name=$1
+       local event_names=$1
        local trace_path=$2
 
+       local count
+
        bail_out_if_no_babeltrace
 
        OLDIFS=$IFS
        IFS=","
-       for i in $event_name; do
-               traced=$($BABELTRACE_BIN $trace_path 2>/dev/null | grep $i | wc -l)
-               if [ "$traced" -ne 0 ]; then
-                       pass "Validate trace for event $i, $traced events"
-               else
-                       fail "Validate trace for event $i"
-                       diag "Found $traced occurrences of $i"
-               fi
+       for event_name in $event_names; do
+               # trace_path is unquoted since callers make use of globbing
+               count=$($BABELTRACE_BIN $trace_path | grep -c "$event_name")
+               test "$count" -gt 0
+               ok $? "Found $count events matching '$event_name'"
        done
-       ret=$?
        IFS=$OLDIFS
-       return $ret
 }
 
-function validate_trace_count
+# Check that the trace contains at least 1 event matching each name in the
+# comma separated list '$event_names' and a total of '$expected' events.
+function validate_trace_count()
 {
-       local event_name=$1
+       local event_names=$1
        local trace_path=$2
-       local expected_count=$3
+       local expected=$3
+
+       local count
+       local total=0
 
        bail_out_if_no_babeltrace
 
-       cnt=0
        OLDIFS=$IFS
        IFS=","
-       for i in $event_name; do
-               traced=$($BABELTRACE_BIN $trace_path 2>/dev/null | grep $i | wc -l)
-               if [ "$traced" -ne 0 ]; then
-                       pass "Validate trace for event $i, $traced events"
-               else
-                       fail "Validate trace for event $i"
-                       diag "Found $traced occurrences of $i"
-               fi
-               cnt=$(($cnt + $traced))
+       for event_name in $event_names; do
+               count=$($BABELTRACE_BIN "$trace_path" | grep -c "$event_name")
+               test "$count" -gt 0
+               ok $? "Found '$count' events matching '$event_name'"
+               total=$(( total + count ))
        done
        IFS=$OLDIFS
-       test $cnt -eq $expected_count
-       ok $? "Read a total of $cnt events, expected $expected_count"
+       test $total -eq "$expected"
+       ok $? "Found $total events, expected $expected events"
 }
 
-function validate_trace_count_range_incl_min_excl_max
+# Check that the trace contains at least '$expected_min' event matching each
+# name in the comma separated list '$event_names' and a total at least
+# '$expected_min' and less than '$expected_max' events.
+function validate_trace_count_range_incl_min_excl_max()
 {
-       local event_name=$1
+       local event_names=$1
        local trace_path=$2
        local expected_min=$3
        local expected_max=$4
 
+       local count
+       local total=0
+
        bail_out_if_no_babeltrace
 
-       cnt=0
        OLDIFS=$IFS
        IFS=","
-       for i in $event_name; do
-               traced=$($BABELTRACE_BIN $trace_path 2>/dev/null | grep $i | wc -l)
-               if [ "$traced" -ge $expected_min ]; then
-                       pass "Validate trace for event $i, $traced events"
-               else
-                       fail "Validate trace for event $i"
-                       diag "Found $traced occurrences of $i"
-               fi
-               cnt=$(($cnt + $traced))
+       for event_name in $event_names; do
+               count=$($BABELTRACE_BIN "$trace_path" | grep -c "$event_name")
+               test "$count" -ge "$expected_min"
+               ok $? "Found $count events matching '$event_name', expected at least $expected_min"
+               total=$(( total + count ))
        done
        IFS=$OLDIFS
-       test $cnt -lt $expected_max
-       ok $? "Read a total of $cnt events, expected between [$expected_min, $expected_max["
+       test $total -ge "$expected_min" && test $total -lt "$expected_max"
+       ok $? "Found a total of $total events, expected at least $expected_min and less than $expected_max"
 }
 
-function trace_first_line
+function trace_first_line()
 {
        local trace_path=$1
 
-       $BABELTRACE_BIN $trace_path 2>/dev/null | head -n 1
+       $BABELTRACE_BIN "$trace_path" | head -n 1
 }
 
+# Check that the trace contains at least 1 event matching the grep extended
+# regexp '$event_exp'.
 function validate_trace_exp()
 {
        local event_exp=$1
        local trace_path=$2
 
+       local count
+
        bail_out_if_no_babeltrace
 
-       traced=$($BABELTRACE_BIN $trace_path 2>/dev/null | grep --extended-regexp ${event_exp} | wc -l)
-       if [ "$traced" -ne 0 ]; then
-               pass "Validate trace for expression '${event_exp}', $traced events"
-       else
-               fail "Validate trace for expression '${event_exp}'"
-               diag "Found $traced occurrences of '${event_exp}'"
-       fi
-       ret=$?
-       return $ret
+       # event_exp is unquoted since it contains multiple grep arguments
+       count=$($BABELTRACE_BIN "$trace_path" | grep -c --extended-regexp $event_exp)
+       test "$count" -gt 0
+       ok $? "Found $count events matching expression '$event_exp'"
 }
 
+# Check that the trace contains at least 1 event matching the grep extended
+# regexp '$event_exp' and zero event not matching it.
 function validate_trace_only_exp()
 {
        local event_exp=$1
        local trace_path=$2
 
+       local count
+       local total
+
        bail_out_if_no_babeltrace
 
-       local count=$($BABELTRACE_BIN $trace_path | grep --extended-regexp ${event_exp} | wc -l)
-       local total=$($BABELTRACE_BIN $trace_path | wc -l)
+       # event_exp is unquoted since it contains multiple grep arguments
+       count=$($BABELTRACE_BIN "$trace_path" | grep -c --extended-regexp $event_exp)
+       total=$($BABELTRACE_BIN "$trace_path" | wc -l)
 
-       if [ "$count" -ne 0 ] && [ "$total" -eq "$count" ]; then
-               pass "Trace match with $total for expression '${event_exp}'"
-       else
-               fail "Trace match"
-               diag "$total syscall event(s) found, only syscalls matching expression '${event_exp}' ($count occurrences) are expected"
-       fi
-       ret=$?
-       return $ret
+       test  "$count" -gt 0 && test "$total" -eq "$count"
+       ok $? "Found $count events matching expression '$event_exp' amongst $total events"
 }
 
+# Check that the trace is valid and contains 0 event.
 function validate_trace_empty()
 {
        local trace_path=$1
 
+       local ret
+       local count
+
        bail_out_if_no_babeltrace
 
-       events=$($BABELTRACE_BIN $trace_path 2>/dev/null)
+       events=$($BABELTRACE_BIN "$trace_path")
        ret=$?
        if [ $ret -ne 0 ]; then
                fail "Failed to parse trace"
                return $ret
        fi
 
-       traced=$(echo -n "$events" | wc -l)
-       if [ "$traced" -eq 0 ]; then
-               pass "Validate empty trace"
-       else
-               fail "Validate empty trace"
-               diag "Found $traced events in trace"
-       fi
-       ret=$?
-       return $ret
+       count=$(echo -n "$events" | wc -l)
+       test "$count" -eq 0
+       ok $? "Validate trace is empty, found $count events"
 }
 
 function validate_directory_empty ()
 {
        local trace_path="$1"
 
+       local files
+       local ret
+       local nb_files
+
        # Do not double quote `$trace_path` below as we want wildcards to be
        # expanded.
        files="$(ls -A $trace_path)"
@@ -2127,7 +2284,8 @@ function validate_directory_empty ()
        fi
 
        nb_files="$(echo -n "$files" | wc -l)"
-       ok $nb_files "Directory \"$trace_path\" is empty"
+       test "$nb_files" -eq 0
+       ok $? "Directory \"$trace_path\" is empty"
 }
 
 function validate_trace_session_ust_empty()
@@ -2366,8 +2524,8 @@ function lttng_remove_trigger_ok()
 
 function list_triggers_matches_ok ()
 {
-       local tmp_stdout=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
-       local tmp_stderr=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stderr.XXXXXX")
+       local tmp_stdout=$(mktemp -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
+       local tmp_stderr=$(mktemp -t "tmp.${FUNCNAME[0]}_stderr.XXXXXX")
 
        local test_name="$1"
        local expected_stdout_file="$2"
@@ -2396,9 +2554,9 @@ function list_triggers_matches_mi_ok ()
        local test_name="$1"
        local expected_stdout_file="$2"
 
-       tmp_stdout_raw=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
-       tmp_stdout=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
-       tmp_stderr=$(mktemp --tmpdir -t "tmp.${FUNCNAME[0]}_stderr.XXXXXX")
+       tmp_stdout_raw=$(mktemp -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
+       tmp_stdout=$(mktemp -t "tmp.${FUNCNAME[0]}_stdout.XXXXXX")
+       tmp_stderr=$(mktemp -t "tmp.${FUNCNAME[0]}_stderr.XXXXXX")
 
        diag "$TESTDIR/../src/bin/lttng/$LTTNG_BIN --mi xml list-triggers"
 
index 9bfd50bda83d8e8ed829e2a7277eef2ae419cc28..3995dde48a27d9d96485f148222b883f58f4ef10 100644 (file)
  *     node;b;
  *     node;c;
  */
+#include <common/defaults.hpp>
+
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+#include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
 
-#include <libxml/tree.h>
-#include <libxml/parser.h>
-#include <libxml/xpath.h>
-#include <libxml/xpathInternals.h>
-#include <common/defaults.hpp>
-
 #if defined(LIBXML_XPATH_ENABLED)
 
 static int opt_verbose;
@@ -56,7 +56,7 @@ static int print_xpath_nodes(xmlDocPtr doc, xmlNodeSetPtr nodes, FILE *output)
        int i;
 
        xmlNodePtr cur;
-       xmlChar *node_child_value_string = NULL;
+       xmlChar *node_child_value_string = nullptr;
 
        LTTNG_ASSERT(output);
        size = (nodes) ? nodes->nodeNr : 0;
@@ -65,8 +65,9 @@ static int print_xpath_nodes(xmlDocPtr doc, xmlNodeSetPtr nodes, FILE *output)
                LTTNG_ASSERT(nodes->nodeTab[i]);
 
                if (nodes->nodeTab[i]->type == XML_NAMESPACE_DECL) {
-                       fprintf(stderr, "ERR:%s\n",
-                                       "This executable does not support xml namespacing\n");
+                       fprintf(stderr,
+                               "ERR:%s\n",
+                               "This executable does not support xml namespacing\n");
                        ret = -1;
                        goto end;
                } else if (nodes->nodeTab[i]->type == XML_ELEMENT_NODE) {
@@ -74,16 +75,17 @@ static int print_xpath_nodes(xmlDocPtr doc, xmlNodeSetPtr nodes, FILE *output)
 
                        if (xmlChildElementCount(cur) == 0) {
                                if (xmlNodeIsText(cur->children)) {
-                                       node_child_value_string = xmlNodeListGetString(doc,
-                                                       cur->children, 1);
+                                       node_child_value_string =
+                                               xmlNodeListGetString(doc, cur->children, 1);
                                        if (node_exist) {
                                                result = true;
                                        } else if (opt_verbose) {
-                                               fprintf(output, "%s;%s;\n", cur->name,
-                                                               node_child_value_string);
+                                               fprintf(output,
+                                                       "%s;%s;\n",
+                                                       cur->name,
+                                                       node_child_value_string);
                                        } else {
-                                               fprintf(output, "%s\n",
-                                                               node_child_value_string);
+                                               fprintf(output, "%s\n", node_child_value_string);
                                        }
                                        xmlFree(node_child_value_string);
                                } else {
@@ -91,8 +93,9 @@ static int print_xpath_nodes(xmlDocPtr doc, xmlNodeSetPtr nodes, FILE *output)
                                        if (node_exist) {
                                                result = true;
                                        } else {
-                                               fprintf(stderr, "ERR:%s\n",
-                                                               "Xpath expression return non-final xml element");
+                                               fprintf(stderr,
+                                                       "ERR:%s\n",
+                                                       "Xpath expression return non-final xml element");
                                                ret = -1;
                                                goto end;
                                        }
@@ -102,8 +105,9 @@ static int print_xpath_nodes(xmlDocPtr doc, xmlNodeSetPtr nodes, FILE *output)
                                        result = true;
                                } else {
                                        /* We don't want to print non-final element */
-                                       fprintf(stderr, "ERR:%s\n",
-                                                       "Xpath expression return non-final xml element");
+                                       fprintf(stderr,
+                                               "ERR:%s\n",
+                                               "Xpath expression return non-final xml element");
                                        ret = -1;
                                        goto end;
                                }
@@ -131,7 +135,7 @@ static int register_lttng_namespace(xmlXPathContextPtr xpathCtx)
 {
        int ret;
        xmlChar *prefix;
-       xmlChar *ns = NULL;
+       xmlChar *ns = nullptr;
 
        prefix = xmlCharStrdup("lttng");
        if (!prefix) {
@@ -165,9 +169,9 @@ end:
 static int extract_xpath(const char *xml_path, const xmlChar *xpath)
 {
        int ret;
-       xmlDocPtr doc = NULL;
-       xmlXPathContextPtr xpathCtx = NULL;
-       xmlXPathObjectPtr xpathObj = NULL;
+       xmlDocPtr doc = nullptr;
+       xmlXPathContextPtr xpathCtx = nullptr;
+       xmlXPathObjectPtr xpathObj = nullptr;
 
        LTTNG_ASSERT(xml_path);
        LTTNG_ASSERT(xpath);
@@ -255,7 +259,7 @@ int main(int argc, char **argv)
                return -1;
        }
        /* Do the main job */
-       if (extract_xpath(argv[optind], (xmlChar *)argv[optind+1])) {
+       if (extract_xpath(argv[optind], (xmlChar *) argv[optind + 1])) {
                return -1;
        }
 
index 887f7af524c146a2f1f6d8b5ecd2ee018cc981c3..ee1e552f85fb5b2f18cb7b5c0e7f568d4277cb64 100644 (file)
@@ -5,27 +5,27 @@
  *
  */
 
- /*
-  * This script validate and xml from an xsd.
-  * argv[1] Path of the xsd
-  * argv[2] Path to the XML to be validated
-  */
+/*
+ * This script validate and xml from an xsd.
+ * argv[1] Path of the xsd
+ * argv[2] Path to the XML to be validated
+ */
+
+#include <common/macros.hpp>
+
+#include <lttng/lttng-error.h>
 
 #include <ctype.h>
+#include <dirent.h>
+#include <inttypes.h>
+#include <libxml/parser.h>
+#include <libxml/xmlschemas.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <inttypes.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <sys/types.h>
 #include <sys/stat.h>
-
-#include <libxml/xmlschemas.h>
-#include <libxml/parser.h>
-
-#include <lttng/lttng-error.h>
-#include <common/macros.hpp>
+#include <sys/types.h>
+#include <unistd.h>
 
 namespace {
 struct validation_ctx {
@@ -35,14 +35,11 @@ struct validation_ctx {
 };
 } /* namespace */
 
-enum command_err_code {
-       CMD_SUCCESS = 0,
-       CMD_ERROR
-};
+enum command_err_code { CMD_SUCCESS = 0, CMD_ERROR };
 
-static ATTR_FORMAT_PRINTF(2, 3)
-void xml_error_handler(void *ctx __attribute__((unused)),
-               const char *format, ...)
+static ATTR_FORMAT_PRINTF(2, 3) void xml_error_handler(void *ctx __attribute__((unused)),
+                                                      const char *format,
+                                                      ...)
 {
        char *err_msg;
        va_list args;
@@ -52,8 +49,7 @@ void xml_error_handler(void *ctx __attribute__((unused)),
        ret = vasprintf(&err_msg, format, args);
        va_end(args);
        if (ret == -1) {
-               fprintf(stderr, "ERR: %s\n",
-                               "String allocation failed in xml error handle");
+               fprintf(stderr, "ERR: %s\n", "String allocation failed in xml error handle");
                return;
        }
 
@@ -61,9 +57,7 @@ void xml_error_handler(void *ctx __attribute__((unused)),
        free(err_msg);
 }
 
-static
-void fini_validation_ctx(
-       struct validation_ctx *ctx)
+static void fini_validation_ctx(struct validation_ctx *ctx)
 {
        if (ctx->parser_ctx) {
                xmlSchemaFreeParserCtxt(ctx->parser_ctx);
@@ -80,9 +74,7 @@ void fini_validation_ctx(
        memset(ctx, 0, sizeof(struct validation_ctx));
 }
 
-static
-int init_validation_ctx(
-       struct validation_ctx *ctx, char *xsd_path)
+static int init_validation_ctx(struct validation_ctx *ctx, char *xsd_path)
 {
        int ret;
 
@@ -96,8 +88,7 @@ int init_validation_ctx(
                ret = -LTTNG_ERR_LOAD_INVALID_CONFIG;
                goto end;
        }
-       xmlSchemaSetParserErrors(ctx->parser_ctx, xml_error_handler,
-               xml_error_handler, NULL);
+       xmlSchemaSetParserErrors(ctx->parser_ctx, xml_error_handler, xml_error_handler, nullptr);
 
        ctx->schema = xmlSchemaParse(ctx->parser_ctx);
        if (!ctx->schema) {
@@ -111,8 +102,8 @@ int init_validation_ctx(
                goto end;
        }
 
-       xmlSchemaSetValidErrors(ctx->schema_validation_ctx, xml_error_handler,
-                       xml_error_handler, NULL);
+       xmlSchemaSetValidErrors(
+               ctx->schema_validation_ctx, xml_error_handler, xml_error_handler, nullptr);
        ret = 0;
 
 end:
@@ -125,7 +116,7 @@ end:
 static int validate_xml(const char *xml_file_path, struct validation_ctx *ctx)
 {
        int ret;
-       xmlDocPtr doc = NULL;
+       xmlDocPtr doc = nullptr;
 
        LTTNG_ASSERT(xml_file_path);
        LTTNG_ASSERT(ctx);
This page took 3.573829 seconds and 4 git commands to generate.